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

+97 -3
View File
@@ -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",