:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(modeling): fix hung temporal workers (#60907)
andrew j. mcgehee17d5505ec612
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 456e0f7cbdfc..187b87146827 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -1,15 +1,12 @@import uuid-import queueimport typingimport asyncio-import threadingimport dataclassesfrom django.conf import settingsimport pyarrow as paimport deltalake-import asyncstdlibimport pyarrow.compute as pcimport pyarrow.parquet as pqfrom structlog.contextvars import bind_contextvars@@ -533,113 +530,44 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializrow_count = 0storage_options = _get_aws_storage_options()delta_table: deltalake.DeltaTable | None = None- # cache the schema of the first written batch so we can synthesize an empty- # parquet for zero-row results without going through delta-rs (whose Schema- # is arro3, not pyarrow).+ # cache the schema of the first batch so we can synthesize an empty parquet for+ # zero-row results without going through delta-rs (whose Schema is arro3, not+ # pyarrow).pa_schema: pa.Schema | None = None- # we stream every batch through a single deltalake write transaction.- # writing per-batch with mode="append" routes through delta-rs's- # DataFusion-backed writer, which lowercases identifiers and breaks- # columns with uppercase characters (`personId`, `Event`, ...) with- # errors like "Generic DeltaTable error: Schema error: No field named- # personid. ... Did you mean 'personId'?".- SENTINEL: typing.Any = object()- batch_queue: queue.Queue[pa.RecordBatch] = queue.Queue(maxsize=2)- producer_error: list[BaseException] = []-- # the producer's queue ops run in a thread via asyncio.to_thread, which is not- # cancellable: once a blocking queue.put/get is in flight, cancelling the- # awaiting coroutine does nothing to the thread. a plain blocking put against a- # full queue would therefore park its thread forever if the consumer stops- # draining (e.g. the write aborts, or the activity is cancelled), orphaning the- # thread and the producer task. so every blocking queue op below is a bounded- # poll on stop_event instead — when stop is requested, the in-flight op returns- # within QUEUE_POLL_SECONDS no matter what. safety is a property of the queue- # primitives, not of how carefully cleanup is sequenced.- stop_event = threading.Event()-- def _put(item: typing.Any) -> None:- while not stop_event.is_set():- try:- batch_queue.put(item, timeout=QUEUE_POLL_SECONDS)- return- except queue.Full:- continue-- def _get() -> typing.Any:- while not stop_event.is_set():- try:- return batch_queue.get(timeout=QUEUE_POLL_SECONDS)- except queue.Empty:- continue- return SENTINEL-- # a producer error is recorded in producer_error and then signalled to the- # consumer as a SENTINEL — i.e. the same clean end-of-stream as success. the- # consumer therefore commits whatever batches it received (a partial overwrite)- # before we re-raise below. that partial commit is harmless: the activity raises,- # Temporal retries, and the retry's delete-first wipes table_uri before rewriting.- async def _produce_batches() -> None:- nonlocal row_count- try:- async for _, res in asyncstdlib.enumerate(hogql_table(hogql_query, team, logger)):- if stop_event.is_set():- break- batch, ch_types = res- batch = _transform_unsupported_decimals(batch)- batch = _transform_date_and_datetimes(batch, ch_types)- num_rows = batch.num_rows- await asyncio.to_thread(_put, batch)- # local reference dropped immediately; the queue (and later- # the consumer) holds the only remaining reference.- del batch, ch_types- row_count = row_count + num_rows- job.rows_materialized = row_count- await database_sync_to_async(job.save)()- except BaseException as e:- producer_error.append(e)- finally:- await asyncio.to_thread(_put, SENTINEL)-- producer_task = asyncio.create_task(_produce_batches())- try:- first_batch = await asyncio.to_thread(_get)- if first_batch is not SENTINEL:- pa_schema = first_batch.schema-- def _batch_iter() -> typing.Iterator[pa.RecordBatch]:- yield first_batch- while True:- item = _get()- if item is SENTINEL:- return- yield item-- reader = pa.RecordBatchReader.from_batches(pa_schema, _batch_iter())- await logger.adebug(- f"Writing batches to delta table in a single transaction: mode=overwrite schema_mode=overwrite first_batch_rows={first_batch.num_rows}"- )+ # write each batch as its own delta commit, imitating the data_imports pipeline+ # (DeltaTableHelper.write_to_deltalake): the first batch overwrites — creating the+ # table from the exact arrow schema, which pins column case like `personId` — and+ # later batches append with schema_mode="merge". this keeps peak memory at ~one+ # batch (hogql_table yields ~100MB combined batches) and, because each write is a+ # brief to_thread released between batches, never pins a worker thread for the whole+ # read — which is what starved the shared executor that heartbeats/db/logging use.+ async for batch, ch_types in hogql_table(hogql_query, team, logger):+ batch = _transform_unsupported_decimals(batch)+ batch = _transform_date_and_datetimes(batch, ch_types)+ if delta_table is None:+ pa_schema = batch.schemaawait asyncio.to_thread(deltalake.write_deltalake,table_or_uri=table_uri,- data=reader,+ data=batch,mode="overwrite",schema_mode="overwrite",storage_options=storage_options,)delta_table = deltalake.DeltaTable(table_uri, storage_options=storage_options)- finally:- # request the producer stop and reap it. stop_event is set synchronously,- # before any await, so even a cancellation delivered at the await below- # cannot leave the producer parked on a queue op — its bounded _put/_get- # observe the flag and return promptly, the producer breaks its loop, and- # the task completes on its own. awaiting it here simply joins that exit.- stop_event.set()- await producer_task-- if producer_error:- raise producer_error[0]+ else:+ await asyncio.to_thread(+ deltalake.write_deltalake,+ table_or_uri=delta_table,+ data=batch,+ mode="append",+ schema_mode="merge",+ storage_options=storage_options,+ )+ row_count = row_count + batch.num_rows+ job.rows_materialized = row_count+ await database_sync_to_async(job.save)()await logger.ainfo(f"Finished writing to delta table. row_count={row_count}")# row count validation warningdiff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 24e1c76f77f9..527c2106b824 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -1,4 +1,3 @@-import asynciofrom collections.abc import Collection, Iterablefrom typing import Any, cast@@ -598,15 +597,13 @@ class TestMaterializeViewActivity:):# regression: multiple batches with case-sensitive columns must materialize cleanly.#- # per-batch mode="append" writes route through delta-rs's DataFusion-backed- # writer, which lowercases identifiers and fails with- # "Generic DeltaTable error: Schema error: No field named personid. ...- # Did you mean 'personId'?" on tables whose column names contain uppercase- # characters. the activity streams every batch through a single mode="overwrite"- # transaction to take the case-safe create path; this test guards both invariants:- # - all rows from every batch are written and column casing is preserved;- # - the delta history contains a single version (i.e. one commit), which would- # regress to N versions if someone reintroduced per-batch append.+ # delta-rs's DataFusion-backed append writer can lowercase identifiers and fail with+ # "Generic DeltaTable error: Schema error: No field named personid. ... Did you mean+ # 'personId'?" on tables whose column names contain uppercase characters. the activity+ # writes the first batch with mode="overwrite" (creating the table from the exact arrow+ # schema, pinning case) and appends later batches with schema_mode="merge" — the+ # data_imports write path. this asserts every batch's rows land and casing survives+ # across the overwrite + append commits.camel_case_names = ["Event", "DistinctId", "personId", "CamelCaseColumn"]def mock_hogql_table(*args, **kwargs):@@ -653,10 +650,6 @@ class TestMaterializeViewActivity:materialized = delta_table.to_pyarrow_table()assert materialized.column_names == camel_case_namesassert materialized.num_rows == 6- # one commit per materialization — guards against reintroducing per-batch- # append, which would record N+ versions and route through the broken- # DataFusion-backed writer.- assert len(delta_table.history()) == 1async def test_zero_row_materialization_writes_empty_parquet(self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag@@ -712,18 +705,9 @@ class TestMaterializeViewActivity:assert pyarrow_table.num_rows == 0assert set(pyarrow_table.column_names) == {"id", "name"}- async def test_aborted_write_releases_producer_parked_on_full_queue(- self, activity_environment, ateam, anode, ajob, bucket_name, adag- ):- # regression: when the consumer (write) aborts while the producer is still- # streaming, the producer must not be orphaned. its queue ops run in a thread- # via asyncio.to_thread (not cancellable), so a plain blocking put against the- # bounded queue would park that thread forever once the consumer stops draining,- # and the cleanup join (await producer_task) would hang with it. the producer's- # _put/_get poll a stop_event that cleanup sets, so the parked op returns and the- # task is reaped. we yield far more batches than the queue holds (maxsize=2) and- # make write_deltalake raise without draining, guaranteeing the producer parks;- # the activity must surface the write error promptly instead of hanging.+ async def test_write_failure_surfaces(self, activity_environment, ateam, anode, ajob, bucket_name, adag):+ # regression: a failure in a per-batch write_deltalake call must surface from the+ # activity so Temporal retries, rather than being swallowed.names = ["a", "b"]def mock_hogql_table(*args, **kwargs):@@ -765,7 +749,5 @@ class TestMaterializeViewActivity:node_id=str(anode.id),job_id=str(ajob.id),)- # wait_for fails the test rather than hanging the suite if the producer is- # orphaned and the cleanup join blocks forever.with pytest.raises(RuntimeError, match="boom"):- await asyncio.wait_for(activity_environment.run(materialize_view_activity, inputs), timeout=10)+ await activity_environment.run(materialize_view_activity, inputs)