feat(install): 三道防坏防丢门禁 —— 尾部实包解码 / 同卷隔离区两阶段提交 / 无缓冲回读

§10.161 的复盘结论不是「再查一遍」,是三个结构性缺口,逐个补上:

① tail_decode_gate():上传后真解码远端副本的最后几秒。
   `+faststart` 把 moov 放在文件头,所以 ffprobe 对截断文件照样报全长 ——
   抽检 1,340 件成品里 6 件截断(1.4 GB 只剩 36.9 MB)全都过了既有门禁。
   窗口 min(5s, dur/2),短片不假阳性;`-map 0:v:0?` 让无视频流不误红。

② 隔离区两阶段提交(move_to_trash / restore_from_trash / purge_trash / publish_staged):
   安装段不再 `os.replace` 覆盖 + `os.remove(src)` 删原件,而是
   目标名上的文件同卷 rename 进 `<dir>/.transcode_trash/<date>/`(0 字节拷贝、可回滚),
   发布成功才让它留在那儿;发布或装后任一闸门失败就地回滚。
   GC 72 h 后回收,且**旁注里的 live 已消失时绝不删**(那是最后一份)。

③ _win_unbuffered_read / _sha_sample_nocache / _sha_remote_sample_nocache:
   抽样回读走 FILE_FLAG_NO_BUFFERING,Dokan/RaiDrive 的缓存池再也答不上话。
   读窗按扇区对齐并按 GetFileSizeEx 裁到最后一个整扇区(无缓冲读不许跨 EOF,
   越过末尾是 ERROR_INVALID_PARAMETER 而不是 EOF);末尾 < 4 KB 的零头用普通读补。
   短读抛 _ShortRead 并**不许**退回缓存读;只有文件系统拒绝该 flag 才降级,
   并把 bypassed=False 写进回执。

隔离区对引擎 collect() 不可见(否则退休的原件会被重新入队)。
门禁默认全开,`--no-tail-gate` 只是紧急刹车,`--trash-ttl-hours` 默认 72。
真共享盘端到端实测:源 213,827 B → hvc1 25,854 B,原件逐字节躺在隔离区,cache_bypass=true。
版本 1.2.0 → 1.3.0(contract 3 不变)。
This commit is contained in:
hoelee committed 2026-11-01 14:15:29 +08:00
1 parent 005b824e4f
commit 46c9177386
3 files changed
+476 -64

No files matched your search

+447 -54
View File
@@ -17,8 +17,12 @@ Per file, in order:
2. encode locally (tier above)
3. structural gate + full decode pass + SSIM-vs-source + size assertion, all on the LOCAL output
4. copy the verified output to the share as <name>.new.mp4
5. read the share copy back end-to-end and compare SHA-256 with the local file
6. ONLY then rename it over the original, and re-probe the result on the share
5. read it back with the WINDOWS CACHE BYPASSED (FILE_FLAG_NO_BUFFERING) and compare SHA-256 with
the local file, then really DECODE its last seconds (a truncated upload passes every metadata
and sampled-hash check: `+faststart` puts the index at the head)
6. ONLY then two-phase-commit it: the original is moved into the same-volume quarantine
`<dir>/.transcode_trash/<date>/` (never deleted), the new file is published, and any failure
puts the original straight back
A file that fails at any step leaves the original untouched and is retried next run.
"""
import argparse
@@ -132,6 +136,7 @@ def _apply_work_dir(path):
VIDEO_EXT = {".mkv", ".mp4", ".mov", ".avi", ".webm", ".flv", ".ts", ".m4v", ".wmv",
".mpg", ".mpeg", ".m2ts", ".3gp", ".ogv", ".vob", ".rmvb", ".rm", ".divx"}
DECODE_CHECK = True
TAIL_GATE = True # 安装前的尾部实包解码;`--no-tail-gate` 是紧急刹车,不是常规开关
# ---- policy (all numbers measured; see references/hevc-conversion-policy.md §10) ----------
CQ_NVENC = 31 # measured: min SSIM 0.989-0.994 at 43-74% of the source video bitrate
@@ -641,6 +646,329 @@ def copy_local_to_remote(local, remote_tmp, tries=4):
return False
# ---------------------------------------------------------------- install safety gates
# 2026-11-01(§10.161 事故复盘):安装段过去是「上传 → 改个名 → 删源档」,三步全在相信
# RaiDrive/Dokan 的回报。抽检 1,340 件成品发现 6 起截断上传、5 起原件未替换 —— 都是这么来的。
# 三道门禁各堵一类,缺一不可:
# ① 尾部实包解码:`moov` 在文件头(+faststart),所以 ffprobe 对截断文件照样报全长;
# 只有真去解**文件末尾**的帧,才逼 ffmpeg 落到物理尾部。
# ② 同卷隔离区两阶段提交:原片不再 `os.remove`,改成同卷 rename 进 `.transcode_trash/<date>/`,
# 发布失败就地回滚;原件 72 h 后由 GC 真正回收(且「正式文件已消失」的条目不删)。
# ③ 无缓冲回读(FILE_FLAG_NO_BUFFERING):抽样指纹不再可能命中 Windows 缓存里的旧内容。
TRASH_DIRNAME = ".transcode_trash"
TRASH_TTL_HOURS = 72.0 # 隔离区里原件留多久;只有「正式文件还在」的条目才会被回收
TRASH_PURGE_EVERY = 3600.0 # 同一个目录最多一小时扫一次,别让 GC 本身成为网络负担
TAIL_GATE_SECONDS = 5.0 # 尾部解码窗口(秒)
class _ShortRead(IOError):
"""A read that came back shorter than asked: on this share that is truncation, never EOF."""
def trash_dir_for(path):
"""`<dir>/.transcode_trash` —— 必须与被替换的文件同一个卷,rename 才是零拷贝零网络 IO。"""
return os.path.join(os.path.dirname(os.path.abspath(path)), TRASH_DIRNAME)
def _trash_dest(path, when=None):
stem, ext = os.path.splitext(os.path.basename(path))
key = hashlib.sha1(os.path.abspath(path).encode("utf-8")).hexdigest()[:8]
day = time.strftime("%Y-%m-%d", time.localtime(when if when else time.time()))
return os.path.join(trash_dir_for(path), day, "%s__%s%s" % (stem, key, ext))
def move_to_trash(path, live, note="", tries=5):
"""把 `path` 移进隔离区(同卷 rename),并写一份旁注。返回隔离区路径。
共享盘会短暂占着句柄(WinError 32,2026-10-28 实测),所以重试;**重试全败就抛**,
由调用方判成「无法安全安装」—— 绝不能退化成「那就算了,直接覆盖/删除」。
"""
dest = _trash_dest(path)
os.makedirs(os.path.dirname(dest), exist_ok=True)
if os.path.exists(dest):
stem, ext = os.path.splitext(dest)
dest = "%s.%d%s" % (stem, int(time.time()), ext)
last = None
for attempt in range(1, tries + 1):
try:
os.replace(path, dest)
last = None
break
except OSError as e:
last = e
log(" ! quarantine move %s held (%s) - retry %d/%d"
% (os.path.basename(path), str(e)[:70], attempt, tries))
time.sleep(0.5 * attempt)
if last is not None:
raise last
rec = {"src": os.path.abspath(path), "live": os.path.abspath(live), "note": note,
"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "pid": os.getpid()}
try:
rec["bytes"] = os.path.getsize(dest)
with open(dest + ".json", "w", encoding="utf-8") as fh:
json.dump(rec, fh, ensure_ascii=False)
except OSError as e:
# 文件已经在安全处了;旁注只是给 GC 与人工恢复用的线索,写不上不该毁掉一次安装。
log(" ! quarantine record for %s not written: %s" % (os.path.basename(dest), e))
return dest
def restore_from_trash(trash_path, original):
"""回滚:把隔离区里的原件放回原位(若半成品占着名字,先删掉它)。"""
try:
if os.path.exists(original):
os.remove(original)
os.replace(trash_path, original)
except OSError as e:
log(" !! ROLLBACK FAILED: the original is still in quarantine at %s (%s) - "
"restore it by hand" % (trash_path, e))
return False
try:
os.remove(trash_path + ".json")
except OSError:
pass
log(" rollback: the original is back at %s" % disp(original))
return True
def purge_trash(dirs, ttl_hours=TRASH_TTL_HOURS, dry=False):
"""回收隔离区里过期的原件 —— 但**绝不删最后一份**。
旁注里记着当初的 `live`;如果那个正式文件已经不见了,说明这正是「原件未替换」的形态
(新文件没落成,原件是唯一的副本),删掉就把可恢复的事故变成数据丢失。留着,并说清楚。
"""
stats = {"removed": 0, "bytes": 0, "kept": 0, "errors": 0, "dirs": 0}
cutoff = time.time() - float(ttl_hours) * 3600.0
for d in sorted({os.path.abspath(x) for x in dirs if x}):
td = os.path.join(d, TRASH_DIRNAME)
if not os.path.isdir(td):
continue
stamp = os.path.join(td, ".purge")
try:
if not dry and os.path.exists(stamp) \
and os.path.getmtime(stamp) > time.time() - TRASH_PURGE_EVERY:
continue
except OSError:
pass
stats["dirs"] += 1
for dp, _dn, fn in os.walk(td):
for name in fn:
if name == ".purge" or name.endswith(".json"):
continue
p = os.path.join(dp, name)
try:
st = os.stat(p)
except OSError:
continue
if st.st_mtime > cutoff:
continue
live = ""
try:
with open(p + ".json", encoding="utf-8") as fh:
live = (json.load(fh) or {}).get("live") or ""
except (OSError, ValueError):
live = ""
if live and not os.path.exists(live):
stats["kept"] += 1
log(" trash: KEEPING %s - %s is gone, this is the last copy"
% (os.path.basename(p), live))
continue
if dry:
stats["removed"] += 1
stats["bytes"] += st.st_size
continue
try:
os.remove(p)
try:
os.remove(p + ".json")
except OSError:
pass
stats["removed"] += 1
stats["bytes"] += st.st_size
except OSError as e:
stats["errors"] += 1
log(" ! trash: cannot remove %s (%s)" % (p, e))
if not dry:
try:
with open(stamp, "w", encoding="utf-8") as fh:
fh.write(time.strftime("%Y-%m-%dT%H:%M:%S"))
except OSError:
pass
return stats
def tail_decode_gate(path, dur=0.0, seconds=TAIL_GATE_SECONDS, timeout=900):
"""真解码 `path` 的最后几秒 —— 唯一能抓住截断上传/尾部空洞的检查。
为什么是尾部:`-movflags +faststart` 把索引 `moov` 放在文件头,于是常规 ffprobe 对
「`mdat` 只写了一半」的文件照样报出完整时长(6 起截断上传就是这么通过所有既有门禁的)。
只有去解物理末尾的帧,ffmpeg 才会 seek 到那里并读真包:短文件报
`partial file` / `Invalid NAL unit size`,不是沉默。
"""
win = float(seconds)
if dur:
win = min(win, max(0.5, float(dur) * 0.5))
cmd = [FFMPEG, "-nostdin", "-v", "error", "-xerror", "-sseof", "-%.3f" % win,
"-i", path, "-map", "0:v:0?", "-f", "null", "-"]
try:
r = run(cmd, timeout=timeout)
except subprocess.TimeoutExpired:
return False, "tail decode timed out after %ds" % timeout
if r.returncode != 0:
return False, "tail decode rc=%s %s" % (r.returncode, (r.stderr or "").strip()[-300:])
return True, "tail %.1fs decoded" % win
_NO_BUFFERING = 0x20000000
_SEQUENTIAL_SCAN = 0x08000000
_SECTOR = 4096 # NO_BUFFERING 要求 offset / 长度 / 缓冲区都按扇区对齐
def _plain_read(path, offset, length):
"""A few bytes, buffered. Only ever used for the file's final PARTIAL sector, which
FILE_FLAG_NO_BUFFERING refuses to read (an unbuffered read may not cross EOF)."""
with open(path, "rb") as f:
f.seek(offset)
return f.read(length)
def _win_unbuffered_read(path, offset, length):
"""用 FILE_FLAG_NO_BUFFERING 读 `length` 字节:绕开 Windows 缓存管理器。
为什么需要它:`_sha_remote_sample` 走普通 open(),Dokan/RaiDrive 会从本地缓存池直接回答,
于是抽样窗口全对、而服务器上只有前几十兆。扇区对齐是这条 flag 的硬要求(offset、长度、
缓冲区三者都要),而且无缓冲读**不许跨过 EOF**,所以:读窗放大到扇区边界、按文件大小裁到
最后一个整扇区;文件末尾那个不满一扇区的零头(< 4 KB)单独用普通读补上。
"""
if os.name != "nt":
raise OSError("FILE_FLAG_NO_BUFFERING is Windows-only")
from ctypes import wintypes
offset, length = int(offset), int(length)
start = offset - (offset % _SECTOR)
end = offset + length
span = ((end - start) + _SECTOR - 1) // _SECTOR * _SECTOR
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateFileW.restype = ctypes.c_void_p
k32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]
h = k32.CreateFileW(str(path), 0x80000000, 0x7, None, 3,
_NO_BUFFERING | _SEQUENTIAL_SCAN, None)
if not h or h == ctypes.c_void_p(-1).value:
raise OSError(ctypes.get_last_error() or 1, "CreateFileW(NO_BUFFERING) refused")
try:
fsize = ctypes.c_longlong(0)
k32.GetFileSizeEx(ctypes.c_void_p(h), ctypes.byref(fsize))
room = int(fsize.value) - start
if room <= 0:
raise _ShortRead("%s: unbuffered read at %d+%d is past EOF (file is %d byte(s)) - "
"truncated" % (os.path.basename(str(path)), offset, length,
int(fsize.value)))
span = min(span, (room // _SECTOR) * _SECTOR) # 不许跨 EOF,且必须整扇区
if not k32.SetFilePointerEx(ctypes.c_void_p(h), ctypes.c_longlong(start), None, 0):
raise OSError(ctypes.get_last_error() or 1, "SetFilePointerEx failed")
buf = ctypes.create_string_buffer(span + _SECTOR)
addr = (ctypes.addressof(buf) + _SECTOR - 1) & ~(_SECTOR - 1)
got = wintypes.DWORD(0)
total = 0
while total < span:
if not k32.ReadFile(ctypes.c_void_p(h), ctypes.c_void_p(addr + total),
span - total, ctypes.byref(got), None):
err = ctypes.get_last_error()
if err in (38, 87): # EOF / the server says the file ends here
break
raise OSError(err, "ReadFile(NO_BUFFERING) failed")
if not got.value:
break
total += got.value
data = ctypes.string_at(addr, total)
finally:
k32.CloseHandle(ctypes.c_void_p(h))
# 末尾不满一扇区的零头:无缓冲读拿不到,用普通读补(< 4 KB;物理尾部另有尾部解码门禁)。
# 只补一个扇区的量:补多了就等于把「绕开缓存」这件事取消了。
tail_start = start + len(data)
if end > tail_start:
data += _plain_read(path, tail_start, min(end - tail_start, _SECTOR))
out = data[offset - start: offset - start + length]
if len(out) != length:
raise _ShortRead("%s: unbuffered read at %d+%d returned %d byte(s) - truncated"
% (os.path.basename(str(path)), offset, length, len(out)))
return out
def _sha_sample_nocache(path, size, label="sampled-nocache"):
"""`_sha_sample` 的三个窗口,但每次读都绕开缓存。窗口相同 -> 指纹可比。"""
h = hashlib.sha256()
size = int(size)
if size <= 3 * SAMPLE_CHUNK:
spans = [(0, size)]
else:
mid = ((size - SAMPLE_CHUNK) // 2) & ~0xFFFFF
spans = [(0, SAMPLE_CHUNK), (mid, SAMPLE_CHUNK), (size - SAMPLE_CHUNK, SAMPLE_CHUNK)]
got = 0
for off, ln in spans:
b = _win_unbuffered_read(path, off, ln)
h.update(b)
got += len(b)
return h.hexdigest(), size, got
def _sha_remote_sample_nocache(path, size, label="remote", tries=3):
"""`_sha_remote_sample` 的无缓冲版。返回 (指纹, 实读字节, 是否真的绕过了缓存)。
`bypassed` 为 False 表示这台机器/这个文件系统拒绝了 NO_BUFFERING,退回普通读 —— 这件事
必须写进回执,不能让「验过了」悄悄等于「问过缓存了」。
"""
last = None
for attempt in range(1, tries + 1):
try:
n = os.path.getsize(path)
if n != int(size):
raise IOError("%s size %d != expected %d" % (label, n, int(size)))
try:
d, _, got = _sha_sample_nocache(path, size, label)
return d, got, True
except _ShortRead:
raise # 截断就是截断,不许退回缓存去问第二遍
except OSError as e:
log(" NOTE: cache bypass unavailable for %s (%s) - buffered read instead"
% (label, e))
d, _, got = _sha_sample(path, size, label)
return d, got, False
except (OSError, MemoryError) as e:
last = e
log(" ! %s unbuffered read attempt %d failed: %s" % (label, attempt, e))
time.sleep(5 * attempt)
raise last
def publish_staged(remote_tmp, live, loc_out=None, tries=5):
"""把校验过的临时件改名到正式名。返回 (ok, how, why),how = "rename" / "direct-write"。
共享盘偶尔占着句柄(WinError 32),所以重试;彻底改不动名说明那是**幽灵暂存名**
(2026-10-28 实测:`exists()` 说有、`ls` 没有、任何 rename 都失败),此时用手上已验过的
本地成品直接写到正式名,而不是让一件已经做完的活失败。
"""
last = None
for attempt in range(1, tries + 1):
try:
os.replace(remote_tmp, live)
return True, "rename", ""
except OSError as e:
last = e
if attempt < tries:
log(" ! rename held by the share (%s) - retry %d/%d"
% (str(e)[:70], attempt, tries))
time.sleep(0.5 * attempt)
if not loc_out:
return False, "", str(last)[:200]
log(" ! rename is impossible on this share (%s) - installing %s directly"
% (str(last)[:70], os.path.basename(live)))
if not copy_local_to_remote(loc_out, live):
return False, "", ("the share refused both the rename (%s) and a direct write"
% str(last)[:70])
return True, "direct-write", ""
def probe_ok(path, info, vcodec="hevc"):
"""Structural gate on any path (local or share)."""
return T.verify(info, path, vcodec, "copy" if info["acodec"] in ("aac", "mp4a", "") else "aac",
@@ -1662,12 +1990,25 @@ def process(src, args, dest=None, origin=None):
# `_sha_sample` 返回 (指纹, size, 实读字节);这里只留指纹与实读字节,size 用 n_loc 自己那份。
smp_loc, _smp_size, smp_n = _sha_sample(loc_out, n_loc, "encoded output")
last = ""
bypassed = False
for up in range(1, 3):
if not copy_local_to_remote(loc_out, remote_tmp):
last = "FAIL upload"
time.sleep(10 * up)
continue
h_rem, n_rem = _sha_remote_sample(remote_tmp, n_loc, "uploaded temp")
# ③ 无缓冲回读:窗口读绕开 Windows 缓存,问的是服务器上真有的字节。
try:
h_rem, n_rem, bypassed = _sha_remote_sample_nocache(remote_tmp, n_loc,
"uploaded temp")
except OSError as e:
last = "FAIL read-back: %s" % e
log(" ! %s (upload %d) - retrying" % (last, up))
try:
os.remove(remote_tmp)
except (OSError, MemoryError):
pass
time.sleep(10 * up)
continue
if (h_rem, n_rem) == (smp_loc, smp_n):
break
last = "FAIL read-back mismatch local=%s/%d remote=%s/%d" % (
@@ -1680,49 +2021,56 @@ def process(src, args, dest=None, origin=None):
time.sleep(10 * up)
else:
return last, None
# 6. atomic replace, then confirm on the share
# ① 尾部实包解码:在共享盘上那份「即将被装成正式文件」的副本上真解末尾几秒。
# 抽样指纹证明的是「这几个窗口的字节对」,尾部解码证明的是「物理末尾真的能解」——
# §10.161 那 6 起截断上传正是前者过了、后者没查。
tail_msg = "tail gate skipped (--no-tail-gate)"
if TAIL_GATE:
tail_ok, tail_msg = tail_decode_gate(remote_tmp, info.get("dur") or 0.0)
if not tail_ok:
try:
os.remove(remote_tmp)
except OSError:
pass
return "FAIL install gate: %s" % tail_msg, None
log(" gate: %s%s" % (tail_msg,
"" if bypassed else " (cache bypass refused - buffered read)"))
# 6. TWO-PHASE COMMIT: quarantine -> publish -> verify, and the original is NEVER deleted.
#
# The upload's write handle is not gone the moment `copy_local_to_remote` returns: an SMB
# client can hold it for a second or two, and the rename then dies with WinError 32 ("being
# used by another process") for a file nobody else has open. That is what failed the
# `.mov -> .mp4` install of one 19 MB clip three times in a row (measured 2026-10-28 on
# Z:\Temporary\短视频\_io-test) while a hand-run os.replace in the SAME directory
# succeeded - so it is the leftover handle, not the share's permissions. Retry a few times
# instead of failing an item that is already encoded AND verified.
for _try in range(1, 6):
# (a) whatever occupies the target name is moved into `.transcode_trash/<date>/` on the
# SAME volume (an inode rename: 0 bytes copied, 0 network IO, reversible);
# (b) the verified staging file takes its place;
# (c) if (b) or any post-install gate fails, (a) is rolled back.
# Nothing here calls os.remove() on an original any more: the ONLY thing that deletes one
# is purge_trash(), TRASH_TTL_HOURS later, and never when it is the last copy (§10.161).
quarantined = [] # [(trash path, original path)]
targets = [live] if os.path.abspath(live) == os.path.abspath(src) else []
if not targets and os.path.exists(live):
targets = [live] # an older output already sitting on the target name
for t in targets:
if origin_used and os.path.abspath(t) == os.path.abspath(src):
continue # the snapshot origin is the archive: never move it
try:
os.replace(remote_tmp, live)
break
quarantined.append((move_to_trash(t, live, note="pre-publish"), t))
except OSError as e:
if _try == 5:
# A rename that cannot be satisfied at all is a PHANTOM staged name, not a
# busy file: the share's local cache reported `...new.mp4` as existing while the
# server had already forgotten it (measured 2026-10-28: os.path.exists() said
# yes, `ls` of the same directory did not list it, and every rename - including
# a hand-run one - failed with WinError 32). Retrying cannot fix that. We still
# HOLD the verified local encode, so install it straight under the final name
# and hash-check it, instead of failing an item that is already done.
log(" ! rename is impossible on this share (%s) - installing %s directly"
% (str(e)[:70], os.path.basename(live)))
if not copy_local_to_remote(loc_out, live):
return ("FAIL install: the share refused both the rename (%s) and a direct "
"write of %s" % (str(e)[:70], live)), None
h_re, n_re = _sha_remote_sample(live, n_loc, "installed file")
if (h_re, n_re) != (smp_loc, smp_n):
return ("FAIL install read-back: %s is %s/%d, encoded was %s/%d"
% (live, h_re[:12], n_re, smp_loc[:12], smp_n)), None
try:
os.remove(remote_tmp)
except OSError:
pass
break
log(" ! rename held by the share (%s) - retry %d/5" % (str(e)[:70], _try))
time.sleep(0.5 * _try)
# NEVER delete the source when it came from the snapshot origin: that is the archive of
# the originals, and removing it would destroy the only clean copy of the library.
if not origin_used and not getattr(args, "keep_source", False) \
and os.path.abspath(live) != os.path.abspath(src):
os.remove(src)
return ("FAIL install refused: %s could not be moved into %s (%s) - nothing was "
"replaced" % (os.path.basename(t), TRASH_DIRNAME, str(e)[:120])), None
def _rollback(why):
"""Put every quarantined original back (removing the half-published file first)."""
for trash_path, original in reversed(quarantined):
restore_from_trash(trash_path, original)
return why
ok, how, why = publish_staged(remote_tmp, live, loc_out)
if not ok:
return _rollback("FAIL install: %s" % why), None
if how == "direct-write":
try:
os.remove(remote_tmp) # the phantom staging name, if the share still lists it
except OSError:
pass
back = probe(live)
# copy 档也要查 hvc1:HEVC 源走 copy 时标签同样必须落成 hvc1(否则 iOS 拒播 + 幂等判据失效)
tag_needed = (plan["container"] == "mp4"
@@ -1730,29 +2078,48 @@ def process(src, args, dest=None, origin=None):
if not back or back["vcodec"] != expect_vc \
or (tag_needed and back["tag"] != "hvc1") \
or abs(back["dur"] - info["dur"]) > max(1.0, info["dur"] * 0.01):
return "FAIL read-back probe: %s" % (back and (back["vcodec"], back["tag"], back["dur"]),), None
return _rollback("FAIL read-back probe: %s"
% (back and (back["vcodec"], back["tag"], back["dur"]),)), None
ok, msg = TR.verify(plan, tjs, TR.probe(live), expect_vc)
if not ok:
return "FAIL post-replace gate on share: %s" % msg, None
return _rollback("FAIL post-replace gate on share: %s" % msg), None
# Metadata can lie on this share. RaiDrive/Dokan serves CACHED attributes, and a rename did
# not actually land for one file while every metadata probe insisted it had: the run
# reported "ok 1085 MB -> 478 MB" and the live file was still the H.264 original afterwards,
# with nothing anywhere reporting an error. So read the installed file back and compare its
# hash with what we encoded - the only check that cannot be served from a cache.
try:
h_back, n_back = _sha_remote_sample(live, n_loc, "installed file")
h_back, n_back, back_bypass = _sha_remote_sample_nocache(live, n_loc, "installed file")
except OSError as e:
return "FAIL install verify: cannot read the installed file back: %s" % e, None
return _rollback("FAIL install verify: cannot read the installed file back: %s" % e), None
if (h_back, n_back) != (smp_loc, smp_n):
return ("FAIL install verify: the live file is NOT the encode we made "
"(live %s/%d bytes vs ours %s/%d) - the replace did not land"
% (h_back[:12], n_back, smp_loc[:12], smp_n)), None
return _rollback("FAIL install verify: the live file is NOT the encode we made "
"(live %s/%d bytes vs ours %s/%d) - the replace did not land"
% (h_back[:12], n_back, smp_loc[:12], smp_n)), None
# The source leaves the library the same way: into the quarantine, not into nothing. A move
# that fails here is NOT a failure of the item - the new file is verified and the original is
# still intact, which is an extra copy, never a loss.
retired = []
if not origin_used and not getattr(args, "keep_source", False) \
and os.path.abspath(live) != os.path.abspath(src) and os.path.exists(src):
try:
retired.append(move_to_trash(src, live, note="post-install"))
except OSError as e:
log(" ! NOTE: the source is still at %s (quarantine move failed: %s) - the "
"installed file is verified, so this is an extra copy, not a loss"
% (disp(src), str(e)[:80]))
return "ok", {"sha256": h_loc, "bytes": n_loc, "src_bytes": n_in,
"src_mb": round(info["size"] / 1e6, 1),
"out_mb": round(n_loc / 1e6, 1),
"ratio": round(100.0 * n_loc / max(info["size"], 1), 1),
"tier": tier, "bpp": round(bpp, 4), "video_pct": round(growth, 1),
"ssim": ssim_note, "encode_s": round(el, 1)}
"ssim": ssim_note, "encode_s": round(el, 1),
# 安装段回执:怎么装的、原件在哪、缓存绕过是否真的生效、尾部解码窗口。
"install": {"how": how, "tail": tail_msg,
"cache_bypass": bool(bypassed and back_bypass),
"quarantine": [os.path.basename(p)
for p, _ in quarantined] + retired}}
finally:
for p in (loc_src, loc_out):
try:
@@ -1767,7 +2134,11 @@ def process(src, args, dest=None, origin=None):
def collect(root):
out = []
for dp, _, fn in os.walk(root):
for dp, dns, fn in os.walk(root):
# The quarantine is full of VIDEO_EXT files with their original names: walking into it
# would re-enqueue every original this engine just retired (and, on a hand-run, encode it
# back into the library it came from).
dns[:] = [d for d in dns if d != TRASH_DIRNAME]
for f in fn:
if os.path.splitext(f)[1].lower() in VIDEO_EXT and ".part." not in f \
and "_src" not in f and ".new." not in f:
@@ -1853,6 +2224,14 @@ def build_parser():
ap.add_argument("--reverse", action="store_true")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--no-decode-check", action="store_true")
ap.add_argument("--no-tail-gate", action="store_true",
help="EMERGENCY ONLY: skip the tail-seek decode of the uploaded copy. That gate "
"is the only check that catches a truncated upload (the moov index sits at "
"the head, so a probe reports the full duration for half a file)")
ap.add_argument("--trash-ttl-hours", type=float, default=TRASH_TTL_HOURS,
help="how long a quarantined original is kept in %s before GC (default %g h); "
"an entry whose installed file is gone is NEVER collected"
% (TRASH_DIRNAME, TRASH_TTL_HOURS))
ap.add_argument("--overwrite", action="store_true", help="re-do files already HEVC")
ap.add_argument("--keep-local", action="store_true",
help="pilot mode: encode + verify + gate locally and report the numbers, then "
@@ -1881,8 +2260,10 @@ CAPABILITIES_VERSION = 3 # bump when the SHAPE or the MEANING of the report
# 3 (2026-10-24): + flags container/audio_downmix/subs, + `containers`
# (1 = Batch 5a introduced it; 2 = 4b-1 added the `qsv` tier and its two
# knobs, so `tiers`/`quality_knobs`/`defaults` all gained entries)
__version__ = "1.2.0" # human/ledger build id; the control plane only prints it
__version__ = "1.3.0" # human/ledger build id; the control plane only prints it
# 1.2.0 (2026-10-24): multi-track audio / subtitles / attachments
# 1.3.0 (2026-11-01): install gates - tail-seek decode, same-volume
# quarantine (no more `os.remove(src)`), cache-bypassed read-back
# Which options are quality dials, and their names in the report. The NAME->option mapping has to be
# written down (only a human knows which flags are quality knobs), but every VALUE is read back out of
@@ -1956,7 +2337,7 @@ def print_capabilities(cap):
def main():
global DECODE_CHECK, STAGE # WORK/STAGE/LEDGER/LOCKF/POLICY move via _apply_work_dir
global DECODE_CHECK, STAGE, TAIL_GATE # WORK/STAGE/LEDGER/LOCKF/POLICY move via _apply_work_dir
ap = build_parser()
args = ap.parse_args()
if args.capabilities:
@@ -1971,6 +2352,7 @@ def main():
print_capabilities(cap)
return
DECODE_CHECK = not args.no_decode_check
TAIL_GATE = not args.no_tail_gate
if args.work_dir:
_apply_work_dir(args.work_dir)
log("=== work dir: %s (ledger, locks, gate_policy.json)" % WORK)
@@ -2008,6 +2390,17 @@ def main():
files = list(reversed(files))
if args.limit:
files = files[:args.limit]
# 隔离区 GC:把过了 TTL 的原件真正回收掉。每个目录最多一小时扫一次(purge_trash 自己看
# `.purge` 时间戳),所以逐项调用也不会变成网络负担;GC 失败只记一笔,绝不影响本轮的活。
try:
gdirs = {os.path.dirname(f) for f in files}
gdirs.add(ROOT)
g = purge_trash(gdirs, args.trash_ttl_hours)
if g["removed"] or g["kept"]:
log(" trash GC: reclaimed %d file(s) / %.1f GB, kept %d as last copy"
% (g["removed"], g["bytes"] / 1e9, g["kept"]))
except OSError as e:
log(" ! trash GC skipped: %s" % e)
if args.tier == "x265":
# x265 is CPU: pin it to the cores the control plane chose so the desktop keeps the rest.
# NB pin_to_e_cores only covers THIS process - Windows does not inherit an affinity mask, so