: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(data-warehouse): implement upstash import source (#70006)
Tom Owers70162b90932a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 37a4cc6cb7bb..02ecafae5034 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -403,6 +403,7 @@ the row lists both.| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ || unleash | HTTP | requests | ✅ |+| upstash | HTTP | requests | ✅ || vantage | HTTP | requests | ✅ || vellum | HTTP | requests | ✅ || vercel | HTTP | requests | ✅ |@@ -835,7 +836,6 @@ doesn't conflict with concurrent PRs.- unleash- unstructured- uppromote-- upstash- uptick- us_census- uservoicediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 3eeec3362884..45363616010b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3919,7 +3919,8 @@ class UpPromoteSourceConfig(config.Config):@config.configclass UpstashSourceConfig(config.Config):- pass+ email: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/canonical_descriptions.pynew file mode 100644index 000000000000..61ffd320b1cc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/canonical_descriptions.py@@ -0,0 +1,91 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the Upstash Developer API reference+# (https://upstash.com/docs/devops/developer-api). Keyed by the endpoint/schema name from+# get_schemas / ENDPOINTS; any column not covered here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "redis_databases": {+ "description": "Every Upstash Redis database on the account, with its configuration, plan, region, and state.",+ "docs_url": "https://upstash.com/docs/devops/developer-api/redis/list_databases",+ "columns": {+ "database_id": "Unique identifier of the database.",+ "database_name": "Name of the database.",+ "region": "Region the database is deployed in (global for global databases).",+ "type": "Plan of the database (free, payg, pro, or paid).",+ "port": "Port the database listens on.",+ "creation_time": "Creation time of the database as Unix time (seconds).",+ "state": "State of the database (active, suspended, or passive).",+ "endpoint": "Endpoint hostname used to connect to the database.",+ "tls": "Whether TLS/SSL is enabled.",+ "eviction": "Whether key eviction is enabled.",+ "auto_upgrade": "Whether auto-upgrade is enabled.",+ "consistent": "Whether strong consistency mode is enabled.",+ "primary_region": "Primary region for the database.",+ "read_regions": "Read replica regions for the database.",+ "db_resource_size": "Provisioned resource size (S, M, L, XL, XXL, or 3XL).",+ "daily_backup_enabled": "Whether daily backups are enabled.",+ },+ },+ "redis_stats": {+ "description": "Usage and billing statistics for each Redis database: daily and monthly commands, bandwidth, storage, latency percentiles, and cache hit/miss counts. One row per database.",+ "docs_url": "https://upstash.com/docs/devops/developer-api/redis/get_database_stats",+ "columns": {+ "database_id": "Identifier of the database these stats belong to.",+ "daily_net_commands": "Total commands run in the last day.",+ "daily_read_requests": "Read requests in the last day.",+ "daily_write_requests": "Write requests in the last day.",+ "dailybandwidth": "Bandwidth used in the last day, in bytes.",+ "total_monthly_billing": "Total billing for the current month.",+ "total_monthly_bandwidth": "Total bandwidth used this month, in bytes.",+ "total_monthly_requests": "Total requests this month.",+ "total_monthly_storage": "Total storage used this month, in bytes.",+ "current_storage": "Current storage used, in bytes.",+ "dailybilling": "Daily billing as a time series of {x, y} points.",+ "dailyrequests": "Daily requests as a time series of {x, y} points.",+ "bandwidths": "Bandwidth as a time series of {x, y} points.",+ },+ },+ "teams": {+ "description": "Teams the account belongs to.",+ "docs_url": "https://upstash.com/docs/devops/developer-api/teams/list_teams",+ "columns": {+ "team_id": "Unique identifier of the team.",+ "team_name": "Name of the team.",+ "copy_cc": "Whether credit card information was copied to the team on creation.",+ },+ },+ "vector_indexes": {+ "description": "Upstash Vector indexes on the account, with their configuration, plan, and per-plan limits.",+ "docs_url": "https://upstash.com/docs/devops/developer-api/vector/list_indices",+ "columns": {+ "id": "Unique identifier of the vector index.",+ "customer_id": "Owner of the index.",+ "name": "Name of the index.",+ "similarity_function": "Similarity function used (COSINE, EUCLIDEAN, or DOT_PRODUCT).",+ "dimension_count": "Number of dimensions per vector.",+ "embedding_model": "Predefined text embedding model, if configured.",+ "index_type": "Index type (DENSE, SPARSE, or HYBRID).",+ "type": "Plan of the index (free, payg, or fixed).",+ "region": "Region the index is deployed in.",+ "endpoint": "REST endpoint of the index.",+ "creation_time": "Creation time of the index as Unix time (seconds).",+ },+ },+ "audit_logs": {+ "description": "Chronological record of actions taken on the account and its databases (creations, deletions, config changes), with the actor and originating IP.",+ "docs_url": "https://upstash.com/docs/devops/developer-api/account/list_audit_logs",+ "columns": {+ "log_id": "Unique identifier for the log entry.",+ "customer_id": "ID or email of the associated customer.",+ "actor": "The user or system that performed the action.",+ "timestamp": "Unix timestamp of when the action occurred.",+ "action": "Numeric id representing the specific action type.",+ "action_string": "Human-readable description of the action.",+ "source": "The source method or client used to perform the action.",+ "entity": "The primary entity affected by the action.",+ "ip": "The IP address from which the request originated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/settings.pynew file mode 100644index 000000000000..122ccbc31767--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/settings.py@@ -0,0 +1,74 @@+from dataclasses import dataclass++# The Upstash Developer (management) API. Almost every resource lives under the versioned base.+UPSTASH_API_BASE_URL = "https://api.upstash.com/v2"+# Audit logs are the one exception: they are served from the unversioned host (GET /auditlogs).+UPSTASH_ROOT_BASE_URL = "https://api.upstash.com"+++@dataclass+class UpstashEndpointConfig:+ name: str+ # Path appended to `base_url`. For fan-out endpoints it is a template carrying `{database_id}`.+ path: str+ # Composite/primary key columns used to dedupe on merge. Fan-out children include the parent id.+ primary_keys: list[str]+ # Host the path is appended to. Defaults to the versioned base; audit logs override it.+ base_url: str = UPSTASH_API_BASE_URL+ # Fan out over every Redis database id, calling `path.format(database_id=...)` once per database.+ fan_out_over_databases: bool = False+ # Whether the table is selected for sync by default in the wizard.+ should_sync_default: bool = True+ # Response fields carrying credentials/secrets. They are stripped from every row before it reaches+ # the warehouse, and their presence disables HTTP sample capture for the endpoint (the generic+ # scrubber does not redact fields named `token`).+ sensitive_fields: frozenset[str] = frozenset()+++# The Upstash management API is full-refresh only: no list endpoint documents pagination, and none+# exposes a server-side created/updated-since filter (probed against the live API — the databases,+# teams, vector index, and auditlogs endpoints accept no query parameters). Entity volumes are tiny+# (an account rarely has more than dozens of databases/indices), so a full refresh over each small+# collection is cheap. No endpoint is incremental, so none declares incremental fields.+UPSTASH_ENDPOINTS: dict[str, UpstashEndpointConfig] = {+ # GET /v2/redis/databases -> raw array of Database objects (config, plan, state, creation_time).+ "redis_databases": UpstashEndpointConfig(+ name="redis_databases",+ path="/redis/databases",+ primary_keys=["database_id"],+ ),+ # GET /v2/redis/stats/{id} -> one DatabaseStats object per database (daily/monthly usage, billing,+ # bandwidth, storage, latency percentiles, cache hits/misses as {x, y} time series). Fanned out+ # over every database id; each row carries its `database_id` so the key is unique table-wide.+ "redis_stats": UpstashEndpointConfig(+ name="redis_stats",+ path="/redis/stats/{database_id}",+ primary_keys=["database_id"],+ fan_out_over_databases=True,+ ),+ # GET /v2/teams -> raw array of Team objects (team_id, team_name, copy_cc).+ "teams": UpstashEndpointConfig(+ name="teams",+ path="/teams",+ primary_keys=["team_id"],+ ),+ # GET /v2/vector/index -> raw array of VectorIndex objects (config, plan, limits, creation_time).+ # `token` and `read_only_token` are write-capable index credentials; strip them so warehouse+ # readers can't retrieve them, and keep the whole response out of HTTP sample capture.+ "vector_indexes": UpstashEndpointConfig(+ name="vector_indexes",+ path="/vector/index",+ primary_keys=["id"],+ sensitive_fields=frozenset({"token", "read_only_token"}),+ ),+ # GET /auditlogs (unversioned host) -> raw array of AuditLog objects (actor, action, entity,+ # timestamp, ip). No time-range or pagination params documented, so it is full refresh.+ "audit_logs": UpstashEndpointConfig(+ name="audit_logs",+ path="/auditlogs",+ primary_keys=["log_id"],+ base_url=UPSTASH_ROOT_BASE_URL,+ ),+}++ENDPOINTS = tuple(UPSTASH_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/source.pyindex 9720d5057a2f..02c5ca8eb159 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UpstashSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.settings import (+ ENDPOINTS,+ UPSTASH_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.upstash import (+ upstash_source,+ validate_credentials as validate_upstash_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass UpstashSource(SimpleSource[UpstashSourceConfig]):+ # get_schemas iterates a static endpoint catalog with no I/O, so the public docs can render the+ # Supported tables section without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.UPSTASH@@ -24,8 +47,87 @@ class UpstashSource(SimpleSource[UpstashSourceConfig]):name=SchemaExternalDataSourceType.UPSTASH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Upstash",- iconPath="/static/services/upstash.png",- keywords=["redis", "serverless", "qstash", "usage"],- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Upstash account email and a management API key to pull your Upstash Redis databases, usage stats, teams, and vector indexes into the PostHog Data warehouse.++Create a management API key in the [Upstash console](https://console.upstash.com/account/api) under **Account > Management API**. The Developer API is only available to native Upstash accounts (not Vercel or Fly.io marketplace accounts).""",+ iconPath="/static/services/upstash.png",+ docsUrl="https://posthog.com/docs/cdp/sources/upstash",+ keywords=["redis", "serverless", "qstash", "vector"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="email",+ label="Account email",+ type=SourceFieldInputConfigType.EMAIL,+ required=True,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="Management API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch` calls raise_for_status(). Retrying+ # never satisfies a credential problem, so stop the sync. Match the stable status text and+ # base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.upstash.com": "Your Upstash email or management API key is invalid or has been revoked. Create a new key in the Upstash console, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.upstash.com": "Your Upstash management API key is not authorized for this resource. Check the key, then reconnect.",+ }++ def get_schemas(+ self,+ config: UpstashSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every Upstash management endpoint is full refresh (no pagination, no server-side time+ # filter), so no schema advertises incremental fields.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=UPSTASH_ENDPOINTS[endpoint].should_sync_default,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: UpstashSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_upstash_credentials(config.email, config.api_key)++ def source_for_pipeline(self, config: UpstashSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return upstash_source(+ email=config.email,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash.pynew file mode 100644index 000000000000..1b5e837dd8f9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash.py@@ -0,0 +1,237 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.upstash import upstash+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.settings import (+ UPSTASH_API_BASE_URL,+ UPSTASH_ENDPOINTS,+ UPSTASH_ROOT_BASE_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.upstash import (+ UpstashRetryableError,+ _fetch,+ get_rows,+ upstash_source,+ validate_credentials,+)+++def _http_error(status: int) -> requests.HTTPError:+ response = requests.Response()+ response.status_code = status+ return requests.HTTPError(response=response)+++def _collect(endpoint: str, url_responses: dict[str, Any]) -> tuple[list[dict], list[str]]:+ """Run get_rows with _fetch stubbed by a URL->response (or exception) map. Records call order."""+ calls: list[str] = []++ def fake_fetch(session: Any, url: str, auth: Any, logger: Any) -> Any:+ calls.append(url)+ result = url_responses[url]+ if isinstance(result, Exception):+ raise result+ return result++ with patch.object(upstash, "_fetch", fake_fetch):+ rows = list(get_rows(email="e", api_key="k", endpoint=endpoint, logger=MagicMock()))+ return rows, calls+++class TestGetRowsListEndpoints:+ @parameterized.expand(+ [+ ("redis_databases", f"{UPSTASH_API_BASE_URL}/redis/databases", "database_id"),+ ("teams", f"{UPSTASH_API_BASE_URL}/teams", "team_id"),+ ("vector_indexes", f"{UPSTASH_API_BASE_URL}/vector/index", "id"),+ # Audit logs are served from the unversioned host, not api.upstash.com/v2.+ ("audit_logs", f"{UPSTASH_ROOT_BASE_URL}/auditlogs", "log_id"),+ ]+ )+ def test_yields_dicts_from_raw_array_at_expected_url(self, endpoint: str, expected_url: str, pk: str) -> None:+ rows, calls = _collect(endpoint, {expected_url: [{pk: "a"}, {pk: "b"}]})+ assert [r[pk] for r in rows] == ["a", "b"]+ assert calls == [expected_url]++ def test_non_list_response_raises(self) -> None:+ # A malformed body (object instead of array) must fail the sync loudly rather than silently+ # replace the warehouse table with zero rows.+ url = f"{UPSTASH_API_BASE_URL}/teams"+ with pytest.raises(ValueError):+ _collect("teams", {url: {"unexpected": "shape"}})++ def test_non_dict_items_are_skipped(self) -> None:+ url = f"{UPSTASH_API_BASE_URL}/teams"+ rows, _ = _collect("teams", {url: [{"team_id": "t1"}, "garbage", None]})+ assert [r["team_id"] for r in rows] == ["t1"]++ def test_sensitive_fields_are_stripped_from_rows(self) -> None:+ # Vector index tokens are write-capable credentials; they must never reach warehouse columns.+ url = f"{UPSTASH_API_BASE_URL}/vector/index"+ rows, _ = _collect(+ "vector_indexes",+ {url: [{"id": "i1", "name": "idx", "token": "secret", "read_only_token": "ro-secret"}]},+ )+ assert rows == [{"id": "i1", "name": "idx"}]+++class TestGetRowsStatsFanOut:+ def test_fans_out_per_database_and_stamps_database_id(self) -> None:+ db_url = f"{UPSTASH_API_BASE_URL}/redis/databases"+ stats1 = f"{UPSTASH_API_BASE_URL}/redis/stats/db1"+ stats2 = f"{UPSTASH_API_BASE_URL}/redis/stats/db2"+ rows, calls = _collect(+ "redis_stats",+ {+ db_url: [{"database_id": "db1"}, {"database_id": "db2"}],+ stats1: {"total_monthly_billing": 1.5},+ stats2: {"total_monthly_billing": 2.0},+ },+ )+ assert rows == [+ {"total_monthly_billing": 1.5, "database_id": "db1"},+ {"total_monthly_billing": 2.0, "database_id": "db2"},+ ]+ assert calls == [db_url, stats1, stats2]++ def test_skips_database_deleted_between_enumeration_and_stats_fetch(self) -> None:+ db_url = f"{UPSTASH_API_BASE_URL}/redis/databases"+ stats1 = f"{UPSTASH_API_BASE_URL}/redis/stats/db1"+ stats2 = f"{UPSTASH_API_BASE_URL}/redis/stats/db2"+ rows, _ = _collect(+ "redis_stats",+ {+ db_url: [{"database_id": "db1"}, {"database_id": "db2"}],+ stats1: _http_error(404),+ stats2: {"total_monthly_billing": 2.0},+ },+ )+ assert rows == [{"total_monthly_billing": 2.0, "database_id": "db2"}]++ def test_non_404_error_during_fan_out_propagates(self) -> None:+ db_url = f"{UPSTASH_API_BASE_URL}/redis/databases"+ stats1 = f"{UPSTASH_API_BASE_URL}/redis/stats/db1"+ try:+ _collect("redis_stats", {db_url: [{"database_id": "db1"}], stats1: _http_error(500)})+ except requests.HTTPError as exc:+ assert exc.response is not None and exc.response.status_code == 500+ else:+ raise AssertionError("expected the 500 to propagate")++ def test_database_row_missing_id_raises(self) -> None:+ # The stats sync fans out over every database id; a row missing its id must fail the sync+ # rather than be silently dropped, which would yield partial usage/billing data.+ db_url = f"{UPSTASH_API_BASE_URL}/redis/databases"+ with pytest.raises(KeyError):+ _collect("redis_stats", {db_url: [{"database_id": "db1"}, {"not_the_id": "x"}]})+++class TestHttpSampleCapture:+ # Responses that carry secrets (vector index tokens) must be excluded from HTTP sample capture,+ # since the generic scrubber does not redact fields named `token`. Other endpoints keep capture on.+ @parameterized.expand([("vector_indexes", False), ("teams", True)])+ def test_capture_flag_tracks_sensitive_endpoints(self, endpoint: str, expected_capture: bool) -> None:+ captured: dict[str, Any] = {}++ def fake_session(*args: Any, **kwargs: Any) -> Any:+ captured["capture"] = kwargs.get("capture", True)+ return MagicMock()++ with patch.object(upstash, "make_tracked_session", fake_session):+ with patch.object(upstash, "_fetch", lambda *a, **k: []):+ list(get_rows(email="e", api_key="k", endpoint=endpoint, logger=MagicMock()))+ assert captured["capture"] is expected_capture+++class TestFetchRetryClassification:+ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ response = requests.Response()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ # stop_after_attempt exhausts and reraises the last UpstashRetryableError.+ try:+ _fetch(session, "https://api.upstash.com/v2/teams", ("e", "k"), MagicMock())+ except UpstashRetryableError:+ pass+ else:+ raise AssertionError("expected UpstashRetryableError")++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_for_status(self, status: int) -> None:+ response = requests.Response()+ response.status_code = status+ response.url = "https://api.upstash.com/v2/teams"+ session = MagicMock()+ session.get.return_value = response+ try:+ _fetch(session, response.url, ("e", "k"), MagicMock())+ except requests.HTTPError:+ pass+ else:+ raise AssertionError("expected HTTPError from raise_for_status")+++class TestValidateCredentials:+ # Only a definitive 401/403 rejects the credentials. 429/5xx are transient (retried during sync)+ # and must not block source creation during an Upstash outage or rate-limit window.+ @parameterized.expand([(200, True), (401, False), (403, False), (429, True), (500, True)])+ def test_status_mapping(self, status: int, expected_ok: bool) -> None:+ response = requests.Response()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(upstash, "make_tracked_session", lambda *a, **k: session):+ ok, error = validate_credentials("e", "k")+ assert ok is expected_ok+ assert (error is None) is expected_ok++ def test_probes_teams_endpoint_with_basic_auth(self) -> None:+ response = requests.Response()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(upstash, "make_tracked_session", lambda *a, **k: session):+ validate_credentials("[email protected]", "secret")+ _, kwargs = session.get.call_args+ assert session.get.call_args[0][0] == f"{UPSTASH_API_BASE_URL}/teams"+ assert kwargs["auth"] == ("[email protected]", "secret")++ def test_request_exception_does_not_block_creation(self) -> None:+ # An unreachable API is transient, not a credential rejection; a genuine auth failure still+ # surfaces at sync time.+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(upstash, "make_tracked_session", lambda *a, **k: session):+ ok, error = validate_credentials("e", "k")+ assert ok is True+ assert error is None+++class TestUpstashSource:+ @parameterized.expand(+ [+ ("redis_databases", ["database_id"]),+ ("redis_stats", ["database_id"]),+ ("teams", ["team_id"]),+ ("vector_indexes", ["id"]),+ ("audit_logs", ["log_id"]),+ ]+ )+ def test_source_response_primary_keys_and_sort(self, endpoint: str, expected_pk: list[str]) -> None:+ response = upstash_source(email="e", api_key="k", endpoint=endpoint, logger=MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == expected_pk+ # Full refresh, replaced wholesale each sync; asc is the pipeline default.+ assert response.sort_mode == "asc"++ def test_every_declared_endpoint_has_a_response(self) -> None:+ for endpoint in UPSTASH_ENDPOINTS:+ response = upstash_source(email="e", api_key="k", endpoint=endpoint, logger=MagicMock())+ assert response.primary_keys == UPSTASH_ENDPOINTS[endpoint].primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash_source.pynew file mode 100644index 000000000000..a9a34305e8cf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/tests/test_upstash_source.py@@ -0,0 +1,127 @@+from typing import Any, cast++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UpstashSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash import source as upstash_source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.source import UpstashSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestUpstashSource:+ def setup_method(self) -> None:+ self.source = UpstashSource()+ self.config = UpstashSourceConfig(email="[email protected]", api_key="key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.UPSTASH++ def test_source_config_metadata(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Upstash"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Hidden until exercised against the live API.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/upstash"++ def test_source_config_fields(self) -> None:+ fields = {f.name: cast(SourceFieldInputConfig, f) for f in self.source.get_source_config.fields}+ assert set(fields) == {"email", "api_key"}+ assert fields["email"].required is True+ # The management API key is a credential: it must be a secret password field so it is never+ # echoed back or logged in the clear.+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas iterates a static catalog with no I/O, so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_are_all_full_refresh(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert set(schemas) == {"redis_databases", "redis_stats", "teams", "vector_indexes", "audit_logs"}+ # No Upstash management endpoint exposes a server-side time filter, so none is incremental.+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["teams"])+ assert [s.name for s in schemas] == ["teams"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # Public-docs table catalog must be derivable with no network/credentials.+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == {"redis_databases", "redis_stats", "teams", "vector_indexes", "audit_logs"}+ assert tables["redis_databases"]["sync_methods"] == ["Full refresh"]+ assert tables["redis_databases"]["primary_keys"] == [] # unknown until first sync++ @parameterized.expand(+ [("valid", (True, None)), ("invalid", (False, "Invalid Upstash email or management API key"))]+ )+ def test_validate_credentials_delegates(self, _name: str, result: tuple) -> None:+ with mock.patch.object(upstash_source_module, "validate_upstash_credentials", lambda email, api_key: result):+ assert self.source.validate_credentials(self.config, team_id=1) == result++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.upstash.com/v2/teams"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.upstash.com/auditlogs"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.upstash.com/v2/teams"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.upstash.com/v2/teams"),+ ("read_timeout", "HTTPSConnectionPool(host='api.upstash.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ captured: dict[str, Any] = {}++ def fake_upstash_source(**kwargs: Any):+ captured.update(kwargs)+ return MagicMock(name="source_response")++ inputs = _source_inputs("redis_databases")+ with mock.patch.object(upstash_source_module, "upstash_source", fake_upstash_source):+ self.source.source_for_pipeline(self.config, inputs)++ assert captured["email"] == "[email protected]"+ assert captured["api_key"] == "key"+ assert captured["endpoint"] == "redis_databases"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/upstash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/upstash.pynew file mode 100644index 000000000000..0bfb62aba09b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/upstash/upstash.py@@ -0,0 +1,160 @@+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.upstash.settings import (+ UPSTASH_API_BASE_URL,+ UPSTASH_ENDPOINTS,+ UpstashEndpointConfig,+)++# Upstash does not document rate limits on the management API, but a 429 or a transient 5xx should+# still back off rather than fail the sync. Auth failures (401/403) are surfaced via raise_for_status+# and matched by get_non_retryable_errors() so the sync stops instead of retrying forever.+_MAX_ATTEMPTS = 5+++class UpstashRetryableError(Exception):+ pass+++def _auth(email: str, api_key: str) -> tuple[str, str]:+ """HTTP Basic auth: account email as username, management API key as password."""+ return (email, api_key)+++@retry(+ retry=retry_if_exception_type((UpstashRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, auth: tuple[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, auth=auth, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise UpstashRetryableError(f"Upstash API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Log only status and the (credential-free) URL. Response bodies can carry account data+ # (e.g. audit-log error payloads), which must not be copied into broadly-readable logs.+ logger.error(f"Upstash API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(email: str, api_key: str) -> tuple[bool, str | None]:+ """Confirm the email + management API key are genuine via GET /v2/teams.++ /v2/teams is the cheapest authenticated probe available to any native Upstash account regardless+ of which resources exist, and it needs no path parameters. Only a definitive 401/403 rejects the+ credentials; a 429, a 5xx, or an unreachable API is transient and must not block source creation,+ since the same statuses are retried during the sync itself and a genuine auth failure still+ surfaces at sync time via get_non_retryable_errors().+ """+ url = f"{UPSTASH_API_BASE_URL}/teams"+ try:+ response = make_tracked_session().get(url, auth=_auth(email, api_key), timeout=10)+ except requests.exceptions.RequestException:+ return True, None++ if response.status_code in (401, 403):+ return False, "Invalid Upstash email or management API key"+ return True, None+++def _fetch_list(session: requests.Session, url: str, auth: tuple[str, str], logger: FilteringBoundLogger) -> list[Any]:+ """Fetch an endpoint that must return a JSON array. A non-list body is a hard error, not an empty+ result: silently yielding nothing would replace the warehouse table with zero rows on an API-shape+ mismatch or a transient proxy body, hiding the failure instead of surfacing it."""+ data = _fetch(session, url, auth, logger)+ if not isinstance(data, list):+ raise ValueError(f"Upstash API returned a non-list response for {url}")+ return data+++def _strip_sensitive(row: dict[str, Any], sensitive_fields: frozenset[str]) -> dict[str, Any]:+ """Drop credential-bearing fields (e.g. vector index tokens) before a row reaches the warehouse."""+ if not sensitive_fields:+ return row+ return {key: value for key, value in row.items() if key not in sensitive_fields}+++def _iter_database_ids(session: requests.Session, auth: tuple[str, str], logger: FilteringBoundLogger) -> list[str]:+ """List every Redis database id, used to fan out the per-database stats endpoint. A database row+ missing its `database_id` is an invalid response and raises rather than being silently dropped:+ the stats sync depends on every id, so a partial list would produce partial usage/billing data."""+ data = _fetch_list(session, f"{UPSTASH_API_BASE_URL}/redis/databases", auth, logger)+ return [db["database_id"] for db in data if isinstance(db, dict)]+++def _fan_out_stats_rows(+ session: requests.Session,+ auth: tuple[str, str],+ logger: FilteringBoundLogger,+ config: UpstashEndpointConfig,+) -> Iterator[dict[str, Any]]:+ """Yield one stats row per Redis database, stamping each with its `database_id`.++ The stats object itself carries no id, so we inject `database_id` (the fan-out parent key) to make+ the primary key unique table-wide. A database deleted between enumeration and its stats fetch 404s;+ skip it rather than failing the whole sync.+ """+ for database_id in _iter_database_ids(session, auth, logger):+ url = f"{config.base_url}{config.path.format(database_id=database_id)}"+ try:+ stats = _fetch(session, url, auth, logger)+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Upstash: database {database_id} not found while fetching stats, skipping")+ continue+ raise+ if isinstance(stats, dict):+ yield _strip_sensitive({**stats, "database_id": database_id}, config.sensitive_fields)+++def get_rows(+ email: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[Any]:+ config = UPSTASH_ENDPOINTS[endpoint]+ auth = _auth(email, api_key)+ # One session reused across every request so urllib3 keeps the connection alive. Endpoints whose+ # responses carry secrets are kept out of HTTP sample capture (the scrubber does not redact tokens).+ session = make_tracked_session(capture=not config.sensitive_fields)++ if config.fan_out_over_databases:+ yield from _fan_out_stats_rows(session, auth, logger, config)+ return++ # Every non-fan-out endpoint returns a raw JSON array in one request (no pagination).+ data = _fetch_list(session, f"{config.base_url}{config.path}", auth, logger)+ for item in data:+ if isinstance(item, dict):+ yield _strip_sensitive(item, config.sensitive_fields)+++def upstash_source(+ email: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ endpoint_config = UPSTASH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(email=email, api_key=api_key, endpoint=endpoint, logger=logger),+ primary_keys=endpoint_config.primary_keys,+ # Full refresh with no server-side ordering guarantee; asc is the pipeline default and the+ # tables are replaced wholesale each sync, so no incremental watermark depends on the order.+ sort_mode="asc",+ )