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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""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()