Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): add openrouter session costs table (#126976)

Tom Owerse5d15321448f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 4adcbaa5dae0..9c30402cda47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -8844,6 +8844,7 @@ Diffed against: <https://openrouter.ai/docs/llms.txt>
- [ ] `workspace budgets` — per-workspace spend limits, needed to compare spend against budget (low)
- [x] `/end-users` — registered end-user tracking IDs, the lookup for the `user` field on inference requests and API keys (medium)
- [x] `/batches` — asynchronous batch inference jobs with status, request counts, usage and cost (medium)
+- [x] `/datasets/session-cost` — weekly median cost per session by harness, model and turn-count range, in the same public datasets family as app and daily rankings (medium)
Note: No public OpenAPI JSON is reachable (openrouter.ai/docs/openapi.json 404s); the operation inventory was read from the official Go SDK reference pages linked from llms.txt. Generations endpoints were excluded because they require a known generation ID and cannot be bulk-listed. Guardrails, presets, BYOK, files and observability destinations excluded as config.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py
index b7c663777f1a..c56fd52de9e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py
@@ -212,4 +212,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"window_days": "Length of the trailing window in days.",
},
},
+ "session_costs": {
+ "description": "Median USD spend per session for each published agent harness, model, and session turn-count range. Covers every OpenRouter account, aggregated from a weekly refreshed sample of sessions.",
+ "docs_url": "https://openrouter.ai/docs/api/api-reference/datasets/cost-per-session-by-harness-and-model",
+ "columns": {
+ "app_name": "Display label of the published harness.",
+ "app_slug": "Stable public slug of the harness, e.g. 'hermes-agent'.",
+ "model_permaslug": "Exact model permaslug, e.g. 'anthropic/claude-4.8-opus'.",
+ "turn_range": "Inclusive session turn-count range: '1-turn', '2-9-turns', '10-49-turns', or '50-plus-turns'.",
+ "median_session_cost_usd": "Median USD spend per sampled session.",
+ "as_of": "ISO-8601 timestamp when the response was generated.",
+ "version": "Dataset version.",
+ "window_days": "Number of days in the weekly session sample window, or null when no snapshot is published.",
+ "window_end_date": "UTC date of the final day in the session sample window, or null when no snapshot is published.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py
index 264519945979..0f5522268a63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py
@@ -197,6 +197,9 @@ def _get_offset_rows(
rows = data.get("data") or []
if not rows:
break
+ if config.snapshot_key is not None:
+ snapshot = data.get(config.snapshot_key) or {}
+ rows = [{**snapshot, **row} for row in rows]
yield rows
@@ -207,6 +210,11 @@ def _get_offset_rows(
break
offset += len(rows)
+ if config.max_offset is not None and offset > config.max_offset:
+ # A full refresh that stops here would replace the table without the rows past the cap.
+ raise OpenRouterPageCapError(
+ f"OpenRouter: {config.name} has rows past the maximum offset {config.max_offset} the API accepts"
+ )
# Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key).
resumable_source_manager.save_state(OpenRouterResumeConfig(offset=offset))
else:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py
index a0433e9299ef..d6ce2aa2cd0f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py
@@ -48,6 +48,10 @@ class OpenRouterEndpointConfig:
parent_id_column: Optional[str] = None
# /classifications/task wraps its rows with the snapshot date and window. See openrouter.py.
task_classifications: bool = False
+ # Top-level response object with snapshot metadata copied onto each row (e.g. /datasets/session-cost `meta`).
+ snapshot_key: Optional[str] = None
+ # Largest `offset` the endpoint accepts. A full page at this offset fails the sync, since rows past it can't be read.
+ max_offset: Optional[int] = None
should_sync_default: bool = True
@@ -155,6 +159,17 @@ OPENROUTER_ENDPOINTS: dict[str, OpenRouterEndpointConfig] = {
params={"window": "7d"},
task_classifications=True,
),
+ "session_costs": OpenRouterEndpointConfig(
+ name="session_costs",
+ path="/datasets/session-cost",
+ requires_management_key=False,
+ # One cell per harness, model and session turn-count bucket.
+ primary_keys=["app_slug", "model_permaslug", "turn_range"],
+ pagination="offset_limit",
+ page_size=500,
+ snapshot_key="meta",
+ max_offset=5000,
+ ),
"batches": OpenRouterEndpointConfig(
name="batches",
path="/batches",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
index 7dbc860568de..81a393f4f8bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
@@ -33,7 +33,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
_MANAGEMENT_KEY_REQUIRED = (
"Requires an OpenRouter management API key. This key is a regular inference key, which can read only "
- "the models, model endpoints, providers, task classifications, and batches tables."
+ "the models, model endpoints, providers, task classifications, session costs, and batches tables."
)
_INFERENCE_KEY_REQUIRED = (
@@ -76,7 +76,7 @@ class OpenRouterSource(ResumableSource[OpenRouterSourceConfig, OpenRouterResumeC
releaseStatus=ReleaseStatus.GA,
caption="""Enter your OpenRouter API key to pull your OpenRouter usage and account data into the PostHog Data warehouse.
-Use a **management API key** (create one under [Settings -> Management Keys](https://openrouter.ai/settings/keys)) so the activity, API keys, credits, end users, organization members, workspaces, and workspace members tables can sync. A regular inference key can read only the models, model endpoints, providers, task classifications, and batches tables.
+Use a **management API key** (create one under [Settings -> Management Keys](https://openrouter.ai/settings/keys)) so the activity, API keys, credits, end users, organization members, workspaces, and workspace members tables can sync. A regular inference key can read only the models, model endpoints, providers, task classifications, session costs, and batches tables.
A management key can't read batches. To sync them, connect a second OpenRouter source with a regular API key.""",
iconPath="/static/services/openrouter.png",
@@ -138,6 +138,8 @@ A management key can't read batches. To sync them, connect a second OpenRouter s
return (
"Share of all OpenRouter traffic by task type over the last 7 days, across every OpenRouter account"
)
+ if endpoint == "session_costs":
+ return "Median cost per session by agent harness and model, across every OpenRouter account, refreshed weekly"
return None
def _build_schema(endpoint: str) -> SourceSchema:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py
index 4fe61d723851..f12e6c511ee2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py
@@ -157,6 +157,26 @@ class TestOffsetPagination:
assert result.params("limit") == ["100"]
assert result.params("include_inactive") == include_inactive
+ @pytest.mark.parametrize("last_page_size,raised", [(499, None), (500, openrouter.OpenRouterPageCapError)])
+ def test_session_costs_copy_meta_onto_rows_and_fail_past_max_offset(self, last_page_size, raised):
+ meta = {
+ "as_of": "2026-08-12T02:00:00.000Z",
+ "version": "v1",
+ "window_days": 30,
+ "window_end_date": "2026-08-11",
+ }
+ pages = [
+ [{"app_slug": f"app{page}", "model_permaslug": f"m{i}", "turn_range": "1-turn"} for i in range(size)]
+ for page, size in enumerate([500] * 10 + [last_page_size])
+ ]
+ # The API rejects an offset above 5000, so a full page there can't prove the dataset is exhausted.
+ result = _driver().run("session_costs", [ScriptedResponse(json={"data": rows, "meta": meta}) for rows in pages])
+
+ assert (type(result.raised) if result.raised else None) is raised
+ assert result.params("offset") == [str(500 * page) for page in range(11)]
+ assert result.params("limit") == ["500"] * 11
+ assert result.items == [[{**meta, **row} for row in rows] for rows in pages]
+
class TestCursorPagination:
def test_batches_follow_last_id_until_has_more_is_false(self):