: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 gusto source (#73791)
Tom Owers25844747ffc6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e8da7dbc6a1c..909964ad047a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -283,6 +283,7 @@ the row lists both.| groq | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ |+| gusto | HTTP | requests | ✅ || harvey | HTTP | requests | ✅ || hatchet | HTTP | requests | ✅ || healthchecks | HTTP | requests | ✅ |@@ -998,7 +999,6 @@ doesn't conflict with concurrent PRs.- guesty- gumloop- gumroad-- gusto- harness- harness_ccm- harness_seidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gusto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gusto.pyindex e1be7bdded5a..9fc04335501f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gusto.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gusto.py@@ -1,9 +1,14 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass GustoSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ refresh_token: str+ environment: Literal["production", "demo"] = config.value(default="production")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/canonical_descriptions.pynew file mode 100644index 000000000000..91c372705d5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/canonical_descriptions.py@@ -0,0 +1,182 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Gusto API reference (https://docs.gusto.com/embedded-payroll/reference).+# Columns prefixed with `_` are stamped on by the sync so fan-out rows stay unique table-wide.+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "companies": {+ "description": "A company the connected Gusto account administers, with its legal identity, entity type, and current onboarding status.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id",+ "columns": {+ "uuid": "The unique identifier of the company.",+ "name": "The legal name of the company.",+ "trade_name": "The company's doing-business-as (DBA) name.",+ "ein": "The company's Employer Identification Number.",+ "entity_type": "The company's legal entity type (e.g. C-Corporation, LLC).",+ "company_status": "Where the company sits in Gusto's onboarding funnel (e.g. Approved, Suspended).",+ "tier": "The Gusto subscription tier the company is on.",+ "is_suspended": "Whether the company is currently suspended from running payroll.",+ "primary_payroll_admin": "The company's primary payroll administrator.",+ "locations": "The company's work and mailing addresses.",+ "compensations": "The pay rates the company has configured for hourly and fixed compensation.",+ },+ },+ "locations": {+ "description": "A work or mailing address belonging to a company. Employees are assigned to a work location, which drives their state and local tax jurisdiction.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id-locations",+ "columns": {+ "uuid": "The unique identifier of the location.",+ "street_1": "First line of the street address.",+ "street_2": "Second line of the street address.",+ "city": "City of the address.",+ "state": "Two-letter state code of the address.",+ "zip": "Postal code of the address.",+ "country": "Country of the address.",+ "active": "Whether the location is currently in use.",+ "mailing_address": "Whether this is the company's mailing address.",+ "filing_address": "Whether this is the company's tax filing address.",+ "phone_number": "Phone number for the location.",+ "_company_uuid": "The company this location belongs to.",+ },+ },+ "employees": {+ "description": "An employee of a company, with their identity, work email, onboarding status, and current jobs.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id-employees",+ "columns": {+ "uuid": "The unique identifier of the employee.",+ "first_name": "The employee's first name.",+ "middle_initial": "The employee's middle initial.",+ "last_name": "The employee's last name.",+ "preferred_first_name": "The name the employee prefers to go by.",+ "email": "The employee's work email address.",+ "company_uuid": "The company the employee works for.",+ "manager_uuid": "The employee's manager.",+ "department": "The department the employee belongs to.",+ "date_of_birth": "The employee's date of birth.",+ "has_ssn": "Whether a Social Security number is on file for the employee.",+ "terminated": "Whether the employee has been terminated.",+ "two_percent_shareholder": "Whether the employee is a 2% shareholder of an S-corporation.",+ "onboarded": "Whether the employee has completed onboarding.",+ "onboarding_status": "Where the employee sits in the onboarding flow.",+ "jobs": "The employee's jobs, including titles and hire dates.",+ "eligible_paid_time_off": "The employee's paid time off policies and accrued balances.",+ "terminations": "The employee's termination records, if any.",+ "custom_fields": "Company-defined custom fields recorded against the employee.",+ "version": "Concurrency token for the employee record — changes on every update.",+ "_company_uuid": "The company this employee belongs to.",+ },+ },+ "jobs": {+ "description": "A job held by an employee: the title, hire date, work location, and whether it is the employee's primary job.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-employees-employee_id-jobs",+ "columns": {+ "uuid": "The unique identifier of the job.",+ "employee_uuid": "The employee who holds the job.",+ "title": "The job title.",+ "hire_date": "The date the employee started this job.",+ "location_uuid": "The work location assigned to the job.",+ "primary": "Whether this is the employee's primary job.",+ "rate": "The current pay rate for the job.",+ "payment_unit": "The unit the rate is paid in (e.g. Hour, Year, Paycheck).",+ "current_compensation_uuid": "The compensation record currently in effect for the job.",+ "compensations": "The history of compensations attached to the job.",+ "state_wc_covered": "Whether the job is covered by state workers' compensation.",+ "version": "Concurrency token for the job record — changes on every update.",+ "_company_uuid": "The company the employee holding this job belongs to.",+ "_employee_uuid": "The employee this job was fetched for.",+ },+ },+ "contractors": {+ "description": "A contractor engaged by a company, either an individual or a business, with their type and start date.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_uuid-contractors",+ "columns": {+ "uuid": "The unique identifier of the contractor.",+ "company_uuid": "The company that engaged the contractor.",+ "type": "Whether the contractor is an Individual or a Business.",+ "wage_type": "How the contractor is paid (Fixed or Hourly).",+ "is_active": "Whether the contractor is currently active.",+ "first_name": "First name, for individual contractors.",+ "last_name": "Last name, for individual contractors.",+ "business_name": "Business name, for business contractors.",+ "ein": "Employer Identification Number, for business contractors.",+ "email": "The contractor's email address.",+ "start_date": "The date the engagement started.",+ "hourly_rate": "The contractor's hourly rate, for hourly contractors.",+ "onboarded": "Whether the contractor has completed onboarding.",+ "version": "Concurrency token for the contractor record — changes on every update.",+ "_company_uuid": "The company this contractor belongs to.",+ },+ },+ "pay_schedules": {+ "description": "A pay schedule defining how often a company pays a group of employees, including the anchor pay period and check dates.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id-pay_schedules",+ "columns": {+ "uuid": "The unique identifier of the pay schedule.",+ "frequency": "How often payroll runs on this schedule (e.g. Every week, Twice per month).",+ "anchor_pay_date": "The check date of the first pay period on this schedule.",+ "anchor_end_of_pay_period": "The end date of the first pay period on this schedule.",+ "day_1": "First day of the month employees are paid, for semi-monthly schedules.",+ "day_2": "Second day of the month employees are paid, for semi-monthly schedules.",+ "name": "The name given to the pay schedule.",+ "auto_pilot": "Whether payrolls on this schedule run automatically.",+ "active": "Whether the pay schedule is currently in use.",+ "_company_uuid": "The company this pay schedule belongs to.",+ },+ },+ "payrolls": {+ "description": "A payroll run for a company, covering one pay period: its check date, processing state, and per-employee compensation totals.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id-payrolls",+ "columns": {+ "payroll_uuid": "The unique identifier of the payroll.",+ "company_uuid": "The company the payroll was run for.",+ "check_date": "The date employees are paid for this payroll. Used as the incremental cursor.",+ "processed": "Whether the payroll has been processed.",+ "processed_date": "The date the payroll was processed.",+ "payroll_deadline": "The deadline for submitting the payroll to Gusto.",+ "calculated_at": "When Gusto last calculated the payroll's totals.",+ "off_cycle": "Whether this is an off-cycle payroll.",+ "off_cycle_reason": "Why the off-cycle payroll was run, if applicable.",+ "external": "Whether the payroll was recorded from an external payroll provider.",+ "pay_period": "The pay period the payroll covers, including its start and end dates and pay schedule.",+ "totals": "Aggregate amounts for the payroll (gross pay, net pay, taxes, benefits, reimbursements).",+ "employee_compensations": "Per-employee gross and net pay, hours, taxes, benefits, and deductions.",+ "payroll_status_meta": "Cancellation and expected-debit metadata for the payroll.",+ "version": "Concurrency token for the payroll record — changes on every update.",+ "_company_uuid": "The company this payroll belongs to.",+ },+ },+ "pay_periods": {+ "description": "A pay period on one of a company's pay schedules, and whether a payroll has been run for it.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_id-pay_periods",+ "columns": {+ "start_date": "First day of the pay period.",+ "end_date": "Last day of the pay period. Used as the incremental cursor.",+ "pay_schedule_uuid": "The pay schedule this period belongs to.",+ "payroll": "The payroll run for this period, including whether it has been processed.",+ "eligible_employees": "The employees eligible to be paid in this period.",+ "_company_uuid": "The company this pay period belongs to.",+ },+ },+ "contractor_payments": {+ "description": "A single payment to a contractor, flattened out of Gusto's per-contractor payment grouping.",+ "docs_url": "https://docs.gusto.com/embedded-payroll/reference/get-v1-companies-company_uuid-contractor_payments",+ "columns": {+ "uuid": "The unique identifier of the contractor payment.",+ "contractor_uuid": "The contractor who was paid.",+ "date": "The check date of the payment. Used as the incremental cursor.",+ "wage": "The wage amount paid, for fixed-wage contractors.",+ "hours": "The number of hours paid, for hourly contractors.",+ "hourly_rate": "The hourly rate the payment was calculated at.",+ "wage_total": "Total wages paid, combining hourly and fixed amounts.",+ "bonus": "Bonus amount included in the payment.",+ "reimbursement": "Reimbursement amount included in the payment.",+ "wage_type": "Whether the payment was Fixed or Hourly.",+ "payment_method": "How the contractor was paid (e.g. Direct Deposit, Check).",+ "status": "The processing status of the payment.",+ "may_cancel": "Whether the payment can still be cancelled.",+ "_company_uuid": "The company that made this payment.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.pynew file mode 100644index 000000000000..de0e3cd8c019--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py@@ -0,0 +1,467 @@+import dataclasses+from collections.abc import Callable, 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 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.gusto.settings import (+ GUSTO_ENDPOINTS,+ GustoEndpointConfig,+)++# Gusto runs a separate demo environment with its own credentials; partner apps build against demo+# until Gusto approves them for production.+GUSTO_HOSTS = {+ "production": "https://api.gusto.com",+ "demo": "https://api.gusto-demo.com",+}+DEFAULT_ENVIRONMENT = "production"+# Dated API version pinned via the `X-Gusto-API-Version` header. Everything below is written+# against this contract; bumping it is a `warehouse-source-new-version` change.+GUSTO_API_VERSION = "2024-04-01"++REQUEST_TIMEOUT_SECONDS = 60+# Source creation runs this synchronously, so keep the credential probe snappy.+VALIDATE_TIMEOUT_SECONDS = 15+# Gusto's collections default to 25 rows per page and cap `per` at 100.+PAGE_SIZE = 100+# Guard against a malformed pagination header looping forever on a single company.+MAX_PAGES_PER_COMPANY = 2000+# Gusto (then ZenPayroll) ran its first payrolls in 2012, so nothing predates this window.+DEFAULT_WINDOW_START = "2011-01-01"+# Payrolls and pay periods are scheduled ahead of today, so the window has to reach forward.+FUTURE_WINDOW_DAYS = 365+# Rows for the date-windowed endpoints are buffered to sort them, then handed over in chunks.+WINDOW_CHUNK_SIZE = 1000+++class GustoResumeConfig:+ # Index into the ordered company list to restart at.+ company_index: int = 0+ # Next 1-indexed page to fetch within that company.+ next_page: int = 1+ # For endpoints fanned out over employees: index into that company's ordered employee list.+ employee_index: int = 0+++class GustoClient:+ """Bearer-auth client that mints its own short-lived access token.++ Gusto issues 2 hour access tokens from an authorization-code refresh token, so the token is+ minted at the start of a sync and re-minted once on a 401 in case a long sync outlives it.+ """++ def __init__(+ self,+ environment: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ api_version: str,+ logger: Optional[FilteringBoundLogger] = None,+ ) -> None:+ self._host = base_url(environment)+ self._client_id = client_id+ self._client_secret = client_secret+ self._refresh_token = refresh_token+ self._logger = logger+ self._token: Optional[str] = None+ self._session = make_tracked_session(+ headers={"Accept": "application/json", "X-Gusto-API-Version": api_version},+ redact_values=(client_secret, refresh_token),+ # Gusto responses carry HR/payroll PII (names, emails, DOBs, addresses, pay rates) that+ # the name-based scrubber can't reliably strip, so keep bodies out of HTTP sample capture.+ capture=False,+ )++ @property+ def logger(self) -> Optional[FilteringBoundLogger]:+ return self._logger++ def mint_token(self, timeout: int = REQUEST_TIMEOUT_SECONDS) -> str:+ response = self._session.post(+ f"{self._host}/oauth/token",+ data={+ "grant_type": "refresh_token",+ "refresh_token": self._refresh_token,+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ },+ timeout=timeout,+ )+ response.raise_for_status()+ token = response.json().get("access_token")+ if not token:+ raise ValueError("Gusto did not return an access token for the supplied refresh token")+ self._token = str(token)+ return self._token++ def request(self, path: str, params: Optional[dict[str, Any]] = None) -> requests.Response:+ url = f"{self._host}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"++ if self._token is None:+ self.mint_token()++ def _do() -> requests.Response:+ return self._session.get(+ url,+ headers={"Authorization": f"Bearer {self._token}"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ response = _do()+ # Access tokens last two hours; a long sync can outlive one, so re-mint once and retry.+ if response.status_code == 401:+ self.mint_token()+ response = _do()++ if not response.ok:+ if self._logger is not None:+ self._logger.error(f"Gusto API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response++ def get_json(self, path: str, params: Optional[dict[str, Any]] = None) -> tuple[Any, requests.Response]:+ response = self.request(path, params)+ return response.json(), response+++def base_url(environment: str) -> str:+ host = GUSTO_HOSTS.get(environment or DEFAULT_ENVIRONMENT)+ if host is None:+ raise ValueError(f"Invalid Gusto environment: {environment!r}. Expected one of {sorted(GUSTO_HOSTS)}.")+ return host+++def extract_next_page(response: requests.Response, page: int, item_count: int) -> Optional[int]:+ """Resolve the next 1-indexed page, or None when the collection is exhausted.++ Gusto's paginated collections return `X-Total-Pages` alongside `X-Page`. Some newer endpoints+ ship `X-Has-Next-Page` instead, and a few return neither — a short page then means the end.+ """+ has_next = response.headers.get("X-Has-Next-Page")+ if has_next is not None:+ return page + 1 if has_next.strip().lower() == "true" else None++ total_pages = response.headers.get("X-Total-Pages")+ if total_pages is not None:+ try:+ return page + 1 if page < int(total_pages) else None+ except ValueError:+ pass++ return page + 1 if item_count >= PAGE_SIZE else None+++def list_companies(client: GustoClient) -> list[dict[str, Any]]:+ """Companies the access token can reach, from the token holder's roles on `/v1/me`.++ Ordered by uuid so a resumed sync walks the same companies in the same order.+ """+ body, _ = client.get_json("/v1/me")+ if not isinstance(body, dict):+ raise ValueError(f"Gusto returned an unexpected /v1/me payload: {type(body).__name__}")++ companies: dict[str, dict[str, Any]] = {}+ roles = body.get("roles")+ if isinstance(roles, dict):+ for role in roles.values():+ if not isinstance(role, dict):+ continue+ for company in role.get("companies") or []:+ if not isinstance(company, dict):+ continue+ uuid = company.get("uuid") or company.get("id")+ if uuid is not None:+ companies[str(uuid)] = company++ return [companies[uuid] for uuid in sorted(companies)]+++def _window_bounds(db_incremental_field_last_value: Optional[Any]) -> tuple[str, str]:+ end = (datetime.now(UTC).date() + timedelta(days=FUTURE_WINDOW_DAYS)).isoformat()+ if db_incremental_field_last_value is None:+ return DEFAULT_WINDOW_START, end++ raw = db_incremental_field_last_value+ if isinstance(raw, datetime | date):+ return raw.isoformat()[:10], end+ return str(raw)[:10] or DEFAULT_WINDOW_START, end+++def _stamp_parents(rows: list[dict[str, Any]], parents: dict[str, str]) -> list[dict[str, Any]]:+ return [{**row, **parents} for row in rows]+++def _normalize_rows(config: GustoEndpointConfig, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ if config.name != "payrolls":+ return rows+ # Payroll objects key their identifier as `payroll_uuid`; mirror a bare `uuid` into it so the+ # declared primary key is always populated.+ return [+ row if "payroll_uuid" in row else {**row, "payroll_uuid": row.get("uuid")}+ for row in rows+ if isinstance(row, dict)+ ]+++def extract_rows(config: GustoEndpointConfig, body: Any) -> list[dict[str, Any]]:+ """Pull the row list out of a Gusto response body."""+ if isinstance(body, list):+ return _normalize_rows(config, [row for row in body if isinstance(row, dict)])++ if not isinstance(body, dict):+ return []++ if config.data_key is None:+ return _normalize_rows(config, [body])++ rows: list[dict[str, Any]] = []+ for group in body.get(config.data_key) or []:+ if not isinstance(group, dict):+ continue+ payments = group.get("payments")+ if isinstance(payments, list):+ # Contractor payments arrive grouped per contractor; the individual payments are the+ # rows, and only the group carries the contractor identifier.+ for payment in payments:+ if isinstance(payment, dict):+ rows.append({"contractor_uuid": group.get("contractor_uuid"), **payment})+ else:+ rows.append(group)++ return _normalize_rows(config, rows)+++def _paginate(+ client: GustoClient,+ config: GustoEndpointConfig,+ path: str,+ parents: dict[str, str],+ first_page: int,+ extra_params: Optional[dict[str, Any]] = None,+ on_page: Optional[Callable[[int], None]] = None,+) -> Iterator[list[dict[str, Any]]]:+ page = max(first_page, 1)+ for _ in range(MAX_PAGES_PER_COMPANY):+ params: dict[str, Any] = {"page": page, "per": PAGE_SIZE, **(extra_params or {})}+ body, response = client.get_json(path, params)+ rows = _stamp_parents(extract_rows(config, body), parents)+ if rows:+ yield rows++ next_page = extract_next_page(response, page, len(rows))+ if next_page is None or not rows:+ return++ page = next_page+ if on_page is not None:+ # Checkpoint AFTER yielding so a crash re-fetches the next page rather than skipping it.+ on_page(page)++ if client.logger is not None:+ client.logger.warning(f"Gusto page cap reached, stopping early. endpoint={config.name}, path={path}")+++def _company_employees(client: GustoClient, company_uuid: str) -> list[dict[str, Any]]:+ """Every employee of a company, ordered by uuid so fan-out resumes deterministically."""+ config = GUSTO_ENDPOINTS["employees"]+ path = config.path.format(company_uuid=company_uuid)+ employees: list[dict[str, Any]] = []+ for batch in _paginate(client, config, path, {}, first_page=1):+ employees.extend(batch)+ return sorted(employees, key=lambda employee: str(employee.get("uuid") or ""))+++def _windowed_rows(+ client: GustoClient,+ config: GustoEndpointConfig,+ companies: list[dict[str, Any]],+ start_date: str,+ end_date: str,+) -> Iterator[list[dict[str, Any]]]:+ rows: list[dict[str, Any]] = []+ window = {"start_date": start_date, "end_date": end_date}++ for company in companies:+ company_uuid = str(company.get("uuid") or company.get("id"))+ path = config.path.format(company_uuid=company_uuid)+ parents = {"_company_uuid": company_uuid}+ if config.paginated:+ for batch in _paginate(client, config, path, parents, first_page=1, extra_params=window):+ rows.extend(batch)+ else:+ body, _ = client.get_json(path, window)+ rows.extend(_stamp_parents(extract_rows(config, body), parents))++ # Gusto documents no ordering for these collections, and the pipeline advances the incremental+ # watermark after every batch — so sort on the cursor field to make `sort_mode="asc"` true.+ cursor = config.date_window_field or ""+ rows.sort(key=lambda row: str(row.get(cursor) or ""))++ for index in range(0, len(rows), WINDOW_CHUNK_SIZE):+ yield rows[index : index + WINDOW_CHUNK_SIZE]+++def get_rows(+ environment: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GustoResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GUSTO_ENDPOINTS[endpoint]+ client = GustoClient(environment, client_id, client_secret, refresh_token, api_version, logger)+ companies = list_companies(client)++ if config.date_window_field is not None:+ start_date, end_date = _window_bounds(db_incremental_field_last_value)+ # The whole window is buffered so it can be sorted, so there is no partial state worth+ # checkpointing here — a retry simply re-requests the window.+ yield from _windowed_rows(client, config, companies, start_date, end_date)+ return++ def checkpoint_page(company_index: int) -> Callable[[int], None]:+ def save(page: int) -> None:+ resumable_source_manager.save_state(GustoResumeConfig(company_index=company_index, next_page=page))++ return save++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ logger.debug(+ f"Gusto: resuming {endpoint} from company_index={resume.company_index}, "+ f"page={resume.next_page}, employee_index={resume.employee_index}"+ )++ for company_index, company in enumerate(companies):+ if resume is not None and company_index < resume.company_index:+ continue++ resuming_here = resume is not None and company_index == resume.company_index+ company_uuid = str(company.get("uuid") or company.get("id"))+ parents = {"_company_uuid": company_uuid}++ if endpoint == "companies":+ body, _ = client.get_json(config.path.format(company_uuid=company_uuid))+ rows = extract_rows(config, body)+ if rows:+ yield rows+ elif config.fans_out_over_employees:+ employees = _company_employees(client, company_uuid)+ first_employee = resume.employee_index if (resuming_here and resume is not None) else 0+ for employee_index, employee in enumerate(employees):+ if employee_index < first_employee:+ continue+ employee_uuid = str(employee.get("uuid") or "")+ body, _ = client.get_json(config.path.format(employee_uuid=employee_uuid))+ rows = _stamp_parents(extract_rows(config, body), {**parents, "_employee_uuid": employee_uuid})+ if rows:+ yield rows+ resumable_source_manager.save_state(+ GustoResumeConfig(company_index=company_index, employee_index=employee_index + 1)+ )+ else:+ first_page = resume.next_page if (resuming_here and resume is not None) else 1+ yield from _paginate(+ client,+ config,+ config.path.format(company_uuid=company_uuid),+ parents,+ first_page=first_page,+ on_page=checkpoint_page(company_index),+ )++ resumable_source_manager.save_state(GustoResumeConfig(company_index=company_index + 1))+++def gusto_source(+ environment: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GustoResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = GUSTO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ environment=environment,+ client_id=client_id,+ client_secret=client_secret,+ refresh_token=refresh_token,+ endpoint=endpoint,+ api_version=api_version,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )+++def validate_credentials(+ environment: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ api_version: str,+) -> tuple[bool, str | None]:+ """Mint an access token and read `/v1/me` to confirm the app credentials work."""+ try:+ client = GustoClient(environment, client_id, client_secret, refresh_token, api_version)+ except ValueError as e:+ return False, str(e)++ try:+ client.mint_token(timeout=VALIDATE_TIMEOUT_SECONDS)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status in (400, 401):+ return (+ False,+ "Gusto rejected these OAuth credentials. Check the client ID and secret, and note that Gusto "+ "rotates refresh tokens — a token that has already been exchanged no longer works.",+ )+ return False, f"Gusto returned HTTP {status} when requesting an access token"+ except ValueError as e:+ return False, str(e)+ except Exception:+ return False, "Could not connect to Gusto. Check the environment and try again."++ try:+ companies = list_companies(client)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status == 403:+ return False, "This Gusto token is not authorized to read company data. Reconnect with a payroll admin."+ return False, f"Gusto returned HTTP {status} when listing companies"+ except Exception:+ return False, "Could not read companies from Gusto"++ if not companies:+ return False, "This Gusto token has no companies attached to it. Authorize it against a company and retry."++ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/settings.pynew file mode 100644index 000000000000..5ef61992335b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/settings.py@@ -0,0 +1,118 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class GustoEndpointConfig:+ name: str+ # Path under the API host. `{company_uuid}` / `{employee_uuid}` are filled in per parent row.+ path: str+ primary_keys: list[str]+ # Company-scoped collections paginate with `page`/`per`; the derived `companies` table and the+ # per-employee child lists come back whole in a single response.+ paginated: bool = True+ # Money-movement endpoints take a `start_date`/`end_date` check-date window instead of being+ # walked in full. The value is the row field the window filters on, which is also the only+ # incremental cursor Gusto offers.+ date_window_field: str | None = None+ # Fan-out endpoints are fetched once per employee of each company.+ fans_out_over_employees: bool = False+ # Rows nested under this key in the response body (None = the body is the array itself).+ data_key: str | None = None+++# Gusto REST API (https://docs.gusto.com/embedded-payroll/reference). Every data endpoint is+# company-scoped, so each stream fans out over the companies the access token can reach+# (`GET /v1/me`). Only the money-movement endpoints accept a server-side date filter — the people+# and configuration tables have no updated-since parameter, so they are full refresh.+GUSTO_ENDPOINTS: dict[str, GustoEndpointConfig] = {+ "companies": GustoEndpointConfig(+ name="companies",+ path="/v1/companies/{company_uuid}",+ primary_keys=["uuid"],+ paginated=False,+ ),+ "locations": GustoEndpointConfig(+ name="locations",+ path="/v1/companies/{company_uuid}/locations",+ primary_keys=["uuid"],+ ),+ "employees": GustoEndpointConfig(+ name="employees",+ path="/v1/companies/{company_uuid}/employees",+ primary_keys=["uuid"],+ ),+ "jobs": GustoEndpointConfig(+ name="jobs",+ path="/v1/employees/{employee_uuid}/jobs",+ # Job uuids are not documented as globally unique, so the parent employee is part of the key.+ primary_keys=["_employee_uuid", "uuid"],+ paginated=False,+ fans_out_over_employees=True,+ ),+ "contractors": GustoEndpointConfig(+ name="contractors",+ path="/v1/companies/{company_uuid}/contractors",+ primary_keys=["uuid"],+ ),+ "pay_schedules": GustoEndpointConfig(+ name="pay_schedules",+ path="/v1/companies/{company_uuid}/pay_schedules",+ primary_keys=["uuid"],+ ),+ "payrolls": GustoEndpointConfig(+ name="payrolls",+ path="/v1/companies/{company_uuid}/payrolls",+ primary_keys=["_company_uuid", "payroll_uuid"],+ date_window_field="check_date",+ ),+ "pay_periods": GustoEndpointConfig(+ name="pay_periods",+ path="/v1/companies/{company_uuid}/pay_periods",+ # Pay periods carry no identifier of their own — the schedule plus the period bounds are+ # what makes a row unique within a company.+ primary_keys=["_company_uuid", "pay_schedule_uuid", "start_date", "end_date"],+ paginated=False,+ date_window_field="end_date",+ ),+ "contractor_payments": GustoEndpointConfig(+ name="contractor_payments",+ path="/v1/companies/{company_uuid}/contractor_payments",+ primary_keys=["_company_uuid", "uuid"],+ paginated=False,+ date_window_field="date",+ # The body groups payments per contractor: {"total": {...}, "contractor_payments": [+ # {"contractor_uuid": ..., "payments": [...]}]}.+ data_key="contractor_payments",+ ),+}++ENDPOINTS = tuple(GUSTO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "payrolls": [+ {+ "label": "check_date",+ "type": IncrementalFieldType.Date,+ "field": "check_date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ "pay_periods": [+ {+ "label": "end_date",+ "type": IncrementalFieldType.Date,+ "field": "end_date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ "contractor_payments": [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/source.pyindex 44a5478444a8..d6e1e98fdea4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/source.py@@ -1,19 +1,53 @@-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 (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gusto import GustoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto import (+ GUSTO_API_VERSION,+ GustoResumeConfig,+ gusto_source,+ validate_credentials as validate_gusto_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.settings import (+ ENDPOINTS,+ GUSTO_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GustoSource(SimpleSource[GustoSourceConfig]):+class GustoSource(ResumableSource[GustoSourceConfig, GustoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ supported_versions = (GUSTO_API_VERSION,)+ default_version = GUSTO_API_VERSION+ api_docs_url = "https://docs.gusto.com/embedded-payroll/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GUSTO@@ -24,7 +58,124 @@ class GustoSource(SimpleSource[GustoSourceConfig]):name=SchemaExternalDataSourceType.GUSTO,category=DataWarehouseSourceCategory.HR___RECRUITING,label="Gusto",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["payroll", "hris", "zenpayroll"],+ caption="""Pull your Gusto payroll and people data into the PostHog Data warehouse.++Company data is only readable through an authorization-code OAuth grant, so you bring your own Gusto developer app: register it in the [Gusto Developer Portal](https://dev.gusto.com), authorize it against your company as a payroll admin, then enter the app's client ID and secret along with the resulting refresh token.++Gusto rotates refresh tokens, so the token you paste here is exchanged on every sync. If syncs start failing with an authorization error, generate a fresh refresh token and update this connection.""",iconPath="/static/services/gusto.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/gusto",+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Demo", value="demo"),+ ],+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Both the production and demo hosts start `https://api.gusto`, so match on that prefix.+ return {+ "400 Client Error: Bad Request for url: https://api.gusto": "Gusto rejected these OAuth credentials. Refresh tokens rotate on use — generate a new one and reconnect.",+ "401 Client Error: Unauthorized for url: https://api.gusto": "Gusto authentication failed. Check your client ID and secret, then reconnect with a fresh refresh token.",+ "403 Client Error: Forbidden for url: https://api.gusto": "Your Gusto app is not authorized to read this data. Reconnect with a payroll admin authorization for the company.",+ }++ def get_schemas(+ self,+ config: GustoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Only the money-movement endpoints take a server-side date filter; the people and+ # configuration tables have no updated-since parameter, so they stay full refresh. Those+ # three are merge-only: a payroll is restated as it moves from calculated to processed, so+ # appending would leave duplicate rows behind.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=tuple(INCREMENTAL_FIELDS))++ def validate_credentials(+ self,+ config: GustoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ # One OAuth grant covers every company-scoped endpoint, so a single probe validates them all.+ return validate_gusto_credentials(+ environment=config.environment,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ api_version=self.resolve_api_version(api_version),+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GustoResumeConfig]:+ return ResumableSourceManager[GustoResumeConfig](inputs, GustoResumeConfig)++ def source_for_pipeline(+ self,+ config: GustoSourceConfig,+ resumable_source_manager: ResumableSourceManager[GustoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in GUSTO_ENDPOINTS:+ raise ValueError(f"Unknown Gusto schema '{inputs.schema_name}'")++ return gusto_source(+ environment=config.environment,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ endpoint=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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/gusto/tests/test_gusto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.pynew file mode 100644index 000000000000..be3e81abad88--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.py@@ -0,0 +1,601 @@+from collections.abc import Iterable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, cast+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto import (+ DEFAULT_WINDOW_START,+ GUSTO_API_VERSION,+ GustoClient,+ GustoResumeConfig,+ _window_bounds,+ base_url,+ extract_next_page,+ extract_rows,+ get_rows,+ gusto_source,+ list_companies,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.settings import ENDPOINTS, GUSTO_ENDPOINTS+++class _FakeResponse:+ def __init__(+ self,+ status_code: int = 200,+ body: Any = None,+ headers: Optional[dict[str, str]] = None,+ ) -> None:+ self.status_code = status_code+ self._body = body if body is not None else []+ self.headers = headers or {}+ self.text = ""++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._body++ def raise_for_status(self) -> None:+ if not self.ok:+ raise requests.HTTPError(f"{self.status_code} Client Error", response=cast(Any, self))+++class _FakeSession:+ """Routes requests by path, replaying a queued response list per path."""++ def __init__(+ self,+ routes: dict[str, list[_FakeResponse]],+ token_responses: Optional[list[_FakeResponse]] = None,+ ) -> None:+ self._routes = routes+ self._token_responses = token_responses or [_FakeResponse(200, {"access_token": "tok-1"})]+ self.get_urls: list[str] = []+ self.post_urls: list[str] = []++ def _next(self, queue: list[_FakeResponse]) -> _FakeResponse:+ return queue.pop(0) if len(queue) > 1 else queue[0]++ def get(self, url: str, headers: Optional[dict[str, str]] = None, timeout: Optional[int] = None) -> _FakeResponse:+ self.get_urls.append(url)+ path = urlparse(url).path+ if path not in self._routes:+ raise AssertionError(f"unexpected Gusto request to {path}")+ return self._next(self._routes[path])++ def post(+ self,+ url: str,+ data: Optional[dict[str, Any]] = None,+ timeout: Optional[int] = None,+ ) -> _FakeResponse:+ self.post_urls.append(url)+ return self._next(self._token_responses)+++class _FakeResumableManager(ResumableSourceManager[GustoResumeConfig]):+ def __init__(self, state: Optional[GustoResumeConfig] = None) -> None:+ self._state = state+ self.saved: list[GustoResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> Optional[GustoResumeConfig]:+ return self._state++ def save_state(self, data: GustoResumeConfig) -> None:+ self.saved.append(data)+++def _me_body(company_uuids: list[str]) -> dict[str, Any]:+ return {+ "email": "[email protected]",+ "roles": {"payroll_admin": {"companies": [{"uuid": uuid, "name": uuid.upper()} for uuid in company_uuids]}},+ }+++def _run(+ endpoint: str,+ routes: dict[str, list[_FakeResponse]],+ manager: Optional[_FakeResumableManager] = None,+ db_incremental_field_last_value: Any = None,+) -> tuple[list[list[dict[str, Any]]], _FakeSession, _FakeResumableManager]:+ session = _FakeSession(routes)+ resume_manager = manager or _FakeResumableManager()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session",+ return_value=session,+ ):+ batches = list(+ get_rows(+ environment="production",+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ endpoint=endpoint,+ api_version=GUSTO_API_VERSION,+ logger=MagicMock(),+ resumable_source_manager=resume_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return batches, session, resume_manager+++class TestBaseUrl:+ @parameterized.expand(+ [+ ("production", "production", "https://api.gusto.com"),+ ("demo", "demo", "https://api.gusto-demo.com"),+ ("blank_defaults_to_production", "", "https://api.gusto.com"),+ ]+ )+ def test_resolves_known_environments(self, _name: str, environment: str, expected: str) -> None:+ assert base_url(environment) == expected++ def test_rejects_unknown_environment(self) -> None:+ with pytest.raises(ValueError, match="Invalid Gusto environment"):+ base_url("sandbox")+++class TestExtractNextPage:+ @parameterized.expand(+ [+ ("has_next_page_true", {"X-Has-Next-Page": "true"}, 3, 1, 4),+ ("has_next_page_mixed_case", {"X-Has-Next-Page": "True"}, 1, 1, 2),+ ("has_next_page_false", {"X-Has-Next-Page": "false"}, 3, 100, None),+ ("total_pages_remaining", {"X-Total-Pages": "4"}, 2, 1, 3),+ ("total_pages_exhausted", {"X-Total-Pages": "2"}, 2, 100, None),+ ("garbage_total_pages_falls_back_to_short_page", {"X-Total-Pages": "many"}, 1, 3, None),+ ("no_headers_full_page", {}, 1, 100, 2),+ ("no_headers_short_page", {}, 1, 7, None),+ ]+ )+ def test_next_page(+ self, _name: str, headers: dict[str, str], page: int, item_count: int, expected: Optional[int]+ ) -> None:+ response = cast(Any, _FakeResponse(200, [], headers))+ assert extract_next_page(response, page, item_count) == expected++ def test_has_next_page_header_wins_over_total_pages(self) -> None:+ # Endpoints that ship both must not terminate early on a stale total-pages count.+ response = cast(Any, _FakeResponse(200, [], {"X-Has-Next-Page": "true", "X-Total-Pages": "1"}))+ assert extract_next_page(response, 1, 100) == 2+++class TestListCompanies:+ def _client(self, body: Any) -> GustoClient:+ session = _FakeSession({"/v1/me": [_FakeResponse(200, body)]})+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session",+ return_value=session,+ ):+ return GustoClient("production", "cid", "secret", "refresh", GUSTO_API_VERSION)++ def test_returns_companies_sorted_by_uuid(self) -> None:+ client = self._client(_me_body(["c-zeta", "c-alpha"]))+ assert [company["uuid"] for company in list_companies(client)] == ["c-alpha", "c-zeta"]++ def test_dedupes_companies_shared_across_roles(self) -> None:+ body = {+ "roles": {+ "payroll_admin": {"companies": [{"uuid": "c-1"}]},+ "manager": {"companies": [{"uuid": "c-1"}, {"uuid": "c-2"}]},+ }+ }+ client = self._client(body)+ assert [company["uuid"] for company in list_companies(client)] == ["c-1", "c-2"]++ @parameterized.expand(+ [+ ("no_roles", {"email": "[email protected]"}),+ ("empty_role", {"roles": {"payroll_admin": {"companies": []}}}),+ ("non_dict_role", {"roles": {"payroll_admin": "nope"}}),+ ("company_without_identifier", {"roles": {"payroll_admin": {"companies": [{"name": "Acme"}]}}}),+ ]+ )+ def test_returns_empty_when_no_companies_are_reachable(self, _name: str, body: dict[str, Any]) -> None:+ assert list_companies(self._client(body)) == []++ def test_rejects_unexpected_payload(self) -> None:+ with pytest.raises(ValueError, match="unexpected /v1/me payload"):+ list_companies(self._client(["not", "a", "dict"]))+++class TestExtractRows:+ def test_bare_array_body(self) -> None:+ rows = extract_rows(GUSTO_ENDPOINTS["employees"], [{"uuid": "e-1"}, "junk", {"uuid": "e-2"}])+ assert rows == [{"uuid": "e-1"}, {"uuid": "e-2"}]++ def test_single_object_body_for_company_detail(self) -> None:+ assert extract_rows(GUSTO_ENDPOINTS["companies"], {"uuid": "c-1"}) == [{"uuid": "c-1"}]++ def test_contractor_payments_are_flattened_out_of_their_contractor_group(self) -> None:+ body = {+ "total": {"reimbursements": "0.00"},+ "contractor_payments": [+ {+ "contractor_uuid": "k-1",+ "payments": [{"uuid": "p-1", "date": "2024-01-05"}, {"uuid": "p-2", "date": "2024-02-05"}],+ },+ {"contractor_uuid": "k-2", "payments": [{"uuid": "p-3", "date": "2024-01-05"}]},+ ],+ }+ rows = extract_rows(GUSTO_ENDPOINTS["contractor_payments"], body)+ assert [(row["uuid"], row["contractor_uuid"]) for row in rows] == [+ ("p-1", "k-1"),+ ("p-2", "k-1"),+ ("p-3", "k-2"),+ ]++ def test_contractor_payment_keeps_its_own_contractor_uuid(self) -> None:+ body = {+ "contractor_payments": [{"contractor_uuid": "k-1", "payments": [{"uuid": "p-1", "contractor_uuid": "k-9"}]}]+ }+ rows = extract_rows(GUSTO_ENDPOINTS["contractor_payments"], body)+ assert rows[0]["contractor_uuid"] == "k-9"++ def test_group_without_payments_is_kept_as_a_row(self) -> None:+ body = {"contractor_payments": [{"contractor_uuid": "k-1", "reimbursement_total": "10.00"}]}+ assert extract_rows(GUSTO_ENDPOINTS["contractor_payments"], body) == [+ {"contractor_uuid": "k-1", "reimbursement_total": "10.00"}+ ]++ @parameterized.expand(+ [+ ("mirrors_bare_uuid", {"uuid": "pr-1"}, "pr-1"),+ ("keeps_existing_payroll_uuid", {"uuid": "pr-1", "payroll_uuid": "pr-9"}, "pr-9"),+ ]+ )+ def test_payroll_primary_key_is_always_populated(self, _name: str, row: dict[str, Any], expected: str) -> None:+ # `payroll_uuid` is the declared primary key, so a response that only carries `uuid` must+ # still merge instead of seeding null-keyed duplicates.+ assert extract_rows(GUSTO_ENDPOINTS["payrolls"], [row])[0]["payroll_uuid"] == expected++ def test_non_mapping_body_yields_nothing(self) -> None:+ assert extract_rows(GUSTO_ENDPOINTS["employees"], "oops") == []+++class TestWindowBounds:+ def test_defaults_to_full_history_without_a_watermark(self) -> None:+ start, end = _window_bounds(None)+ assert start == DEFAULT_WINDOW_START+ # The window reaches forward because payrolls and pay periods are scheduled ahead of today.+ assert end > datetime.now(UTC).date().isoformat()++ @parameterized.expand(+ [+ ("date", date(2024, 5, 6), "2024-05-06"),+ ("datetime", datetime(2024, 5, 6, 12, 30, tzinfo=UTC), "2024-05-06"),+ ("iso_string", "2024-05-06T12:30:00+00:00", "2024-05-06"),+ ("plain_date_string", "2024-05-06", "2024-05-06"),+ ]+ )+ def test_watermark_becomes_the_window_start(self, _name: str, watermark: Any, expected: str) -> None:+ assert _window_bounds(watermark)[0] == expected+++class TestGustoClient:+ def _client(self, session: _FakeSession, environment: str = "production") -> GustoClient:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session",+ return_value=session,+ ):+ return GustoClient(environment, "cid", "secret", "refresh", GUSTO_API_VERSION, MagicMock())++ def test_session_pins_the_api_version_and_redacts_secrets(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session"+ ) as make_session:+ GustoClient("production", "cid", "secret", "refresh", GUSTO_API_VERSION)+ kwargs = make_session.call_args.kwargs+ assert kwargs["headers"]["X-Gusto-API-Version"] == GUSTO_API_VERSION+ assert set(kwargs["redact_values"]) == {"secret", "refresh"}+ # Payroll PII must never reach HTTP sample capture.+ assert kwargs["capture"] is False++ def test_mints_a_token_before_the_first_request(self) -> None:+ session = _FakeSession({"/v1/me": [_FakeResponse(200, {"roles": {}})]})+ client = self._client(session)+ client.request("/v1/me")+ assert session.post_urls == ["https://api.gusto.com/oauth/token"]++ def test_remints_once_when_the_token_expires_mid_sync(self) -> None:+ session = _FakeSession(+ {"/v1/me": [_FakeResponse(401), _FakeResponse(200, {"roles": {}})]},+ token_responses=[+ _FakeResponse(200, {"access_token": "tok-1"}),+ _FakeResponse(200, {"access_token": "tok-2"}),+ ],+ )+ client = self._client(session)+ response = client.request("/v1/me")+ assert response.status_code == 200+ assert len(session.post_urls) == 2++ def test_persistent_401_is_raised_rather_than_reminted_forever(self) -> None:+ session = _FakeSession({"/v1/me": [_FakeResponse(401)]})+ client = self._client(session)+ with pytest.raises(requests.HTTPError):+ client.request("/v1/me")+ assert len(session.post_urls) == 2++ @parameterized.expand([("forbidden", 403), ("not_found", 404), ("server_error", 500)])+ def test_error_statuses_raise(self, _name: str, status: int) -> None:+ session = _FakeSession({"/v1/me": [_FakeResponse(status)]})+ with pytest.raises(requests.HTTPError):+ self._client(session).request("/v1/me")++ def test_missing_access_token_is_an_explicit_failure(self) -> None:+ session = _FakeSession({"/v1/me": [_FakeResponse(200, {})]}, token_responses=[_FakeResponse(200, {})])+ with pytest.raises(ValueError, match="did not return an access token"):+ self._client(session).mint_token()++ def test_demo_environment_targets_the_demo_host(self) -> None:+ session = _FakeSession({"/v1/me": [_FakeResponse(200, {"roles": {}})]})+ client = self._client(session, environment="demo")+ client.request("/v1/me")+ assert session.get_urls == ["https://api.gusto-demo.com/v1/me"]+++class TestGetRowsPaginated:+ def test_walks_every_company_and_stamps_the_parent(self) -> None:+ routes = {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1", "c-2"]))],+ "/v1/companies/c-1/locations": [+ _FakeResponse(200, [{"uuid": "l-1"}], {"X-Total-Pages": "2"}),+ _FakeResponse(200, [{"uuid": "l-2"}], {"X-Total-Pages": "2"}),+ ],+ "/v1/companies/c-2/locations": [_FakeResponse(200, [{"uuid": "l-3"}], {"X-Total-Pages": "1"})],+ }+ batches, _, manager = _run("locations", routes)++ assert [[row["uuid"] for row in batch] for batch in batches] == [["l-1"], ["l-2"], ["l-3"]]+ assert [row["_company_uuid"] for batch in batches for row in batch] == ["c-1", "c-1", "c-2"]+ # Page state is checkpointed mid-company, and each finished company advances the index.+ assert GustoResumeConfig(company_index=0, next_page=2) in manager.saved+ assert manager.saved[-1] == GustoResumeConfig(company_index=2)++ def test_resumes_at_the_saved_company_and_page(self) -> None:+ routes = {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1", "c-2"]))],+ "/v1/companies/c-2/locations": [_FakeResponse(200, [{"uuid": "l-9"}], {"X-Total-Pages": "3"})],+ }+ # c-1 is absent from the routes on purpose: resuming must not re-request it.+ batches, session, _ = _run(+ "locations", routes, manager=_FakeResumableManager(GustoResumeConfig(company_index=1, next_page=3))+ )++ assert [row["uuid"] for batch in batches for row in batch] == ["l-9"]+ assert parse_qs(urlparse(session.get_urls[-1]).query)["page"] == ["3"]++ def test_stops_on_an_empty_page(self) -> None:+ routes = {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1"]))],+ "/v1/companies/c-1/employees": [+ _FakeResponse(200, [{"uuid": "e-1"}], {"X-Has-Next-Page": "true"}),+ _FakeResponse(200, [], {"X-Has-Next-Page": "true"}),+ ],+ }+ batches, _, _ = _run("employees", routes)+ assert [row["uuid"] for batch in batches for row in batch] == ["e-1"]+++class TestGetRowsCompanies:+ def test_yields_the_full_company_detail_per_company(self) -> None:+ routes = {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1", "c-2"]))],+ "/v1/companies/c-1": [_FakeResponse(200, {"uuid": "c-1", "name": "Acme"})],+ "/v1/companies/c-2": [_FakeResponse(200, {"uuid": "c-2", "name": "Globex"})],+ }+ batches, _, _ = _run("companies", routes)+ assert [row["name"] for batch in batches for row in batch] == ["Acme", "Globex"]+++class TestGetRowsFanOut:+ def _routes(self) -> dict[str, list[_FakeResponse]]:+ return {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1"]))],+ "/v1/companies/c-1/employees": [+ _FakeResponse(200, [{"uuid": "e-2"}, {"uuid": "e-1"}], {"X-Total-Pages": "1"})+ ],+ "/v1/employees/e-1/jobs": [_FakeResponse(200, [{"uuid": "j-1", "title": "Engineer"}])],+ "/v1/employees/e-2/jobs": [_FakeResponse(200, [{"uuid": "j-1", "title": "Designer"}])],+ }++ def test_jobs_carry_both_parent_identifiers(self) -> None:+ batches, _, _ = _run("jobs", self._routes())+ rows = [row for batch in batches for row in batch]+ # Employees are walked in uuid order, and the same job uuid under two employees stays+ # distinct because the parent employee is part of the primary key.+ assert [(row["_employee_uuid"], row["uuid"], row["title"]) for row in rows] == [+ ("e-1", "j-1", "Engineer"),+ ("e-2", "j-1", "Designer"),+ ]+ assert {row["_company_uuid"] for row in rows} == {"c-1"}++ def test_checkpoints_after_each_employee(self) -> None:+ _, _, manager = _run("jobs", self._routes())+ assert manager.saved[:2] == [+ GustoResumeConfig(company_index=0, employee_index=1),+ GustoResumeConfig(company_index=0, employee_index=2),+ ]++ def test_resumes_partway_through_a_company_employee_list(self) -> None:+ routes = self._routes()+ del routes["/v1/employees/e-1/jobs"]+ batches, _, _ = _run(+ "jobs", routes, manager=_FakeResumableManager(GustoResumeConfig(company_index=0, employee_index=1))+ )+ assert [row["_employee_uuid"] for batch in batches for row in batch] == ["e-2"]+++class TestGetRowsWindowed:+ def _payroll_routes(self) -> dict[str, list[_FakeResponse]]:+ return {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1", "c-2"]))],+ "/v1/companies/c-1/payrolls": [+ _FakeResponse(200, [{"uuid": "pr-3", "check_date": "2024-03-15"}], {"X-Total-Pages": "1"})+ ],+ "/v1/companies/c-2/payrolls": [+ _FakeResponse(+ 200,+ [+ {"payroll_uuid": "pr-2", "check_date": "2024-02-15"},+ {"payroll_uuid": "pr-1", "check_date": "2024-01-15"},+ ],+ {"X-Total-Pages": "1"},+ )+ ],+ }++ def test_rows_are_sorted_ascending_across_companies(self) -> None:+ # `sort_mode="asc"` promises the pipeline an ascending cursor, and Gusto documents no+ # ordering — so the source has to establish it.+ batches, _, _ = _run("payrolls", self._payroll_routes())+ rows = [row for batch in batches for row in batch]+ assert [row["check_date"] for row in rows] == ["2024-01-15", "2024-02-15", "2024-03-15"]+ assert [row["payroll_uuid"] for row in rows] == ["pr-1", "pr-2", "pr-3"]++ def test_watermark_becomes_the_start_date_filter(self) -> None:+ _, session, _ = _run("payrolls", self._payroll_routes(), db_incremental_field_last_value=date(2024, 2, 1))+ query = parse_qs(urlparse(session.get_urls[1]).query)+ assert query["start_date"] == ["2024-02-01"]+ assert query["end_date"][0] > datetime.now(UTC).date().isoformat()++ def test_first_sync_requests_the_full_history_window(self) -> None:+ _, session, _ = _run("payrolls", self._payroll_routes())+ assert parse_qs(urlparse(session.get_urls[1]).query)["start_date"] == [DEFAULT_WINDOW_START]++ def test_windowed_endpoints_do_not_checkpoint(self) -> None:+ # The whole window is buffered so it can be sorted; there is no partial position to resume.+ _, _, manager = _run("payrolls", self._payroll_routes())+ assert manager.saved == []++ def test_unpaginated_windowed_endpoint_flattens_and_sorts(self) -> None:+ routes = {+ "/v1/me": [_FakeResponse(200, _me_body(["c-1"]))],+ "/v1/companies/c-1/contractor_payments": [+ _FakeResponse(+ 200,+ {+ "contractor_payments": [+ {+ "contractor_uuid": "k-1",+ "payments": [+ {"uuid": "p-2", "date": "2024-06-01"},+ {"uuid": "p-1", "date": "2024-01-01"},+ ],+ }+ ]+ },+ )+ ],+ }+ batches, _, _ = _run("contractor_payments", routes)+ rows = [row for batch in batches for row in batch]+ assert [row["uuid"] for row in rows] == ["p-1", "p-2"]+ assert {row["_company_uuid"] for row in rows} == {"c-1"}+++class TestGustoSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_primary_keys_match_the_endpoint_catalog(self, endpoint: str) -> None:+ response = gusto_source(+ environment="production",+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ endpoint=endpoint,+ api_version=GUSTO_API_VERSION,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == GUSTO_ENDPOINTS[endpoint].primary_keys+ assert response.sort_mode == "asc"++ @parameterized.expand([("jobs",), ("contractor_payments",), ("pay_periods",)])+ def test_fan_out_and_keyless_tables_include_their_parent_in_the_key(self, endpoint: str) -> None:+ # Child rows from every parent land in one table, so a per-parent identifier alone would+ # collide and make each merge multi-match.+ assert any(key.startswith("_") for key in GUSTO_ENDPOINTS[endpoint].primary_keys)++ def test_items_are_lazy(self) -> None:+ response = gusto_source(+ environment="production",+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ endpoint="employees",+ api_version=GUSTO_API_VERSION,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(),+ )+ # Building the response must not touch the network — only iterating does.+ items = cast(Iterable[Any], response.items())+ assert isinstance(items, Iterator)+++class TestValidateCredentials:+ def _validate(+ self,+ routes: dict[str, list[_FakeResponse]],+ token_responses: Optional[list[_FakeResponse]] = None,+ ) -> tuple[bool, Optional[str]]:+ session = _FakeSession(routes, token_responses=token_responses)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session",+ return_value=session,+ ):+ return validate_credentials("production", "cid", "secret", "refresh", GUSTO_API_VERSION)++ def test_accepts_credentials_that_reach_a_company(self) -> None:+ assert self._validate({"/v1/me": [_FakeResponse(200, _me_body(["c-1"]))]}) == (True, None)++ @parameterized.expand([("bad_request", 400), ("unauthorized", 401)])+ def test_rejected_token_exchange_explains_rotation(self, _name: str, status: int) -> None:+ ok, message = self._validate({"/v1/me": []}, token_responses=[_FakeResponse(status)])+ assert ok is False+ assert message is not None and "rotates refresh tokens" in message++ def test_other_token_errors_report_the_status(self) -> None:+ ok, message = self._validate({"/v1/me": []}, token_responses=[_FakeResponse(500)])+ assert (ok, message) == (False, "Gusto returned HTTP 500 when requesting an access token")++ def test_forbidden_company_read_asks_for_a_payroll_admin(self) -> None:+ ok, message = self._validate({"/v1/me": [_FakeResponse(403)]})+ assert ok is False+ assert message is not None and "payroll admin" in message++ def test_token_without_companies_is_rejected(self) -> None:+ ok, message = self._validate({"/v1/me": [_FakeResponse(200, {"roles": {}})]})+ assert ok is False+ assert message is not None and "no companies" in message++ def test_invalid_environment_is_reported(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto.make_tracked_session",+ return_value=_FakeSession({}),+ ):+ ok, message = validate_credentials("sandbox", "cid", "secret", "refresh", GUSTO_API_VERSION)+ assert ok is False+ assert message is not None and "Invalid Gusto environment" in message+++class TestWindowReach:+ def test_future_window_covers_scheduled_pay_periods(self) -> None:+ _, end = _window_bounds(None)+ assert date.fromisoformat(end) > datetime.now(UTC).date() + timedelta(days=180)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto_source.pynew file mode 100644index 000000000000..929008faa6ae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto_source.py@@ -0,0 +1,221 @@+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized++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.generated_configs.gusto import GustoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.gusto import (+ GUSTO_API_VERSION,+ GustoResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.settings import (+ ENDPOINTS,+ GUSTO_ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.source import GustoSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"payrolls", "pay_periods", "contractor_payments"}+++class TestGustoSource:+ def setup_method(self) -> None:+ self.source = GustoSource()+ self.team_id = 123+ self.config = GustoSourceConfig(+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ environment="production",+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.GUSTO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Gusto"+ assert config.label == "Gusto"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/gusto"+ assert config.iconPath == "/static/services/gusto.png"++ def test_source_is_visible_to_users(self) -> None:+ # A truthy `unreleasedSource` hides the connector from the wizard entirely.+ assert not self.source.get_source_config.unreleasedSource++ def test_config_fields(self) -> None:+ fields = self.source.get_source_config.fields+ assert [f.name for f in fields] == ["environment", "client_id", "client_secret", "refresh_token"]++ @parameterized.expand([("client_secret",), ("refresh_token",)])+ def test_oauth_secrets_are_password_fields(self, name: str) -> None:+ field = next(+ f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig) and f.name == name+ )+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_environment_offers_production_and_demo(self) -> None:+ # Gusto partners build against the demo host until their app is approved for production.+ field = next(f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldSelectConfig))+ assert {option.value for option in field.options} == {"production", "demo"}+ assert field.defaultValue == "production"++ def test_api_version_is_pinned_to_what_the_client_sends(self) -> None:+ assert self.source.supported_versions == (GUSTO_API_VERSION,)+ assert self.source.default_version == GUSTO_API_VERSION+ assert self.source.api_docs_url.startswith("https://")++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_the_endpoint_catalog(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_only_date_filtered_endpoints_are_incremental(self, endpoint: str) -> None:+ # Gusto only filters server-side on money-movement check dates; everything else would have+ # to re-walk every page anyway, so it stays full refresh.+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is (endpoint in INCREMENTAL_ENDPOINTS)+ # Rows are restated in place (a payroll moves from calculated to processed), so merge only.+ assert schema.supports_append is False++ @parameterized.expand(+ [+ ("payrolls", "check_date"),+ ("pay_periods", "end_date"),+ ("contractor_payments", "date"),+ ]+ )+ def test_incremental_cursor_matches_the_api_date_filter(self, endpoint: str, expected_field: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert [f["field"] for f in schema.incremental_fields] == [expected_field]+ assert GUSTO_ENDPOINTS[endpoint].date_window_field == expected_field++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["employees"])+ assert [schema.name for schema in schemas] == ["employees"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {table["name"] for table in tables} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)+ assert CANONICAL_DESCRIPTIONS is self.source.get_canonical_descriptions()++ @parameterized.expand([(endpoint,) for endpoint in INCREMENTAL_ENDPOINTS])+ def test_canonical_descriptions_document_the_cursor_column(self, endpoint: str) -> None:+ cursor = INCREMENTAL_FIELDS[endpoint][0]["field"]+ assert cursor in (CANONICAL_DESCRIPTIONS[endpoint].get("columns") or {})++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.gusto.com/oauth/token"),+ ("bad_request", "400 Client Error: Bad Request for url: https://api.gusto.com/oauth/token"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.gusto.com/v1/companies/c-1/payrolls"),+ ]+ )+ def test_auth_failures_are_non_retryable(self, _name: str, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.gusto.com/v1/me"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.gusto.com/v1/me"),+ ]+ )+ def test_transient_failures_stay_retryable(self, _name: str, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.source.validate_gusto_credentials"+ )+ def test_validate_credentials_delegates_the_oauth_app(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.kwargs == {+ "environment": "production",+ "client_id": "cid",+ "client_secret": "secret",+ "refresh_token": "refresh",+ "api_version": GUSTO_API_VERSION,+ }++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gusto.source.validate_gusto_credentials"+ )+ def test_validate_credentials_passes_the_failure_reason_through(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "nope")+ assert self.source.validate_credentials(self.config, self.team_id, schema_name="payrolls") == (False, "nope")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GustoResumeConfig++ def _inputs(self, **overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = "employees"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ inputs.api_version = None+ for key, value in overrides.items():+ setattr(inputs, key, value)+ return inputs++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gusto.source.gusto_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ manager = mock.MagicMock()+ self.source.source_for_pipeline(self.config, manager, self._inputs())++ kwargs = mock_source.call_args.kwargs+ assert kwargs["environment"] == "production"+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "secret"+ assert kwargs["refresh_token"] == "refresh"+ assert kwargs["endpoint"] == "employees"+ assert kwargs["api_version"] == GUSTO_API_VERSION+ assert kwargs["resumable_source_manager"] is manager++ @parameterized.expand(+ [+ ("incremental_run_passes_the_watermark", True, "2024-05-06"),+ ("full_refresh_ignores_a_stale_watermark", False, None),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gusto.source.gusto_source")+ def test_watermark_is_only_used_on_incremental_runs(+ self,+ _name: str,+ should_use_incremental_field: bool,+ expected: Any,+ mock_source: mock.MagicMock,+ ) -> None:+ inputs = self._inputs(+ schema_name="payrolls",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value="2024-05-06",+ )+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] == expected++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ with pytest.raises(ValueError, match="Unknown Gusto schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), self._inputs(schema_name="not_a_table"))