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.

perf(visual-review): parse the baseline file once per blob sha (#100073)

Julian Bezc17e4f9ab12b
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index 1f09d378ef64..77c0fd9cc016 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -833,13 +833,13 @@ class GitHubIntegration(GitHubIntegrationBase):
"status_code": response.status_code,
}
- def get_file_contents(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:
- """Read a file's decoded text and blob SHA at ``ref`` (default branch when omitted).
+ def get_file_entry(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:
+ """Read a file's blob SHA and size at ``ref``, and its text when GitHub sends it inline.
- Returns ``{"content": str, "sha": str}``, or ``None`` when the file does not
- exist — a missing file is a normal state, not an error. The SHA lets a caller
- pass it straight to ``update_file`` for a conflict-safe write. Counterpart to
- ``update_file``, kept here so URL and token handling stay inside the client.
+ Returns ``{"sha": str, "size": int, "content": str | None}``, or ``None`` when the file does
+ not exist. ``content`` is None above the contents API's 1 MB inline limit, so read it with
+ ``get_blob_text``. A blob SHA names the bytes it holds, so a caller that has already read a
+ SHA can skip that read.
Raises ``GitHubIntegrationError`` rather than return a partial or oversized file.
"""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
@@ -863,34 +863,58 @@ class GitHubIntegration(GitHubIntegrationBase):
raise GitHubIntegrationError(
f"{file_path} in {repository} is {size} bytes, over the {_MAX_FILE_CONTENTS_BYTES} byte limit"
)
- content: bytes | bytearray
if payload["encoding"] == "none":
# The contents API omits content above 1 MB.
- blob_response = self.api_request(
- "GET",
- f"/repos/{repo_path}/git/blobs/{payload['sha']}",
- endpoint="/repos/{owner}/{repo}/git/blobs/{file_sha}",
- headers={"Accept": "application/vnd.github.raw+json"},
- stream=True,
- )
- try:
- if blob_response.status_code != 200:
- raise GitHubIntegrationError(
- f"Failed to read {file_path} from {repository}: {blob_response.text}",
- status_code=blob_response.status_code,
- )
- content = bytearray()
- for chunk in blob_response.iter_content(chunk_size=64 * 1024):
- content += chunk
- if len(content) > size:
- break
- finally:
- blob_response.close()
- else:
- content = base64.b64decode(payload["content"])
+ return {"sha": payload["sha"], "size": size, "content": None}
+ content = base64.b64decode(payload["content"])
if len(content) != size:
raise GitHubIntegrationError(f"Read {len(content)} of {size} bytes of {file_path} from {repository}")
- return {"content": content.decode("utf-8"), "sha": payload["sha"]}
+ return {"sha": payload["sha"], "size": size, "content": content.decode("utf-8")}
+
+ def get_blob_text(self, repository: str, blob_sha: str, size: int) -> str:
+ """Stream one blob's text by its SHA, refusing anything that is not exactly ``size`` bytes."""
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ blob_response = self.api_request(
+ "GET",
+ f"/repos/{repo_path}/git/blobs/{blob_sha}",
+ endpoint="/repos/{owner}/{repo}/git/blobs/{file_sha}",
+ headers={"Accept": "application/vnd.github.raw+json"},
+ stream=True,
+ )
+ try:
+ if blob_response.status_code != 200:
+ raise GitHubIntegrationError(
+ f"Failed to read blob {blob_sha} from {repository}: {blob_response.text}",
+ status_code=blob_response.status_code,
+ )
+ content = bytearray()
+ for chunk in blob_response.iter_content(chunk_size=64 * 1024):
+ content += chunk
+ if len(content) > size:
+ break
+ finally:
+ blob_response.close()
+ if len(content) != size:
+ raise GitHubIntegrationError(f"Read {len(content)} of {size} bytes of blob {blob_sha} from {repository}")
+ return content.decode("utf-8")
+
+ def get_file_contents(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:
+ """Read a file's decoded text and blob SHA at ``ref`` (default branch when omitted).
+
+ Returns ``{"content": str, "sha": str}``, or ``None`` when the file does not
+ exist — a missing file is a normal state, not an error. The SHA lets a caller
+ pass it straight to ``update_file`` for a conflict-safe write. Counterpart to
+ ``update_file``, kept here so URL and token handling stay inside the client.
+ Raises ``GitHubIntegrationError`` rather than return a partial or oversized file.
+ """
+ entry = self.get_file_entry(repository, file_path, ref=ref)
+ if entry is None:
+ return None
+ content = entry["content"]
+ if content is None:
+ content = self.get_blob_text(repository, entry["sha"], entry["size"])
+ return {"content": content, "sha": entry["sha"]}
def create_pull_request(
self, repository: str, title: str, body: str, head_branch: str, base_branch: str | None = None
diff --git a/products/visual_review/backend/logic/content_cache.py b/products/visual_review/backend/logic/content_cache.py
new file mode 100644
index 000000000000..075a99df6f18
--- /dev/null
+++ b/products/visual_review/backend/logic/content_cache.py
@@ -0,0 +1,33 @@
+"""Content named by its own hash, parsed once and kept in the cache.
+
+A hash names exactly one content, so a cached value can never be stale and nothing has to
+invalidate it. The timeout only frees memory for content that nobody reads any more. The cache is
+only an optimization, so a cache that cannot be reached counts as a miss and the content is read
+from its source.
+"""
+
+from collections.abc import Callable
+from typing import TypeVar
+
+from posthog.utils import get_safe_cache, safe_cache_set
+
+T = TypeVar("T")
+
+# Short, because entries live in the shared cache. CI runs read the same blob many times within an
+# hour, so a short entry keeps almost every hit.
+_TIMEOUT_SECONDS = 60 * 60
+
+
+def load_by_hash(kind: str, content_hash: str, load: Callable[[], T | None]) -> T | None:
+ """The parsed content that a hash names, from the cache or from `load`.
+
+ None is never cached, so content that could not be read this time is read again next time.
+ """
+ key = f"visual_review:{kind}:{content_hash}"
+ cached = get_safe_cache(key)
+ if cached is not None:
+ return cached
+ value = load()
+ if value is not None:
+ safe_cache_set(key, value, timeout=_TIMEOUT_SECONDS)
+ return value
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
index 5d75a19cc1ce..ec6d1b595985 100644
--- a/products/visual_review/backend/logic/github_api.py
+++ b/products/visual_review/backend/logic/github_api.py
@@ -18,7 +18,7 @@ from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models.github_integration_base import GitHubIntegrationError
from ..models import Repo
-from . import errors
+from . import content_cache, errors
logger = structlog.get_logger(__name__)
@@ -216,6 +216,28 @@ def _get_pr_info(github, repo_full_name: str, pr_number: int) -> dict:
}
+# A larger baseline file is parsed without caching, so one repository cannot fill the shared cache
+# with large parsed files.
+_MAX_CACHED_BASELINE_BYTES = 2 * 1024 * 1024
+
+
+def _parse_baseline_file(text: str) -> dict[str, dict]:
+ """Identifier to its signed entry, for a version 1 baseline file. Empty for anything else."""
+ import yaml
+
+ parsed = yaml.safe_load(text)
+ if not parsed or parsed.get("version") != 1:
+ return {}
+
+ raw_snapshots = parsed.get("snapshots", {})
+
+ normalized: dict[str, dict] = {}
+ for identifier, value in raw_snapshots.items():
+ if isinstance(value, dict) and "hash" in value:
+ normalized[identifier] = value
+ return normalized
+
+
def _fetch_baseline_file(
github, repo_full_name: str, file_path: str, branch: str
) -> tuple[dict[str, dict], str | None]:
@@ -225,29 +247,29 @@ def _fetch_baseline_file(
Returns ``(snapshots_dict, file_sha)``. Snapshots dict maps
identifier to ``{hash: "v1.kid.hash.tag"}`` (the signed format).
If the file doesn't exist, returns ``({}, None)``.
- """
- import yaml
+ The file is parsed once per blob SHA. Every run reads it at least once, and most reads name a
+ blob that an earlier run already downloaded, because the file only changes when a baseline
+ commit lands. The small contents call still runs every time, since a branch ref can move.
+ """
try:
- result = github.get_file_contents(repo_full_name, file_path, ref=branch)
+ entry = github.get_file_entry(repo_full_name, file_path, ref=branch)
+ if entry is None:
+ return {}, None
+
+ def read_and_parse() -> dict[str, dict]:
+ text = entry["content"]
+ if text is None:
+ text = github.get_blob_text(repo_full_name, entry["sha"], entry["size"])
+ return _parse_baseline_file(text)
+
+ if entry["size"] > _MAX_CACHED_BASELINE_BYTES:
+ baselines: dict[str, dict] | None = read_and_parse()
+ else:
+ baselines = content_cache.load_by_hash("baseline_file", entry["sha"], read_and_parse)
except GitHubRateLimitError:
raise
except GitHubIntegrationError as e:
raise errors.GitHubCommitError(f"Failed to fetch baseline file: {e}") from e
- if result is None:
- return {}, None
-
- file_sha = result["sha"]
-
- parsed = yaml.safe_load(result["content"])
- if not parsed or parsed.get("version") != 1:
- return {}, file_sha
-
- raw_snapshots = parsed.get("snapshots", {})
-
- normalized: dict[str, dict] = {}
- for identifier, value in raw_snapshots.items():
- if isinstance(value, dict) and "hash" in value:
- normalized[identifier] = value
- return normalized, file_sha
+ return baselines or {}, entry["sha"]
diff --git a/products/visual_review/backend/tests/logic/test_github_api.py b/products/visual_review/backend/tests/logic/test_github_api.py
new file mode 100644
index 000000000000..82221ea8a502
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_github_api.py
@@ -0,0 +1,61 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+
+from products.visual_review.backend.logic import github_api
+
+_BIG_FILE = "version: 1\nsnapshots:\n button--light:\n hash: v1.k.abc.tag\n"
+
+
+def _github(sha_by_ref: dict[str, str]) -> MagicMock:
+ github = MagicMock()
+ github.get_file_entry.side_effect = lambda repo, path, ref: {
+ "sha": sha_by_ref[ref],
+ "size": len(_BIG_FILE),
+ "content": None,
+ }
+ github.get_blob_text.return_value = _BIG_FILE
+ return github
+
+
+class TestFetchBaselineFile:
+ @pytest.fixture(autouse=True)
+ def _clear_cache(self):
+ cache.clear()
+
+ @pytest.mark.parametrize(
+ "sha_by_ref,blob_reads",
+ [
+ ({"feature": "blob-1", "abc123": "blob-1"}, 1),
+ ({"feature": "blob-1", "abc123": "blob-2"}, 2),
+ ],
+ )
+ def test_a_blob_is_downloaded_once_per_sha(self, sha_by_ref: dict[str, str], blob_reads: int) -> None:
+ github = _github(sha_by_ref)
+
+ results = [github_api._fetch_baseline_file(github, "org/repo", "snapshots.yml", ref) for ref in sha_by_ref]
+
+ assert github.get_blob_text.call_count == blob_reads
+ assert [baseline for baseline, _sha in results] == [{"button--light": {"hash": "v1.k.abc.tag"}}] * 2
+ assert [sha for _baseline, sha in results] == list(sha_by_ref.values())
+
+ def test_an_unreachable_cache_still_reads_the_file(self) -> None:
+ github = _github({"feature": "blob-1"})
+
+ with patch("posthog.utils.cache") as broken_cache:
+ broken_cache.get.side_effect = ConnectionError("cache down")
+ broken_cache.set.side_effect = ConnectionError("cache down")
+ baseline, sha = github_api._fetch_baseline_file(github, "org/repo", "snapshots.yml", "feature")
+
+ assert baseline == {"button--light": {"hash": "v1.k.abc.tag"}}
+ assert sha == "blob-1"
+
+ def test_a_caller_editing_the_result_does_not_change_the_next_read(self) -> None:
+ github = _github({"feature": "blob-1", "other": "blob-1"})
+
+ first, _sha = github_api._fetch_baseline_file(github, "org/repo", "snapshots.yml", "feature")
+ first.pop("button--light")
+ second, _sha = github_api._fetch_baseline_file(github, "org/repo", "snapshots.yml", "other")
+
+ assert second == {"button--light": {"hash": "v1.k.abc.tag"}}