Batch 5a: library_run.py 自报能力(--capabilities --json)

- 新增 --capabilities(人读)/ --capabilities --json(一行 ASCII JSON),在任何运行准备之前返回:
  不做 stage 清道夫、不 mkdir、不加锁、不写台账。
- 契约字段全部从真的 argparse parser 与真的常量读出来(新增 build_parser(),main() 改为调用它):
  tiers 取自 --tier 的 choices、defaults.crf/cq 取自 parser default、locks.template 取自 main() 真正
  使用的 LOCK_TEMPLATE(新常量,两处共用)。加/删参数,自报自动跟随。
- 形状:entry / version / contract / tiers / flags{work_dir,stage_dir,dest,keep_source,lock_tag} /
  quality_knobs{crf,cq,qsv_quality,x265_preset,nvenc_preset} / defaults{work,root,crf,cq,x265_preset,
  nvenc_preset} / locks{template,tags};CAPABILITIES_VERSION=1,__version__=1.0.0。
- 纯加法:不带该参数时行为一字未差(同源 --dry-run 输出与 HEAD 逐字相同)。
- scripts/test_capabilities.py:38/38 PASS(含「自报为真的参数必须真被 argparse 接受」)。
This commit is contained in:
hoelee committed 2026-10-14 11:07:52 +08:00
1 parent 6126ad5c2c
commit b69c52135e
3 files changed
+269 -3

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Capability self-report (`--capabilities`): the engine's own answer about what it supports.
Batch 5a. The control plane (`hoelee/hevc-transcode`) drives this engine but cannot import it, so
before this it GUESSED - a regex over this file for `ROOT`/`WORK` and `"--work-dir" in src`. Guesses
rot silently. `library_run.py --capabilities --json` replaces them with a self-report, and this test
is what keeps the self-report from becoming the next hand-written copy that drifts:
1. the JSON is ONE line, ASCII-only, and parses;
2. the shape is exactly the contract (entry / version / contract / tiers / flags / quality_knobs /
defaults / locks) - a missing key breaks the control plane, so assert the key SETS;
3. every flag reported `true` really exists on the command line: `--help` shows it AND argparse
accepts it (feed it a value; a phantom flag would exit 2);
4. `tiers` equals the real `--tier` choices in `--help`;
5. `defaults.work` / `defaults.root` equal the module's own constants, and crf/cq equal the real
parser defaults - the numbers the control plane will believe;
6. asking creates NOTHING on disk (the report must be free and side-effect-free: no stage dir, no
ledger, no lock, not even the `--work-dir` it was handed);
7. the human-readable listing agrees with the JSON.
Exit code 0 = every assertion held. Usage: python scripts/test_capabilities.py
"""
import json
import os
import re
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import library_run as LR # noqa: E402
ENTRY = os.path.join(HERE, "library_run.py")
PY = sys.executable
def run(*args, **kw):
return subprocess.run([PY, "-u", ENTRY] + list(args), capture_output=True, text=True,
encoding="utf-8", errors="replace", **kw)
checks = {}
def check(name, ok, detail=""):
checks[name] = bool(ok)
print("%-52s %s%s" % (name, "PASS" if ok else "FAIL", (" " + str(detail)) if detail else ""))
# ---- 1/2: the payload itself ---------------------------------------------------------------
p = run("--capabilities", "--json")
stdout = p.stdout or ""
check("json_probe_exits_zero", p.returncode == 0, "rc=%d %s" % (p.returncode, (p.stderr or "")[:200]))
lines = [l for l in stdout.splitlines() if l.strip()]
check("json_is_exactly_one_line", len(lines) == 1, "%d line(s)" % len(lines))
check("json_is_ascii", all(ord(c) < 128 for c in stdout), "non-ASCII survives a cp1252 console badly")
cap = {}
try:
cap = json.loads(lines[0])
except Exception as e: # noqa: BLE001
check("json_parses", False, repr(e))
else:
check("json_parses", True)
check("top_level_keys", set(cap) == {"entry", "version", "contract", "tiers", "flags", "quality_knobs",
"defaults", "locks"}, sorted(cap))
check("entry_names_this_file", cap.get("entry") == "library_run.py", str(cap.get("entry")))
check("version_is_a_string", isinstance(cap.get("version"), str) and cap["version"], str(cap.get("version")))
check("contract_is_an_int", isinstance(cap.get("contract"), int) and cap["contract"] >= 1,
str(cap.get("contract")))
check("flags_key_set", set(cap.get("flags") or {}) == {"work_dir", "stage_dir", "dest", "keep_source",
"lock_tag"}, sorted(cap.get("flags") or {}))
check("quality_knobs_key_set", set(cap.get("quality_knobs") or {}) == {"crf", "cq", "qsv_quality",
"x265_preset", "nvenc_preset"},
sorted(cap.get("quality_knobs") or {}))
check("defaults_key_set", set(cap.get("defaults") or {}) == {"work", "root", "crf", "cq", "x265_preset",
"nvenc_preset"},
sorted(cap.get("defaults") or {}))
check("locks_key_set", set(cap.get("locks") or {}) == {"template", "tags"},
sorted(cap.get("locks") or {}))
# ---- 3: a reported flag must really be accepted by the parser ------------------------------
FLAG_OF = {"work_dir": "--work-dir", "stage_dir": "--stage-dir", "dest": "--dest",
"keep_source": "--keep-source", "lock_tag": "--lock-tag"}
ARG_OF = {"work_dir": "X", "stage_dir": "X", "dest": "X", "lock_tag": "probe"}
help_txt = run("--help").stdout or ""
for key, opt in FLAG_OF.items():
claimed = bool((cap.get("flags") or {}).get(key))
in_help = re.search(r"^\s*%s\b" % re.escape(opt), help_txt, re.M) is not None
check("flag_%s_matches_help" % key, claimed == in_help, "claimed=%s help=%s" % (claimed, in_help))
if claimed:
argv = [opt] + ([ARG_OF[key]] if key in ARG_OF else [])
probe = run(*(argv + ["--capabilities", "--json"]))
check("flag_%s_is_accepted" % key, probe.returncode == 0 and probe.stdout.strip().startswith("{"),
"rc=%d %s" % (probe.returncode, (probe.stderr or "")[-160:].replace("\n", " ")))
# ... and every knob it names must be in --help too
for key, opt in (cap.get("quality_knobs") or {}).items():
if opt:
check("knob_%s_matches_help" % key,
re.search(r"^\s*%s\b" % re.escape(opt), help_txt, re.M) is not None,
"%s -> %s" % (key, opt))
# ---- 4: tiers == the real --tier choices ---------------------------------------------------
m = re.search(r"--tier\s*\{([^}]*)\}", help_txt)
check("tiers_match_help_choices", m is not None and [t.strip() for t in m.group(1).split(",")] ==
list(cap.get("tiers") or []), "help=%s json=%s" % (m.group(1) if m else None, cap.get("tiers")))
# ---- 5: the defaults are the module's own numbers -------------------------------------------
d = cap.get("defaults") or {}
check("default_work_is_the_constant", d.get("work") == LR.WORK, "%r vs %r" % (d.get("work"), LR.WORK))
check("default_root_is_the_constant", d.get("root") == LR.ROOT, "%r vs %r" % (d.get("root"), LR.ROOT))
parser = LR.build_parser()
check("default_crf_is_the_parser_default",
d.get("crf") == parser.parse_args(["--capabilities"]).crf, "%r vs %r" % (d.get("crf"),
LR.CRF_X265))
check("default_cq_is_the_parser_default",
d.get("cq") == parser.parse_args(["--capabilities"]).cq, "%r vs %r" % (d.get("cq"), LR.CQ_NVENC))
check("lock_template_is_what_main_builds", (cap.get("locks") or {}).get("template") == LR.LOCK_TEMPLATE
and LR.LOCK_TEMPLATE % "x265" == "run-x265.lock", str((cap.get("locks") or {}).get("template")))
# ---- 6: asking must not create anything ----------------------------------------------------
with tempfile.TemporaryDirectory(prefix="caps_") as tmp:
work = os.path.join(tmp, "work")
os.makedirs(work)
probe = run("--work-dir", work, "--capabilities", "--json")
left = os.listdir(work)
check("asking_creates_nothing", probe.returncode == 0 and not left, "left behind: %s" % left)
check("work_dir_flag_does_not_move_the_report",
json.loads(probe.stdout.strip()).get("defaults", {}).get("work") == LR.WORK,
"the report always describes the compiled-in default")
# ---- 7: the human listing agrees with the JSON ---------------------------------------------
human = run("--capabilities").stdout or ""
check("human_lists_the_version", LR.__version__ in human and "contract" in human, human.splitlines()[:1])
check("human_lists_every_tier", all(t in human for t in (cap.get("tiers") or [])), cap.get("tiers"))
check("human_carries_the_defaults", all(str(x) in human for x in (d.get("crf"), d.get("cq"))),
"crf=%s cq=%s" % (d.get("crf"), d.get("cq")))
check("human_and_json_agree_on_version",
json.loads(lines[0])["version"] == LR.__version__, LR.__version__)
print("\n%d/%d checks passed" % (sum(checks.values()), len(checks)))
sys.exit(0 if all(checks.values()) else 1)