Skip to content

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

fix(data-warehouse): bound the TemporalIO hand-off queue by bytes (#78171)

Tom Owers97fa13f38336
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
index ae2ddaba9543..0f3f6f4328a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
@@ -114,8 +114,80 @@ async def _with_transient_rpc_retry(
await asyncio.sleep(backoff)
-def _async_iter_to_sync(async_iter):
- q: Queue[Any] = Queue(maxsize=5000)
+# Hand-off queue bounds between the async producer thread and the sync consumer. The item count
+# keeps a stream of ordinary events flowing; the byte cap only binds once events get large, which is
+# where the memory risk actually sits. Below roughly 13 KiB per event the count still governs.
+_QUEUE_MAX_ITEMS = 5000
+_QUEUE_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+
+# Flat charges for values whose real footprint is not worth measuring — see `_estimate_size_bytes`.
+_SCALAR_SIZE_BYTES = 16
+_CONTAINER_SIZE_BYTES = 64
+
+
+def _estimate_size_bytes(value: Any) -> int:
+ """Rough in-memory footprint of a decoded JSON value.
+
+ Sums string and bytes lengths, which dominate a Temporal history event because the workflow
+ inputs and results embedded in it arrive base64-encoded. Scalars and container overhead are
+ charged flat rates rather than measured: the figure only has to be good enough to stop a run of
+ multi-megabyte events from sitting in the queue at once, and an exact walk would cost more than
+ the bound saves.
+ """
+ if isinstance(value, str | bytes | bytearray):
+ return len(value)
+ if isinstance(value, dict):
+ return _CONTAINER_SIZE_BYTES + sum(
+ (len(key) if isinstance(key, str) else _SCALAR_SIZE_BYTES) + _estimate_size_bytes(item)
+ for key, item in value.items()
+ )
+ if isinstance(value, list | tuple):
+ return _CONTAINER_SIZE_BYTES + sum(_estimate_size_bytes(item) for item in value)
+ return _SCALAR_SIZE_BYTES
+
+
+class _ByteBudget:
+ """Admission control for the hand-off queue, bounded by the bytes its items hold.
+
+ An item count alone does not bound memory here. Temporal embeds workflow inputs and results in
+ history events, so a run of large events pins far more than a run of small ones for the same
+ queue depth. Producers reserve before enqueuing and consumers release after yielding, so the
+ bytes in flight stay under `max_bytes` whatever the item size.
+ """
+
+ def __init__(self, max_bytes: int) -> None:
+ self._max_bytes = max_bytes
+ self._in_flight = 0
+ self._condition = threading.Condition()
+
+ def _admits(self, size: int) -> bool:
+ # An empty budget admits anything, so a single item larger than the cap moves through on its
+ # own instead of deadlocking the producer against a bound it could never satisfy.
+ return self._in_flight == 0 or self._in_flight + size <= self._max_bytes
+
+ def reserve(self, size: int) -> None:
+ with self._condition:
+ while not self._admits(size):
+ self._condition.wait()
+ self._in_flight += size
+
+ def release(self, size: int) -> None:
+ with self._condition:
+ # Deliberately unclamped. Every release matches a reserve of the same size, so the total
+ # returns to zero once a stream drains; clamping at zero would hide an unbalanced pair
+ # (which silently widens the bound) instead of leaving it visible.
+ self._in_flight -= size
+ self._condition.notify_all()
+
+ @property
+ def in_flight_bytes(self) -> int:
+ with self._condition:
+ return self._in_flight
+
+
+def _async_iter_to_sync(async_iter, max_items: int = _QUEUE_MAX_ITEMS, max_bytes: int = _QUEUE_MAX_BYTES):
+ q: Queue[tuple[Any, int]] = Queue(maxsize=max_items)
+ budget = _ByteBudget(max_bytes)
sentinel = object()
class _Error:
@@ -125,14 +197,16 @@ def _async_iter_to_sync(async_iter):
async def runner():
try:
async for item in async_iter:
- q.put(item)
+ size = _estimate_size_bytes(item)
+ budget.reserve(size)
+ q.put((item, size))
# The runner lives on a daemon thread, so an uncaught exception would
# terminate silently and the consumer below would see only the sentinel.
# Forward it through the queue so the caller can re-raise it.
except BaseException as exc:
- q.put(_Error(exc))
+ q.put((_Error(exc), 0))
finally:
- q.put(sentinel)
+ q.put((sentinel, 0))
def run_event_loop():
asyncio.run(runner())
@@ -140,7 +214,7 @@ def _async_iter_to_sync(async_iter):
threading.Thread(target=run_event_loop, daemon=True).start()
while True:
- item = q.get()
+ item, size = q.get()
if item is sentinel:
q.task_done()
break
@@ -148,8 +222,13 @@ def _async_iter_to_sync(async_iter):
q.task_done()
raise item.exc
- yield item
- q.task_done()
+ try:
+ yield item
+ finally:
+ # Release once the consumer is done with the item, not when it leaves the queue, so the
+ # bound covers what the pipeline still holds rather than only what is waiting.
+ budget.release(size)
+ q.task_done()
def _sanitize(obj):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
index 629ac907683b..0e62d1261d96 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
@@ -11,7 +11,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio.source import TemporalIOSource
from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio.temporalio import (
+ _CONTAINER_SIZE_BYTES,
+ _SCALAR_SIZE_BYTES,
FakeSettings,
+ _async_iter_to_sync,
+ _ByteBudget,
+ _estimate_size_bytes,
_get_temporal_client,
_with_transient_rpc_retry,
)
@@ -188,3 +193,102 @@ class TestTransientRPCRetry:
await _with_transient_rpc_retry(operation, MagicMock())
assert sleep.await_count == 0
+
+
+class TestEstimateSizeBytes:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ ("abcd", 4),
+ (b"abcd", 4),
+ (True, _SCALAR_SIZE_BYTES),
+ (None, _SCALAR_SIZE_BYTES),
+ (12345, _SCALAR_SIZE_BYTES),
+ ({}, _CONTAINER_SIZE_BYTES),
+ ([], _CONTAINER_SIZE_BYTES),
+ ({"ab": "cdef"}, _CONTAINER_SIZE_BYTES + 2 + 4),
+ (["ab", "cd"], _CONTAINER_SIZE_BYTES + 2 + 2),
+ ],
+ )
+ def test_measures_value(self, value, expected):
+ assert _estimate_size_bytes(value) == expected
+
+ def test_counts_strings_nested_below_the_top_level(self):
+ payload = "x" * 10_000
+ nested = {"events": [{"input": {"payload": payload}}]}
+
+ assert _estimate_size_bytes(nested) >= len(payload)
+
+
+class TestByteBudget:
+ @pytest.mark.parametrize(
+ "reserve_first,size,expected",
+ [
+ # An empty budget admits an item larger than the cap. Without this the producer waits on
+ # a bound it can never satisfy and the whole sync hangs.
+ (0, 5000, True),
+ (0, 10, True),
+ (40, 60, True),
+ (40, 61, False),
+ ],
+ )
+ def test_admits(self, reserve_first, size, expected):
+ budget = _ByteBudget(max_bytes=100)
+ if reserve_first:
+ budget.reserve(reserve_first)
+
+ assert budget._admits(size) is expected
+
+ def test_release_frees_capacity_for_a_blocked_item(self):
+ budget = _ByteBudget(max_bytes=100)
+ budget.reserve(100)
+ assert budget._admits(100) is False
+
+ budget.release(100)
+
+ assert budget.in_flight_bytes == 0
+ assert budget._admits(100) is True
+
+
+class TestAsyncIterToSync:
+ @staticmethod
+ async def _aiter(items):
+ for item in items:
+ yield item
+
+ def test_delivers_every_item_in_order(self):
+ items = [{"id": index} for index in range(50)]
+
+ assert list(_async_iter_to_sync(self._aiter(items))) == items
+
+ def test_propagates_a_producer_exception_to_the_consumer(self):
+ async def failing():
+ yield {"id": 1}
+ raise RuntimeError("boom")
+
+ stream = _async_iter_to_sync(failing())
+
+ assert next(stream) == {"id": 1}
+ with pytest.raises(RuntimeError, match="boom"):
+ next(stream)
+
+ def test_reserves_and_releases_stay_balanced(self):
+ # Catches both halves of the accounting. A reservation the consumer never releases leaks
+ # until the producer blocks on a budget that only fills; an item enqueued without reserving
+ # never counts against the cap at all, which is the unbounded behavior this bound replaced.
+ budgets = []
+
+ def _record(max_bytes):
+ budgets.append(_ByteBudget(max_bytes))
+ return budgets[-1]
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.temporalio.temporalio._ByteBudget",
+ side_effect=_record,
+ ):
+ # A cap every item fits under, so a missing release surfaces as leftover in-flight bytes
+ # rather than a producer that blocks and hangs the test.
+ items = [{"payload": "x" * 100} for _ in range(10)]
+ assert list(_async_iter_to_sync(self._aiter(items), max_bytes=100_000)) == items
+
+ assert budgets[0].in_flight_bytes == 0