: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
feat(devex): reuse ownership cache entries across unrelated head commits (#105034)
Julian Bez34c6c28e597b
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.mdindex 6c2388ee9052..500947156469 100644--- a/posthog/egress/github/README.md+++ b/posthog/egress/github/README.md@@ -27,7 +27,7 @@ Deferrable background callers construct their client on the `BATCH` lane (`GitHuA shed sweep stops for the cycle and resumes on the next scheduled run.A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them. Customer Analytics feature-request link and resume lookups also run on `NORMAL` because an editor waits for the current issue state. Signals refreshes the stored pull request review decision from GitHub webhooks on `BATCH`; the inbox can keep the last known value when the lane is shed and update it after a retry.-The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does.+The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does, and so does the one compare call per new head commit that lets it reuse cached files.The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.diff --git a/posthog/ownership/README.md b/posthog/ownership/README.mdindex eb847ff5ebc6..6a30f8292c75 100644--- a/posthog/ownership/README.md+++ b/posthog/ownership/README.md@@ -48,6 +48,11 @@ It reads at the ref `HEAD` rather than at a commit, because it has no credentialThe authenticated reader caches per commit.The content at a commit never changes, so a blob is held for a day; the head lookup is held for about two minutes, and that is the whole staleness window of an ownership change.+A busy repository moves its head between most reads, and each new commit starts with no entries.+So a reader that sees a new head records the head it replaced, and the first miss at the new commit asks GitHub's compare API which paths changed between the two.+Entries for the other paths are copied from the previous commit, and only the changed paths are read again.+The copy happens only when the compare proves it: the new head descends from the old one, and GitHub listed every changed file, renames included.+Any other answer, or a failed compare, falls back to a full read.The cache key names the credential's audience, an installation or a digest of a token, because a private repository one installation can read is not readable by the next caller that names the same repository.A token never reaches a cache key or a log line.Pass `fresh_head=True` when the run derives a decision it never stores and so cannot correct later, such as digest routing, and the reader asks GitHub for the head instead of reading that shared entry.diff --git a/posthog/ownership/github_files.py b/posthog/ownership/github_files.pyindex 470b026a84b0..e07a4b4beec9 100644--- a/posthog/ownership/github_files.py+++ b/posthog/ownership/github_files.py@@ -12,7 +12,7 @@ the ref `HEAD` and keeps its own cache and its own six-hour staleness window.import jsonfrom collections.abc import Callable, Sequence-from functools import partial+from functools import cached_property, partialfrom http import HTTPStatusfrom typing import Any@@ -25,13 +25,16 @@ from posthog.egress.observability.observability import scope_fingerprintfrom posthog.egress.transport.transport import EgressBudgetExhaustedfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, Integration-from posthog.models.integration.github import _is_safe_github_repo_path+from posthog.models.integration.github import _is_safe_github_repo_path, _is_safe_github_shafrom posthog.ownership.repo_files import (_ABSENT,_MAX_FILE_BYTES,CachedRepoFiles,GitHubRepoFiles,OwnershipUnavailable,+ ResponseTooLarge,+ _cache_set_many,+ _cached_by_path,_fetch_all,capped_text,pooled_session,@@ -47,6 +50,7 @@ _GRAPHQL_URL = f"{_API_HOST}/graphql"EGRESS_SOURCE = "ownership_github_api"_HEAD_ENDPOINT = "/graphql:ownershipHeadCommit"_FILES_ENDPOINT = "/graphql:ownershipFiles"+_COMPARE_ENDPOINT = "/repos/{owner}/{repo}/compare/{basehead}"_TIMEOUT_SECONDS = 10.0# GitHub charges one rate-limit point for a whole aliased query, so the files of a batch cost one@@ -54,6 +58,8 @@ _TIMEOUT_SECONDS = 10.0# hundred files in a few seconds and refuses four hundred with a 502._CHUNK_FILES = 100+# Unchanged entries are copied from one commit to the next, so an entry can outlive the code that+# wrote it by any number of commits. A change to what an entry means must change this prefix._CACHE_PREFIX = "ownership:github_api"# A commit's content is immutable, so the TTL only releases memory. Nothing reads a commit's entries# after the head moves past it, so a longer TTL only keeps dead keys in the shared cache.@@ -74,6 +80,11 @@ _NO_COVERING_INTEGRATION = 0# file is a few kilobytes, so a whole chunk of them is tens of kilobytes; this leaves that room many# times over and still bounds what one answer can cost._MAX_RESPONSE_BYTES = 4 * 1024 * 1024+# GitHub lists at most this many changed files for a whole comparison and pages no further, so a+# list this long can hide a changed ownership file.+_MAX_COMPARE_FILES = 300+# A compare that cannot prove reuse gives the same answer for the same two commits every time.+_UNPROVABLE = "unprovable"_HEAD_QUERY = """query($owner: String!, $name: String!) {@@ -199,7 +210,7 @@ class GitHubFilesFetcher:self._priority = priorityself._session = pooled_session(_API_HOST)- def head_commit_sha(self, repository: str) -> str | None:+ def head_commit_sha(self, repository: str, deadline: float | None = None) -> str | None:"""The commit at the head of the repository's default branch, or None when there is none.A repository with no commits has no default branch, and GitHub answers that with a null@@ -207,7 +218,7 @@ class GitHubFilesFetcher:an unreadable one: a caller that fails it instead would take down every repository it readsbeside this one."""- field = self._graphql(repository, _HEAD_QUERY, {}, endpoint=_HEAD_ENDPOINT)+ field = self._graphql(repository, _HEAD_QUERY, {}, endpoint=_HEAD_ENDPOINT, deadline=deadline)ref = field.get("defaultBranchRef")if ref is None:return None@@ -228,6 +239,47 @@ class GitHubFilesFetcher:repository, sha, paths, deadline, _EXISTS_SELECTION, lambda _path, entry: _is_blob(entry))+ def changed_paths(self, repository: str, base: str, head: str, deadline: float) -> frozenset[str] | None:+ """Every path that a change between the two commits added, removed, modified or renamed.++ None means the answer cannot prove that the other paths are unchanged: ``head`` does not+ descend from ``base`` (a force-push or a rewind), GitHub cut the file list short, or the+ answer is too large to read.+ """+ if not (_is_safe_github_repo_path(repository) and _is_safe_github_sha(base) and _is_safe_github_sha(head)):+ raise OwnershipUnavailable(f"unsafe compare for {repository!r}: {base!r}...{head!r}")+ try:+ status, body = self._answer(+ repository,+ "GET",+ f"{_API_HOST}/repos/{repository}/compare/{base}...{head}",+ endpoint=_COMPARE_ENDPOINT,+ deadline=deadline,+ # The file list comes on the first page whatever the page size, and the commits are not needed.+ params={"per_page": 1},+ )+ except ResponseTooLarge:+ # The body carries each file's patch, so a merge that changes a lockfile can pass the cap.+ return None+ if status != HTTPStatus.OK or not isinstance(body, dict):+ raise OwnershipUnavailable(f"{repository} answered {status} for {_COMPARE_ENDPOINT}")+ merge_base = body.get("merge_base_commit")+ if body.get("status") not in ("ahead", "identical") or not isinstance(merge_base, dict):+ return None+ if merge_base.get("sha") != base:+ return None+ files = body.get("files")+ if not isinstance(files, list) or len(files) >= _MAX_COMPARE_FILES:+ return None+ changed: set[str] = set()+ for file in files:+ if not isinstance(file, dict) or not isinstance(file.get("filename"), str):+ return None+ changed.add(file["filename"])+ if isinstance(file.get("previous_filename"), str):+ changed.add(file["previous_filename"])+ return frozenset(changed)+def _text(self, path: str, entry: dict[str, Any] | None) -> str:if entry is None:return _ABSENT@@ -284,12 +336,16 @@ class GitHubFilesFetcher:raise OwnershipUnavailable(f"unsafe repository path: {repository!r}")owner, name = repository.split("/", 1)payload = {"query": query, "variables": {"owner": owner, "name": name, **variables}}- status, body = self._answer(repository, payload, endpoint=endpoint, deadline=deadline)+ status, body = self._answer(+ repository, "POST", _GRAPHQL_URL, endpoint=endpoint, deadline=deadline, json=payload+ )if status == HTTPStatus.UNAUTHORIZED and self._refresh is not None:# The token was revoked or rotated under the batch, and it stays memoized, so every# later read would fail with it too. A 401 means nothing ran, so the retry is safe.self._refresh_token(repository)- status, body = self._answer(repository, payload, endpoint=endpoint, deadline=deadline)+ status, body = self._answer(+ repository, "POST", _GRAPHQL_URL, endpoint=endpoint, deadline=deadline, json=payload+ )if status != HTTPStatus.OK:raise OwnershipUnavailable(f"{repository} answered {status} for {endpoint}")errors = body.get("errors") if isinstance(body, dict) else None@@ -306,11 +362,11 @@ class GitHubFilesFetcher:return fielddef _answer(- self, repository: str, payload: dict[str, Any], *, endpoint: str, deadline: float | None+ self, repository: str, method: str, url: str, *, endpoint: str, deadline: float | None, **kwargs: Any) -> tuple[int, Any]:- """One POST's status and decoded body, read under the response cap and closed before it+ """One request's status and decoded body, read under the response cap and closed before itreturns."""- with self._post(repository, payload, endpoint=endpoint) as response:+ with self._send(repository, method, url, endpoint=endpoint, **kwargs) as response:if response.status_code != HTTPStatus.OK:return response.status_code, Nonetext = capped_text(@@ -324,21 +380,21 @@ class GitHubFilesFetcher:except ValueError as e:raise OwnershipUnavailable(f"{repository} answered with no JSON for {endpoint}") from e- def _post(self, repository: str, payload: dict[str, Any], *, endpoint: str) -> requests.Response:+ def _send(self, repository: str, method: str, url: str, *, endpoint: str, **kwargs: Any) -> requests.Response:try:response = github_request(- "POST",- _GRAPHQL_URL,+ method,+ url,source=EGRESS_SOURCE,headers={"Authorization": f"Bearer {self._token_value()}"},installation_id=self._installation_id,priority=self._priority,endpoint=endpoint,- json=payload,timeout=_TIMEOUT_SECONDS,session=self._session,# The body is read under a cap in _answer, so it must not be buffered whole first.stream=True,+ **kwargs,)# A rate limit answers 403 or 429, which would otherwise read as a plain refusal. It is# still fail-closed, but the failure says which of the two it was.@@ -371,46 +427,96 @@ class AuthenticatedRepoFiles(CachedRepoFiles):``fresh_head`` asks GitHub for the head on this run rather than reading the shared head cache,for a caller that derives a decision it never stores and so cannot correct later. It stillwrites the head cache, and blob reads stay cached because content at a commit never changes.++ A busy repository moves its head between most reads, and a new commit starts with an empty+ cache. So a reader that sees a new head records the head it replaced, and a miss at the new+ commit asks GitHub once which paths changed between the two. An entry for a path that did not+ change is copied from the previous commit instead of read again."""def __init__(self, repository: str, fetcher: GitHubFilesFetcher, *, fresh_head: bool = False) -> None:super().__init__(repository)self._fetcher = fetcherself._fresh_head = fresh_head- self._sha: str | None = None-- def _head_commit_sha(self) -> str | None:- if self._sha is None:- key = f"{_CACHE_PREFIX}:head:{self._fetcher.audience}:{self.repository}"- cached = None if self._fresh_head else get_safe_cache(key)- if isinstance(cached, str) and cached:- self._sha = cached- else:- self._sha = self._fetcher.head_commit_sha(self.repository)- if self._sha is not None:- safe_cache_set(key, self._sha, _HEAD_CACHE_TTL_SECONDS)- return self._sha++ def _scoped_key(self, kind: str) -> str:+ return f"{_CACHE_PREFIX}:{kind}:{self._fetcher.audience}:{self.repository}"++ def _key_at(self, kind: str, path: str, sha: str) -> str:+ return f"{self._scoped_key(kind)}:{sha}:{path}"++ def _remember_head(self, sha: str) -> None:+ # The head entry expires within minutes, so the head it replaced lives in an entry of its+ # own, as long as the entries it would let a new commit reuse.+ last = get_safe_cache(self._scoped_key("last_head"))+ remembered = {self._scoped_key("last_head"): sha}+ if isinstance(last, str) and last and last != sha:+ remembered[f"{self._scoped_key('previous')}:{sha}"] = last+ _cache_set_many(remembered, _BLOB_CACHE_TTL_SECONDS)+ safe_cache_set(self._scoped_key("head"), sha, _HEAD_CACHE_TTL_SECONDS)++ @cached_property+ def _head_sha(self) -> str | None:+ cached = None if self._fresh_head else get_safe_cache(self._scoped_key("head"))+ if isinstance(cached, str) and cached:+ return cached+ sha = self._fetcher.head_commit_sha(self.repository, self._deadline)+ if sha is not None:+ self._remember_head(sha)+ return shadef _commit(self) -> str:- sha = self._head_commit_sha()- if sha is None:+ if self._head_sha is None:raise OwnershipUnavailable(f"{self.repository} has no commits")- return sha+ return self._head_shadef _cache_key(self, kind: str, path: str) -> str:- return f"{_CACHE_PREFIX}:{kind}:{self._fetcher.audience}:{self.repository}:{self._commit()}:{path}"+ return self._key_at(kind, path, self._commit())def _cache_ttl(self) -> int:return _BLOB_CACHE_TTL_SECONDS+ @cached_property+ def _unchanged_since_previous_head(self) -> tuple[str, frozenset[str]] | None:+ """The previous head and the paths changed since it, or None when no entry can be reused."""+ sha = self._commit()+ previous = get_safe_cache(f"{self._scoped_key('previous')}:{sha}")+ if not isinstance(previous, str) or not previous:+ return None+ key = f"{self._scoped_key('changed')}:{previous}:{sha}"+ cached = get_safe_cache(key)+ if cached == _UNPROVABLE:+ return None+ if isinstance(cached, list):+ return previous, frozenset(cached)+ try:+ changed = self._fetcher.changed_paths(self.repository, previous, sha, self._deadline)+ except OwnershipUnavailable:+ # A failed compare only costs the reuse. The full read that follows fails closed on its own.+ logger.warning("ownership_compare_unavailable", repository=self.repository, exc_info=True)+ return None+ safe_cache_set(key, _UNPROVABLE if changed is None else sorted(changed), _BLOB_CACHE_TTL_SECONDS)+ return None if changed is None else (previous, changed)++ def _reuse_unchanged(self, kind: str, paths: list[str]) -> dict[str, Any]:+ """The previous head's entries for the paths that did not change since it."""+ if self._unchanged_since_previous_head is None:+ return {}+ previous, changed = self._unchanged_since_previous_head+ return _cached_by_path({self._key_at(kind, path, previous): path for path in paths if path not in changed})+def _read_missing(self, paths: list[str]) -> dict[str, str]:- return self._fetcher.read_files(self.repository, self._commit(), paths, self._deadline)+ reused = self._reuse_unchanged("text", paths)+ rest = [path for path in paths if path not in reused]+ return {**reused, **self._fetcher.read_files(self.repository, self._commit(), rest, self._deadline)}def _probe_missing(self, paths: list[str]) -> dict[str, bool]:- return self._fetcher.files_exist(self.repository, self._commit(), paths, self._deadline)+ reused = self._reuse_unchanged("exists", paths)+ rest = [path for path in paths if path not in reused]+ return {**reused, **self._fetcher.files_exist(self.repository, self._commit(), rest, self._deadline)}def read_all(self, paths: list[str]) -> None:- if self._head_commit_sha() is None:+ if self._head_sha is None:# A repository with no commits holds no file. There is no commit to key a cache entry# by, so the absence is answered per batch rather than written to the cache.self._bodies.update({path: _ABSENT for path in paths if path not in self._bodies})@@ -418,7 +524,7 @@ class AuthenticatedRepoFiles(CachedRepoFiles):super().read_all(paths)def exists_all(self, paths: list[str]) -> dict[str, bool]:- if self._head_commit_sha() is None:+ if self._head_sha is None:return dict.fromkeys(paths, False)return super().exists_all(paths)diff --git a/posthog/ownership/repo_files.py b/posthog/ownership/repo_files.pyindex 8ca57f61da91..4fe75b574b64 100644--- a/posthog/ownership/repo_files.py+++ b/posthog/ownership/repo_files.py@@ -65,6 +65,10 @@ class NoRootOwnersFile(OwnershipUnavailable):"""The repository answers with no root owners file, which is normal for most repositories."""+class ResponseTooLarge(OwnershipUnavailable):+ """A response body passed its byte limit. The same request gets the same body every time."""++class RepoFiles(BatchOwnershipSource, Protocol):"""A repository's ownership files: one file, or a whole batch's before the resolver reads any."""@@ -99,7 +103,7 @@ def capped_text(response: requests.Response, *, description: str, limit: int, de# Content-Length can be absent or wrong, so the streamed read below is the actual ceiling.declared = response.headers.get("Content-Length")if declared is not None and declared.isdigit() and int(declared) > limit:- raise OwnershipUnavailable(too_large)+ raise ResponseTooLarge(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@@ -110,7 +114,7 @@ def capped_text(response: requests.Response, *, description: str, limit: int, deraise OwnershipUnavailable(f"reading {description} passed the resolution budget")body.extend(chunk)if len(body) > limit:- raise OwnershipUnavailable(too_large)+ raise ResponseTooLarge(too_large)return body.decode(response.encoding or "utf-8", errors="replace")@@ -138,6 +142,11 @@ def _cache_get_many(keys: list[str]) -> dict[str, Any]:return {}+def _cached_by_path(path_by_key: dict[str, str]) -> dict[str, Any]:+ """The cached values of these keys, by the path each key stands for."""+ return {path_by_key[key]: value for key, value in _cache_get_many(list(path_by_key)).items()}++def _cache_set_many(values: dict[str, Any], ttl: int) -> None:try:cache.set_many(values, ttl)@@ -176,8 +185,7 @@ class CachedRepoFiles:todo = list(dict.fromkeys(paths))if not todo:return {}- by_key = {self._cache_key(kind, path): path for path in todo}- known = {by_key[key]: value for key, value in _cache_get_many(list(by_key)).items()}+ known = _cached_by_path({self._cache_key(kind, path): path for path in todo})missing = [path for path in todo if path not in known]if missing:fetched = fetch(missing)diff --git a/posthog/ownership/test/test_github_files.py b/posthog/ownership/test/test_github_files.pyindex 8ad2ab75abb4..67d3782647b2 100644--- a/posthog/ownership/test/test_github_files.py+++ b/posthog/ownership/test/test_github_files.py@@ -59,8 +59,14 @@ class _FakeGitHub:self.file_calls = 0self.head_calls = 0self.file_shas: list[str] = []-- def __call__(self, _method: str, _url: str, **kwargs: Any) -> _Response:+ self.compare_calls = 0+ self.compare: Callable[[str, str], _Response] = lambda base, _head: _compared(base, [])++ def __call__(self, _method: str, url: str, **kwargs: Any) -> _Response:+ if "/compare/" in url:+ self.compare_calls += 1+ base, head = url.rsplit("/", 1)[1].split("...")+ return self.compare(base, head)payload = kwargs["json"]query, variables = payload["query"], payload["variables"]if "defaultBranchRef" in query:@@ -85,6 +91,12 @@ class _FakeGitHub:return _Response(200, {"data": {"repository": field}})+def _compared(+ base: str, files: list[dict[str, str]], *, status: str = "ahead", merge_base: str | None = None+) -> _Response:+ return _Response(200, {"status": status, "merge_base_commit": {"sha": merge_base or base}, "files": files})++class _ScriptedGitHub:"""Answers a files query with the scripted status codes in order, recording each token used."""@@ -302,11 +314,48 @@ class TestAuthenticatedRepoFiles(SimpleTestCase):assert github.file_shas == [expected_sha]assert cache.get(key) == expected_sha- @parameterized.expand([("present", _ROOT_OWNERS), ("absent", None)])- def test_a_commit_is_read_once_and_a_new_commit_is_read_again(self, _name: str, body: str | None) -> None:- # The cache is keyed by commit, so a merge has to be visible once the head lookup expires,- # and an absent file must not be refetched on every batch until then.+ @parameterized.expand(+ [+ ("unrelated_merge", lambda base, _head: _compared(base, [{"filename": "src/app.py"}]), 1, False),+ ("unrelated_merge_absent_file", lambda base, _head: _compared(base, []), 1, False, None),+ ("file_edited", lambda base, _head: _compared(base, [{"filename": "owners.yaml"}]), 2, True),+ (+ "file_renamed_away",+ lambda base, _head: _compared(base, [{"filename": "team.yaml", "previous_filename": "owners.yaml"}]),+ 2,+ True,+ ),+ # A force-push or a rewind: the old head is not an ancestor, so nothing is proven unchanged.+ ("diverged", lambda base, _head: _compared(base, [], status="diverged"), 2, True),+ ("merge_base_elsewhere", lambda base, _head: _compared(base, [], merge_base="c" * 40), 2, True),+ (+ "file_list_cut_short",+ lambda base, _head: _compared(base, [{"filename": f"src/{index}.py"} for index in range(300)]),+ 2,+ True,+ ),+ (+ "compare_too_large",+ lambda _base, _head: _Response(200, None, raw=b"x" * (_MAX_RESPONSE_BYTES + 1)),+ 2,+ True,+ ),+ # A transient failure can succeed on the next batch, so it is asked again.+ ("compare_failed", lambda _base, _head: _Response(502, None), 2, True, _ROOT_OWNERS, 2),+ ]+ )+ def test_a_new_commit_reuses_only_what_the_compare_proves_unchanged(+ self,+ _name: str,+ compare: Callable[[str, str], _Response],+ file_calls: int,+ sees_edit: bool,+ body: str | None = _ROOT_OWNERS,+ compare_calls: int = 1,+ ) -> None:github = _FakeGitHub({"owners.yaml": body} if body is not None else {})+ github.compare = compare+ edited = "version: 1\nowners: [team-new]\n"with (patch("posthog.ownership.github_files._HEAD_CACHE_TTL_SECONDS", 0),patch("posthog.ownership.github_files.github_request", side_effect=github),@@ -314,9 +363,15 @@ class TestAuthenticatedRepoFiles(SimpleTestCase):assert self._files().read("owners.yaml") == bodyassert self._files().read("owners.yaml") == bodyassert github.file_calls == 1- github.sha = "b" * 40- assert self._files().read("owners.yaml") == body- assert github.file_calls == 2+ github.sha = _NEW_SHA+ if sees_edit:+ github.blobs = {"owners.yaml": edited}+ assert self._files().read("owners.yaml") == (edited if sees_edit else body)+ assert self._files().read("owners.yaml") == (edited if sees_edit else body)+ assert github.file_calls == file_calls+ # Another batch at the same head misses on a new path, and takes the compare answer from the cache.+ assert self._files().read("rust/owners.yaml") is None+ assert github.compare_calls == compare_callsclass TestFetcherForTeam(BaseTest):