Coverage for lab/run_registry.py: 100%

71 statements  

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

1"""A lab's runs: one folder per run (`runs/<id>/run.json` plus what the run wrote), indexed by reading the folders - no 

2database. The lab's trial ledger (`trials.jsonl`) counts every run toward the deflated Sharpe's N. 

3""" 

4 

5from __future__ import annotations 

6 

7import datetime as _datetime 

8import json 

9import uuid 

10from collections.abc import Mapping 

11from pathlib import Path 

12from typing import Any 

13 

14from json_safety import atomic_write_json 

15 

16LAB_FOLDERS = ("models", "runs", "data") 

17LAB_TOML = """# Lab defaults; models/<name>/config.toml overrides them (aq lab new NAME --template mlp|multitask|tcn|linear) 

18[data] 

19dataset = "data/dataset.csv" # aq dataset build --prices closes.csv --out data/dataset.csv 

20 

21[train] 

22seeds = [7] 

23memory_profile = "standard" # low: a 4 GB machine 

24""" 

25 

26 

27def init_lab(folder: Path) -> list[str]: 

28 """Create the lab layout in `folder`; returns what was created (nothing existing is overwritten).""" 

29 created = [] 

30 folder.mkdir(parents=True, exist_ok=True) 

31 for name in LAB_FOLDERS: 

32 if not (folder / name).exists(): 

33 (folder / name).mkdir() 

34 created.append(f"{name}/") 

35 if not (folder / "lab.toml").exists(): 

36 (folder / "lab.toml").write_text(LAB_TOML, encoding="utf-8", newline="\n") 

37 created.append("lab.toml") 

38 return created 

39 

40 

41def find_lab(start: Path) -> Path | None: 

42 """The nearest folder at or above `start` holding a lab.toml.""" 

43 for folder in [start, *start.resolve().parents]: 

44 if (folder / "lab.toml").exists(): 

45 return folder 

46 return None 

47 

48 

49def new_run_id(model: str, now: _datetime.datetime | None = None) -> str: 

50 """A run id that sorts in creation order (to the microsecond: two runs can start in one second), then the model name and a 

51 short random suffix.""" 

52 stamp = (now or _datetime.datetime.now(_datetime.timezone.utc)).strftime("%Y%m%d_%H%M%S_%f") 

53 return f"{stamp}_{model}_{uuid.uuid4().hex[:6]}" 

54 

55 

56def write_run(run_dir: Path, record: Mapping[str, Any]) -> dict[str, Any]: 

57 """Merge `record` into run.json (created if missing) and return the whole record.""" 

58 path = run_dir / "run.json" 

59 current = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} 

60 current.update(record) 

61 run_dir.mkdir(parents=True, exist_ok=True) 

62 atomic_write_json(path, current, indent=2) 

63 return current 

64 

65 

66def read_run(run_dir: Path) -> dict[str, Any]: 

67 """A run folder's `run.json`.""" 

68 return json.loads((run_dir / "run.json").read_text(encoding="utf-8")) 

69 

70 

71def list_runs(lab_dir: Path) -> list[dict]: 

72 """Every run's record, newest first; a folder without run.json is skipped.""" 

73 rows = [] 

74 for folder in sorted((lab_dir / "runs").glob("*/run.json"), reverse=True): 

75 try: 

76 rows.append({"id": folder.parent.name, **json.loads(folder.read_text(encoding="utf-8"))}) 

77 except ValueError: 

78 continue 

79 return rows 

80 

81 

82def find_run(lab_dir: Path, key: str) -> Path: 

83 """A run folder by its id or a unique prefix of it ('latest' is the newest).""" 

84 runs = [] 

85 for path in sorted((lab_dir / "runs").glob("*/run.json")): 

86 try: 

87 json.loads(path.read_text(encoding="utf-8")) 

88 except ValueError: 

89 continue 

90 runs.append(path.parent) 

91 if key == "latest" and runs: 

92 return runs[-1] 

93 matches = [path for path in runs if path.name == key] or [path for path in runs if path.name.startswith(key)] 

94 if len(matches) != 1: 

95 raise KeyError(f"{'no' if not matches else 'more than one'} run matches {key!r} in {lab_dir / 'runs'}") 

96 return matches[0] 

97 

98 

99def render_runs(rows: list[dict]) -> str: 

100 """`aq lab runs`'s text: one line per run.""" 

101 if not rows: 

102 return "no runs yet: aq lab train MODEL" 

103 lines = [] 

104 for row in rows: 

105 metrics = row.get("metrics") or {} 

106 ic = metrics.get("oof_ic_mean") 

107 spread = metrics.get("oof_ic_seed_std") 

108 ic_text = "-" if ic is None else f"{ic:+.4f}" + ("" if spread is None else f" +/-{spread:.4f}") 

109 lines.append(f"{row['id']} {row.get('status', '?'):<8} {row.get('model', '?'):<14} IC {ic_text:<18} N {row.get('trials_n', '-')} {row.get('duration_s', '-')}s") 

110 return "\n".join(lines)