1use serde::{Deserialize, Serialize};
14use std::io::{BufRead, BufReader};
15use std::path::Path;
16
17use super::events::{CheckpointData, hex_to_hash};
18use super::identity::PhaseIdentity;
19
20#[derive(Clone, Debug, Serialize, Deserialize)]
26pub struct Checkpoint {
27 pub version: u32,
32 pub session: String,
37 pub started_at: String,
40 pub checkpoint_at: String,
43 pub invocation: u32,
48 pub phases: Vec<PhaseEntry>,
52}
53
54#[derive(Clone, Debug, Serialize, Deserialize)]
56pub struct PhaseEntry {
57 #[serde(flatten)]
62 pub identity: PhaseIdentity,
63 pub skip_eligible: bool,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub params_consumed: Option<String>,
78 pub status: PhaseStatus,
80 #[serde(default)]
85 pub duration_secs: Option<f64>,
86 #[serde(default)]
90 pub op_counts: Option<OpCounts>,
91 #[serde(default)]
97 pub cursor_state: Option<serde_json::Value>,
98 #[serde(default)]
103 pub error: Option<String>,
104}
105
106#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "lowercase")]
114pub enum PhaseStatus {
115 Pending,
116 Running,
117 Completed,
118 Failed,
119}
120
121impl From<crate::scene_tree::PhaseStatus> for PhaseStatus {
122 fn from(s: crate::scene_tree::PhaseStatus) -> Self {
123 match s {
124 crate::scene_tree::PhaseStatus::Pending => Self::Pending,
125 crate::scene_tree::PhaseStatus::Running => Self::Running,
126 crate::scene_tree::PhaseStatus::Completed => Self::Completed,
127 crate::scene_tree::PhaseStatus::Failed(_) => Self::Failed,
128 }
129 }
130}
131
132#[derive(Clone, Debug, Default, Serialize, Deserialize)]
134pub struct OpCounts {
135 pub started: u64,
136 pub finished: u64,
137 pub errors: u64,
138}
139
140pub fn now_rfc3339() -> String {
146 let dur = std::time::SystemTime::now()
147 .duration_since(std::time::UNIX_EPOCH)
148 .unwrap_or_default();
149 let secs = dur.as_secs();
150 let days = secs / 86400;
151 let time_of_day = secs % 86400;
152 let hours = time_of_day / 3600;
153 let minutes = (time_of_day % 3600) / 60;
154 let seconds = time_of_day % 60;
155 let (year, month, day) = days_to_ymd(days);
156 format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
157}
158
159fn days_to_ymd(days: u64) -> (u64, u64, u64) {
160 let z = days + 719468;
161 let era = z / 146097;
162 let doe = z - era * 146097;
163 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
164 let y = yoe + era * 400;
165 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
166 let mp = (5 * doy + 2) / 153;
167 let d = doy - (153 * mp + 2) / 5 + 1;
168 let m = if mp < 10 { mp + 3 } else { mp - 9 };
169 let y = if m <= 2 { y + 1 } else { y };
170 (y, m, d)
171}
172
173pub fn iter_events(path: &Path) -> Result<Option<EventIter>, String> {
180 match std::fs::File::open(path) {
181 Ok(f) => {
182 let reader = BufReader::new(f);
183 Ok(Some(EventIter {
184 lines: reader.lines(),
185 path: path.to_path_buf(),
186 }))
187 }
188 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
189 Err(e) => Err(format!("read checkpoint log {}: {e}", path.display())),
190 }
191}
192
193pub struct EventIter {
195 lines: std::io::Lines<BufReader<std::fs::File>>,
196 path: std::path::PathBuf,
197}
198
199impl Iterator for EventIter {
200 type Item = Result<CheckpointData, String>;
201
202 fn next(&mut self) -> Option<Self::Item> {
203 loop {
204 let line = match self.lines.next()? {
205 Ok(l) => l,
206 Err(e) => return Some(Err(format!("read line from {}: {e}", self.path.display()))),
207 };
208 if line.trim().is_empty() {
209 continue;
210 }
211 return Some(
212 serde_json::from_str(&line)
213 .map_err(|e| format!("parse line in {}: {e}", self.path.display())),
214 );
215 }
216 }
217}
218
219pub fn read(path: &Path) -> Result<Option<Checkpoint>, String> {
225 use std::collections::HashMap;
226
227 let raw = match std::fs::read(path) {
228 Ok(b) => b,
229 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
230 Err(e) => return Err(format!("read checkpoint log {}: {e}", path.display())),
231 };
232
233 let cutoff = raw
238 .iter()
239 .rposition(|&b| b == b'\n')
240 .map(|i| i + 1)
241 .unwrap_or(0);
242 if cutoff < raw.len() {
243 eprintln!(
244 "warning: checkpoint {}: truncated tail (last {} bytes lacked newline), dropping",
245 path.display(),
246 raw.len() - cutoff,
247 );
248 }
249 let body = &raw[..cutoff];
250 let body_str = std::str::from_utf8(body)
251 .map_err(|e| format!("checkpoint log {}: invalid UTF-8: {e}", path.display()))?;
252
253 let mut lines = body_str.lines().filter(|l| !l.trim().is_empty());
255 let first_line = match lines.next() {
256 Some(l) => l,
257 None => return Ok(None), };
259 let first_event: CheckpointData = serde_json::from_str(first_line).map_err(|e| {
260 format!(
261 "checkpoint log {}: malformed first record: {e}",
262 path.display()
263 )
264 })?;
265
266 let mut doc = match first_event {
267 CheckpointData::SessionStart {
268 version,
269 session,
270 started_at,
271 invocation,
272 at,
273 ..
274 } => {
275 if version != 1 {
276 return Err(format!(
277 "checkpoint {}: unsupported version {version} (this build supports v1)",
278 path.display(),
279 ));
280 }
281 Checkpoint {
282 version,
283 session,
284 started_at,
285 checkpoint_at: at,
286 invocation,
287 phases: Vec::new(),
288 }
289 }
290 other => {
291 return Err(format!(
292 "checkpoint {}: first record must be session_start, got {:?}",
293 path.display(),
294 discriminator(&other),
295 ));
296 }
297 };
298
299 let mut index: HashMap<String, usize> = HashMap::new();
300
301 for line in lines {
302 let event: CheckpointData = match serde_json::from_str(line) {
303 Ok(e) => e,
304 Err(e) => {
305 eprintln!(
314 "warning: checkpoint {}: ignoring unparseable line: {e}",
315 path.display(),
316 );
317 continue;
318 }
319 };
320 apply_event(&mut doc, &mut index, event);
321 }
322
323 Ok(Some(doc))
324}
325
326pub fn latest_adapter_position(
330 path: &Path,
331 adapter: &str,
332 key: &str,
333) -> Result<Option<serde_json::Value>, String> {
334 let Some(events) = iter_events(path)? else {
335 return Ok(None);
336 };
337 let mut latest = None;
338 for event in events.flatten() {
339 if let CheckpointData::AdapterPosition {
340 adapter: a,
341 key: k,
342 position,
343 ..
344 } = event
345 && a == adapter
346 && k == key
347 {
348 latest = Some(position);
349 }
350 }
351 Ok(latest)
352}
353
354fn discriminator(e: &CheckpointData) -> &'static str {
355 match e {
356 CheckpointData::SessionStart { .. } => "session_start",
357 CheckpointData::SessionEnd { .. } => "session_end",
358 CheckpointData::PhaseDeclared { .. } => "phase_declared",
359 CheckpointData::PhaseStarted { .. } => "phase_started",
360 CheckpointData::PhaseProgress { .. } => "phase_progress",
361 CheckpointData::PhaseCompleted { .. } => "phase_completed",
362 CheckpointData::PhaseFailed { .. } => "phase_failed",
363 CheckpointData::PhaseHash { .. } => "phase_hash",
364 CheckpointData::ScopeEnter { .. } => "scope_enter",
365 CheckpointData::ScopeExit { .. } => "scope_exit",
366 CheckpointData::AdapterPosition { .. } => "adapter_position",
367 }
368}
369
370fn apply_event(
371 doc: &mut Checkpoint,
372 index: &mut std::collections::HashMap<String, usize>,
373 event: CheckpointData,
374) {
375 match event {
376 CheckpointData::SessionStart {
377 invocation,
378 at,
379 started_at,
380 session,
381 ..
382 } => {
383 doc.invocation = invocation;
387 doc.checkpoint_at = at;
388 doc.started_at = started_at;
389 doc.session = session;
390 }
391 CheckpointData::SessionEnd { at, .. } => {
392 doc.checkpoint_at = at;
393 }
394 CheckpointData::PhaseDeclared {
395 at,
396 identity,
397 skip_eligible,
398 } => {
399 let key = super::writer::identity_key(&identity);
400 if let std::collections::hash_map::Entry::Vacant(e) = index.entry(key) {
401 doc.phases.push(PhaseEntry {
402 identity,
403 skip_eligible,
404 params_consumed: None,
405 status: PhaseStatus::Pending,
406 duration_secs: None,
407 op_counts: None,
408 cursor_state: None,
409 error: None,
410 });
411 e.insert(doc.phases.len() - 1);
412 }
413 doc.checkpoint_at = at;
414 }
415 CheckpointData::PhaseStarted { at, identity } => {
416 if let Some(entry) = lookup_mut(doc, index, &identity) {
417 entry.status = PhaseStatus::Running;
418 entry.error = None;
419 }
420 doc.checkpoint_at = at;
421 }
422 CheckpointData::PhaseProgress {
423 at,
424 identity,
425 op_counts,
426 cursor_state,
427 } => {
428 if let Some(entry) = lookup_mut(doc, index, &identity) {
429 entry.op_counts = Some(op_counts);
430 if cursor_state.is_some() {
431 entry.cursor_state = cursor_state;
432 }
433 }
434 doc.checkpoint_at = at;
435 }
436 CheckpointData::PhaseCompleted {
437 at,
438 identity,
439 duration_secs,
440 op_counts,
441 } => {
442 if let Some(entry) = lookup_mut(doc, index, &identity) {
443 entry.status = PhaseStatus::Completed;
444 entry.duration_secs = Some(duration_secs);
445 entry.op_counts = Some(op_counts);
446 entry.cursor_state = None;
447 entry.error = None;
448 }
449 doc.checkpoint_at = at;
450 }
451 CheckpointData::PhaseFailed {
452 at,
453 identity,
454 error,
455 op_counts,
456 } => {
457 if let Some(entry) = lookup_mut(doc, index, &identity) {
458 entry.status = PhaseStatus::Failed;
459 entry.error = Some(error);
460 if let Some(c) = op_counts {
461 entry.op_counts = Some(c);
462 }
463 entry.cursor_state = None;
464 }
465 doc.checkpoint_at = at;
466 }
467 CheckpointData::PhaseHash {
468 at,
469 identity,
470 hash_hex,
471 params_consumed,
472 } => {
473 if let Some(entry) = lookup_mut(doc, index, &identity)
474 && let Some(h) = hex_to_hash(&hash_hex)
475 {
476 entry.identity.phase_hash = Some(h);
477 entry.params_consumed = params_consumed;
478 }
479 doc.checkpoint_at = at;
480 }
481 CheckpointData::ScopeEnter { at, .. } | CheckpointData::ScopeExit { at, .. } => {
482 doc.checkpoint_at = at;
485 }
486 CheckpointData::AdapterPosition { at, .. } => {
487 doc.checkpoint_at = at;
491 }
492 }
493}
494
495fn lookup_mut<'a>(
496 doc: &'a mut Checkpoint,
497 index: &std::collections::HashMap<String, usize>,
498 identity: &PhaseIdentity,
499) -> Option<&'a mut PhaseEntry> {
500 let key = super::writer::identity_key(identity);
501 let idx = *index.get(&key)?;
502 Some(&mut doc.phases[idx])
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508 use crate::checkpoint::CheckpointWriter;
509 use crate::checkpoint::PathSegment;
510 use crate::checkpoint::PhaseIdentity;
511
512 fn ident(name: &str) -> PhaseIdentity {
513 PhaseIdentity {
514 yaml_path: vec![
515 PathSegment::Scenario("test".into()),
516 PathSegment::Phase(name.into()),
517 ],
518 coords: String::new(),
519 phase_hash: None,
520 }
521 }
522
523 #[test]
524 fn read_missing_file_yields_none() {
525 let dir = tempdir();
526 let path = dir.join("nonexistent.jsonl");
527 let result = read(&path).expect("read should not error on missing file");
528 assert!(result.is_none());
529 }
530
531 #[test]
532 fn read_empty_file_yields_none() {
533 let dir = tempdir();
534 let path = dir.join("empty.jsonl");
535 std::fs::write(&path, "").expect("write");
536 let result = read(&path).expect("read should not error on empty file");
537 assert!(result.is_none(), "empty log = fresh session");
538 }
539
540 #[test]
541 fn fold_full_lifecycle_matches_in_memory_snapshot() {
542 let dir = tempdir();
546 let path = dir.join("checkpoint.jsonl");
547 let snap_in_memory = {
548 let w = CheckpointWriter::new(
549 path.clone(),
550 "sess".into(),
551 "2026-01-01T00:00:00Z".into(),
552 1,
553 );
554 let id1 = ident("schema");
555 let id2 = ident("rampup");
556 w.declare_phase(id1.clone(), true);
557 w.declare_phase(id2.clone(), true);
558 w.phase_started(&id1);
559 w.phase_completed(&id1, 1.5);
560 w.phase_started(&id2);
561 w.update_op_counts(
562 &id2,
563 OpCounts {
564 started: 100,
565 finished: 99,
566 errors: 1,
567 },
568 );
569 w.flush().expect("flush");
570 w.snapshot()
571 };
572 let folded = read(&path).expect("read").expect("present");
573 assert_eq!(folded.session, snap_in_memory.session);
574 assert_eq!(folded.invocation, snap_in_memory.invocation);
575 assert_eq!(folded.phases.len(), snap_in_memory.phases.len());
576 for (i, phase) in folded.phases.iter().enumerate() {
577 assert_eq!(
578 phase.status, snap_in_memory.phases[i].status,
579 "status mismatch on phase {i}"
580 );
581 assert_eq!(phase.skip_eligible, snap_in_memory.phases[i].skip_eligible);
582 assert_eq!(phase.duration_secs, snap_in_memory.phases[i].duration_secs);
583 assert_eq!(
584 phase.op_counts.as_ref().map(|c| c.started),
585 snap_in_memory.phases[i]
586 .op_counts
587 .as_ref()
588 .map(|c| c.started)
589 );
590 }
591 }
592
593 #[test]
594 fn truncated_tail_is_recovered() {
595 let dir = tempdir();
596 let path = dir.join("checkpoint.jsonl");
597 {
598 let w =
599 CheckpointWriter::new(path.clone(), "s".into(), "2026-01-01T00:00:00Z".into(), 1);
600 w.declare_phase(ident("p"), true);
601 w.flush().expect("flush");
602 }
603 use std::io::Write;
606 let mut f = std::fs::OpenOptions::new()
607 .append(true)
608 .open(&path)
609 .unwrap();
610 f.write_all(b"{\"type\":\"phase_started\",\"at\":\"2026-")
611 .unwrap();
612 drop(f);
613
614 let folded = read(&path).expect("read should recover").expect("present");
615 assert_eq!(folded.phases.len(), 1);
617 }
618
619 #[test]
620 fn first_record_must_be_session_start() {
621 let dir = tempdir();
622 let path = dir.join("checkpoint.jsonl");
623 let body = r#"{"type":"phase_started","at":"x","identity":{"yaml_path":[],"coords":""}}"#;
626 std::fs::write(&path, format!("{body}\n")).expect("write");
627 let err = read(&path).expect_err("first-record check must error");
628 assert!(
629 err.contains("first record must be session_start"),
630 "got: {err}"
631 );
632 }
633
634 #[test]
635 fn unsupported_version_in_session_start_errors() {
636 let dir = tempdir();
637 let path = dir.join("checkpoint.jsonl");
638 let body = r#"{"type":"session_start","at":"t","version":99,"session":"x","started_at":"t","invocation":1}"#;
639 std::fs::write(&path, format!("{body}\n")).expect("write");
640 let err = read(&path).expect_err("expected version-mismatch error");
641 assert!(err.contains("version 99"), "got: {err}");
642 }
643
644 fn tempdir() -> std::path::PathBuf {
645 let d = std::env::temp_dir().join(format!("nmbrs-checkpoint-test-{}", rand_suffix()));
646 std::fs::create_dir_all(&d).unwrap();
647 d
648 }
649
650 fn rand_suffix() -> String {
651 crate::scratch_suffix()
652 }
653}