: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 smartwaiver import source (#69371)
Tom Owerse9c9f6ad8fc6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 685c52fbef88..1ac5cce6ce8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -332,6 +332,7 @@ the row lists both.| smaily | HTTP | requests | ✅ || smartreach | HTTP | requests | ✅ || smartsheet | HTTP | requests | ✅ |+| smartwaiver | HTTP | requests | ✅ || snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || snowflake | DB protocol | snowflake-connector-python | ➖ || solarwinds_service_desk | HTTP | requests | ✅ |@@ -706,6 +707,7 @@ doesn't conflict with concurrent PRs.- simplesat- smartengage- smartwaiver+- solarwinds_service_desk- sonar_cloud- spotify_ads- spotlercrmdiff --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 f20ea961798a..482ddd00cf01 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@@ -3195,7 +3195,7 @@ class SmartsheetSourceConfig(config.Config):@config.configclass SmartwaiverSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/canonical_descriptions.pynew file mode 100644index 000000000000..341fb08a686e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/canonical_descriptions.py@@ -0,0 +1,66 @@+"""Canonical, documentation-sourced descriptions for Smartwaiver endpoints and columns.++Sourced from the official Smartwaiver v4 API reference (https://api.smartwaiver.com/docs/v4).+Keyed by the endpoint names in `settings.py` `SMARTWAIVER_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Smartwaiver 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 = {+ "templates": {+ "description": "A waiver template in your Smartwaiver account — the reusable document participants sign.",+ "docs_url": "https://api.smartwaiver.com/docs/v4",+ "columns": {+ "templateId": "Unique identifier of the waiver template.",+ "title": "Title of the waiver template.",+ "publishedVersion": "Version number of the currently published template.",+ "publishedOn": "Time at which the current version of the template was published.",+ "webUrl": "URL where the template can be signed on the web.",+ "kioskUrl": "URL where the template can be signed in kiosk mode.",+ "vanityUrls": "Custom vanity URLs configured for this template.",+ "webhook": "Webhook configuration for this template (endpoint and email-validation requirement), if any.",+ },+ },+ "waivers": {+ "description": "A signed waiver submitted by a participant, with signer details and template metadata.",+ "docs_url": "https://api.smartwaiver.com/docs/v4",+ "columns": {+ "waiverId": "Unique identifier of the signed waiver.",+ "templateId": "Identifier of the waiver template that was signed.",+ "title": "Title of the waiver at the time of signing.",+ "createdOn": "Time at which the waiver was signed.",+ "expirationDate": "Date the waiver expires, if the template has an expiration configured.",+ "expired": "Whether the waiver has expired.",+ "verified": "Whether the signer's email address has been verified.",+ "kiosk": "Whether the waiver was signed at a kiosk.",+ "firstName": "First name of the first participant on the waiver.",+ "middleName": "Middle name of the first participant on the waiver.",+ "lastName": "Last name of the first participant on the waiver.",+ "dob": "Date of birth of the first participant (1800-01-01 if age is verified with a checkbox).",+ "isMinor": "Whether the first participant is a minor.",+ "autoTag": "Auto-tag value passed via the waiver URL, if any.",+ "tags": "Tags applied to the waiver.",+ "flags": "Flagged questions on the waiver (display text and reason).",+ "events": "Events attached to the waiver (only when requested with event data).",+ },+ },+ "checkins": {+ "description": "A participant check-in recorded against a signed waiver. One waiver can have multiple check-in records — one per signer.",+ "docs_url": "https://api.smartwaiver.com/docs/v4",+ "columns": {+ "checkinId": "Identifier of the check-in record.",+ "date": "Time at which the check-in happened.",+ "waiverId": "Identifier of the signed waiver the check-in belongs to.",+ "position": "Zero-based position of the participant on the waiver; -1 means the guardian.",+ "firstName": "First name of the checked-in participant.",+ "lastName": "Last name of the checked-in participant.",+ "isMinor": "Whether the checked-in participant is a minor.",+ "dateSigned": "Time at which the underlying waiver was signed.",+ "templateId": "Identifier of the waiver template the waiver was created from.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/settings.pynew file mode 100644index 000000000000..220b59c1d1b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/settings.py@@ -0,0 +1,77 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_fields(field_name: str) -> list[IncrementalField]:+ # Smartwaiver's only server-side time filter is `fromDts`/`toDts`, which keys off the+ # resource's creation timestamp. Advertising just that field keeps the user's chosen cursor+ # aligned with what the API filters on.+ return [+ {+ "label": field_name,+ "type": IncrementalFieldType.DateTime,+ "field": field_name,+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@dataclass+class SmartwaiverEndpointConfig:+ name: str+ path: str # Path under https://api.smartwaiver.com, e.g. "/v4/waivers"+ # Key of the record list in the JSON response envelope (`type` matches it).+ response_key: str+ # Whether the endpoint exposes the server-side `fromDts` timestamp filter.+ supports_incremental: bool = False+ # Field `fromDts` filters on; also used as the incremental cursor.+ incremental_field: Optional[str] = None+ # Stable creation-time field to partition by. None when the table is small enough not to bother.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++SMARTWAIVER_ENDPOINTS: dict[str, SmartwaiverEndpointConfig] = {+ # Waiver templates. No pagination — the endpoint returns every template in one response, and+ # accounts hold at most a handful, so it's full refresh only.+ "templates": SmartwaiverEndpointConfig(+ name="templates",+ path="/v4/templates",+ response_key="templates",+ primary_keys=["templateId"],+ ),+ # Signed waiver summaries. `fromDts` filters server-side on the signing timestamp (`createdOn`),+ # so incremental syncs only pull waivers signed after the watermark.+ "waivers": SmartwaiverEndpointConfig(+ name="waivers",+ path="/v4/waivers",+ response_key="waivers",+ supports_incremental=True,+ incremental_field="createdOn",+ partition_key="createdOn",+ incremental_fields=_datetime_incremental_fields("createdOn"),+ primary_keys=["waiverId"],+ ),+ # Participant check-ins. `fromDts`/`toDts` are required and filter server-side on the check-in+ # timestamp (`date`). One waiver can have several check-in records (one per signer, and -1 for+ # the guardian), so the key includes `position`.+ "checkins": SmartwaiverEndpointConfig(+ name="checkins",+ path="/v4/checkins",+ response_key="checkins",+ supports_incremental=True,+ incremental_field="date",+ partition_key="date",+ incremental_fields=_datetime_incremental_fields("date"),+ primary_keys=["checkinId", "position"],+ ),+}++ENDPOINTS = tuple(SMARTWAIVER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SMARTWAIVER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/smartwaiver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/smartwaiver.pynew file mode 100644index 000000000000..9db12a3bdf82--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/smartwaiver.py@@ -0,0 +1,339 @@+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+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.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.settings import (+ SMARTWAIVER_ENDPOINTS,+ SmartwaiverEndpointConfig,+)++SMARTWAIVER_BASE_URL = "https://api.smartwaiver.com"+# /v4/waivers documents limit 1-300 and /v4/checkins documents 1-100; 100 keeps every endpoint on+# the largest page size both allow.+PAGE_SIZE = 100+# /v4/checkins caps `offset` at 1000. Past that the remainder of the window can't be paged, so we+# stop and log rather than loop.+CHECKINS_MAX_OFFSET = 1000+REQUEST_TIMEOUT_SECONDS = 60+# Accounts are limited to 100 requests/minute in a fixed window; a 429 carries a Retry-After header+# with the seconds until the window resets. Cap the sleep so a bogus header can't stall the worker.+MAX_RETRY_AFTER_SECONDS = 120+# /v4/checkins requires `fromDts`; on a full sync we use a date safely before any Smartwaiver data.+DEFAULT_FROM_DTS = "2000-01-01T00:00:00"+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every endpoint.+DEFAULT_PROBE_PATH = "/v4/templates"+++class SmartwaiverRetryableError(Exception):+ pass+++class SmartwaiverResumeConfig:+ # Next zero-based page to fetch. The `fromDts`/`toDts` window is persisted alongside it so a+ # resumed job continues the exact query it was paging through; merge dedupes any re-pulled page+ # on the primary key.+ next_offset: int = 0+ from_dts: str | None = None+ to_dts: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _format_dts(value: Any) -> str:+ """Format an incremental cursor as the ISO 8601 string Smartwaiver expects for `fromDts`/`toDts`.++ The API interprets values as UTC; timestamps in responses come back as naive UTC strings+ ("2018-01-01 12:32:16"), which `fromisoformat` parses directly.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time()).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, str):+ try:+ return _format_dts(datetime.fromisoformat(value))+ except ValueError:+ return value+ return str(value)+++def _start_of_current_hour(now: datetime) -> datetime:+ aware = now if now.tzinfo is not None else now.replace(tzinfo=UTC)+ return aware.astimezone(UTC).replace(minute=0, second=0, microsecond=0)+++def _clamp_before_current_hour(value: Any, now: datetime) -> str:+ """Clamp a cursor so it satisfies the API's "must not be within the current hour" rule.++ Anything the clamp re-pulls is deduped on the primary key by the merge.+ """+ boundary = _start_of_current_hour(now) - timedelta(seconds=1)+ formatted = _format_dts(value)+ boundary_formatted = boundary.strftime("%Y-%m-%dT%H:%M:%S")+ # Both strings are naive-UTC ISO 8601, so lexicographic comparison is chronological.+ return min(formatted, boundary_formatted)+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{SMARTWAIVER_BASE_URL}{path}"+ return f"{SMARTWAIVER_BASE_URL}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((SmartwaiverRetryableError, 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, logger: FilteringBoundLogger) -> dict:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429:+ # The rate-limit window is fixed, so exponential backoff alone can retry into the same+ # window; sleep out Retry-After here. Tenacity still adds its jitter wait on top of this+ # sleep, but the Retry-After sleep is the dominant delay for large windows.+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))+ logger.debug(f"Smartwaiver rate limited; sleeping {retry_after}s before retrying {url}")+ time.sleep(retry_after)+ raise SmartwaiverRetryableError(f"Smartwaiver API error (retryable): status=429, url={url}")++ if response.status_code >= 500:+ raise SmartwaiverRetryableError(f"Smartwaiver API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Smartwaiver API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ raise SmartwaiverRetryableError(f"Smartwaiver returned an unexpected payload for {url}: {type(data).__name__}")++ return data+++def _parse_retry_after(header: str | None) -> int:+ try:+ seconds = int(header) if header is not None else 60+ except ValueError:+ seconds = 60+ return max(1, min(seconds, MAX_RETRY_AFTER_SECONDS))+++def _get_templates(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:+ data = _fetch_page(session, _build_url("/v4/templates", {}), logger)+ items = data.get("templates", [])+ if items:+ yield items+++def _get_waivers(+ session: requests.Session,+ config: SmartwaiverEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmartwaiverResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ offset, from_dts = resume.next_offset, resume.from_dts+ logger.debug(f"Smartwaiver: resuming {config.name} from offset {offset}")+ else:+ offset = 0+ from_dts = (+ _clamp_before_current_hour(db_incremental_field_last_value, datetime.now(UTC))+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}+ if from_dts:+ params["fromDts"] = from_dts++ data = _fetch_page(session, _build_url(config.path, params), logger)+ items = data.get(config.response_key, [])+ if items:+ yield items++ # No has-more flag on this endpoint: a partial page means we've reached the end.+ if len(items) < PAGE_SIZE:+ break++ # `offset` is a zero-based page index ("based on the limit"), not a row offset.+ offset += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes any re-pulled page on the primary key.+ resumable_source_manager.save_state(SmartwaiverResumeConfig(next_offset=offset, from_dts=from_dts))+++def _get_checkins(+ session: requests.Session,+ config: SmartwaiverEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmartwaiverResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ offset, from_dts, to_dts = resume.next_offset, resume.from_dts, resume.to_dts+ logger.debug(f"Smartwaiver: resuming {config.name} from offset {offset}")+ else:+ offset = 0+ now = datetime.now(UTC)+ # Both bounds are required: `fromDts` must not be within the current hour and `toDts` must+ # be before it, so incremental check-in data lags real time by up to an hour. Rows landing+ # after `toDts` are picked up by the next sync (`fromDts` restarts from the watermark).+ cursor = (+ db_incremental_field_last_value+ if should_use_incremental_field and db_incremental_field_last_value+ else DEFAULT_FROM_DTS+ )+ from_dts = _clamp_before_current_hour(cursor, now)+ to_dts = (_start_of_current_hour(now) - timedelta(seconds=1)).strftime("%Y-%m-%dT%H:%M:%S")++ while True:+ params: dict[str, Any] = {"fromDts": from_dts, "toDts": to_dts, "limit": PAGE_SIZE, "offset": offset}++ data = _fetch_page(session, _build_url(config.path, params), logger)+ # The check-in list nests inside a payload object that also carries the paging flag.+ payload = data.get(config.response_key) or {}+ items = payload.get("checkins", []) if isinstance(payload, dict) else []+ if items:+ yield items++ if not (isinstance(payload, dict) and payload.get("moreCheckins")):+ break++ if offset >= CHECKINS_MAX_OFFSET:+ # The API rejects offsets past 1000, so the remainder of this window is unreachable in+ # one sync; the next incremental sync restarts from the advanced watermark.+ logger.warning(+ f"Smartwaiver: checkins window {from_dts}..{to_dts} has more results past the "+ f"offset cap ({CHECKINS_MAX_OFFSET}); stopping this sync early"+ )+ break++ offset += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes any re-pulled page on the primary key.+ resumable_source_manager.save_state(+ SmartwaiverResumeConfig(next_offset=offset, from_dts=from_dts, to_dts=to_dts)+ )+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmartwaiverResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SMARTWAIVER_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ if endpoint == "templates":+ yield from _get_templates(session, logger)+ elif endpoint == "checkins":+ yield from _get_checkins(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif endpoint == "waivers":+ yield from _get_waivers(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ # Explicit so an endpoint added to SMARTWAIVER_ENDPOINTS without a dispatch branch fails+ # fast instead of silently paging with the waivers logic.+ raise ValueError(f"No fetcher implemented for Smartwaiver endpoint '{endpoint}'")+++def smartwaiver_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmartwaiverResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SMARTWAIVER_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,+ ),+ 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,+ # The docs don't state the list order and the related search endpoint defaults to+ # newest-first, so declare "desc": the watermark then only advances once a sync completes,+ # which is correct for either actual order.+ sort_mode="desc",+ )+++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=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(_build_url(path, {}), timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Smartwaiver: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Smartwaiver 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 Smartwaiver API key"+ return False, message or "Could not validate Smartwaiver API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/source.pyindex eb692857be50..760c40719356 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/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.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 SmartwaiverSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SMARTWAIVER_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.smartwaiver import (+ SmartwaiverResumeConfig,+ smartwaiver_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SmartwaiverSource(SimpleSource[SmartwaiverSourceConfig]):+class SmartwaiverSource(ResumableSource[SmartwaiverSourceConfig, SmartwaiverResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SMARTWAIVER@@ -22,9 +46,93 @@ class SmartwaiverSource(SimpleSource[SmartwaiverSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SMARTWAIVER,- category=DataWarehouseSourceCategory.PRODUCTIVITY,+ category=DataWarehouseSourceCategory.SALES,label="Smartwaiver",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Smartwaiver API key to pull your digital waiver data into the PostHog Data warehouse.++You can create an API key under **My Account → API keys** in [Smartwaiver](https://app.smartwaiver.com). The key is account-wide and grants read access to your waiver templates, signed waivers, and check-ins.+""",iconPath="/static/services/smartwaiver.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/smartwaiver",+ keywords=["waiver", "waivers", "e-signature", "esignature"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.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.smartwaiver.com": "Your Smartwaiver API key is invalid or has been revoked. Generate a new key under My Account → API keys, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.smartwaiver.com": "Your Smartwaiver API key does not have access to this data. Check the key in your Smartwaiver account, then reconnect.",+ }++ def get_schemas(+ self,+ config: SmartwaiverSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SMARTWAIVER_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(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: SmartwaiverSourceConfig, 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[SmartwaiverResumeConfig]:+ return ResumableSourceManager[SmartwaiverResumeConfig](inputs, SmartwaiverResumeConfig)++ def source_for_pipeline(+ self,+ config: SmartwaiverSourceConfig,+ resumable_source_manager: ResumableSourceManager[SmartwaiverResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SMARTWAIVER_ENDPOINTS:+ raise ValueError(f"Unknown Smartwaiver schema '{inputs.schema_name}'")++ return smartwaiver_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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.pynew file mode 100644index 000000000000..76d6bede6b46--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py@@ -0,0 +1,310 @@+from datetime import UTC, date, datetime+from typing import Any++from freezegun import freeze_time+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver import smartwaiver+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.smartwaiver import (+ CHECKINS_MAX_OFFSET,+ PAGE_SIZE,+ SmartwaiverResumeConfig,+ _clamp_before_current_hour,+ _format_dts,+ _parse_retry_after,+ get_rows,+ smartwaiver_source,+ validate_credentials,+)++_NOW = datetime(2026, 7, 8, 15, 42, 30, tzinfo=UTC)+# `fromDts` must not be within the current hour, so recent cursors clamp to 14:59:59.+_HOUR_BOUNDARY = "2026-07-08T14:59:59"+++class _FakeResumableManager:+ def __init__(self, state: SmartwaiverResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SmartwaiverResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SmartwaiverResumeConfig | None:+ return self._state++ def save_state(self, data: SmartwaiverResumeConfig) -> None:+ self.saved.append(data)+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(smartwaiver, "_fetch_page", fake_fetch)+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ rows: list[dict] = []+ for batch in get_rows(api_key="key", logger=MagicMock(), resumable_source_manager=manager, **kwargs): # type: ignore[arg-type]+ rows.extend(batch)+ return rows+++def _waiver_page(ids: list[str]) -> dict:+ return {"type": "waivers", "waivers": [{"waiverId": i} for i in ids]}+++def _checkin_page(ids: list[int], more: bool) -> dict:+ return {+ "type": "checkins",+ "checkins": {"moreCheckins": more, "checkins": [{"checkinId": i, "position": 0} for i in ids]},+ }+++class TestFormatDts:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),+ # Smartwaiver responses carry naive space-separated timestamps; they must round-trip+ # into the `T`-separated form the API accepts for `fromDts`.+ ("api_response_string", "2018-01-01 12:32:16", "2018-01-01T12:32:16"),+ ("iso_string", "2018-01-01T12:32:16", "2018-01-01T12:32:16"),+ ("unparseable_string_passthrough", "not-a-date", "not-a-date"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_dts(value) == expected+++class TestClampBeforeCurrentHour:+ @parameterized.expand(+ [+ ("old_value_untouched", "2026-01-01 10:00:00", "2026-01-01T10:00:00"),+ ("within_current_hour_clamped", "2026-07-08 15:30:00", _HOUR_BOUNDARY),+ ("future_value_clamped", datetime(2026, 7, 9, 1, 0, 0, tzinfo=UTC), _HOUR_BOUNDARY),+ ]+ )+ def test_clamp(self, _name: str, value: Any, expected: str) -> None:+ assert _clamp_before_current_hour(value, _NOW) == expected+++class TestParseRetryAfter:+ @parameterized.expand(+ [+ ("normal", "37", 37),+ ("missing_header", None, 60),+ ("garbage", "soon", 60),+ ("zero_floored", "0", 1),+ ("huge_capped", "86400", 120),+ ]+ )+ def test_parse(self, _name: str, header: str | None, expected: int) -> None:+ assert _parse_retry_after(header) == expected+++class TestGetWaivers:+ def test_paginates_until_partial_page(self, monkeypatch: Any) -> None:+ full_page = [str(i) for i in range(PAGE_SIZE)]+ pages = {+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=0": _waiver_page(full_page),+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=1": _waiver_page(["last"]),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="waivers")++ assert len(rows) == PAGE_SIZE + 1+ assert fetched == list(pages)++ def test_saves_resume_state_after_each_yielded_page(self, monkeypatch: Any) -> None:+ full_page = [str(i) for i in range(PAGE_SIZE)]+ pages = {+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=0": _waiver_page(full_page),+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=1": _waiver_page([]),+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="waivers")++ # State is saved only while more pages may remain, never on the final partial page.+ assert manager.saved == [SmartwaiverResumeConfig(next_offset=1, from_dts=None)]++ def test_resumes_from_saved_offset_and_window(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=3&fromDts=2026-01-01T00%3A00%3A00": _waiver_page(+ ["w1"]+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(SmartwaiverResumeConfig(next_offset=3, from_dts="2026-01-01T00:00:00"))+ rows = _collect(monkeypatch, manager, endpoint="waivers")++ assert [r["waiverId"] for r in rows] == ["w1"]+ assert fetched == list(pages)++ @freeze_time(_NOW)+ def test_incremental_cursor_added_and_clamped(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=0&fromDts=2026-01-01T10%3A00%3A00": _waiver_page(+ ["w1"]+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="waivers",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01 10:00:00",+ )+ assert "fromDts=2026-01-01T10%3A00%3A00" in fetched[0]++ def test_full_refresh_omits_time_filter(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.smartwaiver.com/v4/waivers?limit={PAGE_SIZE}&offset=0": _waiver_page(["w1"]),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(monkeypatch, _FakeResumableManager(), endpoint="waivers")++ assert "fromDts" not in fetched[0]+++class TestGetCheckins:+ @freeze_time(_NOW)+ def test_full_sync_uses_default_window(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.smartwaiver.com/v4/checkins?fromDts=2000-01-01T00%3A00%3A00&toDts=2026-07-08T14%3A59%3A59&limit={PAGE_SIZE}&offset=0": _checkin_page(+ [1], more=False+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="checkins")++ assert [r["checkinId"] for r in rows] == [1]+ # Both bounds are required by the API: an old default lower bound and an upper bound+ # strictly before the current hour.+ assert fetched == list(pages)++ @freeze_time(_NOW)+ def test_incremental_sync_starts_window_at_watermark(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.smartwaiver.com/v4/checkins?fromDts=2026-06-01T08%3A00%3A00&toDts=2026-07-08T14%3A59%3A59&limit={PAGE_SIZE}&offset=0": _checkin_page(+ [1], more=False+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="checkins",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-06-01 08:00:00",+ )+ assert fetched == list(pages)++ @freeze_time(_NOW)+ def test_paginates_while_more_checkins_and_saves_state(self, monkeypatch: Any) -> None:+ window = f"fromDts=2000-01-01T00%3A00%3A00&toDts=2026-07-08T14%3A59%3A59&limit={PAGE_SIZE}"+ pages = {+ f"https://api.smartwaiver.com/v4/checkins?{window}&offset=0": _checkin_page([1], more=True),+ f"https://api.smartwaiver.com/v4/checkins?{window}&offset=1": _checkin_page([2], more=False),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(monkeypatch, manager, endpoint="checkins")++ assert [r["checkinId"] for r in rows] == [1, 2]+ assert fetched == list(pages)+ assert manager.saved == [+ SmartwaiverResumeConfig(next_offset=1, from_dts="2000-01-01T00:00:00", to_dts="2026-07-08T14:59:59")+ ]++ def test_stops_at_offset_cap(self, monkeypatch: Any) -> None:+ # A window with more results past the API's offset cap must terminate, not loop.+ state = SmartwaiverResumeConfig(+ next_offset=CHECKINS_MAX_OFFSET, from_dts="2000-01-01T00:00:00", to_dts="2026-07-08T14:59:59"+ )+ window = f"fromDts=2000-01-01T00%3A00%3A00&toDts=2026-07-08T14%3A59%3A59&limit={PAGE_SIZE}"+ pages = {+ f"https://api.smartwaiver.com/v4/checkins?{window}&offset={CHECKINS_MAX_OFFSET}": _checkin_page(+ [1], more=True+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(state)+ rows = _collect(monkeypatch, manager, endpoint="checkins")++ assert [r["checkinId"] for r in rows] == [1]+ assert fetched == list(pages)+ assert manager.saved == []+++class TestGetTemplates:+ def test_single_fetch_yields_templates(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.smartwaiver.com/v4/templates": {+ "type": "templates",+ "templates": [{"templateId": "t1"}, {"templateId": "t2"}],+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="templates")++ assert [r["templateId"] for r in rows] == ["t1", "t2"]+ assert fetched == list(pages)+++class TestSmartwaiverSource:+ @parameterized.expand(+ [+ ("templates", ["templateId"], None),+ ("waivers", ["waiverId"], ["createdOn"]),+ ("checkins", ["checkinId", "position"], ["date"]),+ ]+ )+ def test_source_response_keys_and_partitioning(+ self, endpoint: str, expected_pks: list[str], expected_partition_keys: list[str] | None+ ) -> None:+ response = smartwaiver_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_pks+ assert response.partition_keys == expected_partition_keys+ # List order is undocumented, so the watermark must only advance on completed syncs.+ assert response.sort_mode == "desc"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (200, None), True, None),+ ("unauthorized", (401, None), False, "Invalid Smartwaiver API key"),+ ("forbidden", (403, None), False, "Invalid Smartwaiver API key"),+ ("server_error", (500, "Smartwaiver returned HTTP 500"), False, "Smartwaiver returned HTTP 500"),+ (+ "connection_error",+ (0, "Could not connect to Smartwaiver: boom"),+ False,+ "Could not connect to Smartwaiver: boom",+ ),+ ]+ )+ def test_status_mapping(+ self, _name: str, check_result: tuple[int, str | None], expected_valid: bool, expected_message: str | None+ ) -> None:+ with patch.object(smartwaiver, "check_access", return_value=check_result):+ is_valid, message = validate_credentials("key")+ assert is_valid is expected_valid+ assert message == expected_messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver_source.pynew file mode 100644index 000000000000..275a5613a3fb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver_source.py@@ -0,0 +1,167 @@+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.generated_configs import SmartwaiverSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.settings import (+ ENDPOINTS,+ SMARTWAIVER_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.smartwaiver import (+ SmartwaiverResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.source import SmartwaiverSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++# Endpoints exposing Smartwaiver's server-side `fromDts` timestamp filter.+_INCREMENTAL_ENDPOINTS = {"waivers": "createdOn", "checkins": "date"}+_FULL_REFRESH_ENDPOINTS = {"templates"}+++class TestSmartwaiverSource:+ def setup_method(self):+ self.source = SmartwaiverSource()+ self.team_id = 123+ self.config = SmartwaiverSourceConfig(api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.SMARTWAIVER++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Smartwaiver"+ assert config.label == "Smartwaiver"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/smartwaiver.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/smartwaiver"++ 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):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.smartwaiver.com/v4/waivers?limit=100&offset=0",),+ (+ "403 Client Error: Forbidden for url: https://api.smartwaiver.com/v4/checkins?fromDts=2000-01-01T00%3A00%3A00",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ("429 Client Error: Too Many Requests for url: https://api.smartwaiver.com/v4/waivers",),+ ("500 Server Error: Internal Server Error for url: https://api.smartwaiver.com/v4/waivers",),+ ("HTTPSConnectionPool(host='api.smartwaiver.com', port=443): Read timed out.",),+ ]+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name, cursor_field in _INCREMENTAL_ENDPOINTS.items():+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == [cursor_field]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["waivers"])+ assert len(schemas) == 1+ assert schemas[0].name == "waivers"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(SMARTWAIVER_ENDPOINTS)++ @parameterized.expand(+ [+ ((True, None), True, None),+ ((False, "Invalid Smartwaiver API key"), False, "Invalid Smartwaiver API key"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.source.validate_credentials"+ )+ def test_validate_credentials(self, mock_return, expected_valid, expected_message, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is SmartwaiverResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.source.smartwaiver_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_smartwaiver_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "waivers"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01 00:00:00"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_smartwaiver_source.assert_called_once()+ kwargs = mock_smartwaiver_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "waivers"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01 00:00:00"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartwaiver.source.smartwaiver_source"+ )+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_smartwaiver_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "templates"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01 00:00:00"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_smartwaiver_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "nope"+ with pytest.raises(ValueError, match="Unknown Smartwaiver schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)