: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): add 5 missing tables to the Smartsheet source (#119069)
Tom Owers8bb4013fe4f5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex f2d870f9c3f9..516f79ae9fbd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -11217,10 +11217,10 @@ Diffed against: <https://developers.smartsheet.com/sitemap.xml>- [x] `GET /reports/{reportId}/columns` — the columns of every report (title, type, index), fanned out across all reports (announced Jul-09-2026)- [x] `GET /reports/{reportId}/scope` — each report's source sheets and workspaces, fanned out across all reports (announced Jul-09-2026)-- [ ] `GET /sheets/{sheetId} (rows + cells)` — the actual row/cell data inside every sheet - today only sheet metadata is synced, so no sheet content is queryable (high)-- [ ] `GET /sheets/{sheetId}/columns` — lookup resolving the column ids that every cell references, including picklist options (high)-- [ ] `GET /events (list-events, list-filtered-events)` — the org-wide activity event stream - who changed what and when (high)-- [ ] `GET /groups and group members` — group membership lookup that resolves sharing and contact ids (high)+- [x] `GET /sheets/{sheetId} (rows + cells)` — the actual row/cell data inside every sheet - today only sheet metadata is synced, so no sheet content is queryable (high)+- [x] `GET /sheets/{sheetId}/columns` — lookup resolving the column ids that every cell references, including picklist options (high)+- [x] `GET /events (list-events, list-filtered-events)` — the org-wide activity event stream - who changed what and when (high)+- [x] `GET /groups and group members` — group membership lookup that resolves sharing and contact ids (high)- [ ] `GET /{assetType}/{assetId}/shares (list-asset-shares)` — who has access to each sheet/report/workspace; the access-control fact table (medium)- [ ] `GET /sheets/{sheetId}/discussions and comments` — collaboration threads attached to sheets and rows (medium)- [ ] `GET /sheets/{sheetId}/attachments (also row and discussion scoped)` — attachment metadata per sheet/row (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/canonical_descriptions.pyindex 18dce68fa02f..4828ccbf5349 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/canonical_descriptions.py@@ -2,9 +2,9 @@Sourced from the official Smartsheet API reference (https://smartsheet.redoc.ly). Keyed by theendpoint names in `settings.py` `SMARTSHEET_ENDPOINTS`, which match the `ExternalDataSchema.name`-of a synced Smartsheet table. These are the account-level list endpoints (sheet/report/workspace/-user/contact/template metadata) — not the user-defined cell data inside a sheet. Columns absent-here fall back to LLM enrichment.+of a synced Smartsheet table. Most are account-level list endpoints (sheet/report/workspace/+user/contact/template/group metadata); `sheet_rows` holds the cell data inside each sheet. Columns+absent here fall back to LLM enrichment."""from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -105,4 +105,78 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"assetId": "Identifier of the source asset, according to its assetType.",},},+ "sheet_rows": {+ "description": "A row of a sheet, with its cells — fanned out across every sheet the account can access.",+ "docs_url": "https://developers.smartsheet.com/api/smartsheet/openapi/sheets/getsheet",+ "columns": {+ "sheetId": "Identifier of the sheet this row belongs to.",+ "id": "Row ID.",+ "rowNumber": "Row number within the sheet.",+ "parentId": "Identifies the row that is the hierarchical parent of this row, if one exists.",+ "siblingId": "Identifies the row immediately above this row, if one exists.",+ "cells": "Cells belonging to the row. Each cell holds a columnId (see sheet_columns), a value and a displayValue.",+ "locked": "Whether the row is locked.",+ "createdAt": "Time at which the row was created.",+ "modifiedAt": "Time at which the row was last modified.",+ },+ },+ "sheet_columns": {+ "description": "A column of a sheet — fanned out across every sheet the account can access. Resolves the columnId of each cell in sheet_rows.",+ "docs_url": "https://developers.smartsheet.com/api/smartsheet/openapi/columns/columns-listonsheet",+ "columns": {+ "sheetId": "Identifier of the sheet this column belongs to.",+ "id": "The column's unique identifier.",+ "index": "The column's position in the sheet. Indexes start at 0.",+ "title": "Column title.",+ "type": "The column type (e.g. TEXT_NUMBER, DATE, PICKLIST, CONTACT_LIST, CHECKBOX).",+ "primary": "Whether the column is the sheet's primary column.",+ "options": "The options of a picklist column.",+ "hidden": "Whether the column is hidden.",+ "locked": "Whether the column is locked.",+ "width": "The column's display width, in pixels.",+ "formula": "The formula for the column, if set.",+ "description": "Column description.",+ },+ },+ "events": {+ "description": "An event in the organization's activity stream — an action a user or system took on a Smartsheet object.",+ "docs_url": "https://developers.smartsheet.com/api/smartsheet/openapi/events/list-events",+ "columns": {+ "eventId": "Unique event identifier.",+ "eventTimestamp": "Date and time of the event.",+ "objectType": "The Smartsheet resource that the event affected (e.g. SHEET, REPORT, USER).",+ "action": "The action applied to the object (e.g. CREATE, UPDATE, LOAD, DELETE).",+ "objectId": "Identifier of the object that the event affected.",+ "userId": "User assumed as the one who initiated the event.",+ "requestUserId": "User whose authentication credential is embedded in the request that initiated the event.",+ "accessTokenName": "Name of the access token embedded in the request, if any.",+ "source": "The client or user agent used to initiate the action.",+ "additionalDetails": "Properties specific to the event type.",+ },+ },+ "groups": {+ "description": "A group in the organization account.",+ "docs_url": "https://developers.smartsheet.com/api/smartsheet/openapi/groups/list-groups",+ "columns": {+ "id": "Group ID.",+ "name": "Group name.",+ "description": "Group description.",+ "owner": "Group owner's email address.",+ "ownerId": "Group owner's user ID.",+ "createdAt": "Time at which the group was created.",+ "modifiedAt": "Time at which the group was last modified.",+ },+ },+ "group_members": {+ "description": "A member of a group — fanned out across every group in the organization account.",+ "docs_url": "https://developers.smartsheet.com/api/smartsheet/openapi/groups/get-group",+ "columns": {+ "groupId": "Identifier of the group this member belongs to.",+ "id": "Group member's user ID.",+ "email": "Group member's email address.",+ "name": "Group member's full name.",+ "firstName": "Group member's first name.",+ "lastName": "Group member's last name.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/settings.pyindex c5aa19d3c6e6..43b9067e8639 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/settings.py@@ -1,10 +1,11 @@from dataclasses import dataclass-from typing import Optional+from typing import Literal, Optionalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,)-from products.warehouse_sources.backend.types import IncrementalField+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Smartsheet's account-level list endpoints share the same page-based envelope# ({pageNumber, pageSize, totalPages, totalCount, data: [...]}). We model each as a top-level@@ -13,16 +14,29 @@ from products.warehouse_sources.backend.types import IncrementalField# The report child endpoints (report_columns / report_scope) are different: they fan out from# each report and page by token (`lastKey` / `maxItems`) rather than page number — see smartsheet.py.#-# Incremental sync is intentionally not enabled anywhere. Although `List Sheets` / `List Reports`-# document a `modifiedSince` server-side filter, these list endpoints expose no stable `sort`-# parameter, so we cannot guarantee the ascending ordering the pipeline relies on to advance an-# incremental watermark safely across resumed syncs. The report child endpoints expose no-# timestamp filter at all. The payloads here are small (account-level metadata and per-report+# The metadata endpoints are full refresh. Although `List Sheets` / `List Reports` document a+# `modifiedSince` server-side filter, these list endpoints expose no stable `sort` parameter, so we+# cannot guarantee the ascending ordering the pipeline relies on to advance an incremental watermark+# safely across resumed syncs. The payloads are small (account-level metadata and per-report# structure), so a full refresh is cheap and correct.+#+# `sheet_rows` (`rowsModifiedSince`) and `events` (`since`) are the exceptions: their data is large+# and the server filters it. Neither returns rows in watermark order, so both report+# sort_mode="desc", which commits the watermark only when the sync completes.# The report child endpoints page by token; `maxItems` default and minimum is 100. The `reports`# parent walk keeps the same 100-row page size the top-level `reports` endpoint uses.PAGE_SIZE = 100+# Get Sheet pages its rows with the same `page` / `pageSize` params. A row carries one cell per+# column, so rows get a larger page than the metadata lists but stay well below the response cap.+ROWS_PAGE_SIZE = 500+# The documented maximum of `maxCount` on List Events.+EVENTS_MAX_COUNT = 10000++# How an endpoint pages: `page_number` stops on `totalPages`, `token` follows `lastKey`,+# `sheet_rows` stops on the sheet's `totalRowCount`, and `event_stream` follows+# `nextStreamPosition` until `moreAvailable` is false.+Pagination = Literal["page_number", "token", "single_page", "sheet_rows", "event_stream"]# Mutable so instances satisfy the shared FanoutEndpointLike protocol, which declares settable@@ -36,12 +50,14 @@ class SmartsheetEndpointConfig:# A stable creation-date field used for datetime partitioning. Only set it where the# list response is documented to return it on every row.partition_key: Optional[str] = None- # Fan-out plumbing for the report child endpoints. `default_incremental_field` and- # `page_size` satisfy the shared dependent-resource builder's endpoint protocol; both stay- # at their defaults because these endpoints are full refresh.+ # `default_incremental_field` and `page_size` also satisfy the shared dependent-resource+ # builder's endpoint protocol.default_incremental_field: Optional[str] = Nonepage_size: int = PAGE_SIZEfanout: Optional[DependentEndpointConfig] = None+ pagination: Pagination = "page_number"+ data_selector: str = "data"+ sort_mode: SortMode = "asc"# The parent-report id injected into each report child row (via include_from_parent), used as the@@ -57,6 +73,25 @@ _REPORT_PARENT_FANOUT = DependentEndpointConfig(child_params={"maxItems": PAGE_SIZE},)+# Sheet ids and group ids are injected into each child row the same way as the report id above.+_SHEET_PARENT_FANOUT = DependentEndpointConfig(+ parent_name="sheets",+ resolve_param="sheet_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "sheetId"},+ parent_params={"pageSize": PAGE_SIZE},+)++_GROUP_PARENT_FANOUT = DependentEndpointConfig(+ parent_name="groups",+ resolve_param="group_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "groupId"},+ parent_params={"pageSize": PAGE_SIZE},+)+SMARTSHEET_ENDPOINTS: dict[str, SmartsheetEndpointConfig] = {"sheets": SmartsheetEndpointConfig(@@ -99,6 +134,7 @@ SMARTSHEET_ENDPOINTS: dict[str, SmartsheetEndpointConfig] = {# but is unique only within its report, so the parent report id leads the key.primary_key=["reportId", "virtualId"],fanout=_REPORT_PARENT_FANOUT,+ pagination="token",),"report_scope": SmartsheetEndpointConfig(name="report_scope",@@ -108,6 +144,68 @@ SMARTSHEET_ENDPOINTS: dict[str, SmartsheetEndpointConfig] = {# its assetType, so the key spans the report id, the asset type, and the asset id.primary_key=["reportId", "assetType", "assetId"],fanout=_REPORT_PARENT_FANOUT,+ pagination="token",+ ),+ "sheet_rows": SmartsheetEndpointConfig(+ name="sheet_rows",+ path="/sheets/{sheet_id}",+ incremental_fields=[+ {+ "label": "modifiedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "modifiedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="modifiedAt",+ # Row ids are only documented as unique within a sheet, so the sheet id leads the key.+ primary_key=["sheetId", "id"],+ page_size=ROWS_PAGE_SIZE,+ fanout=_SHEET_PARENT_FANOUT,+ pagination="sheet_rows",+ data_selector="rows",+ sort_mode="desc",+ ),+ "sheet_columns": SmartsheetEndpointConfig(+ name="sheet_columns",+ path="/sheets/{sheet_id}/columns",+ incremental_fields=[],+ primary_key=["sheetId", "id"],+ fanout=_SHEET_PARENT_FANOUT,+ ),+ "events": SmartsheetEndpointConfig(+ name="events",+ path="/events",+ incremental_fields=[+ {+ "label": "eventTimestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "eventTimestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="eventTimestamp",+ primary_key="eventId",+ partition_key="eventTimestamp",+ page_size=EVENTS_MAX_COUNT,+ pagination="event_stream",+ sort_mode="desc",+ ),+ "groups": SmartsheetEndpointConfig(+ name="groups",+ path="/groups",+ partition_key="createdAt",+ incremental_fields=[],+ ),+ "group_members": SmartsheetEndpointConfig(+ name="group_members",+ path="/groups/{group_id}",+ incremental_fields=[],+ # A member id is a user id, so it repeats across every group the user belongs to.+ primary_key=["groupId", "id"],+ fanout=_GROUP_PARENT_FANOUT,+ pagination="single_page",+ data_selector="members",),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/smartsheet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/smartsheet.pyindex 15f3d1999a05..0830ea827f82 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/smartsheet.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/smartsheet.py@@ -1,7 +1,12 @@-import dataclassesfrom collections.abc import Iterable+from datetime import datetime, timedeltafrom typing import Any, Optional, cast+from requests import Request, Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -11,26 +16,111 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resbuild_dependent_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,JSONResponseCursorPaginator,PageNumberPaginator,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.smartsheet.settings import (- PAGE_SIZE,SMARTSHEET_ENDPOINTS,+ Pagination,SmartsheetEndpointConfig,)SMARTSHEET_BASE_URL = "https://api.smartsheet.com/2.0"+# List Events needs a `since` (or a stream position). A full refresh asks from a date before any+# retained event, so it reads the whole retained stream.+EVENTS_FULL_REFRESH_SINCE = "2000-01-01T00:00:00Z"+# Smartsheet resolves `since` to the nearest hour, which can round it past the watermark. Moving+# the watermark back one hour first means no event is skipped; the merge on eventId drops the overlap.+EVENTS_SINCE_OVERLAP = timedelta(hours=1)++@frozenclass SmartsheetResumeConfig:# 1-based number of the next unfetched page — Smartsheet list endpoints page with `page`.- next_page: int+ next_page: Optional[int] = None+ # `nextStreamPosition` of the events stream, which pages by position instead of by page number.+ stream_position: Optional[str] = None+++class SheetRowsPaginator(PageNumberPaginator):+ """Page the rows of Get Sheet.++ The response reports `totalRowCount` but no page count, and a page past the end returns the+ last page again rather than an empty one, so the walk stops on the row count.+ """++ def __init__(self, page_size: int) -> None:+ super().__init__(base_page=1, page_param="page")+ self.page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page:+ return+ total_rows = response.json().get("totalRowCount")+ # `self.page` already points at the next page, so the earlier pages hold every row before it.+ rows_fetched = (self.page - 1) * self.page_size+ if len(data or []) < self.page_size or not isinstance(total_rows, int) or rows_fetched >= total_rows:+ self._has_next_page = False+++class EventStreamPaginator(JSONResponseCursorPaginator):+ """Follow the List Events stream.++ Every response carries a `nextStreamPosition`, so `moreAvailable` is the only end signal. The+ API takes exactly one of `since` and `streamPosition`, so a request with a position drops `since`.+ """++ def __init__(self) -> None:+ super().__init__(cursor_path="nextStreamPosition", cursor_param="streamPosition")++ def init_request(self, request: Request) -> None:+ super().init_request(request)+ self._drop_since(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if response.json().get("moreAvailable") is not True:+ self._has_next_page = False++ def update_request(self, request: Request) -> None:+ super().update_request(request)+ self._drop_since(request)++ def _drop_since(self, request: Request) -> None:+ if self._cursor_value is not None and request.params:+ request.params.pop("since", None)+++def _paginator(pagination: Pagination, page_size: int) -> BasePaginator:+ if pagination == "token":+ return JSONResponseCursorPaginator(cursor_path="lastKey", cursor_param="lastKey")+ if pagination == "single_page":+ return SinglePagePaginator()+ if pagination == "sheet_rows":+ return SheetRowsPaginator(page_size)+ if pagination == "event_stream":+ return EventStreamPaginator()+ return PageNumberPaginator(base_page=1, page_param="page", total_path="totalPages")+++def _incremental_start(+ should_use_incremental_field: bool, db_incremental_field_last_value: Optional[Any]+) -> Optional[datetime]:+ if not should_use_incremental_field:+ return None+ return parse_datetime_value(db_incremental_field_last_value)+++def _iso(value: datetime) -> str:+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")def _non_secret_headers() -> dict[str, str]:@@ -51,20 +141,29 @@ def _primary_keys(config: SmartsheetEndpointConfig) -> list[str]:return config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]-def _report_fanout_source(+def _fanout_source(access_token: str,endpoint: str,config: SmartsheetEndpointConfig,team_id: int,job_id: str,+ incremental_start: Optional[datetime],) -> SourceResponse:- """Fan out from each report to its per-report structure (columns or scope).+ """Fan out from each parent (report, sheet or group) to its child endpoint.- The `reports` parent walks the account's reports page-by-page; each child request resolves a- report id into its path and pages by token (`lastKey`) until Smartsheet omits the key. These- endpoints carry no timestamp, so the child full-refreshes and resume is not wired.+ The parent walks its list page-by-page; each child request resolves a parent id into its path+ and pages the way its `pagination` names. Resume is not wired for fan-out."""assert config.fanout is not None+ pagination = config.pagination+ child_params_extra: Optional[dict[str, Any]] = None+ if pagination == "sheet_rows" and incremental_start is not None:+ # Get Sheet documents `totalRowCount` only for the whole sheet, not for the rows that+ # `rowsModifiedSince` keeps, so a filtered read takes its rows in one unpaged request.+ pagination = "single_page"+ child_params_extra = {"rowsModifiedSince": _iso(incremental_start)}+ elif pagination in ("sheet_rows", "page_number"):+ child_params_extra = {"pageSize": config.page_size}dependent_resource = cast(Iterable[Any],build_dependent_resource(@@ -84,9 +183,10 @@ def _report_fanout_source("data_selector": "data",},child_endpoint_extra={- "paginator": JSONResponseCursorPaginator(cursor_path="lastKey", cursor_param="lastKey"),- "data_selector": "data",+ "paginator": _paginator(pagination, config.page_size),+ "data_selector": config.data_selector,},+ child_params_extra=child_params_extra,),)@@ -96,6 +196,7 @@ def _report_fanout_source(primary_keys=_primary_keys(config),partition_count=1,partition_size=1,+ sort_mode=config.sort_mode,)@@ -105,16 +206,30 @@ def smartsheet_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[SmartsheetResumeConfig],+ should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = SMARTSHEET_ENDPOINTS[endpoint]+ incremental_start = (+ _incremental_start(should_use_incremental_field, db_incremental_field_last_value)+ if config.incremental_fields+ else None+ )if config.fanout is not None:- return _report_fanout_source(access_token, endpoint, config, team_id, job_id)+ return _fanout_source(access_token, endpoint, config, team_id, job_id, incremental_start)client_config = _client_config(access_token)- # Smartsheet returns the grand total of PAGES in `totalPages`; stop after the last one.- client_config["paginator"] = PageNumberPaginator(base_page=1, page_param="page", total_path="totalPages")+ client_config["paginator"] = _paginator(config.pagination, config.page_size)++ params: dict[str, Any] = {"pageSize": config.page_size}+ if config.pagination == "event_stream":+ since = (+ _iso(incremental_start - EVENTS_SINCE_OVERLAP)+ if incremental_start is not None+ else EVENTS_FULL_REFRESH_SINCE+ )+ params = {"since": since, "maxCount": config.page_size}rest_config: RESTAPIConfig = {"client": client_config,@@ -125,8 +240,8 @@ def smartsheet_source("name": endpoint,"endpoint": {"path": config.path,- "params": {"pageSize": PAGE_SIZE},- "data_selector": "data",+ "params": params,+ "data_selector": config.data_selector,},}],@@ -135,13 +250,19 @@ def smartsheet_source(initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()- if resume is not None:+ if resume is not None and resume.stream_position is not None:+ initial_paginator_state = {"cursor": resume.stream_position}+ elif resume is not None and resume.next_page is not None:initial_paginator_state = {"page": resume.next_page}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields# the last page (merge dedupes) rather than skipping it.- if state and state.get("page") is not None:+ if not state:+ return+ if state.get("cursor") is not None:+ resumable_source_manager.save_state(SmartsheetResumeConfig(stream_position=str(state["cursor"])))+ elif state.get("page") is not None:resumable_source_manager.save_state(SmartsheetResumeConfig(next_page=int(state["page"])))resource = rest_api_resource(@@ -162,6 +283,7 @@ def smartsheet_source(partition_mode="datetime" if config.partition_key else None,partition_format="week" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode=config.sort_mode,column_hints=resource.column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/source.pyindex 2aa342e346fe..c6cbd0ad8994 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/source.py@@ -75,7 +75,7 @@ class SmartsheetSource(ResumableSource[SmartsheetSourceConfig, SmartsheetResumeClabel="Smartsheet",caption="""Enter your Smartsheet API access token to pull your Smartsheet data into the PostHog Data warehouse.-You can generate a personal access token under **Personal Settings → API Access** in your [Smartsheet account](https://app.smartsheet.com). The token inherits your account's read access; the `users` table additionally requires a system administrator account.""",+You can generate a personal access token under **Personal Settings → API Access** in your [Smartsheet account](https://app.smartsheet.com). The token inherits your account's read access. The `users` and `events` tables require a system administrator account, and the `events` table also requires the Event Reporting add-on.""",iconPath="/static/services/smartsheet.png",docsUrl="https://posthog.com/docs/cdp/sources/smartsheet",releaseStatus=ReleaseStatus.ALPHA,@@ -103,7 +103,7 @@ You can generate a personal access token under **Personal Settings → API Accesforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=["events"])def validate_credentials(self,@@ -132,5 +132,6 @@ You can generate a personal access token under **Personal Settings → API Accesteam_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,- db_incremental_field_last_value=None, # every Smartsheet endpoint is full refresh+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/tests/test_smartsheet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/tests/test_smartsheet.pyindex 6170dc83e6d5..938ea525bba3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/tests/test_smartsheet.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartsheet/tests/test_smartsheet.py@@ -1,3 +1,4 @@+from datetime import UTC, datetimefrom typing import Anyimport pytest@@ -8,6 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartsheet import (@@ -15,10 +17,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.smartsheet.settings import (ENDPOINTS,+ EVENTS_MAX_COUNT,+ PAGE_SIZE,+ ROWS_PAGE_SIZE,SMARTSHEET_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.smartsheet.smartsheet import (- PAGE_SIZE,SmartsheetResumeConfig,validate_credentials,)@@ -60,6 +64,170 @@ class TestPagination:assert result.params("page")[0] == "3"+def _sheets(*sheet_ids: int) -> ScriptedResponse:+ return _response([{"id": sheet_id} for sheet_id in sheet_ids], total_pages=1)+++def _rows(first_id: int, count: int, total_row_count: int) -> ScriptedResponse:+ return ScriptedResponse(+ json={+ "id": 1,+ "totalRowCount": total_row_count,+ "columns": [{"id": 7, "title": "Status"}],+ "rows": [{"id": first_id + i, "cells": [{"columnId": 7, "value": "Open"}]} for i in range(count)],+ }+ )+++def _events(event_ids: list[str], next_position: str, more_available: bool) -> ScriptedResponse:+ return ScriptedResponse(+ json={+ "nextStreamPosition": next_position,+ "moreAvailable": more_available,+ "data": [{"eventId": event_id, "eventTimestamp": "2026-03-02T10:00:00Z"} for event_id in event_ids],+ }+ )+++class TestSheetRows:+ @pytest.mark.parametrize(+ "row_pages, expected_pages",+ [+ # A short page is the last one.+ ([_rows(1, ROWS_PAGE_SIZE, 600), _rows(501, 100, 600)], ["1", "2"]),+ # A full page that reaches totalRowCount is the last one; asking for page 2 would make+ # Smartsheet return page 1 again.+ ([_rows(1, ROWS_PAGE_SIZE, ROWS_PAGE_SIZE)], ["1"]),+ # No totalRowCount means no safe way to know a next page exists.+ ([ScriptedResponse(json={"rows": [{"id": i} for i in range(ROWS_PAGE_SIZE)]})], ["1"]),+ ],+ )+ def test_full_refresh_pages_rows_until_the_row_count(+ self, row_pages: list[ScriptedResponse], expected_pages: list[str]+ ) -> None:+ result = _run("sheet_rows", route({"/sheets": [_sheets(11)], "/sheets/11": row_pages}))++ assert result.raised is None+ row_requests = [r for r in result.requests if r.path.endswith("/sheets/11")]+ assert [r.param("page") for r in row_requests] == expected_pages+ assert {r.param("pageSize") for r in row_requests} == {str(ROWS_PAGE_SIZE)}+ assert all(r.param("rowsModifiedSince") is None for r in row_requests)+ assert {row["sheetId"] for row in result.rows} == {11}++ @pytest.mark.parametrize(+ "last_value",+ [datetime(2026, 3, 1, 12, 30, tzinfo=UTC), "2026-03-01T12:30:00Z", "2026-03-01T13:30:00+01:00"],+ )+ def test_incremental_reads_modified_rows_of_each_sheet_in_one_request(self, last_value: Any) -> None:+ result = _run(+ "sheet_rows",+ route(+ {+ "/sheets": [_sheets(11, 12)],+ # A full page with a larger totalRowCount must not ask for page 2 once filtered.+ "/sheets/11": [_rows(1, ROWS_PAGE_SIZE, 5000)],+ "/sheets/12": [_rows(9001, 2, 5000)],+ }+ ),+ incremental_field="modifiedAt",+ db_incremental_field_last_value=last_value,+ )++ assert result.raised is None+ row_requests = [r for r in result.requests if "/sheets/1" in r.path]+ assert [r.path.rsplit("/", 1)[-1] for r in row_requests] == ["11", "12"]+ for request in row_requests:+ assert request.param("rowsModifiedSince") == "2026-03-01T12:30:00Z"+ assert request.param("page") is None+ assert request.param("pageSize") is None+ assert len(result.rows) == ROWS_PAGE_SIZE + 2+ assert result.response is not None+ assert result.response.sort_mode == "desc"+++class TestFanOutChildren:+ @pytest.mark.parametrize(+ "endpoint, script, parent_key, expected_rows",+ [+ (+ "sheet_columns",+ {+ "/sheets": [_sheets(11)],+ "/sheets/11/columns": [+ _response([{"id": 7, "options": ["Open", "Done"]}], total_pages=2),+ _response([{"id": 8}], total_pages=2),+ ],+ },+ "sheetId",+ [(11, 7), (11, 8)],+ ),+ (+ "group_members",+ {+ "/groups": [_response([{"id": 21}, {"id": 22}], total_pages=1)],+ "/groups/21": [ScriptedResponse(json={"id": 21, "name": "Ops", "members": [{"id": 5}]})],+ "/groups/22": [ScriptedResponse(json={"id": 22, "name": "Eng", "members": [{"id": 5}, {"id": 6}]})],+ },+ "groupId",+ [(21, 5), (22, 5), (22, 6)],+ ),+ ],+ )+ def test_child_rows_carry_their_parent_id(+ self,+ endpoint: str,+ script: dict[str, list[ScriptedResponse]],+ parent_key: str,+ expected_rows: list[tuple[int, int]],+ ) -> None:+ result = _run(endpoint, route(script))++ assert result.raised is None+ assert [(row[parent_key], row["id"]) for row in result.rows] == expected_rows+++class TestEvents:+ @pytest.mark.parametrize(+ "inputs, expected_since",+ [+ ({}, "2000-01-01T00:00:00Z"),+ (+ {"incremental_field": "eventTimestamp", "db_incremental_field_last_value": "2026-03-02T10:20:00Z"},+ "2026-03-02T09:20:00Z",+ ),+ ],+ )+ def test_walks_the_stream_until_no_more_events(self, inputs: dict[str, Any], expected_since: str) -> None:+ result = _run(+ "events",+ [+ _events(["a", "b"], next_position="pos-2", more_available=True),+ # The stream always returns a next position; moreAvailable=false ends the walk.+ _events(["c"], next_position="pos-3", more_available=False),+ ],+ **inputs,+ )++ assert result.raised is None+ assert [row["eventId"] for row in result.rows] == ["a", "b", "c"]+ # The API takes exactly one of `since` and `streamPosition`.+ assert result.params("since") == [expected_since, None]+ assert result.params("streamPosition") == [None, "pos-2"]+ assert result.params("maxCount") == [str(EVENTS_MAX_COUNT)] * 2+ assert result.saved_states == [SmartsheetResumeConfig(stream_position="pos-2")]++ def test_resumes_from_saved_stream_position(self) -> None:+ result = _run(+ "events",+ [_events(["d"], next_position="pos-5", more_available=False)],+ resume_state=SmartsheetResumeConfig(stream_position="pos-4"),+ )++ assert result.raised is None+ assert result.params("streamPosition") == ["pos-4"]+ assert result.params("since") == [None]++class TestSmartsheetSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint) -> None:@@ -70,7 +238,7 @@ class TestSmartsheetSourceResponse:assert response is not Noneassert response.name == endpointassert response.primary_keys == expected_keys- assert response.sort_mode == "asc"+ assert response.sort_mode == config.sort_modeif config.partition_key:assert response.partition_mode == "datetime"assert response.partition_format == "week"@@ -81,9 +249,9 @@ class TestSmartsheetSourceResponse:@pytest.mark.parametrize("config", list(SMARTSHEET_ENDPOINTS.values()))def test_partition_keys_are_stable_creation_fields(self, config) -> None:- # Never partition on a mutable field like modifiedAt.+ # Never partition on a mutable field like modifiedAt. An event's timestamp never changes.if config.partition_key:- assert config.partition_key == "createdAt"+ assert config.partition_key in ("createdAt", "eventTimestamp")class TestValidateCredentials: