: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 Sim source (#117409)
Tom Owersb686ef8d0126
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 eb4cc4f72834..74907a5a0b82 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@@ -10990,10 +10990,10 @@ Today (2): `logs`, `workflows`Diffed against: <https://docs.sim.ai/openapi.json>-- [ ] `List Workflow Versions (GET /api/v2/workflows/{workflowId}/versions)` — resolve deploymentVersionId in execution logs and compare failures across deployment versions (high)-- [ ] `List Workspaces (GET /api/v2/workspaces)` — resolve workspaceId in workflows and compare automation activity across workspaces (high)-- [ ] `List Tables and List Rows (GET /api/v2/tables; GET /api/v2/tables/{tableId}/rows)` — analyze records created by automation, including enrichment outcomes attached to table rows (high)-- [ ] `List Organization Usage Events (GET /api/v2/organizations/{organizationId}/usage/events)` — measure credit consumption across workflows, chat, and other usage sources (high)+- [x] `List Workflow Versions (GET /api/v2/workflows/{workflowId}/versions)` — resolve deploymentVersionId in execution logs and compare failures across deployment versions (high)+- [x] `List Workspaces (GET /api/v2/workspaces)` — resolve workspaceId in workflows and compare automation activity across workspaces (high)+- [x] `List Tables and List Rows (GET /api/v2/tables; GET /api/v2/tables/{tableId}/rows)` — analyze records created by automation, including enrichment outcomes attached to table rows (high)+- [x] `List Organization Usage Events (GET /api/v2/organizations/{organizationId}/usage/events)` — measure credit consumption across workflows, chat, and other usage sources (high)- [ ] `List Billing Logs (GET /api/v2/billing/logs)` — reconcile credit charges with automation activity over time (medium)- [ ] `List Audit Logs (GET /api/v2/audit-logs)` — track changes to workflows and workspace resources for governance analysis (medium)- [ ] `List Workspace Members (GET /api/v2/workspaces/{workspaceId}/members)` — analyze workspace membership and inherited organization access (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/canonical_descriptions.pyindex e6fea58d1a06..d9562e3ab4f8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/canonical_descriptions.py@@ -28,4 +28,73 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"cost": "Total execution cost in USD, or null when no cost is recorded.",},},+ "workflow_versions": {+ "description": "Immutable deployment versions of each workflow in the workspace.",+ "docs_url": "https://docs.sim.ai/api-reference/workflows/listWorkflowVersionsV2",+ "columns": {+ "id": "Unique deployment-version identifier. Matches deploymentVersionId in execution logs.",+ "workflowId": "Workflow that owns the deployment version.",+ "version": "Monotonically increasing deployment version number.",+ "name": "Optional deployment-version label.",+ "description": "Optional deployment-version release note.",+ "isActive": "Whether this version is currently serving executions.",+ "createdAt": "Timestamp when this version was created.",+ "deployedBy": "Display name of the user who created the deployment, when available.",+ "latestOperationStatus": "Latest lifecycle-operation status for this version.",+ },+ },+ "workspaces": {+ "description": "Active workspaces available to the API key.",+ "docs_url": "https://docs.sim.ai/api-reference/workspaces/listWorkspaces",+ "columns": {+ "id": "Unique workspace identifier.",+ "name": "Workspace display name.",+ "color": "Workspace color as a hexadecimal color value.",+ "logoUrl": "Workspace logo URL, or null when none is configured.",+ "memberCount": "Number of effective members, including inherited organization administrators.",+ "createdAt": "Timestamp when the workspace was created.",+ "updatedAt": "Timestamp when the workspace was last updated.",+ },+ },+ "tables": {+ "description": "Active Sim tables in the workspace, with their column schema.",+ "docs_url": "https://docs.sim.ai/api-reference/tables/listTables",+ "columns": {+ "id": "Unique table identifier.",+ "name": "Table name.",+ "description": "Table description, or null when none is set.",+ "ownerEmail": "Current email address of the table owner.",+ "schema": "Typed table schema with the column definitions.",+ "rowCount": "Current number of rows in the table.",+ "maxRows": "Maximum rows allowed by the workspace plan.",+ "folderPath": "Canonical slash-prefixed folder path.",+ "createdAt": "Timestamp when the table was created.",+ "updatedAt": "Timestamp when the table was last modified.",+ },+ },+ "table_rows": {+ "description": "Rows of every active Sim table in the workspace.",+ "docs_url": "https://docs.sim.ai/api-reference/tables/listTableRows",+ "columns": {+ "id": "Unique row identifier.",+ "tableId": "Table that owns the row.",+ "data": "User-defined row cells keyed by column name.",+ "createdAt": "Timestamp when the row was created.",+ "updatedAt": "Timestamp when the row was last modified.",+ },+ },+ "usage_events": {+ "description": "Organization usage events with the credits each event consumed.",+ "docs_url": "https://docs.sim.ai/api-reference/organizations/listOrganizationUsageEvents",+ "columns": {+ "id": "Usage event identifier.",+ "organizationId": "Organization that recorded the usage.",+ "createdAt": "When the usage event was recorded.",+ "source": "Product surface that recorded the usage, such as workflow or sim-chat.",+ "description": "Usage event description, such as a model name.",+ "workflowName": "Workflow name, or null for non-workflow usage or a deleted workflow.",+ "credits": "Credits consumed by this event, rounded to whole credits.",+ "hasCost": "Whether the event consumed credits before rounding, including sub-credit usage.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/settings.pyindex dec58f86d0c0..fc4403c9434b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/settings.py@@ -1,22 +1,111 @@+from dataclasses import field+from posthog.dataclasses import frozen-from products.warehouse_sources.backend.types import IncrementalField+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++PAGE_SIZE = 100+# Sim rejects a custom usage window longer than 92 calendar days.+USAGE_WINDOW_DAYS = 90@frozenclass SimEndpoint:+ name: strpath: str- primary_key: str+ primary_keys: tuple[str, ...]partition_key: str- sort_field: str+ sort_field: str | None = "createdAt"+ workspace_scoped: bool = True+ page_size: int = PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = NoneENDPOINTS: dict[str, SimEndpoint] = {- "workflows": SimEndpoint(path="workflows", primary_key="id", partition_key="createdAt", sort_field="createdAt"),- "logs": SimEndpoint(path="logs", primary_key="runId", partition_key="startedAt", sort_field="startedAt"),+ "workflows": SimEndpoint(name="workflows", path="workflows", primary_keys=("id",), partition_key="createdAt"),+ "logs": SimEndpoint(+ name="logs", path="logs", primary_keys=("runId",), partition_key="startedAt", sort_field="startedAt"+ ),+ "workflow_versions": SimEndpoint(+ name="workflow_versions",+ path="workflows/{workflow_id}/versions",+ primary_keys=("workflowId", "id"),+ partition_key="createdAt",+ sort_field=None,+ workspace_scoped=False,+ fanout=DependentEndpointConfig(+ parent_name="workflows",+ resolve_param="workflow_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "workflowId"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ ),+ "workspaces": SimEndpoint(+ name="workspaces", path="workspaces", primary_keys=("id",), partition_key="createdAt", workspace_scoped=False+ ),+ "tables": SimEndpoint(name="tables", path="tables", primary_keys=("id",), partition_key="createdAt"),+ "table_rows": SimEndpoint(+ name="table_rows",+ path="tables/{table_id}/rows",+ primary_keys=("tableId", "id"),+ partition_key="createdAt",+ sort_field=None,+ page_size=1000,+ fanout=DependentEndpointConfig(+ parent_name="tables",+ resolve_param="table_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "tableId"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ ),+ "usage_events": SimEndpoint(+ name="usage_events",+ path="organizations/{organization_id}/usage/events",+ primary_keys=("organizationId", "id"),+ partition_key="createdAt",+ workspace_scoped=False,+ fanout=DependentEndpointConfig(+ parent_name="organizations",+ resolve_param="organization_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "organizationId"},+ # Usage needs organization admin rights, which a key can hold in only some of its organizations.+ child_response_actions=[{"status_code": 403, "action": "ignore"}],+ ),+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ default_incremental_field="createdAt",+ ),}-# Run status and cost can change after startedAt, and workflows have no timestamp filter.-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}+# Fan-out parents that are not tables of their own.+PARENT_ENDPOINTS: dict[str, SimEndpoint] = {+ "organizations": SimEndpoint(+ name="organizations",+ path="organizations",+ primary_keys=("id",),+ partition_key="createdAt",+ workspace_scoped=False,+ ),+}-PAGE_SIZE = 100+# Run status and cost can change after startedAt, and the other list endpoints have no timestamp filter.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items() if endpoint.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/sim.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/sim.pyindex 3a94eec6fbc7..c19d88d679a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/sim.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/sim.py@@ -1,15 +1,25 @@+import dataclasses+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime, timedeltafrom typing import Any, castfrom requests.exceptions import HTTPErrorfrom 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.rest_source import (RESTAPIConfig,RESTClient,rest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_auth+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 (+ JSONResponseCursorPaginator,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (ClientConfig,Endpoint,@@ -19,16 +29,38 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sim import SimSourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.sim.settings import ENDPOINTS, PAGE_SIZE+from products.warehouse_sources.backend.temporal.data_imports.sources.sim.settings import (+ ENDPOINTS,+ PARENT_ENDPOINTS,+ USAGE_WINDOW_DAYS,+ SimEndpoint,+)++# Page size for listing organizations while validating usage access.+USAGE_PROBE_ORGANIZATIONS = 10AUTH_ERROR = "Your Sim API key is invalid or expired. Create a new key in Sim settings and reconnect."PERMISSION_ERROR = "Your Sim API key cannot read this workspace. Check the key's workspace access and permissions."WORKSPACE_ERROR = "Sim could not find this workspace. Check the workspace ID and your API key's access."+USAGE_PERMISSION_ERROR = (+ "Sim usage events need a personal API key from an organization admin. Workspace API keys cannot read them."+)++ALL_ENDPOINTS: dict[str, SimEndpoint] = {**ENDPOINTS, **PARENT_ENDPOINTS}+PAGE_EXTRA: Endpoint = {+ "data_selector": "data",+ "data_selector_required": True,+ "paginator": {"type": "cursor", "cursor_path": "nextCursor", "cursor_param": "cursor"},+}@frozenclass SimResumeConfig:- cursor: str+ cursor: str | None = None+ fanout_state: dict[str, Any] | None = None+ # A usage cursor is only valid for the window it was issued for, so a resumed run reuses that window.+ start_date: str | None = None+ end_date: str | None = Nonedef client_config(config: SimSourceConfig, api_version: str) -> ClientConfig:@@ -42,19 +74,22 @@ def client_config(config: SimSourceConfig, api_version: str) -> ClientConfig:}-def get_endpoint(config: SimSourceConfig, name: str, page_size: int = PAGE_SIZE) -> Endpoint:- endpoint = schema_for_resource(ENDPOINTS, name)+def endpoint_filters(config: SimSourceConfig, endpoint: SimEndpoint) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if endpoint.workspace_scoped:+ params["workspaceId"] = config.workspace_id+ if endpoint.sort_field:+ params["sortBy"] = endpoint.sort_field+ params["sortOrder"] = "asc"+ return params+++def get_endpoint(config: SimSourceConfig, name: str, page_size: int | None = None) -> Endpoint:+ endpoint = schema_for_resource(ALL_ENDPOINTS, name)return {"path": endpoint.path,- "params": {- "workspaceId": config.workspace_id,- "limit": page_size,- "sortBy": endpoint.sort_field,- "sortOrder": "asc",- },- "data_selector": "data",- "data_selector_required": True,- "paginator": {"type": "cursor", "cursor_path": "nextCursor", "cursor_param": "cursor"},+ "params": {"limit": page_size or endpoint.page_size, **endpoint_filters(config, endpoint)},+ **PAGE_EXTRA,}@@ -67,10 +102,72 @@ def get_resource(config: SimSourceConfig, name: str) -> EndpointResource:}+@frozen+class UsageWindow:+ start: str+ end: str+++def usage_window(inputs: SourceInputs, resume: SimResumeConfig | None) -> UsageWindow:+ if resume is not None and resume.start_date and resume.end_date:+ return UsageWindow(start=resume.start_date, end=resume.end_date)+ end = datetime.now(UTC).date()+ start = end - timedelta(days=USAGE_WINDOW_DAYS)+ last_value = parse_datetime_value(inputs.db_incremental_field_last_value)+ if inputs.should_use_incremental_field and last_value is not None:+ if last_value.date() < start:+ inputs.logger.warning(+ "Sim usage watermark is older than the longest window Sim serves; older events are skipped",+ watermark=last_value.isoformat(),+ window_start=start.isoformat(),+ )+ start = min(max(start, last_value.date()), end)+ return UsageWindow(start=start.isoformat(), end=end.isoformat())+++def _check_usage_access(+ client: RESTClient, endpoint: SimEndpoint, organization_pages: Iterator[Any]+) -> tuple[bool, str | None]:+ # Listing organizations succeeds for any key, but usage needs organization admin rights in at least one of them.+ end = datetime.now(UTC).date()+ start = end - timedelta(days=1)+ found_organization = False+ for page in organization_pages:+ for organization in page:+ if not organization.get("id"):+ continue+ found_organization = True+ try:+ next(+ client.paginate(+ path=endpoint.path.format(organization_id=organization["id"]),+ params={+ "limit": 1,+ "preset": "custom",+ "startDate": start.isoformat(),+ "endDate": end.isoformat(),+ },+ data_selector="data",+ data_selector_required=True,+ )+ )+ except HTTPError as error:+ if error.response is not None and error.response.status_code in (403, 404):+ continue+ raise+ return True, None+ # A key without organizations has no usage to read, so there is nothing to reject.+ return (False, USAGE_PERMISSION_ERROR) if found_organization else (True, None)++def validate_credentials(config: SimSourceConfig, api_version: str, schema_name: str | None = None) -> tuple[bool, str | None]:- endpoint = get_endpoint(config, schema_name or "workflows", page_size=1)+ endpoint = schema_for_resource(ENDPOINTS, schema_name or "workflows")+ # A fan-out table is readable when its parent list is, because the parent ids drive every child request.+ probe_name = endpoint.fanout.parent_name if endpoint.fanout else endpoint.name+ is_usage = endpoint.name == "usage_events"+ probe = get_endpoint(config, probe_name, page_size=USAGE_PROBE_ORGANIZATIONS if is_usage else 1)client_settings = client_config(config, api_version)client = RESTClient(base_url=client_settings["base_url"],@@ -81,20 +178,26 @@ def validate_credentials(allow_redirects=False,)try:- next(- client.paginate(- path=cast(str, endpoint["path"]),- params=endpoint["params"],- data_selector="data",- data_selector_required=True,- )+ pages = client.paginate(+ path=cast(str, probe["path"]),+ params=probe["params"],+ paginator=JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor")+ if is_usage+ else None,+ data_selector="data",+ data_selector_required=True,)+ if is_usage:+ return _check_usage_access(client, endpoint, pages)+ next(pages)except HTTPError as error:status = error.response.status_code if error.response is not None else Noneif status == 401:return False, AUTH_ERRORif status == 403:- return (True, None) if schema_name is None else (False, PERMISSION_ERROR)+ if schema_name is None:+ return True, None+ return False, USAGE_PERMISSION_ERROR if endpoint.name == "usage_events" else PERMISSION_ERRORif status == 404:return False, WORKSPACE_ERRORraise@@ -110,32 +213,65 @@ def sim_source(api_version: str,) -> SourceResponse:endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)- resource_config: RESTAPIConfig = {- "client": client_config(config, api_version),- "resources": [get_resource(config, inputs.schema_name)],- }- initial_state: dict[str, Any] | None = None- if manager.can_resume():- resume = manager.load_state()- if resume is not None:- initial_state = {"cursor": resume.cursor}-- def save_checkpoint(state: dict[str, Any] | None) -> None:- if state and state.get("cursor"):- manager.save_state(SimResumeConfig(cursor=str(state["cursor"])))-- resource = rest_api_resource(- resource_config,- inputs.team_id,- inputs.job_id,- None,- resume_hook=save_checkpoint,- initial_paginator_state=initial_state,- )+ resume = manager.load_state() if manager.can_resume() else None+ window: UsageWindow | None = None++ resource: Iterable[Any]+ if endpoint.fanout is None:++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state and state.get("cursor"):+ manager.save_state(SimResumeConfig(cursor=str(state["cursor"])))++ resource_config: RESTAPIConfig = {+ "client": client_config(config, api_version),+ "resources": [get_resource(config, inputs.schema_name)],+ }+ resource = rest_api_resource(+ resource_config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state={"cursor": resume.cursor} if resume is not None and resume.cursor else None,+ )+ else:+ child_params = endpoint_filters(config, endpoint)+ if endpoint.name == "usage_events":+ window = usage_window(inputs, resume)+ child_params.update(preset="custom", startDate=window.start, endDate=window.end)++ def save_fanout_checkpoint(state: dict[str, Any] | None) -> None:+ manager.save_state(+ SimResumeConfig(+ fanout_state=state,+ start_date=window.start if window else None,+ end_date=window.end if window else None,+ )+ )++ parent = ALL_ENDPOINTS[endpoint.fanout.parent_name]+ resource = build_dependent_resource(+ endpoint_configs=ALL_ENDPOINTS,+ child_endpoint=endpoint.name,+ fanout=dataclasses.replace(+ endpoint.fanout, parent_params=endpoint_filters(config, parent), child_params=child_params+ ),+ client_config=client_config(config, api_version),+ path_format_values={},+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra=PAGE_EXTRA,+ child_endpoint_extra=PAGE_EXTRA,+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=resume.fanout_state if resume is not None else None,+ )+return SourceResponse(name=inputs.schema_name,items=lambda: resource,- primary_keys=[endpoint.primary_key],+ primary_keys=list(endpoint.primary_keys),partition_keys=[endpoint.partition_key],partition_mode="datetime",partition_format="month",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/source.pyindex 1f75c3a524f8..2e9acb321d63 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/source.py@@ -70,7 +70,7 @@ class SimSource(ResumableSource[SimSourceConfig, SimResumeConfig]):api_version: str | None = None,) -> tuple[bool, str | None]:if schema_name is not None and schema_name not in ENDPOINTS:- return False, f"Unknown Sim table: {schema_name}. Select workflows or logs."+ return False, f"Unknown Sim table: {schema_name}. Select one of: {', '.join(ENDPOINTS)}."return validate_sim_credentials(config, self.resolve_api_version(api_version), schema_name)def get_schemas(@@ -82,7 +82,13 @@ class SimSource(ResumableSource[SimSourceConfig, SimResumeConfig]):force_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,+ # usage_window rereads the watermark's whole day, and append does not deduplicate primary keys.+ merge_only=("usage_events",),+ )def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SimResumeConfig]:return ResumableSourceManager(inputs, SimResumeConfig)@@ -105,7 +111,8 @@ class SimSource(ResumableSource[SimSourceConfig, SimResumeConfig]):keywords=["ai agents", "workflow", "automation", "logs"],docsUrl="https://posthog.com/docs/cdp/sources/sim",caption="Create a personal or workspace API key in Sim settings with read access to the workspace. "- "Find the workspace ID in the URL: `https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}`.",+ "Find the workspace ID in the URL: `https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}`. "+ "The usage events table needs a personal API key from an organization admin.",fields=cast(list[FieldType],[diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.pyindex 8e0e2fae09b0..b030bad0b07e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py@@ -1,9 +1,12 @@from collections.abc import Iterable+from datetime import UTC, datetimefrom typing import Any, castimport pytest+import time_machinefrom unittest.mock import MagicMock+import orjsonfrom requests.exceptions import HTTPErrorfrom requests_mock import Mocker@@ -14,6 +17,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.sim.sim import (AUTH_ERROR,PERMISSION_ERROR,+ USAGE_PERMISSION_ERROR,+ USAGE_PROBE_ORGANIZATIONS,WORKSPACE_ERROR,SimResumeConfig,sim_source,@@ -96,14 +101,18 @@ def test_auth_failures_are_terminal(@pytest.mark.parametrize(- "status,schema,expected",+ "status,schema,probe_path,expected",[- (200, None, (True, None)),- (200, "logs", (True, None)),- (401, None, (False, AUTH_ERROR)),- (403, None, (True, None)),- (403, "logs", (False, PERMISSION_ERROR)),- (404, None, (False, WORKSPACE_ERROR)),+ (200, None, "workflows", (True, None)),+ (200, "logs", "logs", (True, None)),+ (401, None, "workflows", (False, AUTH_ERROR)),+ (403, None, "workflows", (True, None)),+ (403, "logs", "logs", (False, PERMISSION_ERROR)),+ (404, None, "workflows", (False, WORKSPACE_ERROR)),+ (200, "workflow_versions", "workflows", (True, None)),+ (403, "table_rows", "tables", (False, PERMISSION_ERROR)),+ (200, "workspaces", "workspaces", (True, None)),+ (403, "usage_events", "organizations", (False, USAGE_PERMISSION_ERROR)),],)def test_credential_probe_maps_status_and_scopes(@@ -111,19 +120,68 @@ def test_credential_probe_maps_status_and_scopes(http: Mocker,status: int,schema: str | None,+ probe_path: str,expected: tuple[bool, str | None],) -> None:- http.get(- f"https://www.sim.ai/api/v2/{schema or 'workflows'}", status_code=status, json={"data": [], "nextCursor": None}- )+ http.get(f"https://www.sim.ai/api/v2/{probe_path}", status_code=status, json={"data": [], "nextCursor": None})assert validate_credentials(config, "v2", schema) == expectedassert http.call_count == 1assert http.last_request is not None- assert http.last_request.qs["limit"] == ["1"]- assert http.last_request.qs["workspaceid"] == [config.workspace_id]+ assert http.last_request.qs["limit"] == [str(USAGE_PROBE_ORGANIZATIONS) if schema == "usage_events" else "1"]+ assert http.last_request.qs.get("workspaceid") == (+ None if probe_path in ("workspaces", "organizations") else [config.workspace_id]+ )assert http.last_request.headers["X-API-Key"] == config.api_key+ "usage_statuses,organizations,expected",+ [+ ([403, 403], ["org-a", "org-b"], (False, USAGE_PERMISSION_ERROR)),+ ([403, 200], ["org-a", "org-b"], (True, None)),+ ([200], ["org-a"], (True, None)),+ ([], [], (True, None)),+ ],+)+def test_usage_probe_requires_admin_access_in_one_organization(+ config: SimSourceConfig,+ http: Mocker,+ usage_statuses: list[int],+ organizations: list[str],+ expected: tuple[bool, str | None],+) -> None:+ http.get(+ "https://www.sim.ai/api/v2/organizations",+ json={"data": [{"id": organization} for organization in organizations], "nextCursor": None},+ )+ for organization, status in zip(organizations, usage_statuses, strict=True):+ http.get(+ f"https://www.sim.ai/api/v2/organizations/{organization}/usage/events",+ status_code=status,+ json={"data": [], "nextCursor": None},+ )+ assert validate_credentials(config, "v2", "usage_events") == expected+++def test_usage_probe_searches_every_organization_page(config: SimSourceConfig, http: Mocker) -> None:+ http.get(+ "https://www.sim.ai/api/v2/organizations",+ [+ {"json": {"data": [{"id": "org-a"}], "nextCursor": "page-2"}},+ {"json": {"data": [{"id": "org-b"}], "nextCursor": None}},+ ],+ )+ http.get("https://www.sim.ai/api/v2/organizations/org-a/usage/events", status_code=403, json={})+ http.get("https://www.sim.ai/api/v2/organizations/org-b/usage/events", json={"data": [], "nextCursor": None})+ assert validate_credentials(config, "v2", "usage_events") == (True, None)+++def test_usage_events_is_merge_only(config: SimSourceConfig) -> None:+ schemas = {schema.name: schema for schema in SimSource().get_schemas(config, 1)}+ assert schemas["usage_events"].supports_incremental+ assert not schemas["usage_events"].supports_append++def test_invalid_request_is_not_reported_as_invalid_credentials(config: SimSourceConfig, http: Mocker) -> None:http.get("https://www.sim.ai/api/v2/workflows",@@ -132,3 +190,199 @@ def test_invalid_request_is_not_reported_as_invalid_credentials(config: SimSourc)with pytest.raises(HTTPError):validate_credentials(config, "v2")+++ "table,expected_qs",+ [+ ("workspaces", {"limit": ["100"], "sortby": ["createdat"], "sortorder": ["asc"]}),+ (+ "tables",+ {"limit": ["100"], "sortby": ["createdat"], "sortorder": ["asc"], "workspaceid": ["workspace-example"]},+ ),+ ],+)+def test_top_level_tables_send_only_supported_filters(+ config: SimSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[SimResumeConfig],+ http: Mocker,+ table: str,+ expected_qs: dict[str, list[str]],+) -> None:+ inputs.schema_name = table+ http.get(f"https://www.sim.ai/api/v2/{table}", json={"data": [{"id": "row-1"}], "nextCursor": None})+ assert list(cast(Iterable[Any], sim_source(config, inputs, manager, "v2").items())) == [[{"id": "row-1"}]]+ assert http.last_request is not None+ assert http.last_request.qs == expected_qs+++ "table,parent,child_path,parent_key,child_qs",+ [+ ("workflow_versions", "workflows", "workflows/{}/versions", "workflowId", {"limit": ["100"]}),+ (+ "table_rows",+ "tables",+ "tables/{}/rows",+ "tableId",+ {"limit": ["1000"], "workspaceid": ["workspace-example"]},+ ),+ ],+)+def test_fan_out_walks_child_pages_and_skips_deleted_parents(+ config: SimSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[SimResumeConfig],+ http: Mocker,+ table: str,+ parent: str,+ child_path: str,+ parent_key: str,+ child_qs: dict[str, list[str]],+) -> None:+ inputs.schema_name = table+ http.get(+ f"https://www.sim.ai/api/v2/{parent}",+ [+ {"json": {"data": [{"id": "parent-a"}], "nextCursor": "parent-page-2"}},+ {"json": {"data": [{"id": "parent-deleted"}, {"id": "parent-b"}], "nextCursor": None}},+ ],+ )+ http.get(+ f"https://www.sim.ai/api/v2/{child_path.format('parent-a')}",+ [+ {"json": {"data": [{"id": "shared-id"}], "nextCursor": "child-page-2"}},+ {"json": {"data": [{"id": "a-2"}], "nextCursor": None}},+ ],+ )+ http.get(+ f"https://www.sim.ai/api/v2/{child_path.format('parent-deleted')}",+ status_code=404,+ json={"error": {"code": "NOT_FOUND", "message": "Not found"}},+ )+ http.get(+ f"https://www.sim.ai/api/v2/{child_path.format('parent-b')}",+ json={"data": [{"id": "shared-id"}], "nextCursor": None},+ )+ response = sim_source(config, inputs, manager, "v2")+ rows = [row for page in cast(Iterable[Any], response.items()) for row in page]+ assert [(row[parent_key], row["id"]) for row in rows] == [+ ("parent-a", "shared-id"),+ ("parent-a", "a-2"),+ ("parent-b", "shared-id"),+ ]+ assert response.primary_keys == [parent_key, "id"]+ parent_requests = [r for r in http.request_history if r.path == f"/api/v2/{parent}"]+ assert parent_requests[0].qs["workspaceid"] == ["workspace-example"]+ child_request = next(r for r in http.request_history if r.path == f"/api/v2/{child_path.format('parent-b')}")+ assert child_request.qs == child_qs+++ "should_use_incremental,last_value,expected_start",+ [+ (False, None, "2026-07-17"),+ (False, "2026-10-01T08:00:00Z", "2026-07-17"),+ (True, None, "2026-07-17"),+ (True, "2026-10-01T08:00:00Z", "2026-10-01"),+ (True, datetime(2026, 10, 3, 23, 59, tzinfo=UTC), "2026-10-03"),+ (True, "2026-01-01T00:00:00Z", "2026-07-17"),+ (True, "2026-11-01T00:00:00Z", "2026-10-15"),+ ],+)+def test_usage_events_window_stays_within_vendor_limit(+ config: SimSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[SimResumeConfig],+ http: Mocker,+ should_use_incremental: bool,+ last_value: Any,+ expected_start: str,+) -> None:+ inputs.schema_name = "usage_events"+ inputs.should_use_incremental_field = should_use_incremental+ inputs.db_incremental_field_last_value = last_value+ http.get("https://www.sim.ai/api/v2/organizations", json={"data": [{"id": "org-1"}], "nextCursor": None})+ http.get(+ "https://www.sim.ai/api/v2/organizations/org-1/usage/events",+ json={"data": [{"id": "event-1", "createdAt": "2026-10-14T09:00:00Z"}], "nextCursor": None},+ )+ with time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False):+ response = sim_source(config, inputs, manager, "v2")+ rows = [row for page in cast(Iterable[Any], response.items()) for row in page]+ assert rows == [{"id": "event-1", "createdAt": "2026-10-14T09:00:00Z", "organizationId": "org-1"}]+ assert http.last_request is not None+ assert http.last_request.qs == {+ "limit": ["100"],+ "preset": ["custom"],+ "startdate": [expected_start],+ "enddate": ["2026-10-15"],+ "sortby": ["createdat"],+ "sortorder": ["asc"],+ }+ organizations_request = http.request_history[0]+ assert "workspaceid" not in organizations_request.qs+++def test_usage_events_skip_organizations_without_admin_access(+ config: SimSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[SimResumeConfig],+ http: Mocker,+) -> None:+ inputs.schema_name = "usage_events"+ http.get(+ "https://www.sim.ai/api/v2/organizations",+ json={"data": [{"id": "org-member"}, {"id": "org-admin"}], "nextCursor": None},+ )+ http.get(+ "https://www.sim.ai/api/v2/organizations/org-member/usage/events",+ status_code=403,+ json={"error": {"code": "FORBIDDEN", "message": "Organization admin access required"}},+ )+ http.get(+ "https://www.sim.ai/api/v2/organizations/org-admin/usage/events",+ json={"data": [{"id": "event-1"}], "nextCursor": None},+ )+ rows = [row for page in cast(Iterable[Any], sim_source(config, inputs, manager, "v2").items()) for row in page]+ assert rows == [{"id": "event-1", "organizationId": "org-admin"}]+++def test_usage_events_resume_reuses_saved_window_and_child_cursor(+ config: SimSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[SimResumeConfig],+ redis_client: MagicMock,+ http: Mocker,+) -> None:+ inputs.schema_name = "usage_events"+ redis_client.exists.return_value = 1+ redis_client.get.return_value = orjson.dumps(+ {+ "fanout_state": {+ "completed": ["organizations/org-done/usage/events"],+ "current": "organizations/org-2/usage/events",+ "child_state": {"cursor": "saved-cursor"},+ },+ "start_date": "2026-07-01",+ "end_date": "2026-09-28",+ }+ )+ http.get(+ "https://www.sim.ai/api/v2/organizations",+ json={"data": [{"id": "org-done"}, {"id": "org-2"}], "nextCursor": None},+ )+ http.get(+ "https://www.sim.ai/api/v2/organizations/org-2/usage/events",+ json={"data": [{"id": "event-2"}], "nextCursor": None},+ )+ with time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False):+ response = sim_source(config, inputs, manager, "v2")+ rows = [row for page in cast(Iterable[Any], response.items()) for row in page]+ assert rows == [{"id": "event-2", "organizationId": "org-2"}]+ assert http.last_request is not None+ assert http.last_request.qs["cursor"] == ["saved-cursor"]+ assert http.last_request.qs["startdate"] == ["2026-07-01"]+ assert http.last_request.qs["enddate"] == ["2026-09-28"]+ assert all("org-done" not in request.path for request in http.request_history)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim_source.pyindex 96859522cd40..2847a04a9d13 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim_source.py@@ -19,7 +19,7 @@ def test_unknown_schema_rejected_before_network(source = SimSource()valid, message = source.validate_credentials(config, 1, schema_name="unknown")assert not valid- assert message == "Unknown Sim table: unknown. Select workflows or logs."+ assert message is not None and message.startswith("Unknown Sim table: unknown.")inputs.schema_name = "unknown"with pytest.raises(UnknownResourceError, match="unknown"):source.source_for_pipeline(config, manager, inputs)