: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 Appfigures ranks, subscriptions, ratings and lookup tables (#98313)
Tom Owers8dcc6d0e7609
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 61ccd39d8580..cb2d8a1f0df3 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@@ -375,14 +375,14 @@ Note: docs.appdynamics.com now serves an SPA shell and presents a broken TLS cha## Appfigures — gaps-Today (4): `products`, `revenue_report`, `reviews`, `sales_report`+Today (10): `categories`, `countries`, `products`, `ranks`, `ratings_report`, `revenue_report`, `reviews`, `sales_report`, `stores`, `subscriptions_report`Diffed against: <https://docs.appfigures.com/api/reference/v2>-- [ ] `/ranks` — app store category rank history — the vendor's headline ASO metric (high)-- [ ] `/reports/subscriptions` — subscription metrics (new, renewals, churn) that sales/revenue reports do not break out (high)-- [ ] `/reports/ratings` — rating counts and averages over time, the current supported replacement for /ratings (high)-- [ ] `/data/stores, /data/categories, /data/countries` — lookup tables resolving the store, category and country codes on every synced report row (high)+- [x] `/ranks` — app store category rank history — the vendor's headline ASO metric (high)+- [x] `/reports/subscriptions` — subscription metrics (new, renewals, churn) that sales/revenue reports do not break out (high)+- [x] `/reports/ratings` — rating counts and averages over time, the current supported replacement for /ratings (high)+- [x] `/data/stores, /data/categories, /data/countries` — lookup tables resolving the store, category and country codes on every synced report row (high)- [ ] `/aso (keyword ranks and stats)` — tracked keyword positions, the other half of the ASO story with /ranks (high)- [ ] `/reports/adspend` — campaign spend by network, needed for ROAS against revenue_report (medium)- [ ] `/reports/ads` — ad publishing revenue by network, a revenue stream missing from sales_report (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.pyindex cddb2f6d87f4..efde3616eab4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py@@ -1,4 +1,5 @@import dataclasses+from collections import defaultdictfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional@@ -23,6 +24,11 @@ APPFIGURES_BASE_URL = "https://api.appfigures.com/v2"# advance from the stored date watermark.REPORT_BACKFILL_DAYS = 365+# /ranks needs product ids in its path, so the fan-out reads the account catalog first. In-app+# purchases never hold a store category rank, so they are left out of the request.+PRODUCTS_PATH = "/products/mine"+NON_RANKABLE_PRODUCT_TYPES = frozenset({"inapp"})+class AppfiguresRetryableError(Exception):pass@@ -181,6 +187,24 @@ def _iter_paged(manager.save_state(AppfiguresResumeConfig(next_page=page))+def _initial_window_start(+ manager: ResumableSourceManager[AppfiguresResumeConfig],+ today: date,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> date:+ """Where a date-windowed walk picks up: saved resume state, then the incremental watermark, then+ the backfill horizon."""+ resume = manager.load_state() if manager.can_resume() else None+ if resume and resume.window_start:+ return date.fromisoformat(resume.window_start)+ if should_use_incremental_field and db_incremental_field_last_value:+ last = _to_date_str(db_incremental_field_last_value)+ if last:+ return date.fromisoformat(last)+ return today - timedelta(days=REPORT_BACKFILL_DAYS)++def _flatten_report(data: Any) -> list[dict[str, Any]]:"""Turn a group_by=dates report body ({"2024-01-01": {..metrics..}, ...}) into dated rows.@@ -209,14 +233,7 @@ def _iter_report(today = datetime.now(UTC).date()window_days = config.window_days or 30- resume = manager.load_state() if manager.can_resume() else None- if resume and resume.window_start:- window_start = date.fromisoformat(resume.window_start)- elif should_use_incremental_field and db_incremental_field_last_value:- last = _to_date_str(db_incremental_field_last_value)- window_start = date.fromisoformat(last) if last else today - timedelta(days=REPORT_BACKFILL_DAYS)- else:- window_start = today - timedelta(days=REPORT_BACKFILL_DAYS)+ window_start = _initial_window_start(manager, today, should_use_incremental_field, db_incremental_field_last_value)url = f"{APPFIGURES_BASE_URL}{config.path}"while window_start <= today:@@ -240,6 +257,113 @@ def _iter_report(manager.save_state(AppfiguresResumeConfig(window_start=window_start.isoformat()))+def _flatten_ranks(data: Any) -> list[dict[str, Any]]:+ """Turn a columnar /ranks body into one row per product, country, category, and date.++ The body holds a `dates` array plus a series per product/country/category whose `positions` and+ `deltas` arrays line up with it by index.+ """+ if not isinstance(data, dict):+ return []+ dates = data.get("dates") or []+ rows: list[dict[str, Any]] = []+ for series in data.get("data") or []:+ if not isinstance(series, dict):+ continue+ category = series.get("category") or {}+ positions = series.get("positions") or []+ deltas = series.get("deltas") or []+ for index, day in enumerate(dates):+ position = positions[index] if index < len(positions) else None+ # A null position means the product held no rank in that chart that day. The default rank+ # depth makes that the common case, so skipping keeps the table to real observations.+ if position is None:+ continue+ rows.append(+ {+ "date": day,+ "product_id": series.get("product_id"),+ "country": series.get("country"),+ "category_id": category.get("id"),+ "category_name": category.get("name"),+ "category_subtype": category.get("subtype"),+ "category_parent_id": category.get("parent_id"),+ "category_device": category.get("device"),+ "store": category.get("store"),+ "position": position,+ # Appfigures documents this delta as the change from the prior hour even at daily+ # granularity, so it is not a day-over-day move.+ "delta": deltas[index] if index < len(deltas) else None,+ }+ )+ return rows+++def _rankable_product_ids(+ session: requests.Session,+ logger: FilteringBoundLogger,+) -> list[str]:+ data = _fetch(session, f"{APPFIGURES_BASE_URL}{PRODUCTS_PATH}", {}, logger)+ products = data.values() if isinstance(data, dict) else data or []+ ids = {+ str(product["id"])+ for product in products+ if isinstance(product, dict)+ and product.get("id") is not None+ and product.get("type") not in NON_RANKABLE_PRODUCT_TYPES+ }+ # Sorted so the request chunks are stable across syncs and resumes.+ return sorted(ids)+++def _iter_ranks(+ session: requests.Session,+ config: AppfiguresEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppfiguresResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """/ranks, fanned out over the account's products in chunks and walked in date windows."""+ product_ids = _rankable_product_ids(session, logger)+ if not product_ids:+ logger.info("Appfigures: account has no rankable products, skipping ranks")+ return++ chunk_size = config.products_per_request+ chunks = [product_ids[index : index + chunk_size] for index in range(0, len(product_ids), chunk_size)]++ today = datetime.now(UTC).date()+ window_days = config.window_days or 30++ window_start = _initial_window_start(manager, today, should_use_incremental_field, db_incremental_field_last_value)++ while window_start <= today:+ window_end = min(window_start + timedelta(days=window_days - 1), today)++ # Collect the whole window across product chunks before yielding, so rows still leave this+ # iterator in ascending date order and the incremental watermark checkpoints correctly.+ rows_by_date: dict[str, list[dict[str, Any]]] = defaultdict(list)+ for chunk in chunks:+ url = (+ f"{APPFIGURES_BASE_URL}{config.path}/{','.join(chunk)}/{config.granularity}"+ f"/{window_start.isoformat()}/{window_end.isoformat()}"+ )+ for row in _flatten_ranks(_fetch(session, url, {}, logger)):+ rows_by_date[row["date"]].append(row)++ for day in sorted(rows_by_date):+ yield rows_by_date[day]++ if window_end >= today:+ break++ window_start = window_end + timedelta(days=1)+ # Save AFTER yielding the window so a crash re-fetches it rather than skipping; merge dedupes+ # the re-pulled rows on the primary key.+ manager.save_state(AppfiguresResumeConfig(window_start=window_start.isoformat()))++def get_rows(token: str,endpoint: str,@@ -262,6 +386,15 @@ def get_rows(should_use_incremental_field,db_incremental_field_last_value,)+ elif config.kind == "ranks":+ yield from _iter_ranks(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )else: # "report"yield from _iter_report(session,@@ -299,7 +432,8 @@ def appfigures_source(partition_mode="datetime" if config.partition_key else None,partition_format="month" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,- # Reviews are paged ascending by `date`; reports are emitted oldest-window-first. Both arrive- # in ascending order so the incremental watermark checkpoints correctly.+ # Reviews are paged ascending by `date`; reports and ranks are emitted oldest-window-first,+ # ranks buffering each window so its product chunks merge back into date order. All arrive+ # ascending so the incremental watermark checkpoints correctly.sort_mode="asc",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.pyindex 7844f584279d..52cefd1aacd1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py@@ -69,4 +69,118 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"gross_revenue": "Revenue before store commission.",},},+ "subscriptions_report": {+ "description": "Daily subscription report aggregated across the account — active subscriptions, trials, activations, renewals, cancellations, churn, and MRR, one row per day.",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/subscriptions",+ "columns": {+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",+ "all_active_subscriptions": "Every active subscription on the day, including free trials.",+ "active_subscriptions": "Active paid subscriptions on the day.",+ "active_free_trials": "Subscriptions in a free trial on the day.",+ "paying_subscriptions": "Subscriptions that were being paid for on the day.",+ "actual_revenue": "Revenue actually collected on the day.",+ "mrr": "Monthly recurring revenue, net of store commission.",+ "gross_mrr": "Monthly recurring revenue before store commission.",+ "gross_revenue": "Revenue collected on the day before store commission.",+ "activations": "Subscriptions that became active on the day.",+ "cancellations": "Subscriptions that were cancelled on the day.",+ "churn": "Calculated churn rate for the day, as a percentage.",+ "new_subscriptions": "Subscriptions started for the first time on the day.",+ "cancelled_subscriptions": "Subscriptions whose cancellation took effect on the day.",+ "renewals": "Subscriptions that renewed on the day.",+ "reactivations": "Previously cancelled subscriptions that restarted on the day.",+ "new_trials": "Free trials started on the day.",+ "active_trials": "Free trials running on the day.",+ "cancelled_trials": "Free trials cancelled on the day.",+ "trial_conversions": "Free trials that converted to a paid subscription on the day.",+ "transitions_in": "Subscriptions that moved into this group from another plan.",+ "transitions_out": "Subscriptions that moved out of this group to another plan.",+ "first_year_subscribers": "Subscribers in their first year, so the store takes the higher commission. Apple platforms only.",+ "non_first_year_subscribers": "Subscribers past their first year, so the store takes the lower commission. Apple platforms only.",+ "active_discounted_subscriptions": "Active subscriptions on a promotional or discounted price.",+ "active_grace": "Subscriptions in billing grace period on the day.",+ "new_grace": "Subscriptions that entered billing grace period on the day.",+ "grace_drop_off": "Subscriptions that lapsed out of grace period without recovering.",+ "grace_recovery": "Subscriptions that recovered from grace period back to paying.",+ "new_trial_grace": "Free trials that entered grace period on the day.",+ "trial_grace_drop_off": "Free trials that lapsed out of grace period without recovering.",+ "trial_grace_recovery": "Free trials that recovered from grace period.",+ },+ },+ "ratings_report": {+ "description": "Daily ratings report aggregated across the account — rating counts, averages, and star distribution, one row per day. Replaces the deprecated /ratings resource.",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/ratings",+ "columns": {+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",+ "breakdown": "Five-element array of rating counts standing on the last day of the period, where index 0 is one star and index 4 is five stars.",+ "new": "Five-element array of ratings added during the period, where index 0 is one star and index 4 is five stars.",+ "average": "Average of all ratings standing at the end of the period.",+ "total": "Total number of ratings standing at the end of the period.",+ "new_average": "Average of the ratings added during the period.",+ "new_total": "Number of ratings added during the period.",+ "positive": "Standing ratings counted as positive (four and five stars).",+ "negative": "Standing ratings counted as negative (one and two stars).",+ "neutral": "Standing ratings counted as neutral (three stars).",+ "new_positive": "Ratings added during the period counted as positive.",+ "new_negative": "Ratings added during the period counted as negative.",+ "new_neutral": "Ratings added during the period counted as neutral.",+ "one_star_percent": "Share of standing ratings that are one star.",+ "two_star_percent": "Share of standing ratings that are two stars.",+ "three_star_percent": "Share of standing ratings that are three stars.",+ "four_star_percent": "Share of standing ratings that are four stars.",+ "five_star_percent": "Share of standing ratings that are five stars.",+ },+ },+ "ranks": {+ "description": "Store category rank history, one row per product, country, category chart, and day. Rows are only written for days the product actually held a rank, and cover the country Appfigures returns by default (the United States).",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/ranks",+ "columns": {+ "date": "Calendar day the rank was observed (yyyy-mm-dd).",+ "product_id": "Appfigures product id the rank belongs to. Joins to products.id.",+ "country": "ISO code of the storefront the rank was observed in. Joins to countries.iso.",+ "category_id": "Id of the store category chart. Joins to categories.id.",+ "category_name": "Name of the store category chart.",+ "category_subtype": "Which chart within the category the rank is from: free, paid, or topgrossing.",+ "category_parent_id": "Id of the parent category, or null for a top-level category.",+ "category_device": "Device the category chart applies to (for example ios, android).",+ "store": "Name of the store the category belongs to. Joins to stores.name.",+ "position": "Rank position, where 1 is the top of the chart.",+ "delta": "Change in position that Appfigures reports alongside the rank. Appfigures measures this against the prior hour even at daily granularity, so it is not a day-over-day move.",+ },+ },+ "stores": {+ "description": "Reference table of the stores Appfigures supports, with the features and storefronts each one offers. Resolves the store codes on products and ranks.",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/data",+ "columns": {+ "id": "Numeric id of the store.",+ "code": "Short code identifying the store.",+ "name": "Full name of the store.",+ "short_name": "Abbreviated store name.",+ "type": "Kind of store entry, such as store or storefront.",+ "supported_features": "Data sets the store supports, such as sales, ads, reviews, ranks, and featured.",+ "storefronts": "Storefronts within the store, each with its own id, name, short_name, and type.",+ "countries": "Countries the store operates in, each with iso, name, and apple_store_no.",+ },+ },+ "categories": {+ "description": "Reference table of store category charts. Resolves the category ids on rank rows.",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/data",+ "columns": {+ "id": "Id of the category.",+ "store": "Store the category belongs to.",+ "device": "Device the category applies to.",+ "subcategories": "Charts available within the category: free, paid, and topgrossing.",+ "parent_id": "Id of the parent category, or null for a top-level category.",+ "name": "Name of the category.",+ },+ },+ "countries": {+ "description": "Reference table of countries Appfigures reports on. Resolves the ISO codes on reviews, reports, and rank rows.",+ "docs_url": "https://docs.appfigures.com/api/reference/v2/data",+ "columns": {+ "iso": "Two-letter ISO code of the country.",+ "name": "Full country name.",+ "apple_store_no": "Apple storefront number for the country, or an empty string where Apple has no storefront.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.pyindex bc6a3462868c..f630ec62081c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py@@ -1,6 +1,8 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Three response/pagination shapes Appfigures exposes:@@ -11,10 +13,13 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# - "report": /reports/* — a single response that's a JSON object keyed by date (group_by=dates),# with a `start_date`/`end_date` server-side window and per-granularity range caps, so# we walk it in fixed-size date windows. Incremental by date window.-EndpointKind = Literal["paged", "object", "report"]+# - "ranks": /ranks — a columnar response (a `dates` array plus one series per product/country/+# category holding position/delta arrays) whose product ids and date range live in the+# URL path, so we fan out over the account's products in chunks and walk date windows.+EndpointKind = Literal["paged", "object", "report", "ranks"]-@dataclass+@frozenclass AppfiguresEndpointConfig:name: strpath: str@@ -25,6 +30,9 @@ class AppfiguresEndpointConfig:# Stable creation-style field to partition by — never an updated/last-seen field.partition_key: Optional[str] = Noneshould_sync_default: bool = True+ # Endpoint to probe when validating the token's scope for this schema. Defaults to `path`; set it+ # where `path` carries placeholders and so can't be requested as-is.+ probe_path: Optional[str] = None# "paged" endpoints (reviews)# Body key the page's rows live under (e.g. {"total":..,"reviews":[...]}).@@ -41,6 +49,11 @@ class AppfiguresEndpointConfig:# Max days fetched per request — daily granularity is capped at 30 days by Appfigures.window_days: Optional[int] = None+ # "ranks" endpoints+ # How many product ids to put in one /ranks path. Appfigures caps products x date range per+ # request, so keep chunks well inside it rather than sending the whole catalog.+ products_per_request: int = 20+# `date` on reviews is a full timestamp (e.g. 2017-05-19T17:05:00); on reports it's a day string._REVIEW_DATE_FIELD: IncrementalField = {@@ -109,6 +122,70 @@ APPFIGURES_ENDPOINTS: dict[str, AppfiguresEndpointConfig] = {default_incremental_field="date",incremental_fields=[_REPORT_DATE_FIELD],),+ # Daily subscription metrics (activations, renewals, churn, MRR) aggregated across the account.+ "subscriptions_report": AppfiguresEndpointConfig(+ name="subscriptions_report",+ path="/reports/subscriptions",+ kind="report",+ primary_keys=["date"],+ group_by="dates",+ granularity="daily",+ window_days=30,+ partition_key="date",+ default_incremental_field="date",+ incremental_fields=[_REPORT_DATE_FIELD],+ ),+ # Daily rating counts and averages across the account. The supported replacement for /ratings.+ "ratings_report": AppfiguresEndpointConfig(+ name="ratings_report",+ path="/reports/ratings",+ kind="report",+ primary_keys=["date"],+ group_by="dates",+ granularity="daily",+ window_days=30,+ partition_key="date",+ default_incremental_field="date",+ incremental_fields=[_REPORT_DATE_FIELD],+ ),+ # Store category rank history per product, country, and category.+ "ranks": AppfiguresEndpointConfig(+ name="ranks",+ path="/ranks",+ kind="ranks",+ # A category id repeats across its free/paid/topgrossing charts, so the subtype is part of+ # what makes a rank observation unique.+ primary_keys=["date", "product_id", "country", "category_id", "category_subtype"],+ granularity="daily",+ window_days=30,+ partition_key="date",+ default_incremental_field="date",+ incremental_fields=[_REPORT_DATE_FIELD],+ # /ranks takes its product ids in the path, so there is no cheap request to probe. Ranks and+ # reviews both need `public:read`, so probing reviews checks the same grant.+ probe_path="/reviews",+ ),+ # Store metadata resolving the `store` / `store_id` codes on products and rank rows.+ "stores": AppfiguresEndpointConfig(+ name="stores",+ path="/data/stores",+ kind="object",+ primary_keys=["id"],+ ),+ # Category metadata resolving the `category_id` on rank rows.+ "categories": AppfiguresEndpointConfig(+ name="categories",+ path="/data/categories",+ kind="object",+ primary_keys=["id"],+ ),+ # Country metadata resolving the ISO codes on reviews, reports, and rank rows.+ "countries": AppfiguresEndpointConfig(+ name="countries",+ path="/data/countries",+ kind="object",+ primary_keys=["iso"],+ ),}ENDPOINTS = tuple(APPFIGURES_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.pyindex b483266d6350..6969d0635cf5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py@@ -10,6 +10,7 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures import (+ PRODUCTS_PATH,AppfiguresResumeConfig,appfigures_source,check_credentials,@@ -56,8 +57,10 @@ class AppfiguresSource(ResumableSource[AppfiguresSourceConfig, AppfiguresResumeCCreate an API client and Personal Access Token at [appfigures.com/developers/keys](https://appfigures.com/developers/keys). When creating the client, grant the data sets you want to sync:- `products:read` — Products-- `public:read` — Reviews-- `private:read` — Sales and Revenue reports+- `public:read` — Reviews, Ranks, Ratings report+- `private:read` — Sales, Revenue, and Subscriptions reports++Stores, Categories, and Countries are reference tables that need no data set granted.""",iconPath="/static/services/appfigures.png",docsUrl="https://posthog.com/docs/cdp/sources/appfigures",@@ -130,9 +133,10 @@ Create an API client and Personal Access Token at [appfigures.com/developers/key) -> tuple[bool, str | None]:# Probe the endpoint the requested schema actually hits (so per-table scope checks are# accurate), or the cheap products catalog at source-create.- path = "/products/mine"+ path = PRODUCTS_PATHif schema_name and schema_name in APPFIGURES_ENDPOINTS:- path = APPFIGURES_ENDPOINTS[schema_name].path+ endpoint_config = APPFIGURES_ENDPOINTS[schema_name]+ path = endpoint_config.probe_path or endpoint_config.pathstatus = check_credentials(config.personal_access_token, path)if status is None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.pyindex 01eaef2f862e..14ab24e4e644 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py@@ -1,3 +1,4 @@+import dataclassesfrom datetime import UTC, date, datetimefrom typing import Any@@ -8,6 +9,7 @@ from unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.appfigures import appfiguresfrom products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures import (AppfiguresResumeConfig,+ _flatten_ranks,_flatten_report,_headers,_is_page_limit_response,@@ -264,6 +266,206 @@ class TestIterReport:assert fetch.call_args_list[0].args[2]["start_date"] == "2024-02-10"+def _ranks_body(dates: list[str], series: list[dict[str, Any]]) -> dict[str, Any]:+ return {"start_date": dates[0], "end_date": dates[-1], "dates": dates, "data": series}+++class TestFlattenRanks:+ def test_columnar_series_becomes_one_row_per_date(self):+ body = _ranks_body(+ ["2024-01-01", "2024-01-02"],+ [+ {+ "country": "US",+ "product_id": 42,+ "category": {+ "id": 12,+ "name": "Games",+ "subtype": "free",+ "parent_id": 6000,+ "device": "ios",+ "store": "apple",+ },+ "positions": [7, 9],+ "deltas": [0, -2],+ }+ ],+ )+ assert _flatten_ranks(body) == [+ {+ "date": "2024-01-01",+ "product_id": 42,+ "country": "US",+ "category_id": 12,+ "category_name": "Games",+ "category_subtype": "free",+ "category_parent_id": 6000,+ "category_device": "ios",+ "store": "apple",+ "position": 7,+ "delta": 0,+ },+ {+ "date": "2024-01-02",+ "product_id": 42,+ "country": "US",+ "category_id": 12,+ "category_name": "Games",+ "category_subtype": "free",+ "category_parent_id": 6000,+ "category_device": "ios",+ "store": "apple",+ "position": 9,+ "delta": -2,+ },+ ]++ def test_unranked_days_are_dropped(self):+ # Appfigures returns null for a day the product held no rank in that chart. Those aren't rank+ # observations, and at the default rank depth they are most of the array.+ body = _ranks_body(+ ["2024-01-01", "2024-01-02", "2024-01-03"],+ [+ {+ "country": "US",+ "product_id": 1,+ "category": {"id": 12},+ "positions": [None, 3, None],+ "deltas": [None, 1, None],+ }+ ],+ )+ rows = _flatten_ranks(body)+ assert [(r["date"], r["position"]) for r in rows] == [("2024-01-02", 3)]++ def test_series_arrays_shorter_than_dates_do_not_index_error(self):+ body = _ranks_body(+ ["2024-01-01", "2024-01-02"],+ [{"country": "US", "product_id": 1, "category": {"id": 12}, "positions": [4], "deltas": []}],+ )+ rows = _flatten_ranks(body)+ assert [(r["date"], r["position"], r["delta"]) for r in rows] == [("2024-01-01", 4, None)]++ @pytest.mark.parametrize("body", [None, [], {"dates": ["2024-01-01"]}, {"data": [{"positions": [1]}]}])+ def test_missing_or_malformed_body_returns_empty(self, body: Any):+ assert _flatten_ranks(body) == []+++class TestIterRanks:+ @freeze_time("2024-02-15")+ def test_fans_out_over_product_chunks_and_yields_dates_ascending(self):+ products = {str(index): {"id": index, "type": "app"} for index in range(1, 4)}+ # An in-app purchase never holds a store category rank, so it must not reach the /ranks path.+ products["999"] = {"id": 999, "type": "inapp"}++ ranks_calls: list[str] = []++ def fake_fetch(_session, url, _params, _logger):+ if url.endswith(appfigures.PRODUCTS_PATH):+ return products+ ranks_calls.append(url)+ chunk = url.split("/ranks/")[1].split("/")[0].split(",")+ return _ranks_body(+ ["2024-02-14", "2024-02-15"],+ [+ {+ "country": "US",+ "product_id": int(product_id),+ "category": {"id": 12, "subtype": "free"},+ "positions": [2, 1],+ "deltas": [0, 1],+ }+ for product_id in chunk+ ],+ )++ chunked = dataclasses.replace(appfigures.APPFIGURES_ENDPOINTS["ranks"], products_per_request=2)+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):+ with mock.patch.dict(appfigures.APPFIGURES_ENDPOINTS, {"ranks": chunked}):+ batches = list(+ get_rows(+ token="pat",+ endpoint="ranks",+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 2, 14),+ )+ )++ # Three rankable products at 2 per request => two chunked /ranks calls for the one window.+ assert ranks_calls == [+ f"{appfigures.APPFIGURES_BASE_URL}/ranks/1,2/daily/2024-02-14/2024-02-15",+ f"{appfigures.APPFIGURES_BASE_URL}/ranks/3/daily/2024-02-14/2024-02-15",+ ]+ # Batches leave the iterator grouped by date, ascending, with every chunk's rows merged in —+ # sort_mode="asc" is what checkpoints the watermark.+ assert [batch[0]["date"] for batch in batches] == ["2024-02-14", "2024-02-15"]+ assert [sorted(row["product_id"] for row in batch) for batch in batches] == [[1, 2, 3], [1, 2, 3]]++ @freeze_time("2024-02-15")+ def test_walks_date_windows_and_saves_state_after_each(self):+ windows: list[tuple[str, str]] = []++ def fake_fetch(_session, url, _params, _logger):+ if url.endswith(appfigures.PRODUCTS_PATH):+ return {"1": {"id": 1, "type": "app"}}+ _, _, start, end = url.split("/ranks/")[1].split("/")+ windows.append((start, end))+ return _ranks_body(+ [start], [{"country": "US", "product_id": 1, "category": {"id": 12}, "positions": [5], "deltas": [0]}]+ )++ manager = _manager()+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):+ list(+ get_rows(+ token="pat",+ endpoint="ranks",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 1, 1),+ )+ )++ assert windows == [("2024-01-01", "2024-01-30"), ("2024-01-31", "2024-02-15")]+ manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))++ @freeze_time("2024-02-15")+ def test_resume_starts_from_saved_window(self):+ starts: list[str] = []++ def fake_fetch(_session, url, _params, _logger):+ if url.endswith(appfigures.PRODUCTS_PATH):+ return {"1": {"id": 1, "type": "app"}}+ starts.append(url.split("/ranks/")[1].split("/")[2])+ return {}++ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):+ list(+ get_rows(+ token="pat",+ endpoint="ranks",+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(AppfiguresResumeConfig(window_start="2024-02-10")),+ )+ )+ assert starts == ["2024-02-10"]++ def test_account_with_no_rankable_products_makes_no_ranks_request(self):+ def fake_fetch(_session, url, _params, _logger):+ assert url.endswith(appfigures.PRODUCTS_PATH)+ return {"999": {"id": 999, "type": "inapp"}}++ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:+ batches = list(+ get_rows(token="pat", endpoint="ranks", logger=mock.MagicMock(), resumable_source_manager=_manager())+ )+ assert batches == []+ assert fetch.call_count == 1++class TestCheckCredentials:@pytest.mark.parametrize("status", [200, 401, 403, 500])def test_returns_status_code(self, status):@@ -287,6 +489,11 @@ class TestAppfiguresSourceResponse:("reviews", ["id"], "date"),("sales_report", ["date"], "date"),("revenue_report", ["date"], "date"),+ ("ranks", ["date", "product_id", "country", "category_id", "category_subtype"], "date"),+ # The /data lookups carry no date field, so they sync unpartitioned.+ ("stores", ["id"], None),+ ("categories", ["id"], None),+ ("countries", ["iso"], None),],)def test_response_shape(self, endpoint, primary_keys, partition_key):@@ -298,8 +505,8 @@ class TestAppfiguresSourceResponse:)assert response.name == endpointassert response.primary_keys == primary_keys- assert response.partition_mode == "datetime"- assert response.partition_keys == [partition_key]+ assert response.partition_mode == ("datetime" if partition_key else None)+ assert response.partition_keys == ([partition_key] if partition_key else None)assert response.sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.pyindex 1f2461fe9b5c..7affd5f35087 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py@@ -22,11 +22,13 @@ class TestAppfiguresSource:schemas = self.source.get_schemas(self.config, self.team_id)assert {s.name for s in schemas} == set(ENDPOINTS)- def test_products_is_full_refresh_reports_and_reviews_incremental(self):+ def test_catalog_and_lookup_tables_are_full_refresh_dated_tables_incremental(self):schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}- assert schemas["products"].supports_incremental is False- assert schemas["products"].incremental_fields == []- for name in ("reviews", "sales_report", "revenue_report"):+ # The product catalog and the /data lookups have no server-side date filter to drive.+ for name in ("products", "stores", "categories", "countries"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []+ for name in ("reviews", "sales_report", "revenue_report", "subscriptions_report", "ratings_report", "ranks"):assert schemas[name].supports_incremental is Trueassert [f["field"] for f in schemas[name].incremental_fields] == ["date"]@@ -61,13 +63,22 @@ class TestAppfiguresSource:ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)assert ok is expected_ok- def test_validate_credentials_probes_schema_specific_path(self):+ @pytest.mark.parametrize(+ "schema_name,expected_path",+ [+ ("reviews", "/reviews"),+ # /ranks takes product ids in its path, so it can't be requested as-is. It shares the+ # `public:read` grant with reviews, so reviews is what gets probed.+ ("ranks", "/reviews"),+ ],+ )+ def test_validate_credentials_probes_schema_specific_path(self, schema_name: str, expected_path: str):with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",return_value=200,) as probe:- self.source.validate_credentials(self.config, self.team_id, schema_name="reviews")- probe.assert_called_once_with("pat_test", "/reviews")+ self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ probe.assert_called_once_with("pat_test", expected_path)def test_validate_credentials_defaults_to_products_path(self):with mock.patch(