: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 squadcast import source (#71230)
Tom Owersee19375bde82
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 43529acaa96a..50f43cbd4e41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -467,6 +467,7 @@ the row lists both.| spacelift | HTTP (GraphQL) | requests | ✅ || sparkpost | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ |+| squadcast | HTTP | requests | ✅ || square | HTTP | requests | ✅ || squarespace | HTTP | requests | ✅ || statuspage | HTTP | requests | ✅ |@@ -923,7 +924,6 @@ doesn't conflict with concurrent PRs.- spacelift- spotify_ads- spotlercrm-- squadcast- statsig- statuscake- stockdatadiff --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 b21074be9970..8b769d6c0919 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@@ -4082,7 +4082,8 @@ class SpotlerCRMSourceConfig(config.Config):@config.configclass SquadcastSourceConfig(config.Config):- pass+ refresh_token: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/canonical_descriptions.pynew file mode 100644index 000000000000..396d09eb9041--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/canonical_descriptions.py@@ -0,0 +1,206 @@+"""Canonical, documentation-sourced descriptions for Squadcast endpoints and columns.++Sourced from the official SolarWinds Incident Response (Squadcast) API reference+(https://developers.incidents.cloud.solarwinds.com/api-reference). Keyed by the endpoint names in+`settings.py` `SQUADCAST_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table.+Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Stamped onto every fan-out row by the transport; not part of the upstream payload.+_TEAM_ID_COLUMN = "ID of the Squadcast team the row belongs to (added by PostHog during sync)."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "incidents": {+ "description": "An incident triggered on a Squadcast service, pulled from the incident export with its lifecycle timestamps and response metrics.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/export",+ "columns": {+ "id": "Unique identifier for the incident.",+ "title": "Title of the incident.",+ "description": "Description of the incident.",+ "status": "Current status of the incident (e.g. triggered, acknowledged, resolved, suppressed).",+ "service": "Name of the service the incident was triggered on.",+ "alert_source": "Alert source that created the incident.",+ "assignee": "Current assignee of the incident.",+ "created_at": "Time at which the incident was created; the incremental cursor.",+ "acknowledged_at": "Time at which the incident was acknowledged, if applicable.",+ "resolved_at": "Time at which the incident was resolved, if applicable.",+ "slo_name": "Name of the SLO the incident affects, if any.",+ "slis": "SLIs the incident affects.",+ "error_budget_spent": "Error budget consumed by the incident.",+ "tags": "Tags attached to the incident.",+ "event_count": "Number of alert events grouped into the incident.",+ "tta": "Time to acknowledge, in seconds.",+ "ttr": "Time to resolve, in seconds.",+ "children": "Child incidents merged into this incident.",+ "logs": "Timeline log entries for the incident.",+ "url": "URL of the incident in the Squadcast web UI.",+ "priority": "Priority assigned to the incident, if any.",+ "attached_runbooks": "Runbooks attached to the incident.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "postmortems": {+ "description": "A postmortem (retrospective) written for an incident.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/incidents-postmortems",+ "columns": {+ "id": "Unique identifier for the postmortem.",+ "organization_id": "ID of the organization the postmortem belongs to.",+ "incident_id": "ID of the incident the postmortem was written for.",+ "postmortem": "Markdown body of the postmortem.",+ "follow_ups": "Follow-up actions recorded in the postmortem.",+ "created_at": "Time at which the postmortem was created; the incremental cursor.",+ "title": "Title of the postmortem.",+ "status": "Status of the postmortem: in_progress, under_review, or published.",+ "owner": "Owner (typically a team) of the postmortem.",+ "incident_message": "Message of the incident the postmortem covers.",+ "incident_time_of_creation": "Creation time of the incident the postmortem covers.",+ "service_name": "Name of the service the incident occurred on.",+ "service_id": "ID of the service the incident occurred on.",+ "alert_source": "Alert source of the underlying incident.",+ "active_follow_ups_count": "Number of open follow-up actions.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "services": {+ "description": "A service monitored in Squadcast that incidents are triggered against.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/services",+ "columns": {+ "id": "Unique identifier for the service.",+ "name": "Name of the service.",+ "slug": "URL-friendly slug for the service name.",+ "email": "Email address that creates incidents on this service.",+ "escalation_policy_id": "ID of the escalation policy attached to the service.",+ "organization_id": "ID of the organization the service belongs to.",+ "description": "Description of the service.",+ "depends": "IDs of services this service depends on.",+ "owner": "Owner (typically a team) of the service.",+ "on_maintenance": "Whether the service is currently in maintenance mode.",+ "escalation_policy": "Escalation policy attached to the service.",+ "tags": "Tags attached to the service.",+ "created_at": "Time at which the service was created.",+ "updated_at": "Time at which the service was last updated.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "escalation_policies": {+ "description": "An escalation policy defining who is notified about an incident and in what order.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/escalation-policies",+ "columns": {+ "id": "Unique identifier for the escalation policy.",+ "name": "Name of the escalation policy.",+ "description": "Description of the escalation policy.",+ "organization_id": "ID of the organization the policy belongs to.",+ "repetition": "Number of times the entire policy is repeated.",+ "repeat_after": "Time in minutes after which the policy repeats.",+ "rules": "Rules that define the escalation steps.",+ "slug": "URL-friendly slug for the policy name.",+ "enable_incident_reminders": "Whether incident reminders are enabled.",+ "incident_reminder_rules": "Rules for incident reminders.",+ "enable_incident_retrigger": "Whether automatic incident re-triggering is enabled.",+ "retrigger_after": "Time in hours after which an incident is re-triggered.",+ "owner": "Owner (typically a team) of the policy.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "schedules": {+ "description": "An on-call schedule (v4 schedules API) defining who is on call for a team.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/schedule",+ "columns": {+ "id": "Unique identifier for the schedule.",+ "name": "Name of the schedule.",+ "description": "Description of the schedule.",+ "orgID": "ID of the organization the schedule belongs to.",+ "teamID": "ID of the team the schedule belongs to.",+ "timeZone": "Time zone the schedule is defined in.",+ "paused": "Whether the schedule is currently paused.",+ "ownerID": "ID of the schedule's owner entity.",+ "ownerType": "Type of the schedule's owner entity.",+ "tags": "Tags attached to the schedule.",+ "createdAt": "Time at which the schedule was created.",+ "updatedAt": "Time at which the schedule was last updated.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "runbooks": {+ "description": "A runbook of steps responders can attach to and follow during an incident.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/runbooks",+ "columns": {+ "id": "Unique identifier for the runbook.",+ "name": "Name of the runbook.",+ "created": "Information about when the runbook was created.",+ "updated": "Information about when the runbook was last updated.",+ "used_count": "Number of times the runbook has been used.",+ "steps": "Steps that make up the runbook.",+ "organization_id": "ID of the organization the runbook belongs to.",+ "owner": "Owner (typically a team) of the runbook.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "slos": {+ "description": "A service level objective tracked in Squadcast, with its error budget and health.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/slos",+ "columns": {+ "id": "Unique identifier for the SLO.",+ "name": "Name of the SLO.",+ "description": "Description of the SLO.",+ "time_interval_type": "Whether the SLO window is fixed or rolling.",+ "service_ids": "IDs of the services the SLO covers.",+ "slis": "SLIs tracked by the SLO.",+ "target_slo": "Target percentage for the SLO.",+ "current_slo": "Current measured percentage of the SLO.",+ "start_time": "Start of the SLO window.",+ "end_time": "End of the SLO window.",+ "is_healthy": "Whether the SLO is currently healthy.",+ "remaining_error_budget": "Remaining error budget, in minutes.",+ "allocated_error_budget": "Allocated error budget, in minutes.",+ "incident_count": "Number of incidents affecting the SLO.",+ "false_positive_count": "Number of incidents marked as false positives.",+ "owner_id": "ID of the team that owns the SLO.",+ "org_id": "ID of the organization the SLO belongs to.",+ "created_at": "Time at which the SLO was created.",+ "updated_at": "Time at which the SLO was last updated.",+ "duration_in_days": "Length of the SLO window in days.",+ "team_id": _TEAM_ID_COLUMN,+ },+ },+ "users": {+ "description": "A user in the Squadcast organization.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/users",+ "columns": {+ "id": "Unique identifier for the user.",+ "first_name": "First name of the user.",+ "last_name": "Last name of the user.",+ "username_for_display": "Display username of the user.",+ "email": "Email address of the user.",+ "contact": "Contact details (dial code and phone number) of the user.",+ "secondary_emails": "Secondary email addresses of the user.",+ "email_verified": "Whether the user's email address is verified.",+ "time_zone": "Time zone of the user.",+ "title": "Job title of the user.",+ "bio": "Bio of the user.",+ "role_id": "ID of the organization-level role assigned to the user.",+ "role": "Organization-level role of the user (e.g. account_owner, user, stakeholder).",+ },+ },+ "teams": {+ "description": "A team in the Squadcast organization, with its members and roles.",+ "docs_url": "https://developers.incidents.cloud.solarwinds.com/api-reference/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "created_at": "Time at which the team was created.",+ "updated_at": "Time at which the team was last updated.",+ "created_by": "ID of the user who created the team.",+ "organization_id": "ID of the organization the team belongs to.",+ "name": "Name of the team.",+ "description": "Description of the team.",+ "slug": "URL-friendly slug for the team name.",+ "members": "Members of the team with their role IDs.",+ "roles": "Roles defined on the team.",+ "default": "Whether this is the organization's default team.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/settings.pynew file mode 100644index 000000000000..152fba2de643--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/settings.py@@ -0,0 +1,98 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# How each endpoint is iterated. Squadcast mixes several pagination styles across its API+# versions, so the transport dispatches on this instead of hardcoding per-endpoint branches:+# - "none": a single request returns the full list (no pagination params).+# - "offset": 0-based `offset`/`limit` params with a `meta.total` counter (SLOs).+# - "cursor": `pageSize`/`cursor` params with a `pageInfo.nextCursor` reference (v4 schedules).+# - "incident_export": required `start_time`/`end_time` window, chunked client-side (incidents).+# - "postmortems": required `fromDate`/`toDate`/`limit` window, single request per team.+PaginationStyle = Literal["none", "offset", "cursor", "incident_export", "postmortems"]+++@dataclass+class SquadcastEndpointConfig:+ path: str # Path under the regional API base URL, e.g. "/v3/services"+ pagination: PaginationStyle = "none"+ # Query param carrying the team id for team-scoped endpoints ("owner_id" on v3,+ # "teamID" on v4). None means the endpoint is org-level and needs no fan-out.+ team_param: Optional[str] = None+ # Keys to walk in the response body to reach the list of rows.+ envelope: tuple[str, ...] = ("data",)+ primary_key: str = "id"+ partition_key: Optional[str] = None # Stable datetime field used to partition (never a mutable field)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Credential-bearing row fields dropped before rows are yielded, so live keys never+ # land in warehouse tables readable by any PostHog user.+ sensitive_fields: tuple[str, ...] = ()+++_CREATED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++SQUADCAST_ENDPOINTS: dict[str, SquadcastEndpointConfig] = {+ "incidents": SquadcastEndpointConfig(+ # The API has no plain incident list endpoint; the JSON export is the documented way to+ # pull incidents in bulk. Its required `start_time`/`end_time` filters key on creation+ # time, which gives us a genuine server-side incremental window. Status changes to+ # incidents created before the cursor are only picked up by a full refresh.+ path="/v3/incidents/export",+ pagination="incident_export",+ team_param="owner_id",+ partition_key="created_at",+ incremental_fields=_CREATED_AT_INCREMENTAL,+ ),+ "postmortems": SquadcastEndpointConfig(+ path="/v3/incidents/postmortem",+ pagination="postmortems",+ team_param="owner_id",+ partition_key="created_at",+ incremental_fields=_CREATED_AT_INCREMENTAL,+ ),+ "services": SquadcastEndpointConfig(+ path="/v3/services",+ team_param="owner_id",+ # `api_key` is the live key alert sources use to send events to the service.+ sensitive_fields=("api_key",),+ ),+ "escalation_policies": SquadcastEndpointConfig(+ # The endpoint documents optional `page_number`/`page_size` params, but their base+ # (0 vs 1) is undocumented and per-team policy counts are small, so we make a single+ # unpaginated request and warn if `meta.total_count` reports more rows than returned.+ path="/v3/escalation-policies",+ team_param="owner_id",+ ),+ "schedules": SquadcastEndpointConfig(+ path="/v4/schedules",+ pagination="cursor",+ team_param="teamID",+ ),+ "runbooks": SquadcastEndpointConfig(+ path="/v3/runbooks",+ team_param="owner_id",+ ),+ "slos": SquadcastEndpointConfig(+ path="/v3/slo",+ pagination="offset",+ team_param="owner_id",+ envelope=("data", "slos"),+ ),+ "users": SquadcastEndpointConfig(+ path="/v3/users",+ ),+ "teams": SquadcastEndpointConfig(+ path="/v3/teams",+ ),+}++ENDPOINTS = tuple(SQUADCAST_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/source.pyindex 55549167b0c6..affcf29ad451 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/source.py@@ -1,19 +1,44 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SquadcastSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.settings import (+ ENDPOINTS,+ SQUADCAST_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.squadcast import (+ SquadcastResumeConfig,+ squadcast_source,+ validate_credentials as validate_squadcast_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SquadcastSource(SimpleSource[SquadcastSourceConfig]):+class SquadcastSource(ResumableSource[SquadcastSourceConfig, SquadcastResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SQUADCAST@@ -24,7 +49,112 @@ class SquadcastSource(SimpleSource[SquadcastSourceConfig]):name=SchemaExternalDataSourceType.SQUADCAST,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Squadcast (SolarWinds Incident Response)",+ keywords=["solarwinds", "incident response", "on-call", "oncall"],+ caption="""Enter your Squadcast refresh token to pull your incident response data into the PostHog Data warehouse.++You can generate a refresh token from your Squadcast profile page (**Profile → Refresh Token**). PostHog exchanges it for a short-lived access token on each sync.++The token inherits your user role, so the connecting user needs read access to the teams and resources you want to sync.""",iconPath="/static/services/squadcast.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/squadcast",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.squadcast.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.squadcast.com)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SquadcastSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # supports_append=False everywhere: incidents and postmortems mutate after creation and+ # incremental windows re-pull boundary rows, so only merge semantics dedupe correctly.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(SQUADCAST_ENDPOINTS[endpoint].incremental_fields),+ supports_append=False,+ incremental_fields=SQUADCAST_ENDPOINTS[endpoint].incremental_fields,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SquadcastSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status, error = validate_squadcast_credentials(config.refresh_token, config.region, schema_name)+ if ok:+ return True, None++ # A valid token may legitimately lack access to a specific resource (the token inherits+ # the user's role). Accept 403 at source-create so users can connect with a lower-role+ # account; re-raise it for per-schema checks.+ if status == 403 and schema_name is None:+ return True, None++ return False, error++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Squadcast refresh token was rejected": "Your Squadcast refresh token is invalid or expired. Generate a new refresh token from your Squadcast profile page and reconnect.",+ "401 Client Error: Unauthorized for url: https://api.squadcast.com": "Your Squadcast refresh token is invalid or expired. Generate a new refresh token from your Squadcast profile page and reconnect.",+ "401 Client Error: Unauthorized for url: https://api.eu.squadcast.com": "Your Squadcast refresh token is invalid or expired. Generate a new refresh token from your Squadcast profile page and reconnect.",+ "403 Client Error: Forbidden for url: https://api.squadcast.com": "Your Squadcast account does not have the permissions needed to sync this data. The token inherits your user role, so reconnect with an account that can read these resources.",+ "403 Client Error: Forbidden for url: https://api.eu.squadcast.com": "Your Squadcast account does not have the permissions needed to sync this data. The token inherits your user role, so reconnect with an account that can read these resources.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SquadcastResumeConfig]:+ return ResumableSourceManager[SquadcastResumeConfig](inputs, SquadcastResumeConfig)++ def source_for_pipeline(+ self,+ config: SquadcastSourceConfig,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return squadcast_source(+ refresh_token=config.refresh_token,+ region=config.region,+ 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/squadcast/squadcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.pynew file mode 100644index 000000000000..6bf8ca36f28d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.py@@ -0,0 +1,521 @@+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.squadcast.settings import (+ SQUADCAST_ENDPOINTS,+ SquadcastEndpointConfig,+)++# Squadcast is region-sharded: a US account's refresh token only works against the US hosts and+# vice versa, so the user picks the region in the source form.+REGION_HOSTS: dict[str, tuple[str, str]] = {+ "us": ("https://auth.squadcast.com", "https://api.squadcast.com"),+ "eu": ("https://auth.eu.squadcast.com", "https://api.eu.squadcast.com"),+}++PAGE_SIZE = 100++# The postmortem list endpoint requires a `limit` and exposes no offset/page param, so we ask for+# a generous window and warn if the reported total exceeds what came back.+POSTMORTEM_LIMIT = 1000++# The incident export requires a start/end window; chunking it bounds each response's size on+# accounts with years of history and gives us natural resume checkpoints.+INCIDENT_EXPORT_WINDOW_DAYS = 30++# Window start used on full refresh / first sync (predates Squadcast's launch).+FULL_REFRESH_START = datetime(2015, 1, 1, tzinfo=UTC)++# Retry/throttle settings kept near the top for easy tuning.+RETRY_ATTEMPTS = 5+REQUEST_TIMEOUT_SECONDS = 60++# Re-exchange the refresh token this many seconds before the access token's `expires_at`.+TOKEN_REFRESH_LEEWAY_SECONDS = 120+++class SquadcastRetryableError(Exception):+ pass+++class SquadcastAuthError(Exception):+ """Raised when the refresh token exchange is rejected — a permanent credential failure."""+++class SquadcastResumeConfig:+ # Bookmark of the team currently being processed (fan-out endpoints). A stable team-ID+ # bookmark rather than a positional index, so teams added/removed between a crash and the+ # retry can't resume us into the wrong team. None for org-level endpoints.+ team_id: str | None = None+ # Position within the bookmarked team: an offset, a page cursor, or an ISO window start,+ # depending on the endpoint's pagination style. None means "start the team from the top".+ cursor: str | None = None+++def _hosts_for_region(region: str | None) -> tuple[str, str]:+ return REGION_HOSTS.get((region or "us").lower(), REGION_HOSTS["us"])+++def _format_datetime(value: Any) -> str:+ """Format a datetime as RFC 3339 with a Z suffix, which Squadcast's date filters expect."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ elif isinstance(value, date):+ utc_value = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ else:+ return str(value)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _parse_datetime(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)+++def _error_message(response: requests.Response) -> str:+ try:+ return response.json().get("meta", {}).get("error_message") or response.text+ except Exception:+ return response.text+++class SquadcastClient:+ """Minimal Squadcast API client that exchanges the long-lived refresh token for a short-lived+ bearer access token and transparently re-exchanges it before expiry."""++ def __init__(self, refresh_token: str, region: str | None, logger: FilteringBoundLogger) -> None:+ self._auth_host, self.api_host = _hosts_for_region(region)+ self._refresh_token = refresh_token+ self._logger = logger+ # Sessions are reused across requests so urllib3 keeps the connection alive. The refresh+ # token is masked in logs/samples, and redirects are disabled so credentialed headers+ # can't be replayed to a redirect target. Both sessions set `capture=False`: the token+ # exchange response carries the minted tokens, and the API responses carry arbitrary+ # customer-authored operational data (incident descriptions, logs, postmortems, runbook+ # steps) the name-based scrubbers can't recognise, so neither belongs in HTTP samples.+ self._session = make_tracked_session(redact_values=(refresh_token,), allow_redirects=False, capture=False)+ self._auth_session = make_tracked_session(redact_values=(refresh_token,), allow_redirects=False, capture=False)+ self._access_token: Optional[str] = None+ self._token_expires_at: float = 0++ def _get_access_token(self) -> str:+ now = time.time()+ if self._access_token is None or now >= self._token_expires_at - TOKEN_REFRESH_LEEWAY_SECONDS:+ response = self._auth_session.get(+ f"{self._auth_host}/oauth/access-token",+ headers={"X-Refresh-Token": self._refresh_token},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code == 429 or response.status_code >= 500:+ raise SquadcastRetryableError(+ f"Squadcast auth error (retryable): status={response.status_code}, host={self._auth_host}"+ )+ if not response.ok:+ raise SquadcastAuthError(+ f"Squadcast refresh token was rejected (status={response.status_code}): {_error_message(response)}"+ )++ data = response.json().get("data", {})+ access_token = data.get("access_token")+ if not access_token:+ raise SquadcastAuthError("Squadcast token exchange succeeded but returned no access token")++ self._access_token = access_token+ # `expires_at` is a unix timestamp; fall back to a conservative 10 minutes if absent.+ self._token_expires_at = float(data.get("expires_at") or (now + 600))++ assert self._access_token is not None+ return self._access_token++ @retry(+ retry=retry_if_exception_type((SquadcastRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any:+ url = f"{self.api_host}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"++ response = self._session.get(+ url,+ headers={"Authorization": f"Bearer {self._get_access_token()}"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise SquadcastRetryableError(f"Squadcast API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ self._logger.error(f"Squadcast API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++# Elements are unvalidated upstream JSON, so this is honestly `list[Any]` — `_prepare_rows`+# guards against non-dict elements at runtime.+def _extract_rows(data: Any, envelope: tuple[str, ...]) -> list[Any]:+ current = data+ for key in envelope:+ if not isinstance(current, dict):+ return []+ current = current.get(key)+ return current if isinstance(current, list) else []+++def _prepare_rows(rows: list[Any], config: SquadcastEndpointConfig, team_id: str | None = None) -> list[Any]:+ """Drop credential-bearing fields (live keys must never land in warehouse tables) and stamp+ the owning team onto fan-out rows — most Squadcast payloads don't carry it."""+ for row in rows:+ if not isinstance(row, dict):+ continue+ for sensitive_field in config.sensitive_fields:+ row.pop(sensitive_field, None)+ if team_id is not None and "team_id" not in row:+ row["team_id"] = team_id+ return rows+++def _iter_offset_pages(+ client: SquadcastClient,+ config: SquadcastEndpointConfig,+ team_id: str,+ start_cursor: str | None,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ offset = int(start_cursor) if start_cursor else 0+ while True:+ assert config.team_param is not None+ data = client.get(config.path, {config.team_param: team_id, "offset": offset, "limit": PAGE_SIZE})+ rows = _extract_rows(data, config.envelope)+ if not rows:+ break++ yield _prepare_rows(rows, config, team_id)++ if len(rows) < PAGE_SIZE:+ break+ offset += PAGE_SIZE+ # Save AFTER yielding so a crash re-fetches the last page; merge dedupes on primary key.+ resumable_source_manager.save_state(SquadcastResumeConfig(team_id=team_id, cursor=str(offset)))+++def _iter_cursor_pages(+ client: SquadcastClient,+ config: SquadcastEndpointConfig,+ team_id: str,+ start_cursor: str | None,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ cursor = start_cursor+ while True:+ assert config.team_param is not None+ params: dict[str, Any] = {config.team_param: team_id, "pageSize": PAGE_SIZE}+ if cursor:+ params["cursor"] = cursor++ data = client.get(config.path, params)+ rows = _extract_rows(data, config.envelope)+ page_info = data.get("pageInfo", {}) if isinstance(data, dict) else {}+ next_cursor = page_info.get("nextCursor") if page_info.get("hasNext") else None++ if rows:+ yield _prepare_rows(rows, config, team_id)++ if not next_cursor:+ break+ cursor = next_cursor+ resumable_source_manager.save_state(SquadcastResumeConfig(team_id=team_id, cursor=cursor))+++def _iter_incident_export_windows(+ client: SquadcastClient,+ config: SquadcastEndpointConfig,+ team_id: str,+ start_cursor: str | None,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ if start_cursor:+ window_start = _parse_datetime(start_cursor)+ elif db_incremental_field_last_value is not None:+ window_start = _parse_datetime(db_incremental_field_last_value)+ else:+ window_start = FULL_REFRESH_START++ now = datetime.now(UTC)+ while window_start < now:+ window_end = min(window_start + timedelta(days=INCIDENT_EXPORT_WINDOW_DAYS), now)+ assert config.team_param is not None+ data = client.get(+ config.path,+ {+ config.team_param: team_id,+ "type": "json",+ "start_time": _format_datetime(window_start),+ "end_time": _format_datetime(window_end),+ },+ )++ # The JSON export's envelope isn't documented; accept both a bare list and the+ # `{"data": [...]}` / `{"incidents": [...]}` wrappers used elsewhere in the API.+ if isinstance(data, list):+ rows = [row for row in data if isinstance(row, dict)]+ else:+ rows = _extract_rows(data, ("data",)) or _extract_rows(data, ("incidents",))++ if rows:+ yield _prepare_rows(rows, config, team_id)++ window_start = window_end+ if window_start < now:+ resumable_source_manager.save_state(+ SquadcastResumeConfig(team_id=team_id, cursor=_format_datetime(window_start))+ )+++def _get_postmortem_rows(+ client: SquadcastClient,+ config: SquadcastEndpointConfig,+ team_id: str,+ logger: FilteringBoundLogger,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ window_start = (+ _parse_datetime(db_incremental_field_last_value)+ if db_incremental_field_last_value is not None+ else FULL_REFRESH_START+ )+ assert config.team_param is not None+ data = client.get(+ config.path,+ {+ config.team_param: team_id,+ "fromDate": _format_datetime(window_start),+ "toDate": _format_datetime(datetime.now(UTC)),+ "limit": POSTMORTEM_LIMIT,+ },+ )++ rows: list[dict[str, Any]] = []+ total_count: Optional[int] = None+ for item in _extract_rows(data, ("data",)):+ rows.extend(row for row in item.get("result") or [] if isinstance(row, dict))+ for counter in item.get("total_count") or []:+ if isinstance(counter, dict) and counter.get("count") is not None:+ total_count = counter["count"]++ # The endpoint requires `limit` and has no offset param, so an unusually large backlog+ # can't be paged through — surface the truncation instead of hiding it.+ if total_count is not None and total_count > len(rows):+ logger.warning(+ f"Squadcast: postmortems for team {team_id} truncated ({len(rows)} of {total_count}); "+ f"the API exposes no pagination beyond limit={POSTMORTEM_LIMIT}"+ )++ if rows:+ yield _prepare_rows(rows, config, team_id)+++def _iter_team_rows(+ client: SquadcastClient,+ config: SquadcastEndpointConfig,+ team_id: str,+ start_cursor: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ if config.pagination == "offset":+ yield from _iter_offset_pages(client, config, team_id, start_cursor, resumable_source_manager)+ elif config.pagination == "cursor":+ yield from _iter_cursor_pages(client, config, team_id, start_cursor, resumable_source_manager)+ elif config.pagination == "incident_export":+ yield from _iter_incident_export_windows(+ client, config, team_id, start_cursor, resumable_source_manager, db_incremental_field_last_value+ )+ elif config.pagination == "postmortems":+ yield from _get_postmortem_rows(client, config, team_id, logger, db_incremental_field_last_value)+ else:+ assert config.team_param is not None+ data = client.get(config.path, {config.team_param: team_id})+ rows = _extract_rows(data, config.envelope)++ # See settings.py: escalation policies aren't paginated client-side, so check the+ # reported total for silent truncation.+ if isinstance(data, dict):+ total_count = data.get("meta", {}).get("total_count")+ if total_count is not None and total_count > len(rows):+ logger.warning(+ f"Squadcast: endpoint '{config.path}' for team {team_id} returned {len(rows)} "+ f"of {total_count} rows; results may be truncated"+ )++ if rows:+ yield _prepare_rows(rows, config, team_id)+++def get_rows(+ refresh_token: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SQUADCAST_ENDPOINTS[endpoint]+ client = SquadcastClient(refresh_token, region, logger)+ last_value = db_incremental_field_last_value if should_use_incremental_field else None++ if config.team_param is None:+ data = client.get(config.path)+ rows = _extract_rows(data, config.envelope)+ if rows:+ yield _prepare_rows(rows, config)+ return++ team_ids = [str(team["id"]) for team in _extract_rows(client.get("/v3/teams"), ("data",)) if team.get("id")]++ # Resolve the saved team-ID bookmark to the slice of teams still to process. If the+ # bookmarked team no longer exists, start over from the first team — merge dedupes the+ # re-pulled rows on the primary key. `resume_cursor` is consumed by the first team only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = team_ids+ resume_cursor: str | None = None+ if resume is not None and resume.team_id is not None and resume.team_id in team_ids:+ remaining = team_ids[team_ids.index(resume.team_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"Squadcast: resuming {endpoint} from team {resume.team_id}, cursor={resume_cursor}")++ for index, team_id in enumerate(remaining):+ start_cursor = resume_cursor+ resume_cursor = None # only the resumed-into team uses the saved cursor++ try:+ yield from _iter_team_rows(+ client, config, team_id, start_cursor, logger, resumable_source_manager, last_value+ )+ except requests.HTTPError as exc:+ # The connecting user's role may not grant access to every team. Skip teams we+ # can't read rather than failing the whole sync. Any other HTTP error re-raises.+ if exc.response is not None and exc.response.status_code in (403, 404):+ logger.warning(+ f"Squadcast: no access to team {team_id} for endpoint '{endpoint}' "+ f"(status={exc.response.status_code}), skipping"+ )+ else:+ raise++ # Advance the bookmark to the next team so a crash between teams resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(SquadcastResumeConfig(team_id=remaining[index + 1], cursor=None))+++def squadcast_source(+ refresh_token: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SquadcastResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SQUADCAST_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ refresh_token=refresh_token,+ region=region,+ 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_key],+ # Incremental endpoints fan out over teams, so rows are not globally ordered by the+ # incremental field; "desc" makes the pipeline persist the watermark only after the+ # whole job completes instead of checkpointing a possibly-unsafe per-batch maximum.+ sort_mode="desc" if config.incremental_fields else "asc",+ 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,+ )+++def validate_credentials(+ refresh_token: str, region: str | None, endpoint: Optional[str] = None+) -> tuple[bool, int, str | None]:+ """Exchange the refresh token, then probe a cheap list endpoint.++ Returns ``(ok, status_code, error_message)``. ``status_code`` is 0 on transport failure.+ The caller decides how to treat 403 (valid token, missing access for the probed endpoint).+ """+ auth_host, api_host = _hosts_for_region(region)+ # Same credential hardening as SquadcastClient: mask the refresh token, never follow+ # redirects with credentialed headers, and keep both the token exchange and the API probe+ # out of sample capture — the probe response body carries customer operational data.+ session = make_tracked_session(redact_values=(refresh_token,), allow_redirects=False, capture=False)+ auth_session = make_tracked_session(redact_values=(refresh_token,), allow_redirects=False, capture=False)++ try:+ auth_response = auth_session.get(+ f"{auth_host}/oauth/access-token",+ headers={"X-Refresh-Token": refresh_token},+ timeout=10,+ )+ except requests.exceptions.RequestException as e:+ return False, 0, str(e)++ if not auth_response.ok:+ if auth_response.status_code in (400, 401):+ return False, 401, "Invalid Squadcast refresh token"+ return False, auth_response.status_code, _error_message(auth_response)++ access_token = auth_response.json().get("data", {}).get("access_token")+ if not access_token:+ return False, 0, "Squadcast token exchange returned no access token"++ # Team-scoped endpoints require query params a probe can't guess, so probe /v3/teams for+ # them (the fan-out needs it anyway); org-level endpoints are probed directly.+ config = SQUADCAST_ENDPOINTS.get(endpoint) if endpoint else None+ probe_path = config.path if config is not None and config.team_param is None else "/v3/teams"++ try:+ response = session.get(+ f"{api_host}{probe_path}",+ headers={"Authorization": f"Bearer {access_token}"},+ timeout=10,+ )+ except requests.exceptions.RequestException as e:+ return False, 0, str(e)++ if response.status_code == 200:+ return True, 200, None+ if response.status_code == 401:+ return False, 401, "Invalid Squadcast refresh token"+ if response.status_code == 403:+ return False, 403, "Your Squadcast account does not have access to this resource"++ return False, response.status_code, _error_message(response)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast.pynew file mode 100644index 000000000000..8f9355d2f8fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast.py@@ -0,0 +1,589 @@+import time+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.settings import SQUADCAST_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.squadcast import (+ FULL_REFRESH_START,+ PAGE_SIZE,+ SquadcastAuthError,+ SquadcastResumeConfig,+ get_rows,+ squadcast_source,+ validate_credentials,+)++SQUADCAST_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.squadcast"++US_AUTH_URL = "https://auth.squadcast.com/oauth/access-token"+US_API = "https://api.squadcast.com"+++class FakeResumableManager:+ """In-memory stand-in for ResumableSourceManager that records saved state."""++ def __init__(self, resume_state: Optional[SquadcastResumeConfig] = None) -> None:+ self._resume_state = resume_state+ self.saved_states: list[SquadcastResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume_state is not None++ def load_state(self) -> Optional[SquadcastResumeConfig]:+ return self._resume_state++ def save_state(self, data: SquadcastResumeConfig) -> None:+ self.saved_states.append(data)+++def _mock_response(status_code: int = 200, body: Any = None, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.text = text+ response.json.return_value = body if body is not None else {}+ if not response.ok:+ error_response = requests.Response()+ error_response.status_code = status_code+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: error for url: https://api.squadcast.com", response=error_response+ )+ return response+++def _auth_body(expires_in_seconds: float = 3600) -> dict[str, Any]:+ return {"data": {"access_token": "jwt_abc", "expires_at": time.time() + expires_in_seconds}}+++class FakeSession:+ """Dispatches session.get by URL so tests don't depend on exact request ordering."""++ def __init__(self, handler: Callable[[str, dict[str, str]], MagicMock]) -> None:+ self.handler = handler+ self.calls: list[tuple[str, dict[str, str]]] = []++ def get(self, url: str, headers: Optional[dict[str, str]] = None, timeout: Any = None) -> MagicMock:+ self.calls.append((url, headers or {}))+ return self.handler(url, headers or {})++ def calls_to(self, path: str) -> list[tuple[str, dict[str, str]]]:+ return [call for call in self.calls if urlparse(call[0]).path == path]+++def _params(url: str) -> dict[str, str]:+ return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}+++def _standard_handler(+ teams: list[dict[str, Any]],+ endpoint_responses: dict[str, Callable[[str], MagicMock]],+ auth_expires_in: float = 3600,+) -> Callable[[str, dict[str, str]], MagicMock]:+ def handler(url: str, headers: dict[str, str]) -> MagicMock:+ path = urlparse(url).path+ if path == "/oauth/access-token":+ return _mock_response(200, body=_auth_body(auth_expires_in))+ if path == "/v3/teams" and "/v3/teams" not in endpoint_responses:+ return _mock_response(200, body={"data": teams})+ if path in endpoint_responses:+ return endpoint_responses[path](url)+ raise AssertionError(f"unexpected request: {url}")++ return handler+++def _run_get_rows(+ session: FakeSession,+ endpoint: str,+ manager: Optional[FakeResumableManager] = None,+ **kwargs: Any,+) -> list[list[dict[str, Any]]]:+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ return list(+ get_rows(+ "refresh_tok",+ "us",+ endpoint,+ MagicMock(),+ manager if manager is not None else FakeResumableManager(), # type: ignore[arg-type]+ **kwargs,+ )+ )+++class TestAuth:+ def test_bearer_token_from_refresh_exchange_is_sent_to_api(self) -> None:+ session = FakeSession(+ _standard_handler(+ teams=[],+ endpoint_responses={"/v3/users": lambda url: _mock_response(200, body={"data": [{"id": "u1"}]})},+ )+ )+ batches = _run_get_rows(session, "users")++ assert batches == [[{"id": "u1"}]]+ auth_calls = session.calls_to("/oauth/access-token")+ assert auth_calls[0][1]["X-Refresh-Token"] == "refresh_tok"+ user_calls = session.calls_to("/v3/users")+ assert user_calls[0][1]["Authorization"] == "Bearer jwt_abc"++ def test_access_token_reused_while_valid(self) -> None:+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}, {"id": "t2"}],+ endpoint_responses={"/v3/services": lambda url: _mock_response(200, body={"data": [{"id": "s"}]})},+ )+ )+ _run_get_rows(session, "services")++ assert len(session.calls_to("/oauth/access-token")) == 1++ def test_expired_access_token_is_re_exchanged(self) -> None:+ # expires_at in the past forces a re-exchange before every API request.+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/services": lambda url: _mock_response(200, body={"data": [{"id": "s"}]})},+ auth_expires_in=-100,+ )+ )+ _run_get_rows(session, "services")++ # One exchange per API request (teams + services).+ assert len(session.calls_to("/oauth/access-token")) == 2++ def test_rejected_refresh_token_raises_auth_error(self) -> None:+ def handler(url: str, headers: dict[str, str]) -> MagicMock:+ return _mock_response(401, body={"meta": {"status": 401, "error_message": "invalid token"}})++ session = FakeSession(handler)+ with pytest.raises(SquadcastAuthError, match="Squadcast refresh token was rejected"):+ _run_get_rows(session, "users")++ def test_eu_region_uses_eu_hosts(self) -> None:+ urls: list[str] = []++ def handler(url: str, headers: dict[str, str]) -> MagicMock:+ urls.append(url)+ if "/oauth/access-token" in url:+ return _mock_response(200, body=_auth_body())+ return _mock_response(200, body={"data": []})++ session = FakeSession(handler)+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ list(get_rows("refresh_tok", "eu", "users", MagicMock(), FakeResumableManager())) # type: ignore[arg-type]++ assert urls[0].startswith("https://auth.eu.squadcast.com/")+ assert urls[1].startswith("https://api.eu.squadcast.com/")+++class TestCredentialHardening:+ # The refresh token is long-lived: dropping redaction would persist it via HTTP sample+ # capture, and following redirects would replay credentialed headers to the target.+ def _assert_hardened(self, factory: MagicMock) -> None:+ assert factory.call_args_list+ for call in factory.call_args_list:+ assert call.kwargs["redact_values"] == ("refresh_tok",)+ assert call.kwargs["allow_redirects"] is False+ # Every session is excluded from sample capture: the token exchange response carries+ # the minted tokens, and the API responses carry arbitrary customer-authored+ # operational data (incidents, postmortems, runbooks) the scrubbers can't recognise.+ assert call.kwargs["capture"] is False++ def test_sync_sessions_are_hardened(self) -> None:+ session = FakeSession(+ _standard_handler(+ teams=[],+ endpoint_responses={"/v3/users": lambda url: _mock_response(200, body={"data": [{"id": "u1"}]})},+ )+ )+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session) as factory:+ list(get_rows("refresh_tok", "us", "users", MagicMock(), FakeResumableManager())) # type: ignore[arg-type]++ self._assert_hardened(factory)++ def test_validate_credentials_sessions_are_hardened(self) -> None:+ session = FakeSession(+ lambda url, headers: (+ _mock_response(200, body=_auth_body())+ if "/oauth/access-token" in url+ else _mock_response(200, body={"data": []})+ )+ )+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session) as factory:+ validate_credentials("refresh_tok", "us")++ self._assert_hardened(factory)+++class TestTeamFanOut:+ def test_rows_fetched_per_team_and_stamped_with_team_id(self) -> None:+ def services(url: str) -> MagicMock:+ team = _params(url)["owner_id"]+ return _mock_response(200, body={"data": [{"id": f"svc_{team}"}]})++ session = FakeSession(+ _standard_handler(teams=[{"id": "t1"}, {"id": "t2"}], endpoint_responses={"/v3/services": services})+ )+ batches = _run_get_rows(session, "services")++ assert batches == [+ [{"id": "svc_t1", "team_id": "t1"}],+ [{"id": "svc_t2", "team_id": "t2"}],+ ]++ def test_services_api_key_never_reaches_yielded_rows(self) -> None:+ # The services payload carries the live key alert sources use to send events;+ # syncing it would expose it to anyone who can read the warehouse table.+ def services(url: str) -> MagicMock:+ return _mock_response(200, body={"data": [{"id": "svc_1", "api_key": "sq_live_key", "name": "checkout"}]})++ session = FakeSession(_standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/services": services}))+ batches = _run_get_rows(session, "services")++ assert batches == [[{"id": "svc_1", "name": "checkout", "team_id": "t1"}]]++ def test_team_without_access_is_skipped(self) -> None:+ def services(url: str) -> MagicMock:+ team = _params(url)["owner_id"]+ if team == "t2":+ return _mock_response(403, text="forbidden")+ return _mock_response(200, body={"data": [{"id": f"svc_{team}"}]})++ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}, {"id": "t2"}, {"id": "t3"}], endpoint_responses={"/v3/services": services}+ )+ )+ batches = _run_get_rows(session, "services")++ assert [batch[0]["id"] for batch in batches] == ["svc_t1", "svc_t3"]++ def test_non_permission_error_fails_the_sync(self) -> None:+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/services": lambda url: _mock_response(400, text="bad request")},+ )+ )+ with pytest.raises(requests.HTTPError):+ _run_get_rows(session, "services")++ def test_team_bookmark_saved_between_teams(self) -> None:+ manager = FakeResumableManager()+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}, {"id": "t2"}],+ endpoint_responses={"/v3/services": lambda url: _mock_response(200, body={"data": [{"id": "s"}]})},+ )+ )+ _run_get_rows(session, "services", manager)++ assert [(s.team_id, s.cursor) for s in manager.saved_states] == [("t2", None)]++ def test_resume_skips_completed_teams(self) -> None:+ manager = FakeResumableManager(resume_state=SquadcastResumeConfig(team_id="t2", cursor=None))++ def services(url: str) -> MagicMock:+ return _mock_response(200, body={"data": [{"id": f"svc_{_params(url)['owner_id']}"}]})++ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}, {"id": "t2"}, {"id": "t3"}], endpoint_responses={"/v3/services": services}+ )+ )+ batches = _run_get_rows(session, "services", manager)++ assert [batch[0]["id"] for batch in batches] == ["svc_t2", "svc_t3"]++ def test_resume_with_missing_team_starts_over(self) -> None:+ manager = FakeResumableManager(resume_state=SquadcastResumeConfig(team_id="gone", cursor=None))++ def services(url: str) -> MagicMock:+ return _mock_response(200, body={"data": [{"id": f"svc_{_params(url)['owner_id']}"}]})++ session = FakeSession(_standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/services": services}))+ batches = _run_get_rows(session, "services", manager)++ assert [batch[0]["id"] for batch in batches] == ["svc_t1"]+++class TestOffsetPagination:+ def test_paginates_slos_and_saves_state_after_yield(self) -> None:+ manager = FakeResumableManager()+ full_page = [{"id": i} for i in range(PAGE_SIZE)]++ def slos(url: str) -> MagicMock:+ offset = int(_params(url)["offset"])+ body = {"data": {"slos": full_page if offset == 0 else [{"id": "last"}]}}+ return _mock_response(200, body=body)++ session = FakeSession(_standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/slo": slos}))+ batches = _run_get_rows(session, "slos", manager)++ assert len(batches) == 2+ assert len(batches[0]) == PAGE_SIZE+ assert batches[1][0]["id"] == "last"+ assert [(s.team_id, s.cursor) for s in manager.saved_states] == [("t1", str(PAGE_SIZE))]++ def test_resumes_from_saved_offset(self) -> None:+ manager = FakeResumableManager(resume_state=SquadcastResumeConfig(team_id="t1", cursor=str(PAGE_SIZE)))++ def slos(url: str) -> MagicMock:+ assert _params(url)["offset"] == str(PAGE_SIZE)+ return _mock_response(200, body={"data": {"slos": [{"id": "x"}]}})++ session = FakeSession(_standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/slo": slos}))+ batches = _run_get_rows(session, "slos", manager)++ assert batches == [[{"id": "x", "team_id": "t1"}]]+++class TestCursorPagination:+ def test_follows_next_cursor_until_has_next_is_false(self) -> None:+ manager = FakeResumableManager()++ def schedules(url: str) -> MagicMock:+ params = _params(url)+ assert params["teamID"] == "t1"+ if "cursor" not in params:+ return _mock_response(+ 200,+ body={"data": [{"id": 1}], "pageInfo": {"hasNext": True, "nextCursor": "cur_2", "hasPrev": False}},+ )+ assert params["cursor"] == "cur_2"+ return _mock_response(200, body={"data": [{"id": 2}], "pageInfo": {"hasNext": False, "hasPrev": True}})++ session = FakeSession(_standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v4/schedules": schedules}))+ batches = _run_get_rows(session, "schedules", manager)++ assert [batch[0]["id"] for batch in batches] == [1, 2]+ assert [(s.team_id, s.cursor) for s in manager.saved_states] == [("t1", "cur_2")]+++class TestIncidentExport:+ def test_incremental_windows_start_at_last_value(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=2)++ def export(url: str) -> MagicMock:+ return _mock_response(200, body={"data": [{"id": "inc_1", "created_at": "2026-07-14T00:00:00Z"}]})++ session = FakeSession(+ _standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/incidents/export": export})+ )+ batches = _run_get_rows(+ session,+ "incidents",+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )++ assert batches == [[{"id": "inc_1", "created_at": "2026-07-14T00:00:00Z", "team_id": "t1"}]]+ export_calls = session.calls_to("/v3/incidents/export")+ assert len(export_calls) == 1+ params = _params(export_calls[0][0])+ assert params["type"] == "json"+ assert params["owner_id"] == "t1"+ assert params["start_time"] == last_value.strftime("%Y-%m-%dT%H:%M:%SZ")++ def test_full_refresh_starts_at_epoch_and_chunks_windows(self) -> None:+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/incidents/export": lambda url: _mock_response(200, body={"data": []})},+ )+ )+ _run_get_rows(session, "incidents")++ export_calls = session.calls_to("/v3/incidents/export")+ assert len(export_calls) > 1 # chunked into bounded windows, not one giant request+ first_params = _params(export_calls[0][0])+ assert first_params["start_time"] == FULL_REFRESH_START.strftime("%Y-%m-%dT%H:%M:%SZ")+ # Windows are contiguous: each start is the previous end.+ second_params = _params(export_calls[1][0])+ assert second_params["start_time"] == first_params["end_time"]++ def test_resume_cursor_overrides_window_start(self) -> None:+ manager = FakeResumableManager(resume_state=SquadcastResumeConfig(team_id="t1", cursor="2026-07-01T00:00:00Z"))+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/incidents/export": lambda url: _mock_response(200, body={"data": []})},+ )+ )+ _run_get_rows(session, "incidents", manager)++ first_params = _params(session.calls_to("/v3/incidents/export")[0][0])+ assert first_params["start_time"] == "2026-07-01T00:00:00Z"++ def test_bare_list_export_body_is_accepted(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=1)+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/incidents/export": lambda url: _mock_response(200, body=[{"id": "inc_1"}])},+ )+ )+ batches = _run_get_rows(+ session,+ "incidents",+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )++ assert batches == [[{"id": "inc_1", "team_id": "t1"}]]+++class TestPostmortems:+ def test_windows_from_last_value_and_extracts_result_rows(self) -> None:+ last_value = datetime(2026, 6, 1, tzinfo=UTC)++ def postmortems(url: str) -> MagicMock:+ params = _params(url)+ assert params["fromDate"] == "2026-06-01T00:00:00Z"+ assert params["owner_id"] == "t1"+ body = {"data": [{"result": [{"id": "pm_1"}], "total_count": [{"count": 1}]}]}+ return _mock_response(200, body=body)++ session = FakeSession(+ _standard_handler(teams=[{"id": "t1"}], endpoint_responses={"/v3/incidents/postmortem": postmortems})+ )+ batches = _run_get_rows(+ session,+ "postmortems",+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )++ assert batches == [[{"id": "pm_1", "team_id": "t1"}]]++ def test_truncation_is_logged(self) -> None:+ body = {"data": [{"result": [{"id": "pm_1"}], "total_count": [{"count": 50}]}]}+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/incidents/postmortem": lambda url: _mock_response(200, body=body)},+ )+ )+ logger = MagicMock()+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ list(get_rows("refresh_tok", "us", "postmortems", logger, FakeResumableManager())) # type: ignore[arg-type]++ assert logger.warning.called+ assert "truncated" in logger.warning.call_args.args[0]+++class TestEscalationPolicies:+ def test_reported_total_above_returned_rows_is_logged(self) -> None:+ body = {"data": [{"id": "ep_1"}], "meta": {"total_count": 10}}+ session = FakeSession(+ _standard_handler(+ teams=[{"id": "t1"}],+ endpoint_responses={"/v3/escalation-policies": lambda url: _mock_response(200, body=body)},+ )+ )+ logger = MagicMock()+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("refresh_tok", "us", "escalation_policies", logger, FakeResumableManager())) # type: ignore[arg-type]++ assert batches == [[{"id": "ep_1", "team_id": "t1"}]]+ assert logger.warning.called+++class TestSquadcastSourceResponse:+ def test_incidents_partitioned_on_created_at_with_desc_watermark(self) -> None:+ response = squadcast_source("tok", "us", "incidents", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "desc"++ def test_full_refresh_endpoint_has_no_partition_settings(self) -> None:+ response = squadcast_source("tok", "us", "users", MagicMock(), MagicMock())+ assert response.partition_keys is None+ assert response.partition_mode is None+ assert response.sort_mode == "asc"++ @pytest.mark.parametrize("endpoint", list(SQUADCAST_ENDPOINTS.keys()))+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:+ response = squadcast_source("tok", "us", endpoint, MagicMock(), MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == [SQUADCAST_ENDPOINTS[endpoint].primary_key]+ assert callable(response.items)+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "probe_status,expected_ok,expected_status",+ [+ (200, True, 200),+ (401, False, 401),+ (403, False, 403),+ (500, False, 500),+ ],+ )+ def test_probe_status_mapping(self, probe_status: int, expected_ok: bool, expected_status: int) -> None:+ def handler(url: str, headers: dict[str, str]) -> MagicMock:+ if "/oauth/access-token" in url:+ return _mock_response(200, body=_auth_body())+ return _mock_response(probe_status, body={"meta": {"status": probe_status, "error_message": "boom"}})++ session = FakeSession(handler)+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ ok, status, _error = validate_credentials("tok", "us")++ assert ok is expected_ok+ assert status == expected_status++ @pytest.mark.parametrize("auth_status", [400, 401])+ def test_rejected_refresh_token(self, auth_status: int) -> None:+ session = FakeSession(lambda url, headers: _mock_response(auth_status, text="nope"))+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ ok, status, error = validate_credentials("tok", "us")++ assert ok is False+ assert status == 401+ assert error == "Invalid Squadcast refresh token"++ def test_transport_failure_returns_zero_status(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("no network")+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ ok, status, error = validate_credentials("tok", "us")++ assert ok is False+ assert status == 0+ assert error == "no network"++ def test_org_level_schema_probes_its_own_path(self) -> None:+ session = FakeSession(+ lambda url, headers: (+ _mock_response(200, body=_auth_body())+ if "/oauth/access-token" in url+ else _mock_response(200, body={"data": []})+ )+ )+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ validate_credentials("tok", "us", endpoint="users")++ assert len(session.calls_to("/v3/users")) == 1++ def test_team_scoped_schema_probes_teams(self) -> None:+ session = FakeSession(+ lambda url, headers: (+ _mock_response(200, body=_auth_body())+ if "/oauth/access-token" in url+ else _mock_response(200, body={"data": []})+ )+ )+ with patch(f"{SQUADCAST_MODULE}.make_tracked_session", return_value=session):+ validate_credentials("tok", "us", endpoint="incidents")++ assert len(session.calls_to("/v3/teams")) == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast_source.pynew file mode 100644index 000000000000..20a7cd702259--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/tests/test_squadcast_source.py@@ -0,0 +1,151 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.source import SquadcastSource+from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.squadcast import SquadcastResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType++SQUADCAST_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.squadcast"+++class TestSquadcastSource:+ def setup_method(self) -> None:+ self.source = SquadcastSource()+ self.config = MagicMock(refresh_token="refresh_tok", region="us")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SQUADCAST++ def test_source_config_shape(self) -> None:+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ assert config.fields is not None+ token_field, region_field = config.fields+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.name == "refresh_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.name == "region"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ def test_get_schemas_lists_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_date_windowed_endpoints_support_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}++ for name in ("incidents", "postmortems"):+ assert schemas[name].supports_incremental is True, name+ assert schemas[name].incremental_fields[0]["field"] == "created_at"+ assert schemas[name].incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime++ for name in ENDPOINTS:+ if name in ("incidents", "postmortems"):+ continue+ assert schemas[name].supports_incremental is False, name+ assert schemas[name].incremental_fields == [], name++ def test_no_endpoint_supports_append(self) -> None:+ # Incidents and postmortems mutate after creation and window boundaries re-pull rows,+ # so only merge semantics are safe.+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert all(s.supports_append is False for s in schemas)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["incidents", "services"])+ assert {s.name for s in schemas} == {"incidents", "services"}++ @pytest.mark.parametrize(+ "pattern",+ [+ "Squadcast refresh token was rejected",+ "401 Client Error: Unauthorized for url: https://api.squadcast.com",+ "401 Client Error: Unauthorized for url: https://api.eu.squadcast.com",+ "403 Client Error: Forbidden for url: https://api.squadcast.com",+ ],+ )+ def test_non_retryable_errors_includes_pattern(self, pattern: str) -> None:+ assert pattern in self.source.get_non_retryable_errors()++ def test_validate_credentials_success(self) -> None:+ with patch(f"{SQUADCAST_MODULE}.source.validate_squadcast_credentials", return_value=(True, 200, None)):+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)++ def test_validate_credentials_invalid_token(self) -> None:+ with patch(+ f"{SQUADCAST_MODULE}.source.validate_squadcast_credentials",+ return_value=(False, 401, "Invalid Squadcast refresh token"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1)+ assert ok is False+ assert error == "Invalid Squadcast refresh token"++ def test_validate_credentials_accepts_403_at_source_create(self) -> None:+ # A valid token may only have access to a subset of resources; don't block connection.+ with patch(+ f"{SQUADCAST_MODULE}.source.validate_squadcast_credentials",+ return_value=(False, 403, "Your Squadcast account does not have access to this resource"),+ ):+ assert self.source.validate_credentials(self.config, team_id=1, schema_name=None) == (True, None)++ def test_validate_credentials_rejects_403_for_specific_schema(self) -> None:+ with patch(+ f"{SQUADCAST_MODULE}.source.validate_squadcast_credentials",+ return_value=(False, 403, "Your Squadcast account does not have access to this resource"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1, schema_name="incidents")+ assert ok is False+ assert error == "Your Squadcast account does not have access to this resource"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock(team_id=1, job_id="job_1", logger=MagicMock())+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SquadcastResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="incidents",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{SQUADCAST_MODULE}.source.squadcast_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["refresh_token"] == "refresh_tok"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "incidents"+ 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:00+00:00"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="services",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{SQUADCAST_MODULE}.source.squadcast_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None