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
15 changes: 11 additions & 4 deletions cascade/lane_d/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ def build_arg_parser() -> argparse.ArgumentParser:
help="The published-weights registry JSON (default "
"<state-dir>/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,
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion cascade/lane_d/ops_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
142 changes: 130 additions & 12 deletions cascade/lane_d/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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<ctx>:hippius:<ref>``
# where ``ref`` is the entry's vault prefix without its trailing ``/``.
COMMIT_PREFIX = "metro-v1:weights:"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 ──────────────────────────────────────────────────────────

Expand Down Expand Up @@ -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:
Expand All @@ -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 ────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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",
Expand All @@ -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,
Expand Down Expand Up @@ -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."""
Expand All @@ -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).
Expand Down Expand Up @@ -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",
Expand Down
6 changes: 4 additions & 2 deletions cascade/validator/lane_d_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading