: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add heroku attachment, coupling and usage tables (#110732)
Tom Owers169c2f823102
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.mdindex ceca13df4e5a..41f5f98ec669 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@@ -3997,11 +3997,11 @@ Today (11): `addons`, `apps`, `builds`, `collaborators`, `domains`, `dynos`, `foDiffed against: <https://api.heroku.com/schema>- [ ] `team-member` — team membership and role — who has access to which team, no membership table today (high)-- [ ] `add-on-attachment` — lookup resolving which app each add-on is attached to; we sync add-ons but not the attachment join (high)-- [ ] `pipeline-coupling` — lookup joining apps to the pipelines we already sync, including the stage (review/staging/production) (high)+- [x] `add-on-attachment` — lookup resolving which app each add-on is attached to; we sync add-ons but not the attachment join (high). Added as `addon_attachments`.+- [x] `pipeline-coupling` — lookup joining apps to the pipelines we already sync, including the stage (review/staging/production) (high). Added as `pipeline_couplings`.- [ ] `add-on-service` — lookup table naming the add-on service behind every add-on row we sync (high)-- [ ] `plan` — lookup giving the price and tier of each add-on plan id carried on add-ons — required for any cost analysis (high)-- [ ] `team-monthly-usage` — Heroku's headline spend/usage metric per team per month (dyno hours, add-on cost, data usage) (high)+- [ ] `plan` — lookup giving the price and tier of each add-on plan id carried on add-ons — required for any cost analysis (high). Skipped: there is no plan list, only `/addon-services/{id}/plans` across the whole public marketplace, and `addons` rows already carry `billed_price` and the plan name.+- [x] `team-monthly-usage` — Heroku's headline spend/usage metric per team per month (dyno hours, add-on cost, data usage) (high). Added as `team_monthly_usage` (fan-out over Enterprise `teams`, rolling 12 months, off by default).- [ ] `team-daily-usage` — daily granularity of the same usage metric for trend analysis (medium)- [ ] `team-app` — apps owned by each team, the org-level view the /apps personal list misses (medium)- [ ] `team-invoice` — team-level invoices; we only sync personal /account/invoices today (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.pyindex 9b34d35be683..a09011a573e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py@@ -53,6 +53,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"web_url": "URL for logging into web interface of add-on (e.g. a dashboard).",},},+ "addon_attachments": {+ "description": "An add-on attachment represents a connection between an app and an add-on that it has been given access to.",+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#add-on-attachment",+ "columns": {+ "addon": "Identity of add-on.",+ "app": "Application that is attached to add-on.",+ "created_at": "When the add-on attachment was created.",+ "id": "Unique identifier of this add-on attachment.",+ "log_input_url": "Always null: the add-on log input URL embeds a write token, so PostHog does not sync it.",+ "name": "Unique name for this add-on attachment to this app.",+ "namespace": "Attachment namespace.",+ "updated_at": "When the add-on attachment was updated.",+ "web_url": "URL for logging into web interface of add-on in attached app context.",+ },+ },"builds": {"description": "A build represents the process of transforming a code tarball into build artifacts.","docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#build",@@ -162,6 +177,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "When the pipeline was updated.",},},+ "pipeline_couplings": {+ "description": "Information about an app's coupling to a pipeline.",+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#pipeline-coupling",+ "columns": {+ "app": "App involved in the pipeline coupling.",+ "created_at": "When the pipeline coupling was created.",+ "id": "Unique identifier of pipeline coupling.",+ "pipeline": "Pipeline involved in the coupling.",+ "stage": "Target pipeline stage (test, review, development, staging or production).",+ "updated_at": "When the pipeline coupling was updated.",+ },+ },"releases": {"description": "A release represents a combination of code, config vars and add-ons for an app on Heroku.","docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#release",@@ -200,4 +227,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "When the team was updated.",},},+ "team_monthly_usage": {+ "description": "Usage for an enterprise team at a monthly resolution.",+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#team-monthly-usage",+ "columns": {+ "addons": "Total add-on credits used.",+ "apps": "App usage in the team.",+ "connect": "Max Connect rows synced.",+ "data": "Total add-on credits used for first party add-ons.",+ "dynos": "Dynos used.",+ "id": "Team identifier.",+ "month": "Year and month of the usage (YYYY-MM).",+ "name": "Name of the team.",+ "partner": "Total add-on credits used for third party add-ons.",+ "space": "Space credits used.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.pyindex 38c6d5cf572e..c95173f33b89 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py@@ -1,9 +1,11 @@-import dataclasses+import datetime as dtfrom collections.abc import Callablefrom typing import Any, Optionalfrom requests import Request, Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (ClientConfig,@@ -13,7 +15,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,rest_api_resources,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -22,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.setHEROKU_BASE_URL,HEROKU_ENDPOINTS,MAX_PAGES_PER_LIST,+ TEAM_USAGE_LOOKBACK_MONTHS,HerokuEndpointConfig,)@@ -30,7 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.setHEROKU_API_ACCEPT = "application/vnd.heroku+json; version=3"+@frozenclass HerokuResumeConfig:# Verbatim `Next-Range` header value to resume a top-level list from. None means "start at# the first page".@@ -130,10 +136,18 @@ def _client_config(api_key: str) -> ClientConfig:}-def _paginator(config: HerokuEndpointConfig) -> RangeHeaderPaginator:+def _paginator(config: HerokuEndpointConfig) -> BasePaginator:+ if not config.paginated:+ return SinglePagePaginator()return RangeHeaderPaginator(config.range_attribute, DEFAULT_PAGE_SIZE, MAX_PAGES_PER_LIST)+def _month_window(today: dt.date) -> dict[str, str]:+ start_index = today.year * 12 + today.month - TEAM_USAGE_LOOKBACK_MONTHS+ start_year, start_month = divmod(start_index, 12)+ return {"start": f"{start_year:04d}-{start_month + 1:02d}", "end": f"{today.year:04d}-{today.month:02d}"}++def _flat_source(api_key: str,config: HerokuEndpointConfig,@@ -186,15 +200,20 @@ def _fanout_source(job_id: str,resumable_source_manager: ResumableSourceManager[HerokuResumeConfig],) -> Any:- apps_config = HEROKU_ENDPOINTS["apps"]+ assert config.fan_out_parent is not None+ parent_config = HEROKU_ENDPOINTS[config.fan_out_parent]++ params: dict[str, Any] = {"parent_id": {"type": "resolve", "resource": parent_config.name, "field": "id"}}+ if config.month_window:+ params.update(_month_window(dt.datetime.now(dt.UTC).date()))child_endpoint: Endpoint = {"path": config.path,- "params": {"app_id": {"type": "resolve", "resource": "apps", "field": "id"}},+ "params": params,"paginator": _paginator(config),"data_selector_required": True,- # An app deleted between enumeration and this fetch 404s; treat it as an empty page and stop- # this app rather than failing the whole sync — the data is genuinely gone. A 401/403 still+ # A parent deleted between enumeration and this fetch 404s; treat it as an empty page and stop+ # this parent rather than failing the whole sync — the data is genuinely gone. A 401/403 still# falls through to raise_for_status."response_actions": [{"status_code": 404, "action": "ignore"}],}@@ -210,12 +229,12 @@ def _fanout_source("client": _client_config(api_key),"resources": [{- "name": "apps",- # Rows already embed the parent as a nested `app` object, so nothing is injected from- # the parent; Heroku ids are globally unique UUIDs, so `id` stays a table-wide key.+ "name": parent_config.name,+ # Rows already embed the parent (a nested `app` object, or the team's own `id` on usage),+ # so nothing is injected from the parent; Heroku ids are globally unique UUIDs."endpoint": {- "path": apps_config.path,- "paginator": _paginator(apps_config),+ "path": parent_config.path,+ "paginator": _paginator(parent_config),"data_selector_required": True,},},@@ -243,7 +262,10 @@ def _fanout_source(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)- return next(resource for resource in resources if getattr(resource, "name", None) == config.name)+ by_name = {getattr(resource, "name", None): resource for resource in resources}+ if config.parent_filter is not None:+ by_name[parent_config.name].add_filter(config.parent_filter)+ return by_name[config.name]def heroku_source(@@ -255,7 +277,7 @@ def heroku_source() -> SourceResponse:config = HEROKU_ENDPOINTS[endpoint]- if config.fan_out_over_apps:+ if config.fan_out_parent:resource = _fanout_source(api_key, config, team_id, job_id, resumable_source_manager)else:resource = _flat_source(api_key, config, team_id, job_id, resumable_source_manager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.pyindex f60cd8611a6e..13d95e969b5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py@@ -1,4 +1,8 @@-from dataclasses import dataclass, field+from collections.abc import Callable+from dataclasses import field+from typing import Any++from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.types import IncrementalField@@ -8,16 +12,23 @@ HEROKU_BASE_URL = "https://api.heroku.com"# Default page size is 200; the hard max is 1000.DEFAULT_PAGE_SIZE = 1000-# Hard cap on pages walked per list (per app for fan-out endpoints) so a runaway+# Hard cap on pages walked per list (per parent for fan-out endpoints) so a runaway# cursor can't scan unbounded history. 1000-row pages make this 100k rows per list.MAX_PAGES_PER_LIST = 100+# Months of team usage requested per sync, current month included. Usage syncs as a full+# refresh, so the table holds this rolling window.+TEAM_USAGE_LOOKBACK_MONTHS = 12+-@dataclass+@frozenclass HerokuEndpointConfig:name: str- path: str # contains an {app_id} placeholder for fan-out endpoints- fan_out_over_apps: bool = False+ path: str # contains a {parent_id} placeholder for fan-out endpoints+ # Endpoint whose rows' `id` fills `{parent_id}`; None for top-level lists.+ fan_out_parent: str | None = None+ # Parent rows to skip before fanning out, for children that only exist on some parents.+ parent_filter: Callable[[dict[str, Any]], bool] | None = Noneprimary_keys: list[str] = field(default_factory=lambda: ["id"])# Stable creation timestamp used for datetime partitioning. All Heroku resources carry# `created_at`; never partition on `updated_at` (partitions would rewrite every sync).@@ -25,6 +36,11 @@ class HerokuEndpointConfig:# Attribute used in the `Range` header for stable pagination. `id` is Heroku's default# sort attribute and is accepted on every list endpoint.range_attribute: str = "id"+ # False for endpoints that return one unpaginated array rather than a `Range`-cursored list.+ paginated: bool = True+ # Send `start`/`end` (YYYY-MM) covering the last TEAM_USAGE_LOOKBACK_MONTHS; usage endpoints+ # require `start`.+ month_window: bool = Falseshould_sync_default: bool = True# Dotted paths of capability URLs nulled before rows are yielded. These URLs grant# access (source downloads, output streams, dyno attach) without Heroku auth, so they@@ -45,35 +61,40 @@ HEROKU_ENDPOINTS: dict[str, HerokuEndpointConfig] = {name="addons",path="/addons",),+ "addon_attachments": HerokuEndpointConfig(+ name="addon_attachments",+ path="/addon-attachments",+ sensitive_fields=["log_input_url"],+ ),"builds": HerokuEndpointConfig(name="builds",- path="/apps/{app_id}/builds",- fan_out_over_apps=True,+ path="/apps/{parent_id}/builds",+ fan_out_parent="apps",sensitive_fields=["output_stream_url", "source_blob.url"],),"collaborators": HerokuEndpointConfig(name="collaborators",- path="/apps/{app_id}/collaborators",- fan_out_over_apps=True,+ path="/apps/{parent_id}/collaborators",+ fan_out_parent="apps",),"domains": HerokuEndpointConfig(name="domains",- path="/apps/{app_id}/domains",- fan_out_over_apps=True,+ path="/apps/{parent_id}/domains",+ fan_out_parent="apps",),# Dynos are a point-in-time snapshot of running processes; the list is small and churns# constantly, so partitioning adds nothing."dynos": HerokuEndpointConfig(name="dynos",- path="/apps/{app_id}/dynos",- fan_out_over_apps=True,+ path="/apps/{parent_id}/dynos",+ fan_out_parent="apps",partition_key=None,sensitive_fields=["attach_url"],),"formation": HerokuEndpointConfig(name="formation",- path="/apps/{app_id}/formation",- fan_out_over_apps=True,+ path="/apps/{parent_id}/formation",+ fan_out_parent="apps",partition_key=None,),"invoices": HerokuEndpointConfig(@@ -84,16 +105,34 @@ HEROKU_ENDPOINTS: dict[str, HerokuEndpointConfig] = {name="pipelines",path="/pipelines",),+ "pipeline_couplings": HerokuEndpointConfig(+ name="pipeline_couplings",+ path="/pipeline-couplings",+ ),"releases": HerokuEndpointConfig(name="releases",- path="/apps/{app_id}/releases",- fan_out_over_apps=True,+ path="/apps/{parent_id}/releases",+ fan_out_parent="apps",sensitive_fields=["output_stream_url"],),"teams": HerokuEndpointConfig(name="teams",path="/teams",),+ # Usage only exists for teams that belong to a Heroku Enterprise account; other teams are+ # skipped. One row per team per month, and `id` is the team id, so the key is composite.+ "team_monthly_usage": HerokuEndpointConfig(+ name="team_monthly_usage",+ path="/teams/{parent_id}/usage/monthly",+ fan_out_parent="teams",+ parent_filter=lambda team: bool(team.get("enterprise_account")),+ primary_keys=["id", "month"],+ partition_key=None,+ paginated=False,+ month_window=True,+ # Enterprise-only, so most accounts would sync an empty table; opt in explicitly.+ should_sync_default=False,+ ),}ENDPOINTS = tuple(HEROKU_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.pyindex 03c4f9ad7568..9e331d588d05 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py@@ -102,6 +102,8 @@ You can find your API key in your [Heroku account settings](https://dashboard.hereturn "Invoices for your personal Heroku account; team invoices are not included"if endpoint == "teams":return "Only returns data for accounts that belong to Heroku Teams or Enterprise"+ if endpoint == "team_monthly_usage":+ return "Monthly usage for Heroku Enterprise teams, covering the last 12 months"return Nonedef _build_schema(endpoint: str) -> SourceSchema:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.pyindex f34f505a958c..54de9e414ecf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py@@ -1,4 +1,5 @@import json+import datetime as dtfrom typing import Anyimport pytest@@ -11,6 +12,7 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.heroku.heroku import (HEROKU_API_ACCEPT,HerokuResumeConfig,+ _month_window,heroku_source,validate_credentials,)@@ -261,6 +263,46 @@ class TestFanOut:assert headers[1]["Range"] == INITIAL_RANGE+class TestTeamMonthlyUsage:+ @parameterized.expand(+ [+ ("mid_year", dt.date(2026, 10, 2), {"start": "2025-11", "end": "2026-10"}),+ ("january", dt.date(2026, 1, 31), {"start": "2025-02", "end": "2026-01"}),+ ("december", dt.date(2026, 12, 1), {"start": "2026-01", "end": "2026-12"}),+ ]+ )+ def test_month_window_spans_twelve_months_including_current(+ self, _name: str, today: dt.date, expected: dict[str, str]+ ) -> None:+ assert _month_window(today) == expected++ @mock.patch(SESSION_PATCH)+ def test_fans_out_over_enterprise_teams_only_with_month_window(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ headers, urls = _wire(+ session,+ [+ _response(+ 200,+ [+ {"id": "team-ent", "enterprise_account": {"id": "ea-1", "name": "acme"}},+ {"id": "team-plain", "enterprise_account": None},+ ],+ ),+ _response(200, [{"id": "team-ent", "month": "2026-09"}, {"id": "team-ent", "month": "2026-10"}]),+ ],+ )++ rows = _rows(_source("team_monthly_usage", _make_manager()))++ assert rows == [{"id": "team-ent", "month": "2026-09"}, {"id": "team-ent", "month": "2026-10"}]+ assert urls == ["https://api.heroku.com/teams", "https://api.heroku.com/teams/team-ent/usage/monthly"]+ usage_request = session.prepare_request.call_args_list[1].args[0]+ assert set(usage_request.params) == {"start", "end"}+ # Usage is a single array, not a Range-cursored list.+ assert "Range" not in headers[1]++class TestSensitiveFieldRedaction:@parameterized.expand([@@ -286,6 +328,12 @@ class TestSensitiveFieldRedaction:{"id": "d-1", "attach_url": "rendezvous://rendezvous.runtime.heroku.com:5000/secret", "state": "up"},{"id": "d-1", "attach_url": None, "state": "up"},),+ (+ "addon_attachment_log_input_url_nulled",+ "addon_attachments",+ {"id": "att-1", "log_input_url": "https://token:[email protected]/logs", "name": "DATABASE"},+ {"id": "att-1", "log_input_url": None, "name": "DATABASE"},+ ),("row_without_sensitive_fields_untouched","builds",@@ -299,7 +347,8 @@ class TestSensitiveFieldRedaction:self, _name: str, endpoint: str, row: dict[str, Any], expected: dict[str, Any], MockSession: mock.MagicMock) -> None:session = MockSession.return_value- _wire(session, [_response(200, [{"id": "app-1"}]), _response(200, [row])])+ parent_pages = [_response(200, [{"id": "app-1"}])] if HEROKU_ENDPOINTS[endpoint].fan_out_parent else []+ _wire(session, [*parent_pages, _response(200, [row])])rows = _rows(_source(endpoint, _make_manager()))