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(data-warehouse): add Vercel billing usage table (#72672)

Tom Owersc300c3f88299
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/canonical_descriptions.py
index 7267f89c12cc..c93d0e1482d3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/canonical_descriptions.py
@@ -68,4 +68,31 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"deploymentId": "Identifier of the deployment the alias points to.",
},
},
+ # Column keys are the normalized (snake_case) names the columns land under in the warehouse, not
+ # the PascalCase FOCUS field names from the API.
+ "billing_charges": {
+ "description": "A team's billing usage and cost, one row per charge in the FOCUS v1.3 open cost-and-usage standard at 1-day granularity.",
+ "docs_url": "https://vercel.com/docs/rest-api/billing/list-focus-billing-charges",
+ "columns": {
+ "id": "Surrogate key for the charge, derived from the charge period and its billing dimensions so it stays stable as the charge is restated.",
+ "billed_cost": "Charge amount serving as the basis for invoicing.",
+ "billing_currency": "Currency used for billing (ISO 4217), e.g. USD.",
+ "charge_category": "Classification of the charge: Adjustment, Credit, Purchase, Tax, or Usage.",
+ "charge_period_start": "Inclusive start of the charge period, as an ISO 8601 UTC timestamp.",
+ "charge_period_end": "Exclusive end of the charge period, as an ISO 8601 UTC timestamp.",
+ "consumed_quantity": "Volume of the resource consumed; null when the charge has no measurable quantity.",
+ "consumed_unit": "Unit of measurement for the consumed quantity; null when not measured in units.",
+ "effective_cost": "Amortized cost including discounts and pre-commitment credit purchase amounts.",
+ "region_id": "Provider-assigned identifier for the region the charge applies to.",
+ "region_name": "Display name for the region the charge applies to.",
+ "service_name": "Display name for the Vercel service or product the charge is for.",
+ "service_category": "High-level category of the service (e.g. Compute, Storage, Networking).",
+ "service_provider_name": "Entity making the resource or service available for purchase.",
+ "tags": "Charge metadata, including the Vercel ProjectId and ProjectName the charge relates to.",
+ "pricing_category": "Pricing model used for the charge: Committed, Dynamic, Other, or Standard.",
+ "pricing_currency": "Currency the pricing is expressed in (ISO 4217), e.g. USD.",
+ "pricing_quantity": "Quantity the charge was priced on.",
+ "pricing_unit": "Unit the pricing quantity is expressed in.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/settings.py
index fc46afb9ac2a..939cd8e2956c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/settings.py
@@ -10,6 +10,8 @@ class VercelEndpointConfig:
# Versioned path on https://api.vercel.com (Vercel pins each resource to its own API version).
path: str
# Key in the JSON response body that holds the list of rows (e.g. {"deployments": [...]}).
+ # Empty for endpoints that don't return the shared list-envelope shape (e.g. billing charges,
+ # which streams JSONL — see `is_focus_billing`).
response_data_key: str
primary_key: str
incremental_fields: list[IncrementalField] = field(default_factory=list)
@@ -19,12 +21,35 @@ class VercelEndpointConfig:
# Team-owned resources require ?teamId=<id> on each request. Endpoints that list resources
# visible to the token itself (e.g. /v2/teams) are not team-scoped.
team_scoped: bool = True
+ # Whether the schema picker offers incremental (merge) and append sync for this endpoint.
+ # Kept explicit per endpoint because billing supports incremental merge but not append.
+ supports_incremental: bool = False
+ supports_append: bool = False
+ # Stable datetime column to partition the Delta table on (never changes once emitted). None
+ # leaves the table unpartitioned.
+ partition_key: Optional[str] = None
+ # Per-schema default for the incremental overlap re-read window (seconds). The pipeline shifts
+ # the stored watermark back by this on each incremental run so restated rows get re-read and
+ # merged. Only meaningful for incremental endpoints.
+ default_incremental_lookback_seconds: Optional[int] = None
+ # Billing charges endpoint: streams FOCUS v1.3 records as newline-delimited JSON over a
+ # `from`/`to` date window instead of the cursor-paginated list envelope every other endpoint
+ # uses. Routed through its own transport path in vercel.py.
+ is_focus_billing: bool = False
-# Vercel list endpoints share one pagination model: the response carries a `pagination` object
-# with `count`, `next`, and `prev` Unix-ms timestamps; the next page is requested by passing the
-# `next` value back as the `until` query param. Rows arrive newest-first (descending by creation
-# time), so every SourceResponse here is sort_mode="desc".
+# Charges get restated after they first post (usage finalization, plus adjustments, credits, and tax
+# that land later in the billing cycle). Each incremental run re-reads roughly the last billing cycle
+# so those restatements are re-pulled; merge dedupes the overlap on the synthetic charge id. 35 days
+# covers a monthly cycle plus a few days of settling.
+BILLING_LOOKBACK_SECONDS = 60 * 60 * 24 * 35
+
+
+# The cursor list endpoints below share one pagination model: the response carries a `pagination`
+# object with `count`, `next`, and `prev` Unix-ms timestamps; the next page is requested by passing
+# the `next` value back as the `until` query param. Rows arrive newest-first (descending by creation
+# time), so those SourceResponses are sort_mode="desc". billing_charges is the exception — it uses a
+# date-window JSONL transport and yields ascending (see vercel.py).
VERCEL_ENDPOINTS: dict[str, VercelEndpointConfig] = {
"deployments": VercelEndpointConfig(
name="deployments",
@@ -35,6 +60,8 @@ VERCEL_ENDPOINTS: dict[str, VercelEndpointConfig] = {
# deployment creation time. `created` is an immutable epoch-ms integer, so it is both the
# incremental cursor and a stable ordering key.
since_param="since",
+ supports_incremental=True,
+ supports_append=True,
incremental_fields=[
{
"label": "created",
@@ -74,6 +101,30 @@ VERCEL_ENDPOINTS: dict[str, VercelEndpointConfig] = {
response_data_key="aliases",
primary_key="uid",
),
+ # Team billing usage & cost, in the FOCUS v1.3 open cost-and-usage standard. Streamed as JSONL
+ # over a `from`/`to` window at 1-day granularity. FOCUS records carry no natural id, so the
+ # transport synthesizes a stable `id` from the charge period plus its billing dimensions (see
+ # vercel.py) — merge updates a charge in place as it gets restated. Incremental (merge) only:
+ # append would materialize a duplicate every time a restated charge is re-read.
+ "billing_charges": VercelEndpointConfig(
+ name="billing_charges",
+ path="/v1/billing/charges",
+ response_data_key="", # not a list-envelope response; rows stream as JSONL
+ primary_key="id", # synthesized in vercel.py from the charge's identity/dimension fields
+ is_focus_billing=True,
+ supports_incremental=True,
+ supports_append=False,
+ partition_key="charge_period_start",
+ default_incremental_lookback_seconds=BILLING_LOOKBACK_SECONDS,
+ incremental_fields=[
+ {
+ "label": "charge_period_start",
+ "type": IncrementalFieldType.DateTime,
+ "field": "charge_period_start",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
}
ENDPOINTS = tuple(VERCEL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/source.py
index 27787fdd88ac..f7f4eaea01e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/source.py
@@ -21,10 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.reg
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.vercel import VercelSourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.vercel.settings import (
- ENDPOINTS,
- INCREMENTAL_FIELDS,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.vercel.settings import VERCEL_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.vercel.vercel import (
VercelResumeConfig,
validate_credentials as validate_vercel_credentials,
@@ -55,11 +52,11 @@ class VercelSource(ResumableSource[VercelSourceConfig, VercelResumeConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Vercel",
releaseStatus=ReleaseStatus.ALPHA,
- caption="""Enter a Vercel access token to pull your Vercel deployments, projects, teams, domains, and aliases into the PostHog Data warehouse.
+ caption="""Enter a Vercel access token to pull your Vercel deployments, projects, teams, domains, aliases, and billing usage into the PostHog Data warehouse.
Create an access token in your [Vercel account settings](https://vercel.com/account/tokens). A read-only token is sufficient.
-To sync resources owned by a team, also enter the team's ID (found under **Team Settings**). Leave it blank to sync resources owned by the token's user.""",
+To sync resources owned by a team, also enter the team's ID (found under **Team Settings**). Leave it blank to sync resources owned by the token's user. Syncing the **billing_charges** table needs a token whose role can read billing (Owner, Member, Developer, Security, Billing, or Enterprise Viewer).""",
iconPath="/static/services/vercel.png",
docsUrl="https://posthog.com/docs/cdp/sources/vercel",
fields=cast(
@@ -111,12 +108,13 @@ To sync resources owned by a team, also enter the team's ID (found under **Team
) -> list[SourceSchema]:
schemas = [
SourceSchema(
- name=endpoint,
- supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
- supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ name=name,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_append,
+ incremental_fields=endpoint_config.incremental_fields,
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
)
- for endpoint in ENDPOINTS
+ for name, endpoint_config in VERCEL_ENDPOINTS.items()
]
if names is not None:
names_set = set(names)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel.py
index 5388ea710a8d..f1c8943cc92a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel.py
@@ -1,3 +1,5 @@
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any
from unittest.mock import MagicMock, patch
@@ -8,10 +10,16 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.vercel import vercel
from products.warehouse_sources.backend.temporal.data_imports.sources.vercel.settings import VERCEL_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.vercel.vercel import (
+ BILLING_BACKFILL_DAYS,
PAGE_SIZE,
VercelResumeConfig,
+ _billing_window_start,
_build_params,
+ _floor_to_day,
+ _focus_charge_id,
+ _iso8601_utc,
_should_stop_desc,
+ get_billing_rows,
get_rows,
validate_credentials,
vercel_source,
@@ -227,3 +235,143 @@ class TestVercelSource:
assert response.name == endpoint
assert response.primary_keys == [expected_pk]
assert response.sort_mode == "desc"
+
+ def test_billing_source_response_is_incremental_merge(self) -> None:
+ # billing_charges merges on the synthesized `id`, yields ascending, and partitions by the
+ # charge period — unlike the descending, unpartitioned cursor endpoints above.
+ response = vercel_source(
+ access_token="t",
+ endpoint="billing_charges",
+ team_id=None,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == "billing_charges"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["charge_period_start"]
+ assert response.partition_mode == "datetime"
+
+
+class _FakeStreamResponse:
+ def __init__(self, lines: list[str]) -> None:
+ self._lines = lines
+ self.closed = False
+
+ def iter_lines(self, decode_unicode: bool = False) -> Iterator[str]:
+ yield from self._lines
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class TestIso8601Utc:
+ def test_formats_as_utc_z_with_millis(self) -> None:
+ formatted = _iso8601_utc(datetime(2025, 1, 2, 3, 4, 5, tzinfo=UTC))
+ assert formatted == "2025-01-02T03:04:05.000Z"
+
+
+class TestFocusChargeId:
+ def test_stable_when_only_amounts_change(self) -> None:
+ # A restated charge (same dimensions, different measures) must keep its id so merge updates
+ # it in place instead of inserting a duplicate.
+ base = {
+ "ChargePeriodStart": "2025-01-01T00:00:00.000Z",
+ "ServiceName": "Functions",
+ "RegionId": "iad1",
+ "Tags": {"ProjectId": "p_1"},
+ }
+ first = _focus_charge_id({**base, "BilledCost": 1.0, "EffectiveCost": 0.9, "ConsumedQuantity": 10})
+ restated = _focus_charge_id({**base, "BilledCost": 2.0, "EffectiveCost": 1.8, "ConsumedQuantity": 20})
+ assert first == restated
+
+ @parameterized.expand(
+ [
+ ("service", {"ServiceName": "Bandwidth"}),
+ ("region", {"RegionId": "sfo1"}),
+ ("period", {"ChargePeriodStart": "2025-01-02T00:00:00.000Z"}),
+ ("project_tag", {"Tags": {"ProjectId": "p_2"}}),
+ ]
+ )
+ def test_distinct_when_a_dimension_changes(self, _name: str, override: dict[str, Any]) -> None:
+ base = {
+ "ChargePeriodStart": "2025-01-01T00:00:00.000Z",
+ "ServiceName": "Functions",
+ "RegionId": "iad1",
+ "Tags": {"ProjectId": "p_1"},
+ "BilledCost": 1.0,
+ }
+ assert _focus_charge_id(base) != _focus_charge_id({**base, **override})
+
+ def test_missing_dimension_does_not_collide_with_empty_string(self) -> None:
+ # A key present as null must not hash the same as the same key set to "".
+ assert _focus_charge_id({"RegionId": None}) != _focus_charge_id({"RegionId": ""})
+
+
+class TestBillingWindowStart:
+ def test_full_refresh_goes_back_the_backfill_window(self) -> None:
+ now = datetime(2026, 6, 15, 9, 30, tzinfo=UTC)
+ start = _billing_window_start(should_use_incremental_field=False, db_incremental_field_last_value=None, now=now)
+ assert start == _floor_to_day(now) - timedelta(days=BILLING_BACKFILL_DAYS)
+
+ def test_incremental_reads_from_the_day_floored_watermark(self) -> None:
+ now = datetime(2026, 6, 15, 9, 30, tzinfo=UTC)
+ watermark = datetime(2026, 6, 10, 14, 45, tzinfo=UTC)
+ start = _billing_window_start(
+ should_use_incremental_field=True, db_incremental_field_last_value=watermark, now=now
+ )
+ assert start == datetime(2026, 6, 10, tzinfo=UTC)
+
+ def test_watermark_is_capped_at_the_one_year_window(self) -> None:
+ # A stale watermark older than the backfill window can't push `from` past Vercel's cap.
+ now = datetime(2026, 6, 15, 9, 30, tzinfo=UTC)
+ stale = datetime(2024, 1, 1, tzinfo=UTC)
+ start = _billing_window_start(should_use_incremental_field=True, db_incremental_field_last_value=stale, now=now)
+ assert start == _floor_to_day(now) - timedelta(days=BILLING_BACKFILL_DAYS)
+
+
+class TestGetBillingRows:
+ def _collect(
+ self, monkeypatch: Any, response: _FakeStreamResponse, team_id: str | None, **kwargs: Any
+ ) -> tuple[list[dict], str]:
+ captured: dict[str, str] = {}
+
+ def fake_open(session: Any, url: str, headers: dict[str, str], logger: Any) -> _FakeStreamResponse:
+ captured["url"] = url
+ return response
+
+ monkeypatch.setattr(vercel, "make_tracked_session", lambda *a, **k: MagicMock())
+ monkeypatch.setattr(vercel, "_open_billing_stream", fake_open)
+
+ rows: list[dict] = []
+ for table in get_billing_rows("token", "billing_charges", team_id, MagicMock(), **kwargs):
+ rows.extend(table.to_pylist())
+ return rows, captured["url"]
+
+ def test_parses_jsonl_stamps_id_and_sorts_ascending(self, monkeypatch: Any) -> None:
+ response = _FakeStreamResponse(
+ [
+ '{"ChargePeriodStart": "2025-01-03T00:00:00.000Z", "ServiceName": "Functions"}',
+ "",
+ '{"ChargePeriodStart": "2025-01-01T00:00:00.000Z", "ServiceName": "Bandwidth"}',
+ ]
+ )
+ rows, url = self._collect(monkeypatch, response, team_id="team_9")
+
+ # Blank line skipped, and rows arrive oldest-first regardless of stream order.
+ assert [r["ChargePeriodStart"] for r in rows] == [
+ "2025-01-01T00:00:00.000Z",
+ "2025-01-03T00:00:00.000Z",
+ ]
+ assert all(r["id"] for r in rows)
+ assert "teamId=team_9" in url
+ assert "from=" in url and "to=" in url
+ assert response.closed is True
+
+ def test_omits_team_id_when_not_set(self, monkeypatch: Any) -> None:
+ _, url = self._collect(monkeypatch, _FakeStreamResponse([]), team_id=None)
+ assert "teamId" not in url
+
+ def test_empty_stream_yields_no_rows(self, monkeypatch: Any) -> None:
+ rows, _ = self._collect(monkeypatch, _FakeStreamResponse([]), team_id="team_1")
+ assert rows == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel_source.py
index f7b263b01fec..9a1f65fd76d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/tests/test_vercel_source.py
@@ -63,9 +63,9 @@ class TestVercelSource:
assert fields["team_id"].required is False
assert fields["team_id"].secret is False
- def test_get_schemas_incremental_only_for_deployments(self) -> None:
+ def test_get_schemas_sync_capabilities_per_endpoint(self) -> None:
schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}
- assert set(schemas) == {"deployments", "projects", "teams", "domains", "aliases"}
+ assert set(schemas) == {"deployments", "projects", "teams", "domains", "aliases", "billing_charges"}
deployments = schemas["deployments"]
assert deployments.supports_incremental is True
@@ -73,8 +73,18 @@ class TestVercelSource:
assert [f["field"] for f in deployments.incremental_fields] == ["created"]
assert deployments.incremental_fields[0]["field_type"] == IncrementalFieldType.Integer
+ # Billing supports incremental merge but not append (append would duplicate restated charges),
+ # cursors on the charge period, and carries a lookback so restatements get re-read and merged.
+ billing = schemas["billing_charges"]
+ assert billing.supports_incremental is True
+ assert billing.supports_append is False
+ assert [f["field"] for f in billing.incremental_fields] == ["charge_period_start"]
+ assert billing.incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime
+ assert billing.default_incremental_lookback_seconds == 60 * 60 * 24 * 35
+
for full_refresh in ("projects", "teams", "domains", "aliases"):
assert schemas[full_refresh].supports_incremental is False
+ assert schemas[full_refresh].supports_append is False
assert schemas[full_refresh].incremental_fields == []
def test_get_schemas_filters_by_names(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/vercel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/vercel.py
index bff3afea44f8..38ca508e8462 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/vercel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vercel/vercel.py
@@ -1,5 +1,14 @@
+import json
+import hashlib
import dataclasses
from collections.abc import Iterator
+from datetime import (
+ UTC,
+ date,
+ datetime,
+ time as datetime_time,
+ timedelta,
+)
from typing import Any, Optional
from urllib.parse import urlencode
@@ -21,6 +30,15 @@ VERCEL_BASE_URL = "https://api.vercel.com"
# Vercel caps the page size at 100 (default 20); request the max to minimize round-trips.
PAGE_SIZE = 100
+# billing_charges backfill: the endpoint caps the `from`/`to` window at one year. A day-floored start
+# 364 days back keeps the window strictly under that cap once `to` runs to the current instant.
+BILLING_BACKFILL_DAYS = 364
+
+# FOCUS measure fields — the amounts that change when a charge is restated. Everything else on the
+# record is an identity/dimension field, so the synthetic id hashes all-but-these and a restated
+# charge keeps its id (merge updates it in place instead of inserting a duplicate).
+BILLING_MEASURE_FIELDS = frozenset({"BilledCost", "EffectiveCost", "ConsumedQuantity", "PricingQuantity"})
+
# Backstop against an endpoint that silently ignores the `until` cursor (which would otherwise
# re-serve page one forever). Resumable state means an interrupted sync picks back up, so this is
# a runaway guard, not a coverage limit — at 100 rows/page it allows ~1M rows before warning.
@@ -192,6 +210,139 @@ def get_rows(
yield batcher.get_table()
+def _iso8601_utc(moment: datetime) -> str:
+ """Vercel's billing window params want ISO 8601 UTC with a trailing Z, e.g.
+ 2025-01-01T00:00:00.000Z."""
+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+
+
+def _coerce_datetime(value: Any) -> datetime:
+ """Normalize a watermark (datetime, date, or ISO string) to a UTC-aware datetime."""
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime_time.min, tzinfo=UTC)
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)
+
+
+def _floor_to_day(value: datetime) -> datetime:
+ return value.replace(hour=0, minute=0, second=0, microsecond=0)
+
+
+def _focus_charge_id(record: dict[str, Any]) -> str:
+ """Deterministic surrogate id for a FOCUS charge row.
+
+ FOCUS records carry no id. The 1-day grain is defined by the charge's identity/dimension fields
+ (period, service, region, pricing dimensions, and the project carried in Tags), so hashing every
+ field except the amounts yields a stable key: a charge whose cost is restated between runs keeps
+ its id and merge updates it in place instead of inserting a duplicate."""
+ dimensions = {k: v for k, v in record.items() if k not in BILLING_MEASURE_FIELDS}
+ # sort_keys makes the serialization order-independent; default=str tolerates any nested value.
+ serialized = json.dumps(dimensions, sort_keys=True, default=str)
+ return hashlib.sha256(serialized.encode()).hexdigest()
+
+
+def _billing_window_start(
+ should_use_incremental_field: bool, db_incremental_field_last_value: Any, now: datetime
+) -> datetime:
+ """Start of the `from`/`to` window to request.
+
+ Incremental: the pipeline has already shifted the stored watermark back by the schema's lookback,
+ so we day-floor it (keeping `from` aligned to Vercel's day buckets) and re-read from there. First
+ sync / full refresh: go back the full backfill window. Either way, never start earlier than the
+ endpoint's one-year cap."""
+ floor_today = _floor_to_day(now)
+ cap = floor_today - timedelta(days=BILLING_BACKFILL_DAYS)
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ start = min(_floor_to_day(_coerce_datetime(db_incremental_field_last_value)), floor_today)
+ else:
+ start = cap
+
+ return max(start, cap)
+
+
+@retry(
+ retry=retry_if_exception_type((VercelRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _open_billing_stream(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> requests.Response:
+ response = session.get(url, headers=headers, timeout=120, stream=True)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ raise VercelRetryableError(f"Vercel API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ body = response.text
+ response.close()
+ logger.error(f"Vercel API error: status={response.status_code}, body={body}, url={url}")
+ response.raise_for_status()
+
+ return response
+
+
+def get_billing_rows(
+ access_token: str,
+ endpoint: str,
+ team_id: str | None,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ """Stream FOCUS v1.3 billing charges as newline-delimited JSON over a `from`/`to` window, stamp a
+ synthetic id on each record, and yield them sorted by charge period ascending.
+
+ Incremental runs re-read a trailing overlap window (the pipeline shifts the watermark back by the
+ schema lookback) so restated charges are re-pulled; merge dedupes them on the synthetic id. The
+ ascending sort upholds the `sort_mode="asc"` contract so the pipeline checkpoints the watermark
+ correctly."""
+ config = VERCEL_ENDPOINTS[endpoint]
+ now = datetime.now(UTC)
+ window_start = _billing_window_start(should_use_incremental_field, db_incremental_field_last_value, now)
+
+ params: dict[str, Any] = {"from": _iso8601_utc(window_start), "to": _iso8601_utc(now)}
+ if config.team_scoped and team_id:
+ params["teamId"] = team_id
+
+ url = _build_url(config.path, params)
+ headers = _get_headers(access_token)
+ session = make_tracked_session()
+
+ try:
+ # Response order is undocumented, and the pipeline's ascending watermark contract requires rows
+ # to arrive oldest-first. Billing volume at 1-day granularity is small, so buffer the window and
+ # sort it client-side rather than trusting the stream order.
+ records: list[dict[str, Any]] = []
+ response = _open_billing_stream(session, url, headers, logger)
+ try:
+ for line in response.iter_lines(decode_unicode=True):
+ if not line:
+ continue
+ record = json.loads(line)
+ record["id"] = _focus_charge_id(record)
+ records.append(record)
+ finally:
+ response.close()
+
+ records.sort(key=lambda r: r.get("ChargePeriodStart") or "")
+
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ for record in records:
+ batcher.batch(record)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ finally:
+ session.close()
+
+
def vercel_source(
access_token: str,
endpoint: str,
@@ -204,6 +355,28 @@ def vercel_source(
) -> SourceResponse:
endpoint_config = VERCEL_ENDPOINTS[endpoint]
+ if endpoint_config.is_focus_billing:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_billing_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ team_id=team_id,
+ logger=logger,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[endpoint_config.primary_key],
+ # Records are sorted by charge period ascending before yielding; the pipeline checkpoints
+ # the watermark per batch.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
return SourceResponse(
name=endpoint,
items=lambda: get_rows(