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(warehouse): keep operator-pinned partition count across reset (#65598)

Daniel RCe4a314327974
diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
index 57fdfd00f482..2432c84de68d 100644
--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
@@ -131,6 +131,18 @@
<th>partition_count</th>
<td>{{ current_partition_count|default:"None" }}</td>
</tr>
+ {% if current_partition_count_override is not None %}
+ <tr>
+ <th>partition_count_override</th>
+ <td>{{ current_partition_count_override }} (pinned, applies on next reset)</td>
+ </tr>
+ {% endif %}
+ {% if current_partition_size_override is not None %}
+ <tr>
+ <th>partition_size_override</th>
+ <td>{{ current_partition_size_override }} (pinned, applies on next reset)</td>
+ </tr>
+ {% endif %}
<tr>
<th>partitioning_keys</th>
<td>{{ current_partition_keys|default:"None" }}</td>
@@ -179,7 +191,18 @@
{% elif current_partition_mode == "md5" %}
<p class="help">
md5 mode hashes the primary key into <code>partition_count</code> buckets.
- Typical values: 50 to 1,000.
+ <br><br>
+ <strong>Sizing:</strong> the pipeline targets ~200&nbsp;MB per partition, so a
+ good starting point is
+ <code>partition_count ≈ ceil(total table size in bytes / 200&nbsp;MB)</code>.
+ For example a 2&nbsp;GB table → ~10, a 10&nbsp;GB table → ~50. Use the source-side
+ table size (incl. indexes/TOAST for Postgres), not the Delta footprint.
+ <br><br>
+ <strong>Trade-off:</strong> md5 hashing scatters changed rows uniformly, so every
+ incremental sync touches (and rewrites) <em>every</em> partition that has changes.
+ More buckets means more, smaller merges; fewer buckets means fewer, larger ones.
+ Don't over-partition a small or low-churn table — pin a lower count if the
+ auto-detected value is making syncs slow.
</p>
<div class="partitioning-controls">
<label for="partition_count_input">New partition count:</label>
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/utils.py b/posthog/temporal/data_imports/pipelines/pipeline/utils.py
index 546cbfcc18da..fb82a0eff352 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/utils.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/utils.py
@@ -363,8 +363,12 @@ async def setup_partitioning(
resource: SourceResponse,
logger: FilteringBoundLogger,
) -> pa.Table:
- partition_count = schema.partition_count or resource.partition_count
- partition_size = schema.partition_size or resource.partition_size
+ # An operator-pinned override (set via the admin repartition action) wins over both the
+ # persisted auto-detected value and the source's freshly-computed value. Without this,
+ # the reset bundled with repartition wipes `partition_count`/`partition_size`, and a SQL
+ # source silently re-derives its own count — discarding the operator's choice.
+ partition_count = schema.partition_count_override or schema.partition_count or resource.partition_count
+ partition_size = schema.partition_size_override or schema.partition_size or resource.partition_size
partition_keys = schema.partitioning_keys or resource.partition_keys or resource.primary_keys
partition_format = schema.partition_format or resource.partition_format
partition_mode = schema.partition_mode or resource.partition_mode
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 45b3c674d9c5..efbb9e89f10d 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -132,8 +132,15 @@ class PipelineV3(Generic[ResumableData]):
elif self._schema.is_append:
sync_type = "append"
- partition_count = self._schema.partition_count or self._resource.partition_count
- partition_size = self._schema.partition_size or self._resource.partition_size
+ # Operator-pinned overrides (admin repartition action) win over the auto-detected
+ # persisted value and the source-computed value. See setup_partitioning in the v2
+ # pipeline for the same precedence and rationale.
+ partition_count = (
+ self._schema.partition_count_override or self._schema.partition_count or self._resource.partition_count
+ )
+ partition_size = (
+ self._schema.partition_size_override or self._schema.partition_size or self._resource.partition_size
+ )
partition_keys = self._schema.partitioning_keys or self._resource.partition_keys or self._resource.primary_keys
partition_format = self._schema.partition_format or self._resource.partition_format
partition_mode = self._schema.partition_mode or self._resource.partition_mode
diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
index ab256520861b..92d03add292c 100644
--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
@@ -162,7 +162,11 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
if new_size < 1:
messages.error(request, f"partition_size must be >= 1; got {new_size}.")
return redirect(_change_url(schema_id))
- partition_field = "partition_size"
+ # Write the *_override key, not partition_size directly: the bundled reset below
+ # wipes partition_size, so a plain write would be discarded and the source would
+ # re-derive its own value. The override survives the reset and is consumed once
+ # applied (see ExternalDataSchema.set_partitioning_enabled).
+ partition_field = "partition_size_override"
partition_value = new_size
previous_value = schema.partition_size
elif schema.partition_mode == "md5":
@@ -175,7 +179,8 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
if new_count < 1:
messages.error(request, f"partition_count must be >= 1; got {new_count}.")
return redirect(_change_url(schema_id))
- partition_field = "partition_count"
+ # Write the *_override key (survives the reset); see the numerical branch above.
+ partition_field = "partition_count_override"
partition_value = new_count
previous_value = schema.partition_count
else:
@@ -184,7 +189,12 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
# updating this view.
assert_never(schema.partition_mode)
- change_label = f"{partition_field}: {previous_value!r} → {partition_value!r}"
+ # Display the logical knob name (without the _override suffix). *_override keys are
+ # one-shot (consumed on the next reset); partition_format (datetime mode) survives every
+ # reset, so the "pinned for this reset" note only applies to the override variants.
+ display_field = partition_field.removesuffix("_override")
+ pin_note = " (pinned for this reset)" if partition_field.endswith("_override") else ""
+ change_label = f"{display_field}: {previous_value!r} → {partition_value!r}{pin_note}"
# Pause the schedule before triggering an admin resync so the scheduled
# workflow doesn't race with the admin one (Temporal's "OnlyOne" overlap
@@ -399,6 +409,8 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
extra_context["current_partition_keys"] = obj.partitioning_keys
extra_context["current_partition_size"] = obj.partition_size
extra_context["current_partition_count"] = obj.partition_count
+ extra_context["current_partition_count_override"] = obj.partition_count_override
+ extra_context["current_partition_size_override"] = obj.partition_size_override
extra_context["partitioning_enabled"] = obj.partitioning_enabled
extra_context["repartition_url"] = reverse("admin:external_data_schema_repartition", args=[obj.id])
extra_context["trigger_sync_url"] = reverse("admin:external_data_schema_trigger_sync", args=[obj.id])
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index c524b7ddb711..99c10abd7bbc 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -255,6 +255,27 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return None
+ @property
+ def partition_count_override(self) -> int | None:
+ # Operator-pinned partition_count set via the admin repartition action. Unlike
+ # `partition_count` (which is auto-detected and wiped on every reset), this key
+ # survives `update_sync_type_config_for_reset_pipeline` so the operator's choice
+ # wins the reset resync that the repartition triggers. It is consumed (popped) by
+ # `set_partitioning_enabled` once applied, so a later reset re-detects.
+ if self.sync_type_config:
+ return self.sync_type_config.get("partition_count_override", None)
+
+ return None
+
+ @property
+ def partition_size_override(self) -> int | None:
+ # Operator-pinned partition_size for numerical mode. Same one-shot semantics as
+ # `partition_count_override`.
+ if self.sync_type_config:
+ return self.sync_type_config.get("partition_size_override", None)
+
+ return None
+
@property
def partition_mode(self) -> PartitionMode | None:
if self.sync_type_config:
@@ -332,6 +353,12 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config["partitioning_keys"] = partitioning_keys
self.sync_type_config["partition_mode"] = partition_mode
self.sync_type_config["partition_format"] = partition_format
+ # Consume any operator-pinned overrides: they've now been baked into the effective
+ # settings above, so drop them. This makes the pin one-shot — a later reset falls
+ # back to auto-detection instead of re-applying a stale pin (re-pin via the admin
+ # repartition action if needed).
+ self.sync_type_config.pop("partition_count_override", None)
+ self.sync_type_config.pop("partition_size_override", None)
self.save()
def stage_incremental_field_value(self, run_uuid: str, last_value: Any, earliest_value: Any = None) -> None:
@@ -403,6 +430,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("xmin_num_wraparound", None)
# We don't reset partition_format
# We don't reset chunk_size_override
+ # We intentionally don't reset partition_count_override / partition_size_override:
+ # an operator pins those via the admin repartition action precisely so they survive
+ # this reset and win the resync it triggers. They're consumed in set_partitioning_enabled.
self.initial_sync_complete = False
diff --git a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
index a3468b7e6125..0408b2c57c0a 100644
--- a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
@@ -7,6 +7,8 @@ from django.contrib.admin import AdminSite
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
+from parameterized import parameterized
+
from products.warehouse_sources.backend.admin.external_data_schema_admin import ExternalDataSchemaAdmin
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -76,3 +78,51 @@ class TestExternalDataSchemaAdmin(BaseTest):
mock_start.assert_called_once()
inputs = mock_start.call_args.args[2]
assert inputs.billable is False
+
+ @parameterized.expand(
+ [
+ (
+ "md5",
+ {"partition_mode": "md5", "partition_count": 72, "partitioning_enabled": True},
+ {"partition_count": "10"},
+ "partition_count_override",
+ 10,
+ # The operator's count must land on *_override so it survives the bundled reset;
+ # writing partition_count directly would be wiped and the source would re-derive its own value.
+ {"partition_count": 72},
+ ),
+ (
+ "numerical",
+ {"partition_mode": "numerical", "partition_size": 1_000_000, "partitioning_enabled": True},
+ {"partition_size": "5000000"},
+ "partition_size_override",
+ 5_000_000,
+ {},
+ ),
+ ]
+ )
+ def test_repartition_writes_override_key(
+ self,
+ _mode: str,
+ initial_config: dict,
+ post_data: dict,
+ override_key: str,
+ expected_value: int,
+ extra_config_assertions: dict,
+ ) -> None:
+ schema = self._schema(sync_type_config=initial_config)
+
+ with (
+ patch(f"{_ADMIN_MODULE}.sync_connect"),
+ patch(f"{_ADMIN_MODULE}._is_schedule_paused", return_value=True),
+ patch(f"{_ADMIN_MODULE}._start_external_data_workflow") as mock_start,
+ ):
+ response = self.admin.repartition_view(self._request("post", post_data), schema.id)
+
+ assert response.status_code == 302
+ schema.refresh_from_db()
+ assert schema.sync_type_config[override_key] == expected_value
+ assert schema.sync_type_config["reset_pipeline"] is True
+ for key, value in extra_config_assertions.items():
+ assert schema.sync_type_config[key] == value
+ mock_start.assert_called_once()
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 3fab715f5cdd..d427d1859e2a 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -270,6 +270,44 @@ def test_reset_pipeline_clears_xmin_state() -> None:
assert schema.initial_sync_complete is False
+def test_reset_pipeline_preserves_partition_overrides_but_clears_auto_detected() -> None:
+ # The operator pins a count via the admin repartition action; it must survive the reset
+ # that repartition bundles, while the auto-detected partition_count is wiped so it gets
+ # re-derived (and then loses to the override) on the resync.
+ schema = ExternalDataSchema(
+ sync_type_config={
+ "partition_count": 72,
+ "partition_count_override": 10,
+ "partition_size_override": 5,
+ "partitioning_enabled": True,
+ "partition_mode": "md5",
+ }
+ )
+ with patch.object(schema, "save"):
+ schema.update_sync_type_config_for_reset_pipeline()
+ assert "partition_count" not in schema.sync_type_config
+ assert "partitioning_enabled" not in schema.sync_type_config
+ assert schema.partition_count_override == 10
+ assert schema.partition_size_override == 5
+
+
+def test_set_partitioning_enabled_consumes_partition_overrides() -> None:
+ # Once the override is baked into the effective settings, it's a one-shot pin: drop it so
+ # a later reset re-detects instead of re-applying a stale value.
+ schema = ExternalDataSchema(sync_type_config={"partition_count_override": 10, "partition_size_override": 5})
+ with patch.object(schema, "save"):
+ schema.set_partitioning_enabled(
+ partitioning_keys=["id"],
+ partition_count=10,
+ partition_size=None,
+ partition_mode="md5",
+ partition_format=None,
+ )
+ assert schema.partition_count == 10
+ assert schema.partition_count_override is None
+ assert schema.partition_size_override is None
+
+
def test_process_incremental_value_xid_returns_value_as_is() -> None:
assert process_incremental_value(4294967396, IncrementalFieldType.XID) == 4294967396
assert process_incremental_value(None, IncrementalFieldType.XID) is None