Skip to main content

nmbrs_runtime/checkpoint/
writer.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `CheckpointWriter` — append-only event-log owner for the
5//! per-session checkpoint document. SRD-44a §"Writer behaviour".
6//!
7//! Per SRD-44a, every state-changing observation is one event
8//! line written to `logs/<session>/checkpoint.jsonl`. The writer:
9//!
10//! - is created at session bootstrap (or restored from a saved
11//!   document on resume) — emits a `session_start` event,
12//! - has phases *declared* into it during pre-map — one
13//!   `phase_declared` event each,
14//! - receives phase-lifecycle calls (`phase_started`,
15//!   `phase_completed`, `phase_failed`) — one event per call,
16//! - receives op-count and cursor-state updates from the
17//!   metrics tick callback — one `phase_progress` event per
18//!   tick.
19//!
20//! No whole-document rewrite. The file is opened in append mode
21//! (`O_APPEND`); each event is a single `\n`-terminated line.
22//! In-memory state is the same `Checkpoint` document as before
23//! so `snapshot()` and `resume_hint()` keep working without
24//! re-folding from disk.
25//!
26//! The writer is `Send + Sync` (interior mutex) so the executor,
27//! the tick callback, and the cursor-state collector can all
28//! hold one `Arc<CheckpointWriter>`.
29
30use std::collections::{BTreeMap, HashMap};
31use std::fs::{File, OpenOptions};
32use std::io::Write;
33use std::path::PathBuf;
34use std::sync::Mutex;
35
36use super::events::{CheckpointData, hash_to_hex};
37use super::identity::PhaseIdentity;
38use super::storage::{Checkpoint, OpCounts, PhaseEntry, PhaseStatus, now_rfc3339};
39
40/// On-disk checkpoint version this build emits / accepts. Bump
41/// only when an incompatible schema change ships; resume against
42/// a different version is rejected at read time.
43pub const CHECKPOINT_VERSION: u32 = 1;
44
45/// Writer-side handle to the per-session checkpoint event log.
46/// One instance per session; held as `Arc<CheckpointWriter>` and
47/// shared between the executor (lifecycle calls) and the metrics
48/// tick (count + cursor + flush calls).
49pub struct CheckpointWriter {
50    /// Absolute path to `logs/<session>/checkpoint.jsonl`.
51    path: PathBuf,
52    /// When `false` (a dry-run writer), every event is dropped before
53    /// it touches disk and no `checkpoint.jsonl` is created — a dry-run
54    /// records no resumable state (SRD-44). The in-memory mirror is
55    /// still maintained so `snapshot` stays coherent for tests, but
56    /// `resume_hint` stays silent.
57    enabled: bool,
58    inner: Mutex<Inner>,
59    /// Set once by [`Self::mark_run_reached_end`] when the runner
60    /// reaches its session-end boundary (both run shapes converge
61    /// there; early error returns never set it). Read by
62    /// [`Self::resume_hint`]: a run that ended cleanly must not
63    /// read declared-but-never-started phases as resumable work —
64    /// the runner declares EVERY pre-mapped phase up front (so a
65    /// resume can tell "didn't run yet" from "wasn't planned"),
66    /// and runtime predicates (`continue_if`, for-loop bounds)
67    /// legitimately leave some of those entries Pending forever.
68    run_reached_end: std::sync::atomic::AtomicBool,
69    /// Open handle on the held lockfile
70    /// (`logs/<session>/checkpoint.lock`). The handle is owned
71    /// for the lifetime of the writer; closing it (Drop)
72    /// releases the advisory lock automatically. `None` when
73    /// lock acquisition failed soft.
74    _lock_fd: Option<LockHandle>,
75}
76
77/// Owning wrapper around the open lockfile that releases the
78/// advisory lock when dropped — unlock is implicit on close
79/// (`flock(LOCK_UN)` on Unix, `UnlockFile` on Windows; both are
80/// what `std`'s file locking maps to).
81struct LockHandle(#[allow(dead_code)] File);
82
83struct Inner {
84    /// In-memory fold mirror. Always reflects the most recent
85    /// state declared / observed; consumers (`snapshot`,
86    /// `resume_hint`) read this. The on-disk view is the
87    /// append-only event stream — these two converge after a
88    /// reader folds the log.
89    doc: Checkpoint,
90    /// Map from `identity_key(&PhaseIdentity)` to the index of
91    /// the matching entry in `doc.phases`. Avoids an O(n) linear
92    /// scan on every lifecycle call.
93    index: HashMap<String, usize>,
94    /// Open append-mode handle to the JSONL log. Keeping the
95    /// file open avoids one `open(2)` per event; the `O_APPEND`
96    /// flag guarantees writes are atomic up to `PIPE_BUF`
97    /// (4 KB on Linux) without explicit locking.
98    file: File,
99}
100
101impl CheckpointWriter {
102    /// Construct a fresh writer for a brand-new session. Emits
103    /// the leading `session_start` record before returning.
104    /// Subsequent `declare_phase` / lifecycle calls append events
105    /// onto the same log.
106    pub fn new(path: PathBuf, session: String, started_at: String, invocation: u32) -> Self {
107        let doc = Checkpoint {
108            version: CHECKPOINT_VERSION,
109            session: session.clone(),
110            started_at: started_at.clone(),
111            checkpoint_at: started_at.clone(),
112            invocation,
113            phases: Vec::new(),
114        };
115        let lock = acquire_flock(&path);
116        let file = open_append(&path);
117        let writer = Self {
118            path,
119            enabled: true,
120            inner: Mutex::new(Inner {
121                doc,
122                index: HashMap::new(),
123                file,
124            }),
125            run_reached_end: std::sync::atomic::AtomicBool::new(false),
126            _lock_fd: lock,
127        };
128        // Per SRD-44a §"File location and format" — the first
129        // line of a fresh log MUST be a `session_start` record;
130        // the reader rejects logs whose first record is anything
131        // else. Resume continues the same log by appending its
132        // own `session_start`, so this stays correct across
133        // invocations too.
134        writer.append_event(CheckpointData::SessionStart {
135            at: now_rfc3339(),
136            version: CHECKPOINT_VERSION,
137            session,
138            started_at,
139            invocation,
140        });
141        writer
142    }
143
144    /// Restore a writer from a previously-written document on
145    /// resume. The caller is responsible for having parsed and
146    /// version-checked the document via [`super::storage::read`].
147    /// The restored writer keeps the existing phase entries and
148    /// emits a fresh `session_start` event with the new
149    /// invocation counter — appending continues onto the same
150    /// JSONL log per SRD-44a.
151    pub fn from_existing(
152        path: PathBuf,
153        mut doc: Checkpoint,
154        new_checkpoint_at: String,
155        new_invocation: u32,
156    ) -> Self {
157        doc.checkpoint_at = new_checkpoint_at;
158        doc.invocation = new_invocation;
159        let session = doc.session.clone();
160        let started_at = doc.started_at.clone();
161        let index = build_index(&doc.phases);
162        let lock = acquire_flock(&path);
163        let file = open_append(&path);
164        let writer = Self {
165            path,
166            enabled: true,
167            inner: Mutex::new(Inner { doc, index, file }),
168            run_reached_end: std::sync::atomic::AtomicBool::new(false),
169            _lock_fd: lock,
170        };
171        writer.append_event(CheckpointData::SessionStart {
172            at: now_rfc3339(),
173            version: CHECKPOINT_VERSION,
174            session,
175            started_at,
176            invocation: new_invocation,
177        });
178        writer
179    }
180
181    /// A resume-inert writer for dry-runs: no `checkpoint.jsonl` is
182    /// created, no flock is taken, and every lifecycle event is dropped
183    /// before it reaches disk. A dry-run short-circuits ops and may run
184    /// against placeholder params, so persisting its phases as
185    /// "completed" would poison a later `--resume-latest` (SRD-44) —
186    /// this constructor guarantees it can't. The file handle targets
187    /// `/dev/null` purely to keep the struct total; `append_event`
188    /// never writes to it.
189    pub fn disabled(path: PathBuf) -> Self {
190        let doc = Checkpoint {
191            version: CHECKPOINT_VERSION,
192            session: String::new(),
193            started_at: String::new(),
194            checkpoint_at: String::new(),
195            invocation: 0,
196            phases: Vec::new(),
197        };
198        let file = open_append(std::path::Path::new("/dev/null"));
199        Self {
200            path,
201            enabled: false,
202            inner: Mutex::new(Inner {
203                doc,
204                index: HashMap::new(),
205                file,
206            }),
207            run_reached_end: std::sync::atomic::AtomicBool::new(false),
208            _lock_fd: None,
209        }
210    }
211
212    /// Declare a phase the run plans to execute. Called during
213    /// pre-map for every phase; idempotent (re-declaration is a
214    /// no-op so the resume path can declare the same phases the
215    /// saved doc already lists).
216    pub fn declare_phase(&self, identity: PhaseIdentity, skip_eligible: bool) {
217        let event = {
218            let mut g = self.inner.lock().unwrap();
219            let key = identity_key(&identity);
220            if g.index.contains_key(&key) {
221                return;
222            }
223            let entry = PhaseEntry {
224                identity: identity.clone(),
225                skip_eligible,
226                params_consumed: None,
227                status: PhaseStatus::Pending,
228                duration_secs: None,
229                op_counts: None,
230                cursor_state: None,
231                error: None,
232            };
233            g.doc.phases.push(entry);
234            let idx = g.doc.phases.len() - 1;
235            g.index.insert(key, idx);
236            CheckpointData::PhaseDeclared {
237                at: now_rfc3339(),
238                identity,
239                skip_eligible,
240            }
241        };
242        self.append_event(event);
243    }
244
245    /// Mark a declared phase as `Running`.
246    pub fn phase_started(&self, identity: &PhaseIdentity) {
247        let updated = self.with_entry(identity, |e| {
248            e.status = PhaseStatus::Running;
249            e.error = None;
250        });
251        if updated {
252            self.append_event(CheckpointData::PhaseStarted {
253                at: now_rfc3339(),
254                identity: identity.clone(),
255            });
256        }
257    }
258
259    /// Mark a declared phase as `Completed` with the given
260    /// wall-clock duration.
261    pub fn phase_completed(&self, identity: &PhaseIdentity, duration_secs: f64) {
262        let final_counts = {
263            let mut g = self.inner.lock().unwrap();
264            let key = identity_key(identity);
265            if let Some(&idx) = g.index.get(&key) {
266                let entry = &mut g.doc.phases[idx];
267                let counts = entry.op_counts.clone().unwrap_or_default();
268                entry.status = PhaseStatus::Completed;
269                entry.duration_secs = Some(duration_secs);
270                // Pin the final counts on the in-memory mirror
271                // so a subsequent `snapshot()` matches what the
272                // event records — and what the reader-fold will
273                // produce. Leaving it `None` would diverge from
274                // the disk view.
275                entry.op_counts = Some(counts.clone());
276                entry.cursor_state = None;
277                entry.error = None;
278                counts
279            } else {
280                return;
281            }
282        };
283        self.append_event(CheckpointData::PhaseCompleted {
284            at: now_rfc3339(),
285            identity: identity.clone(),
286            duration_secs,
287            op_counts: final_counts,
288        });
289    }
290
291    /// Mark a declared phase as `Failed`. The error message is
292    /// preserved for resume diagnostics.
293    pub fn phase_failed(&self, identity: &PhaseIdentity, error: &str) {
294        let counts = {
295            let err_owned = error.to_string();
296            let mut g = self.inner.lock().unwrap();
297            let key = identity_key(identity);
298            if let Some(&idx) = g.index.get(&key) {
299                let entry = &mut g.doc.phases[idx];
300                entry.status = PhaseStatus::Failed;
301                entry.error = Some(err_owned);
302                entry.cursor_state = None;
303                entry.op_counts.clone()
304            } else {
305                return;
306            }
307        };
308        self.append_event(CheckpointData::PhaseFailed {
309            at: now_rfc3339(),
310            identity: identity.clone(),
311            error: error.to_string(),
312            op_counts: counts,
313        });
314    }
315
316    /// Record op-execution counts from the live activity. Called
317    /// from the metrics tick callback for the currently-running
318    /// phase. Folds into the matching `PhaseEntry` and emits one
319    /// `phase_progress` event per call — the reader keeps only
320    /// the most recent per identity when folding.
321    pub fn update_op_counts(&self, identity: &PhaseIdentity, counts: OpCounts) {
322        let cursor_state = {
323            let mut g = self.inner.lock().unwrap();
324            let key = identity_key(identity);
325            if let Some(&idx) = g.index.get(&key) {
326                let entry = &mut g.doc.phases[idx];
327                entry.op_counts = Some(counts.clone());
328                entry.cursor_state.clone()
329            } else {
330                return;
331            }
332        };
333        self.append_event(CheckpointData::PhaseProgress {
334            at: now_rfc3339(),
335            identity: identity.clone(),
336            op_counts: counts,
337            cursor_state,
338        });
339    }
340
341    /// Set the program-canonical hash on a declared phase.
342    pub fn update_phase_hash(
343        &self,
344        identity: &PhaseIdentity,
345        hash: [u8; 32],
346        params_consumed: Option<String>,
347    ) {
348        let updated = self.with_entry(identity, |e| {
349            e.identity.phase_hash = Some(hash);
350            e.params_consumed = params_consumed.clone();
351        });
352        if updated {
353            self.append_event(CheckpointData::PhaseHash {
354                at: now_rfc3339(),
355                identity: identity.clone(),
356                hash_hex: hash_to_hex(&hash),
357                params_consumed,
358            });
359        }
360    }
361
362    /// Record the latest cursor-state snapshot for a Tier 2
363    /// phase.
364    pub fn update_cursor(&self, identity: &PhaseIdentity, cursor_state: serde_json::Value) {
365        let counts = {
366            let mut g = self.inner.lock().unwrap();
367            let key = identity_key(identity);
368            if let Some(&idx) = g.index.get(&key) {
369                let entry = &mut g.doc.phases[idx];
370                entry.cursor_state = Some(cursor_state.clone());
371                entry.op_counts.clone().unwrap_or_default()
372            } else {
373                return;
374            }
375        };
376        self.append_event(CheckpointData::PhaseProgress {
377            at: now_rfc3339(),
378            identity: identity.clone(),
379            op_counts: counts,
380            cursor_state: Some(cursor_state),
381        });
382    }
383
384    /// Emit a `scope_enter` event marking entry into a
385    /// `for_each` / `for_combinations` / `do_while` / `do_until`
386    /// iteration. Per SRD-44a §"Event taxonomy", `coords` is the
387    /// `{var: value}` map for THIS scope's own bindings and
388    /// `path` is the leaf-first chain of enclosing scopes' coords
389    /// — together they pin the executor's position in the
390    /// scenario tree at iteration time. Scope events are
391    /// write-and-go: the in-memory mirror has no slot to fold
392    /// them into (the reader's fold is also a no-op today), so
393    /// this is one direct `append_event`.
394    pub fn emit_scope_enter(
395        &self,
396        kind: &str,
397        coords: BTreeMap<String, serde_json::Value>,
398        path: Vec<BTreeMap<String, serde_json::Value>>,
399    ) {
400        self.append_event(CheckpointData::ScopeEnter {
401            at: now_rfc3339(),
402            kind: kind.to_string(),
403            coords,
404            path,
405        });
406    }
407
408    /// Emit a `scope_exit` event marking the end of one
409    /// iteration. `outcome` is `"completed"` when the iteration's
410    /// terminal action returned `Ok`, `"interrupted"` when it
411    /// returned an error or the executor unwound through a stop
412    /// signal. Same write-and-go shape as
413    /// [`emit_scope_enter`](Self::emit_scope_enter).
414    pub fn emit_scope_exit(
415        &self,
416        kind: &str,
417        coords: BTreeMap<String, serde_json::Value>,
418        path: Vec<BTreeMap<String, serde_json::Value>>,
419        outcome: &str,
420    ) {
421        self.append_event(CheckpointData::ScopeExit {
422            at: now_rfc3339(),
423            kind: kind.to_string(),
424            coords,
425            path,
426            outcome: outcome.to_string(),
427        });
428    }
429
430    /// Record an adapter's own resumable position (SRD-117 §9.6).
431    /// Write-and-go, like the scope events: the fold keeps none of it,
432    /// and the adapter reads it back with
433    /// [`super::storage::latest_adapter_position`] on resume.
434    pub fn adapter_position(&self, adapter: &str, key: &str, position: serde_json::Value) {
435        self.append_event(CheckpointData::AdapterPosition {
436            at: now_rfc3339(),
437            adapter: adapter.to_string(),
438            key: key.to_string(),
439            position,
440        });
441    }
442
443    /// Force a `fdatasync(2)` on the underlying log. Per SRD-44a
444    /// §"Writer behaviour", lifecycle records (start / completed
445    /// / failed) deserve a per-event sync; the periodic
446    /// progress tick can batch. The runtime calls this at every
447    /// phase-lifecycle boundary so a crash between ticks loses
448    /// at most one tick's worth of progress.
449    pub fn flush(&self) -> Result<(), String> {
450        // Nothing is ever written on a dry-run writer, and its handle is
451        // `/dev/null` (which rejects fdatasync) — so flush is a no-op.
452        if !self.enabled {
453            return Ok(());
454        }
455        let g = self.inner.lock().unwrap();
456        match g.file.sync_data() {
457            Ok(()) => Ok(()),
458            Err(e) => Err(format!("fdatasync {}: {e}", self.path.display())),
459        }
460    }
461
462    /// Read-only snapshot of the current in-memory document.
463    /// Useful for diagnostics and tests.
464    pub fn snapshot(&self) -> Checkpoint {
465        self.inner.lock().unwrap().doc.clone()
466    }
467
468    /// Record that the runner reached its session-end boundary
469    /// (the convergence point right before `run_finished()`).
470    /// Early error returns and interrupts never get here, so the
471    /// flag cleanly separates "the run ended" from "the run was
472    /// cut short" for [`Self::resume_hint`].
473    pub fn mark_run_reached_end(&self) {
474        self.run_reached_end
475            .store(true, std::sync::atomic::Ordering::Relaxed);
476    }
477
478    /// If the workload has incomplete phases declared
479    /// `checkpoint: idempotent`, return a multi-line hint string
480    /// the runtime can show the operator on exit.
481    pub fn resume_hint(&self) -> Option<String> {
482        // A dry-run persisted nothing — never advise resuming it.
483        if !self.enabled {
484            return None;
485        }
486        let ended = self
487            .run_reached_end
488            .load(std::sync::atomic::Ordering::Relaxed);
489        let cp = self.snapshot();
490        let recoverable = cp.phases.iter().any(|e| {
491            e.skip_eligible
492                && match e.status {
493                    PhaseStatus::Completed => false,
494                    // Failed (and the anomalous started-never-finished)
495                    // are actionable regardless of how the run ended.
496                    PhaseStatus::Failed | PhaseStatus::Running => true,
497                    // Declared-but-never-started is only evidence of
498                    // interruption when the run was cut short. Every
499                    // pre-mapped phase is declared up front (so resume
500                    // can tell "didn't run yet" from "wasn't planned"),
501                    // and runtime predicates (`continue_if`, for-loop
502                    // bounds) legitimately leave some entries Pending
503                    // forever — a clean run end must not read those as
504                    // work left behind. (Observed 2026-08-05: a fully
505                    // successful 78/78 adaptive run advised resuming
506                    // its 28 continue_if-excluded tiers.)
507                    PhaseStatus::Pending => !ended,
508                }
509        });
510        if !recoverable {
511            return None;
512        }
513        Some(format!(
514            "This session has resumable phases that didn't complete.\n  \
515             To continue from where it stopped:\n    \
516             nmbrs run <workload> --session-path {} (already set if you exported \
517             NMBRS_SESSION_PATH) --resume\n  \
518             To pin the session name for repeatable resumes:\n    \
519             nmbrs run <workload> --session {} (then add --resume next time)",
520            self.path
521                .parent()
522                .map(|p| p.display().to_string())
523                .unwrap_or_default(),
524            cp.session,
525        ))
526    }
527
528    /// Path the writer flushes to.
529    pub fn path(&self) -> &std::path::Path {
530        &self.path
531    }
532
533    /// Append one event line to the log. Mutates the file, but
534    /// not the in-memory mirror — the caller is responsible for
535    /// updating the mirror first (so a reader-fold and the
536    /// in-memory snapshot stay equivalent).
537    fn append_event(&self, event: CheckpointData) {
538        // Dry-run writer: drop every event before it touches disk so no
539        // resumable state is ever persisted (SRD-44).
540        if !self.enabled {
541            return;
542        }
543        let mut g = self.inner.lock().unwrap();
544        let mut line = match serde_json::to_string(&event) {
545            Ok(s) => s,
546            Err(e) => {
547                // Serialisation failure is a programming bug —
548                // log loudly and drop the event rather than
549                // panicking the whole session.
550                eprintln!("checkpoint: serialise event failed: {e}; dropping record",);
551                return;
552            }
553        };
554        line.push('\n');
555        if let Err(e) = g.file.write_all(line.as_bytes()) {
556            eprintln!("checkpoint: append to {}: {e}", self.path.display(),);
557        }
558    }
559
560    /// Apply a mutation closure to the entry matching `identity`,
561    /// returning `true` when the entry was found and updated. The
562    /// caller emits the event after a successful mutation so the
563    /// in-memory mirror and the on-disk log stay in lock-step.
564    fn with_entry<F: FnOnce(&mut PhaseEntry)>(&self, identity: &PhaseIdentity, f: F) -> bool {
565        let mut g = self.inner.lock().unwrap();
566        let key = identity_key(identity);
567        if let Some(&idx) = g.index.get(&key) {
568            f(&mut g.doc.phases[idx]);
569            true
570        } else {
571            false
572        }
573    }
574}
575
576/// Open `path` in append mode, creating it (and the parent
577/// directory) if needed. Returns the file or panics — the
578/// writer can't function without it, so a hard failure here is
579/// the correct response. Production callers wrap construction
580/// in a fallible bootstrap path; the panic surfaces as a
581/// session-startup error rather than a silent skip.
582fn open_append(path: &std::path::Path) -> File {
583    if let Some(parent) = path.parent()
584        && let Err(e) = std::fs::create_dir_all(parent)
585    {
586        panic!(
587            "checkpoint: create parent dir {} for {}: {e}",
588            parent.display(),
589            path.display(),
590        );
591    }
592    OpenOptions::new()
593        .create(true)
594        .append(true)
595        .open(path)
596        .unwrap_or_else(|e| panic!("checkpoint: open append {} failed: {e}", path.display(),))
597}
598
599/// Build a lookup key for the index map. Identity equality is
600/// `(yaml_path, coords)` per SRD-44; the hash is sufficiency,
601/// not identity, so it's deliberately excluded from the key.
602pub(crate) fn identity_key(identity: &PhaseIdentity) -> String {
603    let path_json = serde_json::to_string(&identity.yaml_path).unwrap_or_else(|_| String::new());
604    format!("{path_json}\x1f{}", identity.coords)
605}
606
607/// Take a non-blocking exclusive advisory lock on a sibling
608/// `checkpoint.lock` file alongside the checkpoint document.
609fn acquire_flock(checkpoint_path: &std::path::Path) -> Option<LockHandle> {
610    let parent = checkpoint_path.parent()?;
611    if let Err(e) = std::fs::create_dir_all(parent) {
612        eprintln!(
613            "warning: could not create checkpoint dir {}: {e} (concurrent-resume protection skipped)",
614            parent.display(),
615        );
616        return None;
617    }
618    let lock_path = checkpoint_path.with_extension("lock");
619    let file = match OpenOptions::new()
620        .read(true)
621        .write(true)
622        .create(true)
623        // A lock file is held, never rewritten: opening it must not
624        // clobber what another holder wrote.
625        .truncate(false)
626        .open(&lock_path)
627    {
628        Ok(f) => f,
629        Err(e) => {
630            eprintln!(
631                "warning: could not open lockfile {}: {e} (concurrent-resume protection skipped)",
632                lock_path.display(),
633            );
634            return None;
635        }
636    };
637    match file.try_lock() {
638        Ok(()) => Some(LockHandle(file)),
639        Err(std::fs::TryLockError::WouldBlock) => {
640            panic!(
641                "checkpoint: another process holds the resume lock at {} \
642                 (concurrent `nmbrs run --resume` against the same session?). \
643                 If you're certain no other process is running, remove the \
644                 lockfile and retry.",
645                lock_path.display(),
646            );
647        }
648        Err(std::fs::TryLockError::Error(e)) => {
649            eprintln!(
650                "warning: lock on {} failed: {e} (concurrent-resume protection skipped)",
651                lock_path.display(),
652            );
653            None
654        }
655    }
656}
657
658fn build_index(phases: &[PhaseEntry]) -> HashMap<String, usize> {
659    let mut m = HashMap::with_capacity(phases.len());
660    for (i, e) in phases.iter().enumerate() {
661        m.insert(identity_key(&e.identity), i);
662    }
663    m
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use crate::checkpoint::{PathSegment, PhaseIdentity};
670
671    fn ident(name: &str, coords: &str) -> PhaseIdentity {
672        PhaseIdentity {
673            yaml_path: vec![
674                PathSegment::Scenario("s".into()),
675                PathSegment::Phase(name.into()),
676            ],
677            coords: coords.into(),
678            phase_hash: Some([0xcd; 32]),
679        }
680    }
681
682    fn tempdir() -> std::path::PathBuf {
683        let d = std::env::temp_dir().join(format!(
684            "nmbrs-checkpoint-writer-{}",
685            crate::scratch_suffix()
686        ));
687        std::fs::create_dir_all(&d).unwrap();
688        d
689    }
690
691    #[test]
692    fn declare_then_complete_then_flush() {
693        let dir = tempdir();
694        let path = dir.join("checkpoint.jsonl");
695        let w = CheckpointWriter::new(
696            path.clone(),
697            "sess".into(),
698            "2026-01-01T00:00:00Z".into(),
699            1,
700        );
701        let id = ident("schema", "");
702        w.declare_phase(id.clone(), true);
703        w.phase_started(&id);
704        w.phase_completed(&id, 1.5);
705        w.flush().expect("flush");
706
707        // Verify in-memory mirror reflects the lifecycle.
708        let snap = w.snapshot();
709        assert_eq!(snap.phases.len(), 1);
710        assert_eq!(snap.phases[0].status, PhaseStatus::Completed);
711        assert_eq!(snap.phases[0].duration_secs, Some(1.5));
712
713        // Verify the on-disk log carries each event line in order.
714        let raw = std::fs::read_to_string(&path).expect("read log");
715        let lines: Vec<&str> = raw.lines().collect();
716        assert_eq!(
717            lines.len(),
718            4,
719            "expected session_start, phase_declared, phase_started, phase_completed"
720        );
721        assert!(lines[0].contains("\"type\":\"session_start\""));
722        assert!(lines[1].contains("\"type\":\"phase_declared\""));
723        assert!(lines[2].contains("\"type\":\"phase_started\""));
724        assert!(lines[3].contains("\"type\":\"phase_completed\""));
725    }
726
727    #[test]
728    fn resume_hint_respects_run_end_boundary() {
729        // The 2026-08-05 false positive: every pre-mapped phase is
730        // declared up front, and runtime predicates (continue_if,
731        // for-loop bounds) leave excluded ones Pending forever — a
732        // fully successful 78/78 run advised resuming its 28
733        // excluded tiers. Pending counts as resumable ONLY when the
734        // run never reached its end boundary; Failed counts always.
735        let dir = tempdir();
736        let w = CheckpointWriter::new(
737            dir.join("checkpoint.jsonl"),
738            "sess".into(),
739            "2026-01-01T00:00:00Z".into(),
740            1,
741        );
742        let ran = ident("tier", "(part=0)");
743        let excluded = ident("tier", "(part=17)");
744        w.declare_phase(ran.clone(), true);
745        w.declare_phase(excluded.clone(), true);
746        w.phase_started(&ran);
747        w.phase_completed(&ran, 1.0);
748
749        // Cut short (no end mark): the Pending entry is resumable.
750        assert!(
751            w.resume_hint().is_some(),
752            "an interrupted run must advise resuming pending phases"
753        );
754
755        // Clean end: the same Pending entry was excluded by a
756        // runtime predicate, not left behind.
757        w.mark_run_reached_end();
758        assert!(
759            w.resume_hint().is_none(),
760            "a run that reached its end must not advise resuming \
761             predicate-excluded phases"
762        );
763
764        // A failure stays actionable even after a clean end.
765        let failed = ident("tier", "(part=3)");
766        w.declare_phase(failed.clone(), true);
767        w.phase_started(&failed);
768        w.phase_failed(&failed, "boom");
769        assert!(
770            w.resume_hint().is_some(),
771            "failed phases must keep the hint even on a clean end"
772        );
773    }
774
775    #[test]
776    fn disabled_writer_persists_nothing() {
777        // SRD-44 dry-run gate: a disabled writer must create NO
778        // checkpoint.jsonl and drop every lifecycle event, so a later
779        // `--resume-latest` can never pick a dry-run's phases up.
780        let dir = tempdir();
781        let path = dir.join("checkpoint.jsonl");
782        let w = CheckpointWriter::disabled(path.clone());
783        let id = ident("teardown", "(table=changeme_default)");
784        w.declare_phase(id.clone(), true);
785        w.phase_started(&id);
786        w.phase_completed(&id, 1.0);
787        w.flush().expect("flush is a harmless no-op");
788
789        assert!(
790            !path.exists(),
791            "dry-run must not create a checkpoint file at {}",
792            path.display()
793        );
794        assert!(
795            w.resume_hint().is_none(),
796            "dry-run must never advertise a resumable session"
797        );
798    }
799
800    #[test]
801    fn redundant_declare_is_idempotent() {
802        let dir = tempdir();
803        let path = dir.join("c.jsonl");
804        let w = CheckpointWriter::new(path.clone(), "s".into(), "t".into(), 1);
805        let id = ident("p", "(k=1)");
806        w.declare_phase(id.clone(), true);
807        w.declare_phase(id.clone(), false); // re-declare ignored
808        let snap = w.snapshot();
809        assert_eq!(snap.phases.len(), 1);
810        assert!(snap.phases[0].skip_eligible, "first declare wins");
811
812        // Only one phase_declared in the log (plus the leading
813        // session_start).
814        let raw = std::fs::read_to_string(&path).expect("read");
815        let count = raw
816            .lines()
817            .filter(|l| l.contains("\"type\":\"phase_declared\""))
818            .count();
819        assert_eq!(count, 1, "second declare must not emit a duplicate event");
820    }
821
822    #[test]
823    fn from_existing_emits_fresh_session_start() {
824        let dir = tempdir();
825        let path = dir.join("c.jsonl");
826        // First session writes some events, then drops to release
827        // the flock. Mirrors the production lifecycle: prior
828        // process exits before resume starts.
829        let saved = {
830            let w =
831                CheckpointWriter::new(path.clone(), "s".into(), "2026-01-01T00:00:00Z".into(), 1);
832            let id = ident("schema", "");
833            w.declare_phase(id.clone(), true);
834            w.phase_completed(&id, 0.5);
835            w.flush().expect("flush");
836            w.snapshot()
837        };
838        let w2 =
839            CheckpointWriter::from_existing(path.clone(), saved, "2026-01-01T00:01:00Z".into(), 2);
840        let snap = w2.snapshot();
841        assert_eq!(snap.invocation, 2);
842        assert_eq!(snap.phases.len(), 1);
843        assert_eq!(snap.phases[0].status, PhaseStatus::Completed);
844
845        // Log carries TWO session_start events, marking the
846        // invocation boundary.
847        let raw = std::fs::read_to_string(&path).expect("read");
848        let count = raw
849            .lines()
850            .filter(|l| l.contains("\"type\":\"session_start\""))
851            .count();
852        assert_eq!(
853            count, 2,
854            "resume must append a fresh session_start, not rewrite"
855        );
856    }
857
858    #[test]
859    fn scope_enter_exit_pairs_for_two_deep_for_each() {
860        // SRD-44a Push 3: drive the writer over the event
861        // sequence the executor's scope walker produces for a
862        // 2-deep `for_each` workload — outer iterates `x in
863        // [1, 2]`, inner iterates `y in ["a", "b"]`. Two
864        // outer iterations × two inner iterations = four leaf
865        // bracket pairs, plus the two outer-loop bracket pairs
866        // wrapping each inner sub-walk.
867        let dir = tempdir();
868        let path = dir.join("c.jsonl");
869        let w = CheckpointWriter::new(path.clone(), "s".into(), "2026-01-01T00:00:00Z".into(), 1);
870
871        // Scope coords as the executor would synthesize per
872        // iteration. `coord_path` is root-first; the writer's
873        // event takes the leaf as `coords` and the prefix
874        // (reversed to leaf-first) as `path`. We model that
875        // shape here directly.
876        let outer_coord = |xv: u64| -> BTreeMap<String, serde_json::Value> {
877            let mut m = BTreeMap::new();
878            m.insert("x".into(), serde_json::Value::from(xv));
879            m
880        };
881        let inner_coord = |yv: &str| -> BTreeMap<String, serde_json::Value> {
882            let mut m = BTreeMap::new();
883            m.insert("y".into(), serde_json::Value::from(yv));
884            m
885        };
886
887        for x in [1u64, 2u64] {
888            // Outer enter: coords={x=…}, path=[]
889            w.emit_scope_enter("for_each", outer_coord(x), Vec::new());
890            for y in ["a", "b"] {
891                // Inner enter: coords={y=…}, path=[{x=…}]
892                w.emit_scope_enter("for_each", inner_coord(y), vec![outer_coord(x)]);
893                w.emit_scope_exit(
894                    "for_each",
895                    inner_coord(y),
896                    vec![outer_coord(x)],
897                    "completed",
898                );
899            }
900            w.emit_scope_exit("for_each", outer_coord(x), Vec::new(), "completed");
901        }
902        w.flush().expect("flush");
903
904        // Parse the JSONL log line-by-line, dropping the
905        // leading session_start. Confirm the bracket sequence
906        // is well-formed and the path/coords carry the
907        // expected x/y values for each iteration.
908        let raw = std::fs::read_to_string(&path).expect("read log");
909        let scope_events: Vec<serde_json::Value> = raw
910            .lines()
911            .map(|l| serde_json::from_str::<serde_json::Value>(l).expect("parse line"))
912            .filter(|v| {
913                let t = v.get("type").and_then(|t| t.as_str()).unwrap_or("");
914                t == "scope_enter" || t == "scope_exit"
915            })
916            .collect();
917        // 2 outer (enter+exit) + 2*2 inner (enter+exit) = 12 events.
918        assert_eq!(
919            scope_events.len(),
920            12,
921            "expected 12 scope events, got {}",
922            scope_events.len()
923        );
924
925        let kind = |v: &serde_json::Value| {
926            v.get("type")
927                .and_then(|t| t.as_str())
928                .unwrap_or("")
929                .to_string()
930        };
931        let x_at = |v: &serde_json::Value, idx: &str| -> Option<u64> {
932            v.pointer(idx).and_then(|n| n.as_u64())
933        };
934        let y_at = |v: &serde_json::Value, idx: &str| -> Option<String> {
935            v.pointer(idx)
936                .and_then(|n| n.as_str())
937                .map(|s| s.to_string())
938        };
939
940        // Outer entry first: coords={x=1}, path=[].
941        assert_eq!(kind(&scope_events[0]), "scope_enter");
942        assert_eq!(x_at(&scope_events[0], "/coords/x"), Some(1));
943        assert!(
944            scope_events[0]
945                .pointer("/path")
946                .and_then(|p| p.as_array())
947                .map(|a| a.is_empty())
948                .unwrap_or(false),
949            "outer enter must have empty path"
950        );
951
952        // First inner enter under x=1, y=a. path leaf-first is
953        // [{x=1}].
954        assert_eq!(kind(&scope_events[1]), "scope_enter");
955        assert_eq!(y_at(&scope_events[1], "/coords/y"), Some("a".to_string()));
956        assert_eq!(x_at(&scope_events[1], "/path/0/x"), Some(1));
957
958        // First inner exit, completed.
959        assert_eq!(kind(&scope_events[2]), "scope_exit");
960        assert_eq!(
961            scope_events[2].pointer("/outcome").and_then(|s| s.as_str()),
962            Some("completed")
963        );
964
965        // Second inner under x=1, y=b.
966        assert_eq!(y_at(&scope_events[3], "/coords/y"), Some("b".to_string()));
967        assert_eq!(kind(&scope_events[4]), "scope_exit");
968
969        // Outer exit for x=1.
970        assert_eq!(kind(&scope_events[5]), "scope_exit");
971        assert_eq!(x_at(&scope_events[5], "/coords/x"), Some(1));
972        assert_eq!(
973            scope_events[5].pointer("/outcome").and_then(|s| s.as_str()),
974            Some("completed")
975        );
976
977        // Second outer (x=2) entry, plus its inner pairs and exit.
978        assert_eq!(kind(&scope_events[6]), "scope_enter");
979        assert_eq!(x_at(&scope_events[6], "/coords/x"), Some(2));
980        assert_eq!(x_at(&scope_events[7], "/path/0/x"), Some(2));
981        assert_eq!(y_at(&scope_events[7], "/coords/y"), Some("a".to_string()));
982        assert_eq!(kind(&scope_events[11]), "scope_exit");
983        assert_eq!(x_at(&scope_events[11], "/coords/x"), Some(2));
984
985        // The reader's fold treats scope events as no-ops in v1
986        // (no scope mirror in the in-memory document), so a
987        // round-trip read should succeed and leave the phases
988        // list untouched.
989        let folded = super::super::storage::read(&path)
990            .expect("read folds")
991            .expect("non-empty");
992        assert!(
993            folded.phases.is_empty(),
994            "no phases declared, fold should be empty"
995        );
996    }
997
998    #[test]
999    fn scope_exit_outcome_distinguishes_interrupted_from_completed() {
1000        // The kind/outcome surface is what distinguishes a clean
1001        // bracket from one closed by a stop signal. Verify both
1002        // outcomes round-trip through the JSONL.
1003        let dir = tempdir();
1004        let path = dir.join("c.jsonl");
1005        let w = CheckpointWriter::new(path.clone(), "s".into(), "t".into(), 1);
1006        let mut coords = BTreeMap::new();
1007        coords.insert("k".into(), serde_json::Value::from(7u64));
1008        w.emit_scope_enter("do_while", coords.clone(), Vec::new());
1009        w.emit_scope_exit("do_while", coords, Vec::new(), "interrupted");
1010        w.flush().expect("flush");
1011
1012        let raw = std::fs::read_to_string(&path).expect("read");
1013        let exit_line = raw
1014            .lines()
1015            .find(|l| l.contains("\"type\":\"scope_exit\""))
1016            .expect("scope_exit line");
1017        let ev: serde_json::Value = serde_json::from_str(exit_line).unwrap();
1018        assert_eq!(
1019            ev.pointer("/kind").and_then(|s| s.as_str()),
1020            Some("do_while")
1021        );
1022        assert_eq!(
1023            ev.pointer("/outcome").and_then(|s| s.as_str()),
1024            Some("interrupted")
1025        );
1026    }
1027
1028    #[test]
1029    fn flock_blocks_concurrent_writer_on_same_path() {
1030        let dir = tempdir();
1031        let path = dir.join("c.jsonl");
1032        let _w = CheckpointWriter::new(path.clone(), "s".into(), "t".into(), 1);
1033        let result = std::panic::catch_unwind(|| {
1034            let _w2 = CheckpointWriter::new(path.clone(), "s".into(), "t".into(), 1);
1035        });
1036        assert!(
1037            result.is_err(),
1038            "second writer should panic on flock contention"
1039        );
1040    }
1041}