Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(customer-analytics): isolate account property staging (#87289)

Arthur Moreira de Deus543586452511
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 42f3bbe5ba03..5791d1ce8cd1 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -249,6 +249,7 @@ class MaterializeViewResult:
person_property_sync_enabled: bool = False
# Defaulted so workflow histories recorded before account staging do not start new children on replay.
account_property_sync_enabled: bool = False
+ delta_version: int | None = None
# Whether this run staged rows for a warehouse-view CDP trigger, so the workflow knows to start
# the producer job. Defaulted so old workflow histories decode without it.
should_trigger_cdp_producer: bool = False
@@ -687,22 +688,21 @@ async def _build_person_property_sink(
return None
-async def _build_account_property_sink(
- objects: MatviewInputObjects, job_id: str, logger: FilteringBoundLogger, *, incremental: bool
-) -> AccountPropertyRowSink | None:
+async def _account_property_sync_enabled(
+ objects: MatviewInputObjects, job_id: str, logger: FilteringBoundLogger
+) -> bool:
sink = AccountPropertyRowSink(
team_id=objects.team.pk,
binding=saved_query_binding(objects.saved_query.id),
job_id=job_id,
logger=logger,
- is_incremental=incremental,
)
try:
- return sink if await sink.should_run() else None
+ return await sink.should_run()
except Exception as error:
await logger.awarning(f"Could not resolve account-property staging for this view: {error}")
capture_exception(error)
- return None
+ return False
async def _clear_person_property_staging(sink: PersonPropertyRowSink, logger: FilteringBoundLogger) -> None:
@@ -714,15 +714,6 @@ async def _clear_person_property_staging(sink: PersonPropertyRowSink, logger: Fi
capture_exception(e)
-async def _clear_account_property_staging(sink: AccountPropertyRowSink, logger: FilteringBoundLogger) -> None:
- try:
- await sink.clear()
- except Exception as error:
- await logger.awarning(f"Could not clear stale account-property staging: {error}")
- capture_exception(error)
- raise
-
-
async def _stage_person_property_batch(
sink: PersonPropertyRowSink | None, batch_index: int, batch: pa.RecordBatch, *, fatal: bool
) -> None:
@@ -750,20 +741,6 @@ async def _stage_person_property_batch(
capture_exception(e)
-async def _stage_account_property_batch(
- sink: AccountPropertyRowSink | None, batch_index: int, batch: pa.RecordBatch, *, fatal: bool
-) -> None:
- if sink is None:
- return
- try:
- await sink.stage_chunk(batch_index, pa.Table.from_batches([batch]))
- except Exception as error:
- await sink.logger.awarning(f"Failed to stage account-property batch {batch_index}: {error}")
- if fatal:
- raise
- capture_exception(error)
-
-
async def _materialize_fully(
objects: MatviewInputObjects,
plan: WritePlan,
@@ -773,7 +750,6 @@ async def _materialize_fully(
logger: FilteringBoundLogger,
cdp_sink: "_CDPRowSink",
person_property_sink: PersonPropertyRowSink | None = None,
- account_property_sink: AccountPropertyRowSink | None = None,
) -> tuple[int, list[str]]:
"""Rebuild the whole table from the query. The only path that creates a Delta table, and the
fallback for every case the incremental path cannot serve."""
@@ -812,7 +788,6 @@ async def _materialize_fully(
if tracker is not None:
await asyncio.to_thread(tracker.check, batch)
await _stage_person_property_batch(person_property_sink, batch_index, batch, fatal=False)
- await _stage_account_property_batch(account_property_sink, batch_index, batch, fatal=True)
batch_index += 1
if delta_table is None:
pa_schema = batch.schema
@@ -875,7 +850,6 @@ async def _materialize_incrementally(
logger: FilteringBoundLogger,
cdp_sink: "_CDPRowSink",
person_property_sink: PersonPropertyRowSink | None = None,
- account_property_sink: AccountPropertyRowSink | None = None,
) -> tuple[int, list[str]]:
"""Upsert only the rows at or after the watermark into the existing table.
@@ -916,7 +890,6 @@ async def _materialize_incrementally(
# of the later batch silently replacing the earlier one.
await asyncio.to_thread(tracker.check, batch)
await _stage_person_property_batch(person_property_sink, batch_index, batch, fatal=True)
- await _stage_account_property_batch(account_property_sink, batch_index, batch, fatal=True)
batch_index += 1
stats = await asyncio.to_thread(
@@ -1054,12 +1027,6 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
# what sweeps long-abandoned sibling job prefixes.
await _clear_person_property_staging(person_property_sink, logger)
- account_property_sink = await _build_account_property_sink(
- objects, inputs.job_id, logger, incremental=plan.incremental
- )
- if account_property_sink is not None:
- await _clear_account_property_staging(account_property_sink, logger)
-
cdp_sink = _CDPRowSink(
CDPProducer.for_view(
team_id=inputs.team_id,
@@ -1095,7 +1062,6 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
logger,
cdp_sink,
person_property_sink,
- account_property_sink,
)
else:
row_count, file_uris = await _materialize_fully(
@@ -1107,7 +1073,6 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
logger,
cdp_sink,
person_property_sink,
- account_property_sink,
)
except (Exception, asyncio.CancelledError):
# A retry stages from scratch and a terminal failure produces nothing, so whatever
@@ -1119,6 +1084,20 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
quality_audit = await database_sync_to_async_pool(data_quality_facade.quality_audit_mode)(
inputs.team_id, str(objects.saved_query.id)
)
+ account_property_sync_enabled = await _account_property_sync_enabled(objects, inputs.job_id, logger)
+ delta_version: int | None = None
+ if account_property_sync_enabled:
+ try:
+ delta_table = await asyncio.to_thread(
+ deltalake.DeltaTable,
+ table_uri,
+ storage_options=storage_options,
+ )
+ delta_version = delta_table.version()
+ except Exception as error:
+ await logger.awarning(f"Could not resolve account-property Delta snapshot: {error}")
+ capture_exception(error)
+ account_property_sync_enabled = False
result = MaterializeViewResult(
node_id=objects.node.id,
node_name=objects.node.name,
@@ -1129,7 +1108,8 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
quality_audit=quality_audit,
incremental=plan.incremental,
person_property_sync_enabled=person_property_sink is not None,
- account_property_sync_enabled=account_property_sink is not None,
+ account_property_sync_enabled=account_property_sync_enabled,
+ delta_version=delta_version,
should_trigger_cdp_producer=cdp_sink.enabled,
)
published = True
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index 78a918e96ac4..5c2f76086149 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -58,7 +58,10 @@ from posthog.temporal.data_modeling.metrics import (
from posthog.temporal.data_modeling.workflows.enrich_view_semantics import EnrichViewSemanticsWorkflow
from posthog.temporal.utils import CDPProducerWorkflowInputs
-from products.customer_analytics.backend.facade.temporal_contracts import DispatchAccountPropertySyncInput
+from products.customer_analytics.backend.facade.temporal_contracts import (
+ DispatchAccountPropertySyncInput,
+ StageAccountPropertySyncInput,
+)
from products.data_modeling.backend.facade.models import DataModelingJobEngine
from products.data_quality.backend.facade.contracts import (
CHECK_SUITE_WORKFLOW_NAME,
@@ -78,6 +81,7 @@ from products.warehouse_sources.backend.facade.hooks import (
# warn-mode suite child.
QUALITY_AUDIT_PATCH = "data-quality-audit-2026-08"
ACCOUNT_PROPERTY_S3_SYNC_PATCH = "account-property-s3-sync-2026-08"
+ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH = "account-property-staging-workflow-2026-08"
# Covers the CDP producer child and the staging-cleanup activity. Both are new commands, so a
# history recorded before this deploy has to keep taking the branch that issues neither.
@@ -381,8 +385,13 @@ class MaterializeViewWorkflow(PostHogWorkflow):
# that reads it. Fire-and-forget on the metadata queue, like enrichment above.
await self._maybe_sync_person_properties(inputs, materialize_result, job_id)
- if temporalio.workflow.patched(ACCOUNT_PROPERTY_S3_SYNC_PATCH):
- await self._maybe_sync_account_properties(inputs, materialize_result, job_id)
+ # New executions start the isolated staging child. A history that recorded the old
+ # inline dispatch under ACCOUNT_PROPERTY_S3_SYNC_PATCH must keep emitting that
+ # command on replay, so keep the old path in the else branch.
+ if temporalio.workflow.patched(ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH):
+ await self._maybe_stage_account_properties(inputs, materialize_result, job_id)
+ elif temporalio.workflow.patched(ACCOUNT_PROPERTY_S3_SYNC_PATCH):
+ await self._replay_account_property_dispatch(inputs, materialize_result, job_id)
# after the main workflow succeeds, collect shadow stats for comparison
if duckgres_shadow_handle is not None:
@@ -627,7 +636,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
extra={"job_id": job_id, "error": str(e)},
)
- async def _maybe_sync_account_properties(
+ async def _replay_account_property_dispatch(
self,
inputs: MaterializeViewWorkflowInputs,
materialize_result: MaterializeViewResult,
@@ -647,6 +656,42 @@ class MaterializeViewWorkflow(PostHogWorkflow):
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=5),
)
+ async def _maybe_stage_account_properties(
+ self,
+ inputs: MaterializeViewWorkflowInputs,
+ materialize_result: MaterializeViewResult,
+ job_id: str,
+ ) -> None:
+ if not materialize_result.account_property_sync_enabled or materialize_result.delta_version is None:
+ return
+ try:
+ await temporalio.workflow.start_child_workflow(
+ "stage-warehouse-account-properties",
+ StageAccountPropertySyncInput(
+ team_id=inputs.team_id,
+ saved_query_id=materialize_result.saved_query_id,
+ job_id=job_id,
+ table_uri=materialize_result.table_uri,
+ delta_version=materialize_result.delta_version,
+ ),
+ id=f"stage-warehouse-account-properties-{job_id}",
+ id_reuse_policy=temporalio.common.WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=dt.timedelta(hours=24),
+ )
+ except WorkflowAlreadyStartedError:
+ temporalio.workflow.logger.info(
+ "Account-property staging already running for this job, skipping",
+ extra={"job_id": job_id},
+ )
+ except Exception as error:
+ capture_exception(error)
+ temporalio.workflow.logger.warning(
+ "Failed to start account-property staging",
+ extra={"job_id": job_id, "error": str(error)},
+ )
+
async def _maybe_produce_cdp_rows(
self,
inputs: MaterializeViewWorkflowInputs,
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 853bdbc2c419..e5ee5df53928 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -42,6 +42,10 @@ from posthog.temporal.data_modeling.activities.materialize_view import (
)
from posthog.temporal.data_modeling.activities.notify_materialization_failure import _SavedQueryViewers
+from products.customer_analytics.backend.facade.temporal_contracts import StageAccountPropertySyncInput
+from products.customer_analytics.backend.temporal.account_property_sync import (
+ stage_warehouse_account_property_files_activity,
+)
from products.data_modeling.backend.facade.api import compute_enrichment_hash
from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view
from products.data_modeling.backend.facade.models import (
@@ -1827,7 +1831,7 @@ class TestMaterializeViewStagesAccountPropertyRows:
return async_generator()
- async def test_stages_account_projection_under_the_materialization_job(
+ async def test_exposes_account_delta_snapshot_without_staging_inside_materialization(
self, activity_environment, ateam, anode, asaved_query, ajob, adag, bucket_name, minio_client
) -> None:
projection = [
@@ -1867,14 +1871,31 @@ class TestMaterializeViewStagesAccountPropertyRows:
saved_query_binding(asaved_query.id),
str(ajob.id),
)
+ listing_before_staging = await minio_client.list_objects_v2(
+ Bucket=bucket_name,
+ Prefix=prefix.removeprefix(f"{bucket_name}/"),
+ )
+ assert result.delta_version is not None
+ staged = await activity_environment.run(
+ stage_warehouse_account_property_files_activity,
+ StageAccountPropertySyncInput(
+ team_id=ateam.pk,
+ saved_query_id=str(asaved_query.id),
+ job_id=str(ajob.id),
+ table_uri=result.table_uri,
+ delta_version=result.delta_version,
+ ),
+ )
+ listing_after_staging = await minio_client.list_objects_v2(
+ Bucket=bucket_name,
+ Prefix=prefix.removeprefix(f"{bucket_name}/"),
+ )
assert result.account_property_sync_enabled is True
- listing = await minio_client.list_objects_v2(
- Bucket=bucket_name,
- Prefix=prefix.removeprefix(f"{bucket_name}/"),
- )
- keys = [obj["Key"] for obj in listing.get("Contents", [])]
+ assert listing_before_staging.get("Contents", []) == []
+ assert staged is True
+ keys = [obj["Key"] for obj in listing_after_staging.get("Contents", [])]
assert len(keys) == 1
- staged = await minio_client.get_object(Bucket=bucket_name, Key=keys[0])
- table = pq.read_table(BytesIO(await staged["Body"].read()))
+ staged_object = await minio_client.get_object(Bucket=bucket_name, Key=keys[0])
+ table = pq.read_table(BytesIO(await staged_object["Body"].read()))
assert table.column_names == ["mrr", "organization_id"]
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index 21c8091d7500..81b5bfe816ce 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -1,5 +1,6 @@
import datetime as dt
import dataclasses
+from collections.abc import Callable
from contextlib import ExitStack
import pytest
@@ -17,13 +18,14 @@ from posthog.temporal.data_modeling.activities import (
fail_materialization_activity,
)
from posthog.temporal.data_modeling.activities.enrich_view_semantics import EnrichViewSemanticsInputs
-from posthog.temporal.data_modeling.activities.materialize_view import _clear_account_property_staging
from posthog.temporal.data_modeling.workflows.materialize_view import (
+ ACCOUNT_PROPERTY_S3_SYNC_PATCH,
+ ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH,
MaterializeViewWorkflow,
MaterializeViewWorkflowInputs,
)
-from products.customer_analytics.backend.facade.temporal_contracts import DispatchAccountPropertySyncInput
+from products.customer_analytics.backend.facade.temporal_contracts import StageAccountPropertySyncInput
from products.data_quality.backend.facade.contracts import CHECK_SUITE_WORKFLOW_NAME, QualityAuditMode
from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncActivityInputs
@@ -54,7 +56,7 @@ class TestQualityGateBranching:
activity_results: list,
child_result: dict | Exception,
*,
- patched: bool = True,
+ patched: bool | Callable[[str], bool] = True,
shadow_handle: AsyncMock | None = None,
start_child: AsyncMock | None = None,
) -> tuple:
@@ -72,7 +74,12 @@ class TestQualityGateBranching:
stack.enter_context(
patch.object(temporalio.workflow, "start_child_workflow", new=start_child or AsyncMock())
)
- stack.enter_context(patch.object(temporalio.workflow, "patched", return_value=patched))
+ patched_mock = (
+ patch.object(temporalio.workflow, "patched", side_effect=patched)
+ if callable(patched)
+ else patch.object(temporalio.workflow, "patched", return_value=patched)
+ )
+ stack.enter_context(patched_mock)
stack.enter_context(patch.object(temporalio.workflow, "info", return_value=info))
stack.enter_context(patch.object(temporalio.workflow, "now", return_value=dt.datetime(2026, 8, 1)))
stack.enter_context(patch.object(temporalio.workflow, "logger"))
@@ -115,8 +122,40 @@ class TestQualityGateBranching:
assert "publish_queryable_table_activity" not in started
assert "succeed_materialization_activity" not in started
- async def test_account_staging_dispatches_parallel_segments(self):
- materialize_result = dataclasses.replace(_materialize_result("skip"), account_property_sync_enabled=True)
+ async def test_account_staging_starts_an_isolated_child_workflow(self):
+ materialize_result = dataclasses.replace(
+ _materialize_result("skip"),
+ account_property_sync_enabled=True,
+ delta_version=5,
+ )
+ activity_results = [
+ False,
+ "job-1",
+ materialize_result,
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
+ None,
+ None,
+ ]
+ start_child = AsyncMock()
+
+ await self._run(activity_results, {}, start_child=start_child)
+
+ staging_call = next(
+ call for call in start_child.await_args_list if call.args[0] == "stage-warehouse-account-properties"
+ )
+ assert isinstance(staging_call.args[1], StageAccountPropertySyncInput)
+ assert staging_call.args[1].job_id == "job-1"
+ assert staging_call.args[1].delta_version == 5
+ assert staging_call.kwargs["parent_close_policy"] == temporalio.workflow.ParentClosePolicy.ABANDON
+
+ async def test_a_legacy_history_replays_the_inline_dispatch_command(self):
+ # A history recorded under ACCOUNT_PROPERTY_S3_SYNC_PATCH holds the old dispatch activity
+ # command and no delta_version. Replaying it with only that marker present must re-emit the
+ # dispatch command, not the staging child, or the execution fails as nondeterministic.
+ materialize_result = dataclasses.replace(
+ _materialize_result("skip"),
+ account_property_sync_enabled=True,
+ )
activity_results = [
False,
"job-1",
@@ -127,15 +166,48 @@ class TestQualityGateBranching:
]
start_child = AsyncMock()
- _, execute_activity = await self._run(activity_results, {}, start_child=start_child)
+ _, execute_activity = await self._run(
+ activity_results,
+ {},
+ patched=lambda change_id: change_id == ACCOUNT_PROPERTY_S3_SYNC_PATCH,
+ start_child=start_child,
+ )
- dispatch_call = next(
- call
- for call in execute_activity.await_args_list
- if call.args[0] == "dispatch-warehouse-account-property-sync"
+ assert any(
+ call.args[0] == "dispatch-warehouse-account-property-sync" for call in execute_activity.await_args_list
+ )
+ assert not [
+ call for call in start_child.await_args_list if call.args[0] == "stage-warehouse-account-properties"
+ ]
+
+ async def test_the_isolated_staging_child_wins_when_both_markers_are_present(self):
+ materialize_result = dataclasses.replace(
+ _materialize_result("skip"),
+ account_property_sync_enabled=True,
+ delta_version=5,
+ )
+ activity_results = [
+ False,
+ "job-1",
+ materialize_result,
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
+ None,
+ ]
+ start_child = AsyncMock()
+
+ _, execute_activity = await self._run(
+ activity_results,
+ {},
+ patched=lambda change_id: (
+ change_id in (ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH, ACCOUNT_PROPERTY_S3_SYNC_PATCH)
+ ),
+ start_child=start_child,
+ )
+
+ assert any(call.args[0] == "stage-warehouse-account-properties" for call in start_child.await_args_list)
+ assert not any(
+ call.args[0] == "dispatch-warehouse-account-property-sync" for call in execute_activity.await_args_list
)
- assert isinstance(dispatch_call.args[1], DispatchAccountPropertySyncInput)
- assert dispatch_call.args[1].job_id == "job-1"
async def test_a_passing_audit_publishes_and_succeeds(self):
activity_results = [
@@ -332,42 +404,50 @@ class TestFinalizeOrphanedDuckgresJob:
await workflow._finalize_orphaned_duckgres_job("job-123", _inputs(), "activity died")
-class TestAccountPropertyStagingCleanup:
- async def test_clear_failure_stops_the_materialization_attempt(self):
- sink = MagicMock()
- sink.clear = AsyncMock(side_effect=PermissionError("access denied"))
- logger = MagicMock()
- logger.awarning = AsyncMock()
-
- with (
- pytest.raises(PermissionError, match="access denied"),
- patch("posthog.temporal.data_modeling.activities.materialize_view.capture_exception"),
- ):
- await _clear_account_property_staging(sink, logger)
+class TestMaybeStageAccountProperties:
+ async def test_starts_an_abandoned_staging_child(self):
+ workflow = MaterializeViewWorkflow()
+ result = dataclasses.replace(
+ _materialize_result("skip"),
+ account_property_sync_enabled=True,
+ delta_version=5,
+ )
+ start_child = AsyncMock()
+ with patch.object(temporalio.workflow, "start_child_workflow", new=start_child):
+ await workflow._maybe_stage_account_properties(_inputs(), result, "job-123")
+ start_child.assert_awaited_once()
+ assert start_child.await_args is not None
+ workflow_name, payload = start_child.await_args.args
+ assert workflow_name == "stage-warehouse-account-properties"
+ assert isinstance(payload, StageAccountPropertySyncInput)
+ assert payload.job_id == "job-123"
+ assert payload.delta_version == 5
+ assert start_child.await_args.kwargs["parent_close_policy"] == temporalio.workflow.ParentClosePolicy.ABANDON
-class TestMaybeSyncAccountProperties:
- async def test_dispatches_both_segments_through_a_retrying_activity(self):
+ async def test_staging_start_failure_does_not_fail_materialization(self):
workflow = MaterializeViewWorkflow()
- result = dataclasses.replace(_materialize_result("skip"), account_property_sync_enabled=True)
- execute_activity = AsyncMock()
- with patch.object(temporalio.workflow, "execute_activity", new=execute_activity):
- await workflow._maybe_sync_account_properties(_inputs(), result, "job-123")
+ result = dataclasses.replace(
+ _materialize_result("skip"),
+ account_property_sync_enabled=True,
+ delta_version=5,
+ )
+ start_child = AsyncMock(side_effect=PermissionError("access denied"))
+ with (
+ patch.object(temporalio.workflow, "start_child_workflow", new=start_child),
+ patch.object(temporalio.workflow, "logger", new=MagicMock()),
+ patch("posthog.temporal.data_modeling.workflows.materialize_view.capture_exception"),
+ ):
+ await workflow._maybe_stage_account_properties(_inputs(), result, "job-123")
- execute_activity.assert_awaited_once()
- assert execute_activity.await_args is not None
- activity_name, payload = execute_activity.await_args.args
- assert activity_name == "dispatch-warehouse-account-property-sync"
- assert isinstance(payload, DispatchAccountPropertySyncInput)
- assert payload.job_id == "job-123"
- assert execute_activity.await_args.kwargs["retry_policy"].maximum_attempts == 5
+ start_child.assert_awaited_once()
- async def test_no_dispatch_when_no_account_rows_were_staged(self):
+ async def test_no_staging_when_no_account_sources_are_enabled(self):
workflow = MaterializeViewWorkflow()
- execute_activity = AsyncMock()
- with patch.object(temporalio.workflow, "execute_activity", new=execute_activity):
- await workflow._maybe_sync_account_properties(_inputs(), _materialize_result("skip"), "job-123")
- execute_activity.assert_not_awaited()
+ start_child = AsyncMock()
+ with patch.object(temporalio.workflow, "start_child_workflow", new=start_child):
+ await workflow._maybe_stage_account_properties(_inputs(), _materialize_result("skip"), "job-123")
+ start_child.assert_not_awaited()
class TestMaybeEnrichViewSemantics:
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
index 10757a3c5822..39daba095144 100644
--- a/products/customer_analytics/backend/COMPROMISES.md
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -13,12 +13,13 @@ Shortcuts taken to ship the first version. Revisit when they bite.
## Custom property view sync
- **Two bulk paths during rollout.** The legacy Celery task still re-queries the live view, records
- source status, and has no retry. Flagged materializations also stage job-scoped Parquet for
- independent tracked and ignored Temporal workflows. Keep the legacy recorder until the staged path
- can aggregate both segment outcomes without double-counting failures. Source create and re-enable
- still use Celery until the staged path gains full-Delta backfills and manual recovery.
-- **Staged runs have no run-level UI yet.** Temporal retries each segment against the same job files,
- but progress is visible only through logs and metrics. The job-scoped Parquet stays until both
+ source status, and has no retry. A flagged successful materialization starts an isolated Temporal
+ workflow that reads its committed Delta snapshot and writes job-scoped Parquet. Staging failures
+ remain visible in Temporal and logs without failing the materialized view. Keep the legacy recorder
+ until the staged path can aggregate both segment outcomes without double-counting failures. Source
+ create and re-enable still use Celery until the staged path gains manual recovery.
+- **Staged runs have no run-level UI yet.** Temporal shows the staging workflow and both segment
+ workflows, while logs carry the job and view identifiers. The job-scoped Parquet stays until both
segments succeed. A bounded sweep removes abandoned staging prefixes.
- **Tracked and ignored segments are independent.** They use separate snapshots, retries, and
completion markers. Churned accounts are excluded from both. Only staged-file cleanup waits for
diff --git a/products/customer_analytics/backend/facade/temporal_contracts.py b/products/customer_analytics/backend/facade/temporal_contracts.py
index 722b8408b4fc..a8f28bae17cf 100644
--- a/products/customer_analytics/backend/facade/temporal_contracts.py
+++ b/products/customer_analytics/backend/facade/temporal_contracts.py
@@ -1,6 +1,15 @@
from posthog.dataclasses import frozen
+@frozen
+class StageAccountPropertySyncInput:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+ table_uri: str
+ delta_version: int
+
+
@frozen
class DispatchAccountPropertySyncInput:
team_id: int
diff --git a/products/customer_analytics/backend/temporal/account_property_sync.py b/products/customer_analytics/backend/temporal/account_property_sync.py
index 5d61f50b143c..42f861c3becb 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync.py
@@ -14,6 +14,7 @@ from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from products.customer_analytics.backend.facade.temporal_contracts import (
AccountPropertySyncInput,
DispatchAccountPropertySyncInput,
+ StageAccountPropertySyncInput,
)
with workflow.unsafe.imports_passed_through():
@@ -32,9 +33,11 @@ with workflow.unsafe.imports_passed_through():
run_account_property_segment_sync,
)
from products.warehouse_sources.backend.facade.hooks import saved_query_binding
+ from products.warehouse_sources.backend.facade.temporal import AccountPropertyRowSink
logger = structlog.get_logger(__name__)
+ACCOUNT_PROPERTY_STAGING_WORKFLOW_NAME = "stage-warehouse-account-properties"
ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME = "sync-warehouse-account-properties"
ACCOUNT_PROPERTY_SYNC_TOTAL = Counter(
@@ -51,6 +54,34 @@ ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS = Histogram(
)
[email protected](name="stage-warehouse-account-property-files")
+async def stage_warehouse_account_property_files_activity(input: StageAccountPropertySyncInput) -> bool:
+ log = logger.bind(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ delta_version=input.delta_version,
+ )
+ sink = AccountPropertyRowSink(
+ team_id=input.team_id,
+ binding=saved_query_binding(input.saved_query_id),
+ job_id=input.job_id,
+ logger=log,
+ )
+ try:
+ async with Heartbeater():
+ staged = await sink.stage_delta_snapshot(input.table_uri, input.delta_version)
+ except Exception as error:
+ log.exception("Account-property staging failed")
+ capture_exception(error)
+ raise
+ if staged:
+ log.info("Account-property staging completed")
+ else:
+ log.info("Account-property staging skipped because no enabled sources remain")
+ return staged
+
+
@activity.defn(name="dispatch-warehouse-account-property-sync")
async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccountPropertySyncInput) -> None:
client = await async_connect()
@@ -113,6 +144,35 @@ async def sync_warehouse_account_properties_activity(input: AccountPropertySyncI
return result
[email protected](name=ACCOUNT_PROPERTY_STAGING_WORKFLOW_NAME)
+class StageWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> StageAccountPropertySyncInput:
+ return StageAccountPropertySyncInput(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, input: StageAccountPropertySyncInput) -> None:
+ staged = await workflow.execute_activity(
+ stage_warehouse_account_property_files_activity,
+ input,
+ start_to_close_timeout=timedelta(hours=6),
+ heartbeat_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=30)),
+ )
+ if not staged:
+ return
+ await workflow.execute_activity(
+ dispatch_warehouse_account_property_sync_activity,
+ DispatchAccountPropertySyncInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=5),
+ )
+
+
@workflow.defn(name=ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME)
class SyncWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
@staticmethod
@@ -130,8 +190,12 @@ class SyncWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
)
-ACCOUNT_PROPERTY_SYNC_WORKFLOWS = [SyncWarehouseAccountPropertiesWorkflow]
+ACCOUNT_PROPERTY_SYNC_WORKFLOWS = [
+ StageWarehouseAccountPropertiesWorkflow,
+ SyncWarehouseAccountPropertiesWorkflow,
+]
ACCOUNT_PROPERTY_SYNC_ACTIVITIES = [
+ stage_warehouse_account_property_files_activity,
dispatch_warehouse_account_property_sync_activity,
sync_warehouse_account_properties_activity,
]
diff --git a/products/customer_analytics/backend/temporal/account_property_sync_test.py b/products/customer_analytics/backend/temporal/account_property_sync_test.py
index aefc8e52f799..d1d288958f78 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync_test.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync_test.py
@@ -1,20 +1,123 @@
+import uuid
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+
import pytest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
-from temporalio import workflow
+from temporalio import activity, workflow
from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
-from products.customer_analytics.backend.facade.temporal_contracts import DispatchAccountPropertySyncInput
+from products.customer_analytics.backend.facade.temporal_contracts import (
+ DispatchAccountPropertySyncInput,
+ StageAccountPropertySyncInput,
+)
from products.customer_analytics.backend.temporal.account_property_sync import (
AccountPropertySyncInput,
+ StageWarehouseAccountPropertiesWorkflow,
SyncWarehouseAccountPropertiesWorkflow,
dispatch_warehouse_account_property_sync_activity,
+ stage_warehouse_account_property_files_activity,
sync_warehouse_account_properties_activity,
)
pytestmark = pytest.mark.asyncio
+def _staging_input() -> StageAccountPropertySyncInput:
+ return StageAccountPropertySyncInput(
+ team_id=7,
+ saved_query_id="019f0000-0000-7000-8000-000000000001",
+ job_id="job-1",
+ table_uri="s3://data-warehouse/dlt/table",
+ delta_version=5,
+ )
+
+
+@asynccontextmanager
+async def _no_heartbeat() -> AsyncIterator[None]:
+ yield
+
+
+async def test_staging_activity_reads_the_committed_delta_version() -> None:
+ sink = MagicMock()
+ sink.stage_delta_snapshot = AsyncMock(return_value=True)
+
+ with (
+ patch(
+ "products.customer_analytics.backend.temporal.account_property_sync.AccountPropertyRowSink",
+ return_value=sink,
+ ),
+ patch(
+ "products.customer_analytics.backend.temporal.account_property_sync.Heartbeater",
+ return_value=_no_heartbeat(),
+ ),
+ ):
+ staged = await stage_warehouse_account_property_files_activity(_staging_input())
+
+ assert staged is True
+ sink.stage_delta_snapshot.assert_awaited_once_with("s3://data-warehouse/dlt/table", 5)
+
+
+async def test_staging_workflow_dispatches_segments_only_after_staging_succeeds() -> None:
+ execute_activity = AsyncMock(side_effect=[True, None])
+
+ with patch.object(workflow, "execute_activity", new=execute_activity):
+ await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
+
+ assert execute_activity.await_count == 2
+ assert execute_activity.await_args_list[0].args[0] == stage_warehouse_account_property_files_activity
+ assert execute_activity.await_args_list[1].args[0] == dispatch_warehouse_account_property_sync_activity
+
+
+async def test_staging_workflow_stops_when_no_sources_remain() -> None:
+ execute_activity = AsyncMock(return_value=False)
+
+ with patch.object(workflow, "execute_activity", new=execute_activity):
+ await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
+
+ execute_activity.assert_awaited_once()
+
+
+async def test_staging_and_dispatch_recover_from_transient_activity_failures() -> None:
+ attempts: list[tuple[str, int]] = []
+
+ @activity.defn(name="stage-warehouse-account-property-files")
+ async def stage_files(_input: StageAccountPropertySyncInput) -> bool:
+ attempt = activity.info().attempt
+ attempts.append(("stage", attempt))
+ if attempt == 1:
+ raise RuntimeError("staging temporarily unavailable")
+ return True
+
+ @activity.defn(name="dispatch-warehouse-account-property-sync")
+ async def dispatch(_input: DispatchAccountPropertySyncInput) -> None:
+ attempt = activity.info().attempt
+ attempts.append(("dispatch", attempt))
+ if attempt == 1:
+ raise RuntimeError("Temporal temporarily unavailable")
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ async with Worker(
+ environment.client,
+ task_queue=task_queue,
+ workflows=[StageWarehouseAccountPropertiesWorkflow],
+ activities=[stage_files, dispatch],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ await environment.client.execute_workflow(
+ StageWarehouseAccountPropertiesWorkflow.run,
+ _staging_input(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ assert attempts == [("stage", 1), ("stage", 2), ("dispatch", 1), ("dispatch", 2)]
+
+
async def test_dispatch_starts_missing_segment_when_its_sibling_already_runs() -> None:
client = AsyncMock()
client.start_workflow.side_effect = [WorkflowAlreadyStartedError("tracked", "workflow"), None]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_paths.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_paths.py
index 9607a2389248..88f635e42a87 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_paths.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_paths.py
@@ -1,3 +1,5 @@
+from urllib.parse import urlparse
+
from django.conf import settings
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import WarehouseBinding
@@ -6,8 +8,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.per
)
+def _warehouse_delta_prefix() -> str:
+ parsed = urlparse(settings.BUCKET_URL)
+ if parsed.scheme != "s3" or not parsed.netloc:
+ raise ValueError("BUCKET_URL must be an S3 URI")
+ return f"{parsed.netloc}{parsed.path.rstrip('/')}"
+
+
def binding_staged_prefix(team_id: int, binding: WarehouseBinding) -> str:
- return f"{settings.DATAWAREHOUSE_BUCKET}/account_property_sync/{team_id}/{binding_path_segment(binding)}"
+ return f"{_warehouse_delta_prefix()}/account_property_sync/{team_id}/{binding_path_segment(binding)}"
def job_staged_prefix(team_id: int, binding: WarehouseBinding, job_id: str) -> str:
@@ -16,10 +25,10 @@ def job_staged_prefix(team_id: int, binding: WarehouseBinding, job_id: str) -> s
def snapshot_prefix(team_id: int, binding: WarehouseBinding, source_id: str, segment: str) -> str:
return (
- f"{settings.DATAWAREHOUSE_BUCKET}/account_property_snapshot/"
+ f"{_warehouse_delta_prefix()}/account_property_snapshot/"
f"{team_id}/{source_id}/{segment}/{binding_path_segment(binding)}"
)
def completion_prefix(team_id: int, binding: WarehouseBinding, job_id: str) -> str:
- return f"{settings.DATAWAREHOUSE_BUCKET}/account_property_runs/{team_id}/{binding_path_segment(binding)}/{job_id}"
+ return f"{_warehouse_delta_prefix()}/account_property_runs/{team_id}/{binding_path_segment(binding)}/{job_id}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py
index ce1576ebdff2..371e1b8039c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py
@@ -1,4 +1,3 @@
-import time
import asyncio
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -6,8 +5,9 @@ from typing import Any
from django.conf import settings
import pyarrow as pa
+import deltalake
import pyarrow.fs as pa_fs
-from pyarrow.parquet import write_table
+from pyarrow.parquet import ParquetFile, write_table
from structlog.types import FilteringBoundLogger
from posthog.sync import database_sync_to_async_pool
@@ -22,30 +22,18 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.acc
binding_staged_prefix,
job_staged_prefix,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import delta_storage_options
# A sibling job prefix whose newest file is older than this is considered abandoned (its consumer
# never ran, or gave up retrying) and is swept. Anything younger may belong to a consumer that is
# merely lagging behind the sync schedule and must survive — deleting it would silently drop that
# sync's staged delta, which an incremental sync never re-stages until the rows change again.
ABANDONED_STAGED_PREFIX_TTL = timedelta(days=7)
+_PARQUET_BATCH_SIZE = 50_000
class AccountPropertyRowSink:
- """Stages a projection of each written chunk to S3 for the account-property upsert job.
-
- Mirrors ``CDPProducer``: gated on a hook so a table with no account-target source stages
- nothing, and only the columns the sources actually need (key + mapped columns) leave the
- pipeline. A source is staged only when its key (account external identifier) column is present in the
- chunk, so a staged file always carries an identifier to attach its properties to. A post-run
- job reads these files and upserts account properties, then clears them.
-
- Data-modeling materializations build this sink and pass it each written batch. Multiple job
- prefixes can coexist under a binding while the consumer lags, so the consumer must apply
- prefixes in job order (or last-write-wins per account key) — a lagged older job
- applied after a newer one would regress properties to stale values. Within one job, staged
- files from a retried attempt sort after the failed attempt's (attempt-timestamped names), so
- per-account last-write-wins inside the job holds too.
- """
+ """Projects a committed materialized-view Delta snapshot into job-scoped Parquet files."""
def __init__(
self,
@@ -53,19 +41,11 @@ class AccountPropertyRowSink:
binding: WarehouseBinding,
job_id: str,
logger: FilteringBoundLogger,
- *,
- is_incremental: bool,
) -> None:
self.team_id = team_id
self.binding = binding
self.job_id = job_id
self.logger = logger
- self._is_incremental = is_incremental
- # Per-attempt token baked into staged filenames. An incremental retry resumes past the
- # already-committed cursor, so its chunk indices restart at 0 while the earlier attempt's
- # rows are never re-extracted — reusing plain `chunk_{n}` names would overwrite (and lose)
- # them. Seconds-since-epoch keeps names lexicographically ordered across attempts.
- self._attempt_token = str(int(time.time()))
self._projection: list[AccountPropertySourceProjection] | None = None
self._projection_resolved = False
self._fs_cache: pa_fs.S3FileSystem | None = None
@@ -91,7 +71,7 @@ class AccountPropertyRowSink:
endpoint_override=settings.OBJECT_STORAGE_ENDPOINT,
)
else:
- self._fs_cache = pa_fs.S3FileSystem()
+ self._fs_cache = pa_fs.S3FileSystem(region=settings.DATA_WAREHOUSE_S3_REGION)
return self._fs_cache
@@ -136,41 +116,47 @@ class AccountPropertyRowSink:
await asyncio.to_thread(
write_table,
projected,
- f"{self._get_path_prefix()}/chunk_{self._attempt_token}_{chunk:06d}.parquet",
+ f"{self._get_path_prefix()}/chunk_{chunk:06d}.parquet",
filesystem=self._get_fs(),
compression="zstd",
use_dictionary=True,
)
+ async def stage_delta_snapshot(self, table_uri: str, delta_version: int) -> bool:
+ projection = await self._get_projection()
+ if not projection:
+ return False
+
+ await self.clear()
+ delta_table = await asyncio.to_thread(
+ deltalake.DeltaTable,
+ table_uri,
+ version=delta_version,
+ storage_options=delta_storage_options(),
+ )
+ chunk = 0
+ for file_uri in sorted(delta_table.file_uris()):
+ input_file = await asyncio.to_thread(self._get_fs().open_input_file, file_uri.removeprefix("s3://"))
+ try:
+ parquet_file = await asyncio.to_thread(ParquetFile, input_file)
+ batches = await asyncio.to_thread(parquet_file.iter_batches, batch_size=_PARQUET_BATCH_SIZE)
+ while (batch := await asyncio.to_thread(next, batches, None)) is not None:
+ await self.stage_chunk(chunk, pa.Table.from_batches([batch]))
+ chunk += 1
+ finally:
+ await asyncio.to_thread(input_file.close)
+ return True
+
async def clear(self) -> None:
- """Drop this job's own staged files (full refresh only), plus sibling job prefixes
- abandoned long enough.
-
- Own-prefix clearing stops a retried job from leaving stale files behind, but it is only
- safe when the retry re-extracts everything — i.e. a full refresh. An incremental retry
- resumes past the cursor the failed attempt already committed, so its earlier staged files
- are that data's only record and must survive; duplicates a full re-window would produce
- are deduped downstream anyway (snapshot diff + last-write-wins).
-
- Sibling prefixes are NOT cleared wholesale: the downstream upsert job deletes them as it
- consumes them, and a recent sibling may simply belong to a consumer that is lagging —
- wiping it would lose that sync's delta. Only prefixes older than
- ``ABANDONED_STAGED_PREFIX_TTL`` are swept, as the backstop against a consumer that never
- ran.
-
- The two clears are independent backstops, so a failure in one (e.g. a permissions error
- deleting the own prefix) must not skip the other — the sweep always runs, and any
- own-prefix error is re-raised only afterward.
- """
+ """Drop this job's prior attempt and sweep abandoned sibling jobs."""
async with aget_s3_client() as s3_client:
own_prefix_error: Exception | None = None
- if not self._is_incremental:
- try:
- await s3_client._rm(f"s3://{self._get_path_prefix()}/", recursive=True)
- except FileNotFoundError:
- pass
- except Exception as e:
- own_prefix_error = e
+ try:
+ await s3_client._rm(f"s3://{self._get_path_prefix()}/", recursive=True)
+ except FileNotFoundError:
+ pass
+ except Exception as e:
+ own_prefix_error = e
await self._sweep_abandoned_sibling_prefixes(s3_client)
if own_prefix_error is not None:
raise own_prefix_error
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py
index 35ffa9e89eef..83224a137967 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py
@@ -3,12 +3,20 @@ from datetime import UTC, datetime, timedelta
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.conf import settings
+
import pyarrow as pa
+import pyarrow.parquet as pq
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
AccountPropertySourceProjection,
saved_query_binding,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_paths import (
+ completion_prefix,
+ job_staged_prefix,
+ snapshot_prefix,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_row_sink import (
ABANDONED_STAGED_PREFIX_TTL,
AccountPropertyRowSink,
@@ -17,7 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.acc
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_row_sink"
-def _sink(*, incremental: bool = False) -> AccountPropertyRowSink:
+def _sink() -> AccountPropertyRowSink:
logger = MagicMock()
logger.adebug = AsyncMock()
return AccountPropertyRowSink(
@@ -25,10 +33,22 @@ def _sink(*, incremental: bool = False) -> AccountPropertyRowSink:
binding=saved_query_binding("019f0000-0000-7000-8000-000000000001"),
job_id="job-1",
logger=logger,
- is_incremental=incremental,
)
+def test_all_account_property_artifacts_use_the_data_modeling_prefix() -> None:
+ binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
+
+ paths = [
+ job_staged_prefix(7, binding, "job-1"),
+ snapshot_prefix(7, binding, "source-1", "tracked"),
+ completion_prefix(7, binding, "job-1"),
+ ]
+
+ expected_root = settings.BUCKET_URL.removeprefix("s3://").rstrip("/")
+ assert all(path.startswith(f"{expected_root}/") for path in paths)
+
+
class _S3ClientContext:
def __init__(self, client: MagicMock) -> None:
self.client = client
@@ -71,12 +91,57 @@ async def test_stages_only_columns_from_sources_with_a_present_key() -> None:
assert to_thread.await_args is not None
assert to_thread.await_args.args[1].column_names == ["mrr", "organization_id"]
- assert "/account_property_sync/7/model_" in to_thread.await_args.args[2]
+ expected_root = settings.BUCKET_URL.removeprefix("s3://").rstrip("/")
+ assert to_thread.await_args.args[2].startswith(f"{expected_root}/account_property_sync/7/model_")
@pytest.mark.asyncio
-async def test_incremental_retry_keeps_its_staged_files_and_sweeps_abandoned_jobs() -> None:
- sink = _sink(incremental=True)
+async def test_stages_an_exact_delta_snapshot_after_materialization() -> None:
+ sink = _sink()
+ table = pa.table({"organization_id": ["org-1"], "mrr": [100]})
+ output = pa.BufferOutputStream()
+ pq.write_table(table, output)
+ delta_table = MagicMock()
+ delta_table.file_uris.return_value = ["s3://data-warehouse/dlt/file.parquet"]
+ filesystem = MagicMock()
+ filesystem.open_input_file.return_value = pa.BufferReader(output.getvalue())
+
+ with (
+ patch.object(
+ sink,
+ "_get_projection",
+ new=AsyncMock(
+ return_value=[
+ AccountPropertySourceProjection(
+ key_column="organization_id",
+ columns=frozenset({"organization_id", "mrr"}),
+ )
+ ]
+ ),
+ ),
+ patch.object(sink, "clear", new=AsyncMock()) as clear,
+ patch.object(sink, "stage_chunk", new=AsyncMock()) as stage_chunk,
+ patch.object(sink, "_get_fs", return_value=filesystem),
+ patch(f"{_MODULE}.deltalake.DeltaTable", return_value=delta_table) as open_delta,
+ patch(f"{_MODULE}.delta_storage_options", return_value={"region_name": "us-east-1"}),
+ ):
+ staged = await sink.stage_delta_snapshot("s3://data-warehouse/dlt/table", 7)
+
+ assert staged is True
+ clear.assert_awaited_once()
+ open_delta.assert_called_once_with(
+ "s3://data-warehouse/dlt/table",
+ version=7,
+ storage_options={"region_name": "us-east-1"},
+ )
+ stage_chunk.assert_awaited_once()
+ assert stage_chunk.await_args is not None
+ assert stage_chunk.await_args.args[1].to_pydict() == table.to_pydict()
+
+
+async def test_retry_clears_its_staged_files_and_sweeps_abandoned_jobs() -> None:
+ sink = _sink()
stale_file = f"{sink._get_binding_prefix()}/job-old/chunk.parquet"
client = MagicMock()
client._find = AsyncMock(
@@ -88,5 +153,5 @@ async def test_incremental_retry_keeps_its_staged_files_and_sweeps_abandoned_job
await sink.clear()
removed = [call.args[0] for call in client._rm.await_args_list]
- assert f"s3://{sink._get_path_prefix()}/" not in removed
+ assert f"s3://{sink._get_path_prefix()}/" in removed
assert [f"s3://{stale_file}"] in removed