text stringlengths 0 1.47k |
|---|
con.execute("COMMIT") |
return {**stored, "_etag": str(new_etag)} |
except (CosmosResourceNotFoundError, CosmosAccessConditionFailedError): |
raise |
except Exception as e: # noqa: BLE001 |
try: |
con.execute("ROLLBACK") |
except Exception: # noqa: BLE001 |
pass |
raise CosmosHttpResponseError(str(e)) from e |
finally: |
con.close() |
async def upsert_item(self, body: dict, **_kw) -> dict: |
item_id = str(body.get("id") or "") |
con = _connect(self._path) |
try: |
con.execute("BEGIN IMMEDIATE") |
row = con.execute("SELECT etag FROM control WHERE id=?", (item_id,)).fetchone() |
new_etag = (int(row[0]) + 1) if row else 1 |
stored = {k: v for k, v in body.items() if k != "_etag"} |
con.execute("INSERT OR REPLACE INTO control(id, pk, body, etag, expires) " |
"VALUES(?,?,?,?,?)", |
(item_id, str(body.get("pk") or ""), json.dumps(stored), new_etag, |
_expires_at(stored))) |
con.execute("COMMIT") |
return {**stored, "_etag": str(new_etag)} |
except Exception as e: # noqa: BLE001 |
try: |
con.execute("ROLLBACK") |
except Exception: # noqa: BLE001 |
pass |
raise CosmosHttpResponseError(str(e)) from e |
finally: |
con.close() |
async def delete_item(self, item: str, partition_key: str = "", **_kw) -> None: |
con = _connect(self._path) |
try: |
if self._live(con, item) is None: |
raise CosmosResourceNotFoundError(item) |
con.execute("DELETE FROM control WHERE id=?", (item,)) |
finally: |
con.close() |
# ===== file: gateway/control_store.py ===== |
"""Durable transactional control state for the harness gateway (HR-INF-010/011/012/013). |
Hot control state (idempotency reservations, per-session execution leases with |
fencing tokens, and monotonic response/cancellation state) lives here in a |
dedicated Cosmos NoSQL container — NOT on the shared Gremlin partition, and NOT |
in per-process dicts that don't survive a replica or coordinate across replicas. |
Why Cosmos NoSQL: point reads, atomic create (409 on duplicate id → race-safe |
reservation), ETag optimistic concurrency (if_match CAS), per-item TTL, and a |
partition key so one org can't be a global hot spot. Auth is AAD via the |
gateway's managed identity (no key on the hot path). |
Design contract: |
- Every item has `pk` (partition key) = f"org::{org}" so all of an org's control |
state co-locates and no cross-org scan is ever needed. |
- Idempotency: id=f"idem::{org}::{sha}". reserve() does create_item; a 409 means |
another request already reserved it — the caller reads the winner and replays. |
- Lease: id=f"lease::{org}::{sid}". A monotonic integer `fence` is bumped once per |
turn; the turn carries its fence and only commits a checkpoint if the lease |
fence still equals it (a newer turn would have advanced it → stale writer skips). |
- Response control: id=f"resp::{org}::{rid}". `terminal` is a one-way latch — once |
a terminal status (cancelled/completed/failed/incomplete) is set, no later write |
may move it back to a live status. This makes cancellation monotonic. |
FAIL-CLOSED where correctness demands it (idempotency reserve), best-effort where |
it only optimizes (lease/heartbeat) — each call site decides. When COSMOS_ENDPOINT |
is unset (local dev), enabled() is False and callers fall back to prior behavior. |
""" |
from __future__ import annotations |
import os |
import time |
_ENDPOINT = os.environ.get("COSMOS_ENDPOINT", "").strip() |
_DB = os.environ.get("HR_CONTROL_DB", "agentstudio") |
_CONTAINER = os.environ.get("HR_CONTROL_CONTAINER", "hr_control") |
# Optional master key (fallback); AAD via managed identity is preferred. |
_KEY = os.environ.get("COSMOS_KEY", "").strip() |
_client = None # CosmosClient (aio) |
_cont = None # ContainerProxy |
def _local_mode() -> bool: |
"""Self-hosted: no hosted document store configured, so use the SQLite container. |
Mirrors how backing.py chooses its storage, so one env var story covers both.""" |
if _ENDPOINT: |
return False |
return (os.environ.get("HR_BACKING", "").strip().lower() or "local") == "local" |
def _exceptions(): |
"""The error namespace matching the ACTIVE container. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.