: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
chore(admin): repartition + non-billable resync from data warehouse schema admin (#56814)
Daniel RCe579e3a6e794
diff --git a/posthog/admin/admins/external_data_schema_admin.py b/posthog/admin/admins/external_data_schema_admin.pyindex 2f01c8ba33c6..76bf356450cd 100644--- a/posthog/admin/admins/external_data_schema_admin.py+++ b/posthog/admin/admins/external_data_schema_admin.py@@ -1,12 +1,62 @@+import time+from typing import Any, assert_never, get_args+from django.conf import settings-from django.contrib import admin+from django.contrib import admin, messagesfrom django.core.paginator import Paginator-from django.urls import reverse+from django.shortcuts import redirect+from django.urls import path, reversefrom django.utils.html import format_html+from asgiref.sync import async_to_sync+from temporalio.client import Client+from temporalio.common import WorkflowIDReusePolicy++from posthog.temporal.common.client import sync_connect+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat+from posthog.temporal.utils import ExternalDataWorkflowInputs++from products.data_warehouse.backend.data_load.service import (+ pause_external_data_schedule,+ unpause_external_data_schedule,+)from products.data_warehouse.backend.models.external_data_job import ExternalDataJobfrom products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema+# Source of truth lives in pipeline.typings.PartitionFormat. Re-deriving here keeps+# the dropdown in sync if a new format is ever added.+PARTITION_FORMAT_CHOICES: tuple[str, ...] = get_args(PartitionFormat)+++@async_to_sync+async def _start_external_data_workflow(client: Client, workflow_id: str, inputs: ExternalDataWorkflowInputs) -> None:+ await client.start_workflow(+ "external-data-job",+ inputs,+ id=workflow_id,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,+ )+++@async_to_sync+async def _is_schedule_paused(client: Client, schedule_id: str) -> bool:+ """Best-effort check whether the per-schema Temporal schedule is currently paused.++ Returns False if the schedule does not exist or describe fails — the caller+ treats that as 'no schedule to pause' and proceeds without pausing.+ """+ handle = client.get_schedule_handle(schedule_id)+ try:+ desc = await handle.describe()+ except Exception:+ return False+ return bool(desc.schedule.state.paused)+++def _change_url(schema_id) -> str:+ return reverse("admin:data_warehouse_externaldataschema_change", args=[schema_id])+class ExternalDataSchemaAdmin(admin.ModelAdmin):list_display = (@@ -33,6 +83,287 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):JOBS_PER_PAGE = 20+ def get_urls(self):+ urls = super().get_urls()+ custom_urls = [+ path(+ "<uuid:schema_id>/repartition/",+ self.admin_site.admin_view(self.repartition_view),+ name="external_data_schema_repartition",+ ),+ path(+ "<uuid:schema_id>/trigger-sync/",+ self.admin_site.admin_view(self.trigger_sync_view),+ name="external_data_schema_trigger_sync",+ ),+ path(+ "<uuid:schema_id>/pause-schedule/",+ self.admin_site.admin_view(self.pause_schedule_view),+ name="external_data_schema_pause_schedule",+ ),+ path(+ "<uuid:schema_id>/unpause-schedule/",+ self.admin_site.admin_view(self.unpause_schedule_view),+ name="external_data_schema_unpause_schedule",+ ),+ ]+ return custom_urls + urls++ def 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.+ if request.method != "POST":+ return redirect(_change_url(schema_id))++ try:+ schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)+ except ExternalDataSchema.DoesNotExist:+ messages.error(request, f"Schema {schema_id} not found.")+ return redirect(reverse("admin:data_warehouse_externaldataschema_changelist"))++ if schema.partition_mode is None:+ 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.",+ )+ 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_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}.")+ return redirect(_change_url(schema_id))+ partition_field = "partition_size"+ 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}.")+ return redirect(_change_url(schema_id))+ 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"+ partition_value = new_count+ previous_value = schema.partition_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)++ change_label = f"{partition_field}: {previous_value!r} → {partition_value!r}"++ # 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.+ try:+ client = sync_connect()+ except Exception as e:+ messages.error(request, f"Failed to connect to Temporal: {e}.")+ return redirect(_change_url(schema_id))++ was_paused = _is_schedule_paused(client, str(schema.id))+ admin_paused_now = False+ if not was_paused:+ try:+ pause_external_data_schedule(str(schema.id))+ admin_paused_now = True+ except 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+ schema.sync_type_config["reset_pipeline"] = True+ if admin_paused_now:+ schema.sync_type_config["admin_unpause_schedule_after_run"] = True+ schema.save(update_fields=["sync_type_config"])++ inputs = ExternalDataWorkflowInputs(+ team_id=schema.team_id,+ external_data_source_id=schema.source.id,+ external_data_schema_id=schema.id,+ billable=False,+ reset_pipeline=None,+ )+ workflow_id = f"{schema.id}-admin-repartition-{int(time.time())}"+ try:+ _start_external_data_workflow(client, workflow_id, inputs)+ except Exception as e:+ # Best-effort rollback of the pause we just did. Without this, a failed+ # workflow start leaves the schedule paused forever (the flag is read+ # by the workflow at completion, and there's no workflow if start+ # failed) and the flag orphaned in sync_type_config.+ if admin_paused_now:+ try:+ unpause_external_data_schedule(str(schema.id))+ schema.sync_type_config.pop("admin_unpause_schedule_after_run", None)+ schema.save(update_fields=["sync_type_config"])+ except Exception:+ pass+ messages.error(+ request,+ 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))++ pause_note = (+ " Schedule paused for the duration of this run; will auto-unpause on a successful completion."+ if admin_paused_now+ else " Schedule was already paused; leaving it paused."+ )+ messages.success(+ request,+ f"{change_label}. Triggered non-billable reset resync (workflow_id={workflow_id}).{pause_note}",+ )+ 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+ # the schedule's stored input cannot override `billable` per-trigger. To avoid+ # racing with the regular scheduled run, mirror repartition_view: pause the+ # schedule (if not already paused), record the auto-unpause marker, and let+ # `update_external_data_job_model` resume the schedule on COMPLETED.+ if request.method != "POST":+ return redirect(_change_url(schema_id))++ try:+ schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)+ except ExternalDataSchema.DoesNotExist:+ messages.error(request, f"Schema {schema_id} not found.")+ return redirect(reverse("admin:data_warehouse_externaldataschema_changelist"))++ # Both checkboxes default to off: an unchecked checkbox isn't sent in the+ # POST body, so .get() returns None, and `None == "on"` is False.+ reset_pipeline = request.POST.get("reset_pipeline") == "on"+ billable = request.POST.get("billable") == "on"++ try:+ client = sync_connect()+ except Exception as e:+ messages.error(request, f"Failed to connect to Temporal: {e}.")+ return redirect(_change_url(schema_id))++ was_paused = _is_schedule_paused(client, str(schema.id))+ admin_paused_now = False+ if not was_paused:+ try:+ pause_external_data_schedule(str(schema.id))+ admin_paused_now = True+ except Exception as e:+ messages.error(request, f"Failed to pause schedule before sync: {e}.")+ return redirect(_change_url(schema_id))++ # Single save: stage reset_pipeline (only when ticked) + the auto-unpause+ # marker. reset_pipeline goes on sync_type_config rather than the workflow+ # input — the pipeline pops it after the first reset; on the input it+ # would re-fire on every activity retry and wipe progress.+ sync_type_config_dirty = False+ if reset_pipeline:+ schema.sync_type_config["reset_pipeline"] = True+ sync_type_config_dirty = True+ if admin_paused_now:+ schema.sync_type_config["admin_unpause_schedule_after_run"] = True+ sync_type_config_dirty = True+ if sync_type_config_dirty:+ schema.save(update_fields=["sync_type_config"])++ inputs = ExternalDataWorkflowInputs(+ team_id=schema.team_id,+ external_data_source_id=schema.source.id,+ external_data_schema_id=schema.id,+ billable=billable,+ reset_pipeline=None,+ )+ workflow_id = f"{schema.id}-admin-resync-{int(time.time())}"+ try:+ _start_external_data_workflow(client, workflow_id, inputs)+ except Exception as e:+ # Best-effort rollback of the pause we just did so the schedule doesn't+ # stay paused forever after a failed workflow start.+ if admin_paused_now:+ try:+ unpause_external_data_schedule(str(schema.id))+ schema.sync_type_config.pop("admin_unpause_schedule_after_run", None)+ schema.save(update_fields=["sync_type_config"])+ except Exception:+ pass+ messages.error(request, f"Failed to trigger sync: {e}")+ return redirect(_change_url(schema_id))++ billable_label = "billable" if billable else "non-billable"+ action_label = "resync (with reset)" if reset_pipeline else "sync"+ pause_note = (+ " Schedule paused for the duration of this run; will auto-unpause on a successful completion."+ if admin_paused_now+ else " Schedule was already paused; leaving it paused."+ )+ messages.success(+ request,+ f"Triggered {billable_label} {action_label} for {schema.name} (workflow_id={workflow_id}).{pause_note}",+ )+ return redirect(_change_url(schema_id))++ def pause_schedule_view(self, request, schema_id):+ if request.method != "POST":+ return redirect(_change_url(schema_id))+ try:+ pause_external_data_schedule(str(schema_id))+ messages.success(request, "Schedule paused. Remember to unpause when admin work is done.")+ except Exception as e:+ messages.error(request, f"Failed to pause schedule: {e}")+ return redirect(_change_url(schema_id))++ def unpause_schedule_view(self, request, schema_id):+ if request.method != "POST":+ return redirect(_change_url(schema_id))+ try:+ unpause_external_data_schedule(str(schema_id))+ messages.success(request, "Schedule unpaused.")+ except Exception as e:+ messages.error(request, f"Failed to unpause schedule: {e}")+ return redirect(_change_url(schema_id))+def change_view(self, request, object_id, form_url="", extra_context=None):extra_context = extra_context or {}obj = self.get_object(request, object_id)@@ -47,6 +378,20 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):extra_context["temporal_namespace"] = settings.TEMPORAL_NAMESPACEextra_context["site_url"] = settings.SITE_URLextra_context["team_id"] = obj.team_id++ extra_context["partition_format_choices"] = PARTITION_FORMAT_CHOICES+ extra_context["current_partition_format"] = obj.partition_format+ extra_context["current_partition_mode"] = obj.partition_mode+ 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["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])+ extra_context["pause_schedule_url"] = reverse("admin:external_data_schema_pause_schedule", args=[obj.id])+ extra_context["unpause_schedule_url"] = reverse(+ "admin:external_data_schema_unpause_schedule", args=[obj.id]+ )return super().change_view(request, object_id, form_url, extra_context=extra_context)@admin.display(description="Team")diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.htmlindex 51d9da5e4abb..78a677e30c16 100644--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html@@ -1,9 +1,254 @@{% extends "admin/change_form.html" %}-{% load i18n %}+{% load i18n admin_modify %}++{% block extrastyle %}+ {{ block.super }}+ <style>+ .partitioning-and-sync .partitioning-section {+ padding: 18px 20px;+ }+ .partitioning-and-sync .partitioning-section + .partitioning-section {+ border-top: 1px solid var(--hairline-color, #eee);+ }+ .partitioning-and-sync h3 {+ margin: 0 0 10px 0;+ font-size: 13px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ opacity: 0.8;+ }+ .partitioning-and-sync .help {+ color: var(--body-quiet-color, #666);+ margin: 0 0 14px 0;+ line-height: 1.5;+ max-width: 720px;+ }+ .partitioning-and-sync .partitioning-info {+ border-collapse: collapse;+ width: 100%;+ max-width: 720px;+ }+ .partitioning-and-sync .partitioning-info th,+ .partitioning-and-sync .partitioning-info td {+ padding: 8px 12px;+ border-bottom: 1px solid var(--hairline-color, #eee);+ }+ .partitioning-and-sync .partitioning-info tr:last-child th,+ .partitioning-and-sync .partitioning-info tr:last-child td {+ border-bottom: 0;+ }+ .partitioning-and-sync .partitioning-info th {+ text-align: left;+ font-weight: 500;+ width: 220px;+ white-space: nowrap;+ }+ .partitioning-and-sync .partitioning-info td {+ font-family: var(--font-family-monospace, monospace);+ }+ .partitioning-and-sync .partitioning-controls {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px;+ }+ .partitioning-and-sync .partitioning-controls label {+ margin: 0;+ font-weight: 500;+ }+ .partitioning-and-sync .partitioning-controls .checkbox-label {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-weight: normal;+ }+ .partitioning-and-sync .partitioning-controls input[type="number"],+ .partitioning-and-sync .partitioning-controls select {+ min-width: 180px;+ }+ .partitioning-and-sync .partitioning-controls button {+ margin-left: 4px;+ }+ </style>+{% endblock %}++{% block object-tools %}+ {{ block.super }}+ {# Hidden sibling forms for the partitioning + sync POST actions. They live #}+ {# outside the main admin <form> so they don't nest (HTML5 disallows it — #}+ {# nesting silently submits the outer form). The visible inputs/buttons #}+ {# below target these via the HTML5 `form="..."` attribute. #}+ <form id="repartition-action-form" method="post" action="{{ repartition_url }}" style="display:none;">+ {% csrf_token %}+ </form>+ <form id="trigger-sync-action-form" method="post" action="{{ trigger_sync_url }}" style="display:none;">+ {% csrf_token %}+ </form>+ <form id="pause-schedule-action-form" method="post" action="{{ pause_schedule_url }}" style="display:none;">+ {% csrf_token %}+ </form>+ <form id="unpause-schedule-action-form" method="post" action="{{ unpause_schedule_url }}" style="display:none;">+ {% csrf_token %}+ </form>+{% endblock %}++{# Suppress the default bottom submit_row — we render it inside `after_field_sets` #}+{# below, immediately above Partitioning & sync, so save/delete sit close to the #}+{# field sets instead of below the operator panel. #}+{% block submit_buttons_bottom %}{% endblock %}{% block after_field_sets %}{{ block.super }}+ <div style="margin: 12px 0;">+ {% submit_row %}+ </div>++ <fieldset class="module aligned partitioning-and-sync">+ <h2>Partitioning & sync</h2>++ <div class="form-row partitioning-section">+ <h3>Current settings</h3>+ <table class="partitioning-info">+ <tr>+ <th>partitioning_enabled</th>+ <td>{{ partitioning_enabled|default:"None" }}</td>+ </tr>+ <tr>+ <th>partition_mode</th>+ <td>{{ current_partition_mode|default:"None" }}</td>+ </tr>+ <tr>+ <th>partition_format</th>+ <td>{{ current_partition_format|default:"None" }}</td>+ </tr>+ <tr>+ <th>partition_size</th>+ <td>{{ current_partition_size|default:"None" }}</td>+ </tr>+ <tr>+ <th>partition_count</th>+ <td>{{ current_partition_count|default:"None" }}</td>+ </tr>+ <tr>+ <th>partitioning_keys</th>+ <td>{{ current_partition_keys|default:"None" }}</td>+ </tr>+ </table>+ </div>++ <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.+ </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>+ {% 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.+ Typical values: 50 to 1,000.+ </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 %}+ </div>++ <div class="form-row partitioning-section">+ <h3>Schedule</h3>+ <p class="help">+ The scheduled sync uses Temporal's <code>OnlyOne</code> overlap policy, but+ ad-hoc admin runs bypass the schedule and can race with it. Pause the schedule+ before doing repartition or trigger-sync work, then unpause when finished.+ </p>+ <div class="partitioning-controls">+ <button type="submit" form="pause-schedule-action-form" class="default"+ onclick="return confirm('Pause the Temporal schedule for this schema?');">+ Pause schedule+ </button>+ <button type="submit" form="unpause-schedule-action-form" class="default"+ onclick="return confirm('Unpause the Temporal schedule for this schema?');">+ Unpause schedule+ </button>+ </div>+ </div>++ <div class="form-row partitioning-section">+ <h3>Trigger ad-hoc sync</h3>+ <p class="help">+ Use this for non-repartition cases (e.g. retrying a failed sync). Repartition+ already triggers its own non-billable reset resync — don't double up.+ <strong>Pause the schedule first</strong> if you have any chance of overlap+ with the regular run.+ </p>+ <div class="partitioning-controls">+ <label class="checkbox-label">+ <input type="checkbox" name="reset_pipeline" form="trigger-sync-action-form">+ Reset pipeline (re-sync from scratch)+ </label>+ <label class="checkbox-label">+ <input type="checkbox" name="billable" form="trigger-sync-action-form">+ Billable+ </label>+ <button type="submit" form="trigger-sync-action-form" class="default"+ onclick="return confirm('Trigger a sync for this schema?');">+ Trigger sync+ </button>+ </div>+ </div>+ </fieldset>+<fieldset class="module aligned"><h2>Temporal schedule</h2><div class="form-row" style="padding: 10px;">diff --git a/posthog/temporal/common/schedule.py b/posthog/temporal/common/schedule.pyindex 9e220bf7f28c..916fc4dda7e9 100644--- a/posthog/temporal/common/schedule.py+++ b/posthog/temporal/common/schedule.py@@ -136,6 +136,12 @@ async def a_pause_schedule(temporal: Client, schedule_id: str, note: str | Noneawait handle.pause(note=note)+async def a_unpause_schedule(temporal: Client, schedule_id: str, note: str | None = None) -> None:+ """Unpause a Temporal Schedule."""+ handle = temporal.get_schedule_handle(schedule_id)+ await handle.unpause(note=note)++@async_to_syncasync def trigger_schedule(temporal: Client, schedule_id: str, note: str | None = None) -> None:"""Trigger a Temporal Schedule."""diff --git a/posthog/temporal/data_imports/external_data_job.py b/posthog/temporal/data_imports/external_data_job.pyindex 769601e0eaa6..875cc4b9d3b6 100644--- a/posthog/temporal/data_imports/external_data_job.py+++ b/posthog/temporal/data_imports/external_data_job.py@@ -55,6 +55,7 @@ from posthog.temporal.ducklake.ducklake_copy_data_imports_workflow import (from posthog.temporal.utils import CDPProducerWorkflowInputs, ExternalDataWorkflowInputsfrom posthog.utils import get_machine_id+from products.data_warehouse.backend.data_load.service import a_unpause_external_data_schedulefrom products.data_warehouse.backend.data_load.source_templates import create_warehouse_templates_for_sourcefrom products.data_warehouse.backend.external_data_source.jobs import update_external_job_statusfrom products.data_warehouse.backend.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource@@ -177,6 +178,35 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpuf"Updated external data job with for external data source {job_id} to status {inputs.status}",)+ # If an admin action paused the schedule before triggering this run, auto-+ # unpause it on COMPLETED so support ops don't have to remember. On any+ # non-COMPLETED outcome (FAILED, BILLING_LIMIT_REACHED, …) the flag stays+ # set and the schedule stays paused — a human looks at it before resuming.+ if inputs.status == ExternalDataJob.Status.COMPLETED:+ await _maybe_unpause_schedule_after_admin_run(inputs.schema_id, logger)+++async def _maybe_unpause_schedule_after_admin_run(schema_id: str, logger) -> None:+ try:+ schema = await database_sync_to_async_pool(ExternalDataSchema.objects.get)(id=schema_id)+ except ExternalDataSchema.DoesNotExist:+ return++ sync_type_config = schema.sync_type_config or {}+ if not sync_type_config.get("admin_unpause_schedule_after_run"):+ return++ try:+ await a_unpause_external_data_schedule(schema_id)+ except Exception:+ logger.exception(f"Failed to auto-unpause schedule for schema {schema_id} after admin run")+ return++ sync_type_config.pop("admin_unpause_schedule_after_run", None)+ schema.sync_type_config = sync_type_config+ await database_sync_to_async_pool(schema.save)(update_fields=["sync_type_config"])+ logger.info(f"Auto-unpaused schedule for schema {schema_id} after successful admin-triggered run")+@dataclasses.dataclassclass CreateSourceTemplateInputs:diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.pyindex b88a6316d010..dbb8752fa316 100644--- a/products/data_warehouse/backend/data_load/service.py+++ b/products/data_warehouse/backend/data_load/service.py@@ -27,6 +27,7 @@ from posthog.temporal.common.schedule import (a_delete_schedule,a_schedule_exists,a_trigger_schedule,+ a_unpause_schedule,a_update_schedule,create_schedule,delete_schedule,@@ -209,6 +210,11 @@ def unpause_external_data_schedule(id: str):unpause_schedule(temporal, schedule_id=id)+async def a_unpause_external_data_schedule(id: str):+ temporal = await async_connect()+ await a_unpause_schedule(temporal, schedule_id=id)++def delete_external_data_schedule(schedule_id: str):temporal = sync_connect()try:diff --git a/products/data_warehouse/backend/migrations/0050_alter_externaldataschema_latest_error.py b/products/data_warehouse/backend/migrations/0050_alter_externaldataschema_latest_error.pynew file mode 100644index 000000000000..f451c705a898--- /dev/null+++ b/products/data_warehouse/backend/migrations/0050_alter_externaldataschema_latest_error.py@@ -0,0 +1,19 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("data_warehouse", "0049_externaldatasource_created_via"),+ ]++ operations = [+ migrations.AlterField(+ model_name="externaldataschema",+ name="latest_error",+ field=models.TextField(+ blank=True,+ help_text="The latest error that occurred when syncing this schema.",+ null=True,+ ),+ ),+ ]diff --git a/products/data_warehouse/backend/migrations/max_migration.txt b/products/data_warehouse/backend/migrations/max_migration.txtindex a412ec3c5ab5..e39d862a3b3d 100644--- a/products/data_warehouse/backend/migrations/max_migration.txt+++ b/products/data_warehouse/backend/migrations/max_migration.txt@@ -1 +1 @@-0049_externaldatasource_created_via+0050_alter_externaldataschema_latest_errordiff --git a/products/data_warehouse/backend/models/external_data_schema.py b/products/data_warehouse/backend/models/external_data_schema.pyindex c9849e2e2be2..fcff42fb8bd7 100644--- a/products/data_warehouse/backend/models/external_data_schema.py+++ b/products/data_warehouse/backend/models/external_data_schema.py@@ -55,7 +55,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldsource = models.ForeignKey("data_warehouse.ExternalDataSource", related_name="schemas", on_delete=models.CASCADE)table = models.ForeignKey("data_warehouse.DataWarehouseTable", on_delete=models.SET_NULL, null=True, blank=True)should_sync = models.BooleanField(default=True)- latest_error = models.TextField(null=True, help_text="The latest error that occurred when syncing this schema.")+ latest_error = models.TextField(+ null=True, blank=True, help_text="The latest error that occurred when syncing this schema."+ )status = models.CharField(max_length=400, null=True, blank=True)last_synced_at = models.DateTimeField(null=True, blank=True)sync_type = models.CharField(max_length=128, choices=SyncType, null=True, blank=True)@@ -198,7 +200,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField@propertydef partition_format(self) -> PartitionFormat | None:- # This key doesn't get reset on pipeline_reset and can only be set via the DB directly right now+ # This key doesn't get reset on pipeline_reset.if self.sync_type_config:return self.sync_type_config.get("partition_format", None)