: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 anvil submissions, signers and log event tables (#116118)
Tom Owers63315a6ca751
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 e4798f83a893..1dfca85e43c4 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@@ -572,11 +572,11 @@ Today (5): `casts`, `etch_packets`, `organizations`, `weld_datas`, `welds`Diffed against: <https://www.useanvil.com/docs/api/graphql/reference/>-- [ ] `Submissions (GraphQL weldData(eid) { submissions })` — provides form answers and completion times missing from workflow submission summaries (high)+- [x] `Submissions (GraphQL weldData(eid) { submissions })` — provides form answers and completion times missing from workflow submission summaries (high)- [ ] `Organization users (GraphQL organization(organizationEid) { organizationUsers { user } })` — provides staff identities, roles, and membership dates for activity attribution (medium)-- [ ] `Etch log events (GraphQL etchPacket(eid) { etchLogEvents }; weldData(eid) { etchLogEvents })` — tracks signing, viewing, downloading, and voiding events for document completion analysis (medium)-- [ ] `WeldData log events (GraphQL weldData(eid) { weldDataLogEvents })` — tracks form activity and workflow progress beyond the latest status (medium)-- [ ] `Workflow signers (GraphQL weldData(eid) { documentGroup { signers } })` — measures signer completion and delays for workflows that require signatures (medium)+- [x] `Etch log events (GraphQL etchPacket(eid) { etchLogEvents }; weldData(eid) { etchLogEvents })` — tracks signing, viewing, downloading, and voiding events for document completion analysis (medium)+- [x] `WeldData log events (GraphQL weldData(eid) { weldDataLogEvents })` — tracks form activity and workflow progress beyond the latest status (medium)+- [x] `Workflow signers (GraphQL weldData(eid) { documentGroup { signers } })` — measures signer completion and delays for workflows that require signatures (medium)Note: Read the complete official GraphQL reference and compared query fields and nested lists with the source's selections. The linked SDL endpoint returned no usable schema. Packet signers already occur inside etch_packets, while workflow signers and event lists need requests for each WeldData or packet. Webhook logs, form configuration, file uploads, and signer tokens were excluded.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.pyindex d76257ceb70e..047b33da3c90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py@@ -1,3 +1,4 @@+import functoolsimport dataclassesfrom collections.abc import Callable, Iteratorfrom typing import Any@@ -10,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settANVIL_GRAPHQL_URL,PAGE_SIZE,AnvilEndpointConfig,+ AnvilNestedList,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (DEFAULT_RETRY,@@ -212,9 +214,9 @@ def _list_organization_eids(execute: _Execute) -> list[str]:return [organization["eid"] for organization in organizations if organization.get("eid")]-def _list_weld_eids(execute: _Execute, logger: FilteringBoundLogger) -> list[str]:+def _list_weld_eids(execute: _Execute, organization_eids: list[str], logger: FilteringBoundLogger) -> list[str]:weld_eids: list[str] = []- for organization_eid in _list_organization_eids(execute):+ for organization_eid in organization_eids:pages = _iter_pages(execute,_build_organization_page_query("welds", "eid"),@@ -239,6 +241,7 @@ def _get_parent_paged_rows(resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],logger: FilteringBoundLogger,context_label: str,+ to_rows: Callable[[list[dict[str, Any]]], list[dict[str, Any]]] | None = None,) -> Iterator[list[dict[str, Any]]]:"""Walk one page walk per parent, tagging each row with the parent it came from.@@ -264,9 +267,13 @@ def _get_parent_paged_rows(logger,f"{context_label} {parent_eid}",):- rows = [{**item, variable_name: parent_eid} for item in items]+ rows = [{**item, variable_name: parent_eid} for item in (to_rows(items) if to_rows else items)]if rows:yield rows+ else:+ # Nested child lists are often empty for a whole page; the staged bookmark still+ # points at this page, so handing off here loses no rows.+ resumable_source_manager.safe_point()# Save AFTER yielding (and only when more pages remain) so a crash re-yields the# last page rather than skipping it; merge dedupes on the primary key.if next_offset:@@ -278,6 +285,83 @@ def _get_parent_paged_rows(resumable_source_manager.save_state(AnvilResumeConfig(next_offset=None, parent_eid=remaining[index + 1]))+def _nest_selection(path: tuple[str, ...], item_fields: str) -> str:+ selection = item_fields+ for name in reversed(path):+ selection = f"{name} {{\n{selection}\n}}"+ return f"eid\n{selection}"+++def _nested_rows(items: list[dict[str, Any]], nested: AnvilNestedList) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for item in items:+ children: Any = item+ for name in nested.path:+ children = children.get(name) if isinstance(children, dict) else None+ for child in children or []:+ rows.append({**child, nested.parent_key: item.get("eid")})+ return rows+++def _get_nested_rows(+ execute: _Execute,+ config: AnvilEndpointConfig,+ resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ organization_eids = _list_organization_eids(execute)+ weld_eids = (+ _list_weld_eids(execute, organization_eids, logger)+ if any(nested.parent == "weld_datas" for nested in config.nested_lists)+ else []+ )++ def walk(nested: AnvilNestedList) -> Iterator[list[dict[str, Any]]]:+ item_fields = _nest_selection(nested.path, config.item_fields)+ to_rows = functools.partial(_nested_rows, nested=nested)+ if nested.parent == "weld_datas":+ return _get_parent_paged_rows(+ execute,+ _build_weld_datas_query(item_fields),+ weld_eids,+ "weldEid",+ lambda data: (data.get("weld") or {}).get("weldDatas"),+ resumable_source_manager,+ logger,+ "weld",+ to_rows,+ )+ return _get_parent_paged_rows(+ execute,+ _build_organization_page_query("etchPackets", item_fields),+ organization_eids,+ "organizationEid",+ lambda data: (data.get("organization") or {}).get("etchPackets"),+ resumable_source_manager,+ logger,+ "organization",+ to_rows,+ )++ walks = [+ (nested, weld_eids if nested.parent == "weld_datas" else organization_eids) for nested in config.nested_lists+ ]++ # Organization and weld eids never collide, so the bookmarked parent identifies which walk+ # to resume; earlier walks already finished.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start = 0+ if resume is not None and resume.parent_eid is not None:+ start = next((index for index, (_, parents) in enumerate(walks) if resume.parent_eid in parents), 0)++ for index in range(start, len(walks)):+ nested, parent_eids = walks[index]+ if index > start and parent_eids:+ # Move the bookmark into this walk so a crash here doesn't repeat the previous one.+ resumable_source_manager.save_state(AnvilResumeConfig(next_offset=None, parent_eid=parent_eids[0]))+ yield from walk(nested)++def get_rows(api_key: str,endpoint: str,@@ -290,11 +374,15 @@ def get_rows(def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:return _execute(session, query, variables, logger)+ if config.nested_lists:+ yield from _get_nested_rows(execute, config, resumable_source_manager, logger)+ return+if config.fan_out_weld_datas:yield from _get_parent_paged_rows(execute,_build_weld_datas_query(config.item_fields),- _list_weld_eids(execute, logger),+ _list_weld_eids(execute, _list_organization_eids(execute), logger),"weldEid",lambda data: (data.get("weld") or {}).get("weldDatas"),resumable_source_manager,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.pyindex 499c4138ba31..18b4d0dc05c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py@@ -119,4 +119,74 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"embeddedAt": "Timestamp when the packet was embedded in an external app.",},},+ "submissions": {+ "description": "A submission holds one webform's progress within a workflow submission. Form answers are not synced.",+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-Submission",+ "columns": {+ "eid": "Unique identifier of the submission.",+ "weldDataEid": "Identifier of the workflow submission (weld data) the webform submission belongs to.",+ "weldEid": "Identifier of the workflow the submission belongs to.",+ "status": "Status of the submission: created, in-progress, waiting-to-sign, user-signed-and-waiting, users-turn-to-sign-ui, users-turn-to-sign-email, someone-else-signed-and-waiting, or completed.",+ "currentStep": "The webform step the user is on.",+ "totalSteps": "Number of steps in the webform.",+ "completionPercentage": "How complete the webform is, between 0 and 1.",+ "isExcluded": "Whether the webform is excluded from the workflow submission.",+ "touchedByUser": "Whether a user has interacted with the webform.",+ "forge": "The webform (forge) this submission fills, with its eid and name.",+ "signer": "The signer associated with the submission, for signers who sign at the end of a workflow.",+ "createdAt": "Timestamp when the submission was created.",+ "updatedAt": "Timestamp when the submission was last updated.",+ "completedAt": "Timestamp when the webform was completed.",+ },+ },+ "workflow_signers": {+ "description": "A signer of a workflow submission that was sent out for signature.",+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-Signer",+ "columns": {+ "eid": "Unique identifier of the signer.",+ "weldDataEid": "Identifier of the workflow submission (weld data) the signer signs.",+ "weldEid": "Identifier of the workflow the submission belongs to.",+ "aliasId": "The signer's user-specified id.",+ "status": "Signing status: sent, viewed, delivered, voided, autoresponded, faxpending, created, skipped, pending, ignored, declined, idCheckFailed, or completed.",+ "provider": "The e-signature provider: etch or docusign.",+ "name": "Name of the signer.",+ "email": "Email address of the signer.",+ "routingOrder": "Step in the signing process where this signer signs. Signers are routed in sorted order.",+ "signatureExperience": "The inferred signing experience: signBeforeReviewing, signWhileReviewing, formCompletionOnly, or acknowledgeOnly.",+ "signActionType": "How the signer signs: email, embedded, or in-person.",+ "clientUserId": "Your id for the person signing, used to trace the signer back to a user in your system.",+ "createdAt": "Timestamp when the signer was created.",+ "updatedAt": "Timestamp when the signer was last updated.",+ "completedAt": "Timestamp when the signer finished signing.",+ },+ },+ "weld_data_log_events": {+ "description": "One action a user took while filling a webform within a workflow, such as viewing, saving, or completing it.",+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-WeldDataLog",+ "columns": {+ "eid": "Unique identifier of the log event.",+ "weldDataEid": "Identifier of the workflow submission (weld data) the event belongs to.",+ "weldEid": "Identifier of the workflow the submission belongs to.",+ "action": "The action taken, e.g. accessed, saved-form, completed, signed, download-files-zip, or voided.",+ "user": "The Anvil user who took the action, if applicable.",+ "submission": "The webform submission the action relates to, if applicable.",+ "createdAt": "Timestamp when the action was taken.",+ },+ },+ "etch_log_events": {+ "description": "One action taken during signing, such as viewing, signing, downloading, or voiding, on an e-signature packet or a workflow submission.",+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-EtchLog",+ "columns": {+ "eid": "Unique identifier of the log event.",+ "etchPacketEid": "Identifier of the e-signature packet the event belongs to; null for workflow events.",+ "organizationEid": "Identifier of the organization the packet belongs to; null for workflow events.",+ "weldDataEid": "Identifier of the workflow submission (weld data) the event belongs to; null for packet events.",+ "weldEid": "Identifier of the workflow the submission belongs to; null for packet events.",+ "action": "The action taken, e.g. accessed, signed, completed, download-file-individual, emailed, or voided.",+ "fileId": "Identifier, often a filename, of the file the action relates to.",+ "user": "The Anvil user who took the action, if applicable.",+ "signer": "The signer who took the action, if applicable.",+ "createdAt": "Timestamp when the action was taken.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.pyindex cfcd09c110a7..a5df5888d032 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py@@ -1,4 +1,5 @@from dataclasses import dataclass, field+from typing import Literalfrom products.warehouse_sources.backend.types import IncrementalField@@ -90,7 +91,23 @@ archivedAtembeddedAt"""-_ETCH_PACKET_ITEM_FIELDS = """+_SIGNER_ITEM_FIELDS = """+eid+aliasId+status+provider+name+routingOrder+signatureExperience+signActionType+clientUserId+createdAt+updatedAt+completedAt+"""++_ETCH_PACKET_ITEM_FIELDS = f"""eidnamestatus@@ -105,7 +122,7 @@ archivedAtcompletedAtsentAtembeddedAt-documentGroup {+documentGroup {{eidstatusprovider@@ -113,25 +130,72 @@ currentRoutingStepcreatedAtupdatedAtcompletedAt-signers {+signers {{+{_SIGNER_ITEM_FIELDS}+}}+}}+"""++_SUBMISSION_ITEM_FIELDS = """eid-aliasIdstatus-provider+currentStep+totalSteps+completionPercentage+isExcluded+touchedByUser+forge {+eidname-routingOrder-signatureExperience-signActionType-clientUserId+}+signer {+eid+}createdAtupdatedAtcompletedAt+"""++# Log `metadata` and the actor's location are free-form and can carry personal data, so+# events keep only what happened, when, and which object ids were involved.+_WELD_DATA_LOG_EVENT_ITEM_FIELDS = """+eid+action+user {+eid+}+submission {+eid}+createdAt+"""++_ETCH_LOG_EVENT_ITEM_FIELDS = """+eid+action+fileId+user {+eid+}+signer {+eid}+createdAt"""+@dataclass(frozen=True)+class AnvilNestedList:+ # Paged parent walk whose items carry the child list. Anvil exposes these children only as+ # unpaginated lists on a single parent, so selecting them inside the parent page avoids a+ # request per parent.+ parent: Literal["weld_datas", "etch_packets"]+ # Path from a parent item to the child list, e.g. ("documentGroup", "signers").+ path: tuple[str, ...]+ # Column stamped onto each child row with its parent item's eid.+ parent_key: str++@dataclass(frozen=True)class AnvilEndpointConfig:# GraphQL selection for one row of this endpoint.@@ -141,6 +205,8 @@ class AnvilEndpointConfig:organization_page_field: str | None = None# Fan out one `weld(eid: ...) { weldDatas }` page walk per weld across every organization.fan_out_weld_datas: bool = False+ # Child lists read from inside parent pages; walked in order when there is more than one.+ nested_lists: tuple[AnvilNestedList, ...] = ()# Anvil eids are 20-character object identifiers unique across their system, so a row's# own eid is a table-wide key even for fan-out children.primary_keys: list[str] = field(default_factory=lambda: ["eid"])@@ -178,6 +244,37 @@ ANVIL_ENDPOINTS: dict[str, AnvilEndpointConfig] = {organization_page_field="etchPackets",description="E-signature packets with their signer status, fetched per organization",),+ "submissions": AnvilEndpointConfig(+ item_fields=_SUBMISSION_ITEM_FIELDS,+ nested_lists=(AnvilNestedList(parent="weld_datas", path=("submissions",), parent_key="weldDataEid"),),+ description=(+ "Webform submissions within each workflow submission, with their step progress and completion "+ "times. Form answers are not synced"+ ),+ ),+ "workflow_signers": AnvilEndpointConfig(+ item_fields=_SIGNER_ITEM_FIELDS,+ nested_lists=(+ AnvilNestedList(parent="weld_datas", path=("documentGroup", "signers"), parent_key="weldDataEid"),+ ),+ description="Signers of each workflow submission sent for signature, with their signing status",+ ),+ "weld_data_log_events": AnvilEndpointConfig(+ item_fields=_WELD_DATA_LOG_EVENT_ITEM_FIELDS,+ nested_lists=(AnvilNestedList(parent="weld_datas", path=("weldDataLogEvents",), parent_key="weldDataEid"),),+ description="Actions taken while filling workflow webforms, such as views, saves, and completions",+ ),+ "etch_log_events": AnvilEndpointConfig(+ item_fields=_ETCH_LOG_EVENT_ITEM_FIELDS,+ nested_lists=(+ AnvilNestedList(parent="etch_packets", path=("etchLogEvents",), parent_key="etchPacketEid"),+ AnvilNestedList(parent="weld_datas", path=("etchLogEvents",), parent_key="weldDataEid"),+ ),+ description=(+ "Signing actions on e-signature packets and workflow submissions, such as views, signatures, "+ "downloads, and voids"+ ),+ ),}ENDPOINTS = tuple(ANVIL_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.pyindex 5d062ff2f933..8fb7527471f3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py@@ -55,7 +55,7 @@ class AnvilSource(ResumableSource[AnvilSourceConfig, AnvilResumeConfig]):category=DataWarehouseSourceCategory.SALES,label="Anvil",keywords=["useanvil.com", "e-signature", "pdf"],- caption="""Sync metadata about your Anvil documents into the PostHog Data warehouse: organizations, PDF templates (casts), workflows (welds), workflow submissions, and e-signature packets with their signer status.+ caption="""Sync metadata about your Anvil documents into the PostHog Data warehouse: organizations, PDF templates (casts), workflows (welds), workflow submissions with their webforms and signers, e-signature packets with their signer status, and form and signing activity logs.Create an API key in your Anvil organization settings, under API settings. Development keys are rate limited to 4 requests per second, so large accounts sync faster with a production key.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.pyindex 5bc9f886ad6f..6385d9aeaf22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvi_build_organization_page_query,_build_weld_datas_query,_execute,+ _nest_selection,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import ANVIL_ENDPOINTS, ENDPOINTS@@ -182,6 +183,68 @@ class TestWeldDatasFanOut:assert [(state.next_offset, state.parent_eid) for state in result.saved_states] == [(2, "w1"), (None, "w2")]+class TestNestedListEndpoints:+ @pytest.mark.parametrize(+ "endpoint,parent_item",+ [+ ("submissions", {"submissions": [{"eid": "s1"}]}),+ ("workflow_signers", {"documentGroup": {"signers": [{"eid": "s1"}]}}),+ ("weld_data_log_events", {"weldDataLogEvents": [{"eid": "s1"}]}),+ ],+ )+ def test_flattens_children_of_weld_datas_and_skips_parents_without_any(+ self, endpoint: str, parent_item: dict[str, Any]+ ) -> None:+ result = _driver().run(+ endpoint,+ [+ _org_eids("o1"),+ _org_page("welds", [{"eid": "w1"}]),+ _weld_datas_page(+ [+ {"eid": "d1", **parent_item},+ {"eid": "d2", "submissions": None, "documentGroup": None, "weldDataLogEvents": []},+ ],+ page=1,+ page_count=2,+ ),+ _weld_datas_page([{"eid": "d3", "documentGroup": None}], page=2, page_count=2),+ ],+ )++ assert result.raised is None+ assert result.rows == [{"eid": "s1", "weldDataEid": "d1", "weldEid": "w1"}]+ assert [request.json()["variables"].get("offset") for request in result.requests[2:]] == [None, 2]++ @pytest.mark.parametrize(+ "resume_state,expected_parents",+ [+ (None, ["o1", "w1"]),+ # A bookmark in the weld walk means the packet walk already finished.+ (AnvilResumeConfig(next_offset=None, parent_eid="w1"), ["w1"]),+ ],+ )+ def test_etch_log_events_walk_packets_then_weld_datas(+ self, resume_state: AnvilResumeConfig | None, expected_parents: list[str]+ ) -> None:+ packet_rows = [{"eid": "e1", "etchPacketEid": "p1", "organizationEid": "o1"}]+ weld_rows = [{"eid": "e2", "weldDataEid": "d1", "weldEid": "w1"}]+ responses = [_org_eids("o1"), _org_page("welds", [{"eid": "w1"}])]+ if resume_state is None:+ responses.append(_org_page("etchPackets", [{"eid": "p1", "etchLogEvents": [{"eid": "e1"}]}]))+ responses.append(_weld_datas_page([{"eid": "d1", "etchLogEvents": [{"eid": "e2"}]}]))++ result = _driver().run("etch_log_events", responses, resume_state=resume_state)++ assert result.raised is None+ assert result.rows == (packet_rows if resume_state is None else []) + weld_rows+ walked = [+ request.json()["variables"].get("weldEid") or request.json()["variables"]["organizationEid"]+ for request in result.requests[2:]+ ]+ assert walked == expected_parents++class TestQueryDocuments:@pytest.mark.parametrize("endpoint",@@ -196,6 +259,16 @@ class TestQueryDocuments:assert declaration in queryassert f"{config.organization_page_field}(limit: $limit, offset: $offset)" in query+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if ANVIL_ENDPOINTS[name].nested_lists])+ def test_nested_list_selection_is_balanced_and_reaches_the_child_list(self, endpoint):+ config = ANVIL_ENDPOINTS[endpoint]+ for nested in config.nested_lists:+ selection = _nest_selection(nested.path, config.item_fields)+ query = _build_weld_datas_query(selection)++ assert query.count("{") == query.count("}")+ assert " {\n".join(nested.path) + " {\n" in selection+def test_weld_datas_query_declares_its_variables(self):query = _build_weld_datas_query(ANVIL_ENDPOINTS["weld_datas"].item_fields)