"""Durable, concurrent Responses API calls with conservative budget accounting. Every network attempt is reserved and committed to SQLite before dispatch. A logical call reuses the first successful result; only technical failures retry. Missing usage and uncertain transport outcomes retain their entire reservation. """ from collections import deque from datetime import datetime, timezone from email.utils import parsedate_to_datetime import fcntl import hashlib import json import math import os from pathlib import Path import sqlite3 import threading import time import requests MODEL = "gpt-5.6-luna" RATES = {"input": 0.20, "cached_input": 0.02, "output": 1.20} MAX_ATTEMPTS = 3 MAX_OUTPUT_TOKENS = 8192 TRANSIENT_STATUSES = {"transport_uncertain", "response_uncertain", "parse_error", "interrupted_uncertain"} class BudgetExceeded(RuntimeError): """The next conservative reservation would exceed the total budget.""" class CallFailed(RuntimeError): """A preserved API attempt cannot be retried within this call's policy.""" def __init__(self, identifier, record): self.record = record super().__init__(f"{identifier}: {record['status']} (attempt {record['attempt_id']})") def _json(value): return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False) def _hash(value): return hashlib.sha256(_json(value).encode()).hexdigest() def _utc(): return datetime.now(timezone.utc).isoformat() def _usage_cost(body): """Output tokens already include reasoning tokens; never count them twice.""" usage = body.get("usage") or {} if not isinstance(usage, dict): return None details = usage.get("input_tokens_details") or {} if not isinstance(details, dict): return None cached = details.get("cached_tokens", 0) if (any(type(usage.get(k)) is not int or usage[k] < 0 for k in ("input_tokens", "output_tokens")) or type(cached) is not int or not 0 <= cached <= usage["input_tokens"]): return None uncached = usage["input_tokens"] - cached known = (uncached * RATES["input"] + cached * RATES["cached_input"] + usage["output_tokens"] * RATES["output"]) / 1e6 premium = uncached * RATES["input"] * 0.25 / 1e6 return known, premium def _cost_summary(db, budget): known, premium, reserved, count = db.execute( "SELECT COALESCE(SUM(cost_usd),0), COALESCE(SUM(input_premium_usd),0), " "COALESCE(SUM(CASE WHEN cost_usd IS NULL THEN accounted_usd ELSE 0 END),0), " "COUNT(*) FROM attempts").fetchone() statuses = dict(db.execute("SELECT status,COUNT(*) FROM attempts GROUP BY status")) return {"budget_usd": budget, "known_cost_usd": known, "input_premium_usd": premium, "reserved_uncertain_usd": reserved, "accounted_usd": known + premium + reserved, "remaining_usd": budget - known - premium - reserved, "attempts": count, "completed_calls": statuses.get("completed", 0), "statuses": statuses, "rates_per_million_usd": RATES, "uncached_input_premium_fraction": 0.25} def read_calls(db_path): """Read-only export, including while a runner holds the process lock.""" db = sqlite3.connect(Path(db_path).resolve().as_uri() + "?mode=ro", uri=True) try: return [json.loads(row[0]) for row in db.execute( "SELECT record_json FROM attempts ORDER BY attempt_id")] finally: db.close() def read_cost_summary(db_path): """Read a consistent status snapshot without an API key or writer lock.""" db = sqlite3.connect(Path(db_path).resolve().as_uri() + "?mode=ro", uri=True) try: db.execute("BEGIN") metadata = json.loads(db.execute( "SELECT metadata_json FROM runs ORDER BY run_id DESC LIMIT 1").fetchone()[0]) return _cost_summary(db, metadata["durable_client"]["budget_usd"]) finally: db.close() class DurableClient: def __init__(self, db_path: Path, metadata: dict, budget_usd: float, max_workers: int = 24, rpm: int = 300): if not math.isfinite(budget_usd) or budget_usd <= 0: raise ValueError("Budget must be finite and positive.") if type(max_workers) is not int or max_workers < 1 or rpm <= 0: raise ValueError("Workers and requests per minute must be positive.") self._key = os.environ.get("OPENAI_API_KEY") if not self._key: raise RuntimeError("OPENAI_API_KEY is absent; no secrets are logged.") self.path = Path(db_path) self.path.parent.mkdir(parents=True, exist_ok=True) self._process_lock = self.path.with_suffix(self.path.suffix + ".lock").open("a") try: fcntl.flock(self._process_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: self._process_lock.close() raise RuntimeError(f"Another runner owns {self.path}.") from None self._lock = threading.RLock() self._logical_locks = {} self._workers = threading.BoundedSemaphore(max_workers) self._rate_lock = threading.Lock() self._next_dispatch = 0.0 self._global_pause_until = 0.0 self._interval = 60.0 / rpm self._token_events = deque() self._tpm = metadata.get("configs", {}).get("tokens_per_minute") if self._tpm is not None and (type(self._tpm) is not int or self._tpm <= 0): self._process_lock.close() raise ValueError("tokens_per_minute must be a positive integer or absent.") self._budget_stopped = threading.Event() self._closed = False self._sessions = [] self._local = threading.local() self._budget = budget_usd self._metadata = metadata try: self._db = sqlite3.connect(self.path, check_same_thread=False) self._db.execute("PRAGMA journal_mode=WAL") self._db.execute("PRAGMA synchronous=FULL") self._db.executescript(""" CREATE TABLE IF NOT EXISTS runs ( run_id INTEGER PRIMARY KEY, metadata_json TEXT NOT NULL); CREATE TABLE IF NOT EXISTS logical_requests ( identifier TEXT PRIMARY KEY, request_sha256 TEXT NOT NULL); CREATE TABLE IF NOT EXISTS attempts ( attempt_id INTEGER PRIMARY KEY, identifier TEXT NOT NULL, status TEXT NOT NULL, accounted_usd REAL NOT NULL, cost_usd REAL, input_premium_usd REAL, record_json TEXT NOT NULL); CREATE INDEX IF NOT EXISTS attempts_identifier ON attempts(identifier); """) run_metadata = dict(metadata) run_metadata["durable_client"] = {"budget_usd": budget_usd, "max_workers": max_workers, "rpm": rpm, "tokens_per_minute": self._tpm, "max_attempts": MAX_ATTEMPTS, "rates_per_million_usd": RATES, "uncached_input_premium_fraction": 0.25} cursor = self._db.execute("INSERT INTO runs(metadata_json) VALUES (?)", (_json(run_metadata),)) self._run_id = cursor.lastrowid # The file lock proves that a previous running entry has no live owner. pending = self._db.execute( "SELECT record_json FROM attempts WHERE status='running'").fetchall() for (raw,) in pending: record = json.loads(raw) record.update(status="interrupted_uncertain", error_type="InterruptedPreviousRun", finished_utc=_utc()) self._save(record, commit=False) self._db.commit() except BaseException: if hasattr(self, "_db"): self._db.close() self._process_lock.close() raise def _post(self, request): if not hasattr(self._local, "session"): self._local.session = requests.Session() with self._lock: self._sessions.append(self._local.session) return self._local.session.post( "https://api.openai.com/v1/responses", headers={"Authorization": "Bearer " + self._key}, json=request, timeout=(15, 180)) def _rate_limit(self, token_estimate): if self._tpm is not None and token_estimate > self._tpm: raise ValueError("A request's token estimate exceeds tokens_per_minute.") while True: if self._budget_stopped.is_set(): raise BudgetExceeded("Budget guard has stopped further dispatch.") with self._rate_lock: now = time.monotonic() while self._token_events and now - self._token_events[0][0] >= 60: self._token_events.popleft() wait = max(0, self._next_dispatch - now, self._global_pause_until - now) if (self._tpm is not None and sum(n for _, n in self._token_events) + token_estimate > self._tpm): wait = max(wait, self._token_events[0][0] + 60 - now) if wait <= 0: self._next_dispatch = now + self._interval if self._tpm is not None: self._token_events.append((now, token_estimate)) return # Do not hold the rate lock while waiting: responses can extend the # shared 429 cooldown and other workers can observe budget stops. self._budget_stopped.wait(min(wait, 1)) def _save(self, record, commit=True): self._db.execute( "UPDATE attempts SET status=?, accounted_usd=?, cost_usd=?, input_premium_usd=?, " "record_json=? WHERE attempt_id=?", (record["status"], record["accounted_usd"], record.get("cost_usd"), record.get("input_premium_usd"), _json(record), record["attempt_id"])) if commit: self._db.commit() def calls(self): """All persisted attempts in dispatch order, including charged failures.""" with self._lock: return [json.loads(row[0]) for row in self._db.execute( "SELECT record_json FROM attempts ORDER BY attempt_id")] def cost_summary(self): with self._lock: return _cost_summary(self._db, self._budget) def _reserve(self, identifier, request, logical_hash): input_bound = len(_json(request).encode()) + 2048 # The budget uses a strict byte bound. Rate pacing uses a separate token # estimate so ordinary English requests are not throttled as byte tokens. token_estimate = math.ceil(len(_json(request)) / 4) + request["max_output_tokens"] self._rate_limit(token_estimate) reserve = (input_bound * RATES["input"] * 1.25 + request["max_output_tokens"] * RATES["output"]) / 1e6 with self._lock: spent = self._db.execute("SELECT COALESCE(SUM(accounted_usd), 0) FROM attempts").fetchone()[0] if self._budget_stopped.is_set() or spent + reserve > self._budget: self._budget_stopped.set() raise BudgetExceeded( f"Accounted ${spent:.6f} + reservation ${reserve:.6f} exceeds ${self._budget:.2f}.") record = {"id": identifier, "request": request, "request_sha256": _hash(request), "logical_request_sha256": logical_hash, "run_id": self._run_id, "commit_hash": self._metadata["commit_hash"], "status": "running", "reservation_usd": reserve, "accounted_usd": reserve, "started_utc": _utc(), "input_token_reservation_bound": input_bound, "rate_token_estimate": token_estimate} cursor = self._db.execute( "INSERT INTO attempts(identifier,status,accounted_usd,record_json) VALUES (?,?,?,?)", (identifier, "running", reserve, "{}")) record["attempt_id"] = cursor.lastrowid self._save(record) return record @staticmethod def _retryable(record): if record["status"] in TRANSIENT_STATUSES: return True if record["status"] == "api_error": return record.get("http_status") == 429 or 500 <= record.get("http_status", 0) < 600 return (record["status"] == "incomplete" and (record.get("response", {}).get("incomplete_details") or {}).get("reason") == "max_output_tokens" and record["request"]["max_output_tokens"] < MAX_OUTPUT_TOKENS) @staticmethod def _retry_delay(record, attempt_count): delay = min(2 ** attempt_count, 30) retry_after = record.get("retry_after") if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: try: date = parsedate_to_datetime(retry_after) delay = max(delay, (date - datetime.now(timezone.utc)).total_seconds()) except (TypeError, ValueError, OverflowError): pass return max(0, delay) def call(self, identifier, instructions, payload, max_output=2048, reasoning_effort="low", schema=None): if self._closed: raise RuntimeError("Client is closed.") if not isinstance(identifier, str) or not identifier: raise ValueError("Identifier must be a nonempty string.") if type(max_output) is not int or not 1 <= max_output <= MAX_OUTPUT_TOKENS: raise ValueError("max_output must be between 1 and 8192.") if reasoning_effort not in ("none", "low"): raise ValueError("Only none and low reasoning are supported for this experiment.") request = {"model": MODEL, "instructions": instructions, "input": "Input JSON:\n" + json.dumps(payload, ensure_ascii=False, allow_nan=False), "reasoning": {"effort": reasoning_effort}, "temperature": 1.0, "max_output_tokens": max_output, "store": False, "service_tier": "default", "text": {"format": {"type": "json_object"}}} if schema is not None: request["text"]["format"] = {"type": "json_schema", "name": "experiment_output", "strict": True, "schema": schema} logical_hash = _hash(request) with self._lock: logical_lock = self._logical_locks.setdefault(identifier, threading.Lock()) # Same-ID callers wait and reuse success; unrelated calls proceed concurrently. with logical_lock, self._workers: with self._lock: prior_hash = self._db.execute( "SELECT request_sha256 FROM logical_requests WHERE identifier=?", (identifier,)).fetchone() if prior_hash and prior_hash[0] != logical_hash: raise ValueError(f"Request changed for {identifier}; use a new logical ID.") if prior_hash is None: self._db.execute("INSERT INTO logical_requests VALUES (?,?)", (identifier, logical_hash)) self._db.commit() existing = [json.loads(row[0]) for row in self._db.execute( "SELECT record_json FROM attempts WHERE identifier=? ORDER BY attempt_id", (identifier,))] successes = [r for r in existing if r["status"] == "completed"] if successes: return successes[0] while True: if existing: previous = existing[-1] if len(existing) >= MAX_ATTEMPTS or not self._retryable(previous): raise CallFailed(identifier, previous) request["max_output_tokens"] = previous["request"]["max_output_tokens"] if previous["status"] == "incomplete": request["max_output_tokens"] = min(MAX_OUTPUT_TOKENS, request["max_output_tokens"] * 2) delay = self._retry_delay(previous, len(existing)) if self._budget_stopped.wait(delay): raise BudgetExceeded("Budget guard has stopped retries.") record = self._reserve(identifier, request.copy(), logical_hash) try: response = self._post(record["request"]) record.update(http_status=response.status_code, request_id=response.headers.get("x-request-id"), retry_after=response.headers.get("Retry-After")) if response.status_code == 429: delay = self._retry_delay(record, len(existing) + 1) with self._rate_lock: self._global_pause_until = max(self._global_pause_until, time.monotonic() + delay) try: body = response.json() if not isinstance(body, dict): raise ValueError("Response is not an object") except ValueError: body = {"unparsed_response_text": response.text[:16384]} record["response"] = body cost = _usage_cost(body) if cost is not None: record["cost_usd"], record["input_premium_usd"] = cost record["accounted_usd"] = sum(cost) elif response.status_code in (400, 401, 403, 404, 422, 429): record.update(cost_usd=0.0, input_premium_usd=0.0, accounted_usd=0.0) else: record["usage_uncertain"] = True if not response.ok: record["status"] = "api_error" elif "unparsed_response_text" in body: record["status"] = "response_uncertain" else: record["text"] = "".join( part.get("text", "") for item in body.get("output", []) if item.get("type") == "message" for part in item.get("content", []) if part.get("type") == "output_text") if body.get("status") != "completed": record["status"] = "incomplete" elif any(part.get("type") == "refusal" for item in body.get("output", []) if item.get("type") == "message" for part in item.get("content", [])): record["status"] = "refused" else: try: def invalid_constant(value): raise ValueError(f"Invalid JSON constant {value}") record["parsed"] = json.loads(record["text"], parse_constant=invalid_constant) if not isinstance(record["parsed"], dict): raise ValueError("Expected a JSON object") record["status"] = "completed" except ValueError: record["status"] = "parse_error" except requests.RequestException as error: record.update(status="transport_uncertain", error_type=type(error).__name__) except BaseException as error: record.update(status="interrupted_uncertain" if isinstance(error, (KeyboardInterrupt, SystemExit)) else "response_uncertain", error_type=type(error).__name__) raise finally: record["finished_utc"] = _utc() with self._lock: self._save(record) if record["status"] == "completed": return record existing.append(record) def close(self): """Call after joining all workers; unfinished records remain reserved.""" with self._lock: if self._closed: return self._closed = True for session in self._sessions: session.close() self._db.close() fcntl.flock(self._process_lock, fcntl.LOCK_UN) self._process_lock.close()