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): read detail pages concurrently (#110365)

Raúl Negrón-Otero9827e53b91c7
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 3e86e6fe54ce..8217eca63e68 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -25,7 +25,7 @@ from typing import TYPE_CHECKING
from django.conf import settings
from django.core.cache import cache
-from django.db import connection
+from django.db import connections
import structlog
@@ -523,7 +523,8 @@ class CuratedGitHubSource:
@contextmanager
def concurrent_reads(self) -> Iterator["ConcurrentReads"]:
"""Run the reads submitted inside the block together when it exits, so a request waits for
- its slowest read instead of the sum of all of them. Read each result after the block."""
+ its slowest read instead of the sum of all of them. Read each result after the block. A read
+ that needs several reads of its own opens its own block."""
reads = ConcurrentReads()
yield reads
reads.run()
@@ -682,7 +683,7 @@ class CuratedGitHubSource:
class ConcurrentReads:
- """Each worker closes the Postgres connection it opens. Under TEST the reads run inline, because a
+ """Each worker closes the Postgres connections it opens. Under TEST the reads run inline, because a
worker's connection cannot see the test transaction."""
def __init__(self) -> None:
@@ -713,16 +714,17 @@ class ConcurrentReads:
raise errors[0]
return
run_in_parallel_threads(
- [partial(_closing_connection, work) for work in self._work],
+ [partial(_closing_connections, work) for work in self._work],
thread_name_prefix="engineering_analytics",
)
-def _closing_connection(work: Callable[[], None]) -> None:
+def _closing_connections(work: Callable[[], None]) -> None:
try:
work()
finally:
- connection.close()
+ # A routed read can open a connection on another alias, so the worker closes all of them.
+ connections.close_all()
def opt_float(value: float | None) -> float | None:
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
index 510dc329b68a..e8d0637d04c8 100644
--- a/products/engineering_analytics/backend/logic/queries/delivery_summary.py
+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
@@ -14,6 +14,8 @@ from datetime import datetime, timedelta
from posthog.hogql import ast
+from posthog.dataclasses import frozen
+
from products.engineering_analytics.backend.facade.contracts import (
DeliveryLeadTime,
DeliverySummary,
@@ -33,7 +35,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
date_to_filter_clause,
run_started_floor_constant,
)
-from products.engineering_analytics.backend.logic.queries.dora import DeployedPR, query_deployed_prs
+from products.engineering_analytics.backend.logic.queries.dora import DeployedPR, DeployedPRs, query_deployed_prs
from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs
from products.engineering_analytics.backend.logic.views.reviews import APPROVED_STATE
@@ -253,20 +255,8 @@ def scope_repo_figure(
def _lead_time(
- curated: CuratedGitHubSource,
- *,
- scope: SummaryScope,
- date_from: datetime,
- date_to: datetime | None,
- scope_merged_count: int,
+ deployed: DeployedPRs | None, *, date_from: datetime, date_to: datetime | None, scope_merged_count: int
) -> DeliveryLeadTime:
- deployed = query_deployed_prs(
- curated=curated,
- date_from=date_from,
- date_to=date_to,
- scope_predicate=scope.pr_predicate(curated, prefix=""),
- scope_placeholders=scope.placeholders(),
- )
empty = duration_distribution([])
if deployed is None:
empty_pair = ScopeRepoDistribution(scope=empty, repo=empty)
@@ -342,14 +332,14 @@ def _query_merged_rows(
]
-def _query_approvals(curated: CuratedGitHubSource, numbers: ast.Constant) -> dict[int, list[datetime]]:
+def _query_approvals(curated: CuratedGitHubSource, pr_numbers: list[int]) -> dict[int, list[datetime]]:
reviews_source = curated.reviews_source()
if reviews_source is None:
return {}
response = curated.run(
_APPROVALS_SELECT.replace("__REVIEWS_SOURCE__", reviews_source),
query_type="engineering_analytics.delivery_summary_approvals",
- placeholders={"pr_numbers": numbers},
+ placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
)
return {int(number): list(times) for number, times in response.results or []}
@@ -383,42 +373,34 @@ def query_ready_to_merge_facts(
rows = _query_merged_rows(curated, scope=scope, date_from=date_from, date_to=date_to)
if not rows:
return []
- approvals = _query_approvals(curated, ast.Constant(value=sorted({row.number for row in rows})))
+ approvals = _query_approvals(curated, sorted({row.number for row in rows}))
return [_merged_facts(row, approved_at=approvals.get(row.number, [])) for row in rows]
-def _query_merged_facts(
- curated: CuratedGitHubSource, *, scope: SummaryScope, date_from: datetime, date_to: datetime | None
-) -> list[MergedPRFacts]:
- rows = _query_merged_rows(curated, scope=scope, date_from=date_from, date_to=date_to)
- pr_numbers = sorted({row.number for row in rows})
- if not pr_numbers:
- return []
-
- run_from = date_from - CI_LOOKBACK
- numbers = ast.Constant(value=pr_numbers)
- approvals = _query_approvals(curated, numbers)
-
- runs_source = curated.run_source(started_floor=True)
+def _query_pushes(curated: CuratedGitHubSource, pr_numbers: list[int], run_from: datetime) -> dict[int, list[datetime]]:
push_rows = push_rows_select(
- runs_source=runs_source,
+ runs_source=curated.run_source(started_floor=True),
run_filter="pr_number IN {pr_numbers} AND run_started_at >= {run_from}",
)
- pushes_response = curated.run(
+ response = curated.run(
_PUSHES_SELECT.replace("__PUSH_ROWS__", push_rows),
query_type="engineering_analytics.delivery_summary_pushes",
placeholders={
- "pr_numbers": numbers,
+ "pr_numbers": ast.Constant(value=pr_numbers),
"run_from": ast.Constant(value=run_from),
"run_started_floor": run_started_floor_constant(run_from),
},
)
- pushes = {int(number): [at for at in times if at is not None] for number, times in pushes_response.results or []}
+ return {int(number): [at for at in times if at is not None] for number, times in response.results or []}
+
+def _query_gate_attempts(
+ curated: CuratedGitHubSource, pr_numbers: list[int], date_from: datetime
+) -> dict[int, list[GateAttempt]]:
gate_from = date_from - GATE_RUN_LOOKBACK
- gates_response = curated.run(
+ response = curated.run(
gate_attempts_sql(
- runs_source=runs_source,
+ runs_source=curated.run_source(started_floor=True),
pull_requests_source=curated.pr_source(),
pull_request_filter="pr.number IN {pr_numbers} AND pr.merged_at IS NOT NULL",
decisive_failure_conclusions_sql=DECISIVE_FAILURE_CONCLUSIONS_SQL,
@@ -426,13 +408,13 @@ def _query_merged_facts(
+ f"\nLIMIT {UNPAGED_SCAN_LIMIT}",
query_type="engineering_analytics.delivery_summary_gate_attempts",
placeholders={
- "pr_numbers": numbers,
+ "pr_numbers": ast.Constant(value=pr_numbers),
"gate_from": ast.Constant(value=gate_from),
"run_started_floor": run_started_floor_constant(gate_from),
},
)
gates: dict[int, list[GateAttempt]] = defaultdict(list)
- for number, attempt, started_at, completed_at, unfinished, failed, _merged_at in gates_response.results or []:
+ for number, attempt, started_at, completed_at, unfinished, failed, _merged_at in response.results or []:
if started_at is not None:
gates[int(number)].append(
GateAttempt(
@@ -442,14 +424,35 @@ def _query_merged_facts(
failed=bool(failed),
)
)
+ return gates
+
+def _query_costs(curated: CuratedGitHubSource, pr_numbers: list[int], run_from: datetime) -> dict[int, PRCostAggregate]:
# A resolved source is one repository's tables, so dropping the owner and name cannot collide two
# pull requests. The timelines read keeps the full key, because it shows the repository per row.
- costs = {
+ return {
number: cost
for (_, _, number), cost in query_pr_costs(curated=curated, pr_numbers=pr_numbers, run_from=run_from).items()
}
+
+def _query_merged_facts(
+ curated: CuratedGitHubSource, *, scope: SummaryScope, date_from: datetime, date_to: datetime | None
+) -> list[MergedPRFacts]:
+ rows = _query_merged_rows(curated, scope=scope, date_from=date_from, date_to=date_to)
+ pr_numbers = sorted({row.number for row in rows})
+ if not pr_numbers:
+ return []
+
+ run_from = date_from - CI_LOOKBACK
+ with curated.concurrent_reads() as reads:
+ approvals_read = reads.submit(lambda: _query_approvals(curated, pr_numbers))
+ pushes_read = reads.submit(lambda: _query_pushes(curated, pr_numbers, run_from))
+ gates_read = reads.submit(lambda: _query_gate_attempts(curated, pr_numbers, date_from))
+ costs_read = reads.submit(lambda: _query_costs(curated, pr_numbers, run_from))
+ approvals, pushes = approvals_read.result(), pushes_read.result()
+ gates, costs = gates_read.result(), costs_read.result()
+
return [
_merged_facts(
row,
@@ -462,21 +465,49 @@ def _query_merged_facts(
]
-def query_delivery_summary(
- *, curated: CuratedGitHubSource, scope: SummaryScope, date_from: datetime, date_to: datetime | None
-) -> DeliverySummary:
- facts = _query_merged_facts(curated, scope=scope, date_from=date_from, date_to=date_to)
- scope_facts = [fact for fact in facts if fact.in_scope]
+@frozen
+class _ScopeCounts:
+ opened: int
+ open_now: int
+ drafts: int
+
+def _query_scope_counts(
+ curated: CuratedGitHubSource, *, scope: SummaryScope, date_from: datetime, date_to: datetime | None
+) -> _ScopeCounts:
placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from), **scope.placeholders()}
- counts = curated.run(
+ response = curated.run(
_SCOPE_COUNTS_SELECT.replace("__SCOPE__", scope.pr_predicate(curated))
.replace("__DATE_TO__", date_to_filter_clause(date_to, placeholders, column="pr.created_at"))
.replace("__PR_SOURCE__", curated.pr_source()),
query_type="engineering_analytics.delivery_summary_counts",
placeholders=placeholders,
)
- opened, open_now, drafts = counts.results[0] if counts.results else (0, 0, 0)
+ opened, open_now, drafts = response.results[0] if response.results else (0, 0, 0)
+ return _ScopeCounts(opened=int(opened or 0), open_now=int(open_now or 0), drafts=int(drafts or 0))
+
+
+def query_delivery_summary(
+ *, curated: CuratedGitHubSource, scope: SummaryScope, date_from: datetime, date_to: datetime | None
+) -> DeliverySummary:
+ with curated.concurrent_reads() as reads:
+ facts_read = reads.submit(
+ lambda: _query_merged_facts(curated, scope=scope, date_from=date_from, date_to=date_to)
+ )
+ counts_read = reads.submit(
+ lambda: _query_scope_counts(curated, scope=scope, date_from=date_from, date_to=date_to)
+ )
+ deployed_read = reads.submit(
+ lambda: query_deployed_prs(
+ curated=curated,
+ date_from=date_from,
+ date_to=date_to,
+ scope_predicate=scope.pr_predicate(curated, prefix=""),
+ scope_placeholders=scope.placeholders(),
+ )
+ )
+ facts, counts = facts_read.result(), counts_read.result()
+ scope_facts = [fact for fact in facts if fact.in_scope]
jobs_available = curated.jobs_source() is not None
costed = [f.cost for f in scope_facts if f.cost and f.cost.estimated_cost_usd is not None]
@@ -487,10 +518,10 @@ def query_delivery_summary(
jobs_available=jobs_available,
review_data_available=curated.reviews_source() is not None,
ready_data_available=curated.ready_to_merge_sql().observable,
- opened_pr_count=int(opened or 0),
+ opened_pr_count=counts.opened,
merged_pr_count=len(scope_facts),
- open_pr_count=int(open_now or 0),
- draft_pr_count=int(drafts or 0),
+ open_pr_count=counts.open_now,
+ draft_pr_count=counts.drafts,
cost_per_merged_pr_usd=scope_repo_figure(scope_facts, facts, _median_cost),
billable_minutes_per_merged_pr=scope_repo_figure(scope_facts, facts, _median_billable_minutes),
cost_per_push_usd=scope_repo_figure(scope_facts, facts, _cost_per_push),
@@ -510,6 +541,6 @@ def query_delivery_summary(
merge_queue_attempts_per_merged_pr=scope_repo_figure(scope_facts, facts, _queue_attempts),
failed_merge_queue_share=scope_repo_figure(scope_facts, facts, _failed_queue_share),
lead_time=_lead_time(
- curated, scope=scope, date_from=date_from, date_to=date_to, scope_merged_count=len(scope_facts)
+ deployed_read.result(), date_from=date_from, date_to=date_to, scope_merged_count=len(scope_facts)
),
)
diff --git a/products/engineering_analytics/backend/logic/queries/dora.py b/products/engineering_analytics/backend/logic/queries/dora.py
index 0a962e76770d..39cf2e357eb4 100644
--- a/products/engineering_analytics/backend/logic/queries/dora.py
+++ b/products/engineering_analytics/backend/logic/queries/dora.py
@@ -667,7 +667,23 @@ def _query_lead_time(
.replace("__PR_SOURCE__", scan.curated.pr_source())
.replace("__TEAM_FILTER__", team_filter)
)
- headline = scan.run(headline_sql, query_type="engineering_analytics.dora_lead_time", placeholders=team_placeholders)
+ series_sql = f"WITH {attribution_ctes} " + (
+ _LEAD_TIME_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(granularity, "deployed_at")).replace(
+ "__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at")
+ )
+ )
+ with scan.curated.concurrent_reads() as reads:
+ headline_read = reads.submit(
+ lambda: scan.run(
+ headline_sql, query_type="engineering_analytics.dora_lead_time", placeholders=team_placeholders
+ )
+ )
+ series_read = reads.submit(
+ lambda: scan.run(
+ series_sql, query_type="engineering_analytics.dora_lead_time_series", placeholders=team_placeholders
+ )
+ )
+ headline, rows = headline_read.result(), series_read.result()
(
deployed_cur,
deployed_prev,
@@ -678,15 +694,6 @@ def _query_lead_time(
attributed_cur,
merged_cur,
) = headline.results[0] if headline.results else (0, 0, None, None, None, None, 0, 0)
-
- series_sql = f"WITH {attribution_ctes} " + (
- _LEAD_TIME_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(granularity, "deployed_at")).replace(
- "__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at")
- )
- )
- rows = scan.run(
- series_sql, query_type="engineering_analytics.dora_lead_time_series", placeholders=team_placeholders
- )
stats_by_bucket = {normalize_bucket(row[0], granularity): row[1:] for row in (rows.results or [])}
buckets = window_buckets(scan.date_from, scan.date_to, granularity)
# Row layout mirrors _LEAD_TIME_SERIES_SELECT: count, then a six-stat slice per stage.
@@ -771,7 +778,6 @@ def query_dora_overview(
deploy_sources = curated.deploy_sources()
members_source = curated.members_source()
has_membership_data = members_source is not None
- github_teams = _query_github_teams(curated, members_source)
if deploy_sources is None:
return _empty_overview(
@@ -779,7 +785,7 @@ def query_dora_overview(
environment_scope=", ".join(validated_environments) if validated_environments else "persistent",
environments=[],
has_membership_data=has_membership_data,
- github_teams=github_teams,
+ github_teams=_query_github_teams(curated, members_source),
granularity=granularity,
)
@@ -788,16 +794,25 @@ def query_dora_overview(
scan = _scan(
curated, deploy_sources, date_from=date_from, date_to=date_to, validated_environments=validated_environments
)
- outcomes = _query_deploy_outcomes(scan)
- lead = _query_lead_time(scan, github_team=github_team, members_source=members_source, granularity=granularity)
+ with curated.concurrent_reads() as reads:
+ github_teams_read = reads.submit(lambda: _query_github_teams(curated, members_source))
+ environments_read = reads.submit(lambda: scan.environment_catalog.options)
+ outcomes_read = reads.submit(lambda: _query_deploy_outcomes(scan))
+ lead_read = reads.submit(
+ lambda: _query_lead_time(
+ scan, github_team=github_team, members_source=members_source, granularity=granularity
+ )
+ )
+ frequency_read = reads.submit(lambda: _query_frequency_series(scan, granularity))
+ outcomes, lead = outcomes_read.result(), lead_read.result()
return DoraOverview(
deploy_data_available=True,
environment_scope=scan.environment_scope.scope,
- environments=scan.environment_catalog.options,
+ environments=environments_read.result(),
selected_environments=scan.environment_scope.values or [],
has_membership_data=has_membership_data,
- github_teams=github_teams,
+ github_teams=github_teams_read.result(),
deployment_count=outcomes.deployment_count,
deployment_count_prev=outcomes.deployment_count_prev,
deployments_per_day=outcomes.deployment_count / window_days,
@@ -817,7 +832,7 @@ def query_dora_overview(
merged_pr_count=lead.merged_count,
unattributed_merged_pr_share=lead.unattributed_share,
latest_deploy_status_at=outcomes.latest_status_at,
- deployment_frequency_series=_query_frequency_series(scan, granularity),
+ deployment_frequency_series=frequency_read.result(),
merge_to_deploy_series=lead.series,
open_to_merge_series=lead.open_to_merge_series,
open_to_deploy_series=lead.open_to_deploy_series,
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
index 8b6030473826..faae54a7fb9e 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
@@ -233,18 +233,31 @@ class PullRequestTimelinesQuery:
# An open PR is listed whatever its age, and one old PR would stretch every scan back months.
# A listed PR's CI is read from the same lookback the summary uses, and its timeline starts there.
run_from = max(run_from, self._date_from - CI_LOOKBACK)
- ready_at = self._query_ready_at(pr_numbers, run_from)
- reviews = self._query_reviews(pr_numbers) if include_details else None
- attempts = self._query_run_attempts(pr_numbers, run_from)
- pushes = self._query_pushes(pr_numbers, run_from)
- gates = self._query_gate_attempts(pr_numbers)
default_branch = next((row[9] for row in prs if row[9]), "")
- master_failures = self._query_master_failures(attempts, default_branch, run_from)
- out_of_queue = self._query_out_of_queue(pr_numbers)
- # Floored like the runs scan: an unfloored cost read scans the whole jobs history for a team scope.
- costs = (
- query_pr_costs(curated=self._curated, pr_numbers=pr_numbers, run_from=run_from) if include_details else {}
- )
+ with self._curated.concurrent_reads() as reads:
+ ready_at_read = reads.submit(lambda: self._query_ready_at(pr_numbers, run_from))
+ attempts_read = reads.submit(
+ lambda: self._query_run_attempts_and_master_failures(pr_numbers, run_from, default_branch)
+ )
+ pushes_read = reads.submit(lambda: self._query_pushes(pr_numbers, run_from))
+ gates_read = reads.submit(lambda: self._query_gate_attempts(pr_numbers))
+ out_of_queue_read = reads.submit(lambda: self._query_out_of_queue(pr_numbers))
+ reviews_read = reads.submit(lambda: self._query_reviews(pr_numbers) if include_details else None)
+ # Floored like the runs scan: an unfloored cost read scans the whole jobs history for a team scope.
+ costs_read = reads.submit(
+ lambda: (
+ query_pr_costs(curated=self._curated, pr_numbers=pr_numbers, run_from=run_from)
+ if include_details
+ else {}
+ )
+ )
+ ready_at = ready_at_read.result()
+ attempts, master_failures = attempts_read.result()
+ pushes = pushes_read.result()
+ gates = gates_read.result()
+ out_of_queue = out_of_queue_read.result()
+ reviews = reviews_read.result()
+ costs = costs_read.result()
items: list[PRTimeline] = []
for row in prs:
@@ -390,7 +403,9 @@ class PullRequestTimelinesQuery:
"run_started_floor": run_started_floor_constant(run_from),
}
- def _query_run_attempts(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[RunAttempt]]:
+ def _query_run_attempts_and_master_failures(
+ self, pr_numbers: list[int], run_from: datetime, default_branch: str
+ ) -> tuple[dict[int, list[RunAttempt]], MasterFailureIndex]:
rows = self._curated.run_paged(
_RUNS_SELECT.replace("__RUNS_SOURCE__", self._curated.run_source(started_floor=True)),
page_key=(("id", 0), ("ci_engine", 11)),
@@ -401,11 +416,25 @@ class PullRequestTimelinesQuery:
# A run on its first attempt that did not fail has exactly one attempt, and its run row already
# describes it. Only re-runs (earlier attempts), failures (failed job names) and runs that stopped
# reporting (whose job rows are the only settled outcome) need the jobs.
- job_attempts = self._query_job_attempts(
- [int(row[0]) for row in runs if int(row[8] or 1) > 1 or row[5] in DECISIVE_FAILURE_CONCLUSIONS or row[10]],
- run_from,
- )
+ runs_with_jobs = [
+ row for row in runs if int(row[8] or 1) > 1 or row[5] in DECISIVE_FAILURE_CONCLUSIONS or row[10]
+ ]
+ # Only these runs can report a failed job, so their workflows cover every failure the index has to
+ # explain. The master failures read therefore does not wait for the job attempts.
+ workflow_names = sorted({row[2] or "" for row in runs_with_jobs})
+ with self._curated.concurrent_reads() as reads:
+ job_attempts_read = reads.submit(
+ lambda: self._query_job_attempts([int(row[0]) for row in runs_with_jobs], run_from)
+ )
+ master_failures_read = reads.submit(
+ lambda: self._query_master_failures(workflow_names, default_branch, run_from)
+ )
+ return self._run_attempts(runs, job_attempts_read.result()), master_failures_read.result()
+ @staticmethod
+ def _run_attempts(
+ runs: list[tuple], job_attempts: dict[tuple[str, int], list[_JobAttempt]]
+ ) -> dict[int, list[RunAttempt]]:
attempts: dict[int, list[RunAttempt]] = defaultdict(list)
for (
run_id,
@@ -550,18 +579,10 @@ class PullRequestTimelinesQuery:
return by_run
def _query_master_failures(
- self, attempts: dict[int, list[RunAttempt]], default_branch: str, run_from: datetime
+ self, workflow_names: list[str], default_branch: str, run_from: datetime
) -> MasterFailureIndex:
# Filtered by workflow, not by job name: the index compares job names without their shard
# suffix, and an exact-name filter would drop the other shards of the same job.
- workflow_names = sorted(
- {
- attempt.workflow_name
- for pr_attempts in attempts.values()
- for attempt in pr_attempts
- if attempt.failed_jobs
- }
- )
jobs_source = self._curated.jobs_source(created_floor=True)
if not workflow_names or not default_branch or jobs_source is None:
return MasterFailureIndex([])
diff --git a/products/engineering_analytics/backend/logic/teams.py b/products/engineering_analytics/backend/logic/teams.py
index 8800c375730a..71ab95c7015f 100644
--- a/products/engineering_analytics/backend/logic/teams.py
+++ b/products/engineering_analytics/backend/logic/teams.py
@@ -1,7 +1,7 @@
"""Team-level orchestration: CI health rollups, per-team activity, and merge trend."""
from dataclasses import replace
-from datetime import datetime, timedelta
+from datetime import timedelta
from products.engineering_analytics.backend.facade.contracts import (
TeamCIActivity,
@@ -59,37 +59,50 @@ def build_team_ci_health(
limit = limit if limit is not None else _DEFAULT_TEAM_LIMIT
if not 1 <= limit <= _MAX_TEAM_LIMIT:
raise ValueError(f"limit must be between 1 and {_MAX_TEAM_LIMIT}")
- roster = query_team_ci_health(
- curated=curated,
- date_from=parsed_from,
- date_to=parsed_to,
- min_failed_prs=min_failed_prs,
+ window = _prior_window(parsed_from, parsed_to)
+ with curated.concurrent_reads() as reads:
+ roster_read = reads.submit(
+ lambda: query_team_ci_health(
+ curated=curated,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ min_failed_prs=min_failed_prs,
+ limit=limit,
+ owner_team=owner_team,
+ )
+ )
+ census_read = reads.submit(
+ lambda: query_census_counts(
+ curated=curated,
+ date_from=parsed_from,
+ scan_from=parsed_from - _CENSUS_LOOKBACK,
+ date_to=window.resolved_to,
+ )
+ )
+ merged_read = reads.submit(
+ lambda: query_team_merged_pr_counts(
+ curated=curated, date_from=parsed_from, scan_from=window.scan_from, date_to=window.resolved_to
+ )
+ )
+ return _enrich_roster(
+ roster_read.result(),
+ census=census_read.result(),
+ merged=merged_read.result(),
limit=limit,
owner_team=owner_team,
)
- return _enrich_roster(
- roster, curated=curated, date_from=parsed_from, date_to=parsed_to, limit=limit, owner_team=owner_team
- )
def _enrich_roster(
roster: TeamCIHealthList,
*,
- curated: CuratedGitHubSource,
- date_from: datetime,
- date_to: datetime | None,
+ census: dict[str, WindowedCount],
+ merged: dict[str, WindowedCount] | None,
limit: int,
owner_team: str | None,
) -> TeamCIHealthList:
"""Attach census and merged-PR context, and add census-only rows so a team whose tests
all pass still appears in the roster instead of vanishing with the signal."""
- window = _prior_window(date_from, date_to)
- census = query_census_counts(
- curated=curated, date_from=date_from, scan_from=date_from - _CENSUS_LOOKBACK, date_to=window.resolved_to
- )
- merged = query_team_merged_pr_counts(
- curated=curated, date_from=date_from, scan_from=window.scan_from, date_to=window.resolved_to
- )
_NO_COUNTS = WindowedCount(current=None, prior=None)
_ZERO_COUNTS = WindowedCount(current=0, prior=0)