: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
refactor(eng-analytics): validate DORA environments once (#102412)
Raúl Negrón-Otero92551ad547f1
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex ae8861d85679..e348209de1e2 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -7,14 +7,14 @@ parameters and return canonical contract types.``repo`` is an optional ``owner/name`` filter, applied against the curated repoidentity (mapped from ``base.repo.full_name``). ``branch`` is an optional exact``head_branch`` filter for workflow health, a workflow's runs list, and its runner-costs; the same surfaces also take a broader ``run_scope`` filter that selects one of-four run groups (``all``, ``default_branch``, ``pull_request``, ``merge_queue``). ``date_from`` / ``date_to`` accept+costs; the same surfaces also take a broader ``run_scope`` filter (see+``WorkflowHealthRunScope``). ``date_from`` / ``date_to`` acceptrelative strings (``-30d``) or ISO8601 and are resolved against the team timezone.``source_id`` selects a specific connected GitHub source when the team has more thanone; it defaults to the oldest connected source. ``user_access_control`` enforces therequesting user's per-source warehouse access (pass the request's; ``None`` for systemcontexts). Each function resolves the team's authorized curated read handle once, here,-then delegates to the read layer — source selection and access control live in this layer,+then delegates to the read layer: source selection and access control live in this layer,not in the query builders below it."""@@ -75,11 +75,11 @@ def _authorized_source(user_access_control: "UserAccessControl | None",repo: str | None = None,) -> "CuratedGitHubSource":- """Resolve this caller's curated read handle — the single place source selection and per-source+ """Resolve this caller's curated read handle: the single place source selection and per-sourcewarehouse access control happen. ``user_access_control`` (None for system/Temporal/CLI contexts)filters out sources the requesting user can't access; ``source_id`` selects a specific source,else the oldest connected. ``repo`` ('owner/name'), when the caller already scopes to one repo,- prefers the source connected for that repo — so a team with one source per repository reads the+ prefers the source connected for that repo, so a team with one source per repository reads theright one. Raises ``GitHubSourceNotConnectedError`` / ``ValueError`` (bad source_id)."""return logic.CuratedGitHubSource.for_team(@@ -164,11 +164,11 @@ def resolve_branch(source_id: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> list[BranchPRMatch]:- """Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam+ """Resolve a git branch to the pull request(s) it belongs to: the cross-product link seam(LLM analytics links a git branch to a PR detail page). ``branch`` is required; ``repo``('owner/name') optionally narrows to one repository. ``timestamp`` (the trace's capture time)prefers the PR that was active at that moment when a branch name was reused across PRs over- time — a ranking hint only, never a filter.+ time. It is a ranking hint only, never a filter."""return logic.build_resolve_branch(curated=_authorized_source(team, source_id, user_access_control, repo=repo),@@ -402,7 +402,7 @@ def list_recently_merged_pull_requests(user_access_control: "UserAccessControl | None" = None,) -> list[MergedPullRequest]:"""Merged pull requests in ``repository`` ('owner/name'), newest first, each with its branch-tip- ``head_sha`` — the discovery seam for ReviewHog telemetry. Raises+ ``head_sha``: the discovery seam for ReviewHog telemetry. Raises``GitHubSourceNotConnectedError`` (propagated to the caller) when no GitHub source is connected.Ask one of two ways. ``numbers`` returns exactly those PRs whatever their merge date, which is@@ -552,7 +552,7 @@ def get_quarantine(user_access_control: "UserAccessControl | None" = None,) -> QuarantineFile:# Quarantine resolves its source lazily (DEBUG reads the local checkout, an explicit ``repo`` needs- # no source) so it stays fail-open where the curated reads above don't — ``source_id`` /+ # no source) so it stays fail-open where the curated reads above don't. ``source_id`` /# ``user_access_control`` only matter when it falls back to the connected source's most-active repo.return logic.build_quarantine(team=team, repo=repo, source_id=source_id, user_access_control=user_access_control)@@ -589,41 +589,25 @@ def get_dora_overview(team: Team,date_from: str | None = None,date_to: str | None = None,- validated_environments: list[str] | None = None,+ environments: list[str] | None = None,github_team: str | None = None,granularity: str | None = None,source_id: str | None = None,repo: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> DoraOverview:+ """Raises ``UnknownDoraEnvironmentError`` when ``environments`` names an environment the source+ did not deploy to in the scan window."""return logic.build_dora_overview(curated=_authorized_source(team, source_id, user_access_control, repo=repo),date_from=date_from,date_to=date_to,- validated_environments=validated_environments,+ environments=environments,github_team=github_team,granularity=granularity,)-def get_dora_environment_choices(- environments: list[str],- *,- team: Team,- date_from: str | None = None,- date_to: str | None = None,- source_id: str | None = None,- repo: str | None = None,- user_access_control: "UserAccessControl | None" = None,-) -> list[str]:- return logic.get_dora_environment_choices(- environments=environments,- curated=_authorized_source(team, source_id, user_access_control, repo=repo),- date_from=date_from,- date_to=date_to,- )--def get_current_branch_health(*,team: Team,@@ -708,10 +692,6 @@ def list_job_aggregates(def resolve_path_owners(repository: str, paths: Sequence[str]) -> PathOwnership:- """Name the team that owns each repository path, from the repository's own ownership files.-- No team parameter: the answer comes from the repository as it stands on its default branch, not- from anything this PostHog team stores. Callers outside this product reach it here so the fetch,- the cache, and the failure contract stay in one place.- """+ """Name the team that owns each repository path, from the ownership files on the repository's+ default branch. It takes no team, because nothing PostHog stores feeds the answer."""return logic.resolve_path_owners(repository, paths)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex bdcb1d74de62..30b17e740685 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -74,6 +74,16 @@ class QuarantineWriteError(Exception):super().__init__(message)+class UnknownDoraEnvironmentError(Exception):+ """A DORA read named deploy environments the source did not deploy to in the scan window.+ Framework-free; the presentation layer maps it to a 400 on the ``environment`` parameter.+ """++ def __init__(self, environments: list[str]) -> None:+ super().__init__(f"Unknown deploy environments: {', '.join(environments)}")+ self.environments = environments++class PRState(StrEnum):OPEN = "open"CLOSED = "closed"diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 0e531b4a6791..7be065ddb740 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -24,10 +24,7 @@ from products.engineering_analytics.backend.logic.delivery import (build_pull_request_timelines as build_pull_request_timelines,)from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope as DeliveryScope-from products.engineering_analytics.backend.logic.dora import (- build_dora_overview as build_dora_overview,- get_dora_environment_choices as get_dora_environment_choices,-)+from products.engineering_analytics.backend.logic.dora import build_dora_overview as build_dora_overviewfrom products.engineering_analytics.backend.logic.ownership import resolve_path_owners as resolve_path_ownersfrom products.engineering_analytics.backend.logic.pull_requests import (build_author_workflow_costs as build_author_workflow_costs,diff --git a/products/engineering_analytics/backend/logic/dora.py b/products/engineering_analytics/backend/logic/dora.pyindex 512ec94247e0..86da429f3503 100644--- a/products/engineering_analytics/backend/logic/dora.py+++ b/products/engineering_analytics/backend/logic/dora.py@@ -1,8 +1,9 @@"""Orchestration for the DORA deploy-metrics read."""+from datetime import datetimefrom typing import cast, get_args-from products.engineering_analytics.backend.facade.contracts import DoraOverview+from products.engineering_analytics.backend.facade.contracts import DoraOverview, UnknownDoraEnvironmentErrorfrom products.engineering_analytics.backend.logic._shared import _DEFAULT_WINDOW, _parse_windowfrom products.engineering_analytics.backend.logic.queries._buckets import Granularityfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource@@ -19,11 +20,12 @@ def build_dora_overview(curated: CuratedGitHubSource,date_from: str | None = None,date_to: str | None = None,- validated_environments: list[str] | None = None,+ environments: list[str] | None = None,github_team: str | None = None,granularity: str | None = None,) -> DoraOverview:parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)+ selected = None if environments is None else _known_environments(curated, environments, parsed_from, parsed_to)parsed_granularity: Granularity | None = Noneif granularity:if granularity not in _GRANULARITIES:@@ -33,16 +35,20 @@ def build_dora_overview(curated=curated,date_from=parsed_from,date_to=parsed_to,- validated_environments=validated_environments,+ validated_environments=selected,github_team=(github_team or "").strip() or None,granularity=parsed_granularity,)-def get_dora_environment_choices(- *, curated: CuratedGitHubSource, environments: list[str], date_from: str | None = None, date_to: str | None = None+def _known_environments(+ curated: CuratedGitHubSource, requested: list[str], date_from: datetime, date_to: datetime | None) -> list[str]:- parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)- return query_dora_environment_choices(- curated=curated, environments=environments, date_from=parsed_from, date_to=parsed_to+ names = list(dict.fromkeys(name.strip() for name in requested))+ known = set(+ query_dora_environment_choices(curated=curated, environments=names, date_from=date_from, date_to=date_to))+ unknown = [name for name in names if name not in known]+ if unknown:+ raise UnknownDoraEnvironmentError(unknown)+ return namesdiff --git a/products/engineering_analytics/backend/logic/queries/dora.py b/products/engineering_analytics/backend/logic/queries/dora.pyindex c9ec4b3bd4f3..70281e9eef6e 100644--- a/products/engineering_analytics/backend/logic/queries/dora.py+++ b/products/engineering_analytics/backend/logic/queries/dora.py@@ -4,30 +4,31 @@ Four quadrants, honestly named (SPEC §4):- Deployment frequency: deployments whose first ``success`` status landed in thewindow, within the environment scope. Computed directly.-- Lead time: ``merge_to_deploy_seconds`` — a merged PR's wait until the first+- Lead time: ``merge_to_deploy_seconds``, a merged PR's wait until the firstsuccessful deployment that *contains* its merge. Containment is resolved throughthe deploy's head commit: its SHA resolves to a merged PR through ``merge_commit_sha``or the workflow-run builder's ``commit_pr_number`` fallback. Every merge at or beforethat head merge is on board. Success time alone- cannot decide this — deploys ship pre-built images, so a deploy routinely+ cannot decide this: deploys ship pre-built images, so a deploy routinelysucceeds *after* a merge it does not contain. The field name says merge-to-deploy,not the full commit-to-deploy DORA definition (pre-merge time is measured elsewhere).- ``open_to_deploy_seconds`` — open to first successful deploy over the same- population — is the full-span headline the Health tile shows.-- Change failure: ``failed_deployment_share`` — deployments with a failure/error+ ``open_to_deploy_seconds`` (open to first successful deploy over the same+ population) is the full-span headline the Health tile shows.+- Change failure: ``failed_deployment_share``, deployments with a failure/errorstatus over deployments that reached any outcome. A proxy: no incident link, soa deploy that succeeded but broke production is invisible.-- Restore: ``median_failed_deploy_to_next_success_seconds`` — first failure status+- Restore: ``median_failed_deploy_to_next_success_seconds``, first failure statusto the next successful deployment in the same environment. A proxy: recovery byanything other than a deploy is invisible, and unrecovered failures are excluded.The PR-scoped lead-time reads follow the locked cycle-time recipe (bots and drafts-excluded) and accept the ``team_members`` join for a GitHub-team filter — a team-surface, aggregates only (SPEC §6). Deploy counts are repo events and ignore the+excluded) and accept the ``team_members`` join for a GitHub-team filter, a team+surface with aggregates only (SPEC §6). Deploy counts are repo events and ignore theteam filter by design."""from datetime import datetime, timedelta+from functools import cached_propertyfrom typing import Anyfrom posthog.schema import HogQLQueryResponse@@ -37,10 +38,12 @@ from posthog.hogql import astfrom posthog.dataclasses import frozenfrom products.engineering_analytics.backend.facade.contracts import (+ DeliveryScopeKind,DeploymentFrequencyBucket,DoraOverview,LeadTimeBucket,)+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScopefrom products.engineering_analytics.backend.logic.queries._buckets import (Granularity,bucket_expr,@@ -51,6 +54,7 @@ from products.engineering_analytics.backend.logic.queries._buckets import (from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, DeploySources, opt_floatfrom products.engineering_analytics.backend.logic.queries._workflow_filters import (UNPAGED_SCAN_LIMIT,+ date_to_filter_clause,run_started_floor_constant,window_pair_predicates,)@@ -73,7 +77,7 @@ _TEAMS_LIMIT = 500# One row per deployment with its outcome timestamps: statuses are append-only transitions, so the# first success / first failure are the outcome edges every read keys on. INNER JOIN drops-# deployments with no status rows — they never reached an outcome. __ENV_PREDICATE__ is one of the+# deployments with no status rows, because they never reached an outcome. __ENV_PREDICATE__ is one of the# trusted variants below (never user input; the exact-match variant reads a placeholder).# Assumes one deployment id per attempt (GitHub's normal shape): a deployment carrying both a# failure and a later success status on the same id would count toward both outcomes and could@@ -162,16 +166,11 @@ _FREQUENCY_SERIES_SELECT = """# merged PR, and that PR's merged_at says which merges the deploy contains. The sanctioned# merge_commit_sha exception (SPEC §6): gated on merged_at (an open PR carries a throwaway# test-merge SHA) and collapsed to one row per deployment (min breaks a shared-SHA tie).-# Missing merge SHAs can resolve through the shared workflow-run attribution, restricted to the-# same repo's default branch. Direct merge-SHA evidence wins over inferred commit-message evidence,-# so the candidate PR must carry no merge commit at all: one that names a commit other than the-# deployed SHA is evidence the suffix is lying, not evidence the deploy carries that PR.-# The candidate PR must also merge INTO that branch: a cherry-pick keeps the original subject line,-# so a release-branch PR's (#N) suffix can ride a default-branch commit and hand the deploy an-# earlier head merge than the one it really contains.-# The merge is bounded by the deployment REQUEST, not its success: GitHub fixes the deployed SHA-# when it creates the record, so a PR merging while the deploy runs cannot have produced that-# commit. Crediting it would over-attribute — every merge at or before it reads as contained.+# A deploy SHA with no merge_commit_sha match falls back to the workflow-run commit_pr_number on+# the same repo's default branch. The candidate PR must have no merge commit of its own, because+# one that names another commit means the (#N) suffix is wrong. It must merge into that branch,+# because a cherry-pick keeps a release-branch PR's subject. It must merge before the deployment+# was created, because GitHub fixes the deployed SHA at creation.# Bot merges stay in as heads on purpose: a bot's merge commit still names what a deploy contains._DEPLOY_HEADS_CTE = """merge_heads AS (@@ -246,10 +245,15 @@ _DEPLOYED_PRS_CTE = """)"""-# The three lead-time stages, one row per deployed PR: the box-plot series all read the SAME-# population, so open → merge and merge → deploy visually compose into open → deploy.+# The three lead-time stages, one row per deployed PR. Every lead-time read selects from here, so the+# box-plot series and the delivery summary's rows measure the SAME population and stages, and+# open → merge and merge → deploy compose into open → deploy._LEAD_TIME_INNER = """SELECT+ number,+ author_handle,+ created_at,+ merged_at,deployed_at,dateDiff('second', merged_at, deployed_at) AS lead_seconds,dateDiff('second', created_at, merged_at) AS open_to_merge_seconds,@@ -259,7 +263,7 @@ _LEAD_TIME_INNER = """# The two one-row CROSS JOIN halves put attribution coverage on the same round trip: how many# PRs merged in the window at all (same bot/draft/team recipe), and how many of those an-# in-scope deployment attributed — the honest denominator behind unattributed_merged_pr_share.+# in-scope deployment attributed: the honest denominator behind unattributed_merged_pr_share._LEAD_TIME_HEADLINE_SELECT = f"""SELECTlead.deployed_cur,@@ -363,16 +367,66 @@ _TEAMS_SELECT = f"""LIMIT {_TEAMS_LIMIT}"""-_TEAM_FILTER = (- "AND pr.author_handle IN (SELECT member_handle FROM __MEMBERS_SOURCE__ AS m WHERE m.team_slug = {github_team})"-)-def _date_to_clause(date_to: datetime | None, column: str) -> str:"""The optional window-end clause on ``column``; empty when the window is open-ended."""return f"AND {column} <= {{date_to}}" if date_to is not None else ""+def _environment_scan_floor(date_from: datetime, date_to: datetime) -> datetime:+ prev_from = date_from - (date_to - date_from)+ return min(prev_from - _DEPLOY_SCAN_SLACK, date_to - _ENVIRONMENT_LOOKBACK)+++def _sorted_names(rows: list[Any]) -> list[str]:+ names = rows[0][0] if rows else []+ return sorted(str(name) for name in names or [] if name)+++@frozen(slots=False)+class _EnvironmentCatalog:+ """The environment names a source deployed to around one window. Each list is its own ClickHouse+ read and runs on first use, so a read that only needs the production default skips the rest."""++ curated: CuratedGitHubSource+ deployments_source: str+ date_from: datetime+ date_to: datetime | None++ def _rows(self, select: str, *, query_type: str, placeholders: dict[str, ast.Expr] | None = None) -> list[Any]:+ end = self.date_to or datetime.now(tz=self.date_from.tzinfo)+ bound: dict[str, ast.Expr] = {+ "environment_scan_floor": ast.Constant(value=_environment_scan_floor(self.date_from, end)),+ **(placeholders or {}),+ }+ sql = select.replace("__DEPLOYMENTS_SOURCE__", self.deployments_source).replace(+ "__DATE_TO_CREATED__", date_to_filter_clause(self.date_to, bound, column="d.created_at")+ )+ return self.curated.run(sql, query_type=query_type, placeholders=bound).results or []++ @cached_property+ def options(self) -> list[str]:+ """The picker's options: persistent environments deployed to in the scan window, most-deployed first."""+ rows = self._rows(_ENVIRONMENTS_SELECT, query_type="engineering_analytics.dora_environments")+ return [str(name) for name, _ in rows if name]++ @cached_property+ def production(self) -> list[str]:+ return _sorted_names(+ self._rows(_PRODUCTION_ENVIRONMENTS_SELECT, query_type="engineering_analytics.dora_production_environments")+ )++ def existing(self, names: list[str]) -> list[str]:+ """The given names the source deployed to in the scan window, transient environments included."""+ return _sorted_names(+ self._rows(+ _ENVIRONMENT_CHOICES_SELECT,+ query_type="engineering_analytics.dora_environment_choices",+ placeholders={"requested_environments": ast.Tuple(exprs=[ast.Constant(value=n) for n in names])},+ )+ )++@frozenclass _EnvironmentScope:# 'persistent', or the exact environment name(s) the scope resolved to (see DoraOverview).@@ -383,53 +437,55 @@ class _EnvironmentScope:# None for the predicate variants that match by flag rather than by name.values: list[str] | None+ @classmethod+ def named(cls, names: list[str]) -> "_EnvironmentScope":+ return cls(scope=", ".join(names), predicate="d.environment IN {environments}", values=names)+@frozenclass _DoraScan:- """One request's bound scan state — the curated handle, the environment-scoped deploys CTE,- the shared placeholder registry, and the window — composed by every deploy sub-query."""+ """One request's bound deploy scan: the curated handle, the resolved environment scope and its+ deploys CTE, the placeholders every deploy sub-query shares, and the window."""curated: CuratedGitHubSource+ environment_catalog: _EnvironmentCatalog+ environment_scope: _EnvironmentScopedeploys_cte: strstatuses_source: strplaceholders: dict[str, ast.Expr]date_from: datetimedate_to: datetime | None- granularity: Granularity- def run(self, sql: str, *, query_type: str) -> HogQLQueryResponse:- return self.curated.run(sql, query_type=query_type, placeholders=self.placeholders)+ def run(self, sql: str, *, query_type: str, placeholders: dict[str, ast.Expr] | None = None) -> HogQLQueryResponse:+ """Run ``sql`` with the shared placeholders plus ``placeholders`` that only this read binds."""+ return self.curated.run(sql, query_type=query_type, placeholders={**self.placeholders, **(placeholders or {})})def date_to_filter(self, column: str) -> str:return _date_to_clause(self.date_to, column)- def window_buckets(self) -> list[datetime]:- return window_buckets(self.date_from, self.date_to, self.granularity)+ def attribution_ctes(self, *, pr_filter: str = "") -> str:+ """The deploys, deploy heads and deployed PRs CTEs. ``pr_filter`` is a trusted ``AND`` clause+ over the pull request source aliased ``pr``."""+ return (+ f"{self.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE}".replace(+ "__PR_SOURCE__", self.curated.pr_source()+ )+ .replace("__RUNS_SOURCE__", self.curated.run_source(started_floor=True))+ .replace("__TEAM_FILTER__", pr_filter)+ )def _resolve_environment_scope(- requested_environments: list[str] | None,- environments: list[str],- production_environments: list[str],+ requested_environments: list[str] | None, catalog: _EnvironmentCatalog) -> _EnvironmentScope:if requested_environments is not None:if requested_environments:- return _EnvironmentScope(- scope=", ".join(requested_environments),- predicate="d.environment IN {environments}",- values=requested_environments,- )+ return _EnvironmentScope.named(requested_environments)return _EnvironmentScope(scope="No matching environments", predicate="0 = 1", values=[])-- if production_environments:- return _EnvironmentScope(- scope=", ".join(production_environments),- predicate="d.environment IN {environments}",- values=production_environments,- )- if environments:- fallback = environments[0]- return _EnvironmentScope(scope=fallback, predicate="d.environment IN {environments}", values=[fallback])+ if catalog.production:+ return _EnvironmentScope.named(catalog.production)+ if catalog.options:+ return _EnvironmentScope.named(catalog.options[:1])return _EnvironmentScope(scope="persistent", predicate="NOT d.is_transient_environment", values=None)@@ -490,7 +546,7 @@ class _DeployOutcomes:# Median failed-deploy-to-next-success seconds (the restore proxy); None when nothing recovered.restore_median_seconds: float | Nonerestore_median_seconds_prev: float | None- # The newest status row synced, any environment — how fresh the deploy data is.+ # The newest status row synced in any environment, which shows how fresh the deploy data is.latest_status_at: datetime | None@property@@ -530,21 +586,20 @@ def _query_deploy_outcomes(scan: _DoraScan) -> _DeployOutcomes:)-def _query_frequency_series(scan: _DoraScan) -> list[DeploymentFrequencyBucket]:+def _query_frequency_series(scan: _DoraScan, granularity: Granularity) -> list[DeploymentFrequencyBucket]:"""Successful deployments per bucket across the window, oldest first, zero-filled."""sql = f"WITH {scan.deploys_cte} " + (- _FREQUENCY_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(scan.granularity, "first_success_at")).replace(+ _FREQUENCY_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(granularity, "first_success_at")).replace("__DATE_TO_SUCCESS__", scan.date_to_filter("first_success_at")))response = scan.run(sql, query_type="engineering_analytics.dora_frequency")count_by_bucket = {- normalize_bucket(bucket_start, scan.granularity): int(count or 0)- for bucket_start, count in response.results or []+ normalize_bucket(bucket_start, granularity): int(count or 0) for bucket_start, count in response.results or []}return [DeploymentFrequencyBucket(bucket_start=bucket, deployment_count=count_by_bucket.get(bucket, 0))- for bucket in scan.window_buckets()+ for bucket in window_buckets(scan.date_from, scan.date_to, granularity)]@@ -586,21 +641,20 @@ _EMPTY_LEAD_TIME = _LeadTime()-def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source: str | None) -> _LeadTime:+def _query_lead_time(+ scan: _DoraScan, *, github_team: str | None, members_source: str | None, granularity: Granularity+) -> _LeadTime:# A team filter without membership data cannot be honored: empty lead-time figures, never# silently unfiltered ones.if github_team and members_source is None:return _EMPTY_LEAD_TIMEteam_filter = ""- if github_team and members_source is not None:- scan.placeholders["github_team"] = ast.Constant(value=github_team)- team_filter = _TEAM_FILTER.replace("__MEMBERS_SOURCE__", members_source)- pr_source = scan.curated.pr_source()- attribution_ctes = (- f"{scan.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE}".replace("__PR_SOURCE__", pr_source)- .replace("__RUNS_SOURCE__", scan.curated.run_source(started_floor=True))- .replace("__TEAM_FILTER__", team_filter)- )+ team_placeholders: dict[str, ast.Expr] = {}+ if github_team:+ team = DeliveryScope(kind=DeliveryScopeKind.GITHUB_TEAM, github_team=github_team)+ team_filter = f"AND {team.pr_predicate(members_source=members_source)}"+ team_placeholders = team.placeholders()+ attribution_ctes = scan.attribution_ctes(pr_filter=team_filter)windows = window_pair_predicates("deployed_at", date_to=scan.date_to)merged_window = window_pair_predicates("merged_at", date_to=scan.date_to)@@ -608,10 +662,10 @@ def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source_LEAD_TIME_HEADLINE_SELECT.replace("__CUR_DEPLOYED__", windows.current).replace("__PREV_DEPLOYED__", windows.previous).replace("__CUR_MERGED__", merged_window.current)- .replace("__PR_SOURCE__", pr_source)+ .replace("__PR_SOURCE__", scan.curated.pr_source()).replace("__TEAM_FILTER__", team_filter))- headline = scan.run(headline_sql, query_type="engineering_analytics.dora_lead_time")+ headline = scan.run(headline_sql, query_type="engineering_analytics.dora_lead_time", placeholders=team_placeholders)(deployed_cur,deployed_prev,@@ -624,13 +678,15 @@ def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source) = 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(scan.granularity, "deployed_at")).replace(+ _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")- stats_by_bucket = {normalize_bucket(row[0], scan.granularity): row[1:] for row in (rows.results or [])}- buckets = scan.window_buckets()+ 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.return _LeadTime(deployed_count=int(deployed_cur or 0),@@ -653,23 +709,14 @@ def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source)-@frozen-class _ScopedScan:- scan: _DoraScan- environment_scope: _EnvironmentScope- # The picker's options: persistent environments deployed to in the scan window.- environments: list[str]---def _scoped_scan(+def _scan(curated: CuratedGitHubSource,deploy_sources: DeploySources,*,date_from: datetime,date_to: datetime | None,validated_environments: list[str] | None,- granularity: Granularity,-) -> _ScopedScan:+) -> _DoraScan:"""Resolve the environment scope and bind the deploys CTE and placeholders every deploy read shares."""end = date_to or datetime.now(tz=date_from.tzinfo)prev_from = date_from - (end - date_from)@@ -677,7 +724,6 @@ def _scoped_scan(placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),- "environment_scan_floor": ast.Constant(value=_environment_scan_floor(date_from, end)),"deploy_scan_floor": ast.Constant(value=prev_from - _DEPLOY_SCAN_SLACK),"merge_scan_floor": ast.Constant(value=prev_from - _MERGE_SCAN_LOOKBACK),"run_started_floor": run_started_floor_constant(prev_from - _MERGE_SCAN_LOOKBACK),@@ -685,34 +731,19 @@ def _scoped_scan(if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)- environments = _query_environments(- curated,- deploy_sources.deployments,- placeholders=placeholders,- date_to_filter=_date_to_clause(date_to, "d.created_at"),- )- production_environments = (- _query_production_environments(- curated,- deploy_sources.deployments,- placeholders=placeholders,- date_to_filter=_date_to_clause(date_to, "d.created_at"),- )- if validated_environments is None- else []- )- env_scope = _resolve_environment_scope(- validated_environments,- environments,- production_environments,+ catalog = _EnvironmentCatalog(+ curated=curated, deployments_source=deploy_sources.deployments, date_from=date_from, date_to=date_to)+ env_scope = _resolve_environment_scope(validated_environments, catalog)# The busiest-environment fallbacks bind the same placeholder as an explicit filter: either# way ``values`` holds exactly the environment names the predicate matches.if env_scope.values is not None:placeholders["environments"] = ast.Tuple(exprs=[ast.Constant(value=name) for name in env_scope.values])- scan = _DoraScan(+ return _DoraScan(curated=curated,+ environment_catalog=catalog,+ environment_scope=env_scope,deploys_cte=(_DEPLOYS_CTE.replace("__DEPLOYMENTS_SOURCE__", deploy_sources.deployments).replace("__STATUSES_SOURCE__", deploy_sources.statuses)@@ -722,9 +753,7 @@ def _scoped_scan(placeholders=placeholders,date_from=date_from,date_to=date_to,- granularity=granularity,)- return _ScopedScan(scan=scan, environment_scope=env_scope, environments=environments)def query_dora_overview(@@ -754,23 +783,17 @@ def query_dora_overview(end = date_to or datetime.now(tz=date_from.tzinfo)window_days = max((end - date_from).total_seconds() / 86400, 1 / 24)- scoped = _scoped_scan(- curated,- deploy_sources,- date_from=date_from,- date_to=date_to,- validated_environments=validated_environments,- granularity=granularity,+ scan = _scan(+ curated, deploy_sources, date_from=date_from, date_to=date_to, validated_environments=validated_environments)- scan, env_scope, environments = scoped.scan, scoped.environment_scope, scoped.environmentsoutcomes = _query_deploy_outcomes(scan)- lead = _query_lead_time(scan, github_team=github_team, members_source=members_source)+ lead = _query_lead_time(scan, github_team=github_team, members_source=members_source, granularity=granularity)return DoraOverview(deploy_data_available=True,- environment_scope=env_scope.scope,- environments=environments,- selected_environments=env_scope.values or [],+ environment_scope=scan.environment_scope.scope,+ environments=scan.environment_catalog.options,+ selected_environments=scan.environment_scope.values or [],has_membership_data=has_membership_data,github_teams=github_teams,deployment_count=outcomes.deployment_count,@@ -792,7 +815,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),+ deployment_frequency_series=_query_frequency_series(scan, granularity),merge_to_deploy_series=lead.series,open_to_merge_series=lead.open_to_merge_series,open_to_deploy_series=lead.open_to_deploy_series,@@ -801,11 +824,19 @@ def query_dora_overview(# Every deployed PR relevant to one window, one row each: deployed in the window (the distribution-# population) or merged in it (the attribution-coverage population). The author page splits the+# population) or merged in it (the attribution-coverage population). The delivery summary splits the# rows in Python, so the containment rule stays defined once, in the CTEs above._DEPLOYED_PR_ROWS_SELECT = f"""- SELECT number, (__SCOPE__) AS in_scope, created_at, merged_at, deployed_at- FROM deployed_prs+ SELECT+ number,+ (__SCOPE__) AS in_scope,+ created_at,+ merged_at,+ deployed_at,+ open_to_merge_seconds,+ lead_seconds,+ open_to_deploy_seconds+ FROM ({_LEAD_TIME_INNER})WHERE (deployed_at >= {{date_from}} __DATE_TO_DEPLOYED__) OR (merged_at >= {{date_from}} __DATE_TO_MERGED__)LIMIT {UNPAGED_SCAN_LIMIT}"""@@ -814,12 +845,14 @@ _DEPLOYED_PR_ROWS_SELECT = f"""@frozenclass DeployedPR:number: int- # True when the caller's scope predicate matches the PR.in_scope: boolcreated_at: datetimemerged_at: datetime# The first successful in-scope deployment that contains the merge.deployed_at: datetime+ open_to_merge_seconds: int+ merge_to_deploy_seconds: int+ open_to_deploy_seconds: int@frozen@@ -843,29 +876,13 @@ def query_deployed_prs(deploy_sources = curated.deploy_sources()if deploy_sources is None:return None- scoped = _scoped_scan(- curated,- deploy_sources,- date_from=date_from,- date_to=date_to,- validated_environments=None,- granularity=pick_granularity(date_from, date_to),- )- scan = scoped.scan- pr_source = curated.pr_source()- sql = f"WITH {scan.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE} " + (- _DEPLOYED_PR_ROWS_SELECT.replace("__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at")).replace(- "__DATE_TO_MERGED__", scan.date_to_filter("merged_at")- )- )- sql = (- sql.replace("__PR_SOURCE__", pr_source)- .replace("__RUNS_SOURCE__", curated.run_source(started_floor=True))- .replace("__TEAM_FILTER__", "")+ scan = _scan(curated, deploy_sources, date_from=date_from, date_to=date_to, validated_environments=None)+ sql = f"WITH {scan.attribution_ctes()} " + (+ _DEPLOYED_PR_ROWS_SELECT.replace("__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at"))+ .replace("__DATE_TO_MERGED__", scan.date_to_filter("merged_at")).replace("__SCOPE__", scope_predicate))- scan.placeholders.update(scope_placeholders)- response = scan.run(sql, query_type="engineering_analytics.deployed_pr_rows")+ response = scan.run(sql, query_type="engineering_analytics.deployed_pr_rows", placeholders=scope_placeholders)rows = [DeployedPR(number=int(number),@@ -873,11 +890,16 @@ def query_deployed_prs(created_at=created_at,merged_at=merged_at,deployed_at=deployed_at,+ open_to_merge_seconds=int(open_to_merge),+ merge_to_deploy_seconds=int(merge_to_deploy),+ open_to_deploy_seconds=int(open_to_deploy),+ )+ for number, in_scope, created_at, merged_at, deployed_at, open_to_merge, merge_to_deploy, open_to_deploy in (+ response.results or [])- for number, in_scope, created_at, merged_at, deployed_at in response.results or []if created_at is not None and merged_at is not None and deployed_at is not None]- return DeployedPRs(environment_scope=scoped.environment_scope.scope, rows=rows)+ return DeployedPRs(environment_scope=scan.environment_scope.scope, rows=rows)def _lead_time_bucket(bucket: datetime, stats: tuple[Any, ...] | None, *, stage: int) -> LeadTimeBucket:@@ -913,45 +935,6 @@ def _lead_time_bucket(bucket: datetime, stats: tuple[Any, ...] | None, *, stage:)-def _query_environments(- curated: CuratedGitHubSource,- deployments_source: str,- *,- placeholders: dict[str, ast.Expr],- date_to_filter: str,-) -> list[str]:- """Persistent environments deployed to in the scan window, most-deployed first."""- sql = _ENVIRONMENTS_SELECT.replace("__DEPLOYMENTS_SOURCE__", deployments_source).replace(- "__DATE_TO_CREATED__", date_to_filter- )- response = curated.run(sql, query_type="engineering_analytics.dora_environments", placeholders=placeholders)- return [str(name) for name, _ in (response.results or []) if name]---def _environment_scan_floor(date_from: datetime, date_to: datetime) -> datetime:- prev_from = date_from - (date_to - date_from)- return min(prev_from - _DEPLOY_SCAN_SLACK, date_to - _ENVIRONMENT_LOOKBACK)---def _query_production_environments(- curated: CuratedGitHubSource,- deployments_source: str,- *,- placeholders: dict[str, ast.Expr],- date_to_filter: str,-) -> list[str]:- sql = _PRODUCTION_ENVIRONMENTS_SELECT.replace("__DEPLOYMENTS_SOURCE__", deployments_source).replace(- "__DATE_TO_CREATED__", date_to_filter- )- response = curated.run(- sql,- query_type="engineering_analytics.dora_production_environments",- placeholders=placeholders,- )- names = response.results[0][0] if response.results else []- return sorted(str(name) for name in names or [] if name)--def query_dora_environment_choices(*,curated: CuratedGitHubSource,@@ -959,30 +942,18 @@ def query_dora_environment_choices(date_from: datetime,date_to: datetime | None,) -> list[str]:+ """The ``environments`` the source deployed to in the scan window; empty without deploy data."""deploy_sources = curated.deploy_sources()if deploy_sources is None or not environments:return []- end = date_to or datetime.now(tz=date_from.tzinfo)- placeholders: dict[str, ast.Expr] = {- "environment_scan_floor": ast.Constant(value=_environment_scan_floor(date_from, end)),- "requested_environments": ast.Tuple(exprs=[ast.Constant(value=name) for name in environments]),- }- if date_to is not None:- placeholders["date_to"] = ast.Constant(value=date_to)- sql = _ENVIRONMENT_CHOICES_SELECT.replace("__DEPLOYMENTS_SOURCE__", deploy_sources.deployments).replace(- "__DATE_TO_CREATED__", _date_to_clause(date_to, "d.created_at")+ catalog = _EnvironmentCatalog(+ curated=curated, deployments_source=deploy_sources.deployments, date_from=date_from, date_to=date_to)- response = curated.run(- sql,- query_type="engineering_analytics.dora_environment_choices",- placeholders=placeholders,- )- names = response.results[0][0] if response.results else []- return sorted(str(name) for name in names or [] if name)+ return catalog.existing(environments)def _query_github_teams(curated: CuratedGitHubSource, members_source: str | None) -> list[str]:- """Distinct GitHub team slugs from the membership snapshot — the team filter's options."""+ """Distinct GitHub team slugs from the membership snapshot: the team filter's options."""if members_source is None:return []response = curated.run(diff --git a/products/engineering_analytics/backend/presentation/serializers/dora.py b/products/engineering_analytics/backend/presentation/serializers/dora.pyindex a8040bafa727..9e7b94424cf5 100644--- a/products/engineering_analytics/backend/presentation/serializers/dora.py+++ b/products/engineering_analytics/backend/presentation/serializers/dora.py@@ -19,13 +19,6 @@ class DoraEnvironmentQuerySerializer(serializers.Serializer):"are rejected. Real transient environments are allowed. Omit to use the production default.",)- def validate_environment(self, value: list[str]) -> list[str]:- names = list(dict.fromkeys(value))- choice = serializers.ChoiceField(choices=self.context["get_environment_choices"](names))- for name in names:- choice.run_validation(name)- return names-class DeploymentFrequencyBucketSerializer(DataclassSerializer):class Meta:diff --git a/products/engineering_analytics/backend/presentation/views/dora.py b/products/engineering_analytics/backend/presentation/views/dora.pyindex d7e80ac10811..c544e8a8f3f0 100644--- a/products/engineering_analytics/backend/presentation/views/dora.py+++ b/products/engineering_analytics/backend/presentation/views/dora.py@@ -1,14 +1,14 @@"""DORA deploy-metrics read."""-from functools import partial-from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from rest_framework import serializersfrom rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom products.engineering_analytics.backend.facade import api+from products.engineering_analytics.backend.facade.contracts import UnknownDoraEnvironmentErrorfrom products.engineering_analytics.backend.presentation.serializers.dora import (DoraEnvironmentQuerySerializer,DoraOverviewSerializer,@@ -29,8 +29,8 @@ _ENVIRONMENT = OpenApiParameter(location=OpenApiParameter.QUERY,required=False,# Explicit explode: the generated client only emits repeated `environment=` keys for params the- # spec marks explode, and Django's getlist needs repeated keys — a comma-joined value matches no- # environment.+ # spec marks explode, and Django's getlist needs repeated keys, because a comma-joined value matches+ # no environment.explode=True,description="Deploy environment(s) to scope to, repeatable (from the response's `environments` list). Omit ""to include all persistent environments marked production or named prod/production (including regional "@@ -88,33 +88,26 @@ class DoraActionsMixin(EngineeringAnalyticsViewSetBase):)@action(detail=False, methods=["get"], pagination_class=None)def dora(self, request: Request, **kwargs) -> Response:+ query = DoraEnvironmentQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)try:- query = DoraEnvironmentQuerySerializer(- data=request.query_params,- context={- "get_environment_choices": partial(- api.get_dora_environment_choices,- team=self.team,- date_from=request.query_params.get("date_from") or None,- date_to=request.query_params.get("date_to") or None,- source_id=request.query_params.get("source_id") or None,- repo=request.query_params.get("repo") or None,- user_access_control=self.user_access_control,- )- },- )- query.is_valid(raise_exception=True)result = api.get_dora_overview(team=self.team,date_from=request.query_params.get("date_from") or None,date_to=request.query_params.get("date_to") or None,- validated_environments=query.validated_data.get("environment"),+ environments=query.validated_data.get("environment"),github_team=request.query_params.get("github_team") or None,granularity=request.query_params.get("granularity") or None,source_id=request.query_params.get("source_id") or None,repo=request.query_params.get("repo") or None,user_access_control=self.user_access_control,)+ except UnknownDoraEnvironmentError as exc:+ # doraLogic recovers the environment picker only from a 400 whose attr is ``environment``.+ raise serializers.ValidationError(+ {"environment": [f'"{name}" is not a valid choice.' for name in exc.environments]},+ code="invalid_choice",+ ) from excexcept ValueError as exc:return _bad_request(exc, fallback="Invalid date_from, date_to, granularity, or source_id")return Response(DoraOverviewSerializer(instance=result).data)diff --git a/products/engineering_analytics/backend/tests/test_dora.py b/products/engineering_analytics/backend/tests/test_dora.pyindex 8eccdfc2dee7..f22cabdb656a 100644--- a/products/engineering_analytics/backend/tests/test_dora.py+++ b/products/engineering_analytics/backend/tests/test_dora.py@@ -11,11 +11,10 @@ from rest_framework import statusfrom posthog.models.team import Team+from products.engineering_analytics.backend.facade.contracts import UnknownDoraEnvironmentError+from products.engineering_analytics.backend.logic.dora import build_dora_overviewfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource-from products.engineering_analytics.backend.logic.queries.dora import (- query_dora_environment_choices,- query_dora_overview,-)+from products.engineering_analytics.backend.logic.queries.dora import query_dora_overviewfrom products.engineering_analytics.backend.logic.sources import GitHubTablesfrom products.engineering_analytics.backend.logic.views.source_schema import (DEPLOYMENT_STATUSES_COLUMNS,@@ -39,23 +38,17 @@ class TestDoraEnvironmentQuerySerializer(SimpleTestCase):@parameterized.expand([("", None),- ("environment=%20prod-us%20&environment=prod-eu&environment=prod-us", ["prod-us", "prod-eu"]),- ("environment=preview-pr-1", ["preview-pr-1"]),+ ("environment=%20prod-us%20&environment=prod-eu", ["prod-us", "prod-eu"]),])def test_valid_environment_selection(self, query: str, expected: list[str] | None) -> None:- serializer = DoraEnvironmentQuerySerializer(- data=QueryDict(query),- context={"get_environment_choices": lambda names: ["prod-eu", "prod-us", "preview-pr-1"]},- )+ serializer = DoraEnvironmentQuerySerializer(data=QueryDict(query))assert serializer.is_valid(), serializer.errorsassert serializer.validated_data.get("environment") == expected- @parameterized.expand([("environment=",), ("environment=%20",), ("environment=prod-us&environment=unknown",)])+ @parameterized.expand([("environment=",), ("environment=%20",)])def test_rejects_invalid_environment_selection(self, query: str) -> None:- serializer = DoraEnvironmentQuerySerializer(- data=QueryDict(query), context={"get_environment_choices": lambda names: ["prod-us"]}- )+ serializer = DoraEnvironmentQuerySerializer(data=QueryDict(query))assert not serializer.is_valid()assert "environment" in serializer.errors@@ -78,23 +71,12 @@ class TestDoraEndpoint(ClickhouseTestMixin, APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/dora/", {"environment": " "})assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/dora/", {"environment": "prod"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"] == "environment"-class TestDoraQuery(ClickhouseTestMixin, BaseTest):- def _validated_environments(self, curated: CuratedGitHubSource, names: list[str]) -> list[str]:- serializer = DoraEnvironmentQuerySerializer(- data={"environment": names},- context={- "get_environment_choices": lambda environments: query_dora_environment_choices(- curated=curated,- environments=environments,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- )- },- )- serializer.is_valid(raise_exception=True)- return serializer.validated_data["environment"]+class TestDoraQuery(ClickhouseTestMixin, BaseTest):def _curated(self,team: Team,@@ -143,9 +125,9 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):# d5 succeeded in the previous window, d6 never reached an outcome (no status rows).# Each successful deploy's sha is a merged PR's merge_commit_sha (its head): PR 1 heads# d1, PR 2 heads d3, PR 5 heads d5. Attribution follows head merge order, not success- # time: PR 6 (carol) merges Jan 12 09:00, AFTER d1's head merge (08:00), so d1 — despite- # succeeding later that day — does not contain it and it waits for d3.- # staging: d4 succeeds Jan 12 09:00 — before d1 — so a production-scope leak would+ # time: PR 6 (carol) merges Jan 12 09:00, AFTER d1's head merge (08:00), so d1 (despite+ # succeeding later that day) does not contain it and it waits for d3.+ # staging: d4 succeeds Jan 12 09:00, before d1, so a production-scope leak would# change PR 1's lead time from 2h to 1h.return self._curated(self.team,@@ -258,7 +240,7 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):assert result.deployed_pr_count == 3 # PRs 1, 2, 6; bot and undeployed merges excludedassert result.deployed_pr_count_prev == 1 # PR 5 via d5- # PR 1: 7200 via d1. PR 2: 9000 via d3. PR 6: 97200 via d3 — the containment rule at+ # PR 1: 7200 via d1. PR 2: 9000 via d3. PR 6: 97200 via d3. The containment rule at# work: d1 succeeded after PR 6's merge but its head merged before it, so d1 doesn't count.assert result.median_merge_to_deploy_seconds == 9000.0assert result.median_merge_to_deploy_seconds_prev == 7200.0@@ -613,11 +595,8 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):),],)- result = query_dora_overview(- curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- validated_environments=self._validated_environments(curated, ["staging"]),+ result = build_dora_overview(+ curated=curated, date_from="2026-01-10", date_to="2026-01-20", environments=["staging"])assert result.environment_scope == "staging"@@ -626,11 +605,11 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):# PR 1 (merged Jan 12 08:00) reaches staging's 09:00 success: a 1h lead time.assert result.median_merge_to_deploy_seconds == 3600.0- both = query_dora_overview(+ both = build_dora_overview(curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- validated_environments=self._validated_environments(curated, [" staging ", "prod", "staging"]),+ date_from="2026-01-10",+ date_to="2026-01-20",+ environments=[" staging ", "prod", "staging"],granularity="week",)@@ -639,6 +618,15 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):assert both.deployment_count == 2 # the multi-environment scope admits d1 and d4assert both.series_granularity == "week" # the caller's override beats the window fit+ with self.assertRaises(UnknownDoraEnvironmentError) as raised:+ build_dora_overview(+ curated=curated,+ date_from="2026-01-10",+ date_to="2026-01-20",+ environments=["missing", "staging", "gone"],+ )+ assert raised.exception.environments == ["missing", "gone"]+def test_exact_environment_scope_can_select_a_transient_environment(self) -> None:curated = self._curated(self.team,@@ -659,50 +647,14 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):],pr_rows=[_pr_row(1, "alice", "open", 0, "2026-01-11 08:00:00")],)- result = query_dora_overview(- curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- validated_environments=self._validated_environments(curated, ["preview-pr-2"]),+ result = build_dora_overview(+ curated=curated, date_from="2026-01-10", date_to="2026-01-20", environments=["preview-pr-2"])assert result.environments == ["prod"]assert result.selected_environments == ["preview-pr-2"]assert result.deployment_count == 1- def test_exact_environment_lookup_is_not_limited_by_picker_options(self) -> None:- deployment_rows = [- _deployment_row(- index,- f"sha-{index}",- f"environment-{index:03}",- "2026-01-12 09:30:00",- production=False,- )- for index in range(1, 102)- ]- status_rows = [- _status_row(index + 1000, index, "success", f"environment-{index:03}", "2026-01-12 10:00:00")- for index in range(1, 102)- ]- curated = self._curated(- self.team,- deployment_rows=deployment_rows,- status_rows=status_rows,- pr_rows=[_pr_row(1, "alice", "open", 0, "2026-01-11 08:00:00")],- )- result = query_dora_overview(- curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- validated_environments=self._validated_environments(curated, ["environment-101"]),- )-- assert len(result.environments) == 100- assert "environment-101" not in result.environments- assert result.selected_environments == ["environment-101"]- assert result.deployment_count == 1-def test_environment_discovery_keeps_a_quiet_persistent_option(self) -> None:curated = self._curated(self.team,@@ -721,7 +673,7 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):assert result.deployment_count == 0assert result.deployment_count_prev == 0- @parameterized.expand([(True, True), (False, False), (True, False)])+ @parameterized.expand([(False, False), (True, False)])def test_default_scope_includes_production_regions(self, us_production: bool, eu_production: bool) -> None:curated = self._curated(self.team,@@ -748,46 +700,6 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):assert result.selected_environments == ["prod-eu", "prod-us"]assert result.deployment_count == 3- def test_default_production_scope_is_not_limited_by_picker_options(self) -> None:- deployment_rows = [- _deployment_row(- index * 10 + repetition,- f"staging-sha-{index}-{repetition}",- f"staging-{index:03}",- "2026-01-12 09:00:00",- production=False,- )- for index in range(1, 101)- for repetition in range(2)- ]- deployment_rows.extend(- [- _deployment_row(2001, "prod-us-sha", "prod-us", "2026-01-12 09:00:00", production=False),- _deployment_row(2002, "prod-eu-sha", "prod-eu", "2026-01-12 09:00:00", production=False),- ]- )- curated = self._curated(- self.team,- deployment_rows=deployment_rows,- status_rows=[- _status_row(3001, 2001, "success", "prod-us", "2026-01-12 10:00:00"),- _status_row(3002, 2002, "success", "prod-eu", "2026-01-12 10:00:00"),- ],- pr_rows=[_pr_row(1, "alice", "open", 0, "2026-01-11 08:00:00")],- )-- result = query_dora_overview(- curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- )-- assert len(result.environments) == 100- assert "prod-us" not in result.environments- assert "prod-eu" not in result.environments- assert result.selected_environments == ["prod-eu", "prod-us"]- assert result.deployment_count == 2-def test_default_scope_includes_flagged_names_and_excludes_transient_production_names(self) -> None:curated = self._curated(self.team,@@ -847,17 +759,16 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):)assert len(result.environments) == 100+ assert "prod-101" not in result.environmentsassert len(result.selected_environments) == 101assert result.selected_environments == [f"prod-{index:03}" for index in range(1, 102)]assert result.deployment_count == 101- explicitly_selected = query_dora_overview(+ explicitly_selected = build_dora_overview(curated=curated,- date_from=datetime(2026, 1, 10, tzinfo=UTC),- date_to=datetime(2026, 1, 20, tzinfo=UTC),- validated_environments=self._validated_environments(- curated, [f"prod-{index:03}" for index in range(1, 102)]- ),+ date_from="2026-01-10",+ date_to="2026-01-20",+ environments=[f"prod-{index:03}" for index in range(1, 102)],)assert explicitly_selected.selected_environments == [f"prod-{index:03}" for index in range(1, 102)]assert explicitly_selected.deployment_count == 101