from __future__ import annotations import os from pathlib import Path from dx_productivity.trial_task_center.retention import ( maintain_quick_run_storage, rotate_text_log, ) def test_log_rotation_preserves_three_newest_complete_segments(tmp_path: Path) -> None: log = tmp_path / "quick-part-replace.log" for text in ("first", "second", "third", "fourth"): log.write_text(text * 4, encoding="utf-8") assert rotate_text_log(log, max_bytes=10, backup_count=3) assert not log.exists() assert log.with_name(f"{log.name}.1").read_text(encoding="utf-8") == "fourth" * 4 assert log.with_name(f"{log.name}.2").read_text(encoding="utf-8") == "third" * 4 assert log.with_name(f"{log.name}.3").read_text(encoding="utf-8") == "second" * 4 def test_history_retention_removes_only_oldest_recognized_entries(tmp_path: Path) -> None: history = tmp_path / "quick-run-history" history.mkdir() now = 2_000_000_000.0 for index in range(6): entry = history / f"batch-{index}" entry.mkdir() (entry / "evidence.bin").write_bytes(bytes(index + 1)) os.utime(entry, (now - 100 + index, now - 100 + index)) unknown = history / "operator-notes" unknown.mkdir() (unknown / "keep.txt").write_text("keep", encoding="utf-8") result = maintain_quick_run_storage( tmp_path, now=now, max_age_days=30, max_entries=3, max_bytes=1024, min_entries=2, ) assert result.removed_entries == ("batch-0", "batch-1", "batch-2") assert result.removed_bytes == 1 + 2 + 3 assert result.skipped_entries == () assert {path.name for path in history.iterdir()} == { "batch-3", "batch-4", "batch-5", "operator-notes" } def test_history_age_and_size_limits_never_delete_minimum_recent_entries(tmp_path: Path) -> None: history = tmp_path / "quick-run-history" history.mkdir() now = 2_000_000_000.0 for index in range(4): entry = history / f"recovery-{index}" entry.mkdir() (entry / "backup.bin").write_bytes(b"x" * 20) os.utime(entry, (now - 40 * 86400 + index, now - 40 * 86400 + index)) result = maintain_quick_run_storage( tmp_path, now=now, max_age_days=30, max_entries=100, max_bytes=25, min_entries=2, ) assert result.removed_entries == ("recovery-0", "recovery-1") assert {path.name for path in history.iterdir()} == {"recovery-2", "recovery-3"}