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(customer-analytics): stage account properties in S3 (#86812)

Arthur Moreira de Deusde568cbd5dc5
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 3096e058fa62..81d3c60c0001 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -1073,7 +1073,7 @@ jobs:
- name: Check for changes that affect data warehouse temporal worker
id: check_changes_data_warehouse_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/hogql|^posthog/temporal/data_modeling|^posthog/temporal/common|^products/warehouse_sources/backend/temporal/data_imports|^posthog/warehouse/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/hogql|^posthog/temporal/data_modeling|^posthog/temporal/common|^products/customer_analytics/backend/|^products/warehouse_sources/backend/temporal/data_imports|^posthog/warehouse/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 648e4f190401..c07b5de1a574 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -168,6 +168,8 @@ from products.conversations.backend.temporal import (
WORKFLOWS as CONVERSATIONS_WORKFLOWS,
)
from products.customer_analytics.backend.facade.temporal import (
+ ACCOUNT_PROPERTY_SYNC_ACTIVITIES,
+ ACCOUNT_PROPERTY_SYNC_WORKFLOWS,
ACTIVITIES as CUSTOMER_ANALYTICS_ACTIVITIES,
WORKFLOWS as CUSTOMER_ANALYTICS_WORKFLOWS,
)
@@ -292,11 +294,13 @@ _task_queue_specs = [
DATA_WAREHOUSE_METADATA_WORKFLOWS
+ SEMANTIC_ENRICHMENT_WORKFLOWS
+ PERSON_PROPERTY_SYNC_WORKFLOWS
- + PERSON_PROPERTY_BACKFILL_WORKFLOWS,
+ + PERSON_PROPERTY_BACKFILL_WORKFLOWS
+ + ACCOUNT_PROPERTY_SYNC_WORKFLOWS,
DATA_WAREHOUSE_METADATA_ACTIVITIES
+ SEMANTIC_ENRICHMENT_ACTIVITIES
+ PERSON_PROPERTY_SYNC_ACTIVITIES
- + PERSON_PROPERTY_BACKFILL_ACTIVITIES,
+ + PERSON_PROPERTY_BACKFILL_ACTIVITIES
+ + ACCOUNT_PROPERTY_SYNC_ACTIVITIES,
),
(
settings.DATA_MODELING_TASK_QUEUE,
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index a600d48bcf0e..42f3bbe5ba03 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -62,7 +62,7 @@ from products.data_warehouse.backend.facade.api import ensure_bucket_exists, get
from products.endpoints.backend.facade.temporal import prepare_executable_query
from products.warehouse_sources.backend.facade.hooks import saved_query_binding
from products.warehouse_sources.backend.facade.pipelines import CDPProducer
-from products.warehouse_sources.backend.facade.temporal import PersonPropertyRowSink
+from products.warehouse_sources.backend.facade.temporal import AccountPropertyRowSink, PersonPropertyRowSink
LOGGER = get_logger(__name__)
@@ -247,6 +247,8 @@ class MaterializeViewResult:
# what the workflow gates the person-property child on. Defaulted to the skip value so an old
# history decodes without it and never fires that child during replay.
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
# 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
@@ -685,6 +687,24 @@ 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:
+ 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
+ except Exception as error:
+ await logger.awarning(f"Could not resolve account-property staging for this view: {error}")
+ capture_exception(error)
+ return None
+
+
async def _clear_person_property_staging(sink: PersonPropertyRowSink, logger: FilteringBoundLogger) -> None:
"""Clear stale staged rows at run start. Never raises, for the same reason staging doesn't."""
try:
@@ -694,6 +714,15 @@ 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:
@@ -721,6 +750,20 @@ 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,
@@ -730,6 +773,7 @@ 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."""
@@ -768,6 +812,7 @@ 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
@@ -830,6 +875,7 @@ 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.
@@ -870,6 +916,7 @@ 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(
@@ -1007,6 +1054,12 @@ 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,
@@ -1034,11 +1087,27 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
try:
if plan.incremental:
row_count, file_uris = await _materialize_incrementally(
- objects, plan, hogql_query, table_uri, storage_options, logger, cdp_sink, person_property_sink
+ objects,
+ plan,
+ hogql_query,
+ table_uri,
+ storage_options,
+ logger,
+ cdp_sink,
+ person_property_sink,
+ account_property_sink,
)
else:
row_count, file_uris = await _materialize_fully(
- objects, plan, hogql_query, table_uri, storage_options, logger, cdp_sink, person_property_sink
+ objects,
+ plan,
+ hogql_query,
+ table_uri,
+ storage_options,
+ 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
@@ -1060,6 +1129,7 @@ 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,
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 2f45c5a0fb5a..78a918e96ac4 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -58,6 +58,7 @@ 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.data_modeling.backend.facade.models import DataModelingJobEngine
from products.data_quality.backend.facade.contracts import (
CHECK_SUITE_WORKFLOW_NAME,
@@ -76,6 +77,7 @@ from products.warehouse_sources.backend.facade.hooks import (
# Covers every command the data quality feature adds here: the stage/audit/publish trio and the
# warn-mode suite child.
QUALITY_AUDIT_PATCH = "data-quality-audit-2026-08"
+ACCOUNT_PROPERTY_S3_SYNC_PATCH = "account-property-s3-sync-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.
@@ -379,6 +381,9 @@ 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)
+
# after the main workflow succeeds, collect shadow stats for comparison
if duckgres_shadow_handle is not None:
await self._collect_shadow_comparison(
@@ -622,6 +627,26 @@ class MaterializeViewWorkflow(PostHogWorkflow):
extra={"job_id": job_id, "error": str(e)},
)
+ async def _maybe_sync_account_properties(
+ self,
+ inputs: MaterializeViewWorkflowInputs,
+ materialize_result: MaterializeViewResult,
+ job_id: str,
+ ) -> None:
+ if not materialize_result.account_property_sync_enabled:
+ return
+ await temporalio.workflow.execute_activity(
+ "dispatch-warehouse-account-property-sync",
+ DispatchAccountPropertySyncInput(
+ team_id=inputs.team_id,
+ saved_query_id=materialize_result.saved_query_id,
+ job_id=job_id,
+ ),
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=5),
+ )
+
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 7bc43a1f4afd..853bdbc2c419 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -54,8 +54,15 @@ from products.data_modeling.backend.facade.models import (
)
from products.data_warehouse.backend.facade.api import CreateTableResult
from products.notifications.backend.facade.api import NotificationType, TargetType
-from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection, saved_query_binding
+from products.warehouse_sources.backend.facade.hooks import (
+ AccountPropertySourceProjection,
+ PersonPropertySourceProjection,
+ saved_query_binding,
+)
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_paths import (
+ job_staged_prefix as account_job_staged_prefix,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_paths import (
job_staged_prefix,
)
@@ -1803,3 +1810,71 @@ class TestMaterializeViewStagesPersonPropertyRows:
assert result.person_property_sync_enabled is False
listing = await minio_client.list_objects_v2(Bucket=bucket_name, Prefix="person_property_sync/")
assert listing.get("Contents", []) == []
+
+
+class TestMaterializeViewStagesAccountPropertyRows:
+ @staticmethod
+ def _hogql_table(*args, **kwargs):
+ del args, kwargs
+ data = cast(
+ Collection[pa.Array],
+ [pa.array(["org-1", "org-2"], type=pa.string()), pa.array([100.0, 200.0], type=pa.float64())],
+ )
+ batch = pa.RecordBatch.from_arrays(data, names=["organization_id", "mrr"])
+
+ async def async_generator():
+ yield batch, [("organization_id", "String"), ("mrr", "Float64")]
+
+ return async_generator()
+
+ async def test_stages_account_projection_under_the_materialization_job(
+ self, activity_environment, ateam, anode, asaved_query, ajob, adag, bucket_name, minio_client
+ ) -> None:
+ projection = [
+ AccountPropertySourceProjection(
+ key_column="organization_id",
+ columns=frozenset({"organization_id", "mrr"}),
+ )
+ ]
+ inputs = MaterializeViewInputs(
+ team_id=ateam.pk,
+ dag_id=str(adag.id),
+ node_id=str(anode.id),
+ job_id=str(ajob.id),
+ )
+ with (
+ override_settings(
+ BUCKET_URL=f"s3://{bucket_name}",
+ DATAWAREHOUSE_BUCKET=bucket_name,
+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
+ USE_LOCAL_SETUP=True,
+ ),
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.materialize_view.hogql_table",
+ self._hogql_table,
+ ),
+ unittest.mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports."
+ "pipelines.core.account_property_row_sink.account_property_projection_for",
+ return_value=projection,
+ ),
+ ):
+ result = await activity_environment.run(materialize_view_activity, inputs)
+ prefix = account_job_staged_prefix(
+ ateam.pk,
+ saved_query_binding(asaved_query.id),
+ str(ajob.id),
+ )
+
+ 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 len(keys) == 1
+ staged = await minio_client.get_object(Bucket=bucket_name, Key=keys[0])
+ table = pq.read_table(BytesIO(await staged["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 bcb4d625aeb4..21c8091d7500 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -17,11 +17,13 @@ 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 (
MaterializeViewWorkflow,
MaterializeViewWorkflowInputs,
)
+from products.customer_analytics.backend.facade.temporal_contracts import DispatchAccountPropertySyncInput
from products.data_quality.backend.facade.contracts import CHECK_SUITE_WORKFLOW_NAME, QualityAuditMode
from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncActivityInputs
@@ -113,6 +115,28 @@ 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)
+ activity_results = [
+ False,
+ "job-1",
+ materialize_result,
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
+ None,
+ None,
+ ]
+ start_child = AsyncMock()
+
+ _, execute_activity = await self._run(activity_results, {}, 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 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 = [
False,
@@ -308,6 +332,44 @@ 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 TestMaybeSyncAccountProperties:
+ async def test_dispatches_both_segments_through_a_retrying_activity(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")
+
+ 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
+
+ async def test_no_dispatch_when_no_account_rows_were_staged(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()
+
+
class TestMaybeEnrichViewSemantics:
async def test_starts_child_when_enrichment_needed(self):
workflow = MaterializeViewWorkflow()
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
index 5b99f5ce6227..10757a3c5822 100644
--- a/products/customer_analytics/backend/COMPROMISES.md
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -12,19 +12,17 @@ Shortcuts taken to ship the first version. Revisit when they bite.
## Custom property view sync
-- **Celery, not Temporal.** The sync runs in a Celery task, not a dedicated Temporal workflow. No
- durable retries and no run-level UI inspection — failures surface via `last_sync_error` on the
- source + error tracking. Move to Temporal if we need durable retries, long-running syncs, or
- per-run inspection.
-- **No retries.** A failed run is not retried; it records the failure (advancing the auto-disable
- streak) and waits for the next materialization. Only transient write conflicts retry, in-logic.
-- **Direct dispatch by task name, not a signal.** Core (`succeed_materialization_activity`) enqueues
- this product's sync task by name via `send_task`. A generic core signal the product subscribes to
- would keep core ignorant of the consumer, but for a single consumer that isn't worth the wiring (a
- signal definition + a receiver + an app-ready hook). By-name dispatch also keeps the product and
- HogQL out of the data-modeling worker's process, since core imports nothing from here. Trade-off:
- core hardcodes this consumer's task name. If a second consumer ever needs the materialization event,
- switch to a core-owned signal (inversion of control) rather than adding another direct dispatch.
+- **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
+ 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
+ both markers.
- **No save-time column validation.** Creating/updating a source does not check that `source_column`
/ `key_column` exist in the view's schema. A bad column surfaces as a per-source sync error (and
advances the auto-disable streak) on the next run, not as a 400 on save. Validate against the saved
diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.py
index 5b2219078262..618dd87376a6 100644
--- a/products/customer_analytics/backend/apps.py
+++ b/products/customer_analytics/backend/apps.py
@@ -8,6 +8,7 @@ class CustomerAnalyticsConfig(AppConfig):
def ready(self) -> None:
self._register_person_property_hooks()
+ self._register_account_property_hooks()
self._register_workflows_account_audience()
def _register_workflows_account_audience(self) -> None:
@@ -40,6 +41,24 @@ class CustomerAnalyticsConfig(AppConfig):
register_account_audience_provider(_Provider())
+ def _register_account_property_hooks(self) -> None:
+ from products.warehouse_sources.backend.facade.hooks import (
+ AccountPropertySourceProjection,
+ WarehouseBinding,
+ register_account_property_projection,
+ )
+
+ def _projection_resolver(
+ team_id: int, binding: WarehouseBinding
+ ) -> list[AccountPropertySourceProjection] | None:
+ from products.customer_analytics.backend.logic.account_property_projection import ( # noqa: PLC0415
+ account_property_projection,
+ )
+
+ return account_property_projection(team_id, binding)
+
+ register_account_property_projection(_projection_resolver)
+
def _register_person_property_hooks(self) -> None:
"""Tell the data-import pipeline which columns to stage for a schema's person-property
sources, and give its post-sync upsert job the full source configs — without
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index 8c5466694126..2a4b6ab63a92 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -13,6 +13,7 @@ CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG = "customer-analytics-feature-requests"
# properties feature: creating person-target custom property sources (API + UI), staging rows during
# syncs, and the post-sync upsert workflow.
WAREHOUSE_PERSON_PROPERTIES_FLAG = "warehouse-person-properties"
+WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC_FLAG = "warehouse-account-properties-s3-sync"
# Mirrors frontend `BILLING_INSIGHT_SHORT_IDS` in accountBillingLogic.ts. These saved insights read
# warehouse-synced billing data to report an account's PostHog consumption (events ingested, rows
diff --git a/products/customer_analytics/backend/facade/temporal.py b/products/customer_analytics/backend/facade/temporal.py
index 13725d373761..0d931c17a4c5 100644
--- a/products/customer_analytics/backend/facade/temporal.py
+++ b/products/customer_analytics/backend/facade/temporal.py
@@ -1,7 +1,19 @@
"""Temporal wiring re-exports — the only path core may use to register this
product's workflows, activities, and schedules."""
+from products.customer_analytics.backend.facade.temporal_contracts import AccountPropertySyncInput
from products.customer_analytics.backend.temporal import ACTIVITIES, WORKFLOWS
+from products.customer_analytics.backend.temporal.account_property_sync import (
+ ACCOUNT_PROPERTY_SYNC_ACTIVITIES,
+ ACCOUNT_PROPERTY_SYNC_WORKFLOWS,
+)
from products.customer_analytics.backend.temporal.calendar_sync import create_calendar_sync_coordinator_schedule
-__all__ = ["ACTIVITIES", "WORKFLOWS", "create_calendar_sync_coordinator_schedule"]
+__all__ = [
+ "ACCOUNT_PROPERTY_SYNC_ACTIVITIES",
+ "ACCOUNT_PROPERTY_SYNC_WORKFLOWS",
+ "ACTIVITIES",
+ "WORKFLOWS",
+ "AccountPropertySyncInput",
+ "create_calendar_sync_coordinator_schedule",
+]
diff --git a/products/customer_analytics/backend/facade/temporal_contracts.py b/products/customer_analytics/backend/facade/temporal_contracts.py
new file mode 100644
index 000000000000..722b8408b4fc
--- /dev/null
+++ b/products/customer_analytics/backend/facade/temporal_contracts.py
@@ -0,0 +1,16 @@
+from posthog.dataclasses import frozen
+
+
+@frozen
+class DispatchAccountPropertySyncInput:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+
+
+@frozen
+class AccountPropertySyncInput:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+ segment: str
diff --git a/products/customer_analytics/backend/logic/account_property_projection.py b/products/customer_analytics/backend/logic/account_property_projection.py
new file mode 100644
index 000000000000..a79f4730221f
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_projection.py
@@ -0,0 +1,59 @@
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+
+from products.customer_analytics.backend.constants import WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC_FLAG
+from products.customer_analytics.backend.models import CustomPropertySource, TargetType
+from products.warehouse_sources.backend.facade.hooks import (
+ BINDING_KIND_SAVED_QUERY,
+ AccountPropertySourceProjection,
+ WarehouseBinding,
+)
+
+
+def account_property_staging_enabled(team_id: int) -> bool:
+ try:
+ organization_id = str(Team.objects.only("organization_id").get(id=team_id).organization_id)
+ except Team.DoesNotExist:
+ return False
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as error:
+ capture_exception(error)
+ return False
+
+
+def account_property_projection(
+ team_id: int, binding: WarehouseBinding
+) -> list[AccountPropertySourceProjection] | None:
+ if binding.kind != BINDING_KIND_SAVED_QUERY:
+ return None
+ sources = list(
+ CustomPropertySource.objects.for_team(team_id)
+ .select_related("definition")
+ .filter(
+ saved_query_id=binding.id,
+ is_enabled=True,
+ definition__target_type=TargetType.ACCOUNT.value,
+ source_column__isnull=False,
+ )
+ )
+ if not sources or not account_property_staging_enabled(team_id):
+ return None
+ return [
+ AccountPropertySourceProjection(
+ key_column=source.key_column,
+ columns=frozenset({source.key_column, source.source_column}),
+ )
+ for source in sources
+ if source.source_column
+ ]
diff --git a/products/customer_analytics/backend/logic/account_property_projection_test.py b/products/customer_analytics/backend/logic/account_property_projection_test.py
new file mode 100644
index 000000000000..c40410b02340
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_projection_test.py
@@ -0,0 +1,52 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from products.customer_analytics.backend.logic.account_property_projection import account_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, create_saved_query
+from products.warehouse_sources.backend.facade.hooks import saved_query_binding, schema_binding
+
+
+class AccountPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.saved_query = create_saved_query(team_id=self.team.id)
+ flag_patch = patch(
+ "products.customer_analytics.backend.logic.account_property_projection.account_property_staging_enabled",
+ return_value=True,
+ )
+ flag_patch.start()
+ self.addCleanup(flag_patch.stop)
+
+ def _source(self, name: str, key_column: str, source_column: str, *, is_enabled: bool = True) -> None:
+ definition = create_custom_property_definition(
+ team_id=self.team.id,
+ name=name,
+ target_type=TargetType.ACCOUNT.value,
+ )
+ CustomPropertySource.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ definition=definition,
+ saved_query=self.saved_query,
+ key_column=key_column,
+ source_column=source_column,
+ is_enabled=is_enabled,
+ )
+
+ def test_projects_key_and_value_columns_for_enabled_account_sources(self) -> None:
+ self._source("MRR", "organization_id", "mrr")
+ self._source("Plan", "account_id", "plan")
+ self._source("Disabled", "organization_id", "disabled", is_enabled=False)
+
+ projection = account_property_projection(self.team.id, saved_query_binding(self.saved_query.id))
+
+ assert projection is not None
+ assert {item.key_column: item.columns for item in projection} == {
+ "organization_id": frozenset({"organization_id", "mrr"}),
+ "account_id": frozenset({"account_id", "plan"}),
+ }
+
+ def test_returns_none_for_schema_bindings_and_views_without_sources(self) -> None:
+ assert account_property_projection(self.team.id, schema_binding("019f0000-0000-7000-8000-000000000001")) is None
+ assert account_property_projection(self.team.id, saved_query_binding(self.saved_query.id)) is None
diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.py
new file mode 100644
index 000000000000..c2b7d5f81305
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_sync.py
@@ -0,0 +1,349 @@
+import io
+import json
+import asyncio
+import hashlib
+from collections.abc import AsyncIterator, Iterator
+from dataclasses import field
+from datetime import date, datetime, time
+from decimal import Decimal
+from enum import StrEnum
+from typing import Any
+from uuid import UUID
+
+import pyarrow as pa
+import structlog
+import pyarrow.parquet as pq
+
+from posthog.dataclasses import frozen
+from posthog.sync import database_sync_to_async
+
+from products.customer_analytics.backend.logic.custom_property_values import (
+ InvalidCustomPropertyValue,
+ set_synced_custom_property_value,
+)
+from products.customer_analytics.backend.models import Account, CustomPropertySource, TargetType
+from products.data_warehouse.backend.facade.api import aget_s3_client
+from products.warehouse_sources.backend.facade.hooks import WarehouseBinding
+from products.warehouse_sources.backend.facade.temporal import (
+ account_property_completion_prefix,
+ account_property_job_staged_prefix,
+ account_property_snapshot_prefix,
+)
+
+logger = structlog.get_logger(__name__)
+
+_ACCOUNT_LOOKUP_CHUNK_SIZE = 1_000
+_PARQUET_BATCH_SIZE = 50_000
+_SEGMENTS_REQUIRED_FOR_CLEANUP = frozenset({"tracked", "ignored"})
+
+
+class AccountPropertySyncSegment(StrEnum):
+ TRACKED = "tracked"
+ IGNORED = "ignored"
+
+
+class AccountPropertySourceValueError(Exception):
+ pass
+
+
+@frozen
+class AppliedSourceValues:
+ written: int
+ hashes: dict[str, str]
+ failed: bool
+
+
+@frozen(frozen=False)
+class SourceSyncState:
+ source: CustomPropertySource
+ prior_hashes: dict[str, str]
+ applied_hashes: dict[str, str] = field(default_factory=dict)
+ failed: bool = False
+
+
+def _json_safe(value: Any) -> Any:
+ if value is None or isinstance(value, (str, bool, int, float)):
+ return value
+ if isinstance(value, (datetime, date, time)):
+ return value.isoformat()
+ if isinstance(value, Decimal):
+ return float(value)
+ if isinstance(value, dict):
+ return {key: _json_safe(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_json_safe(item) for item in value]
+ return str(value)
+
+
+def _value_hash(value: Any) -> str:
+ return hashlib.sha256(json.dumps(_json_safe(value), sort_keys=True).encode("utf-8")).hexdigest()
+
+
+def _decode_parquet_rows(data: bytes) -> list[dict[str, Any]]:
+ return pq.read_table(io.BytesIO(data)).to_pylist()
+
+
+def _encode_snapshot(hashes: dict[str, str]) -> bytes:
+ table = pa.table({"external_id": list(hashes), "value_hash": list(hashes.values())})
+ buffer = pa.BufferOutputStream()
+ pq.write_table(table, buffer, compression="zstd")
+ return buffer.getvalue().to_pybytes()
+
+
+def _parquet_batches(data: bytes) -> Iterator[pa.RecordBatch]:
+ return pq.ParquetFile(io.BytesIO(data)).iter_batches(batch_size=_PARQUET_BATCH_SIZE)
+
+
+async def _iter_parquet_row_batches(
+ team_id: int, binding: WarehouseBinding, job_id: str
+) -> AsyncIterator[list[dict[str, Any]]]:
+ prefix = account_property_job_staged_prefix(team_id, binding, job_id)
+ async with aget_s3_client() as s3_client:
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ return
+ entries = listing.values() if isinstance(listing, dict) else listing
+ file_paths = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")
+ for file_path in file_paths:
+ uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"
+ data = await s3_client._cat_file(uri)
+ batches = await asyncio.to_thread(_parquet_batches, data)
+ while (batch := await asyncio.to_thread(next, batches, None)) is not None:
+ yield await asyncio.to_thread(batch.to_pylist)
+
+
+async def _read_snapshot_hashes(
+ team_id: int, binding: WarehouseBinding, source_id: str, segment: AccountPropertySyncSegment
+) -> dict[str, str]:
+ prefix = account_property_snapshot_prefix(team_id, binding, source_id, segment.value)
+ hashes: dict[str, str] = {}
+ async with aget_s3_client() as s3_client:
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ return hashes
+ entries = listing.values() if isinstance(listing, dict) else listing
+ files = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")
+ for file_path in files:
+ uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"
+ data = await s3_client._cat_file(uri)
+ for row in await asyncio.to_thread(_decode_parquet_rows, data):
+ hashes[str(row["external_id"])] = str(row["value_hash"])
+ return hashes
+
+
+async def _write_snapshot_hashes(
+ team_id: int,
+ binding: WarehouseBinding,
+ source_id: str,
+ segment: AccountPropertySyncSegment,
+ job_id: str,
+ hashes: dict[str, str],
+) -> None:
+ if not hashes:
+ return
+
+ prefix = account_property_snapshot_prefix(team_id, binding, source_id, segment.value)
+ path = f"{prefix}/{job_id}.parquet"
+ async with aget_s3_client() as s3_client:
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ listing = []
+ entries = listing.values() if isinstance(listing, dict) else listing
+ existing_files = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")
+ merged: dict[str, str] = {}
+ for file_path in existing_files:
+ uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"
+ data = await s3_client._cat_file(uri)
+ for row in await asyncio.to_thread(_decode_parquet_rows, data):
+ merged[str(row["external_id"])] = str(row["value_hash"])
+ merged.update(hashes)
+ snapshot = await asyncio.to_thread(_encode_snapshot, merged)
+ await s3_client._pipe_file(f"s3://{path}", snapshot)
+ stale = [file_path for file_path in existing_files if not file_path.endswith(f"/{job_id}.parquet")]
+ if stale:
+ await s3_client._rm(
+ [file_path if file_path.startswith("s3://") else f"s3://{file_path}" for file_path in stale]
+ )
+
+
+def _matching_account_ids(
+ team_id: int, segment: AccountPropertySyncSegment, external_ids: list[str]
+) -> dict[str, UUID]:
+ matching: dict[str, UUID] = {}
+ for start in range(0, len(external_ids), _ACCOUNT_LOOKUP_CHUNK_SIZE):
+ chunk = external_ids[start : start + _ACCOUNT_LOOKUP_CHUNK_SIZE]
+ accounts = Account.objects.for_team(team_id).filter(
+ external_id__in=chunk,
+ churned_at__isnull=True,
+ )
+ if segment == AccountPropertySyncSegment.TRACKED:
+ accounts = accounts.filter(ignored_at__isnull=True)
+ else:
+ accounts = accounts.filter(ignored_at__isnull=False)
+ matching.update(
+ (external_id, account_id)
+ for external_id, account_id in accounts.values_list("external_id", "id")
+ if external_id
+ )
+ return matching
+
+
+def _apply_source_values(
+ team_id: int,
+ source: CustomPropertySource,
+ account_ids: dict[str, UUID],
+ changed: dict[str, Any],
+ segment: AccountPropertySyncSegment,
+) -> AppliedSourceValues:
+ written = 0
+ applied_hashes: dict[str, str] = {}
+ source_failed = False
+ for external_id, account_id in account_ids.items():
+ value = changed[external_id]
+ try:
+ did_write = set_synced_custom_property_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=source.definition,
+ value=value,
+ )
+ except InvalidCustomPropertyValue as error:
+ source_failed = True
+ logger.warning(
+ "account-property sync rejected a source value",
+ team_id=team_id,
+ source_id=str(source.id),
+ segment=segment.value,
+ error=str(error),
+ )
+ continue
+ if did_write:
+ written += 1
+ applied_hashes[external_id] = _value_hash(value)
+ return AppliedSourceValues(written=written, hashes=applied_hashes, failed=source_failed)
+
+
+def _enabled_sources(team_id: int, binding: WarehouseBinding) -> list[CustomPropertySource]:
+ return list(
+ CustomPropertySource.objects.for_team(team_id)
+ .select_related("definition")
+ .filter(
+ saved_query_id=binding.id,
+ is_enabled=True,
+ definition__target_type=TargetType.ACCOUNT.value,
+ source_column__isnull=False,
+ )
+ )
+
+
+async def _segment_already_completed(
+ team_id: int, binding: WarehouseBinding, job_id: str, segment: AccountPropertySyncSegment
+) -> bool:
+ marker = f"{account_property_completion_prefix(team_id, binding, job_id)}/{segment.value}.done"
+ async with aget_s3_client() as s3_client:
+ try:
+ await s3_client._cat_file(f"s3://{marker}")
+ except FileNotFoundError:
+ return False
+ return True
+
+
+async def _mark_completed_and_maybe_cleanup(
+ team_id: int, binding: WarehouseBinding, job_id: str, segment: AccountPropertySyncSegment
+) -> None:
+ prefix = account_property_completion_prefix(team_id, binding, job_id)
+ async with aget_s3_client() as s3_client:
+ await s3_client._pipe_file(f"s3://{prefix}/{segment.value}.done", b"")
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ return
+ entries = listing.values() if isinstance(listing, dict) else listing
+ completed = {
+ entry["Key"].rsplit("/", 1)[-1].removesuffix(".done")
+ for entry in entries
+ if entry.get("type") != "directory"
+ }
+ if not _SEGMENTS_REQUIRED_FOR_CLEANUP.issubset(completed):
+ return
+ try:
+ await s3_client._rm(f"s3://{account_property_job_staged_prefix(team_id, binding, job_id)}/", recursive=True)
+ except FileNotFoundError:
+ pass
+
+
+async def run_account_property_segment_sync(
+ *, team_id: int, binding: WarehouseBinding, job_id: str, segment: AccountPropertySyncSegment
+) -> dict[str, int]:
+ if await _segment_already_completed(team_id, binding, job_id, segment):
+ return {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
+
+ sources = await database_sync_to_async(_enabled_sources, thread_sensitive=False)(team_id, binding)
+ counts = {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
+
+ states: list[SourceSyncState] = []
+ for source in sources:
+ if source.source_column is None:
+ continue
+ states.append(
+ SourceSyncState(
+ source=source,
+ prior_hashes=await _read_snapshot_hashes(team_id, binding, str(source.id), segment),
+ )
+ )
+
+ async for rows in _iter_parquet_row_batches(team_id, binding, job_id):
+ counts["rows_read"] += len(rows)
+ for state in states:
+ source = state.source
+ source_column = source.source_column
+ if source_column is None:
+ continue
+ values_by_external_id: dict[str, Any] = {}
+ for row in rows:
+ external_id = row.get(source.key_column)
+ value = row.get(source_column)
+ if external_id is not None and value is not None:
+ values_by_external_id[str(external_id)] = _json_safe(value)
+ changed = {
+ external_id: value
+ for external_id, value in values_by_external_id.items()
+ if state.prior_hashes.get(external_id) != _value_hash(value)
+ }
+ counts["changed"] += len(changed)
+ if not changed:
+ continue
+ account_ids = await database_sync_to_async(_matching_account_ids, thread_sensitive=False)(
+ team_id, segment, list(changed)
+ )
+ counts["matched"] += len(account_ids)
+ applied = await database_sync_to_async(_apply_source_values, thread_sensitive=False)(
+ team_id, source, account_ids, changed, segment
+ )
+ counts["written"] += applied.written
+ state.failed = state.failed or applied.failed
+ state.applied_hashes.update(applied.hashes)
+ state.prior_hashes.update(applied.hashes)
+
+ for state in states:
+ if state.failed:
+ counts["source_errors"] += 1
+ await _write_snapshot_hashes(
+ team_id,
+ binding,
+ str(state.source.id),
+ segment,
+ job_id,
+ state.applied_hashes,
+ )
+
+ if counts["source_errors"]:
+ raise AccountPropertySourceValueError(
+ f"{counts['source_errors']} account-property source(s) contained invalid values"
+ )
+
+ await _mark_completed_and_maybe_cleanup(team_id, binding, job_id, segment)
+ return counts
diff --git a/products/customer_analytics/backend/logic/account_property_sync_test.py b/products/customer_analytics/backend/logic/account_property_sync_test.py
new file mode 100644
index 000000000000..1e5d7136586d
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py
@@ -0,0 +1,144 @@
+from datetime import UTC, datetime
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+
+from products.customer_analytics.backend.logic.account_property_sync import (
+ AccountPropertySyncSegment,
+ _iter_parquet_row_batches,
+ _mark_completed_and_maybe_cleanup,
+ _matching_account_ids,
+ _value_hash,
+ run_account_property_segment_sync,
+)
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+from products.customer_analytics.backend.test.factories import create_account
+from products.warehouse_sources.backend.facade.hooks import saved_query_binding
+from products.warehouse_sources.backend.facade.temporal import account_property_job_staged_prefix
+
+_MODULE = "products.customer_analytics.backend.logic.account_property_sync"
+
+
+class AccountPropertySegmentTest(TeamScopedTestMixin, BaseTest):
+ def test_segments_tracked_and_ignored_accounts_and_excludes_churned_accounts(self) -> None:
+ tracked = create_account(team_id=self.team.id, external_id="tracked")
+ ignored = create_account(team_id=self.team.id, external_id="ignored", ignored_at=datetime.now(UTC))
+ create_account(team_id=self.team.id, external_id="churned", churned_at=datetime.now(UTC))
+
+ tracked_matches = _matching_account_ids(
+ self.team.id,
+ AccountPropertySyncSegment.TRACKED,
+ ["tracked", "ignored", "churned"],
+ )
+ ignored_matches = _matching_account_ids(
+ self.team.id,
+ AccountPropertySyncSegment.IGNORED,
+ ["tracked", "ignored", "churned"],
+ )
+
+ assert tracked_matches == {"tracked": tracked.id}
+ assert ignored_matches == {"ignored": ignored.id}
+
+ def test_value_hash_is_stable_for_equivalent_values(self) -> None:
+ assert _value_hash({"a": 1, "b": [2, 3]}) == _value_hash({"b": [2, 3], "a": 1})
+
+
+class _S3ClientContext:
+ def __init__(self, client: MagicMock) -> None:
+ self.client = client
+
+ async def __aenter__(self) -> MagicMock:
+ return self.client
+
+ async def __aexit__(self, *args) -> bool:
+ return False
+
+
+async def test_each_staged_batch_is_shared_across_sources() -> None:
+ binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
+ sources = []
+ for index in range(2):
+ source = MagicMock()
+ source.id = f"source-{index}"
+ source.key_column = "organization_id"
+ source.source_column = f"value_{index}"
+ sources.append(source)
+ batch_calls = 0
+
+ async def batches(*args):
+ nonlocal batch_calls
+ batch_calls += 1
+ yield [{"organization_id": "org-1", "value_0": 1, "value_1": 2}]
+
+ with (
+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
+ patch(f"{_MODULE}._enabled_sources", return_value=sources),
+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
+ patch(f"{_MODULE}._iter_parquet_row_batches", side_effect=batches),
+ patch(f"{_MODULE}._matching_account_ids", return_value={}),
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
+ patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
+ ):
+ await run_account_property_segment_sync(
+ team_id=7,
+ binding=binding,
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ )
+
+ assert batch_calls == 1
+
+
+async def test_staged_parquet_is_decoded_in_bounded_batches() -> None:
+ binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
+ table = pa.table({"organization_id": [f"org-{index}" for index in range(50_001)]})
+ buffer = pa.BufferOutputStream()
+ pq.write_table(table, buffer)
+ client = MagicMock()
+ client._ls = AsyncMock(return_value=[{"Key": "prefix/chunk.parquet", "type": "file"}])
+ client._cat_file = AsyncMock(return_value=buffer.getvalue().to_pybytes())
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_S3ClientContext(client)):
+ batch_sizes = [
+ len(rows)
+ async for rows in _iter_parquet_row_batches(
+ 7,
+ binding,
+ "job-1",
+ )
+ ]
+
+ assert batch_sizes == [50_000, 1]
+
+
+async def test_staged_parquet_is_deleted_only_after_both_segments_complete() -> None:
+ binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
+ client = MagicMock()
+ client._pipe_file = AsyncMock()
+ client._rm = AsyncMock()
+ client._ls = AsyncMock(
+ side_effect=[
+ [{"Key": "prefix/tracked.done", "type": "file"}],
+ [
+ {"Key": "prefix/tracked.done", "type": "file"},
+ {"Key": "prefix/ignored.done", "type": "file"},
+ ],
+ ]
+ )
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_S3ClientContext(client)):
+ await _mark_completed_and_maybe_cleanup(7, binding, "job-1", AccountPropertySyncSegment.TRACKED)
+ client._rm.assert_not_awaited()
+ await _mark_completed_and_maybe_cleanup(7, binding, "job-1", AccountPropertySyncSegment.IGNORED)
+
+ client._rm.assert_awaited_once_with(
+ f"s3://{account_property_job_staged_prefix(7, binding, 'job-1')}/",
+ recursive=True,
+ )
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index 87066f50074b..2b13afa49908 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -185,6 +185,30 @@ def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timest
return False
+def set_synced_custom_property_value(
+ *, team_id: int, account_id: str | UUID, definition: CustomPropertyDefinition, value: Any
+) -> bool:
+ """Set a staged warehouse value for an account already resolved inside this team."""
+ _, coerced = _coerce_to_column(definition, value)
+ current = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
+ .first()
+ )
+ if current is not None:
+ current.definition = definition
+ if value_of(current) == coerced:
+ return False
+ _set_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=value,
+ created_by_id=None,
+ )
+ return True
+
+
def _set_value(
*,
team_id: int,
@@ -226,8 +250,6 @@ def _set_value(
f"An active value for custom property '{definition.name}' was set concurrently."
) from exc
raise
- # Cache the definition we already hold so callers reading row.definition.* don't trigger a
- # lazy FK load against the fail-closed manager (which would raise outside request scope).
row.definition = definition
return row
diff --git a/products/customer_analytics/backend/temporal/account_property_sync.py b/products/customer_analytics/backend/temporal/account_property_sync.py
new file mode 100644
index 000000000000..5d61f50b143c
--- /dev/null
+++ b/products/customer_analytics/backend/temporal/account_property_sync.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import json
+import time
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
+
+from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
+
+from products.customer_analytics.backend.facade.temporal_contracts import (
+ AccountPropertySyncInput,
+ DispatchAccountPropertySyncInput,
+)
+
+with workflow.unsafe.imports_passed_through():
+ from datetime import timedelta
+
+ from django.conf import settings
+
+ import structlog
+ from prometheus_client import Counter, Histogram
+
+ from posthog.temporal.common.client import async_connect
+
+ from products.customer_analytics.backend.logic.account_property_sync import (
+ AccountPropertySourceValueError,
+ AccountPropertySyncSegment,
+ run_account_property_segment_sync,
+ )
+ from products.warehouse_sources.backend.facade.hooks import saved_query_binding
+
+logger = structlog.get_logger(__name__)
+
+ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME = "sync-warehouse-account-properties"
+
+ACCOUNT_PROPERTY_SYNC_TOTAL = Counter(
+ "warehouse_account_property_sync_total",
+ "Account-property sync activity attempts by segment and outcome",
+ labelnames=["team_id", "segment", "outcome"],
+)
+
+ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS = Histogram(
+ "warehouse_account_property_sync_duration_seconds",
+ "Duration of one account-property segment sync",
+ labelnames=["segment"],
+ 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),
+)
+
+
[email protected](name="dispatch-warehouse-account-property-sync")
+async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccountPropertySyncInput) -> None:
+ client = await async_connect()
+ for segment in ("tracked", "ignored"):
+ workflow_id = f"sync-warehouse-account-properties-{input.job_id}-{segment}"
+ try:
+ await client.start_workflow(
+ ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME,
+ AccountPropertySyncInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=segment,
+ ),
+ id=workflow_id,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ execution_timeout=timedelta(hours=24),
+ )
+ except WorkflowAlreadyStartedError:
+ logger.info(
+ "Account-property segment sync already running",
+ team_id=input.team_id,
+ job_id=input.job_id,
+ segment=segment,
+ )
+
+
+async def sync_warehouse_account_properties_activity(input: AccountPropertySyncInput) -> dict[str, int]:
+ segment = AccountPropertySyncSegment(input.segment)
+ log = logger.bind(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=segment.value,
+ )
+ started = time.monotonic()
+ try:
+ async with Heartbeater():
+ result = await run_account_property_segment_sync(
+ team_id=input.team_id,
+ binding=saved_query_binding(input.saved_query_id),
+ job_id=input.job_id,
+ segment=segment,
+ )
+ except AccountPropertySourceValueError as error:
+ ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="failed").inc()
+ log.warning("Account-property segment sync rejected invalid source values", error=str(error))
+ raise ApplicationError(str(error), non_retryable=True) from error
+ except Exception as error:
+ ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="failed").inc()
+ log.exception("Account-property segment sync failed")
+ capture_exception(error)
+ raise
+
+ ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="completed").inc()
+ ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS.labels(segment=segment.value).observe(time.monotonic() - started)
+ log.info("Account-property segment sync completed", **result)
+ return result
+
+
[email protected](name=ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME)
+class SyncWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> AccountPropertySyncInput:
+ return AccountPropertySyncInput(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, input: AccountPropertySyncInput) -> None:
+ await workflow.execute_activity(
+ sync_warehouse_account_properties_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)),
+ )
+
+
+ACCOUNT_PROPERTY_SYNC_WORKFLOWS = [SyncWarehouseAccountPropertiesWorkflow]
+ACCOUNT_PROPERTY_SYNC_ACTIVITIES = [
+ 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
new file mode 100644
index 000000000000..aefc8e52f799
--- /dev/null
+++ b/products/customer_analytics/backend/temporal/account_property_sync_test.py
@@ -0,0 +1,49 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from temporalio import workflow
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from products.customer_analytics.backend.facade.temporal_contracts import DispatchAccountPropertySyncInput
+from products.customer_analytics.backend.temporal.account_property_sync import (
+ AccountPropertySyncInput,
+ SyncWarehouseAccountPropertiesWorkflow,
+ dispatch_warehouse_account_property_sync_activity,
+ sync_warehouse_account_properties_activity,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+async def test_dispatch_starts_missing_segment_when_its_sibling_already_runs() -> None:
+ client = AsyncMock()
+ client.start_workflow.side_effect = [WorkflowAlreadyStartedError("tracked", "workflow"), None]
+ input = DispatchAccountPropertySyncInput(
+ team_id=7,
+ saved_query_id="019f0000-0000-7000-8000-000000000001",
+ job_id="job-1",
+ )
+
+ with patch("products.customer_analytics.backend.temporal.account_property_sync.async_connect", return_value=client):
+ await dispatch_warehouse_account_property_sync_activity(input)
+
+ assert client.start_workflow.await_count == 2
+ assert [call.args[1].segment for call in client.start_workflow.await_args_list] == ["tracked", "ignored"]
+
+
+async def test_workflow_executes_one_retryable_segment_activity() -> None:
+ execute_activity = AsyncMock()
+ input = AccountPropertySyncInput(
+ team_id=7,
+ saved_query_id="019f0000-0000-7000-8000-000000000001",
+ job_id="job-1",
+ segment="tracked",
+ )
+
+ with patch.object(workflow, "execute_activity", new=execute_activity):
+ await SyncWarehouseAccountPropertiesWorkflow().run(input)
+
+ execute_activity.assert_awaited_once()
+ assert execute_activity.await_args is not None
+ assert execute_activity.await_args.args == (sync_warehouse_account_properties_activity, input)
+ assert execute_activity.await_args.kwargs["retry_policy"].maximum_attempts == 5
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index 8a64d1771da4..04bf6bb089d9 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -28,6 +28,7 @@ from products.customer_analytics.backend.logic.custom_property_values import (
record_last_slack_message_at,
set_account_custom_properties_by_id,
set_custom_property_value,
+ set_synced_custom_property_value,
)
from products.customer_analytics.backend.models import (
CANONICAL_LAST_SLACK_MESSAGE_AT,
@@ -202,6 +203,38 @@ class TestSetCustomPropertyValue(BaseTest):
first.refresh_from_db()
assert first.is_deleted is True
+ def test_regular_same_value_still_adds_history(self):
+ definition = self._create_property_definition()
+
+ self._set(definition=definition, value="enterprise")
+ self._set(definition=definition, value="enterprise")
+
+ assert (
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=definition)
+ .count()
+ == 2
+ )
+
+ def test_synced_same_value_does_not_add_history(self):
+ definition = self._create_property_definition()
+ self._set(definition=definition, value="enterprise")
+
+ changed = set_synced_custom_property_value(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition=definition,
+ value="enterprise",
+ )
+
+ assert changed is False
+ assert (
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=definition)
+ .count()
+ == 1
+ )
+
def test_list_active_returns_only_current_values(self):
plan = self._create_property_definition(name="Plan")
seats = self._create_property_definition(name="Seats", display_type=DisplayType.NUMBER)
diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.py
index b83819ed828e..67f03dec03f3 100644
--- a/products/warehouse_sources/backend/facade/hooks.py
+++ b/products/warehouse_sources/backend/facade/hooks.py
@@ -12,13 +12,16 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
BINDING_KIND_SAVED_QUERY,
BINDING_KIND_SCHEMA,
MATERIALIZED_VIEW_SOURCE_TYPE,
+ AccountPropertySourceProjection,
EmitSignalsActivityInputs,
PersonPropertySourceProjection,
PersonPropertySyncActivityInputs,
PersonPropertySyncRunRecord,
PersonPropertySyncSource,
WarehouseBinding,
+ account_property_projection_for,
person_property_projection_for,
+ register_account_property_projection,
register_data_quality_checks_gate,
register_emit_signals_gate,
register_engineering_analytics_view_sync,
@@ -37,6 +40,7 @@ __all__ = [
"BINDING_KIND_SAVED_QUERY",
"BINDING_KIND_SCHEMA",
"MATERIALIZED_VIEW_SOURCE_TYPE",
+ "AccountPropertySourceProjection",
"EmitSignalsActivityInputs",
"PersonPropertySourceProjection",
"PersonPropertySyncActivityInputs",
@@ -44,7 +48,9 @@ __all__ = [
"PersonPropertySyncSource",
"RevenueViewSyncInput",
"WarehouseBinding",
+ "account_property_projection_for",
"person_property_projection_for",
+ "register_account_property_projection",
"register_data_quality_checks_gate",
"register_emit_signals_gate",
"register_engineering_analytics_view_sync",
diff --git a/products/warehouse_sources/backend/facade/temporal.py b/products/warehouse_sources/backend/facade/temporal.py
index 92e4362da6a5..002ad2a70613 100644
--- a/products/warehouse_sources/backend/facade/temporal.py
+++ b/products/warehouse_sources/backend/facade/temporal.py
@@ -34,6 +34,14 @@ from products.warehouse_sources.backend.temporal.data_imports.person_property_tr
trigger_saved_query_materialization,
trigger_schema_sync,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_paths import (
+ completion_prefix as account_property_completion_prefix,
+ job_staged_prefix as account_property_job_staged_prefix,
+ snapshot_prefix as account_property_snapshot_prefix,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_row_sink import (
+ AccountPropertyRowSink,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (
PersonPropertyRowSink,
)
@@ -55,6 +63,10 @@ __all__ = [
"PERSON_PROPERTY_SYNC_WORKFLOWS",
"WORKFLOWS",
"ExternalDataSchemaSyncPausedError",
+ "AccountPropertyRowSink",
+ "account_property_completion_prefix",
+ "account_property_job_staged_prefix",
+ "account_property_snapshot_prefix",
"PersonPropertyRowSink",
"SavedQueryNotFoundError",
"SavedQueryNotOnV2ScheduleError",
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 6c3a196a908d..2f5df8af4856 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
@@ -187,6 +187,31 @@ def person_property_sync_enabled_for(team_id: int, binding: WarehouseBinding) ->
return person_property_projection_for(team_id, binding) is not None
[email protected](frozen=True)
+class AccountPropertySourceProjection:
+ """One account-target source's materialization projection."""
+
+ key_column: str
+ columns: frozenset[str]
+
+
+AccountPropertyProjectionResolver = Callable[[int, WarehouseBinding], Optional[list[AccountPropertySourceProjection]]]
+_account_property_projection_resolver: Optional[AccountPropertyProjectionResolver] = None
+
+
+def register_account_property_projection(fn: AccountPropertyProjectionResolver) -> None:
+ global _account_property_projection_resolver
+ _account_property_projection_resolver = fn
+
+
+def account_property_projection_for(
+ team_id: int, binding: WarehouseBinding
+) -> Optional[list[AccountPropertySourceProjection]]:
+ if _account_property_projection_resolver is None:
+ return None
+ return _account_property_projection_resolver(team_id, binding)
+
+
@dataclasses.dataclass(frozen=True)
class PersonPropertySyncSource:
"""One enabled person- or group-target source's sync config, resolved through the hook below so
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
new file mode 100644
index 000000000000..9607a2389248
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_paths.py
@@ -0,0 +1,25 @@
+from django.conf import settings
+
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import WarehouseBinding
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_paths import (
+ binding_path_segment,
+)
+
+
+def binding_staged_prefix(team_id: int, binding: WarehouseBinding) -> str:
+ return f"{settings.DATAWAREHOUSE_BUCKET}/account_property_sync/{team_id}/{binding_path_segment(binding)}"
+
+
+def job_staged_prefix(team_id: int, binding: WarehouseBinding, job_id: str) -> str:
+ return f"{binding_staged_prefix(team_id, binding)}/{job_id}"
+
+
+def snapshot_prefix(team_id: int, binding: WarehouseBinding, source_id: str, segment: str) -> str:
+ return (
+ f"{settings.DATAWAREHOUSE_BUCKET}/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}"
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
new file mode 100644
index 000000000000..ce1576ebdff2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py
@@ -0,0 +1,215 @@
+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 (
+ AccountPropertySourceProjection,
+ WarehouseBinding,
+ account_property_projection_for,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_paths import (
+ binding_staged_prefix,
+ job_staged_prefix,
+)
+
+# 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 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.
+ """
+
+ def __init__(
+ self,
+ team_id: int,
+ 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
+
+ def _get_fs(self) -> pa_fs.S3FileSystem:
+ # Cached per instance: stage_chunk() calls this once per chunk, and a sink lives for a
+ # whole sync (potentially thousands of chunks). A fresh S3FileSystem per call opens its
+ # own AWS SDK client/connections that outlive the call, exhausting the process' file
+ # descriptor limit over a long sync.
+ if self._fs_cache is not None:
+ return self._fs_cache
+
+ 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,
+ )
+ self._fs_cache = pa_fs.S3FileSystem(
+ access_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
+ secret_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
+ endpoint_override=settings.OBJECT_STORAGE_ENDPOINT,
+ )
+ else:
+ self._fs_cache = pa_fs.S3FileSystem()
+
+ return self._fs_cache
+
+ def _get_binding_prefix(self) -> str:
+ return binding_staged_prefix(self.team_id, self.binding)
+
+ def _get_path_prefix(self) -> str:
+ return job_staged_prefix(self.team_id, self.binding, self.job_id)
+
+ async def _get_projection(self) -> list[AccountPropertySourceProjection] | None:
+ """One projection per enabled account source on the binding (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(account_property_projection_for)(
+ self.team_id, self.binding
+ )
+ self._projection_resolved = True
+ return self._projection
+
+ async def should_run(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 (account external 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 account-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(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.
+ """
+ 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
+ await self._sweep_abandoned_sibling_prefixes(s3_client)
+ if own_prefix_error is not None:
+ raise own_prefix_error
+
+ async def _sweep_abandoned_sibling_prefixes(self, s3_client: Any) -> None:
+ try:
+ entries = await s3_client._find(f"s3://{self._get_binding_prefix()}/", detail=True)
+ except FileNotFoundError:
+ return
+ if not isinstance(entries, dict) or not entries:
+ return
+
+ binding_prefix = self._get_binding_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(binding_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 account-property staged files under {binding_prefix}"
+ )
+ await s3_client._rm([f"s3://{key}" for key in stale_files])
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
new file mode 100644
index 000000000000..35ffa9e89eef
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py
@@ -0,0 +1,92 @@
+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 (
+ AccountPropertySourceProjection,
+ saved_query_binding,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_row_sink import (
+ ABANDONED_STAGED_PREFIX_TTL,
+ AccountPropertyRowSink,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.account_property_row_sink"
+
+
+def _sink(*, incremental: bool = False) -> AccountPropertyRowSink:
+ logger = MagicMock()
+ logger.adebug = AsyncMock()
+ return AccountPropertyRowSink(
+ team_id=7,
+ binding=saved_query_binding("019f0000-0000-7000-8000-000000000001"),
+ job_id="job-1",
+ logger=logger,
+ is_incremental=incremental,
+ )
+
+
+class _S3ClientContext:
+ def __init__(self, client: MagicMock) -> None:
+ self.client = client
+
+ async def __aenter__(self) -> MagicMock:
+ return self.client
+
+ async def __aexit__(self, *args) -> bool:
+ return False
+
+
+async def test_stages_only_columns_from_sources_with_a_present_key() -> None:
+ sink = _sink()
+ projection = [
+ AccountPropertySourceProjection(
+ key_column="organization_id",
+ columns=frozenset({"organization_id", "mrr"}),
+ ),
+ AccountPropertySourceProjection(
+ key_column="missing_id",
+ columns=frozenset({"missing_id", "plan"}),
+ ),
+ ]
+ table = pa.table(
+ {
+ "organization_id": ["org-1"],
+ "mrr": [100],
+ "plan": ["pro"],
+ "unused": ["x"],
+ }
+ )
+
+ with (
+ patch(f"{_MODULE}.account_property_projection_for", return_value=projection),
+ patch.object(sink, "_get_fs", return_value=MagicMock()),
+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,
+ ):
+ await sink.stage_chunk(0, table)
+
+ 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]
+
+
+async def test_incremental_retry_keeps_its_staged_files_and_sweeps_abandoned_jobs() -> None:
+ sink = _sink(incremental=True)
+ stale_file = f"{sink._get_binding_prefix()}/job-old/chunk.parquet"
+ client = MagicMock()
+ client._find = AsyncMock(
+ return_value={stale_file: {"LastModified": datetime.now(UTC) - ABANDONED_STAGED_PREFIX_TTL - timedelta(days=1)}}
+ )
+ client._rm = AsyncMock()
+
+ with patch(f"{_MODULE}.aget_s3_client", return_value=_S3ClientContext(client)):
+ 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://{stale_file}"] in removed