Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse_sources): support Marketstack API version v2 (#74168)

Tom Owers7c06ee676858
diff --git a/products/warehouse_sources/backend/migrations/0107_repin_marketstack_api_version_v2.py b/products/warehouse_sources/backend/migrations/0107_repin_marketstack_api_version_v2.py
new file mode 100644
index 000000000000..459cb0cf332a
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0107_repin_marketstack_api_version_v2.py
@@ -0,0 +1,33 @@
+from django.db import migrations
+
+# Marketstack deprecated its v1 API (vendor sunset 2025-06-30) in favor of v2. v2 is a compatible
+# additive superset for every table we sync — same auth, pagination, response/error envelope, and
+# primary keys; only new response columns, which the auto-inferred schema absorbs — so repinning is
+# lossless and needs no data/schema transform. This moves the source-level pin only; schema-level
+# `ExternalDataSchema.api_version` overrides are user-managed and intentionally left untouched.
+SOURCE_TYPE = "Marketstack"
+DEPRECATED_VERSION = "v1"
+NEW_VERSION = "v2"
+
+
+def repin_marketstack_to_v2(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # ExternalDataSource is one row per configured source (thousands, not events-scale), so a single
+ # bulk update in the migration's transaction is quick. Idempotent: a second run finds no v1/NULL
+ # Marketstack rows. NULL pins are repinned too — they otherwise silently follow the flipped
+ # default_version to v2, so pinning them makes the migration to v2 explicit and reviewable.
+ ExternalDataSource.objects.filter(source_type=SOURCE_TYPE, api_version=DEPRECATED_VERSION).update(
+ api_version=NEW_VERSION
+ )
+ ExternalDataSource.objects.filter(source_type=SOURCE_TYPE, api_version__isnull=True).update(api_version=NEW_VERSION)
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0106_repin_clockodo_api_version")]
+
+ operations = [
+ # Reverse is a no-op: once repinned, v2 rows are indistinguishable from natively-created ones,
+ # so a blanket downgrade would clobber legitimate v2 pins made after this ran.
+ migrations.RunPython(repin_marketstack_to_v2, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index f81ed632653c..7f026c73533f 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0106_repin_clockodo_api_version
+0107_repin_marketstack_api_version_v2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
index 3548b264ced5..85ff83f5a077 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
@@ -15,9 +15,28 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import MARKETSTACK_ENDPOINTS
-# Marketstack keeps two live API versions; v1 is stable, covers every endpoint we sync, and is
-# available on the free plan. v2 only adds indices and the /latest lookups we don't use here.
-MARKETSTACK_BASE_URL = "https://api.marketstack.com/v1"
+# Opaque Marketstack version labels (never parsed/ordered). Each version is served under its own
+# path segment; the source pin selects the base URL. v1 is deprecated (vendor sunset 2025-06-30);
+# v2 is the current GA API — same auth, envelope, and pagination, only additive response fields for
+# every endpoint we sync, which the auto-inferred schema absorbs.
+MARKETSTACK_API_VERSION_V1 = "v1"
+MARKETSTACK_API_VERSION_V2 = "v2"
+
+_MARKETSTACK_BASE_URLS = {
+ MARKETSTACK_API_VERSION_V1: "https://api.marketstack.com/v1",
+ MARKETSTACK_API_VERSION_V2: "https://api.marketstack.com/v2",
+}
+
+
+def marketstack_base_url(api_version: str) -> str:
+ # Every supported label must map to a base URL — an unmapped pin raises rather than silently
+ # sending an unversioned host (tracking "latest", the drift the versioning framework prevents).
+ try:
+ return _MARKETSTACK_BASE_URLS[api_version]
+ except KeyError:
+ raise ValueError(f"Unsupported Marketstack API version: {api_version!r}")
+
+
# limit maxes out at 1000; larger pages mean fewer round trips against the 5 req/sec rate limit.
DEFAULT_PAGE_SIZE = 1000
@@ -91,6 +110,7 @@ def marketstack_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+ api_version: str,
symbols: str | None = None,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
@@ -116,7 +136,7 @@ def marketstack_source(
rest_config: RESTAPIConfig = {
"client": {
- "base_url": MARKETSTACK_BASE_URL,
+ "base_url": marketstack_base_url(api_version),
# access_key rides in the query string; the framework auth redacts its value from every
# logged URL, captured sample, and raised error message.
"auth": {"type": "api_key", "api_key": access_key, "name": "access_key", "location": "query"},
@@ -180,11 +200,12 @@ def marketstack_source(
)
-def validate_credentials(access_key: str) -> bool:
+def validate_credentials(access_key: str, api_version: str) -> bool:
# `/exchanges` is a static reference endpoint available on every plan (including free) and needs
- # no symbols, so it's a cheap probe that the access key is genuine. A bad key can surface either
- # as a non-200 status or as an HTTP 200 with a body-level error envelope, so both are checked.
- url = f"{MARKETSTACK_BASE_URL}/exchanges"
+ # no symbols, so it's a cheap probe that the access key is genuine. It's served under both v1 and
+ # v2, so the resolved source pin picks the base URL. A bad key can surface either as a non-200
+ # status or as an HTTP 200 with a body-level error envelope, so both are checked.
+ url = f"{marketstack_base_url(api_version)}/exchanges"
params: dict[str, Any] = {"access_key": access_key, "limit": 1}
try:
session = make_tracked_session(redact_values=(access_key,))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
index d0777e62e1a9..85ba771323ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
@@ -1,3 +1,4 @@
+from datetime import date
from typing import Optional, cast
from posthog.schema import (
@@ -13,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
SourceInputs,
SourceResponse,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -24,6 +29,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MarketstackSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MARKETSTACK_API_VERSION_V1,
+ MARKETSTACK_API_VERSION_V2,
MarketstackResumeConfig,
marketstack_source,
validate_credentials as validate_marketstack_credentials,
@@ -35,9 +42,11 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("v1",)
- default_version = "v1"
- api_docs_url = "https://marketstack.com/documentation"
+ supported_versions = (MARKETSTACK_API_VERSION_V1, MARKETSTACK_API_VERSION_V2)
+ default_version = MARKETSTACK_API_VERSION_V2
+ # Vendor deprecated v1 for use after this date; v2 is the current GA API.
+ deprecated_versions = (VersionDeprecation(version=MARKETSTACK_API_VERSION_V1, sunset_at=date(2025, 6, 30)),)
+ api_docs_url = "https://marketstack.com/documentation_v2"
@property
def source_type(self) -> ExternalDataSourceType:
@@ -79,6 +88,8 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ # The endpoint catalog and incremental fields are identical across v1 and v2 (v2 only adds
+ # response columns, absorbed by the auto-inferred schema), so discovery ignores the pin.
schemas = [
SourceSchema(
name=endpoint.name,
@@ -105,7 +116,9 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_marketstack_credentials(config.access_key):
+ # Pre-creation calls pass no pin and resolve to default_version (what new rows are stamped
+ # with); a pinned source revalidates against its own version's base URL.
+ if validate_marketstack_credentials(config.access_key, self.resolve_api_version(api_version)):
return True, None
return False, "Invalid Marketstack access key"
@@ -125,6 +138,7 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
symbols=config.symbols,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
index 16d0cde33624..2ecab16a18d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
@@ -12,10 +12,12 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack import marketstack
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MARKETSTACK_API_VERSION_V1,
+ MARKETSTACK_API_VERSION_V2,
MarketstackResumeConfig,
_format_date,
+ marketstack_base_url,
marketstack_source,
validate_credentials,
)
@@ -86,6 +88,7 @@ def _source(
*,
symbols: str | None = "AAPL",
db_incremental_field_last_value: Any = None,
+ api_version: str = MARKETSTACK_API_VERSION_V2,
) -> Any:
return marketstack_source(
"supersecret",
@@ -93,6 +96,7 @@ def _source(
team_id=1,
job_id="j",
resumable_source_manager=manager or _make_manager(),
+ api_version=api_version,
symbols=symbols,
db_incremental_field_last_value=db_incremental_field_last_value,
)
@@ -360,14 +364,60 @@ class TestValidateCredentials:
session = mock.MagicMock()
session.get.return_value = response
with mock.patch(MARKETSTACK_SESSION_PATCH, return_value=session):
- assert validate_credentials("k") is expected
+ assert validate_credentials("k", MARKETSTACK_API_VERSION_V2) is expected
def test_handles_network_error(self) -> None:
session = mock.MagicMock()
session.get.side_effect = requests.ConnectionError("boom")
with mock.patch(MARKETSTACK_SESSION_PATCH, return_value=session):
- assert validate_credentials("k") is False
+ assert validate_credentials("k", MARKETSTACK_API_VERSION_V2) is False
+ @parameterized.expand(
+ [
+ (MARKETSTACK_API_VERSION_V1, "https://api.marketstack.com/v1/exchanges"),
+ (MARKETSTACK_API_VERSION_V2, "https://api.marketstack.com/v2/exchanges"),
+ ]
+ )
+ def test_probe_url_matches_pinned_version(self, version: str, expected_url: str) -> None:
+ response = mock.MagicMock()
+ response.status_code = 200
+ response.json.return_value = {"data": []}
+ session = mock.MagicMock()
+ session.get.return_value = response
+ with mock.patch(MARKETSTACK_SESSION_PATCH, return_value=session):
+ validate_credentials("k", version)
+ assert session.get.call_args.args[0] == expected_url
+
+
+class TestBaseUrl:
+ @parameterized.expand(
+ [
+ (MARKETSTACK_API_VERSION_V1, "https://api.marketstack.com/v1"),
+ (MARKETSTACK_API_VERSION_V2, "https://api.marketstack.com/v2"),
+ ]
+ )
+ def test_base_url_per_supported_version(self, version: str, expected: str) -> None:
+ assert marketstack_base_url(version) == expected
+
+ def test_unknown_version_raises(self) -> None:
+ # A pin with no mapped base URL must fail loud rather than silently drop the version segment.
+ with pytest.raises(ValueError, match="Unsupported Marketstack API version"):
+ marketstack_base_url("v3")
+
+ @parameterized.expand([(MARKETSTACK_API_VERSION_V1,), (MARKETSTACK_API_VERSION_V2,)])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_request_hits_pinned_version_host(self, version: str, MockSession) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ sent_urls: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ sent_urls.append(request.url)
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [_page([{"code": "USD"}], total=None)]
+
+ _rows(_source("currencies", symbols=None, api_version=version))
-def test_module_exposes_base_url() -> None:
- assert marketstack.MARKETSTACK_BASE_URL == "https://api.marketstack.com/v1"
+ assert sent_urls[0].startswith(f"https://api.marketstack.com/{version}/")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
index 605648701a03..72eb527bc283 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
@@ -1,3 +1,4 @@
+from datetime import date
from typing import Any
from unittest.mock import MagicMock, patch
@@ -8,6 +9,8 @@ from posthog.schema import SourceFieldInputConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MARKETSTACK_API_VERSION_V1,
+ MARKETSTACK_API_VERSION_V2,
MarketstackResumeConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import ENDPOINTS
@@ -82,10 +85,12 @@ class TestMarketstackSource:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source.validate_marketstack_credentials",
return_value=probe_result,
- ):
+ ) as probe:
ok, message = MarketstackSource().validate_credentials(_make_config(), team_id=1)
assert ok is expected_ok
assert message == expected_message
+ # A pre-creation probe (no pin) resolves to the default version the new row is stamped with.
+ assert probe.call_args.args[1] == MARKETSTACK_API_VERSION_V2
def test_get_resumable_source_manager_binds_resume_config(self) -> None:
inputs = MagicMock()
@@ -100,6 +105,7 @@ class TestMarketstackSource:
inputs.logger = MagicMock()
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = "2021-04-09"
+ inputs.api_version = MARKETSTACK_API_VERSION_V2
response = MarketstackSource().source_for_pipeline(_make_config("abc", "AAPL,MSFT"), MagicMock(), inputs)
@@ -112,6 +118,7 @@ class TestMarketstackSource:
inputs.logger = MagicMock()
inputs.should_use_incremental_field = False
inputs.db_incremental_field_last_value = "should-be-ignored"
+ inputs.api_version = MARKETSTACK_API_VERSION_V2
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source.marketstack_source"
@@ -120,6 +127,37 @@ class TestMarketstackSource:
# A full-refresh run must never forward a stale watermark to the transport.
assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None
+ @parameterized.expand(
+ [
+ ("no_pin_resolves_to_default", None, MARKETSTACK_API_VERSION_V2),
+ ("legacy_pin_honored", MARKETSTACK_API_VERSION_V1, MARKETSTACK_API_VERSION_V1),
+ ("new_pin_honored", MARKETSTACK_API_VERSION_V2, MARKETSTACK_API_VERSION_V2),
+ ]
+ )
+ def test_source_for_pipeline_threads_resolved_version(self, _name: str, pin: str | None, expected: str) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "eod"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = False
+ inputs.api_version = pin
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source.marketstack_source"
+ ) as mocked:
+ MarketstackSource().source_for_pipeline(_make_config(), MagicMock(), inputs)
+ assert mocked.call_args.kwargs["api_version"] == expected
+
+ def test_version_metadata_declares_v1_deprecation(self) -> None:
+ source = MarketstackSource()
+ assert source.supported_versions == (MARKETSTACK_API_VERSION_V1, MARKETSTACK_API_VERSION_V2)
+ assert source.default_version == MARKETSTACK_API_VERSION_V2
+ # The deprecated v1 carries the vendor's announced sunset date; the generic banner reads it.
+ deprecation = source.get_version_deprecation(MARKETSTACK_API_VERSION_V1)
+ assert deprecation is not None
+ assert deprecation.sunset_at == date(2025, 6, 30)
+ # The current default must never be flagged deprecated.
+ assert source.get_version_deprecation(MARKETSTACK_API_VERSION_V2) is None
+
@parameterized.expand(
[
("http_unauthorized", "401 Client Error: Unauthorized for url: https://api.marketstack.com"),