: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 safetyculture structures table (#113868)
Tom Owers62a8a0af76a8
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 ae2fa3a3ed73..07d32e68a1d8 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@@ -7479,6 +7479,7 @@ Diffed against: <https://developer.safetyculture.com/reference/thepubservice_fee- [ ] `feed/investigations (plus investigation fields and relationships)` — incident investigation records linked to the issues and actions we sync (medium)- [ ] `feed/assets_maintenance, feed/maintenance_plans, feed/maintenance_programs` — maintenance schedule and status for the assets we already sync (medium)- [ ] `feed/contractor_companies and feed/contractor_company_user_memberships` — contractor org lookup plus its membership join (medium)+- [x] `POST /structures/v1/structures/search` — organization hierarchy nodes (sites and groups) with their custom field values, from the Structures API (medium)Note: SafetyCulture's warehouse-oriented surface is the /feed/\* family, and roughly 30 feed endpoints exist; the connector covers 10 of them (actions, assets, groups, inspection_items, inspections, issues, schedules, sites, templates, users) and none of the assignee, membership, or timeline joins. Also uncovered: feed/schedule_assignees, feed/action_fields, feed/document_types, feed/user_documents, feed/credentials, feed/credential_types, and the separate training-analytics service (lesson attempts, course statistics, survey answers). Static endpoint catalog, no dynamic discovery. feed/template_permissions was excluded as access-control plumbing.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.pyindex 69b91e8fa6f5..1712da3fc50c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py@@ -203,6 +203,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"parent_id": "ID of the parent of this site.",},},+ "structures": {+ "description": "A node in the organization's hierarchy (a site or a group), from the Structures API.",+ "docs_url": "https://developer.safetyculture.com/reference/structuresservice_searchstructures",+ "columns": {+ "structure_uuid": "UUID of the structure.",+ "name": "Display name of the structure.",+ "structure_type": "Structure type identifier. Empty if not categorized.",+ "description": "Free-text description of the structure. Empty if none is set.",+ "direct_member_count": "Number of direct members.",+ "is_dynamic": "True if membership is governed by a rule rather than explicit assignment.",+ "created_at": "When the structure was created.",+ "updated_at": "When the structure was last modified.",+ "parent": "Parent of the structure. Unset for root structures.",+ "ancestors": "Full ancestor chain from root to direct parent, in order. Empty for root structures and for groups.",+ "fields": "Fully-populated field values for the structure, including custom fields.",+ "similarity_score": "Search relevance score, 0.0 to 1.0. Not meaningful for an unfiltered listing.",+ },+ },"schedules": {"description": "A recurring inspection schedule, with its recurrence pattern, template, and site.","docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedschedules",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.pyindex b22b208a2a4a..7d8274fa6ea1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py@@ -2,7 +2,7 @@ import dataclassesfrom datetime import UTC, date, datetimefrom typing import Any, Optional-from requests import Response+from requests import Request, Responsefrom 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 (@@ -10,8 +10,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,JSONResponsePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpointfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.utils import (resolve_request_url,)@@ -25,9 +27,10 @@ SAFETYCULTURE_BASE_URL = "https://api.safetyculture.io"# Cheap feed used to confirm an API token is genuine. Feed access is permission-scoped, so a 403# here still proves the token itself is valid (see `validate_credentials` on the source class).DEFAULT_PROBE_PATH = "/feed/users"+STRUCTURES_PAGE_SIZE = 100 # Documented maximum for Search structures.[email protected](frozen=True)class SafetyCultureResumeConfig:# The next page to fetch, resolved from the API's `metadata.next_page` (the docs forbid# constructing it yourself). It embeds every filter — including `modified_after` on an@@ -35,6 +38,9 @@ class SafetyCultureResumeConfig:# dedupes the re-pulled page on `id`. Historic saves stored a relative path; the paginator# resolves either form against the API host on load.next_page: str | None = None+ # Structures search only: the structure type being walked and the page token within it.+ structure_type_index: int | None = None+ page_token: str | None = Nonedef _format_modified_after(value: Any) -> str:@@ -78,6 +84,62 @@ class SafetyCultureFeedPaginator(JSONResponsePaginator):self._next_url = resolve_request_url(SAFETYCULTURE_BASE_URL, self._next_url)+class SafetyCultureStructuresPaginator(BasePaginator):+ """Walks Search structures once per structure type.++ Every search is scoped to one type, and the page token sits inside the JSON body at+ `params.page.page_token`. When a type's `next_page_token` runs out, the paginator moves on to+ the next type with a fresh first-page request. An empty page or a repeated token also ends a+ type, so a lingering token can never loop forever.+ """++ def __init__(self, structure_types: tuple[str, ...]) -> None:+ super().__init__()+ self._structure_types = structure_types+ self._type_index = 0+ self._page_token: Optional[str] = None+ self._has_next_page = bool(structure_types)++ def init_request(self, request: Request) -> None:+ self._apply(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ body = response.json()+ token = body.get("next_page_token") if isinstance(body, dict) else None+ if data and token and token != self._page_token:+ self._page_token = token+ return+ self._page_token = None+ self._type_index += 1+ self._has_next_page = self._type_index < len(self._structure_types)++ def update_request(self, request: Request) -> None:+ if self._has_next_page:+ self._apply(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if not self._has_next_page:+ return None+ return {"structure_type_index": self._type_index, "page_token": self._page_token}++ def set_resume_state(self, state: dict[str, Any]) -> None:+ index = state.get("structure_type_index")+ if isinstance(index, int) and 0 <= index < len(self._structure_types):+ self._type_index = index+ self._page_token = state.get("page_token") or None++ def _apply(self, request: Request) -> None:+ body = dict(request.json or {})+ params = dict(body.get("params") or {})+ page: dict[str, Any] = {"page_size": STRUCTURES_PAGE_SIZE}+ if self._page_token:+ page["page_token"] = self._page_token+ params["page"] = page+ body["params"] = params+ body["structure_type"] = {"system_structure_type": self._structure_types[self._type_index]}+ request.json = body++def safetyculture_source(api_token: str,endpoint: str,@@ -96,6 +158,27 @@ def safetyculture_source(if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:params["modified_after"] = _format_modified_after(db_incremental_field_last_value)+ endpoint_config: Endpoint+ if config.structure_types:+ # An empty query lists every structure of the type. Field values carry the org's custom+ # structure fields, the main reason to sync structures over the sites and groups feeds.+ endpoint_config = {+ "path": config.path,+ "method": "POST",+ "json": {"params": {"query": "", "include_fields": True}},+ "paginator": SafetyCultureStructuresPaginator(config.structure_types),+ "data_selector": "results",+ }+ else:+ endpoint_config = {+ "path": config.path,+ "params": params,+ "data_selector": "data",+ # A 200 whose body isn't the documented {"metadata", "data": [...]} envelope is+ # treated as transient (a truncating proxy, a flaky gateway) and retried.+ "data_selector_malformed_retryable": True,+ }+rest_config: RESTAPIConfig = {"client": {"base_url": SAFETYCULTURE_BASE_URL,@@ -114,14 +197,7 @@ def safetyculture_source("resources": [{"name": endpoint,- "endpoint": {- "path": config.path,- "params": params,- "data_selector": "data",- # A 200 whose body isn't the documented {"metadata", "data": [...]} envelope is- # treated as transient (a truncating proxy, a flaky gateway) and retried.- "data_selector_malformed_retryable": True,- },+ "endpoint": endpoint_config,}],}@@ -129,14 +205,28 @@ def safetyculture_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 and resume.next_page:+ if config.structure_types:+ if resume is not None and resume.structure_type_index is not None:+ initial_paginator_state = {+ "structure_type_index": resume.structure_type_index,+ "page_token": resume.page_token,+ }+ elif resume is not None and resume.next_page:initial_paginator_state = {"next_url": resume.next_page}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist AFTER a page is yielded and only while a next page remains, so a crash re-fetches# the next page (merge dedupes) rather than skipping it. A null `next_page` (feed end) or an# empty page yields state=None and nothing is saved.- if state and state.get("next_url"):+ if not state:+ return+ if state.get("structure_type_index") is not None:+ resumable_source_manager.save_state(+ SafetyCultureResumeConfig(+ structure_type_index=state["structure_type_index"], page_token=state.get("page_token")+ )+ )+ elif state.get("next_url"):resumable_source_manager.save_state(SafetyCultureResumeConfig(next_page=state["next_url"]))resource = rest_api_resource(@@ -164,9 +254,14 @@ def safetyculture_source()-def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+def check_access(+ api_token: str, path: str = DEFAULT_PROBE_PATH, structure_type: Optional[str] = None+) -> tuple[int, Optional[str]]:"""Probe a single feed to validate the API token.+ With ``structure_type`` set, ``path`` is the Search structures endpoint, which only answers a+ POST scoped to one structure type.+Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for aconnection problem, other HTTP status otherwise."""@@ -175,7 +270,17 @@ def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Oredact_values=(api_token,),)try:- response = session.get(f"{SAFETYCULTURE_BASE_URL}{path}", timeout=15)+ if structure_type:+ response = session.post(+ f"{SAFETYCULTURE_BASE_URL}{path}",+ json={+ "structure_type": {"system_structure_type": structure_type},+ "params": {"page": {"page_size": 1}},+ },+ timeout=15,+ )+ else:+ response = session.get(f"{SAFETYCULTURE_BASE_URL}{path}", timeout=15)except Exception as e:return 0, f"Could not connect to SafetyCulture: {e}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.pyindex 42e9f1f454b9..d71e089a3fb0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py@@ -17,7 +17,7 @@ def _modified_at_incremental_fields() -> list[IncrementalField]:]-@dataclass+@dataclass(frozen=True)class SafetyCultureEndpointConfig:name: strpath: str # Path under https://api.safetyculture.io, e.g. "/feed/inspections"@@ -32,6 +32,9 @@ class SafetyCultureEndpointConfig:# Every data feed row carries a feed-unique `id` (e.g. inspection_items' `id` is the combined# inspection item ID, distinct from the per-template `item_id`).primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Non-empty marks a POST search endpoint scoped to one structure type per request; the sync+ # walks each listed type in turn.+ structure_types: tuple[str, ...] = ()# SafetyCulture Data Feed endpoints (https://developer.safetyculture.com/reference/data-feeds) —@@ -95,6 +98,16 @@ SAFETYCULTURE_ENDPOINTS: dict[str, SafetyCultureEndpointConfig] = {supports_incremental=False,partition_key=None,),+ # Structures API (https://developer.safetyculture.com/reference/structuresservice_searchstructures).+ # Only the built-in site and group types can be enumerated: org-defined structure types have no+ # public listing endpoint. There is no time filter, so it's full refresh only.+ "structures": SafetyCultureEndpointConfig(+ name="structures",+ path="/structures/v1/structures/search",+ supports_incremental=False,+ primary_keys=["structure_uuid"],+ structure_types=("SYSTEM_STRUCTURE_TYPE_SITE", "SYSTEM_STRUCTURE_TYPE_GROUP"),+ ),"schedules": SafetyCultureEndpointConfig(name="schedules",path="/feed/schedules",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.pyindex 4ae7b2ee5798..9cb6880d0e5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py@@ -105,7 +105,12 @@ You can generate an API token under **Account settings → Integrations → Mana) -> tuple[bool, str | None]:if schema_name is not None and schema_name in SAFETYCULTURE_ENDPOINTS:# Per-schema check: the feed this schema syncs must actually be reachable.- status, message = check_access(config.api_token, SAFETYCULTURE_ENDPOINTS[schema_name].path)+ endpoint = SAFETYCULTURE_ENDPOINTS[schema_name]+ status, message = check_access(+ config.api_token,+ endpoint.path,+ endpoint.structure_types[0] if endpoint.structure_types else None,+ )if status == 200:return True, Noneif status in (401, 403):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.pyindex 89aa7292e75c..9d1f00ee0ff1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py@@ -1,3 +1,4 @@+import copyimport jsonfrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -61,7 +62,9 @@ def _make_manager(resume_state: SafetyCultureResumeConfig | None = None) -> mockreturn manager-def _wire(session: mock.MagicMock, responses: Any) -> tuple[list[str], list[dict[str, Any]]]:+def _wire(+ session: mock.MagicMock, responses: Any, bodies: Optional[list[Any]] = None+) -> tuple[list[str], list[dict[str, Any]]]:"""Wire a mock session; capture each request's url and params AT SEND TIME.``request.url``/``request.params`` are mutated in place across pages (the paginator retargets the@@ -74,6 +77,8 @@ def _wire(session: mock.MagicMock, responses: Any) -> tuple[list[str], list[dictdef _prepare(request: Any) -> mock.MagicMock:url_snapshots.append(request.url)param_snapshots.append(dict(request.params or {}))+ if bodies is not None:+ bodies.append(copy.deepcopy(request.json))prepared = mock.MagicMock()prepared.url = request.urlreturn prepared@@ -244,6 +249,87 @@ class TestPagination:manager.save_state.assert_not_called()+def _structures_response(results: list[dict[str, Any]], next_page_token: str = "") -> Response:+ return _response(+ None,+ raw_body={"results": results, "next_page_token": next_page_token, "total_count": len(results)},+ url=f"{BASE_URL}/structures/v1/structures/search",+ )+++def _structures_body(structure_type: str, page_token: Optional[str] = None) -> dict[str, Any]:+ page: dict[str, Any] = {"page_size": 100}+ if page_token:+ page["page_token"] = page_token+ return {+ "params": {"query": "", "include_fields": True, "page": page},+ "structure_type": {"system_structure_type": structure_type},+ }+++class TestStructures:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_walks_each_structure_type_with_body_page_token(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ bodies: list[Any] = []+ urls, _ = _wire(+ session,+ [+ _structures_response([{"structure_uuid": "s1"}], next_page_token="tok-1"),+ _structures_response([{"structure_uuid": "s2"}]),+ # Protobuf JSON drops an empty `results`, so a type with no structures has no key.+ _response(None, raw_body={"next_page_token": ""}),+ ],+ bodies,+ )++ manager = _make_manager()+ rows = _rows(_source("structures", manager))++ assert rows == [{"structure_uuid": "s1"}, {"structure_uuid": "s2"}]+ assert urls == [f"{BASE_URL}/structures/v1/structures/search"] * 3+ assert bodies == [+ _structures_body("SYSTEM_STRUCTURE_TYPE_SITE"),+ _structures_body("SYSTEM_STRUCTURE_TYPE_SITE", "tok-1"),+ _structures_body("SYSTEM_STRUCTURE_TYPE_GROUP"),+ ]+ assert manager.save_state.call_args_list == [+ mock.call(SafetyCultureResumeConfig(structure_type_index=0, page_token="tok-1")),+ mock.call(SafetyCultureResumeConfig(structure_type_index=1, page_token=None)),+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_repeated_page_token_ends_the_structure_type(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ bodies: list[Any] = []+ _wire(+ session,+ [+ _structures_response([{"structure_uuid": "s1"}], next_page_token="tok-1"),+ _structures_response([{"structure_uuid": "s2"}], next_page_token="tok-1"),+ _structures_response([{"structure_uuid": "g1"}]),+ ],+ bodies,+ )++ rows = _rows(_source("structures", _make_manager()))++ assert rows == [{"structure_uuid": "s1"}, {"structure_uuid": "s2"}, {"structure_uuid": "g1"}]+ assert bodies[2] == _structures_body("SYSTEM_STRUCTURE_TYPE_GROUP")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_structure_type_and_token(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ bodies: list[Any] = []+ _wire(session, [_structures_response([{"structure_uuid": "g2"}])], bodies)++ manager = _make_manager(SafetyCultureResumeConfig(structure_type_index=1, page_token="tok-g"))+ rows = _rows(_source("structures", manager))++ assert rows == [{"structure_uuid": "g2"}]+ assert bodies == [_structures_body("SYSTEM_STRUCTURE_TYPE_GROUP", "tok-g")]++class TestErrorHandling:@parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])@mock.patch(SLEEP_PATCH, return_value=None)@@ -325,6 +411,23 @@ class TestCheckAccess:with self._patch_session(response):assert check_access("sc-token") == (expected_status, expected_message)+ def test_structures_probe_posts_a_scoped_search(self) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = MagicMock()+ session.post.return_value = response+ with mock.patch.object(safetyculture, "make_tracked_session", return_value=session):+ assert check_access("sc-token", "/structures/v1/structures/search", "SYSTEM_STRUCTURE_TYPE_SITE") == (+ 200,+ None,+ )+ session.get.assert_not_called()+ assert session.post.call_args.kwargs["json"] == {+ "structure_type": {"system_structure_type": "SYSTEM_STRUCTURE_TYPE_SITE"},+ "params": {"page": {"page_size": 1}},+ }+def test_connection_error_maps_to_zero(self) -> None:with self._patch_session(requests.ConnectionError("boom")):status, message = check_access("sc-token")@@ -338,7 +441,7 @@ class TestSafetyCultureSourceResponse:response = _source(endpoint, _make_manager())config = SAFETYCULTURE_ENDPOINTS[endpoint]assert response.name == endpoint- assert response.primary_keys == ["id"]+ assert response.primary_keys == config.primary_keysassert response.sort_mode == "asc"if config.partition_key:assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.pyindex 2d734a90f0bb..733baa2e9d20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py@@ -64,15 +64,28 @@ class TestSafetyCultureSource:assert is_valid is expected_validassert returned == expected_message- @parameterized.expand([(200, True), (401, False), (403, False)])+ @parameterized.expand(+ [+ ("inspections", 200, True, "/feed/inspections", None),+ ("inspections", 401, False, "/feed/inspections", None),+ ("inspections", 403, False, "/feed/inspections", None),+ ("structures", 200, True, "/structures/v1/structures/search", "SYSTEM_STRUCTURE_TYPE_SITE"),+ ]+ )@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.check_access")def test_validate_credentials_for_schema_probes_that_feed(- self, status: int, expected_valid: bool, mock_check: mock.MagicMock+ self,+ schema_name: str,+ status: int,+ expected_valid: bool,+ expected_path: str,+ expected_structure_type: str | None,+ mock_check: mock.MagicMock,) -> None:mock_check.return_value = (status, None)- is_valid, _ = self.source.validate_credentials(self.config, self.team_id, schema_name="inspections")+ is_valid, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)assert is_valid is expected_valid- mock_check.assert_called_once_with(self.config.api_token, "/feed/inspections")+ mock_check.assert_called_once_with(self.config.api_token, expected_path, expected_structure_type)@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.safetyculture_source"