: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(coinmarketcap): add historical and metadata warehouse tables (#103352)
Tom Owers630f5cb7bd39
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 ff3a77f64096..4c77a60b0767 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@@ -1881,14 +1881,14 @@ Note: docs.coingecko.com/reference/\* pages are client-rendered and unparseable## CoinMarketCap — gaps-Today (5): `categories`, `cryptocurrency_map`, `exchange_map`, `fiat_map`, `listings_latest`+Today (9): `categories`, `cryptocurrency_info`, `cryptocurrency_map`, `exchange_map`, `fiat_map`, `global_metrics_quotes_historical`, `listings_latest`, `ohlcv_historical`, `quotes_historical`Diffed against: <https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency.md>-- [ ] `GET /v3/cryptocurrency/quotes/historical` — historical price, market cap and volume per coin - the core fact table; today only listings/latest snapshots exist (high)-- [ ] `GET /v2/cryptocurrency/ohlcv/historical` — daily OHLCV candles, required for any price or return analysis (high)-- [ ] `GET /v1/global-metrics/quotes/historical` — total market cap, BTC dominance and altcoin market cap over time - CMC's headline market metric (high)-- [ ] `GET /v2/cryptocurrency/info` — coin metadata (tags, platform, category, urls) that resolves the ids in the cryptocurrency_map we already sync (high)+- [x] `GET /v3/cryptocurrency/quotes/historical` — historical price, market cap and volume per coin - the core fact table; today only listings/latest snapshots exist (high)+- [x] `GET /v2/cryptocurrency/ohlcv/historical` — daily OHLCV candles, required for any price or return analysis (high)+- [x] `GET /v1/global-metrics/quotes/historical` — total market cap, BTC dominance and altcoin market cap over time - CMC's headline market metric (high)+- [x] `GET /v2/cryptocurrency/info` — coin metadata (tags, platform, category, urls) that resolves the ids in the cryptocurrency_map we already sync (high)- [ ] `GET /v1/exchange/listings/latest` — ranked exchanges with volume and liquidity; exchange_map alone carries no metrics (high)- [ ] `GET /v1/exchange/info` — exchange metadata lookup resolving the ids in the synced exchange_map (medium)- [ ] `GET /v1/cryptocurrency/listings/historical` — historical ranked snapshots, letting you reconstruct rank changes without polling listings/latest (medium)@@ -1898,7 +1898,7 @@ Diffed against: <https://pro.coinmarketcap.com/api/documentation/pro-api-referen- [ ] `GET /v1/cryptocurrency/category` — coin membership per category - the categories table we sync lists categories but not their constituents (medium)- [ ] `GET /v3/fear-and-greed/historical` — CMC's proprietary sentiment index over time, a commonly requested signal (medium)-Note: coinmarketcap.com/api/documentation is a client-rendered zudoku app, but every page is served as markdown by appending .md, and pro.coinmarketcap.com/llms.txt indexes the whole reference by family (Cryptocurrency 19, Exchange 7, Global Metrics 6, DEX/Token 16, Holder 5, Derivatives 3, RWA 7, CMC Index 4...). PostHog's five tables are all lookup/snapshot endpoints; every historical family is absent. The DEX (Token/Pool/Holder/OHLCV) and Real World Assets families are also entirely uncovered but are treated as separate products rather than enumerated here.+Note: coinmarketcap.com/api/documentation is a client-rendered zudoku app, but every page is served as markdown by appending .md, and pro.coinmarketcap.com/llms.txt indexes the whole reference by family (Cryptocurrency 19, Exchange 7, Global Metrics 6, DEX/Token 16, Holder 5, Derivatives 3, RWA 7, CMC Index 4...). The cryptocurrency and global-metrics historical families are now covered; the exchange historical family is not. The DEX (Token/Pool/Holder/OHLCV) and Real World Assets families are also entirely uncovered but are treated as separate products rather than enumerated here.## Commercetools — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.pyindex 9a4de481c794..a2ecf98210dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py@@ -80,4 +80,69 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_historical_data": "Timestamp (ISO 8601) of the latest market data record available for this exchange.",},},+ "cryptocurrency_info": {+ "description": "Static metadata for each cryptocurrency: category, tags, platform, description and resource URLs.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency/metadata.md",+ "columns": {+ "id": "The unique CoinMarketCap ID for this cryptocurrency.",+ "name": "The name of this cryptocurrency.",+ "symbol": "The ticker symbol for this cryptocurrency.",+ "category": "The category for this cryptocurrency: coin or token.",+ "slug": "The web URL friendly shorthand version of this cryptocurrency name.",+ "logo": "Link to a CoinMarketCap hosted logo png for this cryptocurrency.",+ "description": "A CoinMarketCap supplied brief description of this cryptocurrency.",+ "date_added": "Timestamp (ISO 8601) of when this cryptocurrency was added to CoinMarketCap.",+ "date_launched": "Timestamp (ISO 8601) of when this cryptocurrency was launched.",+ "notice": "A Markdown formatted notice highlighting a significant event or condition affecting this cryptocurrency, otherwise null.",+ "tags": "Tags associated with this cryptocurrency.",+ "platform": "Metadata about the parent cryptocurrency platform this is a token on, if any.",+ "self_reported_circulating_supply": "The self reported number of coins circulating for this cryptocurrency.",+ "self_reported_market_cap": "The self reported market cap for this cryptocurrency.",+ "self_reported_tags": "Self reported tags associated with this cryptocurrency.",+ "infinite_supply": "True if this cryptocurrency is known to have an infinite supply.",+ "urls": "Resource URLs for this cryptocurrency: website, technical doc, explorer, source code, message board, chat, announcement, reddit and twitter.",+ },+ },+ "quotes_historical": {+ "description": "Historical daily price, 24 hour volume and market cap for the highest-ranked cryptocurrencies by market cap. One row per cryptocurrency per interval.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency/quotes-historical.md",+ "columns": {+ "id": "The CoinMarketCap cryptocurrency ID this quote belongs to.",+ "name": "The cryptocurrency name.",+ "symbol": "The cryptocurrency symbol.",+ "is_active": "1 if this cryptocurrency has at least one active market currently being tracked, otherwise 0.",+ "is_fiat": "1 if this is a fiat currency, otherwise 0.",+ "timestamp": "Timestamp (ISO 8601) of when this historical quote was recorded.",+ "search_interval": "The interval timestamp for the search period that this historical quote was located against.",+ "quote": "Market details for this interval by currency conversion (default USD): price, volume_24hr, market_cap, circulating_supply, total_supply and the conversion timestamp.",+ },+ },+ "ohlcv_historical": {+ "description": "Historical daily OHLCV (open, high, low, close, volume) candles and market cap for the highest-ranked cryptocurrencies by market cap. One row per cryptocurrency per interval.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency/ohlcv-historical.md",+ "columns": {+ "id": "The CoinMarketCap cryptocurrency ID this candle belongs to.",+ "name": "The cryptocurrency name.",+ "symbol": "The cryptocurrency symbol.",+ "time_open": "Timestamp (ISO 8601) of the start of this time series interval.",+ "time_close": "Timestamp (ISO 8601) of the end of this time series interval.",+ "time_high": "Timestamp (ISO 8601) of the high of this time series interval.",+ "time_low": "Timestamp (ISO 8601) of the low of this time series interval.",+ "quote": "Market quote by currency conversion (default USD): open, high, low, close, volume, market_cap and the conversion timestamp.",+ },+ },+ "global_metrics_quotes_historical": {+ "description": "Historical aggregate market metrics across all cryptocurrencies: total market cap, BTC and ETH dominance, and altcoin market cap. One row per interval.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/global-metrics/quotes-historical-3.md",+ "columns": {+ "timestamp": "Timestamp (ISO 8601) of when this historical quote was recorded.",+ "search_interval": "The interval timestamp for the search period that this historical quote was located against.",+ "btc_dominance": "Percent of BTC market dominance by market cap at this interval.",+ "eth_dominance": "Percent of ETH market dominance by market cap at this interval.",+ "active_cryptocurrencies": "Number of active cryptocurrencies tracked by CoinMarketCap at this point in time. Null before 2019-05-10.",+ "active_exchanges": "Number of active exchanges tracked by CoinMarketCap at this point in time. Null before 2019-06-18.",+ "active_market_pairs": "Number of active market pairs tracked across all exchanges at this point in time. Null before 2019-05-10.",+ "quote": "Aggregate market data by currency conversion (default USD): total_market_cap, total_volume_24h, total_volume_24h_reported, altcoin_market_cap, altcoin_volume_24h, altcoin_volume_24h_reported and the conversion timestamp.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.pyindex 08555587a3a2..ba6d184a4e64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py@@ -1,9 +1,20 @@-import dataclasses+import datetime+from collections.abc import Iteratorfrom typing import Any, Optional+import requests+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import (+ COINMARKETCAP_BATCH_ENDPOINTS,COINMARKETCAP_ENDPOINTS,+ HISTORICAL_BACKFILL_DAYS,+ HISTORICAL_COIN_LIMIT,PAGE_SIZE,+ CoinMarketCapBatchEndpointConfig,+ RowShape,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -23,10 +34,17 @@ COINMARKETCAP_BASE_URL = "https://pro-api.coinmarketcap.com"# Header CoinMarketCap recommends for passing the Pro API key (over the query-string form).API_KEY_HEADER = "X-CMC_PRO_API_KEY"+REQUEST_TIMEOUT_SECONDS = 60++@frozenclass CoinMarketCapResumeConfig:- start: int+ # Next `start` for the offset-paginated list endpoints.+ start: int = 1+ # Highest coin id already yielded by an endpoint addressed by an explicit id list. The+ # boundary is an id rather than a batch position because the coin universe changes between+ # attempts: a coin that leaves it would shift later ids into a skipped prefix.+ last_coin_id: int = 0class CoinMarketCapPaginator(OffsetPaginator):@@ -74,13 +92,179 @@ def get_resource(endpoint: str) -> EndpointResource:}+def _api_session(api_key: str) -> requests.Session:+ return make_tracked_session(+ headers={API_KEY_HEADER: api_key},+ redact_values=(api_key,),+ # No legitimate redirect to follow, so pinning it off keeps traffic on the validated host.+ allow_redirects=False,+ )+++def _get(session: requests.Session, path: str, params: dict[str, Any]) -> dict[str, Any]:+ response = session.get(f"{COINMARKETCAP_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ body = response.json()+ return body if isinstance(body, dict) else {}+++def _coin_ids_from_map(session: requests.Session) -> list[int]:+ ids: list[int] = []+ start = 1+ while True:+ page = _get(session, "/v1/cryptocurrency/map", {"start": start, "limit": PAGE_SIZE, "sort": "id"})+ rows = page.get("data") or []+ ids.extend(int(row["id"]) for row in rows if isinstance(row, dict) and row.get("id") is not None)+ # Counted before filtering: an unusable row on a full page must not end the walk.+ if len(rows) < PAGE_SIZE:+ return ids+ start += PAGE_SIZE+++def _top_coin_ids_by_market_cap(session: requests.Session, limit: int) -> list[int]:+ page = _get(+ session,+ "/v1/cryptocurrency/listings/latest",+ {"start": 1, "limit": limit, "sort": "market_cap", "sort_dir": "desc"},+ )+ rows = [row for row in (page.get("data") or []) if isinstance(row, dict) and row.get("id") is not None]+ # Sorted by id rather than left in rank order, so a resumed run batches the same coins in the+ # same order as the run it picks up from even though the ranking itself moves between syncs.+ return sorted(int(row["id"]) for row in rows)+++def _coin_entries(data: Any) -> Iterator[dict[str, Any]]:+ """Yield each cryptocurrency object out of a CoinMarketCap `data` payload.++ Requesting several ids returns a map keyed by id, a single id returns the object on its own,+ and requesting by symbol wraps each value in a list.+ """+ if isinstance(data, dict) and "id" in data:+ yield data+ return+ values = list(data.values()) if isinstance(data, dict) else data if isinstance(data, list) else []+ for value in values:+ if isinstance(value, list):+ yield from (item for item in value if isinstance(item, dict))+ elif isinstance(value, dict):+ yield value+++def _rows_from(row_shape: RowShape, data: Any) -> list[dict[str, Any]]:+ if row_shape == "quote_list":+ quotes = data.get("quotes") if isinstance(data, dict) else None+ return [quote for quote in (quotes or []) if isinstance(quote, dict)]++ if row_shape == "per_coin_quotes":+ rows: list[dict[str, Any]] = []+ for entry in _coin_entries(data):+ identity = {key: value for key, value in entry.items() if key != "quotes"}+ rows.extend({**identity, **quote} for quote in (entry.get("quotes") or []) if isinstance(quote, dict))+ return rows++ return list(_coin_entries(data))+++def _history_start(db_incremental_field_last_value: Optional[Any]) -> str:+ if isinstance(db_incremental_field_last_value, datetime.datetime | datetime.date):+ return db_incremental_field_last_value.isoformat()+ if isinstance(db_incremental_field_last_value, str) and db_incremental_field_last_value:+ return db_incremental_field_last_value+ backfill_start = datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=HISTORICAL_BACKFILL_DAYS)+ return backfill_start.date().isoformat()+++def get_batch_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = COINMARKETCAP_BATCH_ENDPOINTS[endpoint]+ session = _api_session(api_key)++ params: dict[str, Any] = dict(config.extra_params)+ if config.windowed:+ params["time_start"] = _history_start(db_incremental_field_last_value)++ if config.universe is None:+ rows = _rows_from(config.row_shape, _get(session, config.path, params).get("data"))+ if rows:+ yield rows+ return++ coin_ids = (+ _coin_ids_from_map(session)+ if config.universe == "map"+ else _top_coin_ids_by_market_cap(session, HISTORICAL_COIN_LIMIT)+ )+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ last_coin_id = resume_config.last_coin_id if resume_config is not None else 0+ if last_coin_id:+ logger.debug(f"CoinMarketCap: resuming {endpoint} after coin id {last_coin_id}")+ coin_ids = [coin_id for coin_id in coin_ids if coin_id > last_coin_id]++ for index in range(0, len(coin_ids), config.batch_size):+ batch = coin_ids[index : index + config.batch_size]+ body = _get(session, config.path, {**params, "id": ",".join(str(coin_id) for coin_id in batch)})+ rows = _rows_from(config.row_shape, body.get("data"))+ if rows:+ yield rows++ # Saved after the batch is yielded, so a crash re-yields it rather than skipping it;+ # the merge de-duplicates on the endpoint's primary key.+ resumable_source_manager.save_state(CoinMarketCapResumeConfig(last_coin_id=batch[-1]))+++def _batch_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ config: CoinMarketCapBatchEndpointConfig = COINMARKETCAP_BATCH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_batch_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # A per-coin endpoint restarts at the window's earliest point for every batch of coins,+ # so only the single global-metrics series arrives in ascending order.+ sort_mode="asc" if config.universe is None else None,+ )++def coinmarketcap_source(api_key: str,endpoint: str,team_id: int,job_id: str,+ logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:+ if endpoint in COINMARKETCAP_BATCH_ENDPOINTS:+ return _batch_source(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+endpoint_config = COINMARKETCAP_ENDPOINTS[endpoint]rest_config: RESTAPIConfig = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.pyindex 2fd4be4f7b92..1255e8773890 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py@@ -1,13 +1,36 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Literal, Optional-from products.warehouse_sources.backend.types import IncrementalField+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# CoinMarketCap caps `limit` at 5000 records per page across its list endpoints.# A larger page size means fewer HTTP calls (kinder to the per-minute rate limit);# the monthly credit cost is per data point, so it's unaffected by page size.PAGE_SIZE = 5000+# Coins per `id=` request on the endpoints that take an explicit id list. CoinMarketCap bills+# metadata at 1 credit per 250 records returned, so batching on that boundary is the cheapest+# whole multiple. The historical endpoints bill per data point instead, where a smaller batch+# only keeps each response (and the memory it lands in) manageable.+METADATA_BATCH_SIZE = 250+HISTORICAL_BATCH_SIZE = 20++# Per-coin history is billed per data point, so the coin universe has to be bounded: asking for+# a year of daily candles across every listed coin would spend a month of credits in one sync.+# The highest-ranked coins by market cap are what these tables get used for.+HISTORICAL_COIN_LIMIT = 100++# How far back a historical request reaches when there is no watermark to start from. One year+# of daily points is the longest window every paid plan tier serves, so a first sync doesn't+# fail outright on the entry plans.+HISTORICAL_BACKFILL_DAYS = 365++# CoinMarketCap's documented ceiling for `count`. Passed on every windowed request so the API+# doesn't fall back to its 10-item default when `time_start` is ignored for a given plan.+HISTORICAL_MAX_COUNT = 10000+@dataclassclass CoinMarketCapEndpointConfig:@@ -67,10 +90,129 @@ COINMARKETCAP_ENDPOINTS: dict[str, CoinMarketCapEndpointConfig] = {),}-ENDPOINTS = tuple(COINMARKETCAP_ENDPOINTS.keys())+# How a response body turns into rows.+# "object_map": `data` maps an id to one record, which is the row.+# "per_coin_quotes": `data` maps an id to a record holding a `quotes` array; each quote becomes+# a row carrying the coin's identity fields.+# "quote_list": `data` is a single object whose `quotes` array is the whole table.+RowShape = Literal["object_map", "per_coin_quotes", "quote_list"]++# Where the ids for an `id=` param come from.+# "map": every id in /v1/cryptocurrency/map.+# "top_by_market_cap": the HISTORICAL_COIN_LIMIT highest-ranked coins in listings/latest.+CoinUniverse = Literal["map", "top_by_market_cap"]-# Full refresh only. CoinMarketCap's "latest"/"map" endpoints reflect current state-# with no `since`/`updated_after`-style server-side filter, so an "incremental" sync-# would re-fetch every page anyway. Historical endpoints expose `time_start`/`time_end`-# windows, but they're gated behind higher paid tiers, so they aren't synced here.-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}++@frozen+class CoinMarketCapBatchEndpointConfig:+ """An endpoint the source iterates itself instead of driving the offset paginator.++ These take no `start`/`limit`: the lookup and per-coin history endpoints are addressed by an+ explicit id list, and global metrics returns one series in a single response.+ """++ name: str+ path: str+ primary_keys: list[str]+ row_shape: RowShape+ # None for an endpoint that takes no ids at all.+ universe: Optional[CoinUniverse] = None+ batch_size: int = METADATA_BATCH_SIZE+ # Whether the endpoint takes a `time_start` history window.+ windowed: bool = False+ partition_key: Optional[str] = None+ extra_params: dict[str, str] = field(default_factory=dict)+++COINMARKETCAP_BATCH_ENDPOINTS: dict[str, CoinMarketCapBatchEndpointConfig] = {+ # Static metadata (tags, platform, category, urls) resolving the ids in cryptocurrency_map.+ "cryptocurrency_info": CoinMarketCapBatchEndpointConfig(+ name="cryptocurrency_info",+ path="/v2/cryptocurrency/info",+ primary_keys=["id"],+ row_shape="object_map",+ universe="map",+ extra_params={+ "aux": "urls,logo,description,tags,platform,date_added,notice,status",+ # A coin delisted between the map walk and this request would otherwise fail the+ # whole batch rather than the one id.+ "skip_invalid": "true",+ },+ ),+ # Daily price, volume and market cap per coin.+ "quotes_historical": CoinMarketCapBatchEndpointConfig(+ name="quotes_historical",+ path="/v3/cryptocurrency/quotes/historical",+ primary_keys=["id", "timestamp"],+ row_shape="per_coin_quotes",+ universe="top_by_market_cap",+ batch_size=HISTORICAL_BATCH_SIZE,+ windowed=True,+ partition_key="timestamp",+ extra_params={+ "interval": "daily",+ "count": str(HISTORICAL_MAX_COUNT),+ "skip_invalid": "true",+ "aux": (+ "price,volume,market_cap,circulating_supply,total_supply,"+ "quote_timestamp,is_active,is_fiat,search_interval"+ ),+ },+ ),+ # Daily OHLCV candles plus market cap per coin.+ "ohlcv_historical": CoinMarketCapBatchEndpointConfig(+ name="ohlcv_historical",+ path="/v2/cryptocurrency/ohlcv/historical",+ primary_keys=["id", "time_open"],+ row_shape="per_coin_quotes",+ universe="top_by_market_cap",+ batch_size=HISTORICAL_BATCH_SIZE,+ windowed=True,+ partition_key="time_open",+ extra_params={+ "time_period": "daily",+ "interval": "daily",+ "count": str(HISTORICAL_MAX_COUNT),+ "skip_invalid": "true",+ },+ ),+ # Total market cap, BTC/ETH dominance and altcoin market cap over time.+ "global_metrics_quotes_historical": CoinMarketCapBatchEndpointConfig(+ name="global_metrics_quotes_historical",+ path="/v1/global-metrics/quotes/historical",+ primary_keys=["timestamp"],+ row_shape="quote_list",+ windowed=True,+ partition_key="timestamp",+ extra_params={+ "interval": "daily",+ "count": str(HISTORICAL_MAX_COUNT),+ "aux": (+ "btc_dominance,eth_dominance,active_cryptocurrencies,active_exchanges,"+ "active_market_pairs,total_volume_24h,total_volume_24h_reported,"+ "altcoin_market_cap,altcoin_volume_24h,altcoin_volume_24h_reported,search_interval"+ ),+ },+ ),+}++ENDPOINTS = (*COINMARKETCAP_ENDPOINTS.keys(), *COINMARKETCAP_BATCH_ENDPOINTS.keys())++# Only global metrics syncs incrementally. Its `time_start` filter drives a single global series,+# so the one watermark the pipeline hands a source is exactly the right lower bound.+#+# The "latest"/"map" endpoints reflect current state with no `since`-style filter, so an+# "incremental" sync would re-fetch every page anyway. The per-coin historical endpoints do take+# `time_start`, but the coin universe is the top coins by market cap and that ranking churns:+# driving `time_start` off a watermark shared by every coin would give a coin that enters the+# universe later only the history since that watermark, and nothing would ever fill the gap.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "global_metrics_quotes_historical": [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/source.pyindex dfcc2b4178c9..a619eb8030cd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/source.py@@ -49,7 +49,7 @@ class CoinMarketCapSource(ResumableSource[CoinMarketCapSourceConfig, CoinMarketCreleaseStatus=ReleaseStatus.ALPHA,caption="""Enter your CoinMarketCap Pro API key to sync cryptocurrency and market data into the PostHog Data warehouse.-Create a key from your [CoinMarketCap developer dashboard](https://pro.coinmarketcap.com/account). The key grants read access to every endpoint listed below; some (e.g. exchanges) require a higher plan tier.""",+Create a key from your [CoinMarketCap developer dashboard](https://pro.coinmarketcap.com/account). The key grants read access to every endpoint listed below; some (e.g. exchanges and historical data) require a higher plan tier.""",iconPath="/static/services/coinmarketcap.png",docsUrl="https://posthog.com/docs/cdp/sources/coinmarketcap",# Kept hidden from the new-source wizard for now; flip this off to release.@@ -81,6 +81,10 @@ Create a key from your [CoinMarketCap developer dashboard](https://pro.coinmarke# `raise_for_status()`. Retrying can never satisfy a credential problem."401 Client Error": "Your CoinMarketCap API key is invalid or has been revoked. Create a new key in your CoinMarketCap developer dashboard, then reconnect.","Unauthorized for url": "Your CoinMarketCap API key is invalid or has been revoked. Create a new key in your CoinMarketCap developer dashboard, then reconnect.",+ # CoinMarketCap answers 403 when the key is disabled or the plan doesn't cover the+ # endpoint (the historical and exchange tables need a higher tier). Neither clears+ # itself on a retry.+ "403 Client Error": "Your CoinMarketCap plan does not cover this table, or the API key has been disabled. Deselect the table or upgrade your plan, then retry the sync.",}def get_schemas(@@ -129,5 +133,9 @@ Create a key from your [CoinMarketCap developer dashboard](https://pro.coinmarkeendpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,+ logger=inputs.logger,resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.pyindex fc20d74be486..f6f8c3591159 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py@@ -11,15 +11,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketAPI_KEY_HEADER,CoinMarketCapPaginator,CoinMarketCapResumeConfig,+ _history_start,+ _rows_from,coinmarketcap_source,+ get_batch_rows,get_resource,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import (+ COINMARKETCAP_BATCH_ENDPOINTS,COINMARKETCAP_ENDPOINTS,- ENDPOINTS,+ HISTORICAL_BACKFILL_DAYS,+ HISTORICAL_BATCH_SIZE,+ HISTORICAL_COIN_LIMIT,+ METADATA_BATCH_SIZE,PAGE_SIZE,)+from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.source import CoinMarketCapSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -86,7 +94,7 @@ class TestCoinMarketCapPaginator:class TestGetResource:- @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @pytest.mark.parametrize("endpoint", list(COINMARKETCAP_ENDPOINTS))def test_resource_shape(self, endpoint: str) -> None:resource = get_resource(endpoint)config = COINMARKETCAP_ENDPOINTS[endpoint]@@ -142,6 +150,7 @@ class TestCoinMarketCapSourceResumeBehavior:endpoint=endpoint,team_id=123,job_id="test_job",+ logger=MagicMock(),resumable_source_manager=manager,)list(cast(Iterable[Any], source.items()))@@ -252,3 +261,294 @@ class TestValidateCredentials:valid, error = validate_credentials("test-key")assert valid is Falseassert error == "boom"+++def _make_batch_response(body: dict[str, Any], status_code: int = 200, url: str = "") -> Response:+ resp = _make_http_response(body, status_code=status_code)+ resp.url = url+ resp.reason = "Forbidden" if status_code == 403 else "OK"+ return resp+++class _FakeSession:+ """Records every `_get` call and replays a queued list of responses."""++ def __init__(self, responses: list[Response]) -> None:+ self.responses = iter(responses)+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def get(self, url: str, params: dict[str, Any] | None = None, **_kwargs: Any) -> Response:+ self.calls.append((url, dict(params or {})))+ return next(self.responses)+++def _patch_session(responses: list[Response]) -> tuple[Any, _FakeSession]:+ session = _FakeSession(responses)+ patcher = patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.coinmarketcap.make_tracked_session",+ return_value=session,+ )+ return patcher, session+++class TestRowsFrom:+ def test_object_map_keyed_by_id(self) -> None:+ rows = _rows_from("object_map", {"1": {"id": 1, "symbol": "BTC"}, "1027": {"id": 1027, "symbol": "ETH"}})+ assert [row["id"] for row in rows] == [1, 1027]++ def test_object_map_unwraps_a_single_object(self) -> None:+ # A single-id request returns the record directly rather than an id-keyed map.+ assert _rows_from("object_map", {"id": 1, "symbol": "BTC"}) == [{"id": 1, "symbol": "BTC"}]++ def test_object_map_flattens_symbol_keyed_lists(self) -> None:+ # Requesting by symbol wraps each value in a list, because a symbol isn't unique.+ rows = _rows_from("object_map", {"BTC": [{"id": 1}, {"id": 2}]})+ assert [row["id"] for row in rows] == [1, 2]++ def test_per_coin_quotes_stamps_coin_identity_on_each_quote(self) -> None:+ rows = _rows_from(+ "per_coin_quotes",+ {+ "1": {+ "id": 1,+ "name": "Bitcoin",+ "symbol": "BTC",+ "quotes": [+ {"timestamp": "2026-01-01T00:00:00.000Z", "quote": {"USD": {"price": 1.0}}},+ {"timestamp": "2026-01-02T00:00:00.000Z", "quote": {"USD": {"price": 2.0}}},+ ],+ }+ },+ )++ assert len(rows) == 2+ assert all(row["id"] == 1 and row["symbol"] == "BTC" for row in rows)+ assert [row["timestamp"] for row in rows] == ["2026-01-01T00:00:00.000Z", "2026-01-02T00:00:00.000Z"]+ # The nested array must not survive onto the row, or every row carries the whole series.+ assert all("quotes" not in row for row in rows)++ def test_per_coin_quotes_handles_a_single_object_payload(self) -> None:+ # OHLCV historical returns the coin object directly when only one id is requested.+ rows = _rows_from(+ "per_coin_quotes",+ {"id": 1, "symbol": "BTC", "quotes": [{"time_open": "2026-01-01T00:00:00.000Z"}]},+ )+ assert rows == [{"id": 1, "symbol": "BTC", "time_open": "2026-01-01T00:00:00.000Z"}]++ def test_quote_list_reads_the_nested_series(self) -> None:+ rows = _rows_from("quote_list", {"quotes": [{"timestamp": "2026-01-01T00:00:00.000Z", "btc_dominance": 50.0}]})+ assert rows == [{"timestamp": "2026-01-01T00:00:00.000Z", "btc_dominance": 50.0}]++ @pytest.mark.parametrize("data", [None, {}, {"quotes": None}])+ def test_quote_list_tolerates_an_empty_body(self, data: Any) -> None:+ assert _rows_from("quote_list", data) == []+++class TestHistoryStart:+ def test_uses_the_watermark_when_one_is_set(self) -> None:+ import datetime++ watermark = datetime.datetime(2026, 3, 1, 12, 30, tzinfo=datetime.UTC)+ assert _history_start(watermark) == watermark.isoformat()++ def test_falls_back_to_the_backfill_window(self) -> None:+ import datetime++ expected = (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=HISTORICAL_BACKFILL_DAYS)).date()+ assert _history_start(None) == expected.isoformat()++ def test_passes_a_string_watermark_through(self) -> None:+ assert _history_start("2026-01-01T00:00:00.000Z") == "2026-01-01T00:00:00.000Z"+++class TestGetBatchRows:+ def _manager(self, resume_config: CoinMarketCapResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_config is not None+ manager.load_state.return_value = resume_config+ return manager++ def _run(+ self,+ endpoint: str,+ responses: list[Response],+ manager: MagicMock,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], _FakeSession]:+ patcher, session = _patch_session(responses)+ with patcher:+ batches = list(+ get_batch_rows(+ api_key="test-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return [row for batch in batches for row in batch], session++ def test_global_metrics_makes_one_unbatched_request(self) -> None:+ manager = self._manager()+ rows, session = self._run(+ "global_metrics_quotes_historical",+ [_make_batch_response({"data": {"quotes": [{"timestamp": "2026-01-01T00:00:00.000Z"}]}})],+ manager,+ )++ assert rows == [{"timestamp": "2026-01-01T00:00:00.000Z"}]+ assert len(session.calls) == 1+ url, params = session.calls[0]+ assert url.endswith("/v1/global-metrics/quotes/historical")+ assert "id" not in params+ assert params["interval"] == "daily"+ # No coin batches to resume through, so nothing should be checkpointed.+ manager.save_state.assert_not_called()++ def test_full_refresh_sends_the_backfill_window_not_a_watermark(self) -> None:+ _, session = self._run(+ "global_metrics_quotes_historical",+ [_make_batch_response({"data": {"quotes": []}})],+ self._manager(),+ )+ assert session.calls[0][1]["time_start"] == _history_start(None)++ def test_incremental_sends_the_watermark(self) -> None:+ import datetime++ watermark = datetime.datetime(2026, 3, 1, tzinfo=datetime.UTC)+ _, session = self._run(+ "global_metrics_quotes_historical",+ [_make_batch_response({"data": {"quotes": []}})],+ self._manager(),+ db_incremental_field_last_value=watermark,+ )+ assert session.calls[0][1]["time_start"] == watermark.isoformat()++ def test_info_batches_every_id_in_the_map(self) -> None:+ map_page = {"data": [{"id": coin_id} for coin_id in range(1, METADATA_BATCH_SIZE + 3)]}+ manager = self._manager()+ rows, session = self._run(+ "cryptocurrency_info",+ [+ _make_batch_response(map_page),+ _make_batch_response({"data": {"1": {"id": 1}}}),+ _make_batch_response({"data": {"251": {"id": 251}}}),+ ],+ manager,+ )++ map_call, first_batch, second_batch = session.calls+ assert map_call[0].endswith("/v1/cryptocurrency/map")+ assert first_batch[0].endswith("/v2/cryptocurrency/info")+ assert first_batch[1]["id"] == ",".join(str(i) for i in range(1, METADATA_BATCH_SIZE + 1))+ assert second_batch[1]["id"] == f"{METADATA_BATCH_SIZE + 1},{METADATA_BATCH_SIZE + 2}"+ assert [row["id"] for row in rows] == [1, 251]++ # Checkpointed after each batch is yielded, so a crash re-yields rather than skips.+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ CoinMarketCapResumeConfig(last_coin_id=METADATA_BATCH_SIZE),+ CoinMarketCapResumeConfig(last_coin_id=METADATA_BATCH_SIZE + 2),+ ]++ def test_info_walks_every_map_page(self) -> None:+ # The first page is full but carries one unusable row. The walk has to count the raw page,+ # or a single bad row ends it early and the table syncs an incomplete coin set.+ first_page = [{"id": i} for i in range(1, PAGE_SIZE)]+ first_page.append({"no_id": True})+ manager = self._manager()+ _, session = self._run(+ "cryptocurrency_info",+ [+ _make_batch_response({"data": first_page}),+ _make_batch_response({"data": [{"id": PAGE_SIZE + 1}]}),+ *[_make_batch_response({"data": {}}) for _ in range(21)],+ ],+ manager,+ )++ map_calls = [params for url, params in session.calls if url.endswith("/v1/cryptocurrency/map")]+ assert [params["start"] for params in map_calls] == [1, 1 + PAGE_SIZE]++ def test_resume_skips_the_coins_already_yielded(self) -> None:+ map_page = {"data": [{"id": coin_id} for coin_id in range(1, METADATA_BATCH_SIZE + 3)]}+ manager = self._manager(CoinMarketCapResumeConfig(last_coin_id=METADATA_BATCH_SIZE))+ _, session = self._run(+ "cryptocurrency_info",+ [_make_batch_response(map_page), _make_batch_response({"data": {"251": {"id": 251}}})],+ manager,+ )++ info_calls = [params for url, params in session.calls if url.endswith("/v2/cryptocurrency/info")]+ assert len(info_calls) == 1+ assert info_calls[0]["id"] == f"{METADATA_BATCH_SIZE + 1},{METADATA_BATCH_SIZE + 2}"++ def test_resume_holds_its_place_when_a_coin_leaves_the_universe(self) -> None:+ # Id 5 is gone since the attempt that checkpointed. A position-based cursor would slide the+ # whole tail forward by one and skip a coin that was never yielded.+ remaining = [coin_id for coin_id in range(1, HISTORICAL_BATCH_SIZE + 2) if coin_id != 5]+ manager = self._manager(CoinMarketCapResumeConfig(last_coin_id=HISTORICAL_BATCH_SIZE))+ _, session = self._run(+ "quotes_historical",+ [+ _make_batch_response({"data": [{"id": coin_id} for coin_id in remaining]}),+ _make_batch_response({"data": {}}),+ ],+ manager,+ )++ batch_calls = [params for url, params in session.calls if url.endswith("/v3/cryptocurrency/quotes/historical")]+ assert len(batch_calls) == 1+ assert batch_calls[0]["id"] == str(HISTORICAL_BATCH_SIZE + 1)++ @pytest.mark.parametrize("endpoint", ["quotes_historical", "ohlcv_historical"])+ def test_historical_endpoints_rank_the_coin_universe_by_market_cap(self, endpoint: str) -> None:+ listings = {"data": [{"id": coin_id} for coin_id in range(HISTORICAL_BATCH_SIZE + 1, 0, -1)]}+ manager = self._manager()+ _, session = self._run(+ endpoint,+ [_make_batch_response(listings), _make_batch_response({"data": {}}), _make_batch_response({"data": {}})],+ manager,+ )++ universe_call, first_batch, second_batch = session.calls+ assert universe_call[0].endswith("/v1/cryptocurrency/listings/latest")+ assert universe_call[1]["sort"] == "market_cap"+ assert universe_call[1]["sort_dir"] == "desc"+ assert universe_call[1]["limit"] == HISTORICAL_COIN_LIMIT++ # Ids are batched in ascending id order, not in the rank order the listing returned, so a+ # resumed run picks up the same batches even after the ranking moves.+ assert first_batch[1]["id"] == ",".join(str(i) for i in range(1, HISTORICAL_BATCH_SIZE + 1))+ assert second_batch[1]["id"] == str(HISTORICAL_BATCH_SIZE + 1)+ assert first_batch[1]["time_start"] == _history_start(None)+ assert first_batch[0].endswith(COINMARKETCAP_BATCH_ENDPOINTS[endpoint].path)+++class TestBatchEndpointErrors:+ def test_a_plan_refusal_matches_a_non_retryable_error(self) -> None:+ # CoinMarketCap answers 403 when the plan doesn't cover an endpoint. Retrying can never+ # satisfy that, so the raised message has to match one of the source's declared patterns.+ patcher, _ = _patch_session(+ [+ _make_batch_response(+ {"status": {"error_code": 1006}},+ status_code=403,+ url="https://pro-api.coinmarketcap.com/v2/cryptocurrency/ohlcv/historical",+ )+ ]+ )+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patcher, pytest.raises(Exception) as exc_info:+ list(+ get_batch_rows(+ api_key="test-key",+ endpoint="ohlcv_historical",+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )++ assert any(key in str(exc_info.value) for key in CoinMarketCapSource().get_non_retryable_errors())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.pyindex 569bd33a81da..299718d463c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.py@@ -1,4 +1,7 @@-from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.source import CoinMarketCapSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.coinmarketcap import (CoinMarketCapSourceConfig,@@ -11,15 +14,16 @@ class TestCoinMarketCapSource:self.team_id = 123self.config = CoinMarketCapSourceConfig(api_key="test-key")- def test_get_schemas_all_full_refresh(self) -> None:+ def test_get_schemas_offers_incremental_only_where_a_time_filter_drives_it(self) -> None:schemas = self.source.get_schemas(self.config, self.team_id)assert {s.name for s in schemas} == set(ENDPOINTS)- # Every CoinMarketCap "latest"/"map" endpoint is a current-state snapshot with no- # server-side timestamp filter, so all schemas are full refresh only.- assert all(not s.supports_incremental for s in schemas)- assert all(not s.supports_append for s in schemas)- assert all(s.incremental_fields == [] for s in schemas)+ incremental = {s.name for s in schemas if s.supports_incremental}+ # Only global metrics has a `time_start` filter over a single series. Every other table is+ # either a current-state snapshot or a per-coin series the shared watermark can't bound.+ assert incremental == set(INCREMENTAL_FIELDS)+ assert {s.name for s in schemas if s.supports_append} == incremental+ assert all((s.incremental_fields == INCREMENTAL_FIELDS.get(s.name, [])) for s in schemas)def test_get_schemas_filtered_by_names(self) -> None:schemas = self.source.get_schemas(self.config, self.team_id, names=["fiat_map"])