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.

feat(data-warehouse): partition new append-only tables by their date cursor (#116359)

Daniel RC5a33182a3119
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
index ecbd3ec61c33..81a77af20f35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
PartitionMode,
SourceResponse,
)
+from products.warehouse_sources.backend.types import IncrementalFieldType
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -31,6 +32,27 @@ PARTITION_DATETIME_COLUMN_NAMES = ["created_at", "inserted_at", "createdAt"]
# Bucket for rows whose numerical partition key is null — they can't be bucketed arithmetically.
NULL_NUMERICAL_PARTITION = "null"
+DATE_CURSOR_TYPES = frozenset(
+ {IncrementalFieldType.DateTime, IncrementalFieldType.Timestamp, IncrementalFieldType.Date}
+)
+
+
+def append_cursor_partition_keys(schema: ExternalDataSchema, *, table_is_replaced: bool = False) -> list[str] | None:
+ """The cursor column of an append-only schema, when a new table can be partitioned by its date.
+
+ An append-only sync never merges rows, so a hash of the primary key helps no read and no write.
+ Its cursor only moves forward, so date partitions on the cursor let a query that filters on it
+ skip every other partition. A schema that already has partitioning keys keeps them, unless the
+ run deletes the table and loads it again: the saved keys then describe a table that is gone.
+ """
+ if not schema.is_append or schema.partitioning_keys_override:
+ return None
+ if schema.partitioning_keys and not table_is_replaced:
+ return None
+ if schema.incremental_field and schema.incremental_field_type in DATE_CURSOR_TYPES:
+ return [schema.incremental_field]
+ return None
+
async def setup_partitioning(
pa_table: pa.Table,
@@ -54,6 +76,11 @@ async def setup_partitioning(
partition_format = schema.partition_format or resource.partition_format
partition_mode = schema.partition_mode_override or schema.partition_mode or resource.partition_mode
+ if partition_mode is None:
+ cursor_keys = append_cursor_partition_keys(schema)
+ if cursor_keys:
+ partition_keys, partition_mode = cursor_keys, "datetime"
+
if not partition_keys:
logger.debug("No partition keys, skipping partitioning")
return pa_table
@@ -248,8 +275,11 @@ def append_partition_key_to_table(
date_format = "%Y-%m"
if isinstance(date, int):
- date = datetime.datetime.fromtimestamp(date)
- partition_array.append(date.strftime(date_format))
+ try:
+ partition_array.append(datetime.datetime.fromtimestamp(date).strftime(date_format))
+ except (ValueError, OverflowError, OSError):
+ # Not a timestamp in seconds, for example one in milliseconds.
+ partition_array.append("1970-01")
elif isinstance(date, datetime.datetime):
partition_array.append(date.strftime(date_format))
elif isinstance(date, datetime.date):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 9ce3de9afb06..71ff70109440 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
NULL_NUMERICAL_PARTITION,
+ append_cursor_partition_keys,
append_partition_key_to_table,
setup_partitioning,
)
@@ -1536,6 +1537,9 @@ def _mock_schema(**overrides: Any) -> MagicMock:
schema.partition_mode_override = overrides.get("partition_mode_override")
schema.partitioning_keys_override = overrides.get("partitioning_keys_override")
schema.partitioning_enabled = overrides.get("partitioning_enabled", True)
+ schema.is_append = overrides.get("is_append", False)
+ schema.incremental_field = overrides.get("incremental_field")
+ schema.incremental_field_type = overrides.get("incremental_field_type")
schema.set_partitioning_enabled = MagicMock()
return schema
@@ -1631,6 +1635,91 @@ async def test_setup_partitioning_no_delta_table_no_partition_keys_returns_uncha
assert PARTITION_KEY not in result.column_names
+ "schema_kwargs, expected",
+ [
+ ({"is_append": True, "incremental_field": "ts", "incremental_field_type": "timestamp"}, ["ts"]),
+ ({"is_append": True, "incremental_field": "day", "incremental_field_type": "date"}, ["day"]),
+ ({"is_append": False, "incremental_field": "ts", "incremental_field_type": "timestamp"}, None),
+ ({"is_append": True, "incremental_field": "seq", "incremental_field_type": "integer"}, None),
+ ({"is_append": True, "incremental_field": None, "incremental_field_type": None}, None),
+ (
+ {
+ "is_append": True,
+ "incremental_field": "ts",
+ "incremental_field_type": "timestamp",
+ "partitioning_keys": ["id"],
+ },
+ None,
+ ),
+ ],
+ ids=[
+ "append_timestamp_cursor",
+ "append_date_cursor",
+ "incremental_sync_can_merge_so_keeps_its_keys",
+ "integer_cursor_is_not_a_date",
+ "no_cursor",
+ "table_already_has_partitioning_keys",
+ ],
+)
+def test_append_cursor_partition_keys(schema_kwargs: dict[str, Any], expected: list[str] | None):
+ assert append_cursor_partition_keys(_mock_schema(**schema_kwargs)) == expected
+
+
+ "source_mode, expected_partitions, expected_mode",
+ [
+ (None, ["2026-w02", "2026-w02", "2026-w07"], "datetime"),
+ ("md5", None, "md5"),
+ ],
+ ids=["no_mode_from_the_source_uses_the_cursor", "a_mode_from_the_source_wins"],
+)
+async def test_setup_partitioning_new_append_table_is_partitioned_by_its_cursor(
+ source_mode: str | None, expected_partitions: list[str] | None, expected_mode: str
+):
+ logger: FilteringBoundLogger = structlog.get_logger()
+ pa_table = pa.table(
+ {
+ "id": [1, 2, 3],
+ "ts": pa.array(
+ [
+ datetime.datetime(2026, 1, 5, 9),
+ datetime.datetime(2026, 1, 6, 23),
+ datetime.datetime(2026, 2, 10, 1),
+ ],
+ type=pa.timestamp("us"),
+ ),
+ }
+ )
+ schema = _mock_schema(
+ is_append=True, incremental_field="ts", incremental_field_type="timestamp", partitioning_enabled=False
+ )
+
+ result = await setup_partitioning(
+ pa_table=pa_table,
+ existing_delta_table=None,
+ schema=schema,
+ resource=_mock_resource(primary_keys=["id"], partition_count=4, partition_mode=source_mode),
+ logger=logger,
+ )
+
+ assert schema.set_partitioning_enabled.call_args.args[3] == expected_mode
+ if expected_partitions is not None:
+ assert result.column(PARTITION_KEY).to_pylist() == expected_partitions
+ assert schema.set_partitioning_enabled.call_args.args[0] == ["ts"]
+
+
+def test_datetime_partitioning_of_an_integer_that_is_not_seconds_does_not_raise():
+ logger: FilteringBoundLogger = structlog.get_logger()
+ table = pa.table({"ts": [1_760_000_000, 1_760_000_000_000_000_000]})
+
+ result = append_partition_key_to_table(table, None, None, ["ts"], "datetime", "month", logger)
+
+ assert result is not None
+ assert result.table.column(PARTITION_KEY).to_pylist() == ["2025-10", "1970-01"]
+
+
@pytest.mark.asyncio
async def test_setup_partitioning_mode_override_forces_datetime_on_non_standard_column():
# An operator switches a md5 table to datetime on a date column that isn't one of the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index ded0450173a0..f5721f7f7f81 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -76,6 +76,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.bat
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
+ append_cursor_partition_keys,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sinks import (
PipelineSinks,
build_pipeline_sinks,
@@ -275,12 +278,10 @@ class PipelineV3(Generic[ResumableData]):
# A queued repartition target is the scheme of the table when this attempt deletes the table
# and loads it again. The reset then stages that target (see `handle_reset_or_full_refresh`),
# so no rewrite of the old table is necessary.
- staged_scheme = (
- self._schema.pending_scheme_for_table_replacement
- if attempt <= 1
- and resets_table_before_extraction(reset_pipeline, is_resume, self._schema, self._resource.webhook_only)
- else None
+ replaces_table = attempt <= 1 and resets_table_before_extraction(
+ reset_pipeline, is_resume, self._schema, self._resource.webhook_only
)
+ staged_scheme = self._schema.pending_scheme_for_table_replacement if replaces_table else None
self._writes_staged_repartition_scheme = staged_scheme is not None
if staged_scheme is not None:
partition_count = staged_scheme.get("partition_count") or self._resource.partition_count
@@ -312,6 +313,13 @@ class PipelineV3(Generic[ResumableData]):
partition_mode = (
self._schema.partition_mode_override or self._schema.partition_mode or self._resource.partition_mode
)
+ # The reset clears the saved layout only after this point, so a table that this attempt
+ # replaces must not inherit the mode of the table it deletes.
+ saved_mode = None if replaces_table else self._schema.partition_mode
+ if not (self._schema.partition_mode_override or saved_mode or self._resource.partition_mode):
+ cursor_keys = append_cursor_partition_keys(self._schema, table_is_replaced=replaces_table)
+ if cursor_keys:
+ partition_keys, partition_mode = cursor_keys, "datetime"
# Resolved in `_get_models`, not here: the pipeline is built inside an async activity,
# so the query that tells the warehouse from an external destination cannot run here.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index 2af5f24dd030..6133df89e0d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -457,6 +457,7 @@ class TestResetLoadWritesTheQueuedScheme:
attempt: int = 1,
can_resume: bool = False,
webhook_only: bool = False,
+ source_mode: str | None = "md5",
) -> dict[str, Any]:
resource = MagicMock(
name="users",
@@ -465,7 +466,7 @@ class TestResetLoadWritesTheQueuedScheme:
partition_size=None,
partition_keys=["id"],
partition_format=None,
- partition_mode="md5",
+ partition_mode=source_mode,
cdc_write_mode=None,
lanes=None,
webhook_only=webhook_only,
@@ -555,6 +556,40 @@ class TestResetLoadWritesTheQueuedScheme:
assert kwargs["partition_mode"] == "md5"
assert kwargs["partition_keys"] == ["id"]
+ @pytest.mark.parametrize(
+ "saved_layout, reset_pipeline, expected_mode, expected_keys",
+ [
+ ({}, False, "datetime", ["ts"]),
+ (
+ {"partition_mode": "md5", "partition_count": _OLD_COUNT, "partitioning_keys": ["id"]},
+ True,
+ "datetime",
+ ["ts"],
+ ),
+ (
+ {"partition_mode": "md5", "partition_count": _OLD_COUNT, "partitioning_keys": ["id"]},
+ False,
+ "md5",
+ ["id"],
+ ),
+ ],
+ ids=["new_table", "reset_replaces_a_hash_bucket_table", "existing_table_keeps_its_layout"],
+ )
+ def test_an_append_table_is_partitioned_by_its_date_cursor_only_when_it_is_created(
+ self, saved_layout: dict[str, Any], reset_pipeline: bool, expected_mode: str, expected_keys: list[str]
+ ) -> None:
+ schema = ExternalDataSchema(
+ name="events",
+ team_id=1,
+ sync_type="append",
+ sync_type_config={"incremental_field": "ts", "incremental_field_type": "timestamp", **saved_layout},
+ )
+
+ kwargs = self._producer_kwargs(schema, reset_pipeline=reset_pipeline, source_mode=None)
+
+ assert kwargs["partition_mode"] == expected_mode
+ assert kwargs["partition_keys"] == expected_keys
+
@pytest.mark.asyncio
async def test_the_reset_load_writes_the_queued_scheme_and_later_attempts_agree(self, tmp_path) -> None:
schema = self._schema(reset_pipeline=True, repartition_pending=_PENDING_SCHEME, repartition_rewrite={"a": 1})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md b/products/warehouse_sources/backend/temporal/data_imports/sources/README.md
index 01857f6bcb46..612e33ea3e07 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/README.md
@@ -117,6 +117,8 @@ For database sources, we recommend setting `partition_count` and `partition_size
- `partition_count` refers to how many partitions there should exist for the `md5` mode
- `partition_size` refers to how many rows should be bucketed together in a single partition for the `numerical` mode
+When a source sets no `partition_mode`, a new append-only table with a date or timestamp cursor uses `datetime` on that cursor. An append-only sync never merges rows, so a hash of the primary key helps nothing, and date partitions let a query that filters on the cursor skip the rest. A table that already has a layout keeps it.
+
## OAuth Configuration
If your source uses OAuth (SourceFieldOauthConfig):