diff --git a/cascade/lane_d/main.py b/cascade/lane_d/main.py index b590c4bf5..28dbc5c44 100644 --- a/cascade/lane_d/main.py +++ b/cascade/lane_d/main.py @@ -58,6 +58,11 @@ def build_arg_parser() -> argparse.ArgumentParser: help="The published-weights registry JSON (default " "/published_weights.json); dedup fails closed " "without it.") + p.add_argument("--validator-lane-d-state", type=Path, default=None, + help="The validator's local lane_d_state.json (read-only). When set, " + "every refresh tick (and once at startup) closes an open entry " + "the validator judged final (crowned / lost / closed), so its " + "hotkey can submit again. Default: off.") p.add_argument("--per-ip-rpm", type=int, default=DEFAULT_PER_IP_RPM, help="Requests per sliding minute per client IP.") p.add_argument("--per-hotkey-rpm", type=int, default=DEFAULT_PER_HOTKEY_RPM, @@ -153,7 +158,8 @@ def main(argv: Sequence[str] | None = None) -> int: app = LaneDIntake(storage=S3VaultStorage(vault), reads=reads, minter=HippiusMultipartMinter(vault), cfg=cfg.lane_d, ops=ops, state_dir=state_dir, now=time.time, per_ip_rpm=args.per_ip_rpm, - per_hotkey_rpm=args.per_hotkey_rpm, cfg_at=cfg_at) + per_hotkey_rpm=args.per_hotkey_rpm, cfg_at=cfg_at, + verdict_state_path=args.validator_lane_d_state) # #842: refresh once at startup, then every queue_poll_seconds, so # reveals and TTL expiries reach the queue file without traffic. app.tick() @@ -162,9 +168,10 @@ def main(argv: Sequence[str] | None = None) -> int: handler_class=_handler_class(args.request_timeout)) host, port = server.server_address[:2] log.info("lane_d_intake_up intake-laned up: %s on %s:%d upload_path=%s vault=%s/%s " - "state=%s lane_d_active_from=%d refresh_every_s=%d", SERVICE, host, port, - UPLOAD_PATH, ops.vault_bucket, ops.vault_prefix, state_dir, - int(cfg.lane_d.from_block), int(ops.queue_poll_seconds)) + "state=%s lane_d_active_from=%d refresh_every_s=%d verdicts=%s", SERVICE, host, + port, UPLOAD_PATH, ops.vault_bucket, ops.vault_prefix, state_dir, + int(cfg.lane_d.from_block), int(ops.queue_poll_seconds), + args.validator_lane_d_state or "off") timer.start() try: server.serve_forever() diff --git a/cascade/lane_d/ops_jobs.py b/cascade/lane_d/ops_jobs.py index eaa599524..4c05f0bac 100644 --- a/cascade/lane_d/ops_jobs.py +++ b/cascade/lane_d/ops_jobs.py @@ -539,7 +539,8 @@ def _licence(intake_dir: Path, digest: str, hotkey: str) -> str: from .service import LICENCES, QUEUE_FILENAME doc = _read_json(Path(intake_dir) / QUEUE_FILENAME, "intake queue") - rows = [r for r in (doc.get("entries") if isinstance(doc, dict) else None) or [] + rows = [r for r in [*((doc.get("entries") if isinstance(doc, dict) else None) or []), + *((doc.get("retired") if isinstance(doc, dict) else None) or [])] if isinstance(r, dict) and r.get("digest") == digest and r.get("hotkey") == hotkey] lic = rows[0].get("licence") if rows else None if not isinstance(lic, str) or lic not in LICENCES: diff --git a/cascade/lane_d/service.py b/cascade/lane_d/service.py index c136a1c97..247e61947 100644 --- a/cascade/lane_d/service.py +++ b/cascade/lane_d/service.py @@ -31,6 +31,11 @@ NOT rewritten (the validator reads this file); lane D holds no provider key and charges nothing. +Verdict sync: with ``verdict_state_path`` (the validator's local +``lane_d_state.json``, read-only) every timer tick closes an open entry the +validator judged final (:data:`FINAL_VERDICT_STATUSES`), so the hotkey can +submit again; a resubmit keeps the replaced closed row under ``retired``. + Grants (presigned URLs) appear only in the submit response: never in a log record, a file under the state dir, or the queue view. @@ -110,6 +115,20 @@ ENTRY_STATES = (SUBMITTED, READY, REVEALED, READY_EXPIRED, CLOSED) OPEN_STATES = (READY, REVEALED) +# The verdict sync: the intake closes an open entry once the validator's +# local lane D state (``lane_d_state.json``, read-only) holds a final verdict +# for the same (hotkey, digest). Final = every validator entry status that +# is not open (the validator's ``OPEN_STATUSES`` are ``pending`` / ``hold``, +# and no path moves a ``crowned`` / ``lost`` / ``closed`` entry back): a +# ``pending`` or held entry is re-queueable and stays open here. +VALIDATOR_STATE_SCHEMA = "lane-d-state/1" +FINAL_VERDICT_STATUSES = ("crowned", "lost", "closed") +# Entries a new submit of the same hotkey replaced (closed ones only): kept +# under this top-level key of the queue file so a judged digest stays owned +# (``digest_owned`` / ``entry_closed``) and a crowned king's row (files, +# licence) is still found after its hotkey submits again. +RETIRED_KEY = "retired" + # The commitment a readied entry reveals: ``metro-v1:weights:c:hippius:`` # where ``ref`` is the entry's vault prefix without its trailing ``/``. COMMIT_PREFIX = "metro-v1:weights:" @@ -349,7 +368,8 @@ def __init__(self, *, storage: LaneDStorage, reads: LaneDReads, minter: GrantMin ops, state_dir, now: Callable[[], float], per_ip_rpm: int = DEFAULT_PER_IP_RPM, per_hotkey_rpm: int = DEFAULT_PER_HOTKEY_RPM, - cfg_at: Callable[[int], object] | None = None): + cfg_at: Callable[[int], object] | None = None, + verdict_state_path=None): if not isinstance(minter, GrantMinter): raise TypeError(f"minter must be a GrantMinter; got {type(minter).__name__}") if getattr(minter, "upload_path", None) != UPLOAD_PATH: @@ -378,7 +398,13 @@ def __init__(self, *, storage: LaneDStorage, reads: LaneDReads, minter: GrantMin self._limiter = _RateLimiter(RATE_LIMIT_MAX_KEYS) self._last_ts: dict[tuple[str, str], int] = {} self._refreshed_block: int | None = None + self._retired: list[dict] = [] self._entries: dict[str, dict] = self._load() + # The validator's lane D state file (None = the verdict sync is off) + # and the (inode, size, mtime) of the last copy fully synced from. + self.verdict_state_path = (Path(verdict_state_path) + if verdict_state_path is not None else None) + self._verdicts_seen: tuple | None = None # ── persistence ────────────────────────────────────────────────────────── @@ -407,14 +433,24 @@ def _load(self) -> dict[str, dict]: raise RuntimeError(f"lane D intake queue {self.queue_path} holds a malformed " f"entry; refusing to start") out[rec["hotkey"]] = rec + retired = doc.get(RETIRED_KEY, []) + if not isinstance(retired, list) or any( + not isinstance(r, dict) or not isinstance(r.get("hotkey"), str) + or not isinstance(r.get("digest"), str) or r.get("state") != CLOSED + for r in retired): + raise RuntimeError(f"lane D intake queue {self.queue_path} holds a malformed " + f"retired entry; refusing to start") + self._retired = retired return out def _write_queue(self) -> None: """Write the queue atomically (temp file, fsync, ``os.replace``).""" self.state_dir.mkdir(parents=True, exist_ok=True) - text = json.dumps({"schema": QUEUE_SCHEMA, - "entries": [self._entries[k] for k in sorted(self._entries)]}, - sort_keys=True, indent=1) + doc = {"schema": QUEUE_SCHEMA, + "entries": [self._entries[k] for k in sorted(self._entries)]} + if self._retired: + doc[RETIRED_KEY] = self._retired + text = json.dumps(doc, sort_keys=True, indent=1) tmp = self.queue_path.with_name(f".{self.queue_path.name}.tmp-{os.getpid()}") try: with open(tmp, "wb") as f: @@ -435,18 +471,18 @@ def _write_queue(self) -> None: finally: os.close(fd) - def _commit(self, before: dict[str, dict]) -> None: + def _commit(self, before: tuple[dict[str, dict], list[dict]]) -> None: """Persist the in-memory change, or roll it back and refuse.""" try: self._write_queue() except Exception as e: # noqa: BLE001 — any write failure fails closed - self._entries = before + self._entries, self._retired = before log.error("lane_d_intake_unavailable state write failed (%s); change rolled back", type(e).__name__) raise _Refusal(503, "state_unavailable", "the queue could not be persisted") from None - def _snapshot(self) -> dict[str, dict]: - return copy.deepcopy(self._entries) + def _snapshot(self) -> tuple[dict[str, dict], list[dict]]: + return copy.deepcopy(self._entries), copy.deepcopy(self._retired) # ── views ──────────────────────────────────────────────────────────────── @@ -555,10 +591,12 @@ def tick(self) -> int | None: write failed (logged; the next tick retries; nothing changes).""" with self._lock: try: - return self._refresh() + head = self._refresh() except _Refusal as r: log.warning("lane_d_intake_unavailable background refresh skipped (%s)", r.code) - return None + head = None + self.sync_verdicts() + return head def refresh_timer(self, interval_s: float | None = None, *, wait: Callable[[float], bool] | None = None) -> RefreshTimer: @@ -677,8 +715,18 @@ def _owner_of(self, digest: str, besides: str) -> str | None: for hk, rec in self._entries.items(): if hk != besides and rec["digest"] == digest: return hk + for rec in self._retired: + if rec["hotkey"] != besides and rec["digest"] == digest: + return rec["hotkey"] return None + def _closed_digest(self, hotkey: str, digest: str) -> bool: + """Has ``hotkey`` already had ``digest`` closed (judged or voided)?""" + own = self._entries.get(hotkey) + if own is not None and own["state"] == CLOSED and own["digest"] == digest: + return True + return any(r["hotkey"] == hotkey and r["digest"] == digest for r in self._retired) + def _open_weights_elsewhere(self, weights: str, hotkey: str) -> bool: return any(rec["state"] in OPEN_STATES and rec.get("weights") == weights for hk, rec in self._entries.items() if hk != hotkey) @@ -707,6 +755,8 @@ def _submit(self, hotkey: str, digest: str, context: int, body: bytes) -> tuple[ if own is not None and own["state"] in OPEN_STATES: raise _Refusal(409, "hotkey_entry_open", "this hotkey already has an open entry") + if self._closed_digest(hotkey, digest): + raise _Refusal(409, "entry_closed", "this checkpoint was already judged or closed") weights = manifest["files"]["weights.safetensors"]["sha256"] if weights in self._published() or self._open_weights_elsewhere(weights, hotkey): raise _Refusal(409, "duplicate_weights", @@ -720,6 +770,8 @@ def _submit(self, hotkey: str, digest: str, context: int, body: bytes) -> tuple[ sizes = {n: int(manifest["files"][n]["size"]) for n in sorted(names)} grants = self._mint(prefix, sizes) before = self._snapshot() + if own is not None and own["state"] == CLOSED: + self._retired.append(own) self._entries[hotkey] = { "hotkey": hotkey, "digest": digest, "context": int(context), "state": SUBMITTED, "files": sizes, "weights": weights, "reveal_block": None, "closed_reason": None, @@ -879,7 +931,7 @@ def _check_objects(self, prefix: str, digest: str, files: dict[str, int]) -> str raise _Refusal(503, "storage_unavailable", "the vault is unavailable; retry") from None return str(manifest["files"]["weights.safetensors"]["sha256"]) - # ── close (W5h/W17 wire it to the judged status) ───────────────────────── + # ── close (wired to the judged status by :meth:`sync_verdicts`) ────────── def close(self, hotkey: str, digest: str, reason: str) -> dict: """Move an entry to ``closed`` and free its slots; returns its row.""" @@ -898,6 +950,71 @@ def close(self, hotkey: str, digest: str, reason: str) -> dict: log.info("lane_d_intake_closed hotkey=%s digest=%s reason=%s", hotkey, digest, reason) return self._row(rec) + # ── the verdict sync (the validator's judged status closes an entry) ───── + + def _read_verdicts(self, path: Path) -> tuple[tuple, dict] | None: + """``(fingerprint, entries)`` of the validator's lane D state, or + ``None`` when it is absent, unreadable, mid-write or not a + ``lane-d-state/1`` object (logged; nothing closes on it).""" + try: + st = path.stat() + fp = (st.st_ino, st.st_size, st.st_mtime_ns) + if fp == self._verdicts_seen: + return fp, {} + doc = json.loads(path.read_bytes()) + if os.stat(path).st_mtime_ns != st.st_mtime_ns: + raise ValueError("the file changed while it was read") + except (OSError, UnicodeDecodeError, ValueError) as e: + log.warning("lane_d_intake_unavailable verdict source %s unreadable (%s); nothing " + "closed this tick", + path, type(e).__name__) + return None + if not isinstance(doc, dict) or doc.get("schema") != VALIDATOR_STATE_SCHEMA \ + or not isinstance(doc.get("entries"), dict): + log.warning("lane_d_intake_unavailable verdict source %s is not a %s object; nothing " + "closed this tick", path, VALIDATOR_STATE_SCHEMA) + return None + return fp, doc["entries"] + + def sync_verdicts(self) -> list[dict]: + """Close every open entry whose (hotkey, digest) the validator's lane D + state holds with a final status (:data:`FINAL_VERDICT_STATUSES`), + ``closed_reason`` = the validator's reason. Off without + ``verdict_state_path``. The file is parsed outside the request lock and + only when it changed since the last full sync; it never raises. + Returns the closed rows.""" + path = self.verdict_state_path + if path is None: + return [] + with self._lock: + if not any(r["state"] in OPEN_STATES for r in self._entries.values()): + return [] + got = self._read_verdicts(path) + if got is None: + return [] + fp, verdicts = got + closed: list[dict] = [] + complete = True + with self._lock: + for hk in sorted(self._entries): + rec = self._entries[hk] + v = verdicts.get(rec["digest"]) + if rec["state"] not in OPEN_STATES or not isinstance(v, dict) \ + or v.get("hotkey") != hk or v.get("status") not in FINAL_VERDICT_STATUSES: + continue + reason = v.get("reason") + reason = reason if isinstance(reason, str) and reason else v["status"] + try: + closed.append(self.close(hk, rec["digest"], reason)) + except Exception as e: # noqa: BLE001 — the next change retries + complete = False + log.warning("lane_d_intake_unavailable verdict close failed for %s (%s)", + rec["digest"], type(e).__name__) + break + if complete and verdicts: + self._verdicts_seen = fp + return closed + class RefreshTimer: """Refresh the intake queue without traffic (#842). @@ -954,7 +1071,8 @@ def stop(self, timeout: float | None = 5.0) -> None: __all__ = [ - "DEFAULT_PER_HOTKEY_RPM", "DEFAULT_PER_IP_RPM", "ENTRY_STATES", "FRESHNESS_SECONDS", + "DEFAULT_PER_HOTKEY_RPM", "DEFAULT_PER_IP_RPM", "ENTRY_STATES", "FINAL_VERDICT_STATUSES", + "FRESHNESS_SECONDS", "GrantMinter", "LICENCES", "LICENCE_ATTESTATION", "LaneDIntake", "LaneDReads", "RefreshTimer", "MAX_BODY_BYTES", "OFFERED_UPLOAD_PATHS", "OPEN_STATES", "QUEUE_FILENAME", "QUEUE_PATH", "RATE_LIMIT_MAX_KEYS", "READY_PATH", "REFUSAL_CODES", "SUBMIT_PATH", "UPLOAD_PATH", diff --git a/cascade/validator/lane_d_inputs.py b/cascade/validator/lane_d_inputs.py index 358e4d91e..1896762c0 100644 --- a/cascade/validator/lane_d_inputs.py +++ b/cascade/validator/lane_d_inputs.py @@ -1206,8 +1206,10 @@ def _row(self, digest: str) -> dict | None: if not path.exists(): return None doc = json.loads(path.read_text(encoding="utf-8")) - rows = [r for r in doc.get("entries", []) if isinstance(r, dict) - and r.get("digest") == digest] + # ``retired``: closed rows a resubmit of the same hotkey replaced (a + # crowned king's checkpoint stays fetchable after its hotkey resubmits). + rows = [r for r in [*doc.get("entries", []), *doc.get("retired", [])] + if isinstance(r, dict) and r.get("digest") == digest] return sorted(rows, key=lambda r: str(r.get("hotkey")))[0] if rows else None def _url(self, key: str) -> str: diff --git a/tests/accept/w3/test_w3_verdict_sync.py b/tests/accept/w3/test_w3_verdict_sync.py new file mode 100644 index 000000000..30aec2e7e --- /dev/null +++ b/tests/accept/w3/test_w3_verdict_sync.py @@ -0,0 +1,232 @@ +"""W3: the intake closes an entry once the validator judged it final. + +Live 2026-12-03: ``close()`` had no caller, so every judged entry stayed +``revealed`` and its hotkey's next submit was refused ``409 +hotkey_entry_open`` (one lane D submission per hotkey, for life). The intake +now reads the validator's local ``lane_d_state.json`` (``verdict_state_path``, +read-only; off by default) on every refresh tick and closes an open entry +whose (hotkey, digest) holds a final status (``crowned`` / ``lost`` / +``closed``); ``pending`` / ``hold`` stay open. No real sleeps, no torch. +""" + +from __future__ import annotations + +import json +import os + +from .helpers import Env, Miner, checkpoint, digest_of, manifest + + +def _env(tmp_path) -> Env: + env = Env(tmp_path) + env.verdicts = tmp_path / "validator" / "lane_d_state.json" + env.verdicts.parent.mkdir() + env.app.verdict_state_path = env.verdicts + return env + + +def _write_state(env: Env, entries: dict) -> None: + """The validator's state as it writes it (canonical JSON); every write + moves the mtime so the intake sees a change.""" + doc = {"schema": "lane-d-state/1", "boundary": 7, "entries": entries, + "house": {}, "king": {}, "prior_kings": []} + env.verdicts.write_text(json.dumps(doc, sort_keys=True, separators=(",", ":"))) + st = env.verdicts.stat() + bump = getattr(env, "_bump", 0) + 1 + env._bump = bump + os.utime(env.verdicts, ns=(st.st_atime_ns, st.st_mtime_ns + bump * 1_000_000_000)) + + +def _verdict(hotkey: str, status: str, reason: str) -> dict: + return {"hotkey": hotkey, "status": status, "reason": reason, "used_windows": [], + "confirm": None, "frozen_set": None} + + +def _entered(env: Env, name: str, coldkey: str | None = None) -> tuple[Miner, dict, str]: + m = Miner(env, name, coldkey=coldkey or f"ck-{name}") + files = checkpoint(name) + r = m.enter(files) + assert r.status == 200, r + return m, files, digest_of(manifest(files)) + + +def _queue_file(env: Env) -> dict: + return json.loads((env.state_dir / "lane_d_intake_queue.json").read_text(encoding="utf-8")) + + +def _file_rec(env: Env, hotkey: str) -> dict: + (rec,) = [r for r in _queue_file(env)["entries"] if r["hotkey"] == hotkey] + return rec + + +def test_lost_and_crowned_close_pending_stays_open(tmp_path): + env = _env(tmp_path) + lost, _, d_lost = _entered(env, "vs-lost") + king, _, d_king = _entered(env, "vs-king") + gate, _, d_gate = _entered(env, "vs-gate") + pend, _, d_pend = _entered(env, "vs-pend") + hold, _, d_hold = _entered(env, "vs-hold") + _write_state(env, { + d_lost: _verdict(lost.hotkey, "lost", "lost_duel"), + d_king: _verdict(king.hotkey, "crowned", "crowned"), + d_gate: _verdict(gate.hotkey, "closed", "checkpoint_fault"), + d_pend: _verdict(pend.hotkey, "pending", "before_eval_delay"), + d_hold: _verdict(hold.hotkey, "hold", "bench_hold"), + }) + assert env.app.tick() is not None + assert env.entry(lost.hotkey, d_lost)["state"] == "closed" + assert env.entry(king.hotkey, d_king)["state"] == "closed" + assert env.entry(gate.hotkey, d_gate)["state"] == "closed" + assert env.entry(pend.hotkey, d_pend)["state"] != "closed" + assert env.entry(hold.hotkey, d_hold)["state"] != "closed" + # the persisted reason is the validator's + assert _file_rec(env, lost.hotkey)["closed_reason"] == "lost_duel" + assert _file_rec(env, king.hotkey)["closed_reason"] == "crowned" + assert _file_rec(env, gate.hotkey)["closed_reason"] == "checkpoint_fault" + assert _file_rec(env, pend.hotkey)["closed_reason"] is None + + +def test_final_statuses_are_the_validators_non_open_statuses(): + from cascade.lane_d.service import FINAL_VERDICT_STATUSES + from cascade.validator.lane_d_queue import OPEN_STATUSES + from cascade.validator.lane_d_report import ENTRY_STATUSES + + assert set(FINAL_VERDICT_STATUSES) == set(ENTRY_STATUSES) - set(OPEN_STATUSES) + + +def test_unknown_digest_and_hotkey_mismatch_are_ignored(tmp_path): + env = _env(tmp_path) + m, _, dig = _entered(env, "vs-mis") + other = Miner(env, "vs-other") + _write_state(env, {dig: _verdict(other.hotkey, "lost", "lost_duel"), + "f" * 64: _verdict(m.hotkey, "lost", "lost_duel")}) + env.app.tick() + assert env.entry(m.hotkey, dig)["state"] != "closed" + + +def test_unreadable_or_missing_file_closes_nothing(tmp_path): + env = _env(tmp_path) + m, _, dig = _entered(env, "vs-bad") + env.app.tick() # absent file: no crash + assert env.entry(m.hotkey, dig)["state"] != "closed" + good = json.dumps({"schema": "lane-d-state/1", + "entries": {dig: _verdict(m.hotkey, "lost", "lost_duel")}}) + for raw in (good[: len(good) // 2], "[]", json.dumps({"schema": "other/1", "entries": {}}), + json.dumps({"schema": "lane-d-state/1", "entries": []})): + env.verdicts.write_text(raw) + assert env.app.sync_verdicts() == [] + assert env.entry(m.hotkey, dig)["state"] != "closed" + env.verdicts.write_bytes(b"\xff\xfe") + assert env.app.sync_verdicts() == [] + # then a whole file closes it + _write_state(env, {dig: _verdict(m.hotkey, "lost", "lost_duel")}) + assert [r["state"] for r in env.app.sync_verdicts()] == ["closed"] + + +def test_off_by_default(tmp_path): + env = Env(tmp_path) + m, _, dig = _entered(env, "vs-off") + assert env.app.verdict_state_path is None + env.app.tick() + assert env.app.sync_verdicts() == [] + assert env.entry(m.hotkey, dig)["state"] != "closed" + + +def test_closed_hotkey_submits_again_and_rules_still_hold(tmp_path): + env = _env(tmp_path) + m, files, dig = _entered(env, "vs-again") + nxt = checkpoint("vs-again-2") + r = m.submit(nxt) + assert r.status == 409 and r.code == "hotkey_entry_open", r + _write_state(env, {dig: _verdict(m.hotkey, "crowned", "crowned")}) + env.app.tick() + assert env.entry(m.hotkey, dig)["state"] == "closed" + # the judged checkpoint itself cannot come back, from anyone + r = m.submit(files) + assert r.status == 409 and r.code == "entry_closed", r + other = Miner(env, "vs-again-other") + r = other.submit(files) + assert r.status == 409 and r.code == "digest_owned", r + # a new checkpoint is accepted, and the crowned row is kept as retired + r = m.submit(nxt) + assert r.status == 201, r + doc = _queue_file(env) + assert [(x["hotkey"], x["digest"], x["state"], x["closed_reason"]) + for x in doc["retired"]] == [(m.hotkey, dig, "closed", "crowned")] + # still owned after a restart (the retired rows persist) + env.restart() + env.app.verdict_state_path = env.verdicts + r = other.submit(files) + assert r.status == 409 and r.code == "digest_owned", r + # duplicate_weights: another hotkey's open entry's weights are refused + m.upload(nxt) + assert m.ready(nxt).status == 200 + copy = checkpoint("vs-again-copy", weights=nxt["weights.safetensors"]) + r = other.submit(copy) + assert r.status == 409 and r.code == "duplicate_weights", r + # digest_owned: another hotkey's live digest is refused + r = other.submit(nxt) + assert r.status == 409 and r.code == "digest_owned", r + + +def test_unchanged_file_is_not_reparsed(tmp_path, monkeypatch): + env = _env(tmp_path) + a, _, da = _entered(env, "vs-once-a") + b, _, db = _entered(env, "vs-once-b") + _write_state(env, {da: _verdict(a.hotkey, "lost", "lost_duel"), + db: _verdict(b.hotkey, "pending", "pending_floor")}) + assert len(env.app.sync_verdicts()) == 1 + import json as _json + + from cascade.lane_d import service + + calls = [] + real = _json.loads + monkeypatch.setattr(service.json, "loads", lambda raw, *k, **kw: (calls.append(1), + real(raw, *k, **kw))[1]) + assert env.app.sync_verdicts() == [] + assert calls == [] # same file: not read again + _write_state(env, {da: _verdict(a.hotkey, "lost", "lost_duel"), + db: _verdict(b.hotkey, "lost", "gate_regression")}) + closed = env.app.sync_verdicts() + assert [(r["hotkey"], r["state"]) for r in closed] == [(b.hotkey, "closed")] + assert _file_rec(env, b.hotkey)["closed_reason"] == "gate_regression" + + +def test_cli_flag_default_off_and_parsed(): + from cascade.lane_d.main import build_arg_parser + + base = ["--state-dir", "/x", "--chain-toml", "/y"] + assert build_arg_parser().parse_args(base).validator_lane_d_state is None + got = build_arg_parser().parse_args( + [*base, "--validator-lane-d-state", "/root/cascade/lane_d_state.json"]) + assert str(got.validator_lane_d_state) == "/root/cascade/lane_d_state.json" + + +def test_retired_rows_still_serve_grants_and_licence(tmp_path): + """A crowned king's row stays readable after its hotkey resubmits: the + eval host's prefetch grants and the king publish licence fall back to + ``retired``.""" + from cascade.lane_d.ops_jobs import _licence + from cascade.validator.lane_d_inputs import VaultGetGrants + + env = _env(tmp_path) + m, _, dig = _entered(env, "vs-ret") + _write_state(env, {dig: _verdict(m.hotkey, "crowned", "crowned")}) + env.app.tick() + assert m.submit(checkpoint("vs-ret-2")).status == 201 + assert all(r["digest"] != dig for r in _queue_file(env)["entries"]) + assert _licence(env.state_dir, dig, m.hotkey) == "MIT" + + class Vault: + bucket = "b" + + def __call__(self): + return self + + def generate_presigned_url(self, op, Params, ExpiresIn, HttpMethod): + return f"https://vault.invalid/{Params['Key']}" + + g = VaultGetGrants(Vault(), vault_prefix="lane-d", intake_state_dir=env.state_dir)(dig) + assert g is not None and g["hotkey"] == m.hotkey and g["digest"] == dig + assert sorted(g["files"]) == sorted(_queue_file(env)["retired"][0]["files"])