: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 luma import source (#69346)
Tom Owersad6db3ed7a64
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 254764a64a34..41b9fd55a561 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -225,6 +225,7 @@ the row lists both.| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ || linkrunner | HTTP | requests | ✅ || lob | HTTP | requests | ✅ |+| luma | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ || mailerlite | HTTP | requests | ✅ || mailersend | HTTP | requests | ✅ |@@ -589,7 +590,6 @@ doesn't conflict with concurrent PRs.- lokalise- looker- loops-- luma- m3ter- mailtrap- mantlediff --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 31fe8b8fcc61..5aca3bd25e38 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@@ -1997,7 +1997,7 @@ class LoopsSourceConfig(config.Config):@config.configclass LumaSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/canonical_descriptions.pynew file mode 100644index 000000000000..b7481667a369--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/canonical_descriptions.py@@ -0,0 +1,73 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "An event managed by your Luma calendar, including its schedule, location, and public URL.",+ "docs_url": "https://docs.luma.com/reference",+ "columns": {+ "api_id": "Unique identifier for the event (evt-...).",+ "name": "Name of the event.",+ "description": "Plain-text description of the event.",+ "description_md": "Markdown description of the event.",+ "created_at": "When the event was created (ISO 8601).",+ "start_at": "When the event starts (ISO 8601).",+ "end_at": "When the event ends (ISO 8601).",+ "duration_interval": "Duration of the event as an ISO 8601 interval.",+ "timezone": "IANA timezone the event is scheduled in.",+ "event_type": "Type of the event (e.g. independent or series).",+ "cover_url": "URL of the event's cover image.",+ "url": "Public Luma URL of the event page.",+ "meeting_url": "Virtual meeting URL for online events.",+ "zoom_meeting_url": "Zoom meeting URL when the event uses Zoom.",+ "geo_address_json": "Structured address of the venue for in-person events.",+ "geo_latitude": "Latitude of the event venue.",+ "geo_longitude": "Longitude of the event venue.",+ "visibility": "Whether the event is public or private.",+ "user_api_id": "Identifier of the Luma user who created the event.",+ },+ },+ "guests": {+ "description": "A guest registration for one of your events, including approval status, tickets, and registration answers.",+ "docs_url": "https://docs.luma.com/reference",+ "columns": {+ "api_id": "Unique identifier for the guest registration (gst-...).",+ "event_api_id": "Identifier of the event the guest registered for (added by PostHog for joining to events).",+ "approval_status": "Registration status of the guest (e.g. approved, pending_approval, declined).",+ "created_at": "When the guest record was created (ISO 8601).",+ "registered_at": "When the guest registered for the event (ISO 8601).",+ "invited_at": "When the guest was invited to the event (ISO 8601).",+ "name": "Name the guest registered with.",+ "email": "Email address the guest registered with.",+ "phone_number": "Phone number the guest registered with.",+ "user_api_id": "Identifier of the guest's Luma user account.",+ "user_email": "Email address of the guest's Luma user account.",+ "user_name": "Name of the guest's Luma user account.",+ "event_ticket": "Ticket the guest holds for the event, including amount paid.",+ "event_tickets": "All tickets the guest holds for the event.",+ "registration_answers": "Answers the guest gave to the event's registration questions.",+ "check_in_qr_code": "QR code payload used to check the guest in at the event.",+ "custom_source": "Custom source tag attached to the registration link the guest used.",+ "eth_address": "Ethereum wallet address the guest registered with, when collected.",+ },+ },+ "people": {+ "description": "A person on your Luma calendar's audience list, aggregated across event registrations and subscriptions.",+ "docs_url": "https://docs.luma.com/reference",+ "columns": {+ "api_id": "Unique identifier for the person.",+ "name": "Name of the person.",+ "email": "Email address of the person.",+ "created_at": "When the person was added to the calendar (ISO 8601).",+ },+ },+ "person_tags": {+ "description": "A tag used to segment people on your Luma calendar.",+ "docs_url": "https://docs.luma.com/reference",+ "columns": {+ "api_id": "Unique identifier for the tag.",+ "name": "Name of the tag.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.pynew file mode 100644index 000000000000..7fe3a7cbae06--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.py@@ -0,0 +1,247 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.settings import (+ EVENTS_PATH,+ LUMA_ENDPOINTS,+ LumaEndpointConfig,+)++LUMA_BASE_URL = "https://public-api.luma.com"+# The docs don't state a hard maximum for `pagination_limit`; 50 keeps pages small while staying+# well inside the 200-500 req/min rate limits.+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+# Cheap probe used to confirm an API key is genuine. Keys are calendar- or organization-scoped and+# grant access to every read endpoint, so one probe validates the whole source.+DEFAULT_PROBE_PATH = EVENTS_PATH+++class LumaRetryableError(Exception):+ pass+++class LumaResumeConfig:+ # `next_cursor` from the last fully processed page, passed back as `pagination_cursor`. For the+ # guests fan-out this is the *events list* cursor: state is saved only after every guest of an+ # events page has been yielded, so a resume re-pulls at most one page of parents and merge+ # dedupes the re-pulled rows on the primary key.+ pagination_cursor: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"x-luma-api-key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((LumaRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ cursor: str | None,+ logger: FilteringBoundLogger,+ extra_params: dict[str, Any] | None = None,+) -> tuple[list[dict[str, Any]], Optional[str]]:+ params: dict[str, Any] = {"pagination_limit": PAGE_SIZE, **(extra_params or {})}+ # The first request omits the cursor; subsequent requests pass `next_cursor` from the previous page.+ if cursor is not None:+ params["pagination_cursor"] = cursor++ response = session.get(f"{LUMA_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # Luma returns 429 on rate-limit overage with a one-minute back-off window.+ if response.status_code == 429 or response.status_code >= 500:+ raise LumaRetryableError(f"Luma API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Luma API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict) or not isinstance(data.get("entries"), list):+ raise LumaRetryableError(f"Luma returned an unexpected payload for {path}: {type(data).__name__}")++ next_cursor = data.get("next_cursor")+ # `has_more` is authoritative; a lingering `next_cursor` on the last page must not loop.+ if not data.get("has_more") or not isinstance(next_cursor, str) or not next_cursor:+ next_cursor = None++ return data["entries"], next_cursor+++def _flatten_entry(entry: dict[str, Any], nested_key: str | None) -> dict[str, Any]:+ # Some list endpoints wrap the object in an envelope ({"api_id": ..., "event": {...}}); the+ # nested object carries its own `api_id`, so we yield it directly like other connectors do.+ if nested_key is not None:+ nested = entry.get(nested_key)+ if isinstance(nested, dict):+ return nested+ return entry+++def _get_event_api_ids(entries: list[dict[str, Any]]) -> list[str]:+ api_ids: list[str] = []+ for entry in entries:+ event = _flatten_entry(entry, "event")+ api_id = event.get("api_id")+ if isinstance(api_id, str) and api_id:+ api_ids.append(api_id)+ return api_ids+++def _get_guest_rows_for_event(+ session: requests.Session,+ event_api_id: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = LUMA_ENDPOINTS["guests"]+ cursor: str | None = None+ while True:+ entries, next_cursor = _fetch_page(+ session, config.path, cursor, logger, extra_params={"event_api_id": event_api_id}+ )+ rows = [{**_flatten_entry(entry, config.nested_key), "event_api_id": event_api_id} for entry in entries]+ if rows:+ yield rows+ if not next_cursor or not entries:+ break+ cursor = next_cursor+++def _get_fan_out_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LumaResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ events_cursor = resume.pagination_cursor if resume else None+ if events_cursor is not None:+ logger.debug(f"Luma: resuming guests fan-out from events cursor {events_cursor}")++ while True:+ event_entries, next_events_cursor = _fetch_page(session, EVENTS_PATH, events_cursor, logger)+ event_api_ids = _get_event_api_ids(event_entries)+ skipped = len(event_entries) - len(event_api_ids)+ if skipped:+ logger.warning(+ f"Luma: {skipped} of {len(event_entries)} events had no usable api_id; their guests are skipped"+ )+ for event_api_id in event_api_ids:+ yield from _get_guest_rows_for_event(session, event_api_id, logger)++ if not next_events_cursor or not event_entries:+ break++ events_cursor = next_events_cursor+ # Save AFTER yielding every guest of this events page, so a crash re-pulls at most one page+ # of parents; merge dedupes the re-pulled rows on the primary key.+ resumable_source_manager.save_state(LumaResumeConfig(pagination_cursor=events_cursor))+++def _get_top_level_rows(+ session: requests.Session,+ config: LumaEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LumaResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.pagination_cursor if resume else None+ if cursor is not None:+ logger.debug(f"Luma: resuming {config.name} from cursor {cursor}")++ while True:+ entries, next_cursor = _fetch_page(session, config.path, cursor, logger)+ rows = [_flatten_entry(entry, config.nested_key) for entry in entries]+ if rows:+ yield rows++ # `has_more=false` ends the collection; an empty page also terminates defensively so a+ # lingering cursor can never produce an infinite loop.+ if not next_cursor or not entries:+ break++ cursor = next_cursor+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(LumaResumeConfig(pagination_cursor=cursor))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LumaResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = LUMA_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ if config.fan_out_over_events:+ yield from _get_fan_out_rows(session, logger, resumable_source_manager)+ else:+ yield from _get_top_level_rows(session, config, logger, resumable_source_manager)+++def luma_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LumaResumeConfig],+) -> SourceResponse:+ config = LUMA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``400``/``401``/``403`` auth failure, ``0``+ for a connection problem, other HTTP status otherwise. Luma answers 400 when the key header is+ missing/blank and 401 when the key is not recognized.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{LUMA_BASE_URL}{path}", params={"pagination_limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Luma: {e}"++ if response.status_code in (400, 401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Luma returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (400, 401, 403):+ return False, "Invalid Luma API key"+ return False, message or "Could not validate Luma API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/settings.pynew file mode 100644index 000000000000..38e0957600c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/settings.py@@ -0,0 +1,41 @@+from dataclasses import dataclass, field+++@dataclass+class LumaEndpointConfig:+ name: str+ path: str+ # Luma wraps some list entries in an envelope ({"api_id": ..., "event": {...}}); when set, rows+ # are flattened to this nested object (which carries its own `api_id`).+ nested_key: str | None = None+ # Luma object identifiers (`evt-...`, `gst-...`, ...) are globally unique `api_id`s.+ primary_keys: list[str] = field(default_factory=lambda: ["api_id"])+ # Guests are fetched per event via `event_api_id`, iterating the events list as the parent.+ fan_out_over_events: bool = False+++EVENTS_PATH = "/public/v1/calendar/list-events"+GUESTS_PATH = "/public/v1/event/get-guests"++# Luma public API list endpoints. All are full refresh only: pagination is cursor-based+# (`pagination_cursor` + `has_more`/`next_cursor`) and there is no server-side updated-since filter.+# list-events only supports `before`/`after` bounds on the event *start* time, which is not a+# modification cursor, so it cannot drive a reliable incremental sync.+LUMA_ENDPOINTS: dict[str, LumaEndpointConfig] = {+ "events": LumaEndpointConfig(name="events", path=EVENTS_PATH, nested_key="event"),+ # Guest api_ids are registration-scoped, but rows aggregate across every event, so the parent+ # event id is part of the key (and useful for joins back to events).+ "guests": LumaEndpointConfig(+ name="guests",+ path=GUESTS_PATH,+ nested_key="guest",+ primary_keys=["event_api_id", "api_id"],+ fan_out_over_events=True,+ ),+ "people": LumaEndpointConfig(name="people", path="/public/v1/calendar/list-people"),+ "person_tags": LumaEndpointConfig(name="person_tags", path="/public/v1/calendar/list-person-tags"),+}++ENDPOINTS = tuple(LUMA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.pyindex a2c815c954de..ed1f6365fb9e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py@@ -1,19 +1,39 @@-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.sources.common.base import FieldType, SimpleSource+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, ResumableSource+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LumaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.luma import (+ LumaResumeConfig,+ luma_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.settings import ENDPOINTS, LUMA_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LumaSource(SimpleSource[LumaSourceConfig]):+class LumaSource(ResumableSource[LumaSourceConfig, LumaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LUMA@@ -24,7 +44,89 @@ class LumaSource(SimpleSource[LumaSourceConfig]):name=SchemaExternalDataSourceType.LUMA,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Luma",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Luma API key to pull your events, guests, and people into the PostHog Data warehouse.++You can create an API key under **Settings → Developer** in [Luma](https://luma.com) — API access requires a Luma Plus subscription. Calendar API keys are scoped to a single calendar; use an organization API key to import across calendars.+""",iconPath="/static/services/luma.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/luma",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.luma.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://public-api.luma.com": "Your Luma API key is invalid or has been revoked. Generate a new key under Settings → Developer in Luma, then reconnect.",+ "403 Client Error: Forbidden for url: https://public-api.luma.com": "Your Luma API key does not have access to this data. Check the key's calendar or organization scope, then reconnect.",+ }++ def get_schemas(+ self,+ config: LumaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Luma's cursor pagination has no server-side+ # updated-since filter (list-events only bounds on event start time), so there is no+ # reliable timestamp cursor to advance an incremental sync.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: LumaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key grants read access to every endpoint on its calendar/organization, so a+ # single probe validates access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LumaResumeConfig]:+ return ResumableSourceManager[LumaResumeConfig](inputs, LumaResumeConfig)++ def source_for_pipeline(+ self,+ config: LumaSourceConfig,+ resumable_source_manager: ResumableSourceManager[LumaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in LUMA_ENDPOINTS:+ raise ValueError(f"Unknown Luma schema '{inputs.schema_name}'")++ return luma_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.pynew file mode 100644index 000000000000..cd29ba5e3f8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.py@@ -0,0 +1,347 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.luma import luma+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.luma import (+ LUMA_BASE_URL,+ LumaResumeConfig,+ LumaRetryableError,+ check_access,+ get_rows,+ luma_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.settings import (+ ENDPOINTS,+ EVENTS_PATH,+ GUESTS_PATH,+ LUMA_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = luma._fetch_page.__wrapped__ # type: ignore[attr-defined]++# Keyed by (path, cursor); the fan-out variant adds the parent event api_id. Annotated on the+# literals below so mypy doesn't narrow all-None keys to an incompatible invariant dict type.+PageMap = dict[tuple[str, str | None], tuple[list[dict], Optional[str]]]+FanOutPageMap = dict[tuple[str, str | None, str | None], tuple[list[dict], Optional[str]]]+++class _FakeResumableManager:+ def __init__(self, state: LumaResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[LumaResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> LumaResumeConfig | None:+ return self._state++ def save_state(self, data: LumaResumeConfig) -> None:+ self.saved.append(data)+++def _page_router(pages: PageMap) -> Any:+ def fake_fetch(+ session: Any, path: str, cursor: str | None, logger: Any, extra_params: dict | None = None+ ) -> tuple[list[dict], Optional[str]]:+ return pages[(path, cursor)]++ return fake_fetch+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: PageMap,+ endpoint: str,+ ) -> list[dict]:+ monkeypatch.setattr(luma, "_fetch_page", _page_router(pages))+ monkeypatch.setattr(luma, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="luma-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_yields_flattened_events_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: PageMap = {+ (EVENTS_PATH, None): (+ [{"api_id": "evt-1", "event": {"api_id": "evt-1", "name": "Meetup"}}],+ None,+ )+ }+ rows = self._collect(manager, monkeypatch, pages, "events")+ # The `event` envelope is unwrapped so columns are top-level.+ assert rows == [{"api_id": "evt-1", "name": "Meetup"}]+ # No next cursor means the sync ends without persisting resume state.+ assert manager.saved == []++ def test_follows_cursor_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ path = LUMA_ENDPOINTS["people"].path+ pages: PageMap = {+ (path, None): ([{"api_id": "per-1"}], "cur-2"),+ (path, "cur-2"): ([{"api_id": "per-2"}], None),+ }+ rows = self._collect(manager, monkeypatch, pages, "people")+ assert rows == [{"api_id": "per-1"}, {"api_id": "per-2"}]+ # State is saved once — after the first page, pointing at the next cursor — then we stop.+ assert [s.pagination_cursor for s in manager.saved] == ["cur-2"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(LumaResumeConfig(pagination_cursor="cur-2"))+ path = LUMA_ENDPOINTS["people"].path+ # The first page must never be fetched on resume.+ pages: PageMap = {(path, "cur-2"): ([{"api_id": "per-2"}], None)}+ rows = self._collect(manager, monkeypatch, pages, "people")+ assert rows == [{"api_id": "per-2"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: PageMap = {(LUMA_ENDPOINTS["person_tags"].path, None): ([], None)}+ rows = self._collect(manager, monkeypatch, pages, "person_tags")+ assert rows == []+ assert manager.saved == []++ def test_entry_without_envelope_is_yielded_as_is(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ # Defensive path: if an events entry has no nested `event` object we keep the raw entry.+ pages: PageMap = {(EVENTS_PATH, None): ([{"api_id": "evt-9"}], None)}+ rows = self._collect(manager, monkeypatch, pages, "events")+ assert rows == [{"api_id": "evt-9"}]+++class TestGuestsFanOut:+ def _collect(+ self,+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: FanOutPageMap,+ ) -> list[dict]:+ def fake_fetch(+ session: Any, path: str, cursor: str | None, logger: Any, extra_params: dict | None = None+ ) -> tuple[list[dict], Optional[str]]:+ event_api_id = (extra_params or {}).get("event_api_id")+ return pages[(path, cursor, event_api_id)]++ monkeypatch.setattr(luma, "_fetch_page", fake_fetch)+ monkeypatch.setattr(luma, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="luma-key",+ endpoint="guests",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_rows_carry_parent_event_api_id(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: FanOutPageMap = {+ (EVENTS_PATH, None, None): (+ [+ {"api_id": "evt-1", "event": {"api_id": "evt-1"}},+ {"api_id": "evt-2", "event": {"api_id": "evt-2"}},+ ],+ None,+ ),+ (GUESTS_PATH, None, "evt-1"): (+ [{"api_id": "gst-a", "guest": {"api_id": "gst-a", "name": "Ada"}}],+ None,+ ),+ (GUESTS_PATH, None, "evt-2"): ([], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ # The `guest` envelope is unwrapped and the parent event id injected for the composite key.+ assert rows == [{"api_id": "gst-a", "name": "Ada", "event_api_id": "evt-1"}]+ assert manager.saved == []++ def test_paginates_guests_within_an_event(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: FanOutPageMap = {+ (EVENTS_PATH, None, None): ([{"api_id": "evt-1", "event": {"api_id": "evt-1"}}], None),+ (GUESTS_PATH, None, "evt-1"): ([{"api_id": "gst-a", "guest": {"api_id": "gst-a"}}], "gcur-2"),+ (GUESTS_PATH, "gcur-2", "evt-1"): ([{"api_id": "gst-b", "guest": {"api_id": "gst-b"}}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert [r["api_id"] for r in rows] == ["gst-a", "gst-b"]++ def test_saves_events_cursor_after_finishing_events_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: FanOutPageMap = {+ (EVENTS_PATH, None, None): ([{"api_id": "evt-1", "event": {"api_id": "evt-1"}}], "ecur-2"),+ (EVENTS_PATH, "ecur-2", None): ([{"api_id": "evt-2", "event": {"api_id": "evt-2"}}], None),+ (GUESTS_PATH, None, "evt-1"): ([{"api_id": "gst-a", "guest": {"api_id": "gst-a"}}], None),+ (GUESTS_PATH, None, "evt-2"): ([{"api_id": "gst-b", "guest": {"api_id": "gst-b"}}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert [r["event_api_id"] for r in rows] == ["evt-1", "evt-2"]+ # State points at the next *events* page, saved only after all its guests were yielded.+ assert [s.pagination_cursor for s in manager.saved] == ["ecur-2"]++ def test_resumes_from_saved_events_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(LumaResumeConfig(pagination_cursor="ecur-2"))+ # The first events page must never be fetched on resume.+ pages: FanOutPageMap = {+ (EVENTS_PATH, "ecur-2", None): ([{"api_id": "evt-2", "event": {"api_id": "evt-2"}}], None),+ (GUESTS_PATH, None, "evt-2"): ([{"api_id": "gst-b", "guest": {"api_id": "gst-b"}}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"api_id": "gst-b", "event_api_id": "evt-2"}]+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"entries": [], "has_more": False}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(LumaRetryableError):+ _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())++ @parameterized.expand([("bad_request", 400), ("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())++ def test_success_returns_entries_and_next_cursor(self) -> None:+ body = {"entries": [{"api_id": "evt-1"}], "has_more": True, "next_cursor": "cur-2"}+ session = self._session_returning(200, body)+ rows, next_cursor = _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())+ assert rows == [{"api_id": "evt-1"}]+ assert next_cursor == "cur-2"++ @parameterized.expand(+ [+ ("has_more_false", {"entries": [{"api_id": "a"}], "has_more": False, "next_cursor": "cur-2"}),+ ("missing_next_cursor", {"entries": [{"api_id": "a"}], "has_more": True}),+ ("empty_next_cursor", {"entries": [{"api_id": "a"}], "has_more": True, "next_cursor": ""}),+ ]+ )+ def test_pagination_terminates(self, _name: str, body: dict) -> None:+ # `has_more` is authoritative — a lingering cursor on the final page must not loop forever.+ session = self._session_returning(200, body)+ _, next_cursor = _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())+ assert next_cursor is None++ @parameterized.expand([("bare_list", [{"api_id": "a"}]), ("missing_entries", {"has_more": False})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(LumaRetryableError):+ _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())++ def test_request_params_include_cursor_and_extras(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, GUESTS_PATH, "cur-9", MagicMock(), extra_params={"event_api_id": "evt-1"})+ args, kwargs = session.get.call_args+ assert args[0] == f"{LUMA_BASE_URL}{GUESTS_PATH}"+ assert kwargs["params"]["pagination_cursor"] == "cur-9"+ assert kwargs["params"]["event_api_id"] == "evt-1"+ assert kwargs["params"]["pagination_limit"] == luma.PAGE_SIZE++ def test_first_request_omits_cursor(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())+ _, kwargs = session.get.call_args+ assert "pagination_cursor" not in kwargs["params"]+++class TestCheckAccess:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("missing_key", 400, False, 400, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Luma returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with patch.object(luma, "make_tracked_session", return_value=self._session(response)):+ assert check_access("luma-key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(luma, "make_tracked_session", return_value=session):+ status, message = check_access("luma-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("missing_key", 400, False, "Invalid Luma API key"),+ ("unauthorized", 401, False, "Invalid Luma API key"),+ ("forbidden", 403, False, "Invalid Luma API key"),+ ("server_error", 500, False, "Luma returned HTTP 500"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with patch.object(luma, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("luma-key") == (expected_valid, expected_message)+++class TestLumaSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = luma_source(+ api_key="luma-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == LUMA_ENDPOINTS[endpoint].primary_keys+ # `created_at` is nullable in Luma payloads, so we don't partition on it.+ assert response.partition_mode is None++ def test_guests_primary_key_includes_parent_event(self) -> None:+ # Guest rows aggregate across every event, so the key must be unique table-wide.+ assert LUMA_ENDPOINTS["guests"].primary_keys == ["event_api_id", "api_id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma_source.pynew file mode 100644index 000000000000..8dd7fabab932--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma_source.py@@ -0,0 +1,124 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LumaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.luma import LumaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.luma.source import LumaSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestLumaSource:+ def setup_method(self) -> None:+ self.source = LumaSource()+ self.team_id = 123+ self.config = LumaSourceConfig(api_key="luma-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LUMA++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Luma"+ assert config.label == "Luma"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Shipped behind the unreleased flag until the source has synced end-to-end with real credentials.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/luma"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["guests"])+ assert len(schemas) == 1+ assert schemas[0].name == "guests"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://public-api.luma.com/public/v1/calendar/list-events",),+ ("403 Client Error: Forbidden for url: https://public-api.luma.com/public/v1/event/get-guests",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, 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(+ [+ (+ "500 Server Error: Internal Server Error for url: https://public-api.luma.com/public/v1/calendar/list-events",+ ),+ ("429 Client Error: Too Many Requests for url: https://public-api.luma.com/public/v1/event/get-guests",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.luma.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Luma API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid Luma API key")+ mock_validate.assert_called_once_with("luma-key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LumaResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.luma.source.luma_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "luma-key"+ assert kwargs["endpoint"] == "events"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Luma schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)