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(engineering-analytics): cache pr costs for five minutes (#109310)

Raúl Negrón-Otero96ec47c0a669
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index ca98455861e8..8b9e8d14ff37 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -95,6 +95,7 @@ The endpoint catalog is `presentation/views.py`; the agent-facing descriptions l
- Test evidence is counted per CI run, never per span or run attempt (one run fans a test across matrix legs, and every attempt re-tests the same commit), and both span-derived reads group the same `run_evidence()` so the grain and the meaning of flaky cannot drift. A test is `confirmed_flake` only on same-commit recovery proof: a re-run attempt going green, or an in-job retry. Unproven failures rank as `suspected_regression` by blast radius.
- A CI setup break is not per-test evidence. `run_evidence()` drops every trial of a run attempt whose errored tests span 3 or more jobs or 3 or more owning teams, and of a job attempt with 100 or more distinct failed or errored tests, so their failures are no test's failure and their passes are no test's recovery. The spans name the attempt, and GitHub's synced `workflow_jobs` rows confirm it: a run attempt must report 3 or more failed jobs there, a job attempt at least one. CI stamps every span attribute the rule reads, so no evidence is dropped on the spans alone, and an unsynced jobs table drops nothing.
- Reads over optional data (e.g. `team_members`) degrade honestly (`has_membership_data: false`), never 500.
+- A pull request's lifetime cost on the list reads is cached for 5 minutes per pull request, because it needs a full jobs scan however few pull requests a page shows. CI status stays live. The cache key carries a hash of the cost query, so a change to the query, its prices or the resolved tables starts a fresh cache. A cached value is served only when the reader's HogQL catalog grants every table that query reads.
### Exposed warehouse views
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 7df518050597..20faebf2bf6c 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -14,8 +14,9 @@ into these fragments.
"""
import math
+import hashlib
import threading
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Sequence
from concurrent.futures import Future
from contextlib import contextmanager
from dataclasses import dataclass
@@ -23,13 +24,17 @@ from functools import partial
from typing import TYPE_CHECKING
from django.conf import settings
+from django.core.cache import cache
from django.db import connection
+import structlog
+
from posthog.schema import HogQLQueryResponse
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.metadata import get_table_names
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -65,8 +70,12 @@ from products.engineering_analytics.backend.logic.views import (
)
if TYPE_CHECKING:
+ from posthog.models.user import User
+
from products.access_control.backend.facade.user_access_control import UserAccessControl
+logger = structlog.get_logger(__name__)
+
_QUERY_PAGE_SIZE = 5000
@@ -605,6 +614,65 @@ class CuratedGitHubSource:
return rows
cursor = tuple(page[-1][index] for _column, index in page_key)
+ @property
+ def _user(self) -> "User | None":
+ return self._user_access_control.user if self._user_access_control is not None else None
+
+ @property
+ def _bypass_warehouse_access_control(self) -> bool:
+ return self._user_access_control is None
+
+ def _catalog(self) -> Database:
+ with self._lock:
+ if self._database is None:
+ self._database = Database.create_for(
+ team=self._team,
+ user=self._user,
+ user_access_control=self._user_access_control,
+ modifiers=create_default_modifiers_for_team(self._team),
+ bypass_warehouse_access_control=self._bypass_warehouse_access_control,
+ trigger="engineering_analytics",
+ )
+ return self._database
+
+ def read_through[V](
+ self, *, sql: str, keys: Sequence[int], load: Callable[[list[int]], dict[int, V]], ttl_seconds: int
+ ) -> dict[int, V]:
+ """``load``'s value for every key, reusing values another request computed in the last
+ ``ttl_seconds``. ``load`` gets the keys with no cached value and must return one for each.
+
+ ``sql`` is the query ``load`` runs, before its placeholders. Its hash names the cache, so a
+ change to that query, the prices it renders or the tables it resolves starts a fresh one. A
+ cached value is served only when this reader's catalog grants every table that query reads,
+ the decision the query itself would get. A cache that fails to answer loads every key.
+ """
+ prefix = f"engineering_analytics:{self._team.pk}:{hashlib.sha256(sql.encode()).hexdigest()}"
+ cache_keys = {key: f"{prefix}:{key}" for key in keys}
+ cached: dict[str, V] = {}
+ if self._may_read_every_table_in(sql):
+ try:
+ cached = cache.get_many(list(cache_keys.values()))
+ except Exception:
+ logger.warning("engineering_analytics_cache_read_failed", exc_info=True)
+ values = {key: cached[cache_key] for key, cache_key in cache_keys.items() if cache_key in cached}
+ missing = [key for key in keys if key not in values]
+ if not missing:
+ return values
+ loaded = load(missing)
+ try:
+ cache.set_many({cache_keys[key]: value for key, value in loaded.items()}, timeout=ttl_seconds)
+ except Exception:
+ logger.warning("engineering_analytics_cache_write_failed", exc_info=True)
+ return {**values, **loaded}
+
+ def _may_read_every_table_in(self, sql: str) -> bool:
+ # The rule HogQL's own query cache applies: posthog/hogql/ACCESS_CONTROL.md, "Query cache partitioning".
+ catalog = self._catalog()
+ return all(
+ catalog.has_table(table) and not catalog.is_table_access_denied(table)
+ for table in get_table_names(parse_select(sql))
+ )
+
def run(
self,
sql: str,
@@ -629,23 +697,15 @@ class CuratedGitHubSource:
``logs`` table). The warehouse-ACL reasoning above governs warehouse tables only and is a no-op
for such reads — those tables carry no per-table ACL, so the ``team_id`` scope is their boundary.
"""
- uac = self._user_access_control
- user = uac.user if uac is not None else None
- bypass_warehouse_access_control = uac is None
with self._lock:
if self._queries_remaining is not None:
if self._queries_remaining <= 0:
raise QueryWorkLimitExceededError
self._queries_remaining -= 1
- if self._database is None:
- self._database = Database.create_for(
- team=self._team,
- user=user,
- user_access_control=uac,
- modifiers=create_default_modifiers_for_team(self._team),
- bypass_warehouse_access_control=bypass_warehouse_access_control,
- trigger="engineering_analytics",
- )
+ uac = self._user_access_control
+ user = self._user
+ bypass_warehouse_access_control = self._bypass_warehouse_access_control
+ database = self._catalog()
with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=self._team.pk):
return execute_hogql_query(
query=parse_select(sql, placeholders=placeholders),
@@ -662,7 +722,7 @@ class CuratedGitHubSource:
user=user,
user_access_control=uac,
bypass_warehouse_access_control=bypass_warehouse_access_control,
- database=self._database,
+ database=database,
),
)
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index 84d494007949..d0ffc5f7da61 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -215,6 +215,13 @@ _COSTS_BY_PR_SELECT = f"""
"""
+# The endpoint and MCP descriptions state that cost can lag new CI by this long.
+_PR_COSTS_CACHE_SECONDS = 300
+# The cache stores the SQL row, not a PRCostAggregate, because the cache key covers the SQL but not
+# the Python classes that read the row.
+_CostRow = tuple[str, str, float | None, float | None, int | None, int | None, int | None]
+
+
def query_pr_costs(
*, curated: CuratedGitHubSource, pr_numbers: list[int], run_from: datetime | None = None
) -> dict[tuple[str, str, int], PRCostAggregate]:
@@ -240,10 +247,27 @@ def query_pr_costs(
.replace("__COST_AGGREGATES__", _cost_aggregates())
.replace("__RUN_FROM__", run_from_clause)
)
- response = curated.run(sql, query_type="engineering_analytics.pr_costs", placeholders=placeholders)
+
+ def load(numbers: list[int]) -> dict[int, tuple[_CostRow, ...]]:
+ response = curated.run(
+ sql,
+ query_type="engineering_analytics.pr_costs",
+ placeholders={**placeholders, "pr_numbers": ast.Constant(value=numbers)},
+ )
+ by_number: dict[int, list[_CostRow]] = {number: [] for number in numbers}
+ for repo_owner, repo_name, pr_number, *agg in response.results or []:
+ by_number[int(pr_number)].append((repo_owner, repo_name, *agg))
+ # A PR without costed jobs is stored too, so it does not bring the full jobs scan back on every view.
+ return {number: tuple(costs) for number, costs in by_number.items()}
+
+ if run_from is None:
+ costs_by_number = curated.read_through(sql=sql, keys=pr_numbers, load=load, ttl_seconds=_PR_COSTS_CACHE_SECONDS)
+ else:
+ costs_by_number = load(pr_numbers)
return {
- (repo_owner, repo_name, int(pr_number)): _aggregate(*agg)
- for repo_owner, repo_name, pr_number, *agg in response.results or []
+ (repo_owner, repo_name, number): _aggregate(billable, cost, costed, unsettled, excluded)
+ for number, costs in costs_by_number.items()
+ for repo_owner, repo_name, billable, cost, costed, unsettled, excluded in costs
}
diff --git a/products/engineering_analytics/backend/presentation/views/pull_requests.py b/products/engineering_analytics/backend/presentation/views/pull_requests.py
index d48a53511cb4..53f8cb17339b 100644
--- a/products/engineering_analytics/backend/presentation/views/pull_requests.py
+++ b/products/engineering_analytics/backend/presentation/views/pull_requests.py
@@ -92,7 +92,8 @@ class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):
"Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "
"its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards "
"counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; "
- "CI counts can lag until late completions settle."
+ "CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to "
+ "5 minutes."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -120,7 +121,8 @@ class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):
description=(
"Open pull requests that need attention: failing CI, or stuck (open, non-draft, non-bot, older than "
"7 days), by the same rules as the ci_cards counts. Failing first, then newest, capped; `total` counts "
- "every match in the whole open backlog, however old."
+ "every match in the whole open backlog, however old. Cost and billable minutes can lag new CI by up to "
+ "5 minutes."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index 4f31fd08d4c2..7fabe4feeb9a 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -8,6 +8,7 @@ from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from django.core.cache import cache
from django.utils import timezone
import pandas as pd
@@ -174,6 +175,7 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
def setUp(self) -> None:
super().setUp()
+ cache.clear()
self._github_source: ExternalDataSource | None = None
def _create_table(
diff --git a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
index 8d52b712ad93..7a9073870ec3 100644
--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
@@ -9,14 +9,18 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.hogql.database.database import Database
+
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import (
CIStatusRollup,
MetricQuality,
PRLifecycleEventKind,
PRState,
+ PullRequestList,
)
from products.engineering_analytics.backend.logic.queries import pull_request_list
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.views.source_schema import (
ISSUE_EVENTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
@@ -328,12 +332,15 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# No issue-events source seeded: the column degrades to NULL (never 0) and the query still runs.
assert by_number[14].merged_at is not None and by_number[14].ready_to_merge_seconds is None
- def test_pull_request_list_includes_cost_when_jobs_synced(self) -> None:
+ def test_pull_request_list_includes_cost_and_reuses_it(self) -> None:
# With the jobs source synced, the list carries per-PR cost + billable minutes.
self._create_table(
"github_pull_requests",
PULL_REQUESTS_COLUMNS,
- [_pr_row(70, "alice", "open", 0, _ago(1), head_sha="sha70")],
+ [
+ _pr_row(70, "alice", "open", 0, _ago(1), head_sha="sha70"),
+ _pr_row(71, "bob", "open", 0, _ago(1), head_sha="sha71"),
+ ],
)
self._create_table(
"github_workflow_runs",
@@ -345,11 +352,29 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
WORKFLOW_JOBS_COLUMNS,
[_job_row(94000, 9400, "build", "success", labels='["depot-ubuntu-22.04-4"]')],
)
- item = next(i for i in api.list_pull_requests(team=self.team).items if i.number == 70)
+
+ def list_counting_cost_queries() -> tuple[PullRequestList, int]:
+ with mock.patch.object(CuratedGitHubSource, "run", autospec=True, wraps=CuratedGitHubSource.run) as run:
+ result = api.list_pull_requests(team=self.team)
+ queries = [
+ call for call in run.call_args_list if call.kwargs.get("query_type") == "engineering_analytics.pr_costs"
+ ]
+ return result, len(queries)
+
+ result, cost_queries = list_counting_cost_queries()
+ assert cost_queries == 1
+ item = next(i for i in result.items if i.number == 70)
# One 120s job on a 4-vCPU tier: 2 min x $0.004 x 2.
assert item.estimated_cost_usd == pytest.approx(0.016)
assert item.billable_minutes == pytest.approx(2.0)
+ repeat, cost_queries = list_counting_cost_queries()
+ assert cost_queries == 0
+ assert next(i for i in repeat.items if i.number == 70).estimated_cost_usd == pytest.approx(0.016)
+ with mock.patch.object(Database, "is_table_access_denied", return_value=True):
+ _, cost_queries = list_counting_cost_queries()
+ assert cost_queries == 1
+
def test_ready_to_merge_semantics(self) -> None:
# PR 20: only the LAST ready counts. PR 21: no transitions, whole life inside the window ->
# open-to-merge fallback. PR 22: created pre-window -> NULL. PR 23: re-drafted -> NULL.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index b6d8172ff2a3..fdd3a2c91d91 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -103,7 +103,7 @@ export const getEngineeringAnalyticsAttentionPullRequestsUrl = (
}
/**
- * Open pull requests that need attention: failing CI, or stuck (open, non-draft, non-bot, older than 7 days), by the same rules as the ci_cards counts. Failing first, then newest, capped; `total` counts every match in the whole open backlog, however old.
+ * Open pull requests that need attention: failing CI, or stuck (open, non-draft, non-bot, older than 7 days), by the same rules as the ci_cards counts. Failing first, then newest, capped; `total` counts every match in the whole open backlog, however old. Cost and billable minutes can lag new CI by up to 5 minutes.
*/
export const engineeringAnalyticsAttentionPullRequests = async (
projectId: string,
@@ -764,7 +764,7 @@ export const getEngineeringAnalyticsPullRequestsUrl = (
}
/**
- * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle.
+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.
*/
export const engineeringAnalyticsPullRequests = async (
projectId: string,
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 7091f6136979..c1d41f104772 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -365,8 +365,8 @@ tools:
ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR
verifiably never drafted. Null means "not observed" (the issue-events window is bounded), never zero. CI
counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook
- settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft) for throughput
- questions.
+ settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are
+ present; exclude them (author.is_bot, is_draft) for throughput questions.
param_overrides:
date_from:
description: >
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 810e1b7954d2..3bb97d41abd1 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9834,7 +9834,7 @@
}
},
"pull-requests": {
- "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft) for throughput questions.",
+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions.",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "List pull requests with CI status",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 78c1b39e2b22..48240255d957 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10425,7 +10425,7 @@
}
},
"pull-requests": {
- "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft) for throughput questions.",
+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions.",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "List pull requests with CI status",
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 9fbca244b1c1..a9dd679e209f 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -142,7 +142,7 @@ export const EngineeringAnalyticsPrLifecycleQueryParams = () => zod.object({
})
/**
- * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle.
+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.
*/
export const EngineeringAnalyticsPullRequestsParams = () => zod.object({
project_id: zod