text
stringlengths
0
1.47k
async def resp_set_cursor(org: str, rid: str, cursor: int) -> None:
"""Persist the turn's harvest cursor — how many of THIS turn's events (sandbox per-turn index)
have been durably flushed to the trace. This is the resume point if the owning replica dies and
another adopts the turn: it polls the sandbox with since=cursor, so no already-flushed event is
re-written or re-emitted. Monotonic (never moves backward); best-effort; never revives a terminal
record. Cheap single-field patch on the existing resp:: control doc."""
cont = await _container()
cex = _exceptions()
doc_id = f"resp::{org}::{rid}"
try:
curr = await cont.read_item(doc_id, partition_key=_pk(org))
except cex.CosmosResourceNotFoundError:
return # turn not registered yet — nothing to update
if str(curr.get("status")) in _TERMINAL:
return # already settled — cursor is moot
if int(cursor) <= int(curr.get("harvest_cursor", 0) or 0):
return # monotonic: never move the resume point backward
curr["harvest_cursor"] = int(cursor)
curr["ts"] = time.time()
try:
await cont.replace_item(doc_id, curr, etag=curr["_etag"], match_condition=_IF_MATCH)
except cex.CosmosAccessConditionFailedError:
pass # a concurrent write won — fine, cursor is advisory
async def resp_get_cursor(org: str, rid: str) -> int:
"""The durable harvest cursor for a turn (0 if none / unreadable). See resp_set_cursor."""
cont = await _container()
cex = _exceptions()
try:
curr = await cont.read_item(f"resp::{org}::{rid}", partition_key=_pk(org))
return int(curr.get("harvest_cursor", 0) or 0)
except cex.CosmosResourceNotFoundError:
return 0
except Exception: # noqa: BLE001
return 0
async def resp_mark_terminal(org: str, rid: str, status: str, ttl_s: int) -> dict:
"""One-way transition to a terminal status. Returns the record (with sid +
runner_turn_id) so the caller can propagate cancellation to the runner.
Idempotent: re-marking an already-terminal record just returns it."""
cont = await _container()
cex = _exceptions()
doc_id = f"resp::{org}::{rid}"
for _ in range(5):
try:
cur = await cont.read_item(doc_id, partition_key=_pk(org))
if str(cur.get("status")) in _TERMINAL:
return cur
cur.update(status=status, ts=time.time())
try:
await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
return cur
except cex.CosmosAccessConditionFailedError:
continue
except cex.CosmosResourceNotFoundError:
rec = {"id": doc_id, "pk": _pk(org), "kind": "resp", "status": status,
"sid": "", "runner_turn_id": "", "ts": time.time(), "ttl": int(ttl_s)}
try:
await cont.create_item(rec)
return rec
except cex.CosmosResourceExistsError:
continue
return {}
async def resp_is_cancelled(org: str, rid: str) -> bool:
try:
cont = await _container()
cex = _exceptions()
try:
cur = await cont.read_item(f"resp::{org}::{rid}", partition_key=_pk(org))
except cex.CosmosResourceNotFoundError:
return False
return str(cur.get("status")) == "cancelled"
except Exception:
return False
async def try_lock(name: str, ttl_s: int) -> bool:
"""One-shot distributed mutex via atomic create_item: returns True iff WE created the lock doc
(nobody else holds it), False if it already exists (another holder — skip this cycle). Per-item
TTL auto-expires the lock, so a holder that dies never wedges it. RAISES on a store error so the
caller can distinguish 'someone else has it' (skip) from 'store unavailable' (the caller's choice
to fall back). Used for single-flight periodic work (the winner runs it, losers skip)."""
cex = _exceptions()
try:
cont = await _container()
await cont.create_item({"id": f"lock::{name}", "pk": "org::_system", "kind": "lock",
"ts": time.time(), "ttl": int(ttl_s)})
return True
except cex.CosmosResourceExistsError:
return False
# ── API-key hot-read cache (HR-INF-010) ────────────────────────────────────────────────
# The public Bearer auth read (_apikey_resolve) hit the shared Gremlin partition on EVERY public
# request. These make the control store the hot-path read: a SELF-KEYED doc (pk == id == the token
# hash — the org is unknown pre-auth, so an org partition can't serve it) that is a write-through