: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(engineering-analytics): add a materialized per-PR friction view (#105972)
Julian Bez4cc95ef6d772
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 0d052da0bd19..7c535d4f1ecc 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -77,7 +77,7 @@ graph LRCUR --> EPEP --> MCP["MCP tools<br/>enabled subset in mcp/tools.yaml"]EP --> UI["UI scenes"]- CUR --> WV["managed warehouse views<br/>job_costs / ci_job_history / ci_failures<br/>for insights + SQL"]+ CUR --> WV["managed warehouse views<br/>job_costs / ci_job_history / ci_failures / pr_friction<br/>for insights + SQL"]```- Job-level CI: per-job duration, queue time, runner tier, and dollar cost ride `workflow_jobs` (webhook stream plus bounded backfill).@@ -124,7 +124,7 @@ Change one only in a separate PR with a written reason. Engineering-level decisi- Two first-class surfaces, one endpoint set: the in-app UI and MCP tools. Named typed endpoints run the curated read layer privately (no global HogQL views, core imports only the viewset); keep `mcp/tools.yaml` current whenever endpoints change.- One sanctioned write: the test-health sidecar (quarantine, as an issue plus PR through the team's GitHub App). The write now lives behind the API and MCP tool only; the Tests tab became the Trunk quarantine debt scoreboard because Trunk's auto-quarantine outran the file-based flow as the thing teams need to see. No saved views or stateful filters; persisted surfaces are a separate decision.- Data path: HogQL over the warehouse, plus reads from Logs and Traces. PR lifecycle event ingestion deferred. Product Postgres DB stays empty.-- No author leaderboards or per-developer performance rankings, ever. The surveillance risk is turning developer figures into an ordered population or a performance scorecard. An engineer inspecting their own friction is not that risk, and neither is a deliberate comparison with a colleague they already know. So author figures may be read one author at a time, and compared on purpose with another author, a GitHub team, or the repository. The product must never rank, sort, score or enumerate authors by delivery or CI/PR figures. The author page (one author's PRs, CI cost, delivery timing and lead time against the repository) is reached from PR-row author links, and a colleague's page may be opened directly for such a comparison. The author page and the pull request page also set the ready-to-merge time next to the author's own team, as an aggregate. The team page renders the same delivery figures for one GitHub team, as an aggregate and never a per-member figure. It leaves out the author page's per-pull-request day view, which is too long to read at team size.+- No developer performance rankings, ever. The surveillance risk is a performance scorecard: output or speed turned into an ordered population of people. An engineer inspecting their own friction is not that risk, and neither is a deliberate comparison with a colleague they already know. So author figures may be read one author at a time, and compared on purpose with another author, a GitHub team, or the repository. The product must never rank, sort, score or enumerate authors by delivery performance. Friction is not performance: scoring and ordering the friction developers meet (red CI they did not cause, merge-queue kickouts, review waits, rework) finds the people the dev loop costs most, and a friction figure never counts how much or how fast someone ships. The author page (one author's PRs, CI cost, delivery timing and lead time against the repository) is reached from PR-row author links, and a colleague's page may be opened directly for such a comparison. The author page and the pull request page also set the ready-to-merge time next to the author's own team, as an aggregate. The team page renders the same delivery figures for one GitHub team, as an aggregate and never a per-member figure. It leaves out the author page's per-pull-request day view, which is too long to read at team size.- 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, 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.diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 34c6e6754e5e..21d7e8a93d90 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -13,12 +13,13 @@ The goal is Signals for PostHog Desktop (README → "The goal"): Signal detectio## 2. Non-goals-- Per-developer surveillance _rankings_, ever. They exist only to compare people.- - No author leaderboards or cross-author rankings: no read discovers, orders, scores or enumerates authors by their figures, and no flaky-rate scoreboard. Another author's figures come back only when the person asking named that author.+- Rating developers' performance, ever. Such rankings exist only to compare people.+ - No read ranks, scores or compares people by what they produce or how fast they deliver: no leaderboards of merged pull requests, lines or lead time, no "who is slower", and no scorecard of an author's flaky tests. Another author's delivery figures come back only when the person asking named that author.+ - Friction is not performance. A read may score and order the friction developers meet: red CI they did not cause, re-runs that failed again, merge-queue kickouts, review waits and rework. The purpose is to find the people the dev loop costs most. A friction figure is a mean per pull request of what happened to the author, so shipping more or faster does not raise it. The pull request count only decides whether an author gets a score and how far a short record is pulled toward the typical author. Friction reads one fixed 30-day window of merged pull requests on every page, whatever the date picker says, so a pull request's score is the same on its own page and in its author's list. The per-pull-request inputs are defined once in `logic/views/pr_friction.py`.- The author-scoped _page_ is allowed: one author's pull requests, CI cost, delivery timing and lead time, each figure next to the same figure over the whole repository. It answers "is my friction unusual here", never "who is slower". It is reached from the author links on PR rows, and a colleague's page may be opened directly for a deliberate comparison.- The author's own team is the standing baseline next to the repository: the ready-to-merge time also sits next to the aggregate of the team the author works in, on the author page and on the pull request page. When the rule below cannot settle on one of the author's teams, each of those teams gets its own row. A team row is always an aggregate, never a member.- A team figure is shown only when at least two other authors contribute a value to it in the window. Below that the median is one or two pull requests, which reads as a team's pace and is not one. Two keeps a real three-person team readable. This is a noise floor, not a privacy floor: every author page opens by name, and each pull request's own time is on its page, so the median discloses nothing that is not already shown.- - The window is the page's date range on the author page. On the pull request page it is the 30 days before the pull request merged, or the last 30 days while it is open, and the pull request itself stays out of the figures it is compared with.+ - The team baseline's window is the page's date range on the author page. On the pull request page it is the 30 days before the pull request merged, or the last 30 days while it is open, and the pull request itself stays out of the figures it is compared with.- Real-time alerting on individual PRs. That's notification surface, not analytics.- Replacing GitHub's own UI. We surface signal, not the raw PR thread.- Code-quality static analysis. Different product space.@@ -38,7 +39,7 @@ graph TBsubgraph "Surface (thin)"Endpoints["named typed DRF endpoints<br/>@extend_schema → OpenAPI → MCP tools + UI client"]- WV["managed warehouse views<br/>job_costs / ci_job_history / ci_failures"]+ WV["managed warehouse views<br/>job_costs / ci_job_history / ci_failures / pr_friction"]endsubgraph "Curated read layer (domain rules defined ONCE)"@@ -97,9 +98,10 @@ The endpoint catalog is `presentation/views.py`; the agent-facing descriptions l### Exposed warehouse views-Three per-team managed views (`DataWarehouseSavedQuery`, kind `engineering_analytics`) expose the curated CI substrate to insights, subscriptions, other products, and `execute-sql`: the only surface where the read layer is reachable as data rather than through the named endpoints.-One gate for all three: a team gets them only when a GitHub source has **both** `workflow_runs` and `workflow_jobs` synced, so they appear together or not at all.+Per-team managed views (`DataWarehouseSavedQuery`, kind `engineering_analytics`) expose the curated CI substrate to insights, subscriptions, other products, and `execute-sql`: the only surface where the read layer is reachable as data rather than through the named endpoints.+One gate for the three per-job views: a team gets them only when a GitHub source has **both** `workflow_runs` and `workflow_jobs` synced, so they appear together or not at all.They are non-materialized: the rendered SQL is persisted per team and re-synced on every runs/jobs load, so a builder change reaches active teams within one sync cycle.+The per-PR friction view is the exception, below: it also needs the `pull_requests` snapshot, and it is materialized.#### `engineering_analytics_job_costs`@@ -126,6 +128,15 @@ They are non-materialized: the rendered SQL is persisted per team and re-synced- `fingerprint` = test id plus normalized error signature (volatile hex/digits collapsed): the group key across runs.- The recipe lives in code, not a stored materialization, on purpose: it is pytest-only and must evolve by PR as more runners (jest, playwright, cargo) get covered.+#### `engineering_analytics_pr_friction`++- One row per pull request merged in the last 30 days: what its author went through. Red stretches counted by what turned them green, re-runs that failed again, CI running time per push, the wait for the first approval, pushes after approval, merge-queue time and kickouts.+- The red and running time is the PR timeline replay (§6) written as set-based HogQL, so one query covers every pull request in the window. `tests/test_pr_friction.py` replays seeded pull requests through both and asserts they agree, the way the cost view is held to the Python cost model.+- It counts friction and does not score it. Curves and weights are applied when the view is read, so a weight change needs no rematerialization.+- Materialized on the managed-view schedule, because the replay is too heavy to run on every read. Each run replaces the table, so it only holds the pull requests inside the window.+- A materialized view spends the team's warehouse compute, so it exists only for organizations the `engineering-analytics-friction` flag targets. The flag is evaluated per organization, because the view sync runs with no user. When the flag service gives no answer, the sync keeps the view the team already has.+- The view unions every GitHub source of the team, and each row carries its `source_id`. A product read filters on the one source the caller may use. A query on the materialized view itself checks access to the view, not to each source in it, like any materialized managed view.+## 6. Locked decisionsEngineering-specific decisions. Product-level decisions live in README → Locked decisions. If you want to change one, do it in a separate PR with a written reason.@@ -159,8 +170,8 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- **CI Signals use immutable evidence.** Flaky checks require job rows from `github_workflow_jobs` showing a failed attempt followed by a successful later attempt for the same `(run_id, job)`. The run snapshot alone cannot prove this transition. Broken-default-branch detection reads GitHub's reported default branch from the PR snapshot's `base.repo`, the only full repository object in the tables this product reads (`query_default_branches` documents why the runs snapshot cannot answer it). A repo with no PR rows resolves nothing and is skipped: `repo_overview`'s master/main run-volume guess stays a display approximation, because a P1 needs GitHub's report, not inference. Detection gates on the canonical pass rate above. Duration comparisons require enough successful samples because the percentiles exclude failed and cancelled runs. All three conditions carry a week-stable `source_id`, and the coordinator records each emitted key in `SignalEmissionRecord` so an hourly sweep doesn't re-emit the same standing condition within its week. For broken-default-branch that means one signal per week per workflow, accepting that a distinct second breakage of the same workflow inside one week dedupes into the first rather than minting a signal (and a ledger row) per completed run.- **HogQL only for analytics data.** No raw ClickHouse.- **No product Postgres DB.** Analytics data lives in the warehouse / ClickHouse; any product-config model goes on the main DB as a team-scoped model (`TeamScopedRootMixin`), never a separate DB.-- **No author leaderboards or per-developer performance rankings; individual comparison is allowed.** The surveillance risk is turning developer figures into an ordered population or a performance scorecard. It is not an engineer inspecting their own friction, and not a comparison with a colleague they already know. Author figures may therefore be read one author at a time, and compared deliberately with another author, a GitHub team, or the repository. The product must not rank, sort, score or enumerate authors by delivery or CI/PR figures, and a team view must never break its aggregate down into a per-member ranking. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and give repository context. `delivery_comparison` gives explicit comparison context: one author's ready-to-merge medians next to the aggregate of the relevant teams and the repository, and next to another author's figures when the person asking named that author. It does not discover, order or return a population of authors. Review pace differs a lot between teams, so the repository median alone cannot say whether an author's wait is normal for the work they do. The read picks the teams from the author's own memberships by one fixed rule, defined once in the logic layer: the teams the pull request in focus asked to review, else the team asked by the most of the author's pull requests, counting each pull request once per team and only requests made in the window, else every team the author is in. Each picked team gets its own row, and teams are never pooled. What a pull request asked comes from its immutable `review_requested` issue events, never from the pull request snapshot, which drops a request once the team reviews. Without those events the rule falls through to every team the author is in. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reached from PR-row author links, and a colleague's page may be opened directly; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).-- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there. A single pull request replays its full CI history, while its merge-queue evidence uses the shared seven-day gate lookback.+- **No developer performance rankings; individual comparison is allowed.** The surveillance risk is a performance scorecard: output or speed turned into an ordered population of people. It is not an engineer inspecting their own friction, and not a comparison with a colleague they already know. Author figures may therefore be read one author at a time, and compared deliberately with another author, a GitHub team, or the repository. The product must not rank, sort, score or enumerate authors by delivery performance (throughput, lead time, time to merge), and a team view must never break a delivery aggregate down into a per-member ranking. Friction is outside that rule (§2): the per-PR friction view carries each pull request's author next to the friction it met, so a read over it may score and order that friction. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and give repository context. `delivery_comparison` gives explicit comparison context: one author's ready-to-merge medians next to the aggregate of the relevant teams and the repository, and next to another author's figures when the person asking named that author. It does not discover, order or return a population of authors. Review pace differs a lot between teams, so the repository median alone cannot say whether an author's wait is normal for the work they do. The read picks the teams from the author's own memberships by one fixed rule, defined once in the logic layer: the teams the pull request in focus asked to review, else the team asked by the most of the author's pull requests, counting each pull request once per team and only requests made in the window, else every team the author is in. Each picked team gets its own row, and teams are never pooled. What a pull request asked comes from its immutable `review_requested` issue events, never from the pull request snapshot, which drops a request once the team reviews. Without those events the rule falls through to every team the author is in. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reached from PR-row author links, and a colleague's page may be opened directly; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).+- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A commit's state per workflow is its latest started attempt, ordered by start, attempt and run id, so two runs that start in the same second always resolve the same way. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there. A single pull request replays its full CI history, while its merge-queue evidence uses the shared seven-day gate lookback.- **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). 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.diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 714dba108913..830484e1b531 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -50,6 +50,9 @@ class GitHubSourceNotConnectedError(Exception):# The product's rollout flag: gates the API surface (PostHogFeatureFlagPermission) and the CI-signals sweep.ENGINEERING_ANALYTICS_FEATURE_FLAG = "engineering-analytics"+# Evaluated per organization, not per person: the view sync runs with no user, and a materialized view+# spends the team's warehouse compute, so no team gets one without opting in.+FRICTION_VIEW_FEATURE_FLAG = "engineering-analytics-friction"class CISignalsSyncStatus(StrEnum):@@ -285,6 +288,7 @@ class ExpectedWarehouseView:name: strquery: strfields: dict[str, FieldOrTable]+ materialized: bool = False@dataclass(frozen=True)diff --git a/products/engineering_analytics/backend/facade/warehouse_views.py b/products/engineering_analytics/backend/facade/warehouse_views.pyindex 8a6ed6f06891..288dd0b1650e 100644--- a/products/engineering_analytics/backend/facade/warehouse_views.py+++ b/products/engineering_analytics/backend/facade/warehouse_views.py@@ -6,22 +6,63 @@ facade so data_modeling never imports this product's read layer directly — itprovider-neutral ``ExpectedWarehouseView`` contract."""+import posthoganalytics+from posthog.models.team import Team-from products.engineering_analytics.backend.facade.contracts import ExpectedWarehouseView-from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.engineering_analytics.backend.facade.contracts import FRICTION_VIEW_FEATURE_FLAG, ExpectedWarehouseView+from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs, pr_friction+from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKinddef get_expected_warehouse_views(team: Team) -> list[ExpectedWarehouseView]:"""The team's exposed warehouse views. Empty when the team has no GitHub source with both theworkflow_runs and workflow_jobs endpoints synced (so no view is created for such teams).- All three views share that same qualifying-source gate, so they appear together or not at all:+ The three per-job views share that same qualifying-source gate, so they appear together or not at all:per-job cost, per-job-attempt history with commit attribution, and fingerprinted CI failure lines.+ The per-PR friction view also needs the pull-request snapshot, and is materialized because replaying+ every pull request's timeline is too heavy to run on each read. It exists only for organizations the+ friction flag targets."""views: list[ExpectedWarehouseView] = []for module in (job_costs, ci_job_history, ci_failures):query = module.build_team_view(team)if query is not None:views.append(ExpectedWarehouseView(name=module.VIEW_NAME, query=query, fields=module.FIELDS))+ friction_query = pr_friction.build_team_view(team) if _friction_view_enabled(team) else None+ if friction_query is not None:+ views.append(+ ExpectedWarehouseView(+ name=pr_friction.VIEW_NAME, query=friction_query, fields=pr_friction.FIELDS, materialized=True+ )+ )return views+++def _friction_view_enabled(team: Team) -> bool:+ org_id = str(team.organization_id)+ project_id = str(team.id)+ enabled = posthoganalytics.feature_enabled(+ FRICTION_VIEW_FEATURE_FLAG,+ str(team.uuid),+ groups={"organization": org_id, "project": project_id},+ group_properties={"organization": {"id": org_id}, "project": {"id": project_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ if enabled is None:+ # No answer (the flag service failed, or the flag does not exist). The sync deletes every view it+ # does not expect, so keep the view the team has rather than drop a materialized table on an outage.+ return (+ # Only this product's managed view counts: a user's own saved query can carry the same name.+ DataWarehouseSavedQuery.objects.filter(+ team_id=team.id,+ name=pr_friction.VIEW_NAME,+ managed_viewset__kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS,+ )+ .exclude(deleted=True)+ .exists()+ )+ return enableddiff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.pyindex 8a5fed6f6734..90ad6aee00de 100644--- a/products/engineering_analytics/backend/logic/pr_timeline.py+++ b/products/engineering_analytics/backend/logic/pr_timeline.py@@ -152,12 +152,13 @@ class PRTimelineBuilder:for push in pushes:sha_attempts = by_sha[push.head_sha]by_workflow: dict[str, list[RunAttempt]] = defaultdict(list)- for attempt in sorted(sha_attempts, key=lambda a: (a.started_at, a.attempt)):+ # The run id breaks a tie between two runs of one workflow that start in the same second.+ for attempt in sorted(sha_attempts, key=lambda a: (a.started_at, a.attempt, a.run_id)):by_workflow[attempt.workflow_name].append(attempt)grouped.append(_Push(head_sha=push.head_sha, pushed_at=push.pushed_at, attempts_by_workflow=dict(by_workflow)))- return sorted(grouped, key=lambda push: push.pushed_at)+ return sorted(grouped, key=lambda push: (push.pushed_at, push.head_sha))def _queue_span(self) -> _QueueSpan:"""The continuous queue stretch: from the first gate attempt after the last push to the mergediff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex f9129afdfe1a..b2539af03636 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -207,6 +207,9 @@ class JobSourceTables:# Optional: these views qualify on jobs + runs alone, so a repo can reach them with no PR# snapshot. Consumers that enrich from it (default-branch PR attribution) degrade without it.pull_requests: str | None = None+ issue_events: str | None = None+ reviews: str | None = None+ source_id: str = ""def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:@@ -232,6 +235,9 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:workflow_jobs=jobs,workflow_runs=runs,pull_requests=tables.get(PULL_REQUESTS_SCHEMA),+ issue_events=tables.get(ISSUE_EVENTS_SCHEMA),+ reviews=tables.get(REVIEWS_SCHEMA),+ source_id=str(source.id),))return resolveddiff --git a/products/engineering_analytics/backend/logic/views/pr_friction.py b/products/engineering_analytics/backend/logic/views/pr_friction.pynew file mode 100644index 000000000000..abd0ca0d8dc9--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/pr_friction.py@@ -0,0 +1,432 @@+"""Curated per-PR friction view: what each recently merged pull request put its author through.++One row per pull request merged in the last ``FRICTION_WINDOW``. The red and running time comes from+the same replay as ``logic/pr_timeline.py``, written as set-based HogQL so one query covers every PR in+the window. The rules are the timeline's own:++- A commit's check state per workflow is its latest started attempt, ordered by (start, attempt, run id).+- A failed latest attempt is red from its completion until the next attempt of that workflow starts, the+ next push arrives, or the pull request merges.+- A red stretch is labelled by what turned it green: every failed workflow passed a later attempt on the+ same commit (a re-run), else every failed job also failed on the default branch within+ ``MASTER_FAILURE_PROXIMITY`` (master broken), else a later push exists (fixed by a push), else not provable.+- Precedence at any moment: merge queue, red, CI running, then review states.++``tests/test_pr_friction.py`` replays seeded pull requests through both this view and+``PullRequestTimelinesQuery`` and asserts they agree, so the two definitions cannot drift apart.++The view counts friction, it does not score it. Curves and weights are applied when it is read+(``logic/friction.py``), so a weight change needs no rematerialization. Red stretches are counted, not+timed: an author who leaves a red pull request alone is hardly affected, so the length of a stretch+says little about what the author went through.++Materialized on the managed-view schedule. Each run replaces the table, so it only ever holds the+pull requests inside the window.+"""++import re+from datetime import timedelta+from typing import TYPE_CHECKING++from posthog.hogql.database.models import (+ BooleanDatabaseField,+ DateTimeDatabaseField,+ FieldOrTable,+ FloatArrayDatabaseField,+ FloatDatabaseField,+ IntegerDatabaseField,+ StringDatabaseField,+)++from products.engineering_analytics.backend.logic.delivery_scope import CI_LOOKBACK+from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, gate_attempt_expr+from products.engineering_analytics.backend.logic.pr_timeline import MASTER_FAILURE_PROXIMITY+from products.engineering_analytics.backend.logic.queries._workflow_filters import DECISIVE_FAILURE_CONCLUSIONS_SQL+from products.engineering_analytics.backend.logic.sources import resolve_job_source_tables+from products.engineering_analytics.backend.logic.views import (+ issue_events,+ pull_requests,+ reviews,+ workflow_jobs,+ workflow_runs,+)++if TYPE_CHECKING:+ from posthog.models.team import Team++VIEW_NAME = "engineering_analytics_pr_friction"++FRICTION_WINDOW = timedelta(days=30)++FIELDS: dict[str, FieldOrTable] = {+ "repo_owner": StringDatabaseField(name="repo_owner"),+ "repo_name": StringDatabaseField(name="repo_name"),+ "number": IntegerDatabaseField(name="number"),+ "author": StringDatabaseField(name="author"),+ "author_avatar_url": StringDatabaseField(name="author_avatar_url"),+ "is_bot": BooleanDatabaseField(name="is_bot"),+ "merged_at": DateTimeDatabaseField(name="merged_at"),+ "push_count": IntegerDatabaseField(name="push_count"),+ # Red stretches by what turned them green. Adjacent pieces of one kind are one stretch.+ "flake_red_count": IntegerDatabaseField(name="flake_red_count"),+ "master_red_count": IntegerDatabaseField(name="master_red_count"),+ "unknown_red_count": IntegerDatabaseField(name="unknown_red_count"),+ "own_red_count": IntegerDatabaseField(name="own_red_count"),+ "futile_rerun_count": IntegerDatabaseField(name="futile_rerun_count"),+ "ci_wait_seconds": FloatArrayDatabaseField(name="ci_wait_seconds"),+ # NULL when the reviews table is not synced, nobody approved, or the ready time is not observed.+ "first_approval_wait_seconds": FloatDatabaseField(name="first_approval_wait_seconds", nullable=True),+ "pushes_after_approval": IntegerDatabaseField(name="pushes_after_approval", nullable=True),+ # NULL when the pull request never entered the merge queue.+ "queue_seconds": FloatDatabaseField(name="queue_seconds", nullable=True),+ "kickout_count": IntegerDatabaseField(name="kickout_count", nullable=True),+ # A read filters on its own authorized source: the view unions every source, and a member can be denied some.+ "source_id": StringDatabaseField(name="source_id"),+}++# The same regex as ``queries/master_failures.strip_shard_suffix``, so shards of one job group together.+_STRIP_SHARD = "replaceRegexpOne({name}, '\\\\s*\\\\((\\\\d+)/(\\\\d+)\\\\)(\\\\))?$', '\\\\3')"+_SOURCE_ID = re.compile(r"[0-9a-fA-F-]{1,64}")+_FAR = "toDateTime64('2100-01-01 00:00:00', 6, 'UTC')"+_EPOCH = "toDateTime64('1970-01-01 00:00:00', 6, 'UTC')"+++def _days(delta: timedelta) -> int:+ return delta.days+++def _raw_floor(days: int) -> str:+ # Date-only string one day below the window, compared against the raw ISO strings the source lands.+ return f"toString(toDate(now() - INTERVAL {days + 1} DAY))"+++def _strip_shard(expr: str) -> str:+ return _STRIP_SHARD.format(name=expr)+++def build_query(+ *,+ source_id: str,+ pull_requests_table: str,+ workflow_runs_table: str,+ workflow_jobs_table: str,+ issue_events_table: str | None,+ reviews_table: str | None,+) -> str:+ if not _SOURCE_ID.fullmatch(source_id):+ raise ValueError(f"not a source id: {source_id!r}")+ window_days = _days(FRICTION_WINDOW)+ run_days = window_days + _days(CI_LOOKBACK)+ gate_days = window_days + _days(GATE_RUN_LOOKBACK)+ # Re-runs create their jobs before the run's newest start, so the jobs floor sits a week lower.+ job_floor_days = run_days + 7+ proximity_hours = int(MASTER_FAILURE_PROXIMITY.total_seconds() // 3600)++ prs = f"({pull_requests.build_query(pull_requests_table)})"+ runs = workflow_runs.build_query(+ workflow_runs_table, pull_requests_table=pull_requests_table, started_floor=True+ ).replace("{run_started_floor}", _raw_floor(run_days))+ jobs = workflow_jobs.build_query(workflow_jobs_table, created_floor=True).replace(+ "{job_created_floor}", _raw_floor(job_floor_days)+ )+ run_from = f"now() - INTERVAL {run_days} DAY"++ if issue_events_table:+ events = issue_events.build_query(issue_events_table, created_floor=True).replace(+ "{event_created_floor}", _raw_floor(run_days)+ )+ ready_join = f"""+ LEFT JOIN (+ SELECT e.pr_number AS number,+ maxOrNullIf(e.created_at, e.event = '{issue_events.READY_FOR_REVIEW_EVENT}' AND e.created_at <= p2.merged_at) AS ready_at+ FROM ({events}) AS e+ INNER JOIN pr AS p2 ON p2.number = e.pr_number+ GROUP BY e.pr_number+ ) AS rd ON rd.number = p.number"""+ ready_expr = "if(rd.ready_at > toDateTime('2000-01-01 00:00:00') AND rd.ready_at <= p.merged_at, rd.ready_at, p.created_at)"+ # Without a ready event, the created time stands in only when the event scan covers the whole life+ # of the PR. An older PR may have left draft before the scan floor, and an approval given while it+ # was a draft would then read as the first approval.+ # A PR without a ready event has a NULL ready_at, and NULL must not pass the guard as "not false".+ ready_observed_expr = (+ f"ifNull(rd.ready_at > toDateTime('2000-01-01 00:00:00') AND rd.ready_at <= p.merged_at, false) "+ f"OR p.created_at >= now() - INTERVAL {run_days} DAY"+ )+ else:+ ready_join = ""+ ready_expr = "p.created_at"+ ready_observed_expr = "false"++ if reviews_table:+ approvals_join = f"""+ LEFT JOIN (+ SELECT rv.pr_number AS number, groupArray(rv.submitted_at) AS approved_at+ FROM ({reviews.build_query(reviews_table)}) AS rv+ WHERE rv.state = '{reviews.APPROVED_STATE}' AND rv.pr_number IN (SELECT number FROM pr)+ GROUP BY rv.pr_number+ ) AS ap ON ap.number = p.number"""+ approvals_expr = "ap.approved_at"+ else:+ approvals_join = ""+ approvals_expr = "[]"++ return f"""+WITH+pr AS (+ SELECT number, author_handle AS author, author_avatar_url, is_bot, repo_owner, repo_name, default_branch,+ created_at, merged_at+ FROM {prs} AS p+ WHERE merged_at >= now() - INTERVAL {window_days} DAY AND merged_at <= now()+),+bounds AS (+ SELECT p.number AS number, p.author AS author, p.author_avatar_url AS author_avatar_url, p.is_bot AS is_bot,+ p.repo_owner AS repo_owner,+ p.repo_name AS repo_name, p.merged_at AS ended_at,+ {ready_expr} AS ready_at,+ {ready_observed_expr} AS ready_observed,+ greatest({ready_expr}, {run_from}) AS started_at,+ {approvals_expr} AS approved_at+ FROM pr AS p{ready_join}{approvals_join}+),+job_attempts AS (+ SELECT run_id, groupArray(tuple(attempt_number, started_at, completed_at, unfinished, failed_jobs, unsuccessful)) AS jas+ FROM (+ SELECT run_id, ifNull(run_attempt, 1) AS attempt_number,+ min(started_at) AS started_at,+ max(completed_at) AS completed_at,+ countIf(status != 'completed') AS unfinished,+ groupArrayIf(name, conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) AS failed_jobs,+ countIf(conclusion NOT IN ('success', 'skipped')) AS unsuccessful+ FROM ({jobs}) AS j+ WHERE NOT is_rerun_copy+ GROUP BY run_id, attempt_number+ HAVING started_at IS NOT NULL+ )+ GROUP BY run_id+),+master AS (+ SELECT workflow_name, groupArray(tuple(job, completed_at)) AS fails+ FROM (+ SELECT ifNull(workflow_name, '') AS workflow_name,+ {_strip_shard("name")} AS job,+ parseDateTimeBestEffort(completed_at) AS completed_at+ FROM {workflow_jobs_table}+ WHERE created_at >= {_raw_floor(run_days)}+ AND head_branch IN (SELECT default_branch FROM pr WHERE default_branch != '')+ -- The timeline counts failures of default-branch runs that started in its window, gate runs excluded.+ AND run_id IN (SELECT id FROM ({runs}) AS mr WHERE NOT mr.is_merge_queue AND mr.run_started_at >= {run_from})+ AND conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})+ AND completed_at IS NOT NULL+ )+ WHERE completed_at IS NOT NULL+ GROUP BY workflow_name+),+run_rows AS (+ -- One row per run, with its attempts assembled the way PullRequestTimelinesQuery does.+ SELECT r.pr_number AS number, r.id AS run_id, r.is_merge_queue AS is_merge_queue, r.head_sha AS head_sha,+ r.head_branch AS head_branch, r.workflow_name AS workflow_name, r.status AS status,+ r.run_started_at AS run_started_at, r.updated_at AS updated_at,+ coalesce(r.created_at, r.run_started_at) AS queued_at,+ b.started_at AS s0, b.ended_at AS e0,+ NOT r.is_merge_queue AND ifNull(r.conclusion, '') != 'skipped' AS is_ci_run,+ ifNull(r.run_attempt, 1) AS newest,+ r.status = 'completed' AS run_completed,+ r.status = 'completed' AND ifNull(r.conclusion, '') IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL}) AS run_failed,+ r.status = 'completed' AND ifNull(r.conclusion, '') = 'success' AS run_success,+ -- Only re-runs and failures need job rows: a first attempt that did not fail is its run row.+ if(ifNull(r.run_attempt, 1) > 1 OR ifNull(r.conclusion, '') IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL}), ja.jas, []) AS jas,+ m.fails AS master_fails+ FROM ({runs}) AS r+ INNER JOIN bounds AS b ON b.number = r.pr_number+ LEFT JOIN job_attempts AS ja ON ja.run_id = r.id+ LEFT JOIN master AS m ON m.workflow_name = r.workflow_name+ WHERE r.run_started_at >= {run_from} AND r.pr_number > 0+),+runs_with_attempts AS (+ -- Attempt tuple: (attempt, queued_at, started_at, completed_at, failed, succeeded, failed_jobs, run_id).+ -- The run row decides its newest attempt's outcome and end; the jobs sync can lag behind it.+ SELECT *,+ arrayConcat(+ arrayMap(ja -> tuple(+ ja.1,+ queued_at,+ ja.2,+ if(ja.1 = newest AND run_completed, coalesce(updated_at, if(ja.4 > 0, NULL, ja.3)), if(ja.4 > 0, NULL, ja.3)),+ length(ja.5) > 0 OR (ja.1 = newest AND run_failed),+ if(ja.1 = newest AND run_completed, run_success AND length(ja.5) = 0, ja.4 = 0 AND ja.6 = 0 AND length(ja.5) = 0),+ ja.5,+ run_id+ ), jas),+ if(length(jas) = 0 OR newest > arrayMax(arrayMap(ja -> ja.1, jas)),+ [tuple(newest, queued_at, run_started_at, if(run_completed, updated_at, NULL), run_failed, run_success, arrayFilter(x -> 0, ['']), run_id)],+ [])+ ) AS attempts_raw+ FROM run_rows+),+runs_explained AS (+ -- Attempt tuple gains element 9: every failed job also failed on the default branch nearby.+ SELECT number, is_merge_queue, head_sha, head_branch, workflow_name, status, run_started_at, updated_at, queued_at,+ s0, e0, is_ci_run, run_failed,+ if(is_ci_run, arrayMap(a -> tuple(a.1, a.2, a.3, a.4, a.5, a.6, a.7, a.8,+ a.5 AND a.4 IS NOT NULL AND length(a.7) > 0 AND arrayAll(fj -> arrayExists(+ mf -> mf.1 = {_strip_shard("fj")}+ AND mf.2 >= a.4 - toIntervalHour({proximity_hours}) AND mf.2 <= a.4 + toIntervalHour({proximity_hours}),+ ifNull(master_fails, [])), a.7)),+ arrayFilter(a -> a.3 <= e0 OR (a.1 = 1 AND a.2 <= e0), attempts_raw)), []) AS attempts+ FROM runs_with_attempts+),+workflows AS (+ -- One group per workflow on one commit, or per merge-queue gate attempt.+ SELECT number, is_merge_queue, key, wf_key,+ any(s0) AS w_s0, any(e0) AS w_e0,+ minIf(queued_at, NOT is_merge_queue) AS first_created,+ arraySort(x -> tuple(x.3, x.1, x.8), arrayFlatten(groupArray(attempts))) AS xs,+ minIf(run_started_at, is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0) AS gate_start,+ if(countIf(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0+ AND (status != 'completed' OR updated_at IS NULL)) > 0,+ {_FAR}, maxIf(updated_at, is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0)) AS gate_end,+ countIf(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0) > 0 AS has_gate,+ max(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0 AND run_failed) AS gate_failed+ FROM (+ SELECT *,+ if(is_merge_queue, {gate_attempt_expr("head_branch")}, head_sha) AS key,+ if(is_merge_queue, '', workflow_name) AS wf_key+ FROM runs_explained+ )+ GROUP BY number, is_merge_queue, key, wf_key+),+workflow_spans AS (+ -- Red: a failed latest attempt, from its end until the next attempt starts.+ -- Running: a started latest attempt that has not finished, or a first attempt still waiting to start.+ SELECT number, is_merge_queue, key, w_s0 AS s0, w_e0 AS e0, first_created, gate_start, gate_end, has_gate, gate_failed,+ arrayFilter(t -> t.2 > t.1, arrayMap(i -> tuple(+ assumeNotNull(xs[i].4),+ if(i < length(xs), xs[i + 1].3, {_FAR}),+ arrayExists(y -> y.3 >= xs[i].4 AND y.4 IS NOT NULL AND y.6, xs),+ xs[i].9),+ arrayFilter(i -> xs[i].5 AND xs[i].4 IS NOT NULL, arrayEnumerate(xs)))) AS reds,+ arrayFilter(t -> t.2 > t.1, arrayConcat(+ arrayMap(i -> tuple(xs[i].3, least(coalesce(xs[i].4, {_FAR}), if(i < length(xs), xs[i + 1].3, {_FAR}))), arrayEnumerate(xs)),+ if(length(xs) > 0, [tuple(arrayMin(arrayMap(y -> if(y.1 = 1, y.2, {_FAR}), xs)), xs[1].3)], [])+ )) AS runs,+ arrayCount(x -> x.1 > 1 AND x.5, xs) AS futile_reruns+ FROM workflows+),+commits AS (+ SELECT number, is_merge_queue, key,+ any(s0) AS c_s0, any(e0) AS c_e0,+ min(first_created) AS pushed_at,+ arrayFlatten(groupArray(reds)) AS reds, arrayFlatten(groupArray(runs)) AS runs,+ sum(futile_reruns) AS futile_reruns,+ any(gate_start) AS gate_start, any(gate_end) AS gate_end, max(has_gate) AS has_gate, max(gate_failed) AS gate_failed+ FROM workflow_spans+ GROUP BY number, is_merge_queue, key+),+per_pr AS (+ SELECT number, any(c_s0) AS p_s0, any(c_e0) AS p_e0,+ arraySort(p -> tuple(p.1, p.4), groupArrayIf(tuple(pushed_at, reds, runs, key), NOT is_merge_queue AND pushed_at <= c_e0)) AS pushes,+ groupArrayIf(tuple(gate_start, gate_end), is_merge_queue AND has_gate) AS gates,+ countIf(is_merge_queue AND has_gate AND gate_failed) AS kickouts,+ sumIf(futile_reruns, NOT is_merge_queue AND pushed_at <= c_e0) AS futile_reruns+ FROM commits+ GROUP BY number+),+clipped AS (+ -- Each commit's spans only count while it is the head: from its push until the next push.+ SELECT number, p_s0 AS s0, p_e0 AS e0, gates, kickouts, futile_reruns, pushes,+ arrayFlatten(arrayMap(k -> arrayMap(t -> tuple(+ greatest(t.1, pushes[k].1), least(t.2, if(k < length(pushes), pushes[k + 1].1, {_FAR})), t.3, t.4, k < length(pushes)),+ pushes[k].2), arrayEnumerate(pushes))) AS reds,+ arrayFlatten(arrayMap(k -> arrayMap(t -> tuple(+ greatest(t.1, pushes[k].1), least(t.2, if(k < length(pushes), pushes[k + 1].1, {_FAR}))),+ pushes[k].3), arrayEnumerate(pushes))) AS runs,+ if(length(pushes) > 0, pushes[length(pushes)].1, {_EPOCH}) AS last_push_at+ FROM per_pr+ WHERE p_e0 > p_s0+),+with_queue AS (+ -- The queue span runs from the first gate attempt after the last push to the merge.+ SELECT number, s0, e0, reds, runs, kickouts, futile_reruns, pushes, length(gates) > 0 AS queued,+ arrayConcat(gates, if(arrayExists(g -> g.1 >= last_push_at, gates),+ [tuple(arrayMin(arrayMap(g -> g.1, arrayFilter(g -> g.1 >= last_push_at, gates))), e0)], [])) AS queue_spans+ FROM clipped+),+points AS (+ SELECT number, reds, runs, queue_spans, kickouts, futile_reruns, pushes, queued,+ arraySort(arrayDistinct(arrayConcat([s0, e0], arrayFilter(p -> p > s0 AND p < e0, arrayConcat(+ arrayMap(t -> t.1, reds), arrayMap(t -> t.2, reds),+ arrayMap(t -> t.1, runs), arrayMap(t -> t.2, runs),+ arrayMap(t -> t.1, queue_spans), arrayMap(t -> t.2, queue_spans),+ arrayMap(p -> p.1, pushes)+ ))))) AS pts+ FROM with_queue+),+pieces AS (+ -- Piece tuple: (kind, seconds, index of the head push).+ SELECT number, kickouts, futile_reruns, queued, length(pushes) AS push_count, arrayMap(p -> p.1, pushes) AS pushes_at,+ arrayMap(k -> tuple(+ multiIf(+ arrayExists(q -> q.1 <= pts[k] AND pts[k] < q.2, queue_spans), 'merge_queue',+ NOT arrayExists(t -> t.1 <= pts[k] AND pts[k] < t.2, reds),+ if(arrayExists(t -> t.1 <= pts[k] AND pts[k] < t.2, runs), 'ci_running', 'other'),+ arrayAll(t -> t.3, arrayFilter(t -> t.1 <= pts[k] AND pts[k] < t.2, reds)), 'red_passed_on_rerun',+ arrayAll(t -> t.4, arrayFilter(t -> t.1 <= pts[k] AND pts[k] < t.2, reds)), 'red_master_broken',+ arrayFilter(t -> t.1 <= pts[k] AND pts[k] < t.2, reds)[1].5, 'red_fixed_by_push',+ 'red_not_provable'),+ ifNull(dateDiff('second', pts[k], pts[k + 1]), 0),+ arrayCount(p -> p.1 <= pts[k], pushes)),+ range(1, length(pts))) AS parts+ FROM points+),+counted AS (+ SELECT number, kickouts, futile_reruns, queued, push_count, pushes_at,+ arrayMap(kind -> arrayCount(i -> parts[i].1 = kind AND (i = 1 OR parts[i - 1].1 != kind), arrayEnumerate(parts)),+ ['red_passed_on_rerun', 'red_master_broken', 'red_not_provable', 'red_fixed_by_push']) AS red_counts,+ arrayMap(n -> 1.0 * arraySum(arrayMap(p -> if(p.1 = 'ci_running' AND p.3 = n, p.2, 0), parts)), range(1, push_count + 1)) AS ci_wait,+ toFloat(arraySum(arrayMap(p -> if(p.1 = 'merge_queue', p.2, 0), parts))) AS queue_seconds+ FROM pieces+)+SELECT+ b.repo_owner AS repo_owner,+ b.repo_name AS repo_name,+ b.number AS number,+ b.author AS author,+ b.author_avatar_url AS author_avatar_url,+ b.is_bot AS is_bot,+ b.ended_at AS merged_at,+ ifNull(c.push_count, 0) AS push_count,+ ifNull(c.red_counts[1], 0) AS flake_red_count,+ ifNull(c.red_counts[2], 0) AS master_red_count,+ ifNull(c.red_counts[3], 0) AS unknown_red_count,+ ifNull(c.red_counts[4], 0) AS own_red_count,+ ifNull(c.futile_reruns, 0) AS futile_rerun_count,+ ifNull(c.ci_wait, []) AS ci_wait_seconds,+ if(first_approval_at IS NULL, NULL, toFloat(greatest(dateDiff('second', b.ready_at, first_approval_at), 0))) AS first_approval_wait_seconds,+ if(first_approval_at IS NULL, NULL, arrayCount(t -> t > first_approval_at AND t <= b.ended_at, ifNull(c.pushes_at, []))) AS pushes_after_approval,+ if(ifNull(c.queued, 0), c.queue_seconds, NULL) AS queue_seconds,+ if(ifNull(c.queued, 0), c.kickouts, NULL) AS kickout_count,+ '{source_id}' AS source_id+FROM (+ SELECT *,+ -- The first approval after ready; an approval given while still a draft counts as approved at ready.+ if(NOT ready_observed, NULL,+ if(arrayExists(t -> t >= ready_at AND t <= ended_at, ifNull(approved_at, [])),+ arrayMin(arrayFilter(t -> t >= ready_at AND t <= ended_at, ifNull(approved_at, []))),+ if(arrayExists(t -> t < ready_at, ifNull(approved_at, [])), ready_at, NULL))) AS first_approval_at+ FROM bounds+) AS b+LEFT JOIN counted AS c ON c.number = b.number+"""+++def build_team_view(team: "Team") -> str | None:+ """The view body for a team: one SELECT per repository with runs, jobs and pull requests synced."""+ sources = [source for source in resolve_job_source_tables(team) if source.pull_requests]+ if not sources:+ return None+ # Each SELECT carries its own WITH, so each sits in its own subquery to keep the CTE names apart.+ return "\nUNION ALL\n".join(+ f"SELECT * FROM ({build_query(source_id=source.source_id, pull_requests_table=source.pull_requests, workflow_runs_table=source.workflow_runs, workflow_jobs_table=source.workflow_jobs, issue_events_table=source.issue_events, reviews_table=source.reviews)})"+ for source in sources+ if source.pull_requests+ )diff --git a/products/engineering_analytics/backend/tests/test_ci_views.py b/products/engineering_analytics/backend/tests/test_ci_views.pyindex 471f8d59c54d..66b783301d35 100644--- a/products/engineering_analytics/backend/tests/test_ci_views.py+++ b/products/engineering_analytics/backend/tests/test_ci_views.py@@ -4,17 +4,24 @@ from pathlib import Pathfrom typing import Anyfrom posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patchimport pandas as pd+from parameterized import parameterizedfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client import sync_execute+from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet, DataWarehouseSavedQueryfrom products.engineering_analytics.backend.facade.warehouse_views import get_expected_warehouse_viewsfrom products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME-from products.engineering_analytics.backend.logic.sources import WORKFLOW_JOBS_SCHEMA, WORKFLOW_RUNS_SCHEMA-from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs+from products.engineering_analytics.backend.logic.sources import (+ PULL_REQUESTS_SCHEMA,+ WORKFLOW_JOBS_SCHEMA,+ WORKFLOW_RUNS_SCHEMA,+)+from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs, pr_frictionfrom products.engineering_analytics.backend.logic.views.source_schema import (WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,@@ -26,7 +33,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import ()from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceTypeTEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.ci_views"GITHUB_SOURCE_PREFIX = "myprefix"@@ -339,7 +346,7 @@ class TestExpectedWarehouseViews(BaseTest):"""The facade must expose all three views together for a qualifying GitHub source, and nothingfor a team without one — so a consumer sees a coherent set, never a partial one."""- def _qualifying_source(self) -> ExternalDataSource:+ def _qualifying_source(self, *, with_pull_requests: bool = False) -> ExternalDataSource:source = ExternalDataSource.objects.create(team=self.team,source_id="gh",@@ -348,7 +355,10 @@ class TestExpectedWarehouseViews(BaseTest):source_type=ExternalDataSourceType.GITHUB,prefix=GITHUB_SOURCE_PREFIX,)- for schema_name, endpoint in ((WORKFLOW_RUNS_SCHEMA, "workflow_runs"), (WORKFLOW_JOBS_SCHEMA, "workflow_jobs")):+ endpoints = [(WORKFLOW_RUNS_SCHEMA, "workflow_runs"), (WORKFLOW_JOBS_SCHEMA, "workflow_jobs")]+ if with_pull_requests:+ endpoints.append((PULL_REQUESTS_SCHEMA, "pull_requests"))+ for schema_name, endpoint in endpoints:table = DataWarehouseTable.objects.create(team=self.team,name=f"{GITHUB_SOURCE_PREFIX}github_{endpoint}",@@ -369,3 +379,36 @@ class TestExpectedWarehouseViews(BaseTest):self._qualifying_source()names = {view.name for view in get_expected_warehouse_views(self.team)}assert names == {job_costs.VIEW_NAME, ci_job_history.VIEW_NAME, ci_failures.VIEW_NAME}++ @parameterized.expand(+ [+ ("flag_on", True, None, True),+ ("flag_off", False, "managed", False),+ # No answer from the flag service keeps what the team has, so an outage never drops the table.+ ("no_answer_keeps_the_view", None, "managed", True),+ ("no_answer_ignores_a_user_query_of_that_name", None, "user", False),+ ("no_answer_adds_no_view", None, None, False),+ ]+ )+ def test_friction_view_needs_the_pull_request_snapshot_and_the_flag(+ self, _name: str, flag: bool | None, existing_view: str | None, expected: bool+ ) -> None:+ self._qualifying_source(with_pull_requests=True)+ if existing_view:+ viewset = (+ DataWarehouseManagedViewSet.objects.create(+ team=self.team, kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS+ )+ if existing_view == "managed"+ else None+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name=pr_friction.VIEW_NAME,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ managed_viewset=viewset,+ )+ with patch("posthoganalytics.feature_enabled", return_value=flag):+ materialized = {view.name: view.materialized for view in get_expected_warehouse_views(self.team)}+ per_job = {job_costs.VIEW_NAME: False, ci_job_history.VIEW_NAME: False, ci_failures.VIEW_NAME: False}+ assert materialized == ({**per_job, pr_friction.VIEW_NAME: True} if expected else per_job)diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.pyindex 89521ada2ac1..4ffc543b46ad 100644--- a/products/engineering_analytics/backend/tests/test_delivery.py+++ b/products/engineering_analytics/backend/tests/test_delivery.py@@ -92,9 +92,10 @@ def _attempt(succeeded: bool | None = None,attempt: int = 1,jobs: tuple[str, ...] = (),+ run_id: int = 1,) -> RunAttempt:return RunAttempt(- run_id=1,+ run_id=run_id,workflow_name=workflow,head_sha=sha,attempt=attempt,@@ -157,6 +158,12 @@ class TestPRTimelineBuilder(SimpleTestCase):(Kind.APPROVED_NOT_ENQUEUED, 5, 6),],),+ (+ "same_second_runs_break_the_tie_by_run_id",+ _pr(3, [_attempt("a", 0, None, run_id=2), _attempt("a", 0, 1, run_id=1)]),+ [],+ [(Kind.CI_RUNNING, 0, 3)],+ ),("cancelled_rerun_is_not_a_pass",_pr(5, [_attempt("a", 0, 1, failed=True), _attempt("a", 3, 4, attempt=2, succeeded=False)]),diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.pyindex 73d98e65c2e5..fc052a37ba28 100644--- a/products/engineering_analytics/backend/tests/test_logic_sources.py+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py@@ -477,7 +477,7 @@ class TestMultiRepoGitHubResolution(BaseTest):def test_cost_pairs_include_every_repo_in_a_source(self) -> None:# The cost view unions (jobs, runs) across repos. A multi-repo source must contribute one# pair per fully-synced repo — collapsing it to one repo silently under-counts the view.- self._multi_repo_source(+ source = self._multi_repo_source(prefix="cost",legacy_repository="PostHog/posthog",repos={@@ -494,11 +494,13 @@ class TestMultiRepoGitHubResolution(BaseTest):workflow_jobs="costgithub_posthog_posthog_workflow_jobs",workflow_runs="costgithub_posthog_posthog_workflow_runs",pull_requests=None,+ source_id=str(source.id),),JobSourceTables(workflow_jobs="costgithub_posthog_posthog_com_workflow_jobs",workflow_runs="costgithub_posthog_posthog_com_workflow_runs",pull_requests=None,+ source_id=str(source.id),),}diff --git a/products/engineering_analytics/backend/tests/test_pr_friction.py b/products/engineering_analytics/backend/tests/test_pr_friction.pynew file mode 100644index 000000000000..78f4a0545cfc--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_pr_friction.py@@ -0,0 +1,265 @@+from collections import Counter, defaultdict+from datetime import UTC, datetime, timedelta+from typing import Any++from posthog.hogql.query import execute_hogql_query++from products.engineering_analytics.backend.facade.contracts import (+ DeliveryScopeKind,+ PRTimelineSegmentKind as Kind,+)+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.pull_request_timelines import query_pull_request_timelines+from products.engineering_analytics.backend.logic.views import pr_friction+from products.engineering_analytics.backend.logic.views.source_schema import (+ ISSUE_EVENTS_COLUMNS,+ PULL_REQUESTS_COLUMNS,+ REVIEWS_COLUMNS,+ WORKFLOW_JOBS_COLUMNS,+ WORKFLOW_RUNS_COLUMNS,+)+from products.engineering_analytics.backend.tests._github_fixtures import _issue_event_row, _pr_row, _run_row+from products.engineering_analytics.backend.tests._logic_helpers import (+ _ago,+ _ago_offset_with_duration,+ _job_row,+ _WarehouseMixin,+)++_DAY = 3+_GATE_ACTOR = "trunk-io[bot]"+++def _span(offset_minutes: int, duration_minutes: int) -> tuple[str, str]:+ return _ago_offset_with_duration(_DAY, offset_minutes * 60, duration_minutes * 60)+++def _at(offset_minutes: int) -> str:+ return _span(offset_minutes, 0)[0]+++def _run(+ run_id: int,+ sha: str,+ conclusion: str | None,+ offset: int,+ duration: int,+ *,+ created_offset: int | None = None,+ **kwargs: Any,+) -> dict[str, Any]:+ start, end = _span(offset, duration)+ status = "completed" if conclusion else "in_progress"+ row = _run_row(run_id, kwargs.pop("name", "CI"), sha, status, conclusion, start, end, **kwargs)+ # The runs snapshot keeps the newest attempt's start, but the run was created with its first attempt.+ if created_offset is not None:+ row["created_at"] = _at(created_offset)+ return row+++def _job(job_id: int, run_id: int, name: str, conclusion: str, offset: int, duration: int, **kwargs: Any) -> dict:+ start, end = _span(offset, duration)+ return _job_row(job_id, run_id, name, conclusion, started=start, completed=end, **kwargs)+++def _gate(run_id: int, pr: int, attempt: str, conclusion: str, offset: int, duration: int) -> dict[str, Any]:+ return _run(+ run_id,+ f"queue{run_id}",+ conclusion,+ offset,+ duration,+ pr_number=9000 + run_id,+ head_branch=f"trunk-merge/pr-{pr}/{attempt}",+ actor=_GATE_ACTOR,+ )+++def _merged(number: int, merged_offset: int, login: str = "alice") -> dict[str, Any]:+ return _pr_row(number, login, "closed", 0, _ago(_DAY + 1), merged_at=_at(merged_offset), default_branch="master")+++class TestPRFrictionView(_WarehouseMixin):+ def _seed(self) -> None:+ self._create_table(+ "github_pull_requests",+ PULL_REQUESTS_COLUMNS,+ [+ _merged(31, 360),+ _merged(32, 600),+ _merged(33, 180),+ _merged(34, 151),+ _merged(35, 60),+ _merged(36, 120),+ _merged(37, 360),+ _merged(38, 60, login="dependabot[bot]"),+ _pr_row(39, "alice", "closed", 0, _ago(70), merged_at=_at(60), default_branch="master"),+ ],+ )+ self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [+ # 31: a flaky failure that one re-run fixed.+ _run(3101, "sha31", "success", 30, 10, pr_number=31, run_attempt=2, created_offset=0),+ # 32: master is broken; two re-runs fail again, then a push lands after master recovers.+ _run(3201, "sha32", "failure", 40, 10, pr_number=32, run_attempt=3, created_offset=0),+ _run(3202, "sha32b", "success", 120, 10, pr_number=32),+ _run(3901, "master1", "failure", 0, 5, head_branch="master"),+ # 33: the author's own failure, fixed by the next push.+ _run(3301, "sha33a", "failure", 0, 15, pr_number=33),+ _run(3302, "sha33b", "success", 60, 20, pr_number=33),+ # 34: kicked out of the merge queue once, then merged on the second attempt.+ _run(3401, "sha34", "success", 0, 15, pr_number=34),+ _gate(3402, 34, "first", "failure", 60, 30),+ _gate(3403, 34, "second", "success", 120, 30),+ # 35: two runs of one workflow start in the same second; the unfinished one has the higher id.+ _run(3501, "sha35", "success", 0, 5, pr_number=35, name="Lint"),+ _run(3502, "sha35", None, 0, 0, pr_number=35, name="Lint"),+ # 37: approved three hours after ready, then pushed again.+ _run(3701, "sha37a", "success", 0, 10, pr_number=37),+ _run(3702, "sha37b", "success", 300, 10, pr_number=37),+ _run(3801, "sha38", "success", 0, 10, pr_number=38),+ ],+ )+ self._create_table(+ "github_workflow_jobs",+ WORKFLOW_JOBS_COLUMNS,+ [+ _job(1, 3101, "test", "failure", 0, 10),+ _job(2, 3101, "test", "success", 30, 10, run_attempt=2),+ _job(3, 3201, "test (1/2)", "failure", 0, 10),+ _job(4, 3201, "test (1/2)", "failure", 20, 10, run_attempt=2),+ _job(5, 3201, "test (1/2)", "failure", 40, 10, run_attempt=3),+ _job(6, 3901, "test (2/2)", "failure", 0, 5, head_branch="master"),+ ],+ )+ self._create_table(+ "github_issue_events",+ ISSUE_EVENTS_COLUMNS,+ [+ _issue_event_row(1, "ready_for_review", 37, _at(60)),+ # 39 has events, just no ready event, so its ready time reads as NULL rather than missing.+ _issue_event_row(2, "review_requested", 39, _at(30)),+ ],+ )+ self._create_table(+ "github_reviews",+ REVIEWS_COLUMNS,+ [+ {+ "id": 1,+ "pr_number": 37,+ "user": '{"login": "reviewer"}',+ "state": "APPROVED",+ "commit_id": "",+ "submitted_at": _at(240),+ },+ # 39: opened before the event scan floor, so a missing ready event says nothing about drafts.+ {+ "id": 2,+ "pr_number": 39,+ "user": '{"login": "reviewer"}',+ "state": "APPROVED",+ "commit_id": "",+ "submitted_at": _at(30),+ },+ ],+ )++ def _view_rows(self) -> dict[int, dict[str, Any]]:+ query = pr_friction.build_team_view(self.team)+ assert query is not None+ response = execute_hogql_query(+ query=f"SELECT * FROM ({query})", team=self.team, query_type="engineering_analytics.test"+ )+ assert response.columns == list(pr_friction.FIELDS)+ return {row[2]: dict(zip(response.columns, row)) for row in response.results}++ def test_view_matches_the_timeline_replay(self) -> None:+ self._seed()+ rows = self._view_rows()+ timelines = query_pull_request_timelines(+ curated=CuratedGitHubSource.for_team(self.team),+ scope=DeliveryScope(kind=DeliveryScopeKind.AUTHOR, author="alice"),+ date_from=datetime.now(tz=UTC) - pr_friction.FRICTION_WINDOW,+ date_to=None,+ )++ red_columns = {+ Kind.RED_PASSED_ON_RERUN: "flake_red_count",+ Kind.RED_MASTER_BROKEN: "master_red_count",+ Kind.RED_NOT_PROVABLE: "unknown_red_count",+ Kind.RED_FIXED_BY_PUSH: "own_red_count",+ }+ timeline_figures = {}+ for item in timelines.items:+ kinds = Counter(segment.kind for segment in item.segments)+ seconds: defaultdict[Kind, float] = defaultdict(float)+ for segment in item.segments:+ seconds[segment.kind] += (segment.ended_at - segment.started_at).total_seconds()+ timeline_figures[item.number] = {+ **{column: kinds[kind] for kind, column in red_columns.items()},+ "ci_running": seconds[Kind.CI_RUNNING],+ "merge_queue": seconds[Kind.MERGE_QUEUE],+ }+ view_figures = {+ number: {+ **{column: row[column] for column in red_columns.values()},+ "ci_running": sum(row["ci_wait_seconds"]),+ "merge_queue": row["queue_seconds"] or 0,+ }+ for number, row in rows.items()+ if number in timeline_figures+ }++ assert set(timeline_figures) == {31, 32, 33, 34, 35, 36, 37, 39}+ assert view_figures == timeline_figures++ def test_view_counts_what_the_author_went_through(self) -> None:+ self._seed()+ rows = self._view_rows()++ picked = {+ number: {+ column: row[column]+ for column in (+ "is_bot",+ "push_count",+ "flake_red_count",+ "master_red_count",+ "own_red_count",+ "futile_rerun_count",+ "first_approval_wait_seconds",+ "pushes_after_approval",+ "kickout_count",+ )+ }+ for number, row in rows.items()+ }+ base = {+ "is_bot": False,+ "push_count": 1,+ "flake_red_count": 0,+ "master_red_count": 0,+ "own_red_count": 0,+ "futile_rerun_count": 0,+ "first_approval_wait_seconds": None,+ "pushes_after_approval": None,+ "kickout_count": None,+ }+ assert picked == {+ 31: {**base, "flake_red_count": 1},+ 32: {**base, "push_count": 2, "master_red_count": 3, "futile_rerun_count": 2},+ 33: {**base, "push_count": 2, "own_red_count": 1},+ 34: {**base, "kickout_count": 1},+ 35: base,+ 36: {**base, "push_count": 0},+ 37: {**base, "push_count": 2, "first_approval_wait_seconds": 3 * 3600.0, "pushes_after_approval": 1},+ 38: {**base, "is_bot": True},+ 39: {**base, "push_count": 0},+ }+ assert self._github_source is not None+ assert {row["source_id"] for row in rows.values()} == {str(self._github_source.id)}+ assert rows[35]["ci_wait_seconds"] == [timedelta(hours=1).total_seconds()]diff --git a/products/engineering_analytics/backend/warehouse_view_provider.py b/products/engineering_analytics/backend/warehouse_view_provider.pyindex 6ac25b2721df..d3f023184dfd 100644--- a/products/engineering_analytics/backend/warehouse_view_provider.py+++ b/products/engineering_analytics/backend/warehouse_view_provider.py@@ -13,10 +13,11 @@ from products.engineering_analytics.backend.facade.warehouse_views import get_exdef get_provided_views(team: Team) -> list[ProvidedView]:"""The engineering-analytics warehouse views, adapted for data_modeling's managed-viewset sync.- Non-materialized: the view is computed at query time so a Depot rate change propagates- immediately and it never joins the materialization schedule / managed DAG.+ Each view says whether it is materialized. The per-job views are not: they are computed at query+ time so a Depot rate change propagates immediately and they never join the materialization+ schedule / managed DAG."""return [- ProvidedView(name=view.name, query=view.query, fields=view.fields, materialized=False)+ ProvidedView(name=view.name, query=view.query, fields=view.fields, materialized=view.materialized)for view in get_expected_warehouse_views(team)]