From 04a7bc8b74bca5c342d5a06b952cfa5e880ffee3 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:58:46 -0800 Subject: [PATCH 1/9] e2e: scenarios for the other ways Plex and the arrs use an offloaded file Adds to tests/e2e/plex_e2e.py, in the existing style (counts and states on the PASS/FAIL/SKIP/INFO lines, ids only on DETAIL lines, changes put back in finally): T server transcode (lower bitrate, then another container), pulled as an HLS client S seek past the head, back before the fetch point, back into the head, forward again Z long pause past the slot, watched and read-wait timeouts, then resume M two streams at once (same file; a second file only when a role is named) P Plex's own analysis and folder scan must not fetch the whole file R arr refresh and rescan: same file record, the link is still ours, nothing fetched K audio and subtitle track switches during a play, selection put back W no demote starts while a watched file is fetched (read-only) audit nothing left dangling: link, stub and manifest of every row that is not whole rearm_try_row.py makes the try-row re-arm a reusable step (dry unless REARM_APPLY=1). llm_shadow_check.py checks, read-only, that the LLM layer is in shadow mode. The README says what each scenario costs, what should happen per use, and why arr rename, delete and upgrade stay a written plan. Scenarios run only on the real server through runner jobs; nothing here runs in CI. --- tests/e2e/README.md | 106 ++++- tests/e2e/llm_shadow_check.py | 87 ++++ tests/e2e/plex_e2e.py | 755 +++++++++++++++++++++++++++++++++- tests/e2e/rearm_try_row.py | 423 +++++++++++++++++++ 4 files changed, 1351 insertions(+), 20 deletions(-) create mode 100644 tests/e2e/llm_shadow_check.py create mode 100644 tests/e2e/rearm_try_row.py diff --git a/tests/e2e/README.md b/tests/e2e/README.md index f189bff..75de519 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -10,38 +10,110 @@ server's own token (inside the tiering container); it never touches plex.tv. - `plex_e2e.py` runs inside the tiering container: `docker exec -i tiering python3 -I - ... < plex_e2e.py`. It prints `PASS|FAIL|SKIP|INFO text` (counts and states) and `DETAIL` lines (ids; send these to syslog, never to a public log). - `test_plex_e2e.py` is a unit test against a fake Plex (`python3 -m unittest test_plex_e2e`, sandbox or CI only). +- `rearm_try_row.py` (in the tiering container) retires a consumed try row and picks a new one. Its header says what it + writes and how to put it back. Without `REARM_APPLY=1` it stops before the first search. +- `llm_shadow_check.py` (in the arr-webhook container) is scenario L, read-only. + +Scenarios run only on the real server, through runner jobs. They are never run in CI and never against made-up data. ## Scenarios -| id | what | needs | -|----|------|-------| -| up | player is listed by the server with `playback`, proxied command answers | player started | -| A | play the try row, then playMedia the same file at the same offset | now | -| B | `--switch-live --check` during the play, read-only | now | -| I | control port closed: player left alone, no restore | now | -| C | whole-file download of the offloaded try row via the part endpoint: want events, promote, SHA-256 equals the manifest | offloaded try row | -| D | bad chunk ahead of the play position: EIO or stall, never bad bytes; the trigger fires | substitute PR | -| E | planned alternative live: player moves to the usenet substitute, offset keeps advancing, no full local copy, row carries the new release | substitute PR | -| F | planned alternative dead: unplanned release found by a live search | substitute PR | -| G | no alternative: player left alone, alert raised (simulated, nothing real broken) | substitute PR | -| H | the same switch while paused | substitute PR | +| id | what | needs | try row after | +|----|------|-------|---------------| +| up | player is listed by the server with `playback`, proxied command answers | player started | unchanged | +| A | play the try row, then playMedia the same file at the same offset | player | whole (if it was offloaded) | +| B | `--switch-live --check` during the play, read-only | player | unchanged | +| I | control port closed: player left alone, no restore | player | unchanged | +| C | whole-file download of the offloaded try row via the part endpoint: want events, promote, SHA-256 equals the manifest | offloaded try row | whole | +| D | bad chunk ahead of the play position: EIO or stall, never bad bytes; the trigger fires | substitute PR | used | +| E | planned alternative live: player moves to the usenet substitute, offset keeps advancing, no full local copy, row carries the new release | substitute PR | used | +| F | planned alternative dead: unplanned release found by a live search | substitute PR | used | +| G | no alternative: player left alone, alert raised (simulated, nothing real broken) | substitute PR | used | +| H | the same switch while paused | substitute PR | used | +| P | Plex's own tasks: media analysis of the item, then a scan of its folder. No reader may ask for the whole file; the row stays offloaded; Plex keeps the item under the same key | offloaded try row | offloaded | +| R | the arr refreshes and rescans the item: it still lists the same file at full size, the link is still ours, nothing is fetched | offloaded try row, Radarr | offloaded | +| audit | every row that is not whole has its link, stub and manifest; no manifest lacks a row | nothing | unchanged | +| S | seek far past the head, back to the middle before the first fetch point, back into the head, forward again: each time the play goes on | offloaded or promoting try row, player | whole | +| W | while the watched file is fetched, no demote starts (read-only; says whether it ran inside the window with a demote pending) | player | whole | +| M | two streams at once: the player plays while a second client reads 64 MiB elsewhere in the same file; with `E2E_SECOND_ROLE` a second file too | player | whole | +| K | switch the audio track, turn on an embedded and an external subtitle during a play; the selection found is put back | player, a file with the tracks | whole | +| Z | pause for `E2E_PAUSE_S` (default 780 s, past the slot, watched and read-wait timeouts), resume at the same place | player | whole | +| T | server transcode pulled as an HLS client: a forced lower bitrate (video re-encoded), then another container with the streams copied | nothing (no player) | whole | +| L | `llm_shadow_check.py`: the LLM layer is in shadow mode and every decision written during the run is a shadow row | arr-webhook | unchanged | D to H skip unless `E2E_SUBSTITUTE=1`. Never run `--switch-live` without `--check` except on the try row. -## One-shot try row +## One fetch per try row + +Any play, sync or transcode of the offloaded try row starts one fetch of the whole file (a promote), and the file then +stays whole for 60 days. So one offloaded try row serves, in this order: + +1. P, R and audit: they read only and must leave it offloaded (a FAIL here means a background reader fetched the file). +2. one of: C, or one of D to H, or the play group S W M K Z (they share the one fetch; each prints the row state it + started on, and a run on a whole row says that it proves the Plex side only), or T from cold. + +T may also run right after the play group without a new row: it then proves a transcode during or after the fetch. +After step 2, run `rearm_try_row.py` and wait for the runner's nightly window to offload the new row. + +What each costs on Usenet: P, R, audit, L, up, A on a whole row, B, I: nothing. C, the play group, T from cold, D to H: +one fetch of the try file each (count it against the nightly re-download budget). F adds one live indexer search. +A re-arm: up to 6 searches and 3 NZB grabs, no article download. + +## What should happen, per use + +- Plex transcode (T): the transcoder is a stream reader like a play. Its first read asks for the file, the fetch starts at + the position it reads, segments come once those bytes are there, and the file ends whole. +- Seek (S): a seek past the head moves the fetch to the new position; a seek back before the fetch point moves it back. + The viewer waits, then the play goes on. No read error, no zero-filled data. +- Pause (Z): the fetch goes on while paused; after the resume the play continues at the same place, also when the file + became whole in between (the open file must survive the swap back to a plain file). +- Two streams (M): both readers get their bytes; neither starves the other. +- Plex's own tasks (P): the scanner and analysis jobs are background readers. They read the local head and tail, or the + middle straight from the remote, and never fetch the whole file. Intro, credit and preview-thumbnail runs are the same + reader class by design, but Plex has no per-item trigger for them and a library-wide run would touch every item, so + they are not started here; P only reports whether the item already carries their results. +- Arr refresh and rescan (R): the arr sees a file of the full size at the same path and does nothing. +- Tracks (K): a track switch in direct play needs no new bytes. An external subtitle is its own small file and is never + offloaded. Nothing is fetched beyond what the play fetches. +- Demote window and movers (W): while a watched file is fetched, the runner starts no demote. The job prints the + glacier mover's state beside it (it must yield while Plex is busy). +- LLM layer (L): no decision kind is about a play and the tiering runner never asks the layer, so a play adds no + decision. What is proven: shadow mode is on, and every row written during the run is a shadow row. + +## Arr rename, delete and upgrade: a written plan, not a scenario + +These change or replace a real library file, and they cannot be put back, so they are not automated here. + +- Rename. The arr renames the link, tierfs is not touched. The row keeps the old path until the next nightly register + adopts the new one. Until then the runner cannot promote the row, so a play past the head would wait and then fail, + and the new path is outside the allowlist. A rename cannot be undone through the arr (its naming format decides). + Plan: only when the arr itself lists a pending rename for the try item, apply it by hand in the arr in the evening, + run `audit` (it must show one "link missing" row), let the nightly register run, run `audit` again (clean), then + re-arm, because the allowlist still names the old path. +- Delete. The arr removes the link (or moves it to its recycle bin, which copies the whole file out of tierfs first). + The row is then only reported (`l_missing`); its stub and manifest stay. Plex drops the item. Plan: do not test on a + library file. To see the result, read `audit` after the next natural delete of an offloaded item. +- Upgrade. The arr downloads a better release (one real download) and replaces the link with the new file. The row goes + to failed with the note "L replaced"; its stub and manifest are removed after the orphan grace. Plan: no forced + upgrade. After the next natural upgrade of an offloaded item, `audit` must show the row under "L replaced" and, after + the grace, no stray manifest. -Any play or sync makes a file whole (promote) and it stays whole for 60 days. So the offloaded try row serves exactly one of C or -D to H. After it, pick and offload a new try row (as job 0335 does) before the next one. A and B work on a whole row too. +`audit` is the check that nothing is left dangling in all three cases. It does not walk the library, so it cannot see a +link whose row is gone. ## Limits of this player It is mpv, not the Plex app. It does not exercise the app's own buffering, transcode decision, offline sync or error screens. +mpv gives up on a stream that sends nothing for 60 s (its network timeout). A FAIL in S or Z that says the session is +gone means the fetch took longer than this player waits; a phone or TV app has a limit of its own. +T pulls the transcode as an HLS client (the requests Plex Web makes). The server side is real; no app decodes it. ## Needs a human with a real phone or TV app 1. Start a movie from the try row in your own app; later switch it live and watch for a freeze longer than a few seconds or a restart from 0. 2. Pause, wait, resume across a switch. -3. Seek far ahead (past the head) while the file is offloaded: it should wait, then play, not error. +3. Seek far ahead (past the head) while the file is offloaded, in the app (S proves it on mpv): it should wait, then play, not error. 4. App Download of an offloaded item (offline sync): completes, plays offline. 5. Casting from the app to a TV during a switch; a TV app that refuses remote control is left alone. -6. Subtitles and audio track selection survive a switch. +6. Subtitles and audio track selection survive a switch (K proves the selection during a plain play). +7. A transcode the app itself asks for (cellular quality, an unsupported codec), and a track switch during it. diff --git a/tests/e2e/llm_shadow_check.py b/tests/e2e/llm_shadow_check.py new file mode 100644 index 0000000..7bff789 --- /dev/null +++ b/tests/e2e/llm_shadow_check.py @@ -0,0 +1,87 @@ +"""L: the LLM queue layer in shadow mode logs its decisions and changes nothing. + +Runs INSIDE the arr-webhook container, read-only (two GETs to the webhook's own port): + + docker exec -i arr-webhook python3 -I - < llm_shadow_check.py + + is when the play scenarios of the run began. Output follows plex_e2e.py: lines +`PASS|FAIL|SKIP|INFO L ` carry counts and states only; nothing here prints a title or an id. + +No decision kind is about a Plex play (the kinds are queue, import and audit decisions), and the +tiering runner never asks the layer. So a play is not expected to add a decision. What can be +proven on the real system is that the layer is in shadow mode and that every decision it wrote +during the run is a shadow row: logged beside the rules' action, with the rules' action kept. +Environment: E2E_WEBHOOK_URL (default http://127.0.0.1:$PORT, PORT default 9876). +""" +import json +import os +import sys +import time +import urllib.request +from datetime import datetime + +BASE = os.environ.get("E2E_WEBHOOK_URL") or f"http://127.0.0.1:{os.environ.get('PORT', '9876')}" +FAILS = 0 + + +def say(kind, text): + global FAILS + FAILS += 1 if kind == "FAIL" else 0 + print(f"{kind} L {text}", flush=True) + + +def get(path): + try: + with urllib.request.urlopen(BASE + path, timeout=30) as r: + return json.loads(r.read(32 << 20)) + except Exception: + return None + + +def epoch(ts): + try: + return float(ts) + except (TypeError, ValueError): + pass + try: + return datetime.fromisoformat(str(ts).replace("Z", "+00:00")).timestamp() + except ValueError: + return 0.0 + + +def main(argv): + try: + since = float(argv[0]) if argv else time.time() - 3600 + except ValueError: + since = time.time() - 3600 + layers = get("/llm-layers") + if not isinstance(layers, dict) or not layers.get("ok"): + say("SKIP", "the webhook's /llm-layers does not answer (the layer is not deployed here)") + return 0 + mode = str(layers.get("mode") or "") + modes = layers.get("modes") if isinstance(layers.get("modes"), dict) else {} + live = sorted(k for k, m in modes.items() if m not in ("shadow", "off")) + say("INFO", f"layer mode: {mode or 'unset'}; decision kinds: {len(modes)}; kinds not in shadow or off: {len(live)}") + if mode != "shadow": + say("SKIP", f"the layer is not in shadow mode (mode {mode or 'unset'}); the shadow check does not apply") + return 0 + say("PASS" if not live else "FAIL", f"no decision kind acts on its own ({len(live)} kinds outside shadow or off)") + doc = get("/llm-decisions?limit=1000") + rows = [r for r in (doc or {}).get("entries") or [] if isinstance(r, dict) and epoch(r.get("ts")) >= since] + kinds = {} + for r in rows: + kinds[str(r.get("kind"))[:30]] = kinds.get(str(r.get("kind"))[:30], 0) + 1 + say("INFO", f"decisions written since the run began ({int(time.time() - since)} s ago): {len(rows)} {kinds or ''}") + if not rows: + say("SKIP", "no decision was written during the run: no decision kind fires on a Plex play, so none is expected") + return 0 + shadow = sum(1 for r in rows if r.get("mode") == "shadow") + say("PASS" if shadow == len(rows) else "FAIL", f"every decision written during the run is a shadow row ({shadow} of {len(rows)})") + named = sum(1 for r in rows if r.get("rules_action") not in (None, "")) + say("PASS" if named == len(rows) else "FAIL", f"each row records the rules' action, the one that was kept ({named} of {len(rows)})") + say("INFO", f"rows where the model disagreed with the rules (logged only): {sum(1 for r in rows if r.get('agree') is False)}") + return 1 if FAILS else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/e2e/plex_e2e.py b/tests/e2e/plex_e2e.py index bf67844..0a434b8 100644 --- a/tests/e2e/plex_e2e.py +++ b/tests/e2e/plex_e2e.py @@ -11,10 +11,15 @@ Output: lines `PASS|FAIL|SKIP|INFO ` carry counts and states only. Lines that start with `DETAIL ` hold ids and are sent to syslog by the job, never to the runner log. -Scenarios: up, AB (A + B), I, stop, C, D, E, F, G, H, state. +Scenarios: up, AB (A + B), I, stop, C, D, E, F, G, H, state, and the other ways Plex and the arrs use a +file: T (server transcode), S (seek past the head and back), Z (long pause, resume), M (two streams at +once), P (Plex's own analysis and scan), R (arr refresh and rescan), K (audio and subtitle tracks), +W (demotes hold while a watched file is fetched), audit (nothing left dangling). Environment: PLEX_URL, PLEX_TOKEN (container), TIERING_DB, TIERFS_EVENTS, TIERING_ALERTS (container); E2E_SERVER_URL (the server address the PLAYER can reach), E2E_PLAYER_ID, E2E_SUBSTITUTE=1 (the -substitute PR is deployed; D to H skip without it). +substitute PR is deployed; D to H skip without it), E2E_WAIT_S (longest wait for bytes that are not +local, default 600), E2E_PAUSE_S (pause length in Z, default 780), E2E_SECOND_MB (bytes the second +stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file). """ import hashlib import http.client @@ -23,14 +28,17 @@ import sqlite3 import subprocess import sys +import threading import time import urllib.error import urllib.parse import urllib.request +import uuid PLAYER = os.environ.get("E2E_PLAYER_ID", "e2e00000-0000-4000-8000-00000000e2e0") PROVIDER = "com.plexapp.plugins.library" RESULTS = [] +MIB = 1 << 20 def say(kind, scn, text): @@ -77,6 +85,19 @@ def call(self, method, path, params=None, target=None, timeout=20): except ValueError: return st, None + def raw(self, path, params=None, extra=None, timeout=60, limit=64 << 20): + """(status, body bytes) of a GET; for playlists and media segments. Never raises.""" + url = self.base + path + ("?" + urllib.parse.urlencode(params) if params else "") + h = {"X-Plex-Token": self.token, "X-Plex-Client-Identifier": "e2e-harness"} + h.update(extra or {}) + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r: + return r.status, r.read(limit) + except urllib.error.HTTPError as e: + return e.code, b"" + except (urllib.error.URLError, OSError, http.client.HTTPException): + return 0, b"" + def mc(self, path, params=None): st, doc = self.call("GET", path, params) return ((doc or {}).get("MediaContainer") or {}) if st == 200 else {} @@ -632,8 +653,736 @@ def sc_h(): _scn_sub("H", "H") +# ---- the other ways Plex and the arrs use a file ---------------------------------------------- +# +# T, S, Z, M, K and W play the try row, so the first of them that meets it offloaded starts the +# one fetch of the whole file (a promote); the rest run while it is fetched or after. Each prints +# the row state it started on. P, R and audit read only and must leave the row offloaded. + +def _wait_s(): + return _int(os.environ.get("E2E_WAIT_S"), 600) + + +def _meta(plex, rk, **params): + return (plex.mc(f"/library/metadata/{rk}", params or None).get("Metadata") or [{}])[0] + + +def _part(md, size=None): + parts = [p for m in md.get("Media") or [] for p in m.get("Part") or []] + return next((p for p in parts if size is None or _int(p.get("size")) == size), None) + + +def _ms_at(md, row, byte): + """The play position (ms) that holds about this byte of the file.""" + return int(_int(md.get("duration")) * byte / max(_int(row["size"]), 1)) + + +def want_offsets(since_size, id): + """Offsets of the tierfs want events for `id` written after the file was `since_size` bytes.""" + p = os.environ.get("TIERFS_EVENTS", "") + out = [] + if not p or not os.path.exists(p): + return out + with open(p, "rb") as f: + f.seek(min(since_size, os.path.getsize(p))) + for ln in f.read().decode("utf-8", "replace").splitlines(): + try: + j = json.loads(ln) + except ValueError: + continue + if j.get("id") == id and j.get("ev") == "want": + out.append(_int(j.get("offset"))) + return out + + +def wait_advancing(plex, rk, timeout, near_ms=None, tol_ms=120_000): + """Seconds until the player's offset advances (near `near_ms` when given), or None. Gives up + early when the session is gone, which is what a read error does to the player.""" + t0, gone = time.time(), 0 + while time.time() - t0 < timeout: + a, b, adv = advancing(plex, rk, gap=5) + if adv and (near_ms is None or abs(b["vo"] - near_ms) <= tol_ms): + return time.time() - t0 + gone = gone + 1 if b is None else 0 + if gone >= 6: + return None + return None + + +def _begin(scn, plex, row): + """Play the try row on the real player: just before the end of the head when it is not whole + (so the play crosses into bytes that are not local), else a minute in. The session or None.""" + if row["state"] != "whole": + st, ses, off = _play_near_head_end(plex, row) + else: + off = 60_000 + st, _, _ = play(plex, row["rating_key"], off, server_url()) + ses = wait_session(plex, row["rating_key"], 120) if st == 200 else None + say("INFO", scn, f"row state at the start: {row['state']}" + + ("" if row["state"] != "whole" else " (whole: this run proves the Plex side only, not the offload path)")) + if not check(scn, ses is not None, f"a playing session for the try row (playMedia HTTP {st}, offset {off // 1000}s)"): + return None + return ses + + +def _end(scn, id, t0, ev0): + """What every play scenario reports at its end: nothing failed, and the state it left.""" + kinds = event_kinds(id, t0) + check(scn, not [k for k in kinds if k in ("failed", "promote_short_read", "promote_short_remote", "bad_chunk")], + f"no failure event on the row (events since the start: {sorted(set(kinds)) or 'none'})") + ev = tail_events(ev0, id) + say("INFO", scn, f"row state at the end: {row_of(id)['state']}; tierfs events: {ev if ev is not None else 'not visible'}; " + f"alerts: {alert_kinds_since(t0) or 'none'}") + + +def health(): + """The runner's /healthz document, or None.""" + hp = os.environ.get("TIERING_HTTP") or "127.0.0.1:8471" + host, _, port = hp.rpartition(":") + try: + with urllib.request.urlopen(f"http://{host if host not in ('', '0.0.0.0') else '127.0.0.1'}:{port}/healthz", + timeout=10) as r: + return json.loads(r.read(1 << 20)) + except urllib.error.HTTPError as e: + try: + return json.loads(e.read(1 << 20)) + except ValueError: + return None + except (urllib.error.URLError, OSError, ValueError): + return None + + +def _offload_mods(): + """The runner's own modules (path map, arr clients), or None outside the tiering container.""" + if os.path.isdir("/app") and "/app" not in sys.path: + sys.path.insert(0, "/app") + try: + from offload import paths, redownload, register + except Exception: + return None + return paths, register, redownload + + +def _link_state(row, mods): + """ours | missing | replaced: what stands at the library path of a row that is not whole.""" + paths, register, _ = mods + d = paths.disk_paths(row.get("lib_path") or "", paths.parse_path_map(os.environ.get("TIERING_PATH_MAP"))) + if not d: + return "missing" + return "ours" if len(d) == 1 and register._tierfs_link_id(d[0]) == row["id"] else "replaced" + + +# ---- T: server transcode ---------------------------------------------------------------------- + +def _hls_lines(body): + return [ln.strip() for ln in body.decode("utf-8", "replace").splitlines() if ln.strip() and not ln.startswith("#")] + + +def _transcode_once(scn, plex, row, md, label, direct_stream, expect): + """One server transcode of the try row, pulled as an HLS client pulls it (the requests Plex Web + makes). The transcoder and its reads of the file are the real ones. Always stops the session.""" + sid = "e2e-" + uuid.uuid4().hex[:20] + hdr = {"X-Plex-Client-Identifier": "e2e-harness-transcode", "X-Plex-Session-Identifier": sid, + "X-Plex-Product": "Plex Web", "X-Plex-Platform": "Chrome", "X-Plex-Device": "Linux"} + head, size = _int(row.get("head_len")), _int(row["size"]) + off_s = _ms_at(md, row, min(head + 96 * MIB, size // 2)) // 1000 if row["state"] != "whole" else 300 + base = "/video/:/transcode/universal/" + params = {"path": f"/library/metadata/{row['rating_key']}", "mediaIndex": 0, "partIndex": 0, "protocol": "hls", + "offset": off_s, "copyts": 1, "fastSeek": 1, "directPlay": 0, "directStream": direct_stream, + "directStreamAudio": direct_stream, "location": "lan", "hasMDE": 1, "session": sid, + "X-Plex-Platform": "Chrome"} + if not direct_stream: + params.update({"maxVideoBitrate": 2000, "videoResolution": "1280x720", "videoQuality": 60}) + t0 = time.time() + try: + st, body = plex.raw(base + "start.m3u8", params, hdr, timeout=120) + variants = _hls_lines(body) + if not check(scn, st == 200 and bool(variants), f"{label}: the server started a transcode session (HTTP {st}, " + f"{len(variants)} variant playlist(s), start offset {off_s}s)"): + return + vpath = variants[0] if variants[0].startswith("/") else base + variants[0] + vdir = vpath.split("?")[0].rsplit("/", 1)[0] + "/" + end, segs = time.time() + _wait_s(), [] + while time.time() < end and len(segs) < 3: + st, body = plex.raw(vpath, None, hdr, timeout=60) + segs = _hls_lines(body) if st == 200 else [] + if len(segs) < 3: + time.sleep(3) + if not check(scn, len(segs) >= 3, f"{label}: the media playlist lists segments ({len(segs)} after {int(time.time() - t0)} s)"): + return + got, first = [], None + for seg in segs[:3]: + n = 0 + while time.time() < end and not n: + st, body = plex.raw(seg if seg.startswith("/") else vdir + seg, None, hdr, timeout=120) + n = len(body) if st == 200 else 0 + if not n: + time.sleep(3) + if n and first is None: + first = time.time() - t0 + got.append(n) + check(scn, len(got) == 3 and all(got), f"{label}: 3 media segments were delivered ({sum(got) // 1024} KiB, " + f"first one {int(first) if first is not None else '?'} s after the start: the wait a viewer sees)") + mine = [t for t in plex.mc("/transcode/sessions").get("TranscodeSession") or [] if sid in str(t.get("key") or "")] + if mine: + t = mine[0] + say("INFO", scn, f"{label}: video {t.get('videoDecision')}, audio {t.get('audioDecision')}, container " + f"{t.get('container')}, protocol {t.get('protocol')}, speed {t.get('speed')}") + if expect: + check(scn, t.get("videoDecision") == expect, f"{label}: the server's video decision is {expect}") + else: + say("INFO", scn, f"{label}: the session is not in /transcode/sessions (decision not read)") + finally: + st, _ = plex.raw(base + "stop", {"session": sid}, hdr, timeout=30) + say("INFO", scn, f"{label}: transcode session stopped (HTTP {st})") + + +def sc_t(): + """T: Plex transcodes the try row: a forced lower bitrate (video re-encoded), then a different + container with the streams copied. The transcoder reads the file through tierfs like a play.""" + s = setup("T", need_player=False) + if not s: + return + plex, id, row = s + md = _meta(plex, row.get("rating_key")) + if not check("T", bool(row.get("rating_key")) and _int(md.get("duration")) > 0, "Plex lists the try row with a duration"): + return + state0, t0, ev0 = row["state"], time.time(), events_size() + say("INFO", "T", f"row state at the start: {state0}" + + ("" if state0 != "whole" else " (whole: this run proves the Plex side only, not the offload path)")) + _transcode_once("T", plex, row, md, "lower bitrate", 0, "transcode") + _transcode_once("T", plex, row_of(id), md, "other container", 1, None) + if state0 == "offloaded": + ev = tail_events(ev0, id) + if ev is None: + say("INFO", "T", "no tierfs events file visible here; want events not counted") + else: + check("T", ev.get("want", 0) >= 1, f"the transcoder's reads asked for the file (tierfs events: {ev})") + kinds = event_kinds(id, t0) + check("T", "promote_start" in kinds, "the runner started fetching the file for the transcode (promote_start)") + _end("T", id, t0, ev0) + + +# ---- S: seek ---------------------------------------------------------------------------------- + +def _seek(scn, plex, rk, ms, label, timeout): + st = player_cmd(plex, "/player/playback/seekTo", {"offset": int(ms), "type": "video"}) + if not check(scn, st == 200, f"{label}: seekTo accepted by the player (HTTP {st})"): + return False + w = wait_advancing(plex, rk, timeout, near_ms=ms) + cur = my_session(plex) + return check(scn, w is not None, f"{label}: the play goes on at the new position " + + (f"after {int(w)} s" if w is not None else + f"NOT within {timeout} s (session {'still there, ' + cur['state'] if cur else 'gone: the player got an error'})")) + + +def sc_s(): + """S: during a play, seek far past the head, then back to bytes before the first fetch point, + then back into the head. Each time the player must wait and go on, never error.""" + s = setup("S") + if not s: + return + plex, id, row = s + if row["state"] not in ("offloaded", "promoting"): + say("SKIP", "S", f"the try row is {row['state']}; a seek past the head needs it offloaded (re-arm a try row first)") + return + rk, head, size = row.get("rating_key"), _int(row.get("head_len")), _int(row["size"]) + md = _meta(plex, rk) + if not check("S", _int(md.get("duration")) > 0 and size > head + 512 * MIB, "the try row has a duration and a middle of 512 MiB or more"): + return + t0, ev0 = time.time(), events_size() + say("INFO", "S", f"row state at the start: {row['state']}") + st, _, _ = play(plex, rk, 60_000, server_url()) + if not check("S", st == 200 and wait_session(plex, rk, 120) is not None, f"playing inside the head (playMedia HTTP {st})"): + return + far, back = max(int(size * 0.6), head + 256 * MIB), head + 96 * MIB + _seek("S", plex, rk, _ms_at(md, row, far), "forward into the middle", _wait_s()) + wants = want_offsets(ev0, id) + if os.environ.get("TIERFS_EVENTS") and row["state"] == "offloaded": + check("S", any(o >= head + 128 * MIB for o in wants), + f"tierfs asked for bytes far past the head, at the seek target ({len(wants)} want events)") + _seek("S", plex, rk, _ms_at(md, row, back), "backwards, to the middle before the first fetch point", _wait_s()) + if os.environ.get("TIERFS_EVENTS"): + w2 = want_offsets(ev0, id) + say("INFO", "S", f"want events after the seek back: {len(w2)} ({len(set(w2))} distinct offsets)") + _seek("S", plex, rk, 120_000, "backwards into the head (local bytes)", 120) + _seek("S", plex, rk, _ms_at(md, row, far) + 30_000, "forward again to the first target", _wait_s()) + _end("S", id, t0, ev0) + + +# ---- Z: long pause ---------------------------------------------------------------------------- + +def sc_z(): + """Z: pause a play for longer than the timeouts on the way (the unused-stream slot, the watched + window, the read wait), then resume. The play must go on from where it stopped.""" + s = setup("Z") + if not s: + return + plex, id, row = s + rk, pause_s = row.get("rating_key"), _int(os.environ.get("E2E_PAUSE_S"), 780) + t0, ev0 = time.time(), events_size() + if not _begin("Z", plex, row): + return + try: + if not check("Z", wait_advancing(plex, rk, _wait_s()) is not None, "the play advances before the pause"): + return + st = player_cmd(plex, "/player/playback/pause", {"type": "video"}) + time.sleep(6) + a = my_session(plex) + check("Z", st == 200 and a is not None and a["state"] == "paused", f"paused through the proxy (HTTP {st}, session " + f"{a['state'] if a else 'gone'})") + if not a: + return + end = time.time() + pause_s + while time.time() < end: + time.sleep(min(60, max(1, end - time.time()))) + b = my_session(plex) + check("Z", b is not None and b["rk"] == str(rk) and abs(b["vo"] - a["vo"]) < 5000, + f"still paused on the same item after {pause_s} s (session {b['state'] if b else 'gone'})") + ev = tail_events(ev0, id) or {} + say("INFO", "Z", f"during the pause: row state {row_of(id)['state']}, slot timeouts {ev.get('slot_timeout', 0)}, " + f"want events {ev.get('want', 0)}") + st = player_cmd(plex, "/player/playback/play", {"type": "video"}) + w = wait_advancing(plex, rk, _wait_s()) + c = my_session(plex) + check("Z", st == 200 and w is not None, f"resume: the play goes on (HTTP {st}, " + + (f"after {int(w)} s)" if w is not None else f"NOT within {_wait_s()} s; session {'there' if c else 'gone'})")) + if c and w is not None: + check("Z", a["vo"] - 5000 <= c["vo"] <= a["vo"] + (w + 30) * 1000, + f"it resumed where it stopped ({a['vo'] // 1000}s -> {c['vo'] // 1000}s), not from the start") + finally: + cur = my_session(plex) + if cur and cur["state"] == "paused": + player_cmd(plex, "/player/playback/play", {"type": "video"}) + _end("Z", id, t0, ev0) + + +# ---- M: two streams at once ------------------------------------------------------------------- + +def _range_read(plex, key, start, length, out, client): + """Read `length` bytes at `start` of a part through the server, the request a second direct-play + client makes. Fills `out`: status, n, sha, zero (1 MiB blocks of only zeros), secs, error.""" + u = urllib.parse.urlparse(plex.base) + t0, h, n, zero = time.time(), hashlib.sha256(), 0, 0 + conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=_wait_s()) + try: + conn.request("GET", key, headers={"X-Plex-Token": plex.token, "X-Plex-Client-Identifier": client, + "X-Plex-Session-Identifier": client, "Range": f"bytes={start}-{start + length - 1}"}) + r = conn.getresponse() + out["status"] = r.status + while r.status in (200, 206) and n < length: + b = r.read(min(MIB, length - n)) + if not b: + break + zero += 0 if any(b) else 1 + h.update(b) + n += len(b) + except (OSError, http.client.HTTPException) as e: + out["error"] = type(e).__name__ + finally: + conn.close() + out.update(n=n, sha=h.hexdigest(), zero=zero, secs=int(time.time() - t0)) + + +def _local_sha(row, start, length): + """SHA-256 of the same range of the library file once the row is whole again, else None.""" + lp = row.get("lib_path") or "" + if row["state"] != "whole" or not os.path.isfile(lp) or os.path.islink(lp): + return None + h, n = hashlib.sha256(), 0 + with open(lp, "rb") as f: + f.seek(start) + while n < length: + b = f.read(min(MIB, length - n)) + if not b: + break + h.update(b) + n += len(b) + return h.hexdigest() + + +def sc_m(): + """M: two streams at once. The real player plays the try row while a second client reads another + part of the same file through the server. With E2E_SECOND_ROLE, a second file is read as well.""" + s = setup("M") + if not s: + return + plex, id, row = s + rk, size, head = row.get("rating_key"), _int(row["size"]), _int(row.get("head_len")) + part = _part(_meta(plex, rk), size) + if not check("M", part is not None, "Plex has a part of the row's size for the try row"): + return + length = min(_int(os.environ.get("E2E_SECOND_MB"), 64) * MIB, size // 4) + start = max(int(size * 0.4), head) // MIB * MIB + t0, ev0 = time.time(), events_size() + if not _begin("M", plex, row): + return + a = my_session(plex) + jobs = [("same file", id, part["key"], start, {})] + other = (os.environ.get("E2E_SECOND_ROLE") or "").strip() + try: + pick = json.load(open("/state/sync-test/pick.json")) + except (OSError, ValueError): + pick = {} + orow = row_of((pick.get(other) or {}).get("id", "")) if other and isinstance(pick.get(other), dict) else None + if orow and orow["id"] != id and orow["state"] == "offloaded" and orow.get("rating_key"): + opart = _part(_meta(plex, orow["rating_key"]), _int(orow["size"])) + if opart: + jobs.append(("second file", orow["id"], opart["key"], _int(orow.get("head_len")) // MIB * MIB, {})) + if len(jobs) == 1: + say("SKIP", "M", "two different files: no second offloaded test row was named (E2E_SECOND_ROLE); the allowlist " + "holds one try row, and a read makes the second row whole as well") + threads = [threading.Thread(target=_range_read, args=(plex, key, off, length, out, f"e2e-harness-second-{i}"), daemon=True) + for i, (_, _, key, off, out) in enumerate(jobs)] + for t in threads: + t.start() + samples = moved = 0 + while any(t.is_alive() for t in threads) and time.time() - t0 < _wait_s() + 120: + _, _, adv = advancing(plex, rk, gap=10) + samples += 1 + moved += 1 if adv else 0 + for t in threads: + t.join(30) + b = my_session(plex) + for label, oid, _, off, out in jobs: + check("M", out.get("status") in (200, 206) and out.get("n") == length and not out.get("error"), + f"{label}: the second stream got {out.get('n', 0) // MIB} of {length // MIB} MiB in {out.get('secs')} s " + f"(HTTP {out.get('status')}, error {out.get('error') or 'none'})") + check("M", out.get("zero", 0) == 0, f"{label}: no zero-filled block in what it got ({out.get('zero', 0)} of 1 MiB blocks)") + want = _local_sha(row_of(oid), off, length) + if want is None: + say("INFO", "M", f"{label}: not compared with the local file (the row is {row_of(oid)['state']})") + else: + check("M", want == out.get("sha"), f"{label}: the bytes equal the same range of the local file") + detail(f"M: {label} id={oid} offset={off} length={length}") + check("M", a is not None and b is not None and b["rk"] == str(rk) and b["vo"] > a["vo"], + f"the player's own stream went on meanwhile (advancing in {moved} of {samples} samples, " + f"{((b['vo'] - a['vo']) // 1000) if a and b else 0} s of film in {int(time.time() - t0)} s)") + check("M", wait_advancing(plex, rk, 120) is not None, "the player still advances after the second stream ended") + _end("M", id, t0, ev0) + + +# ---- K: audio and subtitle tracks ------------------------------------------------------------- + +def _streams(plex, rk): + part = _part(_meta(plex, rk)) or {} + st = part.get("Stream") or [] + return part.get("id"), [x for x in st if _int(x.get("streamType")) == 2], [x for x in st if _int(x.get("streamType")) == 3] + + +def _selected(streams): + return next((str(x.get("id")) for x in streams if x.get("selected")), "0") + + +def _pick_stream(scn, plex, rk, param, sid, label, kind): + st = player_cmd(plex, "/player/playback/setStreams", {param: sid, "type": "video"}) + ok = check(scn, st == 200, f"{label}: setStreams accepted by the player (HTTP {st})") + end, now = time.time() + 30, "" + while ok and time.time() < end and now != str(sid): + time.sleep(3) + _, au, su = _streams(plex, rk) + now = _selected(au if kind == 2 else su) + if ok: + check(scn, now == str(sid), f"{label}: the server shows the new track as selected") + check(scn, wait_advancing(plex, rk, _wait_s()) is not None, f"{label}: the play goes on after the change") + + +def sc_k(): + """K: switch the audio track and turn on a subtitle (embedded, and external when a sidecar file + exists) during a play. Changes the selected tracks of the try item for the token's account; the + selection it found is put back at the end.""" + s = setup("K") + if not s: + return + plex, id, row = s + rk = row.get("rating_key") + pid, audio, subs = _streams(plex, rk) + a0, s0 = _selected(audio), _selected(subs) + emb = [x for x in subs if x.get("index") is not None] + ext = [x for x in subs if x.get("index") is None and x.get("key")] + say("INFO", "K", f"tracks: audio {len(audio)}, embedded subtitles {len(emb)}, external subtitles {len(ext)}") + if len(audio) < 2 and not subs: + say("SKIP", "K", "the try item has one audio track and no subtitle; nothing to switch (no track is made up)") + return + t0, ev0 = time.time(), events_size() + if not _begin("K", plex, row): + return + try: + if len(audio) >= 2: + other = next(str(x.get("id")) for x in audio if str(x.get("id")) != a0) + _pick_stream("K", plex, rk, "audioStreamID", other, "audio track", 2) + else: + say("SKIP", "K", "audio switch: the try item has one audio track") + if emb: + _pick_stream("K", plex, rk, "subtitleStreamID", str(emb[0].get("id")), "embedded subtitle", 3) + else: + say("SKIP", "K", "embedded subtitle: the try item has none") + if ext: + _pick_stream("K", plex, rk, "subtitleStreamID", str(ext[0].get("id")), "external subtitle", 3) + else: + say("SKIP", "K", "external subtitle: no sidecar file exists for the try item") + finally: + back = {"subtitleStreamID": s0} # 0 turns subtitles off; an audio id of 0 is never sent + if a0 != "0": + back["audioStreamID"] = a0 + if my_session(plex): + player_cmd(plex, "/player/playback/setStreams", dict(back, type="video")) + if pid: + plex.call("PUT", f"/library/parts/{pid}", dict(back, allParts=1)) + time.sleep(3) + _, au, su = _streams(plex, rk) + check("K", _selected(au) == a0 and _selected(su) == s0, "the track selection found at the start is back") + _end("K", id, t0, ev0) + + +# ---- W: the demote window during a play ------------------------------------------------------- + +def sc_w(): + """W: while a watched file is fetched for a play, the runner starts no demote. Read-only. It + exercises the hold only inside the demote window with a demote pending; it says which it met.""" + s = setup("W") + if not s: + return + plex, id, row = s + rk = row.get("rating_key") + if health() is None: + say("SKIP", "W", "the runner's /healthz does not answer from here") + return + t0, ev0 = time.time(), events_size() + cur = my_session(plex) + if not (cur and cur["rk"] == str(rk)) and not _begin("W", plex, row): + return + seen = {"promoting": 0, "blocked": 0, "window": 0, "planned": 0, "samples": 0} + reasons = set() + end = time.time() + _int(os.environ.get("E2E_WINDOW_S"), 120) + while time.time() < end: + h, st = health(), row_of(id)["state"] + if not h: + time.sleep(10) + continue + c = h.get("counts") or {} + block = str(c.get("demote_blocked") or "") + seen["samples"] += 1 + if st == "promoting" or _int(c.get("promotes_running")): + seen["promoting"] += 1 + seen["blocked"] += 1 if block else 0 + seen["window"] += 0 if block.startswith("outside the demote window") else 1 + seen["planned"] = max(seen["planned"], _int(c.get("demotes_planned"))) + reasons.add(block.split(" (")[0] or "none") + time.sleep(10) + started = dbro().execute("select count(*) from events where kind='offload_start' and ts>=?", (t0,)).fetchone()[0] + say("INFO", "W", f"{seen['samples']} samples: a fetch running in {seen['promoting']}, inside the demote window in " + f"{seen['window']}, demotes planned at most {seen['planned']}; demotes blocked by: {sorted(reasons)}") + if not seen["promoting"]: + say("SKIP", "W", f"no fetch of a watched file was running (the try row is {row_of(id)['state']})") + else: + check("W", started == 0, f"no demote started while the watched file was fetched ({started} offload_start events)") + say("INFO", "W", f"the runner's last pass reported demotes as blocked in {seen['blocked']} of {seen['promoting']} " + "samples taken during the fetch (the count is one pass old)") + if not seen["window"] or not seen["planned"]: + say("SKIP", "W", "the hold inside the window was not exercised: " + + ("the run was outside the demote window" if not seen["window"] else "no demote was pending")) + check("W", wait_advancing(plex, rk, _wait_s()) is not None, "the play advances") + _end("W", id, t0, ev0) + + +# ---- P: Plex's own tasks ---------------------------------------------------------------------- + +def _quiet_reads(scn, id, t0, ev0, label): + """A background reader may read the head, or the middle from the remote, and must never ask + for the whole file: no want event, no promote, the row stays offloaded.""" + ev = tail_events(ev0, id) + if ev is None: + say("INFO", scn, f"{label}: no tierfs events file visible here; reads not counted") + else: + say("INFO", scn, f"{label}: the file was opened {ev.get('open', 0)} time(s); reads from the remote in " + f"{ev.get('remote_read', 0)} of them (0 = only the local head and tail were read)") + check(scn, ev.get("want", 0) == 0, f"{label}: no reader asked for the whole file ({ev.get('want', 0)} want events)") + kinds = event_kinds(id, t0) + check(scn, row_of(id)["state"] == "offloaded" and "promote_start" not in kinds, + f"{label}: the row is still offloaded and no promote started (state {row_of(id)['state']})") + + +def sc_p(): + """P: Plex's own tasks on the offloaded try row: media analysis of the item, then a scan of its + folder. Neither may fetch the whole file. Intro, credit and thumbnail runs have no per-item + trigger; P only reports whether the item already carries their results.""" + s = setup("P", need_player=False) + if not s: + return + plex, id, row = s + if row["state"] != "offloaded": + say("SKIP", "P", f"the try row is {row['state']}, not offloaded (re-arm a try row first)") + return + rk, size = row.get("rating_key"), _int(row["size"]) + md = _meta(plex, rk, includeMarkers=1) + part = _part(md, size) + if not check("P", part is not None, "Plex has a part of the row's size for the try row"): + return + say("INFO", "P", f"results the item already carries: markers {len(md.get('Marker') or [])}, " + f"preview thumbnails {'yes' if part.get('indexes') else 'no'}") + t0, ev0 = time.time(), events_size() + st, _ = plex.call("PUT", f"/library/metadata/{rk}/analyze", timeout=60) + check("P", st == 200, f"analysis of the item asked for (HTTP {st})") + end, seen = time.time() + 180, None + while time.time() < end: + time.sleep(10) + ev = tail_events(ev0, id) or {} + if ev.get("close", 0) and ev == seen: + break + seen = ev + _quiet_reads("P", id, t0, ev0, "analysis") + t1, ev1 = time.time(), events_size() + sec, folder = md.get("librarySectionID"), os.path.dirname(part.get("file") or "") + st, _ = plex.call("GET", f"/library/sections/{sec}/refresh", {"path": folder}, timeout=60) + check("P", st == 200, f"scan of the item's folder asked for (HTTP {st})") + end = time.time() + 300 + time.sleep(15) + while time.time() < end: + d = next((x for x in plex.mc("/library/sections").get("Directory") or [] if str(x.get("key")) == str(sec)), {}) + if not d.get("refreshing"): + break + time.sleep(10) + time.sleep(20) + _quiet_reads("P", id, t1, ev1, "folder scan") + md2 = _meta(plex, rk) + check("P", _part(md2, size) is not None and not md2.get("deletedAt"), + "after the scan Plex still lists the item under the same key with the same part") + say("INFO", "P", f"alerts during the run: {alert_kinds_since(t0) or 'none'}") + + +# ---- R: arr refresh and rescan ---------------------------------------------------------------- + +def _arr_file(c, mid): + f = (c.get(f"/api/v3/movie/{mid}") or {}).get("movieFile") or {} + return f.get("id"), f.get("path"), _int(f.get("size")) + + +def _arr_command(c, body, timeout=240): + """Run one arr command to its end. The final status, or the error's name.""" + try: + cid = (c.post("/api/v3/command", body) or {}).get("id") + end, status = time.time() + timeout, "queued" + while cid and time.time() < end: + status = str((c.get(f"/api/v3/command/{cid}") or {}).get("status") or "") + if status in ("completed", "failed", "aborted", "cancelled", "orphaned"): + break + time.sleep(5) + return status if cid else "no command id" + except Exception as e: + return type(e).__name__ + + +def sc_r(): + """R: the arr that holds the offloaded try row refreshes and rescans it (what it does on its own + every day). It must still see its file, and must not pull the whole file or replace the link. + Changes nothing on disk; there is nothing to put back. Rename, delete and upgrade are not run + here: see the README for why and for the written plan.""" + s = setup("R", need_player=False) + if not s: + return + plex, id, row = s + if row["state"] != "offloaded": + say("SKIP", "R", f"the try row is {row['state']}, not offloaded (re-arm a try row first)") + return + mods = _offload_mods() + if not mods: + say("SKIP", "R", "the runner's modules are not importable here") + return + paths, register, redownload = mods + e = os.environ + try: + radarrs, sonarrs = register.clients_from_env() + arrs = redownload.Arrs(radarrs, sonarrs, paths.parse_path_map(e.get("TIERING_ARR_PATH_MAP")), + paths.parse_path_map(e.get("TIERING_PATH_MAP"))) + hit = arrs.find(row["lib_path"]) + except Exception as ex: + say("FAIL", "R", f"the arr could not be read ({type(ex).__name__})") + return + if not hit or hit.get("kind") != "radarr": + say("SKIP", "R", "no Radarr movie holds the try row's file") + return + c, mid = arrs.radarrs[hit["client"]], hit["ids"][0] + t0, ev0 = time.time(), events_size() + before = _arr_file(c, mid) + check("R", before[2] == _int(row["size"]), "before: the arr lists the file at the row's full size") + status = _arr_command(c, {"name": "RefreshMovie", "movieIds": [mid]}) + check("R", status == "completed", f"RefreshMovie ended: {status}") + status = _arr_command(c, {"name": "RescanMovie", "movieId": mid}) + check("R", status == "completed", f"RescanMovie ended: {status}") + time.sleep(45) + try: + after = _arr_file(c, mid) + except Exception as ex: + after = (None, type(ex).__name__, 0) + check("R", after == before and after[0] is not None, "after: the arr holds the same file record, path and size") + detail(f"R: movie id {mid} file ids {before[0]} -> {after[0]}") + link = _link_state(row_of(id), mods) + check("R", link == "ours", f"the library path is still the row's own link ({link})") + _quiet_reads("R", id, t0, ev0, "refresh and rescan") + kinds = event_kinds(id, t0) + check("R", not [k for k in kinds if k in ("l_replaced", "failed")], + f"no l_replaced or failed event (events: {sorted(set(kinds)) or 'none'}); alerts: {alert_kinds_since(t0) or 'none'}") + + +# ---- audit: nothing left dangling ------------------------------------------------------------- + +def sc_audit(): + """audit: every row that is not whole has its link, stub and manifest, and no manifest is + without a row. Read-only. Run it after any scenario, and after an arr upgrade or delete.""" + mods = _offload_mods() + try: + from offload import ops, runner + cfg = runner.Config.from_env() + except Exception as ex: + say("SKIP", "audit", f"the runner's modules are not importable here ({type(ex).__name__})") + return + if not mods: + say("SKIP", "audit", "the runner's modules are not importable here") + return + rows = [dict(r) for r in dbro().execute( + "select id, lib_path, stub_path, state, restore_note, updated_ts from files where state not in ('whole', 'never')")] + n, bad = {}, {"link missing": [], "link replaced": [], "stub missing": [], "manifest missing": []} + for r in rows: + n[r["state"]] = n.get(r["state"], 0) + 1 + if r["state"] not in ("offloaded", "promoting"): + continue + link = _link_state(r, mods) + if link != "ours": + bad["link " + link].append(r["id"]) + if not (r.get("stub_path") and os.path.exists(r["stub_path"])): + bad["stub missing"].append(r["id"]) + if cfg.manifests and not os.path.exists(ops.manifest_path(cfg.manifests, r["id"])): + bad["manifest missing"].append(r["id"]) + say("INFO", "audit", f"rows that are not whole: {n or 'none'}") + for k, ids in bad.items(): + check("audit", not ids, f"{k}: {len(ids)} of {n.get('offloaded', 0) + n.get('promoting', 0)} offloaded rows") + if ids: + detail(f"audit: {k}: {' '.join(ids[:40])}") + failed = [r for r in rows if r["state"] == "failed"] + notes = {} + for r in failed: + k = "L replaced" if r.get("restore_note") == "L replaced" else "other" if r.get("restore_note") else "no note" + notes[k] = notes.get(k, 0) + 1 + say("INFO", "audit", f"failed rows: {len(failed)} {notes or ''} (an arr upgrade leaves 'L replaced'; its stub and " + f"manifest are removed after {getattr(cfg, 'orphan_grace_days', '?')} days)") + stray = [] + if cfg.manifests and os.path.isdir(cfg.manifests): + probe = "0" * 16 + suffix = os.path.basename(ops.manifest_path(cfg.manifests, probe))[len(probe):] + known = {r["id"] for r in rows} + stray = [f[:16] for f in os.listdir(cfg.manifests) + if suffix and f.endswith(suffix) and len(f) == 16 + len(suffix) and f[:16] not in known] + check("audit", not stray, f"manifests without a row that needs one: {len(stray)}") + if stray: + detail(f"audit: stray manifests: {' '.join(stray[:40])}") + else: + say("INFO", "audit", "no manifest folder visible here; stray manifests not counted") + + SCEN = {"diag": sc_diag, "up": sc_up, "state": sc_state, "AB": sc_ab, "I": sc_i, "stop": sc_stop, "C": sc_c, - "D": sc_d, "E": sc_e, "F": sc_f, "G": sc_g, "H": sc_h} + "D": sc_d, "E": sc_e, "F": sc_f, "G": sc_g, "H": sc_h, + "T": sc_t, "S": sc_s, "Z": sc_z, "M": sc_m, "K": sc_k, "W": sc_w, "P": sc_p, "R": sc_r, "audit": sc_audit} def main(argv): diff --git a/tests/e2e/rearm_try_row.py b/tests/e2e/rearm_try_row.py new file mode 100644 index 0000000..c83dedb --- /dev/null +++ b/tests/e2e/rearm_try_row.py @@ -0,0 +1,423 @@ +"""Re-arm the try row: retire the one a scenario consumed and pick a new one. A reusable step. + +Runs INSIDE the tiering container: + + docker exec -i -e REARM_APPLY=1 tiering python3 -I - < rearm_try_row.py + +A play, a sync or a transcode makes the try row whole again, and it stays whole for the idle +window. This step then swaps it for a fresh one. It does not offload anything itself: the runner +qualifies and demotes the new row in its own nightly window. + +What it changes, only with REARM_APPLY=1, and how each is put back: + * /state/sync-test/pick.json: the old "try" entry moves to "dead", the new one becomes "try". + A copy pick.json.bak- is written first; copy it back to undo. + * the allowlist file TIERING_ONLY_PATHS points at (@file): the old try row's path leaves, the + new one's enters. One test row out, one in; the list never grows. A copy .bak- + is written first; copy it back to undo. +Nothing else is written: no library file, no state DB row, no indexer budget file (searches use a +private copy of the runner's budget state). + +When it does nothing: the try row is still offloaded or busy (it is still armed), it waits for its +first demote, or it is failed (put that right by hand first). Without REARM_APPLY=1 it stops +before the first search and prints what it would do. + +Usenet use, at most: REARM_MAX_SEARCH indexer searches (default 6), REARM_MAX_GRAB NZB grabs +(default 3), about 300 article STAT checks per grab. No article is downloaded. The candidate's +local file is read once for a run of zeros (a damaged download), with its atime put back. + +Output follows plex_e2e.py: `PASS|FAIL|SKIP|INFO rearm ` carry counts and states only; +`DETAIL` lines hold ids and titles and go to syslog. Last line: `REARM picked=N searches=N grabs=N`. +""" +import json +import os +import re +import shutil +import sqlite3 +import sys +import time +import xml.etree.ElementTree as ET +from datetime import datetime + +DAY, GB = 86400.0, 10**9 +SAMPLE = 300 +PICK = "/state/sync-test/pick.json" +ZR = b"\0" * (64 << 10) +SCENE = re.compile(r"^[A-Za-z0-9'&+,!-]+(\.[A-Za-z0-9'&+,!-]+)*\.(19|20)\d\d\..*(720p|1080p|2160p).*-[A-Za-z0-9]+$") + + +def say(kind, text): + print(f"{kind} rearm {text}", flush=True) + + +def detail(text): + print(f"DETAIL rearm: {text}", flush=True) + + +def done(picked, searches, grabs, code=0): + print(f"REARM picked={picked} searches={searches} grabs={grabs}", flush=True) + return code + + +def num(k, d): + try: + return float(os.environ.get(k) or d) + except ValueError: + return float(d) + + +def zero_hole(path): + """Offset of the first 64 KiB run of zeros in the file, or None. A download that zero-filled a + lost article leaves one; video data never holds one. The atime is put back.""" + try: + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOATIME", 0)) + except PermissionError: + fd = os.open(path, os.O_RDONLY) + st0 = os.fstat(fd) + prev, off = b"", 0 + try: + while True: + b = os.read(fd, 16 << 20) + if not b: + return None + buf = prev + b + i = buf.find(ZR) + if i >= 0: + return off - len(prev) + i + prev = buf[-(len(ZR) - 1):] + off += len(b) + finally: + os.close(fd) + try: + os.utime(path, ns=(st0.st_atime_ns, st0.st_mtime_ns)) + except OSError: + pass + + +def sample_ids(nzb): + """(message ids to STAT: every file's first segment plus an even sample, segments, files).""" + firsts, alls = [], [] + for f in ET.fromstring(nzb).iter(): + if f.tag.rsplit("}", 1)[-1] != "file": + continue + segs = [] + for s in f.iter(): + if s.tag.rsplit("}", 1)[-1] == "segment" and (s.text or "").strip(): + try: + n = int(s.get("number") or 0) + except ValueError: + n = 0 + segs.append((n, s.text.strip())) + segs.sort() + if segs: + firsts.append(segs[0][1]) + alls += [x for _, x in segs] + step = max(1, len(alls) // SAMPLE) + return list(dict.fromkeys(firsts + alls[::step])), len(alls), len(firsts) + + +def old_try_verdict(db, old): + """retire | keep: | abort: for the try row pick.json names now.""" + r = db.execute("SELECT state FROM files WHERE id=?", (old.get("id"),)).fetchone() + if r is None: + return "retire" # its row is gone (replaced by a substitute or an upgrade): nothing left to arm + state = r["state"] + if state == "failed": + return "abort:the try row is failed; restore it or clear it by hand first" + if state != "whole": + return f"keep:the try row is {state}; it is still armed (or busy)" + kinds = [k for (k,) in db.execute("SELECT kind FROM events WHERE id=? ORDER BY seq", (old.get("id"),))] + if "offloaded" in kinds: + return "retire" # it was offloaded and is whole again: a scenario consumed it + ev = db.execute("SELECT detail FROM events WHERE id=? AND kind='qualify_failed' ORDER BY ts DESC LIMIT 1", + (old.get("id"),)).fetchone() + try: + reasons = set((json.loads(ev[0]) if ev else {}).get("reasons") or []) + except ValueError: + reasons = set() + if reasons & {"hash_mismatch", "local_damaged"}: + return "retire" # it can never qualify + return "keep:the try row is whole and waits for its first demote in the nightly window" + + +def main(): + sys.path.insert(0, "/app") + from offload import newznab as N, nntp_stat as S, paths, plex_watch as pw, qualify as Q, register, runner as R + from offload.redownload import Arrs + + e, now = os.environ, time.time() + apply = e.get("REARM_APPLY") == "1" + max_search, max_grab = int(num("REARM_MAX_SEARCH", 6)), int(num("REARM_MAX_GRAB", 3)) + cfg = R.Config.from_env() + never_secs = {s.strip().lower() for s in (e.get("TIERING_NEVER_SECTIONS", "Adult")).split(",") if s.strip()} + min_play, maxkbps = num("TIERING_MIN_PLAY_S", 1800), num("TIERING_MAX_STREAM_KBPS", 0) + cap = num("TIERING_DEMOTE_GB_PER_NIGHT", 200) * GB + lo, hi = 3 * GB, 40 * GB + idle_s, new_s = num("TIERING_IDLE_DAYS", 60) * DAY, max(num("TIERING_NEW_DAYS", 30), 30.0) * DAY + + spec = (e.get("TIERING_ONLY_PATHS") or "").strip() + allow = spec[1:].strip() if spec.startswith("@") else "" + if not allow or not os.path.isfile(allow) or not os.access(allow, os.W_OK): + say("FAIL", "the allowlist is not an @file this container can write; nothing written") + return done(0, 0, 0, 1) + if apply and e.get("TIERING_APPLY") != "1": + say("FAIL", "TIERING_APPLY is not 1 in the container; nothing written") + return done(0, 0, 0, 1) + try: + pick = json.load(open(PICK)) + except (OSError, ValueError): + pick = {} + db = sqlite3.connect(f"file:{cfg.db}?mode=ro", uri=True) + db.row_factory = sqlite3.Row + + old = pick.get("try") if isinstance(pick.get("try"), dict) else None + retired = None + if old: + verdict = old_try_verdict(db, old) + if verdict.startswith("keep:"): + say("SKIP", verdict[5:] + "; nothing written") + return done(0, 0, 0) + if verdict.startswith("abort:"): + say("FAIL", verdict[6:] + "; nothing written") + return done(0, 0, 0, 1) + retired = old + say("INFO", "the old try row was consumed; it will be retired") + else: + say("INFO", "pick.json names no try row; one will be picked") + + prov = S.ProviderCfg.from_env("primary") + radarrs, _ = register.clients_from_env() + if prov is None or not radarrs: + say("FAIL", f"missing in the container: {'the primary NNTP provider' if prov is None else 'a Radarr client'}; nothing written") + return done(0, 0, 0, 1) + arrs = Arrs(radarrs, [], paths.parse_path_map(e.get("TIERING_ARR_PATH_MAP")), paths.parse_path_map(e.get("TIERING_PATH_MAP"))) + + eras = "" + try: + eras = json.load(open("/state/eras-test/status.json")).get("lib_path") or "" + except (OSError, ValueError): + pass + dead = pick.get("dead") if isinstance(pick.get("dead"), list) else [] + taken = {v.get("id") for v in pick.values() if isinstance(v, dict)} | {d.get("id") for d in dead if isinstance(d, dict)} + lines = open(allow).read().splitlines() + stamp = time.strftime("%Y%m%d-%H%M%S") + have0 = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} + if retired: + gone = [x for x in lines if x.strip() == retired.get("lib_path")] + lines = [x for x in lines if x.strip() != retired.get("lib_path")] + [f"# e2e re-arm {stamp}: retired a consumed try row"] + say("INFO", f"old try row's path in the allowlist: {len(gone)} line(s), to be removed") + have = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} + + cols = ("id, lib_path, size, state, rating_key, kind, is4k, play_ms, nzb_path, release_name, " + "title, year, imdb_id, tvdb_id, season, episode") + rows = [dict(r) for r in db.execute(f"SELECT {cols} FROM files WHERE state='whole'")] + held = 0 + lost = pick.get("lost") + if isinstance(lost, dict): + r = db.execute("SELECT size, state FROM files WHERE id=?", (lost.get("id"),)).fetchone() + if r is not None and r["state"] in ("whole", "offloading"): + held += r["size"] or 0 + try: + own = {str(k): float(ts or 0) for (k, ts) in db.execute("SELECT rating_key, last_ts FROM last_plays")} + except sqlite3.Error: + own = {} + try: + items = pw.library_items() + hist = pw.play_history(0) + busy = {str(x.get("ratingKey")) for x in list(pw.in_progress()) + list(pw.on_deck()) + list(pw.sessions())} + except Exception as ex: + say("FAIL", f"Plex read failed ({type(ex).__name__}); nothing written") + return done(0, 0, 0, 1) + ever = {str(h.get("ratingKey")) for h in hist} | set(own) + recent = {str(h.get("ratingKey")) for h in hist if float(h.get("viewedAt") or 0) > now - idle_s} + recent |= {k for k, ts in own.items() if ts > now - idle_s} + by_rk = {str(it["ratingKey"]): it for it in items if it.get("ratingKey") is not None} + + by_path, grabs_by_movie = {}, {} + try: + for c in arrs.radarrs: + for m in c.get("/api/v3/movie") or []: + f = m.get("movieFile") if isinstance(m, dict) else None + if f and f.get("path"): + by_path[arrs._local(f["path"])] = (c, m) + page = 1 + while page <= 60: # every Usenet grab this Radarr remembers: (client, movie id) -> [(clean title, epoch)] + res = c.get("/api/v3/history", page=page, pageSize=1000, eventType=1, sortKey="date", sortDirection="descending") + recs = (res.get("records") or []) if isinstance(res, dict) else [] + for h in recs: + d = h.get("data") or {} + proto = str(d.get("protocol") or "").lower() + if proto in ("2", "torrent") or d.get("torrentInfoHash") or not (proto in ("1", "usenet") or d.get("nzbInfoUrl")): + continue + try: + ts = datetime.fromisoformat(str(h.get("date")).replace("Z", "+00:00")).timestamp() + except ValueError: + ts = 1.0 + grabs_by_movie.setdefault((id(c), h.get("movieId")), []).append((Q._clean(h.get("sourceTitle") or ""), ts)) + if len(recs) < 1000: + break + page += 1 + except register.ArrError as ex: + say("FAIL", f"Radarr read failed ({type(ex).__name__}); nothing written") + return done(0, 0, 0, 1) + + def why_not(r): + """(None, sort key, play ms, grab epoch) for a candidate, else (reason, ...).""" + size, rk = r["size"] or 0, str(r["rating_key"]) if r["rating_key"] is not None else "" + it = by_rk.get(rk) + if not (lo <= size <= hi): + return "size outside 3-40 GB", None, 0, 0 + if it is None or it.get("type") != "movie": + return "no Plex movie item", None, 0, 0 + if str(it.get("section") or "").strip().lower() in never_secs or r["is4k"]: + return "never-section or 4K", None, 0, 0 + if r["lib_path"] == eras or r["lib_path"] in have or r["lib_path"] in have0 or r["id"] in taken: + return "already a test row (or retired)", None, 0, 0 + if not (r["release_name"] or "").strip() or r["nzb_path"]: + return "no release name, or already has an archived NZB", None, 0, 0 + if rk in busy or rk in recent: + return "in progress, on deck, playing or played inside the idle window", None, 0, 0 + added = float(it.get("addedAt") or 0) + if not added or added + new_s > now: + return "added inside the new-item window (or no date)", None, 0, 0 + ms = r["play_ms"] or max((it.get("durations") or {}).values() or [0]) + if not ms or ms < min_play * 1000: + return "under the play-time floor", None, 0, 0 + if maxkbps > 0 and it.get("bitrate") and float(it["bitrate"]) > maxkbps: + return "over the bitrate cap", None, 0, 0 + d = paths.disk_paths(r["lib_path"], cfg.path_map) + try: + st = os.stat(d[0]) if len(d) == 1 else None + except OSError: + st = None + if st is None or st.st_nlink != 1 or st.st_size != size: + return "not exactly one plain disk copy of the row's size", None, 0, 0 + cm = by_path.get(r["lib_path"]) + if cm is None: + return "no Radarr movie holds it", None, 0, 0 + name = Q.release_name_of(r) + want = Q._clean(name) + ts = max((t for title, t in grabs_by_movie.get((id(cm[0]), cm[1].get("id")), ()) if title == want), default=0) + watched = 1 if rk in ever else 0 + if ts: + return None, (0, watched, -ts), ms, ts + if SCENE.match((name or "").strip()): + return None, (1, watched, -int(r["year"] or 0)), ms, 0 + return "not a Usenet grab and not a scene-style release name", None, 0, 0 + + why, cands = {}, [] + for r in rows: + reason, key, ms, ts = why_not(r) + if reason: + why[reason] = why.get(reason, 0) + 1 + else: + cands.append((key, r, ms, ts)) + cands.sort(key=lambda c: c[0]) + say("INFO", f"rows whole: {len(rows)}; candidates: {len(cands)} ({sum(1 for c in cands if c[0][0] == 0)} Usenet grabs of " + f"the exact release, {sum(1 for c in cands if c[0][1] == 0)} never watched)") + for k, v in sorted(why.items(), key=lambda kv: -kv[1]): + say("INFO", f"skipped, {k}: {v}") + if not apply: + say("SKIP", f"REARM_APPLY is not 1: stopped before the first search (it would run up to {max_search} searches and " + f"{max_grab} grabs over {len(cands)} candidates); nothing written") + return done(0, 0, 0) + if not cands: + say("FAIL", "no candidate; nothing written") + return done(0, 0, 0, 1) + + src = e.get("TIERING_NEWZNAB_STATE") or os.path.join(os.path.dirname(os.path.abspath(cfg.db)), "newznab_state.json") + tmp_state = "/tmp/newznab_state-rearm.json" + try: + shutil.copyfile(src, tmp_state) # the runner's budgets as they are; the real file is never written here + except OSError: + pass + client = N.NewznabClient(N.load_indexers(e.get("NEWZNAB_INDEXERS", "")), state_path=tmp_state) + pool = S.NntpPool(prov) + searches = grabs = 0 + new = None + try: + for _, r, ms, ts in cands: + if new or searches >= max_search or grabs >= max_grab: + break + if held + r["size"] > cap - 2 * GB: + continue + searches += 1 + label = f"search {searches}: {r['size'] / GB:.1f} GB, {ms / 60000:.0f} min, " \ + f"{'grabbed %.0f d ago' % ((now - ts) / DAY) if ts else 'scene name'}" + detail(f"search {searches}: id={r['id']} {r['title']} ({r['year']})") + try: + found = list(Q._search(client, Q.identity(r))) + except Exception as ex: + say("INFO", f"{label}: search failed ({type(ex).__name__})") + continue + name = Q.release_name_of(r) + exact = list(Q._find_exact(found, name)) + others = [x for x in found if Q._clean(x.title) != Q._clean(name) and (x.resolution or 0) >= 1080] + note = f"{len(found)} results, exact {len(exact)}, other >=1080p {len(others)}" + if not (exact and others): + say("INFO", f"{label}: {note}: no") + continue + nzb, how = None, "no exact listing" + for rel in exact[:2]: + if grabs >= max_grab: + how = "grab limit reached" + break + grabs += 1 + try: + nzb = client.fetch_nzb(rel) + break + except N.NewznabError as ex: + how = f"grab failed ({type(ex).__name__})" + ids, total, files = sample_ids(nzb) if nzb is not None else ([], 0, 0) + if not ids: + say("INFO", f"{label}: {note}: {how if nzb is None else 'NZB has no segments'}: no") + continue + res = S.check_ids(iter(ids), pool) + if res["missing"]: + say("INFO", f"{label}: {note}: {files} files, {total} segments, sampled {res['total']}, missing {res['missing']}: no") + continue + t0 = time.time() + hole = zero_hole(paths.disk_paths(r["lib_path"], cfg.path_map)[0]) + say("INFO", f"{label}: {note}: sampled {res['total']} of {total} segments, none missing; local file scanned in " + f"{time.time() - t0:.0f} s: {'a zeroed hole, no' if hole is not None else 'no zeroed hole: picked'}") + if hole is None: + new = {"id": r["id"], "lib_path": r["lib_path"], "title": r["title"], "year": r["year"], + "size": r["size"], "rating_key": r["rating_key"], "play_ms": ms} + except S.NntpUnavailable as ex: + say("FAIL", f"the provider could not be asked ({ex.kind}); nothing written") + return done(0, searches, grabs, 1) + finally: + pool.close() + + if new is None and not retired: + say("FAIL", "no candidate passed; nothing written") + return done(0, searches, grabs, 1) + if retired: + pick.pop("try", None) + pick.setdefault("dead", []).append({"id": retired.get("id"), "role": "try", "why": "consumed by an e2e scenario", "ts": now}) + detail(f"retired try row: id={retired.get('id')}") + if new is not None: + pick["try"] = new + pick["ts_rearm"] = now + lines = lines + [f"# e2e re-arm {stamp}: try row (STAT-checked, no zeroed hole in the local file)", new["lib_path"]] + detail(f"new try row: id={new['id']} {new['title']} ({new['year']}) {new['size'] / GB:.1f} GB") + shutil.copyfile(allow, f"{allow}.bak-{stamp}") + with open(allow + ".tmp-rearm", "w") as f: + f.write("\n".join(lines) + "\n") + os.replace(allow + ".tmp-rearm", allow) + if os.path.exists(PICK): + shutil.copyfile(PICK, f"{PICK}.bak-{stamp}") + with open(PICK + ".tmp-rearm", "w") as f: + json.dump(pick, f, indent=1) + os.replace(PICK + ".tmp-rearm", PICK) + after = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} + ok = len(after) <= len(have0) + (0 if retired else 1) + say("PASS" if ok else "FAIL", f"allowlist: {len(have0)} path(s) before, {len(after)} now (one test row out, one in)") + if new is None: + say("FAIL", "the old try row is retired but no candidate passed: there is no try row now") + return done(0, searches, grabs, 1) + say("PASS", f"new try row picked ({new['size'] / GB:.1f} GB); the runner offloads it in its nightly window") + return done(1, searches, grabs, 0 if ok else 1) + + +if __name__ == "__main__": + sys.exit(main()) From 49a71f456f583d9c1dec4018109b401078a8f0e1 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:01:46 -0800 Subject: [PATCH 2/9] e2e: re-arm writes nothing unless a new row passed; audit skips a row that changes state rearm_try_row.py no longer retires the consumed try row when no candidate passes, and refuses before writing when the allowlist would grow. The audit does not judge a row whose state changes while it is looked at (a fetch that ends mid-check). The harness header now lists E2E_WINDOW_S. --- tests/e2e/plex_e2e.py | 20 ++++++++++++++------ tests/e2e/rearm_try_row.py | 38 +++++++++++++++++++------------------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/tests/e2e/plex_e2e.py b/tests/e2e/plex_e2e.py index 0a434b8..cb9dcfc 100644 --- a/tests/e2e/plex_e2e.py +++ b/tests/e2e/plex_e2e.py @@ -19,7 +19,8 @@ E2E_SERVER_URL (the server address the PLAYER can reach), E2E_PLAYER_ID, E2E_SUBSTITUTE=1 (the substitute PR is deployed; D to H skip without it), E2E_WAIT_S (longest wait for bytes that are not local, default 600), E2E_PAUSE_S (pause length in Z, default 780), E2E_SECOND_MB (bytes the second -stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file). +stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file), +E2E_WINDOW_S (how long W samples the runner, default 120). """ import hashlib import http.client @@ -1342,19 +1343,26 @@ def sc_audit(): return rows = [dict(r) for r in dbro().execute( "select id, lib_path, stub_path, state, restore_note, updated_ts from files where state not in ('whole', 'never')")] - n, bad = {}, {"link missing": [], "link replaced": [], "stub missing": [], "manifest missing": []} + n, bad, moved = {}, {"link missing": [], "link replaced": [], "stub missing": [], "manifest missing": []}, 0 for r in rows: n[r["state"]] = n.get(r["state"], 0) + 1 if r["state"] not in ("offloaded", "promoting"): continue + found = [] link = _link_state(r, mods) if link != "ours": - bad["link " + link].append(r["id"]) + found.append("link " + link) if not (r.get("stub_path") and os.path.exists(r["stub_path"])): - bad["stub missing"].append(r["id"]) + found.append("stub missing") if cfg.manifests and not os.path.exists(ops.manifest_path(cfg.manifests, r["id"])): - bad["manifest missing"].append(r["id"]) - say("INFO", "audit", f"rows that are not whole: {n or 'none'}") + found.append("manifest missing") + if found and (row_of(r["id"]) or {}).get("state") != r["state"]: + moved += 1 # the runner finished a step on this row while it was looked at + continue + for k in found: + bad[k].append(r["id"]) + say("INFO", "audit", f"rows that are not whole: {n or 'none'}" + + (f"; {moved} changed state during the audit and were not judged" if moved else "")) for k, ids in bad.items(): check("audit", not ids, f"{k}: {len(ids)} of {n.get('offloaded', 0) + n.get('promoting', 0)} offloaded rows") if ids: diff --git a/tests/e2e/rearm_try_row.py b/tests/e2e/rearm_try_row.py index c83dedb..2532778 100644 --- a/tests/e2e/rearm_try_row.py +++ b/tests/e2e/rearm_try_row.py @@ -17,9 +17,9 @@ Nothing else is written: no library file, no state DB row, no indexer budget file (searches use a private copy of the runner's budget state). -When it does nothing: the try row is still offloaded or busy (it is still armed), it waits for its -first demote, or it is failed (put that right by hand first). Without REARM_APPLY=1 it stops -before the first search and prints what it would do. +When it writes nothing: the try row is still offloaded or busy (it is still armed), it waits for its +first demote, it is failed (put that right by hand first), no candidate passes, or the allowlist +would grow. Without REARM_APPLY=1 it stops before the first search and prints what it would do. Usenet use, at most: REARM_MAX_SEARCH indexer searches (default 6), REARM_MAX_GRAB NZB grabs (default 3), about 300 article STAT checks per grab. No article is downloaded. The candidate's @@ -388,18 +388,23 @@ def why_not(r): finally: pool.close() - if new is None and not retired: - say("FAIL", "no candidate passed; nothing written") + if new is None: + say("FAIL", "no candidate passed; nothing written" + (" (the consumed try row stays named as it is)" if retired else "")) + return done(0, searches, grabs, 1) + lines = lines + [f"# e2e re-arm {stamp}: try row (STAT-checked, no zeroed hole in the local file)", new["lib_path"]] + after = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} + if len(after) > len(have0) + (0 if retired else 1): + say("FAIL", f"the allowlist would grow from {len(have0)} to {len(after)} path(s) (the old try row's path is not in " + "it); nothing written") return done(0, searches, grabs, 1) if retired: - pick.pop("try", None) - pick.setdefault("dead", []).append({"id": retired.get("id"), "role": "try", "why": "consumed by an e2e scenario", "ts": now}) + if not isinstance(pick.get("dead"), list): + pick["dead"] = [] + pick["dead"].append({"id": retired.get("id"), "role": "try", "why": "consumed by an e2e scenario", "ts": now}) detail(f"retired try row: id={retired.get('id')}") - if new is not None: - pick["try"] = new - pick["ts_rearm"] = now - lines = lines + [f"# e2e re-arm {stamp}: try row (STAT-checked, no zeroed hole in the local file)", new["lib_path"]] - detail(f"new try row: id={new['id']} {new['title']} ({new['year']}) {new['size'] / GB:.1f} GB") + pick["try"] = new + pick["ts_rearm"] = now + detail(f"new try row: id={new['id']} {new['title']} ({new['year']}) {new['size'] / GB:.1f} GB") shutil.copyfile(allow, f"{allow}.bak-{stamp}") with open(allow + ".tmp-rearm", "w") as f: f.write("\n".join(lines) + "\n") @@ -409,14 +414,9 @@ def why_not(r): with open(PICK + ".tmp-rearm", "w") as f: json.dump(pick, f, indent=1) os.replace(PICK + ".tmp-rearm", PICK) - after = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} - ok = len(after) <= len(have0) + (0 if retired else 1) - say("PASS" if ok else "FAIL", f"allowlist: {len(have0)} path(s) before, {len(after)} now (one test row out, one in)") - if new is None: - say("FAIL", "the old try row is retired but no candidate passed: there is no try row now") - return done(0, searches, grabs, 1) + say("PASS", f"allowlist: {len(have0)} path(s) before, {len(after)} now ({'one test row out, one in' if retired else 'one test row in'})") say("PASS", f"new try row picked ({new['size'] / GB:.1f} GB); the runner offloads it in its nightly window") - return done(1, searches, grabs, 0 if ok else 1) + return done(1, searches, grabs) if __name__ == "__main__": From ce3129c3a837051ad080917774e73cd8bb85fdeb Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:04:42 -0800 Subject: [PATCH 3/9] e2e: the default pause in Z outlasts the 900 s limits; README says which scenario starts cold --- tests/e2e/README.md | 6 ++++-- tests/e2e/plex_e2e.py | 9 +++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 75de519..8e9a58c 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -37,7 +37,7 @@ Scenarios run only on the real server, through runner jobs. They are never run i | W | while the watched file is fetched, no demote starts (read-only; says whether it ran inside the window with a demote pending) | player | whole | | M | two streams at once: the player plays while a second client reads 64 MiB elsewhere in the same file; with `E2E_SECOND_ROLE` a second file too | player | whole | | K | switch the audio track, turn on an embedded and an external subtitle during a play; the selection found is put back | player, a file with the tracks | whole | -| Z | pause for `E2E_PAUSE_S` (default 780 s, past the slot, watched and read-wait timeouts), resume at the same place | player | whole | +| Z | pause for `E2E_PAUSE_S` (default 960 s: past the watched window of 600 s and the 900 s after which a want or a waiting read is given up), resume at the same place | player | whole | | T | server transcode pulled as an HLS client: a forced lower bitrate (video re-encoded), then another container with the streams copied | nothing (no player) | whole | | L | `llm_shadow_check.py`: the LLM layer is in shadow mode and every decision written during the run is a shadow row | arr-webhook | unchanged | @@ -52,7 +52,9 @@ stays whole for 60 days. So one offloaded try row serves, in this order: 2. one of: C, or one of D to H, or the play group S W M K Z (they share the one fetch; each prints the row state it started on, and a run on a whole row says that it proves the Plex side only), or T from cold. -T may also run right after the play group without a new row: it then proves a transcode during or after the fetch. +Only the first scenario after a re-arm starts on the offloaded row. S goes first because it needs the middle not yet +fetched; the others then run during or after the fetch. T may also run right after the play group without a new row: +it then proves a transcode during or after the fetch. For Z or T from cold, re-arm again (one night and one fetch each). After step 2, run `rearm_try_row.py` and wait for the runner's nightly window to offload the new row. What each costs on Usenet: P, R, audit, L, up, A on a whole row, B, I: nothing. C, the play group, T from cold, D to H: diff --git a/tests/e2e/plex_e2e.py b/tests/e2e/plex_e2e.py index cb9dcfc..ecf8c4e 100644 --- a/tests/e2e/plex_e2e.py +++ b/tests/e2e/plex_e2e.py @@ -18,7 +18,7 @@ Environment: PLEX_URL, PLEX_TOKEN (container), TIERING_DB, TIERFS_EVENTS, TIERING_ALERTS (container); E2E_SERVER_URL (the server address the PLAYER can reach), E2E_PLAYER_ID, E2E_SUBSTITUTE=1 (the substitute PR is deployed; D to H skip without it), E2E_WAIT_S (longest wait for bytes that are not -local, default 600), E2E_PAUSE_S (pause length in Z, default 780), E2E_SECOND_MB (bytes the second +local, default 600), E2E_PAUSE_S (pause length in Z, default 960), E2E_SECOND_MB (bytes the second stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file), E2E_WINDOW_S (how long W samples the runner, default 120). """ @@ -914,13 +914,14 @@ def sc_s(): # ---- Z: long pause ---------------------------------------------------------------------------- def sc_z(): - """Z: pause a play for longer than the timeouts on the way (the unused-stream slot, the watched - window, the read wait), then resume. The play must go on from where it stopped.""" + """Z: pause a play for longer than the timeouts on the way (the stream slot wait, the watched + window of 600 s, the 900 s after which a want or a waiting read is given up), then resume. The + play must go on from where it stopped.""" s = setup("Z") if not s: return plex, id, row = s - rk, pause_s = row.get("rating_key"), _int(os.environ.get("E2E_PAUSE_S"), 780) + rk, pause_s = row.get("rating_key"), _int(os.environ.get("E2E_PAUSE_S"), 960) t0, ev0 = time.time(), events_size() if not _begin("Z", plex, row): return From fc6f714ecc5ab74e2b3db808806d08678aa768d0 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:06:43 -0800 Subject: [PATCH 4/9] e2e: a crash in the re-arm or the shadow check prints the error's type only --- tests/e2e/llm_shadow_check.py | 6 +++++- tests/e2e/rearm_try_row.py | 8 +++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/e2e/llm_shadow_check.py b/tests/e2e/llm_shadow_check.py index 7bff789..51a9302 100644 --- a/tests/e2e/llm_shadow_check.py +++ b/tests/e2e/llm_shadow_check.py @@ -84,4 +84,8 @@ def main(argv): if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) + try: + sys.exit(main(sys.argv[1:])) + except Exception as ex: # a crash shows as a FAIL with the error's type only + say("FAIL", f"harness error: {type(ex).__name__}") + sys.exit(1) diff --git a/tests/e2e/rearm_try_row.py b/tests/e2e/rearm_try_row.py index 2532778..5996f12 100644 --- a/tests/e2e/rearm_try_row.py +++ b/tests/e2e/rearm_try_row.py @@ -420,4 +420,10 @@ def why_not(r): if __name__ == "__main__": - sys.exit(main()) + try: + sys.exit(main()) + except Exception as ex: # a crash must not put a title, a path or a URL on the result lines + say("FAIL", f"harness error: {type(ex).__name__} (the message is on the DETAIL line); check pick.json and the " + "allowlist against their newest .bak copies before a new run") + detail(f"error: {str(ex)[:300]}") + sys.exit(done(0, 0, 0, 1)) From f7a47f4d38520a6569e1f44f9ab8f1eceef870e4 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:12:40 -0800 Subject: [PATCH 5/9] e2e: the re-arm retires a try row that was played before its first demote A played row stays whole for the idle window, so a try row that a scenario played while it still waited for its first demote would never be offloaded, and the re-arm kept it forever. It now reads Plex first and retires such a row like a consumed one. REARM_VERDICT_ONLY=1 stops after the verdict line, so a job can ask what would happen to the old try row without a search. --- tests/e2e/README.md | 7 +++- tests/e2e/rearm_try_row.py | 73 +++++++++++++++++++++++++------------- 2 files changed, 54 insertions(+), 26 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 8e9a58c..49de583 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -11,7 +11,8 @@ server's own token (inside the tiering container); it never touches plex.tv. It prints `PASS|FAIL|SKIP|INFO text` (counts and states) and `DETAIL` lines (ids; send these to syslog, never to a public log). - `test_plex_e2e.py` is a unit test against a fake Plex (`python3 -m unittest test_plex_e2e`, sandbox or CI only). - `rearm_try_row.py` (in the tiering container) retires a consumed try row and picks a new one. Its header says what it - writes and how to put it back. Without `REARM_APPLY=1` it stops before the first search. + writes and how to put it back. Without `REARM_APPLY=1` it stops before the first search; with `REARM_VERDICT_ONLY=1` it + only says what it would do with the old try row (`old try row verdict: retire|keep|abort|none`). - `llm_shadow_check.py` (in the arr-webhook container) is scenario L, read-only. Scenarios run only on the real server, through runner jobs. They are never run in CI and never against made-up data. @@ -57,6 +58,10 @@ fetched; the others then run during or after the fetch. T may also run right aft it then proves a transcode during or after the fetch. For Z or T from cold, re-arm again (one night and one fetch each). After step 2, run `rearm_try_row.py` and wait for the runner's nightly window to offload the new row. +Never play a try row between its re-arm and its first demote: the runner keeps a played row whole for the idle window, so +that row would never be offloaded. The re-arm retires such a row like a consumed one. The scenarios that play (A, I, C, +S, W, M, K, Z, T) belong on an offloaded row, or on a used one that is about to be retired. + What each costs on Usenet: P, R, audit, L, up, A on a whole row, B, I: nothing. C, the play group, T from cold, D to H: one fetch of the try file each (count it against the nightly re-download budget). F adds one live indexer search. A re-arm: up to 6 searches and 3 NZB grabs, no article download. diff --git a/tests/e2e/rearm_try_row.py b/tests/e2e/rearm_try_row.py index 5996f12..41d6ddc 100644 --- a/tests/e2e/rearm_try_row.py +++ b/tests/e2e/rearm_try_row.py @@ -18,8 +18,11 @@ private copy of the runner's budget state). When it writes nothing: the try row is still offloaded or busy (it is still armed), it waits for its -first demote, it is failed (put that right by hand first), no candidate passes, or the allowlist -would grow. Without REARM_APPLY=1 it stops before the first search and prints what it would do. +first demote and Plex shows no play of it, it is failed (put that right by hand first), no candidate +passes, or the allowlist would grow. A whole try row that was played before its first demote is +retired like a consumed one: the runner keeps a played row whole for the idle window. Without +REARM_APPLY=1 it stops before the first search and prints what it would do; with +REARM_VERDICT_ONLY=1 it stops after the line `old try row verdict: retire|keep|abort|none`. Usenet use, at most: REARM_MAX_SEARCH indexer searches (default 6), REARM_MAX_GRAB NZB grabs (default 3), about 300 article STAT checks per grab. No article is downloaded. The candidate's @@ -116,7 +119,8 @@ def sample_ids(nzb): def old_try_verdict(db, old): - """retire | keep: | abort: for the try row pick.json names now.""" + """retire | keep: | abort: | wait: for the try row pick.json names now. `wait` is a whole row + that was never offloaded: the caller keeps it, unless Plex shows a play of it (then it is retired).""" r = db.execute("SELECT state FROM files WHERE id=?", (old.get("id"),)).fetchone() if r is None: return "retire" # its row is gone (replaced by a substitute or an upgrade): nothing left to arm @@ -136,7 +140,7 @@ def old_try_verdict(db, old): reasons = set() if reasons & {"hash_mismatch", "local_damaged"}: return "retire" # it can never qualify - return "keep:the try row is whole and waits for its first demote in the nightly window" + return "wait:the try row is whole and waits for its first demote in the nightly window" def main(): @@ -170,19 +174,53 @@ def main(): db.row_factory = sqlite3.Row old = pick.get("try") if isinstance(pick.get("try"), dict) else None - retired = None + retired = waiting = None if old: verdict = old_try_verdict(db, old) if verdict.startswith("keep:"): - say("SKIP", verdict[5:] + "; nothing written") + say("SKIP", f"old try row verdict: keep ({verdict[5:]}); nothing written") return done(0, 0, 0) if verdict.startswith("abort:"): - say("FAIL", verdict[6:] + "; nothing written") + say("FAIL", f"old try row verdict: abort ({verdict[6:]}); nothing written") return done(0, 0, 0, 1) - retired = old - say("INFO", "the old try row was consumed; it will be retired") + if verdict.startswith("wait:"): + waiting = verdict[5:] + else: + retired = old + say("INFO", "old try row verdict: retire (it was consumed, or it can never qualify)") else: - say("INFO", "pick.json names no try row; one will be picked") + say("INFO", "old try row verdict: none (pick.json names no try row; one will be picked)") + + try: + own = {str(k): float(ts or 0) for (k, ts) in db.execute("SELECT rating_key, last_ts FROM last_plays")} + except sqlite3.Error: + own = {} + try: + items = pw.library_items() + hist = pw.play_history(0) + busy = {str(x.get("ratingKey")) for x in list(pw.in_progress()) + list(pw.on_deck()) + list(pw.sessions())} + except Exception as ex: + say("FAIL", f"Plex read failed ({type(ex).__name__}); nothing written") + return done(0, 0, 0, 1) + ever = {str(h.get("ratingKey")) for h in hist} | set(own) + recent = {str(h.get("ratingKey")) for h in hist if float(h.get("viewedAt") or 0) > now - idle_s} + recent |= {k for k, ts in own.items() if ts > now - idle_s} + by_rk = {str(it["ratingKey"]): it for it in items if it.get("ratingKey") is not None} + if waiting is not None: + # A play (history, in progress, on deck, a session) keeps a row whole for the idle window, exactly as the + # runner's hot set sees it: a try row played before its first demote will not be demoted, so it is used up. + r = db.execute("SELECT rating_key FROM files WHERE id=?", (old.get("id"),)).fetchone() + rk = str(r["rating_key"]) if r is not None and r["rating_key"] is not None else "" + if rk and (rk in busy or rk in recent): + retired = old + say("INFO", "old try row verdict: retire (it was played before its first demote; a played row stays whole " + "for the idle window)") + else: + say("SKIP", f"old try row verdict: keep ({waiting}); nothing written") + return done(0, 0, 0) + if e.get("REARM_VERDICT_ONLY") == "1": + say("SKIP", "REARM_VERDICT_ONLY is 1: stopped after the verdict; nothing written") + return done(0, 0, 0) prov = S.ProviderCfg.from_env("primary") radarrs, _ = register.clients_from_env() @@ -216,21 +254,6 @@ def main(): r = db.execute("SELECT size, state FROM files WHERE id=?", (lost.get("id"),)).fetchone() if r is not None and r["state"] in ("whole", "offloading"): held += r["size"] or 0 - try: - own = {str(k): float(ts or 0) for (k, ts) in db.execute("SELECT rating_key, last_ts FROM last_plays")} - except sqlite3.Error: - own = {} - try: - items = pw.library_items() - hist = pw.play_history(0) - busy = {str(x.get("ratingKey")) for x in list(pw.in_progress()) + list(pw.on_deck()) + list(pw.sessions())} - except Exception as ex: - say("FAIL", f"Plex read failed ({type(ex).__name__}); nothing written") - return done(0, 0, 0, 1) - ever = {str(h.get("ratingKey")) for h in hist} | set(own) - recent = {str(h.get("ratingKey")) for h in hist if float(h.get("viewedAt") or 0) > now - idle_s} - recent |= {k for k, ts in own.items() if ts > now - idle_s} - by_rk = {str(it["ratingKey"]): it for it in items if it.get("ratingKey") is not None} by_path, grabs_by_movie = {}, {} try: From cf978ffcc70d84564d79cedf5f0547feee4b42e4 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:15:59 -0800 Subject: [PATCH 6/9] e2e: W can wait for another scenario's play instead of starting its own With E2E_ATTACH_S set, W waits that long for a session of the try row before it begins a play itself, so a job can start it beside S and have it sample the runner during S's fetch. --- tests/e2e/README.md | 2 +- tests/e2e/plex_e2e.py | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 49de583..e71fc60 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -35,7 +35,7 @@ Scenarios run only on the real server, through runner jobs. They are never run i | R | the arr refreshes and rescans the item: it still lists the same file at full size, the link is still ours, nothing is fetched | offloaded try row, Radarr | offloaded | | audit | every row that is not whole has its link, stub and manifest; no manifest lacks a row | nothing | unchanged | | S | seek far past the head, back to the middle before the first fetch point, back into the head, forward again: each time the play goes on | offloaded or promoting try row, player | whole | -| W | while the watched file is fetched, no demote starts (read-only; says whether it ran inside the window with a demote pending) | player | whole | +| W | while the watched file is fetched, no demote starts (read-only; says whether it ran inside the window with a demote pending). Run it beside S with `E2E_ATTACH_S` set: it then watches S's play and starts none of its own | player | whole | | M | two streams at once: the player plays while a second client reads 64 MiB elsewhere in the same file; with `E2E_SECOND_ROLE` a second file too | player | whole | | K | switch the audio track, turn on an embedded and an external subtitle during a play; the selection found is put back | player, a file with the tracks | whole | | Z | pause for `E2E_PAUSE_S` (default 960 s: past the watched window of 600 s and the 900 s after which a want or a waiting read is given up), resume at the same place | player | whole | diff --git a/tests/e2e/plex_e2e.py b/tests/e2e/plex_e2e.py index ecf8c4e..de21534 100644 --- a/tests/e2e/plex_e2e.py +++ b/tests/e2e/plex_e2e.py @@ -20,7 +20,8 @@ substitute PR is deployed; D to H skip without it), E2E_WAIT_S (longest wait for bytes that are not local, default 600), E2E_PAUSE_S (pause length in Z, default 960), E2E_SECOND_MB (bytes the second stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file), -E2E_WINDOW_S (how long W samples the runner, default 120). +E2E_WINDOW_S (how long W samples the runner, default 120), E2E_ATTACH_S (how long W waits for another +scenario's play of the try row before it starts its own, default 0: set it when W runs beside S). """ import hashlib import http.client @@ -1152,6 +1153,10 @@ def sc_w(): return t0, ev0 = time.time(), events_size() cur = my_session(plex) + attach_end = time.time() + _int(os.environ.get("E2E_ATTACH_S"), 0) + while not (cur and cur["rk"] == str(rk)) and time.time() < attach_end: + time.sleep(5) # another scenario (S, started beside this one) begins the play; W only watches the runner + cur = my_session(plex) if not (cur and cur["rk"] == str(rk)) and not _begin("W", plex, row): return seen = {"promoting": 0, "blocked": 0, "window": 0, "planned": 0, "samples": 0} From 9fee6ba899a9612f57304cf6014f3e67a1edcaa0 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:51:54 -0800 Subject: [PATCH 7/9] tiering: a substitute is the same cut, gets its SHA-256, and --switch-live by hand uses it When a release behind an offloaded file cannot be fetched, the next copy must take its place without the viewer noticing, and the row must be a normal row afterwards. - The pick: a candidate whose name says another edition or other language words is dropped, the nearest resolution is tried first (the same, higher, lower), and the pick (the planned alternative too) is imported and its first bytes are probed beside our own head: the run times must agree and the first sound track must be in the same language. What cannot be proved is dropped. substitute_pick and substitute_failed say why each candidate was dropped. - The integrity record: the hash build that reads the whole middle once also makes the whole file's SHA-256, so a substituted row has the same records as any row and promote keeps its one strict path. Before this the row had no sha256 and promote refused it for good. The runner waits with a promote while the manifest is pending, and never hashes a row that is retired or failed. - By hand: --switch-live goes through Runner._switch, the automatic switch's own path: the substitute instead of a full local restore, the same auto_switch event and the same owner alerts. Exit 1 when nobody could be switched. - A search that could not be done or checked no longer costs the six-hour cooldown. - The hash build opens its own database connection on its thread. tests/test_substitute_real_path.py runs the real modules end to end over a local remote: mark failed, switch by hand, hash build, promote, and the refusals. --- tiering/OFFLOAD_DESIGN.md | 19 +- tiering/README.md | 8 +- tiering/offload/newznab.py | 56 +++++ tiering/offload/probe.py | 60 +++++ tiering/offload/qualify.py | 106 +++++++- tiering/offload/runner.py | 115 ++++++--- tiering/offload/substitute.py | 228 +++++++++++++++-- tiering/offload/switch_live.py | 19 +- .../tests/test_substitute_real_path.py | 237 ++++++++++++++++++ tiering/offload/tests/test_switch_live.py | 5 +- tiering/offload/wiring.py | 14 +- 11 files changed, 776 insertions(+), 91 deletions(-) create mode 100644 tiering/offload/probe.py create mode 100644 tiering/offload/tests/test_substitute_real_path.py diff --git a/tiering/OFFLOAD_DESIGN.md b/tiering/OFFLOAD_DESIGN.md index 04cff75..78f03fa 100644 --- a/tiering/OFFLOAD_DESIGN.md +++ b/tiering/OFFLOAD_DESIGN.md @@ -434,16 +434,16 @@ Swaps are automatic. One long-running process applies the hot set. ### Live release switch (`switch_live.py`, `--switch-live [--check]`) -Carries a player that is watching the offloaded file onto the restore-path release, at the same scene. Order, chosen so that nothing is ever fetched at switch time and a failure leaves the player where it was: +Carries a player that is watching the offloaded file onto another release of it, at the same scene. By hand and automatic are one code path (`Runner._switch`): `--switch-live ` is the automatic switch started by a person. Order, chosen so that nothing is ever fetched at switch time and a failure leaves the player where it was: 1. `/status/sessions`: sessions whose part file is the row's library file; per session the player's `machineIdentifier`, `viewOffset` and the item's `ratingKey`. 2. Remote-control probe per player: listed by the server's `/clients` with the `playback` capability, else a proxied `/player/timeline/poll` that the player answers. A player that fails both stays on the old file. If no player passes, nothing is restored. -3. The restore callable (skipped when the row is already restored). By hand (`--switch-live`) and when no substitute is configured it is `ops.restore_from_path`; the automatic trigger passes the substitute (below), so no full local copy is made. `restore_from_path` returns only after the new file is local, size-checked, hole-free and hashed twice, so the new release is pre-buffered by construction. The old stub stays, so the player's open file keeps working. +3. The restore callable (skipped when the row is already restored). Both the by-hand command and the automatic trigger pass the substitute (below), so no full local copy is made. Only when no substitute is configured it is `ops.restore_from_path`, which returns only after the new file is local, size-checked, hole-free and hashed twice. The old stub stays, so the player's open file keeps working. 4. Poll `/library/metadata/` (2 minutes) until a part with the new file's size shows (the partial scan from notify.py ran). Timeout: no switch. 5. Per player: re-read `viewOffset`, `watch_hold.map_offset` (old file read through tierfs as the `watch-align` background reader, new file from disk) gives the position in the new release; no confident match (or any error) means no switch, never a fall back to the old offset. 6. `playMedia` through the server's player proxy, following python-plexapi (`PlexClient.playMedia`, `sendCommand` with `proxyThroughServer`): `GET /player/playback/playMedia` with header `X-Plex-Target-Client-Identifier` and query `key`, `offset` (ms), `machineIdentifier`, `protocol`/`address`/`port` (the server as the player should reach it), `type=video`, `providerIdentifier`, `containerKey` (a play queue from `POST /playQueues`), `token` (a short-lived delegation token from `/security/token`) and an increasing `commandID`. Afterwards the session is watched for up to 25 s to see the new part; if it does not show, the run warns. -A paused session is switched at once, like a playing one. `TIERING_APPLY` unset or 0: every read-only step runs and the log says what would be sent; nothing is restored or sent. The Plex token is only in the `X-Plex-Token` header; no URL or token is logged. +A paused session is switched at once, like a playing one. `TIERING_APPLY` unset or 0: every read-only step runs and the log says what would be sent; nothing is restored or sent. By hand the row may be `offloaded` or `failed` (a row marked failed by hand is the usual case: nothing fetches it meanwhile). Exit 0: switched, a dry run, or nobody plays the row. Exit 1: nobody could be switched; the `auto_switch` event and the owner's alert say why. Exit 2: settings or usage. The Plex token is only in the `X-Plex-Token` header; no URL or token is logged. **Automatic trigger (`TIERING_AUTO_SWITCH`, default on).** `switch_live.auto_switch` is run by the runner, without anyone typing `--switch-live`, when a chunk cannot be repaired: - a promote ends `failed` with a chunk mismatch on every copy (the promote runs ahead of the viewer, so this is before the viewer reaches the bad spot), or tierfs reports a `bad_chunk` for a row with no twin (with a twin the promote tries it first and decides); @@ -452,17 +452,18 @@ A paused session is switched at once, like a playing one. `TIERING_APPLY` unset - one switch per row at a time (in-process guard, plus the id lock the restore takes). A row with a running promote (other than the one that just ended) or a running demote is skipped, the same rule that keeps `--mark-failed` rows out of promotes; - every attempt that found a session writes an `auto_switch` event with `outcome` (`switched`, `no_player_control`, `no_restore_path`, `mapping_failed`, `dry_run`) and a `detail`, so a read-only job can count them. `no_restore_path` also covers a restore that failed; - any outcome but `switched` leaves today's behaviour: the row fails and the automatic re-download takes it, plus the one-time alert `auto_switch_` with the reason. `switched` raises the alert `auto_switch`, and the row is not marked lost; -- `TIERING_APPLY` unset or 0: the read-only steps run, the log says what would happen, outcome `dry_run`, nothing is restored or sent. `TIERING_AUTO_SWITCH=0` turns the trigger off. +- `TIERING_APPLY` unset or 0: the read-only steps run, the log says what would happen, outcome `dry_run`, nothing is restored or sent. `TIERING_AUTO_SWITCH=0` turns the trigger off; +- `--switch-live ` by hand runs the same steps and writes the same event and alerts (the `auto_switch` alert carries `took_s`, the seconds the switch took). `TIERING_AUTO_SWITCH` and the once-per-process dry-run note do not apply to it. -**Live substitute (`substitute.py`; no backups saved locally).** The automatic trigger does not copy the replacement to local disk. The substitute is the `restore` callable `auto_switch` passes to `switch_live` (`substitute.make_restore`; `auto_switch(..., search=True)` so a row with no planned alternative is still tried). `substitute.substitute_release(db, row, deps)` is the one function that decides and builds the switch target; the e2e harness can call it with its own `Deps`. +**Live substitute (`substitute.py`; no backups saved locally).** Neither the automatic trigger nor the by-hand switch copies the replacement to local disk. The substitute is the `restore` callable `auto_switch` passes to `switch_live` (`substitute.make_restore`; `auto_switch(..., search=True)` so a row with no planned alternative is still tried). `substitute.substitute_release(db, row, deps)` is the one function that decides and builds the switch target; the e2e harness can call it with its own `Deps`. -1. **Choose** (`choose`). The planned alternative (`nzb_path2`) when it is readable, shares no message-id with `nzb_path`, and every segment is on every provider (qualify's STAT). If it is missing, dead (an NZB that cannot be read, shares ids, or has a segment missing on a provider) the indexers are searched live with qualify's own rules, `qualify.score_restore`: at or above the quality floor (a 4K row tries every 4K alternative before 1080p), a different upload (no message-id shared with `nzb_path` or the dead planned NZB), every segment STATed on every provider. If the planned check is unchecked (a provider could not be asked), the search fails or errors, or no verified candidate exists, nothing is changed: the player stays on the old file and the existing alert `auto_switch_no_restore_path` carries the reason. It never guesses. Indexer etiquette: the searches and grabs go through the shared `NewznabClient` budgets (`NEWZNAB_SEARCH_BUDGET`, default 30 per indexer per day; `NEWZNAB_GRAB_BUDGET`); a 300, 404 or 410 on an item is a strike, as in qualify; only configured indexers are asked, never new ones; and a row whose live search found nothing is not searched again for six hours (kv `substitute_search:`). +1. **Choose** (`choose`). The planned alternative (`nzb_path2`) when it is readable, shares no message-id with `nzb_path`, and every segment is on every provider (qualify's STAT). If it is missing, dead (an NZB that cannot be read, shares ids, or has a segment missing on a provider) the indexers are searched live with qualify's own rules, `qualify.score_restore`: at or above the quality floor (a 4K row tries every 4K alternative before 1080p), a different upload (no message-id shared with `nzb_path` or the dead planned NZB), every segment STATed on every provider. Because the viewer is not asked, the pick must also be the same cut with the same sound (`qualify.Fit`, `probe.py`): a candidate whose name says another edition or other language words than ours is dropped; the candidates nearest to our resolution are tried first (the same, then higher, then lower); and the pick, the planned alternative included, is imported and its first 8 MiB are read by ffmpeg beside the head of our own stub. The run times must agree within `SUBSTITUTE_RUNTIME_TOL_S` (20 s) or `SUBSTITUTE_RUNTIME_TOL_FRAC` (0.5 %), whichever is more, and the first sound track must be in the same language. A fact that cannot be read counts as a difference. After three candidates dropped by the probe no more are tried (each costs an import). The events `substitute_pick` (title, source, run times, sound, picture heights) and `substitute_failed` count the dropped candidates by reason (`why`) and name up to 20 of them (`rejected`). If the planned check is unchecked (a provider could not be asked), the search fails or errors, or no verified candidate exists, nothing is changed: the player stays on the old file and the existing alert `auto_switch_no_restore_path` carries the reason. It never guesses. Indexer etiquette: the searches and grabs go through the shared `NewznabClient` budgets (`NEWZNAB_SEARCH_BUDGET`, default 30 per indexer per day; `NEWZNAB_GRAB_BUDGET`); a 300, 404 or 410 on an item is a strike, as in qualify; only configured indexers are asked, never new ones; and a row whose live search found nothing is not searched again for six hours (kv `substitute_search:`); a search that could not be done or checked is no miss and may be tried again after ten minutes. 2. **Build** (`build`), under the old id's lock. The NZB is imported through AltMount; the head and tail are read from the remote (a zero run of 128 KiB or more in either is a missing segment (real media holds shorter zero runs, such as digital silence in LPCM audio; AltMount zero-fills a whole article of about 384-768 KB, so one side of a chunk-cut article is at least 192 KB): stop, nothing changed); a sparse stub is written (head, tail, a hole between) and a manifest with `"pending": true` and no chunk list. The new release gets a new id, because the old entry must stay served while the player is still on it. Once tierfs serves the new entry the library name is pointed at it (one atomic symlink replace; with a different extension the new name is linked first, then the old one dropped), and in one transaction the library path moves to the new row. The new row carries the new release as `nzb_path` (the planned path, or the newly archived NZB), state `offloaded`. The old row becomes `failed` with the restore note (so the orphan cleanup removes its stub after the grace days and `switch_live` finds it already restored), its `lib_path` becomes a `.dead--` placeholder, and it gets events `release_dead` (its `nzb_path`, `nzb_path2`, the replacement and where it came from) and `restore_done` (the new name and size, which `switch_live` reads). Qualify finds the next night's alternative for the new row as for any row. 3. **Switch.** `switch_live` waits for Plex to show the new file, maps the offset with `watch_hold.map_offset` and sends `playMedia`, as above. This happens as soon as the offset can be placed (about a minute), long before any hash exists. -4. **Hash build** (`hash_build`, a background thread started by `build`). One read of the whole middle at line rate, like promote's read-ahead, recording a BLAKE3 per 4 MiB chunk. Until it ends the manifest is pending, and tierfs serves the middle of a pending entry from the remote for every reader (a player does not wait for a promote): each chunk is checked for a zero run of 128 KiB or more, which AltMount leaves where a segment is missing, and a chunk with one is EIO, never bad bytes and never a `bad_chunk` event. When every chunk is hashed the chunk list is written and the manifest is rewritten without `pending` (with `chunks_b3`), and from then on the entry is verified like any other. A read fault or a zero run in the hash build leaves the manifest pending and writes `substitute_hash_failed`. +4. **Hash build** (`hash_build`; a background thread started by `build` in the runner, and left to the runner's next pass by the short-lived by-hand command). One read of the whole middle at line rate, like promote's read-ahead, recording a BLAKE3 per 4 MiB chunk and feeding the whole file's SHA-256 (the stub's head, each chunk, the stub's tail; head and tail must still be what the build wrote). Until it ends the manifest is pending, and tierfs serves the middle of a pending entry from the remote for every reader (a player does not wait for a promote): each chunk is checked for a zero run of 128 KiB or more, which AltMount leaves where a segment is missing, and a chunk with one is EIO, never bad bytes and never a `bad_chunk` event. When every chunk is hashed the row gets its `sha256` (first), then the chunk list is written and the manifest is rewritten without `pending` (with `chunks_b3`), and the row gets the event `substitute_hashed`. From then on it is a row like any other: promote checks every chunk against the chunk list and the whole file against the SHA-256, with no weaker path for a substituted row. A substitute has no earlier copy to be compared with, so the records mean "the bytes this release served when it was taken, with no missing segment"; computing them while the bytes pass through keeps promote's guarantee (it writes nothing it cannot check) without a second trust rule. A read fault or a zero run in the hash build leaves the manifest pending, leaves the row without a `sha256`, and writes `substitute_hash_failed`, which the owner is alerted about once. A row that is no longer `offloaded` (retired by a later substitute, or failed by hand) is not hashed: its file would be fetched for nothing. -tierfs, `pending` manifests: `pending` replaces the chunk list requirement (`chunks_b3` must be empty); the scan does not look for `.chunks`. A promote needs the chunk list, so one started before the hash build ends fails like any promote without one and is retried later. A process restart during the hash build leaves the manifest pending (still served, still zero-run checked); the runner starts the build again for every pending manifest at its first pass (once per id per process, only with `TIERING_APPLY` and not under `TIERING_QUALIFY_FACTORY`). +tierfs, `pending` manifests: `pending` replaces the chunk list requirement (`chunks_b3` must be empty); the scan does not look for `.chunks`. A promote needs the chunk list and the SHA-256, so the runner does not start one for a row whose manifest is pending: it waits (logged once per id, no failure counted) and starts once the build has written its records. A process restart during the hash build leaves the manifest pending (still served, still zero-run checked); at every pass the runner starts the build for each pending manifest whose row is `offloaded` (once per id per process, only with `TIERING_APPLY`; one build per id across processes, by an id lock). With `TIERING_APPLY` unset the automatic switch logs its dry-run decision once per id per process, not on every repeated `bad_chunk`. -Honest limits: the player reopens the file (a few seconds of rebuffer, and its audio and subtitle choice may reset); which apps honour a proxied `playMedia` is unverified, as is the exact offset unit and `containerKey` behaviour per app; the offset mapping can fail on quiet or very different cuts, and then the player is left alone; the address the player is told must be reachable from the player (`TIERING_PLEX_PLAYER_URL`). Only the fakes in `tests/test_switch_live.py` have exercised the Plex side. +Honest limits: the player reopens the file (a few seconds of rebuffer, and its audio and subtitle choice may reset); which apps honour a proxied `playMedia` is unverified, as is the exact offset unit and `containerKey` behaviour per app; the offset mapping can fail on quiet or very different cuts, and then the player is left alone; the address the player is told must be reachable from the player (`TIERING_PLEX_PLAYER_URL`). A watched substitute is read in full twice (the hash build, then the promote). A hash build that failed is tried again only after a runner restart. A container that keeps its index at the end (some MP4s) cannot be probed and is dropped. A candidate dropped by the probe stays imported in AltMount. The automatic trigger fires only on a chunk mismatch or a `bad_chunk`; a release whose remote cannot be read at all ends as a read error and waits for the by-hand switch. The Plex side is exercised by the fakes in `tests/test_switch_live.py`, by `tests/test_substitute_real_path.py` (the real modules end to end over a local remote), and on the real server by scenarios D to H and N of `tests/e2e`. diff --git a/tiering/README.md b/tiering/README.md index 4335a63..1da02ae 100644 --- a/tiering/README.md +++ b/tiering/README.md @@ -162,10 +162,10 @@ Path settings, each a comma list: `TIERING_AUTO_RESTORE` (default 0): `1` makes the runner restore a file from its restore path (`nzb_path2`, a different release) after a `bad_chunk` or a `promote_short_remote`, once per id and process, in its own thread; the outcome is a `restore_done` or `restore_failed` alert. Off, the row just stays `failed` as before. A dry run only logs. The same restore, for one row on demand: `python -m offload.runner --restore [--release-name]` (a dry run unless `TIERING_APPLY=1`; it does not take the runner lock, so it can run beside the runner). By default the restored file keeps L's base name with the restore file's extension; `--release-name` uses the restore release's own file name. The restore imports `nzb_path2` through AltMount, copies the media file next to L, verifies it (size, no zero-filled hole, SHA-256 against a second full read), swaps it in and drops the symlink. The row ends `failed` with `restore_note` "restored from the restore path"; the old stub and manifest stay until the orphan cleanup above removes them after `TIERING_ORPHAN_GRACE_DAYS` (that cleanup also frees the row's `lib_path`, so register can add the new file). Afterwards Radarr (`RescanMovie`) or Sonarr (`RescanSeries`) is asked to rescan, and Plex gets a partial scan of the folder when `PLEX_URL` and `PLEX_TOKEN` are set (otherwise that is skipped and noted in the `restore_notify` event). Keys and tokens are only sent in headers. See OFFLOAD_DESIGN.md, "Restore path". -`--switch-live` (move a player that is watching an offloaded file onto the restore-path release): `python -m offload.runner --switch-live --check` lists the Plex sessions playing that row and whether each player accepts remote control (read-only, always safe). `python -m offload.runner --switch-live ` is a dry run unless `TIERING_APPLY=1`: a dry run does every read step and logs what it would send. A live run (1) finds the sessions on the row, (2) leaves any player that does not accept remote control on the old file (and restores nothing if none does), (3) restores the row from its restore path unless it already is (the new file is then whole and verified on disk, so it is pre-buffered), (4) waits up to two minutes for Plex's partial scan to show a part of the new file's size, (5) reads each player's position again, maps it onto the new release by the sound around it (`watch_hold.map_offset`), and sends `playMedia` at that position through the Plex server's player proxy. If the mapping is not confident, the scan does not show up in time, or the command fails, that player is not switched and keeps reading the old file; the run says so and exits 1. Needs `PLEX_URL`, `PLEX_TOKEN`, `TIERFS_MOUNT`, and ffmpeg and numpy in the image (the tiering image has them). `TIERING_PLEX_PLAYER_URL` (optional) is the Plex address the player is told to fetch from, when it differs from `PLEX_URL`. The player reopens the file, so expect a few seconds of rebuffer. Limits: which apps accept a proxied `playMedia` is not verified; a player that is not listed by the server with the `playback` capability is only tried when it answers a proxied timeline poll. A live switch makes no full local copy: it picks the planned alternative or, when that is missing or dead, searches the indexers for one (same quality floor, a different upload, every segment on every provider), imports it through AltMount, serves it from a remote-backed stub and moves the player as soon as the offset maps; the chunk hashes are built in the background and, until then, tierfs refuses any chunk with a zero run. If nothing usable is found or a check could not be made, the player is left alone and the alert says why. See OFFLOAD_DESIGN.md, "Live release switch". +`--switch-live` (move a player that is watching an offloaded file onto another release of it; the automatic switch below, started by hand, on the same code path): `python -m offload.runner --switch-live --check` lists the Plex sessions playing that row and whether each player accepts remote control (read-only, always safe). `python -m offload.runner --switch-live ` is a dry run unless `TIERING_APPLY=1`: a dry run does every read step and logs what it would send. A live run (1) finds the sessions on the row, (2) leaves any player that does not accept remote control on the old file (and restores nothing if none does), (3) puts a substitute in the row's place unless one already is: the planned alternative, else a live indexer search, picked only when it is the same cut with the same sound (run time and first sound track probed from the first bytes of both files); it is served from Usenet through tierfs, with no local copy, under a new row id at the same library path, (4) waits up to two minutes for Plex's partial scan to show a part of the new file's size, (5) reads each player's position again, maps it onto the new release by the sound around it (`watch_hold.map_offset`), and sends `playMedia` at that position through the Plex server's player proxy. If the mapping is not confident, the scan does not show up in time, or the command fails, that player is not switched and keeps reading the old file; the run says so and exits 1. Like the automatic switch it writes an `auto_switch` event and tells the owner through `TIERING_ALERTS` (`auto_switch` with `took_s` when it switched, else `auto_switch_` with the reason; the `substitute_pick` or `substitute_failed` event counts the dropped candidates by reason). The new row gets its SHA-256 and chunk list from the runner's hash build (one read of the whole file) and is then promoted and demoted like any row. `SUBSTITUTE_RUNTIME_TOL_S` (20) and `SUBSTITUTE_RUNTIME_TOL_FRAC` (0.005) set how far two run times may differ and still count as the same cut. Needs `PLEX_URL`, `PLEX_TOKEN`, `TIERFS_MOUNT`, and ffmpeg and numpy in the image (the tiering image has them). `TIERING_PLEX_PLAYER_URL` (optional) is the Plex address the player is told to fetch from, when it differs from `PLEX_URL`. The player reopens the file, so expect a few seconds of rebuffer. Limits: which apps accept a proxied `playMedia` is not verified; a player that is not listed by the server with the `playback` capability is only tried when it answers a proxied timeline poll. A live switch makes no full local copy: it picks the planned alternative or, when that is missing or dead, searches the indexers for one (same quality floor, a different upload, every segment on every provider), imports it through AltMount, serves it from a remote-backed stub and moves the player as soon as the offset maps; the chunk hashes are built in the background and, until then, tierfs refuses any chunk with a zero run. If nothing usable is found or a check could not be made, the player is left alone and the alert says why. See OFFLOAD_DESIGN.md, "Live release switch". -`--mark-failed [--undo]`: a live Plex session on an offloaded file starts its promote at once, and a restore cannot run beside a promote. To switch a playing file without a bad chunk (a test), mark the row first: `python -m offload.runner --mark-failed ` sets an `offloaded` row to `failed` (`restore_note` "marked failed by hand"), the state a bad chunk leaves. No promote runs for it, tierfs keeps serving its stub, and `--restore` or `--switch-live` can run while it plays. `--undo` puts a row marked this way back to `offloaded`; it never touches a row that failed for a real reason. A dry run unless `TIERING_APPLY=1`. It reads only `TIERING_DB` and `TIERING_APPLY`. -`TIERING_AUTO_SWITCH` (default 1; `0`, `false`, `no` or `off` turns it off): when a chunk cannot be repaired by provider failover or the twin (a promote ends with a chunk mismatch on every copy, or tierfs reports a bad chunk on a row with no twin) and a Plex session is playing that row, the runner runs the `--switch-live` flow for it by itself: restore from the restore path, wait for Plex's metadata, map the offset, `playMedia`. It needs `PLEX_URL` and `PLEX_TOKEN`. Only with `TIERING_APPLY=1`; otherwise it logs what it would do. With no restore-path release, no player that accepts remote control, or a failed offset mapping nobody is moved: the row fails as before and the re-download flow takes it, and the alert `auto_switch_no_restore_path`, `auto_switch_no_player_control` or `auto_switch_mapping_failed` says why. Every attempt writes an `auto_switch` event with the outcome (`switched`, `no_player_control`, `no_restore_path`, `mapping_failed`, `dry_run`); one switch per row runs at a time. See OFFLOAD_DESIGN.md, "Live release switch". +`--mark-failed [--undo]`: a live Plex session on an offloaded file starts its promote at once, and a restore cannot run beside a promote. To switch a playing file whose release can no longer be fetched (or as a test), mark the row first: `python -m offload.runner --mark-failed ` sets an `offloaded` row to `failed` (`restore_note` "marked failed by hand"), the state a bad chunk leaves. No promote runs for it, tierfs keeps serving its stub, and `--restore` or `--switch-live` can run while it plays. `--undo` puts a row marked this way back to `offloaded`; it never touches a row that failed for a real reason. A dry run unless `TIERING_APPLY=1`. It reads only `TIERING_DB` and `TIERING_APPLY`. +`TIERING_AUTO_SWITCH` (default 1; `0`, `false`, `no` or `off` turns it off): when a chunk cannot be repaired by provider failover or the twin (a promote ends with a chunk mismatch on every copy, or tierfs reports a bad chunk on a row with no twin) and a Plex session is playing that row, the runner runs the `--switch-live` flow for it by itself: put the substitute in place, wait for Plex's metadata, map the offset, `playMedia`. It needs `PLEX_URL` and `PLEX_TOKEN`. Only with `TIERING_APPLY=1`; otherwise it logs what it would do. With no restore-path release, no player that accepts remote control, or a failed offset mapping nobody is moved: the row fails as before and the re-download flow takes it, and the alert `auto_switch_no_restore_path`, `auto_switch_no_player_control` or `auto_switch_mapping_failed` says why. Every attempt writes an `auto_switch` event with the outcome (`switched`, `no_player_control`, `no_restore_path`, `mapping_failed`, `dry_run`); one switch per row runs at a time. See OFFLOAD_DESIGN.md, "Live release switch". ### Restub (after data loss) @@ -180,7 +180,7 @@ python -m offload.runner restub --cap 25 # at most 25 files this run (defaul It needs `TIERING_DB`, `TIERFS_MANIFESTS`, `TIERFS_MOUNT`, `TIERFS_STUB_ROOTS`, `TIERING_PATH_MAP` and the AltMount reader settings (`TIERFS_REMOTE_BASE`, `_USER`, `_PASS`). It refuses when AltMount is down or a stub root is not mounted, reports rows whose manifest or chunk list is gone (they cannot be rebuilt), never replaces a regular file at `L`, and marks a row `failed` with an alert in `TIERING_ALERTS` (`restub_unreadable`) when its head or tail articles are gone. Safe to rerun. Details: "Restub" in `OFFLOAD_DESIGN.md`. -Alerts go to `TIERING_ALERTS` (JSON lines): `bad_chunk`, `slot_timeout`, `promote_failed`, `promote_retrying` (3 failures in a row; retries back off from 5 minutes, doubling to 6 hours), `promote_worker_died`, `demote_failed`, `register_failed`, `weekly_failed`, `history_shrunk`, `orphan_stubs_removed` (once per pass that removed any), `restub_unreadable` (from the restub command), `altmount_unreachable` (once a night, when AltMount still refuses imports on a row's last try), and once per id `promote_short_remote`, `takeover_orphan`, `l_missing` and `promote_stuck`. A row flagged by the weekly check is promoted whether or not the hot set wants it. The runner follows `TIERFS_EVENTS` all the time: the first `want` for a file starts its promote within 1 second, outside `TIERING_PROMOTE_CONCURRENCY`, and later `want`s move the promote's cursor. A live Plex session on an offloaded file counts as a `want`. While someone watches a file, its promote fetches `TIERING_PROMOTE_STREAM_FETCHES` (default 6) chunks at once, and every other promote and the demotes pause until it is done. A file whose qualify found a twin (a second upload of the same bytes) is promoted from either copy: a chunk the first copy fails for `TIERING_PROMOTE_SWITCH_S` (default 20) is read from the other, and while someone watches, a chunk still out after `TIERING_PROMOTE_HEDGE_S` (default 10) is asked of both. An offloaded file keeps 20 minutes of play on local disk (`TIERING_HEAD_MIN_S`, default 1200) and at least 20% of the file. The play time is Plex's, else the one Radarr or Sonarr measured from the file; a file with neither, one under 30 minutes of play (`TIERING_MIN_PLAY_S`, default 1800), or one too short for that head to leave 20% offloaded stays whole. A `want` ignores the retry backoff but not more often than every 60 seconds per file, and never retries a `failed` row. The weekly check runs on start-up and at the start of the demote window when the last run is 7 days old (`kv weekly_last_ts`); that night's demotes wait for it, and a failed run alerts and is retried after an hour. Flags come only from `weekly_flag` events (cursor `kv weekly_flag_cursor`) and end when the promote finishes. A qualify result of `nzb_unsure` (indexers) or `import_unsure` (AltMount did not answer) means try later: nothing is written, and the file is tried again 45 minutes later the same night (up to 3 qualifies a night, not for `grab_failed`), then the next night. One Newznab client serves qualify and the weekly check; its budgets live in `TIERING_NEWZNAB_STATE` (default `newznab_state.json` next to `TIERING_DB`), the weekly report in `TIERING_WEEKLY_REPORT` (default `weekly_report.md` there). `/healthz` reports `worker_deaths` and `stuck_promotes`. The runner keeps its own last-play time per title in the state DB; when Plex's play history is empty or over 20% shorter than last time it refuses that night's demotes (after a deliberate purge, `DELETE FROM kv WHERE key='history_count'`). A register with errors, or with missing or ambiguous files over 5% of the files it listed, blocks that night's demotes. +Alerts go to `TIERING_ALERTS` (JSON lines): `bad_chunk`, `slot_timeout`, `promote_failed`, `promote_retrying` (3 failures in a row; retries back off from 5 minutes, doubling to 6 hours), `promote_worker_died`, `demote_failed`, `register_failed`, `weekly_failed`, `history_shrunk`, `orphan_stubs_removed` (once per pass that removed any), `restub_unreadable` (from the restub command), `altmount_unreachable` (once a night, when AltMount still refuses imports on a row's last try), and once per id `promote_short_remote`, `takeover_orphan`, `substitute_hash_failed` (a substitute's hash build hit a read fault or a missing segment; the row cannot be promoted until it is built), `l_missing` and `promote_stuck`. A row flagged by the weekly check is promoted whether or not the hot set wants it. The runner follows `TIERFS_EVENTS` all the time: the first `want` for a file starts its promote within 1 second, outside `TIERING_PROMOTE_CONCURRENCY`, and later `want`s move the promote's cursor. A live Plex session on an offloaded file counts as a `want`. While someone watches a file, its promote fetches `TIERING_PROMOTE_STREAM_FETCHES` (default 6) chunks at once, and every other promote and the demotes pause until it is done. A file whose qualify found a twin (a second upload of the same bytes) is promoted from either copy: a chunk the first copy fails for `TIERING_PROMOTE_SWITCH_S` (default 20) is read from the other, and while someone watches, a chunk still out after `TIERING_PROMOTE_HEDGE_S` (default 10) is asked of both. An offloaded file keeps 20 minutes of play on local disk (`TIERING_HEAD_MIN_S`, default 1200) and at least 20% of the file. The play time is Plex's, else the one Radarr or Sonarr measured from the file; a file with neither, one under 30 minutes of play (`TIERING_MIN_PLAY_S`, default 1800), or one too short for that head to leave 20% offloaded stays whole. A `want` ignores the retry backoff but not more often than every 60 seconds per file, and never retries a `failed` row. The weekly check runs on start-up and at the start of the demote window when the last run is 7 days old (`kv weekly_last_ts`); that night's demotes wait for it, and a failed run alerts and is retried after an hour. Flags come only from `weekly_flag` events (cursor `kv weekly_flag_cursor`) and end when the promote finishes. A qualify result of `nzb_unsure` (indexers) or `import_unsure` (AltMount did not answer) means try later: nothing is written, and the file is tried again 45 minutes later the same night (up to 3 qualifies a night, not for `grab_failed`), then the next night. One Newznab client serves qualify and the weekly check; its budgets live in `TIERING_NEWZNAB_STATE` (default `newznab_state.json` next to `TIERING_DB`), the weekly report in `TIERING_WEEKLY_REPORT` (default `weekly_report.md` there). `/healthz` reports `worker_deaths` and `stuck_promotes`. The runner keeps its own last-play time per title in the state DB; when Plex's play history is empty or over 20% shorter than last time it refuses that night's demotes (after a deliberate purge, `DELETE FROM kv WHERE key='history_count'`). A register with errors, or with missing or ambiguous files over 5% of the files it listed, blocks that night's demotes. ## Tests (run on a Linux test box) ``` diff --git a/tiering/offload/newznab.py b/tiering/offload/newznab.py index 49ad6ea..db9f63c 100644 --- a/tiering/offload/newznab.py +++ b/tiering/offload/newznab.py @@ -220,6 +220,62 @@ def title_matches(release_title: str, title: str, year: int | None = None, return rest == "" or _STOP.match(rest.split(" ", 1)[0]) is not None +# Words after the title that name the cut. Two names with different sets are different cuts. +_EDITIONS = ( + ("extended", r"extended"), + ("unrated", r"unrated|uncensored"), + ("uncut", r"uncut"), + ("directors cut", r"directors (?:cut|edition)"), + ("theatrical", r"theatrical"), + ("final cut", r"final cut"), + ("ultimate", r"ultimate (?:cut|edition)"), + ("special edition", r"special edition"), + ("collectors", r"collectors (?:cut|edition)"), + ("anniversary", r"anniversary"), + ("imax", r"imax"), + ("open matte", r"open matte"), + ("remastered", r"remastered|restored"), + ("redux", r"redux"), + ("rogue cut", r"rogue cut"), + ("despecialized", r"despecialized"), + ("workprint", r"workprint"), + ("3d", r"3d|hsbs|hou|sbs"), +) +_EDITION_RES = tuple((k, re.compile(rf"(? str: + """The cleaned name without the title in front: a title word ("Uncut ...") is no tag.""" + rel, want = _clean(name), _clean(title or "") + if want and (rel == want or rel.startswith(want + " ")): + return rel[len(want):].strip() + return rel + + +def edition_of(name: str, title: str | None = None) -> frozenset: + """The cut a release name says it is (extended, unrated, IMAX, 3D, ...); empty for the + plain cut. `title` is taken off the front first.""" + rest = _after_title(name, title) + return frozenset(k for k, rx in _EDITION_RES if rx.search(rest)) + + +def language_tags(name: str, title: str | None = None) -> frozenset: + """The language words of a release name (GERMAN, MULTi, DUBBED, hardcoded subtitles, ...); + empty when the name says nothing, which is the original sound.""" + rest = _after_title(name, title) + return frozenset(_LANG_SAME.get(w, w) for w in _LANG_RE.findall(rest)) + + class SearchResult(list): """A list of releases that also says how complete the search was. diff --git a/tiering/offload/probe.py b/tiering/offload/probe.py new file mode 100644 index 0000000..381dfcd --- /dev/null +++ b/tiering/offload/probe.py @@ -0,0 +1,60 @@ +"""What the first bytes of a media file say about it: play time, audio languages, picture height. + +The live substitute (`substitute.py`) uses this to prove that a replacement release is the same +cut with the same sound as the file it replaces, before anything is switched. `probe_bytes` hands +the bytes to ffmpeg on stdin (`-i pipe:0`) and reads what it prints about the input; nothing is +decoded and no file is opened, so tierfs is not involved. A Matroska file carries all of this in +its first megabytes. A container that keeps its index at the end (some MP4s) cannot be read this +way: the result then has no play time, and the caller treats that as "cannot be proved". + +`parse` is the text reader on its own: {"duration_s": float | None, "audio": [language, ...], +"height": int | None}. Languages are ISO 639-2 codes as ffmpeg prints them, mapped to one spelling +(`ger` and `deu` are the same); an untagged track is None. +""" +from __future__ import annotations + +import os +import re +import subprocess + +TIMEOUT_S = 60 +_DUR = re.compile(r"Duration:\s*(\d+):(\d\d):(\d\d(?:\.\d+)?)") +_STREAM = re.compile(r"Stream #\d+:\d+(?:\[[^\]]*\])?(?:\(([A-Za-z-]+)\))?: (Audio|Video): (.*)") +_DIM = re.compile(r"(? str | None: + t = (tag or "").strip().lower() + if t in ("", "und", "unk", "zxx", "mul", "mis"): + return None + return _SAME.get(t, t) + + +def parse(text: str) -> dict: + out = {"duration_s": None, "audio": [], "height": None} + m = _DUR.search(text) + if m: + out["duration_s"] = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3)) + for lang, kind, rest in _STREAM.findall(text): + if kind == "Audio": + out["audio"].append(language(lang)) + elif out["height"] is None and "attached pic" not in rest: + d = _DIM.search(rest) + if d: + out["height"] = int(d.group(2)) + return out + + +def probe_bytes(data: bytes, binary: str | None = None, timeout: float = TIMEOUT_S) -> dict: + """`parse` of what ffmpeg says about a file that starts with `data`. Raises OSError or + subprocess.TimeoutExpired when ffmpeg cannot be run; an input it cannot read gives a result + with nothing in it.""" + binary = binary or os.environ.get("SWITCH_FFMPEG_BIN", "watch-align") + r = subprocess.run([binary, "-hide_banner", "-i", "pipe:0"], input=data, + capture_output=True, timeout=timeout) + return parse(r.stderr.decode("utf-8", "replace")) diff --git a/tiering/offload/qualify.py b/tiering/offload/qualify.py index 0516119..117322e 100644 --- a/tiering/offload/qualify.py +++ b/tiering/offload/qualify.py @@ -53,7 +53,7 @@ from .altmount import AltMountAuthError, AltMountError, ImportFailed, ImportTimeout from .newznab import (BadRelease, GrabBudgetSpent, IndexersUnavailable, ItemFailed, NewznabError, NotNzb, archive_nzb, nzb_segment_ids, parse_resolution, - read_archived, title_matches) + read_archived, title_matches, edition_of, language_tags) from .nntp_stat import NntpUnavailable, ProviderCfg from .usenet_read import CannotTell, UsenetFile @@ -212,8 +212,49 @@ def _stat_ok(raw: bytes, providers, tmp_dir: str, dead: dict): return True if r == "ok" else (False if r == "missing" else None) +MAX_REJECTED = 40 # how many dropped candidates a result names (the counts hold all of them) + + +@dataclass +class Fit: + """The stricter rules of a live substitute (`substitute.py`): the pick must be the same cut + with the same sound, because a viewer is moved onto it without being asked. With a `Fit`, + `score_restore` also drops a candidate whose name says another cut (`edition_of`) or other + language words (`language_tags`) than ours, and tries the candidates nearest to the + source's resolution first: the same, then the next higher, then the next lower. + `accept(rel, raw)` is asked last, for a candidate whose articles are all there: None takes + it, a string says why not (the substitute probes the file's run time and sound there). Each + refusal costs an import, so after `max_refused` of them no more are tried.""" + accept: object = None + max_refused: int = 3 + + +def name_tags(row: dict, tags) -> frozenset: + """`tags` (edition_of or language_tags) of what the row's file is called: its release name + and its library name together.""" + title = row.get("title") + out = set() + for k in ("release_name", "lib_path"): + if row.get(k): + out |= tags(os.path.splitext(os.path.basename(str(row[k])))[0], title) + return frozenset(out) + + +def _nearest_first(src: int): + """Sort key part: the source's resolution first, then higher ones from the nearest up, + then lower ones from the nearest down. An unknown source keeps highest first.""" + def key(res: int): + if not src: + return (0, -res) + if res == src: + return (0, 0) + return (1, res - src) if res > src else (2, src - res) + return key + + def score_restore(row: dict, indexers, own_ids: frozenset | None, - stop_at: int | None = None, found=None, verify=None) -> dict: + stop_at: int | None = None, found=None, verify=None, + fit: Fit | None = None) -> dict: """Count releases that could replace this file if the exact upload dies. ``own_ids`` is the set of message-ids of our NZB. A candidate whose NZB shares @@ -233,10 +274,14 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, spent grab budget, an indexer that cannot be asked or a failed transport also make it unsure. None of these is a "no". + ``fit`` adds the live substitute's rules (see `Fit`); without it nothing here changes. + Returns {count, floor, best, downgrade, below_floor, dead, partial, unsure, note, - candidate}. ``downgrade`` is True when the best verified alternative is below the - source's resolution (a 4K source with only 1080p left). - ``candidate`` is {title, nzb} of the first verified alternative (its NZB bytes), or None. + candidate, rejected, why}. ``downgrade`` is True when the best verified alternative is + below the source's resolution (a 4K source with only 1080p left). + ``candidate`` is {title, nzb, resolution} of the first verified alternative (its NZB + bytes), or None. ``why`` counts every dropped candidate by reason and ``rejected`` names + the first ``MAX_REJECTED`` of them as {title, why} (other titles are counted, not named). ``partial`` means some indexer did not answer; ``unsure`` means ``partial`` or some candidate's NZB could not be checked, or ``own_ids`` was not given. With ``unsure``, a count of 0 means "not checked", not "no restore path". @@ -249,13 +294,33 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, partial = bool(getattr(found, "partial", False)) unsure = partial or own_ids is None own_name = _clean(release_name_of(row)) - cands, below = [], 0 + why: dict = {} + rejected: list = [] + + def drop(rel, reason, named=True): + why[reason] = why.get(reason, 0) + 1 + if named and len(rejected) < MAX_REJECTED: + rejected.append({"title": rel.title, "why": reason}) + + own_cut = name_tags(row, edition_of) if fit else frozenset() + own_lang = name_tags(row, language_tags) if fit else frozenset() + cands, below, unfit = [], 0, 0 for rel in found: if not title_matches(rel.title, ident["title"] or "", ident["year"], ident["season"], ident["episode"]): + drop(rel, "another title", named=False) continue if rel.resolution < floor: below += 1 + drop(rel, "below the quality floor") + continue + if fit and edition_of(rel.title, ident["title"]) != own_cut: + unfit += 1 + drop(rel, "another cut by its name") + continue + if fit and language_tags(rel.title, ident["title"]) != own_lang: + unfit += 1 + drop(rel, "other language words in its name") continue cands.append(rel) # highest resolution first: upgrade or keep, never downgrade while another option is @@ -263,10 +328,14 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, # name that differs from ours is the better bet for a different upload; the name never # decides, only the message-ids do cands.sort(key=lambda r: (-r.resolution, _clean(r.title) == own_name, _clean(r.title), r.link)) + if fit: # a viewer is moved onto the pick: the nearest picture first (the sort is stable) + near = _nearest_first(source_resolution(row)) + cands.sort(key=lambda r: near(r.resolution)) counted: list[frozenset] = [] best = 0 fails = 0 dead = 0 + refused = 0 candidate = None for rel in cands if own_ids is not None else (): if stop_at and len(counted) >= stop_at: @@ -275,17 +344,21 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, ids, raw = indexers.fetch_nzb_ids(rel) except GrabBudgetSpent: unsure = True + drop(rel, "not checked: the grab budget is spent") continue except BadRelease: dead += 1 # known to have no NZB: no restore path, and no grab was spent + drop(rel, "no NZB behind the listing") continue except NotNzb: # one page that is no NZB may be a maintenance page: only a strike, so the # path is unchecked. Dead once the strike confirms (no NZB on two nights) if indexers.is_bad(rel): dead += 1 + drop(rel, "no NZB behind the listing") else: unsure = True + drop(rel, "not checked: the indexer sent no NZB") fails += 1 if fails >= MAX_FAILED_GRABS: unsure = True # the rest were not asked @@ -293,6 +366,7 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, continue except ItemFailed: dead += 1 # the indexer says the item is gone (300, 404, 410): a dead one + drop(rel, "the indexer says it is gone") fails += 1 if fails >= MAX_FAILED_GRABS: unsure = True # the rest were not asked @@ -300,11 +374,13 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, continue except _ERRORS: unsure = True + drop(rel, "not checked: the NZB could not be fetched") fails += 1 if fails >= MAX_FAILED_GRABS: break continue if not ids or ids & own_ids: + drop(rel, "the same upload as ours") continue # the same upload (or nothing to compare) if any(ids & c for c in counted): continue # the same upload as one already counted @@ -312,14 +388,25 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, v = verify(raw) if v is None: unsure = True # a provider could not be asked: more tries would not help + drop(rel, "not checked: a provider did not answer") break if not v: dead += 1 # an alternative whose articles are gone is no restore path + drop(rel, "articles gone") + continue + if fit and fit.accept is not None: + no = fit.accept(rel, raw) + if no: + unfit += 1 + refused += 1 + drop(rel, str(no)) + if refused >= fit.max_refused: + break # each refusal cost an import: the rest are not tried continue counted.append(ids) best = max(best, rel.resolution) if candidate is None: - candidate = {"title": rel.title, "nzb": raw} + candidate = {"title": rel.title, "nzb": raw, "resolution": rel.resolution} count = len(counted) src_res = source_resolution(row) downgrade = bool(count) and 0 < best < src_res @@ -331,13 +418,16 @@ def score_restore(row: dict, indexers, own_ids: frozenset | None, note = "restore path unchecked (an indexer or NZB did not answer)" elif dead: note = f"alternatives found but none can be restored: no NZB or articles gone ({dead})" + elif unfit: + note = f"alternatives found but none is the same cut with the same sound ({unfit})" elif below: note = f"only below-floor alternatives ({below}), floor {floor}p" else: note = "no alternative release found" return {"count": count, "floor": floor, "best": best, "downgrade": downgrade, "below_floor": below, "dead": dead, - "partial": partial, "unsure": unsure, "note": note, "candidate": candidate} + "partial": partial, "unsure": unsure, "note": note, "candidate": candidate, + "rejected": rejected, "why": why} def find_twin(found, name: str, own_ids: frozenset, lib_path: str, *, indexers, importer, diff --git a/tiering/offload/runner.py b/tiering/offload/runner.py index 7e43e62..526c083 100644 --- a/tiering/offload/runner.py +++ b/tiering/offload/runner.py @@ -55,7 +55,8 @@ REGISTER_BAD_FRAC = 0.05 # missing_local + ambiguous over this share of listed fails register (on_pool is not counted) RESTORED_NOTE = "restored from the restore path" # ops.RESTORED_NOTE ORPHAN_NOTES = ("L replaced", RESTORED_NOTE) # failed rows whose stub the orphan cleanup may remove -ALERT_EVENTS = ("promote_short_remote", "takeover_orphan") # ops events, alerted once per id +# ops events, alerted once per id +ALERT_EVENTS = ("promote_short_remote", "takeover_orphan", "substitute_hash_failed") ONCE_KINDS = ALERT_EVENTS + ("l_missing", "promote_stuck", "lost_file") # alerted once per id, ever BACKOFF_MAX = 6 * 3600.0 # promote retry delay: RETRY_DELAY doubling, capped here FAIL_ALERT_AFTER = 3 # failures in a row per id before an alert @@ -428,8 +429,10 @@ def arrs(): return arrs -def load_deps(cfg: Config) -> Deps: - """Wire the real modules. Imported here so the runner imports without them.""" +def load_deps(cfg: Config, short_lived: bool = False) -> Deps: + """Wire the real modules. Imported here so the runner imports without them. + `short_lived`: a by-hand command that ends soon; a substitute it makes leaves its hash + build to the runner.""" from . import altmount, ops from . import state as st @@ -525,7 +528,8 @@ def recheck(db, row, offset): def substitute(db, row, apply, keep_name=True): # clients and the substitute's deps are built on use, like restore's from . import substitute as sub - return sub.make_restore(wiring.substitute_deps(cfg))(db, row, apply, keep_name) + d = wiring.substitute_deps(cfg, short_lived=short_lived) + return sub.make_restore(d)(db, row, apply, keep_name) hash_resume = None if not os.environ.get("TIERING_QUALIFY_FACTORY"): @@ -617,6 +621,7 @@ def __init__(self, cfg: Config, deps: Deps, clock=time.time, sleep=time.sleep): self.ops_alerted: set = set() # (kind, id), once per id, ever self.dry_switched: set = set() # ids whose dry-run auto switch was logged (once per process) self.hash_resumed: set = set() # ids whose pending hash build was resumed (once per process) + self.hash_waiting: set = set() # ids whose promote waits for the hash build (logged once) self.switching: set = set() # ids with an automatic live switch running self.restore_tried: set = set() # ids the auto restore has tried (once per id and process) self.unsure_retry: dict = {} # id -> (night start, qualify tries, not before): nzb_/import_unsure retries @@ -1354,9 +1359,21 @@ def _auto_switch(self, id, why, from_promote=False): per id at a time; a row with a running demote, or a promote other than the one that is calling (`from_promote`), is left alone. TIERING_APPLY unset: logs what it would do and changes nothing.""" - if not self.cfg.auto_switch or self.deps.restore is None: + res = self._switch(id, why, from_promote=from_promote) + return res["outcome"] if res else None + + def _switch(self, id, why, from_promote=False, by_hand=False, plex=None, **more): + """The one live-switch path: the automatic trigger (`_auto_switch`) and `--switch-live` + by hand (`switch_main`, `by_hand`) both end here, so both use the substitute (the + planned alternative, else a live search), write the same `auto_switch` event and send + the owner the same alerts. By hand the TIERING_AUTO_SWITCH switch and the once-only + dry-run note do not apply. Returns `switch_live.auto_switch`'s result, or None when + nothing was decided before it was asked (off, busy, row not switchable, a fault).""" + if (self.deps.substitute if by_hand else None) is None and self.deps.restore is None: + return None + if not by_hand and not self.cfg.auto_switch: return None - if not self.cfg.apply and id in self.dry_switched: + if not by_hand and not self.cfg.apply and id in self.dry_switched: return None # the dry-run decision for this row was logged already from . import switch_live with self.mu: @@ -1369,11 +1386,13 @@ def _auto_switch(self, id, why, from_promote=False): row = self.state.get(db, id) if row is None or row["state"] not in ("offloaded", "failed"): return None - plex = self.deps.switch_plex() if self.deps.switch_plex else switch_live.Plex() + plex = plex or (self.deps.switch_plex() if self.deps.switch_plex + else switch_live.Plex()) kw = {"path_map": self.cfg.path_map, "tierfs_mount": self.cfg.tierfs_mount, "server_url": os.environ.get("TIERING_PLEX_PLAYER_URL") or None} if self.deps.switch_mapper: kw["mapper"] = self.deps.switch_mapper + kw.update(more) sub = self.deps.substitute res = switch_live.auto_switch(db, row, plex, apply=self.cfg.apply, restore=sub or self.deps.restore, search=bool(sub), **kw) @@ -1392,11 +1411,12 @@ def _auto_switch(self, id, why, from_promote=False): if out in ("no_player_control", "no_restore_path", "mapping_failed"): self._once(f"auto_switch_{out}", id, why=why, reason=res["detail"][:200]) elif out == "switched": - self._alert("auto_switch", id, why=why, outcome=out) + took = {k: res[k] for k in ("took_s",) if k in res} + self._alert("auto_switch", id, why=why, outcome=out, **took) if id in self.flagged: self.flagged.discard(id) self._kv_set(self._open(), "flagged", sorted(self.flagged)) - return out + return res def _spawn_switch_or(self, id, why, otherwise): """Run the automatic switch for `id` in its own thread (the pass must not wait for a @@ -1455,8 +1475,9 @@ def _once(self, kind, id, **detail): self._alert(kind, id, **detail) def _resume_hashes(self): - """A substitute whose hash build a restart cut short leaves a `pending` manifest. Start - the build again, once per id per process (the build itself refuses a second run).""" + """A substitute whose hash build a restart cut short, or that a by-hand switch left to + the runner, has a `pending` manifest. Start the build, once per id per process (the + build itself refuses a second run), and only for a row that is `offloaded`.""" if not self.cfg.apply or not self.deps.hash_resume or not self.cfg.manifests: return try: @@ -1474,16 +1495,35 @@ def _resume_hashes(self): continue if not pending: continue + try: + cur = self.state.get(self.db(), id) + except Exception: # noqa: BLE001 # asked again at the next pass + continue + if not cur or cur["state"] != "offloaded": + continue # retired by a later substitute, or failed: its file is not fetched self.hash_resumed.add(id) def run(id=id): try: - self.deps.hash_resume(self._open(), id) + if self.deps.hash_resume(self._open(), id) is None: + # another process is building it (a by-hand switch): look again later + self.hash_resumed.discard(id) except Exception as e: log.error("hash resume %s raised %s", id, type(e).__name__) log.info("resuming the hash build of %s", id) self._spawn(run) + def _hash_pending(self, id) -> bool: + """A substitute whose hash build has not ended: its manifest says `pending`, so there is + no chunk list and no sha256 for a promote to check against yet.""" + if not self.cfg.manifests: + return False + try: + with open(os.path.join(self.cfg.manifests, f"{id}.json")) as f: + return json.load(f).get("pending") is True + except (OSError, ValueError, AttributeError): + return False + def _follow_once(self): """Read new tierfs events. A `want` starts its promote now; the rest wait in tail_events for the next pass.""" @@ -2171,6 +2211,13 @@ def _promote_one(self, db, id, row, wanted=False): if cur is None or cur["state"] not in (ACTIVE_STATES if not wanted else ("offloaded", "promoting")): return + if cur["state"] == "offloaded" and self._hash_pending(id): + # a substitute still being hashed: tierfs serves its middle from the remote, + # and the promote starts once the build has written its records. No failure. + if id not in self.hash_waiting: + self.hash_waiting.add(id) + log.info("promote %s waits for the substitute's hash build", id) + return log.info("promote start %s%s", id, " (wanted)" if wanted else "") kw = {"want": lambda: self.want_off.get(id), "urgent": lambda: self._is_watched(id), "pause": lambda: self._yield_to_watched(id)} @@ -2578,14 +2625,17 @@ def mark_failed_main(args, env=None, deps=None) -> int: def switch_main(args, env=None, deps=None, plex=None, **kw) -> int: - """`--switch-live ID [--check]`: move the players watching row ID onto the restore-path - release (see switch_live.py). `--check` only lists the sessions and whether each player - accepts remote control. Otherwise a dry run unless TIERING_APPLY=1. Like --restore it does - not take the runner lock.""" + """`--switch-live ID [--check]`: move the players watching row ID onto another release of + it. This is the automatic switch run by hand (`Runner._switch`): the same substitute (the + planned alternative, else a live search; no local copy), the same `auto_switch` event and + the same owner alerts. `--check` only lists the sessions and whether each player accepts + remote control. Otherwise a dry run unless TIERING_APPLY=1. Like --restore it does not take + the runner lock. Exit 0: switched, a dry run, or nobody plays the row. 1: nobody could be + switched (the log and the alert say why). 2: settings or usage.""" from . import switch_live try: cfg = Config.from_env(env) - deps = deps or load_deps(cfg) + deps = deps or load_deps(cfg, short_lived=True) except Exception as e: log.error("settings: %s: %s", type(e).__name__, e) return 2 @@ -2604,22 +2654,27 @@ def switch_main(args, env=None, deps=None, plex=None, **kw) -> int: if "--check" in args: switch_live.check(row, plex, out=print) return 0 - if deps.restore is None: - log.error("switch: restore is not available") - return 2 - e = os.environ if env is None else env - res = switch_live.switch_live( - db, row, plex, apply=cfg.apply, restore=deps.restore, path_map=cfg.path_map, - tierfs_mount=cfg.tierfs_mount, server_url=e.get("TIERING_PLEX_PLAYER_URL") or None, - **kw) except switch_live.PlexRCError as e: log.error("switch %s: %s", id, e) return 1 - log.info("switch %s: switched=%d left=%d %s", id, len(res["switched"]), len(res["left"]), - res["note"]) - for m, why in res["left"].items(): - log.warning("switch %s: player %s left on the old file: %s", id, m, why) - return 0 if res["switched"] or not res["left"] else 1 + if getattr(deps, "substitute", None) is None and getattr(deps, "restore", None) is None: + log.error("switch: restore is not available") + return 2 + if row["state"] not in ("offloaded", "failed"): + log.error("switch %s: the row is %s; only an offloaded or failed row is switched", id, + row["state"]) + return 1 + e = os.environ if env is None else env + kw.setdefault("server_url", e.get("TIERING_PLEX_PLAYER_URL") or None) + res = Runner(cfg, deps)._switch(id, "by hand", by_hand=True, plex=plex, **kw) + if res is None: + log.error("switch %s: nothing was done (busy, or a fault: see the lines above)", id) + return 1 + out = res["outcome"] + log.info("switch %s: %s (%s)", id, out or "nothing to do", res["detail"]) + if out in ("switched", "dry_run"): + return 0 + return 0 if out is None and "no session" in res["detail"] else 1 def main(argv=None, env=None, deps=None) -> int: diff --git a/tiering/offload/substitute.py b/tiering/offload/substitute.py index 10104de..2a4f048 100644 --- a/tiering/offload/substitute.py +++ b/tiering/offload/substitute.py @@ -5,11 +5,17 @@ given), and it keeps nothing on local disk but a head, a tail and a hole, like any offloaded row: 1. `choose`: the planned alternative (`nzb_path2`) when every article is on every provider; - else, when it is missing, dead or its check fails, a live search of the indexers with the - qualify rules (`qualify.score_restore`: at or above the quality floor, a different upload with - no message-id shared with `nzb_path` or the dead planned one, every segment STATed on every - provider). A search that finds nothing, or could not be checked, changes nothing: the caller - leaves the player alone and alerts. It never guesses. + else, when it is missing, dead, not the same cut or its check fails, a live search of the + indexers with the qualify rules (`qualify.score_restore`: at or above the quality floor, a + different upload with no message-id shared with `nzb_path` or the planned one, every segment + STATed on every provider) and the rules of `qualify.Fit`, because the viewer is not asked: + the same cut and language words by its name, the nearest resolution first (the same, then + higher, then lower). Last, the pick is imported and its first bytes are probed (`probe.py`) + beside those of our own stub: the run time must agree within `runtime_tol` and the first + sound track must be in the same language, or it is dropped as another cut. What cannot be + proved is dropped too. A search that finds nothing, or could not be checked, changes + nothing: the caller leaves the player alone and alerts, and the events `substitute_pick` and + `substitute_failed` say why each candidate was dropped. It never guesses. 2. `build`: import the NZB through AltMount, make a remote-backed stub (head and tail read from the remote, the middle a hole) and a *pending* manifest (no chunk list yet), point the library path at the new tierfs entry, and move the row's identity over: the new release gets a new id @@ -20,14 +26,21 @@ as soon as it can place it (about a minute), long before any hash exists. 3. the hash build: one background read of the new release at line rate, like promote's read-ahead. Until it ends tierfs serves the middle from the remote and checks each chunk for a zero run - (AltMount zero-fills a missing segment): a zero run is EIO, never bad bytes. When every chunk - is hashed the chunk list is written and the manifest is rewritten without `pending`. + (AltMount zero-fills a missing segment): a zero run is EIO, never bad bytes. The same read + feeds the whole file's SHA-256 (the stub's head, each chunk, the stub's tail). When every + chunk is hashed the row gets that `sha256`, the chunk list is written and the manifest is + rewritten without `pending`: from then on it is a row like any other, and promote checks + what it fetches against these records (each chunk's BLAKE3, then the whole file's SHA-256). + A substitute has no earlier copy to be compared with, so the records say "the bytes this + release served when it was taken, with no missing segment", and a promote that reads + anything else fails as it does for every row. `restore_from_path` stays for the non-live "bring it back" case only. Everything the module talks to (indexers, AltMount, providers, the NZB archive) is passed in, so tests use fakes. """ from __future__ import annotations +import hashlib import json import logging import os @@ -48,7 +61,12 @@ # half of the smallest article: an article cut by a chunk boundary leaves one side of >= 192 KB. ZERO_RUN = 128 * 1024 SEARCH_COOLDOWN_S = 6 * 3600.0 # a row whose live search found nothing is not searched again sooner +SEARCH_FAULT_RETRY_S = 600.0 # a search that could not be done or checked may be tried again this soon DEAD_PREFIX = ".dead-" +PROBE_LEN = 8 * 1024 * 1024 # the first bytes of a file that are probed for its run time and sound +RUNTIME_TOL_S = 20.0 # two files of the same cut differ by less than this, or by RUNTIME_TOL_FRAC +RUNTIME_TOL_FRAC = 0.005 +MAX_NAMED = 20 # dropped candidates named in one event _ZEROS = b"\x00" * ZERO_RUN @@ -63,7 +81,10 @@ class Deps: """What the substitute talks to. `stat_raw(raw)` is qualify's STAT of NZB bytes on every provider ("ok", "missing" or "unchecked"); `read_nzb(path)` gives the NZB as AltMount takes it; `archive(raw, title)` stores it and returns its path; `ids_of(raw)` its message-ids; - `score(row, indexers, own_ids, stop_at, verify)` is `qualify.score_restore`.""" + `score(row, indexers, own_ids, stop_at, verify)` is `qualify.score_restore`. With `fit` + (`qualify.Fit`) the search uses the substitute's name and nearest-resolution rules, and with + `probe` (`probe.probe_bytes`) a pick's run time and sound are compared with our own file's + before it is taken; without them neither check runs.""" indexers: object importer: object reader: object @@ -81,15 +102,58 @@ class Deps: clock: Callable = time.time spawn: Callable = None # spawn(fn): run the hash build; default: a daemon thread cooldown_s: float = SEARCH_COOLDOWN_S + fit: Callable | None = None + probe: Callable | None = None + probe_len: int = PROBE_LEN + runtime_tol_s: float = RUNTIME_TOL_S + runtime_tol_frac: float = RUNTIME_TOL_FRAC def _fail(reason, **kw): return {"ok": False, "reason": reason, **kw} +def _first(langs): + return langs[0] if langs else None + + +def own_facts(row, d: Deps) -> dict: + """What our own file is, from the head its stub holds: {"duration_s", "audio", "height"}. + The run time falls back to the one the arr measured (`play_ms`).""" + facts = {"duration_s": None, "audio": [], "height": None} + try: + with open(row["stub_path"], "rb") as f: + facts = d.probe(f.read(min(d.probe_len, int(row.get("head_len") or 0)))) + except Exception as e: # noqa: BLE001 # no stub, no ffmpeg: the fallback decides + log.warning("%s: our own file cannot be probed (%s)", row.get("id"), type(e).__name__) + if not facts.get("duration_s") and row.get("play_ms"): + facts = {**facts, "duration_s": int(row["play_ms"]) / 1000.0} + return facts + + +def same_cut(own: dict, new: dict, d: Deps) -> str | None: + """None when `new` is the same cut with the same sound as `own`, else why not. A fact that + cannot be read counts as a difference: nothing is taken on a guess.""" + a, b = own.get("duration_s"), new.get("duration_s") + if not b: + return "its run time cannot be read, so the same cut cannot be proved" + if not a: + return "our own run time is not known, so the same cut cannot be proved" + if abs(a - b) > max(d.runtime_tol_s, a * d.runtime_tol_frac): + return f"another cut: its run time differs by {int(abs(a - b))} s" + if not new.get("audio"): + return "no sound track was found in it" + if _first(own.get("audio")) != _first(new.get("audio")): + return "its first sound track is in another language, or one of the two is not labelled" + return None + + def choose(db, row, d: Deps) -> dict: """The release to switch to. {"ok": True, "source": "planned"|"unplanned", "nzb", "title", - "path" (planned only), "dead_planned": bool} or {"ok": False, "reason": str}.""" + "path" (planned only), "dead_planned": bool, "remote" (when it was imported for the probe), + "facts": what the pick was measured as, "why", "rejected"} or {"ok": False, "reason": str, + "why", "rejected"}. "why" counts the dropped candidates by reason and "rejected" names + them ({title, why}), so the caller can say why each one was not taken.""" id = row["id"] try: own = d.ids_of(d.read_nzb(row["nzb_path"])) if row.get("nzb_path") else None @@ -97,6 +161,30 @@ def choose(db, row, d: Deps) -> dict: return _fail(f"the row's own NZB cannot be read ({type(e).__name__})") if not own: return _fail("the row's own NZB has no message-ids to compare with") + why: dict = {} + rejected: list = [] + own = frozenset(own) + mine = own_facts(row, d) if d.probe else None + taken: dict = {} + + def accept(rel, raw): + """Import the candidate and probe its first bytes beside our own: None, or why not.""" + title = (rel.title if rel is not None else row.get("release_name")) or "release" + try: + remote = d.importer.import_nzb(raw, title) + n = min(d.probe_len, int(d.reader.size(remote))) + head = _read_region(d.reader, remote, 0, n, "start") + new = d.probe(head) + except Exception as e: # noqa: BLE001 # import, read or probe fault, missing segments + return f"it cannot be imported or read ({type(e).__name__})" + no = same_cut(mine, new, d) + if no is None: + taken.update(remote=remote, facts={ + "run_s": [mine.get("duration_s"), new.get("duration_s")], + "audio": [_first(mine.get("audio")), _first(new.get("audio"))], + "height": [mine.get("height"), new.get("height")]}) + return no + dead_planned, planned_ids = False, frozenset() p2 = row.get("nzb_path2") if p2: @@ -111,34 +199,57 @@ def choose(db, row, d: Deps) -> dict: dead_planned = True # no ids, or the same upload: not an alternative else: v = d.stat_raw(raw) - if v == "ok": + no = accept(None, raw) if v == "ok" and d.probe else None + if v == "ok" and no is None: return {"ok": True, "source": "planned", "nzb": raw, "path": p2, - "title": row.get("release_name") or "", "dead_planned": False} + "title": row.get("release_name") or "", "dead_planned": False, + "why": why, "rejected": rejected, **taken} if v == "unchecked": return _fail("the planned alternative could not be checked (a provider did " "not answer); leaving the player alone") - dead_planned = True + dead_planned = True # its articles are gone, or it is not the same cut + no = no or "articles gone" + why[no] = 1 + rejected.append({"title": "the planned alternative", "why": no}) # unplanned: ask the indexers key = f"substitute_search:{id}" last = st.kv_get(db, key) if last and d.clock() - float(last) < d.cooldown_s: - return _fail("a live search for this row found nothing recently; not asking again yet") + return _fail("a live search for this row found nothing recently; not asking again yet", + why=why, rejected=rejected) st.kv_set(db, key, d.clock()) + def soon(): + """The search could not be done or checked: that is no miss, so it may be tried again + after SEARCH_FAULT_RETRY_S, not after the whole cooldown.""" + st.kv_set(db, key, d.clock() - max(0.0, d.cooldown_s - SEARCH_FAULT_RETRY_S)) + def verify(raw): v = d.stat_raw(raw) return True if v == "ok" else (False if v == "missing" else None) + kw = {} + if d.fit is not None: + kw["fit"] = d.fit(accept=accept if d.probe else None) try: - sc = d.score(row, d.indexers, frozenset(own | planned_ids), stop_at=1, verify=verify) + sc = d.score(row, d.indexers, frozenset(own | planned_ids), stop_at=1, verify=verify, **kw) except Exception as e: # noqa: BLE001 # no indexer answered, or any other fault - return _fail(f"live search failed ({type(e).__name__}); leaving the player alone") + soon() + return _fail(f"live search failed ({type(e).__name__}); leaving the player alone", + why=why, rejected=rejected) + for k, n in (sc.get("why") or {}).items(): + why[k] = why.get(k, 0) + n + rejected += list(sc.get("rejected") or [])[:MAX_NAMED] cand = sc.get("candidate") if not cand: - return _fail(f"no usable release found: {sc.get('note')}", unsure=bool(sc.get("unsure"))) + if sc.get("unsure"): + soon() + return _fail(f"no usable release found: {sc.get('note')}", unsure=bool(sc.get("unsure")), + why=why, rejected=rejected) st.kv_set(db, key, 0) # found one: the cooldown is for misses return {"ok": True, "source": "unplanned", "nzb": cand["nzb"], "title": cand["title"], - "path": None, "dead_planned": dead_planned} + "resolution": cand.get("resolution"), "path": None, "dead_planned": dead_planned, + "why": why, "rejected": rejected, **taken} def _read_piece(reader, remote, off, n, what): @@ -194,7 +305,7 @@ def fail(reason, **detail): st.log_event(db, id, "substitute_start", {"source": pick["source"], "title": title}) nzb_path = pick["path"] or d.archive(pick["nzb"], title) try: - remote = d.importer.import_nzb(pick["nzb"], title) + remote = pick.get("remote") or d.importer.import_nzb(pick["nzb"], title) size = int(d.reader.size(remote)) lay = ops.plan_layout(share, size, d.head_frac) if d.head_frac is not None \ else ops.plan_layout(share, size) @@ -276,10 +387,31 @@ def undo(): d.notify(st.get(db, nid), new_share) except Exception as e: # noqa: BLE001 # best effort, like a restore's log.warning("%s: substitute notify failed: %s", id, type(e).__name__) - (d.spawn or _thread)(lambda: hash_build(db, nid, d)) + dbfile = _db_file(db) + + def hashing(): + # the build runs on another thread, and an sqlite3 connection belongs to the thread + # that made it: it gets its own + own = st.open_db(dbfile) if dbfile else db + try: + hash_build(own, nid, d) + finally: + if own is not db: + own.close() + (d.spawn or _thread)(hashing) return ops.Result(True, "failed", 0, ops.RESTORED_NOTE) +def _db_file(db) -> str: + r = db.execute("PRAGMA database_list").fetchone() + return (r["file"] if r else "") or "" + + +def no_spawn(fn): + """`Deps.spawn` for a process that ends soon (a by-hand switch): the hash build is not + started here. The manifest stays `pending` and the runner builds it (`_resume_hashes`).""" + + def _thread(fn): threading.Thread(target=fn, daemon=True, name="substitute-hash").start() @@ -307,31 +439,61 @@ def _swap_link(lib, new_lib, old_name, target): _hashing_mu = threading.Lock() -def hash_build(db, nid, d: Deps, *, stop: threading.Event | None = None) -> bool: +def hash_build(db, nid, d: Deps, *, stop: threading.Event | None = None) -> bool | None: """Read the whole middle once, record each chunk's BLAKE3 and refuse any chunk with a zero - run. On success write the chunk list and the final manifest and return True. On a zero run or - a read fault the manifest stays pending (tierfs keeps checking for zero runs) and an event - `substitute_hash_failed` says why.""" + run; the same pass makes the whole file's SHA-256 (the stub's head and tail are read from + disk and must still be what was written). On success the row gets its `sha256`, the chunk + list and the final manifest are written and it returns True: the row can be promoted like + any other. On a zero run or a read fault the manifest stays pending (tierfs keeps checking + for zero runs), the row keeps no `sha256` and an event `substitute_hash_failed` says why. + One build per id at a time: False when this process is already building it, None when + another process is (a by-hand switch beside the runner) or the row is not `offloaded` now + (retired by a later substitute, or failed by hand): nothing is read, and the caller may ask + again later.""" with _hashing_mu: if nid in _hashing: return False # already being built in this process _hashing.add(nid) try: - return _hash_build(db, nid, d, stop) + with ops._id_lock(db, f"{nid}.hash") as mine: + if not mine: + return None + return _hash_build(db, nid, d, stop) finally: with _hashing_mu: _hashing.discard(nid) +def _stub_part(stub, off, n, want_b3, sha, what): + """Feed [off, off+n) of the stub to `sha`. It must still be what the build wrote.""" + b3 = blake3.blake3() + with open(stub, "rb") as f: + f.seek(off) + left = n + while left: + b = f.read(min(ops.CHUNK, left)) + if not b: + raise ops.OpsError(f"the stub's {what} is short") + b3.update(b) + sha.update(b) + left -= len(b) + if b3.hexdigest() != want_b3: + raise ops.OpsError(f"the stub's {what} is not what was written") + + def _hash_build(db, nid, d, stop): row = st.get(db, nid) if row is None: return False + if row["state"] != "offloaded": + return None # a retired row is never read again: its whole file would be fetched for nothing remote, size = row["remote_path"], int(row["size"]) head, tail, cs = int(row["head_len"]), int(row["tail_len"]), ops.CHUNK_SIZE mid_end = size - tail sums, off = [], head + sha = hashlib.sha256() try: + _stub_part(row["stub_path"], 0, head, row["head_b3"], sha, "head") while off < mid_end: if stop is not None and stop.is_set(): return False @@ -342,12 +504,22 @@ def _hash_build(db, nid, d, stop): if has_zero_run(raw): raise ops.OpsError(f"missing segments at {off}") sums.append(blake3.blake3(raw).digest()) + sha.update(raw) off += n + _stub_part(row["stub_path"], mid_end, tail, row["tail_b3"], sha, "tail") except Exception as e: # noqa: BLE001 log.error("%s: substitute hash build stopped: %s", nid, e) st.log_event(db, nid, "substitute_hash_failed", {"reason": str(e)[:200], "offset": off}) return False blob = b"".join(sums) + # the row's sha256 first, the manifest last: a stop in between leaves the manifest pending, + # so the build runs again; a row never has a final manifest without its sha256 + with db: + cur = db.execute("UPDATE files SET sha256=?, updated_ts=? WHERE id=?", + (sha.hexdigest(), time.time(), nid)) + if cur.rowcount != 1: + st.log_event(db, nid, "substitute_hash_failed", {"reason": "the row is gone"}) + return False ops.write_chunks(d.manifest_dir, nid, blob) try: with open(ops.manifest_path(d.manifest_dir, nid)) as f: @@ -358,7 +530,7 @@ def _hash_build(db, nid, d, stop): man.pop("pending", None) man["chunks_b3"] = blake3.blake3(blob).hexdigest() ops.write_manifest(d.manifest_dir, man) - st.log_event(db, nid, "substitute_hashed", {"chunks": len(sums)}) + st.log_event(db, nid, "substitute_hashed", {"chunks": len(sums), "sha256": True}) log.info("%s: substitute hash build done (%d chunks)", nid, len(sums)) return True @@ -368,9 +540,13 @@ def substitute_release(db, row, d: Deps, apply=True) -> ops.Result: `restore` callable `switch_live` and `auto_switch` take (signature `(db, row, apply, keep_name)` via `make_restore`). A failure changes nothing and its reason says why the player was left.""" pick = choose(db, row, d) + said = {"why": pick.get("why") or {}, "rejected": (pick.get("rejected") or [])[:MAX_NAMED]} if not pick["ok"]: - st.log_event(db, row["id"], "substitute_failed", {"reason": pick["reason"]}) + st.log_event(db, row["id"], "substitute_failed", {"reason": pick["reason"], **said}) return ops.Result(False, row["state"], int(row.get("step") or 0), pick["reason"]) + st.log_event(db, row["id"], "substitute_pick", { + "source": pick["source"], "title": pick["title"], "resolution": pick.get("resolution"), + **(pick.get("facts") or {}), **said}) if not apply: return ops.Result(True, row["state"], 0, f"dry run: would switch to the {pick['source']} " "release", dry_run=True) diff --git a/tiering/offload/switch_live.py b/tiering/offload/switch_live.py index fd73dc6..276180e 100644 --- a/tiering/offload/switch_live.py +++ b/tiering/offload/switch_live.py @@ -285,7 +285,9 @@ def check(row, plex, out=print): def switch_live(db, row, plex, *, apply, restore, path_map=None, tierfs_mount=None, server_url=None, mapper=default_map, sleep=time.sleep, clock=time.monotonic, scan_timeout=SCAN_TIMEOUT_S, confirm_timeout=CONFIRM_TIMEOUT_S): - """Returns {'switched': [machine...], 'left': {machine: reason}, 'note': str}. Never raises + """Returns {'switched': [machine...], 'left': {machine: reason}, 'note': str} and, once a + player is seen on the new file, 'took_s': the seconds from the start of the restore to that + sighting (the longest of the players) with 'confirmed': how many were seen. Never raises for a Plex or player problem; a player that is not switched stays on the old file.""" id = row["id"] res = {"switched": [], "left": {}, "note": ""} @@ -326,6 +328,7 @@ def switch_live(db, row, plex, *, apply, restore, path_map=None, tierfs_mount=No lib, why = ops._resolve_lib(row["lib_path"], path_map) if not why and os.path.islink(lib): old_path = os.readlink(lib) + t0 = clock() if not already: r = restore(db, row, True, True) if not r.ok: @@ -400,6 +403,8 @@ def switch_live(db, row, plex, *, apply, restore, path_map=None, tierfs_mount=No except PlexRCError: now = None if now and size in now["part_sizes"]: + res["took_s"] = round(clock() - t0, 1) + res["confirmed"] = res.get("confirmed", 0) + 1 break sleep(2.0) else: @@ -429,7 +434,8 @@ def _classify(res): def auto_switch(db, row, plex, *, apply, restore, search=False, **kw): """The automatic trigger: a chunk of the row cannot be repaired, so move whoever watches it onto the restore-path release. Returns {"outcome": one of OUTCOMES or None, "detail": str, - "switched": [machines]}. Outcome None means there was nothing to decide (no session is + "switched": [machines]} and, for a switch a player confirmed, "took_s" and "confirmed" as + `switch_live` gives them (they are in the event too). Outcome None means there was nothing to decide (no session is playing the row, or the restore is busy): no event, nothing changed. Otherwise one event row `auto_switch` with the outcome is written. Reuses `switch_live` for the whole flow, so the order (restore, metadata wait, offset mapping, playMedia) and the rule "never a wrong @@ -441,12 +447,12 @@ def auto_switch(db, row, plex, *, apply, restore, search=False, **kw): player are decided before anything is restored. A dry run changes nothing.""" id = row["id"] - def done(outcome, detail, switched=()): + def done(outcome, detail, switched=(), **timing): if outcome: st.log_event(db, id, "auto_switch", {"outcome": outcome, "detail": detail, - "switched": len(switched)}) + "switched": len(switched), **timing}) log.info("auto switch %s: %s (%s)", id, outcome, detail) - return {"outcome": outcome, "detail": detail, "switched": list(switched)} + return {"outcome": outcome, "detail": detail, "switched": list(switched), **timing} try: sess = find_sessions(plex, row.get("lib_path")) @@ -473,7 +479,8 @@ def done(outcome, detail, switched=()): except PlexRCError as e: return done("no_player_control", f"plex call failed ({e})") if res["switched"]: - return done("switched", res["note"] or "players moved", res["switched"]) + timing = {k: res[k] for k in ("took_s", "confirmed") if k in res} + return done("switched", res["note"] or "players moved", res["switched"], **timing) why = "; ".join([res.get("note", "")] + sorted(res["left"].values())).strip("; ") if ops._BUSY in why: return {"outcome": None, "detail": "busy", "switched": []} diff --git a/tiering/offload/tests/test_substitute_real_path.py b/tiering/offload/tests/test_substitute_real_path.py new file mode 100644 index 0000000..ad67189 --- /dev/null +++ b/tiering/offload/tests/test_substitute_real_path.py @@ -0,0 +1,237 @@ +"""The live substitute through the code a user's play really hits, with nothing stubbed between +the steps: `--mark-failed` and `--switch-live` by hand (runner.main -> Runner._switch -> +switch_live.auto_switch -> substitute.substitute_release), the hash build the runner resumes, +and then a real ops.promote of the substituted row. Real sqlite, a real stub, manifest, chunk +list and library link in a temp dir. The bytes are made here at run time: there is no media +file and no recorded answer. Only the two far ends are stand-ins, because CI has no Usenet and +no Plex: the reader that serves the release's bytes, and Plex's HTTP answers.""" +import hashlib +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, "..", "..", "..")) + +import pytest # noqa: E402 +import test_substitute as TS # noqa: E402 + +OLD = "aaaaaaaaaaaaaaaa" +MIB = TS.MIB + + +@pytest.fixture(autouse=True) +def _forget_lazy_imports(): + import offload + had = {k for k in sys.modules if k.startswith("offload.")} + attrs = set(vars(offload)) + yield + for k in [k for k in sys.modules if k.startswith("offload.") and k not in had]: + sys.modules.pop(k, None) + for name in set(vars(offload)) - attrs: + delattr(offload, name) + + +def promote(w, id, reader=None): + from offload import ops + return ops.promote(w.db, id, reader or w.reader, apply=True, + manifest_dir=str(w.tmp / "man")) + + +def lib_bytes(w): + with open(w.lib, "rb") as f: + return f.read() + + +# ---- a: a substituted row gets its integrity record and is promoted like any row + +def test_substituted_row_gets_a_sha256_and_promotes_like_any_row(tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch) + assert w.sub.substitute_release(w.db, w.row, w.deps).ok + row = TS.new_row(w) + assert not row.get("sha256") and TS.man(w, row["id"])["pending"] is True + # until the build ends there is nothing to check a fetch against: promote changes nothing + r = promote(w, row["id"]) + assert not r.ok and w.st.get(w.db, row["id"])["state"] == "offloaded" + assert os.path.islink(w.lib) + w.bg[0]() + row = TS.new_row(w) + assert row["sha256"] == hashlib.sha256(TS.DATA).hexdigest() + assert "pending" not in TS.man(w, row["id"]) + r = promote(w, row["id"]) + assert r.ok and r.state == "whole", r.reason + assert not os.path.islink(w.lib) and lib_bytes(w) == TS.DATA + assert w.st.get(w.db, row["id"])["state"] == "whole" + kinds = [e["kind"] for e in w.st.events(w.db, row["id"])] + assert "substitute_hashed" in kinds and "promote_start" in kinds + + +def test_promote_of_a_substituted_row_refuses_bytes_that_were_not_hashed(tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch) + assert w.sub.substitute_release(w.db, w.row, w.deps).ok + w.bg[0]() + row = TS.new_row(w) + bad = bytearray(TS.DATA) + bad[row["head_len"] + 5 * MIB + 17] ^= 0xFF # the remote serves something else later + r = promote(w, row["id"], TS.Reader({TS.NEW_REMOTE: bytes(bad)})) + assert not r.ok and r.reason == "chunk mismatch" + assert os.path.islink(w.lib) # nothing was swapped over the library name + + +def test_hash_build_refuses_a_stub_whose_head_changed(tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch) + assert w.sub.substitute_release(w.db, w.row, w.deps).ok + row = TS.new_row(w) + with open(row["stub_path"], "r+b") as f: + f.seek(4096) + f.write(b"\xff\xfe\xfd") + w.bg[0]() + row = TS.new_row(w) + assert not row.get("sha256") and TS.man(w, row["id"])["pending"] is True + ev = [e for e in w.st.events(w.db, row["id"]) if e["kind"] == "substitute_hash_failed"] + assert ev and "head" in ev[0]["detail"]["reason"] + + +def test_hash_build_runs_once_across_processes(tmp_path, monkeypatch): + from offload import ops + w = TS.world(tmp_path, monkeypatch) + assert w.sub.substitute_release(w.db, w.row, w.deps).ok + nid = TS.new_row(w)["id"] + with ops._id_lock(w.db, f"{nid}.hash") as held: # another process is building it + assert held + assert w.sub.hash_build(w.db, nid, w.deps) is None + assert TS.man(w, nid)["pending"] is True + assert w.sub.hash_build(w.db, nid, w.deps) is True + + +# ---- b: `--switch-live` by hand is the automatic switch's path + +def hand(tmp_path, monkeypatch, w, apply=True): + """The by-hand command's settings and deps on the world `w`: the runner's own Deps, the + real substitute as its switch target, and the hash build left to the runner.""" + import test_auto_switch as A + from offload import ops, runner + from offload import switch_live as sl + monkeypatch.setattr(A, "NEW_SIZE", TS.SIZE) + monkeypatch.setattr(sl, "SCAN_POLL_S", 0.0) + (tmp_path / "ev").mkdir(exist_ok=True) + env = {"TIERING_DB": str(tmp_path / "t.db"), "TIERING_ALERTS": str(tmp_path / "alerts.jsonl"), + "TIERFS_STUB_ROOTS": str(tmp_path / "stubs"), "TIERFS_MOUNT": str(tmp_path / "stubs"), + "TIERFS_MANIFESTS": str(tmp_path / "man"), + "TIERFS_EVENTS": str(tmp_path / "ev" / "events.jsonl"), + "TIERING_GATE_PATH_MAP": f"{tmp_path / 'lib'}=/data"} + if apply: + env["TIERING_APPLY"] = "1" + w.deps.spawn = w.sub.no_spawn # as wiring.substitute_deps(short_lived=True) sets it + h = TS.W() + h.promoted = [] + + def do_promote(db, row, apply): + h.promoted.append(row["id"]) + return ops.promote(db, row["id"], w.reader, apply=apply, manifest_dir=env["TIERFS_MANIFESTS"]) + + h.deps = runner.Deps(w.st, do_promote, None, None, None, + substitute=w.sub.make_restore(w.deps), + hash_resume=lambda db, id: w.sub.hash_build(db, id, w.deps)) + h.env, h.runner, h.fp, h.clock = env, runner, A.FakePlex(w.lib), A.Clock() + h.kw = dict(plex=h.fp.plex, mapper=A.ok_map, sleep=h.clock.sleep, clock=h.clock.now, + scan_timeout=20, confirm_timeout=6) + return h + + +def alerts(h): + try: + with open(h.env["TIERING_ALERTS"]) as f: + return [json.loads(x) for x in f if x.strip()] + except OSError: + return [] + + +def test_by_hand_switch_is_the_substitute_path_and_the_row_is_normal_afterwards( + tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch, planned=None) # no planned alternative: a live search + h = hand(tmp_path, monkeypatch, w) + # the release is made unobtainable the way the owner does it: no row is edited here + assert h.runner.main(["--mark-failed", OLD], env=h.env, deps=h.deps) == 0 + assert w.st.get(w.db, OLD)["state"] == "failed" + assert h.runner.switch_main(["--switch-live", OLD], h.env, h.deps, **h.kw) == 0 + assert len(h.fp.sent("/player/playback/playMedia")) == 1 + assert len(w.scored) == 1 # the indexers were asked: the search path, not a full restore + row = TS.new_row(w) + assert row["id"] != OLD and row["state"] == "offloaded" + assert os.path.basename(os.readlink(w.lib)) == f"{row['id']}.mkv" # same name, no local copy + assert os.stat(row["stub_path"]).st_blocks * 512 < TS.SIZE + # the owner is told, and the event holds how long the swap took + a = [x for x in alerts(h) if x["kind"] == "auto_switch"] + assert len(a) == 1 and a[0]["id"] == OLD and a[0]["why"] == "by hand" and "took_s" in a[0] + ev = [e["detail"] for e in w.st.events(w.db, OLD) if e["kind"] == "auto_switch"] + assert ev[-1]["outcome"] == "switched" and ev[-1]["confirmed"] == 1 and "took_s" in ev[-1] + assert [e for e in w.st.events(w.db, OLD) if e["kind"] == "substitute_pick"] + # the by-hand process left the hash build to the runner: its promote waits, with no failure + assert TS.man(w, row["id"])["pending"] is True and not w.bg + cfg = h.runner.Config.from_env(h.env) + run = h.runner.Runner(cfg, h.deps) + run._promote_one(run.db(), row["id"], row) + assert h.promoted == [] and run.fails == {} and not alerts(h)[1:] + run._resume_hashes() + run.join() + assert "pending" not in TS.man(w, row["id"]) + row = TS.new_row(w) + assert row["sha256"] == hashlib.sha256(TS.DATA).hexdigest() + run._promote_one(run.db(), row["id"], row) + assert h.promoted == [row["id"]] and run.fails == {} + assert w.st.get(w.db, row["id"])["state"] == "whole" + assert not os.path.islink(w.lib) and lib_bytes(w) == TS.DATA + + +def test_a_substitute_that_is_no_longer_the_rows_file_is_not_fetched_for_its_hash( + tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch) + h = hand(tmp_path, monkeypatch, w) + assert w.sub.substitute_release(w.db, w.row, w.deps).ok # hash build left to the runner + nid = TS.new_row(w)["id"] + assert h.runner.main(["--mark-failed", nid], env=h.env, deps=h.deps) == 0 + n = len(w.reader.reads) + assert w.sub.hash_build(w.db, nid, w.deps) is None + run = h.runner.Runner(h.runner.Config.from_env(h.env), h.deps) + run._resume_hashes() + run.join() + assert len(w.reader.reads) == n and not run.hash_resumed # nothing was read for it + assert TS.man(w, nid)["pending"] is True + assert h.runner.main(["--mark-failed", nid, "--undo"], env=h.env, deps=h.deps) == 0 + run._resume_hashes() # the row's file again: built at the next pass + run.join() + assert "pending" not in TS.man(w, nid) and TS.new_row(w)["sha256"] + + +def test_by_hand_switch_with_no_candidate_tells_the_owner_and_leaves_the_row( + tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch, planned_stat="missing", found=None) + h = hand(tmp_path, monkeypatch, w) + assert h.runner.main(["--mark-failed", OLD], env=h.env, deps=h.deps) == 0 + before = w.st.get(w.db, OLD) + assert h.runner.switch_main(["--switch-live", OLD], h.env, h.deps, **h.kw) == 1 + assert not h.fp.sent("/player/playback/playMedia") and not w.importer.calls + after = w.st.get(w.db, OLD) + assert {k: after[k] for k in after if k != "updated_ts"} == \ + {k: before[k] for k in before if k != "updated_ts"} + assert os.path.basename(os.readlink(w.lib)) == f"{OLD}.mkv" + assert os.listdir(str(tmp_path / "man")) == [] + a = [x for x in alerts(h) if x["kind"] == "auto_switch_no_restore_path"] + assert len(a) == 1 and a[0]["id"] == OLD and "no usable release" in a[0]["reason"] + ev = [e["detail"] for e in w.st.events(w.db, OLD) if e["kind"] == "substitute_failed"] + assert ev and ev[-1]["why"] == {"articles gone": 1} # the planned one, and why it was dropped + # the row is back as it was with the owner's own undo + assert h.runner.main(["--mark-failed", OLD, "--undo"], env=h.env, deps=h.deps) == 0 + assert w.st.get(w.db, OLD)["state"] == "offloaded" + + +def test_by_hand_dry_run_changes_nothing(tmp_path, monkeypatch): + w = TS.world(tmp_path, monkeypatch) + h = hand(tmp_path, monkeypatch, w, apply=False) + assert h.runner.switch_main(["--switch-live", OLD], h.env, h.deps, **h.kw) == 0 + assert not h.fp.sent("/player/playback/playMedia") and not w.importer.calls + assert w.st.get(w.db, OLD)["state"] == "offloaded" and not alerts(h) + ev = [e["detail"] for e in w.st.events(w.db, OLD) if e["kind"] == "auto_switch"] + assert ev[-1]["outcome"] == "dry_run" diff --git a/tiering/offload/tests/test_switch_live.py b/tiering/offload/tests/test_switch_live.py index 31ff095..1ea459c 100644 --- a/tiering/offload/tests/test_switch_live.py +++ b/tiering/offload/tests/test_switch_live.py @@ -281,9 +281,8 @@ def test_check_lists_sessions_and_control(env): def test_cli_check_and_dry_run(env, tmp_path, capsys): - deps = type("D", (), {})() - deps.state = st - deps.restore = env.restore + # by hand is the automatic switch's own path: the runner's deps, with the substitute + deps = runner.Deps(st, None, None, None, None, restore=env.restore, substitute=env.restore) e = {"TIERING_DB": str(tmp_path / "t.db")} st.upsert(env.db, {"id": "abc", "lib_path": LIB, "state": "offloaded", "size": OLD_SIZE}) fp = FakePlex() diff --git a/tiering/offload/wiring.py b/tiering/offload/wiring.py index dadbaf4..f6649ef 100644 --- a/tiering/offload/wiring.py +++ b/tiering/offload/wiring.py @@ -135,12 +135,13 @@ def ok() -> bool: return ok -def substitute_deps(cfg, env=None): - """The live substitute's dependencies (`substitute.Deps`) on the shared clients.""" +def substitute_deps(cfg, env=None, short_lived=False): + """The live substitute's dependencies (`substitute.Deps`) on the shared clients. + `short_lived`: the caller's process ends soon, so the hash build is left to the runner.""" e = dict(os.environ if env is None else env) c = clients(e) - qualify, sub, nz, ops, notify = (_mod(n) for n in - ("qualify", "substitute", "newznab", "ops", "notify")) + qualify, sub, nz, ops, notify, probe = ( + _mod(n) for n in ("qualify", "substitute", "newznab", "ops", "notify", "probe")) providers = qualify.present((("secondary", c.stat_secondary), ("primary", c.stat_primary))) dead: dict = {} @@ -153,4 +154,7 @@ def stat_raw(raw): archive=lambda raw, title: nz.archive_nzb(raw, c.archive, title), ids_of=nz.nzb_segment_ids, score=qualify.score_restore, notify=notify.notify_from_env(), manifest_dir=cfg.manifests, - tierfs_mount=cfg.tierfs_mount, path_map=cfg.path_map) + tierfs_mount=cfg.tierfs_mount, path_map=cfg.path_map, + fit=qualify.Fit, probe=probe.probe_bytes, spawn=sub.no_spawn if short_lived else None, + runtime_tol_s=float(e.get("SUBSTITUTE_RUNTIME_TOL_S") or sub.RUNTIME_TOL_S), + runtime_tol_frac=float(e.get("SUBSTITUTE_RUNTIME_TOL_FRAC") or sub.RUNTIME_TOL_FRAC)) From 5fde8954238d9682a5dbedf64a8b5765916228a6 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:51:56 -0800 Subject: [PATCH 8/9] e2e: the live substitute on the real stack (D G E F H N), and offload the try row now - D, G, E, F, H make the release unobtainable the way the owner does (--mark-failed), play the row on the real player and run --switch-live by hand. They check that the play goes on and how long it took, that Plex keeps the item, that the arr keeps its file and grabs nothing, that the pick is the same cut, that the new row is a normal row, that only the owner is told, and that nothing changes when no candidate qualifies. N waits for the runner's hash build and promote of the new row. No event is injected any more. - The try row is followed through a substitute to its newest row (harness, re-arm). - offload_try_row.py runs the runner's own single demote for the try row while the runner is paused, so a used row is cold again without waiting for a night. --- tests/e2e/README.md | 64 +++- tests/e2e/offload_try_row.py | 245 ++++++++++++++ tests/e2e/plex_e2e.py | 629 +++++++++++++++++++++++++++++------ tests/e2e/rearm_try_row.py | 39 ++- 4 files changed, 865 insertions(+), 112 deletions(-) create mode 100644 tests/e2e/offload_try_row.py diff --git a/tests/e2e/README.md b/tests/e2e/README.md index e71fc60..98f3657 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -13,6 +13,10 @@ server's own token (inside the tiering container); it never touches plex.tv. - `rearm_try_row.py` (in the tiering container) retires a consumed try row and picks a new one. Its header says what it writes and how to put it back. Without `REARM_APPLY=1` it stops before the first search; with `REARM_VERDICT_ONLY=1` it only says what it would do with the old try row (`old try row verdict: retire|keep|abort|none`). +- `offload_try_row.py` (in the tiering container, only while the runner is paused) offloads the try row now through the + runner's own single-demote code, so a used row is cold again without waiting for a night. Its header lists the rules + that still apply (the allowlist, the glacier gate, the full qualify) and the three that do not (the hot set, the rules + of a pass, the night record outside the window). Without `OFFLOAD_APPLY=1` it stops after its checks. - `llm_shadow_check.py` (in the arr-webhook container) is scenario L, read-only. Scenarios run only on the real server, through runner jobs. They are never run in CI and never against made-up data. @@ -26,11 +30,13 @@ Scenarios run only on the real server, through runner jobs. They are never run i | B | `--switch-live --check` during the play, read-only | player | unchanged | | I | control port closed: player left alone, no restore | player | unchanged | | C | whole-file download of the offloaded try row via the part endpoint: want events, promote, SHA-256 equals the manifest | offloaded try row | whole | -| D | bad chunk ahead of the play position: EIO or stall, never bad bytes; the trigger fires | substitute PR | used | -| E | planned alternative live: player moves to the usenet substitute, offset keeps advancing, no full local copy, row carries the new release | substitute PR | used | -| F | planned alternative dead: unplanned release found by a live search | substitute PR | used | -| G | no alternative: player left alone, alert raised (simulated, nothing real broken) | substitute PR | used | -| H | the same switch while paused | substitute PR | used | +| D | the release cannot be fetched (the row is failed by hand) and nothing has taken its place: a play past the head waits, gets no zero-filled bytes, and its session does not end | substitute PR, offloaded try row | offloaded (put back) | +| G | nothing qualifies: the real search runs, every candidate is dropped (G sets a run-time tolerance no file meets). Check 7 | substitute PR, offloaded try row | offloaded (put back) | +| E | the planned alternative takes the row's place during the play. Checks 1 to 6 | substitute PR, a row with a planned alternative | a new offloaded row | +| F | no planned alternative: a live indexer search finds the copy. Checks 1 to 6 | substitute PR, a row without a planned alternative (the one E leaves) | a new offloaded row | +| H | the same switch while the player is paused. Checks 1 to 6 | substitute PR | a new offloaded row | +| N | the row a substitute left is a normal row: the live runner builds its hash, then promotes it, while the play goes on. Check 5 | a substituted try row, the runner running | whole | +| fail, unfail | steps for a job: mark the try row failed by hand (so a live runner fetches nothing), and undo it | offloaded try row | failed / offloaded | | P | Plex's own tasks: media analysis of the item, then a scan of its folder. No reader may ask for the whole file; the row stays offloaded; Plex keeps the item under the same key | offloaded try row | offloaded | | R | the arr refreshes and rescans the item: it still lists the same file at full size, the link is still ours, nothing is fetched | offloaded try row, Radarr | offloaded | | audit | every row that is not whole has its link, stub and manifest; no manifest lacks a row | nothing | unchanged | @@ -42,7 +48,38 @@ Scenarios run only on the real server, through runner jobs. They are never run i | T | server transcode pulled as an HLS client: a forced lower bitrate (video re-encoded), then another container with the streams copied | nothing (no player) | whole | | L | `llm_shadow_check.py`: the LLM layer is in shadow mode and every decision written during the run is a shadow row | arr-webhook | unchanged | -D to H skip unless `E2E_SUBSTITUTE=1`. Never run `--switch-live` without `--check` except on the try row. +D to H and N skip unless `E2E_SUBSTITUTE=1`. Never run `--switch-live` without `--check` except on the try row. + +## The live substitute: what "the viewer does not notice" means + +When the release behind an offloaded file cannot be fetched back, the next best copy takes its place. D, G, E, F, H and N +check that on the real stack. Nothing is made up: the release is made unobtainable the way the owner does it +(`runner --mark-failed `: the row is failed, so nothing fetches it), the real player plays it, and the by-hand +`runner --switch-live ` runs. That command and the automatic switch are one code path (`Runner._switch`), so the +scenarios exercise the code a viewer hits. The numbered checks, as the scenarios print them: + +1. The play goes on: the session moves to the new file, the picture moves again, and the time from the start of the + switch to that moment is printed and must be inside `E2E_SWAP_BUDGET_S` (900 s, the wait tierfs gives a read before + it fails). The server may not lose the session for longer than `E2E_GAP_S`. In D, with no copy yet, the play waits. +2. Plex keeps the item: the same rating key, one media with one part of the new size, nothing reported missing, the + watched count, the match and the play position kept, and no second item for the title. +3. The arr keeps its file: after its rescan it holds a file of the new size in the same folder, with nothing queued, + no new grab in its history and no cutoff newly unmet. +4. The pick is the same cut: the run times of both files (from their first bytes) agree, the first sound track has the + same language, Plex's own analysis of the new file agrees on both, and the picture height is printed (equal or + better is preferred). Every dropped candidate carries its reason (counts on the PASS line, titles on DETAIL). +5. The new row is a normal row: offloaded on another release, no full local copy, its link in place, the old row + retired; then (N) a SHA-256, a final manifest, and a promote like any row. +6. Only the owner is told: the alerts file has the `auto_switch` line for the row and nothing else about it. +7. With no candidate (G): exit 1, a `substitute_failed` event with the reasons, an `auto_switch_no_restore_path` alert, + and the row, its manifest, its stub, its link, Plex's file and the arr's record all as they were. The player is left + waiting on its file. + +Order, on one offloaded try row: D, G, E, H with the runner paused (a paused runner cannot fetch the file back between +the steps), then `fail`, un-pause, F and N with the runner running. E uses the planned alternative; the row it leaves +has none, so H and F search live. A later switch may pick the release the first one left: any release that passes +check 4 is a valid pick. Each of E, H and F retires a row; the rows E and H leave are retired before anything read +them in full, and only the last one is hashed and promoted. `E2E_SUB_MAX` (3) caps the substitutes in 20 hours. ## One fetch per try row @@ -55,16 +92,21 @@ stays whole for 60 days. So one offloaded try row serves, in this order: Only the first scenario after a re-arm starts on the offloaded row. S goes first because it needs the middle not yet fetched; the others then run during or after the fetch. T may also run right after the play group without a new row: -it then proves a transcode during or after the fetch. For Z or T from cold, re-arm again (one night and one fetch each). -After step 2, run `rearm_try_row.py` and wait for the runner's nightly window to offload the new row. +it then proves a transcode during or after the fetch. For Z or T from cold, the row must be cold again (one fetch each). +After step 2 the row is whole. Either run `offload_try_row.py` on it (with the runner paused: it is offloaded again within +minutes), or run `rearm_try_row.py` and wait for the runner's nightly window to offload the new row. Never play a try row between its re-arm and its first demote: the runner keeps a played row whole for the idle window, so that row would never be offloaded. The re-arm retires such a row like a consumed one. The scenarios that play (A, I, C, S, W, M, K, Z, T) belong on an offloaded row, or on a used one that is about to be retired. -What each costs on Usenet: P, R, audit, L, up, A on a whole row, B, I: nothing. C, the play group, T from cold, D to H: -one fetch of the try file each (count it against the nightly re-download budget). F adds one live indexer search. -A re-arm: up to 6 searches and 3 NZB grabs, no article download. +What each costs on Usenet: P, R, audit, L, up, A on a whole row, B, I, D, fail, unfail: nothing. C, the play group and +T from cold: one fetch of the try file each (count it against the nightly re-download budget). G: one search per +indexer and up to 3 NZB grabs (the first bytes of each candidate, nothing more). E: the planned alternative's NZB is +already kept, so no search and no grab. H and F: one search per indexer and 1 to 4 grabs each. A switch itself reads +only what the player reads; the two reads of the whole file come afterwards, for the last row only (N: the hash build, +then the promote). `offload_try_row.py`: what one nightly demote costs (one search per indexer, the grabs of the restore +path, one read of the whole file). A re-arm: up to 6 searches and 3 NZB grabs, no article download. ## What should happen, per use diff --git a/tests/e2e/offload_try_row.py b/tests/e2e/offload_try_row.py new file mode 100644 index 0000000..d38dfbc --- /dev/null +++ b/tests/e2e/offload_try_row.py @@ -0,0 +1,245 @@ +"""Offload the try row now, through the runner's own single-demote code. A step for a job. + +Runs INSIDE the tiering container, and only while the runner is paused (the pause file): + + docker exec -i -e OFFLOAD_APPLY=1 tiering python3 -I - < offload_try_row.py + +Why it exists: the runner demotes only inside its nightly window and never a row in its hot set, +and the try row is hot from the first scenario that played it. So a played try row would stay +whole for the idle window, and each cold use would need a new row. This step makes the one row +cold again without waiting for a night. + +What runs is `Runner._demote_one` -> `Runner._demote_inner` of the deployed runner, for ONE id (the +try row of pick.json, or the row a substitute put in its place). Everything a nightly demote does +still applies: the TIERING_ONLY_PATHS allowlist, the single disk path, the head size, the +hard-link and symlink check, the damaged-file memory, the glacier gate (asked before and after +qualify), the full qualify (the local file and the copy on Usenet are both read in full, and a +restore path is searched), the row update, `ops.demote` and the runner's own bookkeeping. + +What is NOT applied, and nothing else: + * the hot set. No pass runs here, so the runner's list of wanted items is empty. The row was + played by a test, not by a viewer; this step refuses to run while Plex lists a session of it. + * the rules of a pass: the demote window, "the Plex read of this pass was complete", the play + history check, the weekly check and tonight's register. The one that is kept: it stops when + the runner's night record of the last 20 hours says a demote or promote failed. + * outside the window the runner has no night record (its code needs one), so this step gives + its own Runner object a private one. The runner's night file is then neither read for the + byte cap nor written. + +It can never race the runner: it stops unless the pause file exists, and it holds the runner's own +exclusive lock (`acquire_lock`) for as long as it runs. It stops when any row is offloading or +promoting. + +What it changes, only with OFFLOAD_APPLY=1: the try row's library file becomes an offloaded stub +(state `offloaded`), exactly as a nightly demote leaves it. Put back: any play, or the runner's +next pass (the row is hot), fetches the whole file back; `runner --restore ` does it by hand. +Nothing else is written. Without OFFLOAD_APPLY=1 it stops after the checks. + +Usenet use: what one nightly demote costs. One search per indexer and the NZB grabs of the restore +path (the row's own NZB is reused), article STATs, and one full read of the file from Usenet. + +Output follows plex_e2e.py: `PASS|FAIL|SKIP|INFO offload ` carry counts and states only; +`DETAIL` lines hold ids and the runner's log lines and go to syslog. Last line: +`OFFLOAD state= took_s=N`. +""" +import json +import logging +import os +import re +import sqlite3 +import sys +import time + +PICK = "/state/sync-test/pick.json" +GB = 10**9 + + +def say(kind, text): + print(f"{kind} offload {text}", flush=True) + + +def detail(text): + print(f"DETAIL offload: {text}", flush=True) + + +def done(state, t0, code=0): + print(f"OFFLOAD state={state} took_s={time.time() - t0:.0f}", flush=True) + return code + + +class Lines(logging.Handler): + """The runner's log lines: all of them to DETAIL, the reason of a skipped demote kept.""" + + def __init__(self, id): + super().__init__() + self.id, self.why = id, "" + + def emit(self, rec): + try: + msg = rec.getMessage() + except Exception: # noqa: BLE001 + return + detail(f"log {rec.levelname}: " + re.sub(r"(?i)(apikey|api_key|token|password|passwd)=[^&\s]+", r"\1=***", msg)) + m = re.match(r"demote \S+ (?:skipped|dropped[^:]*|not tonight|not done): (.*)$", msg) + if m: + self.why = re.sub(r"/\S+", "", m.group(1).replace(self.id, ""))[:90] + + +def newest_try(db): + """(id of the try row as it is now, substitutes that took its place).""" + try: + cur = (json.load(open(PICK)).get("try") or {}).get("id", "") + except (OSError, ValueError, AttributeError): + cur = "" + seen = {cur} + while cur and len(seen) < 20: + nid = "" + for (d,) in db.execute("SELECT detail FROM events WHERE id=? AND kind='restore_done' ORDER BY seq DESC", (cur,)): + try: + nid = str((json.loads(d) or {}).get("substitute") or "") + except (ValueError, AttributeError): + nid = "" + if nid: + break + if not nid or nid in seen or db.execute("SELECT 1 FROM files WHERE id=?", (nid,)).fetchone() is None: + break + seen.add(nid) + cur = nid + return cur, len(seen) - 1 + + +def main(): + t0 = time.time() + sys.path.insert(0, "/app") + from offload import plex_watch as pw, runner as R + + e = os.environ + apply = e.get("OFFLOAD_APPLY") == "1" + try: + cfg = R.Config.from_env() + except ValueError: + say("FAIL", "the runner's settings do not load; nothing done") + return done("unknown", t0, 1) + pause = e.get("SUPERVISE_PAUSE_FILE") or "/state/runner.paused" + if not os.path.exists(pause): + say("FAIL", "the runner is not paused (no pause file); nothing done") + return done("unknown", t0, 1) + if not cfg.apply: + say("FAIL", "TIERING_APPLY is not 1 in the container; nothing done") + return done("unknown", t0, 1) + if not cfg.only_spec.startswith("@"): + say("FAIL", "the allowlist is not an @file; nothing done") + return done("unknown", t0, 1) + lock = R.acquire_lock(cfg.db) + if lock is None: + say("FAIL", "a runner holds the lock (it is not stopped yet); nothing done") + return done("unknown", t0, 1) + try: + return offload(R, pw, cfg, apply, t0) + finally: + lock.close() + + +def offload(R, pw, cfg, apply, t0): + ro = sqlite3.connect(f"file:{cfg.db}?mode=ro", uri=True) + id, subs = newest_try(ro) + ro.close() + if not id: + say("FAIL", "pick.json names no try row; nothing done") + return done("unknown", t0, 1) + detail(f"try row id={id} (substitutes before it: {subs})") + + lines = Lines(id) + lines.addFilter(R.Redact()) + root = logging.getLogger() + root.addHandler(lines) + root.setLevel(logging.INFO) + try: + deps = R.load_deps(cfg, short_lived=True) + except Exception as ex: # noqa: BLE001 # a missing setting; the name of the error only + say("FAIL", f"the runner's modules do not load ({type(ex).__name__}); nothing done") + return done("unknown", t0, 1) + run = R.Runner(cfg, deps) + db = run.db() + run.refresh_only_paths() + run._load_persisted(db) + + rows = run.state.list_files(db) + row = next((r for r in rows if r["id"] == id), None) + if row is None: + say("FAIL", "the try row has no row in the state DB; nothing done") + return done("unknown", t0, 1) + state = row["state"] + busy = sum(1 for r in rows if r["state"] in ("offloading", "promoting")) + say("INFO", f"try row: state={state} size={(row.get('size') or 0) / GB:.1f} GB play time known={'yes' if row.get('play_ms') else 'no'} " + f"substitutes before it={subs}; rows offloading or promoting={busy}; allowlist paths={len(cfg.only_paths)}") + if state == "offloaded": + say("SKIP", "the try row is offloaded already; nothing done") + return done(state, t0) + if state != "whole": + say("FAIL", f"the try row is {state}, not whole; nothing done") + return done(state, t0, 1) + if busy: + say("FAIL", f"{busy} row(s) offloading or promoting; nothing done") + return done(state, t0, 1) + if not run._may_demote(row): + say("FAIL", "the try row's path is not on the allowlist (or the allowlist file cannot be read); nothing done") + return done(state, t0, 1) + try: + live = {str(s.get("ratingKey")) for s in pw.sessions()} + except Exception as ex: # noqa: BLE001 + say("FAIL", f"Plex could not be asked for its sessions ({type(ex).__name__}); nothing done") + return done(state, t0, 1) + if row.get("rating_key") is not None and str(row["rating_key"]) in live: + say("FAIL", "Plex lists a session of the try item; nothing done") + return done(state, t0, 1) + disk = run._resolve_disk(row) + if disk is None: + say("FAIL", "the try row has no single disk path; nothing done") + return done(state, t0, 1) + run.disk = {id: disk} + + now = time.time() + last = run._load_night() + if last.get("failed") and last.get("start") and now - float(last["start"]) < 20 * 3600: + say("FAIL", "the runner's night record says a demote or promote failed in the last 20 hours; look at that first. Nothing done") + return done(state, t0, 1) + in_window = R.night_start(now, cfg.window) is not None + if not in_window: + run.night = {"start": 0.0, "bytes": 0, "failed": False} + run._tonight = lambda _now: run.night + run._save_night = lambda: None + run.desired_rks = set() + + def block(_now, promotes_planned=False): + n = run._tonight(_now) + return "a demote or promote failed tonight" if n and n.get("failed") else "" + + run._demote_block = block + say("INFO", f"rules not applied: the hot set and the rules of a pass; night record: {'the one of the runner (inside the window)' if in_window else 'a private one (outside the window)'}") + if not apply: + say("SKIP", "OFFLOAD_APPLY is not 1: stopped after the checks; nothing done") + return done(state, t0) + + seq0 = db.execute("SELECT COALESCE(MAX(seq), 0) FROM events").fetchone()[0] + try: + run._demote_one(db, id, now) + except Exception as ex: # noqa: BLE001 + say("FAIL", f"the runner's demote raised {type(ex).__name__}") + detail(f"demote raised: {ex}") + kinds = {} + for (k,) in db.execute("SELECT kind FROM events WHERE id=? AND seq>? ORDER BY seq", (id, seq0)): + kinds[k] = kinds.get(k, 0) + 1 + row = run.state.get(db, id) or {} + state = row.get("state", "gone") + say("INFO", "events of the row: " + (", ".join(f"{k}={v}" for k, v in sorted(kinds.items())) or "none")) + if state == "offloaded": + say("PASS", f"the try row is offloaded by the runner's own demote ({time.time() - t0:.0f} s; " + f"restore path kept={'yes' if row.get('nzb_path2') else 'no'}, integrity hash={'yes' if row.get('sha256') else 'no'})") + return done(state, t0) + say("FAIL", f"the try row is {state}, not offloaded: {lines.why or 'the runner gave no reason'}") + return done(state, t0, 1) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/plex_e2e.py b/tests/e2e/plex_e2e.py index de21534..197eae1 100644 --- a/tests/e2e/plex_e2e.py +++ b/tests/e2e/plex_e2e.py @@ -11,13 +11,20 @@ Output: lines `PASS|FAIL|SKIP|INFO ` carry counts and states only. Lines that start with `DETAIL ` hold ids and are sent to syslog by the job, never to the runner log. -Scenarios: up, AB (A + B), I, stop, C, D, E, F, G, H, state, and the other ways Plex and the arrs use a +Scenarios: up, AB (A + B), I, stop, C, state; the live substitute (the release cannot be fetched, the +next best copy takes its place and the viewer does not notice): D (the play waits), G (nothing +qualifies), E (the planned alternative), F (a live search), H (a paused player), N (the new row is a +normal row), fail and unfail (steps for a job); and the other ways Plex and the arrs use a file: T (server transcode), S (seek past the head and back), Z (long pause, resume), M (two streams at once), P (Plex's own analysis and scan), R (arr refresh and rescan), K (audio and subtitle tracks), W (demotes hold while a watched file is fetched), audit (nothing left dangling). Environment: PLEX_URL, PLEX_TOKEN (container), TIERING_DB, TIERFS_EVENTS, TIERING_ALERTS (container); E2E_SERVER_URL (the server address the PLAYER can reach), E2E_PLAYER_ID, E2E_SUBSTITUTE=1 (the -substitute PR is deployed; D to H skip without it), E2E_WAIT_S (longest wait for bytes that are not +substitute PR is deployed; D to H and N skip without it), E2E_SWAP_BUDGET_S (longest time a switch may +take before the picture moves again, default 900: the wait tierfs gives a read), E2E_GAP_S (longest +time the server may list no session during a switch, default 45), E2E_SUB_MAX (substitutes allowed in +20 hours, default 3), E2E_D_WATCH_S (how long D watches the waiting play, default 150), E2E_N_WAIT_S +(how long N waits for the hash build and the promote, default 2400), E2E_WAIT_S (longest wait for bytes that are not local, default 600), E2E_PAUSE_S (pause length in Z, default 960), E2E_SECOND_MB (bytes the second stream reads in M, default 64), E2E_SECOND_ROLE (a pick.json role whose row M may read as a second file), E2E_WINDOW_S (how long W samples the runner, default 120), E2E_ATTACH_S (how long W waits for another @@ -30,6 +37,7 @@ import sqlite3 import subprocess import sys +import tempfile import threading import time import urllib.error @@ -124,7 +132,8 @@ def dbro(): return db -def try_id(): +def picked_id(): + """The id pick.json names as the try row.""" try: return (json.load(open("/state/sync-test/pick.json")).get("try") or {}).get("id", "") except (OSError, ValueError): @@ -136,6 +145,59 @@ def row_of(id): return dict(r) if r else None +def _substitute_of(id): + """The id of the row a substitute put in the place of `id`, or "".""" + for (d,) in dbro().execute("select detail from events where id=? and kind='restore_done' order by seq desc", (id,)): + try: + nid = str((json.loads(d) or {}).get("substitute") or "") + except (ValueError, AttributeError): + nid = "" + if nid: + return nid + return "" + + +def try_chain(): + """The try row's ids, oldest first: the one pick.json names, then each row a substitute put + in its place (a substitute retires the row and makes a new one for the same library file).""" + out = [picked_id()] + while out[-1] and len(out) < 20: + nid = _substitute_of(out[-1]) + if not nid or nid in out or not row_of(nid): + break + out.append(nid) + return out + + +def try_id(): + """The try row as it is now: the last row of the chain.""" + return try_chain()[-1] + + +def events_of(id, since_ts): + """[(kind, detail)] of the row's events since `since_ts`, oldest first.""" + out = [] + for k, d in dbro().execute("select kind, detail from events where id=? and ts>=? order by seq", (id, since_ts)): + try: + j = json.loads(d) if d else {} + except ValueError: + j = {} + out.append((k, j if isinstance(j, dict) else {})) + return out + + +def manifest_of(id): + """The row's tierfs manifest, or None.""" + d = os.environ.get("TIERFS_MANIFESTS", "") + if not d or not id: + return None + try: + with open(os.path.join(d, f"{id}.json")) as f: + return json.load(f) + except (OSError, ValueError): + return None + + def event_kinds(id, since_ts): return [r[0] for r in dbro().execute( "select kind from events where id=? and ts>=? order by seq", (id, since_ts))] @@ -164,9 +226,10 @@ def events_size(): return os.path.getsize(p) if p and os.path.exists(p) else 0 -def alert_kinds_since(ts): +def alerts_since(ts): + """The lines the runner wrote to the owner's alerts file since `ts` (each has kind and id).""" p = os.environ.get("TIERING_ALERTS", "") - out = {} + out = [] if not p or not os.path.exists(p): return out with open(p, "rb") as f: @@ -175,11 +238,18 @@ def alert_kinds_since(ts): try: j = json.loads(ln) t = float(j.get("ts") or 0) - except (ValueError, TypeError): + except (ValueError, TypeError, AttributeError): continue if t >= ts: - k = str(j.get("kind") or j.get("type") or "?")[:30] - out[k] = out.get(k, 0) + 1 + out.append(j) + return out + + +def alert_kinds_since(ts): + out = {} + for j in alerts_since(ts): + k = str(j.get("kind") or j.get("type") or "?")[:30] + out[k] = out.get(k, 0) + 1 return out @@ -344,6 +414,11 @@ def sc_state(): say("INFO", "state", f"try row state={row['state']} size_gb={round((row['size'] or 0) / 1e9, 1)} " f"nzb_path={'yes' if row.get('nzb_path') else 'no'} nzb_path2={'yes' if row.get('nzb_path2') else 'no'} " f"twin={'yes' if row.get('twin_nzb_path') else 'no'} rating_key={'yes' if row.get('rating_key') else 'no'}") + man = manifest_of(id) + say("INFO", "state", f"substitutes that took the try row's place so far: {len(try_chain()) - 1}; " + f"note={'by hand' if row.get('restore_note') == HAND_NOTE else ('yes' if row.get('restore_note') else 'none')} " + f"sha256={'yes' if row.get('sha256') else 'no'} " + f"manifest={'none' if man is None else ('waits for the hash build' if man.get('pending') else 'final')}") plex = Plex() say("INFO", "state", f"player listed: {'yes' if player_client(plex) else 'no'}; " f"sessions on the server: {len(plex.mc('/status/sessions').get('Metadata') or [])}") @@ -501,9 +576,24 @@ def sc_c(): say("INFO", "C", f"alerts during the run: {alert_kinds_since(t0) or 'none'}") -# ---- scenarios that need the substitute PR -------------------------------------------------- - -def _sub_common(scn, need_alt): +# ---- the live substitute: D, G, E, F, H, N ----------------------------------------------------- +# +# What they prove: when the release behind an offloaded file cannot be fetched, the next best copy +# takes its place and the viewer does not notice. Each one makes the release unobtainable the way +# the owner does it (`--mark-failed`: the row is failed, so nothing fetches it), plays the row on +# the real player and then runs the by-hand `--switch-live`, which is the automatic switch's own +# code path. The checks are numbered as in the README: 1 the play goes on, 2 Plex keeps the item, +# 3 the arr keeps its file and grabs nothing, 4 the pick is the same cut, 5 the new row is a +# normal row, 6 only the owner is told, 7 with no candidate nothing changes. +# What they change: the try row only. A swap retires the row and puts a new one (a new id, the +# same library path) in its place: that is the product's result and is not undone. A scenario in +# which no swap happens puts the row back with `--mark-failed --undo`, after stopping the play. + +HAND_NOTE = "marked failed by hand" +SWAP_NOTE = "restored from the restore path" + + +def _sub_common(scn, mode): if os.environ.get("E2E_SUBSTITUTE") != "1": say("SKIP", scn, "waits for the substitute PR (set E2E_SUBSTITUTE=1 once it is deployed)") return None @@ -511,12 +601,23 @@ def _sub_common(scn, need_alt): if not s: return None plex, id, row = s - if row["state"] != "offloaded": - say("SKIP", scn, f"the try row is {row['state']}, not offloaded (re-arm a try row first)") + held = row["state"] == "failed" and row.get("restore_note") == HAND_NOTE + if row["state"] != "offloaded" and not held: + say("SKIP", scn, f"the try row is {row['state']}, not offloaded (offload or re-arm a try row first)") + return None + if mode == "E" and not row.get("nzb_path2"): + say("SKIP", scn, "the try row has no planned alternative (nzb_path2); F covers the live search") return None - if need_alt and not row.get("nzb_path2"): - say("SKIP", scn, "the try row has no planned alternative (nzb_path2)") + if mode == "F" and row.get("nzb_path2"): + say("SKIP", scn, "the try row has a planned alternative, so no live search would run: run E first (the row it leaves has none)") return None + if mode in ("E", "F", "H"): + n = dbro().execute("select count(*) from events where kind='substituted' and ts>=?", + (time.time() - 20 * 3600,)).fetchone()[0] + cap = _int(os.environ.get("E2E_SUB_MAX"), 3) + if n >= cap: + say("SKIP", scn, f"{n} substitutes in the last 20 hours: the cap of {cap} is reached") + return None return plex, id, row @@ -530,129 +631,461 @@ def _play_near_head_end(plex, row): return st, ses, off -def _switch_and_check(scn, plex, id, row, ses, expect_switch=True, extra_env=None): - before = row_of(id) - t0 = time.time() - sizes0 = ses["sizes"] - rc, out = runner_cmd(["--switch-live", id], extra_env) - detail(f"{scn}: switch-live exit {rc}: {out[-800:]}") - s2 = None - end = time.time() + 120 - while time.time() < end: - s2 = my_session(plex) - if s2 and s2["sizes"] != sizes0: - break +def _stop_and_wait(plex, timeout=40): + """Stop the play and wait until the server lists no session of the player.""" + player_cmd(plex, "/player/playback/stop", {"type": "video"}) + end = time.time() + timeout + while time.time() < end and my_session(plex): time.sleep(3) - after = row_of(id) - if expect_switch: - check(scn, s2 is not None and s2["sizes"] != sizes0, "the session shows the new part (size changed)") - if s2 and s2["sizes"] != sizes0: - a, b, adv = advancing(plex, row["rating_key"]) - check(scn, adv, f"viewOffset keeps advancing on the substitute ({a['vo'] // 1000}s -> {b['vo'] // 1000}s)") - sib = [f for f in os.listdir(os.path.dirname(row["lib_path"]))] if os.path.isdir(os.path.dirname(row["lib_path"] or "")) else None - if sib is not None: - big = [f for f in sib if os.path.getsize(os.path.join(os.path.dirname(row["lib_path"]), f)) > _int(row["size"]) // 2 - and os.path.join(os.path.dirname(row["lib_path"]), f) != row["lib_path"]] - check(scn, not big, f"no full local copy was written beside the library file ({len(big)} large extra files)") - changed = [k for k in ("nzb_path", "remote_path", "size", "release_name") if before.get(k) != after.get(k)] - check(scn, bool(changed), f"the row carries the new release (fields changed: {changed})") - else: - check(scn, s2 is not None and s2["sizes"] == sizes0, "the player was left alone (same part)") - al = alert_kinds_since(t0) - check(scn, bool(al), f"an alert was raised: {al or 'none'}") - check(scn, not [k for k in event_kinds(id, t0) if k.startswith("restore_done")], "no release was substituted") + time.sleep(5) # the server closes the file a moment after the session ends + return my_session(plex) is None -def _scn_sub(scn, mode): - s = _sub_common(scn, need_alt=(mode in ("E", "H"))) +def _mark_failed(scn, id): + row = row_of(id) + if row["state"] == "failed": + say("INFO", scn, "the row was already failed by hand when the scenario began") + return True + rc, out = runner_cmd(["--mark-failed", id]) + detail(f"{scn}: mark-failed exit {rc}: {out[-300:]}") + return check(scn, rc == 0 and row_of(id)["state"] == "failed", + "the release is made unobtainable: the row is failed by hand (--mark-failed), so nothing fetches it") + + +def _put_back(scn, plex, id): + """After a scenario in which no substitute took the row's place: stop the play first (a reader + that still waits would make the runner fetch the whole file), then undo the mark.""" + cur = row_of(id) + if not cur or cur["state"] != "failed" or cur.get("restore_note") != HAND_NOTE: + return + gone = _stop_and_wait(plex) + rc, _ = runner_cmd(["--mark-failed", id, "--undo"]) + say("INFO", scn, f"put back: play stopped ({'no session left' if gone else 'a session is still listed'}), " + f"--mark-failed --undo exit {rc}, row state {row_of(id)['state']}") + + +def _plex_facts(plex, rk): + """What Plex holds for the item, from its own analysis of the file.""" + md = _meta(plex, rk, checkFiles=1) + medias = md.get("Media") or [] + parts = [p for m in medias for p in m.get("Part") or []] + audio = [s for p in parts for s in p.get("Stream") or [] if _int(s.get("streamType")) == 2] + m0 = medias[0] if medias else {} + return {"found": bool(md), "medias": len(medias), "parts": len(parts), "sizes": [_int(p.get("size")) for p in parts], + "missing": sum(1 for p in parts if p.get("exists") in (False, 0, "0") or p.get("accessible") in (False, 0, "0")), + "duration": _int(m0.get("duration")), "height": _int(m0.get("height")), + "audio": str((audio[0].get("languageCode") or audio[0].get("languageTag") or "") if audio else ""), + "views": _int(md.get("viewCount")), "guid": md.get("guid") or "", "section": md.get("librarySectionID"), + "title": md.get("title") or "", "year": md.get("year")} + + +def _same_items(plex, facts): + """How many library items Plex holds for this title: 1 unless a scan made a duplicate.""" + if facts.get("section") is None: + return -1 + q = {"guid": facts["guid"]} if facts.get("guid") else {"title": facts["title"], "year": facts.get("year") or ""} + return len(plex.mc(f"/library/sections/{facts['section']}/all", dict(q, type=1)).get("Metadata") or []) + + +def _arr_of(row): + """(client, movie id) of the Radarr movie that holds the row's library file, or None.""" + mods = _offload_mods() + if not mods: + return None + paths, register, redownload = mods + e = os.environ + try: + radarrs, sonarrs = register.clients_from_env() + arrs = redownload.Arrs(radarrs, sonarrs, paths.parse_path_map(e.get("TIERING_ARR_PATH_MAP")), + paths.parse_path_map(e.get("TIERING_PATH_MAP"))) + hit = arrs.find(row["lib_path"]) + except Exception: + return None + if not hit or hit.get("kind") != "radarr": + return None + return arrs.radarrs[hit["client"]], hit["ids"][0] + + +def _arr_facts(c, mid): + """The arr's file record for the movie, what it has queued and how often it grabbed.""" + try: + m = c.get(f"/api/v3/movie/{mid}") or {} + f = m.get("movieFile") or {} + q = c.get("/api/v3/queue/details", movieId=mid) or [] + h = c.get("/api/v3/history/movie", movieId=mid, eventType=1) or [] + except Exception as ex: + return {"error": type(ex).__name__} + return {"has": bool(m.get("hasFile")), "path": f.get("path") or "", "size": _int(f.get("size")), + "cutoff_unmet": bool(f.get("qualityCutoffNotMet")), "queued": len(q) if isinstance(q, list) else -1, + "grabbed": len(h) if isinstance(h, list) else -1} + + +def _switch_watch(plex, id, extra_env, budget): + """Run `--switch-live ` and sample the player's session every 3 s while it runs. + (exit code or None when it was killed at the budget, output, [(seconds, session or None)]).""" + env = dict(os.environ) + env.update(extra_env or {}) + t0, samples = time.time(), [] + with tempfile.TemporaryFile(mode="w+") as log: + p = subprocess.Popen([sys.executable, "-m", "offload.runner", "--switch-live", id], stdout=log, + stderr=subprocess.STDOUT, env=env, cwd="/app" if os.path.isdir("/app") else None) + while p.poll() is None and time.time() - t0 < budget: + samples.append((time.time() - t0, my_session(plex))) + time.sleep(3) + rc = p.poll() + if rc is None: + p.kill() + p.wait() + log.seek(0) + return rc, log.read(), samples + + +def _longest_gap(samples): + """The longest time (s) the server listed no session of the player.""" + worst, start, last = 0.0, None, 0.0 + for t, s in samples: + if s is None and start is None: + start = last + if s is not None and start is not None: + worst, start = max(worst, t - start), None + last = t + return max(worst, last - start) if start is not None else worst + + +def _reasons(why): + return ", ".join(f"{n}x {k[:60]}" for k, n in sorted((why or {}).items())) or "none" + + +def _swap(scn, mode): + s = _sub_common(scn, mode) if not s: return plex, id, row = s - st, ses, off = _play_near_head_end(plex, row) - if not check(scn, ses is not None, f"playing near the end of the head (playMedia HTTP {st})"): + rk, mods = str(row["rating_key"]), _offload_mods() + budget = _int(os.environ.get("E2E_SWAP_BUDGET_S"), 900) + gap_ok = _int(os.environ.get("E2E_GAP_S"), 45) + arr = _arr_of(row) + p0, a0 = _plex_facts(plex, rk), (_arr_facts(*arr) if arr else None) + dup0 = _same_items(plex, p0) + man0 = manifest_of(id) + if not _mark_failed(scn, id): return - saved = row.get("nzb_path2") - rc, out = runner_cmd(["--mark-failed", id]) - check(scn, rc == 0, "row marked failed by hand (the state a bad chunk leaves)") + marked = row_of(id) try: + st, ses, off = _play_near_head_end(plex, row) + if not check(scn, ses is not None, f"playing near the end of the local head (playMedia HTTP {st}, offset {off // 1000}s)"): + return if mode == "H": - check(scn, player_cmd(plex, "/player/playback/pause") == 200, "player paused through the proxy") - time.sleep(4) - ses = my_session(plex) + check(scn, player_cmd(plex, "/player/playback/pause", {"type": "video"}) == 200, "player paused through the proxy") + ses = wait_session(plex, rk, 30, want_state="paused") or my_session(plex) + say("INFO", scn, f"player state before the switch: {(ses or {}).get('state') or 'no session'}") + if not ses: + say("FAIL", scn, "the session was lost on the pause") + return extra = None if mode == "G": - extra = {"NEWZNAB_INDEXERS": "http://127.0.0.1:9/|none"} # no indexer answers: no unplanned release - if mode in ("F", "G"): - db = sqlite3.connect(os.environ.get("TIERING_DB", "/state/tiering.db")) - db.execute("update files set nzb_path2=? where id=?", ("/nonexistent/e2e-dead.nzb.gz" if mode == "F" else "", id)) - db.commit() - db.close() - _switch_and_check(scn, plex, id, row, ses, expect_switch=(mode != "G"), extra_env=extra) + # the one made-up condition: no release may count as the same cut, so every real + # candidate of the real search is dropped and nothing qualifies + extra = {"SUBSTITUTE_RUNTIME_TOL_S": "-1", "SUBSTITUTE_RUNTIME_TOL_FRAC": "-1"} + t0, vo0, sizes0 = time.time(), ses["vo"], ses["sizes"] + rc, out, samples = _switch_watch(plex, id, extra, budget) + detail(f"{scn}: switch-live exit {rc}: {out[-900:]}") + states = {} + for _, x in samples: + k = (x or {}).get("state") or "none" + states[k] = states.get(k, 0) + 1 + say("INFO", scn, f"--switch-live ran {int(time.time() - t0)} s, exit {rc}; player states seen meanwhile: {states}") + if mode == "G": + _no_candidate_checks(scn, plex, id, row, marked, t0, rc, sizes0, p0, a0, arr, man0, mods) + else: + _swapped_checks(scn, mode, plex, id, row, t0, rc, vo0, sizes0, samples, p0, a0, dup0, arr, mods, budget, gap_ok) finally: - if mode in ("F", "G") and saved is not None and row_of(id).get("nzb_path2") in ("", "/nonexistent/e2e-dead.nzb.gz"): - db = sqlite3.connect(os.environ.get("TIERING_DB", "/state/tiering.db")) - db.execute("update files set nzb_path2=? where id=? and nzb_path2 in ('', '/nonexistent/e2e-dead.nzb.gz')", (saved, id)) - db.commit() - db.close() - if row_of(id)["state"] == "failed": - runner_cmd(["--mark-failed", id, "--undo"]) + _put_back(scn, plex, id) + if mode == "G": + # the search G made found nothing by design: its "searched recently" mark would stop the next scenario + try: + db = sqlite3.connect(os.environ.get("TIERING_DB", "/state/tiering.db"), timeout=30) + n = db.execute("delete from kv where key=?", (f"substitute_search:{id}",)).rowcount + db.commit() + db.close() + say("INFO", scn, f"put back: the row's search cooldown mark removed ({n})") + except sqlite3.Error as ex: + say("INFO", scn, f"the search cooldown mark could not be removed ({type(ex).__name__})") + + +def _swapped_checks(scn, mode, plex, id, row, t0, rc, vo0, sizes0, samples, p0, a0, dup0, arr, mods, budget, gap_ok): + rk = str(row["rating_key"]) + new_id = _substitute_of(id) + new = row_of(new_id) if new_id else None + if not check(scn, rc == 0 and new is not None, "the switch ended well and a new row took the try row's place"): + ev = [d for k, d in events_of(id, t0) if k in ("substitute_failed", "auto_switch")] + say("INFO", scn, f"why not: {[str(d.get('detail') or d.get('reason') or '')[:120] for d in ev][-2:]}; " + f"dropped candidates: {_reasons((ev[0] if ev else {}).get('why'))}") + return + detail(f"{scn}: try row {id} -> {new_id}") + # 1: the play goes on + s2, end = my_session(plex), time.time() + 60 + while time.time() < end and not (s2 and s2["rk"] == rk and s2["sizes"] != sizes0): + time.sleep(3) + s2 = my_session(plex) + samples.append((time.time() - t0, s2)) + on_new = bool(s2 and s2["rk"] == rk and _int(new["size"]) in s2["sizes"]) + check(scn, on_new, "1: the session shows the new file (same item, the part has the new size)") + wait = wait_advancing(plex, rk, 120) if on_new and mode != "H" else None + first = int(time.time() - t0) + gap = _longest_gap(samples) + if mode == "H": + s3 = my_session(plex) + check(scn, s3 is not None and s3["rk"] == rk, f"1: the paused player holds the new file (state {(s3 or {}).get('state') or 'no session'})") + else: + check(scn, wait is not None, f"1: the picture moves on the new file {first} s after the switch began") + check(scn, first <= budget, f"1: that is inside the wait a player gets before a read fails ({first} s of {budget} s)") + check(scn, gap <= gap_ok, f"1: the server never lost the session for long (longest gap {int(gap)} s, allowed {gap_ok} s)") + ev = [d for k, d in events_of(id, t0) if k == "auto_switch"] + say("INFO", scn, f"1: the switch itself took {(ev[-1] if ev else {}).get('took_s', '?')} s by its own event; outcome {(ev[-1] if ev else {}).get('outcome')}") + # 2: Plex keeps the item + s3 = my_session(plex) + vo, slack = (s3 or {}).get("vo", -1), 120_000 + int((time.time() - t0) * 1000) + check(scn, s3 is not None and vo0 - 120_000 <= vo <= vo0 + slack, f"2: the play position was kept ({vo0 // 1000}s before, {vo // 1000}s now)") + p1, end = _plex_facts(plex, rk), time.time() + 120 + while time.time() < end and p1["sizes"] != [_int(new["size"])]: + time.sleep(10) + p1 = _plex_facts(plex, rk) + check(scn, p1["found"] and p1["medias"] == 1 and p1["parts"] == 1 and p1["sizes"] == [_int(new["size"])], + f"2: the same rating key holds one file, the new one ({p1['medias']} media, {p1['parts']} parts)") + check(scn, p1["missing"] == 0, f"2: Plex reports no missing or unreadable file ({p1['missing']})") + check(scn, p1["views"] == p0["views"] and p1["guid"] == p0["guid"], f"2: the watched count and the match are unchanged (views {p0['views']} -> {p1['views']})") + dup1 = _same_items(plex, p1) + check(scn, dup1 == dup0 and dup1 <= 1, f"2: no second item for the title ({dup0} before, {dup1} now)") + # 4: the pick, by the substitute's own record and by Plex's analysis of the new file + pk = next((d for k, d in events_of(id, t0) if k == "substitute_pick"), None) + if not check(scn, pk is not None, "4: the pick was recorded (substitute_pick)"): + pk = {} + run, aud, hgt = pk.get("run_s") or [None, None], pk.get("audio") or [None, None], pk.get("height") or [None, None] + detail(f"{scn}: picked {str(pk.get('title'))[:120]} from {pk.get('source')}; dropped: {[(str(r.get('title'))[:80], r.get('why')) for r in pk.get('rejected') or []]}") + same_run = bool(run[0] and run[1]) and abs(run[0] - run[1]) <= max(20.0, run[0] * 0.005) + check(scn, same_run, f"4: the same cut by the first bytes of both files (run time {run[0]} s and {run[1]} s)") + check(scn, bool(aud[0]) and aud[0] == aud[1], f"4: the same language on the first sound track ({aud[0]} and {aud[1]})") + say("INFO", scn, f"4: source {pk.get('source')}; picture height {hgt[0]} -> {hgt[1]}; dropped before it: {_reasons(pk.get('why'))}") + d0, d1 = p0["duration"] / 1000.0, p1["duration"] / 1000.0 + check(scn, d0 > 0 and d1 > 0 and abs(d0 - d1) <= max(20.0, d0 * 0.005), f"4: Plex's own analysis agrees on the run time ({int(d0)} s -> {int(d1)} s)") + check(scn, p0["audio"] == p1["audio"], f"4: Plex lists the same first sound language ({p0['audio'] or '?'} -> {p1['audio'] or '?'})") + say("INFO", scn, f"4: Plex's picture height {p0['height']} -> {p1['height']} ({'equal or better' if p1['height'] >= p0['height'] else 'lower'})") + # 5: the new row is a normal offloaded row (its hash is the runner's work: scenario N) + old = row_of(id) + man = manifest_of(new_id) or {} + stub = new.get("stub_path") or "" + local = os.stat(stub).st_blocks * 512 if os.path.exists(stub) else -1 + check(scn, new["state"] == "offloaded" and bool(new.get("nzb_path")) and new.get("nzb_path") != row.get("nzb_path"), + f"5: the new row is offloaded on another release (state {new['state']})") + check(scn, 0 <= local < _int(new["size"]) // 2, f"5: no full local copy was made ({local * 100 // max(_int(new['size']), 1)}% of the file is on local disk)") + check(scn, bool(man) and (man.get("pending") is True or bool(new.get("sha256"))), + f"5: its manifest is {'waiting for the hash build' if man.get('pending') else 'final'} (sha256 on the row: {'yes' if new.get('sha256') else 'not yet'})") + if mods: + link = _link_state(new, mods) + check(scn, link == "ours", f"5: the library path is the new row's link ({link}); name {'kept' if new.get('lib_path') == row.get('lib_path') else 'changed (another extension)'}") + check(scn, old["state"] == "failed" and old.get("restore_note") == SWAP_NOTE and os.path.basename(old.get("lib_path") or "").startswith(".dead-"), + "5: the old row is retired (failed, restore note, no library path)") + # 3: the arr keeps its file and grabs nothing + if not arr or not a0 or a0.get("error"): + say("SKIP", scn, "3: no Radarr movie holds the try row's file, or the arr did not answer") + else: + a1, end = _arr_facts(*arr), time.time() + 150 + while time.time() < end and not (a1.get("has") and a1.get("size") == _int(new["size"])): + time.sleep(10) + a1 = _arr_facts(*arr) + check(scn, a1.get("has") and a1.get("size") == _int(new["size"]), "3: after its rescan the arr holds a file of the new size") + check(scn, os.path.dirname(a1.get("path") or "") == os.path.dirname(a0["path"]), f"3: in the same folder (file name {'kept' if a1.get('path') == a0['path'] else 'changed'})") + check(scn, a1.get("queued") == 0 and a1.get("grabbed") == a0["grabbed"], f"3: the arr queued nothing and grabbed nothing (queue {a1.get('queued')}, grabs {a0['grabbed']} -> {a1.get('grabbed')})") + check(scn, not a1.get("cutoff_unmet") or a0["cutoff_unmet"], f"3: the new file does not make the arr want an upgrade (cutoff unmet {a0['cutoff_unmet']} -> {a1.get('cutoff_unmet')})") + # 6: only the owner is told + al = alerts_since(t0) + mine = [a for a in al if a.get("id") in (id, new_id)] + kinds = sorted({str(a.get("kind")) for a in mine}) + check(scn, any(a.get("kind") == "auto_switch" and a.get("id") == id for a in mine), f"6: the owner's alert file has the switch (kinds for this row: {kinds})") + check(scn, kinds == ["auto_switch"], f"6: and nothing else about it ({len(al)} alert lines in all since the start)") + + +def _no_candidate_checks(scn, plex, id, row, marked, t0, rc, sizes0, p0, a0, arr, man0, mods): + # 7: nothing qualifies: the owner is told, and nothing is changed + check(scn, rc == 1, f"7: --switch-live says it did not switch (exit {rc})") + fl = next((d for k, d in events_of(id, t0) if k == "substitute_failed"), None) + if check(scn, fl is not None, "7: the refusal was recorded (substitute_failed)"): + detail(f"{scn}: dropped: {[(str(r.get('title'))[:80], r.get('why')) for r in fl.get('rejected') or []]}") + n = sum((fl.get("why") or {}).values()) + if n: + say("PASS", scn, f"4: every candidate was dropped with its reason ({n} dropped: {_reasons(fl.get('why'))})") + else: + say("SKIP", scn, "4: the search offered no candidate at all, so there was no reason to record") + mine = [a for a in alerts_since(t0) if a.get("id") == id] + check(scn, any(a.get("kind") == "auto_switch_no_restore_path" for a in mine), f"7: the owner's alert file says so (kinds for this row: {sorted({str(a.get('kind')) for a in mine})})") + now = row_of(id) + diff = [k for k in now if k != "updated_ts" and now.get(k) != marked.get(k)] + check(scn, not diff and not _substitute_of(id), f"7: the row is as it was (fields changed: {diff or 'none'})") + check(scn, manifest_of(id) == man0 and os.path.exists(row.get("stub_path") or ""), "7: its manifest and stub are untouched") + if mods: + back = dict(now, state="offloaded") + check(scn, _link_state(back, mods) == "ours", "7: the library path is still the row's own link") + s2 = my_session(plex) + check(scn, s2 is not None and s2["sizes"] == sizes0, f"7: the player was left on its file, waiting (state {(s2 or {}).get('state') or 'no session'})") + p1 = _plex_facts(plex, str(row["rating_key"])) + check(scn, p1["sizes"] == p0["sizes"] and p1["medias"] == p0["medias"], "7: Plex holds the same file as before") + if arr and a0 and not a0.get("error"): + a1 = _arr_facts(*arr) + check(scn, {k: a1.get(k) for k in ("has", "path", "size", "queued", "grabbed")} == {k: a0.get(k) for k in ("has", "path", "size", "queued", "grabbed")}, + "7: the arr holds the same file record and grabbed nothing") def sc_d(): - """D: a bad chunk ahead of the play position. The player gets EIO or a stall, never bad bytes; the trigger fires.""" - s = _sub_common("D", need_alt=False) + """D: the release cannot be fetched and nothing has taken its place yet. A play that runs past + the local head waits: it gets no zero-filled bytes and its session does not end. + Changes: the try row is failed by hand for the length of D, and a play starts. Put back: the + play is stopped, then `--mark-failed --undo`.""" + s = _sub_common("D", "D") if not s: return plex, id, row = s - st, ses, off = _play_near_head_end(plex, row) - if not check("D", ses is not None, f"playing near the end of the head (playMedia HTTP {st})"): + rk = str(row["rating_key"]) + if not _mark_failed("D", id): return - t0 = time.time() - runner_cmd(["--mark-failed", id]) + t0, ev0 = time.time(), events_size() try: + st, ses, off = _play_near_head_end(plex, row) + if not check("D", ses is not None, f"playing near the end of the local head (playMedia HTTP {st}, offset {off // 1000}s)"): + return head = _int(row["head_len"]) + part = _part(_meta(plex, rk)) u = urllib.parse.urlparse(plex.base) - md = (plex.mc(f"/library/metadata/{row['rating_key']}").get("Metadata") or [{}])[0] - part = next(p for m in md.get("Media") or [] for p in m.get("Part") or []) conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=25) - got = b"" + got, status = b"", 0 try: - conn.request("GET", part["key"], headers={"X-Plex-Token": plex.token, "Range": f"bytes={head}-{head + (1 << 20) - 1}"}) + conn.request("GET", part["key"], headers={"X-Plex-Token": plex.token, "Range": f"bytes={head}-{head + MIB - 1}"}) r = conn.getresponse() - got = r.read(1 << 20) if r.status in (200, 206) else b"" status = r.status + got = r.read(MIB) if r.status in (200, 206) else b"" except (OSError, http.client.HTTPException): - status = 0 - bad = bool(got) and not any(got) - check("D", not bad and not (got and not any(got)), f"a read at the first middle byte returned no zero-filled data (HTTP {status}, {len(got)} bytes)") - p = os.environ.get("TIERFS_EVENTS", "") - if p: - with open(p, "a") as f: - f.write(json.dumps({"ts": time.time(), "id": id, "ev": "bad_chunk", "offset": head}) + "\n") - time.sleep(90) + pass + finally: + conn.close() + check("D", not (got and not any(got)), f"a read of the first byte past the head got no zero-filled data (HTTP {status}, {len(got)} bytes in 25 s)") + watch, seen, lost = _int(os.environ.get("E2E_D_WATCH_S"), 150), {}, 0 + end = time.time() + watch + while time.time() < end: + x = my_session(plex) + lost += x is None + k = (x or {}).get("state") or "none" + seen[k] = seen.get(k, 0) + 1 + time.sleep(5) + check("D", lost == 0, f"the play ran past the head and its session never ended in {watch} s (player states: {seen})") kinds = event_kinds(id, t0) - say("INFO", "D", f"events after the injected bad chunk: {sorted(set(kinds))}; alerts {alert_kinds_since(t0) or 'none'}") - check("D", any(k.startswith(("switch", "restore")) or k == "bad_chunk" for k in kinds), - "the automatic trigger reacted to the bad chunk (an event was logged)") + check("D", "promote_start" not in kinds and row_of(id)["state"] == "failed", "nothing fetched the failed row") + say("INFO", "D", f"tierfs events: {tail_events(ev0, id)}; alerts: {alert_kinds_since(t0) or 'none'}") finally: - if row_of(id)["state"] == "failed": - runner_cmd(["--mark-failed", id, "--undo"]) + _put_back("D", plex, id) def sc_e(): - _scn_sub("E", "E") + """E: the planned alternative takes the row's place during a play. Checks 1 to 6.""" + _swap("E", "E") def sc_f(): - _scn_sub("F", "F") + """F: no planned alternative: the indexers are searched live. Checks 1 to 6.""" + _swap("F", "F") def sc_g(): - _scn_sub("G", "G") + """G: nothing qualifies (check 7): the real search runs, and every candidate is dropped + because G sets a run-time tolerance no file can meet. No download beyond each candidate's + first bytes.""" + _swap("G", "G") def sc_h(): - _scn_sub("H", "H") + """H: the switch while the player is paused. Checks 1 to 6.""" + _swap("H", "H") + + +def sc_fail(): + """fail: mark the try row failed by hand, for a job that then lets the runner run: a failed + row is never fetched. `unfail` (or the scenario that follows) puts it back.""" + s = setup("fail", need_player=False) + if s and s[2]["state"] == "offloaded": + gone = _stop_and_wait(s[0]) + say("INFO", "fail", f"play stopped first ({'no session left' if gone else 'a session is still listed'})") + _mark_failed("fail", s[1]) + elif s: + say("SKIP", "fail", f"the try row is {s[2]['state']}, not offloaded") + + +def sc_unfail(): + """unfail: undo `fail` (the play is stopped first).""" + s = setup("unfail", need_player=False) + if s: + _put_back("unfail", s[0], s[1]) + say("INFO", "unfail", f"try row state {row_of(s[1])['state']}") + + +def sc_n(): + """N: the row a substitute left is a normal row (check 5). The live runner builds its hash + (one read of the whole file), then promotes it like any row (a second read), while the play + goes on. Changes: one play of the try row; the row ends whole. Nothing to put back.""" + if os.environ.get("E2E_SUBSTITUTE") != "1": + say("SKIP", "N", "waits for the substitute PR (set E2E_SUBSTITUTE=1 once it is deployed)") + return + s = setup("N") + if not s: + return + plex, id, row = s + born = dbro().execute("select ts from events where id=? and kind='substituted' order by seq limit 1", (id,)).fetchone() + if not born: + say("SKIP", "N", "no substitute has taken the try row's place") + return + if health() is None: + say("SKIP", "N", "the runner does not answer (paused?): the hash build and the promote are its work") + return + t0, wait = float(born[0]), _int(os.environ.get("E2E_N_WAIT_S"), 2400) + if row["state"] != "whole" and not my_session(plex): + st, ses, off = _play_near_head_end(plex, row) + check("N", ses is not None, f"a play of the new file (playMedia HTTP {st})") + first, lost, n, hashed, bad = my_session(plex), 0, 0, None, None + end = time.time() + wait + while time.time() < end: + kinds = event_kinds(id, t0) + if hashed is None and "substitute_hashed" in kinds: + hashed = int(time.time() - t0) + say("INFO", "N", f"hash build done {hashed} s after the substitute") + bad = next((k for k in kinds if k in ("substitute_hash_failed", "failed")), None) + if bad or row_of(id)["state"] == "whole": + break + n += 1 + lost += my_session(plex) is None + time.sleep(10) + last, cur, kinds = my_session(plex), row_of(id), event_kinds(id, t0) + if bad or (hashed is None and "substitute_hashed" not in kinds and cur["state"] != "whole"): + if bad: + say("FAIL", "N", f"5: the row's {bad} event") + else: + say("SKIP", "N", f"the hash build did not end within {wait} s (row state {cur['state']}): run N again") + return + man = manifest_of(id) or {} + check("N", bool(cur.get("sha256")) and "pending" not in man and bool(man.get("chunks_b3")), + "5: the row has its SHA-256, and its manifest is final with a chunk list") + if cur["state"] != "whole": + say("SKIP", "N", f"the promote did not end within {wait} s (row state {cur['state']}, promote started: {'yes' if 'promote_start' in kinds else 'no'}): run N again") + return + check("N", "promote_start" in kinds and "promoted" in kinds, "5: the runner promoted it like any row (promote_start, promoted)") + lp = cur.get("lib_path") or "" + mods = _offload_mods() + if mods: + d = mods[0].disk_paths(lp, mods[0].parse_path_map(os.environ.get("TIERING_PATH_MAP"))) + ok = len(d) == 1 and os.path.isfile(d[0]) and not os.path.islink(d[0]) and os.path.getsize(d[0]) == _int(cur["size"]) + check("N", ok, "5: the library file is a regular file of the row's size") + al = sorted({str(a.get("kind")) for a in alerts_since(t0) if a.get("id") == id}) + check("N", not [k for k in al if k != "auto_switch"], f"6: no alert about the new row ({al or 'none'})") + if first and n: + check("N", lost == 0 and last is not None and last["vo"] > first["vo"], + f"1: the play went on through the hash build and the promote ({first['vo'] // 1000}s -> {(last or {}).get('vo', 0) // 1000}s, session missing in {lost} of {n} samples)") # ---- the other ways Plex and the arrs use a file ---------------------------------------------- @@ -1395,7 +1828,7 @@ def sc_audit(): SCEN = {"diag": sc_diag, "up": sc_up, "state": sc_state, "AB": sc_ab, "I": sc_i, "stop": sc_stop, "C": sc_c, - "D": sc_d, "E": sc_e, "F": sc_f, "G": sc_g, "H": sc_h, + "D": sc_d, "E": sc_e, "F": sc_f, "G": sc_g, "H": sc_h, "N": sc_n, "fail": sc_fail, "unfail": sc_unfail, "T": sc_t, "S": sc_s, "Z": sc_z, "M": sc_m, "K": sc_k, "W": sc_w, "P": sc_p, "R": sc_r, "audit": sc_audit} diff --git a/tests/e2e/rearm_try_row.py b/tests/e2e/rearm_try_row.py index 41d6ddc..6af1806 100644 --- a/tests/e2e/rearm_try_row.py +++ b/tests/e2e/rearm_try_row.py @@ -17,6 +17,9 @@ Nothing else is written: no library file, no state DB row, no indexer budget file (searches use a private copy of the runner's budget state). +The try row is the one pick.json names, or the row a live substitute put in its place (the chain of +`restore_done` events is followed to its newest row). + When it writes nothing: the try row is still offloaded or busy (it is still armed), it waits for its first demote and Plex shows no play of it, it is failed (put that right by hand first), no candidate passes, or the allowlist would grow. A whole try row that was played before its first demote is @@ -118,6 +121,28 @@ def sample_ids(nzb): return list(dict.fromkeys(firsts + alls[::step])), len(alls), len(firsts) +def newest_try(db, old): + """(the try entry as it is now, substitutes that took its place). A live substitute retires a + row (it stays as `failed`, its file renamed) and makes a new row for the same library file, so + the entry pick.json names is followed to the last row of that chain.""" + cur, seen = dict(old), {old.get("id")} + while len(seen) < 20: + nid = "" + for (d,) in db.execute("SELECT detail FROM events WHERE id=? AND kind='restore_done' ORDER BY seq DESC", (cur.get("id"),)): + try: + nid = str((json.loads(d) or {}).get("substitute") or "") + except (ValueError, AttributeError): + nid = "" + if nid: + break + r = db.execute("SELECT id, lib_path FROM files WHERE id=?", (nid,)).fetchone() if nid and nid not in seen else None + if r is None: + break + seen.add(nid) + cur = {**cur, "id": r["id"], "lib_path": r["lib_path"]} + return cur, len(seen) - 1 + + def old_try_verdict(db, old): """retire | keep: | abort: | wait: for the try row pick.json names now. `wait` is a whole row that was never offloaded: the caller keeps it, unless Plex shows a play of it (then it is retired).""" @@ -173,9 +198,12 @@ def main(): db = sqlite3.connect(f"file:{cfg.db}?mode=ro", uri=True) db.row_factory = sqlite3.Row - old = pick.get("try") if isinstance(pick.get("try"), dict) else None + named = pick.get("try") if isinstance(pick.get("try"), dict) else None + old, subs = newest_try(db, named) if named else (None, 0) retired = waiting = None if old: + if subs: + say("INFO", f"substitutes that took the try row's place: {subs}; the verdict is about the newest row") verdict = old_try_verdict(db, old) if verdict.startswith("keep:"): say("SKIP", f"old try row verdict: keep ({verdict[5:]}); nothing written") @@ -236,12 +264,15 @@ def main(): pass dead = pick.get("dead") if isinstance(pick.get("dead"), list) else [] taken = {v.get("id") for v in pick.values() if isinstance(v, dict)} | {d.get("id") for d in dead if isinstance(d, dict)} + taken |= {old.get("id")} if old else set() lines = open(allow).read().splitlines() stamp = time.strftime("%Y%m%d-%H%M%S") have0 = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} if retired: - gone = [x for x in lines if x.strip() == retired.get("lib_path")] - lines = [x for x in lines if x.strip() != retired.get("lib_path")] + [f"# e2e re-arm {stamp}: retired a consumed try row"] + # the path pick.json names and the newest row's (a substitute with another extension has another path) + out = {retired.get("lib_path"), named.get("lib_path")} - {None, ""} + gone = [x for x in lines if x.strip() in out] + lines = [x for x in lines if x.strip() not in out] + [f"# e2e re-arm {stamp}: retired a consumed try row"] say("INFO", f"old try row's path in the allowlist: {len(gone)} line(s), to be removed") have = {x.strip() for x in lines if x.strip() and not x.lstrip().startswith("#")} @@ -424,6 +455,8 @@ def why_not(r): if not isinstance(pick.get("dead"), list): pick["dead"] = [] pick["dead"].append({"id": retired.get("id"), "role": "try", "why": "consumed by an e2e scenario", "ts": now}) + if named.get("id") != retired.get("id"): # the row a substitute retired: never picked again either + pick["dead"].append({"id": named.get("id"), "role": "try", "why": "replaced by a substitute", "ts": now}) detail(f"retired try row: id={retired.get('id')}") pick["try"] = new pick["ts_rearm"] = now From 15625e0d6a917720396c9a52e4e3cfe0b72cac96 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:59:04 -0800 Subject: [PATCH 9/9] e2e: a crash in the offload step prints the error's type only --- tests/e2e/offload_try_row.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/e2e/offload_try_row.py b/tests/e2e/offload_try_row.py index d38dfbc..91d1e93 100644 --- a/tests/e2e/offload_try_row.py +++ b/tests/e2e/offload_try_row.py @@ -242,4 +242,10 @@ def block(_now, promotes_planned=False): if __name__ == "__main__": - sys.exit(main()) + _t0 = time.time() + try: + sys.exit(main()) + except Exception as ex: # a crash must not put a title, a path or a URL on the result lines + say("FAIL", f"harness error: {type(ex).__name__} (the message is on the DETAIL line); look at the try row's state before a new run") + detail(f"error: {str(ex)[:300]}") + sys.exit(done("unknown", _t0, 1))