Skip to content

: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.

fix(data-warehouse): format custom-source datetime cursors for the wire (#62166)

Marcus Hofc10d98910cc0
diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.py
index 9ae29429fafc..d3f49bda2532 100644
--- a/posthog/temporal/data_imports/sources/custom/source.py
+++ b/posthog/temporal/data_imports/sources/custom/source.py
@@ -1,6 +1,7 @@
import copy
import json
import graphlib
+from datetime import date
from typing import Any, Literal, NamedTuple, Optional, cast
from urllib.parse import urlparse
@@ -252,6 +253,28 @@ def _validate_resource_graph(manifest: dict[str, Any]) -> dict[str, Optional[Res
return resolved
+def _validate_incremental_configs(manifest: dict[str, Any]) -> None:
+ """Reject incremental config values that would deterministically crash at sync time.
+
+ The structural schema doesn't model ``endpoint.incremental``, so a hand-authored
+ non-string ``datetime_format`` would otherwise only surface mid-sync, and only
+ from the second sync onward (formatting needs a stored watermark).
+ """
+ for resource in manifest.get("resources") or []:
+ if not isinstance(resource, dict):
+ continue
+ endpoint = resource.get("endpoint")
+ incremental = endpoint.get("incremental") if isinstance(endpoint, dict) else None
+ if not isinstance(incremental, dict):
+ continue
+ datetime_format = incremental.get("datetime_format")
+ if datetime_format is not None and not isinstance(datetime_format, str):
+ raise ManifestValidationError(
+ f"Resource {resource.get('name')!r}: endpoint.incremental.datetime_format must be a string "
+ 'strftime pattern (e.g. "%Y-%m-%dT%H:%M:%SZ")'
+ )
+
+
def _format_validation_errors(exc: ValidationError) -> str:
"""Render Pydantic's validation errors as a single user-facing string."""
messages: list[str] = []
@@ -548,6 +571,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# preferable to carrying a permanent leniency mode. The returned
# map feeds the probe's child filter below.
resolved = _validate_resource_graph(manifest)
+ _validate_incremental_configs(manifest)
except ManifestValidationError as exc:
return False, str(exc)
@@ -682,6 +706,11 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
]
engine_manifest = cast(RESTAPIConfig, {**manifest, "resources": engine_resources})
+ # The engine serializes a datetime watermark via str() (space-separated),
+ # which strict APIs reject — format it to the declared wire format first.
+ last_value = inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
+ last_value = _format_incremental_cursor(last_value, chosen)
+
# Inside the try block: the engine raises deterministic ValueErrors at
# build time for config problems the create-time checks can't see
# (e.g. `include_from_parent` on a resource with no resolve param).
@@ -689,9 +718,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
engine_manifest,
team_id=inputs.team_id,
job_id=inputs.job_id,
- db_incremental_field_last_value=(
- inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
- ),
+ db_incremental_field_last_value=last_value,
)
except ValueError as exc:
# A malformed manifest, a missing resource, or a broken parent
@@ -820,11 +847,36 @@ def _incremental_field_type(raw: Any) -> IncrementalFieldType:
# Keys the Custom source understands on ``endpoint.incremental`` that the generic
-# REST engine's ``Incremental(**config)`` constructor does NOT accept. They inform
-# how the cursor is typed (see ``_incremental_field_type``) but must be removed
-# before the engine builds its incremental tracker, or it raises an unexpected
-# keyword-argument error at sync setup.
-_ENGINE_UNSUPPORTED_INCREMENTAL_KEYS = frozenset({"cursor_type"})
+# REST engine's ``Incremental(**config)`` constructor does NOT accept. They must be
+# removed before the engine builds its incremental tracker, or it raises an
+# unexpected keyword-argument error at sync setup.
+_ENGINE_UNSUPPORTED_INCREMENTAL_KEYS = frozenset({"cursor_type", "datetime_format"})
+
+
+def _format_incremental_cursor(value: Any, chosen: dict[str, Any]) -> Any:
+ """Render a datetime/date high-watermark as a string for the REST engine.
+
+ The engine binds the watermark via ``str()``, whose space-separated datetime
+ rendering strict APIs (e.g. Typeform) reject. The resource's
+ ``endpoint.incremental.datetime_format`` strftime pattern controls the wire
+ format, defaulting to ISO-8601; non-datetime cursors pass through untouched.
+
+ A non-string ``datetime_format`` raises ``ManifestValidationError`` (non-retryable)
+ instead of strftime's ``TypeError``, which Temporal would retry — a backstop for
+ manifests stored before ``_validate_incremental_configs`` existed.
+ """
+ # `datetime` is a subclass of `date`, so this matches both.
+ if not isinstance(value, date):
+ return value
+ endpoint = chosen.get("endpoint")
+ incremental = endpoint.get("incremental") if isinstance(endpoint, dict) else None
+ datetime_format = incremental.get("datetime_format") if isinstance(incremental, dict) else None
+ if datetime_format is not None and not isinstance(datetime_format, str):
+ raise ManifestValidationError(
+ f"Resource {chosen.get('name')!r}: endpoint.incremental.datetime_format must be a string "
+ 'strftime pattern (e.g. "%Y-%m-%dT%H:%M:%SZ")'
+ )
+ return value.strftime(datetime_format) if datetime_format else value.isoformat()
def _strip_engine_unsupported_incremental_keys(resource: dict[str, Any]) -> dict[str, Any]:
diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
index 442304998a36..5d445884a76e 100644
--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
@@ -1,6 +1,7 @@
import io
import gzip
import json
+from datetime import UTC, datetime
from typing import Any, cast
from unittest.mock import MagicMock, patch
@@ -1365,3 +1366,104 @@ class TestCustomSourceFanoutSchemasAndProbe(SimpleTestCase):
probed_urls = [call.args[1] for call in mock_session.return_value.request.call_args_list]
assert probed_urls == ["https://api.example.com/forms"]
+
+
+class TestCustomSourceIncrementalDatetimeFormat(SimpleTestCase):
+ def _manifest(self, datetime_format=None) -> dict:
+ manifest = _minimal_manifest()
+ incremental = {"cursor_path": "updated_at", "start_param": "since"}
+ if datetime_format is not None:
+ incremental["datetime_format"] = datetime_format
+ manifest["resources"][0]["endpoint"]["incremental"] = incremental
+ return manifest
+
+ def _run(self, manifest, watermark):
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=1,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ source.source_for_pipeline(config, inputs)
+
+ _DT = datetime(2026, 6, 8, 12, 53, 34, tzinfo=UTC)
+
+ @parameterized.expand(
+ [
+ ("typeform_z", "%Y-%m-%dT%H:%M:%SZ", _DT, "2026-06-08T12:53:34Z"),
+ ("date_only", "%Y-%m-%d", _DT, "2026-06-08"),
+ ("space_separated", "%Y-%m-%d %H:%M:%S", _DT, "2026-06-08 12:53:34"),
+ ("iso8601_default", None, _DT, "2026-06-08T12:53:34+00:00"),
+ ("string_passthrough", "%Y-%m-%dT%H:%M:%SZ", "2026-06-08T00:00:00Z", "2026-06-08T00:00:00Z"),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_datetime_watermark_formatting(self, _name, fmt, watermark, expected, mock_resources):
+ mock_resources.return_value = [_fake_resource("users")]
+ self._run(self._manifest(fmt), watermark)
+
+ assert mock_resources.call_args.kwargs["db_incremental_field_last_value"] == expected
+ incremental = mock_resources.call_args.args[0]["resources"][0]["endpoint"]["incremental"]
+ assert "datetime_format" not in incremental
+
+ @parameterized.expand([("integer", 123), ("object", {"format": "%Y"}), ("list", ["%Y"])])
+ def test_non_string_format_raises_non_retryable(self, _name, fmt):
+ with self.assertRaises(NonRetryableException) as ctx:
+ self._run(self._manifest(fmt), self._DT)
+ assert "datetime_format" in str(ctx.exception)
+
+ @parameterized.expand([("integer", 123), ("object", {"format": "%Y"})])
+ def test_non_string_format_rejected_at_validation(self, _name, fmt):
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(self._manifest(fmt)), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok is False
+ assert err is not None and "datetime_format" in err and "'users'" in err
+
+ @patch("posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")
+ def test_datetime_format_reaches_request_through_real_engine(self, mock_make_session):
+ def _response(body: dict) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+ captured: list[dict] = []
+
+ def send(prepared, **kwargs):
+ captured.append(dict(getattr(prepared, "params", {}) or {}))
+ if "/forms/f1/responses" in prepared.url:
+ return _response({"items": []})
+ return _response({"items": [{"id": "f1"}]})
+
+ session = mock_make_session.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request
+ session.send.side_effect = send
+
+ manifest = _fanout_manifest()
+ for resource in manifest["resources"]:
+ resource["endpoint"]["paginator"] = {"type": "single_page"}
+ manifest["resources"][1]["endpoint"]["incremental"] = {
+ "cursor_path": "submitted_at",
+ "start_param": "since",
+ "datetime_format": "%Y-%m-%dT%H:%M:%SZ",
+ }
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=1,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 8, 12, 53, 34, tzinfo=UTC),
+ )
+ list(cast(Any, source.source_for_pipeline(config, inputs).items()))
+
+ child_params = next((p for p in captured if "since" in p), {})
+ assert child_params.get("since") == "2026-06-08T12:53:34Z"
diff --git a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
index f47cccaec550..9706e2d447e0 100644
--- a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
@@ -66,6 +66,9 @@ const CURSOR_TYPE_LABELS: Record<CursorType, string> = {
}
const CURSOR_TYPE_OPTIONS = CURSOR_TYPES.map((value) => ({ value, label: CURSOR_TYPE_LABELS[value] }))
+// The only cursor types `datetime_format` applies to — the backend ignores it for any other type.
+const DATE_LIKE_CURSOR_TYPES: readonly CursorType[] = ['datetime', 'date', 'timestamp']
+
const SORT_MODE_LABELS: Record<SortMode, string> = {
asc: 'Ascending (oldest first)',
desc: 'Descending (newest first)',
@@ -668,6 +671,19 @@ function IncrementalSection({
Pick "Descending" when the API returns newest rows first — otherwise a resumed sync may skip
rows.
</p>
+ {DATE_LIKE_CURSOR_TYPES.includes(stream.cursor_type) && (
+ <LemonField.Pure label="Datetime format">
+ <LemonInput
+ placeholder="%Y-%m-%dT%H:%M:%SZ"
+ value={stream.datetime_format}
+ onChange={(value) => onUpdate({ datetime_format: value })}
+ />
+ <p className="m-0 mt-1 text-xs text-secondary">
+ strftime pattern for the watermark sent to the API (e.g. <code>%Y-%m-%dT%H:%M:%SZ</code>
+ , <code>%s</code> for unix). Leave blank for ISO-8601.
+ </p>
+ </LemonField.Pure>
+ )}
</>
)}
</div>
diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
index b7061011a6f4..3672164868f7 100644
--- a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
@@ -33,6 +33,7 @@ const baseState = (): ManifestState => ({
cursor_path: '',
cursor_type: 'datetime',
start_param: '',
+ datetime_format: '',
parent_stream: '',
parent_resolve_field: '',
parent_path_param: '',
@@ -273,6 +274,7 @@ describe('parseManifestIntoState', () => {
cursor_path: 'updated_at',
cursor_type: 'datetime',
start_param: 'since',
+ datetime_format: '',
parent_stream: '',
parent_resolve_field: '',
parent_path_param: '',
@@ -418,6 +420,7 @@ describe('parseManifestIntoState', () => {
cursor_path: 'updated_at',
cursor_type: 'timestamp',
start_param: 'since',
+ datetime_format: '',
parent_stream: '',
parent_resolve_field: '',
parent_path_param: '',
@@ -594,6 +597,32 @@ describe('fan-out (parent/child)', () => {
})
})
+describe('datetime_format (incremental cursor)', () => {
+ const incrementalState = (datetimeFormat: string): ManifestState => {
+ const state = baseState()
+ state.streams[0].incremental_enabled = true
+ state.streams[0].cursor_path = 'updated_at'
+ state.streams[0].datetime_format = datetimeFormat
+ return state
+ }
+
+ it('emits datetime_format inside endpoint.incremental when set', () => {
+ const manifest = buildManifest(incrementalState('%Y-%m-%dT%H:%M:%SZ')) as any
+ expect(manifest.resources[0].endpoint.incremental.datetime_format).toBe('%Y-%m-%dT%H:%M:%SZ')
+ })
+
+ it('omits datetime_format when blank', () => {
+ const manifest = buildManifest(incrementalState(' ')) as any
+ expect('datetime_format' in manifest.resources[0].endpoint.incremental).toBe(false)
+ })
+
+ it('hydrates datetime_format on parse and round-trips without drift', () => {
+ const firstJson = JSON.stringify(buildManifest(incrementalState('%Y-%m-%dT%H:%M:%SZ')))
+ expect(parseManifestIntoState(firstJson).streams[0].datetime_format).toBe('%Y-%m-%dT%H:%M:%SZ')
+ expect(JSON.stringify(buildManifest(parseManifestIntoState(firstJson)))).toBe(firstJson)
+ })
+})
+
describe('extractAuthSecrets', () => {
it('returns only the bearer token for bearer auth', () => {
const state = baseState()
diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
index 5f54cefe53cc..59907c53dc61 100644
--- a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
@@ -86,6 +86,8 @@ export interface StreamForm {
cursor_path: string
cursor_type: CursorType
start_param: string
+ // strftime pattern for the outgoing watermark; empty → ISO-8601 default
+ datetime_format: string
// Fan-out (parent/child): when `parent_stream` is set, PostHog fetches that
// stream first and calls this one once per parent row, injecting
// `parent_resolve_field` into the `{parent_path_param}` placeholder in the
@@ -150,6 +152,7 @@ export function emptyStream(): StreamForm {
cursor_path: '',
cursor_type: 'datetime',
start_param: '',
+ datetime_format: '',
passthrough_params: {},
...EMPTY_PARENT_FIELDS,
}
@@ -281,6 +284,9 @@ export function buildManifest(state: ManifestState): Record<string, unknown> {
if (stream.cursor_type !== 'datetime') {
incremental.cursor_type = stream.cursor_type
}
+ if (stream.datetime_format.trim()) {
+ incremental.datetime_format = stream.datetime_format.trim()
+ }
endpoint.incremental = incremental
}
// Fan-out: bind the parent's field into the path placeholder via a
@@ -482,6 +488,7 @@ function parseStream(resource: unknown): StreamForm {
cursor_path: asString(incremental.cursor_path),
cursor_type: cursorType,
start_param: asString(incremental.start_param),
+ datetime_format: asString(incremental.datetime_format),
parent_stream: parentStream,
parent_resolve_field: parentResolveField,
parent_path_param: parentPathParam,