Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 139 additions & 18 deletions tests/e2e/README.md

Large diffs are not rendered by default.

91 changes: 91 additions & 0 deletions tests/e2e/llm_shadow_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""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 - <since-epoch> < llm_shadow_check.py

<since-epoch> is when the play scenarios of the run began. Output follows plex_e2e.py: lines
`PASS|FAIL|SKIP|INFO L <text>` 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__":
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)
251 changes: 251 additions & 0 deletions tests/e2e/offload_try_row.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
"""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 <id>` 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 <text>` carry counts and states only;
`DETAIL` lines hold ids and the runner's log lines and go to syslog. Last line:
`OFFLOAD state=<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+", "<path>", m.group(1).replace(self.id, "<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__":
_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))
Loading