Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(eng-analytics): define a push once (#103808)

Raúl Negrón-Otero65cdb5eb4df7
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 9572b7c634c5..11f63ab4d669 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -155,6 +155,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **Warehouse columns are strings + Nullable JSON; the builders parse and `ifNull`-guard.** Timestamps parse via `parseDateTimeBestEffort`; Nullable columns unwrap before any array function (ClickHouse rejects an Array inside a Nullable). `source_schema.py` mirrors the real landed types so seed and tests exercise the real path; violating this 500'd every endpoint on real data while idealized fixtures stayed green.
- **The warehouse views are managed data, not code registration.** "No global HogQL views" locks out `Database.create_for` (core importing the product, every team's per-query hot path). A per-team `DataWarehouseSavedQuery`, synced only for qualifying teams, reopens nothing: it exists so cost and CI history are queryable by insights, subscriptions, and `execute-sql`.
- **Workflow pass rate uses verdicts, not every completed run.** `success` is a pass. `failure`, `timed_out`, `startup_failure`, and `stale` are decisive failures. Skipped, cancelled, neutral, action-required, unsettled, and unknown outcomes reached no pass-or-fail verdict, so they stay in run volume but not the rate. The backend query layer owns this classification; frontend summaries over raw run rows mirror it in `lifecycle.ts`.
+- **A push is one authored head commit that reached CI.** All runs associated with the pull request for the same head SHA form one push, including when every workflow was skipped. Merge-queue gate runs do not count because the queue created their rebased head SHA. The push time is the earliest run creation time, falling back to the run start when creation time is missing. Delivery summaries, pull request lists, and timelines use this definition.
- **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.
diff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.py
index ac2688533de0..8a5fed6f6734 100644
--- a/products/engineering_analytics/backend/logic/pr_timeline.py
+++ b/products/engineering_analytics/backend/logic/pr_timeline.py
@@ -51,8 +51,8 @@ class RunAttempt:
workflow_name: str
head_sha: str
attempt: int
- # When the run was created, which is when its commit arrived. A queued run starts later.
- pushed_at: datetime
+ # When the workflow run was created. A queued run starts later.
+ queued_at: datetime
started_at: datetime
# None while the attempt is still running.
completed_at: datetime | None
@@ -63,6 +63,12 @@ class RunAttempt:
failed_jobs: tuple[str, ...]
+@frozen
+class Push:
+ head_sha: str
+ pushed_at: datetime
+
+
@frozen
class ReviewVerdict:
reviewer: str
@@ -101,6 +107,7 @@ class PRTimelineInput:
is_open: bool
is_merged: bool
is_draft: bool
+ pushes: list[Push]
attempts: list[RunAttempt]
gate_attempts: list[GateAttempt]
# None when the reviews table is not synced.
@@ -127,7 +134,7 @@ class PRTimelineBuilder:
def __init__(self, pr: PRTimelineInput, master_failures: MasterFailureIndex) -> None:
self._pr = pr
self._master_failures = master_failures
- self._pushes = self._group_pushes(pr.attempts)
+ self._pushes = self._group_pushes(pr.pushes, pr.attempts)
self._push_times = [push.pushed_at for push in self._pushes]
self._verdicts = sorted(
(review for review in pr.reviews or [] if review.state in (APPROVED_STATE, CHANGES_REQUESTED_STATE)),
@@ -137,18 +144,20 @@ class PRTimelineBuilder:
self._queue_from, self._queue_until = queue_span.started_at, queue_span.ended_at
@staticmethod
- def _group_pushes(attempts: list[RunAttempt]) -> list[_Push]:
+ def _group_pushes(pushes: list[Push], attempts: list[RunAttempt]) -> list[_Push]:
by_sha: dict[str, list[RunAttempt]] = defaultdict(list)
for attempt in attempts:
by_sha[attempt.head_sha].append(attempt)
- pushes = []
- for head_sha, sha_attempts in by_sha.items():
+ grouped = []
+ 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)):
by_workflow[attempt.workflow_name].append(attempt)
- pushed_at = min(attempt.pushed_at for attempt in sha_attempts)
- pushes.append(_Push(head_sha=head_sha, pushed_at=pushed_at, attempts_by_workflow=dict(by_workflow)))
- return sorted(pushes, key=lambda push: push.pushed_at)
+ 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)
def _queue_span(self) -> _QueueSpan:
"""The continuous queue stretch: from the first gate attempt after the last push to the merge
@@ -190,7 +199,7 @@ class PRTimelineBuilder:
def _change_points(self) -> list[datetime]:
points: list[datetime] = [*self._push_times]
for attempt in self._pr.attempts:
- points.append(attempt.pushed_at)
+ points.append(attempt.queued_at)
points.append(attempt.started_at)
if attempt.completed_at is not None:
points.append(attempt.completed_at)
@@ -240,9 +249,8 @@ class PRTimelineBuilder:
for attempts in push.attempts_by_workflow.values():
started = [attempt for attempt in attempts if attempt.started_at <= at]
if not started:
- # Only a first attempt proves a queue wait: every attempt of a run carries the run's
- # creation time, so a re-run's would stretch back over the stretch it was red.
- if any(attempt.attempt == 1 and attempt.pushed_at <= at for attempt in attempts):
+ # Only a first attempt proves a queue wait. A re-run starts after the push's first CI.
+ if any(attempt.attempt == 1 and attempt.queued_at <= at for attempt in attempts):
running = True
continue
latest = started[-1]
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 0041d137e378..c637fa05cedc 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -52,6 +52,8 @@ from products.engineering_analytics.backend.logic.views import (
if TYPE_CHECKING:
from products.access_control.backend.facade.user_access_control import UserAccessControl
+_QUERY_PAGE_SIZE = 5000
+
@dataclass(frozen=True, kw_only=True)
class _IssueEventsWindow:
@@ -70,6 +72,17 @@ class DeploySources:
_READY_BY_PR_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"
+_PUSH_RUN_PREDICATE = "pr_number > 0 AND NOT is_merge_queue"
+
+
+def push_rows_select(*, runs_source: str, run_filter: str) -> str:
+ """One row per authored commit that reached CI. Skipped workflows still prove the push."""
+ return f"""
+ SELECT pr_number, head_sha, min(coalesce(created_at, run_started_at)) AS pushed_at
+ FROM {runs_source} AS r
+ WHERE {_PUSH_RUN_PREDICATE} AND ({run_filter})
+ GROUP BY pr_number, head_sha
+ """
@dataclass(frozen=True, kw_only=True)
@@ -463,7 +476,7 @@ class CuratedGitHubSource:
count(DISTINCT head_sha) AS pushes,
countIf(run_attempt > 1) AS rerun_cycles
FROM runs AS r
- WHERE pr_number > 0 AND NOT is_merge_queue
+ WHERE {_PUSH_RUN_PREDICATE}
AND pr_number IN (SELECT number FROM pr_scope)
GROUP BY repo_owner, repo_name, pr_number
)
@@ -488,6 +501,22 @@ class CuratedGitHubSource:
"""Prefix ``select`` with the given CTEs and fill its ``__PR_SOURCE__`` placeholder with the PR source."""
return f"WITH {', '.join(ctes)} {select}".replace("__PR_SOURCE__", self.pr_source())
+ def run_paged(self, sql: str, *, query_type: str, placeholders: dict[str, ast.Expr]) -> list[tuple]:
+ """Read every row of a query with a stable ORDER BY, without the per-query result cap."""
+ rows: list[tuple] = []
+ offset = 0
+ while True:
+ response = self.run(
+ f"{sql}\nLIMIT {_QUERY_PAGE_SIZE} OFFSET {offset}",
+ query_type=query_type,
+ placeholders=placeholders,
+ )
+ page = list(response.results or [])
+ rows.extend(page)
+ if len(page) < _QUERY_PAGE_SIZE:
+ return rows
+ offset += len(page)
+
def run(
self,
sql: str,
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
index 15d6bd0b9673..47fa0c063c7a 100644
--- a/products/engineering_analytics/backend/logic/queries/delivery_summary.py
+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
@@ -26,7 +26,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.logic.cost import PRCostAggregate
from products.engineering_analytics.backend.logic.delivery_scope import CI_LOOKBACK, DeliveryScope, SummaryScope
from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, GateAttempt, gate_attempts_sql
-from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, push_rows_select
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
DECISIVE_FAILURE_CONCLUSIONS_SQL,
UNPAGED_SCAN_LIMIT,
@@ -70,16 +70,9 @@ _APPROVALS_SELECT = f"""
LIMIT {UNPAGED_SCAN_LIMIT}
"""
-# A push is a distinct head commit that triggered CI; gate runs are the queue's rebases, not pushes.
-# The run's creation time is when the commit arrived: a queued run starts later.
_PUSHES_SELECT = f"""
SELECT pr_number, groupArray(pushed_at) AS pushed_at
- FROM (
- SELECT pr_number, head_sha, min(created_at) AS pushed_at
- FROM __RUNS_SOURCE__ AS r
- WHERE pr_number IN {{pr_numbers}} AND NOT is_merge_queue AND run_started_at >= {{run_from}}
- GROUP BY pr_number, head_sha
- )
+ FROM (__PUSH_ROWS__)
GROUP BY pr_number
LIMIT {UNPAGED_SCAN_LIMIT}
"""
@@ -410,8 +403,12 @@ def _query_merged_facts(
approvals = _query_approvals(curated, numbers)
runs_source = curated.run_source(started_floor=True)
+ push_rows = push_rows_select(
+ runs_source=runs_source,
+ run_filter="pr_number IN {pr_numbers} AND run_started_at >= {run_from}",
+ )
pushes_response = curated.run(
- _PUSHES_SELECT.replace("__RUNS_SOURCE__", runs_source),
+ _PUSHES_SELECT.replace("__PUSH_ROWS__", push_rows),
query_type="engineering_analytics.delivery_summary_pushes",
placeholders={
"pr_numbers": numbers,
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
index ae5f93748028..81efa2a36a55 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
@@ -28,10 +28,11 @@ from products.engineering_analytics.backend.logic.pr_timeline import (
MasterFailureIndex,
PRTimelineBuilder,
PRTimelineInput,
+ Push,
ReviewVerdict,
RunAttempt,
)
-from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, push_rows_select
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
DECISIVE_FAILURE_CONCLUSIONS,
DECISIVE_FAILURE_CONCLUSIONS_SQL,
@@ -187,6 +188,7 @@ class PullRequestTimelinesQuery:
ready_at = self._query_ready_at(pr_numbers, run_from)
reviews = self._query_reviews(pr_numbers)
attempts = self._query_run_attempts(pr_numbers, run_from)
+ pushes = self._query_pushes(pr_numbers, run_from)
gates = self._query_gate_attempts(pr_numbers)
default_branch = next((row[9] for row in prs if row[9]), "")
master_failures = self._query_master_failures(attempts, default_branch, run_from)
@@ -222,7 +224,11 @@ class PullRequestTimelinesQuery:
ready = None
# No ready event means never drafted, or issue events not synced.
started_at = max(ready or created_at, run_from)
- pr_attempts = [attempt for attempt in attempts.get(number, []) if attempt.started_at <= ended_at]
+ pr_attempts = [
+ attempt
+ for attempt in attempts.get(number, [])
+ if attempt.started_at <= ended_at or (attempt.attempt == 1 and attempt.queued_at <= ended_at)
+ ]
builder = PRTimelineBuilder(
PRTimelineInput(
started_at=started_at,
@@ -230,6 +236,7 @@ class PullRequestTimelinesQuery:
is_open=is_open,
is_merged=merged_at is not None,
is_draft=bool(is_draft) and is_open,
+ pushes=[push for push in pushes.get(number, []) if push.pushed_at <= ended_at],
attempts=pr_attempts,
gate_attempts=[gate for gate in gates.get(number, []) if gate.started_at <= ended_at],
reviews=reviews.get(number, []) if reviews is not None else None,
@@ -347,10 +354,10 @@ class PullRequestTimelinesQuery:
started_at,
updated_at,
attempt,
- created,
+ created_at,
) in runs:
run_attempts = job_attempts.get(int(run_id), [])
- pushed_at = created or started_at
+ queued_at = created_at or started_at
completed = status == "completed"
run_failed = completed and conclusion in DECISIVE_FAILURE_CONCLUSIONS
newest_attempt = int(attempt or 1)
@@ -371,7 +378,7 @@ class PullRequestTimelinesQuery:
workflow_name=workflow_name or "",
head_sha=head_sha or "",
attempt=job_attempt.attempt,
- pushed_at=pushed_at,
+ queued_at=queued_at,
started_at=job_attempt.started_at,
completed_at=completed_at,
failed=failed,
@@ -389,7 +396,7 @@ class PullRequestTimelinesQuery:
workflow_name=workflow_name or "",
head_sha=head_sha or "",
attempt=newest_attempt,
- pushed_at=pushed_at,
+ queued_at=queued_at,
started_at=started_at,
completed_at=updated_at if completed else None,
failed=run_failed,
@@ -399,6 +406,22 @@ class PullRequestTimelinesQuery:
)
return attempts
+ def _query_pushes(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[Push]]:
+ sql = push_rows_select(
+ runs_source=self._curated.run_source(started_floor=True),
+ run_filter="pr_number IN {pr_numbers} AND run_started_at >= {run_from}",
+ )
+ rows = self._curated.run_paged(
+ sql + "\nORDER BY pr_number, head_sha",
+ query_type="engineering_analytics.pull_request_timelines_pushes",
+ placeholders=self._runs_placeholders(pr_numbers, run_from),
+ )
+ pushes: dict[int, list[Push]] = defaultdict(list)
+ for number, head_sha, pushed_at in rows:
+ if pushed_at is not None:
+ pushes[int(number)].append(Push(head_sha=head_sha or "", pushed_at=pushed_at))
+ return pushes
+
def _query_gate_attempts(self, pr_numbers: list[int]) -> dict[int, list[GateAttempt]]:
gate_from = self._date_from - GATE_RUN_LOOKBACK
gates_response = self._curated.run(
diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.py
index 894a86f5757e..5f675607af2a 100644
--- a/products/engineering_analytics/backend/tests/test_delivery.py
+++ b/products/engineering_analytics/backend/tests/test_delivery.py
@@ -1,3 +1,4 @@
+from collections import defaultdict
from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
@@ -21,6 +22,7 @@ from products.engineering_analytics.backend.logic.pr_timeline import (
MasterFailureIndex,
PRTimelineBuilder,
PRTimelineInput,
+ Push,
ReviewVerdict,
RunAttempt,
)
@@ -44,6 +46,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
REVIEWS_COLUMNS,
TEAM_MEMBERS_COLUMNS,
+ WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
@@ -58,6 +61,7 @@ from products.engineering_analytics.backend.tests._logic_helpers import (
_ago,
_ago_offset_with_duration,
_dt,
+ _job_row,
_WarehouseMixin,
)
@@ -73,18 +77,19 @@ def _attempt(
start: float,
end: float | None,
*,
+ queued: float | None = None,
+ workflow: str = "CI",
failed: bool = False,
succeeded: bool | None = None,
attempt: int = 1,
jobs: tuple[str, ...] = (),
- pushed: float | None = None,
) -> RunAttempt:
return RunAttempt(
run_id=1,
- workflow_name="CI",
+ workflow_name=workflow,
head_sha=sha,
attempt=attempt,
- pushed_at=_at(start if pushed is None else pushed),
+ queued_at=_at(start if queued is None else queued),
started_at=_at(start),
completed_at=_at(end) if end is not None else None,
failed=failed,
@@ -103,13 +108,20 @@ def _pr(
is_merged: bool | None = None,
is_draft: bool = False,
trunk_out: bool = False,
+ pushes: list[Push] | None = None,
) -> PRTimelineInput:
+ pushes_by_sha: dict[str, list[datetime]] = defaultdict(list)
+ for attempt in attempts:
+ pushes_by_sha[attempt.head_sha].append(attempt.started_at)
return PRTimelineInput(
started_at=_at(0),
ended_at=_at(end),
is_open=is_open,
is_merged=not is_open if is_merged is None else is_merged,
is_draft=is_draft,
+ pushes=pushes
+ if pushes is not None
+ else [Push(head_sha=sha, pushed_at=min(times)) for sha, times in pushes_by_sha.items()],
attempts=attempts,
gate_attempts=gates or [],
reviews=reviews,
@@ -151,15 +163,31 @@ class TestPRTimelineBuilder(SimpleTestCase):
"queued_check_counts_as_ci",
_pr(
4,
- [_attempt("a", 1, 2, pushed=0)],
+ [_attempt("a", 1, 2, queued=0)],
reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(0))],
+ pushes=[Push(head_sha="a", pushed_at=_at(0))],
),
[],
[(Kind.CI_RUNNING, 0, 2), (Kind.APPROVED_NOT_ENQUEUED, 2, 4)],
),
+ (
+ "later_workflow_does_not_backfill_queue_time",
+ _pr(
+ 5,
+ [_attempt("a", 0, 1), _attempt("a", 3, 4, queued=2, workflow="Deploy")],
+ reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(0))],
+ ),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.APPROVED_NOT_ENQUEUED, 1, 2),
+ (Kind.CI_RUNNING, 2, 4),
+ (Kind.APPROVED_NOT_ENQUEUED, 4, 5),
+ ],
+ ),
(
"rerun_does_not_backfill_queue_time",
- _pr(5, [_attempt("a", 0, 1, failed=True), _attempt("a", 3, 4, attempt=2, pushed=0)]),
+ _pr(5, [_attempt("a", 0, 1, failed=True), _attempt("a", 3, 4, attempt=2)]),
[],
[
(Kind.CI_RUNNING, 0, 1),
@@ -512,6 +540,7 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
red_start, red_end = _ago_offset_with_duration(2, 0, 3600)
fix_start, fix_end = _ago_offset_with_duration(2, 8 * 3600, 3600)
gate_start, gate_end = _ago_offset_with_duration(2, 20 * 3600, 3600)
+ skipped_start, skipped_end = _ago_offset_with_duration(2, 12 * 3600, 60)
post_merge_probe_start, post_merge_probe_end = _ago_offset_with_duration(1, 3600, 3600)
old_gate_start, old_gate_end = _ago_offset_with_duration(20, 0, 3600)
self._create_table(
@@ -520,6 +549,8 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
[
_run_row(3001, "CI", "sha21a", "completed", "failure", red_start, red_end, pr_number=21),
_run_row(3002, "CI", "sha21b", "completed", "success", fix_start, fix_end, pr_number=21),
+ # A skipped workflow still proves the authored commit reached CI, so it is a push.
+ _run_row(3007, "CI", "sha21c", "completed", "skipped", skipped_start, skipped_end, pr_number=21),
_run_row(
3003,
"CI",
@@ -581,7 +612,7 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
)
assert summary.median_ready_to_merge_seconds.scope == 86400
assert summary.median_ready_to_merge_seconds.repo == (86400 + 3 * 86400) / 2
- assert summary.pushes_after_approval_per_merged_pr.scope == 1
+ assert summary.pushes_after_approval_per_merged_pr.scope == 2
assert summary.merge_queue_attempts_per_merged_pr.scope == 1
assert summary.failed_merge_queue_share.scope == 0
overview = query_merge_queue_overview(
@@ -592,7 +623,7 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
)
assert overview.avg_attempts_per_merge == summary.merge_queue_attempts_per_merged_pr.scope
assert overview.failed_gate_merge_share == summary.failed_merge_queue_share.scope
- assert summary.push_count == 2
+ assert summary.push_count == 3
assert summary.cost_per_merged_pr_usd.scope is None
assert summary.lead_time.deploy_data_available is False
@@ -623,6 +654,7 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
assert [(push.head_sha, push.pushed_at) for push in merged.pushes] == [
("sha21a", _dt(_ago_offset_with_duration(2, 0, 3600)[0])),
("sha21b", _dt(_ago_offset_with_duration(2, 8 * 3600, 3600)[0])),
+ ("sha21c", _dt(_ago_offset_with_duration(2, 12 * 3600, 60)[0])),
]
assert merged.segments[-1].ended_at == merged.merged_at
assert merged.started_at == _dt(_ago(2))
@@ -655,6 +687,43 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
assert reopened.started_at == _dt(_ago(4))
assert reopened.segments != []
+ @parameterized.expand([(1, Kind.CI_RUNNING), (2, Kind.RED_NOT_PROVABLE)])
+ def test_only_a_first_attempt_queued_before_close_stays_in_the_timeline(
+ self, attempt: int, expected_kind: Kind
+ ) -> None:
+ closed_at = _ago(2)
+ queued_at = _ago_offset_with_duration(3, 86340, 0)[0]
+ started_at, completed_at = _ago_offset_with_duration(2, 60, 60)
+ run = _run_row(3101, "CI", "sha31", "completed", "success", started_at, completed_at, pr_number=31)
+ run["created_at"] = queued_at
+ run["run_attempt"] = attempt
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(31, "alice", "closed", 0, _ago(4), closed_at=closed_at)],
+ )
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [run])
+ failure_end = _ago_offset_with_duration(3, 86370, 0)[0]
+ if attempt == 2:
+ self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [_job_row(31001, 3101, "Tests", "failure", started=queued_at, completed=failure_end)],
+ )
+ curated = CuratedGitHubSource.for_team(self.team)
+ scope = DeliveryScope(
+ kind=DeliveryScopeKind.PULL_REQUEST, pr_number=31, repo_owner="PostHog", repo_name="posthog"
+ )
+
+ timelines = query_pull_request_timelines(
+ curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None
+ )
+
+ closed = next(item for item in timelines.items if item.number == 31)
+ assert closed.segments[-1].kind == expected_kind
+ assert closed.segments[-1].started_at == _dt(queued_at if attempt == 1 else failure_end)
+ assert closed.segments[-1].ended_at == _dt(closed_at)
+
def test_an_earlier_ready_event_still_wins_when_the_latest_is_after_the_close(self) -> None:
# PR 33 went ready, back to draft, then ready again; the events and pull-requests tables sync
# apart, so its last ready event lands after its own row's close. Picking the unbounded latest