Coverage for evaluation/ml_cleanup.py: 100%
62 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Disk plan for `ml/` (V5.8.0, `aq clean ml`).
3`ml/` had grown to 15 GB on a 4 GB-RAM / small-disk PC: `ml/versions` 8.9 GB of per-candidate trees (each walk-forward
4window carries a regenerable ~2.2 GB `full_dataset.csv`), `ml/_backup_*` another ~4 GB. This module only PLANS: it lists
5what could go and why, protecting the models in use, and the CLI deletes nothing without `--apply`.
7Protected, always: every version id named by a `version_id` field of the active `ml/*_training_metrics.json` files, the
8newest `keep_versions` version directories by modification time, the newest `keep_backups` backup directories, and the
9active top-level files. Pure stdlib; sizes are summed with `os.scandir` (no file is opened).
10"""
12from __future__ import annotations
14import json
15import os
16from pathlib import Path
19def directory_size(path: Path) -> int:
20 total = 0
21 stack = [str(path)]
22 while stack:
23 current = stack.pop()
24 try:
25 with os.scandir(current) as entries:
26 for entry in entries:
27 if entry.is_dir(follow_symlinks=False):
28 stack.append(entry.path)
29 else:
30 try:
31 total += entry.stat(follow_symlinks=False).st_size
32 except OSError:
33 continue
34 except OSError:
35 continue
36 return total
39def active_version_ids(ml_dir: Path) -> set[str]:
40 """Version ids the active metrics files point at (the lineage of the installed models)."""
41 found: set[str] = set()
42 for path in Path(ml_dir).glob("*training_metrics.json"):
43 try:
44 payload = json.loads(path.read_text(encoding="utf-8"))
45 except (OSError, ValueError):
46 continue
47 if isinstance(payload, dict) and payload.get("version_id"):
48 found.add(str(payload["version_id"]))
49 return found
52def plan_ml_cleanup(
53 ml_dir: Path, *, keep_versions: int = 5, keep_backups: int = 1, strip_walk_forward_datasets: bool = False
54) -> dict:
55 """{"items": [{"path", "bytes", "kind", "reason"}], "total_bytes", "protected": [...]} - nothing is deleted."""
56 ml_dir = Path(ml_dir)
57 protected_ids = active_version_ids(ml_dir)
58 items: list[dict] = []
59 protected: list[str] = []
61 versions_dir = ml_dir / "versions"
62 if versions_dir.is_dir():
63 version_dirs = sorted((d for d in versions_dir.iterdir() if d.is_dir()), key=lambda d: d.stat().st_mtime, reverse=True)
64 newest = {d.name for d in version_dirs[: max(0, keep_versions)]}
65 for directory in version_dirs:
66 if directory.name in protected_ids or directory.name in newest:
67 protected.append(str(directory))
68 if strip_walk_forward_datasets and directory.name.startswith("walk-forward-"):
69 items.extend(_walk_forward_dataset_items(directory))
70 continue
71 items.append({"path": str(directory), "bytes": directory_size(directory), "kind": "version",
72 "reason": "not referenced by an active metrics file and not among the newest versions"})
73 backups = sorted((d for d in ml_dir.glob("_backup_*") if d.is_dir()), key=lambda d: d.stat().st_mtime, reverse=True)
74 for index, directory in enumerate(backups):
75 if index < max(0, keep_backups):
76 protected.append(str(directory))
77 continue
78 items.append({"path": str(directory), "bytes": directory_size(directory), "kind": "backup", "reason": "older backup"})
79 return {"items": items, "total_bytes": sum(item["bytes"] for item in items), "protected": protected,
80 "active_version_ids": sorted(protected_ids)}
83def _walk_forward_dataset_items(directory: Path) -> list[dict]:
84 items = []
85 for window in sorted(directory.glob("window_*")):
86 for name in ("full_dataset.csv", "train_dataset.csv", "validation_dataset.csv", "backtest_dataset.csv"):
87 path = window / name
88 if path.is_file():
89 items.append({"path": str(path), "bytes": path.stat().st_size, "kind": "walk_forward_dataset",
90 "reason": "regenerable window dataset (models, metrics and summary are kept)"})
91 return items