dendro/writer.rs
1//! The writer thread. See DESIGN.md.
2//!
3//! One dedicated thread behind a bounded channel. Encoding a large segment
4//! cannot skew the caller's append cadence and a disk that cannot keep up
5//! applies backpressure instead of growing memory. One bounded exception: a
6//! seal batch is encoded whole before its transaction opens, so its segments'
7//! bytes are all resident at once (see `seal_batch`).
8//!
9//! **A seal batch is one transaction.** The file at `path` is a valid,
10//! openable archive from the moment [`Writer::create`](crate::writer::Writer::create) returns. There is no
11//! staging file, no rename, and no separate manifest to keep in step — the
12//! catalog IS the database, so the container gets transactions instead of
13//! imitating them.
14//!
15//! **There is one writing connection.** A second stalls on SQLite's write lock
16//! for `busy_timeout` before failing, which against a steady append cadence
17//! reads as a hang. Every mutation therefore goes through this thread's
18//! channel, including ones a caller could in principle do itself.
19//!
20//! The writer is panic-free: every fallible operation returns `Err`. A caller that
21//! installs a panic hook exiting the process before unwinding would otherwise
22//! never reach the send-error path here: the source would skip finalize and
23//! the thread would never be joined.
24
25use std::collections::{BTreeMap, BTreeSet};
26use std::path::{Path, PathBuf};
27use std::sync::mpsc::{sync_channel, Receiver, RecvTimeoutError, SyncSender};
28use std::sync::{Arc, Mutex, Weak};
29use std::thread::JoinHandle;
30use std::time::{Duration, Instant};
31
32use tracing::warn;
33
34use crate::archive::{
35 Archive, ArchiveMut, CallerRow, Evicted, RevisionId, SegmentMeta, SourceMeta, WalRow,
36};
37use crate::error::{Error, Result};
38use crate::segment::{EncodeContext, SegmentEncoder};
39
40/// Which streams a retention pass touches; `None` is the whole source.
41///
42/// Boxed and `Send` because the decision is the caller's and crosses the
43/// channel to the writer thread.
44pub type StreamFilter = Box<dyn Fn(&str) -> bool + Send>;
45
46/// A [`CallerRowFloor`](crate::archive::CallerRowFloor) the writer thread
47/// can own: boxed and `Send` for the same reason as [`StreamFilter`]. It runs
48/// on the writer thread while the pass holds the write lock, so it must not
49/// call back into the writer.
50pub type CallerRowFloorFn = Box<dyn Fn(&str, Option<i64>) -> i64 + Send>;
51
52enum Msg {
53 /// Insert a `sources` row and hand its id back.
54 ///
55 /// Goes through the channel rather than being done by the caller because
56 /// the writer thread OWNS the connection — the whole design rests on there
57 /// being exactly one writing connection, since a second stalls on SQLite's
58 /// write lock for `busy_timeout` before failing, which against a tick reads
59 /// as a hang. The reply channel is the same shape `Sync` already uses.
60 AddSource {
61 seed: Box<SourceMeta>,
62 /// The identity the source already has, when it comes from somewhere
63 /// else. `None` mints a fresh one, which is what an ordinary
64 /// `add_source` does.
65 uuid: Option<String>,
66 /// The new handle's liveness token; see `SourceWriter::_alive`.
67 alive: Weak<()>,
68 reply: SyncSender<Result<i64>>,
69 },
70 /// Reopen an existing source for a new writer session: verify it, refuse
71 /// an anchor at or before its newest row, clear `complete`, record the
72 /// session, and hand back what the handle needs.
73 ResumeSource {
74 source_id: i64,
75 clock_anchor_wall_ns: i64,
76 /// The new handle's liveness token; see `SourceWriter::_alive`.
77 alive: Weak<()>,
78 reply: SyncSender<Result<Resumed>>,
79 },
80 /// One tick's WAL rows for every source in the archive, across all
81 /// their streams — one transaction, and therefore one fsync at
82 /// `synchronous=FULL`.
83 ///
84 /// Per tick rather than per source, because the cost is paid on the
85 /// append loop: `wal`/`wal_tick` is a blocking send on a bound-1 channel
86 /// from inside the tick, and a commit per source made that cost scale
87 /// linearly with endpoint count. `seal_batch` already refused the same
88 /// trade ("12 implicit commits would be 12 fsyncs at `synchronous=FULL`
89 /// against a ~46 ms tick"); this carries the argument across sources.
90 Wal { ticks: Vec<(i64, Vec<WalRow>)> },
91 /// One seal batch for one source = one transaction. `max_rows` is the
92 /// most WAL rows one segment may hold; `usize::MAX` for an uncapped
93 /// `seal`.
94 Seal {
95 source_id: i64,
96 batch: Vec<String>,
97 max_rows: usize,
98 },
99 /// One segment built elsewhere, to be inserted at the stream's next
100 /// `seq`. The seal path's other entrance: `Seal` says "encode what is in
101 /// the WAL", this says "here are the bytes". Replies, unlike `Seal`,
102 /// because the sender is applying a stream of them and an overlap it must
103 /// stop on is not something to find out about one frame later.
104 AdoptSegment {
105 source_id: i64,
106 /// Boxed for the reason `AddSource`'s seed is: every message shares
107 /// the size of the largest variant, and this one carries a whole
108 /// segment.
109 segment: Box<Adopted>,
110 /// Whether it was inserted. `false` is a segment the stream's
111 /// watermark already covers, which a reconnect produces normally.
112 reply: SyncSender<Result<bool>>,
113 },
114 /// Retention: drop segments wholly older than `cutoff_ts` and the WAL rows
115 /// before it that a segment covers, then trickle freed pages back if the
116 /// free list has grown. Only a caller with a retention policy sends this.
117 ///
118 /// `streams` restricts the pass, so different streams can be worth
119 /// different amounts of time; `None` is the whole source. It is boxed
120 /// because the decision is the caller's and crosses a thread boundary —
121 /// dendro knows what a cutoff means but not which streams are worth
122 /// keeping.
123 Evict {
124 source_id: i64,
125 cutoff_ts: i64,
126 streams: Option<StreamFilter>,
127 floor: Option<CallerRowFloorFn>,
128 reply: SyncSender<Result<Evicted>>,
129 },
130 /// Delete the live WAL rows of the streams `streams` accepts, keeping
131 /// their segments, and take those streams off the deferred-seal list.
132 DiscardLive {
133 source_id: i64,
134 streams: StreamFilter,
135 reply: SyncSender<Result<usize>>,
136 },
137 /// Merge keys into one source's metadata, in order with the ticks around
138 /// it. What a caller learns only from the rows themselves — a producer's
139 /// epoch changing, a discontinuity worth an event — lands here as it
140 /// happens rather than at finalize, which a kill never reaches. See
141 /// [`crate::keys`] for the conventions.
142 UpdateMetadata {
143 source_id: i64,
144 patch: BTreeMap<String, String>,
145 },
146 /// Replace one source's labels and metadata, in order with the ticks
147 /// around it. A replication subscriber's
148 /// [`SourceUpdate`](crate::replicate::Frame::SourceUpdate).
149 SetIdentity {
150 source_id: i64,
151 labels: BTreeMap<String, String>,
152 metadata: BTreeMap<String, String>,
153 },
154 /// One clock-drift observation, committed on its own.
155 ///
156 /// The writer records these itself at every seal and at finalize
157 /// (FORMAT.md §5), derived from the rows it sealed, so an ordinary
158 /// recording needs this never. It exists for a caller carrying a series
159 /// somebody else observed — a replication subscriber, which must land the
160 /// publisher's observations rather than invent its own from where its own
161 /// seals happened to fall.
162 ///
163 /// At most one observation per `(source, ts)`: the table is keyed that
164 /// way and inserted `OR IGNORE`, so the first at a timestamp wins and a
165 /// second is dropped by the schema rather than by this.
166 ClockOffset {
167 source_id: i64,
168 ts: i64,
169 offset_ns: i64,
170 },
171 /// Rows for the caller's time-keyed store, in order with the ticks
172 /// around them and committed on their own. See
173 /// [`crate::archive::CallerRow`].
174 CallerRows {
175 source_id: i64,
176 stream: String,
177 rows: Vec<CallerRow>,
178 },
179 /// Write a document revision (FORMAT.md §3.6) and hand its id back, or
180 /// the refusal. Archive-level, so it names no source. Replies because a
181 /// conditional write's conflict is the caller's to act on.
182 PutDocument {
183 put: Box<DocumentPut>,
184 reply: SyncSender<Result<RevisionId>>,
185 },
186 /// Delete a document by writing a deletion revision; replies with its
187 /// id, or `None` when there was nothing to delete.
188 DeleteDocument {
189 kind: String,
190 name: String,
191 reply: SyncSender<Result<Option<RevisionId>>>,
192 },
193 /// One source's last clock observation, if it has one; marks *that*
194 /// source complete.
195 ///
196 /// Does not stop the writer: an archive may hold several sources and the
197 /// others may still be running. The thread exits when every handle has been
198 /// dropped and the channel closes — see `writer_thread`.
199 Finalize {
200 source_id: i64,
201 clock_offset: Option<(i64, i64)>,
202 },
203 /// Make a source a replicated copy's (WIRE.md §2.1): its stream bounds
204 /// become the rows it holds, leaving out `bounds`, and the writer poisons
205 /// the source when it would drop any row of a tick or any caller row for
206 /// it ([`SourceWriter::poisoned`]). `alive` is `Some` for an existing source
207 /// continued without a writer session, whose handle this opens; the
208 /// reply carries its labels. `None` for a source just added.
209 Replicate {
210 source_id: i64,
211 alive: Option<Weak<()>>,
212 reply: SyncSender<Result<BTreeMap<String, String>>>,
213 },
214 /// Set one stream of a replicated copy to a sync point (WIRE.md §4.7).
215 SyncStream {
216 source_id: i64,
217 stream: String,
218 at: i64,
219 reply: SyncSender<Result<Synced>>,
220 },
221 /// Insert segments of one stream that each replace a replicated copy's
222 /// live rows above their `after` (WIRE.md §4.8), all in one transaction.
223 /// Replies with the rows deleted below each segment's `first_ts`.
224 AdoptAfter {
225 source_id: i64,
226 parts: Vec<AdoptedAfter>,
227 reply: SyncSender<Result<u64>>,
228 },
229 /// Clear one source's `complete` flag.
230 MarkIncomplete {
231 source_id: i64,
232 reply: SyncSender<Result<()>>,
233 },
234 /// Stop the writer, whatever else is still holding a sender.
235 ///
236 /// The exit signal is explicit rather than "the channel closed" because a
237 /// handle outliving its archive would otherwise deadlock the join: the
238 /// archive drops its own sender and waits, while the handle's clone keeps
239 /// the channel open forever. With this, a leaked handle merely finds the
240 /// receiver gone on its next send — the failure path it already has.
241 Shutdown,
242 /// Reply once everything queued ahead of this has been committed. Carries
243 /// no data and changes nothing — see [`SourceWriter::sync`].
244 Sync(SyncSender<()>),
245 /// Answer with how many transactions the writer's connection has
246 /// committed. A barrier as well as a question, exactly as `Sync` is: the
247 /// reply means everything queued ahead of it has been handled, so a caller
248 /// can count a tick's commits without racing the writer.
249 #[cfg(any(test, feature = "test-support"))]
250 Commits(SyncSender<u64>),
251}
252
253/// A document write crossing to the writer thread. Boxed in [`Msg`] so the
254/// four strings do not set every message's size.
255struct DocumentPut {
256 kind: String,
257 name: String,
258 schema: String,
259 body: String,
260 /// `None` writes unconditionally; `Some(e)` is
261 /// [`ArchiveMut::put_document_if_current`] with `e`.
262 expected: Option<Option<String>>,
263}
264
265/// Where the writer thread leaves its failure so a *handle* can report it.
266///
267/// With one source per archive the handle owned the thread, so a send
268/// failure could join and surface the real error. An archive with several
269/// sources has one thread and many handles, and a handle cannot join what it
270/// does not own — so the thread stores its error here on the way out and every
271/// handle reads it, keeping per-tick errors as specific as they were.
272type ErrorSlot = Arc<Mutex<Option<Arc<Error>>>>;
273
274/// Rows dropped as out of order, per source. Shared with the writer thread,
275/// which is the only thing that can see the watermark — see
276/// [`SourceWriter::dropped_out_of_order`].
277///
278/// A map behind one lock rather than an atomic per source: it is touched only
279/// when a row is actually dropped, which for a well-behaved producer is
280/// never, and read only when a caller asks.
281type ShadowCounts = Arc<Mutex<BTreeMap<i64, Dropped>>>;
282
283/// One source's out-of-order drops.
284#[derive(Clone, Copy, Default)]
285struct Dropped {
286 /// WAL rows; [`SourceWriter::dropped_out_of_order`].
287 rows: u64,
288 /// Caller rows; [`SourceWriter::dropped_caller_rows_out_of_order`].
289 caller_rows: u64,
290 /// A replicated copy's source the writer dropped something for, and
291 /// whose later writes it refuses; [`SourceWriter::poisoned`].
292 poisoned: bool,
293}
294
295/// What a [`Msg::SyncStream`] did, in rows.
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
297pub(crate) struct Synced {
298 /// Live rows at or below the sync point sealed into a segment.
299 pub(crate) sealed: u64,
300 /// Live rows at or below the sync point in no segment afterwards, and
301 /// deleted: the encoder refused them or left them out.
302 pub(crate) unsealable: u64,
303 /// Rows above the sync point deleted, live or in a segment.
304 pub(crate) replaced: u64,
305}
306
307/// Mark a replicated source poisoned.
308fn poison(shadowed: &ShadowCounts, source_id: i64) {
309 if let Ok(mut counts) = shadowed.lock() {
310 counts.entry(source_id).or_default().poisoned = true;
311 }
312}
313
314fn is_poisoned(shadowed: &ShadowCounts, source_id: i64) -> bool {
315 shadowed
316 .lock()
317 .map(|c| c.get(&source_id).is_some_and(|d| d.poisoned))
318 .unwrap_or(true)
319}
320
321/// The refusal of a write to a poisoned replicated source.
322fn poisoned_error(source_id: i64) -> Error {
323 Error::Message(format!(
324 "source {source_id} is a replicated copy whose writer dropped rows; it takes no \
325 more writes until it is resumed"
326 ))
327}
328
329/// Reclaim at most this many pages per retention pass — sized to fit inside a
330/// tick. The point of a cap at all is that a shrunken working set drains back
331/// to the filesystem gradually; a full `VACUUM` would return the same space in
332/// one step and stall the source for seconds doing it.
333#[doc(hidden)]
334pub const RECLAIM_PAGES_PER_PASS: u32 = 100;
335
336/// Reclaim only once the free list exceeds this fraction of the file, as a
337/// divisor: `freelist_count * RECLAIM_FREELIST_DIVISOR > page_count`.
338///
339/// Steady-state eviction reuses freed pages, so the free list stays a rounding
340/// error on a healthy rolling buffer and never pays for a reclaim it does not
341/// need. This fires only when the working set genuinely shrank and left the
342/// file many times larger than its contents, which is the one situation where
343/// handing pages back is worth anything.
344#[doc(hidden)]
345pub const RECLAIM_FREELIST_DIVISOR: u32 = 10;
346
347/// How long a clean close spends returning freed pages before giving up and
348/// leaving the rest to a later retention pass. See `reclaim_all`.
349pub const RECLAIM_AT_CLOSE_BUDGET: Duration = Duration::from_secs(2);
350
351/// Handle to the writer thread. Every fallible hand-off reports the writer's
352/// stored error, in the required order: send-failure → join → report.
353pub struct Writer {
354 /// The master sender. Kept only to clone per-source handles from, and
355 /// dropped by `join` so the writer's channel can actually close.
356 tx: Option<SyncSender<Msg>>,
357 thread: Option<JoinHandle<Result<()>>>,
358 path: PathBuf,
359 err: ErrorSlot,
360 shadowed: ShadowCounts,
361 /// The encoder's [`version`](SegmentEncoder::version), copied before the
362 /// encoder moves to the writer thread.
363 encoder_version: Option<String>,
364}
365
366impl Writer {
367 /// Create the archive at `path` and spawn its writer thread.
368 ///
369 /// The file is a valid, openable archive from the moment this returns:
370 /// there is no `.partial`, no rename at the end, and nothing to move
371 /// aside at the start (`Archive::create` refuses an existing file
372 /// atomically). No staging file is needed: an early-killed source is a
373 /// source whose `complete` is 0.
374 ///
375 /// The archive holds no sources yet; add each with `add_source`.
376 pub fn create(path: &Path, encoder: Box<dyn SegmentEncoder + Send>) -> Result<Self> {
377 Self::create_checkpointing_every(path, encoder, CHECKPOINT_INTERVAL)
378 }
379
380 /// [`create`](Self::create) with the WAL checkpoint cadence chosen by the
381 /// caller.
382 ///
383 /// Exists so the staleness bound is testable: asserting it through
384 /// `create` would mean a test that sleeps [`CHECKPOINT_INTERVAL`].
385 /// Production takes the constant.
386 pub fn create_checkpointing_every(
387 path: &Path,
388 encoder: Box<dyn SegmentEncoder + Send>,
389 checkpoint_every: Duration,
390 ) -> Result<Self> {
391 let db = ArchiveMut::create(path)?;
392 Self::spawn(
393 db,
394 path,
395 encoder,
396 Cadence::checkpointing_every(checkpoint_every),
397 true,
398 )
399 }
400
401 /// [`create`](Self::create) with the heartbeat cadence chosen by the
402 /// caller, so a reader's liveness rule is testable without waiting
403 /// [`HEARTBEAT_INTERVAL`]s.
404 #[cfg(any(test, feature = "test-support"))]
405 pub fn create_beating_every(
406 path: &Path,
407 encoder: Box<dyn SegmentEncoder + Send>,
408 heartbeat_every: Duration,
409 ) -> Result<Self> {
410 let db = ArchiveMut::create(path)?;
411 let cadence = Cadence {
412 checkpoint_every: CHECKPOINT_INTERVAL,
413 heartbeat_every,
414 };
415 Self::spawn(db, path, encoder, cadence, true)
416 }
417
418 /// Reopen an existing archive to append to it.
419 ///
420 /// Opening changes nothing; a source is changed only by
421 /// [`resume_source`](Self::resume_source), which is what a caller that
422 /// wants to continue one calls next. Segment numbering continues from
423 /// what the file holds. A second writer of this file is refused as
424 /// [`Error::InUse`].
425 pub fn open(path: &Path, encoder: Box<dyn SegmentEncoder + Send>) -> Result<Self> {
426 Self::open_checkpointing_every(path, encoder, CHECKPOINT_INTERVAL)
427 }
428
429 /// [`open`](Self::open) with the WAL checkpoint cadence chosen by the
430 /// caller.
431 pub fn open_checkpointing_every(
432 path: &Path,
433 encoder: Box<dyn SegmentEncoder + Send>,
434 checkpoint_every: Duration,
435 ) -> Result<Self> {
436 let db = ArchiveMut::open_for_write(path)?;
437 db.ensure_heartbeat_columns()?;
438 Self::spawn(
439 db,
440 path,
441 encoder,
442 Cadence::checkpointing_every(checkpoint_every),
443 false,
444 )
445 }
446
447 /// [`create_checkpointing_every`](Self::create_checkpointing_every) with
448 /// the writer connection's `busy_timeout` chosen by the caller.
449 ///
450 /// Exists so the writer's retry path is testable: with rusqlite's 5 s
451 /// default, a test that holds the write lock from a second connection
452 /// would wait five seconds per attempt to see the writer notice.
453 #[cfg(any(test, feature = "test-support"))]
454 pub fn create_with_busy_timeout(
455 path: &Path,
456 encoder: Box<dyn SegmentEncoder + Send>,
457 checkpoint_every: Duration,
458 busy_timeout: Duration,
459 ) -> Result<Self> {
460 let db = ArchiveMut::create(path)?;
461 db.set_busy_timeout(busy_timeout)?;
462 Self::spawn(
463 db,
464 path,
465 encoder,
466 Cadence::checkpointing_every(checkpoint_every),
467 true,
468 )
469 }
470
471 /// Start the writer thread over an open connection. `created` says
472 /// whether the file is ours to remove if the spawn fails: a file we just
473 /// created is; one we reopened is not.
474 fn spawn(
475 db: ArchiveMut,
476 path: &Path,
477 encoder: Box<dyn SegmentEncoder + Send>,
478 cadence: Cadence,
479 created: bool,
480 ) -> Result<Self> {
481 // Bound 1: the hand-off blocks while the writer is busy,
482 // which is the intended backpressure signal. One slot for the archive
483 // rather than per source, deliberately — the writer is a single
484 // thread against a single write lock, so a deeper queue would only
485 // move the wait, and one source falling behind SHOULD apply
486 // backpressure to the shared append loop rather than growing a buffer.
487 let (tx, rx) = sync_channel(1);
488 let err: ErrorSlot = Arc::new(Mutex::new(None));
489 let thread_err = Arc::clone(&err);
490 let shadowed: ShadowCounts = Arc::new(Mutex::new(BTreeMap::new()));
491 let thread_shadowed = Arc::clone(&shadowed);
492 let encoder_version = encoder.version().map(str::to_string);
493 // A spawn failure removes the file, sidecars included. It leaves a
494 // VALID empty source at the caller's chosen path — which used to be
495 // the argument for keeping it — but valid is not the same as useful:
496 // it holds nothing, and the writer refuses to overwrite an existing
497 // archive, so leaving it turns the operator's retry into "the file
498 // already exists". That reads as a bug in the retry rather than
499 // fallout from the spawn failure that actually happened.
500 let thread = match std::thread::Builder::new()
501 .name("dendro-writer".to_string())
502 .spawn(move || writer_thread(rx, db, thread_err, thread_shadowed, cadence, encoder))
503 {
504 Ok(thread) => thread,
505 Err(e) => {
506 // The closure was dropped with the failed spawn, and the
507 // connection with it, so the file is closed and ours to remove
508 // — if we made it. A reopened archive is left as it was.
509 if created {
510 Archive::remove_archive(path);
511 }
512 return Err(Error::Message(format!(
513 "failed to spawn the archive writer thread: {e}"
514 )));
515 }
516 };
517
518 Ok(Self {
519 tx: Some(tx),
520 thread: Some(thread),
521 path: path.to_path_buf(),
522 err,
523 shadowed,
524 encoder_version,
525 })
526 }
527
528 /// The version the archive's encoder reports, which the writer records
529 /// under [`keys::ENCODER`](crate::keys::ENCODER) for each source it adds.
530 pub fn encoder_version(&self) -> Option<&str> {
531 self.encoder_version.as_deref()
532 }
533
534 /// Open one source in this archive and return its writer handle.
535 ///
536 /// Several may be open at once — that is the point of the container's
537 /// label-tagged `sources` list — and they are independent: each has its
538 /// own segment sequences, its own clock-offset series, and its own
539 /// `complete` flag.
540 pub fn add_source(&mut self, seed: SourceMeta) -> Result<SourceWriter> {
541 self.add_source_with_uuid(seed, None)
542 }
543
544 /// [`add_source`](Self::add_source), for a source whose identity was
545 /// minted somewhere else.
546 ///
547 /// `add_source` mints a fresh uuid, which is right for a source this
548 /// process is starting. This one carries an existing identity across, so
549 /// that the row here **is** that source rather than another one with the
550 /// same labels — the property `SourceRow::uuid` exists for, and what makes
551 /// "do these two archives hold the same source" a comparison instead of a
552 /// guess (FORMAT.md §3.1).
553 ///
554 /// `None` mints a fresh one, exactly as `add_source` does. That is the
555 /// right answer for a source from an archive written before the column
556 /// existed: a fresh id claims only that two copies are not *known* to
557 /// differ, where reusing a `NULL` would claim they are the same.
558 ///
559 /// A uuid the archive already holds is refused as [`Error::DuplicateSource`]
560 /// (FORMAT.md §3.1). Nothing checks that it is a UUID at all; it is the
561 /// caller's identity to assign, and the archive stores it the way it
562 /// stores labels.
563 pub fn add_source_with_uuid(
564 &mut self,
565 seed: SourceMeta,
566 uuid: Option<&str>,
567 ) -> Result<SourceWriter> {
568 // Derived before the seed is sent, since the seed moves.
569 let stagger_key = crate::seal::source_stagger_key(&seed.labels);
570 let Some(tx) = self.tx.as_ref() else {
571 return Err("the archive writer thread has already been joined".into());
572 };
573 let (reply_tx, reply_rx) = sync_channel(0);
574 let alive = Arc::new(());
575 if tx
576 .send(Msg::AddSource {
577 seed: Box::new(seed),
578 uuid: uuid.map(str::to_string),
579 alive: Arc::downgrade(&alive),
580 reply: reply_tx,
581 })
582 .is_err()
583 {
584 return Err(self.take_error());
585 }
586 let source_id = match reply_rx.recv() {
587 Ok(inserted) => inserted?,
588 // The writer died between accepting the message and replying.
589 Err(_) => return Err(self.take_error()),
590 };
591 Ok(SourceWriter {
592 tx: tx.clone(),
593 source_id,
594 stagger_key,
595 err: Arc::clone(&self.err),
596 path: self.path.clone(),
597 floor_ts: None,
598 shadowed: Arc::clone(&self.shadowed),
599 _alive: alive,
600 })
601 }
602
603 /// Continue an existing source in a reopened archive, as a new writer
604 /// session.
605 ///
606 /// The source's `complete` flag is cleared, the session is recorded
607 /// ([`keys::WRITER_SESSIONS`](crate::keys::WRITER_SESSIONS), plus a
608 /// `writer_session` event under [`keys::EVENTS`](crate::keys::EVENTS) at
609 /// the new anchor), and the handle refuses any row stamped at or before
610 /// the newest row the source has held, the returned `last_ts`. That is
611 /// the newest row it holds, or a newer one that retention or a discard
612 /// removed, since a stream's timestamps strictly increase for the life
613 /// of its source. So a clock that went backwards across the restart is
614 /// [`Error::TimelineBackwards`], not a silent collision or a timeline
615 /// that runs backwards. The anchor itself is checked the same way.
616 ///
617 /// `clock_anchor_wall_ns` is this session's anchor: the resuming process
618 /// has a fresh monotonic clock, so its rows are `anchor + elapsed` from a
619 /// new wall reading, not from the source's original anchor; rows keep
620 /// `timestamp + wall_offset = wall` either way, and the gap between
621 /// sessions is real time during which nothing was recorded.
622 pub fn resume_source(
623 &mut self,
624 source_id: i64,
625 clock_anchor_wall_ns: i64,
626 ) -> Result<(SourceWriter, Option<i64>)> {
627 let Some(tx) = self.tx.as_ref() else {
628 return Err(Error::WriterGone);
629 };
630 let (reply_tx, reply_rx) = sync_channel(0);
631 let alive = Arc::new(());
632 if tx
633 .send(Msg::ResumeSource {
634 source_id,
635 clock_anchor_wall_ns,
636 alive: Arc::downgrade(&alive),
637 reply: reply_tx,
638 })
639 .is_err()
640 {
641 return Err(self.take_error());
642 }
643 let resumed = match reply_rx.recv() {
644 Ok(resumed) => resumed?,
645 Err(_) => return Err(self.take_error()),
646 };
647 Ok((
648 SourceWriter {
649 tx: tx.clone(),
650 source_id,
651 stagger_key: crate::seal::source_stagger_key(&resumed.labels),
652 err: Arc::clone(&self.err),
653 path: self.path.clone(),
654 floor_ts: resumed.last_ts,
655 shadowed: Arc::clone(&self.shadowed),
656 _alive: alive,
657 },
658 resumed.last_ts,
659 ))
660 }
661
662 /// Continue an existing source as a replicated copy (WIRE.md §2.1),
663 /// without a writer session: no `writer_sessions` entry, no event, no
664 /// floor, and `complete` left as it is. The source's stream bounds are
665 /// the rows it holds, leaving out `bounds`, because the protocol sets
666 /// them from here on. Any write the writer would drop for it poisons it
667 /// instead (`SourceWriter::poisoned`).
668 pub(crate) fn continue_replica(&mut self, source_id: i64) -> Result<SourceWriter> {
669 let Some(tx) = self.tx.as_ref() else {
670 return Err(Error::WriterGone);
671 };
672 let (reply_tx, reply_rx) = sync_channel(0);
673 let alive = Arc::new(());
674 if tx
675 .send(Msg::Replicate {
676 source_id,
677 alive: Some(Arc::downgrade(&alive)),
678 reply: reply_tx,
679 })
680 .is_err()
681 {
682 return Err(self.take_error());
683 }
684 let labels = match reply_rx.recv() {
685 Ok(labels) => labels?,
686 Err(_) => return Err(self.take_error()),
687 };
688 Ok(SourceWriter {
689 tx: tx.clone(),
690 source_id,
691 stagger_key: crate::seal::source_stagger_key(&labels),
692 err: Arc::clone(&self.err),
693 path: self.path.clone(),
694 floor_ts: None,
695 shadowed: Arc::clone(&self.shadowed),
696 _alive: alive,
697 })
698 }
699
700 /// The archive being written — valid and readable while it is written.
701 pub fn path(&self) -> &Path {
702 &self.path
703 }
704
705 /// Write a new revision of document `(kind, name)` through the writer
706 /// thread, and return its id and uuid once it is committed.
707 ///
708 /// [`ArchiveMut::put_document`], for an archive this writer is
709 /// recording: an `ArchiveMut` cannot open a file a writer holds, and
710 /// there is one writing connection, so a document written during a
711 /// recording goes through this thread like every other write. It is
712 /// ordered after everything queued before it and committed on its own.
713 /// A refusal (a reserved kind, a body that is not JSON, a v4 archive
714 /// reopened with [`Writer::open`], which takes no documents) is returned
715 /// and does not stop the writer.
716 pub fn put_document(
717 &mut self,
718 kind: &str,
719 name: &str,
720 schema: &str,
721 body: &str,
722 ) -> Result<RevisionId> {
723 self.send_document(kind, name, schema, body, None)
724 }
725
726 /// [`ArchiveMut::put_document_if_current`] through the writer thread:
727 /// refused with [`Error::DocumentConflict`] unless the current
728 /// document's uuid is `expected`.
729 pub fn put_document_if_current(
730 &mut self,
731 kind: &str,
732 name: &str,
733 schema: &str,
734 body: &str,
735 expected: Option<&str>,
736 ) -> Result<RevisionId> {
737 self.send_document(kind, name, schema, body, Some(expected.map(str::to_string)))
738 }
739
740 /// [`ArchiveMut::delete_document`] through the writer thread.
741 pub fn delete_document(&mut self, kind: &str, name: &str) -> Result<Option<RevisionId>> {
742 let Some(tx) = self.tx.as_ref() else {
743 return Err(Error::WriterGone);
744 };
745 let (reply_tx, reply_rx) = sync_channel(0);
746 if tx
747 .send(Msg::DeleteDocument {
748 kind: kind.to_string(),
749 name: name.to_string(),
750 reply: reply_tx,
751 })
752 .is_err()
753 {
754 return Err(self.take_error());
755 }
756 match reply_rx.recv() {
757 Ok(deleted) => deleted,
758 Err(_) => Err(self.take_error()),
759 }
760 }
761
762 fn send_document(
763 &mut self,
764 kind: &str,
765 name: &str,
766 schema: &str,
767 body: &str,
768 expected: Option<Option<String>>,
769 ) -> Result<RevisionId> {
770 let Some(tx) = self.tx.as_ref() else {
771 return Err(Error::WriterGone);
772 };
773 let (reply_tx, reply_rx) = sync_channel(0);
774 let put = Box::new(DocumentPut {
775 kind: kind.to_string(),
776 name: name.to_string(),
777 schema: schema.to_string(),
778 body: body.to_string(),
779 expected,
780 });
781 if tx
782 .send(Msg::PutDocument {
783 put,
784 reply: reply_tx,
785 })
786 .is_err()
787 {
788 return Err(self.take_error());
789 }
790 match reply_rx.recv() {
791 Ok(written) => written,
792 Err(_) => Err(self.take_error()),
793 }
794 }
795
796 /// Close the channel and join the writer, returning its stored result.
797 /// Idempotent: a second call is a no-op `Ok`.
798 ///
799 /// Drop every handle first — but not because this would otherwise block.
800 /// `Shutdown` is sent below *before* our own sender is released, and the
801 /// writer honors it whoever else still holds a clone, so a wrong order is
802 /// an error (work queued after the stop is dropped), not a hang. The
803 /// guarantee comes from `Msg::Shutdown`, not from the drop order, and
804 /// removing it would turn every "must drop first" note in this file into a
805 /// real deadlock.
806 pub fn join(&mut self) -> Result<()> {
807 // Tell the writer to stop before releasing our own sender. A handle
808 // that outlived its archive still holds a clone, so waiting for the
809 // channel to close on its own could wait forever; `Shutdown` ends the
810 // loop regardless of who is still holding one. A failed send just
811 // means the writer already exited.
812 if let Some(tx) = self.tx.as_ref() {
813 let _ = tx.send(Msg::Shutdown);
814 }
815 self.tx = None;
816 match self.thread.take() {
817 // The panic arm is unreachable by contract (the global hook exits
818 // the process before unwinding); it exists so this path cannot
819 // itself panic.
820 Some(handle) => handle
821 .join()
822 .unwrap_or_else(|_| Err("the archive writer thread panicked".into())),
823 None => Ok(()),
824 }
825 }
826
827 fn take_error(&mut self) -> Error {
828 take_writer_error(&self.err)
829 }
830
831 /// Commit one tick's staged rows for every source in one transaction.
832 ///
833 /// The multi-source counterpart to [`SourceWriter::wal`]. Each
834 /// source's rows come from the caller's staging; this hands them
835 /// over together so the archive pays one commit — one fsync at
836 /// `synchronous=FULL` — per tick rather than one per endpoint.
837 ///
838 /// The hand-off is a blocking send on a
839 /// bound-1 channel from inside the append, so a per-source commit
840 /// put a linear-in-endpoint-count fsync bill on the loop that has to keep
841 /// up with the sampling interval. `seal_batch` already refused exactly this
842 /// trade within one source; this is the same argument across them.
843 ///
844 /// An empty batch does not send: it still checks the writer is alive, so a
845 /// tick where nothing advanced cannot mask a dead writer.
846 pub fn wal_tick(&mut self, ticks: Vec<(i64, Vec<WalRow>)>) -> Result<()> {
847 let ticks: Vec<(i64, Vec<WalRow>)> = ticks
848 .into_iter()
849 .filter(|(_, rows)| !rows.is_empty())
850 .collect();
851 if ticks.is_empty() {
852 return self.check_alive();
853 }
854 let Some(tx) = self.tx.as_ref() else {
855 return Err("the archive writer thread has already been joined".into());
856 };
857 if tx.send(Msg::Wal { ticks }).is_ok() {
858 return Ok(());
859 }
860 Err(take_writer_error(&self.err))
861 }
862
863 /// How many transactions the writer has committed, as a barrier: the
864 /// answer arrives only after everything queued ahead of it is handled.
865 ///
866 /// Exists so "one commit per tick, whatever the endpoint count" is a
867 /// property a test asserts rather than a comment claims — an fsync is not
868 /// observable from inside the process, but the commit that causes it is.
869 #[cfg(any(test, feature = "test-support"))]
870 pub fn commits_for_test(&mut self) -> u64 {
871 let (tx, rx) = sync_channel(0);
872 let Some(sender) = self.tx.as_ref() else {
873 return 0;
874 };
875 if sender.send(Msg::Commits(tx)).is_err() {
876 return 0;
877 }
878 rx.recv().unwrap_or(0)
879 }
880
881 /// Whether the writer thread is still alive, without writing anything.
882 ///
883 /// Mirrors `SourceWriter::check_alive`: the shared error slot is the
884 /// only signal available, since the archive cannot ask a thread it owns
885 /// whether it has finished without joining it.
886 fn check_alive(&mut self) -> Result<()> {
887 match self.err.lock() {
888 Ok(guard) if guard.is_some() => Err(Error::Writer(guard.clone().expect("is_some"))),
889 _ => Ok(()),
890 }
891 }
892
893 /// Finalize the one source and join the writer, so the file is fully
894 /// committed when this returns.
895 ///
896 /// The synchronous shape callers had before `finalize` was split: the
897 /// handle can only *queue* completion now, since the archive owns the
898 /// thread, so anything that reads the file straight afterwards has to join
899 /// too.
900 #[cfg(any(test, feature = "test-support"))]
901 pub fn finalize_single(mut self, writer: SourceWriter, clock_offset: (i64, i64)) -> Result<()> {
902 let queued = writer.finalize(clock_offset);
903 let joined = self.join();
904 queued.and(joined)
905 }
906
907 /// Create an archive holding exactly one source.
908 ///
909 /// The shape every caller had before archives could hold several, and
910 /// still what a rolling buffer and a single-producer source want. Returns
911 /// both halves because the archive owns the writer thread and must outlive
912 /// the handle — `Shutdown` means a wrong order is an error rather than a
913 /// hang, but the right order is still: finish with the handle, then join.
914 #[cfg(any(test, feature = "test-support"))]
915 pub fn single(
916 path: &Path,
917 encoder: Box<dyn SegmentEncoder + Send>,
918 seed: SourceMeta,
919 ) -> Result<(Self, SourceWriter)> {
920 let mut archive = Self::create(path, encoder)?;
921 let writer = archive.add_source(seed)?;
922 Ok((archive, writer))
923 }
924}
925
926impl std::fmt::Debug for Writer {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 f.debug_struct("Writer")
929 .field("path", &self.path)
930 .field("joined", &self.thread.is_none())
931 .finish_non_exhaustive()
932 }
933}
934
935impl Drop for Writer {
936 /// The writer must be joined on every path out — including the ones that
937 /// skip an explicit join — so a dropped archive never leaves a detached
938 /// thread still writing to the database.
939 fn drop(&mut self) {
940 if let Err(e) = self.join() {
941 warn!("the archive writer failed: {e}");
942 }
943 }
944}
945
946/// What the writer thread answers a `ResumeSource` with.
947struct Resumed {
948 labels: BTreeMap<String, String>,
949 /// The newest row timestamp the source has held: what it holds,
950 /// segments and WAL together, or a newer row a delete removed
951 /// (`bounds`). `None` for a source that has held no rows.
952 last_ts: Option<i64>,
953}
954
955/// One source's handle onto a shared archive writer.
956///
957/// Cheap and cloneable-in-spirit: it is a sender plus an id. Dropping it
958/// releases this source's claim on the writer; the thread exits once every
959/// handle *and* the archive's master sender are gone.
960pub struct SourceWriter {
961 tx: SyncSender<Msg>,
962 source_id: i64,
963 /// Set on a resumed source: every row this session commits must be
964 /// stamped after it. See [`Writer::resume_source`].
965 floor_ts: Option<i64>,
966 /// This source's stagger identity — its canonical label set at
967 /// `add_source`, which [`set_identity`](Self::set_identity) does not
968 /// change. Held here
969 /// so the seal policy can desync tables ACROSS sources as well as
970 /// within one; see `stagger_bucket`.
971 stagger_key: String,
972 err: ErrorSlot,
973 /// The archive this source lives in. Carried per handle so a caller
974 /// holding only a source can still name its file — one `PathBuf` per
975 /// source, against an archive that holds at most a handful.
976 path: PathBuf,
977 shadowed: ShadowCounts,
978 /// Held only to be dropped with the handle. The writer keeps a `Weak` to
979 /// it and stops this source's heartbeat once it cannot upgrade, so a
980 /// handle dropped without `finalize` reads as a stopped writer, not a
981 /// running one. A token rather than a message from `Drop`: `send` would
982 /// block on the bounded channel, and `try_send` can lose the message.
983 _alive: Arc<()>,
984}
985
986impl std::fmt::Debug for SourceWriter {
987 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
988 f.debug_struct("SourceWriter")
989 .field("source_id", &self.source_id)
990 .field("path", &self.path)
991 .field("floor_ts", &self.floor_ts)
992 .finish_non_exhaustive()
993 }
994}
995
996impl SourceWriter {
997 /// The archive being written — valid and readable while it is written.
998 ///
999 /// Reachable only through a caller that stages per source, which no live caller
1000 /// uses: the recorder asks the archive directly. Kept because a recorder
1001 /// naming its own output is a natural use case.
1002 #[cfg_attr(not(test), allow(dead_code))]
1003 pub fn path(&self) -> &Path {
1004 &self.path
1005 }
1006
1007 /// The `sources` row this handle appends to.
1008 pub fn source_id(&self) -> i64 {
1009 self.source_id
1010 }
1011
1012 #[cfg_attr(not(test), allow(dead_code))]
1013 /// This source's stagger identity — see `stagger_bucket`.
1014 pub fn stagger_key(&self) -> &str {
1015 &self.stagger_key
1016 }
1017
1018 /// Hand one tick's WAL rows to the writer for this source.
1019 ///
1020 /// The single-source spelling.
1021 /// An archive with several sources must stage each one and commit the
1022 /// tick once, through [`Writer::wal_tick`]: one transaction instead of
1023 /// one per source.
1024 pub fn wal(&mut self, rows: Vec<WalRow>) -> Result<()> {
1025 if rows.is_empty() {
1026 return self.check_alive();
1027 }
1028 // The handle's half of the floor: a resumed source refuses, here and
1029 // now, a row at or before the newest row the source has held. The writer
1030 // thread enforces the same rule for rows that arrive through
1031 // `Writer::wal_tick`, which has no handle to ask.
1032 if let Some(floor) = self.floor_ts {
1033 if let Some(r) = rows.iter().find(|r| r.ts <= floor) {
1034 return Err(Error::TimelineBackwards {
1035 source_id: self.source_id,
1036 ts: r.ts,
1037 floor,
1038 });
1039 }
1040 }
1041 self.send(Msg::Wal {
1042 ticks: vec![(self.source_id, rows)],
1043 })
1044 }
1045
1046 /// The newest row timestamp the source has held, including one a
1047 /// delete removed (FORMAT.md §3.7), when this handle resumed a source;
1048 /// every row must be stamped after it.
1049 pub fn floor_ts(&self) -> Option<i64> {
1050 self.floor_ts
1051 }
1052
1053 /// How many of this source's appends have been dropped for arriving at
1054 /// or below their stream's newest row, sealed or live, as it stood before
1055 /// the tick that carried them.
1056 ///
1057 /// A non-zero count is a producer appending out of order within a stream,
1058 /// which this container does not support. Below the newest sealed row such
1059 /// a row cannot be read: the watermark that keeps the seal seam free of
1060 /// duplicates shadows it exactly as it shadows an already-sealed row.
1061 /// Below the newest live row it could be read, but a reader that tails the
1062 /// stream by timestamp, such as a replication publisher, has already passed
1063 /// it. At the newest row's timestamp it would collide with that row. The
1064 /// writer drops it and logs once per stream. Within one tick a stream's
1065 /// rows may arrive in any order; a second row at one timestamp in the tick
1066 /// is dropped. A different stream or a different source has its own bound
1067 /// and is not affected.
1068 ///
1069 /// Counted rather than returned because an append is deliberately
1070 /// fire-and-forget: reporting per call would make every tick a
1071 /// round-trip to the writer thread, which is the cost the bound-1
1072 /// channel exists to avoid. Read it after a [`sync`](Self::sync) for a
1073 /// count that includes everything handed over so far.
1074 pub fn dropped_out_of_order(&self) -> u64 {
1075 self.dropped().rows
1076 }
1077
1078 /// How many of this source's caller rows ([`caller_rows`](Self::caller_rows))
1079 /// have been dropped for arriving below their name's floor, as it stood
1080 /// before the call that carried them.
1081 ///
1082 /// A name's rows append in `ts` order: several may share the newest
1083 /// `ts`, and within one call they may arrive in any order, but a row
1084 /// below the newest is dropped. When the name's newest rows are not in
1085 /// the file, because retention removed them or a time-bounded copy left
1086 /// them out, the next row must be above them (FORMAT.md §3.7). Counted, not
1087 /// returned, for the reason [`dropped_out_of_order`](Self::dropped_out_of_order)
1088 /// gives.
1089 pub fn dropped_caller_rows_out_of_order(&self) -> u64 {
1090 self.dropped().caller_rows
1091 }
1092
1093 fn dropped(&self) -> Dropped {
1094 self.shadowed
1095 .lock()
1096 .ok()
1097 .and_then(|c| c.get(&self.source_id).copied())
1098 .unwrap_or_default()
1099 }
1100
1101 /// Hand one seal batch (= one transaction) to the writer, as the streams
1102 /// to seal. Blocks while the channel is full: that is the intended
1103 /// backpressure signal.
1104 ///
1105 /// Each stream's live rows become one segment, however many there are.
1106 /// A caller that asks for a seal when [`SegmentAccount::is_due`]
1107 /// says so can still get a segment past its policy's `max_rows`: rows
1108 /// that arrive between two seal checks all go into the next segment.
1109 /// [`seal_capped`](Self::seal_capped) bounds that.
1110 ///
1111 /// [`SegmentAccount::is_due`]: crate::seal::SegmentAccount::is_due
1112 pub fn seal(&mut self, batch: Vec<String>) -> Result<()> {
1113 self.seal_capped(batch, usize::MAX)
1114 }
1115
1116 /// [`seal`](Self::seal), with no segment holding more than `max_rows`
1117 /// WAL rows. A stream with more live rows than that is sealed as
1118 /// consecutive segments of `max_rows` rows each, oldest first, and a
1119 /// last one with the remainder: 7 live rows at `max_rows = 2` become
1120 /// segments of 2, 2, 2 and 1 rows. All of them, for every stream in the
1121 /// batch, commit in the batch's one transaction. A `max_rows` of 0 is
1122 /// taken as 1.
1123 ///
1124 /// Pass the policy's `max_rows` ([`SealPolicy::max_rows`]). The cap is
1125 /// on WAL rows, which is what the catalog's `rows` counts, not on the
1126 /// parquet rows an encoder writes for them.
1127 ///
1128 /// Only the row cap is applied here. The byte cap and the age bound
1129 /// stay triggers: they decide when the caller asks for a seal, and a
1130 /// split does not look at them. The writer does not have the byte
1131 /// estimate the caller's account charged for each row, and splitting
1132 /// by a different measure would put the edges where the account did
1133 /// not.
1134 ///
1135 /// Every part after the first is encoded with
1136 /// [`SegmentEncoder::encode_after`], which an encoder whose rows depend
1137 /// on earlier rows must implement. If a part's segment does not hold
1138 /// every row it was given at the edges it shares with its neighbours
1139 /// (it dropped a row there, or returned no segment), the split is
1140 /// abandoned for that stream and its live rows are sealed as one
1141 /// segment, as `seal` would: a dropped row inside the run would
1142 /// otherwise sit below a later part's watermark, out of every segment
1143 /// and every read.
1144 ///
1145 /// [`SealPolicy::max_rows`]: crate::seal::SealPolicy::max_rows
1146 /// [`SegmentEncoder::encode_after`]: crate::segment::SegmentEncoder::encode_after
1147 pub fn seal_capped(&mut self, batch: Vec<String>, max_rows: usize) -> Result<()> {
1148 if batch.is_empty() {
1149 return self.check_alive();
1150 }
1151 self.send(Msg::Seal {
1152 source_id: self.source_id,
1153 batch,
1154 max_rows: max_rows.max(1),
1155 })
1156 }
1157
1158 /// Insert a segment built elsewhere at this stream's next `seq`.
1159 ///
1160 /// The other entrance to the seal path. [`seal`](Self::seal) says "encode
1161 /// what is in the WAL"; this says "here are the bytes". It is what makes a
1162 /// replication catch-up cheap — shipping a sealed segment costs far less
1163 /// than replaying the rows that built it — and it is equally the way to
1164 /// splice a segment from another archive into a live one.
1165 ///
1166 /// **The bytes are not checked against anything.** A seal runs
1167 /// [`segment::materialize`](crate::segment::materialize) because it has the
1168 /// input rows to check the encoder's answer against; here there are none,
1169 /// and `meta` is taken on trust exactly as
1170 /// [`rewrite::copy_sources_into`](crate::rewrite::copy_sources_into) takes
1171 /// a segment it carries across. `meta` must describe the **segment**, never
1172 /// some other rows — see [`Segment`](crate::segment::Segment).
1173 ///
1174 /// What *is* checked is where the segment lands:
1175 ///
1176 /// * A segment wholly at or below the stream's newest sealed row is
1177 /// **already held**, and this returns `Ok(false)`. That is the normal
1178 /// outcome of a reconnect, not a failure.
1179 /// * A segment *straddling* it is refused. Its rows below the watermark
1180 /// could never be read (FORMAT.md §3.3), and splitting it would mean
1181 /// decoding it.
1182 /// * A segment whose span reaches an unsealed row already in the WAL is
1183 /// refused. A seal earns the right to prune by having encoded exactly
1184 /// the rows it covers; this one proves nothing about those rows, so
1185 /// adopting it would shadow rows no segment holds.
1186 ///
1187 /// Unlike `wal` and `seal` this is **not** fire-and-forget: it waits for
1188 /// the writer. A caller applying a stream of segments cannot usefully learn
1189 /// about a refusal several segments later, and the bytes are in the message
1190 /// rather than in the WAL, so there is nothing to retry from.
1191 pub fn adopt_segment(
1192 &mut self,
1193 stream: &str,
1194 meta: &SegmentMeta,
1195 bytes: &[u8],
1196 caller_index: Option<&[u8]>,
1197 ) -> Result<bool> {
1198 let (reply_tx, reply_rx) = sync_channel(0);
1199 if self
1200 .tx
1201 .send(Msg::AdoptSegment {
1202 source_id: self.source_id,
1203 segment: Box::new(Adopted {
1204 stream: stream.to_string(),
1205 meta: *meta,
1206 bytes: bytes.to_vec(),
1207 caller_index: caller_index.map(<[u8]>::to_vec),
1208 }),
1209 reply: reply_tx,
1210 })
1211 .is_err()
1212 {
1213 return Err(take_writer_error(&self.err));
1214 }
1215 match reply_rx.recv() {
1216 Ok(adopted) => adopted,
1217 // The writer died between accepting the message and replying.
1218 Err(_) => Err(take_writer_error(&self.err)),
1219 }
1220 }
1221
1222 /// Make this source, just added, a replicated copy's (WIRE.md §2.1). See
1223 /// [`Writer::continue_replica`].
1224 pub(crate) fn replicate(&mut self) -> Result<()> {
1225 let source_id = self.source_id;
1226 self.request(|reply| Msg::Replicate {
1227 source_id,
1228 alive: None,
1229 reply,
1230 })
1231 .map(|_| ())
1232 }
1233
1234 /// Whether this replicated copy's source has been poisoned: the writer
1235 /// dropped a tick, a row or an entry for it, and refuses its later
1236 /// writes. The file holds what was written before the drop, so a resume
1237 /// request built from it lies below the hole.
1238 pub(crate) fn poisoned(&self) -> bool {
1239 is_poisoned(&self.shadowed, self.source_id)
1240 }
1241
1242 /// Set `stream` to the sync point `at` (WIRE.md §4.7), waiting for the
1243 /// writer. Only on a replicated copy.
1244 pub(crate) fn sync_to(&mut self, stream: &str, at: i64) -> Result<Synced> {
1245 let stream = stream.to_string();
1246 let source_id = self.source_id;
1247 self.request(|reply| Msg::SyncStream {
1248 source_id,
1249 stream,
1250 at,
1251 reply,
1252 })
1253 }
1254
1255 /// Insert segments of `stream`, each of which replaces this copy's live
1256 /// rows in `(after, meta.last_ts]` (WIRE.md §4.8), in one transaction,
1257 /// waiting for the writer, and return the live rows they deleted below
1258 /// their `first_ts`. Each part is checked against the copy as the parts
1259 /// before it leave it; one that fails the check commits none of them.
1260 pub(crate) fn adopt_segments_after(
1261 &mut self,
1262 stream: &str,
1263 parts: Vec<AfterPart>,
1264 ) -> Result<u64> {
1265 let parts = parts
1266 .into_iter()
1267 .map(|p| AdoptedAfter {
1268 after: p.after,
1269 segment: Adopted {
1270 stream: stream.to_string(),
1271 meta: p.meta,
1272 bytes: p.bytes,
1273 caller_index: p.caller_index,
1274 },
1275 })
1276 .collect();
1277 let source_id = self.source_id;
1278 self.request(|reply| Msg::AdoptAfter {
1279 source_id,
1280 parts,
1281 reply,
1282 })
1283 }
1284
1285 /// Clear this source's `complete` flag, waiting for the writer.
1286 pub(crate) fn mark_incomplete(&mut self) -> Result<()> {
1287 let source_id = self.source_id;
1288 self.request(|reply| Msg::MarkIncomplete { source_id, reply })
1289 }
1290
1291 /// Send a message that replies, and wait for the reply.
1292 fn request<T>(&self, msg: impl FnOnce(SyncSender<Result<T>>) -> Msg) -> Result<T> {
1293 let (reply_tx, reply_rx) = sync_channel(0);
1294 if self.tx.send(msg(reply_tx)).is_err() {
1295 return Err(take_writer_error(&self.err));
1296 }
1297 match reply_rx.recv() {
1298 Ok(answer) => answer,
1299 Err(_) => Err(take_writer_error(&self.err)),
1300 }
1301 }
1302
1303 /// Merge `patch` into this source's metadata, ordered with the ticks
1304 /// around it and committed on its own. Fire-and-forget like `wal`.
1305 ///
1306 /// Metadata is not the recording: a patch that cannot be applied — a
1307 /// lock that outlasts the retries, a source the writer cannot find — is
1308 /// logged and skipped, never a reason to stop the writer. A caller that
1309 /// must know it landed follows with [`sync`](Self::sync) and reads it
1310 /// back.
1311 pub fn update_metadata(&mut self, patch: BTreeMap<String, String>) -> Result<()> {
1312 if patch.is_empty() {
1313 return self.check_alive();
1314 }
1315 self.send(Msg::UpdateMetadata {
1316 source_id: self.source_id,
1317 patch,
1318 })
1319 }
1320
1321 /// Replace this source's labels and metadata with these, ordered with
1322 /// the ticks around it and committed on its own. Fire-and-forget like
1323 /// `wal`, and never fatal, for the reason
1324 /// [`update_metadata`](Self::update_metadata) gives.
1325 ///
1326 /// Both maps are replaced whole, so a key absent from them is removed,
1327 /// except the keys this writer maintains, `encoder` and
1328 /// `writer_sessions`, which keep their stored values where the source has
1329 /// them; `events` is written
1330 /// as given, including a `writer_session` event dendro appended at a
1331 /// resume (see
1332 /// [`ArchiveMut::set_source_identity`](crate::archive::ArchiveMut::set_source_identity)).
1333 /// A recording adds keys with `update_metadata`; this is for a caller
1334 /// carrying an identity somebody else changed, such as a replication
1335 /// subscriber applying a
1336 /// [`SourceUpdate`](crate::replicate::Frame::SourceUpdate).
1337 pub fn set_identity(
1338 &mut self,
1339 labels: BTreeMap<String, String>,
1340 metadata: BTreeMap<String, String>,
1341 ) -> Result<()> {
1342 self.send(Msg::SetIdentity {
1343 source_id: self.source_id,
1344 labels,
1345 metadata,
1346 })
1347 }
1348
1349 /// Record one clock-drift observation for this source, ordered with the
1350 /// ticks around it and committed on its own. Fire-and-forget like
1351 /// [`wal`](Self::wal).
1352 ///
1353 /// The writer already records these at every seal and at finalize
1354 /// (FORMAT.md §5), so a recording needs this never. It is for a caller
1355 /// carrying a series somebody else observed: a replication subscriber has
1356 /// to land the publisher's observations, because its own seals fall in
1357 /// different places and would summarize the same rows at different
1358 /// timestamps.
1359 ///
1360 /// At most one observation per `(source, ts)`, first one wins — the
1361 /// schema decides that, not this call.
1362 pub fn clock_offset(&mut self, ts: i64, offset_ns: i64) -> Result<()> {
1363 self.send(Msg::ClockOffset {
1364 source_id: self.source_id,
1365 ts,
1366 offset_ns,
1367 })
1368 }
1369
1370 /// Append rows to the caller's time-keyed store for `stream`, ordered
1371 /// with the ticks around them and committed on their own. Fire-and-forget
1372 /// like [`wal`](Self::wal): a transient failure is retried, and a run of
1373 /// dropped commits stops the writer the way dropped ticks do. See
1374 /// [`CallerRow`] for what the store is.
1375 ///
1376 /// A row whose `ts` is below the name's newest is dropped and counted in
1377 /// [`dropped_caller_rows_out_of_order`](Self::dropped_caller_rows_out_of_order).
1378 /// Rows at the newest `ts` are kept, so several may share one.
1379 pub fn caller_rows(&mut self, stream: impl Into<String>, rows: Vec<CallerRow>) -> Result<()> {
1380 if rows.is_empty() {
1381 return self.check_alive();
1382 }
1383 self.send(Msg::CallerRows {
1384 source_id: self.source_id,
1385 stream: stream.into(),
1386 rows,
1387 })
1388 }
1389
1390 /// Ask the writer to apply retention at `cutoff_ts`.
1391 ///
1392 /// It goes through the writer thread rather than a second connection for
1393 /// the same reason everything else does: the writer OWNS this file, and
1394 /// [`ArchiveMut::open`](crate::archive::ArchiveMut::open) on a file it holds is refused
1395 /// as `InUse`. Readers are unaffected either way; WAL mode
1396 /// lets them proceed while this commits.
1397 ///
1398 /// Not fire-and-forget, unlike `wal` and `seal`: it waits for the writer
1399 /// thread to run the pass and returns what it removed, or its error.
1400 ///
1401 /// The pass keeps every live row, whatever its timestamp, and counts the
1402 /// ones before the cutoff in [`Evicted::kept_live_rows`]; see
1403 /// [`ArchiveMut::evict_before`](crate::archive::ArchiveMut::evict_before).
1404 ///
1405 /// A stream whose last [`seal`](Self::seal) was deferred is sealed first,
1406 /// with that seal's retries, so the rows it seals can be evicted. After
1407 /// the first deferred stream whose retry fails with a retryable error,
1408 /// the remaining ones are not tried, so a pass waits for at most one
1409 /// retry schedule before its own transaction, which waits up to one
1410 /// busy timeout; those stay deferred and are retried before the next
1411 /// pass. A stream whose retried seal fails with an error that is not
1412 /// retryable, such as an encoder error, is logged and no longer
1413 /// deferred. Either way the pass evicts the stream's segments and keeps
1414 /// its live rows, as for any stream. This applies to every eviction
1415 /// spelling.
1416 pub fn evict_before(&mut self, cutoff_ts: i64) -> Result<Evicted> {
1417 self.evict(cutoff_ts, None, None)
1418 }
1419
1420 /// [`evict_before`](Self::evict_before), cutting each name's caller rows
1421 /// where `floor` says rather than at the cutoff. The writer-side spelling
1422 /// of
1423 /// [`ArchiveMut::evict_before_with_floor`](crate::archive::ArchiveMut::evict_before_with_floor);
1424 /// see [`CallerRowFloor`](crate::archive::CallerRowFloor).
1425 pub fn evict_before_with_floor(
1426 &mut self,
1427 cutoff_ts: i64,
1428 floor: CallerRowFloorFn,
1429 ) -> Result<Evicted> {
1430 self.evict(cutoff_ts, None, Some(floor))
1431 }
1432
1433 /// [`evict_before`](Self::evict_before), restricted to the streams `evict`
1434 /// accepts.
1435 ///
1436 /// **The predicate selects what is REMOVED**, matching the verb in the
1437 /// name. It was called `keep` here, which inverted it: a caller following
1438 /// the doc deleted precisely the streams it meant to retain, silently and
1439 /// irreversibly.
1440 ///
1441 /// The writer-side spelling of
1442 /// [`ArchiveMut::evict_streams_before`](crate::archive::ArchiveMut::evict_streams_before),
1443 /// and the one to use while the writer runs: a `ArchiveMut::open` on a file
1444 /// this thread holds is refused as `InUse`.
1445 pub fn evict_streams_before(&mut self, cutoff_ts: i64, keep: StreamFilter) -> Result<Evicted> {
1446 self.evict(cutoff_ts, Some(keep), None)
1447 }
1448
1449 /// [`evict_streams_before`](Self::evict_streams_before) with a
1450 /// [`CallerRowFloorFn`], asked only for the names `evict` accepts.
1451 pub fn evict_streams_before_with_floor(
1452 &mut self,
1453 cutoff_ts: i64,
1454 evict: StreamFilter,
1455 floor: CallerRowFloorFn,
1456 ) -> Result<Evicted> {
1457 self.evict(cutoff_ts, Some(evict), Some(floor))
1458 }
1459
1460 /// Both spellings, and the reply that makes the count reachable.
1461 ///
1462 /// Synchronous, unlike the other hand-offs: a retention pass is not on the
1463 /// append path, and a caller running one wants to know what it did — that
1464 /// is the difference between "the window moved" and "nothing was old enough
1465 /// yet", and a size-bounded policy needs it to decide whether to cut again.
1466 fn evict(
1467 &mut self,
1468 cutoff_ts: i64,
1469 streams: Option<StreamFilter>,
1470 floor: Option<CallerRowFloorFn>,
1471 ) -> Result<Evicted> {
1472 let (tx, rx) = sync_channel(0);
1473 self.send(Msg::Evict {
1474 source_id: self.source_id,
1475 cutoff_ts,
1476 streams,
1477 floor,
1478 reply: tx,
1479 })?;
1480 rx.recv().map_err(|_| take_writer_error(&self.err))?
1481 }
1482
1483 /// Delete the live WAL rows of this source's streams that `discard`
1484 /// accepts, the rows after each stream's newest sealed row or every row
1485 /// of a stream with no segment, keeping the streams' segments, and
1486 /// return how many rows were deleted. The
1487 /// writer-side spelling of
1488 /// [`ArchiveMut::discard_live_rows`](crate::archive::ArchiveMut::discard_live_rows).
1489 ///
1490 /// A deferred seal of those streams is dropped. The stream's timestamps
1491 /// strictly increase for the life of its source (FORMAT.md §3.7): a row
1492 /// written afterwards at or below a discarded row is dropped and counted
1493 /// in [`dropped_out_of_order`](Self::dropped_out_of_order) by this
1494 /// writer, and refused as [`Error::TimelineBackwards`] by a later writer
1495 /// that resumes the source, whose floor includes it. The discard is
1496 /// not replicated: a subscriber that already received the rows keeps
1497 /// them.
1498 /// Waits for the writer thread, as eviction does. A failed discard
1499 /// deletes nothing and does not stop the writer.
1500 pub fn discard_live_rows(&mut self, discard: StreamFilter) -> Result<usize> {
1501 let (tx, rx) = sync_channel(0);
1502 self.send(Msg::DiscardLive {
1503 source_id: self.source_id,
1504 streams: discard,
1505 reply: tx,
1506 })?;
1507 rx.recv().map_err(|_| take_writer_error(&self.err))?
1508 }
1509
1510 /// Block until everything handed off so far has been committed.
1511 ///
1512 /// **It exists because the file lags the caller.** The append hand-offs
1513 /// queue work and return immediately, so a caller that hands off an ingest and
1514 /// then opens a SECOND connection to look at the file, for a status report
1515 /// or a dump, can observe the state from before its own last call. That is
1516 /// fine for a status reading and fatal for an assertion.
1517 ///
1518 /// Ordering is what makes this work rather than any locking: the channel is
1519 /// FIFO and the writer is single-threaded, so the reply cannot be sent
1520 /// until every earlier message has been fully handled. With several
1521 /// sources sharing one writer that is *stronger* than it was, not
1522 /// weaker: the barrier covers the other sources' queued work too.
1523 ///
1524 /// A dropped reply channel is treated as success — it means the writer
1525 /// exited, and its error surfaces through the usual hand-off path rather
1526 /// than here.
1527 ///
1528 /// **Test-only, and that is a statement about the callers rather than the
1529 /// mechanism.** Nothing in production asserts on the file immediately after
1530 /// handing off a tick: a status report showing retention a tick behind is
1531 /// inherent to an asynchronous writer and harmless. Tests do assert it, and
1532 /// without a barrier they race the writer. Give this a `cfg`-free home the
1533 /// moment a real caller needs to see its own last tick.
1534 pub fn sync(&mut self) -> Result<()> {
1535 let (tx, rx) = sync_channel(0);
1536 self.send(Msg::Sync(tx))?;
1537 // A closed reply channel means the writer exited before it reached this
1538 // barrier, which is exactly the case a caller is syncing to find out
1539 // about. Discarding it — `let _ = rx.recv()` — made `sync` report
1540 // success for work that was never committed, so a failed seal reached
1541 // the caller as `Ok(())` and only surfaced on some later send.
1542 rx.recv().map_err(|_| take_writer_error(&self.err))
1543 }
1544
1545 /// Record this source's final clock offset and mark it complete.
1546 ///
1547 /// Consumes the handle, which is what releases its sender: the writer
1548 /// thread ends when the last handle and the archive's master sender are
1549 /// gone, so a handle kept alive past its finalize would stall the join.
1550 /// **Synchronous**, unlike the per-tick hand-offs. It used to queue and
1551 /// return `Ok(())` with nothing committed, so the only way to learn that
1552 /// the final transaction had failed was `Writer::join`, which is easy to
1553 /// omit because `Drop` looks like it handles things — and `Drop` cannot
1554 /// return an error, so it turns the failure into a log line. A caller that
1555 /// skipped the join got a silent downgrade from "finished archive" to
1556 /// "recovery artifact".
1557 ///
1558 /// A barrier costs nothing here: this is the last thing a source does.
1559 pub fn finalize(self, clock_offset: (i64, i64)) -> Result<()> {
1560 self.finalize_with(Some(clock_offset))
1561 }
1562
1563 /// [`finalize`](Self::finalize) with no final clock observation, for a
1564 /// replication subscriber whose publisher sent none.
1565 pub(crate) fn finalize_without_offset(self) -> Result<()> {
1566 self.finalize_with(None)
1567 }
1568
1569 fn finalize_with(mut self, clock_offset: Option<(i64, i64)>) -> Result<()> {
1570 self.send(Msg::Finalize {
1571 source_id: self.source_id,
1572 clock_offset,
1573 })?;
1574 // The handle still holds its sender until this returns, so the writer
1575 // cannot exit on the last-handle rule before answering.
1576 self.sync()
1577 }
1578
1579 /// Report a writer that has already failed, on a hand-off that sends
1580 /// nothing. Without it, writer health would only be polled when there is
1581 /// something to write, and a source whose writer died would go on
1582 /// reporting success for every empty tick in between.
1583 fn check_alive(&mut self) -> Result<()> {
1584 // The shared error slot is the only signal available here: the thread
1585 // belongs to the archive, so this cannot ask whether it has finished,
1586 // and it deliberately does not send — a probe message would be a write
1587 // on a path whose whole point is that it has nothing to write. A
1588 // writer that exited *cleanly* while this handle is live is therefore
1589 // invisible here, which cannot happen today because the only clean
1590 // exit is `Shutdown`, sent last.
1591 match self.err.lock() {
1592 Ok(guard) if guard.is_some() => Err(Error::Writer(guard.clone().expect("is_some"))),
1593 _ => Ok(()),
1594 }
1595 }
1596
1597 fn send(&mut self, msg: Msg) -> Result<()> {
1598 if self.tx.send(msg).is_ok() {
1599 return Ok(());
1600 }
1601 // The receiver is gone, so the writer has exited (it exits its receive
1602 // loop on the first error). The thread stored its error on the way out
1603 // — see `ErrorSlot` — so report that rather than logging per-tick
1604 // against a broken source.
1605 Err(take_writer_error(&self.err))
1606 }
1607}
1608
1609/// Read the writer thread's stored failure, or a generic one if it exited
1610/// without storing one (a clean exit that a handle nonetheless outlived).
1611fn take_writer_error(slot: &ErrorSlot) -> Error {
1612 match slot.lock().ok().and_then(|guard| guard.clone()) {
1613 Some(e) => Error::Writer(e),
1614 None => Error::WriterGone,
1615 }
1616}
1617
1618/// Backoff between attempts at a container operation that failed with a
1619/// condition that can clear on its own ([`Error::is_retryable`]): another
1620/// connection's lock, a full disk, an interrupted call. Three attempts over
1621/// ~310 ms, on the writer thread — which backpressures the append loop
1622/// through the bound-1 channel for that long, a bounded cost against losing
1623/// the tick.
1624const RETRY_BACKOFF: [Duration; 3] = [
1625 Duration::from_millis(10),
1626 Duration::from_millis(50),
1627 Duration::from_millis(250),
1628];
1629
1630/// How many consecutive ticks the writer may drop before it stops. A lock or
1631/// a full disk that clears within a few seconds costs those ticks and nothing
1632/// else; one that does not clear is a failure the caller must hear about
1633/// rather than an archive that holds nothing without reporting it. A writer that swallows
1634/// errors to stay up is worse than one that stops.
1635const MAX_CONSECUTIVE_DROPPED_TICKS: u32 = 30;
1636
1637/// Run `op`, retrying on a retryable failure per [`RETRY_BACKOFF`]. Any other
1638/// failure — and a retryable one that outlasts the schedule — is returned as
1639/// is, for the caller to classify.
1640fn with_retries<T>(what: &str, mut op: impl FnMut() -> Result<T>) -> Result<T> {
1641 let mut attempt = 0usize;
1642 loop {
1643 match op() {
1644 Ok(v) => return Ok(v),
1645 Err(e) if e.is_retryable() && attempt < RETRY_BACKOFF.len() => {
1646 warn!(
1647 "{what} failed ({e}); retrying in {:?}",
1648 RETRY_BACKOFF[attempt]
1649 );
1650 std::thread::sleep(RETRY_BACKOFF[attempt]);
1651 attempt += 1;
1652 }
1653 Err(e) => return Err(e),
1654 }
1655 }
1656}
1657
1658/// What the writer tracks to decide between "warn and carry on" and "stop".
1659#[derive(Default)]
1660struct WriterHealth {
1661 consecutive_dropped: u32,
1662 /// Sources already warned about for a colliding tick, so a producer that
1663 /// repeats a timestamp every tick does not log every tick.
1664 warned_collisions: BTreeSet<i64>,
1665 /// Likewise for a resumed source whose rows fall at or before its floor.
1666 warned_floors: BTreeSet<i64>,
1667 /// Streams already warned about for an out-of-order append, so a
1668 /// producer that is late every tick logs once rather than every tick.
1669 warned_shadowed: BTreeSet<(i64, String)>,
1670 /// Likewise for caller rows below their name's floor.
1671 warned_caller_rows: BTreeSet<(i64, String)>,
1672}
1673
1674/// The floor a caller-row name's next rows must clear: a row is admitted at
1675/// `ts > floor`, or at `ts == floor` while the name still holds rows there.
1676#[derive(Clone, Copy)]
1677struct CallerFloor {
1678 floor: Option<i64>,
1679 /// Whether rows at exactly `floor` are admitted: the name holds rows at
1680 /// its newest `ts`. Not when retention removed them or a copy left them
1681 /// out, and `floor` is their `ts` from `bounds`.
1682 at_floor: bool,
1683}
1684
1685impl CallerFloor {
1686 fn read(db: &ArchiveMut, source_id: i64, name: &str) -> Result<Self> {
1687 let (held, bound) = db.caller_row_floor(source_id, name)?;
1688 Ok(match (held, bound) {
1689 (Some(h), Some(b)) if b > h => CallerFloor {
1690 floor: Some(b),
1691 at_floor: false,
1692 },
1693 (Some(h), _) => CallerFloor {
1694 floor: Some(h),
1695 at_floor: true,
1696 },
1697 (None, b) => CallerFloor {
1698 floor: b,
1699 at_floor: false,
1700 },
1701 })
1702 }
1703
1704 fn admits(&self, ts: i64) -> bool {
1705 match self.floor {
1706 None => true,
1707 Some(f) => ts > f || (self.at_floor && ts == f),
1708 }
1709 }
1710
1711 /// The floor after rows up to `newest` were committed.
1712 fn after(&self, newest: i64) -> Self {
1713 CallerFloor {
1714 floor: Some(self.floor.map_or(newest, |f| f.max(newest))),
1715 at_floor: true,
1716 }
1717 }
1718}
1719
1720impl WriterHealth {
1721 fn committed(&mut self) {
1722 self.consecutive_dropped = 0;
1723 }
1724
1725 /// Count an append dropped as out of order. `bound` is the stream's
1726 /// newest row before the tick, or `None` for a second row at one
1727 /// timestamp within the tick. Logged once per stream.
1728 fn count_shadowed(
1729 &mut self,
1730 shadowed: &ShadowCounts,
1731 source_id: i64,
1732 stream: &str,
1733 ts: i64,
1734 bound: Option<i64>,
1735 ) {
1736 if let Ok(mut counts) = shadowed.lock() {
1737 counts.entry(source_id).or_default().rows += 1;
1738 }
1739 if self.warned_shadowed.insert((source_id, stream.to_string())) {
1740 let why = match bound {
1741 Some(n) => format!("at or below the newest row the stream already holds ({n})"),
1742 None => "a second row at that timestamp in one tick".to_string(),
1743 };
1744 warn!(
1745 "source {source_id}, stream {stream}: dropped an append at {ts}, {why}. Append \
1746 in order per stream; later drops on this stream are counted, not logged"
1747 );
1748 }
1749 }
1750
1751 /// Count caller rows dropped for arriving below their name's floor.
1752 /// Logged once per name.
1753 fn count_late_caller_rows(
1754 &mut self,
1755 shadowed: &ShadowCounts,
1756 source_id: i64,
1757 name: &str,
1758 n: u64,
1759 ) {
1760 if let Ok(mut counts) = shadowed.lock() {
1761 counts.entry(source_id).or_default().caller_rows += n;
1762 }
1763 if self
1764 .warned_caller_rows
1765 .insert((source_id, name.to_string()))
1766 {
1767 warn!(
1768 "source {source_id}, caller rows {name}: dropped {n} row(s) below the newest \
1769 row the name has held. Append caller rows in ts order per name; later \
1770 drops are counted, not logged"
1771 );
1772 }
1773 }
1774
1775 /// A tick was dropped after retries. `Err` once that has happened
1776 /// [`MAX_CONSECUTIVE_DROPPED_TICKS`] times in a row.
1777 fn dropped(&mut self, e: Error) -> Result<()> {
1778 self.consecutive_dropped += 1;
1779 warn!(
1780 "a tick was dropped after retries ({e}); {} consecutive",
1781 self.consecutive_dropped
1782 );
1783 if self.consecutive_dropped >= MAX_CONSECUTIVE_DROPPED_TICKS {
1784 return Err(Error::Message(format!(
1785 "the archive writer dropped {} consecutive ticks; last error: {e}",
1786 self.consecutive_dropped
1787 )));
1788 }
1789 Ok(())
1790 }
1791}
1792
1793/// Commit one tick's rows for every source in the archive.
1794///
1795/// The whole tick is one transaction on the happy path (one fsync). When that
1796/// fails on a constraint — a source repeating a `(stream, ts)` it already
1797/// committed, which the `wal` primary key refuses — the failure is one
1798/// source's, so the tick is re-committed per source and only the colliding
1799/// source loses its rows. Before this, the batched commit meant one source's
1800/// bad tick failed every source in the archive, permanently, and told the
1801/// culprit `Ok`.
1802#[allow(clippy::too_many_arguments)]
1803fn commit_tick(
1804 db: &mut ArchiveMut,
1805 ticks: &[(i64, Vec<WalRow>)],
1806 floors: &BTreeMap<i64, i64>,
1807 newest: &mut BTreeMap<i64, BTreeMap<String, i64>>,
1808 shadowed: &ShadowCounts,
1809 replicas: &BTreeSet<i64>,
1810 health: &mut WriterHealth,
1811) -> Result<()> {
1812 // A replicated copy's rows are all or nothing per source and tick. A row
1813 // the checks below would drop means the copy and its publisher disagree,
1814 // so the source's whole entry is dropped and the source poisoned: a later
1815 // row committed past the hole would put the copy's newest row, and so its
1816 // resume request, above rows it never received.
1817 let screened: Vec<(i64, Vec<WalRow>)>;
1818 let ticks: &[(i64, Vec<WalRow>)] = if ticks.iter().any(|(id, _)| replicas.contains(id)) {
1819 let mut keep = Vec::with_capacity(ticks.len());
1820 for (source_id, rows) in ticks {
1821 if replicas.contains(source_id) {
1822 if is_poisoned(shadowed, *source_id) {
1823 continue;
1824 }
1825 let bound = newest.get(source_id);
1826 let mut seen = BTreeSet::new();
1827 let refused = rows.iter().any(|r| {
1828 bound
1829 .and_then(|b| b.get(&r.stream))
1830 .is_some_and(|n| r.ts <= *n)
1831 || !seen.insert((r.stream.as_str(), r.ts))
1832 });
1833 if refused {
1834 poison(shadowed, *source_id);
1835 warn!(
1836 "source {source_id}: a replicated copy's tick held a row at or below \
1837 its stream's newest; the tick was dropped and the source takes no \
1838 more writes until it is resumed"
1839 );
1840 continue;
1841 }
1842 }
1843 keep.push((*source_id, rows.clone()));
1844 }
1845 screened = keep;
1846 &screened
1847 } else {
1848 ticks
1849 };
1850 let poison_replicas = |ticks: &[(i64, Vec<WalRow>)]| {
1851 for (source_id, _) in ticks {
1852 if replicas.contains(source_id) {
1853 poison(shadowed, *source_id);
1854 }
1855 }
1856 };
1857 // The writer's half of the resume floor (the handle checks `wal`; this
1858 // covers `wal_tick`, which has no handle to ask): a resumed source's rows
1859 // at or before the newest row it has held are that source's problem,
1860 // dropped and warned once, like a collision.
1861 let mut kept: Vec<(i64, Vec<WalRow>)> = Vec::with_capacity(ticks.len());
1862 for (source_id, rows) in ticks {
1863 match floors.get(source_id) {
1864 Some(floor) if rows.iter().any(|r| r.ts <= *floor) => {
1865 if health.warned_floors.insert(*source_id) {
1866 let ts = rows.iter().map(|r| r.ts).min().unwrap_or(*floor);
1867 warn!(
1868 "{}; the tick was dropped, and later ones for this source are \
1869 not logged",
1870 Error::TimelineBackwards {
1871 source_id: *source_id,
1872 ts,
1873 floor: *floor
1874 }
1875 );
1876 }
1877 }
1878 _ => kept.push((*source_id, rows.clone())),
1879 }
1880 }
1881 let ticks: &[(i64, Vec<WalRow>)] = if kept.len() == ticks.len() {
1882 ticks
1883 } else {
1884 &kept
1885 };
1886
1887 // OUT OF ORDER. A row at or below its stream's newest row, sealed or
1888 // live, is dropped rather than stored, and said out loud.
1889 //
1890 // At or below the newest SEALED row it cannot be read: `live_wal`'s
1891 // watermark is what keeps the seal seam free of duplicates, so it shadows
1892 // this row exactly as it shadows one already sealed. At or below the
1893 // newest LIVE row it can be read, but a reader that tails the stream by
1894 // timestamp has already passed it: a replication publisher ships the rows
1895 // after the newest it sent, and never this one. At the same timestamp it
1896 // would collide with the row there, which costs the whole tick. See
1897 // `docs/journal/2026-09-11-out-of-order-appends.md`.
1898 //
1899 // The bound is the newest row before this tick, so a stream's rows may
1900 // arrive in any order within one tick; a second row at one
1901 // `(source, stream, ts)` in the tick, in the same entry or another entry
1902 // for the same source, is the only one of them dropped. Dropped per ROW,
1903 // not per tick, unlike the floor above: the floor says a whole session is
1904 // misaligned, while one late row among a tick's good ones is that row's
1905 // problem alone.
1906 //
1907 // The common tick costs a map lookup and a set insertion per row; the
1908 // rebuild below runs only once something is actually dropped.
1909 let bound = |source_id: i64, stream: &str| {
1910 newest
1911 .get(&source_id)
1912 .and_then(|streams| streams.get(stream))
1913 .copied()
1914 };
1915 let late = |source_id: i64, r: &WalRow| bound(source_id, &r.stream).is_some_and(|n| r.ts <= n);
1916 let repeats_within = || {
1917 let mut seen = std::collections::BTreeSet::new();
1918 ticks.iter().any(|(source_id, rows)| {
1919 rows.iter()
1920 .any(|r| !seen.insert((*source_id, r.stream.as_str(), r.ts)))
1921 })
1922 };
1923 let rebuilt: Vec<(i64, Vec<WalRow>)>;
1924 let ticks: &[(i64, Vec<WalRow>)] = if ticks
1925 .iter()
1926 .any(|(source_id, rows)| rows.iter().any(|r| late(*source_id, r)))
1927 || repeats_within()
1928 {
1929 let mut out: Vec<(i64, Vec<WalRow>)> = Vec::with_capacity(ticks.len());
1930 let mut seen = std::collections::BTreeSet::new();
1931 for (source_id, rows) in ticks {
1932 let mut keep: Vec<WalRow> = Vec::with_capacity(rows.len());
1933 for r in rows {
1934 let before = bound(*source_id, &r.stream);
1935 if before.is_some_and(|n| r.ts <= n) {
1936 health.count_shadowed(shadowed, *source_id, &r.stream, r.ts, before);
1937 } else if !seen.insert((*source_id, r.stream.clone(), r.ts)) {
1938 health.count_shadowed(shadowed, *source_id, &r.stream, r.ts, None);
1939 } else {
1940 keep.push(r.clone());
1941 }
1942 }
1943 if !keep.is_empty() {
1944 out.push((*source_id, keep));
1945 }
1946 }
1947 rebuilt = out;
1948 &rebuilt
1949 } else {
1950 ticks
1951 };
1952
1953 // Raise the bound for the rows of `sources` that committed.
1954 let advance = |newest: &mut BTreeMap<i64, BTreeMap<String, i64>>,
1955 committed: &[(i64, Vec<WalRow>)]| {
1956 for (source_id, rows) in committed {
1957 let streams = newest.entry(*source_id).or_default();
1958 for r in rows {
1959 let n = streams.entry(r.stream.clone()).or_insert(r.ts);
1960 *n = (*n).max(r.ts);
1961 }
1962 }
1963 };
1964
1965 if ticks.is_empty() {
1966 return Ok(());
1967 }
1968 match with_retries("committing a tick", || db.insert_wal_rows_batch(ticks)) {
1969 Ok(()) => {
1970 advance(newest, ticks);
1971 health.committed();
1972 Ok(())
1973 }
1974 Err(e) if e.is_constraint() => {
1975 let mut any = false;
1976 for (source_id, rows) in ticks {
1977 match with_retries("committing a source's tick", || {
1978 db.insert_wal_rows(*source_id, rows)
1979 }) {
1980 Ok(()) => {
1981 any = true;
1982 advance(newest, std::slice::from_ref(&(*source_id, rows.clone())));
1983 }
1984 Err(e) if e.is_constraint() => {
1985 if replicas.contains(source_id) {
1986 poison(shadowed, *source_id);
1987 }
1988 if health.warned_collisions.insert(*source_id) {
1989 warn!(
1990 "source {source_id}: a tick was dropped because its rows \
1991 collide with rows already committed ({e}); later collisions \
1992 for this source are not logged"
1993 );
1994 }
1995 }
1996 Err(e) if e.is_retryable() => {
1997 poison_replicas(std::slice::from_ref(&(*source_id, Vec::new())));
1998 health.dropped(e)?
1999 }
2000 Err(e) => return Err(e),
2001 }
2002 }
2003 if any {
2004 health.committed();
2005 }
2006 Ok(())
2007 }
2008 Err(e) if e.is_retryable() => {
2009 poison_replicas(ticks);
2010 health.dropped(e)
2011 }
2012 Err(e) => Err(e),
2013 }
2014}
2015
2016/// Re-read one source's newest-row bounds after `what` changed its rows. On
2017/// failure the old bounds stay, which drops rows the file would take rather
2018/// than accept rows below one it holds.
2019fn refresh_newest(
2020 db: &ArchiveMut,
2021 newest: &mut BTreeMap<i64, BTreeMap<String, i64>>,
2022 source_id: i64,
2023 what: &str,
2024) {
2025 match db.newest_rows_of(source_id) {
2026 Ok(fresh) => {
2027 newest.insert(source_id, fresh);
2028 }
2029 Err(e) => warn!(
2030 "re-reading source {source_id}'s newest rows after {what} failed ({e}); its \
2031 streams keep their previous bounds until the next refresh or a restart"
2032 ),
2033 }
2034}
2035
2036/// Append a writer session to a source's `WRITER_SESSIONS` metadata — and,
2037/// for a resume, a `writer_session` event under `EVENTS` at the new anchor.
2038fn record_session(
2039 db: &mut ArchiveMut,
2040 source_id: i64,
2041 clock_anchor_wall_ns: i64,
2042 resumed_after_ts: Option<Option<i64>>,
2043) -> Result<()> {
2044 use crate::keys;
2045 let session = db.mint_uuid()?;
2046 let metadata = db.source_metadata(source_id)?;
2047 let mut sessions: Vec<serde_json::Value> = metadata
2048 .get(keys::WRITER_SESSIONS)
2049 .and_then(|v| serde_json::from_str(v).ok())
2050 .unwrap_or_default();
2051 // Which build of this crate appended, for tracing a defect found later
2052 // to the sessions that had it. Provenance, not a gate: readability is
2053 // decided by the schema version in the header alone.
2054 let mut entry = serde_json::json!({
2055 "session": session,
2056 "clock_anchor_wall_ns": clock_anchor_wall_ns,
2057 "dendro": env!("CARGO_PKG_VERSION"),
2058 });
2059 let mut patch = BTreeMap::new();
2060 if let Some(after) = resumed_after_ts {
2061 entry["resumed_after_ts"] = serde_json::json!(after);
2062 // Appended to whatever events the caller already wrote, never a
2063 // replacement: the array is shared with them.
2064 let mut events: serde_json::Value = metadata
2065 .get(keys::EVENTS)
2066 .and_then(|v| serde_json::from_str(v).ok())
2067 .unwrap_or_else(|| serde_json::json!({ "events": [] }));
2068 if !events["events"].is_array() {
2069 events["events"] = serde_json::json!([]);
2070 }
2071 events["events"]
2072 .as_array_mut()
2073 .expect("just ensured")
2074 .push(serde_json::json!({
2075 "timestamp": clock_anchor_wall_ns,
2076 "description": "source resumed by a new writer session",
2077 "kind": "writer_session",
2078 "details": match after {
2079 Some(ts) => format!("previous session's last row at {ts}"),
2080 None => "previous session left no rows".to_string(),
2081 },
2082 "id": format!("writer_session:{session}"),
2083 }));
2084 patch.insert(keys::EVENTS.to_string(), events.to_string());
2085 }
2086 sessions.push(entry);
2087 patch.insert(
2088 keys::WRITER_SESSIONS.to_string(),
2089 serde_json::Value::Array(sessions).to_string(),
2090 );
2091 db.patch_source_metadata(source_id, &patch)
2092}
2093
2094/// The writer-thread half of [`Writer::resume_source`].
2095fn resume_source(
2096 db: &mut ArchiveMut,
2097 source_id: i64,
2098 clock_anchor_wall_ns: i64,
2099 encoder: &(dyn SegmentEncoder + Send),
2100) -> Result<Resumed> {
2101 let Some(src) = db.read_sources()?.into_iter().find(|s| s.id == source_id) else {
2102 return Err(Error::Message(format!(
2103 "no source with id {source_id} to resume"
2104 )));
2105 };
2106 // A resuming writer must encode the way the previous one did, or the
2107 // stream's later segments will not decode like its earlier ones.
2108 crate::segment::check_encoder(source_id, &src.meta.metadata, encoder)?;
2109 let (_, last_ts) = db.source_time_span(source_id)?;
2110 // A stream's timestamps strictly increase across deletes, so the floor
2111 // is the newest row the source has held, not only what it holds now.
2112 let floor_ts = last_ts.max(db.newest_bound(source_id)?);
2113 if let Some(floor) = floor_ts {
2114 if clock_anchor_wall_ns <= floor {
2115 return Err(Error::TimelineBackwards {
2116 source_id,
2117 ts: clock_anchor_wall_ns,
2118 floor,
2119 });
2120 }
2121 }
2122 db.transaction(|tx| tx.mark_incomplete(source_id))?;
2123 record_session(db, source_id, clock_anchor_wall_ns, Some(last_ts))?;
2124 Ok(Resumed {
2125 labels: src.meta.labels,
2126 last_ts: floor_ts,
2127 })
2128}
2129
2130/// An encoded segment waiting to be inserted.
2131struct Encoded {
2132 stream: String,
2133 seq: u64,
2134 meta: SegmentMeta,
2135 bytes: Vec<u8>,
2136 caller_index: Option<Vec<u8>>,
2137}
2138
2139/// One segment built elsewhere, on its way to `adopt_segment`. `Encoded`
2140/// without the `seq`: the sender does not know the stream's numbering, and the
2141/// writer thread is the only thing that does.
2142pub(crate) struct Adopted {
2143 stream: String,
2144 meta: SegmentMeta,
2145 bytes: Vec<u8>,
2146 caller_index: Option<Vec<u8>>,
2147}
2148
2149/// One `SegmentAfter` frame's segment, as the subscriber hands it to
2150/// [`SourceWriter::adopt_segments_after`].
2151pub(crate) struct AfterPart {
2152 pub(crate) after: i64,
2153 pub(crate) meta: SegmentMeta,
2154 pub(crate) bytes: Vec<u8>,
2155 pub(crate) caller_index: Option<Vec<u8>>,
2156}
2157
2158/// An [`AfterPart`] on its way to the writer thread.
2159pub(crate) struct AdoptedAfter {
2160 after: i64,
2161 segment: Adopted,
2162}
2163
2164/// The writer thread body. Every fallible operation returns `Err`; the loop
2165/// exits on the first error so the failure surfaces on the next hand-off
2166/// instead of accumulating against a broken source.
2167fn writer_thread(
2168 rx: Receiver<Msg>,
2169 mut db: ArchiveMut,
2170 err_slot: ErrorSlot,
2171 shadowed: ShadowCounts,
2172 cadence: Cadence,
2173 encoder: Box<dyn SegmentEncoder + Send>,
2174) -> Result<()> {
2175 // `rx` is BORROWED by the loop, not moved into it, so the receiver outlives
2176 // the error store below. That ordering is the whole point: a handle's send
2177 // fails the instant the receiver drops, and if the slot were still empty at
2178 // that moment the handle would report a generic "writer exited" instead of
2179 // the writer's own error. Holding `rx` here means the channel is still open
2180 // while the slot is written, so any send that fails afterwards finds it.
2181 match writer_loop(&rx, &mut db, &shadowed, cadence, encoder.as_ref()) {
2182 Ok(()) => Ok(()),
2183 Err(e) => {
2184 // Shared, not stringified: every handle reports this same failure,
2185 // and flattening it to text here threw away the variant a caller
2186 // wants to branch on. `Error` is not `Clone` (nor is
2187 // `rusqlite::Error`), so the slot holds an `Arc` and the thread's
2188 // own return borrows the same one.
2189 let shared = Arc::new(e);
2190 *err_slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(&shared));
2191 Err(Error::Writer(shared))
2192 }
2193 }
2194}
2195
2196/// How stale a plain copy of a live archive is allowed to be.
2197///
2198/// SQLite commits into a `<file>-wal` sidecar and folds it into the archive at
2199/// a checkpoint, so a copy of the archive alone — which is what anyone who
2200/// `cp`s one, or uploads one to a browser, ends up with — is a consistent view
2201/// as of the last checkpoint and nothing after it. That copy is not corrupt; it
2202/// ends early, and nothing about it says so.
2203///
2204/// [`crate::archive`]'s autocheckpoint bounds how many bytes can accumulate
2205/// (4 MiB). It cannot bound how much TIME they represent: a busy source
2206/// crosses 4 MiB in seconds, a quiet one in hours, and the quiet one is the
2207/// case where a copy is silently useless. Measured before this existed: 123
2208/// ticks — about two minutes at a 1s interval — missing from a plain copy of a
2209/// 2000-tick source.
2210///
2211/// 10s is chosen to be short against the window anyone reasons about (an
2212/// incident, a benchmark run) and long against the work: a passive checkpoint
2213/// of one interval's frames is a few tens of KiB at a typical cadence,
2214/// and it runs on the writer thread rather than the append loop. It does not
2215/// make a copy exact — [`Archive::vacuum_into`] does that — it makes what a
2216/// copy loses bounded and small.
2217pub const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(10);
2218
2219/// How often a writer bumps each open source's heartbeat (FORMAT.md §3.1),
2220/// whether or not it has rows to commit. A reader decides a writer stopped
2221/// after [`STOPPED_AFTER_INTERVALS`](crate::archive::STOPPED_AFTER_INTERVALS)
2222/// of these without a change. One small transaction per interval.
2223pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
2224
2225/// The writer thread's timers.
2226#[derive(Clone, Copy, Debug)]
2227struct Cadence {
2228 checkpoint_every: Duration,
2229 heartbeat_every: Duration,
2230}
2231
2232impl Cadence {
2233 fn checkpointing_every(checkpoint_every: Duration) -> Self {
2234 Self {
2235 checkpoint_every,
2236 heartbeat_every: HEARTBEAT_INTERVAL,
2237 }
2238 }
2239}
2240
2241fn writer_loop(
2242 rx: &Receiver<Msg>,
2243 db: &mut ArchiveMut,
2244 shadowed: &ShadowCounts,
2245 cadence: Cadence,
2246 encoder: &(dyn SegmentEncoder + Send),
2247) -> Result<()> {
2248 let Cadence {
2249 checkpoint_every,
2250 heartbeat_every,
2251 } = cadence;
2252 // Sources added or resumed and not yet finalized, each with the liveness
2253 // tokens of its handles: the ones whose heartbeat this writer bumps,
2254 // while any of their handles lives. A list, because `resume_source` on
2255 // a source whose earlier handle still lives gives it a second one.
2256 let mut beating: BTreeMap<i64, Vec<Weak<()>>> = BTreeMap::new();
2257 let mut last_beat = Instant::now();
2258 // Next segment sequence number, per (source, stream). Keyed by both
2259 // because `seq` is scoped to a source's stream in the `segments` table:
2260 // two sources of the same host have the same stream names and each
2261 // needs its own sequence.
2262 //
2263 // Seeded from the file: empty on a freshly created archive, and on a
2264 // reopened one each stream continues where the previous writer stopped,
2265 // which is what keeps a resumed stream's `seq` from colliding with its
2266 // own past.
2267 let mut next_seq: BTreeMap<(i64, String), u64> = db.next_seqs()?;
2268 // Per resumed source, the newest row its previous session left: rows at
2269 // or before it are refused. See `resume_source`.
2270 let mut floors: BTreeMap<i64, i64> = BTreeMap::new();
2271 // Every stream's newest SEALED row — the watermark a reader compares
2272 // against. Advanced by `seal_batch`, re-read for a source after a
2273 // retention pass (which can evict a stream to nothing), and held here
2274 // rather than queried per append because an append is the hot path; see
2275 // `commit_tick`.
2276 //
2277 // Seeded from the catalog, which on a reopened archive is defense in
2278 // depth rather than the thing doing the work: a resumed source also
2279 // carries a FLOOR (the newest row anywhere in it), the floor is at or
2280 // above every one of its streams' watermarks, and the handle refuses
2281 // against the floor synchronously. The seeding is what keeps this map
2282 // true of the archive regardless, so the check here does not quietly
2283 // depend on a resume having happened.
2284 let mut watermarks: BTreeMap<i64, BTreeMap<String, i64>> = db.sealed_watermarks()?;
2285 // Every stream's newest row, sealed or live: the bound `commit_tick`
2286 // drops a late row against. Seeded from the file, advanced by each
2287 // commit, and re-read for a source after anything that deletes its rows
2288 // (retention, a discard); an adopted segment raises it in place.
2289 let mut newest: BTreeMap<i64, BTreeMap<String, i64>> = db.newest_rows()?;
2290 // Per `(source, caller-row name)`, the floor its next rows must clear.
2291 // Filled on a name's first rows and dropped for a source after
2292 // retention, which can remove a name's newest rows.
2293 let mut caller_floors: BTreeMap<(i64, String), CallerFloor> = BTreeMap::new();
2294 // Per source, the streams whose last seal was deferred, with the
2295 // smallest `max_rows` asked for them. `Evict` retries their seal first;
2296 // a stream still listed after that keeps its live rows through the
2297 // pass, as any stream does. A seal that commits takes its streams off
2298 // the list.
2299 let mut deferred: BTreeMap<i64, BTreeMap<String, usize>> = BTreeMap::new();
2300 // How many sources were opened, and how many closed cleanly. Reclaim at
2301 // exit only when they match: an unclean exit is the recovery artifact and
2302 // must not pay for a vacuum on the way down.
2303 let mut added: usize = 0;
2304 let mut finalized: usize = 0;
2305 // When the sidecar was last folded into the archive. Advanced on every
2306 // checkpoint, including ones taken while idle — the guarantee is about
2307 // elapsed time, not about arriving messages.
2308 let mut last_checkpoint = Instant::now();
2309 let mut health = WriterHealth::default();
2310 // Sources that are replicated copies (`Msg::Replicate`).
2311 let mut replicas: BTreeSet<i64> = BTreeSet::new();
2312
2313 loop {
2314 // `recv_timeout`, not `recv`: a writer with nothing to do still has to
2315 // wake and checkpoint. A source that has gone quiet is exactly when
2316 // someone copies it.
2317 let waited = rx.recv_timeout(
2318 checkpoint_every
2319 .saturating_sub(last_checkpoint.elapsed())
2320 .min(heartbeat_every.saturating_sub(last_beat.elapsed())),
2321 );
2322 if last_beat.elapsed() >= heartbeat_every {
2323 // Best-effort, like the checkpoint: a missed beat is one a reader
2324 // tolerates (it waits several intervals), and failing the writer
2325 // over one would cost the recording.
2326 beating.retain(|_, handles| {
2327 handles.retain(|alive| alive.strong_count() > 0);
2328 !handles.is_empty()
2329 });
2330 if !beating.is_empty() {
2331 let ids: Vec<i64> = beating.keys().copied().collect();
2332 if let Err(e) = db.transaction(|tx| tx.beat(&ids)) {
2333 warn!("failed to bump the heartbeat: {e}");
2334 }
2335 }
2336 last_beat = Instant::now();
2337 }
2338 if last_checkpoint.elapsed() >= checkpoint_every {
2339 // Best-effort: a checkpoint that cannot proceed (a reader is
2340 // holding an older snapshot) is not an error, and failing the
2341 // writer over one would trade every subsequent tick for a copy's
2342 // freshness.
2343 if let Err(e) = db.checkpoint_passive() {
2344 warn!("failed to checkpoint the WAL: {e}");
2345 }
2346 last_checkpoint = Instant::now();
2347 }
2348 let received = match waited {
2349 Ok(msg) => Ok(msg),
2350 // Nothing arrived within the checkpoint window: go round again.
2351 Err(RecvTimeoutError::Timeout) => continue,
2352 // Every handle is gone. Falls into the same arm the blocking
2353 // `recv` used to reach.
2354 Err(RecvTimeoutError::Disconnected) => Err(()),
2355 };
2356 match received {
2357 // Nothing to do but answer: arriving here at all means every
2358 // message queued before it has already been handled.
2359 Ok(Msg::Sync(reply)) => {
2360 let _ = reply.send(());
2361 }
2362 Ok(Msg::AddSource {
2363 seed,
2364 uuid,
2365 alive,
2366 reply,
2367 }) => {
2368 let inserted = db
2369 .insert_source_with_uuid(&seed, uuid.as_deref())
2370 .and_then(|id| {
2371 record_session(db, id, seed.clock_anchor_wall_ns, None)?;
2372 start_heartbeat(db, id, heartbeat_every);
2373 // The encoder that will write this source's rows, so a
2374 // reader can tell whether its own would decode them.
2375 if let Some(version) = encoder.version() {
2376 let mut patch = BTreeMap::new();
2377 patch.insert(crate::keys::ENCODER.to_string(), version.to_string());
2378 db.patch_source_metadata(id, &patch)?;
2379 }
2380 Ok(id)
2381 });
2382 // A failed insert is reported to the caller and does NOT kill
2383 // the writer: an archive's other sources are still valid,
2384 // and the caller decides whether to give up.
2385 if let Ok(id) = &inserted {
2386 added += 1;
2387 beating.entry(*id).or_default().push(alive);
2388 }
2389 let _ = reply.send(inserted);
2390 }
2391 Ok(Msg::ResumeSource {
2392 source_id,
2393 clock_anchor_wall_ns,
2394 alive,
2395 reply,
2396 }) => {
2397 let resumed = resume_source(db, source_id, clock_anchor_wall_ns, encoder);
2398 if resumed.is_ok() {
2399 start_heartbeat(db, source_id, heartbeat_every);
2400 }
2401 if let Ok(Resumed {
2402 last_ts: Some(floor),
2403 ..
2404 }) = &resumed
2405 {
2406 floors.insert(source_id, *floor);
2407 }
2408 if resumed.is_ok() {
2409 added += 1;
2410 beating.entry(source_id).or_default().push(alive);
2411 }
2412 let _ = reply.send(resumed);
2413 }
2414 Ok(Msg::Wal { ticks }) => commit_tick(
2415 db,
2416 &ticks,
2417 &floors,
2418 &mut newest,
2419 shadowed,
2420 &replicas,
2421 &mut health,
2422 )?,
2423 #[cfg(any(test, feature = "test-support"))]
2424 Ok(Msg::Commits(reply)) => {
2425 let _ = reply.send(db.commits());
2426 }
2427 Ok(Msg::Seal {
2428 source_id,
2429 batch,
2430 max_rows,
2431 }) => {
2432 // A seal that cannot commit is DEFERRED, not lost: its rows
2433 // are still live in the WAL, `seal_batch` re-reads them on
2434 // every attempt, and if the schedule runs out they stay live
2435 // and go out with the next batch that seals those streams,
2436 // or with the retry the next `Evict` makes first.
2437 // Nothing has to be undone — `seq` is advanced only by a
2438 // commit. An encoder failure is not retried: it will recur.
2439 match with_retries("sealing a segment batch", || {
2440 seal_batch(
2441 db,
2442 source_id,
2443 &mut next_seq,
2444 &mut watermarks,
2445 batch.clone(),
2446 max_rows,
2447 encoder,
2448 )
2449 }) {
2450 Ok(()) => {
2451 if let Some(pending) = deferred.get_mut(&source_id) {
2452 for stream in &batch {
2453 pending.remove(stream);
2454 }
2455 }
2456 }
2457 Err(e) if e.is_retryable() => {
2458 warn!(
2459 "seal of {} stream(s) for source {source_id} deferred ({e}); their \
2460 rows stay in the WAL and seal with the next batch or \
2461 before the next retention pass",
2462 batch.len()
2463 );
2464 let pending = deferred.entry(source_id).or_default();
2465 for stream in batch {
2466 let cap = pending.entry(stream).or_insert(max_rows);
2467 *cap = (*cap).min(max_rows);
2468 }
2469 }
2470 Err(e) => return Err(e),
2471 }
2472 }
2473 Ok(Msg::AdoptSegment {
2474 source_id,
2475 segment,
2476 reply,
2477 }) => {
2478 // Retried like a seal, and for the same reason: a lock that
2479 // will clear must not cost the frame. Unlike a seal it cannot
2480 // be DEFERRED — there is no WAL row holding the data for a
2481 // later attempt, the bytes are in this message — so a failure
2482 // that outlasts the retries goes back to the sender, which is
2483 // applying a stream and can stop.
2484 let adopted = if replicas.contains(&source_id) && is_poisoned(shadowed, source_id) {
2485 Err(poisoned_error(source_id))
2486 } else {
2487 with_retries("adopting a segment", || {
2488 adopt_segment(db, source_id, &mut next_seq, &mut watermarks, &segment)
2489 })
2490 };
2491 // `adopt_segment` only inserts, and refuses a segment at or
2492 // below a live row, so the bound becomes the segment's end.
2493 if matches!(adopted, Ok(true)) {
2494 let n = newest
2495 .entry(source_id)
2496 .or_default()
2497 .entry(segment.stream.clone())
2498 .or_insert(segment.meta.last_ts);
2499 *n = (*n).max(segment.meta.last_ts);
2500 }
2501 let _ = reply.send(adopted);
2502 }
2503 Ok(Msg::Replicate {
2504 source_id,
2505 alive,
2506 reply,
2507 }) => {
2508 let labels = with_retries("opening a replicated source", || {
2509 let Some(src) = db.read_sources()?.into_iter().find(|s| s.id == source_id)
2510 else {
2511 return Err(Error::Message(format!(
2512 "no source with id {source_id} to replicate into"
2513 )));
2514 };
2515 Ok((src.meta.labels, db.held_newest_rows_of(source_id)?))
2516 });
2517 let labels = labels.map(|(labels, held)| {
2518 // The protocol sets this source's bounds from here on:
2519 // its own rows, not `bounds`, and no session floor.
2520 newest.insert(source_id, held);
2521 floors.remove(&source_id);
2522 caller_floors.retain(|(source, _), _| *source != source_id);
2523 replicas.insert(source_id);
2524 if let Some(alive) = alive {
2525 start_heartbeat(db, source_id, heartbeat_every);
2526 added += 1;
2527 beating.entry(source_id).or_default().push(alive);
2528 }
2529 labels
2530 });
2531 let _ = reply.send(labels);
2532 }
2533 Ok(Msg::SyncStream {
2534 source_id,
2535 stream,
2536 at,
2537 reply,
2538 }) => {
2539 let synced = if !replicas.contains(&source_id) {
2540 Err(Error::Message(format!(
2541 "source {source_id} is not a replicated copy, and only a copy is \
2542 synced"
2543 )))
2544 } else if is_poisoned(shadowed, source_id) {
2545 Err(poisoned_error(source_id))
2546 } else {
2547 sync_stream(
2548 db,
2549 source_id,
2550 &stream,
2551 at,
2552 &mut next_seq,
2553 &mut watermarks,
2554 encoder,
2555 )
2556 };
2557 match &synced {
2558 Ok(_) => {
2559 // Rows above `at` arrive again, so the bound is `at`.
2560 newest.entry(source_id).or_default().insert(stream, at);
2561 }
2562 Err(e) if e.is_retryable() => poison(shadowed, source_id),
2563 Err(_) => {}
2564 }
2565 let _ = reply.send(synced);
2566 }
2567 Ok(Msg::AdoptAfter {
2568 source_id,
2569 parts,
2570 reply,
2571 }) => {
2572 let adopted = if !replicas.contains(&source_id) {
2573 Err(Error::Message(format!(
2574 "source {source_id} is not a replicated copy, and only a copy adopts \
2575 a segment after a point"
2576 )))
2577 } else if is_poisoned(shadowed, source_id) {
2578 Err(poisoned_error(source_id))
2579 } else {
2580 with_retries("adopting a segment", || {
2581 adopt_segments_after(db, source_id, &mut next_seq, &mut watermarks, &parts)
2582 })
2583 };
2584 if adopted.is_ok() {
2585 for part in &parts {
2586 let n = newest
2587 .entry(source_id)
2588 .or_default()
2589 .entry(part.segment.stream.clone())
2590 .or_insert(part.segment.meta.last_ts);
2591 *n = (*n).max(part.segment.meta.last_ts);
2592 }
2593 }
2594 let _ = reply.send(adopted);
2595 }
2596 Ok(Msg::MarkIncomplete { source_id, reply }) => {
2597 let _ = reply.send(with_retries("reopening a source", || {
2598 db.transaction(|tx| tx.mark_incomplete(source_id))
2599 }));
2600 }
2601 Ok(Msg::Evict {
2602 source_id,
2603 cutoff_ts,
2604 streams,
2605 floor,
2606 reply,
2607 }) => {
2608 // A stream whose seal was deferred is sealed now, before
2609 // anything is cut, so the rows it seals can be evicted. One
2610 // still unsealed after a retryable failure stays deferred;
2611 // the pass evicts its segments and keeps its live rows, as
2612 // for any stream.
2613 let unsealed = retry_deferred_seals(
2614 db,
2615 source_id,
2616 &mut deferred,
2617 &mut next_seq,
2618 &mut watermarks,
2619 encoder,
2620 );
2621 if !unsealed.is_empty() {
2622 warn!(
2623 "retention on source {source_id} could not seal {} deferred stream(s) \
2624 first: {:?}; their live rows are kept and they are retried before \
2625 the next pass",
2626 unsealed.len(),
2627 unsealed
2628 );
2629 }
2630 let evicted = match streams {
2631 Some(keep) => match &floor {
2632 Some(floor) => db.evict_streams_before_with_floor(
2633 source_id, cutoff_ts, &*keep, &**floor,
2634 ),
2635 None => db.evict_streams_before(source_id, cutoff_ts, &*keep),
2636 },
2637 None => match &floor {
2638 Some(floor) => db.evict_before_with_floor(source_id, cutoff_ts, &**floor),
2639 None => db.evict_before(source_id, cutoff_ts),
2640 },
2641 };
2642 if let Ok(e) = &evicted {
2643 if e.kept_live_rows > 0 {
2644 warn!(
2645 "retention on source {source_id} kept {} row(s) before the cutoff \
2646 that no segment holds; they stay until a seal covers them or \
2647 `discard_live_rows` deletes them",
2648 e.kept_live_rows
2649 );
2650 }
2651 }
2652 let failed = evicted.is_err();
2653 let _ = reply.send(evicted);
2654 if failed {
2655 // The caller has the error; the writer stays up. Retention
2656 // failing is not a reason to lose the recording.
2657 continue;
2658 }
2659 // A stream whose segments were all evicted has no watermark
2660 // in the file, so its next rows are live whatever their
2661 // timestamp. Re-read this source's watermarks so the cache
2662 // agrees. On failure the old ones stay, which drops rows the
2663 // file would serve rather than accept rows it would not.
2664 match db.sealed_watermarks_of(source_id) {
2665 Ok(fresh) => {
2666 watermarks.insert(source_id, fresh);
2667 }
2668 Err(e) => warn!(
2669 "re-reading source {source_id}'s watermarks after retention failed \
2670 ({e}); a stream evicted to nothing still drops rows at or below its \
2671 old watermark until a later retention pass or a restart re-reads it"
2672 ),
2673 }
2674 refresh_newest(db, &mut newest, source_id, "retention");
2675 caller_floors.retain(|(source, _), _| *source != source_id);
2676 // Same rule for the reclaim that follows: the caller was just
2677 // told retention succeeded, and it did. Handing pages back is
2678 // an optimization; a failure here is the next pass's problem,
2679 // not the recording's.
2680 if let Err(e) = reclaim_if_fragmented(db) {
2681 warn!("reclaiming freed pages after retention failed ({e}); skipped");
2682 }
2683 }
2684 Ok(Msg::DiscardLive {
2685 source_id,
2686 streams,
2687 reply,
2688 }) => {
2689 // Never fatal, as a failed retention pass is not: the caller
2690 // has the error and the rows are still there.
2691 let discarded = with_retries("discarding live rows", || {
2692 db.discard_live_rows(source_id, &*streams)
2693 });
2694 // A deferred seal of a discarded stream would find no live
2695 // rows, and warn about it if the stream never sealed.
2696 if discarded.is_ok() {
2697 if let Some(pending) = deferred.get_mut(&source_id) {
2698 pending.retain(|stream, _| !streams(stream));
2699 }
2700 refresh_newest(db, &mut newest, source_id, "discarding live rows");
2701 }
2702 let _ = reply.send(discarded);
2703 }
2704 Ok(Msg::UpdateMetadata { source_id, patch }) => {
2705 // Never fatal: metadata is not the recording, and the caller
2706 // was told how to find out whether it landed.
2707 if let Err(e) = with_retries("updating source metadata", || {
2708 db.patch_source_metadata(source_id, &patch)
2709 }) {
2710 warn!(
2711 "metadata update for source {source_id} dropped ({e}); keys: {:?}",
2712 patch.keys().collect::<Vec<_>>()
2713 );
2714 }
2715 }
2716 Ok(Msg::SetIdentity {
2717 source_id,
2718 labels,
2719 metadata,
2720 }) => {
2721 // Never fatal, as `UpdateMetadata`.
2722 if let Err(e) = with_retries("replacing source identity", || {
2723 db.set_source_identity(source_id, &labels, &metadata)
2724 }) {
2725 warn!("identity update for source {source_id} dropped ({e})");
2726 }
2727 }
2728 Ok(Msg::PutDocument { put, reply }) => {
2729 // Never fatal: a document is not the recording, and the
2730 // caller is waiting for the answer.
2731 let DocumentPut {
2732 kind,
2733 name,
2734 schema,
2735 body,
2736 expected,
2737 } = *put;
2738 let written = with_retries("writing a document", || {
2739 db.transaction(|tx| match &expected {
2740 None => tx.put_document(&kind, &name, &schema, &body),
2741 Some(e) => {
2742 tx.put_document_if_current(&kind, &name, &schema, &body, e.as_deref())
2743 }
2744 })
2745 });
2746 let _ = reply.send(written);
2747 }
2748 Ok(Msg::DeleteDocument { kind, name, reply }) => {
2749 let deleted = with_retries("deleting a document", || {
2750 db.transaction(|tx| tx.delete_document(&kind, &name))
2751 });
2752 let _ = reply.send(deleted);
2753 }
2754 Ok(Msg::ClockOffset {
2755 source_id,
2756 ts,
2757 offset_ns,
2758 }) => {
2759 // Data, like the caller store: retried, and a run of failures
2760 // stops the writer rather than quietly thinning the series.
2761 match with_retries("committing a clock offset", || {
2762 db.transaction(|tx| tx.insert_clock_offset(source_id, ts, offset_ns))
2763 }) {
2764 Ok(()) => health.committed(),
2765 Err(e) if e.is_retryable() => health.dropped(e)?,
2766 Err(e) => return Err(e),
2767 }
2768 }
2769 Ok(Msg::CallerRows {
2770 source_id,
2771 stream,
2772 rows,
2773 }) => {
2774 // A name's rows append in `ts` order, judged against the
2775 // floor as it stood before this call (FORMAT.md §3.7).
2776 let floor = match caller_floors.get(&(source_id, stream.clone())) {
2777 Some(floor) => *floor,
2778 None => match with_retries("reading a caller-row floor", || {
2779 CallerFloor::read(db, source_id, &stream)
2780 }) {
2781 Ok(floor) => {
2782 caller_floors.insert((source_id, stream.clone()), floor);
2783 floor
2784 }
2785 // Lost like a dropped commit: the rows are not
2786 // written, and a run of these stops the writer.
2787 Err(e) if e.is_retryable() => {
2788 if replicas.contains(&source_id) {
2789 poison(shadowed, source_id);
2790 }
2791 health.dropped(e)?;
2792 continue;
2793 }
2794 Err(e) => return Err(e),
2795 },
2796 };
2797 let offered = rows.len();
2798 if replicas.contains(&source_id) {
2799 // All or nothing, as for a replicated copy's WAL rows.
2800 if is_poisoned(shadowed, source_id) {
2801 continue;
2802 }
2803 if rows.iter().any(|r| !floor.admits(r.ts)) {
2804 poison(shadowed, source_id);
2805 health.count_late_caller_rows(shadowed, source_id, &stream, offered as u64);
2806 continue;
2807 }
2808 }
2809 let rows: Vec<CallerRow> =
2810 rows.into_iter().filter(|r| floor.admits(r.ts)).collect();
2811 if rows.len() < offered {
2812 health.count_late_caller_rows(
2813 shadowed,
2814 source_id,
2815 &stream,
2816 (offered - rows.len()) as u64,
2817 );
2818 }
2819 if rows.is_empty() {
2820 continue;
2821 }
2822 // Data, not metadata: a commit that fails after retries is
2823 // counted like a dropped tick, and a run of them stops the
2824 // writer.
2825 match with_retries("committing caller rows", || {
2826 db.insert_caller_rows(source_id, &stream, &rows)
2827 }) {
2828 Ok(()) => {
2829 health.committed();
2830 let newest = rows.iter().map(|r| r.ts).max().expect("not empty");
2831 caller_floors.insert((source_id, stream), floor.after(newest));
2832 }
2833 Err(e) if e.is_retryable() => {
2834 if replicas.contains(&source_id) {
2835 poison(shadowed, source_id);
2836 }
2837 health.dropped(e)?
2838 }
2839 Err(e) => return Err(e),
2840 }
2841 }
2842 Ok(Msg::Finalize {
2843 source_id,
2844 clock_offset,
2845 }) => {
2846 caller_floors.retain(|(source, _), _| *source != source_id);
2847 // The loop's final tick observation joins the series only when
2848 // it adds a timestamp no sealed row already covers — otherwise
2849 // the series would carry two conflicting offsets at one
2850 // timestamp and consumers could not read it uniformly. The
2851 // row-derived value wins because it is a projection of the
2852 // `:wall_offset` column the segment itself carries. Same rule,
2853 // No `novel` check any more: `clock_offsets` is keyed
2854 // `(source_id, ts)` and inserted `OR IGNORE`, so the first
2855 // observation at a timestamp wins and a second is dropped by
2856 // the schema. That is strictly better than the set this used to
2857 // consult — the set only covered the finalize path, so two seal
2858 // batches landing on one `last_ts` still wrote conflicting
2859 // rows, and it grew for the life of the writer.
2860 with_retries("finalizing a source", || {
2861 db.transaction(|tx| {
2862 if let Some((ts, offset)) = clock_offset {
2863 tx.insert_clock_offset(source_id, ts, offset)?;
2864 }
2865 tx.mark_complete(source_id)
2866 })
2867 })?;
2868 finalized += 1;
2869 beating.remove(&source_id);
2870 // Deliberately NOT returning here, and not reclaiming yet. An
2871 // archive may hold several sources; this one is complete,
2872 // the others may still be writing. The reclaim is a
2873 // whole-file operation and belongs at the end, once — see the
2874 // loop's exit below.
2875 }
2876 // Asked to stop. Same accounting as the channel-close arm below:
2877 // reclaim only if every source opened was also finalized.
2878 Ok(Msg::Shutdown) => {
2879 if added > 0 && finalized == added {
2880 reclaim_all(db)?;
2881 }
2882 return Ok(());
2883 }
2884 // Every handle has been dropped, so no further work can arrive.
2885 //
2886 // If all the sources that were opened also finalized, this is a
2887 // clean close and the free list is drained once, here — the place
2888 // the single-source writer did it inside its `Finalize` arm.
2889 // AFTER every `mark_complete`, deliberately: reclaiming space is an
2890 // optimization, and a crash partway through it must leave complete
2891 // sources that are merely larger than they needed to be, never
2892 // incomplete ones that happen to be compact.
2893 //
2894 // Otherwise a handle was dropped without finalizing. Nothing to
2895 // clean up and nothing to reclaim: the file is already a valid
2896 // archive holding every committed tick, with `complete` still 0 —
2897 // that is the recovery artifact, and a shutdown that may be a kill
2898 // must not pay for a vacuum on the way down.
2899 Err(_) => {
2900 if added > 0 && finalized == added {
2901 reclaim_all(db)?;
2902 }
2903 return Ok(());
2904 }
2905 }
2906 }
2907}
2908
2909/// Record that this writer beats `source_id` every `every`, and give it its
2910/// first beat. Best-effort, like the beats that follow: the source has
2911/// already been added or resumed, and a source whose interval could not be
2912/// set reads as unknown rather than as stopped.
2913fn start_heartbeat(db: &mut ArchiveMut, source_id: i64, every: Duration) {
2914 let interval_ns = i64::try_from(every.as_nanos()).unwrap_or(i64::MAX);
2915 if let Err(e) = db.transaction(|tx| {
2916 tx.set_heartbeat_interval(source_id, interval_ns)?;
2917 tx.beat(&[source_id])
2918 }) {
2919 warn!("failed to start the heartbeat of source {source_id}: {e}");
2920 }
2921}
2922
2923/// Hand freed pages back to the filesystem, but only once the free list is a
2924/// noticeable fraction of the file. See the two constants for why the guard is
2925/// there: without it this would run every pass for no gain, and without the
2926/// reclaim a buffer that shrank would keep its high-water size forever.
2927#[cfg_attr(not(any(test, feature = "test-support")), doc(hidden))]
2928#[doc(hidden)]
2929pub fn reclaim_if_fragmented(db: &mut ArchiveMut) -> Result<()> {
2930 if should_reclaim(
2931 db.pragma_u32("freelist_count")?,
2932 db.pragma_u32("page_count")?,
2933 ) {
2934 db.incremental_vacuum(RECLAIM_PAGES_PER_PASS)?;
2935 }
2936 Ok(())
2937}
2938
2939/// The guard, as a decision rather than a branch — because it is a decision
2940/// about cost, not outcome: reclaiming an unfragmented file is a no-op
2941/// either way, so the only way to test the threshold is to ask it directly.
2942#[cfg_attr(not(any(test, feature = "test-support")), doc(hidden))]
2943#[doc(hidden)]
2944pub fn should_reclaim(free_pages: u32, pages: u32) -> bool {
2945 free_pages.saturating_mul(RECLAIM_FREELIST_DIVISOR) > pages
2946}
2947
2948/// Hand freed pages back to the filesystem at a clean close, in passes of
2949/// [`RECLAIM_PAGES_PER_PASS`], until the free list is empty or
2950/// [`RECLAIM_AT_CLOSE_BUDGET`] is spent.
2951///
2952/// Bounded, unlike the `u32::MAX` this used to pass: it runs on the way out,
2953/// inside `Drop` for a caller that never joined explicitly, and a rolling
2954/// buffer that evicted heavily can hold a free list that takes seconds to
2955/// return. Whatever is left is reclaimed by the next retention pass on the
2956/// next open; nothing is lost by stopping early, only space not yet given
2957/// back.
2958fn reclaim_all(db: &mut ArchiveMut) -> Result<()> {
2959 let started = Instant::now();
2960 while db.pragma_u32("freelist_count")? > 0 {
2961 db.incremental_vacuum(RECLAIM_PAGES_PER_PASS)?;
2962 if started.elapsed() >= RECLAIM_AT_CLOSE_BUDGET {
2963 warn!(
2964 "stopped reclaiming freed pages after {:?}; {} page(s) remain on the free list \
2965 and will be reclaimed by a later retention pass",
2966 RECLAIM_AT_CLOSE_BUDGET,
2967 db.pragma_u32("freelist_count")?
2968 );
2969 break;
2970 }
2971 }
2972 Ok(())
2973}
2974
2975/// Seal `source_id`'s deferred streams, each in its own transaction and
2976/// retried like any seal, and return the ones still unsealed after a
2977/// retryable failure. One stream per transaction, so one stream's encoder
2978/// failure does not hold back another; nothing relies on deferred streams
2979/// sealing together.
2980///
2981/// After the first retryable failure the remaining streams stay deferred
2982/// without being tried. A lock or I/O error that outlasted one retry schedule will
2983/// almost always outlast the next, and a schedule per stream would block
2984/// the writer thread for one schedule (about 20 s at the default busy
2985/// timeout) per deferred stream.
2986///
2987/// A stream that seals, or whose seal fails with an error that is not
2988/// retryable, is taken off `deferred`. The second is logged rather than
2989/// returned, because retention failing must not stop the writer, and it is
2990/// not retried at later passes: an encoder that fails on these rows fails on
2991/// them at every pass, and each retry would re-encode the stream's growing
2992/// backlog. Retention keeps its live rows, so unless the caller deletes them
2993/// with `discard_live_rows`, a `Seal` of the stream that fails the same way
2994/// stops the writer.
2995fn retry_deferred_seals(
2996 db: &mut ArchiveMut,
2997 source_id: i64,
2998 deferred: &mut BTreeMap<i64, BTreeMap<String, usize>>,
2999 next_seq: &mut BTreeMap<(i64, String), u64>,
3000 watermarks: &mut BTreeMap<i64, BTreeMap<String, i64>>,
3001 encoder: &(dyn SegmentEncoder + Send),
3002) -> BTreeSet<String> {
3003 let Some(listed) = deferred.remove(&source_id) else {
3004 return BTreeSet::new();
3005 };
3006 let mut still = BTreeMap::new();
3007 for (stream, cap) in listed {
3008 if !still.is_empty() {
3009 still.insert(stream, cap);
3010 continue;
3011 }
3012 match with_retries("sealing a deferred stream before retention", || {
3013 seal_batch(
3014 db,
3015 source_id,
3016 next_seq,
3017 watermarks,
3018 vec![stream.clone()],
3019 cap,
3020 encoder,
3021 )
3022 }) {
3023 Ok(()) => {}
3024 Err(e) if e.is_retryable() => {
3025 still.insert(stream, cap);
3026 }
3027 Err(e) => warn!(
3028 "sealing deferred stream `{stream}` of source {source_id} before retention \
3029 failed ({e}); its segments are evicted and its live rows are kept"
3030 ),
3031 }
3032 }
3033 let streams = still.keys().cloned().collect();
3034 if !still.is_empty() {
3035 deferred.insert(source_id, still);
3036 }
3037 streams
3038}
3039
3040/// Insert a segment built elsewhere at this stream's next `seq`.
3041///
3042/// The other entrance to the seal path. `seal_batch` encodes what is in the
3043/// WAL; this takes bytes somebody else already encoded, which is what makes a
3044/// replication catch-up cheap — shipping a sealed segment costs far less than
3045/// replaying the rows that built it.
3046///
3047/// **It does not run [`segment::materialize`](crate::segment::materialize).**
3048/// There are no input rows to check the segment against: the sender's own seal
3049/// already ran that contract, and the bytes arrived opaque. This is the same
3050/// trust `rewrite::copy_sources_into` places in a segment it carries across.
3051/// What it checks instead is where the segment lands.
3052///
3053/// Returns whether it inserted. `false` means the stream's watermark already
3054/// covers the segment, which is the **normal** outcome of a reconnect: a
3055/// subscriber that reconnects and asks for the last hour is re-sent segments it
3056/// already holds, and refusing those would make an ordinary reconnect an error.
3057fn adopt_segment(
3058 db: &mut ArchiveMut,
3059 source_id: i64,
3060 next_seq: &mut BTreeMap<(i64, String), u64>,
3061 watermarks: &mut BTreeMap<i64, BTreeMap<String, i64>>,
3062 segment: &Adopted,
3063) -> Result<bool> {
3064 let Adopted {
3065 stream,
3066 meta,
3067 bytes,
3068 caller_index,
3069 } = segment;
3070 let stream = stream.as_str();
3071 // The catalog facts have to describe a segment that could exist. A
3072 // zero-row segment has no span to compare against anything, and an
3073 // inverted one would set a watermark below its own first row.
3074 if meta.rows == 0 || meta.first_ts > meta.last_ts {
3075 return Err(Error::Message(format!(
3076 "source {source_id}: the segment offered for `{stream}` claims {} row(s) over [{}, {}], which is not a segment that can exist",
3077 meta.rows, meta.first_ts, meta.last_ts
3078 )));
3079 }
3080
3081 let watermark = watermarks
3082 .get(&source_id)
3083 .and_then(|m| m.get(stream))
3084 .copied();
3085 if let Some(w) = watermark {
3086 // Wholly at or below the watermark: this stream already has these
3087 // rows. A reconnect re-sends them, so it is a skip and not a failure.
3088 if meta.last_ts <= w {
3089 return Ok(false);
3090 }
3091 // Straddling it is a different thing, and there is nothing sound to do
3092 // with it. Inserting would put the rows below `w` behind the read
3093 // watermark, where `LIVE_WAL_PREDICATE` shadows them and no read can
3094 // ever return them (FORMAT.md §3.3) — the same failure the
3095 // out-of-order rule exists to prevent, arriving as a segment instead of
3096 // a row. Splitting the segment would mean decoding it, which is the
3097 // one thing this layer cannot do.
3098 if meta.first_ts <= w {
3099 return Err(Error::Message(format!(
3100 "source {source_id}: the segment offered for `{stream}` spans [{}, {}], which straddles the stream's newest sealed row ({w}); its rows at or below {w} could never be read, and splitting it would mean decoding it",
3101 meta.first_ts, meta.last_ts
3102 )));
3103 }
3104 }
3105
3106 // Nothing unsealed may be inside the span either. A seal earns the right
3107 // to prune by having encoded exactly the rows it covers; this segment
3108 // proves nothing about the subscriber's own WAL rows, so pruning them
3109 // would delete rows that end up in no segment. Refusing instead keeps
3110 // `adopt_segment` a pure insert: it never deletes anything.
3111 //
3112 // In a well-formed stream this cannot fire — catch-up segments arrive
3113 // before the tail they precede — so it fires when the sender interleaved
3114 // the two, which is a protocol error worth naming.
3115 let live = db.live_wal_span(source_id, stream)?;
3116 if let Some(first) = live.first_ts {
3117 if first <= meta.last_ts {
3118 return Err(Error::Message(format!(
3119 "source {source_id}: the segment offered for `{stream}` ends at {}, at or after an unsealed row already in the WAL ({first}); adopting it would shadow rows no segment holds",
3120 meta.last_ts
3121 )));
3122 }
3123 }
3124
3125 let seq = next_seq
3126 .get(&(source_id, stream.to_string()))
3127 .copied()
3128 .unwrap_or(0);
3129 db.insert_segment_with_index(source_id, stream, seq, meta, bytes, caller_index.as_deref())?;
3130 // After the commit, like `seal_batch`: a failed attempt must reuse the
3131 // same number, or the stream's sequence carries a hole per retry.
3132 next_seq.insert((source_id, stream.to_string()), seq + 1);
3133 watermarks
3134 .entry(source_id)
3135 .or_default()
3136 .insert(stream.to_string(), meta.last_ts);
3137 Ok(true)
3138}
3139
3140/// The writer-thread half of [`SourceWriter::sync_to`] (WIRE.md §4.7).
3141///
3142/// Reads and encodes outside the transaction, then makes every change in
3143/// one: a kill leaves the stream as it was or as the sync left it. An
3144/// encoder error does not fail the sync; the rows it covered are deleted and
3145/// counted in `unsealable`.
3146#[allow(clippy::too_many_arguments)]
3147fn sync_stream(
3148 db: &mut ArchiveMut,
3149 source_id: i64,
3150 stream: &str,
3151 at: i64,
3152 next_seq: &mut BTreeMap<(i64, String), u64>,
3153 watermarks: &mut BTreeMap<i64, BTreeMap<String, i64>>,
3154 encoder: &(dyn SegmentEncoder + Send),
3155) -> Result<Synced> {
3156 let (segments, wal, uuid) = with_retries("reading a stream to sync", || {
3157 Ok((
3158 db.read_segment_meta(source_id, stream)?,
3159 db.read_wal(source_id, stream)?,
3160 db.source_uuid(source_id)?,
3161 ))
3162 })?;
3163 if let Some((_, m)) = segments
3164 .iter()
3165 .find(|(_, m)| m.first_ts <= at && at < m.last_ts)
3166 {
3167 return Err(Error::Message(format!(
3168 "source {source_id}: the sync point {at} of `{stream}` is inside the copy's \
3169 segment [{}, {}], and a sync deletes whole segments",
3170 m.first_ts, m.last_ts
3171 )));
3172 }
3173 let w0 = segments.iter().map(|(_, m)| m.last_ts).max();
3174 let held_newest = wal
3175 .iter()
3176 .map(|r| r.ts)
3177 .chain(segments.iter().map(|(_, m)| m.last_ts))
3178 .max();
3179 let live = |r: &&WalRow| w0.is_none_or(|w| r.ts > w);
3180
3181 // 1. Seal the live rows at or below `at`.
3182 let to_seal: Vec<WalRow> = wal
3183 .iter()
3184 .filter(live)
3185 .filter(|r| r.ts <= at)
3186 .cloned()
3187 .collect();
3188 let sealed = if to_seal.is_empty() {
3189 None
3190 } else {
3191 let ctx = EncodeContext::new(source_id, stream).with_source_uuid(uuid.as_deref());
3192 match crate::segment::materialize(encoder, &ctx, &to_seal) {
3193 Ok(segment) => segment,
3194 Err(e) => {
3195 warn!(
3196 "source {source_id}: sealing {} live row(s) of `{stream}` at or below the \
3197 sync point {at} failed ({e}); they are deleted and counted as unsealable",
3198 to_seal.len()
3199 );
3200 None
3201 }
3202 }
3203 };
3204 let removed: Vec<(u64, SegmentMeta)> = segments
3205 .iter()
3206 .filter(|(_, m)| m.first_ts > at)
3207 .copied()
3208 .collect();
3209 let w1 = segments
3210 .iter()
3211 .filter(|(_, m)| m.last_ts <= at)
3212 .map(|(_, m)| m.last_ts)
3213 .chain(sealed.as_ref().map(|s| s.last_ts))
3214 .max();
3215 let synced = Synced {
3216 sealed: sealed.as_ref().map_or(0, |s| s.rows),
3217 unsealable: to_seal.len() as u64 - sealed.as_ref().map_or(0, |s| s.rows),
3218 replaced: removed.iter().map(|(_, m)| m.rows).sum::<u64>()
3219 + wal.iter().filter(live).filter(|r| r.ts > at).count() as u64,
3220 };
3221 let seq = next_seq
3222 .get(&(source_id, stream.to_string()))
3223 .copied()
3224 .unwrap_or(0);
3225
3226 with_retries("syncing a stream", || {
3227 // Immediate: the first statement, the `CREATE TABLE IF NOT EXISTS
3228 // bounds` that recording a bound or deleting a segment begins with,
3229 // reads.
3230 db.transaction_immediate(|tx| {
3231 if let Some(newest) = held_newest.filter(|n| *n > at) {
3232 tx.record_stream_bound(source_id, stream, newest)?;
3233 }
3234 for (seq, _) in &removed {
3235 tx.delete_segment(source_id, stream, *seq)?;
3236 }
3237 // 2. Delete every WAL row of the stream: the rows above `at` are
3238 // replaced, the live rows at or below it are sealed above or
3239 // counted unsealable, and the rest are at or below `w1`, where a
3240 // segment covers them.
3241 tx.delete_wal_range(source_id, stream, None, None)?;
3242 if let Some(segment) = &sealed {
3243 tx.insert_segment_with_index(
3244 source_id,
3245 stream,
3246 seq,
3247 &SegmentMeta {
3248 rows: segment.rows,
3249 first_ts: segment.first_ts,
3250 last_ts: segment.last_ts,
3251 },
3252 &segment.bytes,
3253 segment.index.as_deref(),
3254 )?;
3255 }
3256 Ok(())
3257 })
3258 })?;
3259 if sealed.is_some() {
3260 next_seq.insert((source_id, stream.to_string()), seq + 1);
3261 }
3262 let marks = watermarks.entry(source_id).or_default();
3263 match w1 {
3264 Some(w) => marks.insert(stream.to_string(), w),
3265 None => marks.remove(stream),
3266 };
3267 Ok(synced)
3268}
3269
3270/// The writer-thread half of [`SourceWriter::adopt_segments_after`] (WIRE.md
3271/// §4.8). Checks every part against the copy as the parts before it leave
3272/// it, then deletes and inserts for all of them in one transaction. Returns
3273/// the live rows deleted below each segment's `first_ts`.
3274fn adopt_segments_after(
3275 db: &mut ArchiveMut,
3276 source_id: i64,
3277 next_seq: &mut BTreeMap<(i64, String), u64>,
3278 watermarks: &mut BTreeMap<i64, BTreeMap<String, i64>>,
3279 parts: &[AdoptedAfter],
3280) -> Result<u64> {
3281 let Some(first) = parts.first() else {
3282 return Ok(0);
3283 };
3284 let stream = first.segment.stream.as_str();
3285 if let Some(p) = parts.iter().find(|p| p.segment.stream != stream) {
3286 return Err(Error::Message(format!(
3287 "source {source_id}: segments of `{stream}` and `{}` offered to adopt together; \
3288 a group belongs to one stream",
3289 p.segment.stream
3290 )));
3291 }
3292 let mut w = watermarks
3293 .get(&source_id)
3294 .and_then(|m| m.get(stream))
3295 .copied();
3296 let mut live: Vec<i64> = db
3297 .live_wal(source_id, stream)?
3298 .iter()
3299 .map(|r| r.ts)
3300 .collect();
3301 let mut pruned = 0u64;
3302 for AdoptedAfter { after, segment } in parts {
3303 let after = *after;
3304 let meta = &segment.meta;
3305 if meta.rows == 0 || meta.first_ts > meta.last_ts || meta.last_ts <= after {
3306 return Err(Error::Message(format!(
3307 "source {source_id}: the segment offered for `{stream}` after {after} claims \
3308 {} row(s) over [{}, {}], which is not a segment that can follow it",
3309 meta.rows, meta.first_ts, meta.last_ts
3310 )));
3311 }
3312 if let Some(w) = w.filter(|w| *w > after || meta.first_ts <= *w) {
3313 return Err(Error::Message(format!(
3314 "source {source_id}: the copy holds `{stream}` sealed to {w}, and the segment \
3315 offered over [{}, {}] after {after} would overlap it",
3316 meta.first_ts, meta.last_ts
3317 )));
3318 }
3319 if let Some(ts) = live.iter().find(|ts| **ts <= after) {
3320 return Err(Error::Message(format!(
3321 "source {source_id}: the copy holds a live row of `{stream}` at {ts}, at or \
3322 below {after}, where the segment offered after {after} says it holds none"
3323 )));
3324 }
3325 pruned += live
3326 .iter()
3327 .filter(|ts| **ts > after && **ts < meta.first_ts)
3328 .count() as u64;
3329 live.retain(|ts| *ts > meta.last_ts);
3330 w = Some(meta.last_ts);
3331 }
3332 let seq = next_seq
3333 .get(&(source_id, stream.to_string()))
3334 .copied()
3335 .unwrap_or(0);
3336 db.transaction(|tx| {
3337 for (i, AdoptedAfter { after, segment }) in parts.iter().enumerate() {
3338 tx.delete_wal_range(source_id, stream, Some(*after), Some(segment.meta.last_ts))?;
3339 tx.insert_segment_with_index(
3340 source_id,
3341 stream,
3342 seq + i as u64,
3343 &segment.meta,
3344 &segment.bytes,
3345 segment.caller_index.as_deref(),
3346 )?;
3347 }
3348 Ok(())
3349 })?;
3350 next_seq.insert((source_id, stream.to_string()), seq + parts.len() as u64);
3351 watermarks
3352 .entry(source_id)
3353 .or_default()
3354 .insert(stream.to_string(), w.expect("one part at least"));
3355 Ok(pruned)
3356}
3357
3358/// Encode one batch's segments, then insert them, record the batch's clock
3359/// observation and delete the WAL rows they cover, all in one transaction.
3360fn seal_batch(
3361 db: &mut ArchiveMut,
3362 source_id: i64,
3363 next_seq: &mut BTreeMap<(i64, String), u64>,
3364 watermarks: &mut BTreeMap<i64, BTreeMap<String, i64>>,
3365 batch: Vec<String>,
3366 max_rows: usize,
3367 encoder: &(dyn SegmentEncoder + Send),
3368) -> Result<()> {
3369 // Read and encode BEFORE the transaction opens. Both are proportional to
3370 // segment size and would hold the write lock for their whole duration.
3371 //
3372 // `live_wal` is what defines the segment: its watermark returns exactly the
3373 // rows past this stream's newest sealed segment, and because the ingest
3374 // side hands rows and seal requests down one FIFO channel, those are
3375 // exactly the rows the seal decision was made about. Nothing has to be
3376 // snapshotted or passed along for that to hold.
3377 let mut encoded = Vec::with_capacity(batch.len());
3378 // The batch's clock observation: the newest SEALED row's own
3379 // `(timestamp, wall_offset)` — one row, both halves. Derived from the rows
3380 // actually sealed, so every entry in the series is a projection of a row
3381 // that exists.
3382 let mut observation: Option<(i64, i64)> = None;
3383 let uuid = db.source_uuid(source_id)?;
3384 for stream in batch {
3385 let rows = db.live_wal(source_id, &stream)?;
3386 if rows.is_empty() {
3387 // No live rows: nothing to catalog and nothing to prune. A stream
3388 // whose rows were all sealed already is not an error worth failing
3389 // the source over.
3390 //
3391 // A stream nobody has ever written is a different thing, and it is
3392 // almost always a typo in the name handed to `seal`. Silence there
3393 // is expensive: the rows the caller meant to seal stay in the WAL
3394 // forever, so the archive grows without bound and re-encodes its
3395 // whole history on every read, with nothing anywhere saying why.
3396 if db.read_segments(source_id, &stream)?.is_empty() {
3397 warn!(
3398 "asked to seal `{stream}`, which has no live rows and has \
3399 never sealed a segment - is the name right?"
3400 );
3401 }
3402 continue;
3403 }
3404 // One contract for the three encode sites; see `segment::materialize`
3405 // for what it checks.
3406 // Split into parts of at most `max_rows`, each its own segment; see
3407 // `split_seal`.
3408 let ctx = EncodeContext::new(source_id, &stream).with_source_uuid(uuid.as_deref());
3409 let parts = split_seal(encoder, &ctx, &rows, max_rows)?;
3410 let Some(tail) = parts.last() else {
3411 continue;
3412 };
3413 // The batch's clock observation: ONE row's `(ts, wall_offset)`, never
3414 // one row's timestamp against another's offset. The series is a
3415 // projection of the rows it summarizes, so an entry has to be a pair
3416 // some single row actually carried.
3417 //
3418 // `tail.last_ts` names the segment's last row, which is the one worth
3419 // recording — but the offset must come from THAT row, not from the raw
3420 // input's last, which is a different row whenever the encoder dropped a
3421 // trailing one. Pairing the two put the observation a whole tick out.
3422 //
3423 // `>=`, so a later stream wins a tie.
3424 let segment_last = rows
3425 .iter()
3426 .rev()
3427 .find(|r| r.ts == tail.last_ts)
3428 .expect("the segment's last_ts is one of the rows; `materialize` refuses a segment whose ends are not");
3429 if observation.is_none_or(|(seen, _)| segment_last.ts >= seen) {
3430 observation = Some((segment_last.ts, segment_last.wall_offset));
3431 }
3432 // Read here, advanced only after the commit below succeeds: a batch
3433 // that fails and is retried must reuse the same numbers, or the
3434 // stream's sequence would carry a hole per failed attempt. Keyed by
3435 // source as well as stream: `segments.seq` is scoped to
3436 // `(source_id, stream)`, so two sources of the same host must not
3437 // share a counter.
3438 let first_seq = next_seq
3439 .get(&(source_id, stream.clone()))
3440 .copied()
3441 .unwrap_or(0);
3442 for (seq, part) in (first_seq..).zip(parts) {
3443 encoded.push(encoded_part(stream.clone(), seq, part));
3444 }
3445 }
3446
3447 // ONE transaction for the whole batch. A real workload seals a dozen
3448 // streams in lockstep, and a dozen implicit commits would be a dozen
3449 // fsyncs at `synchronous=FULL` against a ~46 ms append interval.
3450 //
3451 // The batch's clock observation rides along inside it, for free: no extra
3452 // commit, no extra fsync, and it lands iff the segments it was derived
3453 // from do. It is a `clock_offsets` ROW rather than something a reader has
3454 // to dig out of a segment, which is what keeps drift readable from the
3455 // catalog alone — including on a source that is killed before it ever
3456 // finalizes, where these are the only observations there will be.
3457 //
3458 // The WAL rows the segments cover are deleted in the same transaction,
3459 // so a committed seal leaves no row at or below its watermark and a
3460 // failed one leaves the stream as it was. Each stream is deleted only up
3461 // to its OWN newest segment's `last_ts`: rows it ingested after the
3462 // sealed span, and every other stream's rows, stay live. A split
3463 // stream's parts are consecutive in `encoded`, oldest first, so its last
3464 // part carries the newest `last_ts`. Measured on macOS, the delete here
3465 // was no slower than in a commit of its own after the seal, and faster
3466 // for 12 streams of 100 rows; Linux is not measured
3467 // (docs/journal/2026-11-14-the-live-tail.md).
3468 db.transaction(|tx| {
3469 for e in &encoded {
3470 tx.insert_segment_with_index(
3471 source_id,
3472 &e.stream,
3473 e.seq,
3474 &e.meta,
3475 &e.bytes,
3476 e.caller_index.as_deref(),
3477 )?;
3478 }
3479 if let Some((ts, offset)) = observation {
3480 tx.insert_clock_offset(source_id, ts, offset)?;
3481 }
3482 for (i, e) in encoded.iter().enumerate() {
3483 if encoded
3484 .get(i + 1)
3485 .is_none_or(|next| next.stream != e.stream)
3486 {
3487 tx.delete_wal_range(source_id, &e.stream, None, Some(e.meta.last_ts))?;
3488 }
3489 }
3490 Ok(())
3491 })?;
3492 for e in &encoded {
3493 next_seq.insert((source_id, e.stream.clone()), e.seq + 1);
3494 // The watermark moves with the segment that set it, and only after
3495 // the commit: a deferred batch has not raised anything yet, so an
3496 // append it would have shadowed stays legal until the seal lands.
3497 watermarks
3498 .entry(source_id)
3499 .or_default()
3500 .insert(e.stream.clone(), e.meta.last_ts);
3501 }
3502 Ok(())
3503}
3504
3505/// One part of a stream's seal, numbered and cataloged.
3506fn encoded_part(stream: String, seq: u64, segment: crate::segment::Segment) -> Encoded {
3507 Encoded {
3508 stream,
3509 seq,
3510 meta: SegmentMeta {
3511 // ALL THREE from the segment, never from the input rows. An
3512 // encoder may drop rows it cannot decode on their own, and those
3513 // are real WAL rows that never reach the segment; cataloging the
3514 // input's span would claim coverage the bytes do not have.
3515 //
3516 // `last_ts` is the one that used to come from the input, and it
3517 // was the expensive one: it is what the WAL prune and the read
3518 // watermark are both computed from, so a dropped trailing row was
3519 // deleted from the WAL, absent from the segment, and hidden by a
3520 // watermark claiming to cover it. Taken from the segment, that
3521 // row stays live and seals next time.
3522 rows: segment.rows,
3523 first_ts: segment.first_ts,
3524 last_ts: segment.last_ts,
3525 },
3526 bytes: segment.bytes,
3527 caller_index: segment.index,
3528 }
3529}
3530
3531/// A stream's live rows as segments of at most `max_rows` WAL rows each,
3532/// oldest first; empty when the encoder produces no segment.
3533///
3534/// At or under the cap this is one `materialize`, exactly the unsplit seal.
3535/// Over it, part `k` is `rows[k * max_rows..]` up to `max_rows` rows,
3536/// encoded after the rows before it (`SegmentEncoder::encode_after`).
3537///
3538/// The parts must tile the run with no gap between them. A row an encoder
3539/// drops at the end of one part, or the start of the next, would be below
3540/// the next part's `last_ts`: the prune deletes it and the read watermark
3541/// hides it, so it is in no segment and no WAL. The first part may still
3542/// drop a leading run and the last a trailing one, as an unsplit segment
3543/// may. A part that drops at an inner edge, or yields no segment, abandons
3544/// the split: the whole run is encoded as one segment instead, which is no
3545/// worse than an uncapped seal and loses nothing.
3546fn split_seal(
3547 encoder: &(dyn SegmentEncoder + Send),
3548 ctx: &EncodeContext<'_>,
3549 rows: &[WalRow],
3550 max_rows: usize,
3551) -> Result<Vec<crate::segment::Segment>> {
3552 let stream = ctx.stream;
3553 let max_rows = max_rows.max(1);
3554 if rows.len() <= max_rows {
3555 return Ok(crate::segment::materialize(encoder, ctx, rows)?
3556 .into_iter()
3557 .collect());
3558 }
3559 let mut parts = Vec::with_capacity(rows.len().div_ceil(max_rows));
3560 let mut start = 0;
3561 while start < rows.len() {
3562 let end = rows.len().min(start + max_rows);
3563 let part = &rows[start..end];
3564 let segment = crate::segment::materialize_after(encoder, ctx, &rows[..start], part)?;
3565 let tiles = segment.as_ref().is_some_and(|s| {
3566 (start == 0 || s.first_ts == part[0].ts)
3567 && (end == rows.len() || s.last_ts == part[part.len() - 1].ts)
3568 });
3569 let Some(segment) = segment.filter(|_| tiles) else {
3570 warn!(
3571 "the encoder did not cover rows {start}..{end} of `{stream}`'s {} live rows \
3572 at an edge shared with another part; sealing them as one segment, past the \
3573 row cap of {max_rows}",
3574 rows.len()
3575 );
3576 return Ok(crate::segment::materialize(encoder, ctx, rows)?
3577 .into_iter()
3578 .collect());
3579 };
3580 parts.push(segment);
3581 start = end;
3582 }
3583 Ok(parts)
3584}