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 AppFollow ASO and review statistics tables (#98312)

Tom Owers1a118e05ce74
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 cb2d8a1f0df3..2e3f5e0836e6 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
@@ -396,14 +396,14 @@ Note: The v2 reference index lists the complete resource set; each candidate bel
## Appfollow — gaps
-Today (5): `app_collections`, `app_lists`, `ratings_history`, `reviews`, `users`
+Today (9): `app_collections`, `app_lists`, `app_versions`, `keywords`, `rankings`, `ratings_history`, `reviews`, `reviews_stats`, `users`
Diffed against: <https://docs.api.appfollow.io/reference/app_collections_list_api_v2_account_apps_get-1>
-- [ ] `/api/v2/meta/rankings` — category ranking history — the headline ASO metric, complements ratings_history (high)
-- [ ] `/api/v2/aso/keywords` — tracked keyword positions per app and country (high)
-- [ ] `/api/v2/meta/versions` — app version release history; lookup resolving the version field on synced reviews (high)
-- [ ] `/api/v2/reviews/stats` — aggregate review counts and sentiment without re-aggregating raw reviews (medium)
+- [x] `/api/v2/meta/rankings` — category ranking history — the headline ASO metric, complements ratings_history (high) — synced as `rankings`. v2 takes a single `date`, not a range, so it is a daily snapshot rather than backfillable history.
+- [x] `/api/v2/aso/keywords` — tracked keyword positions per app and country (high) — synced as `keywords`, also a daily snapshot.
+- [x] `/api/v2/meta/versions` — app version release history; lookup resolving the version field on synced reviews (high) — synced as `app_versions`.
+- [x] `/api/v2/reviews/stats` — aggregate review counts and sentiment without re-aggregating raw reviews (medium) — synced as `reviews_stats`, incremental on `date`. Counts only; sentiment lives on `/reviews/semantic`.
- [ ] `/api/v2/reviews/stats/version` — review breakdown by app version, the standard release-quality view (medium)
- [ ] `/api/v2/reviews/stats/ratings` — rating distribution over time (medium)
- [ ] `/api/v2/reviews/stats/replies, /reviews/stats/replies/count, /reviews/stats/replies/speed` — reply coverage and response-time SLA metrics for support teams (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md
index 4a44e063cc02..74b69f1ce850 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md
@@ -3,11 +3,15 @@
Reference for the endpoints this source syncs. AppFollow API v2, base URL `https://api.appfollow.io/api/v2`,
auth via the `X-AppFollow-API-Token` header. Docs: <https://docs.api.appfollow.io/reference/overview>.
-> **Verification status:** the response shapes below are reconstructed from the public API docs and the
-> open-source Airbyte `source-appfollow` connector (which confirms `app_collections`, `app_lists`,
-> `users`, and `ratings` shapes). We did **not** have an API token to curl-verify the `reviews` and
-> `ratings_history` request/response details live, so a few field names and the `last_modified` format
-> are best-effort — see the inline notes in `appfollow.py`.
+> **Verification status:** every path and query parameter below was checked against the published v2
+> OpenAPI definition for that endpoint. Response shapes are a different matter: AppFollow publishes an
+> **empty 200 schema for every v2 endpoint**, so no envelope key or row field is documented anywhere.
+> Those columns are reconstructed from the docs, the open-source Airbyte `source-appfollow` connector
+> (which confirms `app_collections`, `app_lists`, `users`, and `ratings`), and the shape of the
+> product's own UI. We did **not** have an API token to curl-verify anything live, so field names, the
+> `last_modified` format, and the envelope keys marked "unpublished" below are best-effort — see the
+> inline notes in `appfollow.py`. `_extract_rows` takes candidate envelope keys and falls back to a
+> root list for those endpoints, so a wrong guess yields an empty table rather than a wrong one.
## Cost & limits
@@ -20,13 +24,17 @@ auth via the `X-AppFollow-API-Token` header. Docs: <https://docs.api.appfollow.i
## Endpoints
-| Schema | Path | Shape | Rows under | Primary key | Incremental | Default sync |
-| ----------------- | ----------------------------------------------------------------------- | ------------------------------------- | ---------- | ----------------------------- | ----------------------------- | ------------ |
-| `app_collections` | `/account/apps` | single request | `apps` | `[id]` | — (full refresh) | ✅ |
-| `app_lists` | `/account/apps/app?apps_id=<id>` | fan-out over collections | `apps_app` | `[app_collection_id, app_id]` | — (full refresh) | ✅ |
-| `users` | `/account/users` | single request | root list | `[id]` | — (full refresh) | ❌ |
-| `reviews` | `/reviews?ext_id=<ext_id>&from=&to=&page=` | fan-out over apps, page/`pages_count` | `reviews` | `[ext_id, review_id]` | `updated` via `last_modified` | ✅ |
-| `ratings_history` | `/meta/ratings/history?ext_id=<ext_id>&store=&from=&to=&offset=&limit=` | fan-out over apps, offset/limit | `ratings` | `[ext_id, store, date]` | `date` via `from` | ❌ |
+| Schema | Path | Shape | Rows under | Primary key | Incremental | Default sync |
+| ----------------- | ----------------------------------------------------------------------- | ------------------------------------- | ----------- | ------------------------------------------- | ----------------------------- | ------------ |
+| `app_collections` | `/account/apps` | single request | `apps` | `[id]` | — (full refresh) | ✅ |
+| `app_lists` | `/account/apps/app?apps_id=<id>` | fan-out over collections | `apps_app` | `[app_collection_id, app_id]` | — (full refresh) | ✅ |
+| `users` | `/account/users` | single request | root list | `[id]` | — (full refresh) | ❌ |
+| `reviews` | `/reviews?ext_id=<ext_id>&from=&to=&page=` | fan-out over apps, page/`pages_count` | `reviews` | `[ext_id, review_id]` | `updated` via `last_modified` | ✅ |
+| `ratings_history` | `/meta/ratings/history?ext_id=<ext_id>&store=&from=&to=&offset=&limit=` | fan-out over apps, offset/limit | `ratings` | `[ext_id, store, date]` | `date` via `from` | ❌ |
+| `rankings` | `/meta/rankings?ext_id=<ext_id>&date=` | fan-out over apps, single request | unpublished | `[ext_id, country, device, genre_id, date]` | — (full refresh) | ❌ |
+| `keywords` | `/aso/keywords?ext_id=<ext_id>&date=&page=` | fan-out over apps, `page` | unpublished | `[ext_id, country, device, date, keyword]` | — (full refresh) | ❌ |
+| `app_versions` | `/meta/versions?ext_id=<ext_id>&country=&page=` | fan-out over apps, `page` | unpublished | `[ext_id, country, version]` | — (full refresh) | ❌ |
+| `reviews_stats` | `/reviews/stats?ext_id=<ext_id>&from=&to=` | fan-out over apps, single request | unpublished | `[ext_id, date]` | `date` via `from` | ❌ |
## Discovery chain
@@ -48,3 +56,24 @@ enumerate a workspace's apps is:
window to `DEFAULT_START_DATE`..today and let `last_modified` do the incremental work.
- `ratings_history`: `type=total` returns one dated snapshot per day; the `from` date filter is the
incremental cursor (past snapshots don't change, so `from`=watermark is safe).
+- `reviews_stats`: `from`/`to` bound the reported range, so `from`=watermark is the incremental cursor,
+ exactly as for `ratings_history`.
+- `rankings` and `keywords` take a single optional `date`, **not** a range. There is no server-side
+ filter to drive a delta off, and one request per day per app would cost 10 credits each, so both sync
+ as a full refresh of one day. We request today explicitly and stamp that date on every row, so the
+ primary key and the partition key are populated even though the response schema is unpublished.
+- `app_versions`: `/meta/versions` exposes no date parameter at all. Full refresh; the table is small.
+
+## Pagination notes
+
+- `keywords` and `app_versions` page with a bare 1-indexed `page`. Neither publishes a page count, a
+ total, or a page-size parameter, so the walk can only end on an empty page. `MAX_PAGES_PER_APP` caps
+ it and logs when the cap is reached.
+- `rankings` and `reviews_stats` expose no pagination at all — one request per app is the whole walk.
+
+## Country resolution
+
+`/meta/versions` **requires** a `country`, and an app row does not reliably carry one. The fan-out
+resolves it per app: the app's own `country`, then the nested `app.country`, then the collection's
+`default_country`, then the first entry of the collection's `countries`, then `us`. An app tracked in
+two collections with different countries is fetched once per country, because versions vary by country.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py
index 98ede49d1c1c..b4b9b70ba842 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py
@@ -7,6 +7,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
APPFOLLOW_ENDPOINTS,
DEFAULT_START_DATE,
@@ -21,6 +23,14 @@ APPFOLLOW_BASE_URL = "https://api.appfollow.io/api/v2"
# Ratings history is offset/limit paginated; reviews use page/pages_count. Both cap a page at 100 rows.
DEFAULT_PAGE_SIZE = 100
+# The ASO endpoints page with a bare `page` number and publish neither a page count nor a total, so
+# the walk can only end on an empty page. Cap it so a misbehaving endpoint can't spend credits forever.
+MAX_PAGES_PER_APP = 100
+
+# `/meta/versions` requires a country and an app does not always carry one. Last resort when neither
+# the app nor its collection names one.
+FALLBACK_COUNTRY = "us"
+
class AppfollowRetryableError(Exception):
pass
@@ -128,17 +138,25 @@ def _fetch(
return response.json()
-def _extract_rows(data: Any, data_key: str | None) -> list[dict[str, Any]]:
+def _extract_rows(data: Any, data_key: str | tuple[str, ...] | None) -> list[dict[str, Any]]:
"""Pull the row list out of an AppFollow response.
Rows live either at the response root (``data_key is None``) or under a single body key
(e.g. ``apps``, ``reviews``, ``ratings``). Anything unexpected degrades to an empty page rather
than raising, since AppFollow occasionally returns a non-list error envelope with HTTP 200.
+
+ The ASO and review-statistics endpoints publish an empty 200 schema, so their envelope key is a
+ best guess. Those endpoints pass several candidate keys and fall back to a root list, rather than
+ syncing an empty table on a key we guessed wrong.
"""
if data_key is None:
return data if isinstance(data, list) else []
- value = data.get(data_key) if isinstance(data, dict) else None
- return value if isinstance(value, list) else []
+ if isinstance(data, dict):
+ for key in (data_key,) if isinstance(data_key, str) else data_key:
+ value = data.get(key)
+ if isinstance(value, list):
+ return value
+ return data if isinstance(data, list) else []
def check_credentials(api_key: str) -> int | None:
@@ -161,8 +179,14 @@ def _iter_collections(session: requests.Session, logger: FilteringBoundLogger) -
yield from _extract_rows(data, "apps")
-def _iter_apps(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:
- """Fan out over every collection and yield each app row, enriched for keying and downstream fan-out.
+@frozen
+class _CollectionApp:
+ collection: dict[str, Any]
+ app: dict[str, Any]
+
+
+def _iter_collection_apps(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[_CollectionApp]:
+ """Fan out over every collection and yield each app with the collection it came from.
Each app row is stamped with its `app_collection_id` and `collection_name`, and `ext_id`/`store`
are lifted from the nested `app` object to the top level when absent so the review/rating fan-outs
@@ -180,36 +204,73 @@ def _iter_apps(session: requests.Session, logger: FilteringBoundLogger) -> Itera
app["ext_id"] = nested_ext_id
if not app.get("store") and (nested_store := nested.get("store")):
app["store"] = nested_store
- yield app
+ yield _CollectionApp(collection=collection, app=app)
+def _iter_apps(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:
+ for pair in _iter_collection_apps(session, logger):
+ yield pair.app
+
+
+def _resolve_country(collection: dict[str, Any], app: dict[str, Any]) -> str:
+ """Resolve the store country to query an app's country-scoped endpoints with.
+
+ An app row does not reliably carry a country, so fall back to the country its collection tracks.
+ """
+ countries = collection.get("countries")
+ first_tracked = countries[0] if isinstance(countries, list) and countries else None
+ country = (
+ app.get("country")
+ or (app.get("app") or {}).get("country")
+ or collection.get("default_country")
+ or first_tracked
+ or FALLBACK_COUNTRY
+ )
+ return str(country).lower()
+
+
+@frozen
class _AppTarget:
ext_id: str
store: str | None
collection_name: str | None
+ country: str
def _iter_app_targets(
- session: requests.Session, logger: FilteringBoundLogger, *, dedupe_by_store: bool
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ *,
+ dedupe_by_store: bool,
+ dedupe_by_country: bool = False,
) -> list[_AppTarget]:
- """Discover the apps the review/rating fan-outs iterate.
+ """Discover the apps the per-app fan-outs iterate.
- Reviews key on `ext_id` alone; ratings key on `ext_id` + `store`. The same app can appear in
- several collections, so we de-duplicate to avoid fetching (and paying credits for) it twice.
+ Reviews key on `ext_id` alone; ratings key on `ext_id` + `store`; the country-scoped ASO endpoints
+ key on `ext_id` + `country`. The same app can appear in several collections, so we de-duplicate on
+ whichever of those the endpoint varies to avoid fetching (and paying credits for) it twice.
"""
- seen: set[tuple[str, str | None]] = set()
+ seen: set[tuple[str, str | None, str | None]] = set()
targets: list[_AppTarget] = []
- for app in _iter_apps(session, logger):
+ for pair in _iter_collection_apps(session, logger):
+ app = pair.app
ext_id = app.get("ext_id")
if not ext_id:
continue
store = app.get("store")
- key = (str(ext_id), store if dedupe_by_store else None)
+ country = _resolve_country(pair.collection, app)
+ key = (str(ext_id), store if dedupe_by_store else None, country if dedupe_by_country else None)
if key in seen:
continue
seen.add(key)
- targets.append(_AppTarget(ext_id=str(ext_id), store=store, collection_name=app.get("collection_name")))
+ targets.append(
+ _AppTarget(
+ ext_id=str(ext_id),
+ store=store,
+ collection_name=app.get("collection_name"),
+ country=country,
+ )
+ )
return targets
@@ -355,6 +416,84 @@ def _get_ratings(
manager.save_state(AppfollowResumeConfig(ext_id=remaining[i + 1].ext_id, cursor=0))
+def _fanout_time_params(
+ config: AppfollowEndpointConfig,
+ today: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ if config.time_mode == "snapshot":
+ return {"date": today}
+ if config.time_mode == "window":
+ from_date = DEFAULT_START_DATE
+ if should_use_incremental_field and db_incremental_field_last_value:
+ from_date = _to_date_str(_clamp_future_value_to_now(db_incremental_field_last_value)) or DEFAULT_START_DATE
+ return {"from": from_date, "to": today}
+ return {}
+
+
+def _stamp_fanout_row(row: dict[str, Any], config: AppfollowEndpointConfig, target: "_AppTarget", today: str) -> None:
+ """Fill in the key and partition fields the request knows but the response may not carry."""
+ row.setdefault("ext_id", target.ext_id)
+ if config.requires_country:
+ row.setdefault("country", target.country)
+ if config.time_mode == "snapshot":
+ row.setdefault("date", today)
+
+
+def _get_app_fanout(
+ session: requests.Session,
+ config: AppfollowEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppfollowResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the ASO and review-statistics endpoints, which take one `ext_id` per request.
+
+ They differ only in whether they page, whether they need a country, and how they take time, so
+ the endpoint config drives all three rather than each endpoint getting its own walk.
+ """
+ targets = _iter_app_targets(session, logger, dedupe_by_store=False, dedupe_by_country=config.requires_country)
+ remaining, resume_page = _resume_slice(targets, manager)
+
+ today = _today_str()
+ time_params = _fanout_time_params(config, today, should_use_incremental_field, db_incremental_field_last_value)
+
+ for i, target in enumerate(remaining):
+ page = resume_page if i == 0 and resume_page else 1
+ while True:
+ params: dict[str, Any] = {"ext_id": target.ext_id, **time_params}
+ if config.requires_country:
+ params["country"] = target.country
+ if config.paginated:
+ params["page"] = page
+
+ data = _fetch(session, f"{APPFOLLOW_BASE_URL}{config.path}", params, logger)
+ rows = _extract_rows(data, config.data_key)
+
+ if rows:
+ for row in rows:
+ _stamp_fanout_row(row, config, target, today)
+ yield rows
+
+ if not config.paginated or not rows:
+ break
+ if page >= MAX_PAGES_PER_APP:
+ logger.warning(
+ f"AppFollow {config.name}: reached the {MAX_PAGES_PER_APP} page cap for "
+ f"ext_id={target.ext_id}; later pages were not fetched"
+ )
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches the current page rather than skipping it.
+ manager.save_state(AppfollowResumeConfig(ext_id=target.ext_id, cursor=page))
+
+ if i + 1 < len(remaining):
+ manager.save_state(AppfollowResumeConfig(ext_id=remaining[i + 1].ext_id, cursor=1))
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -370,6 +509,15 @@ def get_rows(
yield from _get_list(session, config, logger)
elif config.kind == "apps":
yield from _get_apps(session, logger)
+ elif config.kind == "app_fanout":
+ yield from _get_app_fanout(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
elif config.kind == "reviews":
yield from _get_reviews(
session,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py
index 1a00a07da21b..3c0117a057e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py
@@ -70,6 +70,54 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"user_id": "Store user id of the author, if available.",
},
},
+ "rankings": {
+ "description": "A daily snapshot of each tracked app's category rank positions in the store charts.",
+ "docs_url": "https://docs.api.appfollow.io/reference/rankings_api_v2_meta_rankings_get-1",
+ "columns": {
+ "ext_id": "External store id of the app the rank belongs to.",
+ "country": "Two-letter country code the rank was measured in.",
+ "device": "Device the rank was measured for (for example iphone, ipad).",
+ "genre_id": "Store genre (category) id the rank is within.",
+ "category": "Store genre (category) name the rank is within.",
+ "position": "The app's position in that category chart.",
+ "date": "Day the snapshot was taken.",
+ },
+ },
+ "keywords": {
+ "description": "A daily snapshot of the search position your tracked apps hold for each keyword you track in AppFollow.",
+ "docs_url": "https://docs.api.appfollow.io/reference/keywords_api_v2_aso_keywords_get-1",
+ "columns": {
+ "ext_id": "External store id of the app the keyword is tracked for.",
+ "store": "Store the keyword is tracked on.",
+ "country": "Two-letter country code the keyword is tracked in.",
+ "device": "Device the keyword is tracked for.",
+ "keyword": "The tracked search term.",
+ "pos": "The app's search result position for the keyword.",
+ "popularity": "Keyword popularity score, from 0 to 100.",
+ "date": "Day the snapshot was taken.",
+ },
+ },
+ "app_versions": {
+ "description": "Store release history for your tracked apps, including metadata changes. Resolves the app version recorded on each review.",
+ "docs_url": "https://docs.api.appfollow.io/reference/versions__any_changes_including_meta_data__api_v2_meta_versions_get-1",
+ "columns": {
+ "ext_id": "External store id of the app the release belongs to.",
+ "country": "Two-letter country code the release was published in.",
+ "version": "The app version string.",
+ "release_date": "When the version was released in the store.",
+ "whats_new": "Release notes the developer published with the version.",
+ },
+ },
+ "reviews_stats": {
+ "description": "Aggregate review and reply counts per app and day, so review volume can be charted without syncing every raw review.",
+ "docs_url": "https://docs.api.appfollow.io/reference/stat_reviews_api_v2_reviews_stats_get-1",
+ "columns": {
+ "ext_id": "External store id of the app the statistics are for.",
+ "date": "Day the statistics are for.",
+ "reviews": "Number of reviews collected that day.",
+ "replies": "Number of developer replies posted that day.",
+ },
+ },
"ratings_history": {
"description": "Daily star-rating history per app and store, incrementally synced by date.",
"docs_url": "https://docs.api.appfollow.io/reference/ratings_history_api_v2_meta_ratings_history_get",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md
index 67006cc51aae..dfb5bc2385ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md
@@ -23,9 +23,10 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
[AppFollow](https://appfollow.io) aggregates App Store and Google Play data for app analytics, review
-management, and app store optimization. This connector pulls your tracked apps, their reviews, and their
-rating history into the PostHog Data warehouse, where you can join them with product analytics, build
-insights, and monitor review sentiment over time.
+management, and app store optimization. This connector pulls your tracked apps, their reviews, their
+rating history, and their app store optimization data (category ranks, tracked keyword positions,
+release history, and review statistics) into the PostHog Data warehouse, where you can join them with
+product analytics, build insights, and monitor review sentiment over time.
## Prerequisites
@@ -49,8 +50,12 @@ through the `X-AppFollow-API-Token` header.
<SyncModes />
The `reviews` table syncs incrementally on each review's last-modified timestamp, and `ratings_history`
-syncs incrementally by date, so after the first backfill only new and changed rows are fetched. The
-`app_collections`, `app_lists`, and `users` tables are small and sync as full refresh.
+and `reviews_stats` sync incrementally by date, so after the first backfill only new and changed rows
+are fetched. Every other table syncs as full refresh.
+
+The `rankings` and `keywords` tables are the exception worth knowing about. AppFollow returns rank and
+keyword positions for a single day at a time, with no way to ask for a range, so each sync adds that
+day's snapshot. Their history builds up from the days you sync rather than being backfilled.
## Configuration
@@ -60,10 +65,13 @@ syncs incrementally by date, so after the first backfill only new and changed ro
<SourceTables />
-The `reviews` and `ratings_history` tables are queried per app using the app's store `ext_id`, which is
-discovered by walking your collections (`app_collections`) and their apps (`app_lists`). Because those
-requests cost credits, `ratings_history` and `users` are off by default — enable them in the table
-picker if you want them.
+Every table except `app_collections`, `app_lists`, and `users` is queried per app using the app's store
+`ext_id`, which is discovered by walking your collections (`app_collections`) and their apps
+(`app_lists`). Because those requests cost credits, only `app_collections`, `app_lists`, and `reviews`
+are on by default — enable the rest in the table picker if you want them.
+
+`app_versions` needs a store country, which AppFollow does not always record on an app. We use the
+country your collection tracks, and fall back to `us` when your collection does not name one.
## Troubleshooting
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py
index d34e989ffd4b..8e4851b6fbb8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py
@@ -1,11 +1,13 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# AppFollow's data model is app-centric: most data is queried per app via its store `ext_id`, and the
# only way to discover a workspace's apps is to walk collections (`/account/apps`) and then their apps
-# (`/account/apps/app`). So the source exposes five endpoints across three request shapes:
+# (`/account/apps/app`). So the source exposes its endpoints across five request shapes:
#
# - "list": a single top-level GET whose rows live at the response root or under a body key
# (`app_collections` -> `apps`, `users` -> root). No app context needed. Full refresh.
@@ -16,7 +18,17 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# server-side `last_modified` filter we drive incrementally off the review `updated` field.
# - "ratings": `/meta/ratings/history` — fans out over every app, offset/limit paginated, with a
# server-side `from` date filter we drive incrementally off the record `date` field.
-EndpointKind = Literal["list", "apps", "reviews", "ratings"]
+# - "app_fanout": the ASO and review-statistics endpoints, which all take one `ext_id` per request
+# and differ only in how they page and how they take time. `paginated`, `requires_country`
+# and `time_mode` below describe those differences declaratively.
+EndpointKind = Literal["list", "apps", "reviews", "ratings", "app_fanout"]
+
+# How an "app_fanout" endpoint takes time:
+# - "none": no time parameter at all, so the endpoint returns its whole history (full refresh).
+# - "snapshot": a single `date` parameter selecting one day. We request today and stamp that date on
+# every row, so the primary key and the partition key are always populated.
+# - "window": a `from`/`to` date range. `from` is the incremental cursor.
+TimeMode = Literal["none", "snapshot", "window"]
# AppFollow requires a `from`/`to` window on the reviews and ratings endpoints. On a first (backfill)
# sync we open the window all the way back to this date so the whole history is captured once; from
@@ -25,14 +37,15 @@ EndpointKind = Literal["list", "apps", "reviews", "ratings"]
DEFAULT_START_DATE = "2008-01-01"
-@dataclass
+@frozen
class AppfollowEndpointConfig:
name: str
path: str
kind: EndpointKind
primary_keys: list[str]
- # Body key the rows live under. `None` means the response root is itself the row list.
- data_key: Optional[str] = None
+ # Body key the rows live under. `None` means the response root is itself the row list. A tuple
+ # lists candidate keys for the endpoints whose response envelope AppFollow does not publish.
+ data_key: Optional[str | tuple[str, ...]] = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
default_incremental_field: Optional[str] = None
# Stable, creation-style field to partition by — never an updated/last-modified field.
@@ -40,6 +53,12 @@ class AppfollowEndpointConfig:
should_sync_default: bool = True
# Max rows per page. Reviews cap at 100/page; ratings history uses offset/limit.
page_size: int = 100
+ # "app_fanout" only: walk 1-indexed `page` until a page comes back empty.
+ paginated: bool = False
+ # "app_fanout" only: the endpoint requires a `country`, resolved per app.
+ requires_country: bool = False
+ # "app_fanout" only: see TimeMode.
+ time_mode: TimeMode = "none"
_REVIEW_UPDATED_FIELD: IncrementalField = {
@@ -49,7 +68,7 @@ _REVIEW_UPDATED_FIELD: IncrementalField = {
"field_type": IncrementalFieldType.DateTime,
}
-_RATINGS_DATE_FIELD: IncrementalField = {
+_DATE_FIELD: IncrementalField = {
"label": "date",
"type": IncrementalFieldType.Date,
"field": "date",
@@ -109,7 +128,59 @@ APPFOLLOW_ENDPOINTS: dict[str, AppfollowEndpointConfig] = {
data_key="ratings",
partition_key="date",
default_incremental_field="date",
- incremental_fields=[_RATINGS_DATE_FIELD],
+ incremental_fields=[_DATE_FIELD],
+ should_sync_default=False,
+ ),
+ # Category rank positions per app. AppFollow v2 takes a single optional `date`, not a range, so
+ # this is a daily snapshot rather than rank history — we request today and stamp that date on
+ # every row. Off by default: 10 credits per app per sync.
+ "rankings": AppfollowEndpointConfig(
+ name="rankings",
+ path="/meta/rankings",
+ kind="app_fanout",
+ primary_keys=["ext_id", "country", "device", "genre_id", "date"],
+ data_key=("ranks", "rankings"),
+ partition_key="date",
+ time_mode="snapshot",
+ should_sync_default=False,
+ ),
+ # Tracked ASO keyword positions per app. Same daily-snapshot shape as `rankings`, plus 1-indexed
+ # `page` pagination. Off by default: 10 credits per app per page.
+ "keywords": AppfollowEndpointConfig(
+ name="keywords",
+ path="/aso/keywords",
+ kind="app_fanout",
+ primary_keys=["ext_id", "country", "device", "date", "keyword"],
+ data_key=("keywords",),
+ partition_key="date",
+ time_mode="snapshot",
+ paginated=True,
+ should_sync_default=False,
+ ),
+ # Store release history per app, including metadata changes. Resolves the `app_version` field on
+ # synced reviews. The endpoint requires a `country`, so the fan-out resolves one per app.
+ "app_versions": AppfollowEndpointConfig(
+ name="app_versions",
+ path="/meta/versions",
+ kind="app_fanout",
+ primary_keys=["ext_id", "country", "version"],
+ data_key=("versions",),
+ paginated=True,
+ requires_country=True,
+ should_sync_default=False,
+ ),
+ # Aggregate review and reply counts per app and day, so review volume can be charted without
+ # syncing every raw review. Incremental on `date` via the server-side `from` filter.
+ "reviews_stats": AppfollowEndpointConfig(
+ name="reviews_stats",
+ path="/reviews/stats",
+ kind="app_fanout",
+ primary_keys=["ext_id", "date"],
+ data_key=("stats", "reviews"),
+ partition_key="date",
+ time_mode="window",
+ default_incremental_field="date",
+ incremental_fields=[_DATE_FIELD],
should_sync_default=False,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
index 46c7ea644cc4..c36a4aca07c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
@@ -1,5 +1,5 @@
from datetime import UTC, date, datetime
-from typing import Any
+from typing import Any, Protocol
import pytest
from freezegun import freeze_time
@@ -13,12 +13,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.
AppfollowResumeConfig,
_clamp_future_value_to_now,
_extract_rows,
+ _resolve_country,
_to_date_str,
_to_datetime_str,
appfollow_source,
get_rows,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import APPFOLLOW_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
+ APPFOLLOW_ENDPOINTS,
+ DEFAULT_START_DATE,
+)
class _FakeManager:
@@ -70,7 +74,11 @@ class _FakeApi:
raise AssertionError(f"unexpected url {url}")
-def _collect(endpoint: str, manager: _FakeManager, monkeypatch: Any, api: _FakeApi, **kwargs: Any) -> list[dict]:
+class _CannedApi(Protocol):
+ def fetch(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> Any: ...
+
+
+def _collect(endpoint: str, manager: _FakeManager, monkeypatch: Any, api: _CannedApi, **kwargs: Any) -> list[dict]:
monkeypatch.setattr(appfollow, "_fetch", api.fetch)
monkeypatch.setattr(appfollow, "make_tracked_session", lambda **k: mock.MagicMock())
rows: list[dict] = []
@@ -95,6 +103,12 @@ class TestExtractRows:
({"detail": "Invalid API token"}, "reviews", []),
("boom", None, []),
({"reviews": None}, "reviews", []),
+ # Endpoints whose envelope AppFollow does not publish pass candidate keys, in order.
+ ({"rankings": [{"a": 1}]}, ("ranks", "rankings"), [{"a": 1}]),
+ ({"ranks": [{"a": 1}], "rankings": [{"b": 2}]}, ("ranks", "rankings"), [{"a": 1}]),
+ # ...and fall back to a root list rather than syncing nothing on a key we guessed wrong.
+ ([{"a": 1}], ("ranks", "rankings"), [{"a": 1}]),
+ ({"detail": "Not enough credits."}, ("ranks", "rankings"), []),
],
)
def test_extract_rows(self, data, key, expected):
@@ -361,3 +375,187 @@ class TestSourceResponse:
assert response.partition_keys == [config.partition_key]
else:
assert response.partition_mode is None
+
+
+class _FanoutApi:
+ """Canned responses for the per-app fan-out endpoints, plus a record of every request made."""
+
+ def __init__(
+ self,
+ collections: list[dict[str, Any]],
+ apps_by_collection: dict[Any, list[dict[str, Any]]],
+ pages: list[list[dict[str, Any]]],
+ envelope: str,
+ ) -> None:
+ self.collections = collections
+ self.apps_by_collection = apps_by_collection
+ self.pages = pages
+ self.envelope = envelope
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def fetch(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> Any:
+ self.calls.append((url, params))
+ if url.endswith("/account/apps/app"):
+ return {"apps_app": self.apps_by_collection.get(params["apps_id"], [])}
+ if url.endswith("/account/apps"):
+ return {"apps": self.collections}
+ page = params.get("page", 1)
+ rows = self.pages[page - 1] if 1 <= page <= len(self.pages) else []
+ return {self.envelope: rows}
+
+
+def _fanout_api(
+ pages: list[list[dict[str, Any]]],
+ envelope: str,
+ collection: dict[str, Any] | None = None,
+ app: dict[str, Any] | None = None,
+) -> _FanoutApi:
+ return _FanoutApi(
+ collections=[collection or {"id": 10, "title_normalized": "team"}],
+ apps_by_collection={10: [app or {"app_id": 1, "ext_id": "111", "store": "gp", "app": {}}]},
+ pages=pages,
+ envelope=envelope,
+ )
+
+
+def _calls_to(api: _FanoutApi, suffix: str) -> list[dict[str, Any]]:
+ return [p for (u, p) in api.calls if u.endswith(suffix)]
+
+
+class TestResolveCountry:
+ @pytest.mark.parametrize(
+ "collection,app,expected",
+ [
+ ({}, {"country": "DE"}, "de"),
+ ({}, {"app": {"country": "fr"}}, "fr"),
+ ({"default_country": "gb"}, {}, "gb"),
+ ({"countries": ["jp", "kr"]}, {}, "jp"),
+ # `/meta/versions` rejects a request with no country, so there is always a last resort.
+ ({}, {}, "us"),
+ ({"default_country": "gb", "countries": ["jp"]}, {"country": "de"}, "de"),
+ ],
+ )
+ def test_resolution_order(self, collection, app, expected):
+ assert _resolve_country(collection, app) == expected
+
+
+class TestSnapshotFanOut:
+ @freeze_time("2026-06-15T09:00:00Z")
+ def test_rankings_requests_today_once_per_app_and_stamps_the_key_fields(self, monkeypatch):
+ # `/meta/rankings` has no pagination and no date range, so one request per app is the whole
+ # walk. `ext_id` and `date` are stamped because the primary key and partition key need them.
+ api = _fanout_api([[{"position": 3, "genre_id": "6003"}]], envelope="ranks")
+ rows = _collect("rankings", _FakeManager(), monkeypatch, api)
+ assert rows == [{"position": 3, "genre_id": "6003", "ext_id": "111", "date": "2026-06-15"}]
+ params = _calls_to(api, "/meta/rankings")
+ assert len(params) == 1
+ assert params[0] == {"ext_id": "111", "date": "2026-06-15"}
+
+ @freeze_time("2026-06-15T09:00:00Z")
+ def test_a_row_that_carries_its_own_date_is_not_overwritten(self, monkeypatch):
+ api = _fanout_api([[{"keyword": "photos", "date": "2026-06-14"}]], envelope="keywords")
+ rows = _collect("keywords", _FakeManager(), monkeypatch, api)
+ assert rows[0]["date"] == "2026-06-14"
+
+ def test_keywords_pages_until_a_page_comes_back_empty(self, monkeypatch):
+ # The endpoint publishes neither a page count nor a total, so an empty page is the only signal.
+ api = _fanout_api([[{"keyword": "a"}], [{"keyword": "b"}]], envelope="keywords")
+ rows = _collect("keywords", _FakeManager(), monkeypatch, api)
+ assert [r["keyword"] for r in rows] == ["a", "b"]
+ assert [p["page"] for p in _calls_to(api, "/aso/keywords")] == [1, 2, 3]
+
+ def test_paging_stops_at_the_cap(self, monkeypatch):
+ # An endpoint that never returns an empty page must not spend credits forever.
+ monkeypatch.setattr(appfollow, "MAX_PAGES_PER_APP", 3)
+ api = _fanout_api([[{"keyword": "a"}]] * 50, envelope="keywords")
+ logger = mock.MagicMock()
+ monkeypatch.setattr(appfollow, "_fetch", api.fetch)
+ monkeypatch.setattr(appfollow, "make_tracked_session", lambda **k: mock.MagicMock())
+ list(
+ get_rows(
+ api_key="tok",
+ endpoint="keywords",
+ logger=logger,
+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]
+ )
+ )
+ assert [p["page"] for p in _calls_to(api, "/aso/keywords")] == [1, 2, 3]
+ assert logger.warning.called
+
+ def test_resume_starts_from_the_saved_page(self, monkeypatch):
+ api = _fanout_api([[{"keyword": "a"}], [{"keyword": "b"}]], envelope="keywords")
+ rows = _collect("keywords", _FakeManager(AppfollowResumeConfig(ext_id="111", cursor=2)), monkeypatch, api)
+ assert [r["keyword"] for r in rows] == ["b"]
+
+
+class TestCountryScopedFanOut:
+ def test_app_versions_sends_and_stamps_the_resolved_country(self, monkeypatch):
+ # `country` is required by the endpoint and is part of the primary key, so it must be both
+ # sent and present on every row.
+ api = _fanout_api(
+ [[{"version": "2.1.0"}]],
+ envelope="versions",
+ collection={"id": 10, "title_normalized": "team", "countries": ["gb"]},
+ )
+ rows = _collect("app_versions", _FakeManager(), monkeypatch, api)
+ assert rows[0] == {"version": "2.1.0", "ext_id": "111", "country": "gb"}
+ assert _calls_to(api, "/meta/versions")[0] == {"ext_id": "111", "country": "gb", "page": 1}
+
+ def test_one_app_tracked_in_two_countries_is_fetched_per_country(self, monkeypatch):
+ # Unlike reviews, versions vary by country, so de-duplicating on ext_id alone would drop data.
+ api = _FanoutApi(
+ collections=[
+ {"id": 10, "title_normalized": "eu", "countries": ["gb"]},
+ {"id": 20, "title_normalized": "us", "countries": ["us"]},
+ ],
+ apps_by_collection={
+ 10: [{"app_id": 1, "ext_id": "111", "store": "as", "app": {}}],
+ 20: [{"app_id": 1, "ext_id": "111", "store": "as", "app": {}}],
+ },
+ pages=[[{"version": "2.1.0"}]],
+ envelope="versions",
+ )
+ _collect("app_versions", _FakeManager(), monkeypatch, api)
+ assert sorted(p["country"] for p in _calls_to(api, "/meta/versions") if p["page"] == 1) == ["gb", "us"]
+
+
+class TestWindowedFanOut:
+ @freeze_time("2026-06-15T09:00:00Z")
+ def test_full_refresh_opens_the_whole_window(self, monkeypatch):
+ api = _fanout_api([[{"date": "2026-06-01", "reviews": 4}]], envelope="stats")
+ _collect(
+ "reviews_stats",
+ _FakeManager(),
+ monkeypatch,
+ api,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=date(2026, 6, 10),
+ )
+ params = _calls_to(api, "/reviews/stats")[0]
+ assert params == {"ext_id": "111", "from": DEFAULT_START_DATE, "to": "2026-06-15"}
+
+ @freeze_time("2026-06-15T09:00:00Z")
+ def test_incremental_sync_moves_from_to_the_watermark(self, monkeypatch):
+ api = _fanout_api([[{"date": "2026-06-11", "reviews": 4}]], envelope="stats")
+ _collect(
+ "reviews_stats",
+ _FakeManager(),
+ monkeypatch,
+ api,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 6, 10),
+ )
+ assert _calls_to(api, "/reviews/stats")[0]["from"] == "2026-06-10"
+
+ @freeze_time("2026-06-15T09:00:00Z")
+ def test_a_future_watermark_is_clamped_so_the_table_cannot_freeze(self, monkeypatch):
+ api = _fanout_api([[{"date": "2026-06-11"}]], envelope="stats")
+ _collect(
+ "reviews_stats",
+ _FakeManager(),
+ monkeypatch,
+ api,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2027, 1, 1),
+ )
+ assert _calls_to(api, "/reviews/stats")[0]["from"] == "2026-06-15"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py
index 357599cdbac3..de56b0cc567c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py
@@ -30,6 +30,12 @@ class TestAppfollowSource:
("users", False, None),
("reviews", True, "updated"),
("ratings_history", True, "date"),
+ # Only reviews_stats among the ASO/statistics endpoints takes a from/to range; rankings,
+ # keywords and app_versions expose no server-side time filter at all.
+ ("reviews_stats", True, "date"),
+ ("rankings", False, None),
+ ("keywords", False, None),
+ ("app_versions", False, None),
],
)
def test_incremental_capability_per_endpoint(self, name, incremental, field):
@@ -50,6 +56,10 @@ class TestAppfollowSource:
("reviews", True),
("users", False),
("ratings_history", False),
+ ("rankings", False),
+ ("keywords", False),
+ ("app_versions", False),
+ ("reviews_stats", False),
],
)
def test_should_sync_defaults(self, name, default_sync):
@@ -66,6 +76,10 @@ class TestAppfollowSource:
# Fan-out children must include the parent id so keys stay unique table-wide.
("reviews", ["ext_id", "review_id"]),
("ratings_history", ["ext_id", "store", "date"]),
+ ("rankings", ["ext_id", "country", "device", "genre_id", "date"]),
+ ("keywords", ["ext_id", "country", "device", "date", "keyword"]),
+ ("app_versions", ["ext_id", "country", "version"]),
+ ("reviews_stats", ["ext_id", "date"]),
],
)
def test_primary_keys_are_unique_table_wide(self, name, primary_keys):