: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 incremental sync to crisp conversations and messages (#117105)
Daniel RC0d6501f43943
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.pyindex c6fe36d0c978..351ef6660793 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.py@@ -19,6 +19,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"docs_url": "https://docs.crisp.chat/references/rest-api/v1/#get-messages-in-conversation","columns": {"session_id": "The conversation that contains the message.",+ "conversation_updated_at": "The time when Crisp last updated the conversation that contains the message.","fingerprint": "The message identifier within the conversation.","timestamp": "The time when Crisp sent the message.","content": "The message text or structured content for other message types.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.pyindex b9e7397b3109..43e0c639a4c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.py@@ -1,3 +1,4 @@+import dataclassesfrom collections.abc import Callablefrom datetime import UTC, datetimefrom typing import Any@@ -36,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_@frozenclass CrispResumeConfig:paginator_state: dict[str, Any]+ started_at: str | None = Noneclass CrispPathPaginator(PageNumberPaginator):@@ -137,24 +139,51 @@ def endpoint_config(endpoint: CrispEndpoint, website_id: str) -> Endpoint:}-def resource_config(endpoint: CrispEndpoint, website_id: str) -> EndpointResource:+def format_updated_since(value: datetime) -> str:+ utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc.isoformat(timespec="milliseconds").replace("+00:00", "Z")+++def list_params(endpoint: CrispEndpoint, inputs: SourceInputs) -> dict[str, Any]:+ if not (inputs.should_use_incremental_field and endpoint.updated_since_param):+ return dict(endpoint.params)+ params: dict[str, Any] = dict(endpoint.incremental_params)+ if inputs.db_incremental_field_last_value is not None:+ params[endpoint.updated_since_param] = format_updated_since(inputs.db_incremental_field_last_value)+ return params+++def resource_config(endpoint: CrispEndpoint, website_id: str, inputs: SourceInputs) -> EndpointResource:+ config = endpoint_config(endpoint, website_id)+ config["params"] = list_params(endpoint, inputs)return {"name": endpoint.name,"table_name": endpoint.name,"write_disposition": "replace",- "endpoint": endpoint_config(endpoint, website_id),+ "endpoint": config,}-def parent_path_map(field: str) -> Callable[[dict[str, Any]], dict[str, Any]]:- def encode_path(row: dict[str, Any]) -> dict[str, Any]:- return {**row, "_path_id": quote(str(row[field]), safe="")}+def parent_path_map(+ field: str, included: list[str], updated_before: datetime | None = None+) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:+ cutoff_ms = updated_before.timestamp() * 1000 if updated_before is not None else None++ def encode_path(row: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:+ # A resumed attempt skips the conversations that an earlier attempt finished, even when they+ # changed since then. Messages of a conversation that changed after the run started could move+ # the watermark past that change, so the next run reads the conversation instead.+ updated_at = row.get("updated_at")+ if cutoff_ms is not None and isinstance(updated_at, int | float) and updated_at > cutoff_ms:+ return []+ # The fan-out fails on a parent row that lacks an included field.+ return {**dict.fromkeys(included), **row, "_path_id": quote(str(row[field]), safe="")}return encode_pathdef normalize_row(row: dict[str, Any]) -> dict[str, Any]:- for name in ("created_at", "updated_at", "timestamp", "dispatched_at", "waiting_since"):+ for name in ("created_at", "updated_at", "conversation_updated_at", "timestamp", "dispatched_at", "waiting_since"):value = row.get(name)if isinstance(value, int | float) and not isinstance(value, bool):row[name] = datetime.fromtimestamp(value / 1000, tz=UTC)@@ -198,10 +227,19 @@ def crisp_source() -> SourceResponse:settings = schema_for_resource(ENDPOINTS, inputs.schema_name)resume = manager.load_state()+ incremental = inputs.should_use_incremental_field and bool(settings.incremental_fields)+ defer_changed = incremental and settings.fanout is not None+ started_at = (+ datetime.fromisoformat(resume.started_at)+ if resume is not None and resume.started_at is not None+ else datetime.now(UTC)+ )def save_state(state: dict[str, Any] | None) -> None:if state is not None:- manager.save_state(CrispResumeConfig(paginator_state=state))+ manager.save_state(+ CrispResumeConfig(paginator_state=state, started_at=started_at.isoformat() if defer_changed else None)+ )initial_state = resume.paginator_state if resume is not None else Noneif settings.fanout is not None:@@ -217,15 +255,25 @@ def crisp_source(resource = build_dependent_resource(endpoint_configs=ENDPOINTS,child_endpoint=settings.name,- fanout=settings.fanout,+ fanout=dataclasses.replace(settings.fanout, parent_params=list_params(parent, inputs))+ if incremental+ else settings.fanout,client_config=client_config(config, api_version),path_format_values={"website_id": quote(config.website_id, safe="")},team_id=inputs.team_id,job_id=inputs.job_id,- db_incremental_field_last_value=None,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value if incremental else None,+ should_use_incremental_field=incremental,+ incremental_field=inputs.incremental_field,+ # The watermark filters the parent list, so it binds to no child request param.+ incremental_config_factory=lambda _field: None,parent_endpoint_extra=parent_endpoint,child_endpoint_extra=child_endpoint,- parent_data_map=parent_path_map(settings.fanout.resolve_param),+ parent_data_map=parent_path_map(+ settings.fanout.resolve_param,+ settings.fanout.include_from_parent,+ started_at if defer_changed else None,+ ),page_size_param=None,resume_hook=save_state,initial_paginator_state=initial_state,@@ -234,13 +282,13 @@ def crisp_source(else:rest_config: RESTAPIConfig = {"client": client_config(config, api_version),- "resources": [resource_config(settings, config.website_id)],+ "resources": [resource_config(settings, config.website_id, inputs)],}resource = rest_api_resource(rest_config,inputs.team_id,inputs.job_id,- None,+ inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,resume_hook=save_state,initial_paginator_state=initial_state,)@@ -255,6 +303,8 @@ def crisp_source(partition_keys=[settings.partition_key] if settings.partition_key else None,partition_mode="datetime" if settings.partition_key else None,partition_format="month" if settings.partition_key else None,- sort_mode="desc" if settings.pagination == "messages" else None,+ # "desc" moves the watermark only when the run completes. Crisp does not document the+ # direction of its date order, so a watermark from a partial run could skip rows.+ sort_mode="desc" if settings.pagination == "messages" or inputs.should_use_incremental_field else None,on_complete=manager.clear_state,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.pyindex 63eddce03e19..03d0a485b0ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.py@@ -6,7 +6,7 @@ from posthog.dataclasses import frozenfrom 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.types import IncrementalField, IncrementalFieldType@frozen@@ -17,6 +17,8 @@ class CrispEndpoint:partition_key: str | None = Nonepagination: Literal["path", "messages", "single"] = "path"params: dict[str, str | int] = field(default_factory=dict)+ incremental_params: dict[str, str | int] = field(default_factory=dict)+ updated_since_param: str | None = Nonefanout: DependentEndpointConfig | None = Noneshould_sync_default: bool = Truepage_size: int = 50@@ -24,7 +26,18 @@ class CrispEndpoint:default_incremental_field: str | None = None-# Timestamp filters need an authenticated future-date probe before incremental sync can safely use them.+def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++CONVERSATION_PARAMS: dict[str, str | int] = {"per_page": 50, "include_empty": "1", "filter_inbox_id": "all"}++# The people date filter is on the creation date, so it cannot find updated profiles.# Campaign listing requires user-tier tokens, so website-token imports exclude campaigns.ENDPOINTS: dict[str, CrispEndpoint] = {"conversations": CrispEndpoint(@@ -32,7 +45,12 @@ ENDPOINTS: dict[str, CrispEndpoint] = {path="website/{website_id}/conversations/1",primary_keys=("session_id",),partition_key="created_at",- params={"per_page": 50, "include_empty": "1", "filter_inbox_id": "all", "order_date_created": "1"},+ params={**CONVERSATION_PARAMS, "order_date_created": "1"},+ # A conversation that changes mid-sync moves to a page already read, so no row is skipped.+ incremental_params={**CONVERSATION_PARAMS, "order_date_updated": "1"},+ updated_since_param="filter_date_start",+ incremental_fields=[_datetime_incremental_field("updated_at")],+ default_incremental_field="updated_at",),"messages": CrispEndpoint(name="messages",@@ -44,12 +62,15 @@ ENDPOINTS: dict[str, CrispEndpoint] = {parent_name="conversations",resolve_param="session_id",resolve_field="_path_id",- include_from_parent=["session_id"],- parent_field_renames={"session_id": "session_id"},- parent_params={"per_page": 50, "include_empty": "1", "filter_inbox_id": "all", "order_date_created": "1"},+ include_from_parent=["session_id", "updated_at"],+ parent_field_renames={"session_id": "session_id", "updated_at": "conversation_updated_at"},+ parent_params={**CONVERSATION_PARAMS, "order_date_created": "1"},child_response_actions=[{"status_code": 404, "action": "ignore"}],),should_sync_default=False,+ # Messages have no date filter, so the conversation update time bounds which ones are read.+ incremental_fields=[_datetime_incremental_field("conversation_updated_at")],+ default_incremental_field="conversation_updated_at",),"people": CrispEndpoint(name="people",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.pyindex 53529ff5468b..92216101c97a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py@@ -92,6 +92,8 @@ class CrispSource(ResumableSource[CrispSourceConfig, CrispResumeConfig]):ENDPOINTS,{name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items()},names,+ # An append sync of a child table writes every message of a changed conversation again.+ merge_only=[name for name, endpoint in ENDPOINTS.items() if endpoint.fanout is not None],should_sync_default={name: endpoint.should_sync_default for name, endpoint in ENDPOINTS.items()},)for schema in schemas:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.pyindex 46975df62197..cf4ff1b24911 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.py@@ -67,6 +67,74 @@ def test_out_of_range_page_completes_without_discarding_rows(config: CrispSourceassert result.paths[-1].endswith("/2")+ ("schema", "last_value", "filter_date_start"),+ [+ ("conversations", datetime(2026, 1, 2, 3, 4, 5, 678000, tzinfo=UTC), "2026-01-02T03:04:05.678Z"),+ ("conversations", None, None),+ ("messages", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05.000Z"),+ ("messages", None, None),+ ],+)+def test_incremental_sync_filters_conversations_by_update_date(+ config: CrispSourceConfig, schema: str, last_value: datetime | None, filter_date_start: str | None+) -> None:+ script = [page([{"session_id": "one", "created_at": 1000, "updated_at": 2000}])]+ if schema == "messages":+ script += [page([{"fingerprint": 1, "timestamp": 1500}]), page([])]+ result = SourceDriver(CrispSource(), config).run(+ schema,+ script,+ incremental_field="updated_at" if schema == "conversations" else "conversation_updated_at",+ db_incremental_field_last_value=last_value,+ )+ assert result.raised is None+ expected = {+ "per_page": ("50",),+ "include_empty": ("1",),+ "filter_inbox_id": ("all",),+ "order_date_updated": ("1",),+ }+ if filter_date_start is not None:+ expected["filter_date_start"] = (filter_date_start,)+ assert result.queries[0] == expected+ assert result.response is not None and result.response.sort_mode == "desc"+ cursor = "updated_at" if schema == "conversations" else "conversation_updated_at"+ assert [row[cursor] for row in result.rows] == [datetime.fromtimestamp(2, UTC)]+++def test_resumed_incremental_messages_defer_conversations_updated_after_the_run_started(+ config: CrispSourceConfig,+) -> None:+ started_at = datetime(2026, 1, 1, tzinfo=UTC)+ after_start = int(started_at.timestamp() * 1000) + 1000+ root = f"website/{config.website_id}/conversation"+ result = SourceDriver(CrispSource(), config).run(+ "messages",+ [+ page(+ [+ {"session_id": "finished", "updated_at": after_start},+ {"session_id": "changed", "updated_at": after_start},+ {"session_id": "unchanged", "updated_at": after_start - 86_400_000},+ ]+ ),+ page([{"fingerprint": 2, "timestamp": 1000}]),+ page([]),+ ],+ incremental_field="conversation_updated_at",+ db_incremental_field_last_value=datetime(2025, 12, 1),+ resume_state=CrispResumeConfig(+ paginator_state={"completed": [f"{root}/finished/messages"], "current": None, "child_state": None},+ started_at=started_at.isoformat(),+ ),+ )+ assert result.raised is None+ assert [row["session_id"] for row in result.rows] == ["unchanged"]+ assert not any("/changed/" in path for path in result.paths)+ assert all(state.started_at == started_at.isoformat() for state in result.saved_states)++def test_path_resume_uses_saved_page_after_interruption(config: CrispSourceConfig) -> None:driver = SourceDriver(CrispSource(), config)stopped = driver.run("visitors", [page([{"session_id": "one"}]), RunStopped("handoff")])