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(engineering-analytics): cost CI from Depot's billed clock, skip re-run copies (#90752)

Julian Bezbc652a18d465
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 3146d1e84d90..12f22a7e7b60 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -101,14 +101,19 @@ They are non-materialized: the rendered SQL is persisted per team and re-synced
#### `engineering_analytics_job_costs`
- Grain: one row per job attempt (a retry appears once per attempt; correct for cost). Jobs whose run row is missing keep NULL attribution rather than being dropped.
-- NULL cost is disambiguated by `provider` (non-billable: github-hosted, non-Linux, unclassifiable) vs `completed_at` (unsettled). A queued job is never shown as `$0.00`.
+- Joins jobs to runs on `run_id` alone, never `(run_id, run_attempt)` — same key and same reason as `ci_job_history`: the runs snapshot keeps only the newest attempt's row, so attempt equality blanks attribution for every earlier-attempt job, which after a partial re-run is exactly the population that executed. Attribution is attempt-invariant.
+- NULL cost is disambiguated by `provider` (non-billable: github-hosted, non-Linux, unclassifiable), `completed_at` (unsettled), or `is_rerun_copy` (never executed). A queued job is never shown as `$0.00`.
+- `is_rerun_copy` marks the rows GitHub re-lists but never ran (see §6). They are kept, not dropped — the grain and the row count stay identical to `ci_job_history` — but carry no `billable_seconds` / `estimated_cost_usd`.
+- Cost runs off Depot's billed clock, not `duration_seconds` (§6). `billable_seconds` is that clock; `duration_seconds` stays the full wall-clock GitHub reports.
- Cost is defined once, in `logic/cost.py`, rendered to HogQL; a ClickHouse-backed parity test asserts the view equals the Python model. The endpoint cost queries read the same rendered SELECT (via `_curated.job_cost_source()`), so there is no second cost path to drift.
- `is_merge_queue` splits merge-queue gate spend from the rest without anyone re-deriving what a gate branch is. Both this view and `ci_job_history` carry it, so neither answers "what does the queue cost" by pattern-matching a branch name.
+- **The view carries no scan floor, so filter it tightly.** It is stored SQL with no window of its own, and the `is_rerun_copy` window means an unfiltered `SELECT` sorts the team's whole job history. Insights and `execute-sql` should bound `created_at` (and, for a scan the engine can actually prune, keep the bound close). The product's own endpoint queries pass `created_floor` instead (§6).
#### `engineering_analytics_ci_job_history`
- The per-job-attempt history with commit attribution, for green/red boundary analysis ("master went red at SHA X, authored by Y, via PR Z").
- Column order is the locked contract (it fixes the UNION ALL order and the saved-query schema): append, never reorder.
+- `is_rerun_copy` rides here too (§6), so a green/red boundary or duration read can drop the re-listed rows instead of counting one execution twice.
- Two PR keys, by design (§6): `pr_number` is the run's `pull_requests` association (0 when absent: master pushes, fork PRs), or the PR a merge-queue gate branch was landing when `is_merge_queue`; `commit_pr_number` resolves the merged PR that produced the head commit, which is how a master push gets PR attribution at all.
- Commit attribution joins the raw runs table on `run_id` alone, never `run_attempt`: the runs snapshot upserts by id so only the newest attempt's row exists, and attribution is attempt-invariant (a re-run is the same commit).
@@ -135,6 +140,14 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- A gate run's `pr_number` resolves through its branch (`trunk-merge/pr-<n>/…`), not its `pull_requests` association — the association names the throwaway PR. This is not the head-SHA join banned above: the branch name is immutable for the branch's life and names exactly one PR. `ci_job_history.is_merge_queue` keeps the two populations separable. The same resolution runs over the CI test spans, where the emitter stamps the gate PR from the webhook payload and would otherwise make one test failing across N merge attempts read as N distinct PRs in every blast-radius count.
- A failure on a gate branch that never reached trunk classifies as `blocking_merge_queue`, not `pr_only`: the commit had already passed the PR's own CI, which is the semantic-conflict class the queue exists to catch.
- A queue that batched several PRs onto one gate branch would break the one-PR assumption; that needs a new branch shape in `merge_queue.py`, not a new rule at each call site.
+- **Depot bills from the first step, not from `started_at` — the cost model uses a billed clock.** GitHub stamps a job's `started_at` the moment Depot accepts it; the machine then boots before "Set up job" runs, and Depot bills only the time after the job started running. The gap is tens of seconds per job (the other end, last step -> `completed_at`, is negligible), a few percent of billed minutes at scale. So `billed_elapsed = duration_seconds - provisioning_seconds` (clamped >= 0).
+ - `provisioning_seconds` (the curated jobs builder) is `started_at` -> the first `steps` entry's `started_at`, and NULL when the `steps` payload is missing or empty. NULL subtracts nothing: an under-correction is honest, an over-correction is not.
+ - `duration_seconds` is deliberately left alone — queue and duration UX is about the window GitHub reports. Only the cost columns read the billed clock, and `logic/cost.py` defines it once for both the Python model and the rendered SQL.
+- **A GitHub "re-run failed jobs" copy is not an execution — flagged once, in the `workflow_jobs` builder.** When a run is partially re-run, GitHub's jobs API lists every already-passed job again under the new `run_attempt` with new job ids but the earlier attempt's exact `started_at` / `completed_at` (`filter=latest` returns them too, so the source can't drop them). A row is a copy when the same `(run_id, name, started_at, completed_at)` exists at a lower `run_attempt`; `is_rerun_copy` says so, and `logic/cost.py`'s `render_is_billable_job` is the one predicate every cost consumer partitions on. Copies are a few percent of job rows and minutes; counting them over-reported CI spend, retry pressure, and duration samples by that much.
+ - Copies are flagged, never filtered at the substrate: the exposed views keep one row per job attempt, matching what GitHub shows for the run, and each consumer decides. Cost drops them; so do the per-job aggregates (a copy would double every duration sample and report a retry nobody performed). Red/green reads keep them — a copy is a green re-listing of a green job, so it changes no verdict.
+ - The flag is a window over `(run_id, name, started_at, completed_at)`, which blocks a caller's outer `created_at_raw` predicate from pruning the scan. Windowed callers pass `created_floor=True` so the same coarse floor lands **below** the window instead (see the `workflow_jobs` builder); `job_costs.build_query` and `_curated.job_cost_source()` thread it through for the cost surfaces.
+ - The floor's slack depends on which clock the query windows (`_workflow_filters`). One day when it filters the job's own `created_at` — that only absorbs a timezone offset. A week when it filters the RUN's start, which every cost surface does: a re-run's runs row carries only its newest attempt's `run_started_at`, so its earlier attempts' job rows — the ones that actually ran — were created before the window. A tight floor there would cut them and silently under-report the re-run, undoing the `run_id`-only join above.
+ - Two cost queries stay unfloored on purpose: single-PR cost and the PR-list cost rollup are keyed by PR number, not a window, and no cheap date bound exists for either (see `pr_cost.py`). The per-run job breakdown is unfloored too — it filters `run_id`, the window's leading partition column.
- **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`.
- **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 rate over runs that reached a verdict (cancelled and skipped runs decide nothing). 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.
diff --git a/products/engineering_analytics/backend/logic/cost.py b/products/engineering_analytics/backend/logic/cost.py
index 9ec118ace022..429822f07ee2 100644
--- a/products/engineering_analytics/backend/logic/cost.py
+++ b/products/engineering_analytics/backend/logic/cost.py
@@ -3,9 +3,16 @@
Estimates the Depot dollar cost of CI from GitHub Actions job data. GitHub's jobs
API exposes wall-clock (``started_at`` -> ``completed_at``) and the requested runner
``labels`` -- not Depot's billed minutes -- so every figure here is an estimate:
-``elapsed_minutes x tier_multiplier x reference_rate``. This mirrors the model the
+``billed_minutes x tier_multiplier x reference_rate``. This mirrors the model the
DevEx Depot cost tooling already uses (list price, per-vCPU multiplier ladder).
+Billed, not wall-clock: GitHub stamps ``started_at`` when Depot accepts the job, and the
+machine then boots before the first step runs. Depot bills only the time after the job
+started running, so the elapsed every function here takes is ``billed_elapsed_seconds``
+-- wall-clock minus that provisioning. It is tens of seconds per job, a few percent of
+billed minutes at scale, which is why the correction sits in the model rather than being
+waved off as noise.
+
GitHub/Depot specifics (the ``depot-*`` label shapes, the rate ladder) live here in
the read layer per SPEC section 3; provider-neutral contract types stay in
``facade/contracts.py``.
@@ -152,12 +159,34 @@ def runner_tier_descriptor(provider: str | None, os: str | None, vcpu: int | Non
return "self_hosted", (os or "")
-def estimate_job_cost_usd(labels: list[str], elapsed_seconds: float | None) -> float | None:
+def billed_elapsed_seconds(elapsed_seconds: float | None, provisioning_seconds: float | None) -> float | None:
+ """The seconds Depot bills for one job: its wall-clock elapsed minus the provisioning it opens with.
+
+ ``elapsed_seconds`` is the job's ``started_at`` -> ``completed_at`` (the curated jobs builder's
+ ``duration_seconds``); ``provisioning_seconds`` is its ``started_at`` -> its first step's
+ ``started_at`` (that builder's ``provisioning_seconds``), or ``None`` when the ``steps`` payload
+ isn't there. No steps means nothing is subtracted — an under-correction, never an over-correction.
+ An unknown elapsed (queued / not-yet-finished job) stays ``None`` so it never becomes a measured
+ zero; a negative result is clamped to 0 for clock skew.
+ """
+ if elapsed_seconds is None:
+ return None
+ return max(elapsed_seconds - (provisioning_seconds or 0), 0)
+
+
+def estimate_job_cost_usd(
+ labels: list[str], elapsed_seconds: float | None, *, is_rerun_copy: bool = False
+) -> float | None:
"""Estimated Depot dollar cost for one job, or ``None`` when no honest figure exists.
+ ``elapsed_seconds`` is the BILLED elapsed (``billed_elapsed_seconds``), not the raw wall-clock,
+ so provisioning time Depot doesn't charge for never reaches the rate.
+
``None`` means "no Depot cost to report": the job is github-hosted, its runner can't be
classified, it ran on a non-Linux Depot tier (macOS / Windows — separate price tiers not
- modeled yet, so excluded rather than mis-costed at the Linux rate), OR its elapsed time is
+ modeled yet, so excluded rather than mis-costed at the Linux rate), the row is a GitHub
+ re-run copy (a job GitHub re-listed under a later attempt without re-running it, so nothing
+ executed and nothing was billed — see the ``workflow_jobs`` builder), OR its elapsed time is
unknown (a queued / not-yet-started job). That last case is deliberately distinct from a
job that ran for no measurable time (``started_at == completed_at`` or clock skew), which
is a real, measured ``0.0``: a consumer summing per-PR cost skips ``None`` jobs, so a queued
@@ -166,6 +195,8 @@ def estimate_job_cost_usd(labels: list[str], elapsed_seconds: float | None) -> f
tier = classify_runner(labels)
if tier is None or tier.provider is not RunnerProvider.DEPOT or tier.os is not RunnerOS.LINUX:
return None
+ if is_rerun_copy:
+ return None
if elapsed_seconds is None:
return None
if elapsed_seconds <= 0:
@@ -180,7 +211,8 @@ class PRCostAggregate:
``billable_seconds`` and ``estimated_cost_usd`` cover only the costed jobs (billable Linux,
finished). ``unsettled_jobs`` are billable Linux jobs with no elapsed time (still queued/running)
— excluded from cost so a not-yet-finished job is never shown as ``$0.00``. ``excluded_jobs`` ran
- on provider-hosted (GitHub-hosted, free) or non-Linux runners, which carry no billable figure here.
+ on provider-hosted (GitHub-hosted, free) or non-Linux runners, or never ran at all (a GitHub
+ re-run copy), and so carry no billable figure here.
``estimated_cost_usd`` is ``None`` when no job was costable, distinguishing "nothing to cost" from
a real ``$0.00``.
"""
@@ -302,24 +334,42 @@ def render_is_billable_tier(provider_sql: str, os_sql: str) -> str:
"""SQL predicate: True when a job's classified tier is billable — self-hosted Linux (Depot Linux,
the only modeled billed tier). Generated from the enums so ``'depot'`` / ``'linux'`` never appear
as string literals in the query layer. NULL-safe: an unclassified tier (``provider`` NULL) reads as
- not billable. This is the one place the billable-partition rule is spelled out; the endpoint cost
- aggregates and the two renderers below all read it, so the three-bucket split can't drift."""
+ not billable. Tier only — whether a given ROW costs money is ``render_is_billable_job``, which every
+ cost consumer reads, so the three-bucket split can't drift."""
return f"ifNull({provider_sql} = '{RunnerProvider.DEPOT.value}' AND {os_sql} = '{RunnerOS.LINUX.value}', 0)"
-def render_billable_seconds(provider_sql: str, os_sql: str, elapsed_sql: str) -> str:
+def render_is_billable_job(provider_sql: str, os_sql: str, is_rerun_copy_sql: str) -> str:
+ """SQL predicate: True when a job ROW is billable — a billable tier AND a row that actually
+ executed. GitHub re-lists an already-passed job under a later ``run_attempt`` with the earlier
+ attempt's timestamps (``is_rerun_copy`` in the ``workflow_jobs`` builder); nothing ran, so Depot
+ billed nothing and the row must not be costed. Every cost consumer partitions on this, not on
+ ``render_is_billable_tier``, so the "does this row cost money" rule stays in one place."""
+ return f"({render_is_billable_tier(provider_sql, os_sql)} AND NOT {is_rerun_copy_sql})"
+
+
+def render_billed_elapsed_seconds(elapsed_sql: str, provisioning_sql: str) -> str:
+ """The seconds Depot bills for one job — the SQL form of ``billed_elapsed_seconds``: wall-clock
+ elapsed minus provisioning, clamped at 0, and NULL exactly when the elapsed is NULL so "unsettled"
+ stays the single condition every consumer already tests on ``duration_seconds``."""
+ return f"if({elapsed_sql} IS NULL, NULL, greatest({elapsed_sql} - ifNull({provisioning_sql}, 0), 0))"
+
+
+def render_billable_seconds(provider_sql: str, os_sql: str, is_rerun_copy_sql: str, elapsed_sql: str) -> str:
"""Raw billable wall-clock seconds (NOT multiplier-weighted): ``greatest(elapsed, 0)`` only for
- a billable self-hosted Linux job with a known elapsed, else NULL — mirrors the ``max(0, elapsed)``
+ a billable job row with a known elapsed, else NULL — mirrors the ``max(0, elapsed)``
a costed job contributes to a PR's ``billable_seconds``."""
- billable = render_is_billable_tier(provider_sql, os_sql)
+ billable = render_is_billable_job(provider_sql, os_sql, is_rerun_copy_sql)
return f"if({billable} AND {elapsed_sql} IS NOT NULL, greatest({elapsed_sql}, 0), NULL)"
-def render_estimated_cost_usd(provider_sql: str, os_sql: str, vcpu_sql: str, elapsed_sql: str) -> str:
+def render_estimated_cost_usd(
+ provider_sql: str, os_sql: str, vcpu_sql: str, is_rerun_copy_sql: str, elapsed_sql: str
+) -> str:
"""Estimated Depot dollar cost for one job — the SQL form of ``estimate_job_cost_usd``:
- NULL when not billable (non-Depot / non-Linux / unclassified) and NULL for an unsettled job
- (elapsed unknown, never $0.00), a real 0.0 for non-positive elapsed, else
- ``(elapsed / 60) * REFERENCE_RATE_USD_PER_MIN * multiplier``."""
- is_depot_linux = render_is_billable_tier(provider_sql, os_sql)
+ NULL when the row isn't billable (non-Depot / non-Linux / unclassified, or a re-run copy that
+ never executed) and NULL for an unsettled job (elapsed unknown, never $0.00), a real 0.0 for
+ non-positive elapsed, else ``(elapsed / 60) * REFERENCE_RATE_USD_PER_MIN * multiplier``."""
+ is_billable = render_is_billable_job(provider_sql, os_sql, is_rerun_copy_sql)
cost = f"({elapsed_sql} / 60) * {REFERENCE_RATE_USD_PER_MIN} * {render_multiplier(vcpu_sql)}"
- return f"multiIf(NOT {is_depot_linux}, NULL, {elapsed_sql} IS NULL, NULL, {elapsed_sql} <= 0, 0.0, {cost})"
+ return f"multiIf(NOT {is_billable}, NULL, {elapsed_sql} IS NULL, NULL, {elapsed_sql} <= 0, 0.0, {cost})"
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 37279ef7ff1c..d1f8aab8fdc2 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -184,11 +184,15 @@ class CuratedGitHubSource:
)
return f"({query})"
- def jobs_source(self) -> str | None:
- """Curated workflow-jobs ``SELECT`` subquery, or None when the optional jobs table isn't synced."""
+ def jobs_source(self, *, created_floor: bool = False) -> str | None:
+ """Curated workflow-jobs ``SELECT`` subquery, or None when the optional jobs table isn't synced.
+
+ ``created_floor`` adds the raw-string scan floor inside the builder — callers must register
+ {job_created_floor} (see run_started_floor_constant). A windowed caller needs it: the builder's
+ ``is_rerun_copy`` window blocks an outer ``created_at_raw`` predicate from pruning the scan."""
if not self._tables.workflow_jobs:
return None
- return f"({workflow_jobs.build_query(self._tables.workflow_jobs)})"
+ return f"({workflow_jobs.build_query(self._tables.workflow_jobs, created_floor=created_floor)})"
def trunk_merge_queue_source(self) -> str | None:
"""Curated Trunk merge-queue ``SELECT`` subquery, or None when no TrunkIo source has the
@@ -272,7 +276,7 @@ class CuratedGitHubSource:
)
"""
- def job_cost_source(self) -> str | None:
+ def job_cost_source(self, *, created_floor: bool = False) -> 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`` /
``run_head_branch``). None when the jobs table isn't synced, exactly like ``jobs_source``.
@@ -281,6 +285,12 @@ class CuratedGitHubSource:
/ ``estimated_cost_usd`` are rendered from ``logic.cost`` in ClickHouse, so every endpoint cost
query aggregates the same per-job figures the exposed view (and the parity test) do — there is
no separate Python cost rollup to drift.
+
+ ``created_floor`` adds the raw-string scan floor inside the jobs builder — callers must
+ register {job_created_floor} (see run_windowed_job_created_floor_constant, the right slack for
+ the run-windowed predicates every cost query uses). Every windowed caller wants it: the cost
+ source's window predicates read the RUN's columns and so can never prune the jobs scan, which
+ the ``is_rerun_copy`` window would otherwise sort in full on every call.
"""
if not self._tables.workflow_jobs:
return None
@@ -288,6 +298,7 @@ class CuratedGitHubSource:
jobs_table=self._tables.workflow_jobs,
runs_table=self._tables.workflow_runs,
include_run_columns=True,
+ created_floor=created_floor,
)
return f"({query})"
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
index 17a498e3ce2d..5102f76a4fb0 100644
--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -81,6 +81,49 @@ def run_started_floor_constant(window_start: datetime) -> ast.Constant:
return ast.Constant(value=(window_start - timedelta(days=1)).strftime("%Y-%m-%d"))
+# How far below a window start the jobs-scan floor sits, by what the window actually filters.
+#
+# ON_JOB_CREATED: the query bounds the job's own created_at, so the floor only has to absorb the
+# timezone offset between the window's zone and the UTC strings GitHub lands — one day, exactly like
+# run_started_floor_constant.
+#
+# ON_RUN_STARTED: the query bounds the RUN's start instead, and the two clocks come apart on a re-run.
+# The runs snapshot upserts by id, so a re-run carries only its NEWEST attempt's run_started_at while
+# its earlier attempts' job rows were created back when those attempts ran — and those are the rows
+# that actually executed (a later attempt mostly re-lists them; see the workflow_jobs builder). A
+# one-day floor would cut exactly those, silently under-reporting the re-run's cost. A week covers
+# realistic re-run latency ("re-run on Monday what failed on Friday") and still turns an all-time jobs
+# scan into a bounded one. It is a bound, not a proof: a re-run older than this loses its earlier
+# attempts from the window's cost, which is the coarseness the floor trades for the scan.
+#
+# The same wide floor applies to any query that EXCLUDES re-run copies, whichever clock it windows:
+# the copy is only recognisable while its original attempt is inside the scan, so a tight floor under a
+# late re-run would turn the copy back into an execution. Queries that keep copies (red/green reads)
+# can use the tight floor.
+_JOB_FLOOR_SLACK_ON_JOB_CREATED = timedelta(days=1)
+_JOB_FLOOR_SLACK_ON_RUN_STARTED = timedelta(days=7)
+
+
+def _date_floor(window_start: datetime, slack: timedelta) -> ast.Constant:
+ """A date-only string ``slack`` below the window start. Date-only on purpose: it compares
+ lexicographically below every in-window ISO timestamp ('2026-07-11' < '2026-07-11T...')."""
+ return ast.Constant(value=(window_start - slack).strftime("%Y-%m-%d"))
+
+
+def job_created_floor_constant(window_start: datetime) -> ast.Constant:
+ """Raw-string scan floor for the jobs builder's {job_created_floor} placeholder, for a query that
+ windows the job's own ``created_at``. See ``_JOB_FLOOR_SLACK_ON_JOB_CREATED``."""
+ return _date_floor(window_start, _JOB_FLOOR_SLACK_ON_JOB_CREATED)
+
+
+def run_windowed_job_created_floor_constant(window_start: datetime) -> ast.Constant:
+ """Raw-string scan floor for the jobs builder's {job_created_floor} placeholder, for a query that
+ windows the RUN's start (every cost surface does). Wider than the job-created floor because a
+ re-run's earlier attempts were created before its run_started_at — see
+ ``_JOB_FLOOR_SLACK_ON_RUN_STARTED``."""
+ return _date_floor(window_start, _JOB_FLOOR_SLACK_ON_RUN_STARTED)
+
+
def branch_filter_clause(
branch: str | None, placeholders: dict[str, ast.Expr], *, column: str = "r.head_branch"
) -> str:
diff --git a/products/engineering_analytics/backend/logic/queries/broken_tests.py b/products/engineering_analytics/backend/logic/queries/broken_tests.py
index 2e6208a2db01..6e832f3c7f77 100644
--- a/products/engineering_analytics/backend/logic/queries/broken_tests.py
+++ b/products/engineering_analytics/backend/logic/queries/broken_tests.py
@@ -30,7 +30,7 @@ spread like any other — ``pr_only`` for a single merge attempt, ``flaky`` or `
several — which buries the one failure class the queue was installed to surface.
"""
-from datetime import datetime, timedelta
+from datetime import datetime
from posthog.hogql import ast
@@ -44,6 +44,7 @@ from products.engineering_analytics.backend.facade.contracts import (
)
from products.engineering_analytics.backend.logic.merge_queue import looks_like_merge_queue_branch_expr
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import job_created_floor_constant
from products.engineering_analytics.backend.logic.views import ci_failures
# Branch names treated as trunk — the failure "hit master" and job-status filters key on these.
@@ -122,9 +123,9 @@ _HOURLY_SELECT = """
# Latest default-branch status per (workflow, job), from the curated workflow-jobs source. Keyed by
# workflow too, not job name alone: unrelated workflows can reuse a job name like ``test`` / ``build``,
-# and collapsing them would let one workflow's green job mask another's red one. ``created_at_raw`` is
-# the raw ISO string the scan can prune on (a parsed-column predicate forces a full scan); it floors a
-# day below the precise ``created_at`` window. Recency keys on ``completed_at`` (when the run actually
+# and collapsing them would let one workflow's green job mask another's red one. The scan-pruning floor
+# rides inside the jobs builder (``created_floor=True``, a raw-string predicate a parsed-column one
+# can't replace); it floors a day below the precise ``created_at`` window. Recency keys on ``completed_at`` (when the run actually
# finished), not ``created_at`` — a run that started before a failure but finished green after it is a
# real recovery. ``latest_conclusion`` is that newest-finishing completed run's conclusion (red =
# broken now); ``latest_completed_age`` is how long ago it finished, so the classifier can tell a
@@ -137,7 +138,6 @@ _MASTER_JOBS_SELECT = """
dateDiff('second', maxIf(completed_at, status = 'completed'), now()) AS latest_completed_age
FROM __JOBS_SOURCE__
WHERE head_branch IN {default_branches}
- AND created_at_raw >= {created_floor}
AND created_at >= {date_from}
GROUP BY workflow_name, name
"""
@@ -268,7 +268,7 @@ def query_broken_tests(
# through. Keyed on (workflow_name, job_name) so a job name shared across workflows doesn't collapse.
master_by_key: dict[tuple[str, str], tuple[str | None, int | None]] = {}
breaking_master_jobs: set[str] = set()
- jobs_source = curated.jobs_source()
+ jobs_source = curated.jobs_source(created_floor=True)
if jobs_source is not None:
master_rows = (
curated.run(
@@ -276,7 +276,7 @@ def query_broken_tests(
query_type="engineering_analytics.broken_tests_master_jobs",
placeholders={
"default_branches": ast.Constant(value=_DEFAULT_BRANCHES),
- "created_floor": ast.Constant(value=(date_from - timedelta(days=1)).strftime("%Y-%m-%d")),
+ "job_created_floor": job_created_floor_constant(date_from),
"date_from": ast.Constant(value=date_from),
},
).results
diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
index 50120b0df88b..32a195aa2259 100644
--- a/products/engineering_analytics/backend/logic/queries/job_aggregates.py
+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
@@ -23,6 +23,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
DURATION_PERCENTILE_CONDITION,
branch_filter_clause,
date_to_filter_clause,
+ run_windowed_job_created_floor_constant,
)
_LIMIT = 200
@@ -54,7 +55,11 @@ _AGGREGATE_SELECT = f"""
countIf(conclusion IN ('failure', 'timed_out')) / nullIf(countIf(status = 'completed'), 0) AS failure_rate,
countIf(run_attempt > 1) AS retry_job_count
FROM __JOBS_SOURCE__ AS j
- WHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
+ -- NOT is_rerun_copy: "Re-run failed jobs" re-lists every already-passed job under the new attempt
+ -- with the earlier attempt's timestamps. Counting those would double every duration sample and
+ -- report retry pressure for jobs nobody retried.
+ WHERE NOT is_rerun_copy
+ AND workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
GROUP BY job_name
ORDER BY job_count DESC
LIMIT {_LIMIT}
@@ -89,8 +94,12 @@ def query_job_aggregates(
date_to: datetime | None,
branch: str | None,
) -> list[WorkflowJobAggregate]:
- jobs_source = curated.jobs_source()
- cost_source = curated.job_cost_source()
+ # Both templates window the job's OWN created_at, but this query EXCLUDES re-run copies, and a copy
+ # is only recognisable while its original attempt is still in the scan: a re-run a day or more after
+ # the original push would otherwise pull the copy inside the window, drop the original below a tight
+ # floor, and count the copy as an execution. So take the wide floor, same as the cost surfaces.
+ jobs_source = curated.jobs_source(created_floor=True)
+ cost_source = curated.job_cost_source(created_floor=True)
if jobs_source is None or cost_source is None:
return []
@@ -98,6 +107,7 @@ def query_job_aggregates(
placeholders: dict[str, ast.Expr] = {
"workflow_name": ast.Constant(value=workflow_name),
"date_from": ast.Constant(value=date_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
}
# Shared filter clauses (each registers its own placeholder). The jobs/cost templates window and
# branch-filter on the per-job created_at + head_branch; the run-count template reads the run
diff --git a/products/engineering_analytics/backend/logic/queries/master_failures.py b/products/engineering_analytics/backend/logic/queries/master_failures.py
index 86cc74ee451a..e5eadd59c32c 100644
--- a/products/engineering_analytics/backend/logic/queries/master_failures.py
+++ b/products/engineering_analytics/backend/logic/queries/master_failures.py
@@ -18,6 +18,9 @@ from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import MasterFailureGroup, RepoRef
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ run_windowed_job_created_floor_constant,
+)
# Failed default-branch runs in the window is a triage view, not an archive — cap it.
_RUN_CAP = 500
@@ -74,12 +77,18 @@ def query_master_failures(
# Failed job names per run — empty when the jobs source isn't synced, in which case
# groups degrade to workflow-level (failed_job = '').
jobs_by_run: dict[int, list[str]] = {}
- jobs_source = curated.jobs_source()
+ # run_id IN (...) scopes the result but not the scan, and the builder's is_rerun_copy window would
+ # otherwise sort the whole jobs history. The run ids come from a run_started_at-windowed scan, so
+ # the floor takes the wider re-run slack.
+ jobs_source = curated.jobs_source(created_floor=True)
if jobs_source is not None:
jobs_response = curated.run(
_FAILED_JOBS_SELECT.replace("__JOBS_SOURCE__", jobs_source),
query_type="engineering_analytics.master_failures_jobs",
- placeholders={"run_ids": ast.Constant(value=[run_id for run_id, *_ in runs])},
+ placeholders={
+ "run_ids": ast.Constant(value=[run_id for run_id, *_ in runs]),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
+ },
)
for run_id, job_name in jobs_response.results or []:
jobs_by_run.setdefault(run_id, []).append(job_name)
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index cda53a331d2a..e4b6c9dd9154 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -36,7 +36,7 @@ from products.engineering_analytics.backend.facade.contracts import (
)
from products.engineering_analytics.backend.logic.cost import (
PRCostAggregate,
- render_is_billable_tier,
+ render_is_billable_job,
runner_tier_descriptor,
)
from products.engineering_analytics.backend.logic.queries._buckets import (
@@ -51,12 +51,14 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
date_to_filter_clause,
merge_queue_branch_predicate,
run_scope_filter_clause,
+ run_windowed_job_created_floor_constant,
window_pair_predicates,
)
-# The billable-tier predicate over the cost source's classified columns — defined once in logic.cost
-# so 'depot'/'linux' never appear as literals here.
-_BILLABLE_TIER = render_is_billable_tier("c.provider", "c.os")
+# The billable-row predicate over the cost source's classified columns — defined once in logic.cost
+# so 'depot'/'linux' never appear as literals here. Row, not tier: a GitHub re-run copy sits on a
+# billable tier but never executed, so it belongs in excluded_jobs rather than in no bucket at all.
+_BILLABLE_ROW = render_is_billable_job("c.provider", "c.os", "c.is_rerun_copy")
def _cost_aggregates(when: str = "1", suffix: str = "") -> str:
@@ -65,15 +67,15 @@ def _cost_aggregates(when: str = "1", suffix: str = "") -> str:
``billable_seconds`` sums ``greatest(elapsed, 0)`` over costed rows; ``cost_sum`` sums the rendered
per-job dollar cost; ``costed_jobs`` counts rows with a non-NULL cost; ``unsettled_jobs`` and
- ``excluded_jobs`` complete the three-bucket partition. ``costed_jobs`` is what tells "$0.00" apart
+ ``excluded_jobs`` complete the three-bucket partition (a re-run copy is excluded — it never ran). ``costed_jobs`` is what tells "$0.00" apart
from "nothing to cost" downstream — a SQL sum can't.
"""
return (
f"sumIf(ifNull(c.billable_seconds, 0), {when}) AS billable_seconds{suffix}, "
f"sumIf(c.estimated_cost_usd, c.estimated_cost_usd IS NOT NULL AND ({when})) AS cost_sum{suffix}, "
f"countIf(c.estimated_cost_usd IS NOT NULL AND ({when})) AS costed_jobs{suffix}, "
- f"countIf({_BILLABLE_TIER} AND c.duration_seconds IS NULL AND ({when})) AS unsettled_jobs{suffix}, "
- f"countIf(NOT {_BILLABLE_TIER} AND ({when})) AS excluded_jobs{suffix}"
+ f"countIf({_BILLABLE_ROW} AND c.duration_seconds IS NULL AND ({when})) AS unsettled_jobs{suffix}, "
+ f"countIf(NOT {_BILLABLE_ROW} AND ({when})) AS excluded_jobs{suffix}"
)
@@ -128,6 +130,13 @@ _EMPTY = PRCostSummary(
# per-workflow, and per-run rollups all fold from these rows in Python (cost is linear). Filtering on
# the cost source's run-attribution columns (pr_number is 0→NULL normalized) drops jobs whose run row
# is missing, matching the legacy INNER JOIN population.
+#
+# The only two cost queries with no scan floor (see job_cost_source(created_floor=...)) are this one
+# and _LIST_COST_SELECT: both are keyed by PR number, not by a window, and a PR's created_at would
+# cost an extra round trip here (build_pr_cost is handed a number and a repo, nothing else) or be the
+# min across a whole page there — which for a page holding one old PR is no bound at all. Left
+# unfloored deliberately; if these ever get slow, thread the PR's created_at down and floor a day
+# below it rather than inventing a window.
_PR_COST_SELECT = """
SELECT
c.workflow_name AS workflow_name,
@@ -257,10 +266,13 @@ def query_workflow_window_costs(
run-level ``query_workflow_health`` (a job whose run is missing has a NULL run_started_at and is
excluded by the window filter, matching the legacy INNER JOIN).
"""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=True)
if cost_source is None:
return {}
- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ placeholders: dict[str, ast.Expr] = {
+ "date_from": ast.Constant(value=date_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
+ }
date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")
branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")
run_scope_clause = run_scope_filter_clause(
@@ -308,12 +320,13 @@ def query_author_workflow_costs(
author→runs link goes through their PR numbers (the one attribution rule, SPEC §6) — the cost
source's normalized pr_number never matches on an unattributed (NULL) run.
"""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=True)
if cost_source is None:
return []
placeholders: dict[str, ast.Expr] = {
"author": ast.Constant(value=author),
"date_from": ast.Constant(value=date_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
}
date_to_clause = ""
if date_to is not None:
@@ -374,12 +387,14 @@ def query_workflow_window_costs_with_prev(
prior implementation), so a workflow present only in the other window doesn't create a phantom
zero-cost entry.
"""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=True)
if cost_source is None:
return _EMPTY_WINDOW_COSTS
placeholders: dict[str, ast.Expr] = {
"date_from": ast.Constant(value=date_from),
"prev_from": ast.Constant(value=prev_from),
+ # Floored off prev_from, the earlier of the two window starts — this scan carries both.
+ "job_created_floor": run_windowed_job_created_floor_constant(prev_from),
}
windows = window_pair_predicates("c.run_started_at", date_to=date_to)
date_to_clause = ""
@@ -472,11 +487,14 @@ def query_cost_per_merge_series(
there's no cost to divide, so the series is empty (the UI shows the same "sync jobs" state as
the other cost surfaces).
"""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=True)
if cost_source is None:
return []
- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ placeholders: dict[str, ast.Expr] = {
+ "date_from": ast.Constant(value=date_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
+ }
date_to_runs = ""
date_to_merged = ""
if date_to is not None:
@@ -563,7 +581,7 @@ def query_workflow_runner_costs(
"""A workflow's CI cost broken down by runner tier over [date_from, date_to] (optional branch),
highest spend first. Empty when the jobs source isn't synced. Grouped by the rendered
(provider, os, vcpu) tier and mapped to its display badge/label via ``runner_tier_descriptor``."""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=True)
if cost_source is None:
return []
placeholders: dict[str, ast.Expr] = {
@@ -571,6 +589,7 @@ def query_workflow_runner_costs(
"repo_name": ast.Constant(value=repo_name),
"workflow_name": ast.Constant(value=workflow_name),
"date_from": ast.Constant(value=date_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(date_from),
}
date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")
branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_flakiness.py b/products/engineering_analytics/backend/logic/queries/workflow_flakiness.py
index 3f468354434b..7dcf06442f95 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_flakiness.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_flakiness.py
@@ -8,7 +8,10 @@ from posthog.hogql import ast
from posthog.clickhouse.workload import Workload
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
-from products.engineering_analytics.backend.logic.queries._workflow_filters import run_started_floor_constant
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ job_created_floor_constant,
+ run_started_floor_constant,
+)
# A job that failed in under this many seconds did no real work: it's a required-check aggregator
# echoing a dependency's failure, which double-counts every real flake. The floor separates a job
@@ -39,9 +42,10 @@ _SELECT = """
maxIf(j.duration_seconds, j.conclusion IN ('failure', 'timed_out')) AS failed_duration_seconds
FROM __JOBS_SOURCE__ AS j
INNER JOIN __RUNS_SOURCE__ AS r ON r.id = j.run_id
- -- created_at_raw is the unparsed string the scan can prune on; the parsed j.created_at filter
- -- alone can't push down, so both floors keep the sweep off a full jobs+runs scan each hour.
- WHERE j.created_at >= {date_from} AND j.created_at_raw >= {job_created_floor} AND j.head_sha != ''
+ -- Both sources carry a raw-string floor inside their builder (job_created_floor /
+ -- run_started_floor); the parsed j.created_at filter alone can't push down, so those floors
+ -- keep the sweep off a full jobs+runs scan each hour.
+ WHERE j.created_at >= {date_from} AND j.head_sha != ''
-- concat yields NULL when j.name is NULL, which a bare NOT IN would drop.
AND ifNull(concat(lower(r.repo_owner), '/', lower(r.repo_name), '/', j.name), '')
NOT IN {by_design_failures}
@@ -73,7 +77,7 @@ def query_workflow_flakiness(
min_failed_duration_seconds: int = NO_OP_JOB_MAX_SECONDS,
workload: Workload = Workload.DEFAULT,
) -> list[FlakyJobRun]:
- jobs_source = curated.jobs_source()
+ jobs_source = curated.jobs_source(created_floor=True)
if jobs_source is None:
return []
response = curated.run(
@@ -86,10 +90,11 @@ def query_workflow_flakiness(
"date_from": ast.Constant(value=date_from),
"min_failed_duration_seconds": ast.Constant(value=min_failed_duration_seconds),
"by_design_failures": ast.Constant(value=list(BY_DESIGN_FAILURES)),
- # Same date-only floor for both tables: prunes the runs subquery (run_started_floor) and
- # the jobs scan (job_created_floor via created_at_raw).
+ # Same date-only floor for both tables — each query filters the column it floors, so both
+ # take the tight one-day slack: the runs subquery (run_started_floor) and the jobs
+ # subquery (job_created_floor).
"run_started_floor": run_started_floor_constant(date_from),
- "job_created_floor": run_started_floor_constant(date_from),
+ "job_created_floor": job_created_floor_constant(date_from),
},
)
return [
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py b/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
index 2b38a8ef532d..dd6f86bb3e4d 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
@@ -3,10 +3,13 @@
Reads the curated jobs subquery (``_curated.jobs_source``) for one ``run_id``. Job-level data is an
optional source — when it isn't synced, ``jobs_source()`` is None and this returns ``[]`` so the UI
degrades to an empty breakdown instead of erroring. Per-job cost is derived from the runner tier
-(parsed from ``labels``) and elapsed time via the pure cost model (``logic.cost``).
+(parsed from ``labels``) and Depot's billed elapsed via the pure cost model (``logic.cost``) — the
+same model the exposed cost view renders in SQL, fed the same two inputs.
A re-run carries several attempts under one ``run_id``; scoping to a single ``run_attempt`` keeps a
row's statuses, durations, and costs from merging across attempts (and double-counting cost). The
+attempt's job list is shown whole, matching GitHub's own — including the already-passed jobs GitHub
+re-lists under it — but those rows carry no cost, since nothing ran (``is_rerun_copy``). The
caller passes the attempt it's showing; when omitted, the run's latest attempt is read from the runs
source (not the synced job rows) so a default lookup tracks the canonical attempt even when only older
attempts' jobs have synced — returning an empty breakdown rather than stale jobs for that case.
@@ -18,14 +21,23 @@ from typing import Any
from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import WorkflowJob
-from products.engineering_analytics.backend.logic.cost import estimate_job_cost_usd, runner_descriptor
+from products.engineering_analytics.backend.logic.cost import (
+ billed_elapsed_seconds,
+ estimate_job_cost_usd,
+ runner_descriptor,
+)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
# Explicit high LIMIT: without it HogQL caps at DEFAULT_RETURNED_ROWS (100), and since the rows are ordered
# by start, a run with >100 jobs (matrix builds, re-run attempts) would silently drop its latest-starting
# jobs — the breakdown would then miss jobs and not add up to the run's cost.
+# No scan floor here, unlike every windowed jobs read: this filters `run_id = {run_id}`, and run_id is
+# the leading PARTITION BY column of the builder's is_rerun_copy window — the one filter shape
+# ClickHouse can push below a window step. A floor would also need the run's created_at, which this
+# entry point isn't given (it takes a run id and nothing else), so bounding it would cost a round trip
+# to buy a bound the run filter already provides.
_SELECT = """
- SELECT id, run_id, run_attempt, name, status, conclusion, labels, runner_name, started_at, completed_at, duration_seconds
+ SELECT id, run_id, run_attempt, name, status, conclusion, labels, runner_name, started_at, completed_at, duration_seconds, provisioning_seconds, is_rerun_copy
FROM __JOBS_SOURCE__ AS j
WHERE run_id = {run_id}
ORDER BY started_at ASC, id ASC
@@ -91,6 +103,8 @@ def _to_job(row: tuple[Any, ...]) -> WorkflowJob:
started_at,
completed_at,
duration,
+ provisioning,
+ is_rerun_copy,
) = row
labels = _parse_labels(labels_raw)
duration_seconds = int(duration) if duration is not None else None
@@ -106,7 +120,14 @@ def _to_job(row: tuple[Any, ...]) -> WorkflowJob:
duration_seconds=duration_seconds,
runner_provider=provider,
runner_label=runner_label or (runner_name or ""),
- estimated_cost_usd=estimate_job_cost_usd(labels, duration_seconds),
+ # Cost runs off the billed clock (wall-clock minus runner boot), not duration_seconds, which
+ # stays what the row displays. A row GitHub re-listed under this attempt without re-running it
+ # costs nothing — the attempt that actually ran carries the minutes (see the jobs builder).
+ estimated_cost_usd=estimate_job_cost_usd(
+ labels,
+ billed_elapsed_seconds(duration_seconds, provisioning),
+ is_rerun_copy=bool(is_rerun_copy),
+ ),
)
diff --git a/products/engineering_analytics/backend/logic/views/ci_job_history.py b/products/engineering_analytics/backend/logic/views/ci_job_history.py
index 80f183e7b965..4b61e46be265 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -88,6 +88,10 @@ FIELDS: dict[str, FieldOrTable] = {
"commit_message": StringDatabaseField(name="commit_message", nullable=True),
"commit_pr_number": IntegerDatabaseField(name="commit_pr_number", nullable=True),
"is_merge_queue": BooleanDatabaseField(name="is_merge_queue"),
+ # A job GitHub re-listed under a later run_attempt without re-running it (see the workflow_jobs
+ # builder). Its timestamps and conclusion are the earlier attempt's, so a boundary or duration
+ # read that counts it counts one execution twice.
+ "is_rerun_copy": BooleanDatabaseField(name="is_rerun_copy"),
}
@@ -151,7 +155,8 @@ def build_query(*, jobs_table: str, runs_table: str, pull_requests_table: str |
r.commit_pr_number AS commit_pr_number,
-- The run ran on a merge-queue gate branch, so pr_number above is the PR it was landing
-- rather than an association. Without this the two populations are indistinguishable.
- r.is_merge_queue AS is_merge_queue
+ r.is_merge_queue AS is_merge_queue,
+ j.is_rerun_copy AS is_rerun_copy
FROM ({jobs}) AS j
LEFT JOIN ({runs}) AS r ON j.run_id = r.id
LEFT JOIN ({head_commits}) AS hc ON j.run_id = hc.run_id
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 63b0bf6a5c92..cd80f71c1025 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -3,14 +3,32 @@
Composes the curated ``workflow_jobs`` and ``workflow_runs`` builders (one row per job attempt)
and renders the Depot cost model from ``logic.cost`` as ClickHouse expressions, so
``provider`` / ``os`` / ``vcpu`` / ``multiplier`` / ``billable_seconds`` / ``estimated_cost_usd``
-are computed at query time from the same constants the Python model uses. The cost model stays
+are computed at query time from the same constants the Python model uses. Cost runs off Depot's
+billed clock, which starts at the job's first step rather than at ``started_at`` (GitHub stamps that
+when Depot accepts the job, before the machine has booted); ``duration_seconds`` stays the full
+wall-clock window the duration and queue reads want. The cost model stays
defined once in ``logic.cost``; this module only wires its rendered expressions over the join.
+Rows are kept for every job attempt the source landed, including the ones GitHub re-listed under a
+later attempt without re-running them ("Re-run failed jobs" copies — see the ``workflow_jobs``
+builder). Dropping them would make this view disagree with ``ci_job_history`` on what a run contains,
+so instead they are flagged ``is_rerun_copy`` and carry no cost: nothing executed, so Depot billed
+nothing, and counting them over-reported CI spend by a few percent.
+
``build_query`` produces the SELECT for one GitHub source; ``build_team_view`` unions every
qualifying source into the single view body. The join is a LEFT JOIN (all jobs are kept — a job
whose run row is missing keeps NULL attribution) rather than the INNER join the per-PR cost
queries use, because the view is the full per-job substrate, not a PR-scoped rollup.
+It joins on ``run_id`` ALONE, never ``(run_id, run_attempt)`` — the same key ``ci_job_history`` uses,
+for the same reason. The runs snapshot upserts by ``id``, so only the newest attempt's row survives;
+requiring attempt equality blanked ``repo_owner`` / ``repo_name`` / ``pr_number`` / ``is_merge_queue``
+for every earlier-attempt job, which is precisely the population that actually executed after a
+partial re-run. Attribution is attempt-invariant (a re-run is the same commit, branch, and PR), so
+``run_id`` is the correct key; ``run_attempt`` in the output comes from the jobs side. The bug was
+masked until re-run copies stopped being costed: the attempt-2 copies joined and carried the same
+durations, so the totals looked right while the rows behind them were the wrong ones.
+
Nothing here is registered as a global HogQL view; the view is provisioned per-team as a
non-materialized ``DataWarehouseSavedQuery`` by data_modeling's managed-viewset sync.
"""
@@ -28,6 +46,7 @@ from posthog.hogql.database.models import (
from products.engineering_analytics.backend.logic.cost import (
render_billable_seconds,
+ render_billed_elapsed_seconds,
render_depot_label,
render_estimated_cost_usd,
render_hosted_label,
@@ -67,11 +86,16 @@ FIELDS: dict[str, FieldOrTable] = {
"started_at": DateTimeDatabaseField(name="started_at", nullable=True),
"completed_at": DateTimeDatabaseField(name="completed_at", nullable=True),
"queue_seconds": IntegerDatabaseField(name="queue_seconds", nullable=True),
+ # Full wall-clock, started_at -> completed_at, as GitHub reports it. NOT what Depot bills — that
+ # is billable_seconds, which starts the clock at the job's first step (see logic/cost.py).
"duration_seconds": IntegerDatabaseField(name="duration_seconds", nullable=True),
"provider": StringDatabaseField(name="provider", nullable=True),
"os": StringDatabaseField(name="os", nullable=True),
"vcpu": IntegerDatabaseField(name="vcpu", nullable=True),
"multiplier": IntegerDatabaseField(name="multiplier", nullable=True),
+ # Depot-billed seconds for a billable row: duration_seconds minus the runner boot GitHub stamps
+ # into it. NULL when the row isn't billable (non-Depot / non-Linux / unclassified / a re-run copy)
+ # or hasn't settled.
"billable_seconds": IntegerDatabaseField(name="billable_seconds", nullable=True),
"estimated_cost_usd": FloatDatabaseField(name="estimated_cost_usd", nullable=True),
# Non-nullable unlike the attribution columns above, because it is derived rather than read off
@@ -79,6 +103,12 @@ FIELDS: dict[str, FieldOrTable] = {
# so "what does the merge queue cost" doesn't get answered by re-deriving a gate branch from
# head_branch, which would put that definition somewhere other than logic/merge_queue.py.
"is_merge_queue": BooleanDatabaseField(name="is_merge_queue"),
+ # The row is a job GitHub re-listed under a later run_attempt without re-running it (see the
+ # workflow_jobs builder). Non-nullable, like is_merge_queue: it is derived, not read off the
+ # source. Exposed because it is the third reason the cost columns can be NULL — provider says
+ # "non-billable tier", completed_at says "unsettled", this says "never executed" — so a consumer
+ # can still tell the three apart, and can drop copies from duration metrics too.
+ "is_rerun_copy": BooleanDatabaseField(name="is_rerun_copy"),
}
@@ -105,27 +135,40 @@ def _run_passthrough_aliases() -> str:
return "".join(f",\n {alias}" for alias, _ in _RUN_PASSTHROUGH)
-def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool = False) -> str:
+def build_query(
+ *, jobs_table: str, runs_table: str, include_run_columns: bool = False, created_floor: bool = False
+) -> str:
"""The per-job cost SELECT for one GitHub source: curated jobs LEFT JOIN curated runs.
Grain is one row per job attempt (a retry appears once per attempt — correct for cost). The
- cost columns are derived only from the job's ``labels`` + elapsed, so an unjoined run (no ``r``
- row) leaves only the attribution columns (``repo_owner`` / ``repo_name`` / ``pr_number``) NULL.
+ cost columns are derived only from the job's ``labels``, elapsed, and ``is_rerun_copy``, so an
+ unjoined run (no ``r`` row) leaves only the attribution columns (``repo_owner`` / ``repo_name`` /
+ ``pr_number``) NULL.
- Layered so each per-row classification step is computed once: the join layer parses ``labels_arr``;
+ Layered so each per-row classification step is computed once: the join layer parses ``labels_arr``
+ and derives ``billed_seconds`` (an internal column — the exposed ``billable_seconds`` is that clock
+ gated on the row being billable);
the label layer picks ``depot_label`` / ``hosted_label`` from it (one ``arrayFilter`` scan each);
the tier layer derives ``provider`` / ``os`` / ``vcpu`` from those two cheap columns; the final
layer derives ``multiplier`` / ``billable_seconds`` / ``estimated_cost_usd``.
``include_run_columns`` threads the ``_RUN_PASSTHROUGH`` run columns through every layer — used
only by the endpoint cost queries; the public view omits them.
+
+ ``created_floor`` threads the jobs builder's raw-string scan floor (its ``{job_created_floor}``
+ placeholder, which the caller must register) down to the jobs scan. Every windowed cost query
+ should pass it: the window predicate reads the RUN's attributes, so it can never prune the jobs
+ side, and without a floor the ``is_rerun_copy`` window sorts the team's whole job history on every
+ call. The public saved view can't take one — it is stored SQL with no window of its own — so it is
+ built without it and its consumers filter it themselves.
"""
- jobs = workflow_jobs.build_query(jobs_table)
+ jobs = workflow_jobs.build_query(jobs_table, created_floor=created_floor)
runs = workflow_runs.build_query(runs_table)
# labels is already ifNull'd to '[]' by the jobs builder; JSONExtract to Array(String) yields
# [] for any non-array/invalid JSON, matching cost._parse_labels' empty-on-bad-input behavior.
labels_array = "JSONExtract(labels, 'Array(String)')"
+ billed_seconds = render_billed_elapsed_seconds("j.duration_seconds", "j.provisioning_seconds")
inner_run_columns = _run_passthrough_defs() if include_run_columns else ""
run_columns = _run_passthrough_aliases() if include_run_columns else ""
@@ -152,9 +195,10 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
os,
vcpu,
{render_multiplier("vcpu")} AS multiplier,
- {render_billable_seconds("provider", "os", "duration_seconds")} AS billable_seconds,
- {render_estimated_cost_usd("provider", "os", "vcpu", "duration_seconds")} AS estimated_cost_usd,
- is_merge_queue{run_columns}
+ {render_billable_seconds("provider", "os", "is_rerun_copy", "billed_seconds")} AS billable_seconds,
+ {render_estimated_cost_usd("provider", "os", "vcpu", "is_rerun_copy", "billed_seconds")} AS estimated_cost_usd,
+ is_merge_queue,
+ is_rerun_copy{run_columns}
FROM (
SELECT
repo_owner,
@@ -173,7 +217,9 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
completed_at,
queue_seconds,
duration_seconds,
+ billed_seconds,
is_merge_queue,
+ is_rerun_copy,
{render_provider("depot_label", "hosted_label")} AS provider,
{render_os("depot_label", "hosted_label")} AS os,
{render_vcpu("depot_label", "hosted_label")} AS vcpu{run_columns}
@@ -195,7 +241,9 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
completed_at,
queue_seconds,
duration_seconds,
+ billed_seconds,
is_merge_queue,
+ is_rerun_copy,
{render_depot_label("labels_arr")} AS depot_label,
{render_hosted_label("labels_arr")} AS hosted_label{run_columns}
FROM (
@@ -218,10 +266,14 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
j.completed_at AS completed_at,
j.queue_seconds AS queue_seconds,
j.duration_seconds AS duration_seconds,
+ -- What Depot actually bills: the wall-clock minus the runner boot GitHub
+ -- stamps into it. duration_seconds stays the full window for queue/duration UX.
+ {billed_seconds} AS billed_seconds,
r.is_merge_queue AS is_merge_queue,
+ j.is_rerun_copy AS is_rerun_copy,
{labels_array} AS labels_arr{inner_run_columns}
FROM ({jobs}) AS j
- LEFT JOIN ({runs}) AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt
+ LEFT JOIN ({runs}) AS r ON j.run_id = r.id
)
)
)
diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
index 5a0916fc7d0d..72a58ceeb5c5 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
@@ -7,20 +7,75 @@ runner-tier JSON the cost model parses) is unwrapped from its Nullable column. `
back to ``github_workflow_runs``. The source table name is resolved per-team and passed in (see
``logic.sources``); it is never hardcoded.
-Same two-layer shape as ``workflow_runs``: the inner SELECT parses timestamps with
+Same layered shape as ``workflow_runs``: the inner SELECT parses timestamps with
``parseDateTimeBestEffortOrNull`` (a queued/running job has no start/finish) and unwraps Nullable
-JSON with ``ifNull``; the outer SELECT derives the duration off the parsed columns.
+JSON with ``ifNull``; the outer SELECT derives the durations and the copy flag off the parsed columns.
+
+**``provisioning_seconds`` — the VM boot Depot does not bill.** GitHub stamps a job's ``started_at``
+the moment Depot accepts it, but the machine then boots before the first step ("Set up job") runs, and
+Depot bills only the time after the job started running, not provisioning. The gap is the job's
+``started_at`` to its first step's ``started_at`` — tens of seconds per job, a few percent of billed
+minutes at scale (the tail at the other end, last step to ``completed_at``, is negligible). NULL when the ``steps`` payload is missing or empty, which ``logic.cost`` reads as "don't
+correct" — an under-correction, never an over-correction. ``duration_seconds`` stays the full
+wall-clock, because that is what queue and duration UX is about; only cost reads this.
+
+**``is_rerun_copy`` — rows for jobs that never executed.** "Re-run failed jobs" re-lists every job
+that already passed under the new ``run_attempt``: new job ids, but ``started_at`` / ``completed_at``
+copied verbatim from the attempt that actually ran (a partial re-run of a large matrix re-lists every
+passed job and re-runs only the failed ones; GitHub's ``filter=latest`` returns the re-listings too, so
+the source can't drop them). Those rows are re-listings, not executions — nothing ran and Depot billed
+nothing — and they are a few percent of job rows and minutes. A row is a copy when the same
+``(run_id, name, started_at, completed_at)`` exists at a LOWER ``run_attempt``, which is the window
+below. Consumers counting executions (cost, retry pressure, duration percentiles) must exclude them;
+the flag is defined here so nobody re-derives it.
The raw ``created_at`` string rides along as ``created_at_raw`` (unparsed) because ISO-8601 strings
compare correctly lexicographically. A parsed-column predicate never pushes down to the parquet/S3
scan, so a raw-column floor (``created_at_raw >= '<date>'``) is the only windowing predicate the scan
can prune on — the parsed ``created_at`` stays the precise filter, the raw twin lets the scan skip.
+A caller's own outer ``created_at_raw`` predicate no longer prunes, though: it sits above the
+``is_rerun_copy`` window, and ClickHouse can only push a filter below a window step when it reads
+partition-by columns. Windowed callers therefore pass ``created_floor=True``, which puts the same
+coarse floor in an innermost prefilter on the RAW column — below the window, where the scan can still
+use it — and register the ``{job_created_floor}`` placeholder (see ``run_started_floor_constant``,
+shared with the runs builder). The trade is exact: a run whose earlier attempt falls below the floor
+loses the evidence that its later attempt is a copy, so a boundary re-run reads as billable — the same
+coarseness the floor already has, and why the floor sits a day below the window.
Embedded as a subquery by the jobs query module (see ``_curated``); nothing registers a global view.
"""
+# The moment the job actually began running: the first entry of the ``steps`` JSON array. ``steps`` is
+# a Nullable JSON string, and ClickHouse rejects an Array nested inside a Nullable, so it is
+# ``ifNull``-unwrapped before ``JSONExtractArrayRaw`` (``toString`` keeps this correct if the pipeline
+# ever lands the column as a JSON type rather than a String). An empty array yields '' from
+# ``arrayElement``, which extracts to '' and parses to NULL — the "steps not synced" fallback.
+_FIRST_STEP_STARTED_AT = (
+ "parseDateTimeBestEffort("
+ "JSONExtractString(arrayElement(JSONExtractArrayRaw(ifNull(toString(steps), '[]')), 1), 'started_at')"
+ ")"
+)
+
+# A row GitHub re-listed under a later attempt without re-running it (see the module docstring): the
+# same run, job name, and exact start/finish already exist at a lower attempt. Both timestamps must be
+# present — two still-queued attempts of the same job both carry NULL and are not copies of each other.
+_IS_RERUN_COPY = """ifNull(
+ started_at IS NOT NULL
+ AND completed_at IS NOT NULL
+ AND run_attempt > min(run_attempt) OVER (
+ PARTITION BY run_id, name, started_at, completed_at
+ ),
+ 0
+ )"""
+
-def build_query(table_name: str) -> str:
+def build_query(table_name: str, *, created_floor: bool = False) -> str:
+ # The floor must live in its OWN innermost SELECT on the raw string column, like the runs
+ # builder's: the parsing SELECT below aliases parseDateTimeBestEffort(created_at) AS created_at,
+ # so a WHERE there would compare the parsed DateTime against the floor string.
+ table_source = (
+ f"(SELECT * FROM {table_name} WHERE created_at >= {{job_created_floor}})" if created_floor else table_name
+ )
return f"""
SELECT
id,
@@ -40,7 +95,15 @@ def build_query(table_name: str) -> str:
completed_at,
if(status = 'completed', dateDiff('second', started_at, completed_at), NULL) AS duration_seconds,
-- Queue wait: webhook creation to first execution. NULL while still queued.
- if(started_at IS NOT NULL, dateDiff('second', created_at, started_at), NULL) AS queue_seconds
+ if(started_at IS NOT NULL, dateDiff('second', created_at, started_at), NULL) AS queue_seconds,
+ -- Runner boot: the job's start to its first step's start. NULL when steps aren't synced;
+ -- clamped so a skewed pair can never hand the cost model a negative correction.
+ if(
+ started_at IS NOT NULL AND first_step_started_at IS NOT NULL,
+ greatest(dateDiff('second', started_at, first_step_started_at), 0),
+ NULL
+ ) AS provisioning_seconds,
+ {_IS_RERUN_COPY} AS is_rerun_copy
FROM (
SELECT
id,
@@ -59,7 +122,8 @@ def build_query(table_name: str) -> str:
parseDateTimeBestEffort(created_at) AS created_at,
created_at_raw,
parseDateTimeBestEffort(started_at) AS started_at,
- parseDateTimeBestEffort(completed_at) AS completed_at
- FROM (SELECT *, created_at AS created_at_raw FROM {table_name})
+ parseDateTimeBestEffort(completed_at) AS completed_at,
+ {_FIRST_STEP_STARTED_AT} AS first_step_started_at
+ FROM (SELECT *, created_at AS created_at_raw FROM {table_source})
)
"""
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index 22a82084aedd..d94717670d15 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -104,10 +104,19 @@ def _job_row(
*,
run_attempt: int = 1,
labels: str = '["depot-ubuntu-22.04-4"]',
- started: str = "2026-01-01 00:00:00",
- completed: str = "2026-01-01 00:02:00",
+ started: str | None = None,
+ completed: str | None = None,
head_branch: str = "main",
) -> dict[str, Any]:
+ # Default to the same relative anchor the seeded runs use, not a fixed calendar date. GitHub
+ # creates a job when its run attempt starts, so a job's created_at tracks its run's start — and
+ # the cost queries' jobs-scan floor is derived from exactly that relationship (see
+ # _workflow_filters.run_windowed_job_created_floor_constant). Jobs pinned to 2026-01-01 under runs
+ # seeded at _ago(n) modelled a shape the source cannot produce, and the floor rightly dropped them.
+ # Keeps the 2-minute duration the cost assertions are written against.
+ default_started, default_completed = _ago_with_duration(1, 120)
+ started = started if started is not None else default_started
+ completed = completed if completed is not None else default_completed
return {
"id": job_id,
"run_id": run_id,
diff --git a/products/engineering_analytics/backend/tests/test_cost.py b/products/engineering_analytics/backend/tests/test_cost.py
index 139a556a084d..c0e98392a25f 100644
--- a/products/engineering_analytics/backend/tests/test_cost.py
+++ b/products/engineering_analytics/backend/tests/test_cost.py
@@ -7,6 +7,7 @@ from products.engineering_analytics.backend.logic.cost import (
RunnerOS,
RunnerProvider,
RunnerTier,
+ billed_elapsed_seconds,
billing_multiplier,
classify_runner,
estimate_job_cost_usd,
@@ -90,6 +91,41 @@ class TestCostModel:
def test_estimate_job_cost_is_none_when_not_depot_billed(self, _name, labels, elapsed):
assert estimate_job_cost_usd(labels, elapsed) is None
+ @parameterized.expand(
+ [
+ # Depot doesn't bill the runner boot GitHub stamps into started_at.
+ ("provisioning_subtracted", 600, 23, 577),
+ # No steps payload -> nothing to subtract, so the wall-clock stands (under-correct, never over).
+ ("no_steps_keeps_wall_clock", 600, None, 600),
+ # Clock skew can't hand the rate a negative.
+ ("clamped_at_zero", 10, 25, 0),
+ ]
+ )
+ def test_billed_elapsed_seconds(self, _name, elapsed, provisioning, expected):
+ assert billed_elapsed_seconds(elapsed, provisioning) == expected
+
+ def test_billed_elapsed_seconds_is_none_for_unknown_elapsed(self):
+ # An unsettled job has no elapsed to bill — None, never a measured 0 that would cost $0.00.
+ assert billed_elapsed_seconds(None, 23) is None
+
+ def test_estimate_job_cost_uses_the_billed_elapsed(self):
+ # The provisioning seconds must never reach the rate: a 10-minute job that spent 23s booting
+ # costs 577s, not 600s, worth of Depot minutes.
+ labels = ["depot-ubuntu-latest"]
+ billed = billed_elapsed_seconds(600, 23)
+ cost_billed = estimate_job_cost_usd(labels, billed)
+ cost_wall_clock = estimate_job_cost_usd(labels, 600)
+ assert cost_billed is not None and cost_wall_clock is not None
+ assert cost_billed == pytest.approx(577 / 60 * REFERENCE_RATE_USD_PER_MIN)
+ assert cost_billed < cost_wall_clock
+
+ def test_estimate_job_cost_is_none_for_a_rerun_copy(self):
+ # GitHub re-lists an already-passed job under the next run_attempt with the earlier attempt's
+ # timestamps. Nothing ran, so there are no minutes to bill — None, not the elapsed-derived
+ # figure the same labels and duration would otherwise produce.
+ assert estimate_job_cost_usd(["depot-ubuntu-latest"], 600) is not None
+ assert estimate_job_cost_usd(["depot-ubuntu-latest"], 600, is_rerun_copy=True) is None
+
def test_estimate_job_cost_is_none_for_unknown_elapsed(self):
# A queued / not-yet-started Depot job has no elapsed time: report None ("cost unknown"),
# never 0.0 — so a consumer never shows a pending job as $0.00.
diff --git a/products/engineering_analytics/backend/tests/test_job_costs.py b/products/engineering_analytics/backend/tests/test_job_costs.py
index b5e00df348f8..f69c7edcbe6c 100644
--- a/products/engineering_analytics/backend/tests/test_job_costs.py
+++ b/products/engineering_analytics/backend/tests/test_job_costs.py
@@ -13,6 +13,7 @@ from posthog.hogql.query import execute_hogql_query
from products.engineering_analytics.backend.logic.cost import (
RunnerOS,
RunnerProvider,
+ billed_elapsed_seconds,
billing_multiplier,
classify_runner,
estimate_job_cost_usd,
@@ -22,14 +23,20 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
-from products.engineering_analytics.backend.tests._github_fixtures import seeding_object_storage
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ pr_association_entry,
+ repo_id,
+ seeding_object_storage,
+)
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.job_costs"
GITHUB_SOURCE_PREFIX = "myprefix"
# The classification matrix: (scenario, labels, started_at, completed_at, status). The view derives
-# cost from labels + elapsed only, so every row exercises a distinct classify_runner / cost branch.
+# cost from labels + the billed elapsed only, so every row exercises a distinct classify_runner / cost
+# branch. None of these rows carry a steps payload, so their billed elapsed IS the wall-clock; the
+# first-step correction has its own test below.
# Expected values are computed from the Python model in the test, so a row fails only on Python↔SQL
# drift — exactly the regression this guards.
_BASE = "2026-01-01 10:00:00"
@@ -64,19 +71,30 @@ def _elapsed_seconds(started: str, completed: str | None, status: str) -> int |
return int((pd.Timestamp(completed) - pd.Timestamp(started)).total_seconds())
-def _expected_billable(labels: list[str], elapsed: int | None) -> int | None:
+def _expected_billable(labels: list[str], elapsed: float | None) -> float | None:
tier = classify_runner(labels)
if tier is None or tier.provider is not RunnerProvider.DEPOT or tier.os is not RunnerOS.LINUX or elapsed is None:
return None
return max(elapsed, 0)
-def _job_row(job_id: int, labels: list[str], started: str, completed: str | None, status: str) -> dict[str, Any]:
+def _job_row(
+ job_id: int,
+ labels: list[str],
+ started: str | None,
+ completed: str | None,
+ status: str,
+ *,
+ run_id: int | None = None,
+ run_attempt: int = 1,
+ name: str | None = None,
+ steps: str = "[]",
+) -> dict[str, Any]:
return {
"id": job_id,
- "run_id": 9000 + job_id,
- "run_attempt": 1,
- "name": f"job-{job_id}",
+ "run_id": run_id if run_id is not None else 9000 + job_id,
+ "run_attempt": run_attempt,
+ "name": name if name is not None else f"job-{job_id}",
"workflow_name": "CI",
"status": status,
"conclusion": "success" if status == "completed" else None,
@@ -88,7 +106,29 @@ def _job_row(job_id: int, labels: list[str], started: str, completed: str | None
"created_at": started,
"started_at": started,
"completed_at": completed,
- "steps": "[]",
+ "steps": steps,
+ }
+
+
+_REPO = "PostHog/posthog"
+
+
+def _run_row(run_id: int, *, run_attempt: int, pr_number: int) -> dict[str, Any]:
+ """One runs-snapshot row. The snapshot upserts by id, so a re-run leaves ONLY the newest
+ attempt's row — which is what the jobs↔runs join has to cope with."""
+ return dict.fromkeys(WORKFLOW_RUNS_COLUMNS) | {
+ "id": run_id,
+ "name": "CI",
+ "head_sha": "sha-head",
+ "head_branch": "feature-branch",
+ "status": "completed",
+ "conclusion": "failure",
+ "created_at": _BASE,
+ "run_started_at": _BASE,
+ "updated_at": _plus(1000),
+ "run_attempt": run_attempt,
+ "pull_requests": json.dumps([pr_association_entry(pr_number, base_repo=_REPO)]),
+ "repository": json.dumps({"full_name": _REPO, "id": repo_id(_REPO)}),
}
@@ -154,7 +194,9 @@ class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
by_job = {row[0]: row for row in rows}
for index, (scenario, labels, started, completed, status) in enumerate(_MATRIX):
- elapsed = _elapsed_seconds(started, completed, status)
+ # No steps in these fixtures -> nothing to subtract. Routed through the model anyway, so
+ # the assertion states the billed clock rather than assuming it equals the wall-clock.
+ billed = billed_elapsed_seconds(_elapsed_seconds(started, completed, status), None)
tier = classify_runner(labels)
_job_name, provider, os_, vcpu, multiplier, billable, cost = by_job[f"job-{index}"]
@@ -162,10 +204,161 @@ class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
assert os_ == (tier.os.value if tier else None), scenario
assert vcpu == (tier.vcpu if tier else None), scenario
assert multiplier == (billing_multiplier(tier) if tier else None), scenario
- assert billable == _expected_billable(labels, elapsed), scenario
+ assert billable == _expected_billable(labels, billed), scenario
- expected_cost = estimate_job_cost_usd(labels, elapsed)
+ expected_cost = estimate_job_cost_usd(labels, billed)
if expected_cost is None:
assert cost is None, scenario
else:
assert cost == pytest.approx(expected_cost), scenario
+
+ def test_cost_is_billed_from_the_first_step_not_from_started_at(self) -> None:
+ # GitHub stamps started_at when Depot accepts the job; the machine boots for ~23s before the
+ # first step runs, and Depot doesn't bill provisioning. So a 10-minute job whose steps show it
+ # started running at +23s must cost 577s, not 600s — while duration_seconds stays the full
+ # window GitHub reports. Without the steps payload nothing is subtracted.
+ labels = ["depot-ubuntu-latest"]
+ steps = json.dumps(
+ [
+ {"name": "Set up job", "started_at": _plus(23), "completed_at": _plus(30)},
+ {"name": "Run tests", "started_at": _plus(30), "completed_at": _plus(600)},
+ ]
+ )
+ jobs_table = self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(1, labels, _BASE, _plus(600), "completed", name="with-steps", steps=steps),
+ _job_row(2, labels, _BASE, _plus(600), "completed", name="no-steps"),
+ ],
+ )
+ runs_table = self._create_table(
+ "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [dict.fromkeys(WORKFLOW_RUNS_COLUMNS)]
+ )
+
+ sql = (
+ "SELECT job_name, duration_seconds, billable_seconds, estimated_cost_usd "
+ f"FROM ({job_costs.build_query(jobs_table=jobs_table, runs_table=runs_table)}) ORDER BY job_name"
+ )
+ rows = execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results
+ by_job = {row[0]: row for row in rows}
+
+ _name, duration, billable, cost = by_job["with-steps"]
+ assert duration == 600
+ assert billable == billed_elapsed_seconds(600, 23) == 577
+ assert cost == pytest.approx(estimate_job_cost_usd(labels, 577))
+
+ _name, duration, billable, cost = by_job["no-steps"]
+ assert duration == 600
+ assert billable == billed_elapsed_seconds(600, None) == 600
+ assert cost == pytest.approx(estimate_job_cost_usd(labels, 600))
+
+ def test_earlier_attempt_jobs_keep_their_run_attribution(self) -> None:
+ # The runs snapshot upserts by id, so after a partial re-run only the attempt-2 run row
+ # exists. Joining on (run_id, run_attempt) left every attempt-1 job unjoined — NULL repo,
+ # NULL pr_number — which is exactly the population that actually executed: attempt 2 mostly
+ # re-lists it. That silently dropped those jobs from every repo-/PR-scoped cost aggregate.
+ # Joining on run_id alone attributes them, and the PR total must then be the two real
+ # executions (the passed job from attempt 1 + the genuine re-run), with no double count.
+ labels = ["depot-ubuntu-latest"]
+ run_id, pr_number = 8800, 42
+ jobs_table = self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(1, labels, _BASE, _plus(600), "completed", run_id=run_id, run_attempt=1, name="passed"),
+ _job_row(2, labels, _BASE, _plus(300), "completed", run_id=run_id, run_attempt=1, name="failed"),
+ # attempt 2: the passed job is re-listed verbatim, the failed one genuinely re-runs.
+ _job_row(3, labels, _BASE, _plus(600), "completed", run_id=run_id, run_attempt=2, name="passed"),
+ _job_row(4, labels, _plus(700), _plus(1000), "completed", run_id=run_id, run_attempt=2, name="failed"),
+ ],
+ )
+ # Only the newest attempt's run row — the snapshot shape the join has to survive.
+ runs_table = self._create_table(
+ "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [_run_row(run_id, run_attempt=2, pr_number=pr_number)]
+ )
+
+ sql = (
+ "SELECT job_name, run_attempt, repo_owner, repo_name, pr_number, is_rerun_copy, estimated_cost_usd "
+ f"FROM ({job_costs.build_query(jobs_table=jobs_table, runs_table=runs_table)}) "
+ "ORDER BY job_name, run_attempt"
+ )
+ rows = execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results
+ by_attempt = {(row[0], row[1]): row for row in rows}
+
+ # Every row is attributed, whichever attempt it belongs to — this is the regression.
+ for row in rows:
+ assert (row[2], row[3], row[4]) == ("PostHog", "posthog", pr_number), row[0]
+
+ # The attempt-1 job that really ran keeps its cost...
+ assert not by_attempt[("passed", 1)][5]
+ assert by_attempt[("passed", 1)][6] == pytest.approx(estimate_job_cost_usd(labels, 600))
+ # ...and its attempt-2 re-listing is attributed but costs nothing, so there's no double count.
+ assert by_attempt[("passed", 2)][5]
+ assert by_attempt[("passed", 2)][6] is None
+
+ # The PR's whole bill is the three executions that happened — the passed job once, the failed
+ # job twice (failing, then re-run) — and nothing else. Before the join fix the two attempt-1
+ # rows were unattributed and dropped from this PR-scoped scan, leaving only the re-run;
+ # counting the copy instead would put the passed job's minutes back under the wrong attempt.
+ passed_cost = estimate_job_cost_usd(labels, 600)
+ failed_cost = estimate_job_cost_usd(labels, 300)
+ assert passed_cost is not None and failed_cost is not None
+ total = sum(row[6] for row in rows if row[6] is not None)
+ assert total == pytest.approx(passed_cost + 2 * failed_cost)
+
+ def test_rerun_copies_are_flagged_and_not_costed(self) -> None:
+ # "Re-run failed jobs" on a run whose 'passed' job succeeded and whose 'failed' job did not:
+ # GitHub lists BOTH under attempt 2, but only 'failed' actually ran again — 'passed' is
+ # re-listed with a new id and attempt 1's exact timestamps. Costing that row bills minutes
+ # Depot never charged for. The two 'queued' rows guard the NULL trap: neither attempt has
+ # timestamps yet, and NULL == NULL inside a PARTITION BY, so they must not read as copies.
+ labels = ["depot-ubuntu-latest"]
+ run_id = 7700
+ jobs_table = self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(1, labels, _BASE, _plus(600), "completed", run_id=run_id, run_attempt=1, name="passed"),
+ _job_row(2, labels, _BASE, _plus(300), "completed", run_id=run_id, run_attempt=1, name="failed"),
+ # The re-listing: new job id, attempt 1's start and finish verbatim.
+ _job_row(3, labels, _BASE, _plus(600), "completed", run_id=run_id, run_attempt=2, name="passed"),
+ # The real re-run: same name, but it ran later, so it is not a copy.
+ _job_row(4, labels, _plus(700), _plus(1000), "completed", run_id=run_id, run_attempt=2, name="failed"),
+ _job_row(5, labels, None, None, "queued", run_id=run_id, run_attempt=1, name="queued"),
+ _job_row(6, labels, None, None, "queued", run_id=run_id, run_attempt=2, name="queued"),
+ ],
+ )
+ runs_table = self._create_table(
+ "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [dict.fromkeys(WORKFLOW_RUNS_COLUMNS)]
+ )
+
+ sql = (
+ "SELECT job_name, run_attempt, is_rerun_copy, duration_seconds, billable_seconds, estimated_cost_usd "
+ f"FROM ({job_costs.build_query(jobs_table=jobs_table, runs_table=runs_table)}) "
+ "ORDER BY job_name, run_attempt"
+ )
+ rows = execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results
+ by_attempt = {(row[0], row[1]): row for row in rows}
+
+ # Every attempt is still a row — the view's grain is unchanged, the copy is only flagged.
+ assert len(rows) == 6
+
+ _n, _a, copy, duration, billable, cost = by_attempt[("passed", 2)]
+ assert copy
+ # The wall-clock duration stays honest (it is what GitHub reports); only the money is dropped.
+ assert duration == 600
+ assert billable is None
+ assert cost is None
+
+ for key in (("passed", 1), ("failed", 1), ("failed", 2)):
+ _n, _a, copy, _duration, billable, cost = by_attempt[key]
+ assert not copy, key
+ assert billable == _expected_billable(labels, 600 if key == ("passed", 1) else 300), key
+ assert cost == pytest.approx(estimate_job_cost_usd(labels, billable)), key
+
+ for key in (("queued", 1), ("queued", 2)):
+ _n, _a, copy, duration, billable, cost = by_attempt[key]
+ assert not copy, key
+ # Unsettled, not a copy: no elapsed, so no cost — never a $0.00.
+ assert duration is None and billable is None and cost is None, key