: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 cal_com import source (#69338)
Tom Owers9a588990560d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3bd4e6491353..254764a64a34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -84,6 +84,7 @@ the row lists both.| buildkite | HTTP | requests | ✅ || bunny | HTTP | requests | ✅ || buzzsprout | HTTP | requests | ✅ |+| cal_com | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ || callrail | HTTP | requests | ✅ || campaign_monitor | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.pynew file mode 100644index 000000000000..6a73a8f0087e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py@@ -0,0 +1,299 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlsplit, urlunsplit++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.cal_com.settings import (+ CAL_COM_ENDPOINTS,+ CalComEndpointConfig,+)+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++CAL_COM_BASE_URL = "https://api.cal.com/v2"+# Bookings `limit` and webhooks `take` are documented with a 250 maximum; the largest page+# minimizes round trips against the 120 req/min default rate limit.+PAGE_LIMIT = 250+REQUEST_TIMEOUT_SECONDS = 60+# Cheap single-object endpoint used to confirm an API key is genuine. The key is account-wide, so+# one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/me"+++class CalComRetryableError(Exception):+ pass+++def _scrub_url(url: str | None) -> str:+ # Drop the query string before a URL reaches any error message or log line. Today the API key+ # rides in the Authorization header, but callers can append an arbitrary `path` (with a query)+ # in `check_access`, and future endpoints may take query-string credentials, so scrubbing keeps+ # those out of persisted job errors. The scheme/host/path stays intact so+ # `get_non_retryable_errors()` can still match on the base URL.+ if not url:+ return CAL_COM_BASE_URL+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))+++class CalComResumeConfig:+ # Opaque `pagination.nextCursor` for cursor-paginated endpoints (bookings). A crashed sync+ # resumes from the page after the last one yielded; merge dedupes the re-pulled page on `id`.+ cursor: str | None = None+ # `skip` offset for offset-paginated endpoints (webhooks).+ skip: int | None = None+++def _headers(api_key: str, config: CalComEndpointConfig) -> dict[str, str]:+ headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+ if config.api_version:+ headers["cal-api-version"] = config.api_version+ return headers+++def _format_incremental_value(value: Any) -> str:+ # Cal.com's afterUpdatedAt/afterCreatedAt filters take ISO 8601 date strings; normalize to UTC+ # with a Z suffix to avoid timezone ambiguity.+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return _format_incremental_value(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _build_incremental_params(+ config: CalComEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, str]:+ if not should_use_incremental_field or db_incremental_field_last_value is None:+ return {}++ field = incremental_field or config.default_incremental_field+ if field is None:+ return {}++ param = config.incremental_param_by_field.get(field)+ if param is None:+ raise ValueError(f"Cal.com endpoint '{config.name}' has no server-side filter for field '{field}'")++ return {param: _format_incremental_value(db_incremental_field_last_value)}+++@retry(+ retry=retry_if_exception_type((CalComRetryableError, 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,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, params=params or None, timeout=REQUEST_TIMEOUT_SECONDS)++ # Default rate limit is 120 req/min; 429s and transient 5xx are retried with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise CalComRetryableError(+ f"Cal.com API error (retryable): status={response.status_code}, url={_scrub_url(response.url)}"+ )++ if not response.ok:+ logger.error(+ f"Cal.com API error: status={response.status_code}, body={response.text}, url={_scrub_url(response.url)}"+ )+ # Raise with the query scrubbed from the URL rather than calling raise_for_status(), whose+ # message embeds the full request URL. The base host stays intact so+ # `get_non_retryable_errors()` can still match on it.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",+ response=response,+ )++ data = response.json()+ # Every v2 endpoint wraps its payload as {"status": "success", "data": ...}.+ if not isinstance(data, dict) or "data" not in data:+ raise CalComRetryableError(f"Cal.com returned an unexpected payload for {url}: {type(data).__name__}")++ return data+++def _rows_from_body(body: dict[str, Any], config: CalComEndpointConfig, url: str) -> list[dict[str, Any]]:+ data = body["data"]+ if config.single_object:+ return [data] if isinstance(data, dict) else []+ if not isinstance(data, list):+ raise CalComRetryableError(f"Cal.com returned a non-list payload for {url}: {type(data).__name__}")+ return data+++def _get_cursor_rows(+ session: requests.Session,+ config: CalComEndpointConfig,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if cursor is not None:+ logger.debug(f"Cal.com: resuming {config.name} from cursor {cursor}")++ while True:+ params = {**base_params, "limit": PAGE_LIMIT}+ if cursor is not None:+ params["cursor"] = cursor++ body = _fetch_page(session, url, params, logger)+ items = _rows_from_body(body, config, url)+ if items:+ yield items++ pagination = body.get("pagination") or {}+ next_cursor = pagination.get("nextCursor")+ if not pagination.get("hasMore") or not next_cursor:+ break++ cursor = next_cursor+ # Save AFTER yielding so a crash re-fetches from the next cursor (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(CalComResumeConfig(cursor=next_cursor))+++def _get_offset_rows(+ session: requests.Session,+ config: CalComEndpointConfig,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ skip = resume.skip if resume and resume.skip is not None else 0+ if skip:+ logger.debug(f"Cal.com: resuming {config.name} from offset {skip}")++ while True:+ params = {**base_params, "take": PAGE_LIMIT, "skip": skip}+ body = _fetch_page(session, url, params, logger)+ items = _rows_from_body(body, config, url)+ if items:+ yield items++ # These endpoints return no pagination metadata; a short (or empty) page means we're done.+ if len(items) < PAGE_LIMIT:+ break++ skip += PAGE_LIMIT+ resumable_source_manager.save_state(CalComResumeConfig(skip=skip))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CAL_COM_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key, config), redact_values=(api_key,))+ url = f"{CAL_COM_BASE_URL}{config.path}"+ base_params = _build_incremental_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ if config.pagination == "cursor":+ yield from _get_cursor_rows(session, config, url, base_params, logger, resumable_source_manager)+ return++ if config.pagination == "offset":+ yield from _get_offset_rows(session, config, url, base_params, logger, resumable_source_manager)+ return++ body = _fetch_page(session, url, base_params, logger)+ items = _rows_from_body(body, config, url)+ if items:+ yield items+++def cal_com_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = CAL_COM_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="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Bookings walk `Booking.uuid DESC` (newest-created first) when no status filter is passed,+ # and the opaque cursor doesn't honor sortUpdatedAt/sortCreated. "desc" makes the pipeline+ # commit the incremental watermark only after a complete sync, which stays correct+ # regardless of arrival order.+ sort_mode="desc" if config.incremental_fields else "asc",+ )+++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, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ )+ try:+ response = session.get(f"{CAL_COM_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Cal.com: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Cal.com 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 (401, 403):+ return False, "Invalid Cal.com API key"+ return False, message or "Could not validate Cal.com API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.pynew file mode 100644index 000000000000..a4f39fae012a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py@@ -0,0 +1,120 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Cal.com API v2 reference (https://cal.com/docs/api-reference/v2).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "bookings": {+ "description": "A scheduled meeting booked through Cal.com, including regular, recurring, and seated bookings.",+ "docs_url": "https://cal.com/docs/api-reference/v2/bookings/get-all-bookings",+ "columns": {+ "id": "The unique numeric ID of the booking.",+ "uid": "The unique string identifier (UID) of the booking.",+ "title": "The title of the booking.",+ "description": "The description of the booking.",+ "status": "The booking status (e.g. accepted, cancelled, pending).",+ "cancellationReason": "The reason given when the booking was cancelled.",+ "cancelledByEmail": "Email of the person who cancelled the booking.",+ "reschedulingReason": "The reason given when the booking was rescheduled.",+ "rescheduledByEmail": "Email of the person who rescheduled the booking.",+ "rescheduledFromUid": "UID of the previous booking from which this booking was rescheduled.",+ "rescheduledToUid": "UID of the new booking to which this booking was rescheduled.",+ "start": "When the booked meeting starts.",+ "end": "When the booked meeting ends.",+ "duration": "The duration of the booking in minutes.",+ "eventTypeId": "The ID of the event type the booking was made against (deprecated in favor of eventType).",+ "eventType": "The event type the booking was made against.",+ "location": "Where the booked meeting takes place (e.g. a video call link or address).",+ "absentHost": "Whether the host was marked absent for the booking.",+ "createdAt": "When the booking was created.",+ "updatedAt": "When the booking was last updated (e.g. when its status changed).",+ "rating": "The rating left for the booking.",+ "icsUid": "UID of the ICS calendar event for the booking.",+ "hosts": "The hosts of the booking.",+ "attendees": "The attendees of the booking.",+ "guests": "Email addresses of additional guests invited to the booking.",+ "bookingFieldsResponses": "Responses to custom booking fields, keyed by field slug.",+ "metadata": "Custom metadata attached to the booking.",+ },+ },+ "event_types": {+ "description": "An event type — a bookable meeting template defining duration, availability, and booking rules.",+ "docs_url": "https://cal.com/docs/api-reference/v2/event-types/get-all-event-types",+ "columns": {+ "id": "The unique numeric ID of the event type.",+ "ownerId": "The ID of the user who owns the event type.",+ "title": "The title of the event type.",+ "slug": "The URL slug of the event type.",+ "description": "The description of the event type.",+ "lengthInMinutes": "The default meeting length in minutes.",+ "locations": "The locations offered for meetings booked with this event type.",+ "bookingFields": "The custom fields shown on the booking page.",+ "recurrence": "The recurrence rules for recurring event types.",+ "price": "The price charged to book the event type.",+ "currency": "The currency of the event type's price.",+ "scheduleId": "The ID of the availability schedule used by the event type.",+ "seatsPerTimeSlot": "The number of seats available per time slot for seated event types.",+ "minimumBookingNotice": "The minimum notice (in minutes) required before a booking can be made.",+ "beforeEventBuffer": "Buffer time (in minutes) reserved before each booking.",+ "afterEventBuffer": "Buffer time (in minutes) reserved after each booking.",+ "hidden": "Whether the event type is hidden from the public booking page.",+ "bookingUrl": "The public URL where the event type can be booked.",+ },+ },+ "schedules": {+ "description": "An availability schedule defining when its owner can be booked.",+ "docs_url": "https://cal.com/docs/api-reference/v2/schedules/get-all-schedules",+ "columns": {+ "id": "The unique numeric ID of the schedule.",+ "ownerId": "The ID of the user who owns the schedule.",+ "name": "The name of the schedule.",+ "timeZone": "The time zone the schedule's availability is defined in.",+ "availability": "The weekly recurring availability windows of the schedule.",+ "isDefault": "Whether this is the owner's default schedule.",+ "overrides": "Date-specific overrides to the recurring availability.",+ },+ },+ "teams": {+ "description": "A team the authenticated user belongs to.",+ "docs_url": "https://cal.com/docs/api-reference/v2/teams/get-teams",+ "columns": {+ "id": "The unique numeric ID of the team.",+ "parentId": "The ID of the parent organization, if the team belongs to one.",+ "name": "The name of the team.",+ "slug": "The URL slug of the team.",+ "bio": "The team's bio shown on its booking page.",+ "isOrganization": "Whether this team is an organization.",+ "isPrivate": "Whether the team is private.",+ "timeZone": "The team's time zone.",+ "weekStart": "The day the team's week starts on.",+ },+ },+ "webhooks": {+ "description": "A webhook subscription configured for the authenticated user.",+ "docs_url": "https://cal.com/docs/api-reference/v2/webhooks/get-all-webhooks",+ "columns": {+ "id": "The unique numeric ID of the webhook.",+ "userId": "The ID of the user the webhook belongs to.",+ "subscriberUrl": "The URL webhook payloads are delivered to.",+ "triggers": "The events that trigger the webhook (e.g. BOOKING_CREATED, BOOKING_CANCELLED).",+ "active": "Whether the webhook is active.",+ "payloadTemplate": "The template of the payload sent to the subscriber URL.",+ },+ },+ "me": {+ "description": "The profile of the user the API key belongs to.",+ "docs_url": "https://cal.com/docs/api-reference/v2/me/get-my-profile",+ "columns": {+ "id": "The unique numeric ID of the user.",+ "username": "The user's Cal.com username.",+ "email": "The user's email address.",+ "name": "The user's display name.",+ "timeZone": "The user's time zone.",+ "weekStart": "The day the user's week starts on.",+ "defaultScheduleId": "The ID of the user's default availability schedule.",+ "locale": "The user's locale setting.",+ "organizationId": "The ID of the organization the user belongs to, if any.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.pynew file mode 100644index 000000000000..4b6798523746--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++PaginationStyle = Literal["cursor", "offset", "none"]++_BOOKING_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "updatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class CalComEndpointConfig:+ name: str+ path: str+ # Value for the `cal-api-version` header. Cal.com versions endpoints individually; omitting the+ # header silently falls back to a legacy behavior, so it must be pinned per endpoint.+ api_version: Optional[str] = None+ pagination: PaginationStyle = "none"+ # `/me` returns a single object under `data` instead of a list.+ single_object: bool = False+ # Cal.com numeric ids are unique per resource type across the account, so `id` is a safe key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp used for datetime partitioning (never an updated-at style field).+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Maps an incremental field name to the server-side query param that filters on it.+ incremental_param_by_field: dict[str, str] = field(default_factory=dict)+ default_incremental_field: Optional[str] = None+++# Cal.com API v2 list endpoints (https://cal.com/docs/api-reference/v2/introduction). Only bookings+# exposes server-side timestamp filters (afterUpdatedAt / afterCreatedAt), so it is the only+# incremental-capable endpoint; the rest are small, unpaginated catalogs synced via full refresh.+CAL_COM_ENDPOINTS: dict[str, CalComEndpointConfig] = {+ "bookings": CalComEndpointConfig(+ name="bookings",+ path="/bookings",+ api_version="2026-05-01",+ pagination="cursor",+ partition_key="createdAt",+ incremental_fields=_BOOKING_INCREMENTAL_FIELDS,+ incremental_param_by_field={+ "updatedAt": "afterUpdatedAt",+ "createdAt": "afterCreatedAt",+ },+ default_incremental_field="updatedAt",+ ),+ "event_types": CalComEndpointConfig(+ name="event_types",+ path="/event-types",+ api_version="2024-06-14",+ ),+ "schedules": CalComEndpointConfig(+ name="schedules",+ path="/schedules",+ api_version="2024-06-11",+ ),+ "teams": CalComEndpointConfig(+ name="teams",+ path="/teams",+ ),+ "webhooks": CalComEndpointConfig(+ name="webhooks",+ path="/webhooks",+ pagination="offset",+ ),+ "me": CalComEndpointConfig(+ name="me",+ path="/me",+ single_object=True,+ ),+}++ENDPOINTS = tuple(CAL_COM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CAL_COM_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.pyindex 94fc4c88d983..ebdcad0da83f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/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.cal_com.cal_com import (+ CalComResumeConfig,+ cal_com_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import (+ CAL_COM_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 CalComSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CalComSource(SimpleSource[CalComSourceConfig]):+class CalComSource(ResumableSource[CalComSourceConfig, CalComResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CALCOM@@ -24,7 +48,93 @@ class CalComSource(SimpleSource[CalComSourceConfig]):name=SchemaExternalDataSourceType.CAL_COM,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Cal.com",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Cal.com API key to pull your scheduling data into the PostHog Data warehouse.++You can create an API key under **Settings → Security → API keys** in [Cal.com](https://app.cal.com/settings/developer/api-keys). The key grants read access to your bookings, event types, schedules, teams, and webhooks.+""",iconPath="/static/services/cal_com.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/cal-com",+ keywords=["calcom", "scheduling", "booking"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="cal_live_...",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.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://api.cal.com": "Your Cal.com API key is invalid or has been revoked. Create a new API key under Settings → Security → API keys in Cal.com, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.cal.com": "Your Cal.com API key does not have access to this data. Check the key owner's permissions in Cal.com, then reconnect.",+ }++ def get_schemas(+ self,+ config: CalComSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only bookings exposes server-side timestamp filters (afterUpdatedAt / afterCreatedAt), so+ # it is the only endpoint that supports incremental sync.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(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: CalComSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CalComResumeConfig]:+ return ResumableSourceManager[CalComResumeConfig](inputs, CalComResumeConfig)++ def source_for_pipeline(+ self,+ config: CalComSourceConfig,+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in CAL_COM_ENDPOINTS:+ raise ValueError(f"Unknown Cal.com schema '{inputs.schema_name}'")++ return cal_com_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/cal_com/tests/test_cal_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.pynew file mode 100644index 000000000000..3f769aa72639--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.py@@ -0,0 +1,337 @@+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.sources.cal_com import cal_com+from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.cal_com import (+ CAL_COM_BASE_URL,+ PAGE_LIMIT,+ CalComResumeConfig,+ CalComRetryableError,+ cal_com_source,+ check_access,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import (+ CAL_COM_ENDPOINTS,+ ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = cal_com._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: CalComResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[CalComResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> CalComResumeConfig | None:+ return self._state++ def save_state(self, data: CalComResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager,+ fake_fetch: Any,+ endpoint: str,+ **kwargs: Any,+) -> tuple[list[dict], list[dict[str, Any]]]:+ calls: list[dict[str, Any]] = []++ def _fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:+ calls.append({"url": url, "params": params})+ return fake_fetch(url, params)++ with (+ patch.object(cal_com, "_fetch_page", _fetch),+ patch.object(cal_com, "make_tracked_session", return_value=MagicMock()),+ ):+ rows: list[dict] = []+ for batch in get_rows(+ api_key="cal_live_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows, calls+++class TestBookingsCursorPagination:+ def _pages(self, url: str, params: dict[str, Any]) -> dict[str, Any]:+ cursor = params.get("cursor")+ if cursor is None:+ return {"data": [{"id": 1}], "pagination": {"nextCursor": "c2", "hasMore": True}}+ if cursor == "c2":+ return {"data": [{"id": 2}], "pagination": {"nextCursor": None, "hasMore": False}}+ raise AssertionError(f"unexpected cursor {cursor}")++ def test_follows_next_cursor_until_has_more_false(self) -> None:+ manager = _FakeResumableManager()+ rows, calls = _collect(manager, self._pages, "bookings")+ assert rows == [{"id": 1}, {"id": 2}]+ assert calls[0]["params"] == {"limit": PAGE_LIMIT}+ assert calls[1]["params"] == {"limit": PAGE_LIMIT, "cursor": "c2"}+ # State is saved once — after the first page, pointing at the next cursor — then we stop.+ assert [s.cursor for s in manager.saved] == ["c2"]++ def test_resumes_from_saved_cursor(self) -> None:+ manager = _FakeResumableManager(CalComResumeConfig(cursor="c2"))+ rows, calls = _collect(manager, self._pages, "bookings")+ # The first page must never be re-fetched on resume.+ assert rows == [{"id": 2}]+ assert calls[0]["params"]["cursor"] == "c2"++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _FakeResumableManager()++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ return {"data": [], "pagination": {"nextCursor": None, "hasMore": False}}++ rows, _ = _collect(manager, pages, "bookings")+ assert rows == []+ assert manager.saved == []++ def test_incremental_filter_param_sent_on_every_page(self) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "bookings",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ incremental_field="updatedAt",+ )+ for call in calls:+ assert call["params"]["afterUpdatedAt"] == "2026-01-02T03:04:05.000Z"++ def test_incremental_created_at_maps_to_after_created_at(self) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "bookings",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 2),+ incremental_field="createdAt",+ )+ assert calls[0]["params"]["afterCreatedAt"] == "2026-01-02T00:00:00.000Z"+ assert "afterUpdatedAt" not in calls[0]["params"]++ def test_unknown_incremental_field_raises(self) -> None:+ manager = _FakeResumableManager()+ with pytest.raises(ValueError, match="no server-side filter"):+ _collect(+ manager,+ self._pages,+ "bookings",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ incremental_field="startTime",+ )++ @parameterized.expand(+ [+ ("incremental_disabled", False, "2026-01-01"),+ ("no_last_value", True, None),+ ]+ )+ def test_no_filter_param_without_watermark(self, _name: str, should_use: bool, last_value: Any) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "bookings",+ should_use_incremental_field=should_use,+ db_incremental_field_last_value=last_value,+ incremental_field="updatedAt",+ )+ assert "afterUpdatedAt" not in calls[0]["params"]+++class TestWebhooksOffsetPagination:+ def test_advances_skip_until_short_page(self) -> None:+ manager = _FakeResumableManager()+ full_page = [{"id": i} for i in range(PAGE_LIMIT)]++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ return {"data": full_page if params["skip"] == 0 else [{"id": "last"}]}++ rows, calls = _collect(manager, pages, "webhooks")+ assert len(rows) == PAGE_LIMIT + 1+ assert [c["params"]["skip"] for c in calls] == [0, PAGE_LIMIT]+ assert [s.skip for s in manager.saved] == [PAGE_LIMIT]++ def test_resumes_from_saved_offset(self) -> None:+ manager = _FakeResumableManager(CalComResumeConfig(skip=500))++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ assert params["skip"] == 500+ return {"data": [{"id": "resumed"}]}++ rows, _ = _collect(manager, pages, "webhooks")+ assert rows == [{"id": "resumed"}]+++class TestSingleFetchEndpoints:+ @parameterized.expand([("event_types",), ("schedules",), ("teams",)])+ def test_list_endpoints_yield_single_batch(self, endpoint: str) -> None:+ manager = _FakeResumableManager()+ rows, calls = _collect(manager, lambda url, params: {"data": [{"id": 1}, {"id": 2}]}, endpoint)+ assert rows == [{"id": 1}, {"id": 2}]+ assert len(calls) == 1+ assert manager.saved == []++ def test_me_wraps_single_object_in_list(self) -> None:+ manager = _FakeResumableManager()+ rows, _ = _collect(manager, lambda url, params: {"data": {"id": 42, "username": "tom"}}, "me")+ assert rows == [{"id": 42, "username": "tom"}]++ def test_endpoint_versions_pinned_in_headers(self) -> None:+ # Omitting cal-api-version silently falls back to legacy endpoint behavior, so the+ # versioned endpoints must pin it.+ assert cal_com._headers("k", CAL_COM_ENDPOINTS["bookings"])["cal-api-version"] == "2026-05-01"+ assert cal_com._headers("k", CAL_COM_ENDPOINTS["event_types"])["cal-api-version"] == "2024-06-14"+ assert cal_com._headers("k", CAL_COM_ENDPOINTS["schedules"])["cal-api-version"] == "2024-06-11"+ assert "cal-api-version" not in cal_com._headers("k", CAL_COM_ENDPOINTS["teams"])+++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.reason = "Unauthorized"+ # A query string that would carry credentials on a query-bearing endpoint; the error path+ # must strip it before the URL reaches the exception message.+ response.url = f"{CAL_COM_BASE_URL}/bookings?apiKey=secret-token"+ response.json.return_value = body if body is not None else {"status": "success", "data": []}+ response.text = ""+ 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(CalComRetryableError):+ _fetch_page_unwrapped(session, f"{CAL_COM_BASE_URL}/bookings", {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error_with_scrubbed_url(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page_unwrapped(session, f"{CAL_COM_BASE_URL}/bookings", {}, MagicMock())+ # The base URL stays so `get_non_retryable_errors()` can match, but the credential-bearing+ # query string must never reach the persisted error message.+ message = str(exc_info.value)+ assert f"for url: {CAL_COM_BASE_URL}/bookings" in message+ assert "secret-token" not in message+ assert "?" not in message++ @parameterized.expand([("bare_list", [{"id": 1}]), ("missing_data", {"status": "success"})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(CalComRetryableError):+ _fetch_page_unwrapped(session, f"{CAL_COM_BASE_URL}/me", {}, MagicMock())++ def test_success_returns_full_body(self) -> None:+ body = {"status": "success", "data": [{"id": 1}], "pagination": {"nextCursor": "c2", "hasMore": True}}+ session = self._session_returning(200, body)+ assert _fetch_page_unwrapped(session, f"{CAL_COM_BASE_URL}/bookings", {"limit": 250}, MagicMock()) == body+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": 250}+++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),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Cal.com 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(cal_com, "make_tracked_session", return_value=self._session(response)):+ assert check_access("cal_live_key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(cal_com, "make_tracked_session", return_value=session):+ status, message = check_access("cal_live_key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Cal.com API key"),+ ("forbidden", 403, False, "Invalid Cal.com API key"),+ ("server_error", 500, False, "Cal.com 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(cal_com, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("cal_live_key") == (expected_valid, expected_message)+++class TestCalComSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = cal_com_source(+ api_key="cal_live_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]++ def test_bookings_partitions_on_stable_created_at(self) -> None:+ response = cal_com_source(+ api_key="cal_live_key", endpoint="bookings", logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]+ # Bookings arrive newest-first, so the watermark must only commit after a complete sync.+ assert response.sort_mode == "desc"++ @parameterized.expand([(e,) for e in ENDPOINTS if e != "bookings"])+ def test_full_refresh_endpoints_do_not_partition(self, endpoint: str) -> None:+ response = cal_com_source(+ api_key="cal_live_key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.partition_mode is None+ assert response.sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.pynew file mode 100644index 000000000000..a90f45215e4d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py@@ -0,0 +1,144 @@+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.cal_com.cal_com import CalComResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source import CalComSource+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 CalComSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCalComSource:+ def setup_method(self) -> None:+ self.source = CalComSource()+ self.team_id = 123+ self.config = CalComSourceConfig(api_key="cal_live_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CALCOM++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "CalCom"+ assert config.label == "Cal.com"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cal-com"++ 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(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_bookings_supports_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["bookings"].supports_incremental is True+ assert [f["field"] for f in schemas["bookings"].incremental_fields] == ["updatedAt", "createdAt"]+ for name, schema in schemas.items():+ if name == "bookings":+ continue+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["bookings"])+ assert len(schemas) == 1+ assert schemas[0].name == "bookings"++ 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)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.cal.com/v2/bookings?limit=250",),+ ("403 Client Error: Forbidden for url: https://api.cal.com/v2/me",),+ ]+ )+ 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://api.cal.com/v2/bookings",),+ ("429 Client Error: Too Many Requests for url: https://api.cal.com/v2/teams",),+ ]+ )+ 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.cal_com.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Cal.com API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid Cal.com API key")+ mock_validate.assert_called_once_with("cal_live_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 CalComResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source.cal_com_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "bookings"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "updatedAt"+ 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"] == "cal_live_key"+ assert kwargs["endpoint"] == "bookings"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "updatedAt"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source.cal_com_source")+ def test_source_for_pipeline_drops_incremental_value_when_disabled(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "bookings"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None++ 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 Cal.com schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --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 04a6c90dedbe..31fe8b8fcc61 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@@ -576,7 +576,7 @@ class BuzzsproutSourceConfig(config.Config):@config.configclass CalComSourceConfig(config.Config):- pass+ api_key: str@config.config