Skip to main content

taskfleet_core/
events.rs

1//! Event append primitive + `seq` recovery (design.md §1.4, §4).
2
3use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
4use std::path::{Path, PathBuf};
5
6use chrono::Utc;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use crate::atomic::{open_events_append, write_atomic};
11use crate::error::{Error, Result};
12use crate::lock::{LockedRun, RunLock};
13use crate::paths::RunPaths;
14use crate::projections::{derive_counters, read_manifest_opt, write_manifest};
15use crate::reducer::{commit_ops, reduce_event_to_ops};
16use crate::schema::{Event, NodeId};
17
18/// Backward-scan chunk size when looking for the previous newline.
19const SCAN_CHUNK: u64 = 64 * 1024;
20
21/// Read the last `seq` from `events.jsonl`, or `0` if empty/missing.
22///
23/// Tolerates:
24/// - lines larger than any fixed buffer (`node.report` payloads can be 10s of KB
25///   per `design.md` §1.4) — we scan backwards in chunks for the previous `\n`.
26/// - a crash-truncated final line lacking a trailing `\n` — that partial tail
27///   is discarded and recovery uses the last complete record.
28///
29/// Caller must already hold the run's [`RunLock`] for correctness against
30/// concurrent appenders.
31pub fn recover_last_seq(events_path: &Path) -> Result<u64> {
32    let mut f = match std::fs::File::open(events_path) {
33        Ok(f) => f,
34        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
35        Err(e) => return Err(Error::io(events_path, e)),
36    };
37    let len = f.metadata().map_err(|e| Error::io(events_path, e))?.len();
38    if len == 0 {
39        return Ok(0);
40    }
41
42    // Require a newline-terminated final line; otherwise treat the last
43    // partial chunk as torn and recover from the previous complete line.
44    let mut tail_byte = [0u8; 1];
45    f.seek(SeekFrom::End(-1))
46        .map_err(|e| Error::io(events_path, e))?;
47    f.read_exact(&mut tail_byte)
48        .map_err(|e| Error::io(events_path, e))?;
49    let mut end = if tail_byte[0] == b'\n' {
50        len - 1
51    } else {
52        match find_prev_newline(&mut f, len, events_path)? {
53            Some(p) => p,
54            None => return Ok(0),
55        }
56    };
57
58    // `end` is the byte index of the trailing `\n` of the last complete
59    // record. Walk backward over complete lines, skipping any that are empty
60    // or whitespace-only — consecutive newlines or blank/whitespace lines (e.g.
61    // from external editing) shouldn't fool recovery into reading the wrong
62    // last record — and recover the seq from the last line bearing real bytes.
63    loop {
64        let line_start = match find_prev_newline(&mut f, end, events_path)? {
65            Some(p) => p + 1,
66            None => 0,
67        };
68        let line_len = end - line_start;
69        f.seek(SeekFrom::Start(line_start))
70            .map_err(|e| Error::io(events_path, e))?;
71        let mut line = vec![0u8; line_len as usize];
72        f.read_exact(&mut line)
73            .map_err(|e| Error::io(events_path, e))?;
74        // Any non-whitespace byte means a real record — parse it. Lines that
75        // are empty or hold only ASCII whitespace (a stray `\r`, `\t`, or
76        // spaces left by external editing) carry no record, so skip them and
77        // keep scanning back; serde tolerates whitespace surrounding a real
78        // envelope, so a genuine record with trailing spaces still parses.
79        if line.iter().any(|b| !b.is_ascii_whitespace()) {
80            return parse_seq(&line, events_path);
81        }
82        // Whitespace-only line: no record here. Step to the newline before it
83        // and keep scanning; reaching the start means the log holds no event.
84        if line_start == 0 {
85            return Ok(0);
86        }
87        end = line_start - 1;
88    }
89}
90
91/// The envelope fields recovered from the last complete line. Required fields
92/// mirror [`Event`]'s required shape, so `recover_last_seq` accepts a last line
93/// iff [`read_all_events`] would — the two readers agree on what the last
94/// record is. `data` / `idempotency_key` are skipped (serde ignores unknown
95/// fields) so a multi-KB `node.report` payload isn't re-materialized on the
96/// hot append path just to read `seq`.
97#[derive(Deserialize)]
98#[allow(dead_code)] // fields exist to force serde validation, not to be read
99struct SeqLine {
100    seq: u64,
101    ts: chrono::DateTime<chrono::Utc>,
102    kind: String,
103    run_id: crate::schema::RunId,
104    #[serde(default)]
105    node_id: Option<NodeId>,
106}
107
108fn parse_seq(line: &[u8], events_path: &Path) -> Result<u64> {
109    // The last complete line must be a full, valid event envelope — the same
110    // bar `read_all_events` applies to every line — so a `\n`-terminated line
111    // that parses as JSON but isn't a valid event (e.g. `{"seq":1}` missing
112    // `ts`/`run_id`) is event-log corruption, not a usable seq source. This
113    // keeps the three readers aligned on the last record.
114    let hdr: SeqLine = serde_json::from_slice(line).map_err(|e| Error::CorruptEventLog {
115        path: events_path.to_path_buf(),
116        reason: format!(
117            "last complete line is not a valid event: {} [{e}]",
118            excerpt(line)
119        ),
120    })?;
121    Ok(hdr.seq)
122}
123
124/// Find the byte offset of the last `\n` strictly before `before`. Returns
125/// `None` if no newline exists in `[0, before)`.
126fn find_prev_newline(
127    f: &mut std::fs::File,
128    before: u64,
129    events_path: &Path,
130) -> Result<Option<u64>> {
131    if before == 0 {
132        return Ok(None);
133    }
134    let mut pos = before;
135    loop {
136        let start = pos.saturating_sub(SCAN_CHUNK);
137        let len = pos - start;
138        f.seek(SeekFrom::Start(start))
139            .map_err(|e| Error::io(events_path, e))?;
140        let mut buf = vec![0u8; len as usize];
141        f.read_exact(&mut buf)
142            .map_err(|e| Error::io(events_path, e))?;
143        if let Some(i) = buf.iter().rposition(|b| *b == b'\n') {
144            return Ok(Some(start + i as u64));
145        }
146        if start == 0 {
147            return Ok(None);
148        }
149        pos = start;
150    }
151}
152
153/// Truncate a torn (newline-less) final line off `events.jsonl` so the next
154/// append never concatenates onto a partial record.
155///
156/// `recover_last_seq` only *ignores* a torn tail for seq purposes — it never
157/// removes the bytes. Without this, an append after a crash-truncated write
158/// would write its `\n`-terminated line directly onto the partial bytes,
159/// producing one malformed `…torn…{"seq":…}` line that every later reader
160/// (now sharing a strict torn-tail policy) hard-errors on. Cutting back to
161/// the last complete record here guarantees the file is always empty or
162/// `\n`-terminated before we append.
163///
164/// Caller must hold the run's [`RunLock`]. No-op when the file is absent,
165/// empty, or already `\n`-terminated (the common, clean case — one `stat` +
166/// one-byte read, no rewrite).
167fn truncate_torn_tail(events_path: &Path) -> Result<()> {
168    let mut opts = std::fs::OpenOptions::new();
169    opts.read(true).write(true);
170    // `O_NOFOLLOW`: refuse to rewrite the tail through a symlinked event log.
171    crate::paths::nofollow(&mut opts);
172    let mut f = match opts.open(events_path) {
173        Ok(f) => f,
174        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
175        Err(e) => return Err(Error::io(events_path, e)),
176    };
177    let len = f.metadata().map_err(|e| Error::io(events_path, e))?.len();
178    if len == 0 {
179        return Ok(());
180    }
181    let mut tail = [0u8; 1];
182    f.seek(SeekFrom::End(-1))
183        .map_err(|e| Error::io(events_path, e))?;
184    f.read_exact(&mut tail)
185        .map_err(|e| Error::io(events_path, e))?;
186    if tail[0] == b'\n' {
187        return Ok(());
188    }
189    // Torn final line: cut back to just past the last complete record's
190    // trailing newline, or to empty when no complete record exists.
191    let keep = match find_prev_newline(&mut f, len, events_path)? {
192        Some(nl) => nl + 1,
193        None => 0,
194    };
195    f.set_len(keep).map_err(|e| Error::io(events_path, e))?;
196    f.sync_all().map_err(|e| Error::io(events_path, e))?;
197    // Surface the recovery so an operator inspecting the run knows a
198    // crash-torn tail was discarded (and how many bytes), rather than the
199    // truncation happening invisibly under the lock.
200    tracing::warn!(
201        target: "taskfleet_core::events",
202        path = %events_path.display(),
203        discarded_bytes = len - keep,
204        kept_bytes = keep,
205        "truncated crash-torn final line off events.jsonl before append"
206    );
207    Ok(())
208}
209
210/// Append one event with a caller-supplied `seq`. The `_witness: &LockedRun`
211/// is compile-time proof the caller holds the run's exclusive [`RunLock`] for
212/// the duration of this call; the caller is still responsible for ensuring
213/// `seq` is monotonic. Misuse can corrupt the event log.
214///
215/// Test-only (`#[cfg(test)]`): a raw, no-reducer, caller-managed-`seq`
216/// primitive used by the crate's fixtures and the flock stress test to craft
217/// event logs with explicit seqs. Production mutation goes through
218/// [`append_and_apply_event`]; projection rebuild (future) replays via
219/// [`crate::reducer`], so neither needs this.
220#[cfg(test)]
221pub(crate) fn append_event_with_seq(
222    _witness: &LockedRun<'_>,
223    paths: &RunPaths,
224    seq: u64,
225    kind: &str,
226    node_id: Option<&NodeId>,
227    idempotency_key: Option<&str>,
228    data: Value,
229) -> Result<()> {
230    write_event_line(paths, seq, kind, node_id, idempotency_key, data)
231}
232
233#[cfg(test)]
234fn write_event_line(
235    paths: &RunPaths,
236    seq: u64,
237    kind: &str,
238    node_id: Option<&NodeId>,
239    idempotency_key: Option<&str>,
240    data: Value,
241) -> Result<()> {
242    let ev = Event {
243        ts: Utc::now(),
244        seq,
245        kind: kind.to_string(),
246        run_id: paths.run_id.clone(),
247        node_id: node_id.cloned(),
248        idempotency_key: idempotency_key.map(str::to_string),
249        data,
250    };
251    let events_path = paths.events();
252    let mut line = serde_json::to_vec(&ev).map_err(|e| Error::json(events_path.clone(), e))?;
253    line.push(b'\n');
254    let mut f = open_events_append(&events_path)?;
255    f.write_all(&line)
256        .map_err(|e| Error::io(events_path.clone(), e))?;
257    f.sync_all().map_err(|e| Error::io(events_path, e))?;
258    Ok(())
259}
260
261/// Outcome of an [`append_and_apply_event`] call.
262///
263/// `seq` is the value a caller surfaces to a user: the freshly appended
264/// event's `seq`, or — on an idempotent replay — the `seq` of the
265/// pre-existing matching event. A reducer no-op (e.g. an event dropped by
266/// the terminal-state guard) is still a success at this layer: `seq` names
267/// the appended event regardless of whether the reducer changed anything.
268///
269/// There is intentionally no `derived_event_ids` field. This API mutates
270/// exactly one event; the supervisor's report consumption, which emits a
271/// *batch* of derived discussion/spinoff events under one held lock, uses
272/// [`append_and_apply_unlocked`] instead (the sanctioned lock-held
273/// composition path) and tracks its own emitted ids.
274#[derive(Debug, Serialize)]
275pub struct AppendResult {
276    /// `seq` of the appended event, or of the prior event on an idempotent
277    /// replay.
278    pub seq: u64,
279    /// True when `idempotency_key` matched a prior event so nothing new was
280    /// appended or applied; `seq`/`prior` then describe that prior event.
281    pub idempotent_replay: bool,
282    /// True when the reducer produced at least one projection write for THIS
283    /// append — i.e. the event actually changed state, rather than folding to a
284    /// no-op (an unknown/audit kind, or an event dropped by a `*.created` /
285    /// terminal-state guard). Lets a caller distinguish "the reducer applied my
286    /// event" from "it was a dead event" WITHOUT re-reading the projection and
287    /// pattern-matching a field (issue `reducer-adopt-explicit-merge`).
288    ///
289    /// This is a report of what the reducer did on THIS call, NOT a durable
290    /// "is teardown pending?" signal: it is `false` both on an idempotent replay
291    /// AND on a fresh append the reducer no-op'd (e.g. re-submitting the exact
292    /// report already adopted). Callers making a DURABLE decision (does the run
293    /// still need a teardown actor?) must read projection state, not this flag —
294    /// see `run merge`'s `ensure_report_consumer`, which deliberately does NOT gate
295    /// its reattach on `applied` (that was a crash-retry leak caught in review).
296    pub applied: bool,
297    /// On an idempotent replay, the prior event's recorded `node_id` and
298    /// `data`, so a caller can reject a key reused with a conflicting
299    /// request (Stripe-style). `None` on a fresh append.
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub prior: Option<PriorEvent>,
302}
303
304/// The one canonical mutation entry point: append a single event to
305/// `events.jsonl` *and* fold it into the projection files via the reducer,
306/// all under the run's `flock`, with idempotency-key dedup.
307///
308/// On success, every `events.jsonl` line is folded into `manifest.json` /
309/// `nodes/*.json` / `discussions/*.json` / `spinoffs/*.json` before the lock
310/// is released, so a read CLI run a millisecond later never sees a stale
311/// projection. This is *not* a crash-atomic transaction: the event is fsynced
312/// before the reducer runs, so a crash (or an I/O error from `apply_event`)
313/// after the append but before the projection write leaves the log ahead of
314/// the projections — recoverable only by a future `rebuild_projections`. The
315/// log is the source of truth; projections are a derived cache.
316///
317/// The append is transactional against reducer *validation*: the event is
318/// first reduced through [`reduce_event_to_ops`](crate::reducer) under the
319/// lock — the single plan-then-commit path that both validates and computes
320/// the projection writes — and only a validating event is appended (and
321/// fsynced) and then committed by the reducer. A reducer-rejected event (a
322/// `CorruptEventLog` for a malformed payload) errors *before* any bytes are
323/// written, so the log never gains a poison line that a future replay /
324/// `rebuild_projections` would choke on.
325/// (A pre-existing torn tail may still be truncated before validation runs —
326/// those bytes are uncommitted by definition; see [`recover_last_seq`].)
327///
328/// When `idempotency_key` is `Some` and a prior event with the same `kind` +
329/// key already exists ([`find_prior_with_key`](crate::events)), nothing is appended or
330/// applied: the result carries the prior event's `seq`, `idempotent_replay:
331/// true`, and `prior: Some(..)` so the caller can detect a key reused with a
332/// conflicting payload. With `idempotency_key: None` no scan runs.
333///
334/// Callers that must compose several writes — or a read-modify-write
335/// transaction (read a projection, decide, then append) — under one lock
336/// window hold the lock themselves and use [`append_and_apply_unlocked`],
337/// the sanctioned lock-held composition path. Re-entering this function
338/// while already holding the lock would deadlock: `flock` blocks when a
339/// second open of the lock file from the same process tries `LOCK_EX`.
340pub fn append_and_apply_event(
341    paths: &RunPaths,
342    kind: &str,
343    node_id: Option<&NodeId>,
344    idempotency_key: Option<&str>,
345    data: Value,
346) -> Result<AppendResult> {
347    RunLock::with_lock(paths, |lock| {
348        // Catch the projections up to the event log before either the
349        // idempotency lookup or a fresh append. This is the recovery half of
350        // append+apply atomicity: any unapplied tail left by a prior crash is
351        // folded here, under the same lock, so an idempotent replay returns
352        // only once the prior event's projection is durably committed
353        // (`applied_seq >= prior.seq`) — never a stale "found, but not applied"
354        // result. A clean run with no tail makes this a cheap no-op.
355        replay_unapplied_unlocked(lock, paths)?;
356        // Idempotency lookup + append share this one lock window so a
357        // concurrent retry can't see "no prior event" and double-append.
358        if let Some(key) = idempotency_key {
359            if let Some(prior) = find_prior_with_key(lock, paths, kind, key)? {
360                return Ok(AppendResult {
361                    seq: prior.seq,
362                    idempotent_replay: true,
363                    // Nothing was applied by THIS call — the prior event (already
364                    // folded) carried any state change.
365                    applied: false,
366                    prior: Some(prior),
367                });
368            }
369        }
370        let (seq, applied) =
371            append_and_apply_reporting(lock, paths, kind, node_id, idempotency_key, data)?;
372        Ok(AppendResult {
373            seq,
374            idempotent_replay: false,
375            applied,
376            prior: None,
377        })
378    })
379}
380
381/// Catch projections up to the durable event log under an already-held
382/// exclusive lock, without appending an event. Mutation commands that must
383/// decide from current projections use this before their read/authorize step.
384pub fn replay_unapplied_unlocked(_witness: &LockedRun<'_>, paths: &RunPaths) -> Result<()> {
385    let events_path = paths.checked_events()?;
386    truncate_torn_tail(&events_path)?;
387    replay_unapplied(paths, &events_path)
388}
389
390/// Append one event and fold it into projections. The `_witness: &LockedRun`
391/// is compile-time proof the caller already holds the run's exclusive
392/// [`RunLock`] — obtained from [`RunLock::with_lock`] or [`RunLock::witness`],
393/// so this entry point cannot be reached without the lock. The **sanctioned
394/// lock-held composition path**: use it to fold extra logic (an idempotency-key
395/// lookup, a status precondition) or several writes (the supervisor's
396/// derived discussion/spinoff batch) into one locked critical section.
397/// Calling [`append_and_apply_event`] from within a held lock would
398/// deadlock because `flock` blocks when a second open of the lock file from
399/// the same process tries to acquire `LOCK_EX`.
400///
401/// # The witness is mandatory
402///
403/// Without a `&LockedRun` proof the lock is held, this does not compile — there
404/// is no way to skip the parameter, and [`LockedRun`] cannot be constructed
405/// outside this crate (its field is private), so the only source is a held
406/// [`RunLock`]:
407///
408/// ```compile_fail
409/// use taskfleet_core::{append_and_apply_unlocked, RunPaths};
410/// # fn demo(paths: &RunPaths) {
411/// // No witness passed — the first argument must be a `&LockedRun`, which a
412/// // caller can only obtain by actually holding the run's exclusive lock.
413/// let _ = append_and_apply_unlocked(paths, "run.status", None, None, serde_json::json!({}));
414/// # }
415/// ```
416pub fn append_and_apply_unlocked(
417    witness: &LockedRun<'_>,
418    paths: &RunPaths,
419    kind: &str,
420    node_id: Option<&NodeId>,
421    idempotency_key: Option<&str>,
422    data: Value,
423) -> Result<u64> {
424    append_and_apply_reporting(witness, paths, kind, node_id, idempotency_key, data)
425        .map(|(seq, _)| seq)
426}
427
428/// As [`append_and_apply_unlocked`], but also reports whether the reducer APPLIED
429/// (produced ≥1 projection op) vs folded to a no-op — the `bool` feeding
430/// [`AppendResult::applied`]. Kept private so the public composition primitive
431/// stays `-> u64` for its 15+ callers (none of which need the applied bit); only
432/// [`append_and_apply_event`] threads it out. See [`AppendResult::applied`] for
433/// why callers want it (issue `reducer-adopt-explicit-merge`).
434fn append_and_apply_reporting(
435    witness: &LockedRun<'_>,
436    paths: &RunPaths,
437    kind: &str,
438    node_id: Option<&NodeId>,
439    idempotency_key: Option<&str>,
440    data: Value,
441) -> Result<(u64, bool)> {
442    // Direct lock-held callers get the same catch-up guarantee as the ordinary
443    // append wrapper before computing this event against projections.
444    replay_unapplied_unlocked(witness, paths)?;
445    let events_path = paths.checked_events()?;
446    let last = recover_last_seq(&events_path)?;
447    let seq = last + 1;
448    let ev = Event {
449        ts: Utc::now(),
450        seq,
451        kind: kind.to_string(),
452        run_id: paths.run_id.clone(),
453        node_id: node_id.cloned(),
454        idempotency_key: idempotency_key.map(str::to_string),
455        data,
456    };
457    // Transactional gate, plan-then-commit: reduce the event against current
458    // projection state BEFORE the durable append. `reduce_event_to_ops` both
459    // validates and computes the exact projection writes to make; a reducer-
460    // rejected event errors here and is never written, so a later replay /
461    // rebuild can't trip on a poison line. The planned ops are then committed
462    // *after* the fsynced append — nothing mutates the projections between the
463    // plan and the commit (the append only touches `events.jsonl`), so the
464    // planned writes are still valid. One reduce pass serves both the gate and
465    // the apply, so there is no validate/apply branch pair to drift apart.
466    let ops = reduce_event_to_ops(paths, &ev)?;
467    // Whether the reducer changed state for this event — reported to the caller
468    // via `AppendResult::applied`. Captured before `commit_ops` consumes `ops`.
469    let applied = !ops.is_empty();
470    let mut line = serde_json::to_vec(&ev).map_err(|e| Error::json(events_path.clone(), e))?;
471    line.push(b'\n');
472    let mut f = open_events_append(&events_path)?;
473    f.write_all(&line)
474        .map_err(|e| Error::io(events_path.clone(), e))?;
475    f.sync_all().map_err(|e| Error::io(events_path, e))?;
476    if ev.kind == "caller.settlement_intent"
477        && std::env::var_os("TASKFLEET_TEST_CALLER_INTENT_CRASH_AFTER_SYNC").is_some()
478    {
479        std::process::exit(73);
480    }
481    commit_ops(paths, ops)?;
482    // Advance the watermark only after every projection this event touched is
483    // durably committed. A crash before this point leaves `applied_seq < seq`,
484    // and the next lock acquisition replays the event (idempotently — the
485    // reducer's existence/terminal guards make a re-fold a no-op) before
486    // advancing. So the watermark can only ever lag the projections, never lead
487    // them — the projection a reader sees is always at least as new as
488    // `applied_seq` claims.
489    advance_applied_seq(paths, seq)?;
490    Ok((seq, applied))
491}
492
493/// The three observable outcomes of an [`append_and_apply_idempotent`] call —
494/// the shared `--idempotency-key` contract that `event create`, `discussion
495/// resolve`, and future keyed verbs (`spinoff approve|reject`, `run create`,
496/// `node report`) all answer to, lifted out of each CLI's private log scan.
497///
498/// The discriminator is whether a prior event with the same `kind` + key
499/// already exists, and — if so — whether the call's `(node_id, data)` identity
500/// matches that prior event:
501///
502/// - [`AppendOutcome::Appended`] — no prior event carried this key: a fresh
503///   event was appended and folded into the projections. `seq` is its sequence.
504/// - [`AppendOutcome::IdempotentReplay`] — a prior event carried this key **and**
505///   the same `node_id` + `data`: a true retry. Nothing was appended; the
506///   `prior` event (its `seq` / `node_id` / `data`) is returned so the caller
507///   can surface the original sequence.
508/// - [`AppendOutcome::Conflict`] — a prior event carried this key but with a
509///   **different** `node_id` or `data`: the key was reused for a different
510///   request (a client bug, Stripe-style). Nothing was appended; `prior` is
511///   returned so the caller can build a precise conflict error (e.g. diff the
512///   payload vs. the node id).
513#[derive(Debug)]
514pub enum AppendOutcome {
515    /// A fresh event was appended and applied; `seq` is its sequence number.
516    Appended {
517        /// The appended event's `seq`.
518        seq: u64,
519    },
520    /// The key matched a prior event with identical `node_id` + `data`. No new
521    /// event was written; `prior.seq` is the original sequence to surface.
522    IdempotentReplay {
523        /// The pre-existing matching event (its `seq`, `node_id`, and `data`).
524        prior: PriorEvent,
525    },
526    /// The key matched a prior event whose `node_id` or `data` differs from this
527    /// request. No new event was written; the caller should reject the reuse.
528    Conflict {
529        /// The pre-existing event recorded under the same key, for the caller's
530        /// conflict diagnostics (`prior.seq` is the original sequence).
531        prior: PriorEvent,
532    },
533}
534
535/// Append one keyed event idempotently: scan for a prior event with the same
536/// `kind` + `key`, and either replay it, reject a conflicting reuse, or append
537/// fresh — the centralized `--idempotency-key` primitive (issue
538/// `core-idempotency-api`).
539///
540/// This is the **sanctioned lock-held composition path** for keyed appends: the
541/// `_witness: &LockedRun` proves the caller already holds the run's exclusive
542/// [`RunLock`] (from [`RunLock::with_lock`] or [`RunLock::witness`]), so the
543/// scan and the append share one lock window and a concurrent retry can never
544/// see "no prior event" and double-append. Calling it composes with the
545/// applied-seq watermark and the path-traversal defense exactly as
546/// [`append_and_apply_unlocked`] does — it catches the projections up to the log
547/// (`truncate_torn_tail` + `replay_unapplied`) before scanning, guards the run
548/// root + event log via `RunPaths::checked_events`, and routes the fresh
549/// append through `append_and_apply_unlocked`.
550///
551/// `build` lazily produces the event's `data` payload given the sequence the
552/// fresh event *would* receive. It is a **pure** constructor: it is invoked once
553/// to materialize the candidate payload (to compare against a prior event, or to
554/// write a fresh one) and must not encode caller-side domain preconditions — a
555/// verb whose append is gated on projection state (e.g. `discussion resolve`'s
556/// already-resolved / no-op decision) keeps that logic in its own locked body
557/// and uses [`find_prior_with_key`] directly. The `u64` lets a payload embed its
558/// own `seq`; a payload that does so is not replay-stable and should not be used
559/// with idempotency.
560///
561/// The key must be non-empty: an empty key is rejected with
562/// [`Error::EmptyIdempotencyKey`] before any scan, since `""` would collapse
563/// every keyless append into one dedup slot.
564///
565/// # Examples
566///
567/// ```no_run
568/// use taskfleet_core::{append_and_apply_idempotent, AppendOutcome, RunLock, RunPaths};
569/// use serde_json::json;
570///
571/// # fn demo(paths: &RunPaths) -> taskfleet_core::Result<()> {
572/// let outcome = RunLock::with_lock(paths, |lock| {
573///     append_and_apply_idempotent(
574///         paths,
575///         lock,
576///         "node.status",
577///         None,            // no target node
578///         "retry-key-42",  // the caller's idempotency key (non-empty)
579///         |_seq| Ok(json!({ "status": "running" })),
580///     )
581/// })?;
582/// match outcome {
583///     AppendOutcome::Appended { seq } => println!("appended at seq {seq}"),
584///     AppendOutcome::IdempotentReplay { prior } => println!("replayed seq {}", prior.seq),
585///     AppendOutcome::Conflict { prior } => println!("key reused; prior seq {}", prior.seq),
586/// }
587/// # Ok(())
588/// # }
589/// ```
590pub fn append_and_apply_idempotent<F>(
591    paths: &RunPaths,
592    witness: &LockedRun<'_>,
593    kind: &str,
594    node_id: Option<&NodeId>,
595    key: &str,
596    build: F,
597) -> Result<AppendOutcome>
598where
599    F: FnOnce(u64) -> Result<Value>,
600{
601    if key.is_empty() {
602        return Err(Error::EmptyIdempotencyKey);
603    }
604    // Catch the projections up to the log before scanning, mirroring
605    // `append_and_apply_unlocked`'s recovery half: an idempotent replay must
606    // only report once the prior event's projection is durably committed, never
607    // a stale "found, but not applied" result. A clean run makes this a no-op.
608    let events_path = paths.checked_events()?;
609    truncate_torn_tail(&events_path)?;
610    replay_unapplied(paths, &events_path)?;
611
612    // The sequence a fresh append *would* take. Computed once, after catch-up,
613    // so `build`'s payload sees the same seq `append_and_apply_unlocked` will
614    // assign under this still-held lock.
615    let next_seq = recover_last_seq(&events_path)? + 1;
616    let data = build(next_seq)?;
617
618    if let Some(prior) = find_prior_with_key(witness, paths, kind, key)? {
619        // A prior event carries this key. It is a true replay only when the
620        // full request identity — the envelope `node_id` *and* the `data`
621        // payload — matches; any divergence is a key reused for a different
622        // request and must surface as a conflict, never a silent no-op.
623        let same_node = prior.node_id.as_deref() == node_id.map(NodeId::as_str);
624        if same_node && prior.data == data {
625            return Ok(AppendOutcome::IdempotentReplay { prior });
626        }
627        return Ok(AppendOutcome::Conflict { prior });
628    }
629
630    let seq = append_and_apply_unlocked(witness, paths, kind, node_id, Some(key), data)?;
631    Ok(AppendOutcome::Appended { seq })
632}
633
634/// Replay every unapplied tail event — those with `seq > manifest.applied_seq`
635/// — into the projections, advancing the watermark after each, so the
636/// projection cache is caught up to `events.jsonl` before any new append.
637///
638/// This is the recovery half of the append+apply atomicity guarantee. A writer
639/// that crashed after fsyncing an event row but before fsyncing its projection
640/// (or before advancing `applied_seq`) leaves `applied_seq < last_seq`; the
641/// next lock acquisition heals it here. The reducer is idempotent — every
642/// `*.created` reducer short-circuits when its projection already exists, and
643/// every status/report reducer is a no-op once the target is terminal — so
644/// re-folding an event whose projection *did* land changes nothing. The
645/// manifest's denormalized counters can't desync across this replay either:
646/// they are not folded incrementally but re-derived from projection state by
647/// [`advance_applied_seq`] after each event, so a re-fold simply recomputes the
648/// same totals.
649///
650/// No manifest yet (pre-`run.created`) means there is no watermark to anchor
651/// and nothing durable to catch up, so this returns immediately until the
652/// manifest exists. A legacy manifest reads as `applied_seq = 0` (serde
653/// default), so the first call re-folds the entire log; that is intentional
654/// and safe — see [`crate::schema::Manifest::applied_seq`].
655///
656/// # Corrupt-line tolerance
657///
658/// A line that does not parse as an [`Event`] is skipped, not hard-errored —
659/// the same definition of "corrupt" the quarantine path uses, and the same
660/// tolerance the pre-watermark append path had (it only ever parsed the *last*
661/// line via [`recover_last_seq`]). Bricking every append on an interior poison
662/// line would, among other things, make it impossible to even *record* the
663/// supervisor's `event_log_skipped_line` diagnostic about that very line.
664/// Healing such a line is the supervisor's quarantine job, not the writer's.
665///
666/// A *parse-valid* event whose payload is semantically corrupt is skipped the
667/// same way (with a `warn`), rather than hard-erroring. The dangerous subclass
668/// is an event carrying an embedded id (`child_run_id`, `child_node_id`) that
669/// fails its strict `parse_str` and would
670/// otherwise be joined onto a path — the reducer's independent second line of
671/// defense against a corrupt log, a restored backup, or a future writer that
672/// bypasses the CLI validators (issue `reducer-path-traversal-defense`). Such
673/// an event is a *valid `Event` envelope* (only its `data` is bad), so the
674/// supervisor's [`quarantine_corrupt_lines`] — which only excises lines that
675/// fail the strict envelope parse — can never heal it; hard-erroring here would
676/// brick every future append on that line with no automated recovery path.
677/// Skipping it converges the projection to the largest safe subset and never
678/// joins a tainted id onto a path (the typed-id constructors already make
679/// traversal structurally impossible — a `"../escape"` id never parses into a
680/// [`RunId`](crate::RunId) / [`NodeId`](crate::NodeId), so it can never reach
681/// `nodes/<id>.json`). The append
682/// *gate* stays fail-closed: [`reduce_event_to_ops`] rejects such an event
683/// before it is ever written, so a sanctioned log never reaches this branch and
684/// re-reducing real events on replay is a clean idempotent no-op. A genuine I/O
685/// fault (from the commit or watermark write) still propagates.
686///
687/// Because a sanctioned log is appended in `seq` order under the lock, file
688/// order equals `seq` order for real events; the only out-of-order bytes are
689/// skipped junk, so advancing the watermark to each applied event's `seq` never
690/// jumps over an unfolded real event.
691///
692/// Caller must hold the run's [`RunLock`] and must have already truncated any
693/// torn tail, so the final line is either complete or absent.
694fn replay_unapplied(paths: &RunPaths, events_path: &Path) -> Result<()> {
695    let applied = match read_manifest_opt(paths)? {
696        Some(m) => m.applied_seq,
697        None => return Ok(()),
698    };
699    // Cheap fast path for the overwhelmingly common clean case: the watermark
700    // already covers the log, so there is nothing to replay and no full scan.
701    if applied >= recover_last_seq(events_path)? {
702        return Ok(());
703    }
704    let f = match std::fs::File::open(events_path) {
705        Ok(f) => f,
706        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
707        Err(e) => return Err(Error::io(events_path, e)),
708    };
709    let mut reader = PhysicalLineReader::new(BufReader::new(f));
710    while let Some(line) = reader.next_line().map_err(|e| Error::io(events_path, e))? {
711        // A torn final line is an uncommitted partial write — stop, exactly as
712        // every other reader does.
713        if !line.complete {
714            break;
715        }
716        if line.content.is_empty() {
717            continue;
718        }
719        // Skip a parse-failing line (external junk by the quarantine
720        // definition); apply every event past the watermark in order.
721        let ev: Event = match serde_json::from_slice(line.content) {
722            Ok(ev) => ev,
723            Err(_) => continue,
724        };
725        if ev.seq <= applied {
726            continue;
727        }
728        // Plan the projection writes. A parse-valid but domain-corrupt event —
729        // most dangerously one whose embedded id fails its strict `parse_str`
730        // and would otherwise be joined onto a path — surfaces here as
731        // `CorruptEventLog`. Quarantine cannot excise it (it is a valid
732        // envelope), so we skip it with a warn rather than aborting the whole
733        // catch-up replay; the watermark is not advanced for a skipped event.
734        // See this function's "Corrupt-line tolerance" doc. I/O faults from the
735        // commit/watermark write below still propagate.
736        let ops = match reduce_event_to_ops(paths, &ev) {
737            Ok(ops) => ops,
738            Err(Error::CorruptEventLog { reason, .. }) => {
739                tracing::warn!(
740                    target: "taskfleet_core::events",
741                    path = %events_path.display(),
742                    seq = ev.seq,
743                    kind = %ev.kind,
744                    reason = %reason,
745                    "skipping corrupt event during replay (unsafe id or malformed payload); projection not advanced for it"
746                );
747                continue;
748            }
749            Err(e) => return Err(e),
750        };
751        commit_ops(paths, ops)?;
752        advance_applied_seq(paths, ev.seq)?;
753    }
754    Ok(())
755}
756
757/// Advance `manifest.applied_seq` to `seq` and fsync the manifest (atomic
758/// temp-file + rename), recording that every projection touched by event `seq`
759/// is durably committed.
760///
761/// A no-op when no manifest exists yet, or when the watermark already covers
762/// `seq` — so re-folding an already-applied event (during replay) doesn't churn
763/// the manifest. The reducer for the event may itself have just rewritten the
764/// manifest (e.g. a status transition); reading it back here preserves those
765/// fields while moving only the watermark forward. Caller holds the [`RunLock`].
766///
767/// This is also the single point that persists the manifest's denormalized
768/// `node_count` counter. It is **derived**, not incremented: [`derive_counters`]
769/// recomputes it from the
770/// projection directories — which, because the caller commits an event's
771/// projection ops *before* calling this, already reflect event `seq`. Pinning
772/// the counters to the watermark advance is what makes them undriftable: even
773/// when a crash-replay re-folds an event whose reducer short-circuits to zero
774/// ops (its projection already landed before the crash), this still runs and
775/// re-derives the true counts, healing any counter the old incremental path
776/// would have stranded. See [`derive_counters`] and issue
777/// `manifest-counter-desync`.
778fn advance_applied_seq(paths: &RunPaths, seq: u64) -> Result<()> {
779    if let Some(mut m) = read_manifest_opt(paths)? {
780        if m.applied_seq < seq {
781            let counters = derive_counters(paths)?;
782            m.node_count = counters.node_count;
783            m.applied_seq = seq;
784            write_manifest(paths, &m)?;
785        }
786    }
787    Ok(())
788}
789
790/// One physical line surfaced by [`PhysicalLineReader`]: its content with
791/// any trailing terminator stripped, plus enough framing for the torn-tail
792/// policy (whether it was newline-terminated) and for error context (byte
793/// offset + 1-based line number).
794struct PhysicalLine<'a> {
795    /// Line content with a single trailing terminator (`\n`, optionally
796    /// preceded by `\r`) removed. Interior/leading bytes are untouched.
797    content: &'a [u8],
798    /// `false` only for a final line lacking a trailing `\n` — a torn,
799    /// in-flight append. `true` for every newline-terminated line. Because a
800    /// non-terminated line can only be the last bytes in the file, this is
801    /// `false` for at most one line, and only ever the last one.
802    complete: bool,
803    /// 1-based line number, for `CorruptEventLog` context.
804    lineno: u64,
805}
806
807/// The single physical-line reader behind both [`read_all_events`] and
808/// [`find_prior_with_key`], so the read paths can never disagree about the
809/// torn-tail policy (design.md §1.4; torn-line-policy-consistency).
810///
811/// Bytes are read with [`BufRead::read_until`] (not `read_line`/`lines()`)
812/// for two reasons: it keeps the trailing `\n` so a torn final line is
813/// distinguishable from a newline-terminated interior one, and it reads raw
814/// bytes so a torn tail that cuts a multi-byte UTF-8 sequence is tolerated as
815/// a partial write rather than surfacing as an I/O error. A *newline-
816/// terminated* line with invalid UTF-8 still reaches the caller's parse,
817/// which classifies it as `CorruptEventLog`.
818///
819/// `next_line` lends a slice into an internal buffer, so a caller holds at
820/// most one line at a time — the streaming (lending-iterator) pattern, which
821/// keeps the per-line allocation cost to a single reused buffer.
822struct PhysicalLineReader<R: BufRead> {
823    reader: R,
824    buf: Vec<u8>,
825    lineno: u64,
826    done: bool,
827}
828
829impl<R: BufRead> PhysicalLineReader<R> {
830    fn new(reader: R) -> Self {
831        Self {
832            reader,
833            buf: Vec::new(),
834            lineno: 0,
835            done: false,
836        }
837    }
838
839    /// Yield the next physical line, or `None` at end of file. I/O errors are
840    /// surfaced raw so the caller can attach the log path.
841    fn next_line(&mut self) -> std::io::Result<Option<PhysicalLine<'_>>> {
842        if self.done {
843            return Ok(None);
844        }
845        self.buf.clear();
846        let n = self.reader.read_until(b'\n', &mut self.buf)?;
847        if n == 0 {
848            self.done = true;
849            return Ok(None);
850        }
851        self.lineno += 1;
852        let complete = self.buf.last() == Some(&b'\n');
853        // A non-terminated line is necessarily the final bytes of the file;
854        // stop after handing it back so the torn-tail policy only ever sees
855        // it last.
856        if !complete {
857            self.done = true;
858        }
859        let len = trim_line_end(&self.buf).len();
860        Ok(Some(PhysicalLine {
861            content: &self.buf[..len],
862            complete,
863            lineno: self.lineno,
864        }))
865    }
866}
867
868/// Stream `events.jsonl` line by line, deserializing each complete line into a
869/// caller-chosen envelope probe `T` and invoking `visit(probe, raw_line)`.
870///
871/// This is the streaming counterpart to [`read_all_events`]: it shares the exact
872/// [`PhysicalLineReader`] torn-tail / [`Error::CorruptEventLog`] policy (a torn
873/// final line lacking a trailing `\n` is dropped *without* parsing even if its
874/// bytes are valid JSON; any newline-terminated unparseable line is interior
875/// corruption surfaced as [`Error::CorruptEventLog`]) but never materializes the
876/// whole log — the caller accumulates only what it needs into its own state.
877///
878/// `T` deserializes only the envelope fields it declares; serde ignores the
879/// rest, so a multi-KB `node.report` `data` payload is scanned but never
880/// allocated. The raw line bytes are *lent* to `visit` (a streaming
881/// lending-iterator borrow into the reader's reused buffer), so the closure can
882/// re-parse the full payload for the rare line it must materialize without the
883/// reader holding more than one line at a time.
884///
885/// A missing log is an empty stream (`Ok(())` with no calls). Caller must hold
886/// the run's [`RunLock`]; the scan is read-only over an append-only file.
887pub(crate) fn for_each_event_probe<T, F>(events_path: &Path, mut visit: F) -> Result<()>
888where
889    T: serde::de::DeserializeOwned,
890    F: FnMut(T, &[u8]) -> Result<()>,
891{
892    let f = match std::fs::File::open(events_path) {
893        Ok(f) => f,
894        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
895        Err(e) => return Err(Error::io(events_path, e)),
896    };
897    let mut reader = PhysicalLineReader::new(BufReader::new(f));
898    while let Some(line) = reader.next_line().map_err(|e| Error::io(events_path, e))? {
899        // Torn final line (no trailing newline): uncommitted partial write,
900        // discarded without parsing — mirrors `recover_last_seq`.
901        if !line.complete {
902            break;
903        }
904        if line.content.is_empty() {
905            continue;
906        }
907        let probe: T =
908            serde_json::from_slice(line.content).map_err(|e| Error::CorruptEventLog {
909                path: events_path.to_path_buf(),
910                reason: format!(
911                    "line {} is not a valid event: {} [{e}]",
912                    line.lineno,
913                    excerpt(line.content)
914                ),
915            })?;
916        visit(probe, line.content)?;
917    }
918    Ok(())
919}
920
921/// Read every event from `events.jsonl`. Used by tests and reducer replays.
922///
923/// # Torn-line policy
924///
925/// Built on the shared [`for_each_event_probe`](crate::events) (hence
926/// [`PhysicalLineReader`](crate::events)), so it matches
927/// [`find_prior_with_key`](crate::events) and [`recover_last_seq`] exactly: a
928/// torn final line lacking a trailing `\n` is an in-flight partial write,
929/// dropped *without* parsing even if its bytes happen to be valid JSON. Any
930/// newline-terminated line that fails to parse is interior corruption and
931/// surfaces as [`Error::CorruptEventLog`] — not a transient JSON fault — so a
932/// replay rejects a poisoned log loudly instead of silently dropping a line.
933pub fn read_all_events(events_path: &Path) -> Result<Vec<Event>> {
934    let mut out = Vec::new();
935    for_each_event_probe::<Event, _>(events_path, |ev, _raw| {
936        out.push(ev);
937        Ok(())
938    })?;
939    Ok(out)
940}
941
942/// Outcome of a [`quarantine_corrupt_lines`] call that removed at least one
943/// poison line. `backup_path` is the renamed copy of the original log (kept
944/// verbatim for operator forensics / hand-repair); `removed_byte_offsets`
945/// are the start offsets, in that original, of every newline-terminated line
946/// that failed to parse as an [`Event`] and was excised from the recovered
947/// `events.jsonl`.
948#[derive(Debug, Clone, Serialize)]
949pub struct Quarantine {
950    /// Path to the timestamped `.bak` holding the original poisoned log.
951    pub backup_path: PathBuf,
952    /// Byte offsets (in the original log) of every excised corrupt line.
953    pub removed_byte_offsets: Vec<u64>,
954}
955
956/// Heal a poisoned `events.jsonl` by excising its corrupt physical lines.
957///
958/// P2 made the supervisor *skip* a corrupt JSONL line in memory and keep
959/// tailing, but the bytes stayed on disk forever — so every fresh strict
960/// reader ([`read_all_events`] / a future `rebuild_projections`) still
961/// hard-errors on them, and the skip diagnostic is unreachable to a strict
962/// replay (the corrupt line aborts the read before it). This is the durable
963/// repair: under the run's [`RunLock`], the original log is renamed to
964/// `events.jsonl.corrupt-<ts>.bak` and a recovered `events.jsonl` is written
965/// in its place containing every line *except* the corrupt ones.
966///
967/// "Corrupt" means exactly what the strict readers reject: a
968/// newline-terminated, non-empty line that does not parse as a full [`Event`]
969/// envelope. Empty lines and a torn (newline-less) final line are retained
970/// verbatim — the readers already tolerate both, so excising them would be a
971/// behavior change, not a repair.
972///
973/// Returns `Ok(None)` when the log is missing or already clean (no rename, no
974/// rewrite — the common case is cheap: one read, no corrupt line found).
975/// Returns `Ok(Some(_))` with the backup path and removed offsets when at
976/// least one line was excised. Caller is expected to surface the outcome
977/// (e.g. a `supervisor.event_log_quarantined` diagnostic) and, for a live
978/// tail, restart its read cursor at offset 0 since every byte offset shifts.
979///
980/// `backup_ts` is supplied by the caller (kept out of core so the rename is
981/// deterministic in tests); a filename-safe basic-ISO stamp like
982/// `20260628T120000Z` is the intended form.
983///
984/// # Operator recovery
985///
986/// The excised bytes are never destroyed — they survive verbatim in the
987/// `events.jsonl.corrupt-<ts>.bak` sibling (named by the emitted
988/// `supervisor.event_log_quarantined { backup_path }` diagnostic). To recover
989/// a line the automated repair dropped: open the `.bak`, inspect the line(s)
990/// at the reported `removed_byte_offsets`, hand-fix any salvageable JSON, and —
991/// if you want the record back — stop the run's supervisor, append the
992/// corrected line to the live `events.jsonl` (or replace the file wholesale
993/// from a fixed copy of the backup), then restart the supervisor. The healed
994/// log is the source of truth; projections rebuild from it.
995pub fn quarantine_corrupt_lines(paths: &RunPaths, backup_ts: &str) -> Result<Option<Quarantine>> {
996    RunLock::with_lock(paths, |lock| {
997        quarantine_corrupt_lines_unlocked(lock, paths, backup_ts)
998    })
999}
1000
1001/// As [`quarantine_corrupt_lines`] but takes a `&LockedRun` witness proving the
1002/// caller already holds the run's exclusive [`RunLock`] — the sanctioned
1003/// lock-held composition path, mirroring [`append_and_apply_unlocked`].
1004/// Re-entering [`quarantine_corrupt_lines`] under a held lock would deadlock on
1005/// the second `flock` open.
1006pub fn quarantine_corrupt_lines_unlocked(
1007    _witness: &LockedRun<'_>,
1008    paths: &RunPaths,
1009    backup_ts: &str,
1010) -> Result<Option<Quarantine>> {
1011    // Guard the run root + event log against symlink redirection before the
1012    // rename/rewrite, exactly as the append path does.
1013    let events_path = paths.checked_events()?;
1014    let raw = match std::fs::read(&events_path) {
1015        Ok(b) => b,
1016        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1017        Err(e) => return Err(Error::io(&events_path, e)),
1018    };
1019
1020    // Walk physical lines, keeping the raw bytes (terminator included) of every
1021    // retained line so the recovered file is byte-identical save for the
1022    // excised corruption. A line is corrupt iff it is newline-terminated,
1023    // non-empty, and fails the same strict `Event` parse `read_all_events`
1024    // applies — so the recovered log is guaranteed to pass a strict replay.
1025    let mut recovered: Vec<u8> = Vec::with_capacity(raw.len());
1026    let mut removed_byte_offsets: Vec<u64> = Vec::new();
1027    let mut offset: u64 = 0;
1028    let mut i = 0usize;
1029    while i < raw.len() {
1030        let (line_end, complete) = match raw[i..].iter().position(|b| *b == b'\n') {
1031            Some(p) => (i + p + 1, true), // include the trailing '\n'
1032            None => (raw.len(), false),   // torn final line, no '\n'
1033        };
1034        let raw_line = &raw[i..line_end];
1035        let content = trim_line_end(raw_line);
1036        let corrupt =
1037            complete && !content.is_empty() && serde_json::from_slice::<Event>(content).is_err();
1038        if corrupt {
1039            removed_byte_offsets.push(offset);
1040        } else {
1041            recovered.extend_from_slice(raw_line);
1042        }
1043        offset += raw_line.len() as u64;
1044        i = line_end;
1045    }
1046
1047    if removed_byte_offsets.is_empty() {
1048        return Ok(None);
1049    }
1050
1051    // Rename the poisoned log aside (forensics), then atomically drop the
1052    // recovered log in its place. Order matters: the rename frees the path for
1053    // `write_atomic`'s tempfile+rename and preserves the original even if the
1054    // rewrite then fails.
1055    let backup_path = backup_path_for(&events_path, backup_ts);
1056    std::fs::rename(&events_path, &backup_path).map_err(|e| Error::io(&backup_path, e))?;
1057    write_atomic(&events_path, &recovered)?;
1058    Ok(Some(Quarantine {
1059        backup_path,
1060        removed_byte_offsets,
1061    }))
1062}
1063
1064/// Build the `events.jsonl.corrupt-<ts>.bak` sibling path for a quarantine
1065/// backup, preserving the original file name as a prefix.
1066fn backup_path_for(events_path: &Path, ts: &str) -> PathBuf {
1067    let mut name = events_path
1068        .file_name()
1069        .map(std::ffi::OsStr::to_os_string)
1070        .unwrap_or_default();
1071    name.push(format!(".corrupt-{ts}.bak"));
1072    events_path.with_file_name(name)
1073}
1074
1075/// A prior event located by [`find_prior_with_key`](crate::events). Carries enough to let
1076/// an idempotent-retry caller both return the recorded `seq` and verify the
1077/// retry payload matches what was originally written.
1078#[derive(Debug, Clone, PartialEq, Serialize)]
1079pub struct PriorEvent {
1080    /// The recorded `seq` of the matching event.
1081    pub seq: u64,
1082    /// The event's top-level `node_id`, if any.
1083    pub node_id: Option<String>,
1084    /// The event's `data` payload.
1085    pub data: Value,
1086}
1087
1088/// Fields skimmed from every line to test for a match without ever
1089/// allocating the (potentially large) `data` payload. `seq` is optional and
1090/// used only for best-effort error context — it is never a match key, so a
1091/// line missing it must not change whether a `kind` + `idempotency_key`
1092/// match is found.
1093#[derive(Deserialize)]
1094struct ProbeFields {
1095    #[serde(default)]
1096    seq: Option<u64>,
1097    kind: String,
1098    idempotency_key: Option<String>,
1099}
1100
1101/// Fields pulled from the one matching line, including the full payload.
1102#[derive(Deserialize)]
1103struct FullEventForReplay {
1104    seq: u64,
1105    node_id: Option<String>,
1106    data: Value,
1107}
1108
1109/// Maximum number of bytes from a malformed line to surface (escaped) in an
1110/// [`Error::CorruptEventLog`] reason.
1111const CORRUPT_LINE_EXCERPT_BYTES: usize = 100;
1112
1113/// Stream-scan `events.jsonl` for the first event with matching `kind` and
1114/// `idempotency_key`, returning a typed [`PriorEvent`] (or `None` when the
1115/// log is missing or holds no such event).
1116///
1117/// The skim parses each line's envelope (`kind` / `idempotency_key` / `seq`)
1118/// but never materializes `data` for non-matching lines; the full payload
1119/// (`node_id` plus `data`) is deserialized only for the one matching line.
1120/// JSON parsing still scans every byte of every line, so the scan is linear
1121/// in total log bytes under the lock — there is no payload-skipping shortcut.
1122///
1123/// # Torn-line policy
1124///
1125/// [`recover_last_seq`] tolerates a crash-truncated *final* line that lacks
1126/// a trailing newline and discards it regardless of whether its bytes
1127/// happen to form valid JSON. This scanner mirrors that exactly: a final
1128/// line with no trailing `\n` is treated as an in-flight partial write and
1129/// ignored — *before* any parse attempt — so the read (dedup) and write
1130/// (recovery) paths never disagree about whether that tail is committed.
1131///
1132/// Any *interior* line that fails to parse (it is newline-terminated, so a
1133/// later line follows) is a data-integrity fault, so it returns
1134/// [`Error::CorruptEventLog`] rather than silently skipping a line that
1135/// might carry the very key being looked up, which would let the caller
1136/// double-append. This is strictly *more* conservative than
1137/// `recover_last_seq` (which only inspects the last complete line) — a
1138/// deliberate choice for the dedup read.
1139///
1140/// Bytes are read with [`std::io::BufRead::read_until`] rather than
1141/// `read_line` so a torn tail that cuts a multi-byte UTF-8 sequence is
1142/// tolerated as a partial write (matching `recover_last_seq`) instead of
1143/// surfacing as an I/O error; a *newline-terminated* line containing
1144/// invalid UTF-8 is reported as `CorruptEventLog`, not I/O.
1145///
1146/// The `_witness: &LockedRun` is compile-time proof the caller holds the run's
1147/// exclusive [`RunLock`] — the scan is read-only, but it is only meaningful
1148/// fused with an append under one lock window (otherwise a concurrent retry can
1149/// see "no prior event" and double-append). The witness gates the public surface
1150/// so a caller cannot run the scan-then-append race: it must already hold the
1151/// lock to scan, and the same held lock covers the append it threads into
1152/// [`append_and_apply_unlocked`]. [`append_and_apply_idempotent`] fuses the two
1153/// for the common case; a caller that must interleave domain logic between the
1154/// scan and the append (e.g. `discussion resolve`'s already-resolved / no-op
1155/// precedence) calls this primitive directly under its own held lock.
1156pub fn find_prior_with_key(
1157    _witness: &LockedRun<'_>,
1158    paths: &RunPaths,
1159    kind: &str,
1160    idempotency_key: &str,
1161) -> Result<Option<PriorEvent>> {
1162    // Guard the run root + event log before reading: the idempotency scan
1163    // opens `events.jsonl` ahead of the append, so it must refuse a symlinked
1164    // log too rather than read through it.
1165    let events_path = paths.checked_events()?;
1166    let f = match std::fs::File::open(&events_path) {
1167        Ok(f) => f,
1168        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1169        Err(e) => return Err(Error::io(&events_path, e)),
1170    };
1171    let mut reader = PhysicalLineReader::new(BufReader::new(f));
1172    // `seq` of the last successfully-parsed line, for best-effort error
1173    // context pointing at where corruption begins.
1174    let mut last_good_seq: u64 = 0;
1175    while let Some(line) = reader.next_line().map_err(|e| Error::io(&events_path, e))? {
1176        // Mirror `recover_last_seq`: a final line lacking a trailing newline
1177        // is an uncommitted partial write, discarded WITHOUT parsing — even
1178        // if its bytes form valid JSON. Parsing it could otherwise return a
1179        // "match" for an event recovery considers unwritten, double-counting
1180        // the seq or skipping a real append.
1181        if !line.complete {
1182            break;
1183        }
1184        if line.content.is_empty() {
1185            continue;
1186        }
1187        let probe: ProbeFields =
1188            serde_json::from_slice(line.content).map_err(|e| Error::CorruptEventLog {
1189                path: events_path.clone(),
1190                reason: format!(
1191                    "line {} is not a valid event envelope (last good seq {last_good_seq}): \
1192                 {} [{e}]",
1193                    line.lineno,
1194                    excerpt(line.content),
1195                ),
1196            })?;
1197        if let Some(seq) = probe.seq {
1198            last_good_seq = seq;
1199        }
1200        if probe.kind != kind || probe.idempotency_key.as_deref() != Some(idempotency_key) {
1201            continue;
1202        }
1203        let full: FullEventForReplay =
1204            serde_json::from_slice(line.content).map_err(|e| Error::CorruptEventLog {
1205                path: events_path.clone(),
1206                reason: format!(
1207                    "line {} matched idempotency key but is not a replayable event: {} [{e}]",
1208                    line.lineno,
1209                    excerpt(line.content),
1210                ),
1211            })?;
1212        return Ok(Some(PriorEvent {
1213            seq: full.seq,
1214            node_id: full.node_id,
1215            data: full.data,
1216        }));
1217    }
1218    Ok(None)
1219}
1220
1221/// Strip a single trailing line terminator (`\n`, optionally preceded by
1222/// `\r`) from a raw line. Unlike `trim_end_matches`, this removes exactly
1223/// one terminator so interior/leading bytes are never altered.
1224fn trim_line_end(buf: &[u8]) -> &[u8] {
1225    let mut end = buf.len();
1226    if end > 0 && buf[end - 1] == b'\n' {
1227        end -= 1;
1228        if end > 0 && buf[end - 1] == b'\r' {
1229            end -= 1;
1230        }
1231    }
1232    &buf[..end]
1233}
1234
1235/// Render a bounded, escaped prefix of a malformed log line for inclusion
1236/// in an error message. Bytes are lossily decoded (a torn multi-byte tail
1237/// becomes the replacement char) and control characters are escaped so an
1238/// excerpt can't inject newlines or ANSI sequences into CLI output.
1239pub(crate) fn excerpt(line: &[u8]) -> String {
1240    let shown = &line[..line.len().min(CORRUPT_LINE_EXCERPT_BYTES)];
1241    let mut out: String = String::from_utf8_lossy(shown).escape_debug().to_string();
1242    if line.len() > CORRUPT_LINE_EXCERPT_BYTES {
1243        out.push('…');
1244    }
1245    out
1246}
1247
1248#[cfg(test)]
1249mod tests {
1250    use super::*;
1251    use crate::RunPaths;
1252    use serde_json::json;
1253    use tempfile::TempDir;
1254
1255    #[test]
1256    fn envelope_run_id_comes_from_paths_not_directory_basename() {
1257        // The whole point of storing run_id: even when the on-disk directory
1258        // name disagrees with the run id (symlinked/non-canonical root, the
1259        // original `root.file_name()` bug), the envelope must carry the stored
1260        // run_id verbatim — never the basename.
1261        let tmp = TempDir::new().unwrap();
1262        let dir = tmp.path().join("not-a-ulid-basename");
1263        std::fs::create_dir_all(&dir).unwrap();
1264        let run_id = "01jxsnap000000000000000000";
1265        let paths = RunPaths::new(dir, run_id).unwrap();
1266
1267        let r = append_and_apply_event(&paths, "run.status", None, None, serde_json::json!({}))
1268            .unwrap();
1269        assert_eq!(r.seq, 1);
1270
1271        let events = read_all_events(&paths.events()).unwrap();
1272        assert_eq!(events.len(), 1);
1273        assert_eq!(events[0].run_id.as_str(), run_id);
1274    }
1275
1276    #[cfg(unix)]
1277    #[test]
1278    fn append_rejects_a_symlinked_event_log() {
1279        // `events.jsonl` is the run's source of truth and highest-leverage
1280        // write — a symlinked log must be refused, not appended through.
1281        use crate::Error;
1282        use std::os::unix::fs::symlink;
1283        let tmp = TempDir::new().unwrap();
1284        let paths = fresh_run(&tmp);
1285        let target = tmp.path().join("evil-events.jsonl");
1286        symlink(&target, paths.events()).unwrap();
1287        let err = append_and_apply_event(&paths, "run.status", None, None, json!({})).unwrap_err();
1288        assert!(
1289            matches!(err, Error::SymlinkStateFile { name: "events", .. }),
1290            "got {err:?}"
1291        );
1292        // The forged append never reached the symlink target.
1293        assert!(!target.exists());
1294    }
1295
1296    /// Build a fresh, empty run directory with a valid `RunPaths` whose
1297    /// `run_id` matches the envelope the reducer will fold.
1298    fn fresh_run(tmp: &TempDir) -> RunPaths {
1299        let run_id = "01jxsnap000000000000000000";
1300        let dir = tmp.path().join(run_id);
1301        std::fs::create_dir_all(&dir).unwrap();
1302        RunPaths::new(dir, run_id).unwrap()
1303    }
1304
1305    /// Parse a `NodeId` for a test append call (the typed envelope id).
1306    fn nid(s: &str) -> NodeId {
1307        NodeId::parse_str(s).unwrap()
1308    }
1309
1310    /// Drive a run to a live node so reducer-affecting events have a target.
1311    fn bootstrap_live_node(paths: &RunPaths) {
1312        append_and_apply_event(
1313            paths,
1314            "run.created",
1315            None,
1316            None,
1317            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "fix" }),
1318        )
1319        .unwrap();
1320        append_and_apply_event(
1321            paths,
1322            "node.created",
1323            Some(&nid("n-0001")),
1324            None,
1325            serde_json::json!({ "kind": "spinoff" }),
1326        )
1327        .unwrap();
1328    }
1329
1330    #[test]
1331    fn append_and_apply_event_success_path_appends_and_folds() {
1332        let tmp = TempDir::new().unwrap();
1333        let paths = fresh_run(&tmp);
1334
1335        let r = append_and_apply_event(
1336            &paths,
1337            "run.created",
1338            None,
1339            None,
1340            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" }),
1341        )
1342        .unwrap();
1343        assert_eq!(r.seq, 1);
1344        assert!(!r.idempotent_replay);
1345        assert!(r.prior.is_none());
1346
1347        // The reducer ran under the same lock: the manifest projection exists.
1348        let m = crate::read_manifest(&paths).unwrap();
1349        assert_eq!(m.run_id.as_str(), paths.run_id.as_str());
1350    }
1351
1352    #[test]
1353    fn append_and_apply_idempotent_appended_path_returns_fresh_seq() {
1354        let tmp = TempDir::new().unwrap();
1355        let paths = fresh_run(&tmp);
1356        bootstrap_live_node(&paths); // seq 1 run.created, seq 2 node.created
1357
1358        let before = read_all_events(&paths.events()).unwrap().len();
1359        let data = json!({ "status": "running" });
1360        let outcome = RunLock::with_lock(&paths, |lock| {
1361            append_and_apply_idempotent(
1362                &paths,
1363                lock,
1364                "node.status",
1365                Some(&nid("n-0001")),
1366                "k1",
1367                |_seq| Ok(data.clone()),
1368            )
1369        })
1370        .unwrap();
1371        match outcome {
1372            AppendOutcome::Appended { seq } => {
1373                assert_eq!(seq, 3, "fresh append takes the next seq");
1374            }
1375            other => panic!("expected Appended, got {other:?}"),
1376        }
1377        assert_eq!(
1378            read_all_events(&paths.events()).unwrap().len(),
1379            before + 1,
1380            "a fresh key appends exactly one event"
1381        );
1382    }
1383
1384    #[test]
1385    fn append_and_apply_idempotent_replay_returns_prior_without_appending() {
1386        let tmp = TempDir::new().unwrap();
1387        let paths = fresh_run(&tmp);
1388        bootstrap_live_node(&paths);
1389        let node = nid("n-0001");
1390        let data = json!({ "status": "running" });
1391
1392        let first = RunLock::with_lock(&paths, |lock| {
1393            append_and_apply_idempotent(&paths, lock, "node.status", Some(&node), "k1", |_seq| {
1394                Ok(data.clone())
1395            })
1396        })
1397        .unwrap();
1398        let first_seq = match first {
1399            AppendOutcome::Appended { seq } => seq,
1400            other => panic!("expected Appended, got {other:?}"),
1401        };
1402        let after_first = read_all_events(&paths.events()).unwrap().len();
1403
1404        // Same kind + key + node + data → a true replay: nothing appended, the
1405        // prior event (its seq + data) is returned.
1406        let replay = RunLock::with_lock(&paths, |lock| {
1407            append_and_apply_idempotent(&paths, lock, "node.status", Some(&node), "k1", |_seq| {
1408                Ok(data.clone())
1409            })
1410        })
1411        .unwrap();
1412        match replay {
1413            AppendOutcome::IdempotentReplay { prior } => {
1414                assert_eq!(prior.seq, first_seq);
1415                assert_eq!(prior.node_id.as_deref(), Some("n-0001"));
1416                assert_eq!(prior.data, data);
1417            }
1418            other => panic!("expected IdempotentReplay, got {other:?}"),
1419        }
1420        assert_eq!(
1421            read_all_events(&paths.events()).unwrap().len(),
1422            after_first,
1423            "a replay must not append a new event"
1424        );
1425    }
1426
1427    #[test]
1428    fn append_and_apply_idempotent_conflict_on_different_data() {
1429        let tmp = TempDir::new().unwrap();
1430        let paths = fresh_run(&tmp);
1431        bootstrap_live_node(&paths);
1432        let node = nid("n-0001");
1433
1434        let first = RunLock::with_lock(&paths, |lock| {
1435            append_and_apply_idempotent(&paths, lock, "node.status", Some(&node), "k1", |_seq| {
1436                Ok(json!({ "status": "running" }))
1437            })
1438        })
1439        .unwrap();
1440        let first_seq = match first {
1441            AppendOutcome::Appended { seq } => seq,
1442            other => panic!("expected Appended, got {other:?}"),
1443        };
1444        let after_first = read_all_events(&paths.events()).unwrap().len();
1445
1446        // Same key, DIFFERENT payload → conflict, carrying the prior event's seq;
1447        // nothing new is appended.
1448        let conflict = RunLock::with_lock(&paths, |lock| {
1449            append_and_apply_idempotent(&paths, lock, "node.status", Some(&node), "k1", |_seq| {
1450                Ok(json!({ "status": "done" }))
1451            })
1452        })
1453        .unwrap();
1454        match conflict {
1455            AppendOutcome::Conflict { prior } => {
1456                assert_eq!(prior.seq, first_seq);
1457                assert_eq!(prior.data, json!({ "status": "running" }));
1458            }
1459            other => panic!("expected Conflict, got {other:?}"),
1460        }
1461        assert_eq!(
1462            read_all_events(&paths.events()).unwrap().len(),
1463            after_first,
1464            "a conflict must not append a new event"
1465        );
1466    }
1467
1468    #[test]
1469    fn append_and_apply_idempotent_conflict_on_different_node_id() {
1470        // Same key + same data but a different envelope node is still a reused
1471        // key for a different request → conflict, not a silent replay.
1472        let tmp = TempDir::new().unwrap();
1473        let paths = fresh_run(&tmp);
1474        bootstrap_live_node(&paths);
1475        // A second live node so the conflicting append targets a real node.
1476        append_and_apply_event(
1477            &paths,
1478            "node.created",
1479            Some(&nid("n-0002")),
1480            None,
1481            json!({ "kind": "spinoff" }),
1482        )
1483        .unwrap();
1484        let data = json!({ "status": "running" });
1485
1486        RunLock::with_lock(&paths, |lock| {
1487            append_and_apply_idempotent(
1488                &paths,
1489                lock,
1490                "node.status",
1491                Some(&nid("n-0001")),
1492                "k1",
1493                |_seq| Ok(data.clone()),
1494            )
1495        })
1496        .unwrap();
1497
1498        let conflict = RunLock::with_lock(&paths, |lock| {
1499            append_and_apply_idempotent(
1500                &paths,
1501                lock,
1502                "node.status",
1503                Some(&nid("n-0002")),
1504                "k1",
1505                |_seq| Ok(data.clone()),
1506            )
1507        })
1508        .unwrap();
1509        assert!(
1510            matches!(conflict, AppendOutcome::Conflict { prior } if prior.node_id.as_deref() == Some("n-0001")),
1511            "a node-id mismatch under the same key is a conflict"
1512        );
1513    }
1514
1515    #[test]
1516    fn append_and_apply_idempotent_rejects_empty_key() {
1517        let tmp = TempDir::new().unwrap();
1518        let paths = fresh_run(&tmp);
1519        bootstrap_live_node(&paths);
1520        let err = RunLock::with_lock(&paths, |lock| {
1521            append_and_apply_idempotent(
1522                &paths,
1523                lock,
1524                "node.status",
1525                Some(&nid("n-0001")),
1526                "",
1527                |_seq| Ok(json!({ "status": "running" })),
1528            )
1529        })
1530        .unwrap_err();
1531        assert!(matches!(err, Error::EmptyIdempotencyKey), "got {err:?}");
1532    }
1533
1534    #[test]
1535    fn append_and_apply_event_idempotent_replay_returns_prior_without_appending() {
1536        let tmp = TempDir::new().unwrap();
1537        let paths = fresh_run(&tmp);
1538        bootstrap_live_node(&paths);
1539
1540        let data = serde_json::json!({ "status": "running" });
1541        let first = append_and_apply_event(
1542            &paths,
1543            "node.status",
1544            Some(&nid("n-0001")),
1545            Some("k1"),
1546            data.clone(),
1547        )
1548        .unwrap();
1549        assert!(!first.idempotent_replay);
1550        let before = read_all_events(&paths.events()).unwrap().len();
1551
1552        // Same kind + key: a replay returns the prior event and appends nothing.
1553        let replay = append_and_apply_event(
1554            &paths,
1555            "node.status",
1556            Some(&nid("n-0001")),
1557            Some("k1"),
1558            data.clone(),
1559        )
1560        .unwrap();
1561        assert!(replay.idempotent_replay);
1562        assert!(
1563            !replay.applied,
1564            "an idempotent replay applies nothing this call (applied: false)"
1565        );
1566        assert_eq!(replay.seq, first.seq);
1567        let prior = replay.prior.expect("replay carries the prior event");
1568        assert_eq!(prior.node_id.as_deref(), Some("n-0001"));
1569        assert_eq!(prior.data, data);
1570        assert_eq!(
1571            read_all_events(&paths.events()).unwrap().len(),
1572            before,
1573            "replay must not append a new line"
1574        );
1575    }
1576
1577    #[test]
1578    fn append_and_apply_event_reducer_noop_is_still_a_success() {
1579        let tmp = TempDir::new().unwrap();
1580        let paths = fresh_run(&tmp);
1581        bootstrap_live_node(&paths);
1582
1583        // Settle the node terminal. A real state change → `applied: true`.
1584        let n0001 = nid("n-0001");
1585        let settle = append_and_apply_event(
1586            &paths,
1587            "node.report",
1588            Some(&n0001),
1589            None,
1590            serde_json::json!({ "success": true }),
1591        )
1592        .unwrap();
1593        assert!(
1594            settle.applied,
1595            "a report that terminalizes a live node applied a projection op"
1596        );
1597        assert_eq!(
1598            crate::read_node(&paths, &n0001).unwrap().status,
1599            crate::schema::Status::Done
1600        );
1601
1602        // A later status event is dropped by the terminal-state guard, but the
1603        // append still happened: the result names the appended event's seq and
1604        // is not a replay. The node stays Done. `applied` is FALSE — the reducer
1605        // planned zero ops (issue `reducer-adopt-explicit-merge`).
1606        let before = read_all_events(&paths.events()).unwrap().len();
1607        let r = append_and_apply_event(
1608            &paths,
1609            "node.status",
1610            Some(&n0001),
1611            None,
1612            serde_json::json!({ "status": "running" }),
1613        )
1614        .unwrap();
1615        assert!(!r.idempotent_replay);
1616        assert!(
1617            !r.applied,
1618            "a dead event dropped by the terminal guard reports applied: false"
1619        );
1620        assert_eq!(r.seq as usize, before + 1);
1621        assert_eq!(
1622            read_all_events(&paths.events()).unwrap().len(),
1623            before + 1,
1624            "the event is appended even when the reducer no-ops"
1625        );
1626        assert_eq!(
1627            crate::read_node(&paths, &n0001).unwrap().status,
1628            crate::schema::Status::Done,
1629            "terminal status is frozen"
1630        );
1631    }
1632
1633    #[test]
1634    fn bootstrap_advances_the_watermark_past_every_appended_event() {
1635        // Baseline for the replay tests: the normal append path keeps the
1636        // watermark pinned to the last appended seq, so `applied_seq == last`
1637        // whenever the log is clean.
1638        let tmp = TempDir::new().unwrap();
1639        let paths = fresh_run(&tmp);
1640        bootstrap_live_node(&paths); // seq 1 run.created, seq 2 node.created
1641        assert_eq!(
1642            crate::read_manifest(&paths).unwrap().applied_seq,
1643            2,
1644            "watermark tracks the last appended event"
1645        );
1646    }
1647
1648    #[test]
1649    fn append_replays_unapplied_tail_before_appending() {
1650        use crate::schema::Status;
1651        // Failure scenario 1: a reducer crash after the event-row fsync but
1652        // before the projection/watermark write leaves the log ahead of the
1653        // projections. The next lock acquisition must replay that tail.
1654        let tmp = TempDir::new().unwrap();
1655        let paths = fresh_run(&tmp);
1656        bootstrap_live_node(&paths); // applied_seq == 2, node n-0001 Pending
1657        let n0001 = nid("n-0001");
1658
1659        // Append a tail event (seq 3) WITHOUT running the reducer — exactly the
1660        // on-disk state a crash between the row fsync and the projection write
1661        // would leave behind. The raw append still needs the witness (lock held).
1662        RunLock::with_lock(&paths, |lock| {
1663            append_event_with_seq(
1664                lock,
1665                &paths,
1666                3,
1667                "node.status",
1668                Some(&n0001),
1669                None,
1670                json!({ "status": "running" }),
1671            )
1672        })
1673        .unwrap();
1674        assert_eq!(
1675            crate::read_node(&paths, &n0001).unwrap().status,
1676            Status::Pending,
1677            "the tail event's projection has not landed yet"
1678        );
1679        assert_eq!(crate::read_manifest(&paths).unwrap().applied_seq, 2);
1680
1681        // Any new append acquires the lock and replays seq 3 first, so the new
1682        // event takes seq 4 and the stale projection is healed.
1683        let r = append_and_apply_event(
1684            &paths,
1685            "run.status",
1686            None,
1687            None,
1688            json!({ "status": "running" }),
1689        )
1690        .unwrap();
1691        assert_eq!(r.seq, 4, "the new event follows the replayed tail");
1692        assert_eq!(
1693            crate::read_node(&paths, &n0001).unwrap().status,
1694            Status::Running,
1695            "the previously-unapplied tail event is now folded"
1696        );
1697        assert_eq!(
1698            crate::read_manifest(&paths).unwrap().applied_seq,
1699            4,
1700            "the watermark now covers the whole log"
1701        );
1702    }
1703
1704    #[test]
1705    fn legacy_manifest_without_applied_seq_migrates_on_next_write() {
1706        use crate::schema::Status;
1707        // A `manifest.json` written before `applied_seq` existed must read back
1708        // as 0 (serde default) and self-migrate on the next write via an
1709        // idempotent full replay — without double-counting counters or
1710        // resurrecting a terminal node (failure scenario 2's no-double-count
1711        // guarantee, exercised over the whole log).
1712        let tmp = TempDir::new().unwrap();
1713        let paths = fresh_run(&tmp);
1714        bootstrap_live_node(&paths);
1715        let n0001 = nid("n-0001");
1716        append_and_apply_event(
1717            &paths,
1718            "node.report",
1719            Some(&n0001),
1720            None,
1721            json!({ "success": true }),
1722        )
1723        .unwrap(); // seq 3 → node Done, applied_seq == 3, node_count == 1
1724
1725        // Rewrite the manifest WITHOUT an `applied_seq` field, mimicking a
1726        // pre-watermark binary's output.
1727        let mut mv: serde_json::Value =
1728            serde_json::from_slice(&std::fs::read(paths.manifest()).unwrap()).unwrap();
1729        assert!(mv.as_object_mut().unwrap().remove("applied_seq").is_some());
1730        std::fs::write(paths.manifest(), serde_json::to_vec_pretty(&mv).unwrap()).unwrap();
1731        assert_eq!(
1732            crate::read_manifest(&paths).unwrap().applied_seq,
1733            0,
1734            "a legacy manifest reads as applied_seq 0"
1735        );
1736
1737        // The next write triggers a full idempotent replay of seq 1..=3 (all
1738        // no-ops) and advances the watermark to last_seq.
1739        append_and_apply_event(
1740            &paths,
1741            "run.status",
1742            None,
1743            None,
1744            json!({ "status": "running" }),
1745        )
1746        .unwrap(); // seq 4
1747        let m = crate::read_manifest(&paths).unwrap();
1748        assert_eq!(m.applied_seq, 4, "watermark caught up to the log");
1749        assert_eq!(
1750            m.node_count, 1,
1751            "full replay did not double-count node_count"
1752        );
1753        assert_eq!(
1754            crate::read_node(&paths, &n0001).unwrap().status,
1755            Status::Done,
1756            "replaying its history did not resurrect the terminal node"
1757        );
1758    }
1759
1760    #[test]
1761    fn replay_skips_events_with_unsafe_ids_and_never_escapes_run_dir() {
1762        // Issue `reducer-path-traversal-defense`: the reducer must independently
1763        // defend against ids read from `events.jsonl` that bypass the CLI
1764        // validators — a corrupt log, a restored backup, or a future writer.
1765        // We craft a log straight onto disk (skipping the append gate) holding
1766        // two poison `child.spawned` lines (a traversal-laden and an empty
1767        // `child_run_id`) and one good one, then drive a catch-up replay and
1768        // assert: the poison events are skipped (not fatal) and the good event
1769        // still applies (its child ref lands on the parent node).
1770        let tmp = TempDir::new().unwrap();
1771        let paths = fresh_run(&tmp);
1772        bootstrap_live_node(&paths); // applied_seq == 2, node n-0001 live
1773
1774        // seq 3 — a traversal-laden `child_run_id`; seq 4 — an empty one. Both
1775        // fail their strict `parse_str`, so `reduce_event_to_ops` rejects them.
1776        // seq 5 — a well-formed pair that must be applied despite the poison
1777        // lines preceding it. All three raw appends share one held lock.
1778        let child_run = "02jxsnap000000000000000000";
1779        RunLock::with_lock(&paths, |lock| {
1780            append_event_with_seq(
1781                lock,
1782                &paths,
1783                3,
1784                "child.spawned",
1785                Some(&nid("n-0001")),
1786                None,
1787                json!({ "child_run_id": "../escape", "child_node_id": "n-0001" }),
1788            )?;
1789            append_event_with_seq(
1790                lock,
1791                &paths,
1792                4,
1793                "child.spawned",
1794                Some(&nid("n-0001")),
1795                None,
1796                json!({ "child_run_id": "", "child_node_id": "n-0001" }),
1797            )?;
1798            append_event_with_seq(
1799                lock,
1800                &paths,
1801                5,
1802                "child.spawned",
1803                Some(&nid("n-0001")),
1804                None,
1805                json!({ "child_run_id": child_run, "child_node_id": "n-0001" }),
1806            )
1807        })
1808        .unwrap();
1809
1810        // The poison lines must NOT abort the replay (the regression this fixes:
1811        // a `..`-laden id is a valid envelope quarantine can't excise, so a hard
1812        // error here would brick every future append on the run).
1813        replay_unapplied(&paths, &paths.events()).expect("poison lines skipped, not fatal");
1814
1815        // The good child.spawned landed: the parent node carries exactly one
1816        // child ref, and the two poison ids added nothing.
1817        let parent = crate::read_node(&paths, &nid("n-0001")).unwrap();
1818        assert_eq!(
1819            parent.children.len(),
1820            1,
1821            "only the good child ref was applied; poison ids added none"
1822        );
1823        assert_eq!(parent.children[0].run_id.as_str(), child_run);
1824        assert!(
1825            !paths.root.join("escape").exists(),
1826            "traversal id must never have been joined onto a path"
1827        );
1828
1829        // The watermark jumped past the skipped seqs to the applied good event.
1830        let m = crate::read_manifest(&paths).unwrap();
1831        assert_eq!(
1832            m.applied_seq, 5,
1833            "watermark advanced past the skipped poison"
1834        );
1835    }
1836
1837    #[test]
1838    fn node_count_desync_heals_on_replay() {
1839        // Faithful reproduction of issue `manifest-counter-desync`: a crash left
1840        // the node projection on disk but lost the follow-on manifest write (the
1841        // counter bump + watermark advance). Before the fix, the replay
1842        // short-circuited on the already-existing node and the stale counter
1843        // stuck forever; now the counter is re-derived at the watermark advance.
1844        let tmp = TempDir::new().unwrap();
1845        let paths = fresh_run(&tmp);
1846        bootstrap_live_node(&paths); // node n-0001 on disk, node_count == 1, applied_seq == 2
1847
1848        // Rewind the manifest to the exact mid-crash state: the node file
1849        // exists, but the manifest still shows the pre-node counter and a
1850        // watermark that sits before the `node.created` at seq 2.
1851        let mut m = crate::read_manifest(&paths).unwrap();
1852        assert_eq!(m.node_count, 1, "precondition: bootstrap counted the node");
1853        m.node_count = 0;
1854        m.applied_seq = 1;
1855        write_manifest(&paths, &m).unwrap();
1856
1857        // The next append acquires the lock, replays seq 2 (node already exists,
1858        // so the reducer plans zero ops), and re-derives the counter when it
1859        // advances the watermark past seq 2.
1860        append_and_apply_event(
1861            &paths,
1862            "run.status",
1863            None,
1864            None,
1865            json!({ "status": "running" }),
1866        )
1867        .unwrap();
1868
1869        let healed = crate::read_manifest(&paths).unwrap();
1870        assert_eq!(
1871            healed.node_count, 1,
1872            "node_count converged to the true projection count"
1873        );
1874        assert!(healed.applied_seq >= 2, "watermark caught up past the node");
1875    }
1876
1877    #[test]
1878    fn full_replay_does_not_double_count_any_counter() {
1879        // Idempotence across a full from-scratch replay: re-folding every event
1880        // must re-derive the same total, never accumulate. Covers `node_count`.
1881        let tmp = TempDir::new().unwrap();
1882        let paths = fresh_run(&tmp);
1883        bootstrap_live_node(&paths);
1884        append_and_apply_event(
1885            &paths,
1886            "node.created",
1887            Some(&nid("n-0002")),
1888            None,
1889            json!({ "kind": "spinoff" }),
1890        )
1891        .unwrap();
1892        let before = crate::read_manifest(&paths).unwrap();
1893        assert_eq!(before.node_count, 2, "precondition: two nodes");
1894
1895        // Reset the watermark to force a full idempotent replay of the whole log
1896        // on the next append (the legacy-migration path), and deliberately
1897        // corrupt the counter so a heal is observable.
1898        let mut m = before;
1899        m.applied_seq = 0;
1900        m.node_count = 99;
1901        write_manifest(&paths, &m).unwrap();
1902        append_and_apply_event(
1903            &paths,
1904            "run.status",
1905            None,
1906            None,
1907            json!({ "status": "running" }),
1908        )
1909        .unwrap();
1910
1911        let after = crate::read_manifest(&paths).unwrap();
1912        assert_eq!(
1913            after.node_count, 2,
1914            "counter re-derived to the true total — no double-count across full replay"
1915        );
1916    }
1917
1918    #[test]
1919    fn idempotent_replay_catches_up_projection_before_returning() {
1920        use crate::projections::write_manifest;
1921        use crate::schema::Status;
1922        use crate::write_node;
1923        // Requirement 3: an idempotency-key replay must ensure the projection is
1924        // caught up (`applied_seq >= prior.seq`) before returning the prior
1925        // envelope — never a "found, but not yet applied" result.
1926        let tmp = TempDir::new().unwrap();
1927        let paths = fresh_run(&tmp);
1928        bootstrap_live_node(&paths);
1929        let n0001 = nid("n-0001");
1930
1931        // A keyed event lands and folds normally...
1932        let first = append_and_apply_event(
1933            &paths,
1934            "node.status",
1935            Some(&n0001),
1936            Some("k1"),
1937            json!({ "status": "running" }),
1938        )
1939        .unwrap(); // seq 3
1940        assert!(!first.idempotent_replay);
1941
1942        // ...then simulate a crash that lost the fold: rewind the watermark
1943        // below seq 3 and revert the node to its pre-event Pending state.
1944        let mut m = crate::read_manifest(&paths).unwrap();
1945        m.applied_seq = 2;
1946        write_manifest(&paths, &m).unwrap();
1947        let mut n = crate::read_node(&paths, &n0001).unwrap();
1948        n.status = Status::Pending;
1949        write_node(&paths, &n).unwrap();
1950
1951        // The idempotent retry returns the prior seq AND catches the projection
1952        // up first.
1953        let replay = append_and_apply_event(
1954            &paths,
1955            "node.status",
1956            Some(&n0001),
1957            Some("k1"),
1958            json!({ "status": "running" }),
1959        )
1960        .unwrap();
1961        assert!(replay.idempotent_replay);
1962        assert_eq!(replay.seq, first.seq);
1963        assert!(
1964            crate::read_manifest(&paths).unwrap().applied_seq >= first.seq,
1965            "watermark caught up before the replay returned"
1966        );
1967        assert_eq!(
1968            crate::read_node(&paths, &n0001).unwrap().status,
1969            Status::Running,
1970            "the prior event's projection is durable before returning"
1971        );
1972    }
1973
1974    /// Build a `RunPaths` over a fresh tempdir and write `bytes` verbatim to
1975    /// `events.jsonl` — verbatim so a test can craft torn-line boundaries
1976    /// (a missing trailing `\n`) that the append path never produces.
1977    fn paths_with_events(tmp: &TempDir, bytes: &[u8]) -> RunPaths {
1978        let dir = tmp.path().join("run");
1979        std::fs::create_dir_all(&dir).unwrap();
1980        let paths = RunPaths::new(dir, "01jxsnap000000000000000000").unwrap();
1981        std::fs::write(paths.events(), bytes).unwrap();
1982        paths
1983    }
1984
1985    /// Run [`find_prior_with_key`] under a freshly-acquired exclusive lock —
1986    /// the witness it now requires. The scan is read-only, so taking the lock
1987    /// just to mint the witness is exactly what a real caller does.
1988    fn scan(paths: &RunPaths, kind: &str, key: &str) -> Result<Option<PriorEvent>> {
1989        RunLock::with_lock(paths, |w| find_prior_with_key(w, paths, kind, key))
1990    }
1991
1992    #[test]
1993    fn find_prior_with_key_missing_log_is_none() {
1994        let tmp = TempDir::new().unwrap();
1995        let dir = tmp.path().join("run");
1996        std::fs::create_dir_all(&dir).unwrap();
1997        let paths = RunPaths::new(dir, "01jxsnap000000000000000000").unwrap();
1998        // No events.jsonl written at all.
1999        let got = scan(&paths, "node.report", "k1").unwrap();
2000        assert!(got.is_none());
2001    }
2002
2003    #[test]
2004    fn find_prior_with_key_finds_the_matching_line() {
2005        let tmp = TempDir::new().unwrap();
2006        let log = concat!(
2007            r#"{"seq":1,"kind":"node.status","idempotency_key":"k0","node_id":"n-1","data":{}}"#,
2008            "\n",
2009            r#"{"seq":2,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{"ok":true}}"#,
2010            "\n",
2011        );
2012        let paths = paths_with_events(&tmp, log.as_bytes());
2013        let got = scan(&paths, "node.report", "k1").unwrap().expect("match");
2014        assert_eq!(got.seq, 2);
2015        assert_eq!(got.node_id.as_deref(), Some("n-1"));
2016        assert_eq!(got.data, serde_json::json!({"ok": true}));
2017    }
2018
2019    #[test]
2020    fn find_prior_with_key_no_match_is_none() {
2021        let tmp = TempDir::new().unwrap();
2022        let log = concat!(
2023            r#"{"seq":1,"kind":"node.report","idempotency_key":"other","node_id":"n-1","data":{}}"#,
2024            "\n",
2025        );
2026        let paths = paths_with_events(&tmp, log.as_bytes());
2027        assert!(scan(&paths, "node.report", "k1").unwrap().is_none());
2028    }
2029
2030    #[test]
2031    fn find_prior_with_key_tolerates_torn_final_line() {
2032        // A complete record, then a crash-truncated final line with NO
2033        // trailing newline — exactly what `recover_last_seq` tolerates.
2034        // The scan must still return the earlier match and never error.
2035        let tmp = TempDir::new().unwrap();
2036        let mut log = String::new();
2037        log.push_str(
2038            r#"{"seq":1,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{"ok":true}}"#,
2039        );
2040        log.push('\n');
2041        log.push_str(r#"{"seq":2,"kind":"node.rep"#); // torn mid-write, no newline
2042        let paths = paths_with_events(&tmp, log.as_bytes());
2043
2044        let got = scan(&paths, "node.report", "k1")
2045            .unwrap()
2046            .expect("match before the torn tail");
2047        assert_eq!(got.seq, 1);
2048
2049        // A torn final line with no matching key ahead of it returns None,
2050        // not an error.
2051        let tmp2 = TempDir::new().unwrap();
2052        let paths2 = paths_with_events(&tmp2, br#"{"seq":1,"kind":"node.rep"#);
2053        assert!(scan(&paths2, "node.report", "k1").unwrap().is_none());
2054    }
2055
2056    #[test]
2057    fn find_prior_with_key_ignores_valid_json_final_line_without_newline() {
2058        // The dangerous case: a crash landed a COMPLETE, valid-JSON event
2059        // but the trailing newline never flushed. `recover_last_seq`
2060        // discards any newline-less tail, so it considers this event
2061        // unwritten (returns 0). The dedup scan MUST agree and return None
2062        // — otherwise it would report "already appended", the caller skips
2063        // the append, and the event is lost / the seq double-counts.
2064        let tmp = TempDir::new().unwrap();
2065        let line =
2066            br#"{"seq":1,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{}}"#;
2067        let paths = paths_with_events(&tmp, line);
2068        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 0);
2069        assert!(
2070            scan(&paths, "node.report", "k1").unwrap().is_none(),
2071            "torn tail must be ignored even when it parses as valid JSON"
2072        );
2073    }
2074
2075    #[test]
2076    fn find_prior_with_key_skips_nonmatching_line_missing_seq() {
2077        // `seq` is not a match key, so a NON-matching envelope that happens
2078        // to lack `seq` must be skimmed past, not treated as corruption that
2079        // aborts the scan before a later match. (The pre-lift scanner's
2080        // probe didn't require `seq`; making it required would have been a
2081        // regression that hid a real key behind an unrelated seq-less line.)
2082        let tmp = TempDir::new().unwrap();
2083        let log = concat!(
2084            r#"{"kind":"node.status","idempotency_key":"other","node_id":"n-1","data":{}}"#,
2085            "\n",
2086            r#"{"seq":2,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{"ok":true}}"#,
2087            "\n",
2088        );
2089        let paths = paths_with_events(&tmp, log.as_bytes());
2090        let got = scan(&paths, "node.report", "k1")
2091            .unwrap()
2092            .expect("match after a seq-less non-matching line");
2093        assert_eq!(got.seq, 2);
2094        assert_eq!(got.node_id.as_deref(), Some("n-1"));
2095    }
2096
2097    #[test]
2098    fn find_prior_with_key_matched_line_bad_payload_is_corrupt_log() {
2099        // A line that skims fine (kind + key match) but whose full payload
2100        // is malformed (`node_id` is a number, not a string) is event-log
2101        // corruption — it must surface as CorruptEventLog (exit 1), not a
2102        // generic JSON/io error (exit 2).
2103        let tmp = TempDir::new().unwrap();
2104        let log = concat!(
2105            r#"{"seq":1,"kind":"node.report","idempotency_key":"k1","node_id":42,"data":{}}"#,
2106            "\n",
2107        );
2108        let paths = paths_with_events(&tmp, log.as_bytes());
2109        let err = scan(&paths, "node.report", "k1").unwrap_err();
2110        assert!(
2111            matches!(err, Error::CorruptEventLog { .. }),
2112            "expected CorruptEventLog, got {err:?}"
2113        );
2114    }
2115
2116    #[test]
2117    fn find_prior_with_key_handles_crlf_line_endings() {
2118        let tmp = TempDir::new().unwrap();
2119        let log = concat!(
2120            r#"{"seq":1,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{}}"#,
2121            "\r\n",
2122        );
2123        let paths = paths_with_events(&tmp, log.as_bytes());
2124        let got = scan(&paths, "node.report", "k1")
2125            .unwrap()
2126            .expect("CRLF-terminated match");
2127        assert_eq!(got.seq, 1);
2128    }
2129
2130    #[test]
2131    fn find_prior_with_key_tolerates_partial_utf8_torn_tail() {
2132        // A crash can cut a multi-byte UTF-8 sequence mid-character. With
2133        // byte-oriented reading this torn (newline-less) tail is tolerated
2134        // like any other partial write, not surfaced as an I/O error.
2135        let tmp = TempDir::new().unwrap();
2136        let mut log = Vec::new();
2137        log.extend_from_slice(
2138            br#"{"seq":1,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{}}"#,
2139        );
2140        log.push(b'\n');
2141        log.extend_from_slice(&[0xF0, 0x9F]); // start of a 4-byte char, truncated
2142        let paths = paths_with_events(&tmp, &log);
2143        let got = scan(&paths, "node.report", "k1")
2144            .unwrap()
2145            .expect("match before the partial-UTF8 tail");
2146        assert_eq!(got.seq, 1);
2147    }
2148
2149    #[test]
2150    fn recover_last_seq_newline_terminated_garbage_is_corrupt_log() {
2151        // Consistency guard with find_prior_with_key: a newline-terminated
2152        // final line that isn't valid JSON is CorruptEventLog from BOTH
2153        // readers, so the CLI maps both to the same corrupt-event-log exit.
2154        let tmp = TempDir::new().unwrap();
2155        let paths = paths_with_events(&tmp, b"{not json at all\n");
2156        let err = recover_last_seq(&paths.events()).unwrap_err();
2157        assert!(
2158            matches!(err, Error::CorruptEventLog { .. }),
2159            "expected CorruptEventLog, got {err:?}"
2160        );
2161    }
2162
2163    #[test]
2164    fn rejected_event_is_not_appended() {
2165        // The transactional fix: a reducer-rejected event must error BEFORE
2166        // any durable write, so events.jsonl never gains a poison line.
2167        let tmp = TempDir::new().unwrap();
2168        let paths = fresh_run(&tmp);
2169        bootstrap_live_node(&paths);
2170        let before = read_all_events(&paths.events()).unwrap().len();
2171
2172        // `node.report` with neither success nor cancelled → reducer rejects.
2173        let err =
2174            append_and_apply_event(&paths, "node.report", Some(&nid("n-0001")), None, json!({}))
2175                .unwrap_err();
2176        assert!(matches!(err, Error::CorruptEventLog { .. }), "got {err:?}");
2177
2178        assert_eq!(
2179            read_all_events(&paths.events()).unwrap().len(),
2180            before,
2181            "a rejected event must not be appended"
2182        );
2183        // The log is still clean and re-readable (no poison line stranded it).
2184        assert!(recover_last_seq(&paths.events()).is_ok());
2185        let next = append_and_apply_event(
2186            &paths,
2187            "node.report",
2188            Some(&nid("n-0001")),
2189            None,
2190            json!({ "success": true }),
2191        )
2192        .unwrap();
2193        assert_eq!(
2194            next.seq as usize,
2195            before + 1,
2196            "the next valid append reuses the seq the rejected event never consumed"
2197        );
2198    }
2199
2200    #[test]
2201    fn validate_event_agrees_with_apply_event() {
2202        // Drift guard: `validate_event` (the pre-append gate) must return Err
2203        // in EXACTLY the cases `apply_event` would, for the same state — else
2204        // it would refuse a harmless no-op or let a poison line through.
2205        use crate::reducer::{apply_event, validate_event};
2206
2207        fn ev(paths: &RunPaths, kind: &str, node_id: Option<&str>, data: Value) -> Event {
2208            Event {
2209                ts: Utc::now(),
2210                seq: 999,
2211                kind: kind.to_string(),
2212                run_id: paths.run_id.clone(),
2213                node_id: node_id.map(|s| crate::schema::NodeId::parse_str(s).unwrap()),
2214                idempotency_key: None,
2215                data,
2216            }
2217        }
2218        // validate is read-only, so running it first leaves apply's pre-state
2219        // intact; we compare the two verdicts on the same fresh run.
2220        fn agree(paths: &RunPaths, e: &Event, label: &str) {
2221            let v = validate_event(paths, e).is_err();
2222            let a = apply_event(paths, e).is_err();
2223            assert_eq!(v, a, "{label}: validate_err={v} apply_err={a}");
2224        }
2225
2226        // Live node: bad report rejected; good report accepted; missing
2227        // node_id rejected; bad status rejected.
2228        {
2229            let tmp = TempDir::new().unwrap();
2230            let paths = fresh_run(&tmp);
2231            bootstrap_live_node(&paths);
2232            agree(
2233                &paths,
2234                &ev(&paths, "node.report", Some("n-0001"), json!({})),
2235                "report-bare",
2236            );
2237        }
2238        {
2239            let tmp = TempDir::new().unwrap();
2240            let paths = fresh_run(&tmp);
2241            bootstrap_live_node(&paths);
2242            agree(
2243                &paths,
2244                &ev(
2245                    &paths,
2246                    "node.report",
2247                    Some("n-0001"),
2248                    json!({ "success": true }),
2249                ),
2250                "report-good",
2251            );
2252        }
2253        {
2254            let tmp = TempDir::new().unwrap();
2255            let paths = fresh_run(&tmp);
2256            bootstrap_live_node(&paths);
2257            agree(
2258                &paths,
2259                &ev(&paths, "node.report", None, json!({})),
2260                "report-no-node-id",
2261            );
2262        }
2263        {
2264            let tmp = TempDir::new().unwrap();
2265            let paths = fresh_run(&tmp);
2266            bootstrap_live_node(&paths);
2267            agree(
2268                &paths,
2269                &ev(&paths, "node.status", Some("n-0001"), json!({})),
2270                "status-missing",
2271            );
2272        }
2273        // Terminal node: a malformed report is a clean no-op (guard before
2274        // validate) — both must accept it.
2275        {
2276            let tmp = TempDir::new().unwrap();
2277            let paths = fresh_run(&tmp);
2278            bootstrap_live_node(&paths);
2279            append_and_apply_event(
2280                &paths,
2281                "node.report",
2282                Some(&nid("n-0001")),
2283                None,
2284                json!({ "success": true }),
2285            )
2286            .unwrap();
2287            agree(
2288                &paths,
2289                &ev(&paths, "node.report", Some("n-0001"), json!({})),
2290                "report-bare-on-terminal",
2291            );
2292        }
2293        // Missing node: a status with no `status` field is a no-op.
2294        {
2295            let tmp = TempDir::new().unwrap();
2296            let paths = fresh_run(&tmp);
2297            agree(
2298                &paths,
2299                &ev(&paths, "node.status", Some("n-0001"), json!({})),
2300                "status-missing-node",
2301            );
2302        }
2303        // Existing manifest: a run.status with no `status` is rejected.
2304        {
2305            let tmp = TempDir::new().unwrap();
2306            let paths = fresh_run(&tmp);
2307            bootstrap_live_node(&paths);
2308            agree(
2309                &paths,
2310                &ev(&paths, "run.status", None, json!({})),
2311                "run-status-missing",
2312            );
2313        }
2314        // Open discussion: a resolve without `resolution` is rejected.
2315        {
2316            let tmp = TempDir::new().unwrap();
2317            let paths = fresh_run(&tmp);
2318            bootstrap_live_node(&paths);
2319            append_and_apply_event(
2320                &paths,
2321                "discussion.opened",
2322                Some(&nid("n-0001")),
2323                None,
2324                json!({ "discussion_id": "d-abcdefghij", "topic": "t", "node_id": "n-0001" }),
2325            )
2326            .unwrap();
2327            agree(
2328                &paths,
2329                &ev(
2330                    &paths,
2331                    "discussion.resolved",
2332                    None,
2333                    json!({ "discussion_id": "d-abcdefghij" }),
2334                ),
2335                "resolve-missing-resolution",
2336            );
2337        }
2338        // node.created: new node missing `kind` rejected; replay over an
2339        // existing node with bad payload is a no-op (existence short-circuit).
2340        {
2341            let tmp = TempDir::new().unwrap();
2342            let paths = fresh_run(&tmp);
2343            agree(
2344                &paths,
2345                &ev(&paths, "node.created", Some("n-0002"), json!({})),
2346                "node-created-missing-kind",
2347            );
2348        }
2349        {
2350            let tmp = TempDir::new().unwrap();
2351            let paths = fresh_run(&tmp);
2352            bootstrap_live_node(&paths);
2353            agree(
2354                &paths,
2355                &ev(&paths, "node.created", Some("n-0001"), json!({})),
2356                "node-created-replay-bad-payload",
2357            );
2358        }
2359        // discussion.opened missing `topic`.
2360        {
2361            let tmp = TempDir::new().unwrap();
2362            let paths = fresh_run(&tmp);
2363            bootstrap_live_node(&paths);
2364            agree(
2365                &paths,
2366                &ev(
2367                    &paths,
2368                    "discussion.opened",
2369                    Some("n-0001"),
2370                    json!({ "discussion_id": "d-abcdefghij", "node_id": "n-0001" }),
2371                ),
2372                "discussion-opened-missing-topic",
2373            );
2374        }
2375        // spinoff.proposed missing `proposed_title`; spinoff.{approved,rejected}
2376        // with an unparseable proposal id.
2377        {
2378            let tmp = TempDir::new().unwrap();
2379            let paths = fresh_run(&tmp);
2380            bootstrap_live_node(&paths);
2381            agree(
2382                &paths,
2383                &ev(
2384                    &paths,
2385                    "spinoff.proposed",
2386                    Some("n-0001"),
2387                    json!({ "proposal_id": "p-abcdefghij", "proposed_kind": "spinoff", "node_id": "n-0001" }),
2388                ),
2389                "spinoff-proposed-missing-title",
2390            );
2391        }
2392        {
2393            let tmp = TempDir::new().unwrap();
2394            let paths = fresh_run(&tmp);
2395            agree(
2396                &paths,
2397                &ev(
2398                    &paths,
2399                    "spinoff.approved",
2400                    None,
2401                    json!({ "proposal_id": "not a valid id" }),
2402                ),
2403                "spinoff-approved-bad-id",
2404            );
2405            agree(
2406                &paths,
2407                &ev(
2408                    &paths,
2409                    "spinoff.rejected",
2410                    None,
2411                    json!({ "proposal_id": "not a valid id" }),
2412                ),
2413                "spinoff-rejected-bad-id",
2414            );
2415        }
2416        // child.spawned: missing/invalid child_run_id.
2417        {
2418            let tmp = TempDir::new().unwrap();
2419            let paths = fresh_run(&tmp);
2420            agree(
2421                &paths,
2422                &ev(&paths, "child.spawned", Some("n-0001"), json!({})),
2423                "child-spawned-missing-child-run-id",
2424            );
2425            agree(
2426                &paths,
2427                &ev(
2428                    &paths,
2429                    "child.spawned",
2430                    Some("n-0001"),
2431                    json!({ "child_run_id": "bad" }),
2432                ),
2433                "child-spawned-bad-child-run-id",
2434            );
2435        }
2436        // Cross-run envelope and unknown kind.
2437        {
2438            let tmp = TempDir::new().unwrap();
2439            let paths = fresh_run(&tmp);
2440            let mut foreign = ev(&paths, "run.status", None, json!({ "status": "running" }));
2441            foreign.run_id = crate::schema::RunId::parse_str("02jxsnap000000000000000000").unwrap();
2442            agree(&paths, &foreign, "cross-run");
2443            agree(
2444                &paths,
2445                &ev(&paths, "totally.unknown", None, json!({})),
2446                "unknown-kind",
2447            );
2448        }
2449    }
2450
2451    #[test]
2452    fn read_all_events_drops_torn_final_line() {
2453        // The bug this fixes: `read_all_events` used to silently ACCEPT a
2454        // valid-JSON final line lacking a trailing newline — a line
2455        // `recover_last_seq` discards as an uncommitted partial write. Now it
2456        // shares the torn-tail policy: the torn final line is dropped without
2457        // error, and the reader agrees with `recover_last_seq`.
2458        let tmp = TempDir::new().unwrap();
2459        let mut log = String::new();
2460        log.push_str(
2461            r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2462        );
2463        log.push('\n');
2464        // A COMPLETE, valid-JSON event whose trailing newline never flushed.
2465        log.push_str(
2466            r#"{"ts":"2026-06-12T00:00:00Z","seq":2,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2467        );
2468        let paths = paths_with_events(&tmp, log.as_bytes());
2469
2470        let events = read_all_events(&paths.events()).unwrap();
2471        assert_eq!(
2472            events.iter().map(|e| e.seq).collect::<Vec<_>>(),
2473            vec![1],
2474            "torn final line must be dropped, not parsed"
2475        );
2476        // And it agrees with the recovery path.
2477        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 1);
2478    }
2479
2480    #[test]
2481    fn recover_last_seq_rejects_seq_only_last_line() {
2482        // A `\n`-terminated last line that is valid JSON with a `seq` but is
2483        // NOT a valid event envelope (missing ts/kind/run_id) must be rejected
2484        // by recover_last_seq, matching read_all_events — otherwise an append
2485        // would continue past a line replay can never fold.
2486        let tmp = TempDir::new().unwrap();
2487        let paths = paths_with_events(&tmp, b"{\"seq\":99}\n");
2488        let err = recover_last_seq(&paths.events()).unwrap_err();
2489        assert!(matches!(err, Error::CorruptEventLog { .. }), "got {err:?}");
2490        // And the forward reader agrees.
2491        assert!(matches!(
2492            read_all_events(&paths.events()).unwrap_err(),
2493            Error::CorruptEventLog { .. }
2494        ));
2495    }
2496
2497    #[test]
2498    fn recover_last_seq_skips_multiple_trailing_blank_lines() {
2499        // External editing can leave several trailing blank lines. The forward
2500        // reader skips them; seq recovery must walk back over all of them to
2501        // the last real record (not just one), so the two readers agree.
2502        let tmp = TempDir::new().unwrap();
2503        let mut log = String::new();
2504        log.push_str(
2505            r#"{"ts":"2026-06-12T00:00:00Z","seq":7,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2506        );
2507        log.push_str("\n\n\n\n");
2508        let paths = paths_with_events(&tmp, log.as_bytes());
2509        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 7);
2510        let events = read_all_events(&paths.events()).unwrap();
2511        assert_eq!(events.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![7]);
2512    }
2513
2514    #[test]
2515    fn recover_last_seq_skips_trailing_whitespace_only_lines() {
2516        // External editing can leave trailing lines holding only spaces, tabs,
2517        // or stray CRs. Recovery must walk back over every whitespace-only line
2518        // to the last real record, not stop at (and fail to parse) the blanks.
2519        let tmp = TempDir::new().unwrap();
2520        let mut log = String::new();
2521        log.push_str(
2522            r#"{"ts":"2026-06-12T00:00:00Z","seq":5,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2523        );
2524        log.push_str("\n  \n\t\n \r\n");
2525        let paths = paths_with_events(&tmp, log.as_bytes());
2526        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 5);
2527    }
2528
2529    #[test]
2530    fn recover_last_seq_all_whitespace_file_is_zero() {
2531        // A log holding only blank/whitespace lines carries no event — recovery
2532        // returns the zero-event sentinel rather than erroring on the blanks.
2533        let tmp = TempDir::new().unwrap();
2534        let paths = paths_with_events(&tmp, b"\n  \n\t\n \r\n");
2535        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 0);
2536    }
2537
2538    #[test]
2539    fn recover_last_seq_single_newline_terminated_record_is_regression_guard() {
2540        // The common, healthy case: one record with a single trailing newline
2541        // must still recover its seq unchanged after the blank-line tolerance.
2542        let tmp = TempDir::new().unwrap();
2543        let paths = paths_with_events(
2544            &tmp,
2545            concat!(
2546                r#"{"ts":"2026-06-12T00:00:00Z","seq":5,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2547                "\n",
2548            )
2549            .as_bytes(),
2550        );
2551        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 5);
2552    }
2553
2554    #[test]
2555    fn read_all_events_rejects_corrupt_middle_line() {
2556        // A newline-terminated garbage line FOLLOWED by another line is
2557        // interior corruption — a hard `CorruptEventLog`, never a silent skip.
2558        let tmp = TempDir::new().unwrap();
2559        let log = concat!(
2560            r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2561            "\n",
2562            "{not valid json at all\n",
2563            r#"{"ts":"2026-06-12T00:00:00Z","seq":3,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2564            "\n",
2565        );
2566        let paths = paths_with_events(&tmp, log.as_bytes());
2567        let err = read_all_events(&paths.events()).unwrap_err();
2568        match err {
2569            Error::CorruptEventLog { reason, .. } => {
2570                assert!(reason.contains("line 2"), "reason was: {reason}");
2571            }
2572            other => panic!("expected CorruptEventLog, got {other:?}"),
2573        }
2574    }
2575
2576    #[test]
2577    fn append_truncates_torn_tail_before_writing() {
2578        // A crash left a valid record then a torn (newline-less) partial
2579        // write. The next append must truncate the torn bytes BEFORE writing,
2580        // so the log never gains a `…torn…{"seq":N}` malformed line.
2581        let tmp = TempDir::new().unwrap();
2582        let mut bytes = Vec::new();
2583        bytes.extend_from_slice(
2584            br#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2585        );
2586        bytes.push(b'\n');
2587        bytes.extend_from_slice(br#"{"seq":2,"kind":"TORN_PARTIAL_NEVER_FLUSHED"#); // no newline
2588        let paths = paths_with_events(&tmp, &bytes);
2589
2590        // The torn tail is ignored for seq recovery (last complete seq = 1).
2591        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 1);
2592
2593        // `marker` is an unknown kind → reducer no-op, so the append succeeds
2594        // without any projection prerequisites.
2595        let r = append_and_apply_event(&paths, "marker", None, None, serde_json::json!({"x": 1}))
2596            .unwrap();
2597        assert_eq!(r.seq, 2, "seq continues from the last complete record");
2598
2599        let raw = std::fs::read(paths.events()).unwrap();
2600        assert!(
2601            raw.ends_with(b"\n"),
2602            "log must be newline-terminated after a clean append"
2603        );
2604        assert!(
2605            !String::from_utf8_lossy(&raw).contains("TORN_PARTIAL_NEVER_FLUSHED"),
2606            "the torn tail must be truncated away before the append"
2607        );
2608        let events = read_all_events(&paths.events()).unwrap();
2609        assert_eq!(events.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![1, 2]);
2610    }
2611
2612    #[test]
2613    fn append_truncates_all_torn_file_to_empty_then_writes_seq_1() {
2614        // The whole file is one torn (newline-less) partial write — no complete
2615        // record exists. truncate_torn_tail must cut it to empty, and the next
2616        // append starts a fresh seq 1.
2617        let tmp = TempDir::new().unwrap();
2618        let paths = paths_with_events(&tmp, br#"{"seq":1,"kind":"marker"#);
2619        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 0);
2620
2621        let r = append_and_apply_event(&paths, "marker", None, None, json!({})).unwrap();
2622        assert_eq!(r.seq, 1);
2623        let events = read_all_events(&paths.events()).unwrap();
2624        assert_eq!(events.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![1]);
2625    }
2626
2627    #[test]
2628    fn truncate_torn_tail_cuts_partial_line_at_last_newline() {
2629        // The headline case (issue torn-write-truncate-tail): a complete
2630        // record followed by a torn (newline-less) partial write. Recovery
2631        // must cut the file back to the byte immediately after the last
2632        // complete record's trailing `\n` — the partial bytes are gone.
2633        let tmp = TempDir::new().unwrap();
2634        let complete = r#"{"ts":"2026-06-12T00:00:00Z","seq":5,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#;
2635        let mut bytes = Vec::new();
2636        bytes.extend_from_slice(complete.as_bytes());
2637        bytes.push(b'\n');
2638        let keep = bytes.len() as u64; // offset just past seq-5's newline
2639        bytes.extend_from_slice(br#"{"seq":6,"par"#); // torn mid-line, no newline
2640        let paths = paths_with_events(&tmp, &bytes);
2641
2642        truncate_torn_tail(&paths.events()).unwrap();
2643
2644        let raw = std::fs::read(paths.events()).unwrap();
2645        assert_eq!(
2646            raw.len() as u64,
2647            keep,
2648            "file must end at the offset after seq-5's newline"
2649        );
2650        assert!(raw.ends_with(b"\n"), "file is newline-terminated after cut");
2651        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 5);
2652    }
2653
2654    #[test]
2655    fn truncate_torn_tail_clean_file_is_noop() {
2656        // A file already ending in `\n` is the clean, common case: recovery
2657        // must leave every byte untouched (no rewrite, no length change).
2658        let tmp = TempDir::new().unwrap();
2659        let log = concat!(
2660            r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2661            "\n",
2662        );
2663        let paths = paths_with_events(&tmp, log.as_bytes());
2664
2665        truncate_torn_tail(&paths.events()).unwrap();
2666
2667        assert_eq!(
2668            std::fs::read(paths.events()).unwrap(),
2669            log.as_bytes(),
2670            "a clean, newline-terminated log must be left byte-for-byte intact"
2671        );
2672    }
2673
2674    #[test]
2675    fn truncate_torn_tail_zero_length_file_is_noop() {
2676        // An empty log has no tail to cut: recovery is a no-op and the file
2677        // stays empty.
2678        let tmp = TempDir::new().unwrap();
2679        let paths = paths_with_events(&tmp, b"");
2680        truncate_torn_tail(&paths.events()).unwrap();
2681        assert_eq!(std::fs::read(paths.events()).unwrap(), b"");
2682    }
2683
2684    #[test]
2685    fn truncate_torn_tail_missing_file_is_noop() {
2686        // No `events.jsonl` at all (a run that never appended): recovery must
2687        // not create the file or error.
2688        let tmp = TempDir::new().unwrap();
2689        let dir = tmp.path().join("run");
2690        std::fs::create_dir_all(&dir).unwrap();
2691        let paths = RunPaths::new(dir, "01jxsnap000000000000000000").unwrap();
2692        truncate_torn_tail(&paths.events()).unwrap();
2693        assert!(!paths.events().exists());
2694    }
2695
2696    #[test]
2697    fn truncate_torn_tail_single_complete_row_is_noop() {
2698        // Exactly one complete `\n`-terminated record and nothing else: the
2699        // last byte is already a newline, so there is no tail to cut.
2700        let tmp = TempDir::new().unwrap();
2701        let log = concat!(
2702            r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2703            "\n",
2704        );
2705        let paths = paths_with_events(&tmp, log.as_bytes());
2706        truncate_torn_tail(&paths.events()).unwrap();
2707        assert_eq!(std::fs::read(paths.events()).unwrap(), log.as_bytes());
2708    }
2709
2710    #[test]
2711    fn truncate_torn_tail_single_partial_row_truncates_to_zero() {
2712        // The whole file is one torn (newline-less) partial write with no
2713        // complete record ahead of it: there is nothing to keep, so recovery
2714        // truncates the file to zero length.
2715        let tmp = TempDir::new().unwrap();
2716        let paths = paths_with_events(&tmp, br#"{"seq":1,"kind":"marker"#);
2717        truncate_torn_tail(&paths.events()).unwrap();
2718        assert_eq!(
2719            std::fs::read(paths.events()).unwrap(),
2720            b"",
2721            "a file holding only a partial row must be cut to empty"
2722        );
2723        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 0);
2724    }
2725
2726    #[test]
2727    fn quarantine_excises_corrupt_middle_line_and_recovers() {
2728        // A valid record, a newline-terminated garbage line, then another
2729        // valid record. Quarantine must rename the original aside, write a
2730        // recovered log holding only the two valid lines, and report the bad
2731        // line's byte offset.
2732        let tmp = TempDir::new().unwrap();
2733        let good1 = r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#;
2734        let bad = "{not valid json at all";
2735        let good3 = r#"{"ts":"2026-06-12T00:00:00Z","seq":3,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#;
2736        let log = format!("{good1}\n{bad}\n{good3}\n");
2737        let paths = paths_with_events(&tmp, log.as_bytes());
2738
2739        // Strict replay chokes on the poison line beforehand.
2740        assert!(matches!(
2741            read_all_events(&paths.events()).unwrap_err(),
2742            Error::CorruptEventLog { .. }
2743        ));
2744
2745        let q = quarantine_corrupt_lines(&paths, "20260612T000000Z")
2746            .unwrap()
2747            .expect("a corrupt line was excised");
2748        // The bad line started at the byte after `good1\n`.
2749        assert_eq!(q.removed_byte_offsets, vec![(good1.len() + 1) as u64]);
2750        assert_eq!(
2751            q.backup_path.file_name().unwrap().to_str().unwrap(),
2752            "events.jsonl.corrupt-20260612T000000Z.bak"
2753        );
2754
2755        // The backup is the verbatim original; the recovered log now replays
2756        // strictly with only the two valid records.
2757        assert_eq!(std::fs::read(&q.backup_path).unwrap(), log.as_bytes());
2758        let events = read_all_events(&paths.events()).unwrap();
2759        assert_eq!(events.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![1, 3]);
2760    }
2761
2762    #[test]
2763    fn quarantine_clean_log_is_noop() {
2764        // A log with no corruption must not be renamed or rewritten.
2765        let tmp = TempDir::new().unwrap();
2766        let log = concat!(
2767            r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#,
2768            "\n",
2769        );
2770        let paths = paths_with_events(&tmp, log.as_bytes());
2771        assert!(quarantine_corrupt_lines(&paths, "20260612T000000Z")
2772            .unwrap()
2773            .is_none());
2774        // No backup created; original untouched.
2775        assert_eq!(std::fs::read(paths.events()).unwrap(), log.as_bytes());
2776        let bak = paths
2777            .events()
2778            .with_file_name("events.jsonl.corrupt-20260612T000000Z.bak");
2779        assert!(!bak.exists());
2780    }
2781
2782    #[test]
2783    fn quarantine_missing_log_is_none() {
2784        let tmp = TempDir::new().unwrap();
2785        let dir = tmp.path().join("run");
2786        std::fs::create_dir_all(&dir).unwrap();
2787        let paths = RunPaths::new(dir, "01jxsnap000000000000000000").unwrap();
2788        assert!(quarantine_corrupt_lines(&paths, "20260612T000000Z")
2789            .unwrap()
2790            .is_none());
2791    }
2792
2793    #[test]
2794    fn quarantine_preserves_torn_tail_and_excises_only_corruption() {
2795        // A valid record, a corrupt newline-terminated line, then a torn
2796        // (newline-less) final line. Only the corrupt middle line is excised;
2797        // the torn tail is retained verbatim (the readers tolerate it as an
2798        // in-flight partial write — excising it would change behavior).
2799        let tmp = TempDir::new().unwrap();
2800        let good = r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"marker","run_id":"01jxsnap000000000000000000","data":{}}"#;
2801        let bad = "{garbage";
2802        let torn = r#"{"seq":2,"kind":"node.rep"#; // mid-write, no newline
2803        let mut log = Vec::new();
2804        log.extend_from_slice(format!("{good}\n{bad}\n{torn}").as_bytes());
2805        let paths = paths_with_events(&tmp, &log);
2806
2807        let q = quarantine_corrupt_lines(&paths, "20260612T000000Z")
2808            .unwrap()
2809            .expect("the corrupt middle line was excised");
2810        assert_eq!(q.removed_byte_offsets, vec![(good.len() + 1) as u64]);
2811
2812        let recovered = std::fs::read(paths.events()).unwrap();
2813        assert_eq!(recovered, format!("{good}\n{torn}").as_bytes());
2814        // The torn tail still recovers the last complete seq as 1.
2815        assert_eq!(recover_last_seq(&paths.events()).unwrap(), 1);
2816    }
2817
2818    #[test]
2819    fn find_prior_with_key_rejects_torn_middle_line() {
2820        // A newline-terminated garbage line FOLLOWED by another line: this
2821        // is interior corruption, not an in-flight tail. It must be a hard
2822        // error, never a silent skip — a skipped line could carry the very
2823        // key being looked up and let the caller double-append.
2824        let tmp = TempDir::new().unwrap();
2825        let log = concat!(
2826            r#"{"seq":1,"kind":"node.report","idempotency_key":"k0","node_id":"n-1","data":{}}"#,
2827            "\n",
2828            "{not valid json at all\n",
2829            r#"{"seq":3,"kind":"node.report","idempotency_key":"k1","node_id":"n-1","data":{}}"#,
2830            "\n",
2831        );
2832        let paths = paths_with_events(&tmp, log.as_bytes());
2833        let err = scan(&paths, "node.report", "k1").unwrap_err();
2834        match err {
2835            Error::CorruptEventLog { reason, .. } => {
2836                assert!(reason.contains("line 2"), "reason was: {reason}");
2837                assert!(reason.contains("last good seq 1"), "reason was: {reason}");
2838            }
2839            other => panic!("expected CorruptEventLog, got {other:?}"),
2840        }
2841    }
2842}