Coverage for retraining/run_resume.py: 100%

69 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Resumable runs (V6.6.10): one folder per long run, holding what it needs to continue after a stop (a reboot, a pause for the night). 

2 

3A run folder keeps `resume.json` (the run's settings, written when it starts) and `state.json` (each finished step, written after it). 

4`aq cycle retrain --resume`, `aq train --resume` and `aq pipeline run --resume` find the run to continue here, and `--list-runs` lists 

5them. A run is finished when its record says so or its last step is in its state; anything else can be resumed. Stdlib only. 

6""" 

7 

8from __future__ import annotations 

9 

10import datetime 

11import json 

12import secrets 

13from collections.abc import Sequence 

14from pathlib import Path 

15from typing import Any 

16 

17RECORD = "resume.json" 

18STATE = "state.json" 

19 

20 

21def now() -> str: 

22 return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat() 

23 

24 

25def new_run_id() -> str: 

26 """A date-stamped id that sorts in time and does not collide.""" 

27 return f"{datetime.datetime.now(datetime.timezone.utc):%Y%m%d}_{secrets.token_hex(3)}" 

28 

29 

30def read_json(path: Path, default: Any = None) -> Any: 

31 try: 

32 return json.loads(Path(path).read_text(encoding="utf-8")) 

33 except (OSError, ValueError): 

34 return default 

35 

36 

37def write_json(path: Path, payload: Any) -> None: 

38 """Written beside its final name and renamed into place: a stop mid-write never leaves a torn record to resume from.""" 

39 path = Path(path) 

40 path.parent.mkdir(parents=True, exist_ok=True) 

41 partial = path.with_name(path.name + ".partial") 

42 partial.write_text(json.dumps(payload, indent=1, default=str), encoding="utf-8", newline="\n") 

43 partial.replace(path) 

44 

45 

46def start_record(folder: Path, record: dict[str, Any]) -> dict[str, Any]: 

47 """The run's record, written once when it starts (an existing one is kept: a resumed run keeps its own settings).""" 

48 existing = read_json(Path(folder) / RECORD) 

49 if isinstance(existing, dict): 

50 return existing 

51 payload = {"started": now(), "finished": False, **record} 

52 write_json(Path(folder) / RECORD, payload) 

53 return payload 

54 

55 

56def update_record(folder: Path, **changes: Any) -> dict[str, Any]: 

57 """The run's record with `changes` merged in, written back (a version id once chosen, or `finished=True` at the end).""" 

58 record = {**(read_json(Path(folder) / RECORD, {}) or {}), **changes} 

59 write_json(Path(folder) / RECORD, record) 

60 return record 

61 

62 

63def done_steps(folder: Path) -> list[str]: 

64 """The steps a run has finished, in the order they finished.""" 

65 return list((read_json(Path(folder) / STATE, {}) or {}).get("done", {})) 

66 

67 

68def mark_done(folder: Path, step: str, result: Any = None) -> None: 

69 """Records `step` as finished, with its time and result: a resumed run skips it.""" 

70 state = read_json(Path(folder) / STATE, {}) or {} 

71 state.setdefault("done", {})[step] = {"at": now(), "result": result} 

72 write_json(Path(folder) / STATE, state) 

73 

74 

75def is_finished(folder: Path, *, last_step: str | None = None) -> bool: 

76 """Whether the run ended: its record says so, or its `last_step` is done.""" 

77 record = read_json(Path(folder) / RECORD, {}) or {} 

78 return bool(record.get("finished")) or (last_step is not None and last_step in done_steps(folder)) 

79 

80 

81def find_resumable(root: Path, prefix: str, run_id: str | None = None, *, last_step: str | None = None) -> Path | None: 

82 """The run folder to continue: `<root>/<prefix><run_id>` when named (finished or not, so a finished run reports itself rather 

83 than vanishing), else the newest one with a record that has not finished.""" 

84 if run_id: 

85 folder = Path(root) / f"{prefix}{run_id}" 

86 return folder if (folder / RECORD).exists() else None 

87 unfinished = [folder for folder in Path(root).glob(f"{prefix}*") if (folder / RECORD).exists() and not is_finished(folder, last_step=last_step)] 

88 return max(unfinished, key=lambda folder: (folder / RECORD).stat().st_mtime) if unfinished else None 

89 

90 

91def list_runs(root: Path, prefixes: Sequence[str], *, last_step: str | None = None) -> list[dict[str, Any]]: 

92 """Every run under `root` with a record, newest first: its id, kind, start, finished steps and whether it can be resumed.""" 

93 rows = [] 

94 for prefix in prefixes: 

95 for folder in Path(root).glob(f"{prefix}*"): 

96 record = read_json(folder / RECORD) 

97 if not isinstance(record, dict): 

98 continue 

99 finished = is_finished(folder, last_step=last_step) 

100 rows.append({"run_id": folder.name[len(prefix):], "kind": prefix.rstrip("_"), "started": record.get("started"), "done": done_steps(folder), 

101 "finished": finished, "resumable": not finished, "_mtime": (folder / RECORD).stat().st_mtime}) 

102 rows.sort(key=lambda row: row.pop("_mtime"), reverse=True) 

103 return rows 

104 

105 

106def render_runs(rows: Sequence[dict[str, Any]]) -> str: 

107 """`list_runs`' rows as a table for a terminal: run id, kind, start, state and the steps done.""" 

108 if not rows: 

109 return "no runs with a resume record yet" 

110 lines = [f"{'run':<26} {'kind':<9} {'started':<26} {'state':<10} steps done"] 

111 for row in rows: 

112 state = "finished" if row["finished"] else "resumable" 

113 lines.append(f"{row['run_id']:<26} {row['kind']:<9} {row['started']!s:<26} {state:<10} {', '.join(row['done']) or '-'}") 

114 return "\n".join(lines)