File size: 15,167 Bytes
7956103 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | #!/usr/bin/env python3
"""Recover only known K=4 solver timeouts into a new auditable run directory.
The completed base run is never modified or restarted. Candidate parameters,
the K=3 screening scores, and the selection/ranking remain frozen. Original
errors are retained before narrowly scoped IPM recovery and recertification.
"""
from __future__ import annotations
import argparse
import copy
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import resource
import shutil
import subprocess
import sys
import time
FROZEN_KEYS = ("id", "n", "tau", "weights", "probabilities", "budget", "head_bound")
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def read_json(path):
return json.loads(path.read_text())
def save_json(path, obj):
temporary = path.with_name(path.name + ".pending")
temporary.write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n")
temporary.replace(path)
def frozen(witness):
return {key: witness[key] for key in FROZEN_KEYS}
def payload_witnesses(payload):
if "witnesses" in payload:
return payload["witnesses"]
if "id" in payload and "cases" in payload:
return [payload]
raise ValueError("Retry artifact is not a candidate or witnesses payload")
def utc_now():
return dt.datetime.now(dt.timezone.utc).isoformat()
def main(args):
started = time.monotonic()
deadline = started + 1800
base = args.base_run.resolve(strict=True)
output = args.output_run.resolve()
source_dir = Path(__file__).resolve().parent
if output.exists():
raise ValueError("Output directory must be new; existing results will not be overwritten")
if output == base or base in output.parents:
raise ValueError("New run must not be placed inside the immutable base run")
for name in ("status.json", "search_results.json", "witnesses.json", "config.json"):
if not (base / name).is_file():
raise ValueError(f"Missing required completed-run artifact: {name}")
base_status = read_json(base / "status.json")
search = read_json(base / "search_results.json")
payload = read_json(base / "witnesses.json")
config = read_json(args.config)
if base_status.get("status", "").upper() == "RUNNING":
raise ValueError("The base job is still marked RUNNING; wait for it to finish")
failed_stages = [row for row in base_status.get("stages", [])
if row.get("status") == "FAILED"]
if any(row.get("stage") != "search" for row in failed_stages):
raise ValueError("The base run has a non-search failure outside this recovery scope")
if search.get("status") not in ("complete", "complete_with_errors"):
raise ValueError("The frozen candidate search must have finished")
if digest(args.config) != digest(base / "config.json"):
raise ValueError("Provided configuration bytes differ from the frozen base configuration")
if search["config"] != config:
raise ValueError("Search configuration differs from the supplied non-smoke configuration")
witnesses = payload["witnesses"]
ids = [w["id"] for w in witnesses]
if len(ids) != len(set(ids)) or set(ids) != set(search["selected_ids"]):
raise ValueError("Witness IDs and frozen selected IDs disagree or contain duplicates")
expected_count = len(config["n_values"]) * len(config["budgets"])
if len(witnesses) != expected_count:
raise ValueError("Not all prespecified n/budget groups have a selected witness")
expected_K = set(config["evaluation_K"])
if expected_K != {2, 3, 4}:
raise ValueError("This narrowly scoped finalizer expects K=2,3,4")
missing = {}
for w in witnesses:
present = [c["K"] for c in w["cases"]]
if len(present) != len(set(present)) or not set(present) <= expected_K:
raise ValueError(f"Duplicate or unexpected cases for {w['id']}")
if expected_K - set(present):
if expected_K - set(present) != {4}:
raise ValueError(f"Only a missing K=4 case may be recovered: {w['id']}")
missing[w["id"]] = w
original_errors = copy.deepcopy(search.get("errors", []))
error_ids = []
for error in original_errors:
message = str(error.get("error", "")).lower()
if (error.get("K") != 4 or error.get("id") not in missing
or "time limit" not in message or "lp" not in message):
raise ValueError(f"Unexpected original error; no recovery attempted: {error}")
error_ids.append(error["id"])
if set(error_ids) != set(missing) or len(error_ids) != len(set(error_ids)):
raise ValueError("Missing cases must correspond one-to-one to retained K=4 timeouts")
reusable = {}
if args.reuse_retry:
raw_retry = read_json(args.reuse_retry)
if raw_retry.get("retry_metadata", {}).get("status") != "complete":
raise ValueError("Reusable retry artifact is not marked complete")
reusable = {w["id"]: w for w in payload_witnesses(raw_retry)}
for witness_id, repaired in reusable.items():
if witness_id in missing and frozen(repaired) != frozen(missing[witness_id]):
raise ValueError("Reusable retry differs from exact frozen parameters")
# All preflight checks precede any new result-directory creation.
shutil.copytree(base, output)
for name in ("status.json", "search_results.json", "witnesses.json"):
shutil.copy2(base / name, output / ("original_" + name))
if (output / "source").exists():
shutil.copytree(output / "source", output / "original_source")
(output / "source").mkdir(exist_ok=True)
for file in sorted(source_dir.glob("*.py")):
shutil.copy2(file, output / "source" / file.name)
(output / "logs").mkdir(exist_ok=True)
(output / "retries").mkdir(exist_ok=True)
(output / "figures").mkdir(exist_ok=True)
files = sorted((output / "source").glob("*.py"))
status = {
"run_id": output.name, "status": "RUNNING", "started_utc": utc_now(),
"scope": "Known K4 solver-timeout recovery only; original candidate search not rerun",
"base_run": str(base), "base_status": base_status,
"base_artifact_sha256": {name: digest(base / name) for name in
("status.json", "search_results.json", "witnesses.json", "config.json")},
"config_sha256": digest(output / "config.json"),
"source_sha256": {f.name: digest(f) for f in files},
"historical_errors": original_errors, "recovery_records": [], "stages": [],
"limits": {"total_seconds": 1800, "retry_stage_seconds": 180,
"lp_seconds": 120, "address_space_gib": 8, "cpu_threads": 1},
}
save_json(output / "status.json", status)
env = os.environ.copy()
env.update(OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1",
NUMEXPR_NUM_THREADS="1", MPLBACKEND="Agg", PYTHONUNBUFFERED="1")
def limits():
cap = 8 * 1024**3
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
def stage(name, command, cap_seconds=None):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("Full recovery job exceeded its 1800-second budget")
timeout = remaining if cap_seconds is None else min(remaining, cap_seconds)
row = {"stage": name, "status": "RUNNING", "command": command,
"timeout_seconds": timeout}
status["stages"].append(row)
save_json(output / "status.json", status)
t0 = time.monotonic()
print("START " + name, flush=True)
try:
with (output / "logs" / (name + ".log")).open("w") as log:
completed = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT,
env=env, preexec_fn=limits, timeout=timeout)
row.update(status="COMPLETE" if completed.returncode == 0 else "FAILED",
returncode=completed.returncode, runtime_seconds=time.monotonic() - t0)
if completed.returncode:
raise RuntimeError(f"{name} failed; no automatic fallback is authorized")
except Exception as exc:
row.update(status="FAILED", error=repr(exc), runtime_seconds=time.monotonic() - t0)
raise
finally:
save_json(output / "status.json", status)
print("END " + name, flush=True)
if args.reuse_retry:
shutil.copy2(args.reuse_retry, output / "retries" / "reused_input.json")
try:
for witness in witnesses:
if witness["id"] not in missing:
continue
record = {"id": witness["id"], "K": 4, "method": "highs-ipm"}
if witness["id"] in reusable:
repaired = reusable[witness["id"]]
if frozen(repaired) != frozen(witness):
raise ValueError("Reusable retry differs from exact frozen parameters")
retry_path = output / "retries" / "reused_input.json"
record["source"] = "reused verified IPM retry"
else:
retry_path = output / "retries" / (witness["id"] + "_K4_ipm.json")
candidate_path = output / "candidates" / (witness["id"] + ".json")
if frozen(read_json(candidate_path)) != frozen(witness):
raise ValueError("Candidate artifact differs from selected witness parameters")
stage("retry_" + witness["id"], [
sys.executable, str(output / "source" / "retry_lp_cases.py"),
"--config", str(output / "config.json"), "--input", str(candidate_path),
"--output", str(retry_path), "--method", "highs-ipm", "--K", "4",
"--time-limit", "120"], cap_seconds=180)
retry_payload = read_json(retry_path)
if retry_payload.get("retry_metadata", {}).get("status") != "complete":
raise ValueError("IPM retry did not complete cleanly")
repaired = retry_payload
record["source"] = "new bounded IPM retry"
if frozen(repaired) != frozen(witness):
raise ValueError("Repaired witness parameters differ from frozen input")
additions = [case for case in repaired["cases"] if case["K"] == 4]
if len(additions) != 1 or additions[0].get("lp_optimum") is None:
raise ValueError("Recovery must provide exactly one successful K4 LP case")
if additions[0].get("retry_provenance", {}).get("method") != "highs-ipm":
raise ValueError("Recovered case was not produced by the authorized IPM retry")
case = copy.deepcopy(additions[0])
if any(case["lp_optimum"] > old["lp_optimum"] + 2e-7 for old in witness["cases"]):
raise ValueError("Recovered K4 objective violates fixed-oracle monotonicity")
witness["cases"].append(case)
witness["cases"].sort(key=lambda item: item["K"])
record.update(retry_artifact=str(retry_path.relative_to(output)),
retry_artifact_sha256=digest(retry_path),
lp_optimum=case["lp_optimum"], status="RESOLVED")
status["recovery_records"].append(record)
witness["recovery_metadata"] = record
candidate_path = output / "candidates" / (witness["id"] + ".json")
candidate = read_json(candidate_path)
if frozen(candidate) != frozen(witness):
raise ValueError("Selected candidate changed during recovery")
candidate["cases"] = copy.deepcopy(witness["cases"])
candidate["recovery_metadata"] = record
save_json(candidate_path, candidate)
save_json(output / "witnesses.json", payload)
save_json(output / "status.json", status)
if any({c["K"] for c in w["cases"]} != expected_K for w in witnesses):
raise ValueError("Incomplete cases remain after recovery")
search["historical_errors"] = original_errors
search["errors"] = []
search["status"] = "complete"
search["recovery_metadata"] = {"base_run": str(base),
"records": status["recovery_records"],
"candidate_search_rerun": False,
"candidate_parameters_and_K3_ranking_unchanged": True}
payload["status"] = "complete"
payload["recovery_metadata"] = search["recovery_metadata"]
save_json(output / "search_results.json", search)
save_json(output / "witnesses.json", payload)
stage("recovery_certify", [sys.executable, str(output / "source" / "certify_witness.py"),
"--input", str(output / "witnesses.json"),
"--output", str(output / "certificates.json"), "--self-test"])
stage("recovery_validate_summary", [sys.executable,
str(output / "source" / "normalize_results.py"), "--run-dir", str(output)])
stage("recovery_plots", [sys.executable, str(output / "source" / "plot_phase2.py"),
"--run-dir", str(output)])
paragraph = (
"\n## 求解器超时与独立恢复记录\n\n"
f"原冻结候选搜索完整结束,但其中 {len(original_errors)} 个 K=4 LP 达到 120 秒时限。"
f"本目录在原运行的独立副本中,通过 HiGHS IPM 恢复了 {len(status['recovery_records'])} 个缺失组合;"
"没有重新筛选候选、改变模型参数、改变预算或重新排列 K=3 排名。"
"随后对全部入选模型和轮数组合重新进行了独立有理数认证。\n\n"
"原始失败保存在 original_status.json、original_search_results.json、original_witnesses.json,"
"以及 search_results.json 的 historical_errors 字段;原代码保存在 original_source/。"
"恢复方法、输入哈希、资源限制与日志见 status.json、retries/ 和 logs/。\n")
for name in ("RESULTS_PHASE2.md", "README.md"):
report = output / name
prior = report.read_text() if report.exists() else "# Phase-two recovered run\n"
report.write_text(prior + paragraph)
status["status"] = "COMPLETE"
except Exception as exc:
status.update(status="FAILED", error=repr(exc))
raise
finally:
status.update(finished_utc=utc_now(), runtime_seconds=time.monotonic() - started)
save_json(output / "status.json", status)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-run", type=Path, required=True)
parser.add_argument("--output-run", type=Path, required=True)
parser.add_argument("--config", type=Path, required=True)
parser.add_argument("--reuse-retry", type=Path)
main(parser.parse_args())
|