: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
perf(data-warehouse): fewer per-run activities, incremental stats, deltalite prefetch (#107470)
Tom Owersfcb9870e3ac4
diff --git a/products/warehouse_sources/backend/migrations/0169_warehousecolumnstatistics_full_scan_at.py b/products/warehouse_sources/backend/migrations/0169_warehousecolumnstatistics_full_scan_at.pynew file mode 100644index 000000000000..c279647d3182--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0169_warehousecolumnstatistics_full_scan_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-09-28 00:00++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0168_externaldataschema_scheduled_full_refresh"),+ ]++ operations = [+ migrations.AddField(+ model_name="warehousecolumnstatistics",+ name="full_scan_at",+ field=models.DateTimeField(null=True),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex b30eb7da0f5b..8df71a3a3814 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0168_externaldataschema_scheduled_full_refresh+0169_warehousecolumnstatistics_full_scan_atdiff --git a/products/warehouse_sources/backend/models/column_statistics.py b/products/warehouse_sources/backend/models/column_statistics.pyindex 354338450f03..7aa7e8db8009 100644--- a/products/warehouse_sources/backend/models/column_statistics.py+++ b/products/warehouse_sources/backend/models/column_statistics.py@@ -45,8 +45,14 @@ class WarehouseColumnStatistics(TeamScopedRootMixin, CreatedMetaFields, UpdatedMcomputed_at = models.DateTimeField(null=True)# Delta table version the stats were computed against; provenance + lets us spot staleness.computed_for_delta_version = models.BigIntegerField(null=True)- # How the stats were produced. "delta_log" today; reserved for a future scan/sample basis.+ # How the stats were produced. "delta_log" (a full Add-action scan) or "incremental" (folded commits+ # on top of a prior scan); reserved values for a future scan/sample basis too.stats_basis = models.CharField(max_length=32, default="delta_log")+ # When the last full Add-action scan wrote this row. Unlike `computed_at`, an incremental fold+ # leaves this alone, so it anchors how long the folded numbers have gone uncorrected by a full+ # scan. Null on rows written before this field existed; treat null the same as `computed_at`+ # (every row was a full scan before incremental folding existed).+ full_scan_at = models.DateTimeField(null=True)__repr__ = sane_repr("table_id", "column_name", "computed_at")diff --git a/products/warehouse_sources/backend/temporal/data_imports/batch_phase.py b/products/warehouse_sources/backend/temporal/data_imports/batch_phase.pynew file mode 100644index 000000000000..fed20f897221--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/batch_phase.py@@ -0,0 +1,117 @@+"""Per-phase progress of a load batch, from the processor thread to the consumer's watchdog.++The consumer's liveness watchdog sees only how long a batch has been executing. A merge that is+still making progress and a write hung on a dead connection look the same to it until the flat+stuck-batch timeout, which has to be long enough for the largest legitimate merge. This module+records which phase a batch is in and for how long, so the watchdog log, a per-phase gauge and a+per-phase age gauge can tell the two apart in production before any timeout is tightened.++Observe-only: nothing here changes when a batch is judged stuck. The processor reports through+`workload_report.report_phase`, which forwards here for the batch bound to the current context.+"""++from __future__ import annotations++import time+import threading+from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import dataclass, field++from prometheus_client import Gauge, Histogram++# Phases the processor reports, in the order a batch normally passes through them. `claimed` is+# the engine's own state before the processor's first report; anything unlisted counts as `other`+# so a new report name cannot mint gauge series without a home here.+KNOWN_PHASES = ("claimed", "deliver", "read", "write", "merge", "post_load", "finalize", "other")++BATCH_PHASE_DURATION_SECONDS = Histogram(+ "warehouse_load_batch_phase_duration_seconds",+ "Wall-clock time a load batch spent in one phase before it moved to the next",+ labelnames=["phase"],+ buckets=(0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),+)++BATCHES_IN_PHASE = Gauge(+ "warehouse_load_batches_in_phase",+ "Load batches in flight on this process, by the phase they are in now",+ labelnames=["phase"],+ multiprocess_mode="livesum",+)++# A phase that never ends never reaches the histogram, so its age is the only sign of a hang.+BATCH_PHASE_AGE_SECONDS_MAX = Gauge(+ "warehouse_load_batch_phase_age_seconds_max",+ "Longest time any in-flight load batch on this process has spent in its current phase",+ labelnames=["phase"],+ multiprocess_mode="livemax",+)+++def _known_phase(phase: str) -> str:+ return phase if phase in KNOWN_PHASES else "other"+++@dataclass(frozen=False)+class BatchPhaseProgress:+ """The phase one in-flight batch is in. Written by the processor thread, read by the event loop."""++ phase: str = "claimed"+ phase_started_monotonic: float = field(default_factory=time.monotonic)+ _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)++ def advance(self, phase: str) -> None:+ now = time.monotonic()+ with self._lock:+ if phase == self.phase:+ return+ BATCH_PHASE_DURATION_SECONDS.labels(phase=_known_phase(self.phase)).observe(+ now - self.phase_started_monotonic+ )+ self.phase = phase+ self.phase_started_monotonic = now++ def snapshot(self) -> tuple[str, float]:+ """The current phase and the seconds spent in it, read together."""+ with self._lock:+ return self.phase, time.monotonic() - self.phase_started_monotonic+++_current_progress: ContextVar[BatchPhaseProgress | None] = ContextVar("dwh_batch_phase_progress", default=None)+++def report_batch_phase(phase: str) -> None:+ """Advance the batch bound to the current context; no-op outside one (the import activity)."""+ progress = _current_progress.get()+ if progress is not None:+ progress.advance(phase)+++@contextmanager+def track_batch_phases() -> Iterator[BatchPhaseProgress]:+ """Bind a fresh progress record for the batch processed inside the block.++ Contextvars follow `sync_to_async` into the processor thread, so reports made there land on the+ same record the engine holds.+ """+ progress = BatchPhaseProgress()+ token = _current_progress.set(progress)+ try:+ yield progress+ finally:+ _current_progress.reset(token)+++def publish_phase_gauges(in_flight: list[BatchPhaseProgress]) -> None:+ """Refresh both gauges from the in-flight records, zeroing phases nothing is in."""+ counts = dict.fromkeys(KNOWN_PHASES, 0)+ oldest = dict.fromkeys(KNOWN_PHASES, 0.0)+ for progress in in_flight:+ phase, seconds = progress.snapshot()+ phase = _known_phase(phase)+ counts[phase] += 1+ oldest[phase] = max(oldest[phase], seconds)+ for phase in KNOWN_PHASES:+ BATCHES_IN_PHASE.labels(phase=phase).set(counts[phase])+ BATCH_PHASE_AGE_SECONDS_MAX.labels(phase=phase).set(oldest[phase])diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 68b95deac605..f8fe1162c491 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -2,6 +2,7 @@ import reimport jsonimport uuidimport typing+import asyncioimport datetime as dtimport dataclasses@@ -65,6 +66,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrDUPLICATE_PRIMARY_KEYS_ERROR,MISSING_PRIMARY_KEYS_ERROR,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (+ release_v3_pipeline_lock,+)from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (PostImportWorkflow,PostImportWorkflowInputs,@@ -442,6 +446,7 @@ class UpdateExternalDataJobStatusInputs:# Run id stamped on the job row by the create-job activity, so finalization can resolve this# run's own job when job_id never made it back. Optional for mixed-version workers mid-rollout.workflow_run_id: str | None = None+ release_lock_token: str | None = None@propertydef properties_to_log(self) -> dict[str, typing.Any]:@@ -460,6 +465,19 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpubind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()+ await _update_job_status(inputs, logger)++ # After the status write, as the separate release activity ran, and only when it returned:+ # a status write that raises leaves the lock to its holder, as before. The release itself+ # never raises (see release_v3_pipeline_lock), matching the swallowed failure of that activity.+ if inputs.release_lock_token:+ released = await asyncio.to_thread(+ release_v3_pipeline_lock, inputs.team_id, inputs.schema_id, inputs.release_lock_token+ )+ logger.info("Released V3 pipeline lock after finalization", released=released)+++async def _update_job_status(inputs: UpdateExternalDataJobStatusInputs, logger: FilteringBoundLogger) -> None:rows_tracked = await get_rows(inputs.team_id, inputs.schema_id)if rows_tracked > 0 and inputs.status == ExternalDataJob.Status.COMPLETED:# `rows_tracked` is decremented by rows actually written, but incremented by@@ -877,6 +895,9 @@ class ExternalDataJobWorkflow(PostHogWorkflow):fast_return_eligible = Falsescheduled_full_refresh = Falserepartition_needed = True+ billing_limit_checked = False+ hit_billing_limit = False+ source_templates_needed = Trueelse:job_id = create_job_result.job_idincremental_or_append = create_job_result.incremental_or_append@@ -890,19 +911,25 @@ class ExternalDataJobWorkflow(PostHogWorkflow):fast_return_eligible = create_job_result.fast_return_eligiblescheduled_full_refresh = create_job_result.scheduled_full_refreshrepartition_needed = create_job_result.repartition_needed+ billing_limit_checked = create_job_result.billing_limit_checked+ hit_billing_limit = create_job_result.hit_billing_limit+ source_templates_needed = create_job_result.source_templates_neededupdate_inputs.job_id = str(job_id) if job_id is not None else None- # Check billing limits- hit_billing_limit = await workflow.execute_activity(- check_billing_limits_activity,- CheckBillingLimitsActivityInputs(job_id=job_id, team_id=inputs.team_id),- start_to_close_timeout=dt.timedelta(minutes=1),- retry_policy=RetryPolicy(- initial_interval=dt.timedelta(seconds=10),- maximum_interval=dt.timedelta(seconds=60),- maximum_attempts=3,- ),- )+ # The job-creation activity answers the billing question in the same round trip. The+ # separate check stays for a payload that predates that answer: a history that recorded+ # it must replay it.+ if not billing_limit_checked:+ hit_billing_limit = await workflow.execute_activity(+ check_billing_limits_activity,+ CheckBillingLimitsActivityInputs(job_id=job_id, team_id=inputs.team_id),+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=RetryPolicy(+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(seconds=60),+ maximum_attempts=3,+ ),+ )if hit_billing_limit:update_inputs.status = ExternalDataJob.Status.BILLING_LIMIT_REACHED@@ -1169,13 +1196,13 @@ class ExternalDataJobWorkflow(PostHogWorkflow):extra={"schema_id": str(inputs.external_data_schema_id)},)- # Create source templates- await workflow.execute_activity(- create_source_templates,- CreateSourceTemplateInputs(team_id=inputs.team_id, run_id=job_id),- start_to_close_timeout=dt.timedelta(minutes=10),- retry_policy=RetryPolicy(maximum_attempts=2),- )+ if source_templates_needed:+ await workflow.execute_activity(+ create_source_templates,+ CreateSourceTemplateInputs(team_id=inputs.team_id, run_id=job_id),+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )if not post_import_in_workflow:await workflow.execute_activity(@@ -1284,6 +1311,18 @@ class ExternalDataJobWorkflow(PostHogWorkflow):get_data_import_finished_metric(source_type=source_type, status=update_inputs.status.lower()).add(1)+ # This run still owns the v3 lock when no batch reached the loader (extraction failed+ # before producing batches, or a zero-batch run); the loader releases it otherwise.+ # The finalizer below always runs in that case, so it can release the lock after the+ # status write instead of a separate activity. patched() keeps in-flight pre-patch+ # executions replaying the separate release they recorded.+ workflow_releases_lock = is_v3 and bool(lock_token) and not consumer_manages_job_status+ finalizer_releases_lock = workflow_releases_lock and workflow.patched(+ "data-imports-finalizer-releases-v3-lock-2026-09"+ )+ if finalizer_releases_lock:+ update_inputs.release_lock_token = lock_token+if not skip_status_update:await workflow.execute_activity(update_external_data_job_model,@@ -1297,12 +1336,9 @@ class ExternalDataJobWorkflow(PostHogWorkflow):),)- # Release the V3 pipeline lock when the consumer is NOT managing job- # status (extraction failed before producing batches, or non-V3).- # When consumer_manages_job_status is True, the consumer releases.- # Runs before the post-import start so a raise there (cancellation)- # can't leave the lock held.- if is_v3 and lock_token and not consumer_manages_job_status:+ # Pre-patch replay path of the release above. Runs before the post-import start so a+ # raise there (cancellation) can't leave the lock held.+ if workflow_releases_lock and not finalizer_releases_lock and lock_token is not None:try:await workflow.execute_activity(release_v3_pipeline_lock_activity,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex e6e43ed7116e..71c3988ca18b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -18,6 +18,11 @@ import structlogfrom posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.temporal.data_imports.batch_phase import (+ BatchPhaseProgress,+ publish_phase_gauges,+ track_batch_phases,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (PendingBatch,)@@ -468,6 +473,7 @@ class BatchConsumer:self._last_reconcile_monotonic = 0.0# batch_id -> monotonic start, for the stuck-batch watchdog.self._inflight_started: dict[str, float] = {}+ self._inflight_progress: dict[str, BatchPhaseProgress] = {}self._last_stuck_log_monotonic = 0.0# Consecutive failed polls, for the poll-failure liveness trip.self._consecutive_poll_failures = 0@@ -1169,9 +1175,12 @@ class BatchConsumer:)self._inflight_started[batch.id] = time.monotonic()try:- yield+ with track_batch_phases() as progress:+ self._inflight_progress[batch.id] = progress+ yieldfinally:self._inflight_started.pop(batch.id, None)+ self._inflight_progress.pop(batch.id, None)structlog.contextvars.unbind_contextvars(*bound_keys)async def _process_single(self, batch: PendingBatch, lock_conn: psycopg.AsyncConnection[Any] | None = None) -> bool:@@ -1607,6 +1616,7 @@ class BatchConsumer:"""if self._health_reporter is None:return+ publish_phase_gauges(list(self._inflight_progress.values()))threshold = self._config.poll_failure_liveness_thresholdif threshold is not None and self._consecutive_poll_failures >= threshold:now = time.monotonic()@@ -1625,11 +1635,15 @@ class BatchConsumer:if now - oldest_started > timeout:if now - self._last_stuck_log_monotonic > 60:self._last_stuck_log_monotonic = now+ progress = self._inflight_progress.get(oldest_id)+ phase, phase_seconds = progress.snapshot() if progress is not None else ("unknown", 0.0)logger.error(self._event("stuck_batch_watchdog_tripped"),batch_id=oldest_id,running_seconds=round(now - oldest_started, 1),timeout_seconds=timeout,+ phase=phase,+ phase_seconds=round(phase_seconds, 1),)returnself._health_reporter()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex 86a5e29a4b53..20ceae738aba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -87,7 +87,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_trackingfrom products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying-from products.warehouse_sources.backend.temporal.data_imports.workload_report import workload_reporting+from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_phase, workload_reportinglogger = structlog.get_logger(__name__)@@ -852,6 +852,7 @@ def _process_external_destinations_only(deliver_batch_to_destinations,)+ report_phase("deliver")deliver_batch_to_destinations(export_signal)if not export_signal.is_final_batch:@@ -861,6 +862,7 @@ def _process_external_destinations_only(if verify_ownership is not None:verify_ownership()+ report_phase("finalize")_mark_job_completed(export_signal)@@ -958,6 +960,7 @@ def _process_message_reported(# delivery runs on every path and decides for itself what is left to do. Gating it on# the warehouse's marker would strand a destination that failed, and gating publication# on the write marker would leave a full refresh staged and never swapped in.+ report_phase("deliver")deliver_batch_to_destinations(export_signal)if already_processed and not export_signal.is_final_batch:@@ -981,11 +984,13 @@ def _process_message_reported()if verify_ownership is not None:verify_ownership()+ report_phase("post_load")prepared_queryable_folder = _run_post_load_for_already_processed_batch(export_signal)# Post-load can run minutes (compaction, S3 prep) — re-check before# completion promotes the cursor and releases the lock under a new owner.if verify_ownership is not None:verify_ownership()+ report_phase("finalize")_mark_job_completed(export_signal)if prepared_queryable_folder:_trigger_ducklake_register_data_imports(export_signal, prepared_queryable_folder)@@ -1004,6 +1009,7 @@ def _process_message_reported(sync_type=export_signal.sync_type,)+ report_phase("read")with PARQUET_READ_DURATION_SECONDS.time():if constituents is not None:pa_table = _read_constituents(constituents)@@ -1085,6 +1091,8 @@ def _process_message_reported(if verify_ownership is not None:verify_ownership()+ # The writer narrows this to `merge` for an upsert; an append stays `write` to its commit.+ report_phase("write")if cdc_write_mode == "scd2_append":logger.debug("writing_scd2_to_delta_lake",@@ -1184,6 +1192,7 @@ def _process_message_reported(if verify_ownership is not None:verify_ownership()+ report_phase("post_load")prepared_queryable_folder = async_to_sync(run_post_load_operations)(job=job,schema=schema,@@ -1201,6 +1210,7 @@ def _process_message_reported(if verify_ownership is not None:verify_ownership()+ report_phase("finalize")_mark_job_completed(export_signal)if prepared_queryable_folder:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.pyindex a1e2db52aa10..43c72d126435 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py@@ -1220,3 +1220,74 @@ class TestReadExistingRowsByFirstPk:result = _read_existing_rows_by_first_pk(delta_table, "id", components)assert set(result.column("id").to_pylist()) == set(expected_ids)+++class TestBatchPhaseReports:+ @patch(f"{_PROCESSOR}.report_phase")+ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value=None)+ @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.DeltaWriter")+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ def test_a_fresh_final_batch_reports_each_phase_in_order(+ self,+ mock_job_model: MagicMock,+ mock_helper_cls: MagicMock,+ mock_writer_cls: MagicMock,+ _already: MagicMock,+ _read: MagicMock,+ _post_load: AsyncMock,+ _mark_completed: MagicMock,+ _mark_processed: MagicMock,+ _trigger: MagicMock,+ _analytics: MagicMock,+ mock_report_phase: MagicMock,+ ) -> None:+ delta_table = MagicMock()+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])+ delta_table.file_uris.return_value = []+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=None)+ mock_writer_cls.return_value.write = AsyncMock(return_value=delta_table)+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ process_message(_message(is_final_batch=True, batch_index=4, run_uuid="run-9"))++ assert [call.args[0] for call in mock_report_phase.call_args_list] == [+ "deliver",+ "read",+ "write",+ "post_load",+ "finalize",+ ]++ @patch(f"{_PROCESSOR}.report_phase")+ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(f"{_PROCESSOR}._run_post_load_for_already_processed_batch", return_value=None)+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ @patch(f"{_PROCESSOR}.close_old_connections")+ def test_a_redelivered_final_batch_reports_post_load_and_finalize_only(+ self,+ _close: MagicMock,+ mock_job_model: MagicMock,+ _helper_cls: MagicMock,+ _already: MagicMock,+ _post_load: MagicMock,+ _mark_completed: MagicMock,+ _trigger: MagicMock,+ _analytics: MagicMock,+ mock_report_phase: MagicMock,+ ) -> None:+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ process_message(_message(is_final_batch=True))++ assert [call.args[0] for call in mock_report_phase.call_args_list] == ["deliver", "post_load", "finalize"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 16326e609f05..0ff9676d01a3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -3865,3 +3865,53 @@ class TestProcessGroupCoalescing:await self._run_group(consumer, _run_batches(3))assert process_batch.await_count == 3+++class TestBatchPhaseTracking:+ def test_phase_gauges_follow_the_batch_bound_to_the_processing_context(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.batch_phase import (+ BATCH_PHASE_AGE_SECONDS_MAX,+ BATCHES_IN_PHASE,+ )+ from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_phase++ consumer = _make_consumer()+ consumer._health_reporter = lambda: None+ batch = _make_batch()++ with consumer._batch_log_context(batch, attempt=1):+ report_phase("read")+ consumer._report_health()+ assert BATCHES_IN_PHASE.labels(phase="read")._value.get() == 1+ assert BATCHES_IN_PHASE.labels(phase="claimed")._value.get() == 0+ assert BATCH_PHASE_AGE_SECONDS_MAX.labels(phase="read")._value.get() >= 0++ consumer._report_health()+ assert BATCHES_IN_PHASE.labels(phase="read")._value.get() == 0+ assert BATCH_PHASE_AGE_SECONDS_MAX.labels(phase="read")._value.get() == 0++ report_phase("write")+ consumer._report_health()+ assert BATCHES_IN_PHASE.labels(phase="write")._value.get() == 0++ def test_watchdog_trip_names_the_phase_the_batch_stopped_in(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import (+ batch_consumer as batch_consumer_module,+ )+ from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_phase++ consumer = _make_consumer(stuck_batch_timeout_seconds=0.0)+ calls: list[int] = []+ consumer._health_reporter = lambda: calls.append(1)+ batch = _make_batch()++ with consumer._batch_log_context(batch, attempt=1), patch.object(batch_consumer_module, "logger") as logger:+ report_phase("write")+ consumer._report_health()++ assert calls == [] # tripped: liveness withheld+ logger.error.assert_called_once()+ kwargs = logger.error.call_args.kwargs+ assert kwargs.get("batch_id") == batch.id+ assert kwargs.get("phase") == "write"+ assert kwargs.get("phase_seconds") is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v2_completed.json b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v2_completed.jsonnew file mode 100644index 000000000000..c7033a1c4641--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v2_completed.json@@ -0,0 +1,1020 @@+{+ "events": [+ {+ "eventId": "1",+ "eventTime": "2026-09-27T19:38:21.372Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",+ "workflowExecutionStartedEventAttributes": {+ "workflowType": {+ "name": "external-data-job"+ },+ "taskQueue": {+ "name": "record-history"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImV4dGVybmFsX2RhdGFfc2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwiZXh0ZXJuYWxfZGF0YV9zb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJyZXNldF9waXBlbGluZSI6bnVsbCwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "workflowExecutionTimeout": "315360000s",+ "workflowRunTimeout": "315360000s",+ "workflowTaskTimeout": "10s",+ "originalExecutionRunId": "e95ee3a5-5e3f-4ada-9b42-affaff3f9bbd",+ "identity": "1@replay-fixture",+ "firstExecutionRunId": "e95ee3a5-5e3f-4ada-9b42-affaff3f9bbd",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1+ },+ "attempt": 1,+ "firstWorkflowTaskBackoff": "0s",+ "priority": {}+ }+ },+ {+ "eventId": "2",+ "eventTime": "2026-09-27T19:38:21.372Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "3",+ "eventTime": "2026-09-27T19:38:21.373Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "historySizeBytes": "487"+ }+ },+ {+ "eventId": "4",+ "eventTime": "2026-09-27T19:38:21.386Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {+ "coreUsedFlags": [2, 1, 3],+ "sdkName": "temporal-python",+ "sdkVersion": "1.24.0"+ },+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "5",+ "eventTime": "2026-09-27T19:38:21.386Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "1",+ "activityType": {+ "name": "check_pipeline_version_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "3",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "6",+ "eventTime": "2026-09-27T19:38:21.386Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "5",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "7",+ "eventTime": "2026-09-27T19:38:21.388Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpc192MyI6ZmFsc2V9"+ }+ ]+ },+ "scheduledEventId": "5",+ "startedEventId": "6",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "8",+ "eventTime": "2026-09-27T19:38:21.388Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "9",+ "eventTime": "2026-09-27T19:38:21.388Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "historySizeBytes": "1176"+ }+ },+ {+ "eventId": "10",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "11",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "2",+ "activityType": {+ "name": "create_external_data_job_model_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImlzX3YzIjpmYWxzZSwic2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwic291cmNlX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBhIiwic3RhcnRlZF9ieV9zY2hlZHVsZSI6ZmFsc2UsInRlYW1faWQiOjF9"+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "9",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1,+ "nonRetryableErrorTypes": ["NotNullViolation", "IntegrityError"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "12",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "11",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "13",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsaW5nX2xpbWl0X2NoZWNrZWQiOmZhbHNlLCJlbWl0X3NpZ25hbHNfZW5hYmxlZCI6dHJ1ZSwiZW5yaWNobWVudF9lbmFibGVkIjpmYWxzZSwiZW5yaWNobWVudF9uZWVkZWQiOnRydWUsImZhc3RfcmV0dXJuX2VsaWdpYmxlIjpmYWxzZSwiaGl0X2JpbGxpbmdfbGltaXQiOmZhbHNlLCJpbmNyZW1lbnRhbF9vcl9hcHBlbmQiOmZhbHNlLCJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwicGVyc29uX3Byb3BlcnR5X3N5bmNfZW5hYmxlZCI6dHJ1ZSwicmVwYXJ0aXRpb25fbmVlZGVkIjp0cnVlLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX25hbWUiOiJDdXN0b21lciIsInNvdXJjZV90ZW1wbGF0ZXNfbmVlZGVkIjp0cnVlLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInN0YXRpc3RpY3NfZW5hYmxlZCI6ZmFsc2UsInN0YXRpc3RpY3NfbmVlZGVkIjp0cnVlfQ=="+ }+ ]+ },+ "scheduledEventId": "11",+ "startedEventId": "12",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "14",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "15",+ "eventTime": "2026-09-27T19:38:21.389Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "historySizeBytes": "2416"+ }+ },+ {+ "eventId": "16",+ "eventTime": "2026-09-27T19:38:21.390Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "17",+ "eventTime": "2026-09-27T19:38:21.390Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "3",+ "activityType": {+ "name": "check_billing_limits_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "15",+ "retryPolicy": {+ "initialInterval": "10s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "60s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "18",+ "eventTime": "2026-09-27T19:38:21.390Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "17",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "19",+ "eventTime": "2026-09-27T19:38:21.391Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "ZmFsc2U="+ }+ ]+ },+ "scheduledEventId": "17",+ "startedEventId": "18",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "20",+ "eventTime": "2026-09-27T19:38:21.391Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "21",+ "eventTime": "2026-09-27T19:38:21.391Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3007"+ }+ },+ {+ "eventId": "22",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "23",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "4",+ "activityType": {+ "name": "maybe_repartition_table_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "21600s",+ "heartbeatTimeout": "300s",+ "workflowTaskCompletedEventId": "21",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "24",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "23",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "25",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "23",+ "startedEventId": "24",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "26",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "27",+ "eventTime": "2026-09-27T19:38:21.392Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3705"+ }+ },+ {+ "eventId": "28",+ "eventTime": "2026-09-27T19:38:22.653Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "29",+ "eventTime": "2026-09-27T19:38:22.653Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "5",+ "activityType": {+ "name": "import_data_activity_sync"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJmYXN0X3JldHVybl9lbGlnaWJsZSI6ZmFsc2UsInJlc2V0X3BpcGVsaW5lIjpudWxsLCJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwic291cmNlX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBhIiwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "604800s",+ "heartbeatTimeout": "120s",+ "workflowTaskCompletedEventId": "27",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 20,+ "nonRetryableErrorTypes": ["NonRetryableException", "BillingLimitsWillBeReachedException"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "30",+ "eventTime": "2026-09-27T19:38:22.653Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "29",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "31",+ "eventTime": "2026-09-27T19:38:22.654Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJjb25zdW1lcl9tYW5hZ2VzX2pvYl9zdGF0dXMiOmZhbHNlLCJzaG91bGRfdHJpZ2dlcl9jZHBfcHJvZHVjZXIiOmZhbHNlLCJza2lwX3Bvc3RfaW1wb3J0X2FjdGl2aXRpZXMiOmZhbHNlfQ=="+ }+ ]+ },+ "scheduledEventId": "29",+ "startedEventId": "30",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "32",+ "eventTime": "2026-09-27T19:38:22.654Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "33",+ "eventTime": "2026-09-27T19:38:22.654Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "historySizeBytes": "4650"+ }+ },+ {+ "eventId": "34",+ "eventTime": "2026-09-27T19:38:22.659Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "35",+ "eventTime": "2026-09-27T19:38:22.659Z",+ "eventType": "EVENT_TYPE_MARKER_RECORDED",+ "markerRecordedEventAttributes": {+ "markerName": "core_patch",+ "details": {+ "patch-data": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpZCI6InYyLXBvc3QtaW1wb3J0LXdvcmtmbG93LTIwMjYtMDciLCJkZXByZWNhdGVkIjpmYWxzZX0="+ }+ ]+ }+ },+ "workflowTaskCompletedEventId": "33"+ }+ },+ {+ "eventId": "36",+ "eventTime": "2026-09-27T19:38:22.659Z",+ "eventType": "EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES",+ "upsertWorkflowSearchAttributesEventAttributes": {+ "workflowTaskCompletedEventId": "33",+ "searchAttributes": {+ "indexedFields": {+ "TemporalChangeVersion": {+ "metadata": {+ "type": "S2V5d29yZExpc3Q=",+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "WyJ2Mi1wb3N0LWltcG9ydC13b3JrZmxvdy0yMDI2LTA3Il0="+ }+ }+ }+ }+ },+ {+ "eventId": "37",+ "eventTime": "2026-09-27T19:38:22.659Z",+ "eventType": "EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED",+ "startChildWorkflowExecutionInitiatedEventAttributes": {+ "namespace": "default",+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ },+ "taskQueue": {+ "name": "data-warehouse-metadata-task-queue",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwic2F2ZWRfcXVlcnlfaWQiOm51bGwsInNjaGVtYV9pZCI6IjAxOTYwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwYiIsInNjaGVtYV9uYW1lIjoiQ3VzdG9tZXIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInRlYW1faWQiOjF9"+ }+ ]+ },+ "workflowExecutionTimeout": "21600s",+ "workflowRunTimeout": "0s",+ "workflowTaskTimeout": "10s",+ "parentClosePolicy": "PARENT_CLOSE_POLICY_ABANDON",+ "workflowTaskCompletedEventId": "33",+ "workflowIdReusePolicy": "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY",+ "header": {},+ "memo": {},+ "priority": {}+ }+ },+ {+ "eventId": "38",+ "eventTime": "2026-09-27T19:38:22.660Z",+ "eventType": "EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED",+ "childWorkflowExecutionStartedEventAttributes": {+ "namespace": "default",+ "initiatedEventId": "37",+ "workflowExecution": {+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "runId": "79572dce-afb6-4230-9cfd-9ccc7797f3a2"+ },+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ }+ }+ },+ {+ "eventId": "39",+ "eventTime": "2026-09-27T19:38:22.660Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "40",+ "eventTime": "2026-09-27T19:38:22.660Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "39",+ "identity": "1@replay-fixture",+ "historySizeBytes": "5803"+ }+ },+ {+ "eventId": "41",+ "eventTime": "2026-09-27T19:38:22.661Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "39",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "42",+ "eventTime": "2026-09-27T19:38:22.661Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "6",+ "activityType": {+ "name": "create_source_templates"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "600s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "40",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 2+ },+ "priority": {}+ }+ },+ {+ "eventId": "43",+ "eventTime": "2026-09-27T19:38:22.661Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "42",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "44",+ "eventTime": "2026-09-27T19:38:22.662Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "42",+ "startedEventId": "43",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "45",+ "eventTime": "2026-09-27T19:38:22.662Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "46",+ "eventTime": "2026-09-27T19:38:22.662Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "historySizeBytes": "6383"+ }+ },+ {+ "eventId": "47",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "48",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "7",+ "activityType": {+ "name": "update_external_data_job_model"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpbnRlcm5hbF9lcnJvciI6bnVsbCwiam9iX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwIiwibGF0ZXN0X2Vycm9yIjpudWxsLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzdGF0dXMiOiJDb21wbGV0ZWQiLCJ0ZWFtX2lkIjoxLCJ3b3JrZmxvd19ydW5faWQiOiJlOTVlZTNhNS01ZTNmLTRhZGEtOWI0Mi1hZmZhZmYzZjliYmQifQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "46",+ "retryPolicy": {+ "initialInterval": "10s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "60s",+ "nonRetryableErrorTypes": ["NotNullViolation", "IntegrityError", "DoesNotExist"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "49",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "48",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "50",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "48",+ "startedEventId": "49",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "51",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "52",+ "eventTime": "2026-09-27T19:38:22.663Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "historySizeBytes": "7240"+ }+ },+ {+ "eventId": "53",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "54",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED",+ "startChildWorkflowExecutionInitiatedEventAttributes": {+ "namespace": "default",+ "workflowId": "data-import-post-import-01960000-0000-0000-0000-000000000000",+ "workflowType": {+ "name": "data-import-post-import"+ },+ "taskQueue": {+ "name": "data-warehouse-task-queue",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "workflowExecutionTimeout": "0s",+ "workflowRunTimeout": "0s",+ "workflowTaskTimeout": "10s",+ "parentClosePolicy": "PARENT_CLOSE_POLICY_ABANDON",+ "workflowTaskCompletedEventId": "52",+ "workflowIdReusePolicy": "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY",+ "header": {},+ "memo": {},+ "priority": {}+ }+ },+ {+ "eventId": "55",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED",+ "childWorkflowExecutionStartedEventAttributes": {+ "namespace": "default",+ "initiatedEventId": "54",+ "workflowExecution": {+ "workflowId": "data-import-post-import-01960000-0000-0000-0000-000000000000",+ "runId": "42ae47e8-7c84-4233-b90b-48a869aa47aa"+ },+ "workflowType": {+ "name": "data-import-post-import"+ }+ }+ },+ {+ "eventId": "56",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "57",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "56",+ "identity": "1@replay-fixture",+ "historySizeBytes": "7980"+ }+ },+ {+ "eventId": "58",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "56",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "59",+ "eventTime": "2026-09-27T19:38:22.664Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",+ "workflowExecutionCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "workflowTaskCompletedEventId": "57"+ }+ }+ ]+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_with_batches_consumer_owned.json b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_with_batches_consumer_owned.jsonnew file mode 100644index 000000000000..efc38740b0c1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_with_batches_consumer_owned.json@@ -0,0 +1,936 @@+{+ "events": [+ {+ "eventId": "1",+ "eventTime": "2026-09-27T19:38:22.937Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",+ "workflowExecutionStartedEventAttributes": {+ "workflowType": {+ "name": "external-data-job"+ },+ "taskQueue": {+ "name": "record-history"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImV4dGVybmFsX2RhdGFfc2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwiZXh0ZXJuYWxfZGF0YV9zb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJyZXNldF9waXBlbGluZSI6bnVsbCwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "workflowExecutionTimeout": "315360000s",+ "workflowRunTimeout": "315360000s",+ "workflowTaskTimeout": "10s",+ "originalExecutionRunId": "65fdfad6-698d-46d8-81b4-c50dcec34f23",+ "identity": "1@replay-fixture",+ "firstExecutionRunId": "65fdfad6-698d-46d8-81b4-c50dcec34f23",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1+ },+ "attempt": 1,+ "firstWorkflowTaskBackoff": "0s",+ "priority": {}+ }+ },+ {+ "eventId": "2",+ "eventTime": "2026-09-27T19:38:22.937Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "3",+ "eventTime": "2026-09-27T19:38:22.938Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "historySizeBytes": "487"+ }+ },+ {+ "eventId": "4",+ "eventTime": "2026-09-27T19:38:22.942Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {+ "coreUsedFlags": [1, 2, 3],+ "sdkName": "temporal-python",+ "sdkVersion": "1.24.0"+ },+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "5",+ "eventTime": "2026-09-27T19:38:22.942Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "1",+ "activityType": {+ "name": "check_pipeline_version_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "3",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "6",+ "eventTime": "2026-09-27T19:38:22.942Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "5",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "7",+ "eventTime": "2026-09-27T19:38:22.943Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpc192MyI6dHJ1ZX0="+ }+ ]+ },+ "scheduledEventId": "5",+ "startedEventId": "6",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "8",+ "eventTime": "2026-09-27T19:38:22.943Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "9",+ "eventTime": "2026-09-27T19:38:22.943Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "historySizeBytes": "1175"+ }+ },+ {+ "eventId": "10",+ "eventTime": "2026-09-27T19:38:22.944Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "11",+ "eventTime": "2026-09-27T19:38:22.944Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "2",+ "activityType": {+ "name": "acquire_v3_pipeline_lock_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "9",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1+ },+ "priority": {}+ }+ },+ {+ "eventId": "12",+ "eventTime": "2026-09-27T19:38:22.944Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "11",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "13",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJhY3F1aXJlZCI6dHJ1ZSwidG9rZW4iOiJ0b2tlbiJ9"+ }+ ]+ },+ "scheduledEventId": "11",+ "startedEventId": "12",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "14",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "15",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "historySizeBytes": "1801"+ }+ },+ {+ "eventId": "16",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "17",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "3",+ "activityType": {+ "name": "create_external_data_job_model_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImlzX3YzIjp0cnVlLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzdGFydGVkX2J5X3NjaGVkdWxlIjpmYWxzZSwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "15",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1,+ "nonRetryableErrorTypes": ["NotNullViolation", "IntegrityError"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "18",+ "eventTime": "2026-09-27T19:38:22.945Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "17",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "19",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsaW5nX2xpbWl0X2NoZWNrZWQiOmZhbHNlLCJlbWl0X3NpZ25hbHNfZW5hYmxlZCI6dHJ1ZSwiZW5yaWNobWVudF9lbmFibGVkIjpmYWxzZSwiZW5yaWNobWVudF9uZWVkZWQiOnRydWUsImZhc3RfcmV0dXJuX2VsaWdpYmxlIjpmYWxzZSwiaGl0X2JpbGxpbmdfbGltaXQiOmZhbHNlLCJpbmNyZW1lbnRhbF9vcl9hcHBlbmQiOmZhbHNlLCJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwicGVyc29uX3Byb3BlcnR5X3N5bmNfZW5hYmxlZCI6dHJ1ZSwicmVwYXJ0aXRpb25fbmVlZGVkIjp0cnVlLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX25hbWUiOiJDdXN0b21lciIsInNvdXJjZV90ZW1wbGF0ZXNfbmVlZGVkIjp0cnVlLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInN0YXRpc3RpY3NfZW5hYmxlZCI6ZmFsc2UsInN0YXRpc3RpY3NfbmVlZGVkIjp0cnVlfQ=="+ }+ ]+ },+ "scheduledEventId": "17",+ "startedEventId": "18",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "20",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "21",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3040"+ }+ },+ {+ "eventId": "22",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "23",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "4",+ "activityType": {+ "name": "check_billing_limits_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "21",+ "retryPolicy": {+ "initialInterval": "10s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "60s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "24",+ "eventTime": "2026-09-27T19:38:22.946Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "23",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "25",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "ZmFsc2U="+ }+ ]+ },+ "scheduledEventId": "23",+ "startedEventId": "24",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "26",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "27",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3631"+ }+ },+ {+ "eventId": "28",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "29",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "5",+ "activityType": {+ "name": "maybe_repartition_table_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "21600s",+ "heartbeatTimeout": "300s",+ "workflowTaskCompletedEventId": "27",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "30",+ "eventTime": "2026-09-27T19:38:22.947Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "29",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "31",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "29",+ "startedEventId": "30",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "32",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "33",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "historySizeBytes": "4329"+ }+ },+ {+ "eventId": "34",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "35",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "6",+ "activityType": {+ "name": "import_data_activity_sync"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJmYXN0X3JldHVybl9lbGlnaWJsZSI6ZmFsc2UsInJlc2V0X3BpcGVsaW5lIjpudWxsLCJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwic291cmNlX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBhIiwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "604800s",+ "heartbeatTimeout": "120s",+ "workflowTaskCompletedEventId": "33",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 20,+ "nonRetryableErrorTypes": ["NonRetryableException", "BillingLimitsWillBeReachedException"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "36",+ "eventTime": "2026-09-27T19:38:22.948Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "35",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "37",+ "eventTime": "2026-09-27T19:38:22.949Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJjb25zdW1lcl9tYW5hZ2VzX2pvYl9zdGF0dXMiOnRydWUsInNob3VsZF90cmlnZ2VyX2NkcF9wcm9kdWNlciI6ZmFsc2UsInNraXBfcG9zdF9pbXBvcnRfYWN0aXZpdGllcyI6ZmFsc2V9"+ }+ ]+ },+ "scheduledEventId": "35",+ "startedEventId": "36",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "38",+ "eventTime": "2026-09-27T19:38:22.949Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "39",+ "eventTime": "2026-09-27T19:38:22.949Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "38",+ "identity": "1@replay-fixture",+ "historySizeBytes": "5273"+ }+ },+ {+ "eventId": "40",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "38",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "41",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_MARKER_RECORDED",+ "markerRecordedEventAttributes": {+ "markerName": "core_patch",+ "details": {+ "patch-data": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpZCI6InYzLWNvbnN1bWVyLXBvc3QtaW1wb3J0LTIwMjYtMDciLCJkZXByZWNhdGVkIjpmYWxzZX0="+ }+ ]+ }+ },+ "workflowTaskCompletedEventId": "39"+ }+ },+ {+ "eventId": "42",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES",+ "upsertWorkflowSearchAttributesEventAttributes": {+ "workflowTaskCompletedEventId": "39",+ "searchAttributes": {+ "indexedFields": {+ "TemporalChangeVersion": {+ "metadata": {+ "type": "S2V5d29yZExpc3Q=",+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "WyJ2My1jb25zdW1lci1wb3N0LWltcG9ydC0yMDI2LTA3Il0="+ }+ }+ }+ }+ },+ {+ "eventId": "43",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED",+ "startChildWorkflowExecutionInitiatedEventAttributes": {+ "namespace": "default",+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ },+ "taskQueue": {+ "name": "data-warehouse-metadata-task-queue",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwic2F2ZWRfcXVlcnlfaWQiOm51bGwsInNjaGVtYV9pZCI6IjAxOTYwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwYiIsInNjaGVtYV9uYW1lIjoiQ3VzdG9tZXIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInRlYW1faWQiOjF9"+ }+ ]+ },+ "workflowExecutionTimeout": "21600s",+ "workflowRunTimeout": "0s",+ "workflowTaskTimeout": "10s",+ "parentClosePolicy": "PARENT_CLOSE_POLICY_ABANDON",+ "workflowTaskCompletedEventId": "39",+ "workflowIdReusePolicy": "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY",+ "header": {},+ "memo": {},+ "priority": {}+ }+ },+ {+ "eventId": "44",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED",+ "childWorkflowExecutionStartedEventAttributes": {+ "namespace": "default",+ "initiatedEventId": "43",+ "workflowExecution": {+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "runId": "55329a9f-02db-4ca3-b53b-b09cd9793043"+ },+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ }+ }+ },+ {+ "eventId": "45",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "46",+ "eventTime": "2026-09-27T19:38:22.950Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "historySizeBytes": "6426"+ }+ },+ {+ "eventId": "47",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "48",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "7",+ "activityType": {+ "name": "create_source_templates"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "600s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "46",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 2+ },+ "priority": {}+ }+ },+ {+ "eventId": "49",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "48",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "50",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "48",+ "startedEventId": "49",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "51",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "52",+ "eventTime": "2026-09-27T19:38:22.951Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "historySizeBytes": "7006"+ }+ },+ {+ "eventId": "53",+ "eventTime": "2026-09-27T19:38:22.952Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "54",+ "eventTime": "2026-09-27T19:38:22.952Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",+ "workflowExecutionCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "workflowTaskCompletedEventId": "52"+ }+ }+ ]+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_zero_batches_completed.json b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_zero_batches_completed.jsonnew file mode 100644index 000000000000..1e54d56d1b89--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/histories/pre_phase2_v3_zero_batches_completed.json@@ -0,0 +1,1223 @@+{+ "events": [+ {+ "eventId": "1",+ "eventTime": "2026-09-27T19:38:22.801Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",+ "workflowExecutionStartedEventAttributes": {+ "workflowType": {+ "name": "external-data-job"+ },+ "taskQueue": {+ "name": "record-history"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImV4dGVybmFsX2RhdGFfc2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwiZXh0ZXJuYWxfZGF0YV9zb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJyZXNldF9waXBlbGluZSI6bnVsbCwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "workflowExecutionTimeout": "315360000s",+ "workflowRunTimeout": "315360000s",+ "workflowTaskTimeout": "10s",+ "originalExecutionRunId": "2621f121-d27f-42d5-be17-5a104605ef54",+ "identity": "1@replay-fixture",+ "firstExecutionRunId": "2621f121-d27f-42d5-be17-5a104605ef54",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1+ },+ "attempt": 1,+ "firstWorkflowTaskBackoff": "0s",+ "priority": {}+ }+ },+ {+ "eventId": "2",+ "eventTime": "2026-09-27T19:38:22.801Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "3",+ "eventTime": "2026-09-27T19:38:22.801Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "historySizeBytes": "487"+ }+ },+ {+ "eventId": "4",+ "eventTime": "2026-09-27T19:38:22.805Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "2",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {+ "coreUsedFlags": [2, 3, 1],+ "sdkName": "temporal-python",+ "sdkVersion": "1.24.0"+ },+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "5",+ "eventTime": "2026-09-27T19:38:22.805Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "1",+ "activityType": {+ "name": "check_pipeline_version_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "3",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "6",+ "eventTime": "2026-09-27T19:38:22.805Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "5",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "7",+ "eventTime": "2026-09-27T19:38:22.806Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpc192MyI6dHJ1ZX0="+ }+ ]+ },+ "scheduledEventId": "5",+ "startedEventId": "6",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "8",+ "eventTime": "2026-09-27T19:38:22.806Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "9",+ "eventTime": "2026-09-27T19:38:22.806Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "historySizeBytes": "1175"+ }+ },+ {+ "eventId": "10",+ "eventTime": "2026-09-27T19:38:22.806Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "8",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "11",+ "eventTime": "2026-09-27T19:38:22.806Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "2",+ "activityType": {+ "name": "acquire_v3_pipeline_lock_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "9",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1+ },+ "priority": {}+ }+ },+ {+ "eventId": "12",+ "eventTime": "2026-09-27T19:38:22.807Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "11",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "13",+ "eventTime": "2026-09-27T19:38:22.807Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJhY3F1aXJlZCI6dHJ1ZSwidG9rZW4iOiJ0b2tlbiJ9"+ }+ ]+ },+ "scheduledEventId": "11",+ "startedEventId": "12",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "14",+ "eventTime": "2026-09-27T19:38:22.807Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "15",+ "eventTime": "2026-09-27T19:38:22.807Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "historySizeBytes": "1801"+ }+ },+ {+ "eventId": "16",+ "eventTime": "2026-09-27T19:38:22.808Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "14",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "17",+ "eventTime": "2026-09-27T19:38:22.808Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "3",+ "activityType": {+ "name": "create_external_data_job_model_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsYWJsZSI6ZmFsc2UsImlzX3YzIjp0cnVlLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzdGFydGVkX2J5X3NjaGVkdWxlIjpmYWxzZSwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "15",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 1,+ "nonRetryableErrorTypes": ["NotNullViolation", "IntegrityError"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "18",+ "eventTime": "2026-09-27T19:38:22.808Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "17",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "19",+ "eventTime": "2026-09-27T19:38:22.809Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJiaWxsaW5nX2xpbWl0X2NoZWNrZWQiOmZhbHNlLCJlbWl0X3NpZ25hbHNfZW5hYmxlZCI6dHJ1ZSwiZW5yaWNobWVudF9lbmFibGVkIjpmYWxzZSwiZW5yaWNobWVudF9uZWVkZWQiOnRydWUsImZhc3RfcmV0dXJuX2VsaWdpYmxlIjpmYWxzZSwiaGl0X2JpbGxpbmdfbGltaXQiOmZhbHNlLCJpbmNyZW1lbnRhbF9vcl9hcHBlbmQiOmZhbHNlLCJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwicGVyc29uX3Byb3BlcnR5X3N5bmNfZW5hYmxlZCI6dHJ1ZSwicmVwYXJ0aXRpb25fbmVlZGVkIjp0cnVlLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX25hbWUiOiJDdXN0b21lciIsInNvdXJjZV90ZW1wbGF0ZXNfbmVlZGVkIjp0cnVlLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInN0YXRpc3RpY3NfZW5hYmxlZCI6ZmFsc2UsInN0YXRpc3RpY3NfbmVlZGVkIjp0cnVlfQ=="+ }+ ]+ },+ "scheduledEventId": "17",+ "startedEventId": "18",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "20",+ "eventTime": "2026-09-27T19:38:22.809Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "21",+ "eventTime": "2026-09-27T19:38:22.809Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3040"+ }+ },+ {+ "eventId": "22",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "20",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "23",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "4",+ "activityType": {+ "name": "check_billing_limits_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "21",+ "retryPolicy": {+ "initialInterval": "10s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "60s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "24",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "23",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "25",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "ZmFsc2U="+ }+ ]+ },+ "scheduledEventId": "23",+ "startedEventId": "24",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "26",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "27",+ "eventTime": "2026-09-27T19:38:22.810Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "historySizeBytes": "3631"+ }+ },+ {+ "eventId": "28",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "26",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "29",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "5",+ "activityType": {+ "name": "maybe_repartition_table_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "21600s",+ "heartbeatTimeout": "300s",+ "workflowTaskCompletedEventId": "27",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "30",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "29",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "31",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "29",+ "startedEventId": "30",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "32",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "33",+ "eventTime": "2026-09-27T19:38:22.811Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "historySizeBytes": "4329"+ }+ },+ {+ "eventId": "34",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "32",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "35",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "6",+ "activityType": {+ "name": "import_data_activity_sync"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJmYXN0X3JldHVybl9lbGlnaWJsZSI6ZmFsc2UsInJlc2V0X3BpcGVsaW5lIjpudWxsLCJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlZHVsZWRfZnVsbF9yZWZyZXNoIjpmYWxzZSwic2NoZW1hX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBiIiwic291cmNlX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDBhIiwidGVhbV9pZCI6MX0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "604800s",+ "heartbeatTimeout": "120s",+ "workflowTaskCompletedEventId": "33",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 20,+ "nonRetryableErrorTypes": ["NonRetryableException", "BillingLimitsWillBeReachedException"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "36",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "35",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "37",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJjb25zdW1lcl9tYW5hZ2VzX2pvYl9zdGF0dXMiOmZhbHNlLCJzaG91bGRfdHJpZ2dlcl9jZHBfcHJvZHVjZXIiOmZhbHNlLCJza2lwX3Bvc3RfaW1wb3J0X2FjdGl2aXRpZXMiOmZhbHNlfQ=="+ }+ ]+ },+ "scheduledEventId": "35",+ "startedEventId": "36",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "38",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "39",+ "eventTime": "2026-09-27T19:38:22.812Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "38",+ "identity": "1@replay-fixture",+ "historySizeBytes": "5274"+ }+ },+ {+ "eventId": "40",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "38",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "41",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_MARKER_RECORDED",+ "markerRecordedEventAttributes": {+ "markerName": "core_patch",+ "details": {+ "patch-data": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpZCI6InYyLXBvc3QtaW1wb3J0LXdvcmtmbG93LTIwMjYtMDciLCJkZXByZWNhdGVkIjpmYWxzZX0="+ }+ ]+ }+ },+ "workflowTaskCompletedEventId": "39"+ }+ },+ {+ "eventId": "42",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES",+ "upsertWorkflowSearchAttributesEventAttributes": {+ "workflowTaskCompletedEventId": "39",+ "searchAttributes": {+ "indexedFields": {+ "TemporalChangeVersion": {+ "metadata": {+ "type": "S2V5d29yZExpc3Q=",+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "WyJ2Mi1wb3N0LWltcG9ydC13b3JrZmxvdy0yMDI2LTA3Il0="+ }+ }+ }+ }+ },+ {+ "eventId": "43",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED",+ "startChildWorkflowExecutionInitiatedEventAttributes": {+ "namespace": "default",+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ },+ "taskQueue": {+ "name": "data-warehouse-metadata-task-queue",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJsYXN0X3N5bmNlZF9hdCI6bnVsbCwic2F2ZWRfcXVlcnlfaWQiOm51bGwsInNjaGVtYV9pZCI6IjAxOTYwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwYiIsInNjaGVtYV9uYW1lIjoiQ3VzdG9tZXIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzb3VyY2VfdHlwZSI6IlN0cmlwZSIsInRlYW1faWQiOjF9"+ }+ ]+ },+ "workflowExecutionTimeout": "21600s",+ "workflowRunTimeout": "0s",+ "workflowTaskTimeout": "10s",+ "parentClosePolicy": "PARENT_CLOSE_POLICY_ABANDON",+ "workflowTaskCompletedEventId": "39",+ "workflowIdReusePolicy": "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY",+ "header": {},+ "memo": {},+ "priority": {}+ }+ },+ {+ "eventId": "44",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED",+ "childWorkflowExecutionStartedEventAttributes": {+ "namespace": "default",+ "initiatedEventId": "43",+ "workflowExecution": {+ "workflowId": "sync-warehouse-person-properties-01960000-0000-0000-0000-000000000000",+ "runId": "bf5e0a47-2e68-4f53-a278-fb80c3e8835b"+ },+ "workflowType": {+ "name": "sync-warehouse-person-properties"+ }+ }+ },+ {+ "eventId": "45",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "46",+ "eventTime": "2026-09-27T19:38:22.814Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "historySizeBytes": "6427"+ }+ },+ {+ "eventId": "47",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "45",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "48",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "7",+ "activityType": {+ "name": "create_source_templates"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJydW5faWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "600s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "46",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 2+ },+ "priority": {}+ }+ },+ {+ "eventId": "49",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "48",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "50",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "48",+ "startedEventId": "49",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "51",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "52",+ "eventTime": "2026-09-27T19:38:22.815Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "historySizeBytes": "7007"+ }+ },+ {+ "eventId": "53",+ "eventTime": "2026-09-27T19:38:22.816Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "51",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "54",+ "eventTime": "2026-09-27T19:38:22.816Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "8",+ "activityType": {+ "name": "update_external_data_job_model"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJpbnRlcm5hbF9lcnJvciI6bnVsbCwiam9iX2lkIjoiMDE5NjAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwIiwibGF0ZXN0X2Vycm9yIjpudWxsLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJzdGF0dXMiOiJDb21wbGV0ZWQiLCJ0ZWFtX2lkIjoxLCJ3b3JrZmxvd19ydW5faWQiOiIyNjIxZjEyMS1kMjdmLTQyZDUtYmUxNy01YTEwNDYwNWVmNTQifQ=="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "52",+ "retryPolicy": {+ "initialInterval": "10s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "60s",+ "nonRetryableErrorTypes": ["NotNullViolation", "IntegrityError", "DoesNotExist"]+ },+ "priority": {}+ }+ },+ {+ "eventId": "55",+ "eventTime": "2026-09-27T19:38:22.816Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "54",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "56",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "54",+ "startedEventId": "55",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "57",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "58",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "57",+ "identity": "1@replay-fixture",+ "historySizeBytes": "7864"+ }+ },+ {+ "eventId": "59",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "57",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "60",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",+ "activityTaskScheduledEventAttributes": {+ "activityId": "9",+ "activityType": {+ "name": "release_v3_pipeline_lock_activity"+ },+ "taskQueue": {+ "name": "record-history",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "header": {},+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJ0ZWFtX2lkIjoxLCJ0b2tlbiI6InRva2VuIn0="+ }+ ]+ },+ "scheduleToCloseTimeout": "315360000s",+ "scheduleToStartTimeout": "315360000s",+ "startToCloseTimeout": "60s",+ "heartbeatTimeout": "0s",+ "workflowTaskCompletedEventId": "58",+ "retryPolicy": {+ "initialInterval": "1s",+ "backoffCoefficient": 2.0,+ "maximumInterval": "100s",+ "maximumAttempts": 3+ },+ "priority": {}+ }+ },+ {+ "eventId": "61",+ "eventTime": "2026-09-27T19:38:22.817Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",+ "activityTaskStartedEventAttributes": {+ "scheduledEventId": "60",+ "identity": "1@replay-fixture",+ "attempt": 1+ }+ },+ {+ "eventId": "62",+ "eventTime": "2026-09-27T19:38:22.818Z",+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",+ "activityTaskCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "scheduledEventId": "60",+ "startedEventId": "61",+ "identity": "1@replay-fixture"+ }+ },+ {+ "eventId": "63",+ "eventTime": "2026-09-27T19:38:22.818Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "64",+ "eventTime": "2026-09-27T19:38:22.818Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "63",+ "identity": "1@replay-fixture",+ "historySizeBytes": "8472"+ }+ },+ {+ "eventId": "65",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "63",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "66",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED",+ "startChildWorkflowExecutionInitiatedEventAttributes": {+ "namespace": "default",+ "workflowId": "data-import-post-import-01960000-0000-0000-0000-000000000000",+ "workflowType": {+ "name": "data-import-post-import"+ },+ "taskQueue": {+ "name": "data-warehouse-task-queue",+ "kind": "TASK_QUEUE_KIND_NORMAL"+ },+ "input": {+ "payloads": [+ {+ "metadata": {+ "encoding": "anNvbi9wbGFpbg=="+ },+ "data": "eyJqb2JfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY2hlbWFfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGIiLCJzb3VyY2VfaWQiOiIwMTk2MDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMGEiLCJ0ZWFtX2lkIjoxfQ=="+ }+ ]+ },+ "workflowExecutionTimeout": "0s",+ "workflowRunTimeout": "0s",+ "workflowTaskTimeout": "10s",+ "parentClosePolicy": "PARENT_CLOSE_POLICY_ABANDON",+ "workflowTaskCompletedEventId": "64",+ "workflowIdReusePolicy": "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY",+ "header": {},+ "memo": {},+ "priority": {}+ }+ },+ {+ "eventId": "67",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED",+ "childWorkflowExecutionStartedEventAttributes": {+ "namespace": "default",+ "initiatedEventId": "66",+ "workflowExecution": {+ "workflowId": "data-import-post-import-01960000-0000-0000-0000-000000000000",+ "runId": "67e10f73-56f3-4b95-983b-f1aaf8feb9d5"+ },+ "workflowType": {+ "name": "data-import-post-import"+ }+ }+ },+ {+ "eventId": "68",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",+ "workflowTaskScheduledEventAttributes": {+ "taskQueue": {+ "name": "record-history"+ },+ "startToCloseTimeout": "10s",+ "attempt": 1+ }+ },+ {+ "eventId": "69",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",+ "workflowTaskStartedEventAttributes": {+ "scheduledEventId": "68",+ "identity": "1@replay-fixture",+ "historySizeBytes": "9212"+ }+ },+ {+ "eventId": "70",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",+ "workflowTaskCompletedEventAttributes": {+ "scheduledEventId": "68",+ "identity": "1@replay-fixture",+ "binaryChecksum": "10fdcdf48e7ccec05915a93bf59804fc",+ "sdkMetadata": {},+ "meteringMetadata": {}+ }+ },+ {+ "eventId": "71",+ "eventTime": "2026-09-27T19:38:22.819Z",+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",+ "workflowExecutionCompletedEventAttributes": {+ "result": {+ "payloads": [+ {+ "metadata": {+ "encoding": "YmluYXJ5L251bGw="+ }+ }+ ]+ },+ "workflowTaskCompletedEventId": "69"+ }+ }+ ]+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.pyindex c27e98b1af84..30bc0b41b70e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py@@ -189,6 +189,53 @@ class TestUpdateExternalDataJobModelActivity(BaseTest):mock_finish_row_tracking.assert_called_once_with(self.team.id, inputs.schema_id)mock_update_job_status.assert_called_once()+ @parameterized.expand(+ [+ ("handed_a_token", "run-token", ["update", "release"]),+ ("no_token", None, ["update"]),+ ]+ )+ def test_releases_the_v3_lock_only_when_handed_a_token_and_after_the_status_write(+ self, _name: str, release_lock_token: str | None, expected_calls: list[str]+ ) -> None:+ env = ActivityEnvironment()+ inputs = UpdateExternalDataJobStatusInputs(+ team_id=self.team.id,+ job_id="019fde98-0727-0000-3f05-9991b4c84155",+ schema_id="019fde98-0727-0000-3f05-9991b4c84156",+ source_id="019fde98-0727-0000-3f05-9991b4c84157",+ status=ExternalDataJob.Status.FAILED,+ internal_error=None,+ latest_error=None,+ release_lock_token=release_lock_token,+ )+ calls = mock.Mock()++ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_rows",+ return_value=0,+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.finish_row_tracking"+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.update_external_job_status",+ calls.update,+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.release_v3_pipeline_lock",+ calls.release,+ ),+ ):+ asyncio.run(env.run(update_external_data_job_model, inputs))++ # The release must follow the status write: releasing first would let the next run start+ # while this one's terminal status is still unwritten.+ assert [call[0] for call in calls.mock_calls] == expected_calls+ if release_lock_token is not None:+ calls.release.assert_called_once_with(self.team.id, inputs.schema_id, release_lock_token)+# transaction=True commits the fixture rows: the activity resolves the schema through# database_sync_to_async_pool, whose pool-thread connection can't see a test transaction.diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_replay.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_replay.pynew file mode 100644index 000000000000..32d7c4b657f5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_replay.py@@ -0,0 +1,35 @@+"""Replay compatibility of `external-data-job`.++The histories under `histories/` were recorded from the workflow as it was before the per-run+activities were folded together (billing check into job creation, lock release into the finalizer,+the templates activity gated). On deploy every in-flight execution replays its recorded history+against the new code, so each of these must replay without a non-determinism error: the new code+must keep issuing the old command sequence wherever the recorded activity payloads or missing patch+markers say so.+"""++from pathlib import Path++import pytest+from unittest import mock++from temporalio.client import WorkflowHistory+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner++from products.warehouse_sources.backend.temporal.data_imports.external_data_job import ExternalDataJobWorkflow++HISTORIES = Path(__file__).parent / "histories"++[email protected]("history_name", sorted(path.stem for path in HISTORIES.glob("*.json")))+async def test_pre_change_history_replays(history_name: str) -> None:+ history = WorkflowHistory.from_json("external-data-job", (HISTORIES / f"{history_name}.json").read_text())++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"+ ):+ await Replayer(+ workflows=[ExternalDataJobWorkflow],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ).replay_workflow(history)diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.pyindex 2bc248ba4155..892586bfbdfa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py@@ -22,6 +22,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.temporal.utils import ExternalDataWorkflowInputs+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.external_data_job import (CreateSourceTemplateInputs,ExternalDataJobWorkflow,@@ -67,6 +68,9 @@ def _stub_activities(source_has_new_data: bool = True,scheduled_full_refresh: bool = False,repartition_needed: bool = True,+ billing_limit_checked: bool = True,+ hit_billing_limit: bool = False,+ source_templates_needed: bool = True,) -> list:@activity.defn(name="check_pipeline_version_activity")async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:@@ -98,6 +102,9 @@ def _stub_activities(fast_return_eligible=fast_return_eligible,scheduled_full_refresh=scheduled_full_refresh,repartition_needed=repartition_needed,+ billing_limit_checked=billing_limit_checked,+ hit_billing_limit=hit_billing_limit,+ source_templates_needed=source_templates_needed,)@activity.defn(name="check_billing_limits_activity")@@ -137,6 +144,9 @@ def _stub_activities(@activity.defn(name="update_external_data_job_model")async def update_job(inputs: UpdateExternalDataJobStatusInputs) -> None:executed.append("update_external_data_job_model")+ executed.append(f"update_external_data_job_model:status={inputs.status}")+ if inputs.release_lock_token is not None:+ executed.append(f"update_external_data_job_model:release_lock_token={inputs.release_lock_token}")return [check_pipeline_version,@@ -161,6 +171,9 @@ async def _run_workflow(source_has_new_data: bool = True,scheduled_full_refresh: bool = False,repartition_needed: bool = True,+ billing_limit_checked: bool = True,+ hit_billing_limit: bool = False,+ source_templates_needed: bool = True,) -> tuple[list[str], list[str]]:"""Run the workflow with stubbed activities; return (executed activities + child starts inorder, started child ids)."""@@ -193,6 +206,9 @@ async def _run_workflow(source_has_new_data=source_has_new_data,scheduled_full_refresh=scheduled_full_refresh,repartition_needed=repartition_needed,+ billing_limit_checked=billing_limit_checked,+ hit_billing_limit=hit_billing_limit,+ source_templates_needed=source_templates_needed,),workflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=10),@@ -324,6 +340,62 @@ async def test_repartition_activity_is_scheduled_only_when_job_creation_finds_woassert "import_data_activity_sync" in executed+ "billing_limit_checked,hit_billing_limit,expect_check_activity,expect_import",+ [+ pytest.param(True, False, False, True, id="answered_under_limit_syncs"),+ pytest.param(True, True, False, False, id="answered_over_limit_stops_the_run"),+ pytest.param(False, False, True, True, id="legacy_payload_runs_the_check_activity"),+ ],+)+async def test_billing_limit_answered_by_job_creation_skips_the_check_activity(+ billing_limit_checked: bool, hit_billing_limit: bool, expect_check_activity: bool, expect_import: bool+) -> None:+ executed, _ = await _run_workflow(+ is_v3=False,+ consumer_manages_job_status=False,+ billing_limit_checked=billing_limit_checked,+ hit_billing_limit=hit_billing_limit,+ )++ assert ("check_billing_limits_activity" in executed) is expect_check_activity+ assert ("import_data_activity_sync" in executed) is expect_import+ expected_status = (+ ExternalDataJob.Status.COMPLETED if expect_import else ExternalDataJob.Status.BILLING_LIMIT_REACHED+ )+ assert f"update_external_data_job_model:status={expected_status}" in executed++[email protected]("source_templates_needed", [True, False])+async def test_source_templates_activity_runs_only_when_job_creation_finds_work(source_templates_needed: bool) -> None:+ executed, _ = await _run_workflow(+ is_v3=False, consumer_manages_job_status=False, source_templates_needed=source_templates_needed+ )++ assert ("create_source_templates" in executed) is source_templates_needed+ assert "update_external_data_job_model" in executed+++ "is_v3,consumer_manages_job_status,expect_finalizer_releases",+ [+ pytest.param(True, False, True, id="v3_zero_batches_finalizer_releases"),+ pytest.param(True, True, False, id="v3_with_batches_leaves_lock_to_the_loader"),+ pytest.param(False, False, False, id="v2_has_no_lock"),+ ],+)+async def test_v3_lock_release_rides_the_finalizer(+ is_v3: bool, consumer_manages_job_status: bool, expect_finalizer_releases: bool+) -> None:+ executed, _ = await _run_workflow(is_v3=is_v3, consumer_manages_job_status=consumer_manages_job_status)++ assert "release_v3_pipeline_lock_activity" not in executed+ assert ("update_external_data_job_model:release_lock_token=token" in executed) is expect_finalizer_releases++@pytest.mark.parametrize("search_attributes,expected",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.pyindex 4d4d7b1ce7c4..1606d885cc9c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py@@ -4,14 +4,19 @@ from datetime import UTC, datetimefrom django.db import close_old_connections+import redisfrom structlog.contextvars import bind_contextvars+from structlog.types import FilteringBoundLoggerfrom temporalio import activity+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom posthog.models.team.team import Teamfrom posthog.settings.base_variables import TESTfrom posthog.temporal.common.logger import get_loggerfrom products.warehouse_sources.backend.billing import FREE_HISTORICAL_WINDOW, FREE_PERIOD_END, FREE_PERIOD_START+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retriesfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited@@ -32,30 +37,27 @@ class CheckBillingLimitsActivityInputs:}-@with_internal_db_retries-def check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> bool:- from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (- ExternalDataJob,- ExternalDataSource,- )+# The limiter list lives in Redis. Inside the job-creation activity this check has a single Temporal+# attempt (a retry there would create a duplicate job row), so a connection blip is absorbed here+# instead of failing the run.+@retry(+ retry=retry_if_exception_type((redis.exceptions.ConnectionError, redis.exceptions.TimeoutError)),+ stop=stop_after_attempt(3),+ wait=wait_exponential_jitter(initial=0.5, max=2),+ reraise=True,+)+def _team_is_rows_synced_limited(api_token: str) -> bool:+ return is_team_limited(api_token, QuotaResource.ROWS_SYNCED, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()- close_old_connections()-- try:- job = ExternalDataJob.objects.get(id=inputs.job_id)- except ExternalDataJob.DoesNotExist:- # job_id can be None (or point at a job that no longer exists) when this input came- # from an older worker's create_external_data_job_model_activity result — that legacy- # compatibility path doesn't guarantee a job was created. Nothing to bill for, so let- # the sync proceed rather than fail the whole workflow.- logger.info("Skipping billing limits check: job does not exist", job_id=inputs.job_id)- return False- source: ExternalDataSource = job.pipeline+def billing_limit_reached(+ job: ExternalDataJob, source: ExternalDataSource, team_id: int, logger: FilteringBoundLogger+) -> bool:+ """Whether this run must stop because the team is over its synced-rows quota.+ The decision only needs the job's billable flag and the source's age, so the job-creation+ activity can answer it in the same round trip that creates the job row.+ """if not job.billable:logger.info("Skipping billing limits check for non-billable job")return False@@ -72,10 +74,30 @@ def check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> b)return False- team: Team = Team.objects.only("api_token").get(id=inputs.team_id)+ team: Team = Team.objects.only("api_token").get(id=team_id)- if is_team_limited(team.api_token, QuotaResource.ROWS_SYNCED, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY):+ if _team_is_rows_synced_limited(team.api_token):logger.info("Billing limits hit. Canceling sync")return Truereturn False+++@with_internal_db_retries+def check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> bool:+ bind_contextvars(team_id=inputs.team_id)+ logger = LOGGER.bind()+ close_old_connections()++ try:+ job = ExternalDataJob.objects.get(id=inputs.job_id)+ except ExternalDataJob.DoesNotExist:+ # job_id can be None (or point at a job that no longer exists) when this input came+ # from an older worker's create_external_data_job_model_activity result — that legacy+ # compatibility path doesn't guarantee a job was created. Nothing to bill for, so let+ # the sync proceed rather than fail the whole workflow.+ logger.info("Skipping billing limits check: job does not exist", job_id=inputs.job_id)+ return False++ return billing_limit_reached(job, job.pipeline, inputs.team_id, logger)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.pyindex 22485d75b4d8..d2a1d22b61b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py@@ -10,15 +10,18 @@ exact, whole-table, correct for full-refresh/append/incremental-upsert (live addcurrent files), and scales to any table size. Results land in `WarehouseColumnStatistics`, fullysystem-owned and overwritten on each run. To avoid re-profiling an hourly-syncing table every hour,a row computed within `MIN_RECOMPUTE_INTERVAL` is left alone, and a table whose Delta version has not-moved since the last computation is left alone until `MAX_RECOMPUTE_INTERVAL` has passed.+moved since the last computation is left alone until `MAX_RECOMPUTE_INTERVAL` has passed. A table that+only gained files since then folds the new files' stats into the stored rows instead of rescanning+every live file; any other change falls back to the full scan."""import osimport jsonimport uuidimport dataclasses-from collections.abc import Iterable-from datetime import timedelta+from collections.abc import Callable, Iterable+from datetime import date, datetime, timedelta+from decimal import Decimalfrom typing import Anyfrom django.conf import settings@@ -57,6 +60,9 @@ MIN_RECOMPUTE_INTERVAL = timedelta(hours=int(os.getenv("WAREHOUSE_STATS_MIN_RECO# Add-action scan (the expensive step) can be skipped. The cap still forces a recompute so a change in# the table's registered columns, or in how stats are derived, reaches every table eventually.MAX_RECOMPUTE_INTERVAL = timedelta(days=int(os.getenv("WAREHOUSE_STATS_MAX_RECOMPUTE_INTERVAL_DAYS", "7")))+# Each commit since the last computation is one small object-store read; past this many the full+# Add-action scan is the cheaper path again.+MAX_INCREMENTAL_COMMITS = int(os.getenv("WAREHOUSE_STATS_MAX_INCREMENTAL_COMMITS", "200"))# Product-analytics events — query these to track statistics volume, columns profiled, skips, and errors.EVENT_STARTED = "data warehouse table statistics started"@@ -205,6 +211,234 @@ def _most_recent_computed_version(return min(versions) if versions else None+def _most_recent_full_scan_at(+ existing: dict[str, WarehouseColumnStatistics], current_columns: Iterable[str]+) -> datetime | None:+ """Oldest full-scan time among currently-registered columns, not the newest.++ `computed_at` is bumped on every write, fold included, so it cannot answer "how long has it been+ since a full scan last corrected drift" — `full_scan_at` is left untouched by a fold (see+ `_upsert_statistics`) so it still can. A row written before that field existed has it as None, and+ every such row predates incremental folding, so its `computed_at` was necessarily a full scan's.+ Oldest-of and scoped to `current_columns` for the same partial-write and dropped-column hazards as+ `_most_recent_computed_at`.+ """+ times: list[datetime] = []+ for name, stored in existing.items():+ full_scan_at = stored.full_scan_at or stored.computed_at+ if name in current_columns and full_scan_at is not None:+ times.append(full_scan_at)+ return min(times) if times else None+++ReadCommitActions = Callable[[int], list[dict[str, Any]]]+++def _read_commit_actions(table_uri: str, storage_options: dict[str, str], version: int) -> list[dict[str, Any]]:+ """The actions of one Delta commit, read from its `_delta_log` JSON through delta-rs's own store+ handler, so credentials and endpoints resolve exactly as they did for the table open."""+ import pyarrow.fs as pafs # noqa: PLC0415 — heavy dep kept off this module's flag-check import path+ from deltalake.fs import DeltaStorageHandler # noqa: PLC0415++ filesystem = pafs.PyFileSystem(DeltaStorageHandler(table_uri, storage_options))+ with filesystem.open_input_stream(f"_delta_log/{version:020d}.json") as stream:+ raw = stream.read()+ # Floats as Decimal: a decimal column's stats arrive as JSON numbers, and a float would lose+ # the digits the stored representation keeps.+ return [json.loads(line, parse_float=Decimal) for line in raw.decode().splitlines() if line.strip()]+++# Actions a commit may carry without touching the live file set or the schema. Anything else+# (`remove`, `metaData`, `cdc`, or an action this list does not know) sends the recompute down the+# full path.+_NEUTRAL_ACTIONS = frozenset({"commitInfo", "txn", "protocol", "domainMetadata"})++# Bases a fold may chain onto: a full scan ("delta_log") or a previous fold ("incremental"). Both are+# rows this pipeline derived from the Delta log, so both carry numbers exact enough to fold further.+_FOLDABLE_BASES = frozenset({"delta_log", "incremental"})+++class _UnparseableValue(Exception):+ """A stored or logged min/max could not be parsed as the column's current Delta type.++ Raised instead of the underlying `ValueError`/`ArithmeticError`, whose message embeds the raw+ text a builtin conversion (`int()`, `Decimal()`, `date.fromisoformat()`...) rejected — which can+ be a real customer value. This message never does, so the fold's `except Exception` handler can+ report it to logs and Sentry safely.+ """+++def _parse_stored_value(delta_type: Any, text: str) -> Any:+ """Parse a stored min/max back into the Python value `str()` produced from the Add-action scan.++ Wraps a builtin conversion failure (`int()`, `Decimal()`, `date.fromisoformat()`...) in+ `_UnparseableValue` instead of letting it propagate: those exceptions embed the raw text in their+ message, which can be a real customer value, and the caller reports this exception's `str()` to+ logs and Sentry. `from None` drops the original as this exception's cause, so neither the+ chained message nor its traceback locals reach that report.+ """+ if not isinstance(delta_type, str):+ raise TypeError("nested types carry no min/max")+ try:+ if delta_type in ("byte", "short", "integer", "long"):+ return int(text)+ if delta_type in ("float", "double"):+ return float(text)+ if delta_type == "string":+ return text+ if delta_type == "boolean":+ return text == "True"+ if delta_type == "date":+ return date.fromisoformat(text)+ if delta_type in ("timestamp", "timestamp_ntz"):+ return datetime.fromisoformat(text)+ if delta_type.startswith("decimal("):+ return Decimal(text)+ except (ValueError, ArithmeticError):+ raise _UnparseableValue(f"cannot parse stored value as {delta_type}") from None+ raise TypeError(f"no stored representation for {delta_type}")+++def _parse_log_value(delta_type: Any, value: Any) -> Any:+ """Coerce a commit-log stats value to the Python type the Add-action scan yields for the column,+ so a folded min/max stores the same text the full path would.++ See `_parse_stored_value` for why a conversion failure is wrapped rather than left to propagate.+ """+ if not isinstance(delta_type, str) or isinstance(value, dict | list):+ raise TypeError("nested types carry no min/max")+ try:+ if delta_type in ("byte", "short", "integer", "long"):+ return int(value)+ if delta_type in ("float", "double"):+ return float(value)+ if delta_type == "string":+ if not isinstance(value, str):+ raise TypeError("string stats must be strings")+ return value+ if delta_type == "boolean":+ if not isinstance(value, bool):+ raise TypeError("boolean stats must be booleans")+ return value+ if delta_type == "date":+ return date.fromisoformat(value)+ if delta_type in ("timestamp", "timestamp_ntz"):+ return datetime.fromisoformat(value)+ if delta_type.startswith("decimal("):+ scale = int(delta_type[len("decimal(") : -1].split(",")[1])+ return Decimal(value).quantize(Decimal(1).scaleb(-scale))+ except (ValueError, ArithmeticError):+ raise _UnparseableValue(f"cannot parse log value as {delta_type}") from None+ raise TypeError(f"no log representation for {delta_type}")++[email protected](frozen=False)+class _FoldState:+ """One column's running aggregate while new commits fold into the stored statistics."""++ delta_type: Any+ null_count: int | None+ min_value: Any+ max_value: Any++ def fold(self, stats: dict[str, Any], name: str) -> None:+ # The flattened Add-action scan keys a nested column's stats by leaf (`min.payload.x`), so+ # the full path records nothing for the column itself; a partition column has no stats at+ # all. Both stay as they are.+ if not isinstance(self.delta_type, str):+ return+ null_count = stats.get("nullCount", {}).get(name)+ if isinstance(null_count, int) and not isinstance(null_count, bool):+ self.null_count = (self.null_count or 0) + null_count+ min_value = stats.get("minValues", {}).get(name)+ if min_value is not None:+ parsed = _parse_log_value(self.delta_type, min_value)+ self.min_value = parsed if self.min_value is None else min(self.min_value, parsed)+ max_value = stats.get("maxValues", {}).get(name)+ if max_value is not None:+ parsed = _parse_log_value(self.delta_type, max_value)+ self.max_value = parsed if self.max_value is None else max(self.max_value, parsed)+++def _fold_commit_stats(+ *,+ existing: dict[str, WarehouseColumnStatistics],+ columns: dict[str, Any],+ delta_schema_fields: dict[str, Any],+ base_version: int,+ delta_version: int,+ read_commit_actions: ReadCommitActions,+) -> tuple[int, dict[str, _ColumnStat]] | None:+ """Fold the files added since `base_version` into the stored statistics.++ Row counts, null counts and min/max all combine file by file, so when every commit since the+ stored version only added files the stored numbers plus the new files' stats equal what the+ full scan would compute. Returns None whenever that does not hold — a removed file, a schema+ change, a file without stats, a column the stored rows do not cover — and the caller runs the+ full scan instead.+ """+ if delta_version <= base_version or delta_version - base_version > MAX_INCREMENTAL_COMMITS:+ return None++ row_counts: set[int] = set()+ states: dict[str, _FoldState] = {}+ for name in columns:+ stored = existing.get(name)+ if (+ stored is None+ or stored.computed_for_delta_version != base_version+ or stored.stats_basis not in _FOLDABLE_BASES+ or stored.row_count is None+ ):+ return None+ row_counts.add(stored.row_count)+ delta_type = delta_schema_fields.get(name)+ states[name] = _FoldState(+ delta_type=delta_type,+ null_count=stored.null_count,+ min_value=_parse_stored_value(delta_type, stored.min_value) if stored.min_value is not None else None,+ max_value=_parse_stored_value(delta_type, stored.max_value) if stored.max_value is not None else None,+ )+ if len(row_counts) != 1:+ return None+ row_count = row_counts.pop()++ for version in range(base_version + 1, delta_version + 1):+ for action in read_commit_actions(version):+ kinds = set(action) - _NEUTRAL_ACTIONS+ if not kinds:+ continue+ if kinds != {"add"}:+ return None+ add = action["add"]+ if not add.get("dataChange", True) or not add.get("stats"):+ return None+ stats = json.loads(add["stats"], parse_float=Decimal)+ num_records = stats.get("numRecords")+ if not isinstance(num_records, int) or isinstance(num_records, bool):+ return None+ row_count += num_records+ for name, state in states.items():+ state.fold(stats, name)++ return row_count, {+ name: _ColumnStat(+ column_type=clean_type(_column_type(columns[name])) or "unknown",+ null_count=state.null_count,+ min_value=str(state.min_value) if state.min_value is not None else None,+ max_value=str(state.max_value) if state.max_value is not None else None,+ has_min_max=state.min_value is not None or state.max_value is not None,+ )+ for name, state in states.items()+ }+++def _delta_schema_fields(delta_table: Any) -> dict[str, Any]:+ """Column name to Delta type: a string for a primitive, a dict for a nested type."""+ schema = json.loads(delta_table.schema().to_json())+ return {field["name"]: field["type"] for field in schema.get("fields", [])}++def _all_columns_have_stats(existing: dict[str, WarehouseColumnStatistics], current_columns: Iterable[str]) -> bool:"""Whether every currently-registered column has a statistics row at all.@@ -324,16 +558,28 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[stemit_completed("skipped", reason="no_columns")return {"status": "skipped", "reason": "no_columns"}- add_actions = delta_table.get_add_actions(flatten=True)- if add_actions.num_rows == 0:- emit_completed("skipped", reason="no_files")- return {"status": "skipped", "reason": "no_files"}-- row_count, stats_by_column = _aggregate_add_action_stats(add_actions, columns)+ folded = _fold_since_stored_version(+ delta_table=delta_table,+ storage_options=delta_table_ref.get_storage_options(),+ existing=existing,+ columns=columns,+ delta_version=delta_version,+ log=log,+ )+ if folded is not None:+ row_count, stats_by_column = folded+ basis = "incremental"+ else:+ add_actions = delta_table.get_add_actions(flatten=True)+ if add_actions.num_rows == 0:+ emit_completed("skipped", reason="no_files")+ return {"status": "skipped", "reason": "no_files"}+ row_count, stats_by_column = _aggregate_add_action_stats(add_actions, columns)+ basis = "full"try:for column_name, stat in stats_by_column.items():- _upsert_statistics(team, table, column_name, row_count, stat, delta_version)+ _upsert_statistics(team, table, column_name, row_count, stat, delta_version, basis)except (OperationalError, InterfaceError):# The Delta-log read above can run long enough for the Postgres connection opened by the# earlier metadata queries (team/schema/existing-stats) to go stale — server restart, proxy@@ -344,11 +590,50 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[stif not settings.TEST:close_old_connections()for column_name, stat in stats_by_column.items():- _upsert_statistics(team, table, column_name, row_count, stat, delta_version)+ _upsert_statistics(team, table, column_name, row_count, stat, delta_version, basis)- log.info("warehouse_statistics.done", columns=len(stats_by_column), row_count=row_count)- emit_completed("done", columns=len(stats_by_column), row_count=row_count, delta_version=delta_version)- return {"status": "done", "columns": len(stats_by_column), "row_count": row_count}+ log.info("warehouse_statistics.done", columns=len(stats_by_column), row_count=row_count, basis=basis)+ emit_completed("done", columns=len(stats_by_column), row_count=row_count, delta_version=delta_version, basis=basis)+ return {"status": "done", "columns": len(stats_by_column), "row_count": row_count, "basis": basis}+++def _fold_since_stored_version(+ *,+ delta_table: Any,+ storage_options: dict[str, str],+ existing: dict[str, WarehouseColumnStatistics],+ columns: dict[str, Any],+ delta_version: int,+ log: Any,+) -> tuple[int, dict[str, _ColumnStat]] | None:+ """Try the incremental fold; None means the caller runs the full Add-action scan.++ Only while the last full scan is inside MAX_RECOMPUTE_INTERVAL: the periodic full scan still+ happens, so a fold that drifted (a truncated string bound, say) is corrected within that window.+ Gating on the last full scan rather than the last write matters because a fold does not reset+ the clock (see `_upsert_statistics`) — otherwise a table folding more often than that interval+ would never fall back to a full scan at all.+ """+ base_version = _most_recent_computed_version(existing, columns)+ last_full_scan = _most_recent_full_scan_at(existing, columns)+ if base_version is None or last_full_scan is None or timezone.now() - last_full_scan >= MAX_RECOMPUTE_INTERVAL:+ return None+ try:+ return _fold_commit_stats(+ existing=existing,+ columns=columns,+ delta_schema_fields=_delta_schema_fields(delta_table),+ base_version=base_version,+ delta_version=delta_version,+ read_commit_actions=lambda version: _read_commit_actions(delta_table.table_uri, storage_options, version),+ )+ except Exception as e:+ # A commit file the log retention already removed is expected; anything else is a+ # representation the fold did not anticipate, worth a look but never worth failing over.+ if not isinstance(e, FileNotFoundError):+ capture_exception(e)+ log.warning("warehouse_statistics.incremental_fold_failed", error=str(e), base_version=base_version)+ return Nonedef _upsert_statistics(@@ -358,25 +643,35 @@ def _upsert_statistics(row_count: int,stat: _ColumnStat,delta_version: int,+ basis: str,) -> None:- """Persist (overwrite) one column's stats. Stats are wholly system-owned, so a plain upsert is correct."""+ """Persist (overwrite) one column's stats. Stats are wholly system-owned, so a plain upsert is correct.++ `full_scan_at` is set only for a full scan (`basis == "full"`). Leaving it out of `defaults` for a+ fold means `update_or_create` leaves the existing row's value untouched, so it keeps anchoring the+ `MAX_RECOMPUTE_INTERVAL` check in `_fold_since_stored_version` to the last real full scan, no matter+ how many folds happen in between.+ """null_fraction = (stat.null_count / row_count) if (stat.null_count is not None and row_count > 0) else None+ defaults: dict[str, Any] = {+ "team": team,+ "column_type": stat.column_type,+ "row_count": row_count,+ "null_count": stat.null_count,+ "null_fraction": null_fraction,+ "min_value": stat.min_value,+ "max_value": stat.max_value,+ "has_min_max": stat.has_min_max,+ "computed_at": timezone.now(),+ "computed_for_delta_version": delta_version,+ "stats_basis": "delta_log" if basis == "full" else "incremental",+ }+ if basis == "full":+ defaults["full_scan_at"] = timezone.now()WarehouseColumnStatistics.objects.for_team(team.id).update_or_create(table=table,column_name=column_name,- defaults={- "team": team,- "column_type": stat.column_type,- "row_count": row_count,- "null_count": stat.null_count,- "null_fraction": null_fraction,- "min_value": stat.min_value,- "max_value": stat.max_value,- "has_min_max": stat.has_min_max,- "computed_at": timezone.now(),- "computed_for_delta_version": delta_version,- "stats_basis": "delta_log",- },+ defaults=defaults,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 39e18b141c58..b0af05cda586 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -47,6 +47,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (get_v3_pipeline_lock_holder,)+from products.warehouse_sources.backend.temporal.data_imports.util import retry_internal_db_operation+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits import (+ billing_limit_reached,+)+from products.warehouse_sources.backend.types import ExternalDataSourceTypeWAREHOUSE_PIPELINES_V3_FLAG = "warehouse-pipelines-v3"@@ -330,6 +335,15 @@ class CreateExternalDataJobModelActivityOutputs:# True when the pre-extraction repartition activity has a rewrite, swap or on-disk measurement to# do. Defaults True so a payload from a worker that predates the field still schedules it.repartition_needed: bool = True+ # True when this activity already answered the billing-limit question, so the workflow reads+ # `hit_billing_limit` instead of scheduling the separate check. Defaults False so a payload+ # recorded before the field existed still replays the check activity it recorded.+ billing_limit_checked: bool = False+ hit_billing_limit: bool = False+ # True when the post-import source-templates activity has anything to create: only a Stripe+ # source's first completed sync does. Defaults True so a payload that predates the field still+ # schedules the activity its history recorded.+ source_templates_needed: bool = True@activity.defn@@ -451,6 +465,18 @@ def create_external_data_job_model_activity(# scheduling it at all, which for most syncs is its whole cost.repartition_needed = repartition_activity_has_work(schema)+ # Answered here, after the job row exists, in the order the separate activity ran it. A+ # transient app-DB failure is retried in place: this activity has one Temporal attempt.+ hit_billing_limit = retry_internal_db_operation(+ lambda: billing_limit_reached(job, source, inputs.team_id, logger)+ )++ source_templates_needed = source.source_type == ExternalDataSourceType.STRIPE and not (+ ExternalDataJob.objects.filter(+ team_id=inputs.team_id, pipeline_id=source.id, status=ExternalDataJob.Status.COMPLETED+ ).exists()+ )+return CreateExternalDataJobModelActivityOutputs(job_id=str(job.id),incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,@@ -466,6 +492,9 @@ def create_external_data_job_model_activity(fast_return_eligible=fast_return_eligible,scheduled_full_refresh=scheduled_full_refresh,repartition_needed=repartition_needed,+ billing_limit_checked=True,+ hit_billing_limit=hit_billing_limit,+ source_templates_needed=source_templates_needed,)except V3PipelineLockLostError:# The takeover race the guard handles, not a defect — skip the generic handler'sdiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.pyindex 7ca38a92a641..6b204832ba03 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py@@ -157,14 +157,355 @@ class TestComputeTableStatisticsSync:)return schema, table, job- def _mock_delta(self, add_actions: pa.Table, version: int = 7):+ def _mock_delta(self, add_actions: pa.Table, version: int = 7, delta_types: dict[str, Any] | None = None):delta_table = MagicMock()delta_table.version.return_value = versiondelta_table.get_add_actions.return_value = add_actions+ delta_table.table_uri = "s3://bucket/data/stripe_charge/"+ fields = [{"name": name, "type": kind} for name, kind in (delta_types or {"amount": "long"}).items()]+ delta_table.schema.return_value.to_json.return_value = json.dumps({"type": "struct", "fields": fields})helper = MagicMock()helper.get_delta_table = AsyncMock(return_value=delta_table)+ helper.get_storage_options.return_value = {}return helper+ @pytest.fixture(autouse=True)+ def _no_commit_log(self) -> Any:+ # Tests that want the incremental fold patch the reader themselves; everything else sees a+ # log with no commit files, which sends the computation down the full scan.+ with patch.object(comp, "_read_commit_actions", side_effect=FileNotFoundError("no commit")):+ yield++ def _stored(+ self,+ team: Team,+ table: DataWarehouseTable,+ column_name: str = "amount",+ *,+ version: int = 7,+ age: dt.timedelta = dt.timedelta(days=2),+ row_count: int = 40,+ null_count: int | None = 4,+ min_value: str | None = "2",+ max_value: str | None = "50",+ stats_basis: str = "delta_log",+ full_scan_age: dt.timedelta | None = None,+ ) -> WarehouseColumnStatistics:+ # A row from a real full scan has full_scan_at == computed_at; a caller simulating a folded+ # or pre-full_scan_at row passes full_scan_age explicitly (or None for "no full scan yet").+ full_scan_age = age if full_scan_age is None else full_scan_age+ return WarehouseColumnStatistics.objects.for_team(team.id).create(+ team=team,+ table=table,+ column_name=column_name,+ row_count=row_count,+ null_count=null_count,+ min_value=min_value,+ max_value=max_value,+ has_min_max=min_value is not None or max_value is not None,+ computed_at=timezone.now() - age,+ computed_for_delta_version=version,+ stats_basis=stats_basis,+ full_scan_at=timezone.now() - full_scan_age,+ )++ @staticmethod+ def _add(num_records: int, **columns: tuple[Any, Any, Any]) -> dict[str, Any]:+ """One commit `add` action; each column is (min, max, null_count), None to leave it out."""+ stats: dict[str, Any] = {"numRecords": num_records, "minValues": {}, "maxValues": {}, "nullCount": {}}+ for name, (min_value, max_value, null_count) in columns.items():+ if min_value is not None:+ stats["minValues"][name] = min_value+ if max_value is not None:+ stats["maxValues"][name] = max_value+ if null_count is not None:+ stats["nullCount"][name] = null_count+ return {"add": {"path": f"part-{uuid.uuid4()}.parquet", "dataChange": True, "stats": json.dumps(stats)}}++ def test_append_only_commits_fold_into_the_stored_statistics(self) -> None:+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ self._stored(team, table)+ commits = {+ 8: [{"commitInfo": {"operation": "WRITE"}}, self._add(10, amount=(1, 60, 1))],+ 9: [{"commitInfo": {"operation": "WRITE"}}, self._add(5, amount=(3, 7, 0)), {"txn": {"appId": "x"}}],+ }+ helper = self._mock_delta(pa.table({"num_records": [999]}), version=9)+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", side_effect=lambda _uri, _options, version: commits[version]),+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["status"] == "done"+ assert result["basis"] == "incremental"+ helper.get_delta_table.return_value.get_add_actions.assert_not_called()+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.row_count == 55+ assert stat.null_count == 5+ assert stat.null_fraction == 5 / 55+ assert stat.min_value == "1"+ assert stat.max_value == "60"+ assert stat.has_min_max is True+ assert stat.computed_for_delta_version == 9++ def test_a_fold_does_not_reset_the_full_scan_clock(self) -> None:+ # Regression: the fold gate must read the age of the last *full scan*, not the age of the+ # last write. If a fold bumped the same clock a full scan does, folding more often than+ # MAX_RECOMPUTE_INTERVAL would push that clock forward forever and the periodic full scan+ # that corrects drift would never run.+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ self._stored(team, table, version=7, age=dt.timedelta(days=1))++ # First fold: version 7 -> 8.+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=[self._add(10, amount=(1, 60, 1))]),+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(pa.table({"num_records": [999]}), version=8)),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)+ assert result["basis"] == "incremental"+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.stats_basis == "incremental"+ first_full_scan_at = stat.full_scan_at+ assert first_full_scan_at is not None++ # Age the write past MIN_RECOMPUTE_INTERVAL, without touching when the full scan happened,+ # so the next call is not skipped as "computed recently".+ WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id).update(+ computed_at=timezone.now() - dt.timedelta(days=2)+ )++ # Second fold: version 8 -> 9. A fold that reset full_scan_at would make the row look like+ # it was freshly full-scanned; it must not.+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=[self._add(5, amount=(3, 7, 0))]),+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(pa.table({"num_records": [999]}), version=9)),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)+ assert result["basis"] == "incremental"+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.full_scan_at == first_full_scan_at++ # Push the (still untouched) full scan past MAX_RECOMPUTE_INTERVAL and bump the write time+ # again; the fold gate must now refuse and the caller must fall back to a full scan.+ WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id).update(+ computed_at=timezone.now() - dt.timedelta(days=2),+ full_scan_at=timezone.now() - dt.timedelta(days=8),+ )+ add_actions = pa.table({"num_records": [999], "null_count.amount": [0], "min.amount": [0], "max.amount": [100]})+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=[self._add(2, amount=(0, 100, 0))]) as mock_read,+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions, version=10)),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)+ assert result["basis"] == "full"+ assert not mock_read.called+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.stats_basis == "delta_log"+ assert stat.full_scan_at is not None+ assert stat.full_scan_at > first_full_scan_at++ def test_fold_gate_falls_back_when_the_last_full_scan_is_stale_even_if_recently_folded(self) -> None:+ # Same regression as above, exercised directly: a row that looks freshly written (a recent+ # fold) but whose last full scan is past MAX_RECOMPUTE_INTERVAL must not fold further.+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ self._stored(+ team,+ table,+ version=7,+ age=dt.timedelta(days=2),+ full_scan_age=dt.timedelta(days=8),+ stats_basis="incremental",+ )+ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=[self._add(1, amount=(1, 1, 0))]) as mock_read,+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions, version=8)),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["basis"] == "full"+ assert not mock_read.called+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.stats_basis == "delta_log"++ @parameterized.expand(+ [+ ("long", "long", "2", "50", 1, 60, "1", "60"),+ ("double", "double", "1.5", "2.5", 0.25, 9.75, "0.25", "9.75"),+ ("string", "string", "b", "m", "a", "z", "a", "z"),+ ("boolean", "boolean", "False", "False", True, True, "False", "True"),+ ("date", "date", "2024-01-01", "2024-02-01", "2023-12-31", "2024-03-01", "2023-12-31", "2024-03-01"),+ (+ "timestamp",+ "timestamp",+ "2024-01-01 00:00:00+00:00",+ "2024-02-01 00:00:00+00:00",+ "2023-12-31T23:00:00Z",+ "2024-06-01T12:30:00.000123Z",+ "2023-12-31 23:00:00+00:00",+ "2024-06-01 12:30:00.000123+00:00",+ ),+ ("decimal", "decimal(10,2)", "1.50", "9.99", 0.5, 12.5, "0.50", "12.50"),+ ]+ )+ def test_folded_bounds_keep_the_full_scans_text_representation(+ self,+ _name: str,+ delta_type: str,+ stored_min: str,+ stored_max: str,+ log_min: Any,+ log_max: Any,+ expected_min: str,+ expected_max: str,+ ) -> None:+ # The stored bound is `str()` of the typed value the Add-action scan yields; the commit log+ # carries the same value in JSON form. A fold that compared the two as text, or stored the+ # log's spelling, would drift from what the next full scan writes.+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ self._stored(team, table, min_value=stored_min, max_value=stored_max)+ helper = self._mock_delta(pa.table({"num_records": [999]}), version=8, delta_types={"amount": delta_type})+ commit = [self._add(1, amount=(log_min, log_max, 0))]+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=commit),+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["basis"] == "incremental"+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.min_value == expected_min+ assert stat.max_value == expected_max++ @parameterized.expand(+ [+ ("a_file_was_removed", "remove", 8, dt.timedelta(days=2), {"amount": "long"}, True),+ ("the_schema_changed", "metadata", 8, dt.timedelta(days=2), {"amount": "long"}, True),+ ("a_file_carries_no_stats", "no_stats", 8, dt.timedelta(days=2), {"amount": "long"}, True),+ ("a_column_was_added", "append", 8, dt.timedelta(days=2), {"amount": "long", "total": "long"}, False),+ (+ "too_many_commits",+ "append",+ 8 + comp.MAX_INCREMENTAL_COMMITS,+ dt.timedelta(days=2),+ {"amount": "long"},+ False,+ ),+ ("stored_rows_past_the_max_age", "append", 8, dt.timedelta(days=8), {"amount": "long"}, False),+ ]+ )+ def test_falls_back_to_the_full_scan_when_the_fold_is_not_exact(+ self,+ _name: str,+ commit_kind: str,+ table_version: int,+ age: dt.timedelta,+ columns: dict[str, str],+ expect_log_read: bool,+ ) -> None:+ team = self._team()+ schema, table, _ = self._schema_table_job(+ team, columns={name: {"clickhouse": "Nullable(Int64)"} for name in columns}+ )+ self._stored(team, table, age=age)+ commit: list[dict[str, Any]]+ if commit_kind == "remove":+ commit = [self._add(1, amount=(1, 1, 0)), {"remove": {"path": "old.parquet", "dataChange": True}}]+ elif commit_kind == "metadata":+ commit = [{"metaData": {"schemaString": "{}"}}, self._add(1, amount=(1, 1, 0))]+ elif commit_kind == "no_stats":+ commit = [{"add": {"path": "p.parquet", "dataChange": True, "stats": None}}]+ else:+ commit = [self._add(1, amount=(1, 1, 0))]+ add_actions = pa.table(+ {+ "num_records": [99],+ **{f"null_count.{name}": [0] for name in columns},+ "min.amount": [1],+ "max.amount": [1],+ }+ )+ helper = self._mock_delta(add_actions, version=table_version, delta_types=columns)+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=commit) as mock_read,+ patch.object(comp, "capture_exception") as mock_capture,+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["status"] == "done"+ assert result["basis"] == "full"+ assert mock_read.called is expect_log_read+ mock_capture.assert_not_called()+ helper.get_delta_table.return_value.get_add_actions.assert_called_once()+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.row_count == 99+ assert stat.computed_for_delta_version == table_version++ def test_an_unparseable_stored_value_falls_back_without_leaking_it(self) -> None:+ # A stored bound written under an earlier column type (say string) cannot be parsed under a+ # changed type (say long): `int("not-a-number")` raises `ValueError` with the raw text in its+ # message. The fold must fall back to a full scan, and neither the capture nor the log line it+ # reports on may repeat that text.+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ self._stored(team, table, min_value="not-a-number", max_value="not-a-number-either")+ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})+ helper = self._mock_delta(add_actions, version=8, delta_types={"amount": "long"})+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=[self._add(1, amount=(1, 1, 0))]) as mock_read,+ patch.object(comp, "capture_exception") as mock_capture,+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["status"] == "done"+ assert result["basis"] == "full"+ assert not mock_read.called+ mock_capture.assert_called_once()+ reported = str(mock_capture.call_args[0][0])+ assert "not-a-number" not in reported++ def test_a_nested_column_neither_blocks_nor_gains_bounds_from_the_fold(self) -> None:+ team = self._team()+ schema, table, _ = self._schema_table_job(+ team, columns={"amount": {"clickhouse": "Nullable(Int64)"}, "payload": {"clickhouse": "String"}}+ )+ self._stored(team, table)+ self._stored(team, table, "payload", null_count=None, min_value=None, max_value=None)+ commit = [self._add(10, amount=(1, 60, 1), payload=({"x": 1}, {"x": 2}, {"x": 0}))]+ helper = self._mock_delta(+ pa.table({"num_records": [999]}),+ version=8,+ delta_types={"amount": "long", "payload": {"type": "struct", "fields": []}},+ )+ with (+ patch.object(comp, "statistics_enabled", return_value=True),+ patch.object(comp, "_read_commit_actions", return_value=commit),+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["basis"] == "incremental"+ payload = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="payload")+ assert payload.row_count == 50+ assert payload.has_min_max is False+ assert payload.null_count is None+ amount = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert amount.max_value == "60"+def test_skipped_when_flag_disabled(self) -> None:team = self._team()self._schema_table_job(team)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex 07f7668efba3..9b05747a8361 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -463,3 +463,83 @@ class TestCreateJobActivityDeletedSourceOrSchema:assert is_expected_activity_failure(exc_info.value)mock_delete_schedule.assert_called_once_with(str(schema.id))+++class TestCreateJobActivityPrepareRunOutputs:+ @parameterized.expand(+ [+ ("non_billable_run_is_never_limited", False, True, False),+ ("billable_run_under_quota", True, False, False),+ ("billable_run_over_quota", True, True, True),+ ]+ )+ @patch(f"{MODULE}.close_old_connections")+ @patch(f"{MODULE}.activity")+ def test_answers_the_billing_limit_with_the_job_row(+ self,+ _name: str,+ billable: bool,+ team_limited: bool,+ expect_hit: bool,+ mock_activity: MagicMock,+ _mock_close_connections: MagicMock,+ ) -> None:+ mock_activity.info.return_value.workflow_id = "wf-1"+ mock_activity.info.return_value.workflow_run_id = "run-1"+ team = _team()+ schema = _schema(team, None)+ # Past the free window for a new source, so only the quota decides.+ ExternalDataSource.objects.filter(id=schema.source_id).update(created_at=timezone.now() - dt.timedelta(days=30))++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits.is_team_limited",+ return_value=team_limited,+ ):+ result = create_external_data_job_model_activity(+ CreateExternalDataJobModelActivityInputs(+ team_id=team.id, schema_id=schema.id, source_id=schema.source_id, billable=billable+ )+ )++ assert result.billing_limit_checked is True+ assert result.hit_billing_limit is expect_hit+ assert ExternalDataJob.objects.filter(schema_id=schema.id).count() == 1++ @parameterized.expand(+ [+ ("stripe_first_sync", "Stripe", False, True),+ ("stripe_after_a_completed_sync", "Stripe", True, False),+ ("other_source", "Postgres", False, False),+ ]+ )+ @patch(f"{MODULE}.close_old_connections")+ @patch(f"{MODULE}.activity")+ def test_source_templates_needed_only_for_a_stripe_sources_first_sync(+ self,+ _name: str,+ source_type: str,+ has_completed_job: bool,+ expected: bool,+ mock_activity: MagicMock,+ _mock_close_connections: MagicMock,+ ) -> None:+ mock_activity.info.return_value.workflow_id = "wf-1"+ mock_activity.info.return_value.workflow_run_id = "run-1"+ team = _team()+ source = ExternalDataSource.objects.create(+ source_id="src", connection_id="conn", team=team, source_type=source_type+ )+ schema = ExternalDataSchema.objects.create(name="Charge", team=team, source=source)+ if has_completed_job:+ ExternalDataJob.objects.create(+ team=team, pipeline=source, schema=schema, status=ExternalDataJob.Status.COMPLETED, rows_synced=0+ )++ result = create_external_data_job_model_activity(+ CreateExternalDataJobModelActivityInputs(+ team_id=team.id, schema_id=schema.id, source_id=source.id, billable=False+ )+ )++ assert result.source_templates_needed is expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/workload_report.pyindex 5b03ca07296a..d4403a212e34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workload_report.py@@ -36,6 +36,8 @@ from structlog import get_loggerfrom posthog.redis import get_clientfrom posthog.web_memory_sampler import current_rss_mb+from products.warehouse_sources.backend.temporal.data_imports.batch_phase import report_batch_phase+LOGGER = get_logger(__name__)# Keys live longer than any plausible gap between a death and its retry (heartbeat timeout is minutes),@@ -74,10 +76,15 @@ def _redis_client() -> Any | None:def report_phase(phase: str) -> None:- """Record the current phase from anywhere inside a reporting activity; no-op outside one."""+ """Record the current phase from anywhere inside a reporting activity; no-op outside one.++ Inside the load consumer the same report also moves the batch's phase record, so one call+ site serves both the Redis workload sample and the consumer's watchdog.+ """reporter = _current_reporter.get()if reporter is not None:reporter.set_phase(phase)+ report_batch_phase(phase)def report_buffer_bytes(buffer_bytes: int) -> None:diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 8e94d9d309f3..02816655c4bd 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3936,7 +3936,7 @@ dependencies = [[[package]]name = "deltalite-python"-version = "0.1.8"+version = "0.1.9"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/core/examples/commit_overhead.rs b/rust/deltalite/core/examples/commit_overhead.rsindex 5186bae226b5..72a4a2581990 100644--- a/rust/deltalite/core/examples/commit_overhead.rs+++ b/rust/deltalite/core/examples/commit_overhead.rs@@ -14,10 +14,14 @@//! Usage://! cargo run --release -p deltalite-core --example commit_overhead -- \//! [--versions 1200] [--iters 40] [--rows 50] [--partitions 8] \-//! [--non-nullable-pk] [--reuse-handle] [--dir /path/to/fixture]+//! [--checkpoint-interval 100] [--non-nullable-pk] [--reuse-handle] \+//! [--dir /path/to/fixture]//!//! The fixture table is cached in `--dir` (or a temp dir keyed by the parameters) and//! reused across runs, so only the first run pays the table-building cost.+//!+//! `DELTALITE_CHECKPOINT_PREFETCH_MAX_BYTES=0` disables the checkpoint prefetch, which+//! gives the before/after comparison for that optimisation on one binary.use std::collections::HashMap;use std::path::PathBuf;@@ -36,7 +40,8 @@ use deltalite_core::upsert::{upsert, UpsertOptions};/// not, and it is the quantity S3 latency multiplies in production. This store counts/// reads (GET/HEAD/LIST) and writes per phase; it is registered under a `counted://`/// scheme through delta-rs's factory registries so every open/replay in the run goes-/// through it.+/// through it. Checkpoint Parquet GETs are also counted on their own, since they are+/// what the checkpoint prefetch collapses.mod counted {use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;@@ -50,20 +55,55 @@ mod counted {use object_store::local::LocalFileSystem;use object_store::{CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,- PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,+ ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,};pub static GETS: AtomicUsize = AtomicUsize::new(0);+ pub static CHECKPOINT_GETS: AtomicUsize = AtomicUsize::new(0);pub static LISTS: AtomicUsize = AtomicUsize::new(0);pub static WRITES: AtomicUsize = AtomicUsize::new(0);- /// (gets, lists, writes) since process start.- pub fn snapshot() -> (usize, usize, usize) {- (- GETS.load(Ordering::Relaxed),- LISTS.load(Ordering::Relaxed),- WRITES.load(Ordering::Relaxed),- )+ /// Object-store operations since process start.+ #[derive(Debug, Clone, Copy, Default)]+ pub struct Ops {+ pub gets: usize,+ pub checkpoint_gets: usize,+ pub lists: usize,+ pub writes: usize,+ }++ impl Ops {+ pub fn since(self, before: Ops) -> Ops {+ Ops {+ gets: self.gets - before.gets,+ checkpoint_gets: self.checkpoint_gets - before.checkpoint_gets,+ lists: self.lists - before.lists,+ writes: self.writes - before.writes,+ }+ }++ pub fn add(&mut self, other: Ops) {+ self.gets += other.gets;+ self.checkpoint_gets += other.checkpoint_gets;+ self.lists += other.lists;+ self.writes += other.writes;+ }+ }++ pub fn snapshot() -> Ops {+ Ops {+ gets: GETS.load(Ordering::Relaxed),+ checkpoint_gets: CHECKPOINT_GETS.load(Ordering::Relaxed),+ lists: LISTS.load(Ordering::Relaxed),+ writes: WRITES.load(Ordering::Relaxed),+ }+ }++ fn count_get(location: &Path, n: usize) {+ GETS.fetch_add(n, Ordering::Relaxed);+ if location.as_ref().contains(".checkpoint.") {+ CHECKPOINT_GETS.fetch_add(n, Ordering::Relaxed);+ }}fn sorted(@@ -116,17 +156,30 @@ mod counted {location: &Path,options: GetOptions,) -> object_store::Result<GetResult> {- GETS.fetch_add(1, Ordering::Relaxed);+ count_get(location, 1);self.inner.get_opts(location, options).await}+ // Counted as S3 would issue them: the AmazonS3 store merges ranges closer than+ // `OBJECT_STORE_COALESCE_DEFAULT` into one GET, so `ranges.len()` overstates.async fn get_ranges(&self,location: &Path,ranges: &[std::ops::Range<u64>],) -> object_store::Result<Vec<bytes::Bytes>> {- GETS.fetch_add(ranges.len(), Ordering::Relaxed);- self.inner.get_ranges(location, ranges).await+ let inner = self.inner.clone();+ let location = location.clone();+ object_store::coalesce_ranges(+ ranges,+ move |range| {+ count_get(&location, 1);+ let inner = inner.clone();+ let location = location.clone();+ async move { inner.get_range(&location, range).await }+ },+ object_store::OBJECT_STORE_COALESCE_DEFAULT,+ )+ .await}fn delete_stream(@@ -231,6 +284,7 @@ struct Args {iters: usize,rows: usize,partitions: usize,+ checkpoint_interval: Option<u32>,non_nullable_pk: bool,reuse_handle: bool,dir: Option<PathBuf>,@@ -242,6 +296,7 @@ fn parse_args() -> Args {iters: 40,rows: 50,partitions: 8,+ checkpoint_interval: None,non_nullable_pk: false,reuse_handle: false,dir: None,@@ -255,6 +310,13 @@ fn parse_args() -> Args {"--iters" => args.iters = take("--iters").parse().expect("--iters"),"--rows" => args.rows = take("--rows").parse().expect("--rows"),"--partitions" => args.partitions = take("--partitions").parse().expect("--partitions"),+ "--checkpoint-interval" => {+ args.checkpoint_interval = Some(+ take("--checkpoint-interval")+ .parse()+ .expect("--checkpoint-interval"),+ )+ }"--non-nullable-pk" => args.non_nullable_pk = true,"--reuse-handle" => args.reuse_handle = true,"--dir" => args.dir = Some(PathBuf::from(take("--dir"))),@@ -314,7 +376,7 @@ fn opts() -> UpsertOptions {}}-async fn create_table(uri: &str, non_nullable_pk: bool) {+async fn create_table(uri: &str, non_nullable_pk: bool, checkpoint_interval: Option<u32>) {let cols = vec![StructField::new("pk", KernelType::STRING, !non_nullable_pk),StructField::new("p", KernelType::STRING, true),@@ -322,19 +384,24 @@ async fn create_table(uri: &str, non_nullable_pk: bool) {StructField::new("ts", KernelType::TIMESTAMP_NTZ, true),StructField::new("payload", KernelType::STRING, true),];- CreateBuilder::new()+ let mut builder = CreateBuilder::new().with_location(uri).with_columns(cols)- .with_partition_columns(vec!["p".to_string()])- .await- .expect("create table");+ .with_partition_columns(vec!["p".to_string()]);+ if let Some(interval) = checkpoint_interval {+ builder = builder.with_configuration_property(+ deltalake::TableProperty::CheckpointInterval,+ Some(interval.to_string()),+ );+ }+ builder.await.expect("create table");}/// Build `versions` commits: commit i updates partition `i % partitions` wholesale, so/// the log grows deep (with tombstones and periodic checkpoints) while live files stay/// at ~1 per partition -- matching production's files_probed p50 of 1.async fn build_fixture(uri: &str, args: &Args, schema: &SchemaRef) {- create_table(uri, args.non_nullable_pk).await;+ create_table(uri, args.non_nullable_pk, args.checkpoint_interval).await;let so: HashMap<String, String> = HashMap::new();for i in 0..args.versions {let table = open_table_multipart(uri, so.clone(), MultipartConfig::default())@@ -387,8 +454,12 @@ async fn main() {let dir = args.dir.clone().unwrap_or_else(|| {// nosemgrep: rust.lang.security.temp-dir.temp-dirstd::env::temp_dir().join(format!(- "deltalite-commit-overhead-v{}-r{}-p{}-nn{}",- args.versions, args.rows, args.partitions, args.non_nullable_pk as u8+ "deltalite-commit-overhead-v{}-r{}-p{}-nn{}-ci{}",+ args.versions,+ args.rows,+ args.partitions,+ args.non_nullable_pk as u8,+ args.checkpoint_interval.unwrap_or(0)))});let marker = dir.join(".fixture-complete");@@ -440,14 +511,13 @@ async fn main() {mut t_total,) = (vec![], vec![], vec![], vec![], vec![], vec![], vec![]);let mut t_relax: Vec<f64> = vec![];+ let mut t_initial_open: Vec<f64> = vec![];let mut probed = 0usize;- // Per-phase I/O op deltas: (gets, lists, writes) for open/upsert per iteration.- let mut io = [(0usize, 0usize, 0usize); 2];- let track = |slot: &mut (usize, usize, usize), before: (usize, usize, usize)| {+ // Per-phase I/O op deltas for open/upsert per iteration.+ let mut io = [counted::Ops::default(); 2];+ let track = |slot: &mut counted::Ops, before: counted::Ops| {let now = counted::snapshot();- slot.0 += now.0 - before.0;- slot.1 += now.1 - before.1;- slot.2 += now.2 - before.2;+ slot.add(now.since(before));now};@@ -494,6 +564,7 @@ async fn main() {t_commit.push(stats.commit_ms as f64);t_maint.push(stats.maintenance_ms as f64);t_relax.push(stats.relax_ms as f64);+ t_initial_open.push(stats.initial_open_ms as f64);probed += stats.files_probed;track(&mut io[1], c);@@ -504,14 +575,24 @@ async fn main() {}println!(- "\ncommit_overhead: versions={} iters={} rows={} partitions={} non_nullable_pk={} reuse_handle={} (filesystem; understates S3)",- args.versions, args.iters, args.rows, args.partitions, args.non_nullable_pk, args.reuse_handle+ "\ncommit_overhead: versions={} iters={} rows={} partitions={} checkpoint_interval={} non_nullable_pk={} reuse_handle={} prefetch_max_bytes={} (filesystem; understates S3)",+ args.versions,+ args.iters,+ args.rows,+ args.partitions,+ args.checkpoint_interval.map_or("default".to_string(), |n| n.to_string()),+ args.non_nullable_pk,+ args.reuse_handle,+ deltalite_core::CheckpointCache::from_env().max_bytes());println!("files_probed avg {:.1}\n",probed as f64 / args.iters as f64);stat("open_handle_ms", &t_open);+ // Reported through the stats (once per handle); the wall-clock row above is what+ // the residual excludes, so this row is informational.+ stat("initial_open_ms", &t_initial_open);stat("open_ms", &t_refresh);stat("relax_ms", &t_relax);stat("plan_ms", &t_plan);@@ -533,22 +614,20 @@ async fn main() {println!("\nI/O ops per iteration (deterministic; what S3 latency multiplies):");let n = args.iters as f64;- for (label, (g, l, w)) in ["open_handle", "handle_upsert"].iter().zip(io.iter()) {- println!(- "{label:<16} gets {:7.1} lists {:6.1} writes {:6.1}",- *g as f64 / n,- *l as f64 / n,- *w as f64 / n- );+ let mut total = counted::Ops::default();+ for (label, ops) in ["open_handle", "handle_upsert"].iter().zip(io.iter()) {+ print_ops(label, *ops, n);+ total.add(*ops);}- let (tg, tl, tw) = io- .iter()- .fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2));+ print_ops("TOTAL", total, n);+}++fn print_ops(label: &str, ops: counted::Ops, n: f64) {println!(- "{:<16} gets {:7.1} lists {:6.1} writes {:6.1}",- "TOTAL",- tg as f64 / n,- tl as f64 / n,- tw as f64 / n+ "{label:<16} gets {:7.1} (checkpoint {:5.1}) lists {:6.1} writes {:6.1}",+ ops.gets as f64 / n,+ ops.checkpoint_gets as f64 / n,+ ops.lists as f64 / n,+ ops.writes as f64 / n);}diff --git a/rust/deltalite/core/src/handle.rs b/rust/deltalite/core/src/handle.rsindex f04faf48cbd4..4fa2df5b8453 100644--- a/rust/deltalite/core/src/handle.rs+++ b/rust/deltalite/core/src/handle.rs@@ -9,6 +9,7 @@//! (`update_incremental`), which is one log LIST plus the handful of new commit JSONs.use std::collections::HashMap;+use std::sync::Arc;use std::time::Instant;use arrow_array::RecordBatch;@@ -16,7 +17,8 @@ use arrow_schema::SchemaRef;use deltalake::DeltaTable;use crate::errors::{Error, Result};-use crate::table::{open_table, wrap_multipart, MultipartConfig};+use crate::prefetch::CheckpointCache;+use crate::table::{open_table_prefetched, wrap_multipart, MultipartConfig};use crate::upsert::{upsert_cached, RelaxCache, UpsertOptions, UpsertStats};/// Conflict-retry budget for one upsert call. A concurrent writer can make delta-rs@@ -25,6 +27,20 @@ use crate::upsert::{upsert_cached, RelaxCache, UpsertOptions, UpsertStats};/// keep conflicting, so the only fix is to refresh the snapshot and re-plan.const CONFLICT_RETRIES: usize = 5;+/// One live data file as the loaded snapshot records it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LiveFile {+ /// Path relative to the table root, URL-decoded.+ pub path: String,+ /// Size in bytes from the Add action.+ pub size: i64,+ /// Modification time in milliseconds since the Unix epoch, from the Add action.+ pub modification_time: i64,+ /// Partition column values as the log stores them (strings; `None` is a null+ /// partition value). Empty for an unpartitioned table.+ pub partition_values: HashMap<String, Option<String>>,+}+/// A loaded Delta table plus the per-table caches that make repeated small upserts/// cheap: the snapshot (refreshed incrementally, never rebuilt) and the relax memo.pub struct TableHandle {@@ -32,17 +48,27 @@ pub struct TableHandle {storage_options: HashMap<String, String>,table: DeltaTable,relax_cache: RelaxCache,+ /// Checkpoint bytes the table's stores served the last load from; cleared after+ /// every load so a handle idling between upserts holds only its snapshot.+ prefetch: Arc<CheckpointCache>,+ initial_open_ms: u64,+ initial_open_reported: bool,}impl TableHandle {/// Open an existing Delta table (one full snapshot load).pub async fn open(uri: String, storage_options: HashMap<String, String>) -> Result<Self> {- let table = open_table(&uri, storage_options.clone()).await?;+ let started = Instant::now();+ let (table, prefetch) = open_table_prefetched(&uri, storage_options.clone()).await?;+ prefetch.clear();Ok(Self {uri,storage_options,table,relax_cache: RelaxCache::default(),+ prefetch,+ initial_open_ms: started.elapsed().as_millis() as u64,+ initial_open_reported: false,})}@@ -64,15 +90,69 @@ impl TableHandle {.unwrap_or(-1)}+ /// Wall-clock ms the full snapshot load in [`TableHandle::open`] took.+ pub fn initial_open_ms(&self) -> u64 {+ self.initial_open_ms+ }++ /// The table id from the snapshot's metadata action.+ pub fn table_id(&self) -> Result<String> {+ Ok(self.table.snapshot()?.metadata().id().to_string())+ }++ /// The table configuration (`delta.*` properties and any custom keys).+ pub fn configuration(&self) -> Result<HashMap<String, String>> {+ Ok(self.table.snapshot()?.metadata().configuration().clone())+ }++ /// The Delta schema of the loaded snapshot as its JSON document+ /// (`{"type":"struct","fields":[...]}`).+ pub fn schema_json(&self) -> Result<String> {+ let schema = self.table.snapshot()?.schema();+ serde_json::to_string(schema.as_ref())+ .map_err(|e| Error::Generic(format!("serialising table schema: {e}")))+ }++ /// Number of live data files in the loaded snapshot.+ pub fn num_files(&self) -> Result<usize> {+ Ok(self.table.snapshot()?.log_data().num_files())+ }++ /// The live data files of the loaded snapshot, served from memory.+ pub fn files(&self) -> Result<Vec<LiveFile>> {+ let snapshot = self.table.snapshot()?;+ Ok(snapshot+ .log_data()+ .iter()+ .map(|view| {+ // The only public accessor for the raw partition-value strings; the+ // parsed form would need re-encoding and can be narrowed by a predicate.+ #[allow(deprecated)]+ let add = view.add_action();+ LiveFile {+ path: add.path,+ size: add.size,+ modification_time: add.modification_time,+ partition_values: add.partition_values,+ }+ })+ .collect())+ }+/// Bring the snapshot up to date with commits made elsewhere. Incremental (applies/// only commits newer than the loaded version); falls back to a full re-open when/// the incremental path fails -- e.g. the table was deleted and recreated at a/// lower version, which is not reachable forward from the loaded state.pub async fn refresh(&mut self) -> Result<()> {if self.table.update_incremental(None).await.is_ok() {+ self.prefetch.clear();return Ok(());}- self.table = open_table(&self.uri, self.storage_options.clone()).await?;+ let (table, prefetch) =+ open_table_prefetched(&self.uri, self.storage_options.clone()).await?;+ prefetch.clear();+ self.table = table;+ self.prefetch = prefetch;// The old snapshot is gone; nothing the relax memo verified can be trusted.self.relax_cache = RelaxCache::default();Ok(())@@ -131,10 +211,20 @@ impl TableHandle {self.refresh().await?;open_ms += t.elapsed().as_millis() as u64;stats.open_ms = open_ms;+ stats.initial_open_ms = self.take_initial_open_ms();return Ok(stats);}Err(e) => return Err(e),}}}++ /// The open cost, handed out once so per-upsert stats sum to the handle's total.+ fn take_initial_open_ms(&mut self) -> u64 {+ if self.initial_open_reported {+ return 0;+ }+ self.initial_open_reported = true;+ self.initial_open_ms+ }}diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsindex a3c4a0ea1e59..1cb61965d9c9 100644--- a/rust/deltalite/core/src/lib.rs+++ b/rust/deltalite/core/src/lib.rs@@ -32,13 +32,17 @@ pub mod errors;pub mod handle;pub mod limits;pub mod pkset;+pub mod prefetch;pub mod schema;pub mod store;pub mod table;pub mod upsert;pub use errors::{Error, Result};-pub use handle::TableHandle;+pub use handle::{LiveFile, TableHandle};pub use limits::ProcessLimits;-pub use table::{open_table, open_table_multipart, wrap_multipart, MultipartConfig};+pub use prefetch::CheckpointCache;+pub use table::{+ open_table, open_table_multipart, open_table_prefetched, wrap_multipart, MultipartConfig,+};pub use upsert::{upsert, upsert_cached, PruneStrategy, RelaxCache, UpsertOptions, UpsertStats};diff --git a/rust/deltalite/core/src/limits.rs b/rust/deltalite/core/src/limits.rsindex b4f49ca1c92d..71c543347eb5 100644--- a/rust/deltalite/core/src/limits.rs+++ b/rust/deltalite/core/src/limits.rs@@ -34,6 +34,7 @@ pub const DEFAULT_PROCESS_MAX_BUFFERED_BYTES: usize = 256 * 1024 * 1024;pub const DEFAULT_MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024 * 1024;/// Process-wide concurrency budgets shared by every concurrent `upsert` call.+#[derive(Debug)]pub struct ProcessLimits {partitions: Arc<Semaphore>,files: Arc<Semaphore>,@@ -122,6 +123,16 @@ impl ProcessLimits {.map_err(|_| Error::Generic("process byte-budget semaphore closed".into()))}+ /// Try to reserve `kb` KiB without waiting. Callers that can fall back to a+ /// streaming path use this to avoid deadlocking when several operations each hold+ /// part of the process budget and need one more allocation to finish.+ pub fn try_acquire_buffer_kb(&self, kb: u32) -> Option<OwnedSemaphorePermit> {+ self.buffer+ .clone()+ .try_acquire_many_owned(kb.min(self.buffer_cap_kb).max(1))+ .ok()+ }+/// Capacity of the byte budget in KiB.pub fn buffer_cap_kb(&self) -> u32 {self.buffer_cap_kbdiff --git a/rust/deltalite/core/src/prefetch.rs b/rust/deltalite/core/src/prefetch.rsnew file mode 100644index 000000000000..0513a56c400e--- /dev/null+++ b/rust/deltalite/core/src/prefetch.rs@@ -0,0 +1,821 @@+//! Whole-object prefetch for Delta checkpoint Parquet files.+//!+//! A snapshot load reads the latest checkpoint through the kernel's Parquet reader, which+//! issues one ranged GET for the footer, one for the metadata and one per column chunk it+//! decodes: a dozen or more sequential round trips against a single object, each paid at+//! object-store latency. The load decodes nearly the whole file anyway (every live Add+//! action is materialised), so [`CheckpointPrefetchStore`] fetches the object once on its+//! first ranged read and serves every later range from memory.+//!+//! The rewrite is scoped to checkpoint files under `_delta_log/`. Data files must keep+//! their range reads: the probe reads only the PK columns of a file and the rewrite+//! streams row groups, so buffering a whole data file would defeat the memory bound.+//!+//! Objects above [`CheckpointCache::max_bytes`] fall through to plain range reads. That+//! limit also bounds the aggregate cache for one load, while the process-wide byte budget+//! bounds concurrent loads. [`crate::handle::TableHandle`] clears the cache after every+//! open and refresh so a long-lived handle does not pin checkpoint bytes between upserts.++use std::collections::HashMap;+use std::ops::Range;+use std::sync::{Arc, Mutex};++use async_trait::async_trait;+use bytes::Bytes;+use deltalake::kernel::transaction::TransactionError;+use deltalake::logstore::{CommitOrBytes, LogStore, LogStoreConfig};+use futures::stream::{BoxStream, StreamExt};+use metrics::counter;+use object_store::path::Path;+use object_store::{+ Attributes, GetOptions, GetRange, GetResult, GetResultPayload, ListResult, MultipartUpload,+ ObjectMeta, ObjectStore, ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload,+ PutResult,+};+use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};+use tracing::debug;+use uuid::Uuid;++use crate::limits::ProcessLimits;++/// Largest checkpoint object fetched whole by default. A checkpoint this size describes+/// a table with hundreds of thousands of live files, whose snapshot the kernel holds in+/// memory anyway; the load's peak grows by at most this much while the fetch is in flight.+pub const DEFAULT_CHECKPOINT_PREFETCH_MAX_BYTES: u64 = 128 * 1024 * 1024;++/// Environment override for [`DEFAULT_CHECKPOINT_PREFETCH_MAX_BYTES`]; `0` disables the+/// prefetch entirely (every read passes through as a range read).+pub const CHECKPOINT_PREFETCH_MAX_BYTES_ENV: &str = "DELTALITE_CHECKPOINT_PREFETCH_MAX_BYTES";++/// Whether `location` names a checkpoint Parquet file: `_delta_log/<v>.checkpoint.parquet`+/// or a multi-part / UUID-named `_delta_log/<v>.checkpoint.<...>.parquet`. Sidecar files+/// (`_delta_log/_sidecars/<uuid>.parquet`) are deliberately excluded.+pub fn is_checkpoint_file(location: &Path) -> bool {+ let in_log = location.parts().any(|part| part.as_ref() == "_delta_log");+ let name = location.filename().unwrap_or_default();+ in_log && name.ends_with(".parquet") && name.contains(".checkpoint.")+}++#[derive(Debug, Clone)]+enum Fetched {+ Cached {+ meta: ObjectMeta,+ bytes: Bytes,+ _cache_permit: Arc<OwnedSemaphorePermit>,+ _process_permit: Arc<OwnedSemaphorePermit>,+ },+ /// The object is larger than the cache allows; its reads pass through untouched.+ TooLarge,+}++/// Per-load memory of whole checkpoint objects, shared by every store view of one table.+///+/// Concurrent readers of the same object wait on one fetch (`OnceCell`) instead of each+/// issuing their own whole-object GET. Admission never waits for byte-budget permits;+/// an occupied budget falls back to range reads so multipart loads cannot deadlock.+#[derive(Debug)]+pub struct CheckpointCache {+ max_bytes: u64,+ budget: Arc<Semaphore>,+ budget_kb: u32,+ process_limits: Arc<ProcessLimits>,+ entries: Mutex<HashMap<Path, Arc<OnceCell<Fetched>>>>,+}++impl CheckpointCache {+ /// A cache that fetches checkpoint objects up to `max_bytes` in aggregate; `0`+ /// disables prefetching.+ pub fn new(max_bytes: u64) -> Self {+ Self::with_process_limits(max_bytes, ProcessLimits::global().clone())+ }++ fn with_process_limits(max_bytes: u64, process_limits: Arc<ProcessLimits>) -> Self {+ let budget_kb = max_bytes.div_ceil(1024).clamp(1, u32::MAX as u64) as u32;+ Self {+ max_bytes,+ budget: Arc::new(Semaphore::new(budget_kb as usize)),+ budget_kb,+ process_limits,+ entries: Mutex::new(HashMap::new()),+ }+ }++ /// Size bound from [`CHECKPOINT_PREFETCH_MAX_BYTES_ENV`], else the default. Parsed+ /// here rather than through `limits::env_usize` because `0` is a valid setting.+ pub fn from_env() -> Self {+ let max = match std::env::var(CHECKPOINT_PREFETCH_MAX_BYTES_ENV) {+ Ok(v) => v.trim().parse::<u64>().unwrap_or_else(|_| {+ tracing::warn!(+ var = CHECKPOINT_PREFETCH_MAX_BYTES_ENV,+ value = %v,+ "invalid value, using default"+ );+ DEFAULT_CHECKPOINT_PREFETCH_MAX_BYTES+ }),+ Err(_) => DEFAULT_CHECKPOINT_PREFETCH_MAX_BYTES,+ };+ Self::new(max)+ }++ /// Largest object this cache fetches whole.+ pub fn max_bytes(&self) -> u64 {+ self.max_bytes+ }++ /// Drop every cached object.+ pub fn clear(&self) {+ self.lock().clear();+ }++ /// Bytes currently held (for observability and tests).+ pub fn cached_bytes(&self) -> u64 {+ self.lock()+ .values()+ .filter_map(|cell| match cell.get() {+ Some(Fetched::Cached { bytes, .. }) => Some(bytes.len() as u64),+ _ => None,+ })+ .sum()+ }++ fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<Path, Arc<OnceCell<Fetched>>>> {+ // A poisoned map only means another reader panicked mid-insert; the entries are+ // plain values, so continuing is safe.+ self.entries+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ }++ fn cell(&self, location: &Path) -> Arc<OnceCell<Fetched>> {+ self.lock().entry(location.clone()).or_default().clone()+ }++ /// Record that `location` is too large without touching the store. A ranged read+ /// ending past the bound proves the object is larger than the bound, so the+ /// whole-object GET can be skipped rather than started and abandoned.+ fn mark_too_large(&self, location: &Path) {+ let cell = self.cell(location);+ drop(cell.set(Fetched::TooLarge));+ }++ fn exceeds(&self, ranges: &[Range<u64>]) -> bool {+ ranges.iter().any(|r| r.end > self.max_bytes)+ }++ fn try_reserve(+ &self,+ bytes: u64,+ ) -> Option<(Arc<OwnedSemaphorePermit>, Arc<OwnedSemaphorePermit>)> {+ let kb = bytes.div_ceil(1024).clamp(1, u32::MAX as u64) as u32;+ if kb > self.budget_kb || kb > self.process_limits.buffer_cap_kb() {+ return None;+ }+ let cache = self.budget.clone().try_acquire_many_owned(kb).ok()?;+ let process = self.process_limits.try_acquire_buffer_kb(kb)?;+ Some((Arc::new(cache), Arc::new(process)))+ }++ async fn get_or_fetch(+ &self,+ inner: &Arc<dyn ObjectStore>,+ location: &Path,+ ) -> object_store::Result<Fetched> {+ let cell = self.cell(location);+ let fetched = cell+ .get_or_try_init(|| async {+ let result = inner.get(location).await?;+ if result.meta.size > self.max_bytes {+ debug!(+ path = %location,+ size = result.meta.size,+ max = self.max_bytes,+ "checkpoint exceeds the prefetch bound; reading it by range"+ );+ counter!("deltalite_checkpoint_prefetch_total", "outcome" => "too_large")+ .increment(1);+ return Ok::<_, object_store::Error>(Fetched::TooLarge);+ }+ let Some((_cache_permit, _process_permit)) = self.try_reserve(result.meta.size)+ else {+ debug!(+ path = %location,+ size = result.meta.size,+ "checkpoint prefetch budget is occupied; reading it by range"+ );+ counter!("deltalite_checkpoint_prefetch_total", "outcome" => "budget_exhausted")+ .increment(1);+ return Ok(Fetched::TooLarge);+ };+ let meta = result.meta.clone();+ let bytes = result.bytes().await?;+ debug!(path = %location, size = bytes.len(), "prefetched checkpoint");+ counter!("deltalite_checkpoint_prefetch_total", "outcome" => "fetched")+ .increment(1);+ Ok(Fetched::Cached {+ meta,+ bytes,+ _cache_permit,+ _process_permit,+ })+ })+ .await?;+ Ok(fetched.clone())+ }+}++/// An [`ObjectStore`] wrapper that serves ranged reads of checkpoint files from a+/// whole-object fetch and delegates everything else.+#[derive(Debug)]+pub struct CheckpointPrefetchStore {+ inner: Arc<dyn ObjectStore>,+ cache: Arc<CheckpointCache>,+}++impl CheckpointPrefetchStore {+ /// Wrap `inner`, sharing `cache` with any other view of the same table.+ pub fn new(inner: Arc<dyn ObjectStore>, cache: Arc<CheckpointCache>) -> Self {+ Self { inner, cache }+ }++ /// Only plain reads are served from memory; HEAD and preconditioned or versioned+ /// reads carry semantics the cached copy cannot honour.+ fn serves(&self, location: &Path, options: &GetOptions) -> bool {+ is_checkpoint_file(location)+ && !options.head+ && options.if_match.is_none()+ && options.if_none_match.is_none()+ && options.if_modified_since.is_none()+ && options.if_unmodified_since.is_none()+ && options.version.is_none()+ }++ fn resolve(range: Option<&GetRange>, len: u64) -> Range<u64> {+ match range {+ None => 0..len,+ Some(GetRange::Bounded(r)) => Self::clamp(r, len),+ Some(GetRange::Offset(offset)) => (*offset).min(len)..len,+ Some(GetRange::Suffix(n)) => len.saturating_sub(*n)..len,+ }+ }++ fn clamp(range: &Range<u64>, len: u64) -> Range<u64> {+ let start = range.start.min(len);+ start..range.end.min(len).max(start)+ }++ fn slice(bytes: &Bytes, range: &Range<u64>) -> Bytes {+ bytes.slice(range.start as usize..range.end as usize)+ }+}++impl std::fmt::Display for CheckpointPrefetchStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "CheckpointPrefetchStore({})", self.inner)+ }+}++#[async_trait]+impl ObjectStore for CheckpointPrefetchStore {+ async fn put_opts(+ &self,+ location: &Path,+ payload: PutPayload,+ opts: PutOptions,+ ) -> object_store::Result<PutResult> {+ self.inner.put_opts(location, payload, opts).await+ }++ async fn put_multipart_opts(+ &self,+ location: &Path,+ opts: PutMultipartOptions,+ ) -> object_store::Result<Box<dyn MultipartUpload>> {+ self.inner.put_multipart_opts(location, opts).await+ }++ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ if !self.serves(location, &options) {+ return self.inner.get_opts(location, options).await;+ }+ if let Some(GetRange::Bounded(range)) = &options.range {+ if self.cache.exceeds(std::slice::from_ref(range)) {+ self.cache.mark_too_large(location);+ }+ }+ match self.cache.get_or_fetch(&self.inner, location).await? {+ Fetched::TooLarge => self.inner.get_opts(location, options).await,+ Fetched::Cached { meta, bytes, .. } => {+ let range = Self::resolve(options.range.as_ref(), bytes.len() as u64);+ let slice = Self::slice(&bytes, &range);+ Ok(GetResult {+ payload: GetResultPayload::Stream(+ futures::stream::once(async move { Ok(slice) }).boxed(),+ ),+ meta,+ range,+ attributes: Attributes::default(),+ })+ }+ }+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ if !is_checkpoint_file(location) {+ return self.inner.get_ranges(location, ranges).await;+ }+ if self.cache.exceeds(ranges) {+ self.cache.mark_too_large(location);+ }+ match self.cache.get_or_fetch(&self.inner, location).await? {+ Fetched::TooLarge => self.inner.get_ranges(location, ranges).await,+ Fetched::Cached { bytes, .. } => {+ let len = bytes.len() as u64;+ Ok(ranges+ .iter()+ .map(|r| Self::slice(&bytes, &Self::clamp(r, len)))+ .collect())+ }+ }+ }++ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ self.inner.delete_stream(locations)+ }++ fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list(prefix)+ }++ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list_with_offset(prefix, offset)+ }++ async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {+ self.inner.list_with_delimiter(prefix).await+ }++ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::CopyOptions,+ ) -> object_store::Result<()> {+ self.inner.copy_opts(from, to, options).await+ }++ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::RenameOptions,+ ) -> object_store::Result<()> {+ self.inner.rename_opts(from, to, options).await+ }+}++/// A [`LogStore`] wrapper whose stores prefetch checkpoint files. The kernel engine that+/// reads checkpoints is built from `root_object_store()` (the trait's default `engine()`),+/// so wrapping both store accessors is enough to route every snapshot load through the+/// cache; commit-entry reads and writes stay on the inner log store's own path.+pub struct CheckpointPrefetchLogStore {+ inner: Arc<dyn LogStore>,+ cache: Arc<CheckpointCache>,+}++impl CheckpointPrefetchLogStore {+ /// Wrap `inner`, prefetching through `cache`.+ pub fn new(inner: Arc<dyn LogStore>, cache: Arc<CheckpointCache>) -> Self {+ Self { inner, cache }+ }++ /// The cache this wrapper serves from.+ pub fn cache(&self) -> &Arc<CheckpointCache> {+ &self.cache+ }+}++impl std::fmt::Debug for CheckpointPrefetchLogStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "CheckpointPrefetchLogStore({})", self.inner.name())+ }+}++#[async_trait]+impl LogStore for CheckpointPrefetchLogStore {+ fn name(&self) -> String {+ // Verbatim for the same reason as `MultipartLogStore::name`: delta-rs picks the+ // commit path by string-matching this name.+ self.inner.name()+ }++ async fn refresh(&self) -> deltalake::DeltaResult<()> {+ self.inner.refresh().await+ }++ async fn read_commit_entry(&self, version: u64) -> deltalake::DeltaResult<Option<Bytes>> {+ self.inner.read_commit_entry(version).await+ }++ async fn write_commit_entry(+ &self,+ version: u64,+ commit_or_bytes: CommitOrBytes,+ operation_id: Uuid,+ ) -> Result<(), TransactionError> {+ self.inner+ .write_commit_entry(version, commit_or_bytes, operation_id)+ .await+ }++ async fn abort_commit_entry(+ &self,+ version: u64,+ commit_or_bytes: CommitOrBytes,+ operation_id: Uuid,+ ) -> Result<(), TransactionError> {+ self.inner+ .abort_commit_entry(version, commit_or_bytes, operation_id)+ .await+ }++ async fn get_latest_version(&self, start_version: u64) -> deltalake::DeltaResult<u64> {+ self.inner.get_latest_version(start_version).await+ }++ fn object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {+ Arc::new(CheckpointPrefetchStore::new(+ self.inner.object_store(operation_id),+ self.cache.clone(),+ ))+ }++ fn root_object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {+ Arc::new(CheckpointPrefetchStore::new(+ self.inner.root_object_store(operation_id),+ self.cache.clone(),+ ))+ }++ fn config(&self) -> &LogStoreConfig {+ self.inner.config()+ }+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicUsize, Ordering};++ use object_store::memory::InMemory;++ use super::*;++ /// Counts GETs reaching the wrapped store: whole or ranged `get_opts` as one each,+ /// `get_ranges` as one per range (what an uncoalesced store would issue).+ #[derive(Debug)]+ struct Counting {+ inner: InMemory,+ gets: AtomicUsize,+ }++ impl std::fmt::Display for Counting {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Counting")+ }+ }++ #[async_trait]+ impl ObjectStore for Counting {+ async fn put_opts(+ &self,+ location: &Path,+ payload: PutPayload,+ opts: PutOptions,+ ) -> object_store::Result<PutResult> {+ self.inner.put_opts(location, payload, opts).await+ }+ async fn put_multipart_opts(+ &self,+ location: &Path,+ opts: PutMultipartOptions,+ ) -> object_store::Result<Box<dyn MultipartUpload>> {+ self.inner.put_multipart_opts(location, opts).await+ }+ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ self.gets.fetch_add(1, Ordering::SeqCst);+ self.inner.get_opts(location, options).await+ }+ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ self.gets.fetch_add(ranges.len(), Ordering::SeqCst);+ self.inner.get_ranges(location, ranges).await+ }+ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ self.inner.delete_stream(locations)+ }+ fn list(+ &self,+ prefix: Option<&Path>,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list(prefix)+ }+ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list_with_offset(prefix, offset)+ }+ async fn list_with_delimiter(+ &self,+ prefix: Option<&Path>,+ ) -> object_store::Result<ListResult> {+ self.inner.list_with_delimiter(prefix).await+ }+ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::CopyOptions,+ ) -> object_store::Result<()> {+ self.inner.copy_opts(from, to, options).await+ }+ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::RenameOptions,+ ) -> object_store::Result<()> {+ self.inner.rename_opts(from, to, options).await+ }+ }++ const CHECKPOINT: &str = "bucket/table/_delta_log/00000000000000000010.checkpoint.parquet";+ const CHECKPOINT_2: &str = "bucket/table/_delta_log/00000000000000000011.checkpoint.parquet";++ fn body(len: usize) -> Bytes {+ Bytes::from((0..len).map(|i| (i % 251) as u8).collect::<Vec<u8>>())+ }++ async fn fixture(max_bytes: u64) -> (Arc<Counting>, CheckpointPrefetchStore, Bytes) {+ let counting = Arc::new(Counting {+ inner: InMemory::new(),+ gets: AtomicUsize::new(0),+ });+ let data = body(10_000);+ for path in [CHECKPOINT, CHECKPOINT_2, "bucket/table/p=1/part-0.parquet"] {+ counting+ .put(&Path::from(path), PutPayload::from_bytes(data.clone()))+ .await+ .unwrap();+ }+ let store = CheckpointPrefetchStore::new(+ counting.clone(),+ Arc::new(CheckpointCache::new(max_bytes)),+ );+ (counting, store, data)+ }++ fn gets(counting: &Counting) -> usize {+ counting.gets.load(Ordering::SeqCst)+ }++ #[test]+ fn checkpoint_paths_are_recognised_and_nothing_else_is() {+ for yes in [+ "_delta_log/00000000000000000010.checkpoint.parquet",+ "b/t/_delta_log/00000000000000000010.checkpoint.parquet",+ "b/t/_delta_log/00000000000000000010.checkpoint.0000000001.0000000003.parquet",+ "b/t/_delta_log/00000000000000000010.checkpoint.0d5c4a1e-1111-2222-3333-444444444444.parquet",+ ] {+ assert!(is_checkpoint_file(&Path::from(yes)), "{yes}");+ }+ for no in [+ "b/t/_delta_log/00000000000000000010.json",+ "b/t/_delta_log/_last_checkpoint",+ "b/t/_delta_log/_sidecars/0d5c4a1e-1111-2222-3333-444444444444.parquet",+ "b/t/p=1/part-00000.checkpoint.parquet",+ "b/t/part-0.parquet",+ ] {+ assert!(!is_checkpoint_file(&Path::from(no)), "{no}");+ }+ }++ #[tokio::test]+ async fn ranged_reads_of_one_checkpoint_cost_one_get() {+ let (counting, store, data) = fixture(u64::MAX).await;+ let path = Path::from(CHECKPOINT);++ let footer = store.get_range(&path, 9_992..10_000).await.unwrap();+ let chunks = store+ .get_ranges(&path, &[0..100, 5_000..5_010, 9_000..9_500])+ .await+ .unwrap();+ let whole = store.get(&path).await.unwrap().bytes().await.unwrap();++ assert_eq!(gets(&counting), 1, "every range must come from one fetch");+ assert_eq!(footer, data.slice(9_992..10_000));+ assert_eq!(chunks[0], data.slice(0..100));+ assert_eq!(chunks[1], data.slice(5_000..5_010));+ assert_eq!(chunks[2], data.slice(9_000..9_500));+ assert_eq!(whole, data);+ }++ #[tokio::test]+ async fn suffix_and_offset_ranges_resolve_against_the_cached_length() {+ let (counting, store, data) = fixture(u64::MAX).await;+ let path = Path::from(CHECKPOINT);++ let suffix = store+ .get_opts(+ &path,+ GetOptions {+ range: Some(GetRange::Suffix(8)),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(suffix.range, 9_992..10_000);+ assert_eq!(suffix.bytes().await.unwrap(), data.slice(9_992..10_000));++ let offset = store+ .get_opts(+ &path,+ GetOptions {+ range: Some(GetRange::Offset(9_990)),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(offset.range, 9_990..10_000);+ assert_eq!(offset.bytes().await.unwrap(), data.slice(9_990..10_000));+ assert_eq!(gets(&counting), 1);+ }++ #[tokio::test]+ async fn data_files_and_head_requests_pass_through() {+ let (counting, store, _) = fixture(u64::MAX).await;+ let data_file = Path::from("bucket/table/p=1/part-0.parquet");++ store.get_range(&data_file, 0..10).await.unwrap();+ store.get_range(&data_file, 10..20).await.unwrap();+ assert_eq!(gets(&counting), 2, "data files keep their range reads");++ store.head(&Path::from(CHECKPOINT)).await.unwrap();+ assert_eq!(gets(&counting), 3, "HEAD is not served from the cache");+ assert_eq!(store.cache.cached_bytes(), 0);+ }++ #[tokio::test]+ async fn oversized_checkpoints_fall_through_to_range_reads() {+ let (counting, store, data) = fixture(1_000).await;+ let path = Path::from(CHECKPOINT);++ // The footer read ends past the bound, so the whole-object fetch is never issued.+ let footer = store.get_range(&path, 9_992..10_000).await.unwrap();+ let chunk = store.get_range(&path, 0..10).await.unwrap();++ assert_eq!(footer, data.slice(9_992..10_000));+ assert_eq!(chunk, data.slice(0..10));+ assert_eq!(+ gets(&counting),+ 2,+ "one passthrough GET per range, no prefetch"+ );+ assert_eq!(store.cache.cached_bytes(), 0);+ }++ #[tokio::test]+ async fn a_small_first_range_still_bounds_on_the_real_size() {+ let (counting, store, data) = fixture(1_000).await;+ let path = Path::from(CHECKPOINT);++ // Nothing in the request reveals the size; the fetch discovers it and backs off.+ let chunk = store.get_range(&path, 0..10).await.unwrap();+ let again = store.get_range(&path, 20..30).await.unwrap();++ assert_eq!(chunk, data.slice(0..10));+ assert_eq!(again, data.slice(20..30));+ assert_eq!(+ gets(&counting),+ 3,+ "one abandoned whole fetch, then a passthrough per range"+ );+ assert_eq!(store.cache.cached_bytes(), 0);+ }++ #[tokio::test]+ async fn the_per_load_budget_bounds_multipart_checkpoints_in_aggregate() {+ let (counting, store, data) = fixture(15_000).await;++ store+ .get_range(&Path::from(CHECKPOINT), 0..10)+ .await+ .unwrap();+ let second = store+ .get_range(&Path::from(CHECKPOINT_2), 0..10)+ .await+ .unwrap();++ assert_eq!(second, data.slice(0..10));+ assert_eq!(store.cache.cached_bytes(), 10_000);+ assert_eq!(+ gets(&counting),+ 3,+ "the second checkpoint falls back after its whole-object probe"+ );+ }++ #[tokio::test]+ async fn the_process_budget_bounds_concurrent_table_caches() {+ let limits = Arc::new(ProcessLimits::new(1, 1, 15_000));+ let counting = Arc::new(Counting {+ inner: InMemory::new(),+ gets: AtomicUsize::new(0),+ });+ let data = body(10_000);+ counting+ .put(+ &Path::from(CHECKPOINT),+ PutPayload::from_bytes(data.clone()),+ )+ .await+ .unwrap();+ let first = CheckpointPrefetchStore::new(+ counting.clone(),+ Arc::new(CheckpointCache::with_process_limits(15_000, limits.clone())),+ );+ let second = CheckpointPrefetchStore::new(+ counting.clone(),+ Arc::new(CheckpointCache::with_process_limits(15_000, limits)),+ );++ first+ .get_range(&Path::from(CHECKPOINT), 0..10)+ .await+ .unwrap();+ let range = second+ .get_range(&Path::from(CHECKPOINT), 0..10)+ .await+ .unwrap();++ assert_eq!(range, data.slice(0..10));+ assert_eq!(first.cache.cached_bytes(), 10_000);+ assert_eq!(second.cache.cached_bytes(), 0);+ assert_eq!(+ gets(&counting),+ 3,+ "the second cache falls back after its whole-object probe"+ );+ }++ #[tokio::test]+ async fn clear_releases_the_bytes_and_the_next_read_fetches_again() {+ let (counting, store, _) = fixture(u64::MAX).await;+ let path = Path::from(CHECKPOINT);++ store.get_range(&path, 0..10).await.unwrap();+ assert_eq!(store.cache.cached_bytes(), 10_000);+ store.cache.clear();+ assert_eq!(store.cache.cached_bytes(), 0);++ store.get_range(&path, 0..10).await.unwrap();+ assert_eq!(gets(&counting), 2);+ }++ #[tokio::test]+ async fn a_zero_bound_disables_prefetching() {+ let (counting, store, _) = fixture(0).await;+ let path = Path::from(CHECKPOINT);+ store.get_range(&path, 0..10).await.unwrap();+ store.get_range(&path, 10..20).await.unwrap();+ assert_eq!(gets(&counting), 2, "every range passes straight through");+ assert_eq!(store.cache.cached_bytes(), 0);+ }+}diff --git a/rust/deltalite/core/src/table.rs b/rust/deltalite/core/src/table.rsindex 404e60de96a5..3ace258b13fa 100644--- a/rust/deltalite/core/src/table.rs+++ b/rust/deltalite/core/src/table.rs@@ -6,6 +6,7 @@ use std::sync::Arc;use deltalake::{DeltaTable, DeltaTableBuilder};use crate::errors::{Error, Result};+use crate::prefetch::{CheckpointCache, CheckpointPrefetchLogStore};use crate::store::MultipartLogStore;/// How data-file uploads are performed.@@ -45,13 +46,36 @@ impl MultipartConfig {/// Open and load a Delta table from `uri` with the given delta-rs `storage_options`/// (the same keys the Python package accepts; the dict passes through unchanged).+///+/// The load reads its checkpoint through the prefetch wrapper (see [`crate::prefetch`])+/// and releases the prefetched bytes before returning, so the table costs no more memory+/// than a plain load once it is open.pub async fn open_table(uri: &str, storage_options: HashMap<String, String>) -> Result<DeltaTable> {+ let (table, prefetch) = open_table_prefetched(uri, storage_options).await?;+ prefetch.clear();+ Ok(table)+}++/// [`open_table`] that also hands back the checkpoint cache the table's stores serve+/// from, still holding the checkpoint bytes read by this load. The caller clears it once+/// it is done and can clear it again after each later load through the same table.+pub async fn open_table_prefetched(+ uri: &str,+ storage_options: HashMap<String, String>,+) -> Result<(DeltaTable, Arc<CheckpointCache>)> {let url = deltalake::ensure_table_uri(uri).map_err(|e| Error::NotFound(format!("invalid table uri {uri}: {e}")))?;- Ok(DeltaTableBuilder::from_url(url)?+ let built = DeltaTableBuilder::from_url(url)?.with_storage_options(storage_options)- .load()- .await?)+ .build()?;+ let cache = Arc::new(CheckpointCache::from_env());+ let log_store = Arc::new(CheckpointPrefetchLogStore::new(+ built.log_store(),+ cache.clone(),+ ));+ let mut table = DeltaTable::new(log_store, built.config.clone());+ table.load().await?;+ Ok((table, cache))}/// Open a table whose data-file uploads go through the multipart-aware store wrapperdiff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 64c86968b881..5eeef8415119 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -255,6 +255,11 @@ pub struct UpsertStats {/// (initial refresh, conflict-retry refreshes, post-commit refresh). Set by/// [`crate::handle::TableHandle::upsert`]; 0 when the core `upsert` runs directly.pub open_ms: u64,+ /// Wall-clock ms of the full snapshot load that opened the handle. Reported on the+ /// first upsert through a [`crate::handle::TableHandle`] and 0 on every later one,+ /// so summing it over a handle's upserts gives the open cost exactly once; 0 when+ /// the core `upsert` runs directly.+ pub initial_open_ms: u64,/// Wall-clock ms spent importing the caller's source data into Arrow batches. Set/// by the language binding that owns the import; 0 when unset.pub ingest_ms: u64,diff --git a/rust/deltalite/core/tests/handle_and_open.rs b/rust/deltalite/core/tests/handle_and_open.rsindex d85ea666b979..de7edc49ce76 100644--- a/rust/deltalite/core/tests/handle_and_open.rs+++ b/rust/deltalite/core/tests/handle_and_open.rs@@ -1,10 +1,10 @@//! Integration tests for the open/refresh path: the single-load guarantee of-//! `open_table_multipart`, snapshot preservation in `wrap_multipart`, and the-//! `TableHandle` upsert orchestration (incremental refresh, relax with a warm cache).+//! `open_table_multipart`, snapshot preservation in `wrap_multipart`, the checkpoint+//! prefetch, and the `TableHandle` upsert orchestration (incremental refresh, relax with+//! a warm cache, open timing, snapshot accessors).use std::collections::HashMap;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::Arc;+use std::sync::{Arc, LazyLock, Mutex};use arrow_array::{Int64Array, RecordBatch, StringArray};use arrow_schema::{DataType, Field, Schema, SchemaRef};@@ -14,7 +14,7 @@ use deltalake::logstore::{ObjectStoreFactory, StorageConfig,};use deltalake::operations::create::CreateBuilder;-use deltalake::{DeltaResult, Path};+use deltalake::{DeltaResult, Path, TableProperty};use deltalite_core::handle::TableHandle;use deltalite_core::table::{open_table, open_table_multipart, wrap_multipart, MultipartConfig};use deltalite_core::upsert::UpsertOptions;@@ -27,10 +27,60 @@ use object_store::{// ---- read-counting store, registered as its own URL scheme -------------------------static READS: AtomicUsize = AtomicUsize::new(0);+/// Reads (GET/HEAD/LIST) keyed by the path or listing prefix they targeted. Per path+/// rather than one global counter so the tests, which run concurrently in one process+/// and share this scheme, each measure only their own table.+static READS: LazyLock<Mutex<HashMap<String, usize>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));-fn reads() -> usize {- READS.load(Ordering::SeqCst)+/// GETs per checkpoint Parquet file (one per `get_opts`, one per range in `get_ranges`),+/// keyed by path, so a test can assert how many round trips one checkpoint cost.+static CHECKPOINT_GETS: LazyLock<Mutex<HashMap<String, usize>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));++fn record_read(target: String, n: usize) {+ *READS.lock().unwrap().entry(target).or_default() += n;+}++/// Reads issued against paths under `root` (an object-store path, no leading slash).+fn reads_under(root: &str) -> usize {+ READS+ .lock()+ .unwrap()+ .iter()+ .filter(|(path, _)| path.starts_with(root))+ .map(|(_, n)| n)+ .sum()+}++/// The object-store path a `dltest://<dir>` table's reads are recorded under.+fn table_root(dir: &std::path::Path) -> String {+ Path::from(dir.to_string_lossy().as_ref()).to_string()+}++fn count_checkpoint_get(location: &Path, n: usize) {+ if location.as_ref().contains(".checkpoint.") {+ *CHECKPOINT_GETS+ .lock()+ .unwrap()+ .entry(location.to_string())+ .or_default() += n;+ }+}++fn checkpoint_gets() -> HashMap<String, usize> {+ CHECKPOINT_GETS.lock().unwrap().clone()+}++/// Checkpoint GETs issued since `before`, per file.+fn checkpoint_gets_since(before: &HashMap<String, usize>) -> HashMap<String, usize> {+ checkpoint_gets()+ .into_iter()+ .filter_map(|(path, n)| {+ let delta = n - before.get(&path).copied().unwrap_or(0);+ (delta > 0).then_some((path, delta))+ })+ .collect()}#[derive(Debug)]@@ -68,7 +118,10 @@ impl ObjectStore for CountingStore {location: &Path,options: GetOptions,) -> object_store::Result<GetResult> {- READS.fetch_add(1, Ordering::SeqCst);+ record_read(location.to_string(), 1);+ if !options.head {+ count_checkpoint_get(location, 1);+ }self.inner.get_opts(location, options).await}@@ -77,7 +130,8 @@ impl ObjectStore for CountingStore {location: &Path,ranges: &[std::ops::Range<u64>],) -> object_store::Result<Vec<bytes::Bytes>> {- READS.fetch_add(ranges.len(), Ordering::SeqCst);+ record_read(location.to_string(), ranges.len());+ count_checkpoint_get(location, ranges.len());self.inner.get_ranges(location, ranges).await}@@ -91,7 +145,7 @@ impl ObjectStore for CountingStore {// Sorted before returning: cloud stores list keys lexicographically and// delta-kernel relies on it, while `LocalFileSystem` yields directory order.fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {- READS.fetch_add(1, Ordering::SeqCst);+ record_read(prefix_key(prefix), 1);sorted(self.inner.list(prefix))}@@ -100,12 +154,12 @@ impl ObjectStore for CountingStore {prefix: Option<&Path>,offset: &Path,) -> BoxStream<'static, object_store::Result<ObjectMeta>> {- READS.fetch_add(1, Ordering::SeqCst);+ record_read(prefix_key(prefix), 1);sorted(self.inner.list_with_offset(prefix, offset))}async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {- READS.fetch_add(1, Ordering::SeqCst);+ record_read(prefix_key(prefix), 1);self.inner.list_with_delimiter(prefix).await}@@ -128,6 +182,10 @@ impl ObjectStore for CountingStore {}}+fn prefix_key(prefix: Option<&Path>) -> String {+ prefix.map(ToString::to_string).unwrap_or_default()+}+fn sorted(stream: BoxStream<'static, object_store::Result<ObjectMeta>>,) -> BoxStream<'static, object_store::Result<ObjectMeta>> {@@ -210,17 +268,32 @@ fn opts() -> UpsertOptions {/// Create an unpartitioned table at `uri` with a non-nullable `pk` and a `v` column of/// the given nullability, then seed it with a few commits so opening has log to replay.async fn create_seeded_table(uri: &str, v_nullable: bool) -> SchemaRef {- CreateBuilder::new()- .with_location(uri)- .with_columns(vec![- StructField::new("pk", KernelType::STRING, false),- StructField::new("v", KernelType::LONG, v_nullable),- ])- .await- .expect("create table");+ create_seeded_table_with(uri, v_nullable, None, 3).await+}++/// [`create_seeded_table`] with a checkpoint interval and commit count. deltalite writes+/// a checkpoint when `(version + 1) % interval == 0`, so an interval of 2 over 4 commits+/// checkpoints versions 1 and 3 and leaves one JSON commit after the last checkpoint.+async fn create_seeded_table_with(+ uri: &str,+ v_nullable: bool,+ checkpoint_interval: Option<u32>,+ commits: i64,+) -> SchemaRef {+ let mut builder = CreateBuilder::new().with_location(uri).with_columns(vec![+ StructField::new("pk", KernelType::STRING, false),+ StructField::new("v", KernelType::LONG, v_nullable),+ ]);+ if let Some(interval) = checkpoint_interval {+ builder = builder.with_configuration_property(+ TableProperty::CheckpointInterval,+ Some(interval.to_string()),+ );+ }+ builder.await.expect("create table");let s = schema(v_nullable);- for i in 0..3 {+ for i in 0..commits {let mut handle = TableHandle::open(uri.to_string(), HashMap::new()).await.expect("open for seeding");@@ -233,28 +306,74 @@ async fn create_seeded_table(uri: &str, v_nullable: bool) -> SchemaRef {s}+/// Create a table partitioned on `p` at `uri` with one file in each of two partitions.+async fn create_partitioned_table(uri: &str) -> SchemaRef {+ CreateBuilder::new()+ .with_location(uri)+ .with_columns(vec![+ StructField::new("pk", KernelType::STRING, false),+ StructField::new("p", KernelType::STRING, true),+ StructField::new("v", KernelType::LONG, true),+ ])+ .with_partition_columns(vec!["p".to_string()])+ .await+ .expect("create partitioned table");++ let s: SchemaRef = Arc::new(Schema::new(vec![+ Field::new("pk", DataType::Utf8, false),+ Field::new("p", DataType::Utf8, true),+ Field::new("v", DataType::Int64, true),+ ]));+ let b = RecordBatch::try_new(+ s.clone(),+ vec![+ Arc::new(StringArray::from(vec!["a", "b"])),+ Arc::new(StringArray::from(vec!["x", "y"])),+ Arc::new(Int64Array::from(vec![1, 2])),+ ],+ )+ .expect("partitioned batch");+ let mut handle = TableHandle::open(uri.to_string(), HashMap::new())+ .await+ .expect("open for seeding");+ handle+ .upsert(+ vec![b],+ s.clone(),+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ partition_key: Some("p".to_string()),+ ..Default::default()+ },+ MultipartConfig::default(),+ )+ .await+ .expect("partitioned seed upsert");+ s+}+// ---- tests -------------------------------------------------------------------------/// Pins the double-load fix: opening through the multipart wrapper must cost the same-/// storage reads as a plain open, not twice as many. Serial with the other counting-/// test via the shared atomic; each measurement is deltas around one call, and the-/// tests run in one process where no other code touches the `dltest://` scheme.+/// storage reads as a plain open, not twice as many.#[tokio::test]async fn open_table_multipart_replays_the_log_once() {register_counting_scheme();let dir = tempfile::tempdir().expect("tempdir");- let uri = format!("dltest://{}", dir.path().join("t1").to_string_lossy());+ let table_dir = dir.path().join("t1");+ let uri = format!("dltest://{}", table_dir.to_string_lossy());+ let root = table_root(&table_dir);create_seeded_table(&uri, true).await;- let before_plain = reads();+ let before_plain = reads_under(&root);let plain = open_table(&uri, HashMap::new()).await.expect("plain open");- let plain_reads = reads() - before_plain;+ let plain_reads = reads_under(&root) - before_plain;- let before_multipart = reads();+ let before_multipart = reads_under(&root);let multipart = open_table_multipart(&uri, HashMap::new(), MultipartConfig::default()).await.expect("multipart open");- let multipart_reads = reads() - before_multipart;+ let multipart_reads = reads_under(&root) - before_multipart;assert_eq!(plain.version(), multipart.version());assert!(plain.version().is_some(), "open must load the snapshot");@@ -394,3 +513,184 @@ async fn warm_relax_cache_still_relaxes_when_the_batch_carries_nulls() {.expect("post-relax upsert");assert_eq!(stats.columns_relaxed, 0);}++/// The checkpoint prefetch: a snapshot load must read each checkpoint Parquet file with+/// one whole-object GET instead of one ranged GET per footer, metadata and column chunk.+/// Covers both the initial open and the post-commit refresh that adopts a checkpoint the+/// upsert's own maintenance just wrote (through the multipart-wrapped view).+#[tokio::test]+async fn checkpoint_files_are_read_with_one_get_each() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = format!("dltest://{}", dir.path().join("t5").to_string_lossy());+ let s = create_seeded_table_with(&uri, true, Some(2), 4).await;++ let before = checkpoint_gets();+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open handle");+ let opened = checkpoint_gets_since(&before);+ assert_eq!(handle.version(), 4);+ assert!(!opened.is_empty(), "the open must load from a checkpoint");+ for (path, gets) in &opened {+ assert_eq!(+ *gets, 1,+ "{path} was read with {gets} GETs; expected one prefetch"+ );+ }++ // Version 5 sits on the interval boundary: maintenance writes checkpoint 5 and the+ // post-commit refresh rebuilds the snapshot from it.+ let before = checkpoint_gets();+ let stats = handle+ .upsert(+ vec![batch(&s, &["c"], vec![Some(9)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("boundary upsert");+ assert_eq!(stats.version, 5);+ let refreshed = checkpoint_gets_since(&before);+ assert!(+ refreshed.keys().any(|p| p.contains("00000000000000000005")),+ "the refresh must adopt the new checkpoint (read: {refreshed:?})"+ );+ for (path, gets) in &refreshed {+ assert_eq!(+ *gets, 1,+ "{path} was read with {gets} GETs; expected one prefetch"+ );+ }+}++/// The full load that opens a handle is reported once, on the first upsert through it,+/// so a caller summing per-upsert stats attributes the open cost exactly once.+#[tokio::test]+async fn initial_open_is_timed_and_reported_on_the_first_upsert_only() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t6").to_string_lossy().to_string();+ let s = create_seeded_table_with(&uri, true, Some(2), 6).await;++ let mut handle = TableHandle::open(uri, HashMap::new())+ .await+ .expect("open handle");+ assert!(+ handle.initial_open_ms() > 0,+ "a checkpoint load plus log replay must register on the clock"+ );++ let first = handle+ .upsert(+ vec![batch(&s, &["a"], vec![Some(1)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("first upsert");+ assert_eq!(first.initial_open_ms, handle.initial_open_ms());++ let second = handle+ .upsert(+ vec![batch(&s, &["a"], vec![Some(2)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("second upsert");+ assert_eq!(second.initial_open_ms, 0, "reported once per handle");+}++/// The snapshot accessors describe the loaded table without I/O and agree with what+/// delta-rs itself reports for the same snapshot.+#[tokio::test]+async fn snapshot_accessors_describe_the_loaded_table() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let table_dir = dir.path().join("t7");+ let uri = format!("dltest://{}", table_dir.to_string_lossy());+ let root = table_root(&table_dir);+ create_seeded_table_with(&uri, true, Some(2), 3).await;++ let handle = TableHandle::open(uri, HashMap::new())+ .await+ .expect("open handle");+ let snapshot = handle.table().snapshot().expect("loaded snapshot");++ let before = reads_under(&root);+ let files = handle.files().expect("files");+ let uris: Vec<String> = handle.table().get_file_uris().expect("file uris").collect();+ assert_eq!(files.len(), uris.len());+ assert_eq!(handle.num_files().expect("num_files"), files.len());+ for f in &files {+ assert!(+ uris.iter().any(|u| u.ends_with(&f.path)),+ "{} is not a live file ({uris:?})",+ f.path+ );+ assert!(f.size > 0);+ assert!(f.modification_time > 0);+ assert!(f.partition_values.is_empty(), "unpartitioned table");+ }++ let schema: serde_json::Value =+ serde_json::from_str(&handle.schema_json().expect("schema_json")).expect("valid json");+ assert_eq!(schema["type"], "struct");+ let names: Vec<&str> = schema["fields"]+ .as_array()+ .expect("fields")+ .iter()+ .map(|f| f["name"].as_str().expect("name"))+ .collect();+ assert_eq!(names, ["pk", "v"]);++ assert_eq!(+ handle.table_id().expect("table_id"),+ snapshot.metadata().id()+ );+ let configuration = handle.configuration().expect("configuration");+ assert_eq!(&configuration, snapshot.metadata().configuration());+ assert_eq!(+ configuration+ .get("delta.checkpointInterval")+ .map(String::as_str),+ Some("2")+ );+ assert_eq!(+ reads_under(&root),+ before,+ "accessors must be served from memory"+ );+}++#[tokio::test]+async fn files_carry_partition_values() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t8").to_string_lossy().to_string();+ create_partitioned_table(&uri).await;++ let handle = TableHandle::open(uri, HashMap::new())+ .await+ .expect("open handle");+ let mut files = handle.files().expect("files");+ files.sort_by(|a, b| a.path.cmp(&b.path));+ assert_eq!(files.len(), 2);+ let mut partitions: Vec<Option<String>> = files+ .iter()+ .map(|f| {+ assert_eq!(f.partition_values.len(), 1);+ assert!(f.path.starts_with(&format!(+ "p={}/",+ f.partition_values["p"]+ .as_deref()+ .unwrap_or("__HIVE_DEFAULT_PARTITION__")+ )));+ f.partition_values["p"].clone()+ })+ .collect();+ partitions.sort();+ assert_eq!(partitions, [Some("x".to_string()), Some("y".to_string())]);+}diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex 8e14c1734b09..0879c0573210 100644--- a/rust/deltalite/python/Cargo.toml+++ b/rust/deltalite/python/Cargo.toml@@ -1,7 +1,7 @@[package]name = "deltalite-python"# Mirrors pyproject.toml in this directory (always identical); bump both together.-version = "0.1.8"+version = "0.1.9"edition = "2021"# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).diff --git a/rust/deltalite/python/README.md b/rust/deltalite/python/README.mdindex 2099ae8775ea..b8f88db8261d 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -101,23 +101,35 @@ rejected (raising `DeltaLiteError`) rather than silently double-inserted.| `.upsert(data, primary_keys, partition_key=None, **opts)` | Insert-or-replace `data` by key. Returns `UpsertStats`. See knobs below. || `.version()` | Current table version (`int`). || `.reload()` | Bring the table state up to date with the log (incremental; falls back to a full re-open). |+| `.table_id()` | The table id from the metadata action (`str`). |+| `.configuration()` | Table configuration, `delta.*` properties and custom keys (`dict[str, str]`). || `.schema_arrow()` | Table schema as a pyarrow `Schema`. |+| `.schema_json()` | Table schema as the Delta JSON document (`str`), as `DeltaTable.schema().to_json()` returns it. || `.partition_columns()` | Partition column names (`list[str]`). |+| `.num_files()` | Number of active data files (`int`). |+| `.files()` | Active data files as dicts: `path` (relative to the table root), `size`, `modification_time` (epoch ms), `partition_values` (`dict[str, str \| None]`). || `.file_uris()` | URIs of the table's active data files. || `.history(limit)` | Recent commit history entries. |+`version`, `table_id`, `configuration`, `schema_*`, `partition_columns`,+`num_files`, `files` and `file_uris` read the loaded snapshot in memory and do+no I/O; call `reload()` first when the table may have moved. `history` reads the+log.+### `UpsertStats`Returned by `upsert`. Counts: `version`, `partitions_touched`, `files_added`,`files_removed`, `files_carried_over`, `files_probed`, `rows_updated`,`rows_inserted`, `rows_copied`, `source_rows`, `null_pk_rows`. Per-phasewall-clock timings (milliseconds): `ingest_ms` (importing the pyarrow source),-`open_ms` (snapshot refreshes around the upsert), `relax_ms` (nullability-relax-check), `plan_ms` (listing + pruning files), `rewrite_ms` (reading + rewriting-the touched partitions), `commit_ms` (committing to the Delta log),-`maintenance_ms` (checkpoint/log cleanup, non-zero only on checkpoint-boundary-commits). `columns_relaxed` counts non-nullable columns flipped to nullable-before the write.+`initial_open_ms` (the full snapshot load in `DeltaLiteTable.open`, reported on+the first upsert through a handle and `0` afterwards, so a sum over a handle's+upserts counts it once), `open_ms` (snapshot refreshes around the upsert),+`relax_ms` (nullability-relax check), `plan_ms` (listing + pruning files),+`rewrite_ms` (reading + rewriting the touched partitions), `commit_ms`+(committing to the Delta log), `maintenance_ms` (checkpoint/log cleanup,+non-zero only on checkpoint-boundary commits). `columns_relaxed` counts+non-nullable columns flipped to nullable before the write.### Exceptions@@ -161,13 +173,24 @@ budgets:`DELTALITE_MAX_SOURCE_BYTES`, `DELTALITE_MULTIPART_THRESHOLD_BYTES`,`DELTALITE_MULTIPART_PART_SIZE_BYTES`.+**Checkpoint prefetch.** Opening or reloading a table reads its latest+checkpoint Parquet file whole in one GET and serves the Parquet reader's many+small range reads from memory, instead of one round trip per footer, metadata+block and column chunk. `DELTALITE_CHECKPOINT_PREFETCH_MAX_BYTES` (128 MiB)+bounds the total checkpoint bytes cached by one table load; larger files or+multipart checkpoints that exhaust the budget fall back to range reads, and `0`+disables the prefetch. Cached bytes also reserve space from+`DELTALITE_PROCESS_MAX_BUFFERED_BYTES`, so concurrent table opens share the+process-wide budget. The bytes are released as soon as the load finishes.+## Metricsdeltalite emits via the Rust [`metrics`](https://docs.rs/metrics) facade (staticlabels only): `deltalite_upserts_total` (`outcome`, `prune_strategy`,`error_kind`), `deltalite_upsert_duration_seconds`,-`deltalite_files_{added,removed,carried_over,probed}_total`, and-`deltalite_rows_{updated,inserted,copied}_total`.+`deltalite_files_{added,removed,carried_over,probed}_total`,+`deltalite_rows_{updated,inserted,copied}_total`, and+`deltalite_checkpoint_prefetch_total` (`outcome`).## Compatibility & statusdiff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlindex 5492d46a5c3f..0233b80aba87 100644--- a/rust/deltalite/python/pyproject.toml+++ b/rust/deltalite/python/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "maturin"[project]name = "deltalite"# Mirrors `rust/deltalite/python/Cargo.toml` (always identical); bump both together.-version = "0.1.8"+version = "0.1.9"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"diff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsindex 1821644a1f2d..b1039cc1b15d 100644--- a/rust/deltalite/python/src/lib.rs+++ b/rust/deltalite/python/src/lib.rs@@ -172,6 +172,8 @@ pub struct UpsertStats {#[pyo3(get)]pub open_ms: u64,#[pyo3(get)]+ pub initial_open_ms: u64,+ #[pyo3(get)]pub ingest_ms: u64,#[pyo3(get)]pub relax_ms: u64,@@ -218,6 +220,7 @@ impl From<deltalite_core::upsert::UpsertStats> for UpsertStats {commit_ms: s.commit_ms,columns_relaxed: s.columns_relaxed,open_ms: s.open_ms,+ initial_open_ms: s.initial_open_ms,ingest_ms: s.ingest_ms,relax_ms: s.relax_ms,maintenance_ms: s.maintenance_ms,@@ -225,9 +228,10 @@ impl From<deltalite_core::upsert::UpsertStats> for UpsertStats {}}-/// A handle on a Delta table for deltalite writes. Reads (schema, history, file-/// listing) exist for parity tooling; production read paths stay on the Python-/// `deltalake` package -- both address the same `_delta_log`.+/// A handle on a Delta table for deltalite writes, plus snapshot reads (version, table+/// id, schema, live files) served from the loaded state so a writer does not need a+/// second delta-rs `DeltaTable` open for them. `history` is the one read that goes back+/// to the log.#[pyclass(module = "deltalite")]pub struct DeltaLiteTable {handle: TableHandle,@@ -269,6 +273,43 @@ impl DeltaLiteTable {self.handle.version()}+ /// The table id from the snapshot's metadata action.+ fn table_id(&self) -> PyResult<String> {+ self.handle.table_id().map_err(to_py_err)+ }++ /// The table configuration (`delta.*` properties and custom keys).+ fn configuration(&self) -> PyResult<HashMap<String, String>> {+ self.handle.configuration().map_err(to_py_err)+ }++ /// The Delta schema of the loaded snapshot as a JSON string, in the form+ /// `deltalake.DeltaTable.schema().to_json()` returns.+ fn schema_json(&self) -> PyResult<String> {+ self.handle.schema_json().map_err(to_py_err)+ }++ /// Number of live data files in the loaded snapshot.+ fn num_files(&self) -> PyResult<usize> {+ self.handle.num_files().map_err(to_py_err)+ }++ /// The live data files of the loaded snapshot, one dict per file with `path`+ /// (relative to the table root), `size`, `modification_time` (epoch ms) and+ /// `partition_values` (`dict[str, str | None]`, empty when unpartitioned).+ fn files(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {+ let out = PyList::empty(py);+ for file in self.handle.files().map_err(to_py_err)? {+ let d = PyDict::new(py);+ d.set_item("path", file.path)?;+ d.set_item("size", file.size)?;+ d.set_item("modification_time", file.modification_time)?;+ d.set_item("partition_values", file.partition_values)?;+ out.append(d)?;+ }+ Ok(out.into())+ }+/// Re-read the log so this handle observes commits made elsewhere. Incremental --/// only commits newer than the loaded version are read -- with a full re-open/// fallback when the log is not reachable forward from the loaded state.diff --git a/rust/deltalite/python/tests/test_snapshot.py b/rust/deltalite/python/tests/test_snapshot.pynew file mode 100644index 000000000000..bf7cc6a0b559--- /dev/null+++ b/rust/deltalite/python/tests/test_snapshot.py@@ -0,0 +1,97 @@+"""Snapshot reads served from the deltalite handle's in-memory state.++A writer that already holds a `DeltaLiteTable` should not need a second delta-rs+`DeltaTable` open to learn the table's identity, schema or live files. These tests hold+the handle's answers to what delta-rs reports for the same table, and check they follow+the handle's own commits.+"""++from __future__ import annotations++import sys+import json+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, create_table # noqa: E402+++def rows(ids: list[int], part: list[str] | None = None) -> pa.Table:+ return pa.table(+ {+ "id": pa.array(ids, pa.int64()),+ "v": pa.array([i * 10 for i in ids], pa.int64()),+ PARTITION_KEY: pa.array(part or ["p1"] * len(ids), pa.string()),+ }+ )+++def add_actions_by_path(dt: deltalake.DeltaTable) -> dict[str, dict]:+ """delta-rs's view of the live files, keyed by path (it returns an arro3 table)."""+ actions = pa.table(dt.get_add_actions(flatten=False)).to_pylist()+ return {a["path"]: a for a in actions}++[email protected]("partitioned", [False, True], ids=["unpartitioned", "partitioned"])+def test_snapshot_reads_match_delta_rs(tmp_path, partitioned):+ import deltalite++ uri = str(tmp_path / "t")+ create_table(uri, rows([1, 2, 3, 4], ["p1", "p1", "p2", "p2"]), partitioned=partitioned)++ rs = deltalite.DeltaLiteTable.open(uri)+ dt = deltalake.DeltaTable(uri)++ assert rs.version() == dt.version()+ assert rs.table_id() == dt.metadata().id+ assert rs.configuration() == dt.metadata().configuration+ assert json.loads(rs.schema_json()) == json.loads(dt.schema().to_json())++ expected = add_actions_by_path(dt)+ assert rs.num_files() == len(expected)+ files = rs.files()+ assert sorted(f["path"] for f in files) == sorted(expected)+ for f in files:+ action = expected[f["path"]]+ assert f["size"] == action["size_bytes"]+ assert f["modification_time"] == action["modification_time"]+ if partitioned:+ assert f["partition_values"] == action["partition"]+ assert f["path"].startswith(f"{PARTITION_KEY}={f['partition_values'][PARTITION_KEY]}/")+ else:+ assert f["partition_values"] == {}+++def test_files_follow_the_handles_own_commit(tmp_path):+ import deltalite++ uri = str(tmp_path / "t")+ create_table(uri, rows([1, 2], ["p1", "p1"]), partitioned=True)++ rs = deltalite.DeltaLiteTable.open(uri)+ before = {f["path"] for f in rs.files()}+ stats = rs.upsert(rows([3], ["p2"]), primary_keys=["id"], partition_key=PARTITION_KEY)++ assert rs.version() == stats.version+ after = {f["path"] for f in rs.files()}+ assert before < after, "the new partition's file must appear without a reload"+ assert sorted(after) == sorted(add_actions_by_path(deltalake.DeltaTable(uri)))+++def test_initial_open_is_reported_on_the_first_upsert_only(tmp_path):+ import deltalite++ uri = str(tmp_path / "t")+ create_table(uri, rows([1, 2]), partitioned=False)++ rs = deltalite.DeltaLiteTable.open(uri)+ first = rs.upsert(rows([1]), primary_keys=["id"])+ second = rs.upsert(rows([2]), primary_keys=["id"])++ assert isinstance(first.initial_open_ms, int)+ assert second.initial_open_ms == 0