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.

fix(warehouse-sources): make App Store Connect restatements resolvable without a manual view (#82974)

jake sciottobeffa8305951
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py
new file mode 100644
index 000000000000..68396c2f6e25
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py
@@ -0,0 +1,288 @@
+"""Query guidance for Apple's restated analytics report streams.
+
+Apple restates each analytics report date for about six days: every daily instance
+republishes recent report dates in full, and the sync keeps each instance's rows under
+their own ``processing_date`` (the streams key on app, processing date and file line).
+One report date therefore accumulates several vintages, and a naive
+``SUM ... GROUP BY date`` overcounts severalfold without any error.
+
+The source cannot resolve this in the data itself. The warehouse-source framework has no
+hook for a source to ship a companion view, and the pipeline's merge only touches the
+primary keys present in an arriving batch, so rows written earlier (superseded vintages,
+or the one-time snapshot backfill) can never be re-flagged: an ``is_latest_restatement``
+column would silently go stale on the next restatement. What the source can do in-module
+is document the resolution exactly, per stream. Everything here derives from the endpoint
+catalog in ``settings.py`` and the column catalog in ``canonical_descriptions.py``, so
+analytics streams added to the catalog later are covered without code changes.
+"""
+
+from collections.abc import Mapping
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (
+ APP_STORE_CONNECT_ENDPOINTS,
+ AppStoreConnectEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+ CanonicalEndpoint,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_ANALYTICS_KIND = "analytics_report"
+
+# The measure columns across Apple's analytics reports: the columns consumers sum, which take
+# the argMax in the deduplicating query; every other documented column is a grouping dimension.
+# This is Apple's column vocabulary, not a list of stream names, so a new stream built from the
+# same columns needs no code change here. A stream with no recognized measure falls back to the
+# latest-vintage join recipe: guessing the split would group by a measure and silently keep one
+# row per vintage.
+_MEASURE_COLUMNS: frozenset[str] = frozenset(
+ {
+ "sessions",
+ "total_session_duration",
+ "unique_devices",
+ "counts",
+ "unique_counts",
+ "crashes",
+ "pre_orders_placed",
+ "pre_orders_canceled",
+ }
+)
+
+# Apple includes the report date in every analytics report as `date`; restatements always
+# supersede whole report dates within an app.
+_REPORT_DATE_COLUMN = "date"
+
+# Mirrors `pipelines.helpers.build_table_name`, whose physical name is the source's optional
+# user-set table prefix followed by this one. Naming the table wrongly fails silently rather than
+# loudly: a second App Store Connect source is forced to take a prefix, so the unprefixed name
+# resolves to the first source's table instead of erroring.
+_TABLE_NAME_PREFIX = f"{ExternalDataSourceType.APPSTORECONNECT.value}_".lower()
+
+# Shown only where the guidance is built without a source in hand (the public docs endpoint and the
+# source caption), so the prefix is unknowable rather than known to be empty.
+_TABLE_PREFIX_NOTE = (
+ "This query names the table as connected without a table name prefix; if you set one, add it "
+ "wherever the table name appears."
+)
+
+_MEASURE_GUIDANCE = (
+ "Kept for every restatement of a report date; aggregate only the latest restatement (see the table description)."
+)
+
+
+def analytics_stream_names(endpoints: Mapping[str, AppStoreConnectEndpointConfig]) -> tuple[str, ...]:
+ """Names of the streams that carry restated analytics report data, from the catalog."""
+ return tuple(name for name, config in endpoints.items() if config.kind == _ANALYTICS_KIND)
+
+
+@frozen
+class RestatementRecipe:
+ """The query that returns one row per report date and dimension tuple for one stream."""
+
+ stream: str
+ table_name: str
+ # The column whose highest value per app and report date marks the current vintage.
+ vintage_column: str
+ # Grouping columns of the argMax form; empty for the latest-vintage join form.
+ dimensions: tuple[str, ...]
+ # Measure columns resolved with argMax; empty for the latest-vintage join form.
+ measures: tuple[str, ...]
+ sql: str
+
+ @property
+ def sql_single_line(self) -> str:
+ return " ".join(self.sql.split())
+
+
+def _vintage_column(config: AppStoreConnectEndpointConfig) -> str | None:
+ # The incremental field that is also part of the primary key: each restatement arrives as
+ # new rows under a new value of it.
+ for field in config.incremental_fields:
+ name = field.get("field")
+ if name and name in config.primary_keys:
+ return name
+ return None
+
+
+def _identity_keys(config: AppStoreConnectEndpointConfig, vintage_column: str) -> list[str]:
+ # Primary keys minus the vintage and the parser's synthetic file-position keys (underscore
+ # prefixed, like `_line`): what identifies the entity across vintages, e.g. the app.
+ return [key for key in config.primary_keys if key != vintage_column and not key.startswith("_")]
+
+
+def _latest_vintage_join(table_name: str, identity_keys: list[str], vintage_column: str) -> str:
+ # Restricts the table to the newest restatement of each report date. A restatement
+ # republishes its report date in full, so a dimension tuple the newest one omits is gone
+ # rather than unchanged: reading a value for it from an older vintage would resurrect it.
+ keys = [*identity_keys, _REPORT_DATE_COLUMN]
+ key_list = ", ".join(keys)
+ conditions = " AND ".join(f"raw.{key} = latest.{key}" for key in [*keys, vintage_column])
+ return (
+ f"FROM {table_name} AS raw\n"
+ "INNER JOIN (\n"
+ f" SELECT {key_list}, max({vintage_column}) AS {vintage_column}\n"
+ f" FROM {table_name}\n"
+ f" GROUP BY {key_list}\n"
+ ") AS latest\n"
+ f" ON {conditions}"
+ )
+
+
+def _latest_vintage_sql(table_name: str, identity_keys: list[str], vintage_column: str) -> str:
+ return f"SELECT raw.*\n{_latest_vintage_join(table_name, identity_keys, vintage_column)}"
+
+
+def restatement_recipe(
+ config: AppStoreConnectEndpointConfig, columns: Mapping[str, str], table_prefix: str = ""
+) -> RestatementRecipe | None:
+ """Build the stream's deduplicating query from its catalog entry and documented columns.
+
+ Prefers the argMax form (one row per report date and dimension tuple, each measure taken
+ from the latest vintage). Falls back to the latest-vintage join (the newest restatement of
+ each report date, whole) when the documented columns can't be split into dimensions and
+ measures. ``None`` for streams whose catalog entry carries no vintage key to dedup on.
+
+ ``table_prefix`` is the connected source's user-set table prefix, so the query names the
+ table the reader actually has.
+ """
+ if config.kind != _ANALYTICS_KIND:
+ return None
+ vintage_column = _vintage_column(config)
+ if vintage_column is None:
+ return None
+
+ table_name = f"{table_prefix}{_TABLE_NAME_PREFIX}{config.name}"
+ excluded = {vintage_column, *(key for key in config.primary_keys if key.startswith("_"))}
+ names = [name for name in columns if name not in excluded]
+ measures = tuple(name for name in names if name in _MEASURE_COLUMNS)
+ dimensions = tuple(name for name in names if name not in _MEASURE_COLUMNS)
+ if _REPORT_DATE_COLUMN in dimensions:
+ dimensions = (_REPORT_DATE_COLUMN, *(name for name in dimensions if name != _REPORT_DATE_COLUMN))
+
+ if not measures or _REPORT_DATE_COLUMN not in dimensions:
+ return RestatementRecipe(
+ stream=config.name,
+ table_name=table_name,
+ vintage_column=vintage_column,
+ dimensions=(),
+ measures=(),
+ sql=_latest_vintage_sql(table_name, _identity_keys(config, vintage_column), vintage_column),
+ )
+
+ select_lines = [
+ *(f"raw.{dimension}" for dimension in dimensions),
+ *(f"argMax(raw.{measure}, raw.{vintage_column}) AS {measure}" for measure in measures),
+ ]
+ select_body = ",\n ".join(select_lines)
+ group_body = ",\n ".join(f"raw.{dimension}" for dimension in dimensions)
+ join_body = _latest_vintage_join(table_name, _identity_keys(config, vintage_column), vintage_column)
+ sql = f"SELECT\n {select_body}\n{join_body}\nGROUP BY\n {group_body}"
+ return RestatementRecipe(
+ stream=config.name,
+ table_name=table_name,
+ vintage_column=vintage_column,
+ dimensions=dimensions,
+ measures=measures,
+ sql=sql,
+ )
+
+
+def _table_guidance(recipe: RestatementRecipe, prefix_known: bool) -> str:
+ warning = (
+ f"Apple restates each report date for about six days, and every restatement is kept as new "
+ f"rows with a later {recipe.vintage_column}, so summing raw rows overcounts."
+ )
+ if recipe.measures:
+ resolution = "Get one row per report date and dimension combination with"
+ else:
+ resolution = "Keep only the latest restatement of each report date with"
+ guidance = f"{warning} {resolution}: {recipe.sql_single_line}"
+ return guidance if prefix_known else f"{guidance} {_TABLE_PREFIX_NOTE}"
+
+
+def _vintage_column_guidance(vintage_column: str) -> str:
+ return (
+ f"The rows with the highest {vintage_column} for an app and report date are the current "
+ "restatement; see the table description for the deduplicating query."
+ )
+
+
+def with_restatement_guidance(
+ descriptions: Mapping[str, CanonicalEndpoint],
+ endpoints: Mapping[str, AppStoreConnectEndpointConfig] = APP_STORE_CONNECT_ENDPOINTS,
+ table_prefix: str | None = None,
+) -> CanonicalDescriptions:
+ """A copy of ``descriptions`` where every analytics stream in the catalog documents its dedup.
+
+ Applied at read time (`AppStoreConnectSource.get_canonical_descriptions`) rather than baked
+ into the ``CANONICAL_DESCRIPTIONS`` literal, so entries other code derives from stay pristine
+ and streams are covered regardless of where in the module their entry is added. Idempotent:
+ guidance already present is never appended twice.
+
+ ``table_prefix`` is the connected source's user-set prefix, so the queries name the reader's
+ own table. ``None`` means no source was in hand (the public docs endpoint, which describes the
+ source generically); the queries then name the unprefixed table and say so.
+ """
+ result: CanonicalDescriptions = dict(descriptions)
+ for name in analytics_stream_names(endpoints):
+ existing = result.get(name)
+ entry: CanonicalEndpoint = existing.copy() if existing is not None else {}
+ columns = dict(entry.get("columns") or {})
+ recipe = restatement_recipe(endpoints[name], columns, table_prefix or "")
+ if recipe is None:
+ continue
+
+ guidance = _table_guidance(recipe, prefix_known=table_prefix is not None)
+ description = (entry.get("description") or "").strip()
+ if guidance not in description:
+ entry["description"] = f"{description} {guidance}".strip()
+
+ vintage_note = _vintage_column_guidance(recipe.vintage_column)
+ if recipe.vintage_column in columns and vintage_note not in columns[recipe.vintage_column]:
+ columns[recipe.vintage_column] = f"{columns[recipe.vintage_column].rstrip()} {vintage_note}"
+ for measure in recipe.measures:
+ if _MEASURE_GUIDANCE not in columns[measure]:
+ columns[measure] = f"{columns[measure].rstrip()} {_MEASURE_GUIDANCE}"
+ if columns:
+ entry["columns"] = columns
+ result[name] = entry
+ return result
+
+
+def restatement_caption(
+ endpoints: Mapping[str, AppStoreConnectEndpointConfig] = APP_STORE_CONNECT_ENDPOINTS,
+ descriptions: Mapping[str, CanonicalEndpoint] = CANONICAL_DESCRIPTIONS,
+) -> str:
+ """Markdown section for the source caption documenting the analytics restatement dedup.
+
+ Carries the exact query for the catalog's first analytics stream with a full argMax recipe,
+ so the caption stays true to whatever streams the catalog ships.
+ """
+ example: RestatementRecipe | None = None
+ for name in analytics_stream_names(endpoints):
+ entry = descriptions.get(name) or {}
+ recipe = restatement_recipe(endpoints[name], entry.get("columns") or {})
+ if recipe is None:
+ continue
+ if recipe.measures:
+ example = recipe
+ break
+ example = example or recipe
+ if example is None:
+ return ""
+ return (
+ "Analytics report tables keep every restatement Apple publishes for a report date (about six "
+ "days of revisions), so a raw `SUM` grouped by date overcounts. The raw rows preserve the "
+ "restatement history; to aggregate, keep only the latest restatement per report date and "
+ "dimension combination, for example:\n"
+ "\n"
+ f"```\n{example.sql}\n```\n"
+ "\n"
+ f"{_TABLE_PREFIX_NOTE} Each analytics table's description carries the exact query for that table."
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
index db13056fe27d..b2aa8b83af3b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
@@ -53,17 +53,26 @@ class AppStoreConnectSource(ResumableSource[AppStoreConnectSourceConfig, AppStor
@property
def get_source_config(self) -> SourceConfig:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.restatements import (
+ restatement_caption,
+ )
+
+ caption = """Pull your App Store apps, versions, builds, reviews and sales reports into the PostHog Data warehouse.
+
+An Account Holder or Admin creates an API key under **Users and Access → Integrations → App Store Connect API** in App Store Connect. Copy the issuer ID and key ID from that page, then paste the contents of the `.p8` private key file you download. Apple only lets you download that file once, so keep a copy.
+
+Sales and subscription reports also need your vendor number (App Store Connect → **Payments and Financial Reports**) and a key with the Finance, Sales, or Admin role. Leave it blank if you only want app, review and build data."""
+ restatement_note = restatement_caption()
+ if restatement_note:
+ caption = f"{caption}\n\n{restatement_note}"
+
return SourceConfig(
name=SchemaExternalDataSourceType.APP_STORE_CONNECT,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Apple (App Store Connect)",
releaseStatus=ReleaseStatus.BETA,
keywords=["app store", "ios", "apple", "mobile analytics"],
- caption="""Pull your App Store apps, versions, builds, reviews and sales reports into the PostHog Data warehouse.
-
-An Account Holder or Admin creates an API key under **Users and Access → Integrations → App Store Connect API** in App Store Connect. Copy the issuer ID and key ID from that page, then paste the contents of the `.p8` private key file you download. Apple only lets you download that file once, so keep a copy.
-
-Sales and subscription reports also need your vendor number (App Store Connect → **Payments and Financial Reports**) and a key with the Finance, Sales, or Admin role. Leave it blank if you only want app, review and build data.""",
+ caption=caption,
iconPath="/static/services/app_store_connect.png",
docsUrl="https://posthog.com/docs/cdp/sources/app-store-connect",
fields=cast(
@@ -109,8 +118,24 @@ Sales and subscription reports also need your vendor number (App Store Connect
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.canonical_descriptions import (
CANONICAL_DESCRIPTIONS,
)
+ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.restatements import (
+ with_restatement_guidance,
+ )
+
+ # Applied at read time so every analytics stream in the catalog carries its restatement
+ # dedup query, wherever in the module its entry was added.
+ return with_restatement_guidance(CANONICAL_DESCRIPTIONS)
+
+ def get_canonical_descriptions_for_table_prefix(self, table_prefix: str) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.restatements import (
+ with_restatement_guidance,
+ )
- return CANONICAL_DESCRIPTIONS
+ # The dedup queries name a physical table, so they are rebuilt for this source's prefix.
+ return with_restatement_guidance(CANONICAL_DESCRIPTIONS, table_prefix=table_prefix)
def get_non_retryable_errors(self) -> dict[str, str | None]:
# Match the stable status text plus the base host, not the per-request path and cursor.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py
new file mode 100644
index 000000000000..225e9343e8c9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py
@@ -0,0 +1,207 @@
+from datetime import date
+
+import pytest
+
+import duckdb
+
+from posthog.hogql.parser import parse_select
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.restatements import (
+ analytics_stream_names,
+ restatement_caption,
+ restatement_recipe,
+ with_restatement_guidance,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (
+ APP_STORE_CONNECT_ENDPOINTS,
+ AppStoreConnectEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.source import (
+ AppStoreConnectSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+
+def _analytics_config(name: str) -> AppStoreConnectEndpointConfig:
+ return AppStoreConnectEndpointConfig(
+ name=name,
+ kind="analytics_report",
+ primary_keys=["app_id", "processing_date", "_line"],
+ incremental_fields=[incremental_field("processing_date", IncrementalFieldType.Date)],
+ partition_key="processing_date",
+ )
+
+
+# One report date restated across vintages, plus snapshot-backfilled history (negative _line):
+# - 2026-06-15 exists only in the snapshot vintage (processing_date 2026-07-02).
+# - 2026-07-01 has a snapshot row at the boundary plus two ongoing vintages (07-03, 07-04);
+# the (US) tuple is restated in every vintage, the (DE) tuple only in the older ongoing one.
+_VINTAGE_ROWS: list[tuple[str, date, int, date, str, int]] = [
+ ("app1", date(2026, 7, 2), -1, date(2026, 6, 15), "US", 7),
+ ("app1", date(2026, 7, 2), -2, date(2026, 7, 1), "US", 99),
+ ("app1", date(2026, 7, 3), 1, date(2026, 7, 1), "US", 5),
+ ("app1", date(2026, 7, 3), 2, date(2026, 7, 1), "DE", 3),
+ ("app1", date(2026, 7, 4), 1, date(2026, 7, 1), "US", 6),
+]
+
+
+def _run_recipe_on_vintages(sql: str, table_name: str, value_column: str) -> list[tuple]:
+ connection = duckdb.connect()
+ connection.execute(
+ f"CREATE TABLE {table_name} "
+ f"(app_id VARCHAR, processing_date DATE, _line BIGINT, date DATE, territory VARCHAR, {value_column} BIGINT)"
+ )
+ connection.executemany(f"INSERT INTO {table_name} VALUES (?, ?, ?, ?, ?, ?)", _VINTAGE_ROWS)
+ return connection.execute(sql).fetchall()
+
+
+class TestAppStoreConnectRestatements:
+ def test_analytics_streams_derive_from_the_catalog(self) -> None:
+ expected = tuple(
+ name for name, config in APP_STORE_CONNECT_ENDPOINTS.items() if config.kind == "analytics_report"
+ )
+
+ assert analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS) == expected
+ assert "sales_reports" not in expected
+
+ extended = {
+ **APP_STORE_CONNECT_ENDPOINTS,
+ "analytics_future_stream": _analytics_config("analytics_future_stream"),
+ }
+ assert "analytics_future_stream" in analytics_stream_names(extended)
+
+ def test_dimension_tuple_is_derived_per_stream(self) -> None:
+ recipes = {
+ name: restatement_recipe(
+ APP_STORE_CONNECT_ENDPOINTS[name], CANONICAL_DESCRIPTIONS[name].get("columns") or {}
+ )
+ for name in ("analytics_app_sessions", "analytics_app_crashes")
+ }
+ sessions = recipes["analytics_app_sessions"]
+ crashes = recipes["analytics_app_crashes"]
+
+ assert sessions is not None and crashes is not None
+ assert sessions.dimensions != crashes.dimensions
+ assert "territory" in sessions.dimensions
+ assert "territory" not in crashes.dimensions
+ for recipe in (sessions, crashes):
+ assert recipe.dimensions[0] == "date"
+ assert "processing_date" not in recipe.dimensions
+ assert "_line" not in recipe.dimensions
+ assert not set(recipe.measures) & set(recipe.dimensions)
+ assert set(sessions.measures) == {"sessions", "total_session_duration", "unique_devices"}
+ assert set(crashes.measures) == {"crashes", "unique_devices"}
+
+ def test_recipe_keeps_one_row_per_date_and_dimension_tuple_from_the_latest_vintage(self) -> None:
+ columns = dict.fromkeys(("app_id", "processing_date", "_line", "date", "territory", "sessions"), "")
+ recipe = restatement_recipe(_analytics_config("analytics_events"), columns)
+
+ assert recipe is not None
+ assert recipe.dimensions == ("date", "app_id", "territory")
+ assert recipe.measures == ("sessions",)
+
+ rows = _run_recipe_on_vintages(recipe.sql, recipe.table_name, "sessions")
+
+ # The 07-04 restatement of 2026-07-01 carries no DE row, and a restatement republishes
+ # its report date in full, so DE is gone rather than unchanged. Reading its 07-03 value
+ # forward would resurrect a tuple Apple dropped and inflate every total taken from it.
+ assert sorted(rows) == [
+ (date(2026, 6, 15), "app1", "US", 7),
+ (date(2026, 7, 1), "app1", "US", 6),
+ ]
+
+ def test_fallback_recipe_keeps_only_the_latest_vintage_when_measures_are_unknown(self) -> None:
+ columns = dict.fromkeys(("app_id", "processing_date", "_line", "date", "territory", "happiness"), "")
+ recipe = restatement_recipe(_analytics_config("analytics_events"), columns)
+
+ assert recipe is not None
+ assert "argMax(" not in recipe.sql
+ assert recipe.measures == ()
+
+ rows = _run_recipe_on_vintages(recipe.sql, recipe.table_name, "happiness")
+
+ assert sorted((row[3], row[0], row[4], row[5]) for row in rows) == [
+ (date(2026, 6, 15), "app1", "US", 7),
+ (date(2026, 7, 1), "app1", "US", 6),
+ ]
+
+ def test_every_recipe_parses_as_hogql(self) -> None:
+ for name in analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS):
+ recipe = restatement_recipe(APP_STORE_CONNECT_ENDPOINTS[name], CANONICAL_DESCRIPTIONS[name]["columns"])
+ assert recipe is not None
+ parse_select(recipe.sql)
+ fallback = restatement_recipe(APP_STORE_CONNECT_ENDPOINTS["analytics_app_sessions"], {"unknown_measure": ""})
+ assert fallback is not None
+ parse_select(fallback.sql)
+
+ def test_every_analytics_table_description_carries_its_dedup_query(self) -> None:
+ descriptions = AppStoreConnectSource().get_canonical_descriptions()
+
+ for name in analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS):
+ entry = descriptions[name]
+ description = entry.get("description") or ""
+ assert "restat" in description.lower(), name
+ assert "argMax(" in description, name
+ assert f"appstoreconnect_{name}" in description, name
+ columns = entry.get("columns") or {}
+ assert "restat" in columns["processing_date"].lower(), name
+ recipe = restatement_recipe(APP_STORE_CONNECT_ENDPOINTS[name], CANONICAL_DESCRIPTIONS[name]["columns"])
+ assert recipe is not None
+ for measure in recipe.measures:
+ assert "restat" in columns[measure].lower(), (name, measure)
+
+ def test_non_analytics_tables_are_left_untouched(self) -> None:
+ descriptions = AppStoreConnectSource().get_canonical_descriptions()
+
+ for name in ("apps", "sales_reports", "customer_reviews"):
+ assert descriptions[name] == CANONICAL_DESCRIPTIONS[name]
+
+ def test_guidance_is_not_applied_twice(self) -> None:
+ once = with_restatement_guidance(CANONICAL_DESCRIPTIONS)
+
+ assert with_restatement_guidance(once) == once
+
+ def test_caption_documents_the_restatement_dedup(self) -> None:
+ caption = AppStoreConnectSource().get_source_config.caption or ""
+
+ assert "restat" in caption.lower()
+ assert "argMax(" in caption
+ assert "processing_date" in caption
+
+ def test_caption_recipe_follows_the_catalog(self) -> None:
+ caption = restatement_caption()
+ first_analytics = analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS)[0]
+
+ assert f"appstoreconnect_{first_analytics}" in caption
+
+ @pytest.mark.parametrize(
+ "table_prefix,expected_table_prefix,expects_caveat",
+ [
+ # No source in hand (the public docs endpoint): the prefix is unknowable, so the query
+ # names the unprefixed table and the description says as much.
+ (None, "", True),
+ # A connected source that set no prefix — the caveat would only be noise.
+ ("", "", False),
+ ("acme_", "acme_", False),
+ ],
+ )
+ def test_recipe_names_the_table_the_connected_source_has(
+ self, table_prefix: str | None, expected_table_prefix: str, expects_caveat: bool
+ ) -> None:
+ descriptions = with_restatement_guidance(CANONICAL_DESCRIPTIONS, table_prefix=table_prefix)
+ name = analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS)[0]
+ description = descriptions[name].get("description") or ""
+
+ assert f"FROM {expected_table_prefix}appstoreconnect_{name} AS raw" in description
+ assert ("table name prefix" in description) is expects_caveat
+
+ def test_source_rebuilds_its_descriptions_for_a_table_prefix(self) -> None:
+ # Guards the wiring: a recipe that honours a prefix is useless if the source never passes one.
+ name = analytics_stream_names(APP_STORE_CONNECT_ENDPOINTS)[0]
+ descriptions = AppStoreConnectSource().get_canonical_descriptions_for_table_prefix("acme_")
+
+ assert f"FROM acme_appstoreconnect_{name} AS raw" in (descriptions[name].get("description") or "")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 29e4b6b5b19d..77b04fe12913 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -246,6 +246,17 @@ class _BaseSource(ABC, Generic[ConfigType]):
return {}
+ def get_canonical_descriptions_for_table_prefix(self, table_prefix: str) -> CanonicalDescriptions:
+ """Curated descriptions adapted to one connected source's physical table names.
+
+ `get_canonical_descriptions` is keyed by source type, so a description that names a physical
+ table is written for a source connected without a table prefix, while `build_table_name`
+ prepends whatever prefix that source was given. Sources whose descriptions embed table names
+ override this to rebuild them for `table_prefix`; almost none do, so the default ignores it.
+ """
+
+ return self.get_canonical_descriptions()
+
def get_schemas(
self,
config: ConfigType,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/canonical_descriptions.py
index 2f3be47a627d..ef506769629a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/canonical_descriptions.py
@@ -28,11 +28,14 @@ class CanonicalEndpoint(TypedDict, total=False):
CanonicalDescriptions = dict[str, CanonicalEndpoint]
-def get_canonical_descriptions_for_source(source_type: "ExternalDataSourceType | str") -> CanonicalDescriptions:
+def get_canonical_descriptions_for_source(
+ source_type: "ExternalDataSourceType | str", table_prefix: str = ""
+) -> CanonicalDescriptions:
"""Resolve a source's curated descriptions via the registry. ``{}`` when the source ships none.
Accepts the raw `ExternalDataSource.source_type` string (or the enum) and normalizes it; an
- unknown value resolves to ``{}``.
+ unknown value resolves to ``{}``. ``table_prefix`` is the connected source's
+ `ExternalDataSource.prefix`, so descriptions that name a physical table name the right one.
"""
# Imported lazily: the registry pulls in every source's (often heavy) dependencies on first use.
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import (
@@ -45,6 +48,6 @@ def get_canonical_descriptions_for_source(source_type: "ExternalDataSourceType |
except Exception:
return {}
try:
- return source.get_canonical_descriptions()
+ return source.get_canonical_descriptions_for_table_prefix(table_prefix)
except Exception:
return {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_base.py
index de9a907cb13f..c92579c8ea47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_base.py
@@ -1,6 +1,40 @@
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from posthog.schema import SourceConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ _BaseSource,
+ error_message_matches,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.config import Config
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class _DescriptionsOnlySource(_BaseSource[Config]):
+ # Only the descriptions matter here; the hook under test never reaches the rest of the surface.
+ @property
+ def source_type(self) -> ExternalDataSourceType:
+ raise NotImplementedError()
+
+ @property
+ def get_source_config(self) -> SourceConfig:
+ raise NotImplementedError()
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return {"widgets": {"description": "A widget."}}
+
+
+def test_table_prefix_hook_defaults_to_the_plain_descriptions() -> None:
+ # Almost no source overrides this, so a default that dropped or emptied the descriptions
+ # would silently strip curated docs from every one of them on the enrichment path.
+ source = _DescriptionsOnlySource()
+
+ result = source.get_canonical_descriptions_for_table_prefix("acme_")
+
+ assert result == {"widgets": {"description": "A widget."}}
@parameterized.expand(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
index 85b907dcbe0f..9ac45a385a5c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
@@ -355,7 +355,9 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,
# (`created_at`, `customer_id`) each column surfaces as, so the description lands on the column that
# `information_schema` and the AI agent actually see. Columns with no rename map to themselves.
hogql_name_by_raw = get_hogql_column_name_mapping(table.table_name_without_prefix())
- canonical = get_canonical_descriptions_for_source(schema.source.source_type).get(schema.name, {})
+ canonical = get_canonical_descriptions_for_source(
+ schema.source.source_type, table_prefix=schema.source.prefix or ""
+ ).get(schema.name, {})
canonical_columns = {
hogql_name_by_raw.get(raw_name, raw_name): description
for raw_name, description in (canonical.get("columns") or {}).items()