: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(replay-vision): stop the network read refusing the median recording (#102468)
Tue Haulundbecb3a89c279
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_network.py b/products/replay_vision/backend/temporal/activities/fetch_session_network.pyindex 325e457fb268..4ea0499c9d94 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_network.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_network.py@@ -1,5 +1,6 @@"""Fetch a session's captured network requests from the recording blocks and stash them in Redis."""+import timeimport asyncioimport structlog@@ -27,16 +28,23 @@ logger = structlog.get_logger(__name__)# load to the recording API._BLOCK_CONCURRENCY = 4-# Gate on the listing's compressed bytes the way the rasterizer does-# (`maxRecordingCompressedBytes` in nodejs/src/session-replay/recording-rasterizer/config.ts), because a-# block count bounds neither the read nor the memory it needs. Set well below the rasterizer's 512 MiB:-# this is a side input, so an outlier is worth skipping rather than straining the worker for.-_MAX_COMPRESSED_BYTES = 64 * 1024 * 1024+# Matches the rasterizer's `maxRecordingCompressedBytes`+# (nodejs/src/session-replay/recording-rasterizer/config.ts), which is sized against real recordings. A+# lower figure here skipped the median recording: on 2026-09-17 the skipped sessions had a median of 88+# MiB compressed and a 95th percentile of 380 MiB.+_MAX_COMPRESSED_BYTES = 512 * 1024 * 1024-# Bytes alone do not bound the number of requests: many small blocks stay under the byte budget while-# still issuing a fetch each. The activity's own timeout is enforced from outside, so it would abort the-# scan rather than degrade it.-_MAX_BLOCKS = 250+# What the read is really bounded by. Memory is already bounded by the batch, so the risk of a long+# listing is the activity's own 2 minute timeout, which the server enforces from outside and which no+# block count predicts. Stop at the deadline and report what was read instead of refusing the session.+# The deadline bounds the batch in flight as well as the next one: a request carries its own 30 second+# timeout, so checking only between batches would let the read run to 90 seconds.+_READ_BUDGET_SECONDS = 60.0++# Bytes allowed in flight at once. Concurrency alone does not bound memory, because a block can be large:+# on 2026-09-17 the median recording averaged 368 KiB per block, the 95th percentile 2 MiB, and the worst+# 37 MiB. Four of those decompressed together would threaten the worker's memory limit.+_MAX_BATCH_COMPRESSED_BYTES = 16 * 1024 * 1024@activity.defn@@ -92,7 +100,7 @@ async def _load_payload(team_id: int, session_id: str) -> SessionNetworkPayload:return SessionNetworkPayload()compressed_bytes = sum(max(0, block.end_byte - block.start_byte) for block in blocks)- if len(blocks) > _MAX_BLOCKS or compressed_bytes > _MAX_COMPRESSED_BYTES:+ if compressed_bytes > _MAX_COMPRESSED_BYTES:logger.info("replay_vision.fetch_network.skipped_large_recording",session_id=session_id,@@ -111,6 +119,33 @@ def _build_recording(team_id: int, session_id: str) -> SessionRecording:return SessionRecording(session_id=session_id, team_id=team_id)+def _next_batch(blocks: list[RecordingBlock], start: int) -> list[RecordingBlock]:+ """The blocks to fetch together: at most `_BLOCK_CONCURRENCY`, and at most `_MAX_BATCH_COMPRESSED_BYTES`.++ A single block larger than the byte budget goes on its own rather than being skipped, so a recording+ with one huge block is still read.+ """+ batch: list[RecordingBlock] = []+ total = 0+ for block in blocks[start : start + _BLOCK_CONCURRENCY]:+ size = max(0, block.end_byte - block.start_byte)+ if batch and total + size > _MAX_BATCH_COMPRESSED_BYTES:+ break+ batch.append(block)+ total += size+ return batch+++def _log_budget_spent(session_id: str, team_id: int, blocks_read: int, block_count: int) -> None:+ logger.info(+ "replay_vision.fetch_network.read_budget_spent",+ session_id=session_id,+ team_id=team_id,+ blocks_read=blocks_read,+ block_count=block_count,+ )++async def _collect(blocks: list[RecordingBlock], *, session_id: str, team_id: int) -> SessionNetworkPayload:"""Fetch the blocks a batch at a time and decode each batch before fetching the next.@@ -122,6 +157,7 @@ async def _collect(blocks: list[RecordingBlock], *, session_id: str, team_id: in"""collector = NetworkCollector()partial = False+ deadline = time.monotonic() + _READ_BUDGET_SECONDSasync with recording_api_client() as client:@@ -145,13 +181,38 @@ async def _collect(blocks: list[RecordingBlock], *, session_id: str, team_id: inreturn Nonereturn content.decode("utf-8", errors="replace").splitlines()- for start in range(0, len(blocks), _BLOCK_CONCURRENCY):- batch = blocks[start : start + _BLOCK_CONCURRENCY]- for block_lines in await asyncio.gather(*(fetch(block) for block in batch)):+ index = 0+ while index < len(blocks):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ partial = True+ _log_budget_spent(session_id, team_id, index, len(blocks))+ break+ batch = _next_batch(blocks, index)+ index += len(batch)+ tasks = [asyncio.create_task(fetch(block)) for block in batch]+ # `wait` rather than `wait_for`: a timeout must not discard the blocks of this batch that+ # already came back, which is the partial result the caller is promised.+ done, pending = await asyncio.wait(tasks, timeout=remaining)+ for task in pending:+ task.cancel()+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ # Batch order, not completion order, so the same recording yields the same payload.+ for task in tasks:+ if task not in done:+ continue+ block_lines = task.result()if block_lines is None:partial = Truecontinuecollector.feed(block_lines)+ if pending:+ # Out of time mid-batch. What was read still helps; `partial` stops the scan reading the+ # rest of the session as "nothing failed here".+ partial = True+ _log_budget_spent(session_id, team_id, index - len(batch), len(blocks))+ breakif collector.full:breakdiff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex cd36fb27ae6f..7499ef23dcb6 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1,7 +1,10 @@+import jsonimport timeimport uuid+import asyncioimport datetime as dtimport threading+import contextlibfrom typing import Anyimport pytest@@ -36,6 +39,7 @@ from posthog.models import Organization, Teamfrom posthog.models.user import Userfrom posthog.redis import get_async_clientfrom posthog.session_recordings.queries.session_replay_events import SessionEventsPage, SessionReplayEvents+from posthog.session_recordings.session_recording_v2_service import RecordingBlockfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.api.observation_progress import stream_observation_progress@@ -104,6 +108,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants impoREDIS_INDEX_KEY as _GEMINI_REDIS_INDEX_KEY,REDIS_KEY_PREFIX as _GEMINI_REDIS_KEY_PREFIX,)+from products.replay_vision.backend.temporal.network_capture import SessionNetworkPayloadfrom products.replay_vision.backend.temporal.scanners.base import ChipSegment, Segment, SignalFinding, TextSegmentfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput, ClassifierScannerfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput, MonitorScanner@@ -2328,6 +2333,144 @@ class TestFetchSessionNetworkActivity:assert exc_info.value.non_retryable is Trueassert "RECORDING_API_URL" in str(exc_info.value)+ @pytest.mark.asyncio+ async def test_a_long_block_listing_is_read_not_refused(self) -> None:+ # A block count gate refused the median recording: real sessions run to hundreds of blocks. Only+ # the compressed size refuses a session now, and the read itself is bounded by its own deadline.+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod++ blocks = [+ RecordingBlock(key=f"k{i}", start_byte=0, end_byte=1024, start_timestamp="", end_timestamp="")+ for i in range(700)+ ]+ with (+ patch.object(mod, "list_blocks_async", AsyncMock(return_value=blocks)),+ patch.object(mod, "_collect", AsyncMock(return_value=SessionNetworkPayload(captured=True))) as collect,+ ):+ payload = await mod._load_payload(team_id=1, session_id="sess-1")++ assert collect.await_count == 1, "a 700-block listing must still be read"+ assert payload.captured is True++ @pytest.mark.asyncio+ async def test_a_stalled_block_cannot_outlive_the_read_budget(self) -> None:+ # A request carries its own 30s timeout, so a deadline checked only between batches lets the read+ # run far past its budget and can spend the activity's whole timeout before anything is stored.+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod++ blocks = [+ RecordingBlock(key=f"k{i}", start_byte=0, end_byte=16, start_timestamp="", end_timestamp="")+ for i in range(8)+ ]++ class _StalledClient:+ async def fetch_block(self, *args: Any, **kwargs: Any) -> bytes:+ await asyncio.sleep(30)+ return b""++ @contextlib.asynccontextmanager+ async def _client(*args: Any, **kwargs: Any) -> Any:+ yield _StalledClient()++ started = time.monotonic()+ with (+ patch.object(mod, "recording_api_client", _client),+ patch.object(mod, "_READ_BUDGET_SECONDS", 0.2),+ ):+ payload = await mod._collect(blocks, session_id="sess-1", team_id=1)+ elapsed = time.monotonic() - started++ assert elapsed < 5, f"the read ran {elapsed:.1f}s past a 0.2s budget"+ assert payload.partial is True+ assert payload.captured is False++ @pytest.mark.asyncio+ async def test_a_stalled_block_does_not_discard_its_finished_siblings(self) -> None:+ # Cancelling the batch on timeout must not throw away the blocks that already came back: those+ # requests are the partial result the scan is promised.+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod++ fast = json.dumps(+ {+ "window_id": "w1",+ "data": [+ {+ "type": 6,+ "timestamp": 1000,+ "data": {+ "plugin": "rrweb/network@1",+ "payload": {"requests": [{"name": "https://app.test/boom", "status": 500}]},+ },+ }+ ],+ }+ ).encode()++ class _OneFastOneStalled:+ def __init__(self) -> None:+ self.served = 0++ async def fetch_block(self, key: str, *args: Any, **kwargs: Any) -> bytes:+ if key == "fast":+ self.served += 1+ return fast+ await asyncio.sleep(30)+ return b""++ @contextlib.asynccontextmanager+ async def _client(*args: Any, **kwargs: Any) -> Any:+ yield _OneFastOneStalled()++ blocks = [+ RecordingBlock(key="fast", start_byte=0, end_byte=16, start_timestamp="", end_timestamp=""),+ RecordingBlock(key="stalled", start_byte=0, end_byte=16, start_timestamp="", end_timestamp=""),+ ]+ with (+ patch.object(mod, "recording_api_client", _client),+ patch.object(mod, "_READ_BUDGET_SECONDS", 0.3),+ ):+ payload = await mod._collect(blocks, session_id="sess-1", team_id=1)++ assert payload.partial is True+ assert [r.url for r in payload.requests] == ["https://app.test/boom"], "the finished block was lost"++ def test_a_batch_is_bounded_by_bytes_not_only_by_count(self) -> None:+ # Concurrency alone does not bound memory: blocks reach tens of MiB, and four decompressed at+ # once would threaten the worker's limit.+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod++ def block(size: int) -> RecordingBlock:+ return RecordingBlock(key="k", start_byte=0, end_byte=size, start_timestamp="", end_timestamp="")++ small = [block(1024) for _ in range(8)]+ assert len(mod._next_batch(small, 0)) == mod._BLOCK_CONCURRENCY++ large = [block(mod._MAX_BATCH_COMPRESSED_BYTES) for _ in range(4)]+ assert len(mod._next_batch(large, 0)) == 1, "one oversized block must not ride with three others"++ # A block bigger than the whole budget still gets read, on its own.+ assert len(mod._next_batch([block(mod._MAX_BATCH_COMPRESSED_BYTES * 4)], 0)) == 1++ @pytest.mark.asyncio+ async def test_a_listing_over_the_size_ceiling_is_refused(self) -> None:+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod++ huge = [+ RecordingBlock(+ key="k", start_byte=0, end_byte=mod._MAX_COMPRESSED_BYTES + 1, start_timestamp="", end_timestamp=""+ )+ ]+ with (+ patch.object(mod, "list_blocks_async", AsyncMock(return_value=huge)),+ patch.object(mod, "_collect", AsyncMock()) as collect,+ ):+ payload = await mod._load_payload(team_id=1, session_id="sess-1")++ assert collect.await_count == 0+ # Not "clean": a session never read cannot show that nothing failed.+ assert payload.partial is True+ assert payload.captured is False+@pytest.mark.django_db(transaction=True)class TestEnsureSessionAssetActivity: