Skip to content

: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.

feat(data-warehouse): add Tally source (#77083)

Tom Owers74f25901a994
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index a3b6ca48c23d..b56f65fdb22e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -608,6 +608,7 @@ the row lists both.
| swarmia | HTTP | requests | ✅ |
| taboola | HTTP | requests | ✅ |
| tailscale | HTTP | requests | ✅ |
+| tally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| tavus | HTTP | requests | ✅ |
| tawk_to | HTTP | requests | ✅ |
| teachable | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1349,7 +1350,6 @@ doesn't conflict with concurrent PRs.
- systeme
- tackle_io
- talkdesk
-- tally
- teamup_fitness
- tebra
- telli
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tally.py
index c552daa36762..af92a2798842 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tally.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tally.py
@@ -1,9 +1,12 @@
# 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.config
class TallySourceConfig(config.Config):
- pass
+ api_key: str
+ submission_filter: Literal["completed", "all"] | None = config.value(default="completed")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/canonical_descriptions.py
new file mode 100644
index 000000000000..8b27aca1cd18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/canonical_descriptions.py
@@ -0,0 +1,91 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workspaces": {
+ "description": "A workspace groups forms and the members who can access them.",
+ "docs_url": "https://developers.tally.so/api-reference/endpoint/workspaces/list",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Name of the workspace.",
+ "index": "Position of the workspace in the account's workspace list.",
+ "members": "Users who belong to the workspace.",
+ "invites": "Pending invitations to join the workspace.",
+ "folders": "Folders used to organize the workspace's forms.",
+ "createdByUserId": "Identifier of the user who created the workspace.",
+ "createdAt": "When the workspace was created.",
+ "updatedAt": "When the workspace was last updated.",
+ },
+ },
+ "forms": {
+ "description": "A form or survey, including its publication status and submission count.",
+ "docs_url": "https://developers.tally.so/api-reference/endpoint/forms/list",
+ "columns": {
+ "id": "Unique identifier for the form.",
+ "name": "Name of the form.",
+ "workspaceId": "Identifier of the workspace the form belongs to.",
+ "status": "Publication status of the form: BLANK, DRAFT, PUBLISHED, or DELETED.",
+ "numberOfSubmissions": "Number of submissions the form has received.",
+ "isClosed": "Whether the form has stopped accepting submissions.",
+ "payments": "Payment amounts and currencies configured on the form.",
+ "createdAt": "When the form was created.",
+ "updatedAt": "When the form was last updated.",
+ },
+ },
+ "questions": {
+ "description": (
+ "A question in a form. Submission answers are keyed by question id, so this table is "
+ "what makes the submissions table readable."
+ ),
+ "docs_url": "https://developers.tally.so/api-reference/endpoint/forms/questions/list",
+ "columns": {
+ "id": "Unique identifier for the question within its form.",
+ "formId": "Identifier of the form the question belongs to.",
+ "type": "Block type of the question, such as INPUT_TEXT or MULTIPLE_CHOICE.",
+ "title": "Question text shown to respondents.",
+ "isTitleModifiedByUser": "Whether the question title was edited rather than left at its default.",
+ "isDeleted": "Whether the question has been removed from the form.",
+ "numberOfResponses": "Number of responses recorded for this question.",
+ "fields": "Individual input fields that make up the question block.",
+ "createdAt": "When the question was created.",
+ "updatedAt": "When the question was last updated.",
+ },
+ },
+ "submissions": {
+ "description": (
+ "A single submission of a form, with every answer nested under `responses`. Answers are "
+ "keyed by question id, which joins to the questions table."
+ ),
+ "docs_url": "https://developers.tally.so/api-reference/endpoint/forms/submissions/list",
+ "columns": {
+ "id": "Unique identifier for the submission within its form.",
+ "formId": "Identifier of the form that was submitted.",
+ "isCompleted": "Whether the respondent finished the form or left it partially filled in.",
+ "submittedAt": "When the submission was recorded.",
+ "previewUrl": "Link to a rendered preview of the submission.",
+ "pdfUrl": "Link to a PDF export of the submission.",
+ "responses": (
+ "The answers in this submission. Each carries the question id it answers, the raw "
+ "answer, a formatted answer, and the respondent and session identifiers."
+ ),
+ },
+ },
+ "webhooks": {
+ "description": "A webhook registered on a form to push form events to an external URL.",
+ "docs_url": "https://developers.tally.so/api-reference/endpoint/webhooks/get",
+ "columns": {
+ "id": "Unique identifier for the webhook.",
+ "formId": "Identifier of the form the webhook is registered on.",
+ "url": "Destination the webhook posts events to.",
+ "signingSecret": "Secret used to sign webhook payloads, if one was set.",
+ "httpHeaders": "Custom headers sent with each delivery.",
+ "eventTypes": "Events the webhook is subscribed to.",
+ "externalSubscriber": "Optional identifier of the system that registered the webhook.",
+ "isEnabled": "Whether the webhook is currently delivering events.",
+ "lastSyncedAt": "When the webhook last delivered successfully.",
+ "createdAt": "When the webhook was created.",
+ "updatedAt": "When the webhook was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/settings.py
new file mode 100644
index 000000000000..801f170d36bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/settings.py
@@ -0,0 +1,140 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Tally is a single-tenant API — no per-account subdomain.
+TALLY_BASE_URL = "https://api.tally.so"
+
+# The API is date-versioned. Without this header the response shape is governed by whatever version
+# the API key happened to be created against (the 2025-02-01 release turned /forms from a bare array
+# into a paginated envelope), so every request pins it explicitly.
+TALLY_VERSION_HEADER = "tally-version"
+TALLY_API_VERSION = "2025-02-01"
+
+# /forms and /forms/{formId}/submissions both cap `limit` at 500. Tally allows 100 requests per
+# minute and submissions are fetched once per form, so the largest page keeps the fan-out cheap.
+FORMS_PAGE_SIZE = 500
+SUBMISSIONS_PAGE_SIZE = 500
+# /webhooks caps `limit` at 100.
+WEBHOOKS_PAGE_SIZE = 100
+
+# `filter` values accepted by /forms/{formId}/submissions. Typed as literals so they stay
+# assignment-compatible with the generated config field.
+SUBMISSION_FILTER_COMPLETED: Literal["completed"] = "completed"
+SUBMISSION_FILTER_ALL: Literal["all"] = "all"
+
+
+@dataclass
+class TallyEndpointConfig:
+ name: str
+ path: str
+ # jsonpath to the row array. Tally wraps rows under a per-endpoint key rather than a shared one.
+ data_selector: str
+ # Read by the fan-out helper for the parent/child `limit`; ignored when `page_size_param` is None.
+ page_size: int = FORMS_PAGE_SIZE
+ # Query param carrying the page size, or None for endpoints that document no page-size param.
+ page_size_param: Optional[str] = "limit"
+ # False for endpoints that return the whole collection in one response.
+ paginated: bool = True
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation timestamp used to partition the Delta table — never a mutable field.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ fanout: Optional[DependentEndpointConfig] = None
+ # Response fields nulled out before rows are written — secret material we must never persist.
+ redact_fields: tuple[str, ...] = ()
+ # Whether responses may be retained as HTTP samples. False for endpoints whose bodies carry
+ # secrets the name-based sample scrubbers can't recognise.
+ capture_samples: bool = True
+
+
+def _forms_fanout(parent_params: Optional[dict[str, object]] = None) -> DependentEndpointConfig:
+ # Child rows already carry `formId`, but injecting the parent id guarantees the composite
+ # primary key's column exists even if a future response shape drops it.
+ return DependentEndpointConfig(
+ parent_name="forms",
+ resolve_param="formId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "formId"},
+ parent_params=dict(parent_params or {}),
+ )
+
+
+TALLY_ENDPOINTS: dict[str, TallyEndpointConfig] = {
+ "workspaces": TallyEndpointConfig(
+ name="workspaces",
+ path="/workspaces",
+ data_selector="items",
+ # /workspaces documents `page` only, so no page-size param is sent.
+ page_size_param=None,
+ partition_key="createdAt",
+ ),
+ "forms": TallyEndpointConfig(
+ name="forms",
+ path="/forms",
+ data_selector="items",
+ page_size=FORMS_PAGE_SIZE,
+ partition_key="createdAt",
+ ),
+ # One request per form. Questions are what make the submission `responses` readable — answers
+ # are keyed by question id, so without this table the submissions rows are opaque.
+ "questions": TallyEndpointConfig(
+ name="questions",
+ path="/forms/{formId}/questions",
+ data_selector="questions",
+ # The endpoint returns every question in one unpaginated response and documents no params.
+ page_size_param=None,
+ paginated=False,
+ # A question id is only unique within its form.
+ primary_keys=["formId", "id"],
+ partition_key="createdAt",
+ # The fan-out helper applies one page-size param to parent and child alike, and the child
+ # takes none — so the parent's page size is passed as an explicit parent param instead.
+ fanout=_forms_fanout(parent_params={"limit": FORMS_PAGE_SIZE}),
+ ),
+ # The main fact table: one row per submission, with its answers nested under `responses`.
+ "submissions": TallyEndpointConfig(
+ name="submissions",
+ path="/forms/{formId}/submissions",
+ data_selector="submissions",
+ page_size=SUBMISSIONS_PAGE_SIZE,
+ # Tally documents the submission id as the id of a submission within a form, so the parent
+ # form is part of the key — the table aggregates submissions across every form.
+ primary_keys=["formId", "id"],
+ partition_key="submittedAt",
+ incremental_fields=[incremental_field("submittedAt")],
+ default_incremental_field="submittedAt",
+ # Tally documents no sort order for submissions, and the table interleaves one form's
+ # history after another's, so the stream is not globally ascending. "desc" makes the
+ # pipeline hold the watermark until the whole sync finishes instead of advancing it
+ # per batch, which would strand the forms that had not been read yet.
+ sort_mode="desc",
+ fanout=_forms_fanout(),
+ ),
+ # Webhook configs carry the signing secret and any custom auth headers — credentials that would
+ # let anyone with warehouse read access forge signed deliveries or reuse embedded tokens. Null
+ # them before they land, and keep the raw responses out of HTTP sample capture entirely.
+ "webhooks": TallyEndpointConfig(
+ name="webhooks",
+ path="/webhooks",
+ data_selector="webhooks",
+ page_size=WEBHOOKS_PAGE_SIZE,
+ partition_key="createdAt",
+ redact_fields=("signingSecret", "httpHeaders"),
+ capture_samples=False,
+ ),
+}
+
+ENDPOINTS = tuple(TALLY_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TALLY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/source.py
index 7befc8c87481..553bf4af4127 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/source.py
@@ -1,19 +1,53 @@
-from typing import cast
+from typing import Optional, cast
from 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.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.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tally import TallySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SUBMISSION_FILTER_ALL,
+ SUBMISSION_FILTER_COMPLETED,
+ TALLY_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.tally import (
+ TallyResumeConfig,
+ tally_source,
+ validate_credentials as validate_tally_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TallySource(SimpleSource[TallySourceConfig]):
+class TallySource(ResumableSource[TallySourceConfig, TallyResumeConfig]):
+ # Tally versions its API by date. 2025-02-01 is the newest version the docs describe, and it is
+ # the shape this source is written against (paginated envelopes on the list endpoints).
+ supported_versions = (TALLY_API_VERSION,)
+ default_version = TALLY_API_VERSION
+ api_docs_url = "https://developers.tally.so/api-reference/versioning"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TALLY
@@ -24,7 +58,123 @@ class TallySource(SimpleSource[TallySourceConfig]):
name=SchemaExternalDataSourceType.TALLY,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Tally",
+ keywords=["forms", "surveys", "tally.so"],
iconPath="/static/services/tally.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/tally",
+ caption="""Enter a Tally API key to sync your workspaces, forms, questions, submissions, and webhooks.
+
+You can create an API key in your [Tally settings](https://tally.so/settings/api-keys). No extra scopes are needed.
+
+Submissions are fetched one form at a time and Tally allows 100 requests per minute, so the first sync of an account with many forms can take a while.""",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="tly-...",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="submission_filter",
+ label="Submissions to sync",
+ required=False,
+ defaultValue=SUBMISSION_FILTER_COMPLETED,
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Completed submissions only", value=SUBMISSION_FILTER_COMPLETED
+ ),
+ SourceFieldSelectConfigOption(
+ label="All submissions, including partial ones", value=SUBMISSION_FILTER_ALL
+ ),
+ ],
+ caption=(
+ "Completed submissions sync incrementally. Including partial ones syncs the whole "
+ "submissions table on every run, because a partial submission is still being filled "
+ "in and its submitted time is not a settled cursor. **To apply this change to an "
+ "existing source, use 'Delete table and resync' on the submissions table. 'Sync now' "
+ "alone won't backfill the submissions you're adding.**"
+ ),
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.tally.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.tally.so": "Your Tally API key is invalid or has been revoked. Create a new key in your Tally settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.tally.so": "Your Tally API key does not have access to this data. Reconnect with a key from an account that can see these forms.",
+ }
+
+ def get_schemas(
+ self,
+ config: TallySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ incremental_fields = dict(INCREMENTAL_FIELDS)
+ if (config.submission_filter or SUBMISSION_FILTER_COMPLETED) != SUBMISSION_FILTER_COMPLETED:
+ # A partial submission is still being filled in, so `submittedAt` is not a settled
+ # cursor for it. Including partials means full refresh only.
+ incremental_fields["submissions"] = []
+
+ # `submissions` is merge-only: `startDate` is inclusive, so an append sync would re-write
+ # the watermark's own rows as duplicates.
+ return build_endpoint_schemas(ENDPOINTS, incremental_fields, names, merge_only=("submissions",))
+
+ def validate_credentials(
+ self,
+ config: TallySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ ok, status = validate_tally_credentials(config.api_key, self.resolve_api_version(api_version))
+ if ok:
+ return True, None
+ if status == 401:
+ return False, "Invalid Tally API key"
+ if status == 403:
+ # The key works but can't see this data — reaching the API isn't the problem.
+ return (
+ False,
+ "Your Tally API key does not have access to this data. Reconnect with a key from an account that can see these forms.",
+ )
+ return False, "Could not reach the Tally API with this key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TallyResumeConfig]:
+ return ResumableSourceManager[TallyResumeConfig](inputs, TallyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TallySourceConfig,
+ resumable_source_manager: ResumableSourceManager[TallyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return tally_source(
+ api_key=config.api_key,
+ api_version=self.resolve_api_version(inputs.api_version),
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ submission_filter=config.submission_filter or SUBMISSION_FILTER_COMPLETED,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tally.py
new file mode 100644
index 000000000000..1bee8004c26b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tally.py
@@ -0,0 +1,325 @@
+import dataclasses
+from collections.abc import Callable
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.settings import (
+ SUBMISSION_FILTER_COMPLETED,
+ TALLY_API_VERSION,
+ TALLY_BASE_URL,
+ TALLY_ENDPOINTS,
+ TALLY_VERSION_HEADER,
+ TallyEndpointConfig,
+)
+
+
+class TallyResumeConfig:
+ # Page bookmark for a top-level endpoint. None means "start at page one".
+ next_page: Optional[int] = None
+ # Framework fan-out resume state for the per-form endpoints, opaque to this source and passed
+ # straight back to the fan-out helper:
+ # {"completed": [child_path, ...], "current": child_path | None, "child_state": {"page": n} | None}.
+ fanout_state: Optional[dict[str, Any]] = None
+
+
+class TallyPaginator(PageNumberPaginator):
+ """Page-number paginator that terminates on Tally's `hasMore` flag.
+
+ Every Tally list endpoint returns `page`, `limit` and a `hasMore` boolean alongside its rows,
+ and the docs name `hasMore` as the end-of-pages signal. Stopping on it avoids both the extra
+ empty-page round trip the default paginator pays and the off-by-one risk of deriving a page
+ count from `total`, which shifts while a sync is running.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(base_page=1, page_param="page")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ payload = response.json()
+ has_more = isinstance(payload, dict) and payload.get("hasMore") is True
+ # An empty page that still claims `hasMore` would loop forever; treat it as the end.
+ if not has_more or not data:
+ self._has_next_page = False
+ return
+
+ self.page += 1
+ self._has_next_page = True
+
+
+def _paginator_for(config: TallyEndpointConfig) -> BasePaginator:
+ return TallyPaginator() if config.paginated else SinglePagePaginator()
+
+
+def _client_config(api_key: str, api_version: str, capture: bool = True) -> ClientConfig:
+ config: ClientConfig = {
+ "base_url": TALLY_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json", TALLY_VERSION_HEADER: api_version},
+ }
+ if not capture:
+ # This endpoint's body carries secrets the name-based sample scrubbers can't spot, so keep
+ # its responses out of HTTP sample capture (they're still metered and logged). RESTClient
+ # applies the auth and headers above on top of this session.
+ config["session"] = make_tracked_session(redact_values=(api_key,), capture=False)
+ return config
+
+
+def _redact_row_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ """Return a `data_map` that nulls out the named fields on every row, keeping the columns (as
+ null) so the table shape stays stable while the secret values never reach the warehouse.
+ """
+
+ def _redact(row: dict[str, Any]) -> dict[str, Any]:
+ for name in fields:
+ if name in row:
+ row[name] = None
+ return row
+
+ return _redact
+
+
+def _to_iso8601(value: Any) -> str:
+ """Format an incremental watermark the way Tally's `startDate` filter expects (ISO 8601, UTC)."""
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+
+ # A watermark ahead of now (clock skew, a restated row) would filter out every submission.
+ return min(normalized, datetime.now(UTC)).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _submissions_incremental(cursor_path: str) -> IncrementalConfig:
+ # `startDate` filters server-side on submission time, and page-number pagination keeps every
+ # query param on later pages — so an incremental run never walks past the watermark.
+ return {
+ "cursor_path": cursor_path,
+ "start_param": "startDate",
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _to_iso8601,
+ }
+
+
+def _supports_incremental(config: TallyEndpointConfig, submission_filter: str) -> bool:
+ if not config.incremental_fields:
+ return False
+ # Partial submissions are still being filled in, so we can't rely on `submittedAt` being a
+ # settled cursor for them. Including partials therefore drops to full refresh (see get_schemas).
+ return submission_filter == SUBMISSION_FILTER_COMPLETED
+
+
+def _source_response(config: TallyEndpointConfig, items: Any) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: items,
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ 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 _top_level_source(
+ api_key: str,
+ api_version: str,
+ config: TallyEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TallyResumeConfig],
+) -> SourceResponse:
+ params: dict[str, Any] = {}
+ if config.page_size_param is not None:
+ params[config.page_size_param] = config.page_size
+
+ endpoint: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "paginator": _paginator_for(config),
+ "data_selector": config.data_selector,
+ }
+ resource: EndpointResource = {
+ "name": config.name,
+ "table_name": config.name,
+ # No top-level endpoint exposes a server-side updated-since filter, so they full refresh.
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ if config.redact_fields:
+ resource["data_map"] = _redact_row_fields(config.redact_fields)
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key, api_version, capture=config.capture_samples),
+ "resource_defaults": {},
+ "resources": [resource],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.next_page:
+ initial_paginator_state = {"page": resume.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Saved after a page is yielded, so a crash re-yields the last page rather than skipping it.
+ if state and state.get("page"):
+ resumable_source_manager.save_state(TallyResumeConfig(next_page=int(state["page"])))
+
+ return _source_response(
+ config,
+ rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+
+
+def _fanout_source(
+ api_key: str,
+ api_version: str,
+ endpoint: str,
+ config: TallyEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TallyResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str],
+ submission_filter: str,
+) -> SourceResponse:
+ """Fan out one paginated request per form, tagging every child row with its owning form id."""
+ assert config.fanout is not None
+
+ child_params_extra: Optional[dict[str, Any]] = None
+ if endpoint == "submissions":
+ child_params_extra = {"filter": submission_filter}
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.fanout_state:
+ initial_paginator_state = resume.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ resumable_source_manager.save_state(TallyResumeConfig(fanout_state=state))
+
+ resource = build_dependent_resource(
+ endpoint_configs=TALLY_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key, api_version),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field and _supports_incremental(config, submission_filter),
+ incremental_field=incremental_field,
+ incremental_config_factory=_submissions_incremental,
+ page_size_param=config.page_size_param,
+ parent_endpoint_extra={
+ "paginator": TallyPaginator(),
+ "data_selector": TALLY_ENDPOINTS[config.fanout.parent_name].data_selector,
+ },
+ child_endpoint_extra={
+ "paginator": _paginator_for(config),
+ "data_selector": config.data_selector,
+ # A form trashed between enumeration and this fetch 404s. Skip it rather than failing
+ # the whole sync — the form's data is gone either way.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ child_params_extra=child_params_extra,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _source_response(config, resource)
+
+
+def tally_source(
+ api_key: str,
+ api_version: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TallyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+ submission_filter: str = SUBMISSION_FILTER_COMPLETED,
+) -> SourceResponse:
+ config = TALLY_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(
+ api_key=api_key,
+ api_version=api_version,
+ endpoint=endpoint,
+ config=config,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ submission_filter=submission_filter,
+ )
+
+ return _top_level_source(
+ api_key=api_key,
+ api_version=api_version,
+ config=config,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+
+
+def validate_credentials(api_key: str, api_version: str = TALLY_API_VERSION) -> tuple[bool, Optional[int]]:
+ """Probe the cheapest authenticated endpoint and report `(is_valid, status_code)`.
+
+ `/forms?limit=1` needs no extra grant beyond a working key, so it validates the key itself
+ rather than access to any one table.
+ """
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{TALLY_BASE_URL}/forms?limit=1",
+ headers={
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ TALLY_VERSION_HEADER: api_version,
+ },
+ )
+
+
+__all__ = ["TallyPaginator", "TallyResumeConfig", "tally_source", "validate_credentials"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally.py
new file mode 100644
index 000000000000..d405e7b3f2b6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally.py
@@ -0,0 +1,447 @@
+import json
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+from urllib.parse import parse_qsl, urlsplit
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.settings import (
+ FORMS_PAGE_SIZE,
+ SUBMISSION_FILTER_ALL,
+ SUBMISSION_FILTER_COMPLETED,
+ SUBMISSIONS_PAGE_SIZE,
+ TALLY_API_VERSION,
+ TALLY_BASE_URL,
+ WEBHOOKS_PAGE_SIZE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.tally import (
+ TallyResumeConfig,
+ tally_source,
+ validate_credentials,
+)
+
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+TALLY_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.tally.tally.make_tracked_session"
+)
+SLEEP_PATCH = "tenacity.nap.time.sleep"
+
+BASE = TALLY_BASE_URL
+FORMS_PAGE_1 = f"{BASE}/forms?limit={FORMS_PAGE_SIZE}&page=1"
+
+
+def _resp(body: Any, status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _page(rows: list[dict[str, Any]], key: str = "items", has_more: bool = False) -> Response:
+ return _resp({key: rows, "page": 1, "limit": 50, "hasMore": has_more})
+
+
+def _norm(url: str) -> tuple[str, tuple[tuple[str, str], ...]]:
+ parts = urlsplit(url)
+ return parts.path, tuple(sorted(parse_qsl(parts.query)))
+
+
+def _make_manager(resume_state: TallyResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses_by_url: dict[str, list[Response]]) -> list[dict[str, Any]]:
+ session.headers = {}
+ normalized: dict[tuple[str, tuple[tuple[str, str], ...]], list[Response]] = {
+ _norm(url): list(queue) for url, queue in responses_by_url.items()
+ }
+ param_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> Any:
+ param_snapshots.append(dict(request.params or {}))
+ return request.prepare()
+
+ def _send(prepared: Any, **_kwargs: Any) -> Response:
+ queue = normalized.get(_norm(prepared.url))
+ if not queue:
+ raise AssertionError(f"unexpected request url {prepared.url!r}")
+ return queue.pop(0)
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = _send
+ return param_snapshots
+
+
+def _run(
+ endpoint: str,
+ responses_by_url: dict[str, list[Response]],
+ manager: mock.MagicMock | None = None,
+ **kwargs: Any,
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], mock.MagicMock]:
+ # Endpoints that disable sample capture build their own session in `_client_config`, so patch
+ # that factory too and point it at the same wired session the rest client would otherwise use.
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession, mock.patch(TALLY_SESSION_PATCH) as MockTallySession:
+ session = MockSession.return_value
+ MockTallySession.return_value = session
+ params = _wire(session, responses_by_url)
+ response = tally_source(
+ api_key="key",
+ api_version=TALLY_API_VERSION,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager if manager is not None else _make_manager(),
+ **kwargs,
+ )
+ rows = [row for page in cast(Any, response.items()) for row in page]
+ return rows, params, session
+
+
+class TestSourceResponseShape:
+ @parameterized.expand(
+ [
+ ("workspaces", ["id"], "createdAt", "asc"),
+ ("forms", ["id"], "createdAt", "asc"),
+ ("questions", ["formId", "id"], "createdAt", "asc"),
+ ("submissions", ["formId", "id"], "submittedAt", "desc"),
+ ("webhooks", ["id"], "createdAt", "asc"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_shape(
+ self,
+ endpoint: str,
+ expected_keys: list[str],
+ expected_partition_key: str,
+ expected_sort_mode: str,
+ _MockSession: Any,
+ ) -> None:
+ response = tally_source(
+ api_key="key",
+ api_version=TALLY_API_VERSION,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_make_manager(),
+ )
+ assert response.name == endpoint
+ # Child tables aggregate rows from every form, so their key must carry the parent form id.
+ assert response.primary_keys == expected_keys
+ assert response.partition_keys == [expected_partition_key]
+ assert response.partition_mode == "datetime"
+ # Submissions interleave one form's history after another's, so the stream is not globally
+ # ascending and the watermark must only advance once the whole sync finishes.
+ assert response.sort_mode == expected_sort_mode
+
+
+class TestPagination:
+ def test_follows_has_more_across_pages(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}], has_more=True)],
+ f"{BASE}/forms?limit={FORMS_PAGE_SIZE}&page=2": [_page([{"id": "F2"}], has_more=False)],
+ }
+ rows, params, _session = _run("forms", responses)
+ assert rows == [{"id": "F1"}, {"id": "F2"}]
+ assert params[0]["page"] == 1
+ assert params[1]["page"] == 2
+
+ def test_stops_when_has_more_is_false_even_with_a_full_page(self) -> None:
+ # `hasMore` is the authoritative end-of-pages signal; a full last page must not trigger
+ # another request that would 400 or re-read page one.
+ responses = {FORMS_PAGE_1: [_page([{"id": "F1"}, {"id": "F2"}], has_more=False)]}
+ rows, params, _session = _run("forms", responses)
+ assert rows == [{"id": "F1"}, {"id": "F2"}]
+ assert len(params) == 1
+
+ def test_empty_page_claiming_has_more_terminates(self) -> None:
+ # Guards against an infinite paging loop if the API ever returns hasMore with no rows.
+ responses = {FORMS_PAGE_1: [_page([], has_more=True)]}
+ rows, params, _session = _run("forms", responses)
+ assert rows == []
+ assert len(params) == 1
+
+ @parameterized.expand(
+ [
+ ("workspaces", f"{BASE}/workspaces?page=1", "items", None),
+ ("forms", FORMS_PAGE_1, "items", FORMS_PAGE_SIZE),
+ ("webhooks", f"{BASE}/webhooks?limit={WEBHOOKS_PAGE_SIZE}&page=1", "webhooks", WEBHOOKS_PAGE_SIZE),
+ ]
+ )
+ def test_top_level_endpoint_request_shape(
+ self, endpoint: str, url: str, selector: str, expected_limit: int | None
+ ) -> None:
+ # /workspaces documents no page-size param, so sending one would be an undocumented param;
+ # the other two carry the vendor's documented maximum.
+ rows, params, _session = _run(endpoint, {url: [_page([{"id": "X"}], key=selector)]})
+ assert rows == [{"id": "X"}]
+ assert params[0].get("limit") == expected_limit
+
+ def test_version_header_is_pinned_on_every_request(self) -> None:
+ # Without the header the response shape follows whatever version the API key was created
+ # against, which changed the /forms envelope between versions.
+ _rows, _params, session = _run("forms", {FORMS_PAGE_1: [_page([{"id": "F1"}])]})
+ assert session.headers["tally-version"] == TALLY_API_VERSION
+
+
+class TestTopLevelResume:
+ def test_saves_next_page_after_yielding_each_page(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}], has_more=True)],
+ f"{BASE}/forms?limit={FORMS_PAGE_SIZE}&page=2": [_page([{"id": "F2"}])],
+ }
+ manager = _make_manager()
+ _run("forms", responses, manager)
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [TallyResumeConfig(next_page=2)]
+
+ def test_resumes_from_saved_page(self) -> None:
+ responses = {f"{BASE}/forms?limit={FORMS_PAGE_SIZE}&page=4": [_page([{"id": "F9"}])]}
+ rows, params, _session = _run("forms", responses, _make_manager(TallyResumeConfig(next_page=4)))
+ assert rows == [{"id": "F9"}]
+ assert params[0]["page"] == 4
+
+
+class TestFanOut:
+ def test_questions_are_tagged_with_their_form(self) -> None:
+ # The questions endpoint takes no page-size param, so only the parent carries `limit`.
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}, {"id": "F2"}])],
+ f"{BASE}/forms/F1/questions": [_resp({"questions": [{"id": "Q1"}], "hasResponses": True})],
+ f"{BASE}/forms/F2/questions": [_resp({"questions": [{"id": "Q1"}], "hasResponses": False})],
+ }
+ rows, params, _session = _run("questions", responses)
+ # A question id is only unique within its form, so both rows keep their own formId.
+ assert rows == [{"id": "Q1", "formId": "F1"}, {"id": "Q1", "formId": "F2"}]
+ assert "limit" not in params[1]
+
+ def test_questions_do_not_request_a_second_page(self) -> None:
+ # The endpoint returns every question at once; paging it would re-read the same rows.
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/questions": [_resp({"questions": [{"id": "Q1"}], "hasMore": True})],
+ }
+ rows, params, _session = _run("questions", responses)
+ assert rows == [{"id": "Q1", "formId": "F1"}]
+ assert len(params) == 2
+
+ def test_submissions_page_per_form(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter=completed": [
+ _resp({"submissions": [{"id": "S1"}], "hasMore": True})
+ ],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=2&filter=completed": [
+ _resp({"submissions": [{"id": "S2"}], "hasMore": False})
+ ],
+ }
+ rows, _params, _session = _run("submissions", responses)
+ assert rows == [{"id": "S1", "formId": "F1"}, {"id": "S2", "formId": "F1"}]
+
+ @parameterized.expand([(SUBMISSION_FILTER_COMPLETED,), (SUBMISSION_FILTER_ALL,)])
+ def test_submission_filter_is_sent_verbatim(self, submission_filter: str) -> None:
+ # Tally documents no default for `filter`, so the chosen value must always be sent.
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter={submission_filter}": [
+ _resp({"submissions": [], "hasMore": False})
+ ],
+ }
+ _rows, params, _session = _run("submissions", responses, submission_filter=submission_filter)
+ assert params[1]["filter"] == submission_filter
+
+ def test_form_deleted_mid_sync_is_skipped(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}, {"id": "GONE"}, {"id": "F2"}])],
+ f"{BASE}/forms/F1/questions": [_resp({"questions": [{"id": "Q1"}]})],
+ f"{BASE}/forms/GONE/questions": [_resp({"message": "not found"}, status=404)],
+ f"{BASE}/forms/F2/questions": [_resp({"questions": [{"id": "Q2"}]})],
+ }
+ rows, _params, _session = _run("questions", responses)
+ assert rows == [{"id": "Q1", "formId": "F1"}, {"id": "Q2", "formId": "F2"}]
+
+ def test_resume_skips_forms_already_drained(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}, {"id": "F2"}])],
+ f"{BASE}/forms/F2/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter=completed": [
+ _resp({"submissions": [{"id": "S2"}], "hasMore": False})
+ ],
+ }
+ state = TallyResumeConfig(
+ fanout_state={"completed": ["/forms/F1/submissions"], "current": None, "child_state": None}
+ )
+ rows, _params, _session = _run("submissions", responses, _make_manager(state))
+ assert rows == [{"id": "S2", "formId": "F2"}]
+
+ def test_resume_continues_mid_form_from_the_saved_page(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=3&filter=completed": [
+ _resp({"submissions": [{"id": "S3"}], "hasMore": False})
+ ],
+ }
+ state = TallyResumeConfig(
+ fanout_state={"completed": [], "current": "/forms/F1/submissions", "child_state": {"page": 3}}
+ )
+ rows, params, _session = _run("submissions", responses, _make_manager(state))
+ assert rows == [{"id": "S3", "formId": "F1"}]
+ assert params[1]["page"] == 3
+
+
+class TestWebhookSecrets:
+ def test_signing_secret_and_headers_are_nulled_and_kept_out_of_capture(self) -> None:
+ # Webhook signing secrets and custom auth headers are credentials — persisting them would let
+ # anyone with warehouse read access forge signed deliveries or reuse embedded tokens. They
+ # must land as null, and the raw responses must stay out of HTTP sample capture.
+ session = mock.MagicMock()
+ responses = {
+ f"{BASE}/webhooks?limit={WEBHOOKS_PAGE_SIZE}&page=1": [
+ _page(
+ [
+ {
+ "id": "W1",
+ "url": "https://example.com/hook",
+ "signingSecret": "shh",
+ "httpHeaders": [{"name": "X-Auth", "value": "tok"}],
+ }
+ ],
+ key="webhooks",
+ )
+ ],
+ }
+ with mock.patch(TALLY_SESSION_PATCH, return_value=session) as mock_tally_session:
+ _wire(session, responses)
+ response = tally_source(
+ api_key="key",
+ api_version=TALLY_API_VERSION,
+ endpoint="webhooks",
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_make_manager(),
+ )
+ rows = [row for page in cast(Any, response.items()) for row in page]
+
+ assert rows == [{"id": "W1", "url": "https://example.com/hook", "signingSecret": None, "httpHeaders": None}]
+ assert mock_tally_session.call_args.kwargs["capture"] is False
+
+
+class TestIncremental:
+ def test_watermark_becomes_a_server_side_start_date(self) -> None:
+ # `startDate` is the only reason this table is incremental; dropping it would re-read every
+ # submission of every form on each run.
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter=completed"
+ f"&startDate=2026-01-02T03%3A04%3A05Z": [_resp({"submissions": [], "hasMore": False})],
+ }
+ _rows, params, _session = _run(
+ "submissions",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="submittedAt",
+ )
+ assert params[1]["startDate"] == "2026-01-02T03:04:05Z"
+
+ def test_full_refresh_sends_no_start_date(self) -> None:
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter=completed": [
+ _resp({"submissions": [], "hasMore": False})
+ ],
+ }
+ _rows, params, _session = _run("submissions", responses, should_use_incremental_field=False)
+ assert "startDate" not in params[1]
+
+ def test_including_partials_falls_back_to_full_refresh(self) -> None:
+ # A partial submission is still being filled in, so `submittedAt` is not a settled cursor;
+ # the source must not filter on a watermark it cannot trust.
+ responses = {
+ FORMS_PAGE_1: [_page([{"id": "F1"}])],
+ f"{BASE}/forms/F1/submissions?limit={SUBMISSIONS_PAGE_SIZE}&page=1&filter=all": [
+ _resp({"submissions": [], "hasMore": False})
+ ],
+ }
+ _rows, params, _session = _run(
+ "submissions",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ submission_filter=SUBMISSION_FILTER_ALL,
+ )
+ assert "startDate" not in params[1]
+
+ def test_future_watermark_is_clamped_to_now(self) -> None:
+ # A watermark ahead of the clock would filter out every submission, syncing nothing forever.
+ future = datetime.now(UTC) + timedelta(days=30)
+ captured: dict[str, Any] = {}
+
+ def _send(prepared: Any, **_kwargs: Any) -> Response:
+ if "/submissions" in prepared.url:
+ captured.update(dict(parse_qsl(urlsplit(prepared.url).query)))
+ return _resp({"submissions": [], "hasMore": False})
+ return _page([{"id": "F1"}])
+
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request.prepare()
+ session.send.side_effect = _send
+ response = tally_source(
+ api_key="key",
+ api_version=TALLY_API_VERSION,
+ endpoint="submissions",
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=future,
+ )
+ list(cast(Any, response.items()))
+
+ assert captured["startDate"] < future.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+class TestRetryClassification:
+ @parameterized.expand([(429,), (500,), (503,)])
+ @mock.patch(SLEEP_PATCH)
+ def test_transient_status_is_retried(self, status: int, _sleep: Any) -> None:
+ responses = {FORMS_PAGE_1: [_resp({"error": "later"}, status=status), _page([{"id": "F1"}])]}
+ rows, _params, _session = _run("forms", responses)
+ assert rows == [{"id": "F1"}]
+
+ @parameterized.expand([(401,), (403,)])
+ @mock.patch(SLEEP_PATCH)
+ def test_credential_error_fails_loud(self, status: int, _sleep: Any) -> None:
+ responses = {FORMS_PAGE_1: [_resp({"error": "nope"}, status=status)]}
+ with pytest.raises(requests.HTTPError):
+ _run("forms", responses)
+
+
+class TestValidateCredentials:
+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])
+ @mock.patch(TALLY_SESSION_PATCH)
+ def test_status_mapping(self, status: int, expected_ok: bool, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)
+ ok, returned_status = validate_credentials("key")
+ assert ok is expected_ok
+ assert returned_status == status
+
+ @mock.patch(TALLY_SESSION_PATCH)
+ def test_transport_error_is_not_a_validation_failure_crash(self, mock_session: Any) -> None:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ assert validate_credentials("key") == (False, None)
+
+ @mock.patch(TALLY_SESSION_PATCH)
+ def test_probe_pins_the_api_version(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("key")
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["tally-version"] == TALLY_API_VERSION
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally_source.py
new file mode 100644
index 000000000000..e8d53390716d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tally/tests/test_tally_source.py
@@ -0,0 +1,182 @@
+from typing import Any
+
+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.tally import TallySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.settings import (
+ ENDPOINTS,
+ SUBMISSION_FILTER_ALL,
+ SUBMISSION_FILTER_COMPLETED,
+ TALLY_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.source import TallySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.tally.tally import TallyResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> mock.MagicMock:
+ inputs = mock.MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "submissions")
+ inputs.team_id = overrides.get("team_id", 123)
+ inputs.job_id = overrides.get("job_id", "job-1")
+ inputs.api_version = overrides.get("api_version", None)
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)
+ inputs.incremental_field = overrides.get("incremental_field", None)
+ return inputs
+
+
+class TestTallySource:
+ def setup_method(self) -> None:
+ self.source = TallySource()
+ self.team_id = 123
+ self.config = TallySourceConfig(api_key="key-test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TALLY
+
+ def test_source_is_visible_and_marked_alpha(self) -> None:
+ config = self.source.get_source_config
+ # A finished source must not stay hidden behind unreleasedSource.
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_api_key_field_is_stored_as_a_secret(self) -> None:
+ api_key_field = self.source.get_source_config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_submission_filter_offers_the_documented_values(self) -> None:
+ filter_field = self.source.get_source_config.fields[1]
+ assert isinstance(filter_field, SourceFieldSelectConfig)
+ assert filter_field.name == "submission_filter"
+ assert filter_field.defaultValue == SUBMISSION_FILTER_COMPLETED
+ assert [option.value for option in filter_field.options] == [
+ SUBMISSION_FILTER_COMPLETED,
+ SUBMISSION_FILTER_ALL,
+ ]
+
+ def test_pins_the_version_the_request_code_sends(self) -> None:
+ assert self.source.supported_versions == (TALLY_API_VERSION,)
+ assert self.source.default_version == TALLY_API_VERSION
+ assert self.source.resolve_api_version(None) == TALLY_API_VERSION
+
+ def test_get_schemas_matches_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["forms", "submissions"])
+ assert {schema.name for schema in schemas} == {"forms", "submissions"}
+
+ def test_only_submissions_is_incremental(self) -> None:
+ # `startDate` on the submissions endpoint is the source's only server-side timestamp filter;
+ # advertising incremental anywhere else would fetch every page and call it incremental.
+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert by_name["submissions"].supports_incremental is True
+ assert [field["field"] for field in by_name["submissions"].incremental_fields] == ["submittedAt"]
+ # `startDate` is inclusive, so append mode would re-write the watermark's own rows.
+ assert by_name["submissions"].supports_append is False
+ for name in ("workspaces", "forms", "questions", "webhooks"):
+ assert by_name[name].supports_incremental is False
+ assert by_name[name].incremental_fields == []
+
+ def test_including_partial_submissions_drops_to_full_refresh(self) -> None:
+ config = TallySourceConfig(api_key="key-test", submission_filter=SUBMISSION_FILTER_ALL)
+ by_name = {schema.name: schema for schema in self.source.get_schemas(config, self.team_id)}
+ assert by_name["submissions"].supports_incremental is False
+ assert by_name["submissions"].incremental_fields == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ described = set(self.source.get_canonical_descriptions().keys())
+ assert set(ENDPOINTS).issubset(described)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.tally.so/forms?limit=500&page=1"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.tally.so/forms/F1/submissions"),
+ ]
+ )
+ def test_credential_errors_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.tally.so/forms"),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.tally.so/forms"),
+ ("read_timeout", "HTTPSConnectionPool(host='api.tally.so', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed_error: str) -> None:
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("valid", True, 200, True, None),
+ ("bad_key", False, 401, False, "Invalid Tally API key"),
+ (
+ "forbidden",
+ False,
+ 403,
+ False,
+ "Your Tally API key does not have access to this data. Reconnect with a key from an account that can see these forms.",
+ ),
+ ("unreachable", False, None, False, "Could not reach the Tally API with this key"),
+ ]
+ )
+ def test_validate_credentials_maps_probe_result(
+ self, _name: str, probe_ok: bool, probe_status: int | None, expected_ok: bool, expected_error: str | None
+ ) -> None:
+ with mock.patch.object(source_module, "validate_tally_credentials", return_value=(probe_ok, probe_status)):
+ ok, error = self.source.validate_credentials(self.config, self.team_id)
+ assert ok is expected_ok
+ assert error == expected_error
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TallyResumeConfig
+
+ def test_source_for_pipeline_plumbs_config_and_inputs(self) -> None:
+ manager = mock.MagicMock()
+ inputs = _make_inputs(
+ schema_name="submissions",
+ team_id=99,
+ job_id="job-xyz",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="submittedAt",
+ )
+ with mock.patch.object(source_module, "tally_source") as tally_source_fn:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ tally_source_fn.assert_called_once_with(
+ api_key="key-test",
+ api_version=TALLY_API_VERSION,
+ endpoint="submissions",
+ team_id=99,
+ job_id="job-xyz",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="submittedAt",
+ submission_filter=SUBMISSION_FILTER_COMPLETED,
+ )
+
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:
+ # A stale watermark must not leak into a full-refresh run as a startDate filter.
+ manager = mock.MagicMock()
+ inputs = _make_inputs(
+ should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01T00:00:00Z"
+ )
+ with mock.patch.object(source_module, "tally_source") as tally_source_fn:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ assert tally_source_fn.call_args.kwargs["db_incremental_field_last_value"] is None