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.

feat(data-warehouse): stage person-property rows during sync (#69983)

Tom Owers6a2428692f72
diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.py
index ee4e47cccbe6..f559f4730ae8 100644
--- a/products/customer_analytics/backend/apps.py
+++ b/products/customer_analytics/backend/apps.py
@@ -5,3 +5,25 @@ class CustomerAnalyticsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.customer_analytics.backend"
label = "customer_analytics"
+
+ def ready(self) -> None:
+ self._register_person_property_projection()
+
+ def _register_person_property_projection(self) -> None:
+ """Tell the data-import pipeline which columns to stage for a schema's person-property
+ sources, without warehouse_sources importing this product. The impl is imported lazily so
+ the models stay off the django.setup() path.
+ """
+ from products.warehouse_sources.backend.facade.hooks import (
+ PersonPropertySourceProjection,
+ register_person_property_projection,
+ )
+
+ def _resolver(team_id: int, schema_id) -> list[PersonPropertySourceProjection] | None:
+ from products.customer_analytics.backend.logic.person_property_projection import ( # noqa: PLC0415
+ person_property_projection,
+ )
+
+ return person_property_projection(team_id, schema_id)
+
+ register_person_property_projection(_resolver)
diff --git a/products/customer_analytics/backend/logic/person_property_projection.py b/products/customer_analytics/backend/logic/person_property_projection.py
new file mode 100644
index 000000000000..54b9098bfca3
--- /dev/null
+++ b/products/customer_analytics/backend/logic/person_property_projection.py
@@ -0,0 +1,31 @@
+"""Resolves which warehouse columns to stage for a schema's person-property sources.
+
+Registered as the data-import pipeline's projection hook (see apps.ready). Called from the
+pipeline, outside request context, so it scopes explicitly with ``for_team``.
+"""
+
+from uuid import UUID
+
+from products.customer_analytics.backend.models import CustomPropertySource, TargetType
+from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection
+
+
+def person_property_projection(team_id: int, schema_id: str | UUID) -> list[PersonPropertySourceProjection] | None:
+ """One projection per enabled person-target source on the schema (its key column plus its
+ mapped columns), or None when the schema feeds no person properties (so the pipeline stages
+ nothing). Sources without a key column are skipped: their rows have no person identifier to
+ attach the properties to."""
+ sources = CustomPropertySource.objects.for_team(team_id).filter(
+ external_data_schema_id=schema_id,
+ is_enabled=True,
+ definition__target_type=TargetType.PERSON.value,
+ )
+ projections = [
+ PersonPropertySourceProjection(
+ key_column=source.key_column,
+ columns=frozenset({source.key_column, *(source.column_property_map or {}).keys()}),
+ )
+ for source in sources
+ if source.key_column
+ ]
+ return projections or None
diff --git a/products/customer_analytics/backend/logic/person_property_projection_test.py b/products/customer_analytics/backend/logic/person_property_projection_test.py
new file mode 100644
index 000000000000..88a19861d9c3
--- /dev/null
+++ b/products/customer_analytics/backend/logic/person_property_projection_test.py
@@ -0,0 +1,70 @@
+from posthog.test.base import BaseTest
+
+from products.customer_analytics.backend.logic.person_property_projection import person_property_projection
+from products.customer_analytics.backend.models import CustomPropertySource, TargetType
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+from products.customer_analytics.backend.test.factories import create_custom_property_definition
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+
+class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe"
+ )
+ self.schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+
+ def _person_source(self, name, key_column, column_property_map, *, is_enabled=True, schema=None):
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name=name, target_type=TargetType.PERSON.value
+ )
+ return CustomPropertySource.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ definition=definition,
+ external_data_schema=schema or self.schema,
+ key_column=key_column,
+ column_property_map=column_property_map,
+ is_enabled=is_enabled,
+ )
+
+ def _projected(self):
+ projection = person_property_projection(self.team.id, self.schema.id)
+ return {source.key_column: sorted(source.columns) for source in (projection or [])}
+
+ def test_returns_none_when_no_person_sources(self):
+ assert person_property_projection(self.team.id, self.schema.id) is None
+
+ def test_projects_key_and_mapped_columns_per_enabled_person_source(self):
+ self._person_source("A", "distinct_id", {"plan": "plan_tier"})
+ self._person_source("B", "user_id", {"seats": "seat_count", "region": "region"})
+
+ assert self._projected() == {
+ "distinct_id": ["distinct_id", "plan"],
+ "user_id": ["region", "seats", "user_id"],
+ }
+
+ def test_skips_source_without_key_column(self):
+ # A source with no key column has no person identifier to attach properties to.
+ self._person_source("keyless", "", {"plan": "plan_tier"})
+
+ assert person_property_projection(self.team.id, self.schema.id) is None
+
+ def test_ignores_disabled_account_and_other_schema_sources(self):
+ self._person_source("enabled", "distinct_id", {"plan": "plan_tier"})
+ self._person_source("disabled", "other_id", {"col": "prop"}, is_enabled=False)
+
+ # Account-target source on the same schema must not contribute.
+ account_def = create_custom_property_definition(
+ team_id=self.team.id, name="MRR", target_type=TargetType.ACCOUNT.value
+ )
+ CustomPropertySource.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ definition=account_def,
+ external_data_schema=self.schema,
+ key_column="acct_id",
+ column_property_map={"mrr": "mrr"},
+ )
+
+ assert self._projected() == {"distinct_id": ["distinct_id", "plan"]}
diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.py
index 5d80f0183bcc..4b5019548209 100644
--- a/products/warehouse_sources/backend/facade/hooks.py
+++ b/products/warehouse_sources/backend/facade/hooks.py
@@ -10,14 +10,20 @@ on the startup path does not drag the whole pipeline onto every process boot.
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
EmitSignalsActivityInputs,
+ PersonPropertySourceProjection,
+ person_property_projection_for,
register_emit_signals_gate,
register_engineering_analytics_view_sync,
+ register_person_property_projection,
register_revenue_view_sync,
)
__all__ = [
"EmitSignalsActivityInputs",
+ "PersonPropertySourceProjection",
+ "person_property_projection_for",
"register_emit_signals_gate",
"register_engineering_analytics_view_sync",
+ "register_person_property_projection",
"register_revenue_view_sync",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
index 84813ca5a8e5..8b5d5964a7bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
@@ -98,3 +98,40 @@ def run_engineering_analytics_view_sync(schema: "ExternalDataSchema", source: "E
if _engineering_analytics_view_sync is None:
return
_engineering_analytics_view_sync(schema, source)
+
+
+# --- Person-property staging projection -----------------------------------------------
+# Person-target Customer analytics sources stage a projection of each synced chunk to S3 so a
+# post-sync job can upsert warehouse columns onto person properties. The pipeline asks this hook
+# which columns to stage for a schema; each enabled person source contributes its key (the person
+# identifier) plus its mapped property columns. Key columns are tracked separately from mapped
+# columns so the sink never stages property values with no person identifier to attach them to.
+# The hook returns None when nothing needs staging. customer_analytics registers the resolver at
+# app-ready; when nothing is registered this returns None and the pipeline stages nothing, so
+# warehouse_sources stays importable on its own.
+
+
[email protected](frozen=True)
+class PersonPropertySourceProjection:
+ """One person-target source's staging projection: its key column (the person identifier) and
+ the warehouse columns to stage for it (the key plus its mapped property columns)."""
+
+ key_column: str
+ columns: frozenset[str]
+
+
+PersonPropertyProjectionResolver = Callable[[int, "str | uuid.UUID"], Optional[list[PersonPropertySourceProjection]]]
+_person_property_projection_resolver: Optional[PersonPropertyProjectionResolver] = None
+
+
+def register_person_property_projection(fn: PersonPropertyProjectionResolver) -> None:
+ global _person_property_projection_resolver
+ _person_property_projection_resolver = fn
+
+
+def person_property_projection_for(
+ team_id: int, schema_id: "str | uuid.UUID"
+) -> Optional[list[PersonPropertySourceProjection]]:
+ if _person_property_projection_resolver is None:
+ return None
+ return _person_property_projection_resolver(team_id, schema_id)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 3f534ceb5819..7bd3f3ceb6a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -18,6 +18,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
DeltaTableHelper,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_row_sink import (
+ PersonPropertyRowSink,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (
BillingLimitsWillBeReachedException,
@@ -642,6 +645,16 @@ async def write_chunk_for_cdp_producer(cdp_producer: CDPProducer, index: int, pa
await cdp_producer.write_chunk_for_cdp_producer(chunk=index, table=pa_table)
+async def person_property_sink_clear_chunks(sink: PersonPropertyRowSink):
+ if await sink.should_stage():
+ await sink.clear_chunks()
+
+
+async def stage_chunk_for_person_property_sink(sink: PersonPropertyRowSink, index: int, pa_table: pa.Table):
+ if await sink.should_stage():
+ await sink.stage_chunk(chunk=index, table=pa_table)
+
+
async def run_pre_write_defensive_compact(
delta_table_helper: DeltaTableHelper,
schema: "ExternalDataSchema",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink.py
new file mode 100644
index 000000000000..c78716d6588b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink.py
@@ -0,0 +1,184 @@
+import time
+import asyncio
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from django.conf import settings
+
+import pyarrow as pa
+import pyarrow.fs as pa_fs
+from pyarrow.parquet import write_table
+from structlog.types import FilteringBoundLogger
+
+from posthog.sync import database_sync_to_async_pool
+
+from products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_exists
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertySourceProjection,
+ person_property_projection_for,
+)
+
+# 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)
+
+
+class PersonPropertyRowSink:
+ """Stages a projection of each synced chunk to S3 for the person-property upsert job.
+
+ Mirrors ``CDPProducer``: gated on a hook so a table with no person-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 (person identifier) column is present in the
+ synced chunk, so a staged file always carries an identifier to attach its properties to. A
+ post-sync job (later PR) reads these files and upserts person properties, then clears them.
+
+ Multiple job prefixes can coexist under a schema while the consumer lags, so the consumer
+ must apply prefixes in job order (or last-write-wins per person 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-person last-write-wins inside the job holds too.
+ """
+
+ def __init__(
+ self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger, *, is_incremental: bool
+ ) -> None:
+ self.team_id = team_id
+ self.schema_id = schema_id
+ 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[PersonPropertySourceProjection] | None = None
+ self._projection_resolved = False
+
+ def _get_fs(self) -> pa_fs.S3FileSystem:
+ if settings.USE_LOCAL_SETUP:
+ ensure_bucket_exists(
+ f"s3://{self._get_path_prefix()}",
+ settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
+ settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
+ settings.OBJECT_STORAGE_ENDPOINT,
+ )
+ return pa_fs.S3FileSystem(
+ access_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
+ secret_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
+ endpoint_override=settings.OBJECT_STORAGE_ENDPOINT,
+ )
+
+ return pa_fs.S3FileSystem()
+
+ def _get_schema_prefix(self) -> str:
+ return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{self.team_id}/{self.schema_id}"
+
+ def _get_path_prefix(self) -> str:
+ return f"{self._get_schema_prefix()}/{self.job_id}"
+
+ async def _get_projection(self) -> list[PersonPropertySourceProjection] | None:
+ """One projection per enabled person source on the schema (key + mapped columns), or None
+ when nothing needs staging. Resolved once per run."""
+ if not self._projection_resolved:
+ self._projection = await database_sync_to_async_pool(person_property_projection_for)(
+ self.team_id, self.schema_id
+ )
+ self._projection_resolved = True
+ return self._projection
+
+ async def should_stage(self) -> bool:
+ return bool(await self._get_projection())
+
+ async def stage_chunk(self, chunk: int, table: pa.Table) -> None:
+ projection = await self._get_projection()
+ if not projection:
+ return
+ table_columns = set(table.column_names)
+ # Stage a source only when its key (person identifier) column is present, so a staged file
+ # never carries property values with no identifier to attach them to. A missing key column
+ # skips that source rather than failing the sync (e.g. after upstream schema drift).
+ columns: set[str] = set()
+ for source in projection:
+ if source.key_column not in table_columns:
+ continue
+ columns.update(column for column in source.columns if column in table_columns)
+ if not columns:
+ return
+ projected = table.select(sorted(columns))
+ await self.logger.adebug(
+ f"Staging person-property chunk {chunk} ({len(columns)} cols) to {self._get_path_prefix()}"
+ )
+ await asyncio.to_thread(
+ write_table,
+ projected,
+ f"{self._get_path_prefix()}/chunk_{self._attempt_token}_{chunk:06d}.parquet",
+ filesystem=self._get_fs(),
+ compression="zstd",
+ use_dictionary=True,
+ )
+
+ async def clear_chunks(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.
+ """
+ async with aget_s3_client() as s3_client:
+ if not self._is_incremental:
+ try:
+ await s3_client._rm(f"s3://{self._get_path_prefix()}/", recursive=True)
+ except FileNotFoundError:
+ pass
+ await self._sweep_abandoned_sibling_prefixes(s3_client)
+
+ async def _sweep_abandoned_sibling_prefixes(self, s3_client: Any) -> None:
+ try:
+ entries = await s3_client._find(f"s3://{self._get_schema_prefix()}/", detail=True)
+ except FileNotFoundError:
+ return
+ if not isinstance(entries, dict) or not entries:
+ return
+
+ schema_prefix = self._get_schema_prefix().lstrip("/")
+ files_by_job: dict[str, list[str]] = {}
+ newest_by_job: dict[str, datetime] = {}
+ for path, info in entries.items():
+ key = path.lstrip("/")
+ relative = key[len(schema_prefix) :].lstrip("/")
+ job_segment = relative.split("/", 1)[0]
+ if not job_segment or job_segment == str(self.job_id):
+ continue
+ files_by_job.setdefault(job_segment, []).append(key)
+ last_modified = info.get("LastModified") if isinstance(info, dict) else None
+ if last_modified is not None:
+ current = newest_by_job.get(job_segment)
+ if current is None or last_modified > current:
+ newest_by_job[job_segment] = last_modified
+
+ cutoff = datetime.now(UTC) - ABANDONED_STAGED_PREFIX_TTL
+ stale_files = [
+ key
+ for job_segment, keys in files_by_job.items()
+ # A prefix with no LastModified at all holds only directory markers — safe to sweep.
+ if (newest := newest_by_job.get(job_segment)) is None or newest < cutoff
+ for key in keys
+ ]
+ if not stale_files:
+ return
+ await self.logger.adebug(
+ f"Sweeping {len(stale_files)} abandoned person-property staged files under {schema_prefix}"
+ )
+ await s3_client._rm([f"s3://{key}" for key in stale_files])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink_test.py
new file mode 100644
index 000000000000..33af6c538520
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_row_sink_test.py
@@ -0,0 +1,189 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pyarrow as pa
+
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertySourceProjection,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_row_sink import (
+ ABANDONED_STAGED_PREFIX_TTL,
+ PersonPropertyRowSink,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_row_sink"
+
+
+def _sink(is_incremental: bool = False) -> PersonPropertyRowSink:
+ logger = MagicMock()
+ logger.adebug = AsyncMock()
+ return PersonPropertyRowSink(
+ team_id=1, schema_id="schema-1", job_id="job-1", logger=logger, is_incremental=is_incremental
+ )
+
+
+def _table() -> pa.Table:
+ return pa.table({"distinct_id": ["a"], "plan": ["pro"], "seats": [3], "unused": ["x"]})
+
+
+def _projection(key_column: str, *columns: str) -> PersonPropertySourceProjection:
+ return PersonPropertySourceProjection(key_column=key_column, columns=frozenset({key_column, *columns}))
+
+
+async def test_should_stage_reflects_projection():
+ sink = _sink()
+ with patch(f"{_MODULE}.person_property_projection_for", return_value=None):
+ assert await sink.should_stage() is False
+
+ other = _sink()
+ with patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan")]):
+ assert await other.should_stage() is True
+
+
+async def test_stage_chunk_writes_only_projected_columns_present_in_table():
+ sink = _sink()
+ with (
+ patch(
+ f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan", "missing")]
+ ),
+ patch.object(sink, "_get_fs", return_value=MagicMock()),
+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,
+ ):
+ await sink.stage_chunk(chunk=0, table=_table())
+
+ to_thread.assert_awaited_once()
+ assert to_thread.await_args is not None
+ written_table = to_thread.await_args.args[1]
+ # Only projected columns that exist in the table are staged; "missing" and "unused" are dropped.
+ assert written_table.column_names == ["distinct_id", "plan"]
+
+
+async def test_stage_chunk_skips_source_whose_key_column_is_absent():
+ # The key column (person identifier) is missing from the table, so the source's property
+ # columns must not be staged with no identifier to attach them to.
+ sink = _sink()
+ with (
+ patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("user_id", "plan")]),
+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,
+ ):
+ await sink.stage_chunk(chunk=0, table=_table())
+
+ to_thread.assert_not_awaited()
+
+
+async def test_stage_chunk_stages_only_sources_with_key_present():
+ # Two sources: one keyed on a present column, one on an absent column. Only the present
+ # source's columns are staged; the absent source's mapped column ("seats") is dropped.
+ sink = _sink()
+ with (
+ patch(
+ f"{_MODULE}.person_property_projection_for",
+ return_value=[_projection("distinct_id", "plan"), _projection("user_id", "seats")],
+ ),
+ patch.object(sink, "_get_fs", return_value=MagicMock()),
+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,
+ ):
+ await sink.stage_chunk(chunk=0, table=_table())
+
+ to_thread.assert_awaited_once()
+ assert to_thread.await_args is not None
+ written_table = to_thread.await_args.args[1]
+ assert written_table.column_names == ["distinct_id", "plan"]
+
+
+class _FakeS3ClientCM:
+ def __init__(self, s3_client):
+ self._s3_client = s3_client
+
+ async def __aenter__(self):
+ return self._s3_client
+
+ async def __aexit__(self, *exc):
+ return False
+
+
+def _s3_client(find_result=None) -> MagicMock:
+ s3_client = MagicMock()
+ s3_client._rm = AsyncMock()
+ s3_client._find = AsyncMock(return_value=find_result if find_result is not None else {})
+ return s3_client
+
+
+async def test_clear_chunks_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_ones():
+ # A fresh sibling prefix belongs to a consumer that is merely lagging — deleting it loses an
+ # incremental sync's staged delta for good. Only long-abandoned prefixes may be swept.
+ sink = _sink()
+ schema_prefix = sink._get_schema_prefix()
+ fresh_file = f"{schema_prefix}/job-recent/chunk_0.parquet"
+ stale_file = f"{schema_prefix}/job-old/chunk_0.parquet"
+ now = datetime.now(UTC)
+ s3_client = _s3_client(
+ find_result={
+ fresh_file: {"LastModified": now - timedelta(hours=1)},
+ stale_file: {"LastModified": now - ABANDONED_STAGED_PREFIX_TTL - timedelta(days=1)},
+ }
+ )
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
+ await sink.clear_chunks()
+
+ removed = [call.args[0] for call in s3_client._rm.await_args_list]
+ assert f"s3://{sink._get_path_prefix()}/" in removed # own job prefix cleared on full refresh
+ assert [f"s3://{stale_file}"] in removed # abandoned sibling swept
+ assert all(fresh_file not in str(args) for args in removed) # lagging sibling survives
+
+
+async def test_clear_chunks_keeps_own_prefix_on_incremental_syncs():
+ # An incremental retry resumes past the committed cursor, so the failed attempt's staged
+ # files are the only record of those rows — clearing the job prefix would lose them for good.
+ sink = _sink(is_incremental=True)
+ stale_file = f"{sink._get_schema_prefix()}/job-old/chunk_0.parquet"
+ s3_client = _s3_client(
+ find_result={stale_file: {"LastModified": datetime.now(UTC) - ABANDONED_STAGED_PREFIX_TTL - timedelta(days=1)}}
+ )
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
+ await sink.clear_chunks()
+
+ removed = [call.args[0] for call in s3_client._rm.await_args_list]
+ assert f"s3://{sink._get_path_prefix()}/" not in removed # own prefix survives the retry
+ assert [f"s3://{stale_file}"] in removed # the abandoned-sibling backstop still runs
+
+
+async def test_stage_chunk_filenames_are_unique_per_attempt():
+ # A retried incremental attempt restarts chunk indices at 0 while its predecessor's rows are
+ # never re-extracted; identical filenames would overwrite (and lose) the earlier staging.
+ paths = []
+ for attempt in (_sink(is_incremental=True), _sink(is_incremental=True)):
+ attempt._attempt_token = str(id(attempt)) # distinct per attempt, as wall-clock time is
+ with (
+ patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan")]),
+ patch.object(attempt, "_get_fs", return_value=MagicMock()),
+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,
+ ):
+ await attempt.stage_chunk(chunk=0, table=_table())
+ assert to_thread.await_args is not None
+ paths.append(to_thread.await_args.args[2])
+
+ assert len(set(paths)) == 2
+
+
+async def test_clear_chunks_tolerates_missing_prefixes():
+ # First sync of a schema has nothing staged anywhere; clearing must not fail the sync.
+ sink = _sink()
+ s3_client = _s3_client()
+ s3_client._rm = AsyncMock(side_effect=FileNotFoundError)
+ s3_client._find = AsyncMock(side_effect=FileNotFoundError)
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
+ await sink.clear_chunks()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
index 1a5c210f8d59..ef34473add7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -31,11 +31,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
+ person_property_sink_clear_chunks,
reset_rows_synced_if_needed,
resolve_primary_keys,
run_pre_write_defensive_compact,
setup_row_tracking_with_billing_check,
should_check_shutdown,
+ stage_chunk_for_person_property_sink,
update_incremental_field_values,
update_row_tracking_after_batch,
validate_incremental_sync,
@@ -55,6 +57,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DeltaTableHelper,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.hogql_schema import HogQLSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_row_sink import (
+ PersonPropertyRowSink,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
PipelineResult,
ResumableData,
@@ -202,6 +207,13 @@ class PipelineNonDLT(Generic[ResumableData]):
self._cdp_producer = CDPProducer(
team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._logger
)
+ self._person_property_sink = PersonPropertyRowSink(
+ team_id=self._job.team_id,
+ schema_id=self._schema.id,
+ job_id=job_id,
+ logger=self._logger,
+ is_incremental=self._is_incremental,
+ )
self._shutdown_monitor = shutdown_monitor
self._last_incremental_field_value: Any = None
self._earliest_incremental_field_value: Any = process_incremental_value(
@@ -223,6 +235,7 @@ class PipelineNonDLT(Generic[ResumableData]):
try:
await cdp_producer_clear_chunks(self._cdp_producer)
+ await person_property_sink_clear_chunks(self._person_property_sink)
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
@@ -402,6 +415,7 @@ class PipelineNonDLT(Generic[ResumableData]):
self._internal_schema.add_pyarrow_table(pa_table)
await write_chunk_for_cdp_producer(self._cdp_producer, index, pa_table)
+ await stage_chunk_for_person_property_sink(self._person_property_sink, index, pa_table)
(
self._last_incremental_field_value,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 180147edcaae..8ca0b6ecd559 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -33,11 +33,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
+ person_property_sink_clear_chunks,
reset_rows_synced_if_needed,
resolve_primary_keys,
run_pre_write_defensive_compact,
setup_row_tracking_with_billing_check,
should_check_shutdown,
+ stage_chunk_for_person_property_sink,
update_incremental_field_values,
update_row_tracking_after_batch,
validate_incremental_sync,
@@ -49,6 +51,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DeltaTableHelper,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.hogql_schema import HogQLSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_row_sink import (
+ PersonPropertyRowSink,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.pipeline import async_iterate
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
PipelineResult,
@@ -219,6 +224,13 @@ class PipelineV3(Generic[ResumableData]):
self._cdp_producer = CDPProducer(
team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._logger
)
+ self._person_property_sink = PersonPropertyRowSink(
+ team_id=self._job.team_id,
+ schema_id=self._schema.id,
+ job_id=job_id,
+ logger=self._logger,
+ is_incremental=self._is_incremental,
+ )
self._accumulated_pa_schema = None
self._shutdown_monitor = shutdown_monitor
self._last_incremental_field_value: Any = None
@@ -256,6 +268,7 @@ class PipelineV3(Generic[ResumableData]):
try:
await cdp_producer_clear_chunks(self._cdp_producer)
+ await person_property_sink_clear_chunks(self._person_property_sink)
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
@@ -425,6 +438,7 @@ class PipelineV3(Generic[ResumableData]):
self._internal_schema.add_pyarrow_table(pa_table)
await write_chunk_for_cdp_producer(self._cdp_producer, batch_index, pa_table)
+ await stage_chunk_for_person_property_sink(self._person_property_sink, batch_index, pa_table)
# Update accumulated schema with any new columns from this batch
if self._accumulated_pa_schema is None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index a652fc9fb5d1..4c2084167288 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -41,6 +41,7 @@ def _make_pipeline() -> PipelineV3:
pipeline._resumable_source_manager = None
pipeline._internal_schema = MagicMock()
pipeline._cdp_producer = MagicMock()
+ pipeline._person_property_sink = MagicMock(should_stage=AsyncMock(return_value=False))
pipeline._batcher = MagicMock()
pipeline._load_id = 1
pipeline._s3_batch_writer = MagicMock()