: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 polymarket biggest winners table (#113304)
Tom Owers5d74758d7ec6
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 d9e868ec0616..5278541b7103 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@@ -6859,6 +6859,17 @@ No material gaps found.Note: The entire published Plunk API is seven operations: four listable collections (contacts, campaigns, templates, segments) plus three write-only actions (POST /v1/send, POST /v1/track, POST /v1/verify). PostHog already exposes all four listable collections, so there is nothing left to sync. Workflows and events are documented as product concepts but have no REST endpoints in the spec or in the API reference section of https://docs.useplunk.com/llms.txt.+## Polymarket — gaps++Today (5): `biggest_winners`, `events`, `markets`, `series`, `tags`++Diffed against: <https://data-api.polymarket.com/v2/openapi.json>++- [x] `/v2/biggest-winners` — the all-time board of the biggest single winning positions (medium)+- [ ] `/v2/resolutions` — resolution lifecycle state per market (low)++Note: `/v2/resolutions` only looks up up to 20 condition or event ids per call and has no list mode, so syncing it as a table means fanning out across the whole Gamma event catalog on every full refresh. The markets table already carries each market's resolution status.+## PrefectCloud — gapsToday (6): `deployments`, `flow_runs`, `flows`, `task_runs`, `work_pools`, `work_queues`diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/canonical_descriptions.pyindex d0a573bd19a5..420d9ef88602 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/canonical_descriptions.py@@ -157,4 +157,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updatedBy": "Identifier of the user who last changed the tag.",},},+ "biggest_winners": {+ "description": "The all-time board of the biggest single winning positions, one row per wallet and winning position, capped at the top 500.",+ "docs_url": "https://data-api.polymarket.com/v2/openapi.json",+ "columns": {+ "win_rank": "1-based rank on the board. Equal profit does not share a rank.",+ "kind": "`market` for a single-market win, `combo` for a combinatorial win.",+ "user_id": "Wallet address that held the winning position.",+ "user_name": "Profile display name of the wallet.",+ "profile_image": "Profile image URL of the wallet.",+ "pnl": "Realized profit on the position, `final_value - initial_value`, in USDC.",+ "initial_value": "Cost basis of the winning position, in USDC.",+ "final_value": "Value of the position at resolution, in USDC.",+ "resolved_at": "When the position resolved, in Unix seconds.",+ "condition_id": "On-chain condition id of the market, or of the combo for combo rows.",+ "position_id": "Token id of the winning position.",+ "event_id": "Gamma event id of the parent event. 0 on combo rows.",+ "event_slug": "Parent event slug. Empty on combo rows.",+ "event_title": "Parent event title. On combo rows, the leg questions joined with ' / '.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/polymarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/polymarket.pyindex 07942b47c8f8..8bb4052d0614 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/polymarket.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/polymarket.py@@ -16,22 +16,32 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.polymarket.settings import (+ GAMMA_BASE_URL,POLYMARKET_ENDPOINTS,PolymarketEndpointConfig,)-POLYMARKET_BASE_URL = "https://gamma-api.polymarket.com"-@frozenclass PolymarketResumeConfig:- # Keyset endpoints resume from an opaque cursor; offset endpoints resume from a row offset.+ # Keyset and cursor endpoints resume from an opaque cursor; offset endpoints resume from a row offset.# Exactly one is set, matching the endpoint's pagination style.cursor: Optional[str] = Noneoffset: Optional[int] = Nonedef _build_endpoint(config: PolymarketEndpointConfig) -> Endpoint:+ if config.pagination == "cursor":+ # The Data API pages only by `pagination.next_cursor`, which is null on the last page.+ # Sending `offset` is a 400, so the offset paginator must never touch these endpoints.+ return {+ "path": config.path,+ "params": {"limit": config.page_size, **config.params},+ "data_selector": config.data_key,+ "data_selector_required": True,+ "paginator": JSONResponseCursorPaginator(cursor_path="pagination.next_cursor", cursor_param="cursor"),+ }+# `order=id&ascending=true` is what makes paging stable. Without an explicit order the offset# endpoints return rows in an unspecified order, so a row inserted mid-sync shifts every later# page and silently skips or duplicates rows.@@ -66,10 +76,10 @@ def polymarket_source() -> SourceResponse:config = POLYMARKET_ENDPOINTS[endpoint]- # Gamma's read endpoints are public and take no credential, so no `auth` is configured.+ # Gamma and the Data API are public and take no credential, so no `auth` is configured.rest_config: RESTAPIConfig = {"client": {- "base_url": POLYMARKET_BASE_URL,+ "base_url": config.base_url,"headers": {"Accept": "application/json"},},"resource_defaults": {},@@ -85,7 +95,7 @@ def polymarket_source(if resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None:- if config.pagination == "keyset" and resume.cursor is not None:+ if config.pagination in ("keyset", "cursor") and resume.cursor is not None:initial_paginator_state = {"cursor": resume.cursor}elif config.pagination == "offset" and resume.offset is not None:initial_paginator_state = {"offset": resume.offset}@@ -95,7 +105,7 @@ def polymarket_source(# primary key) instead of skipping it.if not state:return- if config.pagination == "keyset":+ if config.pagination in ("keyset", "cursor"):if state.get("cursor"):resumable_source_manager.save_state(PolymarketResumeConfig(cursor=str(state["cursor"])))elif state.get("offset") is not None:@@ -131,7 +141,7 @@ def validate_credentials() -> bool:# against an endpoint that has moved.ok, _status = validate_via_probe(make_tracked_session,- f"{POLYMARKET_BASE_URL}/status",+ f"{GAMMA_BASE_URL}/status",headers={"Accept": "application/json"},)return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/settings.pyindex 16ff8c865433..d68d89afe9e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/settings.py@@ -1,11 +1,14 @@from dataclasses import field-from typing import Literal, Optional+from typing import Any, Literal, Optionalfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.types import IncrementalField-PaginationStyle = Literal["keyset", "offset"]+PaginationStyle = Literal["keyset", "offset", "cursor"]++GAMMA_BASE_URL = "https://gamma-api.polymarket.com"+DATA_API_BASE_URL = "https://data-api.polymarket.com"@frozen@@ -13,12 +16,14 @@ class PolymarketEndpointConfig:name: strpath: strpagination: PaginationStyle- # Wrapper key holding the array on the keyset endpoints. The offset endpoints return a bare- # JSON array, so they select nothing.+ base_url: str = GAMMA_BASE_URL+ # Wrapper key holding the array on the keyset and cursor endpoints. The offset endpoints+ # return a bare JSON array, so they select nothing.data_key: Optional[str] = Noneprimary_keys: list[str] = field(default_factory=lambda: ["id"])partition_key: Optional[str] = Nonepage_size: int = 500+ params: dict[str, Any] = field(default_factory=dict)# Gamma exposes no server-side filter on `createdAt` or `updatedAt`, so every table is full@@ -55,6 +60,19 @@ POLYMARKET_ENDPOINTS: dict[str, PolymarketEndpointConfig] = {pagination="offset",partition_key="createdAt",),+ # The top winning positions by realized profit, read from the Data API. The board holds at most+ # 500 rows per window, so `time_period=all` keeps the all-time board rather than one day's.+ # One position can be won by many wallets, so the wallet is part of the key.+ "biggest_winners": PolymarketEndpointConfig(+ name="biggest_winners",+ path="/v2/biggest-winners",+ pagination="cursor",+ base_url=DATA_API_BASE_URL,+ data_key="data",+ primary_keys=["position_id", "user_id"],+ page_size=1000,+ params={"time_period": "all"},+ ),}ENDPOINTS = tuple(POLYMARKET_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/source.pyindex f19f623c9fa9..e73151cdb930 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/source.py@@ -51,7 +51,7 @@ class PolymarketSource(ResumableSource[PolymarketSourceConfig, PolymarketResumeCreleaseStatus=ReleaseStatus.ALPHA,caption="""Polymarket's Gamma API is public, so this source needs no API key.-It syncs events, markets, series, and tags. Order books, price history, and wallet positions come from separate APIs and are not supported yet.""",+It syncs events, markets, series, tags, and the all-time biggest wins board. Order books, price history, and wallet positions are not supported yet.""",iconPath="/static/services/polymarket.png",docsUrl="https://posthog.com/docs/cdp/sources/polymarket",keywords=["prediction market", "gamma", "trading"],@@ -69,6 +69,7 @@ It syncs events, markets, series, and tags. Order books, price history, and wallreturn {# There is no credential to fix, so a 403 means Gamma is refusing this caller."403 Client Error: Forbidden for url: https://gamma-api.polymarket.com": "Polymarket refused the request. Access is restricted from some regions, so this source may not be usable from where PostHog runs.",+ "403 Client Error: Forbidden for url: https://data-api.polymarket.com": "Polymarket refused the request. Access is restricted from some regions, so this source may not be usable from where PostHog runs.",}def get_schemas(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/tests/test_polymarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/tests/test_polymarket.pyindex 668a96878c00..91bbb13e7de7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/tests/test_polymarket.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/polymarket/tests/test_polymarket.py@@ -29,6 +29,15 @@ def _keyset_response(data_key: str, items: list[dict[str, Any]], *, next_cursor:return resp+def _data_api_response(items: list[dict[str, Any]], *, next_cursor: str | None = None) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(+ {"data": items, "pagination": {"limit": 1000, "has_more": next_cursor is not None, "next_cursor": next_cursor}}+ ).encode()+ return resp++def _array_response(items: list[dict[str, Any]]) -> Response:resp = Response()resp.status_code = 200@@ -126,13 +135,45 @@ class TestPolymarketTransport:assert params[1]["offset"] == page_size@mock.patch(CLIENT_SESSION_PATCH)- def test_keyset_resume_seeds_the_cursor(self, MockSession) -> None:+ def test_data_api_cursor_pagination_walks_then_stops(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _data_api_response([{"position_id": "1", "user_id": "0xa"}], next_cursor="c1"),+ _data_api_response([{"position_id": "2", "user_id": "0xb"}]),+ ],+ )++ rows = _rows(_source("biggest_winners", _make_manager()))++ assert [row["position_id"] for row in rows] == ["1", "2"]+ assert all(+ c.args[0].url == "https://data-api.polymarket.com/v2/biggest-winners"+ for c in session.prepare_request.call_args_list+ )+ # The board defaults to one day; without time_period=all each sync replaces the table with+ # only that day's wins. Sending offset is a 400 on the Data API.+ assert params[0] == {"limit": 1000, "time_period": "all"}+ assert params[1]["cursor"] == "c1"+ assert not any("offset" in p or "order" in p for p in params)++ @parameterized.expand(+ [+ ("events", _keyset_response("events", [{"id": "9"}]), "after_cursor"),+ ("biggest_winners", _data_api_response([{"position_id": "9", "user_id": "0xa"}]), "cursor"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_cursor_resume_seeds_the_cursor(+ self, endpoint: str, response: Response, cursor_param: str, MockSession+ ) -> None:session = MockSession.return_value- params = _wire(session, [_keyset_response("events", [{"id": "9"}])])+ params = _wire(session, [response])- _rows(_source("events", _make_manager(PolymarketResumeConfig(cursor="saved"))))+ _rows(_source(endpoint, _make_manager(PolymarketResumeConfig(cursor="saved"))))- assert params[0]["after_cursor"] == "saved"+ assert params[0][cursor_param] == "saved"@mock.patch(CLIENT_SESSION_PATCH)def test_offset_resume_seeds_the_offset(self, MockSession) -> None: