:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(eng-analytics): ready-to-merge cycle time (#76006)
Raúl Negrón-Otero4d727232c0f7
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 8adaebcd0c57..4d86cb16f9d9 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -64,7 +64,7 @@ Return shapes are typed contracts whose caveats ride in honest field names (`ope```mermaidgraph LRsubgraph "Data in"- WH[("warehouse: GitHub source<br/>pull_requests / workflow_runs<br/>workflow_jobs / team_members")]+ WH[("warehouse: GitHub source<br/>pull_requests / workflow_runs<br/>workflow_jobs / team_members<br/>issue_events")]LOGS[("Logs: github-ci-logs<br/>thinned CI failure lines")]TRACES[("Traces: per-test CI spans<br/>emitted by Backend and Frontend CI")]end@@ -97,7 +97,8 @@ Shortening ready-for-review-to-merge is the headline metric this serves.| ---------------------------------------------------------------------------- | -------------------------------------------------------------------- || CI and job durations, queue time, cost, failure logs, flaky and broken tests | Warehouse + Logs + Traces || Open to merge time (coarse: `open_to_merge_seconds`) | PR snapshot |-| Draft/ready transitions, time-in-review, approvals | PR lifecycle events (webhooks to events, PR as group type): deferred |+| Ready to merge time (`ready_to_merge_seconds`), draft/ready transitions | Warehouse `github_issue_events` (bounded window, grows forward) |+| Time-in-review, approvals | PR lifecycle events (webhooks to events, PR as group type): deferred || Deploys and DORA | Deploy data: deferred |The warehouse snapshots overwrite state on update, so transition timing is unrecoverable from them.@@ -116,7 +117,7 @@ Change one only in a separate PR with a written reason. Engineering-level decisi- No author leaderboards or per-developer performance rankings, ever. The author page (own PRs plus own CI cost, reached only from PR-row author links) is allowed; ranking people against each other is not.- Bots and drafts excluded by default in throughput / cycle-time reads; bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.- Author identity = `Author{handle, display_name, avatar_url, is_bot}`. No PostHog-user mapping.-- Time to merge = `open_to_merge_seconds` = `merged_at - created_at`: coarse until state-transition events exist, and named so.+- Time to merge = `open_to_merge_seconds` = `merged_at - created_at`: coarse, and named so. `ready_to_merge_seconds` is the precise companion (last observed ready-for-review to merge, from `github_issue_events`); NULL means "not observed", never zero.- The GitHub `reviews` endpoint syncs, but review reads stay deferred until a wedge tool needs them.## Glossarydiff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 45e8cf762459..93938ddc98a9 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -44,7 +44,7 @@ graph TBendsubgraph Storage- WH[("warehouse: GitHub source<br/>pull_requests / workflow_runs<br/>workflow_jobs / team_members")]+ WH[("warehouse: GitHub source<br/>pull_requests / workflow_runs<br/>workflow_jobs / team_members<br/>issue_events")]LOGS[("Logs: github-ci-logs<br/>thinned CI failure lines")]TRACES[("Traces: per-test CI spans<br/>from Backend and Frontend CI")]end@@ -137,7 +137,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- **No author leaderboards or per-developer performance rankings; the author page is allowed.** The surveillance risk is ranking people against each other, not an engineer viewing their own PRs and CI cost. The page is reachable only from PR-row author links; `author_workflow_costs` stays a UI-only read (MCP `enabled: false`).- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.-- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined) until state-transition events exist.+- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.- **Team ownership is stamped at CI emission time, never mirrored server-side.** The CI emitter stamps `test.owner_team` from the repo's ownership map (`products/*/product.yaml` + CODEOWNERS, first listed owner); unstamped spans aggregate as the first-class team `unowned`. Capture-time truth is intentional: a test belongs to whoever owned it when it flaked. Team surfaces stay team-level: author→team joins (via the `team_members` snapshot) produce aggregates only, never per-member figures or cross-team rankings; a slug mismatch yields an empty series, never another team's data.- **No provider abstraction until a second code host lands.** GitHub-isms stay below the builder boundary, canonical types above it; that seam makes extracting a `CodeHostProvider` Protocol mechanical.@@ -149,6 +149,7 @@ Warehouse tables (GitHub source):- `github_workflow_runs`: CI runs. Webhook-only (the webhook is the source of truth; history is a deliberate one-off backfill). A settled run never changes, so durations and trends are precise; until settled, `status` / `conclusion` mutate (see the freshness caveat).- `github_workflow_jobs`: per-job attempts (runner labels, queue and duration timestamps), the cost substrate. Webhook stream plus a window-limited backfill poll; per-run polling is infeasible at this volume.- `github_team_members`: org team membership, the author→team key. Optional at the source; every read that touches it must degrade gracefully when unsynced.+- `github_issue_events`: immutable issue/PR state transitions, landed raw with every event type kept (a source-side filter would pin the desc-walk watermark). The draft/ready transitions in them back `ready_to_merge_seconds` and the lifecycle timeline. GitHub caps the endpoint's history walk, so rows cover a bounded recent window growing forward from the first sync; optional, and reads must degrade gracefully when unsynced.Other products read as sources:@@ -157,7 +158,7 @@ Other products read as sources:**Freshness caveat:** a run's `conclusion` settles via the `workflow_run` webhook, which can lag or miss deliveries; the read layer surfaces `status` honestly rather than implying a settled conclusion.-Lifecycle data the snapshots can't hold (PR state transitions, reviews/approvals, deploys, DORA) needs immutable timestamped events (GitHub webhooks → PostHog events, PR as group type). That is the only thing the deferred events destination is for. See README → "The data boundary".+Lifecycle data the snapshots can't hold and `github_issue_events` doesn't carry (reviews/approvals, deploys, DORA) needs immutable timestamped events (GitHub webhooks → PostHog events, PR as group type). That is the only thing the deferred events destination is for. See README → "The data boundary".## 8. Reference readingdiff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 3b41dba21c43..c0301b6d9ce7 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -135,6 +135,8 @@ class BrokenTestState(StrEnum):class PRLifecycleEventKind(StrEnum):OPENED = "opened"+ READY_FOR_REVIEW = "ready_for_review"+ CONVERTED_TO_DRAFT = "converted_to_draft"CI_STARTED = "ci_started"CI_FINISHED = "ci_finished"MERGED = "merged"@@ -762,6 +764,10 @@ class PullRequestListItem:merged_at: datetime | None# merged_at - created_at; coarse (fuses draft + ready-for-review time). None until merged.open_to_merge_seconds: int | None+ # merged_at minus the LAST observed ready_for_review transition, falling back to created_at+ # for a merged PR verifiably never drafted. None when unmerged, re-drafted, or not observed+ # (the PR's life isn't fully inside the synced issue-event window); never "never drafted".+ ready_to_merge_seconds: int | Nonelabels: list[str]ci: CIStatusRollup# CI triggers attributed to this PR: distinct head SHAs across its workflow runs (a rundiff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex adf512c05305..ca32e2b5abad 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -14,6 +14,7 @@ into these fragments."""import math+from dataclasses import dataclassfrom typing import TYPE_CHECKINGfrom posthog.schema import HogQLQueryResponse@@ -28,6 +29,7 @@ from posthog.models.team import Teamfrom products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tablesfrom products.engineering_analytics.backend.logic.views import (+ issue_events,job_costs,pull_requests,team_members,@@ -39,6 +41,14 @@ if TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControl+@dataclass(frozen=True, kw_only=True)+class IssueEventsWindow:+ """The observed issue-event range's edges as scalar subquery strings."""++ start: str+ end: str++class CuratedGitHubSource:"""A team's curated GitHub read layer, bound to its resolved warehouse tables.@@ -109,6 +119,49 @@ class CuratedGitHubSource:return Nonereturn f"({team_members.build_query(self._tables.team_members)})"+ def issue_events_source(self) -> str | None:+ """Curated PR draft/ready transitions ``SELECT`` subquery, or None when the optional+ issue-events table isn't synced."""+ if not self._tables.issue_events:+ return None+ return f"({issue_events.build_query(self._tables.issue_events)})"++ def issue_events_window(self) -> "IssueEventsWindow | None":+ """Scalar subqueries bounding the observed issue-event range, or None when the table+ isn't synced. The desc walk lands a contiguous range, so the min and max landed+ timestamps are its edges; both are NULL over an empty table, so comparisons against+ them are never-true."""+ if not self._tables.issue_events:+ return None+ return IssueEventsWindow(+ start=f"({issue_events.build_window_start_query(self._tables.issue_events)})",+ end=f"({issue_events.build_window_end_query(self._tables.issue_events)})",+ )++ def ready_by_pr_cte(self) -> str | None:+ """CTE: each PR's last observed draft-state transition, or None when the table isn't synced.++ Only the LAST switch counts: for a merged PR the newest transition is necessarily the ready+ that preceded the merge (a draft can't merge); an open PR goes false while re-drafted. The+ event id breaks same-second ties (GitHub timestamps are second-coarse). Keyed on+ ``pr_number`` alone, unlike ``runs_by_pr``: a run's association can list the fork network's+ PRs (which is why that rollup needs the repo qualifier), whereas every row of a resolved+ issue-events table belongs to that one repo by table construction.+ """+ source = self.issue_events_source()+ if source is None:+ return None+ return f"""+ ready_by_pr AS (+ SELECT+ pr_number,+ argMax(event, tuple(created_at, id)) = '{issue_events.READY_FOR_REVIEW_EVENT}' AS last_is_ready,+ max(created_at) AS last_transition_at+ FROM {source} AS se+ GROUP BY pr_number+ )+ """+def job_cost_source(self) -> str | None:"""Per-job cost ``SELECT`` subquery — the same view body ``engineering_analytics_job_costs``exposes, but with the endpoint-only run pass-through columns (``run_started_at`` /@@ -209,8 +262,14 @@ class CuratedGitHubSource:"""def pr_list_rollup_query(self, select: str) -> str:- """``pr_rollup_query`` plus the per-PR runs rollup (pushes / re-run cycles)."""- return self._compose_pr_query([self.runs_cte(), self.ci_rollup_cte(), self.runs_by_pr_cte()], select)+ """``pr_rollup_query`` plus the per-PR runs rollup and, when the issue-events table is+ synced, the ``ready_by_pr`` rollup; reference it only when ``issue_events_source()``+ is non-None."""+ ctes = [self.runs_cte(), self.ci_rollup_cte(), self.runs_by_pr_cte()]+ ready_cte = self.ready_by_pr_cte()+ if ready_cte is not None:+ ctes.append(ready_cte)+ return self._compose_pr_query(ctes, select)def _compose_pr_query(self, ctes: list[str], select: str) -> str:"""Prefix ``select`` with the given CTEs and fill its ``__PR_SOURCE__`` placeholder with the PR source."""diff --git a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.pyindex 3dce7ee5d949..f10dcf9654d4 100644--- a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py+++ b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py@@ -23,6 +23,7 @@ from products.engineering_analytics.backend.facade.contracts import ()from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._pr_header import pr_header_placeholders, pr_header_query+from products.engineering_analytics.backend.logic.views import issue_events# The curated subqueries and the repo filter are filled with str.replace (trusted# constants), leaving the HogQL {value} placeholders untouched for parse_select.@@ -42,6 +43,20 @@ _RUNS = """ORDER BY run_started_at ASC"""+# pr_number alone is the key: a resolved table set is a single repo's, the same repo the+# PR header was resolved from.+_STATE_EVENTS = """+ SELECT event, created_at, actor_login+ FROM __STATE_EVENTS_SOURCE__ AS se+ WHERE pr_number = {pr_number}+ ORDER BY created_at ASC, id ASC+"""++_STATE_EVENT_KINDS = {+ issue_events.READY_FOR_REVIEW_EVENT: PRLifecycleEventKind.READY_FOR_REVIEW,+ issue_events.CONVERT_TO_DRAFT_EVENT: PRLifecycleEventKind.CONVERTED_TO_DRAFT,+}+def query_pr_lifecycle(*,@@ -109,6 +124,19 @@ def query_pr_lifecycle(events.append(PRLifecycleEvent(kind=kind, at=at, detail=detail, run_id=run_id))add(PRLifecycleEventKind.OPENED, created_at)++ state_events_source = curated.issue_events_source()+ if state_events_source is not None:+ transitions = curated.run(+ _STATE_EVENTS.replace("__STATE_EVENTS_SOURCE__", state_events_source),+ query_type="engineering_analytics.pr_lifecycle.state_events",+ placeholders={"pr_number": ast.Constant(value=pr_number)},+ )+ for event, at, actor_login in transitions.results:+ kind = _STATE_EVENT_KINDS.get(event)+ if kind is not None:+ add(kind, at, detail=actor_login or None)+runs = (curated.run(_RUNS.replace("__RUNS_SOURCE__", curated.run_source()),diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.pyindex 893b36308b8a..6d106398f73b 100644--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py@@ -33,7 +33,9 @@ _SELECT = f"""pr.number, pr.title, pr.repo_owner, pr.repo_name,pr.author_handle, pr.author_avatar_url, pr.is_bot,pr.state, pr.is_draft, pr.created_at, pr.merged_at,- pr.open_to_merge_seconds, pr.labels,+ pr.open_to_merge_seconds,+ __READY_TO_MERGE__,+ pr.labels,coalesce(ci.runs, 0) AS runs,coalesce(ci.passing, 0) AS passing,coalesce(ci.failing, 0) AS failing,@@ -45,6 +47,7 @@ _SELECT = f"""LEFT JOIN ci_rollup AS ci ON ci.head_sha = pr.head_shaLEFT JOIN runs_by_pr AS rpON rp.repo_owner = pr.repo_owner AND rp.repo_name = pr.repo_name AND rp.pr_number = pr.number+ __READY_JOIN__WHERE (pr.state = 'open'OR pr.merged_at >= {{date_from}}@@ -54,6 +57,25 @@ _SELECT = f"""LIMIT {_LIMIT + 1}"""+# Per merged PR: last transition is a ready -> merged_at minus it; no transition rows and the+# PR's whole open-to-merge life inside the observed window -> never left ready, so open-to-merge+# IS ready-to-merge; otherwise NULL (re-drafted, or unobservable). Both window bounds are load-+# bearing: created_at before the window means pre-window flips are possible, and merged_at past+# the window means the transitions may simply not have synced yet (every merge lands a `merged`+# issue event, so an in-range merge with no transition rows is proof of never drafting). The+# coalesce guards normalize a missed join, which lands NULL or 0 depending on join_use_nulls.+_READY_TO_MERGE = """+ multiIf(+ pr.merged_at IS NULL, NULL,+ coalesce(re.last_is_ready, 0) = 1, dateDiff('second', re.last_transition_at, pr.merged_at),+ coalesce(re.pr_number, 0) = 0+ AND pr.created_at >= __READY_WINDOW_START__+ AND pr.merged_at <= __READY_WINDOW_END__, pr.open_to_merge_seconds,+ NULL+ ) AS ready_to_merge_seconds+"""+_READY_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"+# Per-push CI rounds for the visible PRs, for the push-history sparkline. Verdicts collapse like# ``ci_rollup``: latest run per (push, workflow) via argMax, then any decisive failure turns the@@ -130,8 +152,24 @@ def query_pull_request_list(if author:author_clause = "AND pr.author_handle = {author}"placeholders["author"] = ast.Constant(value=author)+ # Without the optional issue-events table the column degrades to NULL rather than+ # referencing the absent ready_by_pr CTE.+ window = curated.issue_events_window()+ if window is not None:+ ready_column = _READY_TO_MERGE.replace("__READY_WINDOW_START__", window.start).replace(+ "__READY_WINDOW_END__", window.end+ )+ ready_join = _READY_JOIN+ else:+ ready_column = "NULL AS ready_to_merge_seconds"+ ready_join = ""+ select = (+ _SELECT.replace("__READY_TO_MERGE__", ready_column)+ .replace("__READY_JOIN__", ready_join)+ .replace("__AUTHOR__", author_clause)+ )response = curated.run(- curated.pr_list_rollup_query(_SELECT.replace("__AUTHOR__", author_clause)),+ curated.pr_list_rollup_query(select),query_type="engineering_analytics.pull_request_list",placeholders=placeholders,)@@ -165,6 +203,7 @@ def _map_row(created_at,merged_at,open_to_merge_seconds,+ ready_to_merge_seconds,labels,runs,passing,@@ -190,6 +229,7 @@ def _map_row(created_at=created_at,merged_at=merged_at,open_to_merge_seconds=open_to_merge_seconds,+ ready_to_merge_seconds=int(ready_to_merge_seconds) if ready_to_merge_seconds is not None else None,labels=list(labels),# A PR with no CI misses the LEFT JOIN; the array column then comes back empty or NULL# depending on join_use_nulls — normalize both to [].diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex dc3a28132aa9..64344f088af7 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -50,10 +50,15 @@ WORKFLOW_JOBS_SCHEMA = "workflow_jobs"# timing. Optional and off by default at the source (needs the org Members:Read grant), so reads# must degrade gracefully (no membership data) exactly like workflow_jobs.TEAM_MEMBERS_SCHEMA = "team_members"+# Immutable issue/PR events, the substrate for ready-to-merge timing. Optional at the source,+# so reads must degrade gracefully (no transition data) exactly like workflow_jobs.+ISSUE_EVENTS_SCHEMA = "issue_events"# The curated endpoints we resolve per repo. A source's other synced endpoints (issues, commits,# teams, …) are irrelevant to the CI/PR read layer and dropped during grouping.-_CURATED_ENDPOINTS = frozenset({PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA})+_CURATED_ENDPOINTS = frozenset(+ {PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA, ISSUE_EVENTS_SCHEMA}+)# Resolved names are interpolated into HogQL ``FROM`` clauses. Warehouse table names are# always plain identifiers (the prefix is validated to ``[A-Za-z0-9_]`` at connect time and@@ -72,6 +77,8 @@ class GitHubTables:workflow_jobs: str | None = None# Optional: present only once org team membership is synced; None means "no membership data".team_members: str | None = None+ # Optional: present only once issue events are synced; None means "no transition data".+ issue_events: str | None = None# Used to scope cross-store reads such as CI traces to the selected source's repository.repository: str = ""@@ -140,6 +147,7 @@ def resolve_github_tables(workflow_runs=workflow_runs,workflow_jobs=tables.get(WORKFLOW_JOBS_SCHEMA),team_members=tables.get(TEAM_MEMBERS_SCHEMA),+ issue_events=tables.get(ISSUE_EVENTS_SCHEMA),repository=candidate.repository,)if source_id is not None:diff --git a/products/engineering_analytics/backend/logic/views/issue_events.py b/products/engineering_analytics/backend/logic/views/issue_events.pynew file mode 100644index 000000000000..6e4ff273854f--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/issue_events.py@@ -0,0 +1,41 @@+"""Curated PR draft/ready transitions query builder.++The transition vocabulary and the "transitions only" rule live here once; consumers+import the event constants rather than restating the raw strings. GitHub caps the+issue-events history walk, so the table covers a bounded window growing forward from+the first sync: a PR with no transition rows is ambiguous (opened ready, or its flips+just aren't in the window). The window builders disambiguate: the min/max timestamps+over ALL landed event types bound the observed range, because the desc walk lands a+contiguous range; a merged PR with no transitions whose whole open-to-merge life sits+inside that range verifiably never left ready.+"""++# GitHub's issue-event vocabulary for the draft/ready transitions.+READY_FOR_REVIEW_EVENT = "ready_for_review"+CONVERT_TO_DRAFT_EVENT = "convert_to_draft"+++def build_query(table_name: str) -> str:+ # A row whose timestamp parses to NULL cannot be ordered and would poison the per-PR argMax.+ return f"""+ SELECT id, event, pr_number, actor_login, created_at+ FROM (+ SELECT+ id,+ event,+ JSONExtractInt(issue, 'number') AS pr_number,+ ifNull(JSONExtractString(actor, 'login'), '') AS actor_login,+ parseDateTimeBestEffort(created_at) AS created_at+ FROM {table_name}+ WHERE event IN ('{READY_FOR_REVIEW_EVENT}', '{CONVERT_TO_DRAFT_EVENT}')+ )+ WHERE created_at IS NOT NULL+ """+++def build_window_start_query(table_name: str) -> str:+ return f"SELECT min(parseDateTimeBestEffort(created_at)) AS window_start FROM {table_name}"+++def build_window_end_query(table_name: str) -> str:+ return f"SELECT max(parseDateTimeBestEffort(created_at)) AS window_end FROM {table_name}"diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.pyindex abbe45a05822..836eb17001c5 100644--- a/products/engineering_analytics/backend/logic/views/pull_requests.py+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py@@ -1,9 +1,10 @@"""Curated pull-requests query builder.Maps the raw GitHub pull-requests warehouse snapshot (GitHub's PR JSON, landed-verbatim) into honest, query-able columns. This is the ONLY place PR domain rules-live — bot detection, repo identity from ``base.repo.full_name``, label extraction,-the canonical PR state, and the coarse open-to-merge duration. The source table name+verbatim) into honest, query-able columns. This is the ONLY place PR-snapshot domain+rules live — bot detection, repo identity from ``base.repo.full_name``, label+extraction, the canonical PR state, and the coarse open-to-merge duration; the+draft/ready-transition rules live once in ``issue_events`` + ``_curated``. The source table nameis resolved per-team and passed in (see ``logic.sources``); it is never hardcoded,because a warehouse table's name is ``prefix + "github_pull_requests"`` and the prefixis user-chosen. Every query module embeds this ``SELECT`` as a subquery (seediff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 346d90863ff2..13df230885eb 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -83,6 +83,17 @@ WORKFLOW_JOBS_COLUMNS: dict[str, dict[str, str]] = {"steps": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}+# Contract for the ``github_issue_events`` warehouse source: immutable issue/PR events, every+# type kept (a source-side filter would pin the desc-walk watermark). ``actor`` / ``issue`` are+# the nested GitHub objects verbatim as JSON. Same Nullable/string discipline as above.+ISSUE_EVENTS_COLUMNS: dict[str, dict[str, str]] = {+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ "event": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "actor": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "issue": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "created_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}+# Contract for the ``github_team_members`` warehouse source (org team membership). Member rows# are GitHub user objects with the parent team's identity injected by the source fan-out# (``team_id`` / ``team_slug`` / ``team_name``); ``login`` + ``team_slug`` are the join keys thediff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex b048552e3603..29bec1667d61 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -49,6 +49,7 @@ from posthog.storage import object_storagefrom products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAMEfrom products.engineering_analytics.backend.logic.queries._test_spans import PYTEST_CI_SERVICE_NAMEfrom products.engineering_analytics.backend.logic.sources import (+ ISSUE_EVENTS_SCHEMA,PULL_REQUESTS_SCHEMA,TEAM_MEMBERS_SCHEMA,WORKFLOW_JOBS_SCHEMA,@@ -56,6 +57,7 @@ from products.engineering_analytics.backend.logic.sources import ()from products.engineering_analytics.backend.logic.views.pull_requests import KNOWN_BOT_HANDLESfrom products.engineering_analytics.backend.logic.views.source_schema import (+ ISSUE_EVENTS_COLUMNS,PULL_REQUESTS_COLUMNS,TEAM_MEMBERS_COLUMNS,WORKFLOW_JOBS_COLUMNS,@@ -326,6 +328,57 @@ def _spread_merges(prs: list[dict[str, Any]], anchor: datetime) -> None:pr["created_at"] = (merged_at - timedelta(hours=open_hours)).strftime("%Y-%m-%dT%H:%M:%SZ")+# Synthetic PR draft/ready transition stream backing ready_to_merge_seconds and the lifecycle+# timeline. A real issue-events sync covers a bounded recent window (GitHub caps the history+# walk), so the seed mirrors that: events land only inside the last _ISSUE_EVENTS_WINDOW_DAYS+# of the merge spread, leaving older merges NULL ("not observed") exactly like production.+# Every in-window merge lands its `merged` event too — that is what arms the never-drafted+# fallback's window proof. Deterministic (index arithmetic, no random).+_ISSUE_EVENTS_WINDOW_DAYS = 10+++def _issue_event_rows(prs: list[dict[str, Any]], anchor: datetime) -> list[dict[str, Any]]:+ window_start = anchor - timedelta(days=_ISSUE_EVENTS_WINDOW_DAYS)+ rows: list[dict[str, Any]] = []++ def add(event_id: int, event: str, pr: dict[str, Any], at: datetime) -> None:+ if at < window_start: # a real desc walk never lands rows past its cap+ return+ rows.append(+ {+ "id": event_id,+ "event": event,+ "actor": json.dumps({"login": (pr.get("user") or {}).get("login") or "", "avatar_url": ""}),+ "issue": json.dumps({"number": pr["number"]}),+ "created_at": at.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+ )++ merged = [pr for pr in prs if pr.get("merged_at")]+ if merged:+ # Pin the observed range's left edge with a non-transition event type, so the window+ # bound is deterministic rather than whichever transition happens to land first.+ add(7_000_000_000, "labeled", merged[0], window_start)+ for index, pr in enumerate(merged):+ created = datetime.fromisoformat(pr["created_at"])+ merged_at = datetime.fromisoformat(pr["merged_at"])+ life = merged_at - created+ base_id = 7_000_000_100 + index * 10+ add(base_id, "merged", pr, merged_at)+ if index % 3 == 0: # opened as a draft, readied once (opening as draft emits no event)+ add(base_id + 1, "ready_for_review", pr, created + life * 0.4)+ elif index % 3 == 1: # re-drafted mid-review, then readied again — only the last ready counts+ add(base_id + 1, "convert_to_draft", pr, created + life * 0.3)+ add(base_id + 2, "ready_for_review", pr, created + life * 0.75)+ # index % 3 == 2: no transitions — an in-window life takes the never-drafted fallback+ demo_pr = next((pr for pr in prs if pr.get("number") == _DEMO_PR_NUMBER), None)+ if demo_pr is not None: # the multi-push demo PR's timeline shows both transition kinds+ created = datetime.fromisoformat(demo_pr["created_at"])+ add(7_000_000_050, "convert_to_draft", demo_pr, created + timedelta(hours=6))+ add(7_000_000_051, "ready_for_review", demo_pr, created + timedelta(hours=30))+ return rows++def _demo_multi_push(prs: list[dict[str, Any]], runs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[dict[str, Any]]]:@@ -937,11 +990,15 @@ class Command(BaseCommand):# merge_commit_sha with the commit it landed, which is what the attribution join reads.merged_prs = [pr for pr in prs if pr.get("merged_at")]runs.extend(_demo_master_commits(_fixture_anchor(prs, runs), merged_prs))+ # Synthetic draft/ready transitions + merged events for ready_to_merge_seconds, windowed+ # like a real capped issue-events sync (see _issue_event_rows).+ issue_events = _issue_event_rows(prs, _fixture_anchor(prs, runs))# Always normalize timestamps to a ClickHouse-friendly format; rebasing is optional.shift = timedelta(0) if options["keep_dates"] else self._rebase_delta(prs, runs)prs = [self._shift_dates(pr, PR_DATE_FIELDS, shift) for pr in prs]runs = [self._shift_dates(run, RUN_DATE_FIELDS, shift) for run in runs]+ issue_events = [self._shift_dates(event, ("created_at",), shift) for event in issue_events]if shift:self.stdout.write(f"Rebased timestamps forward by {shift}.")@@ -967,6 +1024,9 @@ class Command(BaseCommand):self._upsert_schema_table(team, source, credential, prefix, TEAM_MEMBERS_SCHEMA, TEAM_MEMBERS_COLUMNS, _team_membership_rows(prs))+ self._upsert_schema_table(+ team, source, credential, prefix, ISSUE_EVENTS_SCHEMA, ISSUE_EVENTS_COLUMNS, issue_events+ )# Per-test CI spans back the flaky-test leaderboard and the team CI health surfaces.# Best-effort: a dev stack without the traces table still gets the warehouse seed.diff --git a/products/engineering_analytics/backend/presentation/serializers/pull_requests.py b/products/engineering_analytics/backend/presentation/serializers/pull_requests.pyindex 64881cd6f308..3ad9d457dadb 100644--- a/products/engineering_analytics/backend/presentation/serializers/pull_requests.py+++ b/products/engineering_analytics/backend/presentation/serializers/pull_requests.py@@ -58,10 +58,14 @@ class PRLifecycleEventSerializer(DataclassSerializer):class Meta:dataclass = PRLifecycleEventextra_kwargs = {- "kind": {"help_text": "Event kind: opened, ci_started, ci_finished, merged, or closed."},+ "kind": {+ "help_text": "Event kind: opened, ready_for_review, converted_to_draft, ci_started, "+ "ci_finished, merged, or closed."+ },"at": {"help_text": "When the event occurred."},"detail": {- "help_text": "Optional detail, e.g. workflow name and conclusion for CI events.",+ "help_text": "Optional detail: workflow name and conclusion for CI events, the acting "+ "user's login for draft/ready transitions.","allow_null": True,},"run_id": {@@ -247,6 +251,13 @@ class PullRequestListItemSerializer(DataclassSerializer):"ready-for-review time). Null until merged.","allow_null": True,},+ "ready_to_merge_seconds": {+ "help_text": "True ready-to-merge cycle time in seconds: 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 when unmerged or not observed (the PR's life "+ "isn't fully inside the synced issue-event window) - null never means zero.",+ "allow_null": True,+ },"labels": {"help_text": "GitHub label names on the pull request."},"pushes": {"help_text": "CI triggers attributed to this PR: distinct head SHAs across its workflow runs. "diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.pyindex 6885ead60969..55e795cc8e2a 100644--- a/products/engineering_analytics/backend/tests/_github_fixtures.py+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py@@ -13,6 +13,7 @@ import pandas as pdfrom posthog.models.team import Teamfrom products.engineering_analytics.backend.logic.sources import (+ ISSUE_EVENTS_SCHEMA,PULL_REQUESTS_SCHEMA,WORKFLOW_RUNS_SCHEMA,GitHubTables,@@ -69,19 +70,30 @@ def create_warehouse_table_row(def connect_github_source_without_data(- team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, repository: str = ""+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, repository: str = "", include_issue_events: bool = False) -> GitHubTables:"""A GitHub source with pull_requests/workflow_runs schemas over empty ORM tables.The resolver finds these without touching object storage; pair with a mocked query- when only resolution (not real warehouse data) matters.+ when only resolution (not real warehouse data) matters. ``include_issue_events``+ links the optional issue-events schema too, activating the transition reads."""source = create_github_source(team, prefix=prefix, repository=repository)pr_table = create_warehouse_table_row(team, name=f"{prefix}github_pull_requests", source=source)run_table = create_warehouse_table_row(team, name=f"{prefix}github_workflow_runs", source=source)link_schema(team, source, name=PULL_REQUESTS_SCHEMA, table=pr_table)link_schema(team, source, name=WORKFLOW_RUNS_SCHEMA, table=run_table)- return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name, repository=repository)+ issue_events_table = None+ if include_issue_events:+ events_table = create_warehouse_table_row(team, name=f"{prefix}github_issue_events", source=source)+ link_schema(team, source, name=ISSUE_EVENTS_SCHEMA, table=events_table)+ issue_events_table = events_table.name+ return GitHubTables(+ pull_requests=pr_table.name,+ workflow_runs=run_table.name,+ issue_events=issue_events_table,+ repository=repository,+ )def repo_id(full_name: str) -> int:@@ -149,6 +161,23 @@ def _pr_row(}+def _issue_event_row(+ event_id: int,+ event: str,+ pr_number: int,+ created_at: str,+ *,+ login: str = "alice",+) -> dict[str, Any]:+ return {+ "id": event_id,+ "event": event,+ "actor": _user(login),+ "issue": f'{{"number": {pr_number}}}',+ "created_at": created_at,+ }++def _run_row(run_id: int,name: str,diff --git a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py b/products/engineering_analytics/backend/tests/test_logic_pull_requests.pyindex a6d1451b1281..1698813903bb 100644--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py@@ -12,11 +12,13 @@ from parameterized import parameterizedfrom products.engineering_analytics.backend.facade import apifrom products.engineering_analytics.backend.facade.contracts import MetricQuality, PRLifecycleEventKind, PRStatefrom products.engineering_analytics.backend.logic.views.source_schema import (+ ISSUE_EVENTS_COLUMNS,PULL_REQUESTS_COLUMNS,WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,)from products.engineering_analytics.backend.tests._github_fixtures import (+ _issue_event_row,_pr_row,_run_row,connect_github_source_without_data,@@ -110,6 +112,35 @@ class TestPRLifecycleMapping(BaseTest):assert [e.kind for e in lifecycle.events] == [PRLifecycleEventKind.OPENED, PRLifecycleEventKind.CLOSED]+class TestPRLifecycleTransitionsMapping(BaseTest):+ """The lifecycle path with the issue-events schema linked; the side_effect order pins the+ header -> transitions -> runs issuance order."""++ def setUp(self) -> None:+ super().setUp()+ connect_github_source_without_data(self.team, include_issue_events=True)++ def test_interleaves_transitions_with_actor_detail(self) -> None:+ header = _header("merged", merged_at=_dt("2026-01-12T15:00:00"))+ transitions = [+ ("convert_to_draft", _dt("2026-01-10T10:00:00"), "alice"),+ ("ready_for_review", _dt("2026-01-11T08:00:00"), "bob"),+ ]+ runs = [(2001, "CI", "completed", "success", _dt("2026-01-11T09:00:00"), _dt("2026-01-11T12:00:00"))]+ with mock.patch(_RUN_QUERY, side_effect=[_resp([header]), _resp(transitions), _resp(runs)]):+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")++ assert lifecycle is not None+ assert [(e.kind, e.detail) for e in lifecycle.events] == [+ (PRLifecycleEventKind.OPENED, None),+ (PRLifecycleEventKind.CONVERTED_TO_DRAFT, "alice"),+ (PRLifecycleEventKind.READY_FOR_REVIEW, "bob"),+ (PRLifecycleEventKind.CI_STARTED, "CI"),+ (PRLifecycleEventKind.CI_FINISHED, "CI: success"),+ (PRLifecycleEventKind.MERGED, None),+ ]++class TestPullRequestEndpointMapping(BaseTest):"""Row mapping for the aggregate endpoints (the query method mocked, no warehouse).A GitHub source is connected (ORM only) so the resolver succeeds before the mocked@@ -138,6 +169,7 @@ class TestPullRequestEndpointMapping(BaseTest):_dt("2026-01-10T09:00:00"),None,None,+ None,["bug", "p1"],3,2,@@ -165,6 +197,7 @@ class TestPullRequestEndpointMapping(BaseTest):assert item.state == PRState.OPENassert item.labels == ["bug", "p1"]assert item.open_to_merge_seconds is None+ assert item.ready_to_merge_seconds is Noneassert (item.ci.runs, item.ci.passing, item.ci.failing, item.ci.pending) == (3, 2, 1, 0)assert item.ci.failing_workflows == ["E2E CI"]assert (item.pushes, item.rerun_cycles) == (5, 2)@@ -190,6 +223,7 @@ class TestPullRequestEndpointMapping(BaseTest):_dt("2026-01-10T09:00:00"),None,None,+ None,["bug"],0,0,@@ -264,6 +298,8 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert (by_number[11].pushes, by_number[11].rerun_cycles) == (1, 0)assert by_number[12].pushes == 0 # no runs attributed to this PRassert by_number[10].estimated_cost_usd is None # no jobs source seeded here → no cost figure+ # 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 Nonedef test_pull_request_list_includes_cost_when_jobs_synced(self) -> None:# With the jobs source synced, the list carries per-PR cost + billable minutes.@@ -286,6 +322,62 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert item.estimated_cost_usd is not None and item.estimated_cost_usd > 0assert item.billable_minutes is not None and item.billable_minutes > 0+ 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.+ # PR 24: same-second flip, the event id breaks the tie -> the higher-id ready wins.+ # PR 25: merged past the window end (events not synced yet) -> NULL, never a wrong number.+ # One clock base for every row: _ago re-reads the clock per call, so the seconds-exact+ # dateDiff assertions below would drift by 1 whenever table-creation I/O straddles a+ # second boundary between the PR seed and the events seed.+ base = timezone.now()++ def ago(days: int) -> str:+ return (base - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")++ self._create_table(+ "github_pull_requests",+ PULL_REQUESTS_COLUMNS,+ [+ _pr_row(20, "alice", "closed", 0, ago(10), merged_at=ago(1), head_sha="sha20"),+ _pr_row(21, "alice", "closed", 0, ago(5), merged_at=ago(1), head_sha="sha21"),+ _pr_row(22, "alice", "closed", 0, ago(40), merged_at=ago(1), head_sha="sha22"),+ _pr_row(23, "alice", "open", 1, ago(6), head_sha="sha23"),+ _pr_row(24, "alice", "closed", 0, ago(10), merged_at=ago(1), head_sha="sha24"),+ _pr_row(25, "alice", "closed", 0, ago(5), merged_at=ago(0), head_sha="sha25"),+ ],+ )+ self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [_run_row(9500, "CI", "sha20", "completed", "success", ago(1), ago(1), pr_number=20)],+ )+ self._create_table(+ "github_issue_events",+ ISSUE_EVENTS_COLUMNS,+ [+ # The window must come from the WHOLE table, not the filtered transitions view.+ _issue_event_row(5000, "labeled", 20, ago(20)),+ _issue_event_row(5001, "ready_for_review", 20, ago(9)),+ _issue_event_row(5002, "convert_to_draft", 20, ago(8)),+ _issue_event_row(5003, "ready_for_review", 20, ago(2)),+ _issue_event_row(5004, "ready_for_review", 23, ago(4)),+ _issue_event_row(5005, "convert_to_draft", 23, ago(3)),+ _issue_event_row(5006, "convert_to_draft", 24, ago(2)),+ _issue_event_row(5007, "ready_for_review", 24, ago(2)),+ # PR 21's merge event: proves the window covers its merge, arming the fallback.+ _issue_event_row(5008, "merged", 21, ago(1)),+ ],+ )+ by_number = {item.number: item for item in api.list_pull_requests(team=self.team).items}+ day = 86400+ assert by_number[20].ready_to_merge_seconds == day+ assert by_number[21].ready_to_merge_seconds == by_number[21].open_to_merge_seconds == 4 * day+ assert by_number[22].ready_to_merge_seconds is None+ assert by_number[23].ready_to_merge_seconds is None+ assert by_number[24].ready_to_merge_seconds == day+ assert by_number[25].ready_to_merge_seconds is None+def test_pr_cost_sums_all_jobs_past_the_default_row_cap(self) -> None:# A PR with more jobs than HogQL's default 100-row cap: the detail cost must sum every job, not# silently truncate to the first 100 (the truncation that made PR detail cost disagree with the list).diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 94bb0f08bd43..a7ad64a9426b 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -88,6 +88,7 @@ def _pr_list_item() -> contracts.PullRequestListItem:created_at=datetime(2026, 1, 10, tzinfo=UTC),merged_at=None,open_to_merge_seconds=None,+ ready_to_merge_seconds=None,labels=["bug"],ci=contracts.CIStatusRollup(runs=3, passing=2, failing=1, pending=0),pushes=4,diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex c2c6709740e2..4c8cd753b189 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -436,6 +436,8 @@ export interface PullRequestApi {/*** * `opened` - OPENED+ * * `ready_for_review` - READY_FOR_REVIEW+ * * `converted_to_draft` - CONVERTED_TO_DRAFT* * `ci_started` - CI_STARTED* * `ci_finished` - CI_FINISHED* * `merged` - MERGED@@ -445,6 +447,8 @@ export type PRLifecycleEventKindEnumApi = (typeof PRLifecycleEventKindEnumApi)[kexport const PRLifecycleEventKindEnumApi = {Opened: 'opened',+ ReadyForReview: 'ready_for_review',+ ConvertedToDraft: 'converted_to_draft',CiStarted: 'ci_started',CiFinished: 'ci_finished',Merged: 'merged',@@ -452,9 +456,11 @@ export const PRLifecycleEventKindEnumApi = {} as constexport interface PRLifecycleEventApi {- /** Event kind: opened, ci_started, ci_finished, merged, or closed.+ /** Event kind: opened, ready_for_review, converted_to_draft, ci_started, ci_finished, merged, or closed.** * `opened` - OPENED+ * * `ready_for_review` - READY_FOR_REVIEW+ * * `converted_to_draft` - CONVERTED_TO_DRAFT* * `ci_started` - CI_STARTED* * `ci_finished` - CI_FINISHED* * `merged` - MERGED@@ -463,7 +469,7 @@ export interface PRLifecycleEventApi {/** When the event occurred. */at: string/**- * Optional detail, e.g. workflow name and conclusion for CI events.+ * Optional detail: workflow name and conclusion for CI events, the acting user's login for draft/ready transitions.* @nullable*/detail?: string | null@@ -606,6 +612,11 @@ export interface PullRequestListItemApi {* @nullable*/open_to_merge_seconds: number | null+ /**+ * True ready-to-merge cycle time in seconds: 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 when unmerged or not observed (the PR's life isn't fully inside the synced issue-event window) - null never means zero.+ * @nullable+ */+ ready_to_merge_seconds: number | null/** GitHub label names on the pull request. */labels: string[]/** CI triggers attributed to this PR: distinct head SHAs across its workflow runs. Fork-PR runs are unattributed. */diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsxindex 055c6c5d089e..9e6925704fde 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -156,6 +156,7 @@ const PULL_REQUESTS: PullRequestListApi = {created_at: '2026-06-24T10:00:00Z',merged_at: null,open_to_merge_seconds: null,+ ready_to_merge_seconds: null,labels: [],pushes: 9,rerun_cycles: 3,@@ -196,6 +197,7 @@ const PULL_REQUESTS: PullRequestListApi = {created_at: '2026-06-30T09:00:00Z',merged_at: '2026-07-01T08:30:00Z',open_to_merge_seconds: 84600,+ ready_to_merge_seconds: 79200,labels: [],pushes: 3,rerun_cycles: 0,diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex c9642a0ee4f3..f4924aeaf852 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -168,6 +168,7 @@ function apiPr(overrides: Partial<PullRequestListItemApi> = {}): PullRequestListcreated_at: '2026-05-01T00:00:00Z',merged_at: null,open_to_merge_seconds: null,+ ready_to_merge_seconds: null,labels: [],pushes: 0,push_history: [],diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex e46b9b8a6f02..06233120d5cc 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -275,9 +275,11 @@ tools:title: PR lifecycle timelinedescription: >The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus- ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer "where is this PR- stuck and what happened to it". metric_quality is "partial" — it covers CI events only; review and comment- events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.+ ordered events — opened, ready for review, converted to draft, CI started, CI finished, and merged or+ closed. Use this to answer "where is this PR stuck and what happened to it". Draft/ready transitions appear+ only when the issue-events table is synced and cover a bounded recent window. metric_quality is "partial" —+ review and comment events are not yet available. For aggregate questions use the pull-requests and+ workflow-health tools.feature_flag: engineering-analyticspull-requests:operation: engineering_analytics_pull_requests@@ -295,9 +297,12 @@ tools:rollup (runs / passing / failing / pending). Use this for "which PRs are stuck", "which open PRs havefailing or pending CI", and per-author or per-repo PR triage. open_to_merge_seconds is coarse — it ismerged_at minus created_at and fuses draft and ready-for-review time, so report it as "open to merge", never- "cycle time". 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.+ "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.param_overrides:date_from:description: >diff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.mdindex f780283f47d7..176e622d6916 100644--- a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md+++ b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md@@ -21,11 +21,11 @@ autonomous agents (e.g. PostHog Desktop) reasoning about their own PRs.- **`pull-requests`** — the PR workhorse. Open PRs plus anything merged or closed since `date_from` (default`-30d`), newest first. Each row carries `author` (nested object: `handle`, `display_name`, `is_bot`), `repo`- (nested: `owner`, `name`), `state`, `is_draft`, `labels`, `open_to_merge_seconds`, and a `ci` rollup- (`runs` / `passing` / `failing` / `pending`) from the head-SHA join. Answers most PR-level questions:- which PRs have failing or pending CI, which are stuck open longest, per-author or per-repo triage, and- time-to-merge stats (aggregate `open_to_merge_seconds` over the returned merged rows yourself — median and p95,- never a mean).+ (nested: `owner`, `name`), `state`, `is_draft`, `labels`, `open_to_merge_seconds`, `ready_to_merge_seconds`,+ and a `ci` rollup (`runs` / `passing` / `failing` / `pending`) from the head-SHA join. Answers most PR-level+ questions: which PRs have failing or pending CI, which are stuck open longest, per-author or per-repo triage, and+ time-to-merge stats (aggregate over the returned merged rows yourself, median and p95, never a mean; prefer+ `ready_to_merge_seconds` where non-null, it excludes draft time).- **`workflow-health`** — per-workflow CI health over a window (`date_from` / `date_to`, default last 24 hours):`run_count`, `success_rate`, `p50_seconds`, `p95_seconds`, `last_failure_at`. Answers "is CI getting faster orslower" and "which workflow is the slow or flaky long pole". There is no built-in trend — call it over two@@ -34,9 +34,10 @@ autonomous agents (e.g. PostHog Desktop) reasoning about their own PRs.when a window has no qualifying runs — guard for null before comparing two windows (a workflow can have runsin one and none in the other). `run_scope=pull_request` scopes to PR-attributed runs, excluding master/main(same-repo PRs only — fork runs carry no PR attribution).-- **`pr-lifecycle`** — a single PR's timeline: a header plus ordered events — opened, then a CI started/finished- pair **per workflow run** (many on a multi-workflow repo, interleaved by time), then merged/closed. Answers- "where is PR N stuck". `metric_quality` is `partial`.+- **`pr-lifecycle`** — a single PR's timeline: a header plus ordered events — opened, ready-for-review and+ converted-to-draft transitions (when the issue-events table is synced), then a CI started/finished pair+ **per workflow run** (many on a multi-workflow repo, interleaved by time), then merged/closed. Answers+ "where is PR N stuck". `metric_quality` is `partial` (no review or comment events).- **`engineering-analytics-flaky-tests`** — the active test-health queue from the per-test CI spans, over awindow (`date_from` default `-7d`, max 30 days). Evidence is counted per CI run, never per span or run attempt.`classification` is `confirmed_flake` only where the evidence proves nondeterminism@@ -59,6 +60,10 @@ These are structural limits of today's snapshot data — state them, don't paper- **`open_to_merge_seconds` is coarse.** It fuses _draft_ time and _ready-for-review_ time into one figure. Reportit as "open to merge", never "cycle time" or "review time". Flag it when long-lived drafts inflate a number.+- **`ready_to_merge_seconds` is the precise companion**: 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 PR's life isn't fully inside the synced issue-event window, or the+ table isn't synced), never zero, so aggregate only over non-null rows and say how many were observable.- **CI status can be stale.** The CI source syncs on a watermark and does not refresh a run that completes afternewer runs land (until the `workflow_run` webhook ships). Treat a `pending` count as unsettled, not as a settledfailure; lead with status, not a verdict.@@ -76,14 +81,14 @@ These are structural limits of today's snapshot data — state them, don't paper## Choosing a tool-| The question | Tool | How |-| ------------------------------------------------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Is CI getting slower? Which workflow is the long pole? | `workflow-health` | Call over two adjacent windows (e.g. `date_from=-14d`, then `date_from=-28d` `date_to=-14d`); compare `p50_seconds` and `p95_seconds` per workflow. Lead with the median but always check p95 separately — they move independently. |-| Which open PRs have failing or pending CI? | `pull-requests` | Keep rows where `ci.failing > 0` or `ci.pending > 0`. `pending` means unsettled (or stale) — not a settled failure. |-| Which PRs are stuck open longest? | `pull-requests` | Keep `state = open`, not `is_draft`, not `author.is_bot`; sort by `created_at` ascending (oldest first). |-| How long are PRs taking to merge? Per author? | `pull-requests` | Over merged rows (`merged_at` set, not bot, not draft), aggregate `open_to_merge_seconds` — median and p95. Group by `author.handle` for **cohort context, not a ranking** (per-developer surveillance is an explicit non-goal). Trend it by calling with two `date_from` windows. |-| Where is PR N stuck? | `pr-lifecycle` | Walk the sorted events: `opened → first CI started`, the CI span (first start → last finish; one pair per workflow), `last CI finished → merged`. The largest gap is the bottleneck. A long open→merge with quick CI points at review/idle time the `partial` data can't itemize yet — say so. |-| What is a failing test costing us? What to quarantine? | `engineering-analytics-flaky-tests` | Default window is `-7d`; rows are already ranked by blast radius (master failures, then distinct PRs hit). Report counts, never rates. For "is it flaky": only `confirmed_flake` rows are proven, and only for tests hand-marked with reruns. |+| The question | Tool | How |+| ------------------------------------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Is CI getting slower? Which workflow is the long pole? | `workflow-health` | Call over two adjacent windows (e.g. `date_from=-14d`, then `date_from=-28d` `date_to=-14d`); compare `p50_seconds` and `p95_seconds` per workflow. Lead with the median but always check p95 separately — they move independently. |+| Which open PRs have failing or pending CI? | `pull-requests` | Keep rows where `ci.failing > 0` or `ci.pending > 0`. `pending` means unsettled (or stale) — not a settled failure. |+| Which PRs are stuck open longest? | `pull-requests` | Keep `state = open`, not `is_draft`, not `author.is_bot`; sort by `created_at` ascending (oldest first). |+| How long are PRs taking to merge? Per author? | `pull-requests` | Over merged rows (`merged_at` set, not bot, not draft), aggregate `ready_to_merge_seconds` where non-null (fall back to `open_to_merge_seconds`, labeled as coarse) — median and p95. Group by `author.handle` for **cohort context, not a ranking** (per-developer surveillance is an explicit non-goal). Trend it by calling with two `date_from` windows. |+| Where is PR N stuck? | `pr-lifecycle` | Walk the sorted events: `opened → ready_for_review` (draft time, when transition events are present), the CI span (first start → last finish; one pair per workflow), `last CI finished → merged`. The largest gap is the bottleneck. A long ready→merge with quick CI points at review/idle time the `partial` data can't itemize yet — say so. |+| What is a failing test costing us? What to quarantine? | `engineering-analytics-flaky-tests` | Default window is `-7d`; rows are already ranked by blast radius (master failures, then distinct PRs hit). Report counts, never rates. For "is it flaky": only `confirmed_flake` rows are proven, and only for tests hand-marked with reruns. |## The high-value chain@@ -107,7 +112,8 @@ CI before merging."## What NOT to do-- Don't call `open_to_merge_seconds` cycle time or review time — it's coarse open-to-merge.+- Don't call `open_to_merge_seconds` cycle time or review time — it's coarse open-to-merge;+ `ready_to_merge_seconds` is the cycle-time figure, and only where non-null.- Don't report a CI count as a settled failure when `pending > 0` — it may be unsettled or stale.- Don't infer reviews, approvals, per-check counts, or deploys — that data isn't ingested yet.- Don't turn per-author buckets into a leaderboard — they're for finding stuck work, not ranking people.diff --git a/products/engineering_analytics/skills/turning-engineering-analytics-into-insights/references/hogql-recipes.md b/products/engineering_analytics/skills/turning-engineering-analytics-into-insights/references/hogql-recipes.mdindex c54c580f063f..f887cf3e5ca9 100644--- a/products/engineering_analytics/skills/turning-engineering-analytics-into-insights/references/hogql-recipes.md+++ b/products/engineering_analytics/skills/turning-engineering-analytics-into-insights/references/hogql-recipes.md@@ -211,7 +211,7 @@ GROUP BY weekORDER BY week```-Name it "open to first review", not "time in review": there is no ready-for-review timestamp, so draft time is fused in, same caveat as `open_to_merge_seconds`.+Name it "open to first review", not "time in review": this recipe reads the PR snapshot only, so draft time is fused in, same caveat as `open_to_merge_seconds` (ready-for-review timestamps live in `<prefix>github_issue_events`, when synced).The reviewer handle is `ifNull(JSONExtractString(user, 'login'), '')` when needed (e.g. to exclude self-reviews by comparing against `author_handle`) — but never build per-reviewer leaderboards.## Recipe: a team's weekly merge time (team_members table)diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5b063db8257d..346851cd476f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6993,7 +6993,7 @@}},"pr-lifecycle": {- "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". metric_quality is \"partial\" — it covers CI events only; review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.",+ "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, ready for review, converted to draft, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". Draft/ready transitions appear only when the issue-events table is synced and cover a bounded recent window. metric_quality is \"partial\" — review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.","category": "Engineering analytics","feature": "engineering_analytics","summary": "PR lifecycle timeline",@@ -7120,7 +7120,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\". 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. Bots and drafts are present; exclude them (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.jsonindex adf56cae9cd7..b0b0fd616997 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7547,7 +7547,7 @@}},"pr-lifecycle": {- "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". metric_quality is \"partial\" — it covers CI events only; review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.",+ "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, ready for review, converted to draft, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". Draft/ready transitions appear only when the issue-events table is synced and cover a bounded recent window. metric_quality is \"partial\" — review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.","category": "Engineering analytics","feature": "engineering_analytics","summary": "PR lifecycle timeline",@@ -7702,7 +7702,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\". 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. Bots and drafts are present; exclude them (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/api/generated.ts b/services/mcp/src/api/generated.tsindex aee4340c6842..d972fcbb3bee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44313,6 +44313,8 @@ export namespace Schemas {/*** * `opened` - OPENED+ * * `ready_for_review` - READY_FOR_REVIEW+ * * `converted_to_draft` - CONVERTED_TO_DRAFT* * `ci_started` - CI_STARTED* * `ci_finished` - CI_FINISHED* * `merged` - MERGED@@ -44323,6 +44325,8 @@ export namespace Schemas {export const PRLifecycleEventKindEnum = {Opened: 'opened',+ ReadyForReview: 'ready_for_review',+ ConvertedToDraft: 'converted_to_draft',CiStarted: 'ci_started',CiFinished: 'ci_finished',Merged: 'merged',@@ -44330,9 +44334,11 @@ export namespace Schemas {} as const;export interface PRLifecycleEvent {- /** Event kind: opened, ci_started, ci_finished, merged, or closed.+ /** Event kind: opened, ready_for_review, converted_to_draft, ci_started, ci_finished, merged, or closed.** * `opened` - OPENED+ * * `ready_for_review` - READY_FOR_REVIEW+ * * `converted_to_draft` - CONVERTED_TO_DRAFT* * `ci_started` - CI_STARTED* * `ci_finished` - CI_FINISHED* * `merged` - MERGED@@ -44341,7 +44347,7 @@ export namespace Schemas {/** When the event occurred. */at: string;/**- * Optional detail, e.g. workflow name and conclusion for CI events.+ * Optional detail: workflow name and conclusion for CI events, the acting user's login for draft/ready transitions.* @nullable*/detail?: string | null;@@ -60375,6 +60381,11 @@ export namespace Schemas {* @nullable*/open_to_merge_seconds: number | null;+ /**+ * True ready-to-merge cycle time in seconds: 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 when unmerged or not observed (the PR's life isn't fully inside the synced issue-event window) - null never means zero.+ * @nullable+ */+ ready_to_merge_seconds: number | null;/** GitHub label names on the pull request. */labels: string[];/** CI triggers attributed to this PR: distinct head SHAs across its workflow runs. Fork-PR runs are unattributed. */