diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c8f5ba..8f35341 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -221,7 +221,9 @@ jobs: # regenerates to a no-op diff, commits nothing, and proceeds to the # compare-mode test — a commit-message guard below is the final # backstop against a regen/push loop. - runs-on: ubuntu-latest + # Playwright 1.60 supports Ubuntu 24.04; ubuntu-latest now selects 26.04, + # where Chromium dependency installation fails before visual tests run. + runs-on: ubuntu-24.04 permissions: contents: write # Needed to remove the vrt-baseline-update label after committing. diff --git a/docs/claude-credit-campaign.md b/docs/claude-credit-campaign.md new file mode 100644 index 0000000..febd390 --- /dev/null +++ b/docs/claude-credit-campaign.md @@ -0,0 +1,121 @@ +# Claude credit campaign + +The November 25, 2026 campaign tests three product decisions: which Claude +models merit routing coverage, whether population conditioning and structured +capture improve fidelity independently, and whether more synthetic samples +reduce error or merely stabilize a biased distribution. + +## Collection + +`scripts/run-credit-campaign.py` collects individual responses into a private, +append-only JSONL journal. It uses the existing OpenRouter raw prompt and +Althing survey request builders. This is an experimental collection format, +not a leaderboard submission or a measurement of the entire Althing product. + +Each task has a unique `id`, `dataset`, `question_key`, explicit OpenRouter +`anthropic/*` model, and `provider` (`openrouter` or `althing`). Optional fields +are `elicitation`, `persona_pack`, `replicate`, `sample_index`, and +`samples_per_question`. Population allocations use the question key and +replicate as their seed; the same allocation is used across capture modes. + +Run `--help` for the interface. A no-network preflight is: + +```sh +.venv/bin/python scripts/run-credit-campaign.py \ + --tasks .runtime/claude-credit-20261125/pilot-tasks.jsonl \ + --journal .runtime/claude-credit-20261125/pilot.jsonl \ + --questions-dir .runtime/claude-credit-20261125 \ + --pricing .runtime/claude-credit-20261125/openrouter-models.json \ + --max-usd 5 --deadline 2026-11-25T23:15:00Z --dry-run +``` + +Supply `OPENROUTER_API_KEY` privately through Doppler for actual inference. +Question snapshots contain licensed text and answer keys: keep snapshots, +manifests, and journals in the ignored `.runtime/` directory or private storage. +Only request-side text, options, and respondent population reach the model. +Never commit answer keys or raw campaign journals to this public repository. + +## Budget and replay + +The funding is a separate Claude promotion on the account's upstream BYOK +credential. A real probe returned `is_byok=true`, gateway `usage.cost=0`, and +positive `cost_details.upstream_inference_cost`. Therefore a zero gateway +charge must never be treated as free inference. The collector accounts the +larger of upstream and gateway charges, without adding the two together; +when billing evidence is unavailable it retains a conservative reservation or +uses an explicitly labeled token-rate estimate. + +Reservations are written before dispatch and include outstanding requests. +Lost or failed requests retain their reservation because an absent response +does not prove absence of upstream billing. Final tasks are not dispatched +again. Runtime, pricing, and question-input fingerprints prevent incompatible +replays. A changed collector/runtime requires a new journal and a budget that +subtracts prior spending. Keep a separate campaign-wide total across journals. + +The request reserve uses UTF-8 bytes, framing allowance, output ceilings, and +a cache-write premium. This is a conservative estimate, not a formal provider +token-count guarantee. An observed overrun stops collection for reconciliation. +Althing's internal retries are disabled; raw adapter recovery attempts are +reserved and recorded individually. These retry settings are part of the +campaign's provenance. + +## Frozen experiment + +Initial spending ceilings are $5 pilot, $60 model screening, $80 population +and capture, and $35 sample-size analysis, with $20 held for useful extensions. +Stop new requests at the frozen deadline, conservatively before credit expiry. +The deadline governs admission, not completion: allow at least three minutes +for in-flight calls and billing reconciliation before the actual expiry. + +- Screening: Haiku 5.5, Sonnet 5.5, and Opus 5.5; raw and Althing; four core + datasets; 50 questions and 20 samples per cell. Extend promising candidates + only after measuring actual cost and throughput. +- Population and capture: Haiku 5.5 and Sonnet 4.6; generic and global-respondents; + natural and structured; 60 matched GlobalOpinionQA questions, 30 samples, + and three independent repetitions. Freeze roughly two thirds development + and one third evaluation before inspecting outputs. Assign by normalized + question-text hash, keeping identical items in the same split across datasets. +- Sample size: two configurations, 60 questions, up to 150 samples. Analyze + nested prefixes at 10, 20, 30, 60, 100, and 150 responses. + +The pilot found that Sonnet 5.5 rejects forced tool capture (`tool_choice` +types `tool` and `any`) with HTTP 400. It stays in natural model screening; +Sonnet 4.6 replaces it only in the matched capture experiment. Do not silently +change structured capture to optional tool use: that would change the +experimental condition. All eight Haiku 5.5/Sonnet 4.6 population and capture +combinations passed the revised connectivity pilot. + +Althing's Messages passthrough returns an Anthropic `msg_*` body id and an +OpenRouter `gen-*` header. The per-instance instrumentation in +`campaign_transport.py` preserves both ids and raw usage without changing +native request bodies, provider routing, decoding parameters, or parsing. +The generation header is required for successful OpenRouter billing lookup; +an Anthropic message id cannot be looked up as an OpenRouter generation. + +Prefer questions absent from committed result artifacts. The available +GlobalOpinionQA and SubPOP pools contain such items; the available OpinionsQA +and GSS pools do not. Label the latter as replications. Absence from local +results does not establish absence from model training. + +The restored SubPOP snapshot is a population-average distribution, not a +conditioned demographic benchmark. Its screening result cannot establish +subgroup fidelity. Country-level conclusions likewise need sufficient +country-specific samples. Report paired question-level uncertainty, keep +development and evaluation results separate, and never count synthetic +respondents as independent human observations. Publish only validated, +complete and comparable configurations through the normal submission flow. + +The analysis reports unscored-cell counts alongside its means. It deliberately +declines paired contrasts when either side has unscorable cells; dropping +questions a model refused entirely could make that model appear better. +All-refusal or all-unparseable cells have no distributional score rather than +receiving the runner's historical uniform fallback. These experimental means +are conditional on scorable cells and must not be presented as leaderboard SPS. + +## Adapter change + +OpenRouter now omits temperature when the caller omits it, preserving explicit +values including zero. Historical absent-temperature raw runs actually sent +1.0; new absent-temperature runs use the upstream default. Both retain the +existing `tdefault` identity, so campaign comparisons must use the recorded +runtime and request evidence rather than silently pooling old and new runs. diff --git a/scripts/analyze-credit-campaign.py b/scripts/analyze-credit-campaign.py new file mode 100644 index 0000000..f131d99 --- /dev/null +++ b/scripts/analyze-credit-campaign.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Analyze private campaign journals without network access.""" + +from synthbench.campaign_analysis import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/run-credit-campaign.py b/scripts/run-credit-campaign.py new file mode 100755 index 0000000..cd3c96b --- /dev/null +++ b/scripts/run-credit-campaign.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Run a private, resumable OpenRouter campaign (see --help).""" + +from synthbench.campaign import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/synthbench/campaign.py b/src/synthbench/campaign.py new file mode 100644 index 0000000..6a9b2f8 --- /dev/null +++ b/src/synthbench/campaign.py @@ -0,0 +1,714 @@ +"""Private, resumable response collection with an append-only spending ledger. + +This is an experiment runner, not a leaderboard submission format. Keep its +question snapshots and journals private: they may contain licensed survey text. +Errors and interrupted requests retain their entire reservation, since a lost +response does not prove that the upstream request was free. Resume never retries +a task with a final record; intentional retries must use a new task id. +""" + +from __future__ import annotations + +import argparse +import asyncio +import contextvars +import dataclasses +import datetime as dt +import fcntl +import hashlib +from importlib.metadata import PackageNotFoundError, version +import json +import math +import os +import threading +import time +import uuid +from decimal import Decimal +from pathlib import Path +from typing import Any + +import httpx + + +class CampaignStopped(RuntimeError): + """The deadline or conservative spending limit prevents another request.""" + + +def _usd(value: Any) -> Decimal: + result = Decimal(str(value)) + if not result.is_finite() or result < 0: + raise ValueError("Costs must be finite and nonnegative") + return result + + +def _json(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str) + + +def _now() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat() + + +class Ledger: + """Single-writer durable reservations, safe across concurrent samples.""" + + def __init__(self, path: Path, max_usd: float, deadline: float): + self.path = path + self.max_usd = _usd(max_usd) + self.deadline = deadline + self.lock = threading.RLock() + self.charges: dict[str, Decimal] = {} + self.completed: dict[str, dict] = {} + self.task_hashes: dict[str, str] = {} + self.metadata: dict | None = None + self.halted = False + self.path.parent.mkdir(parents=True, exist_ok=True) + self.file = path.open("a+", encoding="utf-8") + os.chmod(path, 0o600) + try: + fcntl.flock(self.file, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.file.seek(0) + for line in self.file: + row = json.loads(line) # A torn record fails closed; do not discard it. + if row["kind"] == "reservation": + self.charges[row["attempt_id"]] = _usd(row["reserved_usd"]) + elif row["kind"] == "attempt": + if row["attempt_id"] not in self.charges: + raise ValueError("Attempt has no durable reservation") + amount = _usd(row["accounted_usd"]) + self.halted |= ( + bool(row.get("halted")) + or amount > self.charges[row["attempt_id"]] + ) + self.charges[row["attempt_id"]] = amount + elif row["kind"] == "final": + self.completed[row["task_id"]] = row + elif row["kind"] == "campaign": + if self.metadata is not None and self.metadata != row["metadata"]: + raise ValueError( + "Journal contains inconsistent campaign metadata" + ) + self.metadata = row["metadata"] + if row.get("task_hash"): + old = self.task_hashes.setdefault(row["task_id"], row["task_hash"]) + if old != row["task_hash"]: + raise ValueError( + "Journal task id was reused with different inputs" + ) + self.file.seek(0, os.SEEK_END) + except BaseException: + self.file.close() + raise + + @property + def accounted(self) -> Decimal: + return sum(self.charges.values(), Decimal(0)) + + def append(self, row: dict) -> None: + with self.lock: + self.file.write(_json({"at": _now(), **row}) + "\n") + self.file.flush() + os.fsync(self.file.fileno()) + + def reserve(self, task: dict, amount: Decimal, request: dict) -> str: + with self.lock: + if self.halted: + raise CampaignStopped("journal halted; reconcile before new dispatch") + if time.time() >= self.deadline: + raise CampaignStopped("deadline") + if self.accounted + amount > self.max_usd: + raise CampaignStopped("budget") + attempt_id = uuid.uuid4().hex + fingerprint = hashlib.sha256(_json(task).encode()).hexdigest() + self.append( + { + "kind": "reservation", + "attempt_id": attempt_id, + "task_id": task["id"], + "task_hash": fingerprint, + "reserved_usd": str(amount), + "request": request, + } + ) + self.charges[attempt_id] = amount + self.task_hashes[task["id"]] = fingerprint + return attempt_id + + def settle(self, attempt_id: str, amount: Decimal, **details: Any) -> None: + with self.lock: + reserved = self.charges[attempt_id] + halted = ( + amount > reserved or self.accounted - reserved + amount > self.max_usd + ) + self.append( + { + "kind": "attempt", + "attempt_id": attempt_id, + "accounted_usd": str(amount), + "halted": halted, + **details, + } + ) + self.charges[attempt_id] = amount + self.halted |= halted + if self.halted: + raise CampaignStopped( + "reported cost exceeded reservation; stop and reconcile" + ) + + def final(self, task: dict, **details: Any) -> None: + row = { + "kind": "final", + "task_id": task["id"], + "task_hash": hashlib.sha256(_json(task).encode()).hexdigest(), + "task": task, + **details, + } + self.append(row) + self.completed[task["id"]] = row + self.task_hashes[task["id"]] = row["task_hash"] + + def close(self) -> None: + self.file.close() + + def bind_campaign(self, metadata: dict) -> None: + # Normalize Decimals exactly as persisted JSON before comparing. + normalized = json.loads(_json(metadata)) + if self.metadata is not None and self.metadata != normalized: + raise ValueError("Campaign pricing or runtime changed; use a new journal") + if self.metadata is None: + if self.charges or self.completed: + raise ValueError( + "Existing journal lacks campaign provenance; use a new journal" + ) + self.append({"kind": "campaign", "metadata": normalized}) + self.metadata = normalized + + +def load_tasks(path: Path) -> list[dict]: + tasks = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + ids = set() + for task in tasks: + for field in ("id", "dataset", "question_key", "model", "provider"): + if not isinstance(task.get(field), str) or not task[field]: + raise ValueError(f"Task needs a nonempty {field}") + if task["id"] in ids: + raise ValueError(f"Duplicate task id: {task['id']}") + ids.add(task["id"]) + if task["provider"] not in ("openrouter", "althing"): + raise ValueError("Only OpenRouter-backed providers are permitted") + if not task["model"].startswith("anthropic/"): + raise ValueError("Campaign is restricted to explicit anthropic/* model ids") + if task.get("elicitation", "natural") not in ("natural", "structured"): + raise ValueError("Unknown elicitation mode") + if task["provider"] == "openrouter" and ( + task.get("persona_pack") or task.get("elicitation", "natural") != "natural" + ): + raise ValueError( + "Raw provider does not support packs or structured capture" + ) + for key, default in ( + ("replicate", 0), + ("sample_index", 0), + ("samples_per_question", 30), + ): + value = task.get(key, default) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"Invalid {key}") + if task.get("sample_index", 0) >= task.get("samples_per_question", 30): + raise ValueError("sample_index must be below samples_per_question") + return tasks + + +def load_pricing(path: Path) -> dict[str, tuple[Decimal, Decimal]]: + data = json.loads(path.read_text()) + if "data" in data and isinstance(data["data"], list): + data = { + row["id"]: { + "input_per_million": _usd(row["pricing"]["prompt"]) * 1_000_000, + "output_per_million": _usd(row["pricing"]["completion"]) * 1_000_000, + } + for row in data["data"] + if row["id"].startswith("anthropic/") + } + return { + model: (_usd(rates["input_per_million"]), _usd(rates["output_per_million"])) + for model, rates in data.items() + } + + +def load_questions( + tasks: list[dict], directory: Path | None +) -> dict[tuple[str, str], dict]: + from synthbench.datasets import DATASETS + + questions = {} + for dataset in sorted({task["dataset"] for task in tasks}): + if directory: + rows = json.loads( + (directory / f"{dataset}-questions-private.json").read_text() + ) + if isinstance(rows, dict): + rows = rows["questions"] + else: + rows = [dataclasses.asdict(q) for q in DATASETS[dataset]().load()] + for q in rows: + # Deliberately keep only request-side fields; never answer keys. + questions[dataset, q["key"]] = { + key: q.get(key) + for key in ("key", "text", "options", "respondent_population") + } + for task in tasks: + q = questions[task["dataset"], task["question_key"]] + if not q["text"] or not q["options"]: + raise ValueError("Question lacks text or options") + return questions + + +class _SingleAttempt: + def run(self, fn, **kwargs): + return fn() + + +_task_context: contextvars.ContextVar[dict] = contextvars.ContextVar("campaign_task") + + +class Collector: + def __init__( + self, ledger: Ledger, pricing: dict, questions: dict, concurrency: int = 8 + ): + if concurrency < 1: + raise ValueError("concurrency must be positive") + self.ledger = ledger + self.pricing = pricing + self.questions = questions + self.concurrency = concurrency + packages = {} + for package in ("synthbench-eval", "althing", "openai"): + try: + packages[package] = version(package) + except PackageNotFoundError: + packages[package] = "unavailable" + ledger.bind_campaign( + { + "pricing": pricing, + "packages": packages, + "max_usd": str(ledger.max_usd), + "deadline": ledger.deadline, + "collector_sha256": hashlib.sha256( + Path(__file__).read_bytes() + ).hexdigest(), + "transport_sha256": hashlib.sha256( + Path(__file__).with_name("campaign_transport.py").read_bytes() + ).hexdigest(), + } + ) + self.providers: dict[tuple, Any] = {} + self.last_attempts: dict[str, dict] = {} + self.cost_client = httpx.AsyncClient(timeout=10, follow_redirects=False) + self.stopped: str | None = None + + def _reserve(self, task: dict, request: dict) -> tuple[str, Decimal]: + input_rate, output_rate = self.pricing[task["model"]] + # UTF8 bytes are a conservative text-token bound. Add 4096 tokens + # for chat/tool framing, and 25% input premium for cache creation. + # This is explicitly an estimate, not a provider token-count proof. + input_bound = len(_json(request).encode("utf-8")) + 4096 + output_bound = int(request["max_tokens"]) + amount = ( + Decimal(input_bound) * input_rate * Decimal("1.25") + + Decimal(output_bound) * output_rate + ) / 1_000_000 + return self.ledger.reserve(task, amount, request), amount + + async def _cost( + self, model: str, generation_id: str | None, usage: dict + ) -> tuple[Decimal, str]: + def reported(data: dict) -> Decimal: + # BYOK Claude promotions can debit upstream credits while + # OpenRouter's own cost is zero. Never interpret gateway $0 as + # a free inference, nor add overlapping billing measures. + costs = [ + _usd(data[key]) + for key in ( + "cost", + "total_cost", + "provider_reported_cost", + "upstream_inference_cost", + ) + if data.get(key) is not None + ] + details = data.get("cost_details") + if ( + isinstance(details, dict) + and details.get("upstream_inference_cost") is not None + ): + costs.append(_usd(details["upstream_inference_cost"])) + return max(costs, default=Decimal(0)) + + native = reported(usage) + if native > 0: + return native, "provider-reported-max-gateway-upstream" + if generation_id: + for delay in (0, 0.5, 1, 2): + if delay: + await asyncio.sleep(delay) + try: + response = await self.cost_client.get( + "https://openrouter.ai/api/v1/generation", + params={"id": generation_id}, + headers={ + "Authorization": "Bearer " + + os.environ["OPENROUTER_API_KEY"] + }, + ) + if response.status_code == 200: + billing = response.json().get("data", {}) + cost = reported(billing) + if cost > 0: + # Preserve gateway/upstream evidence lost by the + # Althing typed usage parser, without response text. + for field in ( + "total_cost", + "upstream_inference_cost", + "is_byok", + ): + if billing.get(field) is not None: + usage[field] = billing[field] + return cost, "generation-api-max-gateway-upstream" + elif response.status_code != 404: + break + except (httpx.HTTPError, ValueError, KeyError): + break + input_rate, output_rate = self.pricing[model] + inputs = int(usage.get("input_tokens", usage.get("prompt_tokens", 0))) + outputs = int(usage.get("output_tokens", usage.get("completion_tokens", 0))) + details = usage.get("prompt_tokens_details") or {} + writes = int( + usage.get("cache_write_tokens", details.get("cache_write_tokens", 0)) + ) + reads = int(usage.get("cache_read_tokens", 0)) + if not usage or inputs + outputs + writes + reads == 0: + raise ValueError("No usable billing evidence") + cost = ( + Decimal(inputs + reads) * input_rate + + Decimal(writes) * input_rate * Decimal("1.25") + + Decimal(outputs) * output_rate + ) / 1_000_000 + return cost, "catalog-token-estimate" + + def _raw_provider(self, task: dict): + from synthbench.providers.openrouter import OpenRouterProvider + + key = ("openrouter", task["model"]) + if key not in self.providers: + provider = OpenRouterProvider(model=task["model"], temperature=None) + provider._client.max_retries = 0 + provider._client.timeout = httpx.Timeout(120) + original = provider._request + + async def request(kwargs): + active = _task_context.get() + attempt_id, reserved = self._reserve(active, kwargs) + started = time.monotonic() + try: + response = await original(kwargs) + usage = response.usage.model_dump() if response.usage else {} + self.ledger.append( + { + "kind": "received", + "attempt_id": attempt_id, + "task_id": active["id"], + "generation_id": response.id, + "usage": usage, + "response": response.model_dump(), + } + ) + self.last_attempts[active["id"]] = { + "attempt_id": attempt_id, + "generation_id": response.id, + "reasoning_request": kwargs.get("extra_body", {}).get( + "reasoning" + ), + } + cost, source = await self._cost(active["model"], response.id, usage) + self.ledger.settle( + attempt_id, + cost, + task_id=active["id"], + generation_id=response.id, + usage=usage, + response=response.model_dump(), + cost_source=source, + elapsed_seconds=time.monotonic() - started, + ) + return response + except BaseException as exc: + # Budget exceptions raised before dispatch are outside this + # try. All dispatched failures conservatively stay charged. + if ( + attempt_id in self.ledger.charges + and self.ledger.charges[attempt_id] == reserved + ): + self.ledger.settle( + attempt_id, + reserved, + task_id=active["id"], + error=type(exc).__name__, + cost_source="reservation-retained", + elapsed_seconds=time.monotonic() - started, + ) + raise + + provider._request = request + self.providers[key] = provider + return self.providers[key] + + def _althing_provider(self, task: dict): + from synthbench.providers.althing import AlthingProvider + + key = ( + "althing", + task["model"], + task.get("elicitation", "natural"), + task.get("persona_pack"), + ) + if key not in self.providers: + provider = AlthingProvider( + model="openrouter/" + task["model"], + elicitation=task.get("elicitation", "natural"), + persona_pack=task.get("persona_pack"), + ) + if not provider._use_api: + raise ValueError("Campaign requires the direct Althing Python API") + from synthbench.campaign_transport import attach_openrouter_billing + + attach_openrouter_billing(provider._client, task["model"]) + provider._client._retry_policy = _SingleAttempt() + self.providers[key] = provider + return self.providers[key] + + def _population_system( + self, task: dict, question: dict, provider: Any + ) -> str | None: + if not task.get("persona_pack"): + return None + from althing.population import allocate_population + from althing.prompts import persona_system_prompt + + population = question.get("respondent_population") + if not population or len(population) != 1: + raise ValueError( + "Population task needs exactly one respondent-population attribute" + ) + ((key, members),) = population.items() + allocation = allocate_population( + provider._pack_personas, + key=key, + members=members, + n_samples=task.get("samples_per_question", 30), + seed=f"{question['key']}:{task.get('replicate', 0)}", + ) + personas = [persona for persona, count in allocation for _ in range(count)] + return persona_system_prompt(personas[task.get("sample_index", 0)]) + + async def _one_althing(self, task: dict, question: dict): + from synthbench.providers.base import Response + + provider = self._althing_provider(task) + system = self._population_system(task, question, provider) + request = provider._build_api_request( + question["text"], question["options"], None, system=system + ) + request_dict = dataclasses.asdict(request) + attempt_id, reserved = self._reserve(task, request_dict) + started = time.monotonic() + try: + response = await asyncio.to_thread(provider._client.send, request) + usage = { + **dataclasses.asdict(response.usage), + **getattr(response, "_openrouter_usage", {}), + } + generation_id = getattr(response, "_openrouter_generation_id", None) + if not generation_id and response.id.startswith("gen-"): + generation_id = response.id + self.ledger.append( + { + "kind": "received", + "attempt_id": attempt_id, + "task_id": task["id"], + "generation_id": generation_id, + "native_response_id": response.id, + "usage": usage, + "response": dataclasses.asdict(response), + } + ) + cost, source = await self._cost(task["model"], generation_id, usage) + self.ledger.settle( + attempt_id, + cost, + task_id=task["id"], + generation_id=generation_id, + native_response_id=response.id, + usage=usage, + response=dataclasses.asdict(response), + cost_source=source, + elapsed_seconds=time.monotonic() - started, + ) + raw, parsed = provider._parse_api_response(response, question["options"]) + return Response( + selected_option=parsed.option, + raw_text=raw, + refusal=parsed.refusal, + metadata={ + "model": response.model, + "usage": usage, + "generation_id": generation_id, + "native_response_id": response.id, + "transport": "anthropic-messages-passthrough", + }, + ) + except BaseException as exc: + if self.ledger.charges.get(attempt_id) == reserved: + self.ledger.settle( + attempt_id, + reserved, + task_id=task["id"], + error=type(exc).__name__, + cost_source="reservation-retained", + elapsed_seconds=time.monotonic() - started, + ) + raise + + async def _one(self, task: dict) -> None: + question = self.questions[task["dataset"], task["question_key"]] + task = { + **task, + "_question_hash": hashlib.sha256(_json(question).encode()).hexdigest(), + } + fingerprint = hashlib.sha256(_json(task).encode()).hexdigest() + if ( + task["id"] in self.ledger.task_hashes + and self.ledger.task_hashes[task["id"]] != fingerprint + ): + raise ValueError("Task id reused with different inputs") + if task["id"] in self.ledger.completed: + return + if self.stopped: + return + context = _task_context.set(task) + started = time.monotonic() + try: + if task["provider"] == "openrouter": + provider = self._raw_provider(task) + response = await provider.respond(question["text"], question["options"]) + evidence = self.last_attempts.pop(task["id"], {}) + response.metadata = {**(response.metadata or {}), **evidence} + settings = { + "reasoning_request": evidence.get("reasoning_request"), + "transport": "openai-chat-completions", + } + else: + response = await self._one_althing(task, question) + settings = { + "transport": "anthropic-messages-passthrough", + "internal_retries": 0, + } + self.ledger.final( + task, + status="completed", + response=dataclasses.asdict(response), + settings=settings, + elapsed_seconds=time.monotonic() - started, + ) + except CampaignStopped as exc: + self.stopped = str(exc) + except Exception as exc: # noqa: BLE001 — persist task failure without secret-bearing exception text + self.ledger.final( + task, + status="error", + error=type(exc).__name__, + elapsed_seconds=time.monotonic() - started, + ) + finally: + _task_context.reset(context) + + async def run(self, tasks: list[dict]) -> dict: + iterator = iter(tasks) + + async def worker(): + for task in iterator: + if self.stopped: + break + await self._one(task) + + try: + await asyncio.gather(*(worker() for _ in range(self.concurrency))) + finally: + for provider in self.providers.values(): + if hasattr(provider, "close"): + result = provider.close() + if asyncio.iscoroutine(result): + await result + executor = getattr(provider, "_executor", None) + if executor: + executor.shutdown(wait=True) + await self.cost_client.aclose() + requested_ids = {task["id"] for task in tasks} + finals = [ + row for key, row in self.ledger.completed.items() if key in requested_ids + ] + return { + "requested": len(tasks), + "completed": sum(r["status"] == "completed" for r in finals), + "errors": sum(r["status"] == "error" for r in finals), + "accounted_usd": str(self.ledger.accounted), + "max_usd": str(self.ledger.max_usd), + "stopped": self.stopped, + "at": _now(), + "billing_note": "Includes conservative retained reservations; reconcile against provider billing.", + } + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tasks", required=True, type=Path) + parser.add_argument("--journal", required=True, type=Path) + parser.add_argument("--questions-dir", type=Path) + parser.add_argument("--pricing", required=True, type=Path) + parser.add_argument("--max-usd", required=True, type=float) + parser.add_argument( + "--deadline", required=True, help="Timezone-aware ISO timestamp" + ) + parser.add_argument("--concurrency", default=8, type=int) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv) + deadline = dt.datetime.fromisoformat(args.deadline.replace("Z", "+00:00")) + if deadline.tzinfo is None or not math.isfinite(args.max_usd) or args.max_usd < 0: + parser.error("Deadline needs timezone; budget must be finite and nonnegative") + tasks = load_tasks(args.tasks) + pricing = load_pricing(args.pricing) + if any(task["model"] not in pricing for task in tasks): + parser.error("Missing model pricing") + questions = load_questions(tasks, args.questions_dir) + if args.dry_run: + print( + _json({"tasks": len(tasks), "questions": len(questions), "paid_calls": 0}) + ) + return 0 + ledger = Ledger(args.journal, args.max_usd, deadline.timestamp()) + try: + summary = asyncio.run( + Collector(ledger, pricing, questions, args.concurrency).run(tasks) + ) + summary_path = args.journal.with_suffix(".summary.json") + summary_path.write_text(_json(summary) + "\n") + os.chmod(summary_path, 0o600) + print(_json(summary)) + return 0 if summary["completed"] == len(tasks) else 2 + finally: + ledger.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/synthbench/campaign_analysis.py b/src/synthbench/campaign_analysis.py new file mode 100644 index 0000000..4f00bf3 --- /dev/null +++ b/src/synthbench/campaign_analysis.py @@ -0,0 +1,509 @@ +"""Offline analysis of private campaign journals; never emits survey answers/text. + +Only fully observed question cells enter headline scores. Prefix estimates are +separate, explicitly labeled views, never replacements for missing full cells. +Question-level paired inference averages replicates before bootstrapping. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from itertools import combinations +import json +import math +import os +from pathlib import Path +from statistics import mean, median + +from synthbench.datasets.base import Question +from synthbench.metrics import synthbench_parity_score +from synthbench.runner import _score_question +from synthbench.stats import bootstrap_ci + +METRICS = ("sps", "p_dist", "p_rank", "p_refuse") +PREFIXES = (10, 20, 30, 60, 100, 150) +CONFIG_FIELDS = ("dataset", "model", "provider", "elicitation", "persona_pack") + + +def _configuration(task): + return { + **{key: task.get(key) for key in CONFIG_FIELDS}, + "elicitation": task.get("elicitation", "natural"), + "samples_per_question": task.get("samples_per_question", 30), + } + + +def _config_key(task): + return json.dumps(_configuration(task), sort_keys=True) + + +def _number(value): + if value is None: + return None + result = float(value) + if not math.isfinite(result) or result < 0: + raise ValueError("Journal has invalid cost or latency") + return result + + +def _latencies(values): + values = sorted(v for v in values if v is not None) + if not values: + return { + "count": 0, + "mean_seconds": None, + "p50_seconds": None, + "p95_seconds": None, + } + return { + "count": len(values), + "mean_seconds": mean(values), + "p50_seconds": median(values), + "p95_seconds": values[max(0, math.ceil(0.95 * len(values)) - 1)], + } + + +def _billing(reservations, attempts): + accounted = 0.0 + reported = {"gateway_usd": [], "upstream_usd": [], "provider_reported_usd": []} + sources = Counter() + elapsed = [] + for attempt_id, reservation in reservations.items(): + row = attempts.get(attempt_id) + if row is None: + accounted += _number(reservation["reserved_usd"]) + sources["unsettled-reservation"] += 1 + continue + accounted += _number(row["accounted_usd"]) + sources[row.get("cost_source", "unknown")] += 1 + elapsed.append(_number(row.get("elapsed_seconds"))) + usage = row.get("usage") or {} + gateway = usage.get("cost", usage.get("total_cost")) + upstream = (usage.get("cost_details") or {}).get( + "upstream_inference_cost", usage.get("upstream_inference_cost") + ) + for key, value in ( + ("gateway_usd", gateway), + ("upstream_usd", upstream), + ("provider_reported_usd", usage.get("provider_reported_cost")), + ): + if value is not None: + reported[key].append(_number(value)) + return { + "attempt_count": len(reservations), + "unsettled_attempt_count": len(reservations.keys() - attempts.keys()), + "accounted_usd": accounted, + "reported_costs": { + key: { + "usd": sum(values) if values else None, + "attempts_with_evidence": len(values), + } + for key, values in reported.items() + }, + "cost_sources": dict(sources), + "attempt_latency": _latencies(elapsed), + } + + +def _cell_score(question, rows): + n = len(rows) + responses = [row["response"] for row in rows] + refused = sum(bool(row.get("refusal")) for row in responses) + selected = [ + row.get("selected_option") + for row in responses + if not row.get("refusal") and row.get("selected_option") in question.options + ] + invalid = n - refused - len(selected) + result = { + "n_completed": n, + "n_valid_answers": len(selected), + "n_refusals": refused, + "n_parse_failures": invalid, + "refusal_rate": refused / n, + "parse_failure_rate": invalid / n, + "scores": None, + "score_unavailable_reason": None, + } + if not selected: + result["score_unavailable_reason"] = "no_valid_answers" + return result + if question.answer_withheld or not question.human_distribution: + result["score_unavailable_reason"] = "answer_key_unavailable" + return result + counts = Counter(selected) + model = {option: counts[option] / len(selected) for option in question.options} + human_refusal, jsd, tau, _parity = _score_question(question, model) + # Runner denominator excludes parse failures but includes refusals. + refusal_denominator = len(selected) + refused + scores = { + "p_dist": 1 - jsd, + "p_rank": (1 + tau) / 2, + "p_refuse": 1 - abs(refused / refusal_denominator - human_refusal), + } + result["scores"] = {"sps": synthbench_parity_score(scores), **scores} + return result + + +def _summary(cells): + scored = [cell for cell in cells if cell.get("scores") is not None] + complete = [cell for cell in cells if cell["complete"]] + return { + "n_question_cells": len(cells), + "n_complete_cells": len(complete), + "n_scored_cells": len(scored), + "n_distinct_scored_questions": len({cell["question_key"] for cell in scored}), + "scores": { + metric: mean(cell["scores"][metric] for cell in scored) + for metric in METRICS + } + if scored + else None, + "refusal_rate": sum(cell.get("n_refusals", 0) for cell in complete) + / sum(cell["n_completed"] for cell in complete) + if complete + else None, + "parse_failure_rate": sum(cell.get("n_parse_failures", 0) for cell in complete) + / sum(cell["n_completed"] for cell in complete) + if complete + else None, + } + + +def _paired(configurations, resamples): + contrasts, skipped = [], [] + for left, right in combinations(configurations, 2): + a, b = left["config"], right["config"] + if a["dataset"] != b["dataset"]: + continue + cells_a = {(c["question_key"], c["replicate"]): c for c in left["questions"]} + cells_b = {(c["question_key"], c["replicate"]): c for c in right["questions"]} + pair = { + "left": left["id"], + "right": right["id"], + "direction": "right-minus-left", + } + if ( + a["samples_per_question"] != b["samples_per_question"] + or cells_a.keys() != cells_b.keys() + or not cells_a + or any(not c["complete"] for c in [*cells_a.values(), *cells_b.values()]) + ): + skipped.append( + { + **pair, + "reason": "question_replicate_sample_coverage_not_identical_and_complete", + } + ) + continue + if any(c.get("scores") is None for c in [*cells_a.values(), *cells_b.values()]): + skipped.append( + { + **pair, + "reason": "unscorable_cells_no_paired_estimate", + "unscorable_cells_left": sum( + c.get("scores") is None for c in cells_a.values() + ), + "unscorable_cells_right": sum( + c.get("scores") is None for c in cells_b.values() + ), + } + ) + continue + question_diffs = defaultdict(lambda: defaultdict(list)) + for key in sorted(cells_a): + for metric in METRICS: + question_diffs[key[0]][metric].append( + cells_b[key]["scores"][metric] - cells_a[key]["scores"][metric] + ) + metrics = {} + for metric in METRICS: + values = [mean(diffs[metric]) for diffs in question_diffs.values()] + estimate = mean(values) + ci = None + if len(values) >= 5: + interval = bootstrap_ci(values, mean, n_resamples=resamples, seed=42) + ci = [interval.ci_lower, interval.ci_upper] + metrics[metric] = {"delta": estimate, "ci95": ci} + contrasts.append( + { + **pair, + "n_questions": len(question_diffs), + "n_replicate_cells": len(cells_a), + "bootstrap_unit": "question_with_replicates_averaged", + "confidence": 0.95, + "bootstrap_method": "BCa", + "bootstrap_resamples": resamples, + "multiple_comparison_adjustment": "none; exploratory contrasts", + "metrics": metrics, + } + ) + return contrasts, skipped + + +def analyze_campaign( + journals, + questions_dir, + *, + task_files=(), + selection=None, + split=None, + resamples=2000, +): + """Return private numeric analysis; no network or upstream data access.""" + if resamples < 1: + raise ValueError("resamples must be positive") + finals, tasks, reservations, attempts = {}, {}, {}, {} + for path in dict.fromkeys(Path(p).resolve() for p in journals): + with path.open() as source: + for line in source: + if not line.strip(): + continue + row = json.loads(line) + kind = row["kind"] + if kind == "final": + task = row["task"] + compact = { + key: row.get(key) + for key in ("status", "elapsed_seconds", "error", "settings") + } + compact["response"] = { + key: (row.get("response") or {}).get(key) + for key in ("selected_option", "refusal") + } + if task["id"] in tasks and tasks[task["id"]] != task: + raise ValueError("Task id has conflicting inputs") + if task["id"] in finals and finals[task["id"]] != compact: + raise ValueError("Task has conflicting final records") + tasks[task["id"]], finals[task["id"]] = task, compact + elif kind in ("reservation", "attempt"): + target = reservations if kind == "reservation" else attempts + key = row["attempt_id"] + fields = ( + ("task_id", "reserved_usd") + if kind == "reservation" + else ( + "task_id", + "accounted_usd", + "usage", + "cost_source", + "elapsed_seconds", + ) + ) + compact = {field: row.get(field) for field in fields} + if key in target and target[key] != compact: + raise ValueError("Attempt id has conflicting records") + target[key] = compact + for path in task_files: + for line in Path(path).read_text().splitlines(): + if line.strip(): + task = json.loads(line) + existing = { + key: value + for key, value in tasks.get(task["id"], {}).items() + if key != "_question_hash" + } + if existing and existing != task: + raise ValueError("Task manifest conflicts with journal") + tasks[task["id"]] = task + if attempts.keys() - reservations.keys(): + raise ValueError("Attempt has no reservation") + if split is not None and selection is None: + raise ValueError("--split requires --selection") + if selection: + for groups in selection.values(): + if isinstance(groups, dict) and set(groups.get("development", [])) & set( + groups.get("evaluation", []) + ): + raise ValueError("Development and evaluation keys overlap") + groups = defaultdict(list) + for task_id, task in tasks.items(): + if selection is not None: + keys = selection.get(task["dataset"], []) + if isinstance(keys, dict): + keys = ( + keys.get(split, []) + if split + else [key for values in keys.values() for key in values] + ) + elif split: + raise ValueError( + "Named split requires dataset -> split -> keys selection" + ) + if task["question_key"] not in keys: + continue + groups[_config_key(task)].append((task, finals.get(task_id))) + configurations, prefix_rows = [], [] + for index, (config_key, members) in enumerate(sorted(groups.items())): + config = json.loads(config_key) + dataset = config["dataset"] + raw = json.loads( + (Path(questions_dir) / f"{dataset}-questions-private.json").read_text() + ) + lookup = { + row["key"]: row + for row in (raw["questions"] if isinstance(raw, dict) else raw) + } + cells = defaultdict(dict) + for task, final in members: + key = (task["question_key"], task.get("replicate", 0)) + sample = task.get("sample_index", 0) + expected = config["samples_per_question"] + if ( + isinstance(sample, bool) + or not isinstance(sample, int) + or not isinstance(expected, int) + or expected <= 0 + or not 0 <= sample < expected + ): + raise ValueError("Invalid sample index or expected sample count") + if sample in cells[key]: + raise ValueError("Duplicate logical sample across task ids") + cells[key][sample] = final + output_cells = [] + for (question_key, replicate), by_sample in sorted(cells.items()): + q = lookup[question_key] + question = Question( + key=question_key, + text="", + options=q["options"], + human_distribution=q.get("human_distribution") or {}, + answer_withheld=q.get("answer_withheld", False), + ) + complete_rows = { + i: row + for i, row in by_sample.items() + if row is not None and row["status"] == "completed" + } + missing = sorted(set(range(expected)) - complete_rows.keys()) + cell = { + "question_key": question_key, + "replicate": replicate, + "complete": not missing, + "expected_samples": expected, + "n_completed": len(complete_rows), + "missing_sample_indices": missing, + "n_errors": sum( + row is not None and row["status"] == "error" + for row in by_sample.values() + ), + "scores": None, + } + if not missing: + cell.update( + _cell_score(question, [complete_rows[i] for i in range(expected)]) + ) + output_cells.append(cell) + for prefix in PREFIXES: + if prefix <= expected and all( + i in complete_rows for i in range(prefix) + ): + prefix_rows.append( + { + "config_id": f"config-{index}", + "question_key": question_key, + "replicate": replicate, + "prefix_samples": prefix, + "source_cell_complete": not missing, + **_cell_score( + question, [complete_rows[i] for i in range(prefix)] + ), + } + ) + member_ids = {task["id"] for task, _ in members} + relevant_reservations = { + key: row + for key, row in reservations.items() + if row["task_id"] in member_ids + } + relevant_attempts = { + key: row for key, row in attempts.items() if key in relevant_reservations + } + configurations.append( + { + "id": f"config-{index}", + "config": config, + "summary": _summary(output_cells), + "replicates": { + str(rep): _summary( + [cell for cell in output_cells if cell["replicate"] == rep] + ) + for rep in sorted({cell["replicate"] for cell in output_cells}) + }, + "questions": output_cells, + "billing": _billing(relevant_reservations, relevant_attempts), + "response_latency": _latencies( + [ + _number(row.get("elapsed_seconds")) + for _, row in members + if row is not None + ] + ), + "settings_counts": dict( + Counter( + json.dumps(row.get("settings"), sort_keys=True) + for _, row in members + if row is not None + ) + ), + "errors": dict( + Counter( + row.get("error") or "unknown" + for _, row in members + if row is not None and row["status"] == "error" + ) + ), + } + ) + contrasts, skipped = _paired(configurations, resamples) + return { + "schema_version": 1, + "scope": "private campaign analysis; distributional survey fidelity only", + "split": split, + "coverage_scope": "task manifests plus observed journal tasks" + if task_files + else "observed final tasks only; undispatched tasks require --tasks", + "configuration_count": len(configurations), + "configurations": configurations, + "convergence_prefixes": prefix_rows, + "paired_contrasts": contrasts, + "unpaired_configurations": skipped, + "all_journal_billing": _billing(reservations, attempts), + "unattributed_attempt_tasks": len( + {row["task_id"] for row in reservations.values()} - tasks.keys() + ), + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--journal", nargs="+", required=True, type=Path) + parser.add_argument("--questions-dir", required=True, type=Path) + parser.add_argument("--tasks", nargs="*", default=[], type=Path) + parser.add_argument( + "--selection", + type=Path, + help="JSON dataset -> keys, or dataset -> {development: keys, evaluation: keys}", + ) + parser.add_argument("--split", choices=("development", "evaluation")) + parser.add_argument("--resamples", type=int, default=2000) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args(argv) + result = analyze_campaign( + args.journal, + args.questions_dir, + task_files=args.tasks, + selection=json.loads(args.selection.read_text()) if args.selection else None, + split=args.split, + resamples=args.resamples, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(args.output.suffix + ".tmp") + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as target: + os.fchmod(target.fileno(), 0o600) + json.dump(result, target, indent=2, allow_nan=False) + target.write("\n") + os.replace(temporary, args.output) + return 0 diff --git a/src/synthbench/campaign_transport.py b/src/synthbench/campaign_transport.py new file mode 100644 index 0000000..065a042 --- /dev/null +++ b/src/synthbench/campaign_transport.py @@ -0,0 +1,94 @@ +"""Preserve OpenRouter billing evidence on Althing's native Messages transport. + +This per-instance shim mirrors Althing 1.9.1's ``_send_anthropic`` request, +error handling, and parsing. It changes no prompt or decoding parameter and +does not replace the native message id. Remove it when the upstream adapter +retains response-header generation ids and its raw usage block itself. +""" + +from __future__ import annotations + +import json +from types import MethodType +from typing import Any, Callable + +import httpx + + +def attach_openrouter_billing( + client: Any, + canonical_model: str, + *, + post: Callable[..., httpx.Response] | None = None, +) -> dict[str, str]: + """Annotate responses from one resolved OpenRouter provider instance. + + ``canonical_model`` accepts ``anthropic/...`` or + ``openrouter/anthropic/...``. Explicit routing prevents credential-based + fallback to a direct Anthropic provider. The returned metadata contains + no credentials, request headers, or request body. ``post`` is injectable + for offline transport-equivalence tests. + """ + from althing.llm.providers import openrouter as native + + upstream_model = canonical_model.removeprefix("openrouter/") + if not upstream_model.startswith("anthropic/"): + raise ValueError( + "Billing instrumentation requires an explicit Anthropic OpenRouter model" + ) + provider = client._resolve_provider("openrouter/" + upstream_model) + if not isinstance(provider, native.OpenRouterProvider): + raise TypeError("Resolved provider is not Althing's OpenRouter adapter") + metadata = { + "transport": "anthropic-messages-passthrough", + "billing_instrumentation": "generation-header-and-native-usage-v1", + } + if getattr(provider, "_synthbench_openrouter_billing_attached", False): + return metadata + send_post = post if post is not None else httpx.post + + def send_anthropic(self, request): + # Keep this wire path equivalent to the installed native method. + url = f"{self._base_url}/v1/messages" + body = native.build_anthropic_body(request) + native._apply_provider_routing(body, request) + try: + resp = send_post( + url, + headers=self._headers(anthropic_passthrough=True), + json=body, + timeout=120.0, + ) + except httpx.HTTPError as exc: + raise native.LLMError( + f"Transport error: {exc}", + native.LLMErrorCategory.TRANSPORT, + cause=exc, + ) from exc + if resp.status_code != 200: + raise native._openrouter_error_from_response(resp) + try: + data = resp.json() + except (json.JSONDecodeError, ValueError) as exc: + raise native.LLMError( + "Failed to parse OpenRouter Anthropic-passthrough response", + native.LLMErrorCategory.DESERIALIZATION, + cause=exc, + ) from exc + response = native.parse_anthropic_response(data, request.model) + + generation_id = resp.headers.get("x-generation-id") + if not generation_id: + request_id = resp.headers.get("request-id") or resp.headers.get( + "x-request-id" + ) + if request_id and request_id.startswith("gen-"): + generation_id = request_id + response._openrouter_generation_id = generation_id + usage = data.get("usage") + response._openrouter_usage = usage if isinstance(usage, dict) else {} + return response + + provider._send_anthropic = MethodType(send_anthropic, provider) + provider._synthbench_openrouter_billing_attached = True + return metadata diff --git a/src/synthbench/providers/openrouter.py b/src/synthbench/providers/openrouter.py index f6d6b03..8c57a95 100644 --- a/src/synthbench/providers/openrouter.py +++ b/src/synthbench/providers/openrouter.py @@ -78,7 +78,7 @@ class OpenRouterProvider(Provider): def __init__( self, model: str = "openai/gpt-4o-mini", - temperature: float = 1.0, + temperature: float | None = None, effort: str | None = None, ): try: @@ -126,12 +126,13 @@ async def respond( request_kwargs: dict = { "model": self._model, "max_tokens": RAW_ANSWER_MAX_TOKENS, - "temperature": self._temperature, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": prompt}, ], } + if self._temperature is not None: + request_kwargs["temperature"] = self._temperature if self._effort is not None: # OpenRouter's unified reasoning parameter (sent via extra_body so # it reaches the request JSON regardless of openai SDK version). diff --git a/tests/test_campaign.py b/tests/test_campaign.py new file mode 100644 index 0000000..27a2795 --- /dev/null +++ b/tests/test_campaign.py @@ -0,0 +1,403 @@ +"""No-network checks for campaign billing and durable response collection.""" + +import asyncio +import hashlib +import json +import time +from decimal import Decimal +from types import SimpleNamespace + +import pytest +import httpx + +from synthbench.campaign import ( + CampaignStopped, + Collector, + Ledger, + load_pricing, + load_questions, + load_tasks, +) + + +def task(index=0): + return { + "id": f"task-{index}", + "dataset": "gss", + "question_key": "q", + "provider": "openrouter", + "model": "anthropic/test", + "sample_index": index, + } + + +def test_concurrent_reservations_cannot_oversubscribe(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + + async def reserve(i): + try: + return await asyncio.to_thread(ledger.reserve, task(i), Decimal("0.4"), {}) + except CampaignStopped: + return None + + async def run(): + return await asyncio.gather(*(reserve(i) for i in range(10))) + + try: + reservations = asyncio.run(run()) + assert sum(x is not None for x in reservations) == 2 + assert ledger.accounted == Decimal("0.8") + finally: + ledger.close() + + +def test_resume_keeps_unsettled_and_failed_reservations(tmp_path): + path = tmp_path / "journal.jsonl" + ledger = Ledger(path, 1, time.time() + 60) + abandoned = ledger.reserve(task(), Decimal("0.4"), {}) + failed = ledger.reserve(task(1), Decimal("0.4"), {}) + ledger.settle(failed, Decimal("0.4"), cost_source="reservation-retained") + ledger.final(task(1), status="error") + ledger.close() + ledger = Ledger(path, 1, time.time() + 60) + try: + assert ledger.charges[abandoned] == Decimal("0.4") + assert ledger.accounted == Decimal("0.8") + assert ledger.completed["task-1"]["status"] == "error" + with pytest.raises(CampaignStopped): + ledger.reserve(task(2), Decimal("0.3"), {}) + finally: + ledger.close() + + +def test_cost_settlement_releases_only_unused_reserve(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + try: + attempt = ledger.reserve(task(), Decimal("0.8"), {}) + ledger.settle(attempt, Decimal("0.2"), cost_source="provider-reported") + ledger.reserve(task(1), Decimal("0.8"), {}) + assert ledger.accounted == Decimal(1) + finally: + ledger.close() + + +def test_deadline_and_single_writer_fail_closed(tmp_path): + path = tmp_path / "journal.jsonl" + ledger = Ledger(path, 1, time.time() - 1) + try: + with pytest.raises(CampaignStopped, match="deadline"): + ledger.reserve(task(), Decimal("0.1"), {}) + with pytest.raises(BlockingIOError): + Ledger(path, 1, time.time() + 60) + assert path.read_text() == "" + finally: + ledger.close() + + +def test_torn_record_is_not_silently_discarded(tmp_path): + path = tmp_path / "journal.jsonl" + path.write_text('{"kind":"reservation"') + with pytest.raises(json.JSONDecodeError): + Ledger(path, 1, time.time() + 60) + + +def test_task_validation_and_question_answer_key_exclusion(tmp_path): + tasks_path = tmp_path / "tasks.jsonl" + tasks_path.write_text(json.dumps(task()) + "\n") + tasks = load_tasks(tasks_path) + (tmp_path / "gss-questions-private.json").write_text( + json.dumps( + [ + { + "key": "q", + "text": "Question?", + "options": ["Yes", "No"], + "human_distribution": {"Yes": 0.5, "No": 0.5}, + } + ] + ) + ) + questions = load_questions(tasks, tmp_path) + assert "human_distribution" not in questions["gss", "q"] + tasks_path.write_text((json.dumps(task()) + "\n") * 2) + with pytest.raises(ValueError, match="Duplicate"): + load_tasks(tasks_path) + + +def test_catalog_ignores_unrelated_prices_but_rejects_invalid_claude_rate(tmp_path): + path = tmp_path / "pricing.json" + catalog = { + "data": [ + {"id": "unrelated/credit", "pricing": {"prompt": "-1", "completion": "-1"}}, + { + "id": "anthropic/test", + "pricing": {"prompt": "0.000002", "completion": "0.00001"}, + }, + ] + } + path.write_text(json.dumps(catalog)) + assert load_pricing(path) == {"anthropic/test": (Decimal(2), Decimal(10))} + catalog["data"][1]["pricing"]["prompt"] = "-1" + path.write_text(json.dumps(catalog)) + with pytest.raises(ValueError, match="finite and nonnegative"): + load_pricing(path) + + +@pytest.mark.asyncio +async def test_completed_task_not_dispatched_and_inputs_cannot_change(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + collector = Collector(ledger, {}, {("gss", "q"): {}}, 2) + ledger.final( + {**task(), "_question_hash": hashlib.sha256(b"{}").hexdigest()}, + status="completed", + ) + try: + await collector._one(task()) + assert not collector.providers + with pytest.raises(ValueError, match="different inputs"): + await collector._one({**task(), "replicate": 9}) + collector.questions["gss", "q"] = {"text": "Changed snapshot"} + with pytest.raises(ValueError, match="different inputs"): + await collector._one(task()) + finally: + await collector.cost_client.aclose() + ledger.close() + + +@pytest.mark.asyncio +async def test_raw_attempts_are_individually_billed_and_response_retained( + tmp_path, monkeypatch +): + import synthbench.providers.openrouter as raw_module + from synthbench.providers.base import Response + + class FakeRaw: + def __init__(self, **kwargs): + self._client = SimpleNamespace() + self.reasoning = None + + async def _request(self, kwargs): + return SimpleNamespace( + id="gen-test", + usage=SimpleNamespace(model_dump=lambda: {"cost": 0.1}), + model_dump=lambda: {"id": "gen-test", "raw": "A"}, + ) + + async def respond(self, question, options): + await self._request({"max_tokens": 64, "messages": [{"content": question}]}) + await self._request({"max_tokens": 64, "messages": [{"content": question}]}) + return Response("Yes", "A") + + async def close(self): + pass + + monkeypatch.setattr(raw_module, "OpenRouterProvider", FakeRaw) + ledger = Ledger(tmp_path / "journal.jsonl", 2, time.time() + 60) + collector = Collector( + ledger, + {"anthropic/test": (Decimal(100), Decimal(100))}, + {("gss", "q"): {"text": "Question?", "options": ["Yes", "No"]}}, + ) + try: + summary = await collector.run([task()]) + assert summary["completed"] == 1 + assert ledger.accounted == Decimal("0.2") + rows = [json.loads(line) for line in ledger.path.read_text().splitlines()] + assert [row["kind"] for row in rows] == [ + "campaign", + "reservation", + "received", + "attempt", + "reservation", + "received", + "attempt", + "final", + ] + assert rows[-1]["response"]["raw_text"] == "A" + assert rows[-1]["response"]["metadata"]["generation_id"] == "gen-test" + assert rows[-1]["response"]["metadata"]["attempt_id"] + assert rows[-1]["settings"]["reasoning_request"] is None + finally: + ledger.close() + + +@pytest.mark.asyncio +async def test_transport_failure_retains_reservation(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + collector = Collector( + ledger, {}, {("gss", "q"): {"text": "Q", "options": ["A", "B"]}} + ) + + async def fail(task_arg, question): + ledger.reserve(task_arg, Decimal("0.25"), {}) + raise ConnectionError("Do not persist arbitrary exception strings") + + collector._one_althing = fail + current = {**task(), "provider": "althing"} + try: + summary = await collector.run([current]) + assert summary["errors"] == 1 + assert ledger.accounted == Decimal("0.25") + assert "Do not persist" not in ledger.path.read_text() + finally: + ledger.close() + + +@pytest.mark.asyncio +async def test_byok_zero_gateway_cost_accounts_upstream_credits(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + collector = Collector(ledger, {"anthropic/test": (Decimal(2), Decimal(10))}, {}) + try: + cost, source = await collector._cost( + "anthropic/test", + None, + { + "cost": 0, + "is_byok": True, + "cost_details": {"upstream_inference_cost": 0.0123}, + "prompt_tokens": 100, + "completion_tokens": 10, + }, + ) + assert cost == Decimal("0.0123") + assert "upstream" in source + cost, source = await collector._cost( + "anthropic/test", + None, + { + "cost": 0, + "prompt_tokens": 100, + "completion_tokens": 10, + }, + ) + assert cost == Decimal("0.0003") + assert source == "catalog-token-estimate" + cost, _ = await collector._cost( + "anthropic/test", + None, + { + "cost": 0.02, + "cost_details": {"upstream_inference_cost": 0.01}, + }, + ) + assert cost == Decimal("0.02") + finally: + await collector.cost_client.aclose() + ledger.close() + + +def test_underestimated_reservation_stops_even_before_total_budget(tmp_path): + ledger = Ledger(tmp_path / "journal.jsonl", 100, time.time() + 60) + try: + attempt = ledger.reserve(task(), Decimal("0.001"), {}) + with pytest.raises(CampaignStopped, match="exceeded reservation"): + ledger.settle(attempt, Decimal("0.002")) + assert ledger.accounted == Decimal("0.002") + finally: + ledger.close() + + +def test_campaign_provenance_rejects_pricing_edits_on_resume(tmp_path): + path = tmp_path / "journal.jsonl" + ledger = Ledger(path, 100, time.time() + 60) + ledger.bind_campaign({"pricing": {"anthropic/test": ["2", "10"]}}) + ledger.close() + ledger = Ledger(path, 100, time.time() + 60) + try: + ledger.bind_campaign({"pricing": {"anthropic/test": ["2", "10"]}}) + with pytest.raises(ValueError, match="pricing or runtime changed"): + ledger.bind_campaign({"pricing": {"anthropic/test": ["4", "20"]}}) + finally: + ledger.close() + + +def test_overrun_halt_survives_resume_with_larger_cap(tmp_path): + path = tmp_path / "journal.jsonl" + ledger = Ledger(path, 1, time.time() + 60) + attempt = ledger.reserve(task(), Decimal("0.01"), {}) + with pytest.raises(CampaignStopped): + ledger.settle(attempt, Decimal("0.02")) + ledger.close() + resumed = Ledger(path, 10, time.time() + 60) + try: + with pytest.raises(CampaignStopped, match="journal halted"): + resumed.reserve(task(1), Decimal("0.01"), {}) + finally: + resumed.close() + + +@pytest.mark.asyncio +async def test_received_answer_survives_billing_failure(tmp_path, monkeypatch): + import synthbench.providers.openrouter as raw_module + + class FakeRaw: + def __init__(self, **kwargs): + self._client = SimpleNamespace() + + async def _request(self, kwargs): + return SimpleNamespace( + id="gen-recoverable", + usage=SimpleNamespace(model_dump=lambda: {"cost": "invalid"}), + model_dump=lambda: {"id": "gen-recoverable", "answer": "A"}, + ) + + async def respond(self, question, options): + await self._request({"max_tokens": 64, "messages": []}) + + monkeypatch.setattr(raw_module, "OpenRouterProvider", FakeRaw) + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + collector = Collector( + ledger, + {"anthropic/test": (Decimal(2), Decimal(10))}, + {("gss", "q"): {"text": "Q", "options": ["Yes", "No"]}}, + ) + try: + result = await collector.run([task()]) + assert result["errors"] == 1 + rows = [json.loads(line) for line in ledger.path.read_text().splitlines()] + received = next(row for row in rows if row["kind"] == "received") + assert received["generation_id"] == "gen-recoverable" + assert received["response"]["answer"] == "A" + assert ledger.accounted > 0 + finally: + ledger.close() + + +@pytest.mark.asyncio +async def test_generation_lookup_uses_upstream_cost_when_gateway_is_zero( + tmp_path, monkeypatch +): + monkeypatch.setenv("OPENROUTER_API_KEY", "fake-not-a-secret") + ledger = Ledger(tmp_path / "journal.jsonl", 1, time.time() + 60) + collector = Collector(ledger, {"anthropic/test": (Decimal(2), Decimal(10))}, {}) + await collector.cost_client.aclose() + + calls = [] + + def respond(request): + assert request.url.params["id"] == "gen-example" + calls.append(request) + if len(calls) == 1: + return httpx.Response(404, json={"error": "not indexed yet"}) + return httpx.Response( + 200, + json={ + "data": { + "total_cost": 0, + "is_byok": True, + "upstream_inference_cost": 0.0000068, + } + }, + ) + + collector.cost_client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + try: + cost, source = await collector._cost( + "anthropic/test", "gen-example", {"cost": 0} + ) + assert cost == Decimal("0.0000068") + assert source == "generation-api-max-gateway-upstream" + assert len(calls) == 2 + finally: + await collector.cost_client.aclose() + ledger.close() diff --git a/tests/test_campaign_analysis.py b/tests/test_campaign_analysis.py new file mode 100644 index 0000000..8a4908f --- /dev/null +++ b/tests/test_campaign_analysis.py @@ -0,0 +1,347 @@ +"""Campaign inference uses complete distributions and question-level units.""" + +from __future__ import annotations + +import json +import stat + +import pytest + +from synthbench.campaign_analysis import analyze_campaign, main +from synthbench.metrics import jensen_shannon_divergence + + +def _task(model="good", question="q0", sample=0, n=5, replicate=0): + return { + "id": f"{model}-{question}-{replicate}-{n}-{sample}", + "dataset": "fixture", + "model": model, + "provider": "althing", + "question_key": question, + "replicate": replicate, + "sample_index": sample, + "samples_per_question": n, + } + + +def _final(task, option="A", refusal=False, status="completed"): + return { + "kind": "final", + "task_id": task["id"], + "task": task, + "status": status, + "error": "TransportError" if status == "error" else None, + "response": { + "selected_option": option, + "refusal": refusal, + "raw_text": "PRIVATE RESPONSE", + }, + "elapsed_seconds": 2.0, + } + + +@pytest.fixture +def files(tmp_path): + questions = [ + { + "key": f"q{i}", + "text": "PRIVATE SURVEY TEXT", + "options": ["A", "B"], + "human_distribution": {"A": 0.8, "B": 0.2}, + } + for i in range(6) + ] + (tmp_path / "fixture-questions-private.json").write_text(json.dumps(questions)) + + def write(rows, name="journal.jsonl"): + path = tmp_path / name + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + return path + + return tmp_path, write + + +def test_known_distribution_and_replicates_remain_separate(files): + directory, write = files + rows = [] + for replicate in (0, 1): + for sample in range(5): + rows.append( + _final( + _task(sample=sample, replicate=replicate), + "A" if sample < (4 if replicate == 0 else 1) else "B", + ) + ) + result = analyze_campaign([write(rows)], directory) + config = result["configurations"][0] + assert config["replicates"]["0"]["scores"] == { + "sps": 1.0, + "p_dist": 1.0, + "p_rank": 1.0, + "p_refuse": 1.0, + } + assert config["replicates"]["1"]["scores"]["p_rank"] == 0.0 + assert len(config["questions"]) == 2 + assert config["summary"]["n_distinct_scored_questions"] == 1 + assert config["summary"]["scores"]["p_rank"] == 0.5 + serialized = json.dumps(result) + for secret in ( + "PRIVATE SURVEY TEXT", + "PRIVATE RESPONSE", + "human_distribution", + "model_distribution", + ): + assert secret not in serialized + + +def test_incomplete_cell_is_not_scored_but_complete_prefix_is_labeled(files): + directory, write = files + rows = [_final(_task(sample=i, n=30), "A" if i < 10 else "B") for i in range(20)] + rows.append(_final(_task(sample=20, n=30), status="error")) + result = analyze_campaign([write(list(reversed(rows)))], directory) + config = result["configurations"][0] + assert config["summary"]["scores"] is None + cell = config["questions"][0] + assert cell["n_completed"] == 20 + assert cell["missing_sample_indices"] == list(range(20, 30)) + assert cell["n_errors"] == 1 + assert [row["prefix_samples"] for row in result["convergence_prefixes"]] == [10, 20] + assert all( + not row["source_cell_complete"] for row in result["convergence_prefixes"] + ) + assert result["convergence_prefixes"][0]["scores"]["p_rank"] == 1.0 + assert result["convergence_prefixes"][1]["scores"]["p_rank"] == 0.5 + + +def test_no_uniform_fallback_for_all_refusals_and_parse_failures(files): + directory, write = files + rows = [_final(_task(sample=i), option=None, refusal=i < 3) for i in range(5)] + cell = analyze_campaign([write(rows)], directory)["configurations"][0]["questions"][ + 0 + ] + assert cell["complete"] + assert cell["scores"] is None + assert cell["score_unavailable_reason"] == "no_valid_answers" + assert cell["refusal_rate"] == 0.6 + assert cell["parse_failure_rate"] == 0.4 + + +def test_some_parse_failures_use_runner_refusal_denominator(files): + directory, write = files + rows = [ + _final(_task(sample=i), option="A" if i < 3 else None, refusal=i == 3) + for i in range(5) + ] + cell = analyze_campaign([write(rows)], directory)["configurations"][0]["questions"][ + 0 + ] + assert cell["scores"]["p_refuse"] == 0.75 # 1 refusal / 4 valid-or-refused outcomes + assert cell["refusal_rate"] == 0.2 # Display rates include parse failures. + assert cell["parse_failure_rate"] == 0.2 + assert cell["scores"]["p_dist"] == pytest.approx( + 1 - jensen_shannon_divergence({"A": 0.8, "B": 0.2}, {"A": 1.0, "B": 0.0}) + ) + + +@pytest.mark.asyncio +async def test_scores_match_existing_runner(files, mock_dataset): + from synthbench.providers.base import Provider, Response + from synthbench.runner import BenchmarkRunner + + directory, write = files + question = mock_dataset.load(n=1)[0] + (directory / "fixture-questions-private.json").write_text( + json.dumps( + [ + { + "key": question.key, + "options": question.options, + "human_distribution": question.human_distribution, + } + ] + ) + ) + outcomes = [ + Response(selected_option=question.options[0]), + Response(selected_option=question.options[0]), + Response(selected_option=question.options[1]), + Response(selected_option=None, refusal=True), + Response(selected_option=None), + ] + + class SequenceProvider(Provider): + name = "sequence" + + def __init__(self): + self.responses = iter(outcomes) + + async def respond(self, question, options, *, persona=None): + return next(self.responses) + + runner_result = await BenchmarkRunner( + mock_dataset, SequenceProvider(), samples_per_question=5, concurrency=1 + ).run(n=1) + rows = [ + _final( + _task(question=question.key, sample=i), + response.selected_option, + response.refusal, + ) + for i, response in enumerate(outcomes) + ] + result = analyze_campaign([write(rows)], directory) + scores = result["configurations"][0]["summary"]["scores"] + assert scores == pytest.approx( + { + "sps": runner_result.sps, + "p_dist": runner_result.p_dist, + "p_rank": runner_result.p_rank, + "p_refuse": runner_result.p_refuse, + } + ) + + +def test_pairs_bootstrap_questions_after_averaging_replicates(files): + directory, write = files + rows = [] + for question in range(5): + for replicate in range(3): + for model, option in (("good", "A"), ("bad", "B")): + for i in range(5): + rows.append( + _final( + _task( + model=model, + question=f"q{question}", + sample=i, + replicate=replicate, + ), + option, + ) + ) + result = analyze_campaign([write(rows)], directory, resamples=100) + contrast = result["paired_contrasts"][0] + assert contrast["n_questions"] == 5 + assert contrast["n_replicate_cells"] == 15 + assert contrast["bootstrap_unit"] == "question_with_replicates_averaged" + # Sorted configs put bad before good: positive right-minus-left rank difference. + assert contrast["metrics"]["p_rank"] == {"delta": 1.0, "ci95": [1.0, 1.0]} + + +def test_mismatched_question_sets_are_not_compared(files): + directory, write = files + rows = [ + _final(_task(model=model, question=q, sample=i)) + for model, q in (("good", "q0"), ("bad", "q1")) + for i in range(5) + ] + result = analyze_campaign([write(rows)], directory) + assert not result["paired_contrasts"] + assert len(result["unpaired_configurations"]) == 1 + + +def test_billing_counts_cutoff_attempts_and_unsettled_reservations(files): + directory, write = files + task = _task() + rows = [] + for i in range(3): + rows.append( + { + "kind": "reservation", + "attempt_id": str(i), + "task_id": task["id"], + "reserved_usd": "0.5", + } + ) + if i < 2: + rows.append( + { + "kind": "attempt", + "attempt_id": str(i), + "task_id": task["id"], + "accounted_usd": "0.2", + "cost_source": "provider-reported-max-gateway-upstream", + "usage": { + "cost": 0.0, + "cost_details": {"upstream_inference_cost": 0.2}, + }, + "elapsed_seconds": 1, + } + ) + rows.append(_final(task)) + journal = write(rows) + result = analyze_campaign([journal, journal], directory) + cost = result["all_journal_billing"] + assert cost["accounted_usd"] == 0.9 + assert cost["attempt_count"] == 3 + assert cost["unsettled_attempt_count"] == 1 + assert cost["reported_costs"]["gateway_usd"] == { + "usd": 0.0, + "attempts_with_evidence": 2, + } + assert cost["reported_costs"]["upstream_usd"]["usd"] == 0.4 + assert cost["reported_costs"]["provider_reported_usd"]["usd"] is None + + +def test_manifest_reveals_fully_undispatched_cells(files): + directory, write = files + tasks = [_task(question=q, sample=i) for q in ("q0", "q1") for i in range(5)] + manifest = write(tasks, "tasks.jsonl") + finals = [ + _final({**t, "_question_hash": "actual-collector-input-hash"}) + for t in tasks[:5] + ] + result = analyze_campaign([write(finals)], directory, task_files=[manifest]) + config = result["configurations"][0] + assert config["summary"]["n_question_cells"] == 2 + assert config["summary"]["n_complete_cells"] == 1 + assert config["questions"][1]["missing_sample_indices"] == list(range(5)) + + +def test_selection_filters_frozen_evaluation_and_cli_writes_private_file(files): + directory, write = files + journal = write( + [_final(_task(question=q, sample=i)) for q in ("q0", "q1") for i in range(5)] + ) + selection = directory / "selection.json" + selection.write_text( + json.dumps({"fixture": {"development": ["q0"], "evaluation": ["q1"]}}) + ) + output = directory / "analysis.json" + assert ( + main( + [ + "--journal", + str(journal), + "--questions-dir", + str(directory), + "--selection", + str(selection), + "--split", + "evaluation", + "--output", + str(output), + ] + ) + == 0 + ) + result = json.loads(output.read_text()) + assert [ + cell["question_key"] for cell in result["configurations"][0]["questions"] + ] == ["q1"] + assert stat.S_IMODE(output.stat().st_mode) == 0o600 + + +def test_conflicting_logical_samples_and_split_overlap_fail_closed(files): + directory, write = files + task = _task() + duplicate = {**task, "id": "different-id"} + journal = write([_final(task), _final(duplicate)]) + with pytest.raises(ValueError, match="Duplicate logical sample"): + analyze_campaign([journal], directory) + with pytest.raises(ValueError, match="overlap"): + analyze_campaign( + [journal], + directory, + selection={"fixture": {"development": ["q0"], "evaluation": ["q0"]}}, + ) diff --git a/tests/test_campaign_transport.py b/tests/test_campaign_transport.py new file mode 100644 index 0000000..0d0bcf5 --- /dev/null +++ b/tests/test_campaign_transport.py @@ -0,0 +1,206 @@ +"""Native wire-equivalence and billing-header retention, without API calls.""" + +from copy import deepcopy + +import httpx +import pytest + +from synthbench.campaign_transport import attach_openrouter_billing + +native = pytest.importorskip("althing.llm.providers.openrouter") +models = pytest.importorskip("althing.llm.models") + + +class Client: + def __init__(self, provider): + self.provider = provider + self.resolved = [] + + def _resolve_provider(self, model): + self.resolved.append(model) + return self.provider + + +def provider(): + result = native.OpenRouterProvider.__new__(native.OpenRouterProvider) + result._api_key = "test-key-not-a-secret" + result._base_url = "https://openrouter.ai/api" + return result + + +def request(*, cache=True): + return models.CompletionRequest( + model="anthropic/claude-haiku-5.5", + max_tokens=1024, + messages=[ + models.InputMessage( + role="user", content=[models.TextBlock(text="Choose A or B.")] + ) + ], + system="Answer as the selected survey respondent.", + tools=[ + models.ToolDefinition( + name="answer", + input_schema={ + "type": "object", + "properties": {"option": {"enum": ["A", "B"]}}, + "required": ["option"], + }, + ) + ], + tool_choice=models.ToolChoice(kind="tool", name="answer"), + provider_routing={"order": ["Anthropic"], "allow_fallbacks": False}, + cache_enabled=cache, + ) + + +def payload(): + return { + "id": "msg_native_id", + "model": "claude-haiku-5.5", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": "tool_native", + "name": "answer", + "input": {"option": "A"}, + } + ], + "stop_reason": "tool_use", + "usage": { + "input_tokens": 120, + "output_tokens": 20, + "cost": 0, + "cost_details": {"upstream_inference_cost": 0.000022}, + "is_byok": True, + }, + } + + +def response(*, headers=None, status=200, body=None): + return httpx.Response( + status, + headers=headers, + json=payload() if body is None else body, + request=httpx.Request("POST", "https://openrouter.ai/api/v1/messages"), + ) + + +@pytest.mark.parametrize("cache", [False, True]) +def test_preserves_native_wire_and_message_id_while_retaining_billing( + monkeypatch, cache +): + original = provider() + instrumented = provider() + sent = [] + + def post(url, **kwargs): + sent.append((url, deepcopy(kwargs))) + return response(headers={"x-generation-id": "gen-openrouter-id"}) + + with monkeypatch.context() as context: + context.setattr(native.httpx, "post", post) + baseline = original._send_anthropic(request(cache=cache)) + client = Client(instrumented) + metadata = attach_openrouter_billing( + client, "anthropic/claude-haiku-5.5", post=post + ) + actual = instrumented._send_anthropic(request(cache=cache)) + + assert sent[0] == sent[1] + assert sent[1][1]["timeout"] == 120.0 + assert "temperature" not in sent[1][1]["json"] + assert sent[1][1]["json"]["provider"] == { + "order": ["Anthropic"], + "allow_fallbacks": False, + } + assert actual.id == baseline.id == "msg_native_id" + assert actual.content == baseline.content + assert actual.usage == baseline.usage + assert actual._openrouter_generation_id == "gen-openrouter-id" + assert actual._openrouter_usage == payload()["usage"] + assert client.resolved == ["openrouter/anthropic/claude-haiku-5.5"] + assert "test-key" not in str(metadata) + assert not hasattr(original, "_synthbench_openrouter_billing_attached") + + +@pytest.mark.parametrize( + "headers,expected", + [ + ({"request-id": "gen-fallback"}, "gen-fallback"), + ({"x-request-id": "gen-x-fallback"}, "gen-x-fallback"), + ({"request-id": "request-unrelated"}, None), + ( + {"x-generation-id": "gen-primary", "request-id": "gen-secondary"}, + "gen-primary", + ), + ({}, None), + ], +) +def test_header_fallback_is_generation_specific(headers, expected): + actual = provider() + attach_openrouter_billing( + Client(actual), + "openrouter/anthropic/claude-haiku-5.5", + post=lambda *args, **kwargs: response(headers=headers), + ) + assert actual._send_anthropic(request())._openrouter_generation_id == expected + + +def test_keeps_native_error_classification(): + actual = provider() + body = { + "error": { + "code": 429, + "message": "Rate limited", + "type": "rate_limit_error", + "metadata": {"provider_name": "Anthropic"}, + } + } + error_response = response(status=429, body=body) + expected = native._openrouter_error_from_response(error_response) + attach_openrouter_billing( + Client(actual), + "anthropic/claude-haiku-5.5", + post=lambda *args, **kwargs: error_response, + ) + with pytest.raises(native.LLMError) as caught: + actual._send_anthropic(request()) + assert caught.value.category == expected.category + assert caught.value.status_code == expected.status_code + assert caught.value.downstream_provider == expected.downstream_provider + assert str(caught.value) == str(expected) + + +@pytest.mark.parametrize("failure", ["transport", "json"]) +def test_transport_and_json_errors_match_native_categories(failure): + actual = provider() + + def post(*args, **kwargs): + if failure == "transport": + raise httpx.ReadTimeout("test timeout") + return httpx.Response(200, content=b"not json") + + attach_openrouter_billing(Client(actual), "anthropic/claude-haiku-5.5", post=post) + with pytest.raises(native.LLMError) as caught: + actual._send_anthropic(request()) + expected = ( + native.LLMErrorCategory.TRANSPORT + if failure == "transport" + else native.LLMErrorCategory.DESERIALIZATION + ) + assert caught.value.category == expected + + +def test_attachment_is_idempotent_and_rejects_wrong_provider(): + actual = provider() + client = Client(actual) + first = attach_openrouter_billing(client, "anthropic/claude-haiku-5.5") + method = actual._send_anthropic + assert attach_openrouter_billing(client, "anthropic/claude-haiku-5.5") == first + assert actual._send_anthropic is method + with pytest.raises(ValueError, match="explicit Anthropic"): + attach_openrouter_billing(client, "google/not-eligible") + with pytest.raises(TypeError, match="not Althing's OpenRouter"): + attach_openrouter_billing(Client(object()), "anthropic/claude-haiku-5.5") diff --git a/tests/test_openrouter_reasoning.py b/tests/test_openrouter_reasoning.py index 803b820..9da36f1 100644 --- a/tests/test_openrouter_reasoning.py +++ b/tests/test_openrouter_reasoning.py @@ -5,6 +5,7 @@ import asyncio from types import SimpleNamespace +import httpx import pytest openai = pytest.importorskip("openai") @@ -50,8 +51,11 @@ async def create(self, **kw): if answer == "mandatory": raise openai.BadRequestError( "Reasoning is mandatory for this endpoint", - response=SimpleNamespace( - request=None, status_code=400, headers={}, json=lambda: {} + response=httpx.Response( + 400, + request=httpx.Request( + "POST", "https://openrouter.ai/api/v1/chat/completions" + ), ), body=None, ) diff --git a/tests/test_openrouter_temperature.py b/tests/test_openrouter_temperature.py new file mode 100644 index 0000000..200e74c --- /dev/null +++ b/tests/test_openrouter_temperature.py @@ -0,0 +1,89 @@ +"""An omitted decoding knob stays omitted on the wire and in CLI metadata.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner + +openai = pytest.importorskip("openai") + +from synthbench.cli import main # noqa: E402 +from synthbench.providers.openrouter import OpenRouterProvider # noqa: E402 + + +@pytest.fixture +def completions(monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "test-key") + create = AsyncMock( + return_value=SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace(content="A"), finish_reason="stop" + ) + ], + usage=None, + ) + ) + client = SimpleNamespace( + chat=SimpleNamespace(completions=SimpleNamespace(create=create)), + close=AsyncMock(), + ) + monkeypatch.setattr(openai, "AsyncOpenAI", lambda **_kwargs: client) + return create + + +@pytest.mark.asyncio +@pytest.mark.parametrize("temperature", [None, 0.0, 0.85, 1.0]) +async def test_request_preserves_explicit_temperature_only(completions, temperature): + kwargs = {} if temperature is None else {"temperature": temperature} + provider = OpenRouterProvider(model="anthropic/claude-sonnet-5.5", **kwargs) + + response = await provider.respond("Favor or oppose?", ["Favor", "Oppose"]) + + assert response.selected_option == "Favor" + sent = completions.call_args.kwargs + if temperature is None: + assert "temperature" not in sent + else: + assert sent["temperature"] == temperature + + +@pytest.mark.parametrize("temperature", [None, 0.0, 0.85]) +def test_cli_temperature_metadata_matches_request( + completions, monkeypatch, mock_dataset, tmp_path, temperature +): + from synthbench.datasets import DATASETS + + monkeypatch.setitem(DATASETS, "mock", type(mock_dataset)) + args = [ + "run", + "--provider", + "openrouter", + "--model", + "anthropic/claude-sonnet-5.5", + "--dataset", + "mock", + "--n", + "1", + "--samples", + "1", + "--output", + str(tmp_path), + ] + if temperature is not None: + args += ["--temperature", str(temperature)] + + result = CliRunner().invoke(main, args) + + assert result.exit_code == 0, result.output + artifact = json.loads(next(tmp_path.glob("*.json")).read_text()) + assert artifact["config"].get("temperature") == temperature + sent = completions.call_args.kwargs + if temperature is None: + assert "temperature" not in sent + else: + assert sent["temperature"] == temperature