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(eng-analytics): bound slow ownership reads (#102586)

Raúl Negrón-Otero958388edf2bc
diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.py
index 1e6433d238b0..6bd7dd090d19 100644
--- a/products/engineering_analytics/backend/logic/ownership.py
+++ b/products/engineering_analytics/backend/logic/ownership.py
@@ -168,6 +168,12 @@ class GitHubRepoFiles:
raise OwnershipUnavailable(too_large)
body = bytearray()
for chunk in response.iter_content(chunk_size=8192):
+ # The request timeout starts again on every chunk received, so a host that sends the body
+ # slowly enough holds this read for as long as the byte limit allows. _fetch_all stops
+ # waiting for a fetch at the deadline, so the fetch stops at the first chunk after it,
+ # which the request timeout puts within _TIMEOUT_SECONDS of the deadline.
+ if monotonic() > self._deadline:
+ raise OwnershipUnavailable(f"reading {path} from {self.repository} passed the resolution budget")
body.extend(chunk)
if len(body) > _MAX_FILE_BYTES:
raise OwnershipUnavailable(too_large)
@@ -281,17 +287,17 @@ def _fetch_all(fetch: Callable[[str], _T], paths: Iterable[str], deadline: float
todo = list(dict.fromkeys(paths))
if not todo:
return {}
- with ThreadPoolExecutor(max_workers=min(_FETCH_WORKERS, len(todo))) as pool:
+ pool = ThreadPoolExecutor(max_workers=min(_FETCH_WORKERS, len(todo)))
+ try:
futures = {path: pool.submit(fetch, path) for path in todo}
- try:
- return {path: future.result(max(deadline - monotonic(), 0)) for path, future in futures.items()}
- except TimeoutError as e:
- pool.shutdown(cancel_futures=True)
- raise OwnershipUnavailable(f"ownership took longer than {_RESOLVE_BUDGET_SECONDS}s") from e
- except Exception:
- # The batch is already lost, so drop the rest instead of holding the request thread.
- pool.shutdown(cancel_futures=True)
- raise
+ return {path: future.result(max(deadline - monotonic(), 0)) for path, future in futures.items()}
+ except TimeoutError as e:
+ raise OwnershipUnavailable(f"ownership took longer than {_RESOLVE_BUDGET_SECONDS}s") from e
+ finally:
+ # Not a `with` block: its exit waits for every running fetch, which holds the request thread
+ # past the deadline. A lost batch drops the queued fetches and leaves the running ones to
+ # stop at the same deadline on their own, which the read in _capped_text enforces.
+ pool.shutdown(wait=False, cancel_futures=True)
def _candidate_paths(test: QuarantinedTestFile) -> list[str]:
diff --git a/products/engineering_analytics/backend/tests/test_ownership.py b/products/engineering_analytics/backend/tests/test_ownership.py
index b4d3b0bc5424..4d07921900ec 100644
--- a/products/engineering_analytics/backend/tests/test_ownership.py
+++ b/products/engineering_analytics/backend/tests/test_ownership.py
@@ -1,6 +1,7 @@
from collections.abc import Iterator
from dataclasses import field
-from time import monotonic, sleep
+from threading import Event
+from time import monotonic
from unittest.mock import patch
@@ -180,13 +181,47 @@ class TestGitHubRepoFiles(SimpleTestCase):
def test_a_slow_repository_gives_up_instead_of_holding_the_worker(self) -> None:
# A cold board asks for hundreds of files. Without a budget for the whole resolution, a
# stalled raw host holds a web worker far past the per-request timeout.
- def never_returns(_method: str, _url: str, **_kwargs: object) -> object:
- sleep(2)
- raise AssertionError("unreachable")
-
- with patch("products.engineering_analytics.backend.logic.ownership.github_request", side_effect=never_returns):
- files = GitHubRepoFiles("PostHog/posthog")
- files._deadline = monotonic()
+ started, release, finished = Event(), Event(), Event()
+ self.addCleanup(release.set)
+
+ def stalls(_method: str, _url: str, **_kwargs: object) -> _response:
+ started.set()
+ release.wait(timeout=10)
+ finished.set()
+ return _response(404)
+
+ files = GitHubRepoFiles("PostHog/posthog")
+
+ def at_the_deadline_once_the_fetch_runs() -> float:
+ assert started.wait(timeout=10)
+ return files._deadline
+
+ with (
+ patch("products.engineering_analytics.backend.logic.ownership.github_request", side_effect=stalls),
+ patch(
+ "products.engineering_analytics.backend.logic.ownership.monotonic",
+ side_effect=at_the_deadline_once_the_fetch_runs,
+ ),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ files.read("owners.yaml")
+ assert not finished.is_set()
+
+ def test_a_file_that_arrives_too_slowly_is_refused(self) -> None:
+ # The per-request timeout starts again on each chunk, so the byte limit alone lets one read
+ # run for minutes. Nothing waits for the fetch after the deadline, so nothing else stops it.
+ files = GitHubRepoFiles("PostHog/posthog")
+ response = _response(200)
+
+ def expires_mid_body(chunk_size: int) -> Iterator[bytes]:
+ yield b"x" * chunk_size
+ files._deadline = monotonic() - 1
+ yield b"x" * chunk_size
+
+ with (
+ patch("products.engineering_analytics.backend.logic.ownership.github_request", return_value=response),
+ patch.object(response, "iter_content", expires_mid_body),
+ ):
with self.assertRaises(OwnershipUnavailable):
files.read("owners.yaml")