From 750bf80b82326a4819592291df5834639861ed56 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:28:31 -0800 Subject: [PATCH 1/2] tiering: follow a moved link, mark a deleted one, leave no refused import, keep the allowlist entry with a substituted row - an offloaded row whose link is gone from lib_path is looked up in the arr by identity; when the arr's file is this id's tierfs link at another path, lib_path follows (event l_moved) - a row with no link for TIERING_L_GONE_DAYS (default 7) while the arr has no file and nothing queued moves to failed with a fixed reason (event l_gone, one alert); stub and remote data are kept; many at once act on none - a dry run imports no substitute candidate; imports are recorded by job id and a refused one is removed through the AltMount API, never by name - a TIERING_ONLY_PATHS entry follows the row to its new path after a substitute or a rename adoption (the list itself is not widened or written) --- tiering/offload/altmount.py | 33 ++++++- tiering/offload/redownload.py | 37 +++++++ tiering/offload/register.py | 5 + tiering/offload/runner.py | 176 +++++++++++++++++++++++++++++++++- tiering/offload/state.py | 24 +++++ tiering/offload/substitute.py | 107 ++++++++++++++++++++- 6 files changed, 374 insertions(+), 8 deletions(-) diff --git a/tiering/offload/altmount.py b/tiering/offload/altmount.py index 425e069..c4f7ba9 100644 --- a/tiering/offload/altmount.py +++ b/tiering/offload/altmount.py @@ -33,6 +33,7 @@ import os import re import ssl +import threading import time import urllib.parse import uuid @@ -262,6 +263,33 @@ def __init__(self, url: str | None = None, apikey: str | None = None, *, self._timeout = timeout self._sleep = sleep self._clock = clock + self._jobs: dict = {} # path an import returned -> the job id this client made for it + self._jobs_mu = threading.Lock() + + def job_of(self, remote_path: str): + """The job id this client used for the import that returned `remote_path`, or None.""" + with self._jobs_mu: + return self._jobs.get(remote_path) + + def remove(self, job_id: str) -> bool: + """Remove one import by the job id this client made, through AltMount's SABnzbd + history delete (the same endpoint and key as the import). Only a job id this client + made is accepted (the caller keeps the record of it, so it survives a restart). AltMount + answers true even for an id it does not know.""" + if not re.fullmatch(r"[0-9a-f]{32}", str(job_id)): + raise AltMountError("not a job id of ours") + q = urllib.parse.urlencode({"name": "delete", "value": job_id, "del_files": "1"}) + body = urllib.parse.urlencode({"mode": "history", "output": "json", + "apikey": self._key}).encode() + conn, resp = self._http.open( + "POST", f"/sabnzbd/api?{q}", + {"Content-Type": "application/x-www-form-urlencoded"}, body) + if not self._json(resp, conn).get("status"): + raise AltMountError("altmount refused the removal") + with self._jobs_mu: + for k in [k for k, v in self._jobs.items() if v == job_id]: + del self._jobs[k] + return True def _json(self, resp, conn): try: @@ -329,7 +357,10 @@ def import_nzb(self, nzb_bytes: bytes, release_name: str) -> str: if slot: st = (slot.get("status") or "").lower() if st == "completed": - return self._remote_path(slot) + path = self._remote_path(slot) + with self._jobs_mu: + self._jobs[path] = job_id + return path if st == "failed": raise ImportFailed("altmount import failed") if self._clock() >= deadline: diff --git a/tiering/offload/redownload.py b/tiering/offload/redownload.py index 6db1309..edd6d2c 100644 --- a/tiering/offload/redownload.py +++ b/tiering/offload/redownload.py @@ -98,6 +98,43 @@ def find(self, lib_path: str): "unmonitored": [e["id"] for e in hit if not e.get("monitored")]} return None + def locate(self, row): + """Where the arrs themselves put the row's media item now, by its identity (never by + the path it used to have): {"paths": [share paths of its file], "has_file": bool, + "queued": bool}. None when the row has no identity to ask by. Raises ArrError when an + arr cannot answer (what an arr did not say is not "no file"). A movie is asked by its + imdb id, an episode by its series' tvdb id with its season and episode number.""" + kind = row.get("kind") + out = {"paths": [], "has_file": False, "queued": False} + if kind == "movie" and row.get("imdb_id"): + for c in self.radarrs: + for m in c.get("/api/v3/movie", imdbId=str(row["imdb_id"])) or []: + f = m.get("movieFile") if isinstance(m, dict) else None + if f and f.get("path"): + out["paths"].append(self._local(f["path"])) + out["has_file"] = out["has_file"] or bool(m.get("hasFile")) + if c.get("/api/v3/queue/details", movieId=int(m["id"])): + out["queued"] = True + return out + if (kind == "episode" and row.get("tvdb_id") and row.get("season") is not None + and row.get("episode") is not None): + for c in self.sonarrs: + for sr in c.get("/api/v3/series", tvdbId=str(row["tvdb_id"])) or []: + eps = c.get("/api/v3/episode", seriesId=sr["id"], + seasonNumber=int(row["season"]), includeEpisodeFile="true") + for e in eps or []: + if e.get("episodeNumber") != int(row["episode"]): + continue + f = e.get("episodeFile") + if isinstance(f, dict) and f.get("path"): + out["paths"].append(self._local(f["path"])) + out["has_file"] = out["has_file"] or bool(e.get("hasFile")) + if c.get("/api/v3/queue/details", seriesId=sr["id"], + episodeIds=int(e["id"])): + out["queued"] = True + return out + return None + def _client(self, item): pool = self.radarrs if item["kind"] == "radarr" else self.sonarrs try: diff --git a/tiering/offload/register.py b/tiering/offload/register.py index ff2494d..a7225d3 100644 --- a/tiering/offload/register.py +++ b/tiering/offload/register.py @@ -405,6 +405,11 @@ def _adopt_renamed(state, db, apply, local, cand, resolve, mount, out) -> bool: if apply and not state.update_if(db, id, row["state"], lib_path=local): out["renamed"] -= 1 out["renamed_skipped"] += 1 + elif apply and getattr(state, "note_only_follow", None) and row.get("lib_path"): + try: # a TIERING_ONLY_PATHS entry follows the row to its new path (and only that one) + state.note_only_follow(db, row["lib_path"], local) + except Exception as e: # noqa: BLE001 + log.warning("register: the allowlist could not follow row %s (%s)", id, type(e).__name__) return True diff --git a/tiering/offload/runner.py b/tiering/offload/runner.py index 526c083..07bdb65 100644 --- a/tiering/offload/runner.py +++ b/tiering/offload/runner.py @@ -55,9 +55,14 @@ 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 +GONE_NOTE = "L gone: removed by the arr or the user" # kept apart from ORPHAN_NOTES: its stub is not removed +GONE_DAYS = 7.0 # L missing this long, with the arr saying it has no file for the item (TIERING_L_GONE_DAYS; 0: never) +GONE_LOOKUP_EVERY = 3600.0 # a row whose L is missing is looked up in the arrs this often +GONE_LOOKUPS_PER_PASS = 10 # arr lookups for missing L per pass: a few calls each, never a sweep +GONE_MASS = 25 # this many rows past the grace at once look like an unmounted disk, not deletions: act on none # 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 +ONCE_KINDS = ALERT_EVENTS + ("l_missing", "l_gone", "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 REGISTER_KEYS = ("listed", "missing_local", "ambiguous", "errors") # required in the result @@ -219,6 +224,7 @@ class Config: check_max_h: float = CHECK_MAX_H auto_redownload: bool = True # TIERING_AUTO_REDOWNLOAD (only acts with apply) redownload_max: int = REDOWNLOAD_MAX + l_gone_days: float = GONE_DAYS auto_switch: bool = True # TIERING_AUTO_SWITCH: move watchers to the restore path on an unrepairable chunk @classmethod @@ -294,6 +300,7 @@ def from_env(cls, env=None) -> "Config": auto_switch=e.get("TIERING_AUTO_SWITCH", "1").strip().lower() not in ("0", "false", "no", "off"), redownload_max=max(1, int(e.get("TIERING_REDOWNLOAD_MAX_PER_NIGHT") or REDOWNLOAD_MAX)), + l_gone_days=max(0.0, float(e.get("TIERING_L_GONE_DAYS") or GONE_DAYS)), ) @@ -668,6 +675,11 @@ def __init__(self, cfg: Config, deps: Deps, clock=time.time, sleep=time.sleep): self.errors = 0 self.counts: dict = {} self.only_blocked = False + self._gone_verdict: dict = {} # id -> the arrs' last answer for a row whose L is missing + self._gone_due: list = [] + self._gone_cache = None + self.gone_next: dict = {} # id -> when its missing L is looked up in the arrs again + self.only_follow: dict = {} # path -> allowlist entry it descends from (state.note_only_follow) self.heartbeat_path = cfg.db + ".heartbeat" # ---- small helpers @@ -677,13 +689,26 @@ def _may_demote(self, row) -> bool: if self.only_blocked: # the allowlist file could not be read this pass: no demotes return False only = self.cfg.only_paths - return not only or _norm_only(str(row.get("lib_path") or "")) in only + if not only: + return True + p = _norm_only(str(row.get("lib_path") or "")) + # a row that moved (a substitute with another extension, an arr rename) keeps the + # entry of the path it came from; the entry must still be on the list + return p in only or self.only_follow.get(p) in only def refresh_only_paths(self): """Start of each pass: an `@file` allowlist is read again. A file that cannot be read, or that holds no paths, blocks every demote this pass (never opens them up). The log holds the count only, never a path.""" self.only_blocked = False + if not self.cfg.only_spec and not self.cfg.only_paths: + return + try: + f = getattr(self.state, "only_follow", None) + self.only_follow = dict(f(self.db())) if f else {} + except Exception as e: # noqa: BLE001 # no pairs: only the listed paths count + self.only_follow = {} + log.warning("TIERING_ONLY_PATHS: moved paths not readable (%s)", type(e).__name__) if not self.cfg.only_spec: return try: @@ -1185,14 +1210,155 @@ def _rebase_atime(self, db, id): # ---- reconcile and bad chunks + def _arrs(self): + """The arr clients (redownload.Arrs), or None when none are set or one cannot be built.""" + if self.deps.arrs is None: + return None + try: + return self.deps.arrs() + except Exception as e: # noqa: BLE001 + log.error("arr clients not usable: %s", type(e).__name__) + return None + + def _gone_clear(self, db, id): + """L is back (or the row moved on): its missing-since mark goes.""" + self.gone_next.pop(id, None) + if self.cfg.apply and id in self._gone_load(db): + g = dict(self._gone_load(db)) + g.pop(id, None) + self._kv_set(db, "l_gone_since", g) + self._gone_cache = g + + def _gone_load(self, db) -> dict: + if getattr(self, "_gone_cache", None) is None: + g = self._kv_get(db, "l_gone_since", {}) + self._gone_cache = {str(k): float(v) for k, v in g.items()} if isinstance(g, dict) else {} + return self._gone_cache + + def _l_gone(self, db, row, now, budget) -> bool: + """An offloaded row whose L is missing from its recorded path. Asks the arrs where + they have the item now (by its identity, never a guess at a name): if the file + there is the tierfs symlink of this id, the row's lib_path follows it. Else, with + the arr answering that it has no file and nothing queued, the row is marked gone + once L has been missing for TIERING_L_GONE_DAYS. Nothing else is touched: no stub, + no remote data, no link. Returns True when it used one of the pass's lookups.""" + id, cfg = row["id"], self.cfg + arrs = self._arrs() + if arrs is None or not hasattr(arrs, "locate"): + self._once("l_missing", id, lib_path=row.get("lib_path")) + return False + gone = self._gone_load(db) + if id not in gone: + gone[id] = now + self._kv_set(db, "l_gone_since", gone) # (a dry run keeps it in memory only) + since = gone.get(id, now) + used = False + if now >= self.gone_next.get(id, 0.0): + if budget[0] <= 0: + return False # this pass's lookups are spent; the next pass goes on + self.gone_next[id] = now + GONE_LOOKUP_EVERY + used = True + try: + loc = arrs.locate(row) + except Exception as e: # noqa: BLE001 # an arr that does not answer says nothing + log.warning("%s: L is missing and an arr did not answer (%s)", id, type(e).__name__) + loc = None + if loc is not None and self._l_moved(db, row, loc): + self._gone_clear(db, id) + return used + self._gone_verdict[id] = loc # kept for the grace check below + self._once("l_missing", id, lib_path=row.get("lib_path")) + loc = self._gone_verdict.get(id) + days = cfg.l_gone_days + if (days > 0 and loc is not None and not loc["paths"] and not loc["has_file"] + and not loc["queued"] and now - since >= days * DAY): + self._gone_due.append((row, since, loc)) + return used + + def _l_moved(self, db, row, loc) -> bool: + """The arr's file for this row is a tierfs symlink of this id at another path: follow it.""" + id = row["id"] + for share in loc["paths"]: + if share == row.get("lib_path"): + continue + found = self._find_disk({"lib_path": share}) + if len(found) != 1: + continue + try: + got = os.readlink(found[0]) + except OSError: + continue + ext = os.path.splitext(share)[1] + if os.path.basename(got) != f"{id}{ext}": + continue + other = self.state.by_path(db, share) + if other is not None and other["id"] != id: + log.warning("%s: its link is at a path another row holds; not moving it", id) + return False + if not self.cfg.apply: + log.warning("dry run: would point %s at the path the arr has its link at", id) + return True + old = row.get("lib_path") + if not self.state.update_if(db, id, "offloaded", lib_path=share): + return False + self.state.log_event(db, id, "l_moved", {"from": old, "to": share}) + log.warning("%s: the arr moved its link; lib_path follows", id) + try: + self.state.note_only_follow(db, old, share) + except Exception as e: # noqa: BLE001 + log.warning("%s: the allowlist could not follow the row (%s)", id, type(e).__name__) + return True + return False + + def _gone_finish(self, db, now): + """The rows `_l_gone` found past the grace: mark them gone, once each, and alert. Many + at once is not a set of deletions (a disk that is not mounted looks the same): none.""" + due, self._gone_due = self._gone_due, [] + if not due: + return + if len(due) >= GONE_MASS: + self._once("l_gone_mass", "all", rows=len(due)) + log.error("%d rows have had no L for over %g days; this looks like a missing " + "disk, not deletions: none is marked", len(due), self.cfg.l_gone_days) + return + for row, since, _loc in due: + id = row["id"] + if id in self.promote_running or id in self.demote_running: + continue + arrs = self._arrs() # the verdict is asked again now, not taken from an hour ago + try: + loc = arrs.locate(row) + except Exception as e: # noqa: BLE001 + log.warning("%s: not marked gone: an arr did not answer (%s)", id, type(e).__name__) + continue + if (loc is None or loc["paths"] or loc["has_file"] or loc["queued"] + or self._find_disk(row)): + continue + if not self.cfg.apply: + log.warning("dry run: would mark %s gone, no L for %.1f days", id, + (now - since) / DAY) + continue + if self.state.update_if(db, id, "offloaded", state="failed", restore_note=GONE_NOTE): + self.state.log_event(db, id, "l_gone", { + "since": since, "days": round((now - since) / DAY, 1), + "reason": "no link for this id in the arr's path and the arr has no file " + "or queue entry for the item"}) + self._once("l_gone", id, days=round((now - since) / DAY, 1)) + self._gone_clear(db, id) + log.warning("%s: its L is gone; no longer managed (stub and remote data kept)", id) + def _reconcile(self, db, rows, now): + budget = [GONE_LOOKUPS_PER_PASS] + self._gone_due: list = [] for row in rows: if row["state"] != "offloaded" or row["id"] in self.promote_running: continue found = self._find_disk(row) if not found: # L is gone from every disk: alert, never fail the row for it - self._once("l_missing", row["id"], lib_path=row.get("lib_path")) + if self._l_gone(db, row, now, budget): + budget[0] -= 1 continue + self._gone_clear(db, row["id"]) if len(found) > 1: self._log_skip(row, found) continue @@ -1212,6 +1378,10 @@ def _reconcile(self, db, rows, now): restore_note="L replaced"): self.state.log_event(db, row["id"], "l_replaced", {"lib_path": row.get("lib_path")}) log.warning("%s: L replaced, no longer managed", row["id"]) + self._gone_finish(db, now) + live = {r["id"] for r in rows if r["state"] == "offloaded"} + for id in [i for i in self._gone_load(db) if i not in live]: + self._gone_clear(db, id) # the row moved on (promoted, failed, gone): no mark # ---- orphan stub cleanup diff --git a/tiering/offload/state.py b/tiering/offload/state.py index 83e0f24..14b12e3 100644 --- a/tiering/offload/state.py +++ b/tiering/offload/state.py @@ -272,6 +272,30 @@ def kv_set(db, key, value) -> None: (key, json.dumps(value, sort_keys=True))) +def _only_norm(p) -> str: + p = str(p or "").strip() + return p.rstrip("/") if len(p) > 1 else p + + +def only_follow(db) -> dict: + """{library path: the TIERING_ONLY_PATHS entry it descends from}, for a row whose library + path changed (a substitute with another extension, an arr rename). It grants nothing by + itself: the runner honours a pair only while its entry is still on the allowlist.""" + d = kv_get(db, "only_follow", {}) + return d if isinstance(d, dict) else {} + + +def note_only_follow(db, old, new) -> None: + """The row at `old` now lives at `new`: the allowlist entry that covered `old` covers `new` + (and only `new`). A chain of moves keeps pointing at the first path.""" + old, new = _only_norm(old), _only_norm(new) + if not old or not new or old == new: + return + d = only_follow(db) + d[new] = d.get(old, old) + kv_set(db, "only_follow", d) + + def last_plays(db) -> dict: """{rating_key: last play time} the runner has seen, kept so a wiped Plex history cannot make a played file look idle.""" diff --git a/tiering/offload/substitute.py b/tiering/offload/substitute.py index 2a4f048..ede7ffc 100644 --- a/tiering/offload/substitute.py +++ b/tiering/offload/substitute.py @@ -148,13 +148,97 @@ def same_cut(own: dict, new: dict, d: Deps) -> str | None: return None -def choose(db, row, d: Deps) -> dict: +IMPORTS_KEY = "substitute_imports" +SWEEP_MAX = 5 # refused imports retried per choose() + + +def _imports(db) -> dict: + v = st.kv_get(db, IMPORTS_KEY, {}) + return v if isinstance(v, dict) else {} + + +def _note_import(db, d: Deps, remote, row_id): + """Record an import this code made for a candidate (AltMount's job id and the path it + gave back), so a refused one can be removed again by that id and no other way. None when + the importer does not tell its job ids.""" + job = (getattr(d.importer, "job_of", None) or (lambda _r: None))(remote) + if not job: + return None + imp = _imports(db) + imp[str(job)] = {"remote": remote, "row": row_id, "ts": d.clock()} + st.kv_set(db, IMPORTS_KEY, imp) + return str(job) + + +def forget_import(db, remote) -> None: + """The release at `remote` became a row's file: its records are not candidates any more.""" + try: + imp = _imports(db) + keep = {j: r for j, r in imp.items() if r.get("remote") != remote} + if len(keep) != len(imp): + st.kv_set(db, IMPORTS_KEY, keep) + except Exception as e: # noqa: BLE001 + log.warning("substitute: import records not updated (%s)", type(e).__name__) + + +def _drop_import(db, d: Deps, job) -> bool: + """Remove the import recorded under `job` through AltMount's own API, when it was refused + and no row uses its path. True when it is gone (or never was). A failure keeps the record + so a later pass tries again. Only a recorded job id is ever removed, never a name.""" + imp = _imports(db) + rec = imp.get(job) + if not rec: + return True + rm = getattr(d.importer, "remove", None) + if rm is None: + return False + remote = rec.get("remote") + if db.execute("SELECT 1 FROM files WHERE remote_path=? OR twin_remote_path=? LIMIT 1", + (remote, remote)).fetchone(): + imp.pop(job, None) # a row holds this path: it is no candidate now, and stays + st.kv_set(db, IMPORTS_KEY, imp) + return True + if any(j != job and r.get("remote") == remote and not r.get("refused") for j, r in imp.items()): + return False # another candidate was imported to the same path and is not refused + try: + rm(job) + except Exception as e: # noqa: BLE001 # AltMount down, or the call failed + log.warning("substitute: a refused import could not be removed (%s)", type(e).__name__) + return False + imp.pop(job, None) + st.kv_set(db, IMPORTS_KEY, imp) + return True + + +def _refuse_import(db, d: Deps, job) -> None: + if not job: + return + imp = _imports(db) + if job in imp: + imp[job]["refused"] = True + st.kv_set(db, IMPORTS_KEY, imp) + _drop_import(db, d, job) + + +def sweep_imports(db, d: Deps) -> int: + """Retry the removal of refused candidates an earlier try could not remove.""" + n = 0 + for job, rec in list(_imports(db).items()): + if rec.get("refused") and n < SWEEP_MAX: + n += 1 + _drop_import(db, d, job) + return n + + +def choose(db, row, d: Deps, apply=True) -> dict: """The release to switch to. {"ok": True, "source": "planned"|"unplanned", "nzb", "title", "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"] + if apply: + sweep_imports(db, d) try: own = d.ids_of(d.read_nzb(row["nzb_path"])) if row.get("nzb_path") else None except Exception as e: # noqa: BLE001 # unreadable archive: nothing can be proved disjoint @@ -168,16 +252,24 @@ def choose(db, row, d: Deps) -> dict: taken: dict = {} def accept(rel, raw): - """Import the candidate and probe its first bytes beside our own: None, or why not.""" + """Import the candidate and probe its first bytes beside our own: None, or why not. + A dry run imports nothing, so it cannot probe: its pick is unproven.""" + if not apply: + return None title = (rel.title if rel is not None else row.get("release_name")) or "release" + remote = job = None try: remote = d.importer.import_nzb(raw, title) + job = _note_import(db, d, remote, id) 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 + _refuse_import(db, d, job) return f"it cannot be imported or read ({type(e).__name__})" no = same_cut(mine, new, d) + if no is not None: + _refuse_import(db, d, job) if no is None: taken.update(remote=remote, facts={ "run_s": [mine.get("duration_s"), new.get("duration_s")], @@ -374,6 +466,13 @@ def undo(): time.time(), id)) db.execute("UPDATE files SET lib_path=?, updated_ts=? WHERE id=?", (new_share, time.time(), nid)) + if new_share != share: # another extension: the allowlist entry follows the row to its new path + try: + st.note_only_follow(db, share, new_share) + except Exception as e: # noqa: BLE001 # the row is switched; only a later re-offload is held back + log.warning("%s: substitute: the allowlist could not follow the row (%s)", id, + type(e).__name__) + forget_import(db, remote) st.log_event(db, id, "release_dead", {"nzb_path": row.get("nzb_path"), "nzb_path2": row.get("nzb_path2"), "replaced_by": nid, "source": pick["source"]}) @@ -539,7 +638,7 @@ def substitute_release(db, row, d: Deps, apply=True) -> ops.Result: """The one switch target: pick the release, import it, make it the row's file. This is the `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) + pick = choose(db, row, d, apply) 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"], **said}) @@ -549,7 +648,7 @@ def substitute_release(db, row, d: Deps, apply=True) -> ops.Result: **(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) + "release (nothing was imported, so its cut is not proved)", dry_run=True) return build(db, row, pick, d) From 8b6a3abd81200aa5410a20e78b114bc2eca28ca9 Mon Sep 17 00:00:00 2001 From: frindle <69526085+frindle@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:08:07 -0800 Subject: [PATCH 2/2] tiering: count every overdue row in the missing-disk guard The guard that refuses to mark rows gone counted only the rows the arrs were asked about in this pass. After a restart the lookups come back 10 a pass, so a missing disk's rows would have been marked 10 at a time. It now counts every row past the grace before the lookup budget is checked. The fresh answer of the recheck is kept, so a row whose arr has a file is not asked again every pass. --- tiering/offload/runner.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tiering/offload/runner.py b/tiering/offload/runner.py index 07bdb65..84f5564 100644 --- a/tiering/offload/runner.py +++ b/tiering/offload/runner.py @@ -677,6 +677,7 @@ def __init__(self, cfg: Config, deps: Deps, clock=time.time, sleep=time.sleep): self.only_blocked = False self._gone_verdict: dict = {} # id -> the arrs' last answer for a row whose L is missing self._gone_due: list = [] + self._gone_overdue = 0 # rows this pass whose L has been missing past the grace, asked or not self._gone_cache = None self.gone_next: dict = {} # id -> when its missing L is looked up in the arrs again self.only_follow: dict = {} # path -> allowlist entry it descends from (state.note_only_follow) @@ -1253,6 +1254,8 @@ def _l_gone(self, db, row, now, budget) -> bool: self._kv_set(db, "l_gone_since", gone) # (a dry run keeps it in memory only) since = gone.get(id, now) used = False + if cfg.l_gone_days > 0 and now - since >= cfg.l_gone_days * DAY: + self._gone_overdue += 1 # counted before the lookup budget, for the mass guard if now >= self.gone_next.get(id, 0.0): if budget[0] <= 0: return False # this pass's lookups are spent; the next pass goes on @@ -1314,12 +1317,17 @@ def _gone_finish(self, db, now): """The rows `_l_gone` found past the grace: mark them gone, once each, and alert. Many at once is not a set of deletions (a disk that is not mounted looks the same): none.""" due, self._gone_due = self._gone_due, [] + overdue, self._gone_overdue = self._gone_overdue, 0 if not due: return - if len(due) >= GONE_MASS: - self._once("l_gone_mass", "all", rows=len(due)) + # counted over every row past the grace, not only the ones the arrs were asked about + # this pass: after a restart the lookups come back 10 a pass, and a guard on `due` + # alone would mark a missing disk's rows 10 at a time + if max(overdue, len(due)) >= GONE_MASS: + self._once("l_gone_mass", "all", rows=max(overdue, len(due))) log.error("%d rows have had no L for over %g days; this looks like a missing " - "disk, not deletions: none is marked", len(due), self.cfg.l_gone_days) + "disk, not deletions: none is marked", max(overdue, len(due)), + self.cfg.l_gone_days) return for row, since, _loc in due: id = row["id"] @@ -1331,6 +1339,7 @@ def _gone_finish(self, db, now): except Exception as e: # noqa: BLE001 log.warning("%s: not marked gone: an arr did not answer (%s)", id, type(e).__name__) continue + self._gone_verdict[id] = loc # the fresh answer stands until the next hourly lookup if (loc is None or loc["paths"] or loc["has_file"] or loc["queued"] or self._find_disk(row)): continue @@ -1350,6 +1359,7 @@ def _gone_finish(self, db, now): def _reconcile(self, db, rows, now): budget = [GONE_LOOKUPS_PER_PASS] self._gone_due: list = [] + self._gone_overdue = 0 for row in rows: if row["state"] != "offloaded" or row["id"] in self.promote_running: continue