Coverage for retraining/vault_client.py: 100%

114 statements  

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

1"""Aether-Vault (`av`) subprocess execution wrapper (Phase V2-17). 

2 

3Never raises and never crashes the retraining pipeline: `av` may not be 

4installed/on PATH in a given environment, and a missing/failing vault commit 

5must fail the retraining_event gracefully (status="failed") rather than 

6taking down the orchestrator/worker process. Uses 

7retraining/vault_commands.py's pure argv builders - this module only knows 

8how to run a command and interpret its result. 

9""" 

10 

11from __future__ import annotations 

12 

13import json 

14import logging 

15import re 

16import subprocess 

17from pathlib import Path 

18 

19from retraining.vault_commands import ( 

20 build_av_head_command, 

21 build_av_restore_command, 

22 build_av_status_command, 

23 build_commit_plan, 

24) 

25 

26logger = logging.getLogger(__name__) 

27 

28_COMMIT_HASH_PATTERN = re.compile(r"\b[0-9a-f]{7,64}\b", re.IGNORECASE) 

29_VERSION_PATTERN = re.compile(r"(\d+(?:\.\d+)*)") 

30 

31 

32def run_av_command(argv: list[str], cwd: Path | None = None, timeout: int = 120) -> dict: 

33 """Runs one `av` subprocess call, never raising. 

34 

35 Returns {"ok": bool, "returncode": int | None, "stdout": str, "stderr": str, "error": str | None}. 

36 """ 

37 try: 

38 # Explicit UTF-8: av prints box-drawing characters, and Windows' default codepage 

39 # makes the reader thread die on them, leaving stdout None. 

40 result = subprocess.run( 

41 argv, 

42 cwd=str(cwd) if cwd else None, 

43 capture_output=True, 

44 text=True, 

45 encoding="utf-8", 

46 errors="replace", 

47 timeout=timeout, check=False, 

48 ) 

49 except FileNotFoundError: 

50 logger.warning("run_av_command: '%s' not found on PATH.", argv[0] if argv else "av") 

51 return {"ok": False, "returncode": None, "stdout": "", "stderr": "", "error": "av_binary_not_found"} 

52 except subprocess.TimeoutExpired: 

53 logger.error("run_av_command: %s timed out after %ds.", argv, timeout) 

54 return {"ok": False, "returncode": None, "stdout": "", "stderr": "", "error": "av_command_timed_out"} 

55 except Exception as exc: # never let a vault call crash the pipeline 

56 logger.error("run_av_command: unexpected error running %s - %s", argv, exc) 

57 return {"ok": False, "returncode": None, "stdout": "", "stderr": "", "error": str(exc)} 

58 

59 ok = result.returncode == 0 

60 return { 

61 "ok": ok, 

62 "returncode": result.returncode, 

63 "stdout": result.stdout, 

64 "stderr": result.stderr, 

65 "error": None if ok else (result.stderr or result.stdout or "av_command_failed"), 

66 } 

67 

68 

69def parse_av_envelope(stdout: str | None) -> dict | None: 

70 """The JSON envelope from `av --output json ...`, or None. The envelope is the last JSON 

71 object printed, since progress lines may precede it.""" 

72 for line in reversed((stdout or "").strip().splitlines()): 

73 line = line.strip() 

74 if not line.startswith("{"): 

75 continue 

76 try: 

77 parsed = json.loads(line) 

78 except ValueError: 

79 continue 

80 if isinstance(parsed, dict) and "ok" in parsed: 

81 return parsed 

82 return None 

83 

84 

85def parse_vault_commit_hash(stdout: str | None) -> str | None: 

86 """The commit's full hash from the JSON envelope, falling back to the first hex token in 

87 human output (`[abc1234] message`) for an `av` that printed no envelope.""" 

88 envelope = parse_av_envelope(stdout) 

89 if envelope is not None: 

90 value = (envelope.get("data") or {}).get("hash") 

91 return str(value) if value else None 

92 match = _COMMIT_HASH_PATTERN.search(stdout or "") 

93 return match.group(0) if match else None 

94 

95 

96def parse_push_state(stdout: str | None) -> str: 

97 """"drained" when nothing is left to send, "queued" when commits wait in av's offline queue. 

98 

99 A queued push is a safe outcome for av (exit 0, nothing lost), so it is told apart here.""" 

100 envelope = parse_av_envelope(stdout) 

101 if envelope is None: 

102 return "unknown" 

103 return "queued" if int((envelope.get("data") or {}).get("still_queued") or 0) > 0 else "drained" 

104 

105 

106def _version_tuple(text: str | None) -> tuple[int, ...] | None: 

107 match = _VERSION_PATTERN.search(text or "") 

108 return tuple(int(part) for part in match.group(1).split(".")) if match else None 

109 

110 

111def vault_preflight(config: dict, cwd: Path | None = None) -> dict: 

112 """Can a candidate be committed from here? Run before training, so a worker without `av` 

113 fails in seconds instead of after a whole training run. 

114 

115 Returns {"ok": bool, "reason": str, "av_version": str | None}. 

116 """ 

117 if not config.get("enabled", True): 

118 return {"ok": True, "reason": "vault_disabled", "av_version": None} 

119 timeout = int(config.get("timeout_seconds", 120)) 

120 result = run_av_command([config.get("av_binary", "av"), "--version"], cwd=cwd, timeout=timeout) 

121 if not result["ok"]: 

122 return {"ok": False, "reason": str(result["error"]), "av_version": None} 

123 version = (result["stdout"] or "").strip() or None 

124 minimum = config.get("min_version") 

125 if minimum: 

126 have, need = _version_tuple(version), _version_tuple(str(minimum)) 

127 if have is None or need is None or have < need: 

128 return {"ok": False, "reason": f"av_version_below_minimum: {version} < {minimum}", "av_version": version} 

129 repo_root = Path(cwd) if cwd else Path.cwd() 

130 if not (repo_root / ".av").is_dir(): 

131 return {"ok": False, "reason": f"not_an_av_repo: {repo_root} (run `av init`)", "av_version": version} 

132 return {"ok": True, "reason": "ready", "av_version": version} 

133 

134 

135def staged_leftovers(av_binary: str = "av", cwd: Path | None = None, timeout: int = 120) -> list[str] | None: 

136 """What is already staged, which `av commit` would sweep into the next commit; None when `av status` can't answer.""" 

137 envelope = parse_av_envelope(run_av_command(build_av_status_command(av_binary), cwd=cwd, timeout=timeout)["stdout"]) 

138 if not envelope or not envelope.get("ok"): 

139 return None 

140 data = envelope.get("data") or {} 

141 return sorted(set(data.get("staged") or []) | set(data.get("removed") or [])) 

142 

143 

144def current_head_hash(av_binary: str = "av", cwd: Path | None = None, timeout: int = 120) -> str | None: 

145 envelope = parse_av_envelope(run_av_command(build_av_head_command(av_binary), cwd=cwd, timeout=timeout)["stdout"]) 

146 commits = ((envelope or {}).get("data") or {}).get("commits") or [] 

147 return commits[0].get("hash") if commits else None 

148 

149 

150def commit_candidate_to_vault( 

151 version_id: str, 

152 add_paths: list[str], 

153 metrics: dict[str, float], 

154 config: dict, 

155 cwd: Path | None = None, 

156) -> dict: 

157 """Runs add -> commit -> push sequentially, stopping at the first failing stage. 

158 

159 Returns {"ok": bool, "stage": "add"|"commit"|"push"|"done", "vault_commit": str | None, 

160 "push_state": "skipped"|"drained"|"queued"|"unknown"|"failed"|None, "steps": {...}}. 

161 On ok=False the caller (retraining/orchestrator.py) sets 

162 retraining_events.status="failed" and appends `steps` to notes - the 

163 pipeline never proceeds to promotion on a vault failure. A push left queued 

164 only fails when config["require_push"] is true. 

165 """ 

166 plan = build_commit_plan(version_id, add_paths, metrics, config) 

167 timeout = int(config.get("timeout_seconds", 120)) 

168 steps: dict[str, dict] = {} 

169 av_binary = plan["add"][0] 

170 

171 # A failed gate's leftovers must not land under this candidate's label. 

172 leftovers = staged_leftovers(av_binary, cwd=cwd, timeout=timeout) 

173 if leftovers: 

174 steps["staged_leftovers"] = {"ok": False, "paths": leftovers[:20], "error": "run `av unstage` first"} 

175 return {"ok": False, "stage": "staged_leftovers", "vault_commit": None, "push_state": None, "steps": steps} 

176 

177 add_result = run_av_command(plan["add"], cwd=cwd, timeout=timeout) 

178 steps["add"] = add_result 

179 if not add_result["ok"]: 

180 return {"ok": False, "stage": "add", "vault_commit": None, "push_state": None, "steps": steps} 

181 

182 commit_result = run_av_command(plan["commit"], cwd=cwd, timeout=timeout) 

183 steps["commit"] = commit_result 

184 if not commit_result["ok"]: 

185 error = (parse_av_envelope(commit_result["stdout"]) or {}).get("error") or {} 

186 if error.get("code") != "nothing_to_commit": 

187 return {"ok": False, "stage": "commit", "vault_commit": None, "push_state": None, "steps": steps} 

188 # An unchanged candidate is already in the vault: a retry after a killed run must succeed. 

189 vault_commit = current_head_hash(av_binary, cwd=cwd, timeout=timeout) 

190 if vault_commit is None: 

191 return {"ok": False, "stage": "commit", "vault_commit": None, "push_state": None, "steps": steps} 

192 else: 

193 vault_commit = parse_vault_commit_hash(commit_result["stdout"]) 

194 

195 if plan["push"] is None: 

196 return {"ok": True, "stage": "done", "vault_commit": vault_commit, "push_state": "skipped", "steps": steps} 

197 

198 push_result = run_av_command(plan["push"], cwd=cwd, timeout=timeout) 

199 steps["push"] = push_result 

200 if not push_result["ok"]: 

201 return {"ok": False, "stage": "push", "vault_commit": vault_commit, "push_state": "failed", "steps": steps} 

202 

203 push_state = parse_push_state(push_result["stdout"]) 

204 if push_state == "queued" and config.get("require_push", False): 

205 return {"ok": False, "stage": "push", "vault_commit": vault_commit, "push_state": push_state, "steps": steps} 

206 return {"ok": True, "stage": "done", "vault_commit": vault_commit, "push_state": push_state, "steps": steps} 

207 

208 

209def restore_candidate_from_vault(commit_hash: str, relative_dir: str, config: dict, cwd: Path | None = None) -> dict: 

210 """Restores one candidate directory from a vault commit, touching nothing else. 

211 

212 A repo-wide `av checkout` must never be used for this: it overwrites main.py, train.py and 

213 config.json and deletes every file the old commit did not track. 

214 """ 

215 argv = build_av_restore_command(commit_hash, [relative_dir], av_binary=config.get("av_binary", "av")) 

216 return run_av_command(argv, cwd=cwd, timeout=int(config.get("timeout_seconds", 120)))