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:
1 parent
6126ad5c2c
commit
b69c52135e
3 files changed
+269
-3
No files matched your search
+97
-3
@@ -110,6 +110,9 @@ WORK = r"C:\AI\transcode-run"
|
||||
STAGE = os.path.join(WORK, "stage")
|
||||
LEDGER = os.path.join(WORK, "ledger.jsonl")
|
||||
LOCKF = os.path.join(WORK, "run.lock")
|
||||
# The tier lock's NAME PATTERN, in one place: `main()` builds the file from it and `capabilities()`
|
||||
# reports it, so a change here cannot leave the control plane describing a lock nobody writes.
|
||||
LOCK_TEMPLATE = "run-%s.lock"
|
||||
|
||||
|
||||
def _apply_work_dir(path):
|
||||
@@ -1355,8 +1358,13 @@ def collect(root):
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def main():
|
||||
global DECODE_CHECK, STAGE # WORK/STAGE/LEDGER/LOCKF/POLICY move via _apply_work_dir
|
||||
def build_parser():
|
||||
"""The engine's command line, in ONE place.
|
||||
|
||||
Split out of `main()` in Batch 5a so `capabilities()` can read the REAL parser back instead of
|
||||
keeping a second, hand-written list of the flags this build supports. That duplicate is exactly
|
||||
how a cross-repository contract rots: drop `--work-dir` and the copy still says it is there.
|
||||
"""
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cq", type=int, default=CQ_NVENC, help="nvenc tier quality (measured default 30)")
|
||||
ap.add_argument("--crf", type=int, default=CRF_X265, help="x265 tier quality (measured default 24)")
|
||||
@@ -1408,7 +1416,93 @@ def main():
|
||||
ap.add_argument("--keep-local", action="store_true",
|
||||
help="pilot mode: encode + verify + gate locally and report the numbers, then "
|
||||
"THROW THE OUTPUT AWAY - nothing is uploaded and nothing is replaced")
|
||||
ap.add_argument("--capabilities", action="store_true",
|
||||
help="print what THIS BUILD supports (tiers, flags, quality knobs, defaults, "
|
||||
"locks) and exit - it is the machine-readable contract the control plane "
|
||||
"asks for BEFORE it runs anything (Batch 5a)")
|
||||
ap.add_argument("--json", action="store_true",
|
||||
help="with --capabilities: emit one line of machine-readable JSON instead of "
|
||||
"the human-readable listing")
|
||||
return ap
|
||||
|
||||
|
||||
# ---- capability self-report (Batch 5a) -----------------------------------------------------------
|
||||
# The control plane drives this engine but cannot import it (it needs ffmpeg, its own policy files and
|
||||
# a whole library tree), so it used to GUESS what this build supports: a regex over this file for the
|
||||
# `ROOT`/`WORK` constants and `"--work-dir" in src`. Every guess fails SILENTLY - rename a constant,
|
||||
# move a path, drop a flag, and the other repository keeps running on a stale answer. `--capabilities
|
||||
# --json` replaces the guess with a self-report. The two rules that keep it honest:
|
||||
# * every field is DERIVED from the real parser and the real constants below - never a hand-written
|
||||
# copy that can disagree with the code it describes;
|
||||
# * it prints one line and exits BEFORE any run setup (no stage sweep, no mkdir, no lock), so asking
|
||||
# costs nothing and changes nothing.
|
||||
CAPABILITIES_VERSION = 1 # bump when the SHAPE or the MEANING of the report changes
|
||||
__version__ = "1.0.0" # human/ledger build id; the control plane only prints it
|
||||
|
||||
|
||||
def capabilities(ap=None):
|
||||
"""What THIS build supports, read back out of the parser and the constants it really uses."""
|
||||
ap = build_parser() if ap is None else ap
|
||||
acts = list(getattr(ap, "_actions", []) or [])
|
||||
|
||||
def act(opt):
|
||||
return next((a for a in acts if opt in (getattr(a, "option_strings", []) or [])), None)
|
||||
|
||||
opts = set(o for a in acts for o in (getattr(a, "option_strings", []) or []))
|
||||
knob = lambda opt: opt if opt in opts else None # noqa: E731
|
||||
tier = act("--tier")
|
||||
return {
|
||||
"entry": os.path.basename(__file__),
|
||||
"version": __version__,
|
||||
"contract": CAPABILITIES_VERSION,
|
||||
"tiers": list(getattr(tier, "choices", None) or []),
|
||||
"flags": {k: (v in opts) for k, v in (("work_dir", "--work-dir"),
|
||||
("stage_dir", "--stage-dir"),
|
||||
("dest", "--dest"),
|
||||
("keep_source", "--keep-source"),
|
||||
("lock_tag", "--lock-tag"))},
|
||||
"quality_knobs": {"crf": knob("--crf"), "cq": knob("--cq"),
|
||||
"qsv_quality": knob("--qsv-quality"),
|
||||
"x265_preset": knob("--x265-preset"),
|
||||
"nvenc_preset": knob("--nvenc-preset")},
|
||||
"defaults": {"work": WORK, "root": ROOT,
|
||||
"crf": getattr(act("--crf"), "default", None),
|
||||
"cq": getattr(act("--cq"), "default", None),
|
||||
"x265_preset": getattr(act("--x265-preset"), "default", None),
|
||||
"nvenc_preset": getattr(act("--nvenc-preset"), "default", None)},
|
||||
"locks": {"template": LOCK_TEMPLATE, "tags": "--lock-tag" in opts},
|
||||
}
|
||||
|
||||
|
||||
def print_capabilities(cap):
|
||||
"""The same report for a human at a terminal (`--capabilities` without `--json`)."""
|
||||
print("%s version %s (capability contract %d)" % (cap["entry"], cap["version"], cap["contract"]))
|
||||
print(" tiers : %s" % ", ".join(cap["tiers"]))
|
||||
print(" flags : %s" % ", ".join(sorted(k for k, v in cap["flags"].items() if v)))
|
||||
print(" knobs : %s" % ", ".join("%s=%s" % (k, v) for k, v in sorted(
|
||||
cap["quality_knobs"].items()) if v))
|
||||
print(" defaults : work=%s root=%s crf=%s cq=%s x265_preset=%s nvenc_preset=%s" % (
|
||||
cap["defaults"]["work"], cap["defaults"]["root"], cap["defaults"]["crf"],
|
||||
cap["defaults"]["cq"], cap["defaults"]["x265_preset"], cap["defaults"]["nvenc_preset"]))
|
||||
print(" locks : %s%s" % (cap["locks"]["template"],
|
||||
" (own lock per --lock-tag)" if cap["locks"]["tags"] else ""))
|
||||
|
||||
|
||||
def main():
|
||||
global DECODE_CHECK, STAGE # WORK/STAGE/LEDGER/LOCKF/POLICY move via _apply_work_dir
|
||||
ap = build_parser()
|
||||
args = ap.parse_args()
|
||||
if args.capabilities:
|
||||
# BEFORE any run setup: no stage sweep, no makedirs, no lock, no ledger. Asking what this
|
||||
# build can do must never change anything on disk (and `sweep_stage()` below DELETES files).
|
||||
cap = capabilities(ap)
|
||||
if args.json:
|
||||
# ensure_ascii: the payload has to survive a console whose codepage is not UTF-8 (the
|
||||
# ROOT default is a Chinese path); the reader parses it as plain ASCII.
|
||||
print(json.dumps(cap, ensure_ascii=True, sort_keys=True))
|
||||
else:
|
||||
print_capabilities(cap)
|
||||
return
|
||||
DECODE_CHECK = not args.no_decode_check
|
||||
if args.work_dir:
|
||||
_apply_work_dir(args.work_dir)
|
||||
@@ -1456,7 +1550,7 @@ def main():
|
||||
# encoders racing on the same unit/output, and the control plane splits the cores explicitly
|
||||
# (measured 2026-10-12: two 720p x265 processes with 10 threads on disjoint core sets = +48%
|
||||
# aggregate throughput over one process with 22 threads, because x265 caps at wpp(12 rows)).
|
||||
lockf = os.path.join(WORK, "run-%s.lock" % (args.lock_tag or args.tier
|
||||
lockf = os.path.join(WORK, LOCK_TEMPLATE % (args.lock_tag or args.tier
|
||||
or ("single" if args.path else "all")))
|
||||
log("=== %d file(s) tier=%s cq=%d crf=%d audio=%s decode_check=%s lock=%s" %
|
||||
(len(files), args.tier or "auto", args.cq, args.crf, args.audio or "source-matched",
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user