: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 beamer import source (#66754)
Tom Owerse5987d204840
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a6966eaa5a8d..2e712df8d488 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -58,6 +58,7 @@ the row lists both.| attio | HTTP | requests + `rest_source.RESTClient` | ✅ || azure_devops | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ |+| beamer | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ || braintree | HTTP (GraphQL) | requests | ✅ |@@ -304,7 +305,6 @@ doesn't conflict with concurrent PRs.- azure_table_storage- babelforce- basecamp-- beamer- bigcommerce- bigmailer- bitlydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/beamer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/beamer.pynew file mode 100644index 000000000000..baf123f79f76--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/beamer.py@@ -0,0 +1,300 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++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.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.settings import (+ BEAMER_ENDPOINTS,+ BeamerEndpointConfig,+)+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++BEAMER_BASE_URL = "https://api.getbeamer.com/v0"+REQUEST_TIMEOUT = 60+# Beamer's `page` query param is documented as paginating alongside `maxResults` but the docs don't+# state whether it's 0- or 1-based. We could not curl-verify against the live API without a paid key,+# so we assume the common convention (page 1 = first page). If a real key shows it's 0-based, change+# this constant — pagination termination ("a short page ends the loop") is index-independent.+FIRST_PAGE = 1+++class BeamerRetryableError(Exception):+ pass+++class BeamerResumeConfig:+ # Next page to fetch (1-based, see FIRST_PAGE).+ page: int = FIRST_PAGE+ # Fan-out bookmark: id of the parent currently being processed. A stable parent-id bookmark (not a+ # positional index) so parents added/removed between a crash and the retry can't resume us into the+ # wrong parent. None for the top-level (non-fan-out) endpoints.+ parent_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"Beamer-Api-Key": api_key, "Accept": "application/json"}+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as the ISO-8601 `...Z` string Beamer's `dateFrom` expects."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime(value.year, value.month, value.day, tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _build_url(path: str, params: dict[str, Any]) -> str:+ query = {key: value for key, value in params.items() if value is not None}+ base = f"{BEAMER_BASE_URL}{path}"+ return f"{base}?{urlencode(query)}" if query else base+++@retry(+ retry=retry_if_exception_type((BeamerRetryableError, 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, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT)++ # 429 (rate limit) and 5xx are transient — back off and retry. Beamer allows 30 req/sec on paid+ # plans plus a monthly quota, both of which surface as 429.+ if response.status_code == 429 or response.status_code >= 500:+ raise BeamerRetryableError(f"Beamer API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 happens when a parent is deleted mid fan-out; the caller handles it. Everything else is+ # a hard error (e.g. 401/403 bad-or-unscoped key) raised for `get_non_retryable_errors`.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Beamer API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ # Beamer list endpoints return a bare JSON array.+ return response.json()+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ # A bad key 401s; a valid-but-unscoped key 403s (the 'Read posts' permission is optional). Both+ # mean the key is genuine, so only a 401 fails source-create — per-endpoint scope is surfaced+ # separately at sync time via `get_non_retryable_errors`. Transport failures and unexpected+ # statuses are inconclusive: reporting them as an invalid key would push users to needlessly+ # rotate a working credential (and re-enter it into a possibly-degraded environment), so they+ # get a generic retry message instead. `redact_values` masks the key from any captured sample.+ url = _build_url("/posts", {"maxResults": 1})+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ except requests.RequestException:+ return False, "Could not reach Beamer to validate the API key. Please try again."+ if response.status_code in (200, 403):+ return True, None+ if response.status_code == 401:+ return False, "Invalid Beamer API key"+ return False, f"Beamer could not validate the API key right now (status {response.status_code}). Please try again."+++def _iter_parent_ids(+ session: requests.Session,+ parent_config: BeamerEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Iterator[str]:+ """Page through a parent collection (posts / feature requests) yielding each row's id."""+ page = FIRST_PAGE+ while True:+ url = _build_url(parent_config.path, {"maxResults": parent_config.max_results, "page": page})+ items = _fetch_page(session, url, headers, logger)+ if not items:+ break+ for item in items:+ # `id` is the required primary key on every parent row; direct access so a missing+ # field fails loudly rather than silently dropping the parent's children.+ yield str(item["id"])+ if len(items) < parent_config.max_results:+ break+ page += 1+++def _iter_top_level_rows(+ session: requests.Session,+ config: BeamerEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[BeamerResumeConfig],+ base_params: dict[str, Any],+ start_page: int,+) -> Iterator[Any]:+ page = start_page+ while True:+ url = _build_url(config.path, {**base_params, "page": page})+ items = _fetch_page(session, url, headers, logger)+ if not items:+ break++ has_more = len(items) >= config.max_results+ last_index = len(items) - 1+ for index, item in enumerate(items):+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # The batcher just flushed everything buffered up to this item, so checkpoint here.+ # Advance to the next page only on the page's last item; a mid-page flush (the bytes+ # cap firing before the count cap) leaves this page's tail un-batched, so resume from+ # this same page and let merge dedupe the rows already flushed. Saving page+1 mid-page+ # would skip those trailing items on a crash.+ resume_page = page + 1 if index == last_index and has_more else page+ manager.save_state(BeamerResumeConfig(page=resume_page))++ if not has_more:+ break+ page += 1+++def _iter_fan_out_rows(+ session: requests.Session,+ config: BeamerEndpointConfig,+ parent_config: BeamerEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[BeamerResumeConfig],+) -> Iterator[Any]:+ assert config.parent_key is not None # set on every fan-out endpoint in settings.py+ parent_ids = list(_iter_parent_ids(session, parent_config, headers, logger))++ # Resolve the saved parent-id bookmark to the slice of parents still to process. If the bookmarked+ # parent no longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.+ resume = manager.load_state() if manager.can_resume() else None+ remaining = parent_ids+ resume_page = FIRST_PAGE+ if resume is not None and resume.parent_id is not None and resume.parent_id in parent_ids:+ remaining = parent_ids[parent_ids.index(resume.parent_id) :]+ resume_page = resume.page+ logger.debug(f"Beamer: resuming {config.name} from parent_id={resume.parent_id}, page={resume_page}")++ for index, parent_id in enumerate(remaining):+ page = resume_page if index == 0 else FIRST_PAGE+ child_path = config.path.replace("{parent_id}", parent_id)+ try:+ while True:+ url = _build_url(child_path, {"maxResults": config.max_results, "page": page})+ items = _fetch_page(session, url, headers, logger)+ if not items:+ break++ has_more = len(items) >= config.max_results+ last_index = len(items) - 1+ for item_index, item in enumerate(items):+ batcher.batch({**item, config.parent_key: parent_id})+ if batcher.should_yield():+ yield batcher.get_table()+ # Same checkpoint rule as the top-level path: only advance the page on the+ # page's last item, otherwise resume from this page (merge dedupes).+ checkpoint_page = page + 1 if item_index == last_index and has_more else page+ manager.save_state(BeamerResumeConfig(page=checkpoint_page, parent_id=parent_id))++ if not has_more:+ break+ page += 1+ except requests.HTTPError as exc:+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than failing the+ # whole sync — the children are genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Beamer: {parent_config.name} {parent_id} not found while fetching {config.name}")+ else:+ raise++ # Advance the bookmark to the next parent so a crash between parents resumes correctly — but+ # only when the batcher holds no unflushed rows. If this parent's tail is still buffered,+ # advancing past it would skip those rows on resume; we leave the last on-yield checkpoint in+ # place instead (a crash re-fetches from there and merge dedupes).+ if index + 1 < len(remaining) and not batcher.should_yield(include_incomplete_chunk=True):+ manager.save_state(BeamerResumeConfig(page=FIRST_PAGE, parent_id=remaining[index + 1]))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BeamerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = BEAMER_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page (and, for fan-out, every parent) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. `redact_values` masks the API key+ # (sent in the `Beamer-Api-Key` header) from any captured HTTP samples or logged requests.+ session = make_tracked_session(redact_values=(api_key,))++ if config.parent is not None:+ parent_config = BEAMER_ENDPOINTS[config.parent]+ yield from _iter_fan_out_rows(+ session, config, parent_config, headers, logger, batcher, resumable_source_manager+ )+ else:+ base_params: dict[str, Any] = {"maxResults": config.max_results}+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:+ base_params["dateFrom"] = _format_datetime(db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_page = resume.page if resume is not None and resume.parent_id is None else FIRST_PAGE+ yield from _iter_top_level_rows(+ session, config, headers, logger, batcher, resumable_source_manager, base_params, start_page+ )++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def beamer_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BeamerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = BEAMER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Beamer doesn't document a sort param on these collections and we couldn't verify the default+ # order against the live API. For incremental endpoints we bound the low end with `dateFrom` and+ # use "desc" semantics so the watermark is only persisted at the end of a successful sync — a+ # mid-sync crash re-fetches from the unchanged watermark instead of skipping rows. Full-refresh+ # endpoints ignore sort_mode.+ sort_mode="desc" if config.supports_incremental else "asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/canonical_descriptions.pynew file mode 100644index 000000000000..daf7b548eca6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/canonical_descriptions.py@@ -0,0 +1,130 @@+"""Canonical, documentation-sourced descriptions for Beamer endpoints and columns.++Sourced from the official Beamer API reference (https://www.getbeamer.com/help/beamer-api-documentation).+Keyed by the endpoint names in `settings.py` `BEAMER_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Beamer table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "posts": {+ "description": "A changelog post / announcement (the notifications shown in the Beamer feed and widget).",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the post.",+ "date": "Date the post was published.",+ "dueDate": "Date the post is scheduled to expire, if set.",+ "published": "Whether the post is currently published.",+ "pinned": "Whether the post is pinned to the top of the feed.",+ "category": "The post's category (e.g. new, improvement, fix).",+ "translations": "Per-language title, content, and link for the post.",+ "feedbackEnabled": "Whether readers can leave feedback on the post.",+ "reactionsEnabled": "Whether readers can react to the post.",+ "views": "Total number of views.",+ "uniqueViews": "Number of unique users who viewed the post.",+ "clicks": "Number of clicks on the post's link.",+ "feedbacks": "Number of feedback responses received.",+ "positiveReactions": "Count of positive reactions.",+ "neutralReactions": "Count of neutral reactions.",+ "negativeReactions": "Count of negative reactions.",+ },+ },+ "feature_requests": {+ "description": "An Idea / feature request submitted on the Beamer roadmap, with vote and comment counts.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the feature request.",+ "date": "Date the feature request was created.",+ "visible": "Whether the feature request is publicly visible.",+ "category": "The feature request's category.",+ "status": "Current roadmap status (e.g. open, planned, in progress, done).",+ "translations": "Per-language title and content for the feature request.",+ "votesCount": "Number of votes the feature request has received.",+ "commentsCount": "Number of comments on the feature request.",+ "userId": "Your identifier for the user who submitted the request.",+ "userEmail": "Email of the user who submitted the request.",+ },+ },+ "nps": {+ "description": "A Net Promoter Score (NPS) survey response, including the score and optional feedback.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the NPS response.",+ "date": "Date the NPS response was submitted.",+ "score": "The NPS score the user gave (0-10).",+ "feedback": "Free-text feedback the user left with the score.",+ "userId": "Your identifier for the responding user.",+ "userEmail": "Email of the responding user.",+ "url": "URL the user was on when they responded.",+ },+ },+ "users": {+ "description": "An end user tracked by Beamer (Scale plan only), with first/last seen and location data.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "beamerId": "Beamer's internal unique identifier for the user.",+ "userId": "Your identifier for the user.",+ "userEmail": "The user's email address.",+ "firstSeen": "Timestamp the user was first seen.",+ "lastSeen": "Timestamp the user was last seen.",+ "browser": "The user's browser.",+ "os": "The user's operating system.",+ "city": "The user's city, derived from IP.",+ "country": "The user's country, derived from IP.",+ },+ },+ "post_comments": {+ "description": "A comment left by a user on a changelog post.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the comment.",+ "post_id": "Identifier of the post the comment belongs to (injected during sync).",+ "date": "Date the comment was created.",+ "text": "The comment text.",+ "postTitle": "Title of the post the comment is on.",+ "userId": "Your identifier for the commenting user.",+ "userEmail": "Email of the commenting user.",+ },+ },+ "post_reactions": {+ "description": "A reaction left by a user on a changelog post.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the reaction.",+ "post_id": "Identifier of the post the reaction belongs to (injected during sync).",+ "date": "Date the reaction was created.",+ "reaction": "The reaction type (e.g. positive, neutral, negative).",+ "postTitle": "Title of the post the reaction is on.",+ "userId": "Your identifier for the reacting user.",+ "userEmail": "Email of the reacting user.",+ },+ },+ "feature_request_comments": {+ "description": "A comment left on a feature request / Idea.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the comment.",+ "feature_request_id": "Identifier of the feature request the comment belongs to (injected during sync).",+ "date": "Date the comment was created.",+ "text": "The comment text.",+ "featureRequestTitle": "Title of the feature request the comment is on.",+ "userId": "Your identifier for the commenting user.",+ "userEmail": "Email of the commenting user.",+ },+ },+ "feature_request_votes": {+ "description": "A vote cast by a user on a feature request / Idea.",+ "docs_url": "https://www.getbeamer.com/help/beamer-api-documentation",+ "columns": {+ "id": "Unique identifier for the vote.",+ "feature_request_id": "Identifier of the feature request the vote belongs to (injected during sync).",+ "date": "Date the vote was cast.",+ "featureRequestTitle": "Title of the feature request the vote is on.",+ "userId": "Your identifier for the voting user.",+ "userEmail": "Email of the voting user.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/settings.pynew file mode 100644index 000000000000..285667d48f4f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/settings.py@@ -0,0 +1,126 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class BeamerEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation timestamp used for datetime partitioning. Never an update/last-seen field.+ partition_key: Optional[str] = None+ # Beamer caps page size per endpoint: 10 for posts/comments/reactions/requests/votes,+ # 100 for nps/users.+ max_results: int = 10+ # Only True where the endpoint exposes the server-side `dateFrom` filter on the `date` field.+ supports_incremental: bool = False+ should_sync_default: bool = True+ # Fan-out: when set, iterate the parent endpoint's rows and call `path` (with its `{parent_id}`+ # placeholder filled in) once per parent. `parent_key` is the column the parent id is injected+ # into on each child row so the composite primary key stays unique table-wide.+ parent: Optional[str] = None+ parent_key: Optional[str] = None+++def _date_incremental_field() -> list[IncrementalField]:+ # Every incremental Beamer collection exposes a single `date` creation timestamp filtered by+ # the `dateFrom` query param.+ return [+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++BEAMER_ENDPOINTS: dict[str, BeamerEndpointConfig] = {+ "posts": BeamerEndpointConfig(+ name="posts",+ path="/posts",+ primary_keys=["id"],+ incremental_fields=_date_incremental_field(),+ partition_key="date",+ max_results=10,+ supports_incremental=True,+ ),+ "feature_requests": BeamerEndpointConfig(+ name="feature_requests",+ path="/requests",+ primary_keys=["id"],+ incremental_fields=_date_incremental_field(),+ partition_key="date",+ max_results=10,+ supports_incremental=True,+ ),+ "nps": BeamerEndpointConfig(+ name="nps",+ path="/nps",+ primary_keys=["id"],+ incremental_fields=_date_incremental_field(),+ partition_key="date",+ max_results=100,+ supports_incremental=True,+ ),+ # /users is Scale-plan only and exposes no `dateFrom` filter, so it's full refresh and off by+ # default to avoid 403-ing every non-Scale account's sync.+ "users": BeamerEndpointConfig(+ name="users",+ path="/users",+ primary_keys=["beamerId"],+ partition_key="firstSeen",+ max_results=100,+ supports_incremental=False,+ should_sync_default=False,+ ),+ # Fan-out children. Comments/reactions hang off posts; comments/votes hang off feature requests.+ # No server-side incremental on the fan-out (we'd still have to enumerate every parent), so these+ # are full refresh — merge dedupes the re-pulled rows on the composite primary key.+ "post_comments": BeamerEndpointConfig(+ name="post_comments",+ path="/posts/{parent_id}/comments",+ primary_keys=["post_id", "id"],+ partition_key="date",+ max_results=10,+ parent="posts",+ parent_key="post_id",+ ),+ "post_reactions": BeamerEndpointConfig(+ name="post_reactions",+ path="/posts/{parent_id}/reactions",+ primary_keys=["post_id", "id"],+ partition_key="date",+ max_results=10,+ parent="posts",+ parent_key="post_id",+ should_sync_default=False,+ ),+ "feature_request_comments": BeamerEndpointConfig(+ name="feature_request_comments",+ path="/requests/{parent_id}/comments",+ primary_keys=["feature_request_id", "id"],+ partition_key="date",+ max_results=10,+ parent="feature_requests",+ parent_key="feature_request_id",+ ),+ "feature_request_votes": BeamerEndpointConfig(+ name="feature_request_votes",+ path="/requests/{parent_id}/votes",+ primary_keys=["feature_request_id", "id"],+ partition_key="date",+ max_results=10,+ parent="feature_requests",+ parent_key="feature_request_id",+ ),+}++ENDPOINTS = tuple(BEAMER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BEAMER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/source.pyindex 5ef99feae94c..11d369ecd4f5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/source.py@@ -1,19 +1,43 @@-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.beamer.beamer import (+ BeamerResumeConfig,+ beamer_source,+ validate_credentials as validate_beamer_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.settings import (+ BEAMER_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 BeamerSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BeamerSource(SimpleSource[BeamerSourceConfig]):+class BeamerSource(ResumableSource[BeamerSourceConfig, BeamerResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BEAMER@@ -24,7 +48,101 @@ class BeamerSource(SimpleSource[BeamerSourceConfig]):name=SchemaExternalDataSourceType.BEAMER,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Beamer",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Beamer API key to sync your changelog posts, feature requests, comments, votes, reactions, and NPS responses into the PostHog Data warehouse.++You can find your API key in your [Beamer account settings](https://app.getbeamer.com/settings#api). Beamer sends it in the `Beamer-Api-Key` header.++Notes:+- The **Users** table requires a Beamer **Scale** plan and is off by default.+- Some post queries need the API key's **Read posts (ignore filters)** permission.""",iconPath="/static/services/beamer.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/beamer",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="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.beamer.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_page` calls `raise_for_status()`.+ # Retrying can never satisfy a credential/permission problem, so fail the sync. Match the+ # stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.getbeamer.com": "Your Beamer API key is invalid or has been revoked. Generate a new key in your Beamer account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.getbeamer.com": "Your Beamer API key is missing the permissions or plan needed to sync this table (e.g. Users needs a Scale plan, and some post queries need the 'Read posts (ignore filters)' permission). Adjust the key in your Beamer account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: BeamerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "users":+ return "Requires a Beamer Scale plan. Full refresh only"+ if BEAMER_ENDPOINTS[endpoint].parent is not None:+ return "Full refresh only (fanned out over every parent record)"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = BEAMER_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) 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: BeamerSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_beamer_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BeamerResumeConfig]:+ return ResumableSourceManager[BeamerResumeConfig](inputs, BeamerResumeConfig)++ def source_for_pipeline(+ self,+ config: BeamerSourceConfig,+ resumable_source_manager: ResumableSourceManager[BeamerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return beamer_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer.pynew file mode 100644index 000000000000..79008ead7df8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer.py@@ -0,0 +1,299 @@+from datetime import UTC, date, datetime+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.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer import beamer+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.beamer import (+ BeamerResumeConfig,+ _build_url,+ _format_datetime,+ beamer_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.settings import BEAMER_ENDPOINTS+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"),+ ]+ )+ def test_format_datetime(self, _name: str, value: object, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestBuildUrl:+ def test_drops_none_params(self) -> None:+ url = _build_url("/posts", {"maxResults": 10, "page": 1, "dateFrom": None})+ assert url == "https://api.getbeamer.com/v0/posts?maxResults=10&page=1"++ def test_no_params_has_no_query_string(self) -> None:+ assert _build_url("/posts", {}) == "https://api.getbeamer.com/v0/posts"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ # 200 = good key, 403 = real key missing the optional 'Read posts' permission — both valid.+ ("ok", 200, True, None),+ ("forbidden_is_valid_key", 403, True, None),+ ("unauthorized_is_invalid", 401, False, "Invalid Beamer API key"),+ # A 5xx is inconclusive — never reported as an invalid key (would prompt a needless rotation).+ ("server_error_is_inconclusive", 500, False, "could not validate"),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool, expected_msg: str | None) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(beamer, "make_tracked_session", return_value=session):+ ok, message = validate_credentials("key")+ assert ok is expected_ok+ if expected_msg is None:+ assert message is None+ else:+ assert message is not None and expected_msg in message++ def test_network_error_is_inconclusive_not_invalid(self) -> None:+ # A transport failure must not be reported as an invalid key.+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError()+ with patch.object(beamer, "make_tracked_session", return_value=session):+ ok, message = validate_credentials("key")+ assert ok is False+ assert message is not None and "Could not reach Beamer" in message+++class _FakeResumableManager:+ def __init__(self, state: BeamerResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[BeamerResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> BeamerResumeConfig | None:+ return self._state++ def save_state(self, data: BeamerResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ monkeypatch: Any,+ endpoint: str,+ pages: dict[str, Any],+ manager: _FakeResumableManager | None = None,+ **kwargs: Any,+) -> tuple[list[dict], list[str]]:+ """Run get_rows against a fake page map keyed by URL, returning (rows, fetched_urls)."""+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(beamer, "_fetch_page", fake_fetch)+ monkeypatch.setattr(beamer, "make_tracked_session", lambda *args, **kwargs: MagicMock())++ rows: list[dict] = []+ for table in get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ return rows, fetched+++class TestTopLevelPagination:+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=1": [+ {"id": i, "date": "2026-01-01"} for i in range(10)+ ],+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=2": [{"id": 10, "date": "2026-01-02"}],+ }+ rows, fetched = _collect(monkeypatch, "posts", pages)+ assert [r["id"] for r in rows] == list(range(11))+ # Stops after the short second page; never requests page 3.+ assert fetched == [+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=1",+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=2",+ ]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ pages: dict[str, list[dict[str, Any]]] = {"https://api.getbeamer.com/v0/posts?maxResults=10&page=1": []}+ rows, fetched = _collect(monkeypatch, "posts", pages)+ assert rows == []++ def test_incremental_adds_datefrom(self, monkeypatch: Any) -> None:+ url = "https://api.getbeamer.com/v0/posts?maxResults=10&dateFrom=2026-03-04T02%3A58%3A14Z&page=1"+ pages = {url: [{"id": 1, "date": "2026-03-05"}]}+ rows, fetched = _collect(+ monkeypatch,+ "posts",+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="date",+ )+ assert rows == [{"id": 1, "date": "2026-03-05"}]+ assert "dateFrom=2026-03-04T02%3A58%3A14Z" in fetched[0]++ def test_nps_uses_larger_page_size(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.getbeamer.com/v0/nps?maxResults=100&page=1": [{"id": 1, "date": "2026-01-01", "score": 9}]+ }+ rows, fetched = _collect(monkeypatch, "nps", pages)+ assert rows[0]["score"] == 9+ assert "maxResults=100" in fetched[0]++ def test_resume_starts_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {"https://api.getbeamer.com/v0/posts?maxResults=10&page=3": [{"id": 99, "date": "2026-01-01"}]}+ manager = _FakeResumableManager(BeamerResumeConfig(page=3, parent_id=None))+ rows, fetched = _collect(monkeypatch, "posts", pages, manager=manager)+ assert rows == [{"id": 99, "date": "2026-01-01"}]+ assert fetched == ["https://api.getbeamer.com/v0/posts?maxResults=10&page=3"]++ def test_mid_page_yield_checkpoints_current_page_not_next(self, monkeypatch: Any) -> None:+ # Force a flush on every item (chunk_size=1) so we can observe the per-item checkpoint. A+ # mid-page flush must save the current page, not page+1 — saving page+1 mid-page would skip+ # the page's un-batched tail on a crash. Only the page's final item advances the checkpoint.+ monkeypatch.setattr(beamer, "Batcher", lambda **kwargs: Batcher(logger=MagicMock(), chunk_size=1))+ pages = {+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=1": [+ {"id": i, "date": "2026-01-01"} for i in range(10)+ ],+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=2": [{"id": 10, "date": "2026-01-02"}],+ }+ manager = _FakeResumableManager()+ _collect(monkeypatch, "posts", pages, manager=manager)+ saved_pages = [state.page for state in manager.saved]+ # Page 1 is full: its first nine items checkpoint page 1, its last item advances to page 2.+ # Page 2 is short (no further pages): its lone item checkpoints page 2, never page 3.+ assert saved_pages == [1] * 9 + [2, 2]+++class TestFanOut:+ def _post_pages(self, extra: dict[str, Any]) -> dict[str, Any]:+ pages = {+ "https://api.getbeamer.com/v0/posts?maxResults=10&page=1": [{"id": "P1"}, {"id": "P2"}],+ }+ pages.update(extra)+ return pages++ def test_injects_parent_id_into_child_rows(self, monkeypatch: Any) -> None:+ pages = self._post_pages(+ {+ "https://api.getbeamer.com/v0/posts/P1/comments?maxResults=10&page=1": [+ {"id": "C1", "date": "2026-01-01", "text": "hi"}+ ],+ "https://api.getbeamer.com/v0/posts/P2/comments?maxResults=10&page=1": [+ {"id": "C2", "date": "2026-01-02", "text": "yo"}+ ],+ }+ )+ rows, _ = _collect(monkeypatch, "post_comments", pages)+ assert rows == [+ {"id": "C1", "date": "2026-01-01", "text": "hi", "post_id": "P1"},+ {"id": "C2", "date": "2026-01-02", "text": "yo", "post_id": "P2"},+ ]++ def test_feature_request_votes_inject_feature_request_id(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.getbeamer.com/v0/requests?maxResults=10&page=1": [{"id": "R1"}],+ "https://api.getbeamer.com/v0/requests/R1/votes?maxResults=10&page=1": [{"id": "V1", "date": "2026-01-01"}],+ }+ rows, _ = _collect(monkeypatch, "feature_request_votes", pages)+ assert rows == [{"id": "V1", "date": "2026-01-01", "feature_request_id": "R1"}]++ def test_deleted_parent_404_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=MagicMock(status_code=404))+ pages = self._post_pages(+ {+ "https://api.getbeamer.com/v0/posts/P1/comments?maxResults=10&page=1": not_found,+ "https://api.getbeamer.com/v0/posts/P2/comments?maxResults=10&page=1": [+ {"id": "C2", "date": "2026-01-02"}+ ],+ }+ )+ rows, _ = _collect(monkeypatch, "post_comments", pages)+ assert rows == [{"id": "C2", "date": "2026-01-02", "post_id": "P2"}]++ def test_non_404_error_propagates(self, monkeypatch: Any) -> None:+ server_error = requests.HTTPError(response=MagicMock(status_code=500))+ pages = self._post_pages({"https://api.getbeamer.com/v0/posts/P1/comments?maxResults=10&page=1": server_error})+ with pytest.raises(requests.HTTPError):+ _collect(monkeypatch, "post_comments", pages)++ def test_resume_from_bookmarked_parent(self, monkeypatch: Any) -> None:+ # Bookmarked at P2 — P1 is skipped, P2 resumed at page 2.+ pages = self._post_pages(+ {+ "https://api.getbeamer.com/v0/posts/P2/comments?maxResults=10&page=2": [+ {"id": "C9", "date": "2026-01-09"}+ ],+ }+ )+ manager = _FakeResumableManager(BeamerResumeConfig(page=2, parent_id="P2"))+ rows, fetched = _collect(monkeypatch, "post_comments", pages, manager=manager)+ assert rows == [{"id": "C9", "date": "2026-01-09", "post_id": "P2"}]+ assert "https://api.getbeamer.com/v0/posts/P1/comments?maxResults=10&page=1" not in fetched+++class TestBeamerSourceResponse:+ @parameterized.expand(+ [+ ("posts", ["id"], "date", "desc"),+ ("feature_requests", ["id"], "date", "desc"),+ ("nps", ["id"], "date", "desc"),+ ("users", ["beamerId"], "firstSeen", "asc"),+ ("post_comments", ["post_id", "id"], "date", "asc"),+ ("feature_request_votes", ["feature_request_id", "id"], "date", "asc"),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, primary_keys: list[str], partition_key: str, sort_mode: str+ ) -> None:+ response = beamer_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == sort_mode++ def test_incremental_endpoints_sort_desc(self) -> None:+ # Endpoints with a server-side dateFrom filter must use "desc" so the watermark is only+ # persisted at the end of a successful sync (we can't verify the API's default sort order).+ for name, config in BEAMER_ENDPOINTS.items():+ response = beamer_source(+ api_key="key", endpoint=name, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ expected = "desc" if config.supports_incremental else "asc"+ assert response.sort_mode == expected, namediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer_source.pynew file mode 100644index 000000000000..8c92eca0aa39--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beamer/tests/test_beamer_source.py@@ -0,0 +1,156 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.beamer import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.beamer import BeamerResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.beamer.source import BeamerSource+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 BeamerSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestBeamerSourceConfig:+ def setup_method(self) -> None:+ self.source = BeamerSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.BEAMER++ def test_config_has_api_key_password_field(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields}+ assert set(fields) == {"api_key"}+ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True++ def test_config_is_released_alpha(self) -> None:+ config = self.source.get_source_config+ # A finished source is visible (no unreleasedSource) and labelled alpha.+ assert config.unreleasedSource is None+ assert config.releaseStatus == "alpha"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/beamer"++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required for the public-docs table list to render.+ assert self.source.lists_tables_without_credentials is True+++class TestGetSchemas:+ def setup_method(self) -> None:+ self.schemas = {s.name: s for s in BeamerSource().get_schemas(MagicMock(), team_id=1)}++ def test_all_expected_tables_present(self) -> None:+ assert set(self.schemas) == {+ "posts",+ "feature_requests",+ "nps",+ "users",+ "post_comments",+ "post_reactions",+ "feature_request_comments",+ "feature_request_votes",+ }++ @parameterized.expand(["posts", "feature_requests", "nps"])+ def test_top_level_collections_are_incremental(self, name: str) -> None:+ schema = self.schemas[name]+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["date"]++ @parameterized.expand(+ ["users", "post_comments", "post_reactions", "feature_request_comments", "feature_request_votes"]+ )+ def test_full_refresh_only_tables(self, name: str) -> None:+ assert self.schemas[name].supports_incremental is False++ def test_scale_only_and_high_volume_tables_off_by_default(self) -> None:+ assert self.schemas["users"].should_sync_default is False+ assert self.schemas["post_reactions"].should_sync_default is False+ assert self.schemas["posts"].should_sync_default is True++ def test_names_filter(self) -> None:+ filtered = BeamerSource().get_schemas(MagicMock(), team_id=1, names=["posts"])+ assert [s.name for s in filtered] == ["posts"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "Invalid Beamer API key")),+ ("inconclusive", (False, "Could not reach Beamer to validate the API key. Please try again.")),+ ]+ )+ def test_validate_credentials_passes_probe_result_through(self, _name: str, probe_result: tuple) -> None:+ config = BeamerSourceConfig(api_key="key")+ with patch.object(source_module, "validate_beamer_credentials", return_value=probe_result):+ assert BeamerSource().validate_credentials(config, team_id=1) == probe_result+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.getbeamer.com/v0/posts?maxResults=1"),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.getbeamer.com/v0/users?maxResults=100&page=1",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = BeamerSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.getbeamer.com/v0/posts"),+ ("read_timeout", "HTTPSConnectionPool(host='api.getbeamer.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = BeamerSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumablePlumbing:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = BeamerSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BeamerResumeConfig++ def test_source_for_pipeline_passes_incremental_inputs(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "posts"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "date"+ config = BeamerSourceConfig(api_key="key")+ manager = MagicMock()++ with patch.object(source_module, "beamer_source") as mock_source:+ BeamerSource().source_for_pipeline(config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "posts"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.incremental_field = None+ config = BeamerSourceConfig(api_key="key")++ with patch.object(source_module, "beamer_source") as mock_source:+ BeamerSource().source_for_pipeline(config, MagicMock(), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is Nonediff --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 f7111fb87e50..955b3b7c97f8 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@@ -399,7 +399,7 @@ class BaserowSourceConfig(config.Config):@config.configclass BeamerSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.pyindex f598658d2e32..d29ea53bf671 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py@@ -1,6 +1,7 @@import pytestfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ BeamerSourceConfig,BigQuerySourceConfig,ChargebeeSourceConfig,DoItSourceConfig,@@ -55,6 +56,11 @@ def test_bigquery_config():assert config.dataset_project.dataset_project_id == ""+def test_beamer_config():+ config = BeamerSourceConfig.from_dict({"api_key": "api_key"})+ assert config.api_key == "api_key"++def test_chargebee_config():config = ChargebeeSourceConfig.from_dict({"api_key": "api_key", "site_name": "subdomain"})assert config.api_key == "api_key"