: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): backfill crisp messages in windows that each run completes (#117739)
Daniel RC3ada1f77694c
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 43e0c639a4c6..a4473b2c18d9 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,6 +1,5 @@-import dataclasses-from collections.abc import Callable-from datetime import UTC, datetime+from collections.abc import Callable, Iterator+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom urllib.parse import quote@@ -11,9 +10,11 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (build_dependent_resource,+ rename_parent_fields,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,@@ -30,9 +31,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom 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, SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.settings import ENDPOINTS, CrispEndpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.settings import (+ CONVERSATION_PARAMS,+ ENDPOINTS,+ CrispEndpoint,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig+# A window that one list page holds cannot lose a conversation to a page shift during the run.+WINDOW_PAGE_SIZE = int(CONVERSATION_PARAMS["per_page"])+# An incremental message sync stops after this many conversations with messages, so that the run+# completes and keeps its watermark. A website token allows 10,000 requests a day, and a backfill+# that needs more would otherwise start again from zero every run.+CONVERSATIONS_PER_RUN = 3000+EARLIEST_UPDATE = datetime(2000, 1, 1, tzinfo=UTC)+ONE_MILLISECOND = timedelta(milliseconds=1)+@frozenclass CrispResumeConfig:@@ -182,6 +196,37 @@ def parent_path_map(return encode_path+def conversation_windows(+ list_window: Callable[[datetime, datetime, bool], list[dict[str, Any]]],+ start: datetime,+ end: datetime,+ done: Callable[[], bool],+ safe_point: Callable[[], None],+) -> Iterator[list[dict[str, Any]]]:+ """Yield the conversations updated in [start, end], oldest window first.++ A full page can hide more conversations, so its window splits in two until one page holds it.+ The halves share their middle millisecond, because Crisp does not document whether its date+ filter includes the bounds. The fan-out skips a conversation that it already finished.+ """+ pending = [(start, end)]+ while pending and not done():+ low, high = pending.pop()+ rows = list_window(low, high, False)+ if len(rows) >= WINDOW_PAGE_SIZE:+ # The left half is one millisecond wider than half the window, so only a window wider+ # than two milliseconds splits into strictly smaller halves.+ if high - low > 2 * ONE_MILLISECOND:+ middle = low + (high - low) / 2+ pending.append((middle, high))+ pending.append((low, middle + ONE_MILLISECOND))+ safe_point()+ continue+ # More conversations than a page share the same few milliseconds, so only page numbers reach them.+ rows = list_window(low, high, True)+ yield rows++def normalize_row(row: dict[str, Any]) -> dict[str, Any]:for name in ("created_at", "updated_at", "conversation_updated_at", "timestamp", "dispatched_at", "waiting_since"):value = row.get(name)@@ -195,6 +240,99 @@ def normalize_operator(row: dict[str, Any]) -> dict[str, Any]:return {"type": row["type"], **row["details"]}+def windowed_messages_resource(+ config: CrispSourceConfig,+ inputs: SourceInputs,+ api_version: str,+ settings: CrispEndpoint,+ started_at: datetime,+ manager: ResumableSourceManager[CrispResumeConfig],+ save_state: Callable[[dict[str, Any] | None], None],+ initial_state: dict[str, Any] | None,+) -> Resource:+ fanout = settings.fanout+ assert fanout is not None+ parent = ENDPOINTS[fanout.parent_name]+ last_value = inputs.db_incremental_field_last_value+ start = (+ (last_value.replace(tzinfo=UTC) if last_value.tzinfo is None else last_value) - ONE_MILLISECOND+ if isinstance(last_value, datetime)+ else EARLIEST_UPDATE+ )++ def list_window(low: datetime, high: datetime, all_pages: bool) -> list[dict[str, Any]]:+ endpoint = endpoint_config(parent, config.website_id)+ endpoint["params"] = {+ **CONVERSATION_PARAMS,+ "order_date_created": "1",+ "filter_date_start": format_updated_since(low),+ "filter_date_end": format_updated_since(high),+ }+ if not all_pages:+ endpoint["paginator"] = SinglePagePaginator()+ window: RESTAPIConfig = {+ "client": client_config(config, api_version),+ "resources": [{"name": parent.name, "endpoint": endpoint}],+ }+ rows: list[dict[str, Any]] = []+ for page in rest_api_resource(window, inputs.team_id, inputs.job_id, None):+ rows.extend(page if isinstance(page, list) else [page])+ return rows++ with_messages: set[str] = set()++ def count_conversation(row: dict[str, Any]) -> dict[str, Any]:+ with_messages.add(str(row.get("session_id")))+ return row++ child_endpoint = endpoint_config(settings, config.website_id)+ child_endpoint["params"] = {+ fanout.resolve_param: {"type": "resolve", "resource": parent.name, "field": fanout.resolve_field}+ }+ child_endpoint["response_actions"] = [+ *fanout.child_response_actions,+ *(child_endpoint.get("response_actions") or []),+ ]+ rest_config: RESTAPIConfig = {+ "client": client_config(config, api_version),+ "resources": [+ {+ "name": parent.name,+ "table_name": parent.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config(parent, config.website_id),+ "data_iterator": lambda: conversation_windows(+ list_window,+ start,+ started_at,+ lambda: len(with_messages) >= CONVERSATIONS_PER_RUN,+ manager.safe_point,+ ),+ "data_map": parent_path_map(fanout.resolve_param, fanout.include_from_parent, started_at),+ },+ {+ "name": settings.name,+ "table_name": settings.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"},+ "include_from_parent": fanout.include_from_parent,+ "endpoint": child_endpoint,+ "table_format": "delta",+ },+ ],+ }+ resources = rest_api_resources(+ rest_config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ child = next(resource for resource in resources if resource.name == settings.name)+ child.add_map(rename_parent_fields(parent.name, fanout.parent_field_renames))+ return child.add_map(count_conversation)++def credential_resource(config: CrispSourceConfig, team_id: int, api_version: str, schema_name: str | None) -> Resource:if schema_name is None:endpoint: Endpoint = {@@ -242,7 +380,18 @@ def crisp_source()initial_state = resume.paginator_state if resume is not None else None- if settings.fanout is not None:+ if defer_changed:+ resource = windowed_messages_resource(+ config,+ inputs,+ api_version,+ settings,+ started_at,+ manager,+ save_state,+ initial_state,+ )+ elif settings.fanout is not None:parent = ENDPOINTS[settings.fanout.parent_name]parent_endpoint = endpoint_config(parent, config.website_id)parent_endpoint.pop("params", None)@@ -252,33 +401,24 @@ def crisp_source(*settings.fanout.child_response_actions,*(child_endpoint.get("response_actions") or []),]- resource = build_dependent_resource(+ dependent = build_dependent_resource(endpoint_configs=ENDPOINTS,child_endpoint=settings.name,- fanout=dataclasses.replace(settings.fanout, parent_params=list_params(parent, inputs))- if incremental- else settings.fanout,+ fanout=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=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,+ db_incremental_field_last_value=None,parent_endpoint_extra=parent_endpoint,child_endpoint_extra=child_endpoint,- parent_data_map=parent_path_map(- settings.fanout.resolve_param,- settings.fanout.include_from_parent,- started_at if defer_changed else None,- ),+ parent_data_map=parent_path_map(settings.fanout.resolve_param, settings.fanout.include_from_parent),page_size_param=None,resume_hook=save_state,initial_paginator_state=initial_state,)- assert isinstance(resource, Resource)+ assert isinstance(dependent, Resource)+ resource = dependentelse:rest_config: RESTAPIConfig = {"client": client_config(config, api_version),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 cf4ff1b24911..05ec1367c6ec 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@@ -6,10 +6,12 @@ import pytestfrom requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,RunStopped,ScriptedResponse,SourceDriver,)+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp import crisp as crisp_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.crisp.crisp import CrispResumeConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.crisp.source import CrispSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig@@ -68,24 +70,19 @@ def test_out_of_range_page_completes_without_discarding_rows(config: CrispSource@pytest.mark.parametrize(- ("schema", "last_value", "filter_date_start"),+ ("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),+ (datetime(2026, 1, 2, 3, 4, 5, 678000, tzinfo=UTC), "2026-01-02T03:04:05.678Z"),+ (None, None),],)-def test_incremental_sync_filters_conversations_by_update_date(- config: CrispSourceConfig, schema: str, last_value: datetime | None, filter_date_start: str | None+def test_incremental_conversations_filter_by_update_date(+ config: CrispSourceConfig, 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",+ "conversations",+ [page([{"session_id": "one", "created_at": 1000, "updated_at": 2000}])],+ incremental_field="updated_at",db_incremental_field_last_value=last_value,)assert result.raised is None@@ -99,8 +96,78 @@ def test_incremental_sync_filters_conversations_by_update_date(expected["filter_date_start"] = (filter_date_start,)assert result.queries[0] == expectedassert 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)]+ assert [row["updated_at"] for row in result.rows] == [datetime.fromtimestamp(2, UTC)]+++ ("last_value", "first_window_start"),+ [+ (None, "2000-01-01T00:00:00.000Z"),+ (datetime(2025, 12, 31, 12, 0, 0), "2025-12-31T11:59:59.999Z"),+ ],+)+def test_incremental_messages_read_small_windows_oldest_first_and_stop_after_the_run_budget(+ config: CrispSourceConfig,+ monkeypatch: pytest.MonkeyPatch,+ last_value: datetime | None,+ first_window_start: str,+) -> None:+ monkeypatch.setattr(crisp_module, "WINDOW_PAGE_SIZE", 2)+ monkeypatch.setattr(crisp_module, "CONVERSATIONS_PER_RUN", 3)+ hour_ms = 3_600_000+ first = int(datetime(2026, 1, 1, tzinfo=UTC).timestamp() * 1000)+ conversations: list[dict[str, Any]] = [+ {"session_id": f"c{number}", "updated_at": first + number * hour_ms} for number in range(4)+ ]++ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path.endswith("/messages"):+ if request.param("timestamp_before") is not None:+ return page([])+ return page([{"fingerprint": 1, "timestamp": 1000}])+ low = datetime.fromisoformat(request.param("filter_date_start") or "").timestamp() * 1000+ high = datetime.fromisoformat(request.param("filter_date_end") or "").timestamp() * 1000+ return page([row for row in conversations if low <= row["updated_at"] <= high][:2])++ result = SourceDriver(CrispSource(), config).run(+ "messages",+ respond,+ incremental_field="conversation_updated_at",+ db_incremental_field_last_value=last_value,+ )+ assert result.raised is None+ windows = [request for request in result.requests if request.path.endswith("/conversations/1")]+ assert windows[0].param("filter_date_start") == first_window_start+ assert all(request.param("order_date_created") == "1" for request in windows)+ assert [row["session_id"] for row in result.rows] == ["c0", "c1", "c2"]+ assert not any("/c3/" in path for path in result.paths)+ assert result.rows[0]["conversation_updated_at"] == datetime.fromtimestamp(first / 1000, UTC)+ assert result.response is not None and result.response.sort_mode == "desc"+++def test_incremental_messages_page_through_a_window_that_no_split_can_shrink(config: CrispSourceConfig) -> None:+ updated_at = int(datetime(2026, 1, 1, tzinfo=UTC).timestamp() * 1000)+ conversations: list[dict[str, Any]] = [+ {"session_id": f"c{number}", "updated_at": updated_at} for number in range(51)+ ]+ list_requests = 0++ def respond(request: RecordedRequest) -> ScriptedResponse:+ nonlocal list_requests+ if request.path.endswith("/messages"):+ return page([]) if request.param("timestamp_before") else page([{"fingerprint": 1, "timestamp": 1000}])+ list_requests += 1+ if list_requests > 200:+ raise RuntimeError("the window walk did not terminate")+ low = datetime.fromisoformat(request.param("filter_date_start") or "").timestamp() * 1000+ high = datetime.fromisoformat(request.param("filter_date_end") or "").timestamp() * 1000+ matching = [row for row in conversations if low <= row["updated_at"] <= high]+ number = int(request.path.rsplit("/", 1)[1])+ return page(matching[(number - 1) * 50 : number * 50])++ result = SourceDriver(CrispSource(), config).run("messages", respond, incremental_field="conversation_updated_at")+ assert result.raised is None+ assert sorted(row["session_id"] for row in result.rows) == sorted(row["session_id"] for row in conversations)def test_resumed_incremental_messages_defer_conversations_updated_after_the_run_started(