: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): admin action to change a schema's partition mode (#66325)
Daniel RC03a484c1f85d
diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.htmlindex 2432c84de68d..7706d5d94c9f 100644--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html@@ -143,6 +143,18 @@<td>{{ current_partition_size_override }} (pinned, applies on next reset)</td></tr>{% endif %}+ {% if current_partition_mode_override is not None %}+ <tr>+ <th>partition_mode_override</th>+ <td>{{ current_partition_mode_override }} (pinned, applies on next reset)</td>+ </tr>+ {% endif %}+ {% if current_partitioning_keys_override is not None %}+ <tr>+ <th>partitioning_keys_override</th>+ <td>{{ current_partitioning_keys_override }} (pinned, applies on next reset)</td>+ </tr>+ {% endif %}<tr><th>partitioning_keys</th><td>{{ current_partition_keys|default:"None" }}</td>@@ -153,79 +165,147 @@<div class="form-row partitioning-section"><h3>Repartition & resync</h3><p class="help">- <strong>Pause the schedule first</strong> using the buttons below to avoid races- with the regular scheduled sync. Saving here updates the partition knob and- immediately kicks off a non-billable workflow with <code>reset_pipeline=true</code>- — repartition without reset would mix old and new layouts in the same Delta- table and corrupt the data.+ <strong>Pause the schedule first</strong> (buttons below) to avoid racing the+ scheduled sync. This stages the partition settings and kicks off a non-billable+ workflow with <code>reset_pipeline=true</code> — repartitioning without a reset+ would mix old and new layouts in the same Delta table and corrupt it. The schedule+ auto-pauses for the run and unpauses on success.</p>- {% if current_partition_mode == "datetime" %}- <div class="partitioning-controls">- <label for="partition_format_select">New partition format:</label>- <select id="partition_format_select" name="partition_format" form="repartition-action-form" required>- {% for choice in partition_format_choices %}- <option value="{{ choice }}" {% if choice == current_partition_format %}selected{% endif %}>{{ choice }}</option>+ <p class="help">+ Pick the partition <strong>mode</strong> (defaults to the current one). Keep the+ mode and change only its knob to repartition in place; change the mode to switch+ strategy — most often <code>md5</code> → <code>datetime</code> on a date column when+ the primary key has one (the pipeline only auto-selects datetime for columns+ literally named <code>created_at</code>/<code>inserted_at</code>).+ </p>+ <div class="partitioning-controls">+ <label for="partition_mode_select">Partition mode:</label>+ <select id="partition_mode_select" name="partition_mode" form="repartition-action-form" required>+ {% for choice in partition_mode_choices %}+ <option value="{{ choice }}" {% if choice == effective_partition_mode %}selected{% endif %}>{{ choice }}</option>+ {% endfor %}+ </select>+ </div>+ <div class="partitioning-controls" id="repartition_keys_row">+ <label for="repartition_keys">Partitioning key(s):</label>+ {% if available_columns %}+ <select id="repartition_keys" name="partitioning_keys" form="repartition-action-form" multiple size="6">+ {% for col in available_columns %}+ <option value="{{ col }}" {% if current_partition_keys and col in current_partition_keys %}selected{% endif %}>{{ col }}</option>{% endfor %}</select>- <button type="submit" form="repartition-action-form" class="default"- onclick="return confirm('Repartition + reset resync (non-billable) for this schema?');">- Repartition & resync- </button>- </div>- {% elif current_partition_mode == "numerical" %}- <p class="help">- Numerical mode partitions by integer id, <code>partition_size</code> rows per bucket.- Typical values: 1,000,000 to 10,000,000.- </p>- <div class="partitioning-controls">- <label for="partition_size_input">New partition size:</label>- <input id="partition_size_input" name="partition_size" form="repartition-action-form"- type="number" min="1" step="1" required- value="{{ current_partition_size|default_if_none:'' }}"- placeholder="rows per bucket">- <button type="submit" form="repartition-action-form" class="default"- onclick="return confirm('Repartition + reset resync (non-billable) for this schema?');">- Repartition & resync- </button>- </div>- {% elif current_partition_mode == "md5" %}- <p class="help">- md5 mode hashes the primary key into <code>partition_count</code> buckets.- <br><br>- <strong>Sizing:</strong> the pipeline targets ~200 MB per partition, so a- good starting point is- <code>partition_count ≈ ceil(total table size in bytes / 200 MB)</code>.- For example a 2 GB table → ~10, a 10 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>- <input id="partition_count_input" name="partition_count" form="repartition-action-form"- type="number" min="1" step="1" required- value="{{ current_partition_count|default_if_none:'' }}"- placeholder="number of buckets">- <button type="submit" form="repartition-action-form" class="default"- onclick="return confirm('Repartition + reset resync (non-billable) for this schema?');">- Repartition & resync- </button>- </div>- {% elif current_partition_mode is None %}- <p class="help">- No <code>partition_mode</code> set yet — the pipeline picks the mode on the- first sync based on the table's columns. Run a sync to enable partitioning,- then come back here to tune it.- </p>- {% else %}- <p class="help">- Unsupported <code>partition_mode</code>: <code>{{ current_partition_mode }}</code>.- </p>- {% endif %}+ {% else %}+ <input id="repartition_keys" name="partitioning_keys" form="repartition-action-form"+ type="text" value="{% if current_partition_keys %}{{ current_partition_keys|join:',' }}{% endif %}"+ placeholder="comma-separated column names (table not synced yet)">+ {% endif %}+ <span class="help" id="repartition_keys_hint">md5 hashes one or more keys together; datetime/numerical use a single column. Leave blank for md5 to use the table's primary keys.</span>+ </div>+ <div class="partitioning-controls" id="repartition_format_row"{% if effective_partition_mode != "datetime" %} style="display: none"{% endif %}>+ <label for="repartition_format">Partition format:</label>+ <select id="repartition_format" name="partition_format" form="repartition-action-form">+ {% for choice in partition_format_choices %}+ <option value="{{ choice }}" {% if choice == current_partition_format %}selected{% endif %}>{{ choice }}</option>+ {% endfor %}+ </select>+ </div>+ <div class="partitioning-controls" id="repartition_count_row"{% if effective_partition_mode != "md5" %} style="display: none"{% endif %}>+ <label for="repartition_count">Partition count:</label>+ <input id="repartition_count" name="partition_count" form="repartition-action-form"+ type="number" min="1" step="1" value="{{ current_partition_count|default_if_none:'' }}"+ placeholder="number of buckets">+ </div>+ <p class="help" id="repartition_md5_help"{% if effective_partition_mode != "md5" %} style="display: none"{% endif %}>+ md5 hashes the primary key into <code>partition_count</code> buckets.+ <strong>Sizing:</strong> the pipeline targets ~200 MB per partition, so a good+ start is <code>partition_count ≈ ceil(table size / 200 MB)</code> (2 GB → ~10,+ 10 GB → ~50; use the source-side size incl. indexes/TOAST). md5 scatters changed+ rows across all buckets, so every incremental sync rewrites every changed partition —+ don't over-partition a small or low-churn table.+ </p>+ <div class="partitioning-controls" id="repartition_size_row"{% if effective_partition_mode != "numerical" %} style="display: none"{% endif %}>+ <label for="repartition_size">Partition size:</label>+ <input id="repartition_size" name="partition_size" form="repartition-action-form"+ type="number" min="1" step="1" value="{{ current_partition_size|default_if_none:'' }}"+ placeholder="rows per bucket">+ </div>+ <p class="help" id="repartition_numerical_help"{% if effective_partition_mode != "numerical" %} style="display: none"{% endif %}>+ Numerical mode buckets by an integer id, <code>partition_size</code> rows per bucket+ (typical 1,000,000–10,000,000).+ </p>+ <div class="partitioning-controls">+ <button type="submit" form="repartition-action-form" class="default"+ onclick="return confirm('Repartition + reset resync (non-billable) for this schema?');">+ Repartition & resync+ </button>+ </div>+ <script nonce="{{ request.csp_nonce }}">+ (function () {+ var modeSelect = document.getElementById("partition_mode_select");+ if (!modeSelect) return;+ // Each mode reveals only its own knob (+ help); the others are hidden AND+ // disabled so a hidden control is never submitted or HTML5-validated.+ var groups = {+ datetime: ["repartition_format_row"],+ md5: ["repartition_count_row", "repartition_md5_help"],+ numerical: ["repartition_size_row", "repartition_numerical_help"],+ };+ function setVisible(id, visible) {+ var el = document.getElementById(id);+ if (!el) return;+ el.style.display = visible ? "" : "none";+ el.querySelectorAll("input, select").forEach(function (c) {+ c.disabled = !visible;+ });+ }+ // md5 hashes all keys together (composite), so it allows several; datetime and+ // numerical only use the first key, so restrict to a single choice. The picker+ // stays a `multiple` listbox in every mode (same size, easy to read the options)+ // — we just enforce one selection in JS rather than collapsing the widget.+ var keysEl = document.getElementById("repartition_keys");+ var keysIsSelect = keysEl && keysEl.tagName === "SELECT";+ function keysSelected() {+ return keysIsSelect+ ? Array.prototype.filter.call(keysEl.options, function (o) { return o.selected; })+ : [];+ }+ var prevKeys = keysSelected().map(function (o) { return o.value; });+ function collapseToSingle() {+ // Keep the most recently added option (else the first selected) and drop the rest.+ var selected = keysSelected();+ var added = selected.filter(function (o) { return prevKeys.indexOf(o.value) === -1; });+ var keep = added.length ? added[added.length - 1] : selected[0];+ Array.prototype.forEach.call(keysEl.options, function (o) { o.selected = o === keep; });+ }+ function applyKeyMode(mode) {+ if (!keysIsSelect) return;+ keysEl._singleKey = mode === "datetime" || mode === "numerical";+ if (keysEl._singleKey && keysSelected().length > 1) {+ collapseToSingle();+ }+ prevKeys = keysSelected().map(function (o) { return o.value; });+ }+ if (keysIsSelect) {+ keysEl.addEventListener("change", function () {+ if (keysEl._singleKey && keysSelected().length > 1) {+ collapseToSingle();+ }+ prevKeys = keysSelected().map(function (o) { return o.value; });+ });+ }+ function sync() {+ var mode = modeSelect.value;+ Object.keys(groups).forEach(function (m) {+ groups[m].forEach(function (id) {+ setVisible(id, m === mode);+ });+ });+ applyKeyMode(mode);+ }+ modeSelect.addEventListener("change", sync);+ sync();+ })();+ </script></div><div class="form-row partitioning-section">diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.pyindex 576be5af756f..11e55e01d578 100644--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py@@ -1,8 +1,9 @@import time-from typing import Any, assert_never, get_args+from typing import Any, assert_never, cast, get_argsfrom django.conf import settingsfrom django.contrib import admin, messages+from django.core.exceptions import PermissionDeniedfrom django.core.paginator import Paginatorfrom django.shortcuts import redirectfrom django.urls import path, reverse@@ -18,11 +19,15 @@ from posthog.temporal.utils import ExternalDataWorkflowInputsfrom products.data_warehouse.backend.facade.api import pause_external_data_schedule, unpause_external_data_schedulefrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ PartitionFormat,+ PartitionMode,+)-# Source of truth lives in pipeline.typings.PartitionFormat. Re-deriving here keeps-# the dropdown in sync if a new format is ever added.+# Source of truth lives in pipeline.typings. Re-deriving here keeps the dropdowns in+# sync if a new format / mode is ever added.PARTITION_FORMAT_CHOICES: tuple[str, ...] = get_args(PartitionFormat)+PARTITION_MODE_CHOICES: tuple[str, ...] = get_args(PartitionMode)@async_to_sync@@ -55,6 +60,45 @@ def _change_url(schema_id) -> str:return reverse("admin:warehouse_sources_externaldataschema_change", args=[schema_id])+def _parse_positive_int(request, field: str, label: str) -> int | None:+ """Parse a required positive integer from POST, posting a flash message on failure.++ Returns the parsed value, or None if the field is empty / not an integer / < 1+ (after posting the appropriate `messages.error`). Callers redirect back to the+ change page when None is returned. The repartition form takes operator-typed partition+ counts/sizes.+ """+ raw = request.POST.get(field, "").strip()+ if not raw:+ messages.error(request, f"{label} is required.")+ return None+ try:+ value = int(raw)+ except ValueError:+ messages.error(request, f"{label} must be an integer; got {raw!r}.")+ return None+ if value < 1:+ messages.error(request, f"{label} must be >= 1; got {value}.")+ return None+ return value+++def _parse_partition_keys(request) -> list[str]:+ """Collect partitioning keys from POST, order-preserving and de-duplicated.++ Handles both form shapes: the multi-select (synced tables) submits repeated+ `partitioning_keys` values, while the free-text fallback (unsynced tables) submits a+ single comma-separated value. Returns [] when none were supplied.+ """+ keys: list[str] = []+ for raw in request.POST.getlist("partitioning_keys"):+ for part in raw.split(","):+ stripped = part.strip()+ if stripped and stripped not in keys:+ keys.append(stripped)+ return keys++@admin.register(ExternalDataSchema)class ExternalDataSchemaAdmin(admin.ModelAdmin):list_display = (@@ -108,16 +152,12 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):return custom_urls + urlsdef repartition_view(self, request, schema_id):- # Update the partition knob that matches the schema's partition_mode AND- # immediately trigger a non-billable resync with reset_pipeline=True.- # Repartition without a reset risks mixing old/new partition layouts in- # the same Delta table, which corrupts the data with no easy way to- # recover — so the two actions are bundled.- #- # We require an explicit partition_mode on the schema. The pipeline picks- # the mode the first time a table is partitioned (based on column shape);- # forcing a mode here would cause the next sync to crash if the table- # doesn't carry a column compatible with that mode.+ # Stage partition settings and trigger a non-billable reset resync. Covers both+ # repartitioning in place (keep the mode, change its knob — count/size/format) and+ # switching the mode entirely (e.g. md5 → datetime on a date column). The chosen+ # mode/keys/knob are written as *_override keys that survive the bundled reset and are+ # consumed once applied. Repartition without the reset would mix old and new layouts in+ # the same Delta table and corrupt it, so the reset is always bundled in.if request.method != "POST":return redirect(_change_url(schema_id))@@ -127,82 +167,129 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):messages.error(request, f"Schema {schema_id} not found.")return redirect(reverse("admin:warehouse_sources_externaldataschema_changelist"))- if schema.partition_mode is None:+ if not self.has_change_permission(request, schema):+ raise PermissionDenied++ # Mode comes from the form; fall back to the schema's current mode for a pure in-place+ # repartition. Must resolve to a known mode (the pipeline picks one on the first sync, so+ # before that the operator has to choose).+ new_mode = request.POST.get("partition_mode") or schema.partition_mode+ if new_mode not in get_args(PartitionMode):messages.error(request,- "Schema has no partition_mode set. Run a sync first so the pipeline can pick "- "the appropriate mode for this table, then come back to repartition.",+ f"Invalid partition_mode: {new_mode!r}. Choose one of {', '.join(get_args(PartitionMode))} "+ "(or run a sync first so the pipeline picks one).",)return redirect(_change_url(schema_id))-- # Validate input by mode and stage the value to write. We defer the actual- # save so we can do one DB write that updates the partition knob AND sets- # reset_pipeline AND records whether to auto-unpause the schedule.- partition_field: str- partition_value: Any- previous_value: Any- if schema.partition_mode == "datetime":+ new_mode = cast(PartitionMode, new_mode)+ mode_changed = new_mode != schema.partition_mode++ # Everything is staged as *_override keys: the bundled reset wipes the auto-detected+ # partition_mode / count / size / keys, so a plain write would be discarded and the source+ # would re-derive its own values. The overrides survive the reset and are consumed once+ # applied (see ExternalDataSchema.set_partitioning_enabled).+ staged: dict[str, Any] = {"partition_mode_override": new_mode}+ label_bits: list[str] = []+ if mode_changed:+ label_bits.append(f"partition_mode: {schema.partition_mode!r} → {new_mode!r}")++ # Keys are optional: omitting them keeps the existing keys (in-place repartition). When+ # switching INTO datetime/numerical they're required — the existing composite PK is usually+ # unsuitable for single-column bucketing.+ keys = _parse_partition_keys(request)++ if new_mode == "datetime":+ if keys:+ if len(keys) != 1:+ messages.error(+ request,+ "datetime mode needs exactly one partitioning key — the date/timestamp "+ "column to bucket on (e.g. action_date).",+ )+ return redirect(_change_url(schema_id))+ staged["partitioning_keys_override"] = keys+ label_bits.append(f"keys={keys}")+ elif mode_changed:+ messages.error(+ request,+ "Switching to datetime needs exactly one partitioning key — the date/timestamp "+ "column to bucket on (e.g. action_date).",+ )+ return redirect(_change_url(schema_id))new_format = request.POST.get("partition_format")if new_format not in PARTITION_FORMAT_CHOICES:messages.error(request, f"Invalid partition_format: {new_format!r}.")return redirect(_change_url(schema_id))- partition_field = "partition_format"- partition_value = new_format- previous_value = schema.partition_format- elif schema.partition_mode == "numerical":- raw = request.POST.get("partition_size", "").strip()- try:- new_size = int(raw)- except ValueError:- messages.error(request, f"partition_size must be an integer; got {raw!r}.")- return redirect(_change_url(schema_id))- if new_size < 1:- messages.error(request, f"partition_size must be >= 1; got {new_size}.")+ # partition_format already survives the reset and is read directly by the pipeline.+ staged["partition_format"] = new_format+ label_bits.append(f"format={new_format!r}")+ elif new_mode == "numerical":+ if keys:+ if len(keys) != 1:+ messages.error(request, "numerical mode needs exactly one integer partitioning key.")+ return redirect(_change_url(schema_id))+ staged["partitioning_keys_override"] = keys+ label_bits.append(f"keys={keys}")+ elif mode_changed:+ messages.error(request, "Switching to numerical needs exactly one integer partitioning key.")return redirect(_change_url(schema_id))- # 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":- raw = request.POST.get("partition_count", "").strip()- try:- new_count = int(raw)- except ValueError:- messages.error(request, f"partition_count must be an integer; got {raw!r}.")+ new_size = _parse_positive_int(request, "partition_size", "partition_size")+ if new_size is None:return redirect(_change_url(schema_id))- if new_count < 1:- messages.error(request, f"partition_count must be >= 1; got {new_count}.")+ staged["partition_size_override"] = new_size+ label_bits.append(f"partition_size={new_size}")+ elif new_mode == "md5":+ new_count = _parse_positive_int(request, "partition_count", "partition_count")+ if new_count is None:return redirect(_change_url(schema_id))- # 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+ if keys:+ staged["partitioning_keys_override"] = keys+ label_bits.append(f"keys={keys}")+ elif mode_changed:+ # Switching INTO md5: clear any stale keys override so md5 falls back to the table's+ # primary keys instead of a date column pinned by an earlier datetime attempt.+ staged["partitioning_keys_override"] = None+ staged["partition_count_override"] = new_count+ label_bits.append(f"partition_count={new_count}")else:- # Exhaustive over PartitionMode after the None check above; assert_never- # makes mypy happy and crashes loudly if a new mode is added without- # updating this view.- assert_never(schema.partition_mode)-- # 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- # policy is per-schedule, not across schedule + ad-hoc workflow). If the- # schedule was already paused (operator paused it manually beforehand),- # skip auto-unpause so we don't undo their action.+ # Exhaustive over PartitionMode; assert_never makes mypy enforce an update here if a+ # new mode is ever added.+ assert_never(new_mode)++ change_label = (+ ", ".join(label_bits) + " (pinned for this reset)" if label_bits else "repartition (pinned for this reset)"+ )++ return self._pause_save_and_resync(+ request,+ schema,+ staged_updates=staged,+ change_label=change_label,+ workflow_kind="repartition",+ )++ def _pause_save_and_resync(+ self,+ request,+ schema: ExternalDataSchema,+ *,+ staged_updates: dict[str, Any],+ change_label: str,+ workflow_kind: str,+ ):+ # Shared tail for the partition-tuning admin actions (repartition, change partition mode):+ # pause the schedule, stage the operator's sync_type_config updates alongside+ # reset_pipeline, and trigger a single non-billable reset resync.+ #+ # Pause first so the scheduled workflow doesn't race with the admin one (Temporal's+ # "OnlyOne" overlap policy is per-schedule, not across schedule + ad-hoc workflow). If+ # the schedule was already paused (operator paused it manually beforehand), skip+ # auto-unpause so we don't undo their action.try:client = sync_connect()except Exception as e:messages.error(request, f"Failed to connect to Temporal: {e}.")- return redirect(_change_url(schema_id))+ return redirect(_change_url(schema.id))was_paused = _is_schedule_paused(client, str(schema.id))admin_paused_now = False@@ -212,15 +299,15 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):admin_paused_now = Trueexcept Exception as e:messages.error(request, f"Failed to pause schedule before resync: {e}.")- return redirect(_change_url(schema_id))-- # Single save: stage the partition update, reset_pipeline, and the auto-- # unpause marker (read by `update_external_data_job_model` at workflow end)- # in one round-trip. reset_pipeline goes on sync_type_config rather than the- # workflow input so the pipeline can pop it after the first reset; passing- # it on inputs makes every activity retry re-read True and wipe Delta +- # cursor, restarting from row 0.- schema.sync_type_config[partition_field] = partition_value+ return redirect(_change_url(schema.id))++ # Single save: stage the partition update(s), reset_pipeline, and the auto-unpause+ # marker (read by `update_external_data_job_model` at workflow end) in one round-trip.+ # reset_pipeline goes on sync_type_config rather than the workflow input so the pipeline+ # can pop it after the first reset; passing it on inputs makes every activity retry+ # re-read True and wipe Delta + cursor, restarting from row 0.+ for key, value in staged_updates.items():+ schema.sync_type_config[key] = valueschema.sync_type_config["reset_pipeline"] = Trueif admin_paused_now:schema.sync_type_config["admin_unpause_schedule_after_run"] = True@@ -233,7 +320,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):billable=False,reset_pipeline=None,)- workflow_id = f"{schema.id}-admin-repartition-{int(time.time())}"+ workflow_id = f"{schema.id}-admin-{workflow_kind}-{int(time.time())}"try:_start_external_data_workflow(client, workflow_id, inputs)except Exception as e:@@ -253,7 +340,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):f"Saved {change_label}, but failed to trigger reset resync: {e}. "f"Trigger one manually before the next scheduled sync.",)- return redirect(_change_url(schema_id))+ return redirect(_change_url(schema.id))pause_note = (" Schedule paused for the duration of this run; will auto-unpause on a successful completion."@@ -264,7 +351,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):request,f"{change_label}. Triggered non-billable reset resync (workflow_id={workflow_id}).{pause_note}",)- return redirect(_change_url(schema_id))+ return redirect(_change_url(schema.id))def trigger_sync_view(self, request, schema_id):# Ad-hoc external-data-job workflow execution. Bypasses the schedule because@@ -401,14 +488,26 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):extra_context["team_id"] = obj.team_idextra_context["partition_format_choices"] = PARTITION_FORMAT_CHOICES+ extra_context["partition_mode_choices"] = PARTITION_MODE_CHOICESextra_context["current_partition_format"] = obj.partition_formatextra_context["current_partition_mode"] = obj.partition_mode+ # The mode the form opens on: the current mode, or the first dropdown option when unset+ # (no sync yet). Drives both the selected <option> and the initial server-side field+ # show/hide so the right fields render before the JS toggle runs.+ extra_context["effective_partition_mode"] = obj.partition_mode or PARTITION_MODE_CHOICES[0]extra_context["current_partition_keys"] = obj.partitioning_keysextra_context["current_partition_size"] = obj.partition_sizeextra_context["current_partition_count"] = obj.partition_countextra_context["current_partition_count_override"] = obj.partition_count_overrideextra_context["current_partition_size_override"] = obj.partition_size_override+ extra_context["current_partition_mode_override"] = obj.partition_mode_override+ extra_context["current_partitioning_keys_override"] = obj.partitioning_keys_overrideextra_context["partitioning_enabled"] = obj.partitioning_enabled+ # Column names for the partition-key multi-select. Populated once the table has synced;+ # None before the first sync, in which case the template falls back to a free-text input.+ extra_context["available_columns"] = (+ sorted((obj.table.columns or {}).keys()) if obj.table and obj.table.columns else None+ )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])extra_context["pause_schedule_url"] = reverse("admin:external_data_schema_pause_schedule", args=[obj.id])diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex efebe9f81909..a559d949e919 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -280,6 +280,27 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn None+ @property+ def partition_mode_override(self) -> PartitionMode | None:+ # Operator-pinned partition_mode set via the admin "change partition mode" action.+ # Like `partition_count_override`, it survives `update_sync_type_config_for_reset_pipeline`+ # (which wipes the auto-detected `partition_mode`) so the operator's choice wins the reset+ # resync that the mode change triggers, then is consumed by `set_partitioning_enabled`.+ if self.sync_type_config:+ return self.sync_type_config.get("partition_mode_override", None)++ return None++ @property+ def partitioning_keys_override(self) -> list[str] | None:+ # Operator-pinned partitioning_keys paired with `partition_mode_override` — e.g. the+ # date/timestamp column to bucket on when switching a table to datetime mode. Same+ # one-shot, reset-surviving semantics as `partition_mode_override`.+ if self.sync_type_config:+ return self.sync_type_config.get("partitioning_keys_override", None)++ return None+@propertydef partition_mode(self) -> PartitionMode | None:if self.sync_type_config:@@ -363,6 +384,8 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# repartition action if needed).self.sync_type_config.pop("partition_count_override", None)self.sync_type_config.pop("partition_size_override", None)+ self.sync_type_config.pop("partition_mode_override", None)+ self.sync_type_config.pop("partitioning_keys_override", None)self.save()def stage_incremental_field_value(self, run_uuid: str, last_value: Any, earliest_value: Any = None) -> None:@@ -434,9 +457,10 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldself.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.+ # We intentionally don't reset partition_count_override / partition_size_override /+ # partition_mode_override / partitioning_keys_override: an operator pins those via the admin+ # repartition / change-partition-mode actions precisely so they survive this reset and win+ # the resync it triggers. They're consumed in set_partitioning_enabled.self.initial_sync_complete = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.pyindex d9bd2b1a02ae..7cf00318f0ab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py@@ -869,6 +869,13 @@ def _mock_schema(**overrides: Any) -> MagicMock:schema.partitioning_keys = overrides.get("partitioning_keys")schema.partition_format = overrides.get("partition_format")schema.partition_mode = overrides.get("partition_mode")+ # Operator-pinned overrides default to None (as on the real model). Without setting these+ # explicitly the MagicMock would auto-create truthy attributes that win the `*_override or ...`+ # precedence in setup_partitioning.+ schema.partition_count_override = overrides.get("partition_count_override")+ schema.partition_size_override = overrides.get("partition_size_override")+ 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.set_partitioning_enabled = MagicMock()return schema@@ -963,3 +970,47 @@ async def test_setup_partitioning_no_delta_table_no_partition_keys_returns_unchaassert result.equals(pa_table)assert PARTITION_KEY not in result.column_names+++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+ # auto-detected names (created_at/inserted_at/...). The mode + keys overrides must win, so the+ # rows bucket by the date column rather than being md5-hashed by the composite primary key.+ logger: FilteringBoundLogger = structlog.get_logger()+ pa_table = pa.table(+ {+ "record_id": ["a", "b", "c"],+ "action_date": [+ datetime.datetime(2026, 1, 15),+ datetime.datetime(2026, 1, 20),+ datetime.datetime(2026, 2, 3),+ ],+ }+ )+ schema = _mock_schema(+ partition_mode="md5",+ partition_count=30,+ partitioning_keys=["record_id", "action_date"],+ partition_mode_override="datetime",+ partitioning_keys_override=["action_date"],+ partition_format="month",+ partitioning_enabled=False,+ )++ result = await setup_partitioning(+ pa_table=pa_table,+ existing_delta_table=None,+ schema=schema,+ resource=_mock_resource(primary_keys=["record_id", "action_date"]),+ logger=logger,+ )++ assert PARTITION_KEY in result.column_names+ # datetime/month bucketing, not md5 hashing of the composite key.+ assert result.column(PARTITION_KEY).to_pylist() == ["2026-01", "2026-01", "2026-02"]+ schema.set_partitioning_enabled.assert_called_once()+ applied_keys, _count, _size, applied_mode, applied_format = schema.set_partitioning_enabled.call_args.args+ assert applied_mode == "datetime"+ assert applied_keys == ["action_date"]+ assert applied_format == "month"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.pyindex bee66f40d124..f7cd02a7ae3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py@@ -374,9 +374,14 @@ async def setup_partitioning(# 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_countpartition_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_keys = (+ schema.partitioning_keys_override+ or 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+ partition_mode = schema.partition_mode_override or schema.partition_mode or resource.partition_modeif not partition_keys:logger.debug("No partition keys, skipping partitioning")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.pyindex 12c052c0acd0..812c31c57731 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@@ -150,9 +150,16 @@ class PipelineV3(Generic[ResumableData]):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_keys = (+ self._schema.partitioning_keys_override+ or 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+ partition_mode = (+ self._schema.partition_mode_override or self._schema.partition_mode or self._resource.partition_mode+ )# Determine if this is the first-ever sync (no DWH table exists yet)is_first_ever_sync = self._schema.table is Nonediff --git a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.pyindex 0408b2c57c0a..0982149f36d1 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@@ -5,6 +5,7 @@ from unittest.mock import patchfrom django.contrib.admin import AdminSitefrom django.contrib.messages.storage.fallback import FallbackStorage+from django.core.exceptions import PermissionDeniedfrom django.test import RequestFactoryfrom parameterized import parameterized@@ -19,6 +20,8 @@ _ADMIN_MODULE = "products.warehouse_sources.backend.admin.external_data_schema_aclass TestExternalDataSchemaAdmin(BaseTest):def setUp(self) -> None:super().setUp()+ self.user.is_staff = True+ self.user.save()self.admin = ExternalDataSchemaAdmin(ExternalDataSchema, AdminSite())self.factory = RequestFactory()@@ -26,6 +29,7 @@ class TestExternalDataSchemaAdmin(BaseTest):request = getattr(self.factory, method)("/", data=data or {})request.session = {}request._messages = FallbackStorage(request)+ request.user = self.userreturn requestdef _schema(self, **kwargs) -> ExternalDataSchema:@@ -126,3 +130,154 @@ class TestExternalDataSchemaAdmin(BaseTest):for key, value in extra_config_assertions.items():assert schema.sync_type_config[key] == valuemock_start.assert_called_once()++ @parameterized.expand(+ [+ (+ "md5_to_datetime",+ {"partition_mode": "md5", "partition_count": 30, "partitioning_enabled": True},+ {"partition_mode": "datetime", "partitioning_keys": "action_date", "partition_format": "month"},+ {+ "partition_mode_override": "datetime",+ "partitioning_keys_override": ["action_date"],+ "partition_format": "month",+ },+ ),+ (+ "to_numerical",+ {"partition_mode": "md5", "partition_count": 30, "partitioning_enabled": True},+ {"partition_mode": "numerical", "partitioning_keys": "id", "partition_size": "1000000"},+ {+ "partition_mode_override": "numerical",+ "partitioning_keys_override": ["id"],+ "partition_size_override": 1_000_000,+ },+ ),+ (+ "to_md5_with_keys",+ {"partition_mode": "datetime", "partition_format": "month", "partitioning_enabled": True},+ {"partition_mode": "md5", "partition_count": "10", "partitioning_keys": "record_id,action_date"},+ {+ "partition_mode_override": "md5",+ "partition_count_override": 10,+ "partitioning_keys_override": ["record_id", "action_date"],+ },+ ),+ (+ # md5 without keys must explicitly clear a stale partitioning_keys_override left by a+ # prior datetime attempt — otherwise it survives the reset and md5 hashes the wrong+ # column instead of falling back to the table's primary keys.+ "to_md5_clears_stale_keys",+ {+ "partition_mode": "datetime",+ "partitioning_keys_override": ["action_date"],+ "partition_format": "month",+ "partitioning_enabled": True,+ },+ {"partition_mode": "md5", "partition_count": "10"},+ {+ "partition_mode_override": "md5",+ "partition_count_override": 10,+ "partitioning_keys_override": None,+ },+ ),+ (+ # Multi-select submits repeated values (a list) rather than a comma-joined string.+ "to_md5_multiselect_keys",+ {"partition_mode": "datetime", "partition_format": "month", "partitioning_enabled": True},+ {"partition_mode": "md5", "partition_count": "10", "partitioning_keys": ["record_id", "action_date"]},+ {+ "partition_mode_override": "md5",+ "partition_count_override": 10,+ "partitioning_keys_override": ["record_id", "action_date"],+ },+ ),+ (+ # In-place format change with the mode unchanged — the merged "repartition" case+ # that used to be a separate action. No keys needed since the mode isn't changing.+ "datetime_in_place_format_change",+ {+ "partition_mode": "datetime",+ "partition_format": "week",+ "partitioning_keys": ["action_date"],+ "partitioning_enabled": True,+ },+ {"partition_mode": "datetime", "partition_format": "day"},+ {+ "partition_mode_override": "datetime",+ "partition_format": "day",+ },+ ),+ ]+ )+ def test_change_partition_mode_writes_overrides(+ self,+ _name: str,+ initial_config: dict,+ post_data: dict,+ expected_config: 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()+ for key, value in expected_config.items():+ assert schema.sync_type_config[key] == value+ assert schema.sync_type_config["reset_pipeline"] is True+ # The resync must be non-billable — the operator's reset shouldn't charge the customer.+ mock_start.assert_called_once()+ assert mock_start.call_args.args[2].billable is False++ @parameterized.expand(+ [+ # datetime/numerical need exactly one key (here a mode change supplies none / too many).+ # The count/size inputs are intentionally not `required` (the form disables them when+ # their mode isn't selected, so a hidden control can't block submission), which means an+ # empty submission reaches the server and must be rejected here rather than blowing up on+ # int("") or staging a half-built override.+ (+ "datetime_without_single_key",+ {"partition_mode": "datetime", "partitioning_keys": "record_id,action_date"},+ ),+ ("md5_without_count", {"partition_mode": "md5"}),+ ("numerical_without_size", {"partition_mode": "numerical", "partitioning_keys": "id"}),+ ]+ )+ def test_change_partition_mode_rejects_invalid_input(self, _name: str, post_data: dict) -> None:+ schema = self._schema(sync_type_config={"partition_mode": "md5", "partition_count": 30})++ with (+ patch(f"{_ADMIN_MODULE}.sync_connect"),+ 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()+ # Invalid input must not stage an override or kick off a resync.+ assert "partition_mode_override" not in schema.sync_type_config+ assert "reset_pipeline" not in schema.sync_type_config+ mock_start.assert_not_called()++ def test_change_partition_mode_denies_without_change_permission(self) -> None:+ schema = self._schema(sync_type_config={"partition_mode": "md5", "partition_count": 30})+ post_data = {"partition_mode": "md5", "partition_count": "10"}++ with (+ patch(f"{_ADMIN_MODULE}.sync_connect"),+ patch(f"{_ADMIN_MODULE}._start_external_data_workflow") as mock_start,+ patch.object(self.admin, "has_change_permission", return_value=False),+ ):+ with self.assertRaises(PermissionDenied):+ self.admin.repartition_view(self._request("post", post_data), schema.id)++ schema.refresh_from_db()+ assert "partition_mode_override" not in schema.sync_type_config+ mock_start.assert_not_called()diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex b16bda071106..827e864f7030 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -428,6 +428,49 @@ def test_set_partitioning_enabled_consumes_partition_overrides() -> None:assert schema.partition_size_override is None+def test_reset_pipeline_preserves_partition_mode_override() -> None:+ # Operator switches a table from md5 to datetime via the admin change-partition-mode action.+ # The mode/keys overrides must survive the bundled reset (which wipes the auto-detected+ # partition_mode and partitioning_keys) so the new mode wins the resync.+ schema = ExternalDataSchema(+ sync_type_config={+ "partition_mode": "md5",+ "partitioning_keys": ["record_id", "action_date"],+ "partition_count": 30,+ "partition_mode_override": "datetime",+ "partitioning_keys_override": ["action_date"],+ "partition_format": "month",+ "partitioning_enabled": True,+ }+ )+ with patch.object(schema, "save"):+ schema.update_sync_type_config_for_reset_pipeline()+ assert "partition_mode" not in schema.sync_type_config+ assert "partitioning_keys" not in schema.sync_type_config+ assert schema.partition_mode_override == "datetime"+ assert schema.partitioning_keys_override == ["action_date"]+ # partition_format is never reset, so the datetime granularity carries into the resync.+ assert schema.partition_format == "month"+++def test_set_partitioning_enabled_consumes_partition_mode_override() -> None:+ schema = ExternalDataSchema(+ sync_type_config={"partition_mode_override": "datetime", "partitioning_keys_override": ["action_date"]}+ )+ with patch.object(schema, "save"):+ schema.set_partitioning_enabled(+ partitioning_keys=["action_date"],+ partition_count=None,+ partition_size=None,+ partition_mode="datetime",+ partition_format="month",+ )+ assert schema.partition_mode == "datetime"+ assert schema.partitioning_keys == ["action_date"]+ assert schema.partition_mode_override is None+ assert schema.partitioning_keys_override is None++def test_process_incremental_value_xid_returns_value_as_is() -> None:assert process_incremental_value(4294967396, IncrementalFieldType.XID) == 4294967396assert process_incremental_value(None, IncrementalFieldType.XID) is None