mira/pipeline.rs
1//! The ingest path.
2//!
3//! One bounded `tokio::sync::mpsc` channel per shard feeding one flusher task.
4//!
5//! The brief called for a lock-free ring buffer. That is the right structure
6//! when items are ~150ns order structs arriving millions per second; here an
7//! item is a whole export request costing 10^5–10^6 ns to decode and encode, and
8//! the realistic arrival rate is 10^2–10^4 per second. At that ratio the queue
9//! is never the bottleneck, and a bounded async channel buys the thing a
10//! lock-free queue cannot: `send().await` applies real backpressure that
11//! propagates out as HTTP/2 flow control to the exporter, instead of either
12//! spinning or dropping. If a queue ever shows up in a profile, this is one type
13//! to change.
14//!
15//! Flush is `spawn_blocking`: it fsyncs.
16//!
17//! Where the acknowledgement happens is [`Config::wal`]'s decision, and it is
18//! the only one in this file. Without a log the export is acknowledged after
19//! the block directory rename is durable, because OTLP's retryable status set
20//! covers exports in flight at a crash — acking earlier is the one window where
21//! data is lost with the client believing it was stored. That costs a whole
22//! `max_block_age` at the tail, which is section 11's 2.6 s p99. With a log the frame
23//! *is* the durable record, the publish is a background reorganisation of data
24//! that is already safe, and the ack costs a `write(2)`. Everything else here —
25//! the queue, the carry, the failure contract — is identical either way.
26
27use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
29use std::sync::{Arc, Mutex};
30use std::time::Duration;
31
32use mira_core::SignalBuilder;
33use mira_core::block;
34use mira_core::signal::Open;
35use mira_core::wal::{self, Wal};
36use tokio::sync::{mpsc, oneshot};
37use tokio::time::{Instant, sleep_until};
38
39/// Engine configuration.
40///
41/// Note what is *not* reachable from `config.rs`: `target_block_bytes` and
42/// `max_block_age` are derived constants, not settings. They are the two numbers
43/// an operator would most expect to tune and the two the engine is best placed
44/// to own, so principle 2c applies and there is no YAML key for either.
45pub struct Config {
46 pub data_dir: PathBuf,
47 /// Writer identity, from `mira_core::block::node_id`. Makes block names
48 /// unique across replicas with no coordination.
49 pub node: u32,
50 /// Seal a block once it reaches roughly this many bytes.
51 pub target_block_bytes: usize,
52 /// Seal a block after this long regardless of size, so acknowledgement
53 /// latency is bounded by time and not by the caller's traffic.
54 pub max_block_age: Duration,
55 pub retention: Duration,
56 /// Where a block goes just before retention unlinks it, or `None` to
57 /// unlink it outright. Parsed in `main` so an unsupported scheme is a
58 /// refusal to start rather than a warning at 3am.
59 pub offload: Option<mira_core::offload::Target>,
60 /// How many exports may wait for one signal's flusher. See
61 /// `crate::config::Config::queue`, which is where the reasoning is.
62 ///
63 /// Split across [`shards`](Self::shards), so the number an operator sets is
64 /// still the number of decoded exports this signal can be holding.
65 pub queue: usize,
66 /// How many flusher tasks one signal runs, each with its own channel, open
67 /// block and block sequence.
68 ///
69 /// One per core, not one per resource hash — section 4's "A note on
70 /// sharding" is explicit about which of those is the right unit, and the
71 /// reason is that resource cardinality in real fleets is bimodal, so a hash
72 /// gives a permanently hot shard and a small-file explosion in the tail.
73 /// Files per flush interval should be a function of core count, known at
74 /// startup, not of the customer's topology.
75 ///
76 /// One, not `available_parallelism`, by default: `main` resolves the real
77 /// number from `ingest.shards` and the core count, and everything that
78 /// builds a `Config` by hand — every unit test, every e2e node — wants the
79 /// deterministic one block per seal that a single shard gives.
80 pub shards: usize,
81 /// The write-ahead log, shared by all three signals, or `None` to
82 /// acknowledge on the block publish as Mira always has.
83 ///
84 /// One `Option` rather than a separate durability setting, because the two
85 /// are the same decision: with a log, an export is recoverable the moment
86 /// it is framed and there is nothing left for the acknowledgement to wait
87 /// for; without one, the publish is the only thing that makes it
88 /// recoverable. A flag that let those disagree would only be able to
89 /// express wrong answers.
90 ///
91 /// Off by default. Turning it on would trade read-your-writes away — see
92 /// `mira_core::wal`'s module docs — were it not for
93 /// `mira_core::query::search_open`, which scans the flusher's open builder
94 /// alongside the sealed blocks and buys it back.
95 pub wal: Option<Arc<Wal>>,
96}
97
98impl Default for Config {
99 fn default() -> Self {
100 Self {
101 data_dir: PathBuf::from("./data"),
102 node: block::node_id("mira"),
103 target_block_bytes: 32 << 20,
104 max_block_age: Duration::from_secs(2),
105 retention: Duration::from_secs(7 * 24 * 3600),
106 offload: None,
107 queue: 128,
108 shards: 1,
109 wal: None,
110 }
111 }
112}
113
114// `pub(crate)` only so `receiver`'s tests can put a queue into the two states
115// `submit` refuses from — full and closed — without a flusher behind it.
116pub(crate) struct Job<R> {
117 req: R,
118 ack: oneshot::Sender<Result<(), Rejected>>,
119 /// The log sequence this export was framed at, if there is a log. The
120 /// flusher collects them per block and asks `Wal::watermark_for` what
121 /// `wal_hi` that set permits — not the maximum over the block, which would
122 /// step over an older frame a sibling shard is still holding.
123 wal_seq: Option<u64>,
124}
125
126/// The write handle for one signal. `R` is that signal's OTLP export request.
127pub struct Ingest<R> {
128 // `pub(crate)` so a test can build one around a queue it controls; see
129 // [`Job`]. Nothing outside this module constructs one in anger — `spawn`
130 // is the only supported way to get a handle.
131 //
132 // One sender per flusher shard, and never empty. `Arc<[_]>` rather than
133 // `Vec` because every receiver holds a clone of this handle and the shard
134 // count is fixed at startup.
135 pub(crate) tx: Arc<[mpsc::Sender<Job<R>>]>,
136 /// Where the next export that cannot go to shard 0 starts looking. Shared
137 /// across clones, because the point of it is to spread waiters over shards
138 /// rather than over handles.
139 pub(crate) turn: Arc<AtomicU64>,
140 pub(crate) rejects: &'static Rejects,
141 pub(crate) wal: Option<Arc<Wal>>,
142 pub(crate) signal: wal::Signal,
143}
144
145// Derived `Clone` would demand `R: Clone`, which no export request is. Only the
146// `Sender`s are cloned, and that is unconditional.
147impl<R> Clone for Ingest<R> {
148 fn clone(&self) -> Self {
149 Self {
150 tx: self.tx.clone(),
151 turn: self.turn.clone(),
152 rejects: self.rejects,
153 wal: self.wal.clone(),
154 signal: self.signal,
155 }
156 }
157}
158
159/// Why an export could not be admitted. None of these is a partial success:
160/// OTLP forbids the client from retrying a partial success, so reporting
161/// overload that way permanently destroys the data and blames the sender.
162///
163/// The split between the last two is the whole of the failure contract. OTLP's
164/// retryable set is closed — gRPC `UNAVAILABLE` and friends, HTTP 429/502/503/504
165/// — and an exporter handed anything outside it drops the batch on the floor. So
166/// "we could not write it, try again" and "this export can never be written"
167/// cannot share a variant, however similar they look from inside the flusher.
168pub enum Rejected {
169 /// Queue full. Transient; retry.
170 Busy,
171 /// The engine is shutting down.
172 Closed,
173 /// The block this export was in did not become durable — a full disk, an
174 /// EIO, a flush task that panicked. Nothing about the export caused it and
175 /// the next one may well land, so it is answered like [`Rejected::Busy`].
176 Unavailable(String),
177 /// This export can never be stored: it does not fit an empty block. A retry
178 /// produces the same answer, so the client must be told not to send one.
179 Failed(String),
180}
181
182/// Wall-clock seconds. Only ever used for rate limits and for ages an operator
183/// reads; block timestamps come from the data, never from this clock.
184fn now_secs() -> u64 {
185 std::time::SystemTime::now()
186 .duration_since(std::time::UNIX_EPOCH)
187 .unwrap_or_default()
188 .as_secs()
189}
190
191/// True at most once per wall-clock second per gate, for whichever caller gets
192/// there first.
193///
194/// A node in trouble is in trouble thousands of times a second and the log line
195/// is worth exactly one of them; the rest is in the counter beside it. `swap`,
196/// not load-then-store, so of the many threads arriving in the same second
197/// exactly one sees the old value.
198fn once_a_second(gate: &AtomicU64) -> bool {
199 let now = now_secs();
200 gate.swap(now, Relaxed) != now
201}
202
203/// How long a signal has to be unable to store anything before this node calls
204/// itself unready.
205///
206/// It has to outlast the automatic recovery, or readiness flaps through every
207/// incident it is supposed to report. The two recoveries are a retention sweep,
208/// which runs every 60s and is what frees a full volume ([`reclaim`]), and the
209/// next flush, which is at most `max_block_age` behind it. Two sweeps gives that
210/// path two chances before the endpoint is pulled — and at a 2s block age it is
211/// already ~60 consecutive failed publishes, which is nobody's transient.
212pub const UNREADY_AFTER: Duration = Duration::from_secs(120);
213
214/// How long an export waits for room in the queue before it is shed.
215///
216/// Under the OTLP exporter timeout, which is 10s in every SDK that follows the
217/// spec's default, so a waiter is answered by this node rather than abandoned
218/// by its client — an abandoned request is the one case where the work is paid
219/// twice and nobody is told. Over `max_block_age`, which is 2s, so a queue that
220/// is full only because a flush is in flight drains within the wait instead of
221/// shedding around it. Five seconds sits in the middle of that range.
222///
223/// This is the tail bound, not a target: at the operating point nothing waits
224/// at all. It matters when a sender is faster than the disk, and there the
225/// choice is between a slow ack and a 503 that costs the sender a retry and
226/// this node the decode it already did.
227const ADMIT_WAIT: Duration = Duration::from_secs(5);
228
229/// What each signal has refused, published and been stuck on, since start.
230///
231/// A handful of counters and one warn a second, not a metrics subsystem. An
232/// exporter being NACKed already logs Mira's own reason on its side; what only
233/// the server can say is the *rate* and how long it has been going on, which is
234/// what an operator reads out of `/health`, `/readyz` and `/api/v1/stats` (see
235/// `main`) when deciding whether to grow the disk or the node.
236///
237/// Static because those three endpoints need all three signals at once and
238/// nothing else ever reads them: threading a handle per signal through two
239/// routers to reach one probe would be more plumbing than the numbers are worth.
240pub struct Rejects {
241 /// The signal these count for, so the endpoints can name them.
242 pub signal: &'static str,
243 /// Exports refused before the queue, because it was full.
244 pub shed: AtomicU64,
245 /// Exports accepted and then NACKed, because the write did not land.
246 pub failed: AtomicU64,
247 /// Exports refused permanently, whose records are gone: the client is told
248 /// not to retry, so this is the only counter that measures lost data.
249 pub refused: AtomicU64,
250 /// Blocks and rows that reached the disk, and the bytes they took there.
251 pub published: AtomicU64,
252 pub rows: AtomicU64,
253 pub bytes: AtomicU64,
254 /// Unix second the oldest currently open block of this signal took its
255 /// first row, or 0 if nothing is open. An age that keeps growing past
256 /// `max_block_age` is a flusher that is not flushing.
257 ///
258 /// Derived from [`shard_open_since`](Self::shard_open_since) and not
259 /// written directly by a
260 /// flusher: with more than one shard per signal, a shard that has just
261 /// sealed would otherwise clear a sibling's clock and the stuck flusher
262 /// this number exists to expose would read as healthy. The oldest of them,
263 /// because the question it answers is "is anything stuck".
264 pub open_since: AtomicU64,
265 /// Unix second of the first publish failure in the current run of them, or 0
266 /// if the last publish worked. See [`UNREADY_AFTER`]. Derived like
267 /// `open_since`, and for the same reason.
268 pub stalled_since: AtomicU64,
269 /// What each flusher shard actually writes; the two above are the oldest of
270 /// each.
271 ///
272 /// Fixed arrays rather than ones sized at `spawn`: these live in a `static`
273 /// that outlives every flusher and is re-entered by the next test in the
274 /// process, so a `OnceLock` sized by whoever spawned first would be the
275 /// wrong length for whoever spawns second. [`MAX_SHARDS`] pairs is 256
276 /// bytes a signal.
277 shard_open_since: [AtomicU64; MAX_SHARDS],
278 shard_stalled_since: [AtomicU64; MAX_SHARDS],
279 /// Rate-limit gates, one per line that can fire per export.
280 warned: AtomicU64,
281 refuse_warned: AtomicU64,
282}
283
284impl Rejects {
285 const fn new(signal: &'static str) -> Self {
286 Self {
287 signal,
288 shed: AtomicU64::new(0),
289 failed: AtomicU64::new(0),
290 refused: AtomicU64::new(0),
291 published: AtomicU64::new(0),
292 rows: AtomicU64::new(0),
293 bytes: AtomicU64::new(0),
294 open_since: AtomicU64::new(0),
295 stalled_since: AtomicU64::new(0),
296 shard_open_since: [const { AtomicU64::new(0) }; MAX_SHARDS],
297 shard_stalled_since: [const { AtomicU64::new(0) }; MAX_SHARDS],
298 warned: AtomicU64::new(0),
299 refuse_warned: AtomicU64::new(0),
300 }
301 }
302
303 /// The oldest non-zero timestamp any shard is reporting, or 0 if none is.
304 ///
305 /// Recomputed on every write rather than on every read because the readers
306 /// are `/healthz`, `/metrics` and the TUI — three calls a second between
307 /// them against a hot loop — and [`MAX_SHARDS`] relaxed loads is cheaper
308 /// than the branch that would decide when to skip it.
309 fn oldest(slots: &[AtomicU64; MAX_SHARDS]) -> u64 {
310 slots
311 .iter()
312 .map(|t| t.load(Relaxed))
313 .filter(|&t| t != 0)
314 .min()
315 .unwrap_or(0)
316 }
317
318 /// Report when `shard`'s open block took its first row, or 0 for "nothing
319 /// open".
320 fn set_open_since(&self, shard: usize, at: u64) {
321 self.shard_open_since[shard].store(at, Relaxed);
322 self.open_since
323 .store(Self::oldest(&self.shard_open_since), Relaxed);
324 }
325
326 /// Start the clock on a run of failures in `shard`, or leave it where it is.
327 ///
328 /// Not a `store`: readiness is about how *long* this has been going on, so
329 /// the timestamp that matters is the first failure of the run, not the
330 /// latest. One flusher owns each shard slot, so the compare-exchange cannot
331 /// lose a race — it is here to keep the first value.
332 fn mark_stalled(&self, shard: usize) {
333 let _ = self.shard_stalled_since[shard].compare_exchange(
334 0,
335 now_secs().max(1),
336 Relaxed,
337 Relaxed,
338 );
339 self.stalled_since
340 .store(Self::oldest(&self.shard_stalled_since), Relaxed);
341 }
342
343 /// Zero every open-block clock, shard slots included.
344 ///
345 /// Only the in-process end-to-end harness calls this — see
346 /// `e2e::forget_open_blocks` for why it has to. Clearing the aggregate
347 /// alone would not do it: the next shard to open a block recomputes the
348 /// aggregate from the slots, and a dead flusher's slot would come back.
349 #[cfg(test)]
350 pub fn forget_open(&self) {
351 for t in &self.shard_open_since {
352 t.store(0, Relaxed);
353 }
354 self.open_since.store(0, Relaxed);
355 }
356
357 /// `shard` stored a block, so its run of failures is over. The signal is
358 /// only unstalled once every shard's is.
359 fn clear_stalled(&self, shard: usize) {
360 self.shard_stalled_since[shard].store(0, Relaxed);
361 self.stalled_since
362 .store(Self::oldest(&self.shard_stalled_since), Relaxed);
363 }
364
365 fn record_shed(&self) {
366 self.shed.fetch_add(1, Relaxed);
367 if once_a_second(&self.warned) {
368 tracing::warn!(
369 signal = self.signal,
370 "ingest queue full; shedding exports (senders are told to retry)"
371 );
372 }
373 }
374}
375
376/// Parallel to [`SIGNALS`].
377pub static REJECTS: [Rejects; SIGNALS.len()] = [
378 Rejects::new(SIGNALS[0]),
379 Rejects::new(SIGNALS[1]),
380 Rejects::new(SIGNALS[2]),
381];
382
383fn rejects_for(signal: &str) -> &'static Rejects {
384 REJECTS
385 .iter()
386 .find(|r| r.signal == signal)
387 .expect("every signal that has a builder has a counter slot")
388}
389
390/// Seconds `r` has been unable to store an export, if that is long enough to be
391/// worth acting on. Split out from [`stalled`] so the threshold is testable
392/// without writing to a process-wide static that three live flushers also own.
393fn stall_of(r: &Rejects, now: u64) -> Option<u64> {
394 match r.stalled_since.load(Relaxed) {
395 0 => None,
396 since => {
397 let secs = now.saturating_sub(since);
398 (secs >= UNREADY_AFTER.as_secs()).then_some(secs)
399 }
400 }
401}
402
403/// The first signal this node has been unable to store for longer than
404/// [`UNREADY_AFTER`], and for how many seconds. `None` means every signal is
405/// either healthy or has only just started failing.
406pub fn stalled() -> Option<(&'static str, u64)> {
407 let now = now_secs();
408 REJECTS
409 .iter()
410 .find_map(|r| stall_of(r, now).map(|secs| (r.signal, secs)))
411}
412
413impl<R> Ingest<R> {
414 /// A slot in the first shard that has one, or `None` if every shard is full
415 /// or gone.
416 ///
417 /// First fit from shard 0 rather than round-robin, and that is the whole
418 /// sharding policy. Round-robin spreads a trickle of exports over every
419 /// shard, and since each shard owns its own open block, a node doing two
420 /// exports a second would publish `shards` nearly-empty blocks every
421 /// `max_block_age` instead of one — the small-file explosion section 4
422 /// rejects hash sharding for, arrived at from the other direction. First
423 /// fit keeps a node that is not saturating one flusher behaving exactly as
424 /// it did with one, and starts using the second shard at the moment the
425 /// first one's queue stops draining, which is the moment the consumer's
426 /// service time became the curve.
427 ///
428 /// Ordering across shards is not preserved and does not need to be: two
429 /// exports are two OTLP requests, the spec orders neither against the
430 /// other, and block timestamps come from the data. Ordering *within* a
431 /// shard still is, which is what the carry rule in [`flusher`] needs.
432 fn reserve(&self) -> Option<mpsc::Permit<'_, Job<R>>> {
433 self.tx.iter().find_map(|tx| tx.try_reserve().ok())
434 }
435}
436
437impl<R: prost::Message> Ingest<R> {
438 /// Enqueue and wait for durability.
439 ///
440 /// What "durable" means here is the one thing [`Config::wal`] decides.
441 /// Without a log this returns once the block containing the request has
442 /// been fsynced and renamed into place, which is correct and costs a whole
443 /// `max_block_age` at the tail. With one it returns once the request is a
444 /// frame in the log's page cache, which is section 11's 2.6 s p99 turned into
445 /// microseconds and is why the log exists.
446 pub async fn submit(&self, req: R) -> Result<(), Rejected> {
447 let _t_submit = mira_core::diag::Scope::new(&mira_core::diag::SUBMIT_TOTAL);
448 let t_admit = std::time::Instant::now();
449 let (ack, wait) = oneshot::channel();
450 // Wait for room, and only shed once the wait has run out. The first
451 // revision shed the moment the queue was full, on the reasoning that a
452 // fast NACK beats an unbounded latency tail. The tail argument is right
453 // and [`ADMIT_WAIT`] bounds it; the "fast" was not. Tonic and axum both
454 // decode the request before the handler is called, so by the time this
455 // runs the expensive part of the export is already paid, and shedding
456 // throws it away for a client that will send the same bytes again.
457 // Measured at 96 connections that cost more than the queue ever saved:
458 // 93% of exports shed, four cores busy, and a third of the throughput
459 // two connections get on one core. Parking instead is bounded by the
460 // connection count — every waiter is a request already in memory — where
461 // a deeper queue is bounded by nothing.
462 //
463 // Before the log append, not after: an export shed here never happened,
464 // whereas one framed and then shed would be replayed into a node whose
465 // client has already retried it elsewhere.
466 let permit = match self.reserve() {
467 Some(p) => p,
468 // Every shard is full. Park on one of them rather than on all of
469 // them: `reserve` is not cancel-safe enough to race K of them and
470 // drop the losers' permits, and at this point the choice of shard
471 // does not matter — they are all behind their flusher. The turn
472 // counter spreads the parked waiters so they wake as each drains
473 // rather than all behind the same one.
474 None => {
475 let i = self.turn.fetch_add(1, Relaxed) as usize % self.tx.len();
476 match tokio::time::timeout(ADMIT_WAIT, self.tx[i].reserve()).await {
477 Ok(Ok(p)) => p,
478 Ok(Err(_)) => return Err(Rejected::Closed),
479 Err(_) => {
480 self.rejects.record_shed();
481 return Err(Rejected::Busy);
482 }
483 }
484 }
485 };
486 mira_core::diag::SUBMIT_ADMIT.record(t_admit.elapsed().as_nanos() as u64);
487 if let Some(wal) = &self.wal {
488 // Re-encoded, not the bytes off the wire: tonic decodes before the
489 // handler sees the request, and a KYAML body was never protobuf at
490 // all. Measured at 864 MiB/s against the 244 MiB/s decode already in
491 // the path — see `mira_core::wal`'s module docs for why owning a
492 // tonic `Codec` to avoid it is the worse trade.
493 let t_enc = std::time::Instant::now();
494 let body = req.encode_to_vec();
495 mira_core::diag::WAL_ENCODE.record(t_enc.elapsed().as_nanos() as u64);
496 // The enqueue rides inside the append so the queue cannot reorder
497 // what the log numbered — see `Wal::append_then`.
498 return match wal.append_then(self.signal, &body, move |seq| {
499 permit.send(Job {
500 req,
501 ack,
502 wal_seq: Some(seq),
503 });
504 }) {
505 Ok(_) => Ok(()),
506 Err(e) => {
507 self.rejects.failed.fetch_add(1, Relaxed);
508 // Only one log error is the sender's to fix, and retrying an
509 // export too large to frame just burns the link.
510 Err(match e {
511 mira_core::Error::WalFrameTooLarge { .. } => {
512 Rejected::Failed(e.to_string())
513 }
514 _ => Rejected::Unavailable(e.to_string()),
515 })
516 }
517 };
518 }
519 permit.send(Job {
520 req,
521 ack,
522 wal_seq: None,
523 });
524 let _t_ack = mira_core::diag::Scope::new(&mira_core::diag::SUBMIT_WAIT_ACK);
525 match wait.await {
526 Ok(Ok(())) => Ok(()),
527 // One counter for both refusals after acceptance: the difference
528 // between them is the status code, and the number an operator wants
529 // is "how much did not get stored".
530 Ok(Err(r)) => {
531 self.rejects.failed.fetch_add(1, Relaxed);
532 Err(r)
533 }
534 Err(_) => Err(Rejected::Closed),
535 }
536 }
537}
538
539impl<R: prost::Message + Default> Ingest<R> {
540 /// Push one frame recovered from the log back into this signal's flusher,
541 /// under the sequence it already has.
542 ///
543 /// Not [`submit`](Self::submit): the frame is in the log already, so
544 /// re-appending it would number it above every watermark and the block
545 /// storing it would claim the copy instead of the original — which replays
546 /// again on the next boot, and the one after that. Nothing waits for the
547 /// ack either; the client that sent this got its answer before the crash,
548 /// or gave up long ago.
549 ///
550 /// Blocking, and deliberately: this is called from a `spawn_blocking` hop
551 /// at boot, and the bounded channel is the only thing keeping a multi-
552 /// gigabyte log from being decoded into memory faster than it can be
553 /// sealed.
554 /// The two failures are worth telling apart: [`Rejected::Failed`] is one
555 /// frame that will never decode, which is a line in the log and the next
556 /// frame; [`Rejected::Closed`] is the flusher being gone, which means the
557 /// rest of the replay would go nowhere.
558 pub fn replay(&self, body: &[u8], seq: u64) -> Result<(), Rejected> {
559 // Back among the unpublished before it is decoded, let alone queued, for
560 // the same reason `submit` numbers and enqueues under one lock: a shard
561 // that sealed in between would compute a watermark that steps over this
562 // frame.
563 if let Some(w) = &self.wal {
564 w.reframed(self.signal, seq);
565 }
566 let req = match R::decode(body) {
567 Ok(r) => r,
568 Err(e) => {
569 // Retired on the spot, and that is a decision rather than a
570 // leak. This frame will not decode on this boot and will not
571 // decode on any other, so leaving it unpublished would hold the
572 // signal's watermark at its sequence for the life of the volume
573 // — and every frame published after it would be replayed again
574 // on every boot, duplicating stored data to keep re-reading one
575 // that never becomes readable. `main::replay` says out loud that
576 // those exports are gone; this is the line that makes it true.
577 if let Some(w) = &self.wal {
578 w.published(self.signal, &[seq]);
579 }
580 return Err(Rejected::Failed(e.to_string()));
581 }
582 };
583 let job = Job {
584 req,
585 ack: oneshot::channel().0,
586 wal_seq: Some(seq),
587 };
588 // First fit like `submit`, falling back to blocking on shard 0. Replay
589 // is the one caller that must not shed, so the bounded channel is the
590 // pacing: see the note above about decoding a multi-gigabyte log.
591 match self.reserve() {
592 Some(p) => {
593 p.send(job);
594 Ok(())
595 }
596 None => self.tx[0].blocking_send(job).map_err(|_| Rejected::Closed),
597 }
598 }
599}
600
601/// Every signal that has an on-disk directory. Retention sweeps all of them;
602/// [`block::scan`] treats a missing one as empty, so listing a signal before its
603/// encoder exists is harmless.
604pub const SIGNALS: [&str; 3] = ["logs", "traces", "metrics"];
605
606/// The most flusher shards one signal will run.
607///
608/// A ceiling, not a target: it sizes the per-shard health clocks in a `static`
609/// and it bounds how many blocks a signal can publish per flush interval. Above
610/// this the flushers are no longer the bottleneck — the decode in front of them
611/// is — and every extra shard is another open block's worth of resident memory
612/// against the footprint axis. Sixteen is also `mira_core::query`'s scan fanout,
613/// and a machine wide enough to want more of one wants more of both.
614pub const MAX_SHARDS: usize = 16;
615
616/// How many flusher shards to run, given the configured value and what the
617/// machine reports.
618///
619/// Zero means "ask the machine", which is the default and the only value
620/// `config.rs` documents as auto. The count is a function of core count and
621/// nothing else — not of the resource cardinality, not of the connection count
622/// — which is section 4's rule for what a shard may be keyed on.
623///
624/// Halved, because a shard is a *consumer*: the producers are the decode
625/// and the runtime's own work, and giving every core a flusher leaves nothing
626/// to feed them. Section 11 measured 1.56M records/s on 2.18 cores with one
627/// flusher per signal, so the transcode is around a third of the total and
628/// three consumers per two producers would be an idle two-thirds.
629pub fn shard_count(configured: usize, cores: usize) -> usize {
630 match configured {
631 0 => (cores / 2).clamp(1, MAX_SHARDS),
632 n => n.min(MAX_SHARDS),
633 }
634}
635
636/// The handle over one signal's flusher shards: what a single `JoinHandle`
637/// meant when there was one of them, kept true now that there are several.
638///
639/// Awaiting it resolves when every shard has stopped; `abort` — test-only, see
640/// below — stops them all where they stand. A [`JoinSet`](tokio::task::JoinSet) and not
641/// a task that awaits a `Vec` of handles, because that shape gets the second
642/// half wrong: aborting such a task drops only its own future, so the shards
643/// keep running, and a shard that outlives the node it belonged to watches its
644/// senders drop, reads that as a graceful close, and seals a block — under a
645/// sequence, and into a staging directory, that the successor node is already
646/// using.
647pub struct Flushers(tokio::task::JoinSet<()>);
648
649/// Dropping the handle detaches, as dropping a `JoinHandle` does — a `JoinSet`
650/// on its own would abort instead. Read-only test harnesses build a node and
651/// keep only the parts they query; turning that into "and stop ingesting" would
652/// be a trap, and every caller that means to stop has one of the two ways to
653/// say so above.
654impl Drop for Flushers {
655 fn drop(&mut self) {
656 self.0.detach_all();
657 }
658}
659
660impl Flushers {
661 /// Stop every shard where it stands. Nothing is sealed; what survives is
662 /// whatever the log already holds — which is the claim every test that
663 /// calls this is making.
664 ///
665 /// Test-only, and that is not an oversight: the binary sets
666 /// `panic = "abort"`, so in production a flusher that stops without being
667 /// asked takes the process with it and there is nobody left to abort.
668 #[cfg(test)]
669 pub fn abort(&mut self) {
670 self.0.abort_all();
671 }
672
673 /// Three shards that will never stop, for the drain path that has to give
674 /// up on them.
675 #[cfg(test)]
676 pub fn wedged() -> Self {
677 let mut set = tokio::task::JoinSet::new();
678 set.spawn(std::future::pending());
679 Self(set)
680 }
681}
682
683impl std::future::Future for Flushers {
684 type Output = Result<(), tokio::task::JoinError>;
685
686 /// Ready once the set has drained. Unlike a `JoinHandle` this is safe to
687 /// poll again afterwards — an emptied set answers `Ready` forever — which
688 /// is what lets `main` await a handle `first_stopped` may already have run
689 /// to completion.
690 fn poll(
691 mut self: std::pin::Pin<&mut Self>,
692 cx: &mut std::task::Context<'_>,
693 ) -> std::task::Poll<Self::Output> {
694 use std::task::Poll;
695 loop {
696 match self.0.poll_join_next(cx) {
697 Poll::Ready(Some(Ok(()))) => {}
698 // Surfaced rather than swallowed: `cargo test` does not build
699 // with `panic = "abort"`, so a flusher that panics under test
700 // is a `JoinError` here and nothing else anywhere.
701 Poll::Ready(Some(Err(e))) => return Poll::Ready(Err(e)),
702 Poll::Ready(None) => return Poll::Ready(Ok(())),
703 Poll::Pending => return Poll::Pending,
704 }
705 }
706 }
707}
708
709/// Start one signal's ingest pipeline. Returns the handle its receivers push
710/// into. Each signal gets its own channels, flusher tasks and block sequences,
711/// so a slow flush on one cannot stall another.
712///
713/// [`Flushers`] is the shutdown contract: drop every [`Ingest`] clone and every
714/// shard seals whatever is open, acks everyone waiting on it and returns; the
715/// handle resolves once they all have. A caller that exits without awaiting it
716/// turns a graceful stop into a reset for those waiters.
717pub fn spawn<B: SignalBuilder>(cfg: &Arc<Config>) -> (Ingest<B::Request>, OpenSlot, Flushers) {
718 let shards = cfg.shards.clamp(1, MAX_SHARDS);
719 // Once for the signal, before any shard can publish. Inside the flusher it
720 // would be one sweep per shard, and `sweep_staging` filters by signal and
721 // node — not by sequence — so shard 3 booting a moment late would delete the
722 // staging directory shard 0 was already writing tables into.
723 //
724 // Not fatal if it fails: a leaked directory under `.tmp` costs disk and
725 // nothing else, and refusing to ingest over it would turn a janitorial
726 // problem into an outage.
727 match block::sweep_staging(&cfg.data_dir, B::SIGNAL, cfg.node) {
728 Ok(0) => {}
729 Ok(n) => tracing::info!(signal = B::SIGNAL, count = n, "swept stale staging dirs"),
730 Err(e) => tracing::warn!(signal = B::SIGNAL, error = %e, "cannot sweep staging dirs"),
731 }
732 // Resume the sequence past whatever is already on disk so block directory
733 // names stay unique across restarts. This is the entirety of crash recovery.
734 //
735 // `max`, not `last`: `scan` sorts by `(min_ts, seq)`, so the last element is
736 // the latest-timestamped block, which is not the highest sequence number
737 // whenever a restart follows a backlog replay. Reusing a sequence makes the
738 // next `rename` land on an existing directory and the node never publishes
739 // again.
740 //
741 // Scanned here and handed to every shard rather than scanned by each of
742 // them, and that is load-bearing: a shard that read the directory after a
743 // sibling had already published would resume one higher and its stride
744 // would land on the sibling's next sequence. One base, distinct offsets.
745 let resume = match block::scan(&cfg.data_dir, B::SIGNAL) {
746 Ok(blocks) => Some(blocks.iter().map(|b| b.seq).max().map_or(0, |s| s + 1)),
747 Err(e) => {
748 tracing::error!(signal = B::SIGNAL, error = %e, "cannot scan data directory");
749 None
750 }
751 };
752 let rejects = rejects_for(B::SIGNAL);
753 // The configured depth is the signal's, not each shard's: it is a bound on
754 // how many decoded exports this node can be holding, and that does not get
755 // larger because there are more consumers.
756 let depth = cfg.queue.div_ceil(shards).max(1);
757 let mut txs = Vec::with_capacity(shards);
758 let mut slots = Vec::with_capacity(shards);
759 let mut tasks = tokio::task::JoinSet::new();
760 for shard in 0..shards {
761 let (tx, rx) = mpsc::channel(depth);
762 // Eight concurrent askers, because a ninth gets a snapshot at most a
763 // millisecond older and waiting in line for one is worth less than that.
764 let (ask, asks) = mpsc::channel(8);
765 let slot = Shard {
766 cur: Arc::default(),
767 ask,
768 };
769 txs.push(tx);
770 // No flusher if the data directory could not be read, which drops the
771 // receiver and leaves the sender closed: `submit` answers `Closed` and
772 // the handle resolves at once. The same thing the flusher's own early
773 // return did, decided once instead of `shards` times.
774 if let Some(resume) = resume {
775 tasks.spawn(flusher::<B>(
776 rx,
777 asks,
778 cfg.clone(),
779 slot.clone(),
780 shard,
781 shards,
782 resume,
783 ));
784 }
785 slots.push(slot);
786 }
787 let ingest = Ingest {
788 tx: txs.into(),
789 turn: Arc::default(),
790 rejects,
791 wal: cfg.wal.clone(),
792 signal: wal::Signal::named(B::SIGNAL).expect("every signal has a log discriminant"),
793 };
794 // One handle over all of them, so `main` still holds three. Awaiting every
795 // shard rather than the first to finish is the same contract it was: under
796 // `panic = "abort"` a flusher that dies takes the process with it, and the
797 // one way a shard returns early — an unreadable data directory at startup —
798 // is a condition every shard of the signal meets at once.
799 (
800 ingest,
801 OpenSlot {
802 shards: slots.into(),
803 },
804 Flushers(tasks),
805 )
806}
807
808/// Where the read path asks one flusher shard for a readable copy of its open
809/// block (section 4), and where the last copy it produced is cached.
810///
811/// The snapshot is taken on demand, never on a timer: an idle node with nobody
812/// querying it copies nothing. A `Mutex` around the cached list rather than an
813/// `ArcSwap` — the critical section clones at most two pointers and a crate
814/// for that would be a crate for nothing.
815#[derive(Clone)]
816struct Shard {
817 cur: Arc<Mutex<Snapshot>>,
818 /// Handing the flusher somewhere to put an answer. Not generic in the
819 /// signal's request type, which is the whole reason the read path can hold
820 /// three of these in one array.
821 ask: mpsc::Sender<oneshot::Sender<Snapshot>>,
822}
823
824/// What one shard has open, newest sequence last.
825///
826/// Two entries and not one because a shard's block stays readable while its
827/// rename is in flight: the sealed block is not on disk yet, and the builder
828/// behind it is already taking rows. Answering with either alone would be a
829/// row vanishing under a live reader. Empty on an idle shard, one deep on a
830/// busy one, two only inside a publish.
831type Snapshot = Vec<Arc<Open>>;
832
833/// Every shard of one signal's open blocks, asked together.
834///
835/// The interesting half is [`OpenSlot::fresh`], and what makes it *fresh*
836/// rather than merely recent is the order the queues already enforce. `submit`
837/// acknowledges an export only after the job is in some shard's channel, so
838/// every acknowledged export is queued before a request issued after it — and
839/// if each shard answers only once its own channel is empty, the answers
840/// together necessarily contain them all. That is read-your-writes, for the
841/// price of FIFOs Mira was already paying, with no shared counter and no clock.
842///
843/// Sharding does not weaken it, because the argument never depended on there
844/// being one queue: an acknowledged export is in exactly one shard's channel
845/// until that shard appends it. It does mean the read path has to ask all of
846/// them, which is what `fresh` does.
847#[derive(Clone, Default)]
848pub struct OpenSlot {
849 /// Empty for a slot nobody serves: `fresh` returns nothing, forever. That
850 /// is exactly what a unit test that only wants an `Api` wants.
851 shards: Arc<[Shard]>,
852}
853
854impl OpenSlot {
855 /// Everything acknowledged before this call, as one readable block per
856 /// shard that has anything open.
857 ///
858 /// Falls back to a shard's last snapshot when its flusher cannot be
859 /// reached: the request queue is full, or the task is gone. Both are
860 /// overload or shutdown, and a query that waits its turn behind an
861 /// overloaded ingest path is a worse answer than one that is a few
862 /// milliseconds stale.
863 ///
864 /// Every ask goes out before any answer is awaited, so the shards work
865 /// concurrently; awaiting them in turn would put a whole flusher's backlog
866 /// between one shard's answer and the next one's question.
867 pub async fn fresh(&self) -> Vec<Arc<Open>> {
868 let mut out = Vec::with_capacity(self.shards.len());
869 let mut waiting = Vec::with_capacity(self.shards.len());
870 for s in self.shards.iter() {
871 let (tx, rx) = oneshot::channel();
872 match s.ask.try_send(tx) {
873 Ok(()) => waiting.push((s, rx)),
874 Err(_) => out.extend(s.get()),
875 }
876 }
877 for (s, rx) in waiting {
878 out.extend(rx.await.unwrap_or_else(|_| s.get()));
879 }
880 out
881 }
882}
883
884impl Shard {
885 /// The last snapshot taken, without asking for a new one.
886 fn get(&self) -> Snapshot {
887 self.lock().clone()
888 }
889
890 fn put(&self, v: Snapshot) {
891 *self.lock() = v;
892 }
893
894 /// A panic in this critical section is not possible — it clones or drops an
895 /// `Arc` and nothing else — so poisoning carries no information and
896 /// unwrapping it would only turn an impossible bug into an outage.
897 fn lock(&self) -> std::sync::MutexGuard<'_, Snapshot> {
898 self.cur.lock().unwrap_or_else(|e| e.into_inner())
899 }
900}
901
902/// The three signals' open blocks, in [`SIGNALS`] order.
903pub type OpenSlots = [OpenSlot; SIGNALS.len()];
904
905/// One sweep for all signals, not one per signal: retention is IO against the
906/// directory tree, and three tasks waking on the same minute boundary to unlink
907/// from the same volume is contention for nothing.
908pub fn spawn_retention(cfg: Arc<Config>) {
909 tokio::spawn(retention(cfg.clone()));
910 if cfg.wal.is_some() {
911 tokio::spawn(wal_maintenance(cfg));
912 }
913}
914
915/// How long an acknowledged export can sit in the page cache before it is on
916/// the device.
917///
918/// This is the entire power-loss exposure window, and it is a constant for the
919/// same reason `max_block_age` is: the operator cannot price the trade without
920/// knowing what an fsync costs on their volume, and the engine measures that
921/// every time it does one. On this machine `F_FULLFSYNC` is ~4 ms (section 10), so a
922/// quarter-second period spends under 2% of one thread and bounds the loss at
923/// a quarter second of ingest. Shorter buys very little — the exposure is
924/// already smaller than a Collector's own batch timeout, so the exporter is
925/// holding more unsent data than this window holds unsynced.
926pub const WAL_SYNC_PERIOD: Duration = Duration::from_millis(250);
927
928/// Sync the log to the device, and drop the segments every signal has published
929/// past.
930///
931/// Truncation is not on the sync period. It costs three `readdir`s of the block
932/// tree — [`block::wal_watermarks`] is the whole manifest, re-derived — and what
933/// it can reclaim is whole segments, which only become removable once every
934/// signal has published past them. At the rate a demo or a quiet service
935/// produces, that is minutes apart and four sweeps a second would be hundreds of
936/// scans finding nothing; at section 11's measured 190.6 MiB/s a 64 MiB segment
937/// fills in a third of a second, and a minute of them is ~180 files that one `readdir`
938/// retires as cheaply as it retires one. The period is set by how much disk a
939/// minute of unreclaimed log is worth, which is the same answer at both ends.
940async fn wal_maintenance(cfg: Arc<Config>) {
941 let Some(wal) = cfg.wal.clone() else { return };
942 let mut tick = tokio::time::interval(WAL_SYNC_PERIOD);
943 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
944 let mut ticks: u64 = 0;
945 loop {
946 tick.tick().await;
947 ticks += 1;
948 wal_sweep(wal.clone(), cfg.data_dir.clone(), ticks.is_multiple_of(240)).await;
949 }
950}
951
952/// One pass of the above. Separate from the loop so a test can drive both kinds
953/// of tick without waiting out the sixty seconds of real time between them.
954async fn wal_sweep(wal: Arc<Wal>, dir: PathBuf, truncating: bool) {
955 // The whole sweep is one blocking hop: `sync` is `F_FULLFSYNC` and truncate
956 // is `readdir` plus `unlink`, and neither belongs on a runtime thread that
957 // has three flushers' worth of acks to hand out.
958 let done = tokio::task::spawn_blocking(move || {
959 wal.sync()?;
960 if !truncating {
961 return Ok(0);
962 }
963 // The minimum across signals, not each signal's own: one segment holds
964 // frames for all three, so it can only go once the last of them has
965 // claimed everything in it. Scoped to this log's own writer, because
966 // what is about to happen to the segments below `covered` is `unlink`.
967 //
968 // This read happens *after* the `sync` above, so a block renamed
969 // between the two is counted as covered by a sync that predates it.
970 // Safe only because `block::publish` barriers a block durable before
971 // its rename — take those barriers out (performance-barrier.md prices
972 // them) and this is a data-loss path. Reorder to watermarks, sync,
973 // truncate at the same time, not afterwards.
974 let covered = block::wal_watermarks(&dir, wal.node())?
975 .into_iter()
976 .min()
977 .unwrap_or(0);
978 wal.truncate(covered)
979 })
980 .await;
981 match done {
982 Ok(Ok(0)) => {}
983 Ok(Ok(n)) => tracing::info!(segments = n, "write-ahead log segments removed"),
984 // Warn and keep going. A log that cannot sync is still absorbing appends
985 // and still replayable after anything short of power loss, so refusing
986 // to ingest over it would trade a narrowed durability guarantee for a
987 // certain outage.
988 Ok(Err(e)) => tracing::warn!(error = %e, "write-ahead log maintenance failed"),
989 Err(e) => tracing::warn!(error = %e, "write-ahead log maintenance panicked"),
990 }
991}
992
993async fn flusher<B: SignalBuilder>(
994 mut rx: mpsc::Receiver<Job<B::Request>>,
995 mut asks: mpsc::Receiver<oneshot::Sender<Snapshot>>,
996 cfg: Arc<Config>,
997 open_slot: Shard,
998 shard: usize,
999 shards: usize,
1000 resume: u64,
1001) {
1002 let rejects = rejects_for(B::SIGNAL);
1003 // Shard k takes `resume + k`, `resume + k + shards`, and so on, so the
1004 // shards of a signal partition the sequence space with no allocator and no
1005 // agreement — a sequence only has to be unique, and the residues mod
1006 // `shards` are distinct. It stays unique across a restart that runs a
1007 // different number of shards, because the next `resume` is above every
1008 // stride. That is the whole cost of a per-shard block sequence: the block
1009 // directory is the manifest and a sequence is a filename, so nothing else
1010 // has to know.
1011 let mut seq = resume.saturating_add(shard as u64);
1012 let signal = wal::Signal::named(B::SIGNAL).expect("every signal has a log discriminant");
1013
1014 let mut builder = B::default();
1015 let mut waiters: Vec<oneshot::Sender<Result<(), Rejected>>> = Vec::new();
1016 let mut batch = Vec::with_capacity(64);
1017 // Jobs that did not fit the open block. They go into the next one, so a full
1018 // dictionary costs a slightly small block and never costs a caller its data.
1019 let mut carry: Vec<Job<B::Request>> = Vec::new();
1020 let mut deadline = Instant::now() + cfg.max_block_age;
1021 let mut open = true;
1022 // The log sequences this shard has finished with since the last publish,
1023 // ascending, or empty when there is no log. "Finished with" and not
1024 // "stored": an empty export and a permanently refused one both leave
1025 // nothing to recover, so replaying them forever would only keep the log
1026 // from truncating. A carried job is deliberately absent — it has not landed
1027 // anywhere yet, and claiming it here is how the watermark would lie.
1028 //
1029 // A list rather than the running maximum it used to be, because with more
1030 // than one shard per signal the maximum is no longer the watermark: see
1031 // `Wal::watermark_for`, which needs to know exactly which sequences this
1032 // block is retiring in order to answer what the *others* still hold.
1033 let mut wal_seqs: Vec<u64> = Vec::new();
1034 // Readers waiting to be told what is in the block, and the builder size the
1035 // last answer was taken at. Answered only with an empty `rx` — see
1036 // [`OpenSlot::fresh`] — so they survive as many loop turns as the backlog
1037 // takes.
1038 let mut asked: Vec<oneshot::Sender<Snapshot>> = Vec::new();
1039 // The last copy of the builder taken, and the size it was taken at. One
1040 // field and not two so the copy cannot outlive the size it answers for.
1041 let mut snapped: Option<(usize, Arc<Open>)> = None;
1042 // The block on its way to disk, if there is one. At most one: see
1043 // [`InFlight`].
1044 let mut in_flight: Option<InFlight> = None;
1045
1046 // Carry outlives the channel: a request deferred by the last block still has
1047 // to land somewhere before the task exits.
1048 // Deliberately not `|| in_flight.is_some()`: once `rx` is closed
1049 // `recv_many` returns 0 without waiting, so a turn taken only to wait for
1050 // a publish would spin the select rather than park in it. The drain below
1051 // the loop is what that case is for.
1052 while open || !carry.is_empty() {
1053 // Before the wait, not after the work: a turn that seals parks again
1054 // immediately, and a reader answered only on the next arrival would
1055 // wait for someone else's export.
1056 answer::<B>(
1057 &builder,
1058 &mut asked,
1059 &mut snapped,
1060 !carry.is_empty() || !rx.is_empty(),
1061 in_flight.as_ref().map(|f| &f.open),
1062 &open_slot,
1063 cfg.node,
1064 seq,
1065 );
1066 let mut aged = false;
1067 // Skip the wait while there is carry: those jobs are already accepted and
1068 // unacknowledged, so holding them behind an idle receiver would add a
1069 // whole block age to their latency.
1070 if carry.is_empty() {
1071 tokio::select! {
1072 n = rx.recv_many(&mut batch, 64) => {
1073 if n == 0 {
1074 open = false;
1075 }
1076 }
1077 // A reader wanting the open block. Closing this channel is not a
1078 // shutdown signal — the `Ingest` handles are — so a `None` here
1079 // only means nobody will ever ask again.
1080 who = asks.recv() => {
1081 if let Some(who) = who {
1082 asked.push(who);
1083 }
1084 }
1085 // The block in flight landing. Here and not only at the next
1086 // seal, because its callers are waiting on an acknowledgement
1087 // the device has already given: on a quiet shard the next seal
1088 // is a whole `max_block_age` away.
1089 res = joined(&mut in_flight) => {
1090 let f = in_flight.take().expect("joined resolves only with a block in flight");
1091 land::<B>(f, res, &cfg, &open_slot, &snapped, rejects, shard, signal);
1092 }
1093 _ = sleep_until(deadline) => aged = true,
1094 }
1095 }
1096 // Drained in the same turn as the jobs, so a reader that arrives with a
1097 // backlog behind it is answered once, after the backlog.
1098 while let Ok(who) = asks.try_recv() {
1099 asked.push(who);
1100 }
1101
1102 let mut jobs = std::mem::take(&mut carry);
1103 jobs.append(&mut batch);
1104 let mut dict_full = false;
1105 for job in jobs {
1106 // On an empty block the headroom hint is deliberately not consulted.
1107 //
1108 // The hint assumes every attribute in the request introduces a new
1109 // dictionary key, because counting the distinct ones would mean
1110 // hashing the whole request on the hot path to answer a question
1111 // that is almost always "yes, plenty of room". That estimate is the
1112 // right one when it decides *whether to seal first* — being wrong
1113 // costs a slightly small block. It is the wrong one when the block
1114 // is already empty, because then it is not choosing between two
1115 // blocks, it is rejecting the export outright: a single batch of
1116 // ~13k records at five attributes each exceeds 65536 attribute rows
1117 // and used to be NACKed permanently, retry included, for data whose
1118 // real key cardinality is a few dozen.
1119 //
1120 // Sealing cannot help a block with nothing in it, so the only honest
1121 // test left is the append itself.
1122 let empty = builder.is_empty();
1123 // Once one job has been deferred, every job after it must be too, or
1124 // the block would acknowledge exports out of arrival order.
1125 if !empty && (dict_full || !builder.has_headroom_for(&job.req)) {
1126 dict_full = true;
1127 carry.push(job);
1128 continue;
1129 }
1130 // The first job of a block starts its age clock, so acknowledgement
1131 // latency is bounded from the moment data arrived rather than from
1132 // the last flush.
1133 if waiters.is_empty() {
1134 deadline = Instant::now() + cfg.max_block_age;
1135 }
1136 if let Some(seq) = job.wal_seq {
1137 wal_seqs.push(seq);
1138 }
1139 match builder.append_request(&job.req) {
1140 // An export carrying no records is legal — the Collector emits
1141 // one whenever a batch empties out — and there is nothing in it
1142 // to make durable. Parking its caller behind a block that will
1143 // never be sealed, because nothing was added to seal, strands
1144 // that caller for as long as it is willing to wait.
1145 Ok(0) => {
1146 let _ = job.ack.send(Ok(()));
1147 }
1148 Ok(_) => {
1149 // The reported age tracks unacknowledged rows, not the
1150 // deadline: an export carrying no records resets the timer
1151 // above without leaving anything open, and an "open block"
1152 // that is never sealed because there is nothing in it is
1153 // the exact false alarm this number would be read as.
1154 if waiters.is_empty() {
1155 rejects.set_open_since(shard, now_secs());
1156 }
1157 waiters.push(job.ack);
1158 }
1159 Err(e) => {
1160 // The append can fail part-way through, having already
1161 // written some of the request's rows. The client will retry
1162 // the whole export, so publishing those rows would
1163 // guarantee duplicates. Discarding the builder is only safe
1164 // — and only necessary — when this job started on an empty
1165 // block, which is exactly the case that skipped the hint
1166 // above; anything else passed a conservative check and
1167 // cannot overflow.
1168 if empty {
1169 let _ = builder.finish();
1170 }
1171 // The only permanent refusal in the pipeline: this request
1172 // did not fit a block with nothing in it, so no retry of it
1173 // ever will.
1174 //
1175 // Loud, because it is the one refusal that destroys data.
1176 // Everything else in this file is answered `Unavailable`
1177 // and comes back on the next attempt; this one tells the
1178 // exporter not to try, and the exporter obeys. Rate-limited
1179 // like the shed warning — a sender in this state is in it
1180 // for every export it has — and carrying the running total,
1181 // because one line an incident later is not a quantity.
1182 let refused = rejects.refused.fetch_add(1, Relaxed) + 1;
1183 if once_a_second(&rejects.refuse_warned) {
1184 tracing::error!(
1185 signal = B::SIGNAL,
1186 error = %e,
1187 refused,
1188 "export permanently refused; its records are gone. The sender \
1189 is told not to retry, so nothing will bring them back — the \
1190 request does not fit an empty block, which means splitting it \
1191 at the sender is the only fix"
1192 );
1193 }
1194 let _ = job.ack.send(Err(Rejected::Failed(e.to_string())));
1195 }
1196 }
1197 }
1198
1199 let full = dict_full || builder.approx_bytes() >= cfg.target_block_bytes;
1200 if builder.is_empty() || !(full || (aged && !waiters.is_empty()) || !open) {
1201 // Push the idle timer out so a stale deadline does not spin the loop.
1202 if waiters.is_empty() {
1203 deadline = Instant::now() + cfg.max_block_age;
1204 rejects.set_open_since(shard, 0);
1205 }
1206 continue;
1207 }
1208
1209 rejects.set_open_since(shard, 0);
1210 let sealed = match builder.finish() {
1211 Ok(s) => s,
1212 Err(e) => {
1213 let msg = e.to_string();
1214 rejects.mark_stalled(shard);
1215 for w in waiters.drain(..) {
1216 // Whose export broke the encoder is not knowable from here,
1217 // so nobody is blamed permanently: everyone is told to send
1218 // it again.
1219 let _ = w.send(Err(Rejected::Unavailable(msg.clone())));
1220 }
1221 // `finish` leaves a fresh builder behind even when it fails, so
1222 // there is nothing to repair here — see `SignalBuilder::finish`.
1223 //
1224 // The watermark goes with it. Nothing claimed these sequences,
1225 // so they stay unpublished, keep every sibling shard's
1226 // watermark behind them, and come back on the next boot — which
1227 // is the only reason the callers above could be told to retry
1228 // without that being a lie about where their data went.
1229 wal_seqs.clear();
1230 // Those rows are gone; a snapshot still advertising them would
1231 // be the read path promising data no restart can produce.
1232 snapped = None;
1233 open_slot.put(in_flight.iter().map(|f| f.open.clone()).collect());
1234 tracing::error!(signal = B::SIGNAL, error = %msg, "block discarded");
1235 continue;
1236 }
1237 };
1238
1239 // The seal is done and the next block's builder is already fresh, so
1240 // this is the last moment the overlap is worth anything — and the
1241 // first at which a second sealed block would be resident. Waiting
1242 // here, after `finish`, is what bounds it to one.
1243 if let Some(f) = in_flight.take() {
1244 settle::<B>(f, &cfg, &open_slot, &snapped, rejects, shard, signal).await;
1245 }
1246
1247 let dir = cfg.data_dir.clone();
1248 let node = cfg.node;
1249 let this_seq = seq;
1250 seq += shards as u64;
1251 let block_seqs = std::mem::take(&mut wal_seqs);
1252 // Asked before the publish, because the answer is part of the directory
1253 // name, and answered against what every shard of this signal is still
1254 // holding rather than against this block alone. The sequences are not
1255 // retired until the rename lands.
1256 let block_wal_hi = match &cfg.wal {
1257 Some(w) => w.watermark_for(signal, &block_seqs),
1258 None => 0,
1259 };
1260 // The sealed block, in the shape the read path already understands.
1261 // Publishing borrows it out of the same `Arc` the slot holds, so
1262 // keeping it readable for the length of the rename costs one pointer
1263 // and copies no rows.
1264 let open = Arc::new(Open {
1265 node,
1266 seq: this_seq,
1267 sealed,
1268 });
1269 let publishing = open.clone();
1270 let task = tokio::task::spawn_blocking(move || {
1271 // The size is measured in the same blocking hop as the write, off
1272 // the runtime: it is a handful of `stat`s against pages the publish
1273 // just touched, and it is the only exact answer to "how much disk
1274 // did this node write" that does not mean walking the whole tree.
1275 block::publish(
1276 &dir,
1277 B::SIGNAL,
1278 node,
1279 this_seq,
1280 block_wal_hi,
1281 &publishing.sealed,
1282 )
1283 .map(|b| (dir_bytes(&b.dir), b.dir))
1284 });
1285 // Not awaited here, and that is the change section 11's barrier page
1286 // was looking for. `publish` is eleven `F_FULLFSYNC` plus the encode's
1287 // bytes, and awaiting it stopped this shard reading its channel for the
1288 // whole of it — so the queue slot that `submit.admit` blocks on was not
1289 // freed by a shard that had nothing to do but wait for a device. The
1290 // loop now turns straight back to `recv_many` and the next block's
1291 // Arrow encode runs against the current one's device time.
1292 //
1293 // Nothing about durability moves: the waiters below are still answered
1294 // only by `settle`, after the rename. What overlaps is the encode, not
1295 // the acknowledgement.
1296 in_flight = Some(InFlight {
1297 task,
1298 waiters: std::mem::take(&mut waiters),
1299 block_seqs,
1300 open,
1301 });
1302 snapped = None;
1303 deadline = Instant::now() + cfg.max_block_age;
1304 }
1305 // The loop exits without waiting for a publish — see the condition — so
1306 // this is where the last block of a shutting-down shard is waited for. Its
1307 // callers are owed an answer: dropping the handle here would abort a
1308 // publish the shutdown path exists to finish.
1309 if let Some(f) = in_flight.take() {
1310 settle::<B>(f, &cfg, &open_slot, &snapped, rejects, shard, signal).await;
1311 }
1312}
1313
1314/// A block on its way to disk, and everyone owed an answer when it lands.
1315///
1316/// The flusher keeps at most one of these so the next block's Arrow encode
1317/// overlaps the current one's device time instead of queueing behind it — see
1318/// the `settle` call sites. One and not more: a second in flight would be a
1319/// second sealed block's worth of resident bytes per shard against the
1320/// footprint axis, and the stall this removes is already gone at one.
1321struct InFlight {
1322 task: tokio::task::JoinHandle<mira_core::Result<(u64, PathBuf)>>,
1323 /// Acknowledged only when the rename lands. Holding them here rather than
1324 /// on the stack is the whole reason the loop may turn again meanwhile: the
1325 /// durability contract is unchanged, it is the *waiting* that moved.
1326 waiters: Vec<oneshot::Sender<Result<(), Rejected>>>,
1327 /// Retired against the log only on success, exactly as before. While this
1328 /// is unlanded the sequences stay in `Wal::pending`, so the next block's
1329 /// `watermark_for` finds them and refuses to claim them — the overlap is
1330 /// safe here by construction rather than by an added check.
1331 block_seqs: Vec<u64>,
1332 /// Also what the read path is served from until the rename lands, which is
1333 /// why it is an `Arc` and not the bare `Sealed` the publish needs.
1334 open: Arc<Open>,
1335}
1336
1337/// The join result of a publish: the outer layer is the task's, the inner the
1338/// filesystem's.
1339type Published = std::result::Result<mira_core::Result<(u64, PathBuf)>, tokio::task::JoinError>;
1340
1341/// Resolve when the block in flight lands, leaving it in place for [`land`].
1342///
1343/// Pending forever when there is nothing in flight, which is what makes this a
1344/// `select!` arm needing no guard. Polling a `&mut JoinHandle` and dropping it
1345/// is cancel-safe, so losing the race to an arriving export costs nothing.
1346async fn joined(flight: &mut Option<InFlight>) -> Published {
1347 match flight {
1348 Some(f) => (&mut f.task).await,
1349 None => std::future::pending().await,
1350 }
1351}
1352
1353/// Await the block in flight and hand it to [`land`]. The publish half of what
1354/// used to be one straight-line `.await`.
1355#[allow(clippy::too_many_arguments)]
1356async fn settle<B: SignalBuilder>(
1357 mut flight: InFlight,
1358 cfg: &Config,
1359 open_slot: &Shard,
1360 snapped: &Option<(usize, Arc<Open>)>,
1361 rejects: &'static Rejects,
1362 shard: usize,
1363 signal: wal::Signal,
1364) {
1365 let res = (&mut flight.task).await;
1366 land::<B>(flight, res, cfg, open_slot, snapped, rejects, shard, signal);
1367}
1368
1369/// Acknowledge a landed block's waiters and retire its log sequences.
1370///
1371/// Synchronous, because by here the device has already answered: this is the
1372/// same tail the straight-line version ran, with the `.await` lifted out so a
1373/// `select!` arm can reach it too.
1374#[allow(clippy::too_many_arguments)]
1375fn land<B: SignalBuilder>(
1376 flight: InFlight,
1377 res: Published,
1378 cfg: &Config,
1379 open_slot: &Shard,
1380 snapped: &Option<(usize, Arc<Open>)>,
1381 rejects: &'static Rejects,
1382 shard: usize,
1383 signal: wal::Signal,
1384) {
1385 let InFlight {
1386 task: _,
1387 waiters,
1388 block_seqs,
1389 open,
1390 } = flight;
1391 let (rows, seq) = (open.sealed.num_rows, open.seq);
1392 let outcome = match res {
1393 Ok(Ok((bytes, path))) => {
1394 if let Some(w) = &cfg.wal {
1395 w.published(signal, &block_seqs);
1396 }
1397 rejects.published.fetch_add(1, Relaxed);
1398 rejects.rows.fetch_add(rows as u64, Relaxed);
1399 rejects.bytes.fetch_add(bytes, Relaxed);
1400 rejects.clear_stalled(shard);
1401 tracing::info!(signal = B::SIGNAL, rows, bytes, seq, path = %path.display(), "block published");
1402 Ok(())
1403 }
1404 // Logged here and not only counted: a disk that filled up at 02:00
1405 // is the one fact that explains every NACK the senders are about to
1406 // report, and it is invisible from their side.
1407 Ok(Err(e)) => {
1408 rejects.mark_stalled(shard);
1409 tracing::error!(signal = B::SIGNAL, seq, error = %e, "block not published");
1410 Err(e.to_string())
1411 }
1412 Err(e) => {
1413 rejects.mark_stalled(shard);
1414 Err(format!("flush task panicked: {e}"))
1415 }
1416 };
1417 // The rows are on disk now, so the copy the slot was serving them from can
1418 // go and the builder behind it is all that is left to answer with. Dropped
1419 // here rather than at `finish` so they stay visible for the length of the
1420 // rename; the read path discards a snapshot the instant a block with the
1421 // same `(node, seq)` appears on disk, so the overlap shows nothing twice.
1422 drop(open);
1423 open_slot.put(snapped.iter().map(|(_, o)| o.clone()).collect());
1424 for w in waiters {
1425 // Every failure here is the block's, not any one caller's, so they
1426 // all get a retryable answer.
1427 let _ = w.send(outcome.clone().map_err(Rejected::Unavailable));
1428 }
1429}
1430
1431/// Answer every reader waiting on the open block, if there is nothing left
1432/// queued ahead of them (section 4).
1433///
1434/// `pending` is the correctness condition, not an optimisation: a reader is
1435/// promised everything acknowledged before it asked, and an acknowledged export
1436/// is in the channel or in `carry` until the flusher appends it. Answering with
1437/// either non-empty would be answering early. Nothing is lost by waiting —
1438/// non-empty means the loop is about to turn again anyway.
1439///
1440/// The snapshot itself is best-effort. One that fails to build is a query that
1441/// misses the newest rows for a moment; failing the flush over it would turn a
1442/// read-path nicety into an ingest outage, and the same error is about to be
1443/// reported properly by the real seal.
1444#[allow(clippy::too_many_arguments)]
1445fn answer<B: SignalBuilder>(
1446 builder: &B,
1447 asked: &mut Vec<oneshot::Sender<Snapshot>>,
1448 snapped: &mut Option<(usize, Arc<Open>)>,
1449 pending: bool,
1450 // A block of this shard's between `finish` and its rename, if there is
1451 // one. It is the *older* of the two — the builder behind it has already
1452 // started taking rows — and it is on neither the disk nor the builder, so
1453 // an answer that left it out would be a row disappearing under a reader
1454 // that had already been shown it.
1455 in_flight: Option<&Arc<Open>>,
1456 slot: &Shard,
1457 node: u32,
1458 seq: u64,
1459) {
1460 if asked.is_empty() || pending {
1461 return;
1462 }
1463 // Re-copying a block nothing has been appended to since the last answer
1464 // would be pure memcpy, and a live tail asks several times a second for
1465 // exactly that. `approx_bytes` and not a row count because it is the number
1466 // the builder already keeps; appends only ever grow it.
1467 let bytes = builder.approx_bytes();
1468 if builder.is_empty() {
1469 *snapped = None;
1470 } else if snapped.as_ref().map(|(n, _)| *n) != Some(bytes) {
1471 *snapped = match builder.snapshot() {
1472 Ok(sealed) => Some((bytes, Arc::new(Open { node, seq, sealed }))),
1473 Err(e) => {
1474 tracing::debug!(signal = B::SIGNAL, error = %e, "open block not snapshotted");
1475 None
1476 }
1477 };
1478 }
1479 // Oldest first, which is the order the sequences are in.
1480 let cur: Snapshot = in_flight
1481 .into_iter()
1482 .chain(snapped.as_ref().map(|(_, o)| o))
1483 .cloned()
1484 .collect();
1485 slot.put(cur.clone());
1486 for who in asked.drain(..) {
1487 let _ = who.send(cur.clone());
1488 }
1489}
1490
1491/// The size of one block, as the filesystem sees it. Best-effort: a block being
1492/// unlinked by another replica mid-walk is worth a slightly low counter, not an
1493/// error path on the flush.
1494fn dir_bytes(dir: &Path) -> u64 {
1495 std::fs::read_dir(dir)
1496 .into_iter()
1497 .flatten()
1498 .flatten()
1499 .filter_map(|e| e.metadata().ok())
1500 .map(|m| m.len())
1501 .sum()
1502}
1503
1504/// Free space below which retention stops waiting for the TTL.
1505///
1506/// This is not a setting and there is deliberately no key for it. Retention as a
1507/// TTL alone assumes the ingest rate the window was sized for; the first spike,
1508/// chatty service or debug level left on fills the volume before the clock
1509/// expires anything, every `publish` then fails ENOSPC, every export is NACKed,
1510/// and nothing in the process ever undoes it — the only thing that deletes
1511/// blocks is a clock that has not advanced far enough. The number the engine
1512/// needs is not "how full may I get", it is read off the volume every sweep; the
1513/// only constant here is the margin, and 10% is enough headroom for the blocks
1514/// in flight (three signals' `target_block_bytes` plus their staging copies) on
1515/// any volume big enough to hold a day of telemetry, while still leaving the
1516/// sweep room to act before `publish` starts failing.
1517const MIN_FREE: f64 = 0.10;
1518
1519/// Free space below which the margin above stops being a margin, in bytes.
1520///
1521/// [`MIN_FREE`] on its own is a ratio, and a ratio does not know how big the
1522/// volume is. On a 1 TB disk shared with everything else on the machine, 10% is
1523/// 100 GB: a developer sitting at 45 GB free is under the floor, so every block
1524/// is deleted within a sweep of being written, and the only sign is a warning in
1525/// a log nobody is reading. The disk was never in danger — 45 GB is more than
1526/// Mira had ever asked for.
1527///
1528/// So both have to say "full" before anything is deleted, and this is the term
1529/// that has to be true in bytes. It covers what can actually be lost: the blocks
1530/// in flight are three signals' `target_block_bytes` plus their staging copies,
1531/// 192 MiB at the default, and retention sweeps on a 60s interval, so the floor
1532/// also has to absorb whatever lands between two sweeps — a minute of a
1533/// saturated gigabit link is about 7.5 GB. 8 GiB clears both with the margin the
1534/// ratio was there to provide, and stays far under any volume where the ratio is
1535/// the binding term.
1536const MIN_FREE_BYTES: u64 = 8 << 30;
1537
1538/// Drop the oldest blocks, across every signal, until the volume is back above
1539/// `min_free` — the ratio and the byte floor both. Returns what was unlinked,
1540/// oldest first.
1541///
1542/// Deleting data the operator did not ask to lose needs both terms to agree: a
1543/// small volume trips the ratio first and a large one trips the bytes first, and
1544/// either alone is wrong somewhere. See [`MIN_FREE_BYTES`].
1545///
1546/// They are parameters only so a test can say "pretend the volume is full"
1547/// without one; the sweep passes the two constants and nothing else ever will.
1548///
1549/// ponytail: one `statfs` per unlink and one full `scan` per sweep that trips.
1550/// Both are O(blocks) on a path that only runs when the volume is nearly full,
1551/// where the unlink dominates anyway. If a volume ever spends long enough down
1552/// here for that to matter, the fix is to stop after freeing a target fraction
1553/// in one pass rather than re-measuring per block.
1554fn reclaim(
1555 dir: &Path,
1556 min_free: f64,
1557 min_free_bytes: u64,
1558) -> mira_core::error::Result<Vec<PathBuf>> {
1559 let mut dropped = Vec::new();
1560 let (mut free, mut free_bytes) = block::free(dir)?;
1561 if free >= min_free || free_bytes >= min_free_bytes {
1562 return Ok(dropped);
1563 }
1564 // Oldest first across all three signals at once, not one signal at a time:
1565 // the volume is shared, so the block worth losing is the oldest one on it. A
1566 // per-signal sweep would drop an hour-old trace block while a week-old log
1567 // block sat beside it.
1568 let mut blocks = Vec::new();
1569 for s in SIGNALS {
1570 blocks.extend(block::scan(dir, s)?);
1571 }
1572 blocks.sort_by_key(|b| (b.max_ts, b.seq));
1573 for b in blocks {
1574 if free >= min_free || free_bytes >= min_free_bytes {
1575 break;
1576 }
1577 // The unlink `block::expire` does, read the same way: another replica
1578 // sharing this volume getting there first is not a conflict, and a
1579 // block this process cannot remove says nothing about the next one.
1580 match std::fs::remove_dir_all(&b.dir) {
1581 Ok(()) => {
1582 // WARN and one line per block. Deleting a user's telemetry
1583 // before they asked is only defensible if it is impossible to
1584 // miss afterwards, and "which blocks" is the question the
1585 // person who finds the gap will ask.
1586 tracing::warn!(
1587 block = %b.dir.display(),
1588 free = format!("{free:.3}"),
1589 "volume is nearly full; dropped a block that had not reached its retention"
1590 );
1591 dropped.push(b.dir);
1592 }
1593 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1594 Err(e) => tracing::warn!(
1595 block = %b.dir.display(),
1596 error = %e,
1597 "cannot drop block to reclaim space; skipping it",
1598 ),
1599 }
1600 // Re-read rather than subtracting the block's size: compaction, another
1601 // replica and everything else on this volume are all moving it too.
1602 (free, free_bytes) = block::free(dir)?;
1603 }
1604 if !dropped.is_empty() {
1605 // One line for the whole burst above it, carrying the thing the operator
1606 // has to change: the per-block warnings say what went, this says why it
1607 // will keep going.
1608 tracing::warn!(
1609 blocks = dropped.len(),
1610 free = format!("{free:.3}"),
1611 free_bytes,
1612 "dropped blocks ahead of their retention to keep the volume writable; \
1613 retention is longer than this disk can hold at the current ingest rate"
1614 );
1615 }
1616 Ok(dropped)
1617}
1618
1619async fn retention(cfg: Arc<Config>) {
1620 let mut tick = tokio::time::interval(Duration::from_secs(60));
1621 loop {
1622 tick.tick().await;
1623 let dir = cfg.data_dir.clone();
1624 let ttl = cfg.retention;
1625 let node = cfg.node;
1626 let offload = cfg.offload.clone();
1627 let swept = tokio::task::spawn_blocking(move || {
1628 // Wall clock is only used to place the horizons; block timestamps
1629 // themselves come from the data, never from this clock.
1630 let now = std::time::SystemTime::now()
1631 .duration_since(std::time::UNIX_EPOCH)
1632 .unwrap_or_default()
1633 .as_nanos() as i64;
1634 // Saturating, and not `now - ttl.as_nanos() as i64`: a retention
1635 // longer than ~292 years does not fit an `i64` of nanoseconds, and
1636 // `as` wraps it negative — which puts the cutoff in the *future*
1637 // and expires the whole volume on the first sweep. `retention:
1638 // 999999d` is how an operator says "keep it forever", and it used
1639 // to mean the exact opposite.
1640 let cutoff = now.saturating_sub(i64::try_from(ttl.as_nanos()).unwrap_or(i64::MAX));
1641 // One signal failing must not skip the others; a full disk is
1642 // exactly when the remaining sweeps matter most.
1643 let results = SIGNALS.map(|s| {
1644 // With `--offload`, the copy is the hook `expire_with` runs
1645 // just before each unlink, so the block is in the store before
1646 // it leaves the disk and a copy that fails keeps its block for
1647 // the next sweep. Without it, this is the unlink it always was.
1648 let dropped = match &offload {
1649 Some(t) => block::expire_with(&dir, s, cutoff, &|b| t.push(s, b).map(|_| ())),
1650 None => block::expire(&dir, s, cutoff),
1651 };
1652 // Expire first: compressing a block this sweep is about to
1653 // delete is pure wasted bandwidth.
1654 let cold = block::compact(&dir, s, node, now - block::COLD_AFTER_NS);
1655 (s, dropped, cold)
1656 });
1657 // Last, and only then: the TTL is the policy, and free space is the
1658 // floor under it. A sweep that expired enough by the clock has
1659 // nothing to do here and pays one `statfs` to find that out.
1660 //
1661 // `--offload` deliberately does not apply here. This path runs
1662 // because the volume is nearly full and its whole contract is to
1663 // get back over the floor now; putting a copy to an object store in
1664 // front of each unlink means an unreachable store stops reclaiming
1665 // and the disk fills, which is the failure the floor exists to
1666 // prevent. So a block dropped by the floor is gone, and the WARN it
1667 // already logs per block is the record of it.
1668 (results, reclaim(&dir, MIN_FREE, MIN_FREE_BYTES))
1669 })
1670 .await;
1671 match swept {
1672 Ok((results, reclaimed)) => report_sweep(results, &reclaimed),
1673 Err(e) => tracing::warn!(error = %e, "retention task panicked"),
1674 }
1675 }
1676}
1677
1678/// What a finished sweep is worth saying.
1679///
1680/// Its own function rather than the tail of the loop because a sweep only
1681/// happens on a minute's tick over blocks old enough to act on, so under test
1682/// these arms run by coincidence or not at all — and a field that is only
1683/// evaluated when something is listening is exactly the kind that rots unseen.
1684fn report_sweep(
1685 results: [(
1686 &str,
1687 mira_core::error::Result<usize>,
1688 mira_core::error::Result<usize>,
1689 ); 3],
1690 reclaimed: &mira_core::error::Result<Vec<PathBuf>>,
1691) {
1692 // `reclaim` has already logged every block it dropped and why. Only the
1693 // case where it could not even ask the volume is left, and it is a warning
1694 // rather than a stop: a sweep that cannot read free space still expired by
1695 // TTL above.
1696 if let Err(e) = reclaimed {
1697 tracing::warn!(error = %e, "cannot read free space; retention is TTL-only this sweep");
1698 }
1699 for (signal, dropped, cold) in results {
1700 // Nothing dropped says nothing: three signals reporting a zero every
1701 // minute is the entire log of an idle node.
1702 match dropped {
1703 Ok(0) => {}
1704 Ok(n) => tracing::info!(signal, blocks = n, "retention dropped blocks"),
1705 Err(e) => tracing::warn!(signal, error = %e, "retention failed"),
1706 }
1707 match cold {
1708 Ok(0) => {}
1709 Ok(n) => tracing::info!(signal, blocks = n, "compacted blocks to zstd"),
1710 Err(e) => tracing::warn!(signal, error = %e, "compaction failed"),
1711 }
1712 }
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717 use super::*;
1718 use mira_core::logs::LogsBuilder;
1719 use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
1720 use mira_proto::common::v1::{AnyValue, KeyValue, any_value};
1721 use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
1722
1723 fn cfg(name: &str) -> (Arc<Config>, PathBuf) {
1724 let dir = std::env::temp_dir().join(format!("mira-pipe-{name}-{}", std::process::id()));
1725 let _ = std::fs::remove_dir_all(&dir);
1726 std::fs::create_dir_all(&dir).unwrap();
1727 (
1728 Arc::new(Config {
1729 data_dir: dir.clone(),
1730 // Short enough that a test can wait out the age timer, long
1731 // enough that two submits still land in one `recv_many`.
1732 max_block_age: Duration::from_millis(50),
1733 ..Default::default()
1734 }),
1735 dir,
1736 )
1737 }
1738
1739 fn blocks(dir: &std::path::Path) -> usize {
1740 block::scan(dir, "logs").map_or(0, |b| b.len())
1741 }
1742
1743 /// Every published logs block's sequence, ascending.
1744 fn seqs(dir: &std::path::Path) -> Vec<u64> {
1745 let mut v: Vec<u64> = block::scan(dir, "logs")
1746 .unwrap()
1747 .iter()
1748 .map(|b| b.seq)
1749 .collect();
1750 v.sort_unstable();
1751 v
1752 }
1753
1754 /// One record carrying `n` attributes with distinct keys. The key dictionary
1755 /// is the thing with a ceiling, and distinct keys are the only way to reach
1756 /// it — a million records sharing one key never do.
1757 fn wide(n: usize) -> ExportLogsServiceRequest {
1758 ExportLogsServiceRequest {
1759 resource_logs: vec![ResourceLogs {
1760 scope_logs: vec![ScopeLogs {
1761 log_records: vec![LogRecord {
1762 time_unix_nano: 1_000,
1763 attributes: (0..n)
1764 .map(|i| KeyValue {
1765 key: format!("k{i}"),
1766 value: Some(AnyValue {
1767 value: Some(any_value::Value::StringValue("v".into())),
1768 }),
1769 })
1770 .collect(),
1771 ..Default::default()
1772 }],
1773 ..Default::default()
1774 }],
1775 ..Default::default()
1776 }],
1777 }
1778 }
1779
1780 /// A request that does not fit the open block is deferred into the next one,
1781 /// never refused and never reordered.
1782 ///
1783 /// Both submits are acknowledged, so neither caller loses its data, and both
1784 /// blocks land — which is the difference between "the dictionary is full" and
1785 /// "your export is rejected". The second is what a client sees as a permanent
1786 /// failure for data whose real cardinality was fine.
1787 #[tokio::test]
1788 async fn a_request_that_does_not_fit_lands_in_the_next_block() {
1789 let (c, dir) = cfg("carry");
1790 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1791 // 40k distinct keys each: the first fits an empty block, the second
1792 // cannot join it, and 80k would overflow the u16 dictionary.
1793 let (a, b) = tokio::join!(tx.submit(wide(40_000)), tx.submit(wide(40_000)));
1794 assert!(a.is_ok() && b.is_ok(), "both callers must be acknowledged");
1795 drop(tx);
1796 h.await.unwrap();
1797 assert_eq!(blocks(&dir), 2, "the deferred request got its own block");
1798 let _ = std::fs::remove_dir_all(&dir);
1799 }
1800
1801 /// The case the headroom hint deliberately cannot answer: one request that
1802 /// is too wide for *any* block. Sealing first cannot help, so the append is
1803 /// attempted and its failure is the caller's answer — after which the
1804 /// builder has to be usable again, or the node rejects everything until it
1805 /// is restarted.
1806 #[tokio::test]
1807 async fn an_impossible_request_fails_only_itself() {
1808 let (c, dir) = cfg("toowide");
1809 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1810 let before = tx.rejects.failed.load(Relaxed);
1811 let destroyed = tx.rejects.refused.load(Relaxed);
1812 // `Failed`, not `Unavailable`: this one is permanent, and the receiver
1813 // turns the two into statuses an exporter treats differently.
1814 let refusal = tx.submit(wide(70_000)).await;
1815 assert!(
1816 matches!(&refusal, Err(Rejected::Failed(e))
1817 if e.contains("65535") || e.contains("dictionary")),
1818 "70k distinct keys cannot fit a u16 dictionary, and the refusal has \
1819 to be the permanent one that names why"
1820 );
1821 // `>`, not `== before + 1`: `REJECTS` is process-wide and the other
1822 // tests in this file refuse logs exports of their own, in parallel.
1823 assert!(tx.rejects.failed.load(Relaxed) > before);
1824 // Counted apart from `failed`, because this is the only refusal in the
1825 // pipeline that destroys data: the sender is told not to retry and it
1826 // will not. A number nobody can read is a deletion nobody can audit.
1827 assert!(tx.rejects.refused.load(Relaxed) > destroyed);
1828 // The next export proves the builder was replaced, not poisoned.
1829 tx.submit(crate::e2e::logs_export("checkout", 2_000, 4))
1830 .await
1831 .unwrap_or_else(|_| panic!("the pipeline is still open for business"));
1832 drop(tx);
1833 h.await.unwrap();
1834 assert_eq!(blocks(&dir), 1, "only the good export was published");
1835 let _ = std::fs::remove_dir_all(&dir);
1836 }
1837
1838 /// An export with no records is legal and the Collector sends them. There is
1839 /// nothing in it to make durable, so parking its caller behind a block that
1840 /// will never be sealed strands them for as long as they are willing to wait.
1841 #[tokio::test]
1842 async fn an_empty_export_is_acknowledged_without_a_block() {
1843 let (c, dir) = cfg("empty");
1844 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1845 // No timeout needed: if this ever blocks, it blocks forever, and the
1846 // test harness reports the hang for what it is.
1847 tx.submit(ExportLogsServiceRequest::default())
1848 .await
1849 .unwrap_or_else(|_| panic!("an empty export is not an error"));
1850 drop(tx);
1851 h.await.unwrap();
1852 assert_eq!(blocks(&dir), 0, "nothing to seal, so nothing was sealed");
1853 let _ = std::fs::remove_dir_all(&dir);
1854 }
1855
1856 /// The whole point of the log, in one assertion: with one configured, the
1857 /// acknowledgement lands while the block is still open.
1858 ///
1859 /// `max_block_age` is a full second here and the submit is not allowed to
1860 /// take a tenth of it. Without the log that submit is the block age by
1861 /// definition — it is section 11's 2,647 ms p99 — so a regression that quietly
1862 /// puts the ack back behind the publish fails this by a factor of ten
1863 /// rather than by a margin that could be scheduler noise.
1864 #[tokio::test]
1865 async fn a_logged_export_is_acknowledged_before_its_block_is_sealed() {
1866 let dir = std::env::temp_dir().join(format!("mira-pipe-wal-{}", std::process::id()));
1867 let _ = std::fs::remove_dir_all(&dir);
1868 std::fs::create_dir_all(&dir).unwrap();
1869 let node = block::node_id("waltest");
1870 let wal = Arc::new(Wal::open(&dir, node).unwrap());
1871 let c = Arc::new(Config {
1872 data_dir: dir.clone(),
1873 node,
1874 max_block_age: Duration::from_secs(1),
1875 wal: Some(Arc::clone(&wal)),
1876 ..Default::default()
1877 });
1878 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1879
1880 let started = std::time::Instant::now();
1881 tx.submit(crate::e2e::logs_export("checkout", 2_000, 4))
1882 .await
1883 .unwrap_or_else(|_| panic!("the log accepted it"));
1884 let acked = started.elapsed();
1885 assert!(
1886 acked < Duration::from_millis(100),
1887 "acknowledged in {acked:?}, which is the block age, not the log"
1888 );
1889 assert_eq!(blocks(&dir), 0, "the ack did not wait for a block");
1890 assert_eq!(wal.next_seq(), 1, "the export is a frame");
1891
1892 drop(tx);
1893 h.await.unwrap();
1894
1895 // The block claims the frame, so the next boot does not replay it. The
1896 // watermark is exclusive and nothing else is pending, so it is the
1897 // log's `next_seq` — 1, for the single frame 0.
1898 let published = block::scan(&dir, "logs").unwrap();
1899 assert_eq!(published.len(), 1);
1900 assert_eq!(published[0].wal_hi, 1);
1901 assert_eq!(block::wal_watermarks(&dir, node).unwrap(), [1, 0, 0]);
1902 let _ = std::fs::remove_dir_all(&dir);
1903 }
1904
1905 /// A frame that no block claims comes back, under its own sequence, and
1906 /// then *is* claimed — so the boot after that one replays nothing.
1907 ///
1908 /// Convergence is the property, not recovery. Re-appending a replayed frame
1909 /// instead of carrying its sequence would leave the original uncovered and
1910 /// replay it again at every start, for ever, growing the log each time.
1911 #[tokio::test]
1912 async fn a_replayed_frame_is_claimed_by_the_block_that_finally_stores_it() {
1913 let dir = std::env::temp_dir().join(format!("mira-pipe-replay-{}", std::process::id()));
1914 let _ = std::fs::remove_dir_all(&dir);
1915 std::fs::create_dir_all(&dir).unwrap();
1916 let node = block::node_id("replaytest");
1917
1918 // A crash: framed, never sealed. Dropping the log without `sync` is the
1919 // harsher case — the frames are only in the page cache, which is what
1920 // an acknowledgement here promises and all it promises.
1921 let wal = Wal::open(&dir, node).unwrap();
1922 let body = {
1923 use prost::Message as _;
1924 crate::e2e::logs_export("checkout", 2_000, 4).encode_to_vec()
1925 };
1926 wal.append(wal::Signal::Logs, &body).unwrap();
1927 wal.append(wal::Signal::Logs, &body).unwrap();
1928 drop(wal);
1929
1930 let wal = Arc::new(Wal::open(&dir, node).unwrap());
1931 let c = Arc::new(Config {
1932 data_dir: dir.clone(),
1933 node,
1934 max_block_age: Duration::from_millis(50),
1935 wal: Some(Arc::clone(&wal)),
1936 ..Default::default()
1937 });
1938 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1939 let replayed = {
1940 let tx = tx.clone();
1941 let dir = dir.clone();
1942 tokio::task::spawn_blocking(move || {
1943 Wal::replay(&dir, node, [0, 0, 0], |_, seq, body| {
1944 assert!(tx.replay(body, seq).is_ok(), "the flusher took it");
1945 Ok(())
1946 })
1947 .unwrap()
1948 })
1949 .await
1950 .unwrap()
1951 };
1952 assert_eq!(replayed.replayed, 2);
1953
1954 drop(tx);
1955 h.await.unwrap();
1956 assert_eq!(block::wal_watermarks(&dir, node).unwrap(), [2, 0, 0]);
1957
1958 // The second boot: every frame is behind the watermark, so nothing is
1959 // handed back and the log can be truncated.
1960 let again = Wal::replay(
1961 &dir,
1962 node,
1963 block::wal_watermarks(&dir, node).unwrap(),
1964 |_, _, _| unreachable!("a frame a block already claims must never be replayed again"),
1965 )
1966 .unwrap();
1967 assert_eq!((again.replayed, again.skipped), (0, 2));
1968 let _ = std::fs::remove_dir_all(&dir);
1969 }
1970
1971 /// A volume that stops accepting blocks NACKs retryably. Nobody is told
1972 /// their export is stored, and the signal starts counting as stalled —
1973 /// which is what `/health` reads, and what takes this node out of a load
1974 /// balancer instead of leaving it silently eating telemetry.
1975 #[tokio::test]
1976 async fn a_block_that_cannot_be_published_is_a_retryable_answer() {
1977 let (c, dir) = cfg("unpublishable");
1978 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
1979 // A file where the staging directory belongs: every publish fails at its
1980 // first `create_dir_all` and none of them can reach the block tree. That
1981 // is the shape of a full or detached volume without needing one, and it
1982 // is the one the flusher cannot see at startup — a signal directory it
1983 // cannot scan stops it before it takes a single export.
1984 std::fs::write(dir.join(".tmp"), b"not a directory").unwrap();
1985
1986 let answer = tx.submit(wide(1)).await;
1987 assert!(
1988 matches!(&answer, Err(Rejected::Unavailable(why)) if !why.is_empty()),
1989 "a publish that failed has to be answered retryably, and with a reason: \
1990 `Failed` would have the exporter drop the batch, and an empty string \
1991 leaves the operator reading the sender's log for a disk fault"
1992 );
1993 // Not asserted here: the stall clock this also starts. `REJECTS` is
1994 // process-wide and the other tests in this file publish into it, so the
1995 // threshold is pinned on a local `Rejects` instead — see
1996 // `a_stall_is_only_reportable_once_it_has_outlasted_the_recovery`.
1997 drop(tx);
1998 h.await.unwrap();
1999 let _ = std::fs::remove_dir_all(&dir);
2000 }
2001
2002 /// An export too large to frame is the one log failure the sender can fix,
2003 /// so it is the one that comes back as permanent. Retrying it would burn the
2004 /// link forever: the second attempt is the same bytes and the same refusal.
2005 #[tokio::test]
2006 async fn an_export_too_large_for_a_frame_is_refused_permanently() {
2007 let dir = std::env::temp_dir().join(format!("mira-pipe-huge-{}", std::process::id()));
2008 let _ = std::fs::remove_dir_all(&dir);
2009 std::fs::create_dir_all(&dir).unwrap();
2010 let node = block::node_id("hugetest");
2011 let c = Arc::new(Config {
2012 data_dir: dir.clone(),
2013 node,
2014 wal: Some(Arc::new(Wal::open(&dir, node).unwrap())),
2015 ..Default::default()
2016 });
2017 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2018
2019 let mut req = wide(1);
2020 req.resource_logs[0].scope_logs[0].log_records[0].body = Some(AnyValue {
2021 value: Some(any_value::Value::StringValue("x".repeat(64 << 20))),
2022 });
2023 let answer = tx.submit(req).await;
2024 assert!(
2025 matches!(&answer, Err(Rejected::Failed(why)) if why.contains("frame")),
2026 "an export that can never be framed has to be refused permanently and \
2027 named as a framing limit; retrying it burns the link on the same bytes"
2028 );
2029
2030 drop(tx);
2031 h.await.unwrap();
2032 assert_eq!(blocks(&dir), 0, "nothing was framed, so nothing was stored");
2033 let _ = std::fs::remove_dir_all(&dir);
2034 }
2035
2036 /// The sweep is two jobs on one blocking hop, and only every 240th tick
2037 /// does the second: a sync every quarter second, a truncate every minute.
2038 ///
2039 /// The open segment is never dropped, whichever tick it is, so what the
2040 /// first half pins is the watermark arithmetic being reached at all, and a
2041 /// truncate half that fails leaving the sync half done rather than taking
2042 /// the maintenance task down with it.
2043 ///
2044 /// Then the case where the slow tick does have something to remove: the
2045 /// slow tick is the only thing that ever shrinks the log, and a sweep that
2046 /// removed a segment on the fast tick — or left a dead one on the slow one
2047 /// — is the difference between a log that stays bounded and one that drops
2048 /// frames no block has claimed yet.
2049 #[tokio::test]
2050 async fn a_wal_sweep_syncs_every_tick_and_only_truncates_on_the_slow_one() {
2051 let dir = std::env::temp_dir().join(format!("mira-pipe-sweep-{}", std::process::id()));
2052 let _ = std::fs::remove_dir_all(&dir);
2053 std::fs::create_dir_all(&dir).unwrap();
2054 let node = block::node_id("sweeptest");
2055 let wal = Arc::new(Wal::open(&dir, node).unwrap());
2056 wal.append(wal::Signal::Logs, b"a frame").unwrap();
2057 // Segments only. The log's directory also holds the writer lock this
2058 // node took at `Wal::open`, which no sweep has any business removing.
2059 let segments = |dir: &std::path::Path| {
2060 std::fs::read_dir(dir.join(".wal"))
2061 .unwrap()
2062 .filter(|e| {
2063 e.as_ref()
2064 .unwrap()
2065 .path()
2066 .extension()
2067 .is_some_and(|x| x == "wal")
2068 })
2069 .count()
2070 };
2071
2072 // The common tick: sync, and nothing else looked at.
2073 wal_sweep(Arc::clone(&wal), dir.clone(), false).await;
2074 // The 240th: no block claims that frame, so the covered watermark is 0
2075 // and the segment holding it stays.
2076 wal_sweep(Arc::clone(&wal), dir.clone(), true).await;
2077 assert_eq!(wal.next_seq(), 1, "a sweep renumbers nothing");
2078 assert_eq!(segments(&dir), 1, "the open segment is never dropped");
2079
2080 // A truncate that cannot read the block tree is a warning, not a stop:
2081 // the sync half already happened and the next append still lands. A
2082 // file where the `logs` directory belongs is the cheapest unreadable
2083 // tree — a *missing* one is legitimately empty, and scans as such.
2084 let bad = dir.join("unreadable");
2085 std::fs::create_dir_all(&bad).unwrap();
2086 std::fs::write(bad.join("logs"), b"not a directory").unwrap();
2087 wal_sweep(Arc::clone(&wal), bad, true).await;
2088 wal.append(wal::Signal::Logs, b"another").unwrap();
2089 assert_eq!(wal.next_seq(), 2);
2090
2091 // The segment a crash between `roll` and the first append leaves: no
2092 // frames, so no watermark can ever cover it, and the empty-segment rule
2093 // is the only thing that will ever get rid of it.
2094 let stale = dir.join(".wal").join(format!("{node:08x}-{:020}.wal", 9));
2095 std::fs::File::create(&stale).unwrap();
2096 wal_sweep(Arc::clone(&wal), dir.clone(), false).await;
2097 assert!(stale.exists(), "a sync is not a truncation");
2098 wal_sweep(Arc::clone(&wal), dir.clone(), true).await;
2099 assert!(!stale.exists(), "the slow tick removed the dead segment");
2100 assert_eq!(
2101 segments(&dir),
2102 1,
2103 "and left the open one, which is still holding two unclaimed frames"
2104 );
2105 let _ = std::fs::remove_dir_all(&dir);
2106 }
2107
2108 /// A queue that stays full past [`ADMIT_WAIT`] sheds, and shedding has to be
2109 /// distinguishable from shutdown: `Busy` is retryable and `Closed` is not,
2110 /// and an exporter that confuses them either drops good data or hammers a
2111 /// draining node.
2112 ///
2113 /// `start_paused`, so the five seconds are five seconds of the test's clock.
2114 /// Tokio only auto-advances once every task is idle, which here is exactly
2115 /// the state the wait is supposed to end in.
2116 #[tokio::test(start_paused = true)]
2117 async fn a_full_queue_sheds_and_a_closed_one_says_so() {
2118 let (tx, rx) = mpsc::channel::<Job<ExportLogsServiceRequest>>(1);
2119 let rejects = &REJECTS[0];
2120 let ingest = Ingest {
2121 tx: [tx].into(),
2122 turn: Arc::default(),
2123 rejects,
2124 wal: None,
2125 signal: wal::Signal::Logs,
2126 };
2127 let req = || ExportLogsServiceRequest::default();
2128 // Relative, not absolute: the counters are process-wide and every other
2129 // test in this binary shares them.
2130 let before = rejects.shed.load(Relaxed);
2131
2132 // Nothing is reading, so the first send fills the channel and the
2133 // second finds no permit. The first never returns; that is the point.
2134 let pending = tokio::spawn({
2135 let i = ingest.clone();
2136 async move { i.submit(req()).await }
2137 });
2138 while rx.capacity() > 0 {
2139 tokio::task::yield_now().await;
2140 }
2141 assert!(matches!(ingest.submit(req()).await, Err(Rejected::Busy)));
2142 // Shedding is counted, because a 503 with no server-side number behind
2143 // it is a fact the operator can only get from the sender's log.
2144 assert_eq!(rejects.shed.load(Relaxed), before + 1);
2145
2146 // The flusher is gone. In flight becomes `Closed` because the ack sender
2147 // dropped with it; new work becomes `Closed` because the channel did.
2148 drop(rx);
2149 assert!(matches!(pending.await.unwrap(), Err(Rejected::Closed)));
2150 assert!(matches!(ingest.submit(req()).await, Err(Rejected::Closed)));
2151 }
2152
2153 /// The other half of that contract, and the one the measurement is about: a
2154 /// queue that is full *now* but drains inside [`ADMIT_WAIT`] admits the
2155 /// export instead of shedding it. Without this the sender re-sends bytes
2156 /// this node has already decoded, which at 96 connections cost 93% of
2157 /// exports and two thirds of the throughput.
2158 #[tokio::test(start_paused = true)]
2159 async fn a_queue_that_drains_inside_the_wait_admits_instead_of_shedding() {
2160 let (tx, mut rx) = mpsc::channel::<Job<ExportLogsServiceRequest>>(1);
2161 // Its own counter, not `REJECTS[0]`: this one asserts that *nothing* was
2162 // shed, and the process-wide slot is being written by whichever other
2163 // test in this binary is running beside it.
2164 let rejects: &'static Rejects = Box::leak(Box::new(Rejects::new("logs")));
2165 let ingest = Ingest {
2166 tx: [tx].into(),
2167 turn: Arc::default(),
2168 rejects,
2169 wal: None,
2170 signal: wal::Signal::Logs,
2171 };
2172 let req = || ExportLogsServiceRequest::default();
2173
2174 // Fill it, and leave the filler parked on its ack so the slot stays
2175 // taken until something reads.
2176 let first = tokio::spawn({
2177 let i = ingest.clone();
2178 async move { i.submit(req()).await }
2179 });
2180 while rx.capacity() > 0 {
2181 tokio::task::yield_now().await;
2182 }
2183
2184 // A second export finds no permit and waits. A reader that comes back
2185 // four seconds later — inside the wait, well past anything `try_reserve`
2186 // would have tolerated — frees the slot, and the waiter takes it.
2187 let waiter = tokio::spawn({
2188 let i = ingest.clone();
2189 async move { i.submit(req()).await }
2190 });
2191 tokio::time::sleep(Duration::from_secs(4)).await;
2192 let job = rx.recv().await.expect("the filler's job");
2193 let _ = job.ack.send(Ok(()));
2194 assert!(matches!(first.await.unwrap(), Ok(())));
2195
2196 // The waiter is now queued rather than shed. Ack it the same way.
2197 let job = rx.recv().await.expect("the waiter's job");
2198 let _ = job.ack.send(Ok(()));
2199 assert!(matches!(waiter.await.unwrap(), Ok(())));
2200 assert_eq!(rejects.shed.load(Relaxed), 0, "nothing was shed");
2201 }
2202
2203 /// A data directory that cannot be scanned stops the flusher at startup
2204 /// rather than at the first flush. Sequence numbers are resumed from what is
2205 /// on disk, so a pipeline that could not read it would reuse a sequence and
2206 /// never publish again — failing loudly here is the cheaper end of that.
2207 #[tokio::test]
2208 async fn an_unreadable_data_directory_stops_the_flusher_at_startup() {
2209 let (c, dir) = cfg("unscannable");
2210 std::fs::write(dir.join("logs"), b"not a directory").unwrap();
2211 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2212 h.await.unwrap();
2213 assert!(matches!(
2214 tx.submit(ExportLogsServiceRequest::default()).await,
2215 Err(Rejected::Closed)
2216 ));
2217 let _ = std::fs::remove_dir_all(&dir);
2218 }
2219
2220 /// Retention runs on a timer, and `interval` fires its first tick straight
2221 /// away — so a zero TTL expires everything on the first pass, with no clock
2222 /// to advance and no sleep to wait out.
2223 #[tokio::test]
2224 async fn retention_drops_expired_blocks_on_its_first_pass() {
2225 let (c, dir) = cfg("retention");
2226 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2227 tx.submit(crate::e2e::logs_export("checkout", 1_000, 4))
2228 .await
2229 .unwrap_or_else(|_| panic!("export"));
2230 drop(tx);
2231 h.await.unwrap();
2232 assert_eq!(blocks(&dir), 1);
2233
2234 spawn_retention(Arc::new(Config {
2235 data_dir: dir.clone(),
2236 retention: Duration::ZERO,
2237 ..Default::default()
2238 }));
2239 // The sweep is a `spawn_blocking`, so yielding is not enough to see it.
2240 until(|| blocks(&dir) == 0).await;
2241 assert_eq!(blocks(&dir), 0, "a block older than its TTL is unlinked");
2242 let _ = std::fs::remove_dir_all(&dir);
2243 }
2244
2245 /// The same sweep with `--offload` set: the block leaves the disk and is
2246 /// in the store, in that order.
2247 ///
2248 /// `mira_core::offload` owns the copy and tests it; what this covers is the
2249 /// wiring — that the retention worker passes the target down rather than
2250 /// taking the plain `expire` branch. Mutation check: swap the `match` in
2251 /// `retention` for an unconditional `block::expire` and the store is empty
2252 /// here while the local count still reaches zero.
2253 #[tokio::test]
2254 async fn retention_with_offload_puts_the_block_in_the_store_before_unlinking_it() {
2255 let (c, dir) = cfg("retention-offload");
2256 let store = dir.join("cold");
2257 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2258 tx.submit(crate::e2e::logs_export("checkout", 1_000, 4))
2259 .await
2260 .unwrap_or_else(|_| panic!("export"));
2261 drop(tx);
2262 h.await.unwrap();
2263 assert_eq!(blocks(&dir), 1);
2264
2265 let target = mira_core::offload::Target::parse(&format!("file://{}", store.display()))
2266 .expect("file:// target");
2267 spawn_retention(Arc::new(Config {
2268 data_dir: dir.clone(),
2269 retention: Duration::ZERO,
2270 offload: Some(target.clone()),
2271 ..Default::default()
2272 }));
2273 for _ in 0..200 {
2274 if blocks(&dir) == 0 {
2275 break;
2276 }
2277 tokio::time::sleep(Duration::from_millis(10)).await;
2278 }
2279 assert_eq!(blocks(&dir), 0, "the local copy still goes");
2280 assert_eq!(
2281 target.list("logs").unwrap().len(),
2282 1,
2283 "and the store has it, listed by name with no index written"
2284 );
2285 let _ = std::fs::remove_dir_all(&dir);
2286 }
2287
2288 /// A volume that fills faster than the TTL expires is the outage the whole
2289 /// stack exists to explain, and before this it was permanent: every
2290 /// `publish` ENOSPC, every export NACKed, and the only thing that deletes
2291 /// blocks a clock that has not advanced far enough.
2292 ///
2293 /// The order is the contract, not the count. Three blocks are published with
2294 /// their timestamps deliberately out of sequence order, so a sweep that
2295 /// walked the directory as `scan` returns it — or in the order the blocks
2296 /// were written — would drop the newest first and delete the data the
2297 /// incident is being read out of.
2298 #[tokio::test]
2299 async fn a_full_volume_drops_the_oldest_blocks_before_their_ttl() {
2300 let (c, dir) = cfg("space");
2301 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2302 // Awaited one at a time: `submit` returns only once the block holding it
2303 // is durable, so each of these is a block of its own.
2304 for ts in [3_000_000, 1_000_000, 2_000_000] {
2305 tx.submit(crate::e2e::logs_export("checkout", ts, 4))
2306 .await
2307 .unwrap_or_else(|_| panic!("export"));
2308 }
2309 drop(tx);
2310 h.await.unwrap();
2311 assert_eq!(blocks(&dir), 3);
2312
2313 // Publishing is counted, or `/api/v1/stats` is three zeroes. Relative
2314 // and monotone, because every other test in this binary shares these.
2315 let logs = rejects_for("logs");
2316 assert!(logs.published.load(Relaxed) >= 3, "blocks are counted");
2317 assert!(logs.rows.load(Relaxed) >= 12, "rows are counted");
2318 assert!(logs.bytes.load(Relaxed) > 0, "bytes on disk are counted");
2319
2320 // The TTL is the policy and free space is only the floor under it, so a
2321 // volume with room loses nothing whatever its blocks' ages.
2322 assert!(reclaim(&dir, 0.0, 0).unwrap().is_empty());
2323
2324 // Margins no real volume can satisfy stand in for a full disk: every
2325 // block goes, oldest first, and the returned order is that order.
2326 let mut want = block::scan(&dir, "logs").unwrap();
2327 want.sort_by_key(|b| b.max_ts);
2328 let want: Vec<PathBuf> = want.into_iter().map(|b| b.dir).collect();
2329 assert_eq!(reclaim(&dir, 2.0, u64::MAX).unwrap(), want);
2330 assert_eq!(blocks(&dir), 0);
2331 let _ = std::fs::remove_dir_all(&dir);
2332 }
2333
2334 /// Runs `f` with a subscriber attached.
2335 ///
2336 /// Not decoration. A `tracing` field whose value is a call —
2337 /// `%dir.display()`, `format!("{free:.3}")` — is not evaluated at all when
2338 /// nothing is listening, so the code that builds the warnings below only
2339 /// *runs* under this. Thread-local rather than global, so the flushers the
2340 /// other tests in this binary are running stay quiet.
2341 fn listening<T>(f: impl FnOnce() -> T) -> T {
2342 let sub = tracing_subscriber::fmt()
2343 .with_max_level(tracing::Level::TRACE)
2344 .with_test_writer()
2345 .finish();
2346 tracing::subscriber::with_default(sub, f)
2347 }
2348
2349 /// Every arm of the sweep report, driven directly.
2350 ///
2351 /// What this proves is what `listening` exists for and no more: that each
2352 /// arm's fields actually *evaluate*. It does not read the output back —
2353 /// there is nothing here worth a capturing writer for. The reason it is a
2354 /// test at all is that a real sweep needs a minute's tick and blocks old
2355 /// enough to act on, so whether these arms ran during a test run used to be
2356 /// a coincidence, and a line covered by coincidence is not covered.
2357 #[test]
2358 fn a_sweep_reports_what_it_did_and_a_quiet_one_says_nothing() {
2359 let bad = || mira_core::error::Error::BadMagic {
2360 path: PathBuf::from("/data/logs/0000"),
2361 };
2362 listening(|| {
2363 // Nothing to say, and the volume answered: silent on every arm.
2364 report_sweep(
2365 [
2366 ("logs", Ok(0), Ok(0)),
2367 ("traces", Ok(0), Ok(0)),
2368 ("metrics", Ok(0), Ok(0)),
2369 ],
2370 &Ok(Vec::new()),
2371 );
2372 // One signal expired, one compacted, one failed at both — and the
2373 // floor could not be read. A signal failing does not silence the
2374 // two beside it, which is the property the loop is built around.
2375 report_sweep(
2376 [
2377 ("logs", Ok(2), Ok(0)),
2378 ("traces", Ok(0), Ok(1)),
2379 ("metrics", Err(bad()), Err(bad())),
2380 ],
2381 &Err(bad()),
2382 );
2383 });
2384 }
2385
2386 /// Polls `done` for a minute. The sweeps below run on a blocking thread, so
2387 /// yielding is not enough to see one land, and a fixed sleep is either a
2388 /// flake on a loaded machine or dead time on an idle one.
2389 ///
2390 /// The budget was two seconds and that was not enough: with all twelve cores
2391 /// busy, three of the sweep tests here fail together, because a
2392 /// `spawn_blocking` that has to queue behind the machine takes longer than
2393 /// the poll waits. Polling is what makes a generous budget free — the wait
2394 /// ends when the condition holds, so a minute costs an idle machine nothing
2395 /// and only ever spends itself on a failure that was going to happen anyway.
2396 async fn until(mut done: impl FnMut() -> bool) -> bool {
2397 for _ in 0..6_000 {
2398 if done() {
2399 return true;
2400 }
2401 tokio::time::sleep(Duration::from_millis(10)).await;
2402 }
2403 done()
2404 }
2405
2406 /// A block directory with nothing in it. `scan` reads the name and
2407 /// `reclaim` unlinks the directory; neither opens a table, so a test about
2408 /// *which* blocks go does not need a flusher to produce them.
2409 fn fake_block(dir: &Path, signal: &str, max_ts: i64, seq: u64) -> PathBuf {
2410 let partition = dir.join(signal).join("p=1970-01-01-00");
2411 std::fs::create_dir_all(&partition).unwrap();
2412 let block = partition.join(format!(
2413 "{:020}-{max_ts:020}-{:08x}-{seq:012}-{:020}",
2414 0, 7, 0
2415 ));
2416 std::fs::create_dir_all(&block).unwrap();
2417 block
2418 }
2419
2420 /// Shedding is thousands of exports a second when it happens at all: the
2421 /// counter has to take every one of them and the log has to take one a
2422 /// second, or the incident is either invisible or drowned in its own
2423 /// warnings. A local `Rejects`, not the process-wide one, so the count is
2424 /// exact rather than a lower bound.
2425 #[test]
2426 fn every_shed_export_is_counted_and_at_most_one_a_second_is_logged() {
2427 let gate = AtomicU64::new(0);
2428 assert!(once_a_second(&gate), "the first caller in a second speaks");
2429 assert!(!once_a_second(&gate), "and everyone behind it is silent");
2430
2431 let r = Rejects::new("logs");
2432 listening(|| {
2433 for _ in 0..3 {
2434 r.record_shed();
2435 }
2436 });
2437 assert_eq!(r.shed.load(Relaxed), 3, "every shed export is counted");
2438 assert_ne!(
2439 r.warned.load(Relaxed),
2440 0,
2441 "the gate is armed, so the next thousand this second are silent"
2442 );
2443 }
2444
2445 /// A log that cannot take a frame is not the sender's fault unless the
2446 /// frame is too large, and the difference is the whole failure contract: a
2447 /// full or detached volume answered `Failed` has every exporter drop the
2448 /// batch it is holding, which is data loss chosen by an error variant.
2449 #[tokio::test]
2450 async fn a_log_failure_that_is_not_the_senders_fault_is_answered_retryably() {
2451 let dir = std::env::temp_dir().join(format!("mira-pipe-walgone-{}", std::process::id()));
2452 let _ = std::fs::remove_dir_all(&dir);
2453 std::fs::create_dir_all(&dir).unwrap();
2454 let node = block::node_id("walgone");
2455 let wal = Arc::new(Wal::open(&dir, node).unwrap());
2456 // One segment's worth, so the next append has to roll to a new file.
2457 // The size trigger is the only way in from here — `Wal`'s internals are
2458 // private to `mira-core` — and it buys the one failure that is neither
2459 // "too large" nor a corrupt disk.
2460 wal.append(wal::Signal::Logs, &vec![0u8; 64 << 20]).unwrap();
2461 let c = Arc::new(Config {
2462 data_dir: dir.clone(),
2463 node,
2464 wal: Some(Arc::clone(&wal)),
2465 ..Default::default()
2466 });
2467 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2468 // The log's directory, removed under it: the roll cannot create its
2469 // successor, which is what a volume that went away looks like from
2470 // inside `append`.
2471 std::fs::remove_dir_all(dir.join(".wal")).unwrap();
2472
2473 let answer = tx.submit(wide(1)).await;
2474 assert!(
2475 matches!(&answer, Err(Rejected::Unavailable(why)) if !why.is_empty()),
2476 "a log that cannot write must be retryable and say why"
2477 );
2478 drop(tx);
2479 h.await.unwrap();
2480 let _ = std::fs::remove_dir_all(&dir);
2481 }
2482
2483 /// `spawn_retention` only starts the maintenance task when a log is
2484 /// configured, and the guard inside it is what makes that safe to get
2485 /// wrong: without it the task would tick four times a second on a node
2486 /// that has nothing to sync.
2487 #[tokio::test]
2488 async fn wal_maintenance_without_a_log_has_nothing_to_do() {
2489 let (c, dir) = cfg("nowal");
2490 assert!(
2491 c.wal.is_none(),
2492 "the shipped default for this test's config"
2493 );
2494 // It returns. If the guard were gone this would tick for ever and the
2495 // timeout, not the assertion, would be the failure.
2496 tokio::time::timeout(Duration::from_millis(250), wal_maintenance(c))
2497 .await
2498 .expect("a node with no log has no maintenance loop to run");
2499 let _ = std::fs::remove_dir_all(&dir);
2500 }
2501
2502 /// A staging directory is what a `publish` killed mid-write leaves behind.
2503 /// Nothing will ever finish it and nothing reads it, so a boot that did not
2504 /// sweep it would leak a copy of a whole block per crash onto the volume
2505 /// retention is trying to keep free.
2506 #[tokio::test]
2507 async fn a_staging_directory_a_crash_left_behind_is_swept_at_boot() {
2508 let (c, dir) = cfg("staging");
2509 let node = c.node;
2510 let stale = dir
2511 .join(".tmp")
2512 .join(format!("logs-{node:08x}-000000000007"));
2513 std::fs::create_dir_all(&stale).unwrap();
2514 std::fs::write(stale.join("logs.arrow"), b"half a block").unwrap();
2515 // Another node's staging directory, on the shared volume of section 12: not
2516 // this process's to remove, and removing it would delete a block a live
2517 // replica is part-way through writing.
2518 let theirs = dir
2519 .join(".tmp")
2520 .join(format!("logs-{:08x}-000000000007", 0));
2521 std::fs::create_dir_all(&theirs).unwrap();
2522
2523 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2524 tx.submit(ExportLogsServiceRequest::default())
2525 .await
2526 .unwrap_or_else(|_| panic!("the flusher booted"));
2527 drop(tx);
2528 h.await.unwrap();
2529
2530 assert!(!stale.exists(), "the leaked staging directory is gone");
2531 assert!(
2532 theirs.exists(),
2533 "another replica's is not this node's to take"
2534 );
2535 let _ = std::fs::remove_dir_all(&dir);
2536 }
2537
2538 /// A builder that fails where the real ones only fail on a request no
2539 /// block can hold. `SEAL` picks which of the two seams breaks: the seal
2540 /// that publishes, or the snapshot the read path asks for. Reaching either
2541 /// through `LogsBuilder` would take a 65k-key request per attempt, and
2542 /// what is under test is not the encoder — it is what the flusher promises
2543 /// when an encoder does fail.
2544 #[derive(Default)]
2545 struct Brittle<const SEAL: bool>(LogsBuilder);
2546
2547 impl<const SEAL: bool> SignalBuilder for Brittle<SEAL> {
2548 type Request = ExportLogsServiceRequest;
2549 const SIGNAL: &'static str = "logs";
2550
2551 fn has_headroom_for(&self, req: &Self::Request) -> bool {
2552 self.0.has_headroom_for(req)
2553 }
2554 fn append_request(&mut self, req: &Self::Request) -> mira_core::error::Result<usize> {
2555 self.0.append_request(req)
2556 }
2557 fn approx_bytes(&self) -> usize {
2558 self.0.approx_bytes()
2559 }
2560 fn is_empty(&self) -> bool {
2561 self.0.is_empty()
2562 }
2563 fn finish(&mut self) -> mira_core::error::Result<mira_core::signal::Sealed> {
2564 if SEAL {
2565 // A real one: this is what an overflowing dictionary raises,
2566 // and `finish` leaves a fresh builder behind either way.
2567 let _ = self.0.finish();
2568 return Err(mira_core::Error::DictionaryFull("attr_key"));
2569 }
2570 self.0.finish()
2571 }
2572 fn snapshot(&self) -> mira_core::error::Result<mira_core::signal::Sealed> {
2573 if SEAL {
2574 return self.0.snapshot();
2575 }
2576 Err(mira_core::Error::DictionaryFull("attr_key"))
2577 }
2578 }
2579
2580 /// A block that cannot be sealed must not take anybody's data with it. Every
2581 /// caller is told `Unavailable` — never `Failed`, because whose export broke
2582 /// the encoder is not knowable from here — and, with a log, the watermark
2583 /// the discarded block would have claimed is dropped on the floor so the
2584 /// frames come back on the next boot. A `wal_hi` left standing here is the
2585 /// one bug in this file that loses acknowledged data silently: the block
2586 /// never existed, but the log would be truncated as if it had.
2587 #[tokio::test]
2588 async fn a_block_that_cannot_be_sealed_nacks_retryably_and_leaves_its_frames_in_the_log() {
2589 // Without a log the caller is the one waiting on the seal, so it is the
2590 // one that has to be told.
2591 let (c, dir) = cfg("brittle-seal");
2592 let (tx, _open, h) = spawn::<Brittle<true>>(&c);
2593 let answer = tx.submit(wide(1)).await;
2594 assert!(
2595 matches!(&answer, Err(Rejected::Unavailable(why)) if why.contains("dictionary")),
2596 "a seal that failed is the block's fault, not this caller's"
2597 );
2598 drop(tx);
2599 h.await.unwrap();
2600 assert_eq!(blocks(&dir), 0, "nothing was published");
2601 let _ = std::fs::remove_dir_all(&dir);
2602
2603 // With one, the caller was acknowledged long before the seal, so the
2604 // promise that survives is the log's.
2605 let dir = std::env::temp_dir().join(format!("mira-pipe-brittle-{}", std::process::id()));
2606 let _ = std::fs::remove_dir_all(&dir);
2607 std::fs::create_dir_all(&dir).unwrap();
2608 let node = block::node_id("brittletest");
2609 let wal = Arc::new(Wal::open(&dir, node).unwrap());
2610 let c = Arc::new(Config {
2611 data_dir: dir.clone(),
2612 node,
2613 max_block_age: Duration::from_millis(50),
2614 wal: Some(Arc::clone(&wal)),
2615 ..Default::default()
2616 });
2617 let (tx, open, h) = spawn::<Brittle<true>>(&c);
2618 tx.submit(wide(1))
2619 .await
2620 .unwrap_or_else(|_| panic!("the log took it, whatever the block does later"));
2621 drop(tx);
2622 h.await.unwrap();
2623
2624 assert_eq!(
2625 block::wal_watermarks(&dir, node).unwrap(),
2626 [0, 0, 0],
2627 "a block that was never published claims no sequence"
2628 );
2629 assert!(
2630 open.fresh().await.is_empty(),
2631 "and advertises no rows the read path could no longer produce"
2632 );
2633 // Which is what makes the acknowledgement honest: the frame is still
2634 // there and the next boot hands it back.
2635 let replayed = Wal::replay(
2636 &dir,
2637 node,
2638 block::wal_watermarks(&dir, node).unwrap(),
2639 |_, _, _| Ok(()),
2640 )
2641 .unwrap();
2642 assert_eq!(
2643 (replayed.replayed, replayed.skipped),
2644 (1, 0),
2645 "the acknowledged export survived the block that could not hold it"
2646 );
2647 let _ = std::fs::remove_dir_all(&dir);
2648 }
2649
2650 /// The open-block snapshot is best-effort, and "best-effort" has to mean
2651 /// *nothing* rather than *something stale*: the read path shows a snapshot
2652 /// as if it were on disk, so one that could not be rebuilt must clear the
2653 /// slot. Leaving the last one in place would serve rows from a block that
2654 /// has since been sealed and republished — the same records twice.
2655 #[tokio::test]
2656 async fn an_open_block_that_cannot_be_snapshotted_shows_nothing_rather_than_stale_rows() {
2657 for (breaks, want) in [(true, false), (false, true)] {
2658 let dir =
2659 std::env::temp_dir().join(format!("mira-pipe-snap{breaks}-{}", std::process::id()));
2660 let _ = std::fs::remove_dir_all(&dir);
2661 std::fs::create_dir_all(&dir).unwrap();
2662 let node = block::node_id("snaptest");
2663 let c = Arc::new(Config {
2664 data_dir: dir.clone(),
2665 node,
2666 // Long enough that nothing seals under the test: what is being
2667 // read is the block while it is still open.
2668 max_block_age: Duration::from_secs(30),
2669 wal: Some(Arc::new(Wal::open(&dir, node).unwrap())),
2670 ..Default::default()
2671 });
2672 // `Brittle<false>` fails `snapshot` and seals fine; `Brittle<true>`
2673 // is the other way round, so the healthy comparison runs through
2674 // the same wrapper rather than a different type.
2675 let (tx, open, h) = if breaks {
2676 spawn::<Brittle<false>>(&c)
2677 } else {
2678 spawn::<Brittle<true>>(&c)
2679 };
2680 tx.submit(crate::e2e::logs_export("checkout", 2_000, 4))
2681 .await
2682 .unwrap_or_else(|_| panic!("acknowledged by the log"));
2683
2684 // `fresh` waits for the flusher to drain its queue, so this is not
2685 // a race: the export is in the builder by the time it answers.
2686 assert_eq!(
2687 !open.fresh().await.is_empty(),
2688 want,
2689 "breaks={breaks}: a snapshot that failed must clear the slot"
2690 );
2691 drop(tx);
2692 h.await.unwrap();
2693 let _ = std::fs::remove_dir_all(&dir);
2694 }
2695 }
2696
2697 /// Reclaim stops the moment the volume is back above the floor. It is
2698 /// deleting telemetry nobody asked it to delete, so "enough" is the whole
2699 /// contract: a sweep that ran to the end of the list because it only
2700 /// checked before the first unlink would empty the disk to free one block's
2701 /// worth of space.
2702 ///
2703 /// ponytail: the floor is derived from 128 MiB of real files on the real
2704 /// volume, because `free_fraction` is a `statfs` and there is nothing to
2705 /// inject. Something else on this disk moving 64 MiB the wrong way during
2706 /// the sweep would flap it; the upgrade path is a free-space probe the
2707 /// caller supplies, which would also make this test instant.
2708 #[test]
2709 fn reclaim_stops_as_soon_as_the_volume_is_back_over_the_floor() {
2710 let dir = std::env::temp_dir().join(format!("mira-pipe-ballast-{}", std::process::id()));
2711 let _ = std::fs::remove_dir_all(&dir);
2712 std::fs::create_dir_all(&dir).unwrap();
2713 let oldest = fake_block(&dir, "logs", 1_000, 0);
2714 let newer = fake_block(&dir, "logs", 2_000, 1);
2715 let newest = fake_block(&dir, "traces", 3_000, 2);
2716
2717 let empty = block::free_fraction(&dir).unwrap();
2718 // Many synced files rather than one big one, and both halves matter.
2719 // Synced, because until the extents are allocated `statfs` has not
2720 // noticed them and `full` below is just `empty`. Many, because APFS
2721 // returns the space of an unlinked file asynchronously — measured here
2722 // at up to 176 ms for a single 64 MiB file, which is far longer than
2723 // the whole sweep — while a directory of 1 MiB files comes back
2724 // essentially whole by the time the last unlink returns (measured:
2725 // 0.998 of it, worst of five runs).
2726 {
2727 use std::io::Write;
2728 for i in 0..128 {
2729 let mut f = std::fs::File::create(oldest.join(format!("{i}.arrow"))).unwrap();
2730 f.write_all(&vec![0u8; 1 << 20]).unwrap();
2731 f.sync_all().unwrap();
2732 }
2733 }
2734 let full = block::free_fraction(&dir).unwrap();
2735 assert!(full < empty, "128 MiB moved the needle: {full} vs {empty}");
2736 // Halfway between the two, so the sweep starts below the floor and is
2737 // back above it after exactly one unlink.
2738 let floor = (full + empty) / 2.0;
2739
2740 // `u64::MAX` so the byte floor is never satisfied and the ratio is the
2741 // binding term — this test is about where the sweep stops, not which
2742 // term started it.
2743 let dropped = listening(|| reclaim(&dir, floor, u64::MAX).unwrap());
2744 assert_eq!(
2745 dropped,
2746 vec![oldest],
2747 "the oldest block, and then it stopped"
2748 );
2749 assert!(
2750 newer.exists() && newest.exists(),
2751 "nothing else was touched"
2752 );
2753 let _ = std::fs::remove_dir_all(&dir);
2754 }
2755
2756 /// A ratio alone deleted a developer's whole data directory on a 1 TB disk
2757 /// sitting at 45 GB free, because 45 GB is under 10% — and 45 GB was never
2758 /// a disk in trouble. Both terms have to agree before anything is unlinked.
2759 ///
2760 /// The ratio here is one no real volume satisfies, so it stands in for
2761 /// "95% full" without needing a 95%-full volume; the byte floor is read off
2762 /// this machine so the test means the same thing on any runner.
2763 #[test]
2764 fn reclaim_keeps_blocks_when_the_volume_is_proportionally_full_but_roomy() {
2765 let dir = std::env::temp_dir().join(format!("mira-pipe-roomy-{}", std::process::id()));
2766 let _ = std::fs::remove_dir_all(&dir);
2767 std::fs::create_dir_all(&dir).unwrap();
2768 let a = fake_block(&dir, "logs", 1_000, 0);
2769 let b = fake_block(&dir, "traces", 2_000, 1);
2770
2771 let (_, free_bytes) = block::free(&dir).unwrap();
2772 assert!(free_bytes > 0, "the volume reports some free space");
2773
2774 let kept = listening(|| reclaim(&dir, 1.0, free_bytes / 2).unwrap());
2775 assert!(kept.is_empty(), "bytes to spare, so nothing went: {kept:?}");
2776 assert!(a.exists() && b.exists(), "both blocks are still there");
2777
2778 // And the guard still fires when the bytes agree: same ratio, a floor
2779 // above what the volume has.
2780 let gone = listening(|| reclaim(&dir, 1.0, free_bytes.saturating_mul(2)).unwrap());
2781 assert_eq!(gone.len(), 2, "both terms said full, so both blocks went");
2782 let _ = std::fs::remove_dir_all(&dir);
2783 }
2784
2785 /// One block the sweep cannot unlink says nothing about the next one.
2786 /// Returning at the first error stopped retention for the whole volume at
2787 /// its oldest broken block — the disk stayed full and every export was
2788 /// NACKed, which is the outage reclaim exists to prevent — and a block
2789 /// another replica removed first is not an error at all.
2790 #[test]
2791 fn a_block_that_cannot_be_dropped_does_not_stop_the_ones_behind_it() {
2792 let dir = std::env::temp_dir().join(format!("mira-pipe-undrop-{}", std::process::id()));
2793 let _ = std::fs::remove_dir_all(&dir);
2794 std::fs::create_dir_all(&dir).unwrap();
2795
2796 // A regular file wearing a block's name. `scan` reads names, so it is
2797 // returned like any other block and `remove_dir_all` refuses it — the
2798 // same shape as a directory this process cannot traverse.
2799 let partition = dir.join("logs").join("p=1970-01-01-00");
2800 std::fs::create_dir_all(&partition).unwrap();
2801 let impostor = partition.join(format!("{:020}-{:020}-{:08x}-{:012}-{:020}", 0, 1, 7, 0, 0));
2802 std::fs::write(&impostor, b"not a block").unwrap();
2803
2804 // A margin no volume can satisfy: the sweep tries everything it can see.
2805 let dropped = listening(|| reclaim(&dir, 2.0, u64::MAX).unwrap());
2806 assert!(
2807 dropped.is_empty() && impostor.exists(),
2808 "nothing was dropped, and the sweep still returned"
2809 );
2810
2811 // The same block seen twice — one replica's unlink landing between this
2812 // sweep's `scan` and its `remove_dir_all` — simulated by listing one
2813 // tree under two signals.
2814 let real = fake_block(&dir, "traces", 5_000, 3);
2815 std::os::unix::fs::symlink(dir.join("traces"), dir.join("metrics")).unwrap();
2816 let dropped = listening(|| reclaim(&dir, 2.0, u64::MAX).unwrap());
2817 assert_eq!(
2818 dropped,
2819 vec![real.clone()],
2820 "the block is reported once, and the second sighting is not an error"
2821 );
2822 assert!(!real.exists());
2823 let _ = std::fs::remove_dir_all(&dir);
2824 }
2825
2826 /// Every way one sweep can fail, and the property is the same for all of
2827 /// them: the loop keeps its next tick. Retention is the only thing that
2828 /// frees space, so a sweep that took the task down with it would turn one
2829 /// unreadable signal into a volume that fills up and stays full.
2830 #[tokio::test]
2831 async fn a_sweep_that_fails_never_takes_the_retention_loop_with_it() {
2832 let dir = std::env::temp_dir().join(format!("mira-pipe-sweepfail-{}", std::process::id()));
2833 let _ = std::fs::remove_dir_all(&dir);
2834 std::fs::create_dir_all(&dir).unwrap();
2835 // `logs` cannot be scanned, so both `expire` and `compact` fail for it;
2836 // `traces` holds a block a zero TTL expires. One signal failing must
2837 // not skip the others, which is the half of this that is silent.
2838 std::fs::write(dir.join("logs"), b"not a directory").unwrap();
2839 let doomed = fake_block(&dir, "traces", 1_000, 0);
2840
2841 // The first tick is immediate and the second is a minute away, so a
2842 // task that is still unfinished after its sweep is a task that took the
2843 // failure and went back to waiting.
2844 let sweeping = tokio::spawn(retention(Arc::new(Config {
2845 data_dir: dir.clone(),
2846 retention: Duration::ZERO,
2847 ..Default::default()
2848 })));
2849 assert!(
2850 until(|| !doomed.exists()).await,
2851 "the signal that could be swept was swept, whatever the broken one did"
2852 );
2853 assert!(!sweeping.is_finished(), "and the loop kept its next tick");
2854 sweeping.abort();
2855
2856 // A data directory that is not there: `free_fraction` cannot answer, so
2857 // the sweep is TTL-only rather than a dead task. Nothing on disk changes
2858 // — the observable is that the task is still there afterwards.
2859 let sweeping = tokio::spawn(retention(Arc::new(Config {
2860 data_dir: dir.join("never-created"),
2861 retention: Duration::ZERO,
2862 ..Default::default()
2863 })));
2864 tokio::time::sleep(Duration::from_millis(200)).await;
2865 assert!(
2866 !sweeping.is_finished(),
2867 "a volume it cannot even measure is not a reason to stop measuring it"
2868 );
2869 sweeping.abort();
2870 let _ = std::fs::remove_dir_all(&dir);
2871 }
2872
2873 /// `retention: 999999d` is how an operator writes "keep it forever", and
2874 /// until the cutoff was made saturating it meant the exact opposite: the
2875 /// TTL in nanoseconds overflowed an `i64`, wrapped negative, and put the
2876 /// cutoff in the future — where every block on the volume is older than it.
2877 /// The sweep still has to do its other job while keeping everything.
2878 #[tokio::test]
2879 async fn an_absurd_retention_keeps_every_block_and_still_compacts_the_cold_ones() {
2880 let (c, dir) = cfg("forever");
2881 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
2882 // Timestamped in 1970, so it is cold by any clock: the compaction half
2883 // of the sweep has something to do and the TTL half must not.
2884 tx.submit(crate::e2e::logs_export("checkout", 1_000, 4))
2885 .await
2886 .unwrap_or_else(|_| panic!("export"));
2887 drop(tx);
2888 h.await.unwrap();
2889 assert_eq!(blocks(&dir), 1);
2890
2891 let cfg = Arc::new(Config {
2892 data_dir: dir.clone(),
2893 // 547 years. `Duration::as_nanos` is a `u128` and holds it; an
2894 // `i64` of nanoseconds does not.
2895 retention: Duration::from_secs(200_000 * 86_400),
2896 ..Default::default()
2897 });
2898 let sweeping = tokio::spawn(retention(cfg));
2899 let cold = block::scan(&dir, "logs").unwrap()[0].dir.join("cold");
2900 assert!(
2901 until(|| cold.exists()).await,
2902 "the block was compacted rather than deleted"
2903 );
2904 assert!(
2905 !sweeping.is_finished(),
2906 "one sweep, and the loop is still there"
2907 );
2908 sweeping.abort();
2909
2910 assert_eq!(
2911 blocks(&dir),
2912 1,
2913 "a retention longer than i64 nanoseconds keeps everything"
2914 );
2915 let _ = std::fs::remove_dir_all(&dir);
2916 }
2917
2918 /// Readiness has to be a *sustained* condition. A probe that flipped on the
2919 /// first failed publish would pull the node out of its Service for every
2920 /// EIO and every remount, and an endpoint list that changes every ten
2921 /// seconds loses more exports than the node it is protecting.
2922 #[test]
2923 fn a_stall_is_only_reportable_once_it_has_outlasted_the_recovery() {
2924 let r = Rejects::new("logs");
2925 let now = 1_700_000_000;
2926 assert_eq!(stall_of(&r, now), None, "a healthy signal is never unready");
2927
2928 r.stalled_since.store(now, Relaxed);
2929 let after = UNREADY_AFTER.as_secs();
2930 assert_eq!(
2931 stall_of(&r, now),
2932 None,
2933 "one failed publish is not an outage"
2934 );
2935 assert_eq!(stall_of(&r, now + after - 1), None);
2936 assert_eq!(stall_of(&r, now + after), Some(after));
2937
2938 // The clock is the *first* failure of the run, not the latest one, or a
2939 // node failing every two seconds would reset itself to healthy forever.
2940 r.shard_stalled_since[0].store(1, Relaxed);
2941 r.mark_stalled(0);
2942 assert_eq!(r.stalled_since.load(Relaxed), 1);
2943 // ...and the first failure does start it, from zero.
2944 let fresh = Rejects::new("logs");
2945 assert_eq!(fresh.stalled_since.load(Relaxed), 0);
2946 fresh.mark_stalled(0);
2947 assert_ne!(fresh.stalled_since.load(Relaxed), 0);
2948
2949 // Nothing in this test binary has been unable to store for two minutes,
2950 // so the live answer is the healthy one.
2951 assert_eq!(stalled(), None);
2952 }
2953
2954 /// A signal's health is the worst of its shards, not the last one to report.
2955 ///
2956 /// The bug this exists to prevent: with the flushers writing the aggregate
2957 /// directly, a shard sealing normally would clear `open_since` while a
2958 /// sibling sat on a block it could not flush, and `/healthz` would call a
2959 /// stuck node healthy. Oldest-of-nonzero is the only reduction that answers
2960 /// "is anything stuck" rather than "was the last thing that happened fine".
2961 #[test]
2962 fn a_signals_clocks_report_the_worst_shard_not_the_latest_one() {
2963 let r = Rejects::new("logs");
2964 r.set_open_since(0, 100);
2965 r.set_open_since(1, 500);
2966 assert_eq!(r.open_since.load(Relaxed), 100);
2967
2968 // Shard 0 seals. Shard 1 is still holding its block open, so the signal
2969 // still has something open — and it is shard 1's clock now.
2970 r.set_open_since(0, 0);
2971 assert_eq!(r.open_since.load(Relaxed), 500);
2972 r.set_open_since(1, 0);
2973 assert_eq!(
2974 r.open_since.load(Relaxed),
2975 0,
2976 "nothing open is zero, not min"
2977 );
2978
2979 // Same rule for stalls, and the same failure mode: one shard recovering
2980 // does not make the node ready while another cannot write.
2981 r.shard_stalled_since[1].store(900, Relaxed);
2982 r.mark_stalled(0);
2983 let both = r.stalled_since.load(Relaxed);
2984 assert!(both > 0 && both <= 900, "the older of the two, got {both}");
2985 r.clear_stalled(0);
2986 assert_eq!(r.stalled_since.load(Relaxed), 900);
2987 r.clear_stalled(1);
2988 assert_eq!(r.stalled_since.load(Relaxed), 0);
2989 }
2990
2991 /// Shard count is a function of core count and nothing else — section 4's
2992 /// rule for what a shard may be keyed on.
2993 #[test]
2994 fn shards_are_counted_from_cores_and_clamped_at_both_ends() {
2995 // Auto. Halved because a flusher is a consumer and the decode is the
2996 // producer; never zero, whatever the machine claims.
2997 assert_eq!(shard_count(0, 1), 1);
2998 assert_eq!(shard_count(0, 2), 1);
2999 assert_eq!(shard_count(0, 12), 6);
3000 // The ceiling is what keeps a 128-core host from publishing 64 files
3001 // per seal window per signal.
3002 assert_eq!(shard_count(0, 128), MAX_SHARDS);
3003 // Configured wins, up to the same ceiling — this is the escape hatch
3004 // for a machine that miscounts the cores this process actually gets,
3005 // and an operator who types 1 gets the old behaviour.
3006 assert_eq!(shard_count(1, 128), 1);
3007 assert_eq!(shard_count(4, 2), 4);
3008 assert_eq!(shard_count(999, 2), MAX_SHARDS);
3009 }
3010
3011 /// A sharded config with the log on, which is the shipped default and the
3012 /// only setting under which a test can submit without waiting for a seal.
3013 ///
3014 /// Without a log `submit` returns at the publish, so a long `max_block_age`
3015 /// makes every serial submit wait out the age timer and publish a block of
3016 /// its own — which is the behaviour under test, inverted.
3017 fn sharded(name: &str, shards: usize) -> (Arc<Config>, PathBuf) {
3018 let (c, dir) = cfg(name);
3019 let node = block::node_id(name);
3020 let mut c = Arc::try_unwrap(c).ok().expect("freshly built");
3021 c.node = node;
3022 c.shards = shards;
3023 c.wal = Some(Arc::new(Wal::open(&dir, node).unwrap()));
3024 // Long enough that nothing seals on the timer mid-test: the blocks here
3025 // are sealed by a full dictionary or by the shutdown path.
3026 c.max_block_age = Duration::from_secs(30);
3027 (Arc::new(c), dir)
3028 }
3029
3030 /// Every shard's blocks land, and no two of them collide on a sequence.
3031 ///
3032 /// A collision is not a cosmetic problem: the block directory name is the
3033 /// manifest, so `rename` onto an existing directory means the node stops
3034 /// publishing — and with one queue per shard, "shard 2 picks the next
3035 /// number" is not a thing anything can observe. Stride and offset are all
3036 /// that keep them apart.
3037 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3038 async fn shards_partition_the_sequence_space() {
3039 let (c, dir) = sharded("shardseq", 4);
3040 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
3041 // 40k distinct keys each: two of these cannot share a `UInt16`
3042 // dictionary, so whichever shard takes two publishes two, and the
3043 // sequences still may not collide.
3044 let mut sent = Vec::new();
3045 for _ in 0..8 {
3046 let tx = tx.clone();
3047 sent.push(tokio::spawn(async move { tx.submit(wide(40_000)).await }));
3048 }
3049 for s in sent {
3050 s.await
3051 .unwrap()
3052 .unwrap_or_else(|_| panic!("nothing may be shed: the wait is 5s"));
3053 }
3054 drop(tx);
3055 h.await.unwrap();
3056
3057 let seqs = seqs(&dir);
3058 assert_eq!(seqs.len(), 8, "one block per export, none lost");
3059 let mut uniq = seqs.clone();
3060 uniq.dedup();
3061 assert_eq!(uniq, seqs, "two shards reused a sequence: {seqs:?}");
3062 let _ = std::fs::remove_dir_all(&dir);
3063 }
3064
3065 /// A node that is not saturating one flusher keeps behaving like a node
3066 /// with one flusher, and its sequences stride by the shard count.
3067 ///
3068 /// The reason dispatch is first-fit and not round-robin. Round-robin would
3069 /// spread a trickle over every shard and publish `shards` nearly-empty
3070 /// blocks per seal window, which is the small-file explosion section 4
3071 /// rejects hash sharding for, arrived at from the other direction. Shard
3072 /// 0's queue has room every time, so `try_reserve` never has to look past
3073 /// it.
3074 #[tokio::test]
3075 async fn a_trickle_stays_on_one_shard_and_strides_its_sequences() {
3076 let (c, dir) = sharded("shardtrickle", 4);
3077 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
3078 for _ in 0..4 {
3079 tx.submit(crate::e2e::logs_export("checkout", 2_000, 4))
3080 .await
3081 .unwrap_or_else(|_| panic!("acknowledged"));
3082 }
3083 // Two 40k-key exports: the first joins the open block, the second
3084 // cannot share its dictionary and so seals it. Two blocks from one
3085 // shard, which is what makes the stride observable.
3086 for _ in 0..2 {
3087 tx.submit(wide(40_000))
3088 .await
3089 .unwrap_or_else(|_| panic!("acknowledged"));
3090 }
3091 drop(tx);
3092 h.await.unwrap();
3093 assert_eq!(
3094 seqs(&dir),
3095 vec![0, 4],
3096 "one shard's blocks, striding by the shard count — four shards must \
3097 not mean four files for a load one shard can take"
3098 );
3099 let _ = std::fs::remove_dir_all(&dir);
3100 }
3101
3102 /// A `Config` that never went through [`shard_count`] is still bounded, and
3103 /// the bound is observable from outside: the sequence stride *is* the shard
3104 /// count.
3105 ///
3106 /// [`shard_count`] is what `main` calls, so it is the gate an operator hits.
3107 /// This tests the other one — [`spawn`]'s own `clamp` — because a `Config`
3108 /// is also built by hand, by the TUI, by a test, and by whatever calls this
3109 /// next. A count of zero would spawn no flushers and hang every export
3110 /// forever; a count of 4 billion would try to spawn 4 billion tasks. Neither
3111 /// belongs to `main`'s gate alone.
3112 #[tokio::test]
3113 async fn spawn_bounds_a_shard_count_that_never_went_through_shard_count() {
3114 for (configured, stride) in [(0, 1), (usize::MAX, MAX_SHARDS)] {
3115 let (c, dir) = sharded(&format!("shardclamp{configured}"), configured);
3116 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
3117 // First fit keeps a trickle on shard 0, so consecutive blocks off
3118 // that one shard are exactly `stride` apart.
3119 for _ in 0..2 {
3120 tx.submit(wide(40_000))
3121 .await
3122 .unwrap_or_else(|_| panic!("acknowledged"));
3123 }
3124 drop(tx);
3125 h.await.unwrap();
3126 assert_eq!(
3127 seqs(&dir),
3128 vec![0, stride as u64],
3129 "{configured} shards must be clamped to {stride}"
3130 );
3131 let _ = std::fs::remove_dir_all(&dir);
3132 }
3133 }
3134
3135 /// A crash after a shard sealed *out of sequence order* replays every frame
3136 /// no published block holds — and in particular replays the older frame the
3137 /// sealed block's own sequences step over.
3138 ///
3139 /// This is the whole reason the watermark is a set rather than
3140 /// `max(seq) + 1`, driven end to end instead of at the `Wal` API: real
3141 /// flushers, a real block directory name carrying `wal_hi`, the real
3142 /// `wal_watermarks` reduction over it, and a real `Wal::replay`. Getting it
3143 /// wrong is silent loss, and silent loss is exactly what a test that only
3144 /// counts rows does not see.
3145 ///
3146 /// The schedule is forced, not hoped for. Holding shard 0's only queue slot
3147 /// makes first-fit spill to shard 1 deterministically, so shard 1 takes the
3148 /// *higher* sequences and is made to seal — by a second 40k-key dictionary
3149 /// it cannot merge — while frame 0 is still sitting in shard 0. If the
3150 /// sealed block claimed `max(seq) + 1` it would claim 2, the watermark would
3151 /// be 2, and frame 0 would never be handed back by any later boot.
3152 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3153 async fn a_crash_after_an_out_of_order_seal_replays_every_frame_no_block_holds() {
3154 let (mut c, dir) = sharded("shardcrash", 2);
3155 // One slot per shard: `queue` is a per-signal total and splits.
3156 Arc::get_mut(&mut c).unwrap().queue = 2;
3157 let node = c.node;
3158 let wal = Arc::clone(c.wal.as_ref().unwrap());
3159 let (tx, _open, mut h) = spawn::<LogsBuilder>(&c);
3160
3161 // Frame 0 goes to shard 0 by first fit, and stays there: nothing below
3162 // seals it.
3163 tx.submit(crate::e2e::logs_export("checkout", 2_000, 4))
3164 .await
3165 .unwrap_or_else(|_| panic!("the log took it"));
3166
3167 // Shard 0's one slot, taken and held. The await is itself the barrier
3168 // that frame 0 has left the channel — capacity only comes back when the
3169 // flusher has taken it.
3170 let held = tx.tx[0].clone().reserve_owned().await.unwrap();
3171
3172 // So frames 1 and 2 both land on shard 1, and 2 cannot share 1's key
3173 // dictionary — which seals the block holding frame 1 and carries 2 into
3174 // the next one.
3175 for _ in 0..2 {
3176 tx.submit(wide(40_000))
3177 .await
3178 .unwrap_or_else(|_| panic!("the log took it"));
3179 }
3180 assert!(
3181 until(|| blocks(&dir) == 1).await,
3182 "shard 1's first block never landed"
3183 );
3184
3185 // The crash: every shard stops where it stands, so frames 0 and 2 are
3186 // in the log and in nobody's block.
3187 h.abort();
3188 drop(held);
3189
3190 let published = block::scan(&dir, "logs").unwrap();
3191 assert_eq!(published.len(), 1);
3192 assert_eq!(
3193 published[0].wal_hi, 0,
3194 "a block holding frame 1 may not claim past frame 0, which shard 0 \
3195 still has — this is the assertion `max(seq) + 1` fails"
3196 );
3197 assert_eq!(
3198 block::wal_watermarks(&dir, node).unwrap(),
3199 [0, 0, 0],
3200 "and the reduction over the directory says the same"
3201 );
3202
3203 // Recovery: nothing is skipped, and the frame the sealed block does
3204 // hold comes back too. Re-ingesting frame 1 is the direction the
3205 // watermark is allowed to be wrong in — the other direction is the one
3206 // that loses data.
3207 let mut got = Vec::new();
3208 let replayed = Wal::replay(
3209 &dir,
3210 node,
3211 block::wal_watermarks(&dir, node).unwrap(),
3212 |_, seq, body| {
3213 got.push((seq, body.to_vec()));
3214 Ok(())
3215 },
3216 )
3217 .unwrap();
3218 assert_eq!(
3219 got.iter().map(|(s, _)| *s).collect::<Vec<_>>(),
3220 vec![0, 1, 2],
3221 "every frame, none skipped"
3222 );
3223 assert_eq!((replayed.replayed, replayed.skipped), (3, 0));
3224
3225 // And it converges. Feeding the recovered frames to a fresh node under
3226 // their own sequences leaves every one of them claimed, so the boot
3227 // after this one replays nothing at all.
3228 let (tx, _open, h) = spawn::<LogsBuilder>(&c);
3229 for (seq, body) in got {
3230 tx.replay(&body, seq)
3231 .unwrap_or_else(|_| panic!("the flusher took frame {seq}"));
3232 }
3233 drop(tx);
3234 h.await.unwrap();
3235 assert_eq!(
3236 wal.watermark_for(wal::Signal::Logs, &[]),
3237 3,
3238 "every frame is published, so nothing is pending"
3239 );
3240 let again = Wal::replay(
3241 &dir,
3242 node,
3243 block::wal_watermarks(&dir, node).unwrap(),
3244 |_, seq, _| unreachable!("frame {seq} is in a block already"),
3245 )
3246 .unwrap();
3247 assert_eq!((again.replayed, again.skipped), (0, 3));
3248 let _ = std::fs::remove_dir_all(&dir);
3249 }
3250
3251 /// Read-your-writes survives the fan-out: every acknowledged export is
3252 /// visible in some shard's open block, before anything has been sealed.
3253 ///
3254 /// The property section 4 buys from FIFO ordering, re-asserted now that
3255 /// there is more than one FIFO. It holds for the same reason it did — an
3256 /// acknowledged export is in exactly one shard's channel until that shard
3257 /// appends it — but only because `fresh` asks all of them.
3258 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3259 async fn every_shard_answers_the_read_path() {
3260 let (mut c, dir) = sharded("shardfresh", 4);
3261 // One slot per shard, so eight concurrent submits have to spill past
3262 // shard 0 rather than hoping the scheduler spreads them.
3263 Arc::get_mut(&mut c).unwrap().queue = 4;
3264 let (tx, open, h) = spawn::<LogsBuilder>(&c);
3265 let mut sent = Vec::new();
3266 for i in 0..8 {
3267 let tx = tx.clone();
3268 sent.push(tokio::spawn(async move {
3269 tx.submit(crate::e2e::logs_export("checkout", 2_000 + i * 10, 4))
3270 .await
3271 }));
3272 }
3273 for s in sent {
3274 s.await.unwrap().unwrap_or_else(|_| panic!("acknowledged"));
3275 }
3276 let rows: usize = open.fresh().await.iter().map(|o| o.sealed.num_rows).sum();
3277 assert_eq!(
3278 rows, 32,
3279 "eight exports of four records, all of them findable"
3280 );
3281
3282 drop(tx);
3283 h.await.unwrap();
3284 let _ = std::fs::remove_dir_all(&dir);
3285 }
3286
3287 /// The second shard takes what the first one cannot.
3288 ///
3289 /// `reserve` at the unit level, with no flusher behind either channel: the
3290 /// first is full, so the job has to land in the second rather than wait out
3291 /// `ADMIT_WAIT` and shed.
3292 #[tokio::test]
3293 async fn a_full_shard_spills_into_the_next_one() {
3294 let (tx0, _rx0) = mpsc::channel::<Job<ExportLogsServiceRequest>>(1);
3295 let (tx1, mut rx1) = mpsc::channel::<Job<ExportLogsServiceRequest>>(1);
3296 // Shard 0's one slot, taken and held.
3297 let _held = tx0.clone().reserve_owned().await.unwrap();
3298 let ingest = Ingest {
3299 tx: [tx0, tx1].into(),
3300 turn: Arc::default(),
3301 rejects: Box::leak(Box::new(Rejects::new("logs"))),
3302 wal: None,
3303 signal: wal::Signal::Logs,
3304 };
3305 let sent = tokio::spawn({
3306 let i = ingest.clone();
3307 async move { i.submit(ExportLogsServiceRequest::default()).await }
3308 });
3309 let job = rx1
3310 .recv()
3311 .await
3312 .expect("shard 1 gets what shard 0 cannot take");
3313 let _ = job.ack.send(Ok(()));
3314 sent.await
3315 .unwrap()
3316 .unwrap_or_else(|_| panic!("admitted, not shed"));
3317 assert_eq!(
3318 ingest.rejects.shed.load(Relaxed),
3319 0,
3320 "spilling to a free shard is not shedding"
3321 );
3322 }
3323}