1use std::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15
16use crate::layer::Line;
17use crate::manifest::LayerManifest;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum RollbackVerdict {
22 Accept,
24 Rollback {
26 line: String,
27 presented: u64,
28 high_water: u64,
29 },
30 BelowFloor {
44 line: String,
45 presented: u64,
46 floor: u64,
47 },
48}
49
50#[derive(Debug)]
53pub struct HighWaterMarks {
54 path: PathBuf,
55 marks: BTreeMap<String, u64>,
56 carried: Carried,
59}
60
61#[derive(Debug, Default)]
62struct Carried {
63 index: BTreeMap<String, crate::lineindex::LineIndex>,
64 status: BTreeMap<String, crate::linestatus::LineStatus>,
65}
66
67#[derive(Debug, thiserror::Error)]
68pub enum RollbackError {
69 #[error("io error at {path}")]
73 Io {
74 path: String,
75 #[source]
76 source: std::io::Error,
77 },
78 #[error(
79 "{path}: high-water-mark state is corrupt: {reason} — refusing to guess; repair or remove the file"
80 )]
81 Corrupt { path: String, reason: String },
82}
83
84impl HighWaterMarks {
85 pub fn load(root: &Path) -> Result<Self, RollbackError> {
87 let path = root.join("state").join("high-water-marks.json");
88 let marks = match std::fs::read(&path) {
89 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| RollbackError::Corrupt {
90 path: path.display().to_string(),
91 reason: e.to_string(),
92 })?,
93 Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
94 Err(source) => {
95 return Err(RollbackError::Io {
96 path: path.display().to_string(),
97 source,
98 });
99 }
100 };
101 Ok(HighWaterMarks {
102 path,
103 marks,
104 carried: Carried::default(),
105 })
106 }
107
108 pub fn carry_index(&mut self, doc: crate::lineindex::LineIndex) {
120 let keep = self
121 .carried
122 .index
123 .get(&doc.line)
124 .is_none_or(|have| doc.counter > have.counter);
125 if keep {
126 self.carried.index.insert(doc.line.clone(), doc);
127 }
128 }
129
130 pub fn carried_index(&self, line: &str) -> Option<crate::lineindex::LineIndex> {
132 self.carried.index.get(line).cloned()
133 }
134
135 pub fn carry_status(&mut self, doc: crate::linestatus::LineStatus) {
137 let keep = self
138 .carried
139 .status
140 .get(&doc.line)
141 .is_none_or(|have| doc.counter > have.counter);
142 if keep {
143 self.carried.status.insert(doc.line.clone(), doc);
144 }
145 }
146
147 pub fn carried_status(&self, line: &str) -> Option<crate::linestatus::LineStatus> {
149 self.carried.status.get(line).cloned()
150 }
151
152 pub fn mark(&self, line: &Line) -> Option<u64> {
154 self.marks.get(&line.to_string()).copied()
155 }
156
157 pub fn check(&self, manifest: &LayerManifest) -> RollbackVerdict {
161 self.check_with_floor(manifest, None)
162 }
163
164 pub fn check_with_floor(
177 &self,
178 manifest: &LayerManifest,
179 floor: Option<u64>,
180 ) -> RollbackVerdict {
181 let line = manifest.layer.line().to_string();
182 match self.marks.get(&line) {
183 Some(&high_water) if manifest.counter < high_water => RollbackVerdict::Rollback {
184 line,
185 presented: manifest.counter,
186 high_water,
187 },
188 Some(_) => RollbackVerdict::Accept,
192 None => match floor {
193 Some(floor) if manifest.counter < floor => RollbackVerdict::BelowFloor {
194 line,
195 presented: manifest.counter,
196 floor,
197 },
198 _ => RollbackVerdict::Accept,
199 },
200 }
201 }
202
203 pub fn advance(&mut self, manifest: &LayerManifest) -> Result<(), RollbackError> {
206 let line = manifest.layer.line().to_string();
207 let mark = self.marks.entry(line).or_insert(0);
208 *mark = (*mark).max(manifest.counter);
209 self.persist()
210 }
211
212 fn persist(&self) -> Result<(), RollbackError> {
213 let io = |path: &Path, source: std::io::Error| RollbackError::Io {
214 path: path.display().to_string(),
215 source,
216 };
217 let dir = self.path.parent().expect("state file has a parent");
218 std::fs::create_dir_all(dir).map_err(|e| io(dir, e))?;
219 let bytes = serde_json::to_vec_pretty(&self.marks).expect("marks serialize");
220 std::fs::write(&self.path, bytes).map_err(|e| io(&self.path, e))?;
221 Ok(())
222 }
223}
224
225pub fn staleness_warning(issued_at: &str, now: &str, threshold_days: u32) -> Option<i64> {
231 let age = epoch_days(now)? - epoch_days(issued_at)?;
232 (age > i64::from(threshold_days)).then_some(age)
233}
234
235pub fn epoch_days(rfc3339: &str) -> Option<i64> {
242 let date = rfc3339.split_once('T').map_or(rfc3339, |(d, _)| d);
246 let b = date.as_bytes();
247 if date.len() != 10 || b[4] != b'-' || b[7] != b'-' {
248 return None;
249 }
250 let y: i64 = date[0..4].parse().ok()?;
251 let m: i64 = date[5..7].parse().ok()?;
252 let d: i64 = date[8..10].parse().ok()?;
253 if !(1..=12).contains(&m) {
254 return None;
255 }
256 let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
259 let dim = [
260 31,
261 if leap { 29 } else { 28 },
262 31,
263 30,
264 31,
265 30,
266 31,
267 31,
268 30,
269 31,
270 30,
271 31,
272 ];
273 if d < 1 || d > dim[(m - 1) as usize] {
274 return None;
275 }
276 let y = y - i64::from(m <= 2);
278 let era = if y >= 0 { y } else { y - 399 } / 400;
279 let yoe = y - era * 400;
280 let mp = (m + 9) % 12;
281 let doy = (153 * mp + 2) / 5 + d - 1;
282 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
283 Some(era * 146_097 + doe - 719_468)
284}
285
286#[cfg(test)]
287mod tests {
288 fn idx(line: &str, counter: u64, digest: &str) -> crate::lineindex::LineIndex {
289 crate::lineindex::LineIndex {
290 line: line.into(),
291 counter,
292 issued_at: "2026-08-18T00:00:00Z".into(),
293 layers: vec![crate::lineindex::IndexedLayer {
294 layer: format!("{line}.0"),
295 digest: digest.into(),
296 channel: "rolling".into(),
297 counter: 1,
298 }],
299 }
300 }
301
302 fn status(line: &str, counter: u64, min: Option<u64>) -> crate::linestatus::LineStatus {
303 crate::linestatus::LineStatus {
304 line: line.into(),
305 counter,
306 issued_at: "2026-08-18T00:00:00Z".into(),
307 support_until: None,
308 min_counter: min,
309 yanked: Default::default(),
310 known_problems: Vec::new(),
311 }
312 }
313
314 #[test]
316 fn carried_documents_keep_the_highest_counter_per_line_and_never_touch_disk() {
317 let tmp = tempfile::tempdir().unwrap();
318 let mut marks = HighWaterMarks::load(tmp.path()).unwrap();
319 assert!(marks.carried_index("2026.08").is_none());
320 assert!(marks.carried_status("2026.08").is_none());
321
322 marks.carry_index(idx("2026.08", 5, "sha256:aa"));
323 marks.carry_index(idx("2026.08", 2, "sha256:bb"));
325 marks.carry_index(idx("2026.08", 5, "sha256:cc"));
326 assert_eq!(
327 marks.carried_index("2026.08"),
328 Some(idx("2026.08", 5, "sha256:aa"))
329 );
330 marks.carry_index(idx("2026.08", 7, "sha256:dd"));
331 assert_eq!(marks.carried_index("2026.08").unwrap().counter, 7);
332 assert!(marks.carried_index("2026.09").is_none());
334
335 marks.carry_status(status("2026.08", 3, Some(5)));
336 marks.carry_status(status("2026.08", 2, None));
337 assert_eq!(
338 marks.carried_status("2026.08"),
339 Some(status("2026.08", 3, Some(5)))
340 );
341 marks.carry_status(status("2026.08", 3, Some(9)));
343 assert_eq!(
344 marks.carried_status("2026.08"),
345 Some(status("2026.08", 3, Some(5)))
346 );
347 marks.carry_status(status("2026.08", 4, Some(6)));
348 assert_eq!(
349 marks.carried_status("2026.08").unwrap().min_counter,
350 Some(6)
351 );
352 assert!(marks.carried_status("2026.09").is_none());
353
354 assert!(
356 HighWaterMarks::load(tmp.path())
357 .unwrap()
358 .carried_index("2026.08")
359 .is_none()
360 );
361 assert!(!tmp.path().join("state").exists());
362 }
363
364 #[test]
366 fn the_leap_rule_holds_at_the_year_the_solver_found() {
367 assert!(
375 epoch_days("8192-02-29").is_some(),
376 "8192 is a leap year: 8192-02-29 must be a real date"
377 );
378 assert!(
380 epoch_days("8100-02-29").is_none(),
381 "8100 %% 100 == 0, %% 400 != 0"
382 );
383 assert!(epoch_days("8000-02-29").is_some(), "8000 %% 400 == 0");
384 assert!(
385 epoch_days("8193-02-29").is_none(),
386 "8193 is not divisible by 4"
387 );
388 }
389 use super::*;
390 use crate::manifest::{LayerManifest, fixtures};
391
392 fn manifest(layer: &str, counter: u64) -> LayerManifest {
393 LayerManifest::parse(&fixtures::manifest(
394 layer,
395 "qualified",
396 counter,
397 "2026-07-31T09:14:00Z",
398 ))
399 .unwrap()
400 }
401
402 #[test]
404 fn first_contact_accepts_and_advance_records_the_mark() {
405 let tmp = tempfile::tempdir().unwrap();
406 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
407 let m = manifest("2026.07.0", 3);
408 assert_eq!(hwm.check(&m), RollbackVerdict::Accept);
409 assert_eq!(hwm.mark(m.layer.line()), None, "check must not advance");
410 hwm.advance(&m).unwrap();
411 assert_eq!(hwm.mark(m.layer.line()), Some(3));
412 }
413
414 #[test]
427 fn advance_never_lowers_a_mark_however_it_is_called() {
428 let tmp = tempfile::tempdir().unwrap();
429 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
430 hwm.advance(&manifest("2026.07.3", 9)).unwrap();
431 assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(9));
432
433 for lower in [8, 4, 1, 0] {
435 hwm.advance(&manifest("2026.07.0", lower)).unwrap();
436 assert_eq!(
437 hwm.mark(manifest("2026.07.0", 1).layer.line()),
438 Some(9),
439 "advancing with counter {lower} lowered the mark"
440 );
441 }
442 hwm.advance(&manifest("2026.07.3", 9)).unwrap();
444 assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(9));
445 hwm.advance(&manifest("2026.07.4", 10)).unwrap();
446 assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(10));
447
448 let reloaded = HighWaterMarks::load(tmp.path()).unwrap();
451 assert_eq!(
452 reloaded.mark(manifest("2026.07.0", 1).layer.line()),
453 Some(10),
454 "the mark did not persist at its highest value"
455 );
456 }
457
458 #[test]
460 fn a_counter_below_the_mark_is_rejected() {
461 let tmp = tempfile::tempdir().unwrap();
462 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
463 hwm.advance(&manifest("2026.07.1", 4)).unwrap();
464 let verdict = hwm.check(&manifest("2026.07.0", 3));
465 assert_eq!(
466 verdict,
467 RollbackVerdict::Rollback {
468 line: "2026.07".into(),
469 presented: 3,
470 high_water: 4
471 }
472 );
473 }
474
475 #[test]
477 fn an_equal_counter_reinstalls_cleanly() {
478 let tmp = tempfile::tempdir().unwrap();
479 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
480 hwm.advance(&manifest("2026.07.0", 3)).unwrap();
481 assert_eq!(
482 hwm.check(&manifest("2026.07.0", 3)),
483 RollbackVerdict::Accept
484 );
485 }
486
487 #[test]
489 fn counters_are_scoped_per_line() {
490 let tmp = tempfile::tempdir().unwrap();
491 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
492 hwm.advance(&manifest("2026.08.0", 9)).unwrap();
493 assert_eq!(
496 hwm.check(&manifest("2026.07.0", 1)),
497 RollbackVerdict::Accept
498 );
499 }
500
501 #[test]
503 fn marks_survive_a_new_session() {
504 let tmp = tempfile::tempdir().unwrap();
505 {
506 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
507 hwm.advance(&manifest("2026.07.1", 5)).unwrap();
508 }
509 let hwm = HighWaterMarks::load(tmp.path()).unwrap();
510 assert_eq!(
511 hwm.check(&manifest("2026.07.0", 2)),
512 RollbackVerdict::Rollback {
513 line: "2026.07".into(),
514 presented: 2,
515 high_water: 5
516 }
517 );
518 }
519
520 #[test]
522 fn advance_never_lowers_a_mark() {
523 let tmp = tempfile::tempdir().unwrap();
524 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
525 hwm.advance(&manifest("2026.07.1", 5)).unwrap();
526 hwm.advance(&manifest("2026.07.0", 2)).unwrap();
527 assert_eq!(hwm.mark(manifest("2026.07.0", 2).layer.line()), Some(5));
528 }
529
530 #[test]
532 fn corrupt_state_is_an_error_not_a_reset() {
533 let tmp = tempfile::tempdir().unwrap();
534 let state_dir = tmp.path().join("state");
535 std::fs::create_dir_all(&state_dir).unwrap();
536 std::fs::write(state_dir.join("high-water-marks.json"), b"{ nope").unwrap();
537 assert!(matches!(
539 HighWaterMarks::load(tmp.path()),
540 Err(RollbackError::Corrupt { .. })
541 ));
542 }
543
544 #[test]
546 fn epoch_day_arithmetic_matches_the_civil_calendar() {
547 for (ts, days) in [
552 ("1970-01-01T00:00:00Z", 0i64),
553 ("1970-01-02T00:00:00Z", 1),
554 ("1969-12-31T00:00:00Z", -1),
555 ("2000-02-29T00:00:00Z", 11016),
556 ("2026-08-07T00:00:00Z", 20672),
557 ("2026-03-01T00:00:00Z", 20513),
558 ("2024-02-29T00:00:00Z", 19782),
559 ("2100-01-01T00:00:00Z", 47482),
560 ("1900-03-01T00:00:00Z", -25508),
561 ("2026-12-31T00:00:00Z", 20818),
562 ("0000-03-01T00:00:00Z", -719468),
563 ("0000-01-01T00:00:00Z", -719528),
564 ("0000-02-29T00:00:00Z", -719469),
565 ] {
566 assert_eq!(epoch_days(ts), Some(days), "epoch_days({ts})");
567 }
568 for bad in [
570 "2026-13-01T00:00:00Z",
571 "2026-00-01T00:00:00Z",
572 "2026-01-32T00:00:00Z",
573 "2026-01-00T00:00:00Z",
574 ] {
575 assert_eq!(epoch_days(bad), None, "{bad}");
576 }
577 }
578
579 #[test]
581 fn epoch_days_enforces_the_exact_yyyy_mm_dd_t_shape() {
582 assert_eq!(epoch_days("2026-08-07"), Some(20672));
584 assert_eq!(epoch_days("2026-08-07 00:00:00Z"), None, "space, not T");
585 assert_eq!(epoch_days("2026-08-07X"), None, "non-T separator");
586 for bad in [
588 "2026-08-7T00:00:00Z", "2026X08-07T00:00:00Z", "2026-08X07T00:00:00Z", "202608-07T00:00:00Z", ] {
593 assert_eq!(epoch_days(bad), None, "{bad}");
594 }
595 }
596
597 #[test]
599 fn epoch_days_applies_the_full_gregorian_leap_rule() {
600 assert!(epoch_days("2024-02-29T00:00:00Z").is_some(), "2024 %4 leap");
603 assert_eq!(epoch_days("2023-02-29T00:00:00Z"), None, "2023 non-leap");
604 assert_eq!(
605 epoch_days("1900-02-29T00:00:00Z"),
606 None,
607 "1900 %100 non-leap"
608 );
609 assert!(
610 epoch_days("2000-02-29T00:00:00Z").is_some(),
611 "2000 %400 leap"
612 );
613 assert!(epoch_days("2023-02-28T00:00:00Z").is_some());
615 assert_eq!(epoch_days("2024-02-30T00:00:00Z"), None);
616 assert!(epoch_days("2026-04-30T00:00:00Z").is_some());
618 assert_eq!(epoch_days("2026-04-31T00:00:00Z"), None, "April has 30");
619 }
620
621 #[test]
623 fn staleness_threshold_boundary_is_strictly_greater_than() {
624 assert_eq!(
626 staleness_warning("2026-07-01T00:00:00Z", "2026-07-31T00:00:00Z", 30),
627 None
628 );
629 assert_eq!(
630 staleness_warning("2026-07-01T00:00:00Z", "2026-08-01T00:00:00Z", 30),
631 Some(31)
632 );
633 }
634
635 #[test]
637 fn an_unreadable_state_file_is_an_io_error_not_first_contact() {
638 let tmp = tempfile::tempdir().unwrap();
642 std::fs::create_dir_all(tmp.path().join("state/high-water-marks.json")).unwrap();
643 assert!(matches!(
644 HighWaterMarks::load(tmp.path()),
645 Err(RollbackError::Io { .. })
646 ));
647 }
648
649 #[test]
651 fn staleness_is_a_pure_function_of_issued_at_now_and_threshold() {
652 assert_eq!(
654 staleness_warning("2026-04-01T00:00:00Z", "2026-07-10T00:00:00Z", 90),
655 Some(100)
656 );
657 assert_eq!(
659 staleness_warning("2026-06-30T00:00:00Z", "2026-07-10T00:00:00Z", 90),
660 None
661 );
662 assert_eq!(
666 staleness_warning("2026-08-01T00:00:00Z", "2026-07-10T00:00:00Z", 90),
667 None
668 );
669 }
670}
671
672#[cfg(test)]
673mod first_contact_tests {
674 use super::*;
675
676 use crate::manifest::{LayerManifest, fixtures};
677
678 fn manifest(layer: &str, counter: u64) -> LayerManifest {
679 LayerManifest::parse(&fixtures::manifest(
680 layer,
681 "qualified",
682 counter,
683 "2026-07-31T09:14:00Z",
684 ))
685 .unwrap()
686 }
687
688 fn fresh() -> (tempfile::TempDir, HighWaterMarks) {
691 let tmp = tempfile::tempdir().unwrap();
692 let hwm = HighWaterMarks::load(tmp.path()).unwrap();
693 (tmp, hwm)
694 }
695
696 fn with_mark(line: &str, counter: u64) -> (tempfile::TempDir, HighWaterMarks) {
697 let tmp = tempfile::tempdir().unwrap();
698 let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
699 hwm.advance(&manifest(&format!("{line}.{counter}"), counter))
700 .unwrap();
701 (tmp, hwm)
702 }
703
704 #[test]
712 fn a_first_contact_below_the_signed_floor_is_refused() {
713 let (_t, hwm) = fresh();
714 assert_eq!(
716 hwm.check(&manifest("2026.07.2", 2)),
717 RollbackVerdict::Accept
718 );
719 match hwm.check_with_floor(&manifest("2026.07.2", 2), Some(5)) {
721 RollbackVerdict::BelowFloor {
722 line,
723 presented,
724 floor,
725 } => {
726 assert_eq!(line, "2026.07");
727 assert_eq!(presented, 2);
728 assert_eq!(floor, 5);
729 }
730 other => panic!("expected BelowFloor, got {other:?}"),
731 }
732 }
733
734 #[test]
736 fn a_first_contact_at_or_above_the_floor_is_accepted() {
737 let (_t, hwm) = fresh();
738 assert_eq!(
739 hwm.check_with_floor(&manifest("2026.07.5", 5), Some(5)),
740 RollbackVerdict::Accept
741 );
742 assert_eq!(
743 hwm.check_with_floor(&manifest("2026.07.9", 9), Some(5)),
744 RollbackVerdict::Accept
745 );
746 }
747
748 #[test]
753 fn a_floor_below_a_recorded_mark_does_not_reopen_the_window() {
754 let (_t, hwm) = with_mark("2026.07", 9);
755 match hwm.check_with_floor(&manifest("2026.07.3", 3), Some(3)) {
756 RollbackVerdict::Rollback { high_water, .. } => assert_eq!(high_water, 9),
757 other => panic!("the local mark must still win: {other:?}"),
758 }
759 }
760
761 #[test]
765 fn a_line_with_no_stated_floor_is_unchanged() {
766 let (_t, hwm) = fresh();
767 assert_eq!(
768 hwm.check_with_floor(&manifest("2026.07.0", 0), None),
769 RollbackVerdict::Accept
770 );
771 assert_eq!(
772 hwm.check(&manifest("2026.07.0", 0)),
773 hwm.check_with_floor(&manifest("2026.07.0", 0), None)
774 );
775 }
776
777 #[test]
783 fn a_floor_of_zero_accepts_everything_exactly_as_no_floor_does() {
784 let (_t, hwm) = fresh();
785 assert_eq!(
786 hwm.check_with_floor(&manifest("2026.07.0", 0), Some(0)),
787 RollbackVerdict::Accept
788 );
789 }
790
791 #[test]
795 fn the_floor_applies_to_the_line_it_was_stated_for() {
796 let (_t, hwm) = with_mark("2026.07", 9);
797 match hwm.check_with_floor(&manifest("2026.08.1", 1), Some(4)) {
799 RollbackVerdict::BelowFloor { line, .. } => assert_eq!(line, "2026.08"),
800 other => panic!("{other:?}"),
801 }
802 }
803}