:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ci): weekly digest reports depot spend in dollars (#127463)
Raúl Negrón-Otero3d44fb868760
diff --git a/.github/scripts/eng-analytics-weekly-digest.mjs b/.github/scripts/eng-analytics-weekly-digest.mjsindex 0d9d22bfebb1..8c28c02b43a2 100644--- a/.github/scripts/eng-analytics-weekly-digest.mjs+++ b/.github/scripts/eng-analytics-weekly-digest.mjs@@ -1,47 +1,14 @@-// Weekly engineering-analytics CI digest, posted to #alerts-devex on Monday.-//-// PULL model: this script reads the engineering_analytics product's repo_overview-// endpoint (the same curated layer that backs its MCP tools and UI) ONCE for the-// last 7 complete UTC days — every headline ships with its equal-length previous-window twin,-// so one call carries the whole week-over-week table — and relays it to Slack. It-// asks for headlines only (include_series=false; the chart series exist for the-// UI) and does NOT re-derive any metric from the GitHub API — the product owns-// the numbers, this owns the cadence + the Slack relay.-//-// GHA cron ──> GET /api/projects/:id/engineering_analytics/repo_overview/ ──> Slack-//-// One native-table message (Block Kit `table`), one row per metric, each with its WoW delta:-// - CI minutes: billable (self-hosted) compute minutes across the whole bill,-// master and scheduled runs included.-// - └ merge queue: the slice of CI minutes spent on merge-queue batch branches-// (trunk-merge/**) — broken out so queue-settings changes get their own delta.-// - └ Depot CI: the slice of CI minutes that ran on the Depot CI engine. Depot does not count-// these against the contract's GitHub Actions minutes, so a move to Depot CI lowers the-// contract rows below without lowering this one.-// - min / merged PR: the same bill divided by the week's merged-PR count (bots-// included — the merge population that triggered the spend).-// - est. Depot $: the product's tier-laddered estimate of that spend.-// - ready→merge median: time from ready-for-review to merge, bots/drafts excluded-// upstream. Falls back to the coarse open→merge median (draft + ready fused, and-// labelled as such) when the draft/ready transitions aren't synced.-// - re-run cycles: runs with run_attempt > 1 — the waste driver behind minutes.-// - Depot runner min, all repos: the minutes Depot billed for GitHub Actions jobs in the whole-// organization, read from Depot's usage API. Depot counts these against the contract. Depot CI-// minutes are not part of that count. A sentence under the table says when the contract-// minutes run out at the reported week's rate. Both are left out when the API cannot be read.-//-// Data caveat: the runs/jobs warehouse tables are webhook-fed and do not backfill-// a missed window, so a webhook outage undercounts the count-based rows (minutes,-// $, re-runs) and the WoW delta absorbs the hole. The PR-snapshot rows (merge-// count, cycle-time median) are robust to gaps.+// Weekly CI digest for #alerts-devex. It compares the last 7 complete UTC days with the 7 days before.+// Spend covers every repository in the organization. Runner and container build minutes come from+// Depot's usage API. Depot CI comes from the depot_ci_usage endpoint, which counts only repositories+// with a synced Depot source. Cache storage is not counted.import { pathToFileURL } from 'node:url'const HOST = (process.env.POSTHOG_HOST || 'https://us.posthog.com').replace(/\/$/, '')const PROJECT_ID = process.env.POSTHOG_PROJECT_ID || ''const API_KEY = process.env.POSTHOG_API_KEY || ''-// Pin the source when the project has more than one connected GitHub source; otherwise-// the endpoints default to the oldest, which may not be the repo you mean.+// Pins the GitHub source when the project has more than one. Otherwise the oldest one answers.const SOURCE_ID = process.env.ENG_ANALYTICS_SOURCE_ID || ''const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN || ''const SLACK_CHANNEL = process.env.SLACK_CHANNEL || 'C0AS64N6DJL' // #alerts-devex@@ -49,23 +16,34 @@ const DRY_RUN = ['1', 'true', 'yes'].includes((process.env.DRY_RUN || '').toLoweconst GITHUB_SERVER_URL = process.env.GITHUB_SERVER_URL || 'https://github.com'const GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY || ''-// 'owner/repo/.github/workflows/x.yml@refs/heads/master' — set by Actions on every run,-// so the digest's self-link survives a rename of this workflow file.+// 'owner/repo/.github/workflows/x.yml@refs/heads/master'. Actions sets it, so the edit link survives a rename.const GITHUB_WORKFLOW_REF = process.env.GITHUB_WORKFLOW_REF || ''const GITHUB_REF_NAME = process.env.GITHUB_REF_NAME || 'master'-// The Depot contract terms come from repository variables, so a renewal needs no code change.const DEPOT_TOKEN = process.env.DEPOT_TOKEN || ''-const DEPOT_CONTRACT_MINUTES = Number(process.env.DEPOT_CONTRACT_MINUTES || 0)+const DEPOT_CONTRACT_USD = Number(process.env.DEPOT_CONTRACT_USD || 0)const DEPOT_CONTRACT_START = process.env.DEPOT_CONTRACT_START || ''const DEPOT_CONTRACT_END = process.env.DEPOT_CONTRACT_END || ''+// The depot_ci_usage endpoint prices Depot CI.+const RUNNER_USD_PER_MINUTE = 0.004+const BUILD_USD_PER_MINUTE = 0.04+const DAY_MS = 24 * 60 * 60 * 1000const WEEK_MS = 7 * DAY_MS-// Minutes Depot billed for GitHub Actions jobs in every repository of the organization. Depot counts-// these minutes against the contract, and its billing page shows their sum from the contract start.-async function depotBilledMinutes(startAt, endAt) {+function billedMinutes(entry) {+ // Protobuf JSON omits a field at its zero default.+ const minutes = entry?.minutesBilled ?? 0+ if (!Number.isFinite(minutes) || minutes < 0) {+ throw new Error('Depot GetUsage returned invalid billed minutes')+ }+ return minutes+}++async function depotUsageSpend(startAt, endAt) {+ // Error messages are fixed text, because they reach the public Actions log and Depot's responses+ // carry billing data.const res = await fetch('https://api.depot.dev/depot.core.v1.UsageService/GetUsage', {method: 'POST',headers: {@@ -75,116 +53,151 @@ async function depotBilledMinutes(startAt, endAt) {},body: JSON.stringify({ startAt: startAt.toISOString(), endAt: endAt.toISOString() }),signal: AbortSignal.timeout(60_000),- })- if (!res.ok) {- // The response body stays out of the message, because the message goes to the public Actions log.- throw new Error(`Depot GetUsage -> ${res.status}`)+ }).catch(() => null)+ if (!res?.ok) {+ throw Object.assign(new Error(`Depot GetUsage failed${res ? ` with ${res.status}` : ''}`), {+ retryable: !res || res.status >= 500 || res.status === 429,+ })}- const usage = await res.json()- // Protobuf JSON omits empty repeated fields.+ const usage = await res.json().catch(() => null)const jobs = usage?.githubActionsJobs ?? []- if (!usage || typeof usage !== 'object' || Array.isArray(usage) || !Array.isArray(jobs)) {+ const builds = usage?.containerBuild ?? []+ if (!usage || typeof usage !== 'object' || !Array.isArray(jobs) || !Array.isArray(builds)) {throw new Error('Depot GetUsage returned invalid usage')}- return jobs.reduce((sum, repo) => {- // Protobuf JSON omits scalar fields at their zero default.- const minutes = repo?.total?.minutesBilled ?? 0- if (!repo?.total || !Number.isFinite(minutes) || minutes < 0 || !Number.isFinite(sum + minutes)) {- throw new Error('Depot GetUsage returned invalid billed minutes')+ let runners = 0+ let repoRunners = 0+ for (const repo of jobs) {+ const usd = billedMinutes(repo?.total) * RUNNER_USD_PER_MINUTE+ runners += usd+ if (isThisRepository(repo?.repo)) {+ repoRunners += usd}- return sum + minutes- }, 0)+ }+ const containerBuilds = builds.reduce((sum, project) => sum + billedMinutes(project) * BUILD_USD_PER_MINUTE, 0)+ return { runners, repoRunners, containerBuilds }+}++async function depotCiSpend(startAt, endAt) {+ const usage = await withRetry(() =>+ api('depot_ci_usage', { date_from: startAt.toISOString(), date_to: endAt.toISOString() })+ )+ if (!Array.isArray(usage) || usage.some((repo) => !Number.isFinite(repo?.estimated_cost_usd))) {+ throw new Error('depot_ci_usage returned invalid usage')+ }+ const sum = (repos) => repos.reduce((total, repo) => total + repo.estimated_cost_usd, 0)+ return {+ depotCi: sum(usage),+ repoDepotCi: sum(usage.filter((repo) => isThisRepository(repo.repo))),+ depotCiRepos: usage.map((repo) => repo.repo),+ }+}++function isThisRepository(name) {+ return typeof name === 'string' && name.toLowerCase() === GITHUB_REPOSITORY.toLowerCase()+}++async function spend(startAt, endAt) {+ const [usage, ci] = await Promise.all([+ withRetry(() => depotUsageSpend(startAt, endAt)),+ depotCiSpend(startAt, endAt),+ ])+ return { ...usage, ...ci, total: usage.runners + ci.depotCi + usage.containerBuilds }+}++function contractDates(weekEnd) {+ const start = new Date(`${DEPOT_CONTRACT_START}T00:00:00Z`)+ const end = new Date(`${DEPOT_CONTRACT_END}T00:00:00Z`)+ const valid =+ Number.isFinite(DEPOT_CONTRACT_USD) &&+ DEPOT_CONTRACT_USD > 0 &&+ Number.isFinite(start.getTime()) &&+ Number.isFinite(end.getTime()) &&+ isoDay(start) === DEPOT_CONTRACT_START &&+ isoDay(end) === DEPOT_CONTRACT_END &&+ start < weekEnd &&+ end > weekEnd+ return valid ? { start, end } : null+}++function unavailable(what) {+ return (err) => {+ console.warn(`${what} unavailable: ${err.message}. Posting without it.`)+ return null+ }}-// Contract usage through the end of the reported week, or null when it cannot be read. The digest-// still posts without it, because the CI table does not depend on Depot's API.-async function depotContractUsage(weekStart, weekEnd) {- const contractStart = new Date(`${DEPOT_CONTRACT_START}T00:00:00Z`)- const contractEnd = new Date(`${DEPOT_CONTRACT_END}T00:00:00Z`)- if (- !DEPOT_TOKEN ||- !Number.isFinite(DEPOT_CONTRACT_MINUTES) ||- DEPOT_CONTRACT_MINUTES <= 0 ||- !Number.isFinite(contractStart.getTime()) ||- !Number.isFinite(contractEnd.getTime()) ||- isoDay(contractStart) !== DEPOT_CONTRACT_START ||- isoDay(contractEnd) !== DEPOT_CONTRACT_END ||- contractStart >= weekEnd ||- contractEnd <= weekEnd- ) {- console.warn('Depot token or active contract terms missing or invalid. Skipping the contract rows.')+// Null when either week cannot be read, because a partial total would mislead.+async function readSpend(weekStart, weekEnd) {+ if (!DEPOT_TOKEN) {+ console.warn('DEPOT_TOKEN not set. Posting without spend.')return null}- try {- const [used, lastWeek, priorWeek] = await Promise.all([- depotBilledMinutes(contractStart, weekEnd),- depotBilledMinutes(weekStart, weekEnd),- depotBilledMinutes(new Date(weekStart.getTime() - WEEK_MS), weekStart),- ])- return { used, lastWeek, priorWeek, contractEnd }- } catch {- // Fetch and parse errors can include response data in the public Actions log.- console.warn('Depot usage unavailable. Skipping the contract rows.')+ const contract = contractDates(weekEnd)+ if (!contract) {+ console.warn('Depot contract variables missing or invalid. Posting without the contract sentence.')+ }+ const [weeks, used] = await Promise.all([+ Promise.all([spend(weekStart, weekEnd), spend(new Date(weekStart.getTime() - WEEK_MS), weekStart)]).catch(+ unavailable('Spend')+ ),+ contract &&+ spend(contract.start, weekEnd)+ .then((contractSpend) => contractSpend.total)+ .catch(unavailable('Contract spend')),+ ])+ if (!weeks) {return null}+ const [lastWeek, priorWeek] = weeks+ return { lastWeek, priorWeek, contract: used == null ? null : { ...contract, used } }}function isoDay(date) {return date.toISOString().slice(0, 10)}-function contractSummary(contract, weekEnd) {- const used = `Depot contract: ${fmtMinutes(contract.used)} of ${fmtMinutes(DEPOT_CONTRACT_MINUTES)} GitHub Actions minutes used through ${isoDay(new Date(weekEnd.getTime() - DAY_MS))}. Depot CI minutes are not counted here.`- const remaining = DEPOT_CONTRACT_MINUTES - contract.used+function contractSummary(contract, weeklySpend, weekEnd) {+ const used = `Depot contract: ${fmtUsd(contract.used)} of ${fmtUsd(DEPOT_CONTRACT_USD)} used through ${isoDay(new Date(weekEnd.getTime() - DAY_MS))}, not counting cache storage.`+ const remaining = DEPOT_CONTRACT_USD - contract.usedif (remaining <= 0) {- return `${used} The contract minutes are used up.`+ return `${used} The contract is used up.`}- if (!(contract.lastWeek > 0)) {+ if (!(weeklySpend > 0)) {return used}- const remainingDays = remaining / (contract.lastWeek / 7)- const daysLeft = (contract.contractEnd.getTime() - weekEnd.getTime()) / DAY_MS- const contractEnd = isoDay(contract.contractEnd)+ const remainingDays = remaining / (weeklySpend / 7)+ const daysLeft = (contract.end.getTime() - weekEnd.getTime()) / DAY_MS+ const end = isoDay(contract.end)const daysShort = Math.round(daysLeft - remainingDays)if (daysShort <= 0) {- return `${used} At last week's rate they last until the contract ends on ${contractEnd}.`+ return `${used} At last week's spend it lasts until the contract ends on ${end}.`}const runOut = new Date(weekEnd.getTime() + remainingDays * DAY_MS)- return `${used} At last week's rate they run out around ${isoDay(runOut)}, ${daysShort} days before the contract ends on ${contractEnd}.`+ return `${used} At last week's spend it runs out around ${isoDay(runOut)}, ${daysShort} days before the contract ends on ${end}.`}-async function api(action, params = {}) {+async function api(action, params) {const url = new URL(`${HOST}/api/projects/${PROJECT_ID}/engineering_analytics/${action}/`)for (const [k, v] of Object.entries(params)) {- if (v !== undefined && v !== null && v !== '') {+ if (v) {url.searchParams.set(k, v)}}- if (SOURCE_ID) {- url.searchParams.set('source_id', SOURCE_ID)- }- // Bounds every attempt (the gateway answers within ~2min; this only catches a hung connection)- // so worst-case retries stay well inside the workflow's timeout-minutes.+ // Catches a hung connection. Every retry together stays inside the job's timeout-minutes.const res = await fetch(url, {headers: { Authorization: `Bearer ${API_KEY}` },signal: AbortSignal.timeout(150_000),})- const body = await res.text()- const fail = (detail, retryable) => {+ // A 4xx is a configuration error that a retry cannot fix.+ const retryable = res.ok || res.status >= 500 || res.status === 429+ const fail = (detail) => {throw Object.assign(new Error(`${action} -> ${res.status}: ${detail}`), { retryable })}- let parsed- try {- parsed = JSON.parse(body)- } catch {- // A non-JSON body (proxy interstitial, maintenance HTML) is still a failure whatever the- // status — the endpoint only speaks JSON — but it's infra noise, so always worth retrying.- fail(`non-JSON response (${body.slice(0, 120)})`, true)- }+ // The message never quotes the body, because depot_ci_usage returns billing data.+ const parsed = await res.json().catch(() => fail('non-JSON response'))if (!res.ok) {- // The endpoint 400s with a clear `detail` when no GitHub source is connected — a- // configuration error a retry can't fix; 5xx/429 are transients worth riding out.- fail(parsed?.detail || body, res.status >= 500 || res.status === 429)+ fail(typeof parsed?.detail === 'string' ? parsed.detail : 'request failed')}return parsed}@@ -192,18 +205,17 @@ async function api(action, params = {}) {const RETRY_ATTEMPTS = 3const RETRY_DELAY_MS = 30_000-// The warehouse queries share a ClickHouse cluster with everything else; a contended Monday-// morning can push one attempt past the API gateway's timeout. Ride transients out instead of-// failing the week's digest. Errors without a retryable flag (network failures, aborts) retry too.-async function apiWithRetry(action, params) {+// A busy ClickHouse cluster can push one attempt past the API gateway's timeout, and Depot's API+// returns an occasional 503.+async function withRetry(call) {for (let attempt = 1; ; attempt++) {try {- return await api(action, params)+ return await call()} catch (err) {if (err.retryable === false || attempt >= RETRY_ATTEMPTS) {throw err}- console.warn(`${err.message} — attempt ${attempt}/${RETRY_ATTEMPTS}, retrying in ${RETRY_DELAY_MS / 1000}s`)+ console.warn(`${err.message}. Attempt ${attempt}/${RETRY_ATTEMPTS}, retrying in ${RETRY_DELAY_MS / 1000}s.`)await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))}}@@ -213,19 +225,11 @@ function fmtInt(n) {return Math.round(n).toLocaleString('en-US')}-// Minutes at CI-bill scale: M-notation from 100k up ('3.04M', '0.38M'), thousands-separated-// below. The low threshold keeps same-unit rows — CI minutes and its merge-queue slice — in one-// notation, while a near-zero slice still reads as a plain count instead of '0.00M'.-function fmtMinutes(minutes) {- return minutes >= 100_000 ? `${(minutes / 1_000_000).toFixed(2)}M` : fmtInt(minutes)-}--// Estimated dollars, no cents ('$13,160').function fmtUsd(amount) {return `$${fmtInt(amount)}`}-// PR-lifecycle durations: seconds → '3d4h' / '7h55m' / '42m'.+// Seconds as '3d4h', '7h55m' or '42m'.function fmtLongDuration(seconds) {const totalMinutes = Math.round(seconds / 60)const d = Math.floor(totalMinutes / 1440)@@ -240,15 +244,13 @@ function fmtLongDuration(seconds) {return `${m}m`}-// Signed one-decimal WoW delta: '+66.5%' / '-1.0%'. '+0.0%' covers the -0.0 rounding edge.-// A zero prior-week baseline (e.g. a clean week with no re-run cycles) has no finite-// percent, so 0->positive shows '+∞%' and 0->0 stays '+0.0%'.+// Signed change with one decimal: '+66.5%', '-1.0%'. A change from zero has no finite percent,+// so it reads '+∞%', and zero to zero reads '+0.0%'.function fmtDelta(current, previous) {if (previous === 0) {return current === 0 ? '+0.0%' : '+∞%'}- const pct = ((current - previous) / previous) * 100- let s = pct.toFixed(1)+ let s = (((current - previous) / previous) * 100).toFixed(1)if (s === '-0.0') {s = '0.0'}@@ -259,91 +261,95 @@ function cell(text) {return { type: 'raw_text', text }}-function metricRow(metric, curValue, prevValue, format) {- return [cell(metric), cell(format(curValue)), cell(format(prevValue)), cell(fmtDelta(curValue, prevValue))]-}+const HIDDEN = 'hidden in dry runs'-// One table row per metric, added only when both windows carry the value, so a-// not-yet-synced jobs source (null cost fields) or an old backend (no merged_pr_count)-// degrades to fewer rows instead of a broken message.-function tableRows(overview) {- const rows = []- const add = (metric, curValue, prevValue, format) => {- if (curValue == null || prevValue == null) {- return- }- rows.push(metricRow(metric, curValue, prevValue, format))+// Null when either week lacks the metric, so a source that is not synced yet gives a shorter table.+function compare(metric, current, previous, format) {+ if (current == null || previous == null) {+ return null}- // Null-propagating so `add`'s missing-value guard stays the only degradation path.- const perPr = (minutes, merges) => (minutes != null && merges ? minutes / merges : null)- add('CI minutes', overview.billable_minutes, overview.billable_minutes_prev, fmtMinutes)- add('└ merge queue', overview.merge_queue_billable_minutes, overview.merge_queue_billable_minutes_prev, fmtMinutes)- add('└ Depot CI', overview.depot_ci_billable_minutes, overview.depot_ci_billable_minutes_prev, fmtMinutes)- add(- 'min / merged PR',- perPr(overview.billable_minutes, overview.merged_pr_count),- perPr(overview.billable_minutes_prev, overview.merged_pr_count_prev),- fmtInt- )- add('est. Depot $', overview.estimated_cost_usd, overview.estimated_cost_usd_prev, fmtUsd)- // Cycle time reads ready→merge, which excludes time spent as a draft. Both windows have to carry- // it to compare like with like, so a repo without the issue-events sync (or a week that straddles- // its first sync) falls back to the coarse open→merge median, labelled as what it is.- const [cycleMetric, cycleCur, cyclePrev] =- overview.median_ready_to_merge_seconds != null && overview.median_ready_to_merge_seconds_prev != null- ? [- 'ready→merge median',- overview.median_ready_to_merge_seconds,- overview.median_ready_to_merge_seconds_prev,- ]- : ['open→merge median', overview.median_open_to_merge_seconds, overview.median_open_to_merge_seconds_prev]- add(cycleMetric, cycleCur, cyclePrev, fmtLongDuration)- add('re-run cycles', overview.rerun_cycles, overview.rerun_cycles_prev, fmtInt)- return rows+ return [metric, format(current), format(previous), fmtDelta(current, previous)]}-// Actions logs are public, so dry runs use placeholders for Depot's billing data.-function depotDigest(contract, weekEnd) {- const metric = 'Depot runner min, all repos'- if (DRY_RUN) {- return {- row: [cell(metric), ...Array(3).fill(cell('hidden in dry runs'))],- summary: 'Depot contract line hidden in dry runs.',- }- }- return {- row: metricRow(metric, contract.lastWeek, contract.priorWeek, fmtMinutes),- summary: contractSummary(contract, weekEnd),- }+function spendRows({ lastWeek: last, priorWeek: prior }, overview) {+ const perPr = (week, merges) => (merges ? (week.repoRunners + week.repoDepotCi) / merges : null)+ return [+ compare('Depot spend', last.total, prior.total, fmtUsd),+ compare('└ runners', last.runners, prior.runners, fmtUsd),+ compare('└ Depot CI', last.depotCi, prior.depotCi, fmtUsd),+ compare('└ container builds', last.containerBuilds, prior.containerBuilds, fmtUsd),+ compare(+ '$ / merged PR',+ perPr(last, overview.merged_pr_count),+ perPr(prior, overview.merged_pr_count_prev),+ fmtUsd+ ),+ ].filter(Boolean)+}++function tableRows(overview, weeks) {+ const spend = weeks ? spendRows(weeks, overview) : []+ // Both weeks need ready→merge to compare like with like. Otherwise the row shows open→merge.+ const ready = overview.median_ready_to_merge_seconds != null && overview.median_ready_to_merge_seconds_prev != null+ return [+ // Actions logs are public, so a dry run prints no spend.+ ...(DRY_RUN ? spend.map(([metric]) => [metric, HIDDEN, HIDDEN, HIDDEN]) : spend),+ compare('merged PRs', overview.merged_pr_count, overview.merged_pr_count_prev, fmtInt),+ compare(+ ready ? 'ready→merge median' : 'open→merge median',+ ready ? overview.median_ready_to_merge_seconds : overview.median_open_to_merge_seconds,+ ready ? overview.median_ready_to_merge_seconds_prev : overview.median_open_to_merge_seconds_prev,+ fmtLongDuration+ ),+ ]+ .filter(Boolean)+ .map((row) => row.map(cell))}-function buildBlocks(weekStart, weekEnd, rows, depotSummary) {+function buildBlocks(weekStart, weekEnd, rows, notes) {const lastDay = new Date(weekEnd.getTime() - DAY_MS)const blocks = [{type: 'section',- text: {- type: 'mrkdwn',- text: `*Weekly CI, ${isoDay(weekStart)} to ${isoDay(lastDay)} UTC* _(vs prior week)_`,- },+ text: { type: 'mrkdwn', text: `*Weekly CI, ${isoDay(weekStart)} to ${isoDay(lastDay)} UTC*` },},{type: 'table',column_settings: [{ align: 'left' }, { align: 'right' }, { align: 'right' }, { align: 'right' }],- rows: [[cell('metric'), cell('last week'), cell('prior week'), cell('Δ')], ...rows],+ rows: [[cell(''), cell('last week'), cell('week before'), cell('change')], ...rows],},]- if (depotSummary) {- blocks.push({ type: 'section', text: { type: 'mrkdwn', text: depotSummary } })+ for (const note of notes) {+ blocks.push({ type: 'section', text: { type: 'mrkdwn', text: note } })}const workflowPath = GITHUB_WORKFLOW_REF.split('@')[0].replace(`${GITHUB_REPOSITORY}/`, '')if (GITHUB_REPOSITORY && workflowPath) {const editUrl = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/edit/${GITHUB_REF_NAME}/${workflowPath}`- blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: `<${editUrl}|edit this workflow>` }] })+ blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: `<${editUrl}|Edit this workflow>` }] })}return blocks}+function spendNotes(weeks, weekEnd) {+ if (!weeks) {+ return []+ }+ const repos = weeks.lastWeek.depotCiRepos+ const notes = [+ repos.length+ ? `Depot CI counts ${repos.join(', ')}.`+ : 'Depot CI counts no repository, because no Depot source is synced.',+ ]+ if (weeks.contract) {+ notes.push(+ DRY_RUN+ ? `Depot contract sentence ${HIDDEN}.`+ : contractSummary(weeks.contract, weeks.lastWeek.total, weekEnd)+ )+ }+ return notes+}+async function postToSlack(blocks) {const res = await fetch('https://slack.com/api/chat.postMessage', {method: 'POST',@@ -363,44 +369,40 @@ async function postToSlack(blocks) {export async function main() {if (!PROJECT_ID || !API_KEY) {- // No-op (don't fail the scheduled run) until the project + read key are wired.- console.warn('POSTHOG_PROJECT_ID / POSTHOG_API_KEY not set — skipping digest. Wire them to enable.')+ // A scheduled run without these does nothing instead of failing every week.+ console.warn('POSTHOG_PROJECT_ID or POSTHOG_API_KEY not set. Skipping the digest.')return}- // The window ends at the last UTC midnight instead of at run time. The Depot job-attempts table- // syncs on a schedule and a job that is still running has no duration, so a window that ends at- // run time under-counts its last hours. Whole UTC days also match the days on Depot's usage page,- // which lets a reader reconcile the minutes against it.+ // The window ends at the last UTC midnight. Depot sources sync on a schedule and a running job has+ // no duration yet, so the hours before the run are incomplete. Whole UTC days also match Depot's+ // usage page, so a reader can check the figures there.const weekEnd = new Date()weekEnd.setUTCHours(0, 0, 0, 0)const weekStart = new Date(weekEnd.getTime() - WEEK_MS)- // One headline-only call: the endpoint bakes every metric's equal-length previous-window- // twin (prev = [date_from - 7d, date_from)) and the merged-PR counts into the same scans,- // so the rows share windows exactly without a second call.- const overview = await apiWithRetry('repo_overview', {- date_from: weekStart.toISOString(),- date_to: weekEnd.toISOString(),- include_series: 'false',- })- const rows = tableRows(overview)+ const [overview, weeks] = await Promise.all([+ // Every figure carries its value for the 7 days before date_from, so one call covers both weeks.+ withRetry(() =>+ api('repo_overview', {+ date_from: weekStart.toISOString(),+ date_to: weekEnd.toISOString(),+ include_series: 'false',+ source_id: SOURCE_ID,+ repo: GITHUB_REPOSITORY,+ })+ ),+ readSpend(weekStart, weekEnd),+ ])+ const rows = tableRows(overview, weeks)if (rows.length === 0) {- // Every metric was null (key valid but nothing synced). Fail the job so the- // breakage is visible instead of posting an empty table.- throw new Error('repo_overview returned no usable metrics — not posting. Check the connected source.')- }- const contract = await depotContractUsage(weekStart, weekEnd)- const depot = contract && depotDigest(contract, weekEnd)- if (depot) {- rows.push(depot.row)+ throw new Error('No figures to post. Check the GitHub and Depot sources and DEPOT_TOKEN.')}- const blocks = buildBlocks(weekStart, weekEnd, rows, depot?.summary)+ const blocks = buildBlocks(weekStart, weekEnd, rows, spendNotes(weeks, weekEnd))if (DRY_RUN) {console.info(JSON.stringify(blocks, null, 2))return}if (!SLACK_BOT_TOKEN) {- // Distinct from dry-run: a real run with no token is a misconfiguration, not a success.- throw new Error('SLACK_BOT_TOKEN not set on a non-dry run — refusing to silently skip.')+ throw new Error('SLACK_BOT_TOKEN not set on a run that should post.')}await postToSlack(blocks)console.info(`Posted weekly CI digest to ${SLACK_CHANNEL}.`)diff --git a/.github/scripts/eng-analytics-weekly-digest.test.mjs b/.github/scripts/eng-analytics-weekly-digest.test.mjsindex 7a88bb28b081..e0f78a18020f 100644--- a/.github/scripts/eng-analytics-weekly-digest.test.mjs+++ b/.github/scripts/eng-analytics-weekly-digest.test.mjs@@ -2,12 +2,12 @@ import assert from 'node:assert/strict'import { describe, it } from 'node:test'const OVERVIEW = {- billable_minutes: 700,- billable_minutes_prev: 350,- depot_ci_billable_minutes: 200,- depot_ci_billable_minutes_prev: 100,+ merged_pr_count: 100,+ merged_pr_count_prev: 70,+ median_ready_to_merge_seconds: 3600,+ median_ready_to_merge_seconds_prev: 7200,}-const CONTRACT_ENV = {+const ENV = {POSTHOG_HOST: 'https://example.com',POSTHOG_PROJECT_ID: '1',POSTHOG_API_KEY: 'fake-posthog-token',@@ -15,50 +15,73 @@ const CONTRACT_ENV = {SLACK_BOT_TOKEN: 'fake-slack-token',SLACK_CHANNEL: 'fake-channel',DEPOT_TOKEN: 'fake-depot-token',- DEPOT_CONTRACT_MINUTES: '10000',+ DEPOT_CONTRACT_USD: '60000',DEPOT_CONTRACT_START: '2026-01-01',DEPOT_CONTRACT_END: '2027-01-01',DRY_RUN: '',- GITHUB_REPOSITORY: '',+ GITHUB_REPOSITORY: 'PostHog/posthog',GITHUB_WORKFLOW_REF: '',}+const WEEK = '2026-09-28T00:00:00.000Z'+const PRIOR_WEEK = '2026-09-21T00:00:00.000Z'+const CONTRACT = '2026-01-01T00:00:00.000Z'+// Runners $600 ($400 in this repository), builds $400, Depot CI $1,100 ($1,000 here): $2,100.+// The week before: runners $200, builds $200, Depot CI $500: $900. The contract so far: $50,000.+const DEPOT_USAGE = {+ [WEEK]: {+ githubActionsJobs: [+ { repo: 'PostHog/posthog', total: { minutesBilled: 100_000 } },+ { repo: 'PostHog/other', total: { minutesBilled: 50_000 } },+ ],+ containerBuild: [{ minutesBilled: 10_000 }],+ },+ [PRIOR_WEEK]: {+ githubActionsJobs: [{ repo: 'PostHog/posthog', total: { minutesBilled: 50_000 } }],+ containerBuild: [{ minutesBilled: 5_000 }],+ },+ [CONTRACT]: {+ githubActionsJobs: [{ repo: 'PostHog/posthog', total: { minutesBilled: 10_000_000 } }],+ containerBuild: [{ minutesBilled: 100_000 }],+ },+}+const DEPOT_CI_USAGE = {+ [WEEK]: [+ { repo: 'posthog/posthog', estimated_cost_usd: 1000 },+ { repo: 'posthog/posthog-private', estimated_cost_usd: 100 },+ ],+ [PRIOR_WEEK]: [{ repo: 'posthog/posthog', estimated_cost_usd: 500 }],+ [CONTRACT]: [{ repo: 'posthog/posthog', estimated_cost_usd: 6000 }],+}let importCount = 0-async function runDigest(t, { env = {}, usage = [9000, 700, 350], overview = OVERVIEW } = {}) {- t.mock.timers.enable({ apis: ['Date'], now: new Date('2026-10-05T13:00:00Z') })- const settings = { ...CONTRACT_ENV, ...env }+async function runDigest(t, { env = {}, depotUsage = DEPOT_USAGE, depotCiUsage = DEPOT_CI_USAGE } = {}) {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: new Date('2026-10-05T13:00:00Z') })+ const settings = { ...ENV, ...env }const previousEnv = Object.fromEntries(Object.keys(settings).map((key) => [key, process.env[key]]))Object.assign(process.env, settings)const requests = []const logs = []let blocks- let usageIndex = 0t.mock.method(console, 'info', (message) => logs.push(message))t.mock.method(console, 'warn', (message) => logs.push(message))t.mock.method(globalThis, 'fetch', async (url, options) => {const href = String(url)requests.push({ url: href, ...options })if (href.startsWith('https://example.com/')) {- return Response.json(overview)+ const parsed = new URL(href)+ if (parsed.pathname.endsWith('/depot_ci_usage/')) {+ const usage = depotCiUsage[parsed.searchParams.get('date_from')]+ return usage instanceof Response ? usage : Response.json(usage)+ }+ return Response.json(OVERVIEW)}if (href.startsWith('https://api.depot.dev/')) {- const value = usage[usageIndex++]- if (value instanceof Error) {- throw value+ const answer = depotUsage[JSON.parse(options.body).startAt]+ const usage = Array.isArray(answer) ? answer.shift() : answer+ if (usage instanceof Error) {+ throw usage}- if (value instanceof Response) {- return value- }- return Response.json(- typeof value === 'number'- ? {- githubActionsJobs: [- { total: { minutesBilled: value / 2 } },- { total: { minutesBilled: value / 2 } },- ],- }- : value- )+ return usage instanceof Response ? usage : Response.json(usage)}assert.equal(href, 'https://slack.com/api/chat.postMessage')blocks = JSON.parse(options.body).blocks@@ -66,7 +89,15 @@ async function runDigest(t, { env = {}, usage = [9000, 700, 350], overview = OVE})try {const { main } = await import(`./eng-analytics-weekly-digest.mjs?test=${++importCount}`)- await main()+ let settled = false+ const run = main().finally(() => {+ settled = true+ })+ while (!settled) {+ await new Promise((resolve) => setImmediate(resolve))+ t.mock.timers.tick(30_000)+ }+ await runreturn { blocks, logs, requests }} finally {for (const [key, value] of Object.entries(previousEnv)) {@@ -79,90 +110,111 @@ async function runDigest(t, { env = {}, usage = [9000, 700, 350], overview = OVE}}-describe('weekly engineering analytics digest', () => {- it('uses complete UTC weeks and sums billed minutes across repositories', async (t) => {- const { blocks, requests } = await runDigest(t)- const overviewUrl = new URL(requests[0].url)- assert.equal(overviewUrl.searchParams.get('date_from'), '2026-09-28T00:00:00.000Z')- assert.equal(overviewUrl.searchParams.get('date_to'), '2026-10-05T00:00:00.000Z')- assert.equal(overviewUrl.searchParams.get('include_series'), 'false')- assert.match(blocks[0].text.text, /2026-09-28 to 2026-10-04 UTC/)- assert.deepEqual(- requests- .filter((request) => request.url.startsWith('https://api.depot.dev/'))- .map((request) => JSON.parse(request.body)),- [- { startAt: '2026-01-01T00:00:00.000Z', endAt: '2026-10-05T00:00:00.000Z' },- { startAt: '2026-09-28T00:00:00.000Z', endAt: '2026-10-05T00:00:00.000Z' },- { startAt: '2026-09-21T00:00:00.000Z', endAt: '2026-09-28T00:00:00.000Z' },- ]- )- assert.deepEqual(- blocks[1].rows.at(-1).map((cell) => cell.text),- ['Depot runner min, all repos', '700', '350', '+100.0%']- )- assert.match(blocks[2].text.text, /9,000 of 10,000/)- assert.match(blocks[2].text.text, /run out around 2026-10-15, 78 days before/)- })+function tableText(blocks) {+ return blocks[1].rows.slice(1).map((row) => row.map((cell) => cell.text))+}- for (const [name, usage, expected] of [- ['exhausted minutes', [10000, 700, 350], /The contract minutes are used up/],- ['zero usage', [9000, 0, 350], /minutes are not counted here\.$/],- ['omitted protobuf list', [9000, {}, 350], /minutes are not counted here\.$/],+describe('weekly engineering analytics digest', () => {+ for (const [name, override] of [+ ['', {}],[- 'omitted protobuf zero',- [9000, { githubActionsJobs: [{ total: {} }] }, 350],- /minutes are not counted here\.$/,+ ' after a transient Depot failure',+ { depotUsage: { ...DEPOT_USAGE, [WEEK]: [new Response('', { status: 503 }), DEPOT_USAGE[WEEK]] } },],]) {- it(`handles ${name} without breaking the digest`, async (t) => {- const { blocks } = await runDigest(t, { usage })- assert.match(blocks[2].text.text, expected)+ it(`reports Depot spend for complete UTC weeks and the contract${name}`, async (t) => {+ const { blocks, requests } = await runDigest(t, override)+ const overviewUrl = new URL(requests.find((request) => request.url.includes('/repo_overview/')).url)+ assert.equal(overviewUrl.searchParams.get('date_from'), WEEK)+ assert.equal(overviewUrl.searchParams.get('date_to'), '2026-10-05T00:00:00.000Z')+ assert.equal(overviewUrl.searchParams.get('repo'), 'PostHog/posthog')+ assert.match(blocks[0].text.text, /2026-09-28 to 2026-10-04 UTC/)+ assert.deepEqual(tableText(blocks), [+ ['Depot spend', '$2,100', '$900', '+133.3%'],+ ['└ runners', '$600', '$200', '+200.0%'],+ ['└ Depot CI', '$1,100', '$500', '+120.0%'],+ ['└ container builds', '$400', '$200', '+100.0%'],+ ['$ / merged PR', '$14', '$10', '+40.0%'],+ ['merged PRs', '100', '70', '+42.9%'],+ ['ready→merge median', '1h', '2h', '-50.0%'],+ ])+ assert.equal(blocks[2].text.text, 'Depot CI counts posthog/posthog, posthog/posthog-private.')+ assert.match(blocks[3].text.text, /\$50,000 of \$60,000 used through 2026-10-04/)+ assert.match(+ blocks[3].text.text,+ /runs out around 2026-11-07, 55 days before the contract ends on 2027-01-01\.$/+ )})}- for (const [name, env] of [- ['missing token', { DEPOT_TOKEN: '' }],- ['non-finite allowance', { DEPOT_CONTRACT_MINUTES: 'Infinity' }],- ['invalid calendar date', { DEPOT_CONTRACT_START: '2026-02-30' }],- ['future contract', { DEPOT_CONTRACT_START: '2026-10-06' }],- ['expired contract', { DEPOT_CONTRACT_END: '2026-10-04' }],+ for (const [name, allowance, expected] of [+ ['a used-up contract', '50000', /The contract is used up\.$/],+ ['a contract that lasts', '1000000', /it lasts until the contract ends on 2027-01-01\.$/],]) {- it(`posts the CI table without Depot data with ${name}`, async (t) => {- const { blocks, requests } = await runDigest(t, { env })- assert.equal(blocks.length, 2)- assert.equal(requests.length, 2)- assert.equal(blocks[1].rows[1][0].text, 'CI minutes')+ it(`describes ${name}`, async (t) => {+ const { blocks } = await runDigest(t, { env: { DEPOT_CONTRACT_USD: allowance } })+ assert.match(blocks[3].text.text, expected)})}- for (const [name, failedUsage] of [- ['HTTP failure', new Response('confidential-response', { status: 503 })],- ['invalid JSON', new Response('confidential-response')],- ['network failure', new Error('confidential-response')],- ['missing totals', { githubActionsJobs: [{}] }],- ['string minutes', { githubActionsJobs: [{ total: { minutesBilled: 'confidential-response' } }] }],- ['negative minutes', { githubActionsJobs: [{ total: { minutesBilled: -1 } }] }],- ['non-finite protobuf float', { githubActionsJobs: [{ total: { minutesBilled: 'Infinity' } }] }],+ for (const [name, override] of [+ ['the contract variables are missing', { env: { DEPOT_CONTRACT_USD: '' } }],+ [+ 'the contract read fails',+ {+ depotCiUsage: {+ ...DEPOT_CI_USAGE,+ [CONTRACT]: Response.json({ detail: 'Not found.' }, { status: 404 }),+ },+ },+ ],+ ]) {+ it(`posts spend without the contract sentence when ${name}`, async (t) => {+ const { blocks } = await runDigest(t, override)+ assert.equal(tableText(blocks)[0][0], 'Depot spend')+ assert.ok(blocks.every((block) => !block.text?.text.startsWith('Depot contract')))+ })+ }++ for (const [name, override] of [+ [+ 'a Depot HTTP failure',+ { depotUsage: { ...DEPOT_USAGE, [WEEK]: new Response('confidential-response', { status: 503 }) } },+ ],+ ['invalid Depot JSON', { depotUsage: { ...DEPOT_USAGE, [WEEK]: new Response('confidential-response') } }],+ ['a Depot network failure', { depotUsage: { ...DEPOT_USAGE, [WEEK]: new Error('confidential-response') } }],+ [+ 'negative Depot minutes',+ { depotUsage: { ...DEPOT_USAGE, [PRIOR_WEEK]: { githubActionsJobs: [{ total: { minutesBilled: -1 } }] } } },+ ],+ [+ 'a non-JSON depot_ci_usage response',+ {+ depotCiUsage: {+ ...DEPOT_CI_USAGE,+ [WEEK]: new Response('confidential-response', { status: 400 }),+ },+ },+ ],+ ['a missing token', { env: { DEPOT_TOKEN: '' } }],]) {- it(`omits unavailable Depot data and protects logs on ${name}`, async (t) => {- const { blocks, logs } = await runDigest(t, { usage: [failedUsage, 700, 350] })+ it(`posts without spend on ${name} and keeps Depot data out of the logs`, async (t) => {+ const { blocks, logs } = await runDigest(t, override)+ assert.deepEqual(+ tableText(blocks).map((row) => row[0]),+ ['merged PRs', 'ready→merge median']+ )assert.equal(blocks.length, 2)assert.doesNotMatch(JSON.stringify(logs), /confidential-response/)assert.ok(logs.length > 0)})}- it('hides Depot figures and never posts to Slack in a dry run', async (t) => {- const { blocks, logs, requests } = await runDigest(t, { env: { DRY_RUN: 'true' }, usage: [9876, 654, 321] })+ it('hides spend and never posts to Slack in a dry run', async (t) => {+ const { blocks, logs, requests } = await runDigest(t, { env: { DRY_RUN: 'true' } })assert.equal(blocks, undefined)assert.ok(requests.every((request) => !request.url.startsWith('https://slack.com/')))- assert.doesNotMatch(JSON.stringify(logs), /9876|9,876|654|321|10,000|2027-01-01/)+ assert.doesNotMatch(JSON.stringify(logs), /\$[0-9]|60,000|2027-01-01/)assert.match(logs[0], /hidden in dry runs/)})-- it('omits the Depot CI row until both backend windows are available', async (t) => {- const { blocks } = await runDigest(t, { overview: { ...OVERVIEW, depot_ci_billable_minutes_prev: null } })- assert.ok(blocks[1].rows.every((row) => row[0].text !== '└ Depot CI'))- })})diff --git a/.github/workflows/eng-analytics-weekly-digest.yml b/.github/workflows/eng-analytics-weekly-digest.ymlindex f43d05fafa04..d8796c45ada3 100644--- a/.github/workflows/eng-analytics-weekly-digest.yml+++ b/.github/workflows/eng-analytics-weekly-digest.yml@@ -1,23 +1,20 @@name: Engineering analytics weekly digest-# Posts a weekly CI digest to #alerts-devex every Monday morning. PULL model: the-# script reads the engineering_analytics product's repo_overview endpoint (the-# curated layer behind its MCP tools/UI) and relays one week-over-week CI cost-# table to Slack — it does not re-derive any metric from the GitHub API. See-# .github/scripts/eng-analytics-weekly-digest.mjs for the row definitions.+# Posts last week's Depot spend and pull request figures to #alerts-devex every Monday.+# .github/scripts/eng-analytics-weekly-digest.mjs says where each figure comes from.#-# Requires (no-ops with a warning until set, so it never spams failures):-# - vars.ENG_ANALYTICS_PROJECT_ID — the PostHog project with the GitHub data-# warehouse source connected (the one ingesting PostHog/posthog PR + CI data).-# - secrets.ENG_ANALYTICS_POSTHOG_API_KEY — a personal API key scoped to-# engineering_analytics:read for that project.-# - secrets.SLACK_DEVEX_BOT_TOKEN — the existing DevEx Slack bot (already used by-# ci-alerts-devex).+# Required. Until these are set, the job logs a warning and posts nothing:+# - vars.ENG_ANALYTICS_PROJECT_ID: the PostHog project with the GitHub and Depot warehouse sources.+# - secrets.ENG_ANALYTICS_POSTHOG_API_KEY: a personal API key for that project, scoped to+# engineering_analytics:read.+# - secrets.SLACK_DEVEX_BOT_TOKEN: the DevEx Slack bot.#-# Optional (the digest posts without the Depot contract rows when one is missing):-# - secrets.DEPOT_TOKEN: a Depot organization token that can read usage.-# - vars.DEPOT_CONTRACT_MINUTES: the GitHub Actions minutes the Depot contract includes.+# Optional:+# - secrets.DEPOT_TOKEN: a Depot organization token that can read usage. Without it the digest+# posts no spend.+# - vars.DEPOT_CONTRACT_USD: the Depot contract's usage allowance in list-price dollars.# - vars.DEPOT_CONTRACT_START and vars.DEPOT_CONTRACT_END: the contract dates, as YYYY-MM-DD.+# Without all three the digest posts no contract sentence.on:schedule:@@ -35,9 +32,8 @@ permissions:jobs:digest:runs-on: ubuntu-24.04- # Covers the script's worst case: 3 endpoint attempts x 150s abort plus 2 x 30s- # backoffs (~8.5min; it retries transient 5xxs from a contended warehouse cluster), plus the- # 60s abort on the Depot usage calls, plus setup.+ # The endpoint calls run in parallel. The slowest takes about 8.5 minutes: 3 attempts of 150s+ # with 30s between them.timeout-minutes: 12# Never run from forks (no secret access anyway), only the canonical repo.# Manual dispatch is master-only so branch-controlled code can't run with the secrets.@@ -57,17 +53,17 @@ jobs:node-version-file: .nvmrc- name: Build and post weekly CI digest- # POSTHOG_HOST and SLACK_CHANNEL (#alerts-devex) ride the script's defaults.+ # POSTHOG_HOST and SLACK_CHANNEL (#alerts-devex) use the script's defaults.env:POSTHOG_PROJECT_ID: ${{ vars.ENG_ANALYTICS_PROJECT_ID }}POSTHOG_API_KEY: ${{ secrets.ENG_ANALYTICS_POSTHOG_API_KEY }}- # Optional: pin a specific GitHub source if the project has more than one.+ # Pins the GitHub source when the project has more than one.ENG_ANALYTICS_SOURCE_ID: ${{ vars.ENG_ANALYTICS_SOURCE_ID }}SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEVEX_BOT_TOKEN }}DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}- DEPOT_CONTRACT_MINUTES: ${{ vars.DEPOT_CONTRACT_MINUTES }}+ DEPOT_CONTRACT_USD: ${{ vars.DEPOT_CONTRACT_USD }}DEPOT_CONTRACT_START: ${{ vars.DEPOT_CONTRACT_START }}DEPOT_CONTRACT_END: ${{ vars.DEPOT_CONTRACT_END }}- # Manual runs default to dry-run; the scheduled run posts (empty on schedule events).+ # Manual runs default to a dry run. Scheduled runs have no inputs, so they post.DRY_RUN: ${{ inputs.dry_run }}run: node .github/scripts/eng-analytics-weekly-digest.mjsdiff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex a4038dee6bb7..da7c82251647 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -211,6 +211,7 @@ Warehouse table (Depot source):Failed, canceled, and unsettled relays and waits stay visible, and a recovered relay retains its earlier failure history.Suppression applies to runs and jobs; raw source rows remain available for full runner-cost accounting.Curated cost estimates cover visible execution jobs and exclude suppressed hand-off and relay overhead, so they cannot establish total runner spend or reconcile an invoice.+ `depot_ci_usage` sums the raw attempts of every Depot source and prices them at the Depot CI rate in `logic/cost.py`.The Depot source is attempt-grained. A terminal run with no executed job attempts has no row here, sothe normalized run inventory cannot establish total run completeness. Vendor pagination can omit runsdiff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 4bc034101b94..de45d036f5c8 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -41,6 +41,7 @@ from products.engineering_analytics.backend.facade.contracts import (CurrentBranchHealth,DeliveryComparison,DeliverySummary,+ DepotCIRepoUsage,DoraOverview,FlakyTestList,GitHubSource,@@ -887,3 +888,15 @@ def get_github_team_roster(*, team: Team, user_access_control: "UserAccessControinsists on. An unsynced snapshot comes back as ``synced=False``, never an error."""return logic.build_github_team_roster(team=team, user_access_control=user_access_control)+++def get_depot_ci_usage(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> list[DepotCIRepoUsage]:+ return logic.build_depot_ci_usage(+ team=team, date_from=date_from, date_to=date_to, user_access_control=user_access_control+ )diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 9176c5a4f89c..646f512b522d 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -268,6 +268,13 @@ class GitHubTeamMembership:is_maintainer: bool+@dataclass(frozen=True)+class DepotCIRepoUsage:+ repo: str+ elapsed_seconds: float+ estimated_cost_usd: float++@dataclass(frozen=True)class GitHubTeamRoster:"""Every synced org team membership, and whether there was a snapshot to read at all.diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 00ba27925050..05e7d71b663e 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -30,6 +30,7 @@ from products.engineering_analytics.backend.logic.delivery_scope import (DeliveryScope as DeliveryScope,SummaryScope as SummaryScope,)+from products.engineering_analytics.backend.logic.depot_ci_usage import build_depot_ci_usage as build_depot_ci_usagefrom products.engineering_analytics.backend.logic.dora import build_dora_overview as build_dora_overviewfrom products.engineering_analytics.backend.logic.friction import (build_author_friction as build_author_friction,diff --git a/products/engineering_analytics/backend/logic/cost.py b/products/engineering_analytics/backend/logic/cost.pyindex 429822f07ee2..06baf980ddf6 100644--- a/products/engineering_analytics/backend/logic/cost.py+++ b/products/engineering_analytics/backend/logic/cost.py@@ -34,6 +34,9 @@ from enum import StrEnum# documented follow-up (SPEC section 7).REFERENCE_RATE_USD_PER_MIN = 0.004+# Depot CI list price. Depot CI bills vCPU-seconds, not runner minutes.+DEPOT_CI_RATE_USD_PER_VCPU_SECOND = 0.00005+# Depot billing multiplier per vCPU count (2cpu = 1x, doubling each step)._MULTIPLIER_BY_VCPU: dict[int, int] = {2: 1, 4: 2, 8: 4, 16: 8, 32: 16, 64: 32}@@ -204,6 +207,11 @@ def estimate_job_cost_usd(return (elapsed_seconds / 60) * REFERENCE_RATE_USD_PER_MIN * billing_multiplier(tier)+def estimate_depot_ci_cost_usd(elapsed_seconds: float) -> float:+ # Depot's API reports no runs-on, so every attempt is priced as the default 2-vCPU sandbox.+ return elapsed_seconds * _DEFAULT_DEPOT_VCPU * DEPOT_CI_RATE_USD_PER_VCPU_SECOND++@dataclass(frozen=True)class PRCostAggregate:"""One PR's job costs rolled up — billable (self-hosted Linux) runners only.diff --git a/products/engineering_analytics/backend/logic/depot_ci_usage.py b/products/engineering_analytics/backend/logic/depot_ci_usage.pynew file mode 100644index 000000000000..3f3f3f48182c--- /dev/null+++ b/products/engineering_analytics/backend/logic/depot_ci_usage.py@@ -0,0 +1,51 @@+"""Depot CI run time and cost per synced Depot source. It needs no GitHub tables, so it reads outside+``CuratedGitHubSource``."""++from typing import TYPE_CHECKING++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import DepotCIRepoUsage+from products.engineering_analytics.backend.logic._shared import _parse_window+from products.engineering_analytics.backend.logic.cost import estimate_depot_ci_cost_usd+from products.engineering_analytics.backend.logic.sources import resolve_depot_job_attempts_tables+from products.engineering_analytics.backend.logic.views.depot_ci import build_billed_seconds_query++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl+++def build_depot_ci_usage(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> list[DepotCIRepoUsage]:+ window_from, window_to = _parse_window(team, date_from, date_to, default="-7d")+ placeholders: dict[str, ast.Expr] = {+ "window_from": ast.Constant(value=window_from),+ "window_to": ast.Constant(value=window_to) if window_to else ast.Call(name="now", args=[]),+ }+ usage: list[DepotCIRepoUsage] = []+ for repo, attempts in resolve_depot_job_attempts_tables(team, user_access_control).items():+ with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):+ response = execute_hogql_query(+ query=parse_select(build_billed_seconds_query(attempts), placeholders=placeholders),+ team=team,+ query_type="engineering_analytics.depot_ci_usage",+ user=user_access_control.user if user_access_control is not None else None,+ user_access_control=user_access_control,+ # A userless caller has no ACL to honor, and HogQL would otherwise deny every warehouse table.+ bypass_warehouse_access_control=user_access_control is None,+ )+ seconds = float((response.results or [[0]])[0][0] or 0)+ usage.append(+ DepotCIRepoUsage(repo=repo, elapsed_seconds=seconds, estimated_cost_usd=estimate_depot_ci_cost_usd(seconds))+ )+ return usagediff --git a/products/engineering_analytics/backend/logic/views/depot_ci.py b/products/engineering_analytics/backend/logic/views/depot_ci.pyindex 471e2f0117eb..113d9821b996 100644--- a/products/engineering_analytics/backend/logic/views/depot_ci.py+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py@@ -112,6 +112,30 @@ def _conclusion(status: str) -> str:return f"multiIf({status} = 'finished', 'success', {status} = 'failed', 'failure', {status})"+def _of_repository(depot: DepotJobAttempts) -> str:+ return f"lower(ifNull(a.repo, '')) = '{depot.repository.lower()}'"+++def build_billed_seconds_query(depot: DepotJobAttempts) -> str:+ """Run time of the finished attempts that started in ``[{window_from}, {window_to})``.++ Reads the raw rows, so the hand-off shells the union drops still count, as Depot bills them.+ """+ return f"""+ SELECT sum(dateDiff('millisecond', started_at, finished_at)) / 1000+ FROM (+ SELECT+ parseDateTimeBestEffort(a.attempt_started_at) AS started_at,+ parseDateTimeBestEffort(a.attempt_finished_at) AS finished_at+ FROM {depot.table} AS a+ WHERE {_of_repository(depot)}+ AND ifNull(a.attempt_started_at, '') != ''+ AND ifNull(a.attempt_finished_at, '') != ''+ )+ WHERE started_at >= {{window_from}} AND started_at < {{window_to}} AND finished_at >= started_at+ """++def _attempts(depot: DepotJobAttempts, pull_requests_table: str | None) -> str:# Depot reports no branch, so a PR run takes its head branch from the PR snapshot, and branch# filters then match it like a GitHub run of the same PR.@@ -161,7 +185,7 @@ def _attempts(depot: DepotJobAttempts, pull_requests_table: str | None) -> str:a.sandbox_id AS sandbox_idFROM {depot.table} AS a{branch_join}- WHERE lower(ifNull(a.repo, '')) = '{depot.repository.lower()}'+ WHERE {_of_repository(depot)}AND {_is_id("a.run_id")} AND {_is_id("a.workflow_id")} AND {_is_id("a.attempt_id")})"""diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex 68730b944632..a8586ea3ae00 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -16,6 +16,7 @@ from products.engineering_analytics.backend.facade.contracts import (CurrentBranchHealth,DeliveryPipeline,DeliveryStageTiming,+ DepotCIRepoUsage,JobLogBadge,JobLogInsights,JobStepLogBadges,@@ -698,6 +699,22 @@ class DeliveryPipelineSerializer(DataclassSerializer):}+class DepotCIRepoUsageSerializer(DataclassSerializer):+ class Meta:+ dataclass = DepotCIRepoUsage+ extra_kwargs = {+ "repo": {"help_text": "Repository the Depot source syncs, as lowercase 'owner/name'."},+ "elapsed_seconds": {+ "help_text": "Run time of the finished Depot CI job attempts that started in the window, hand-off jobs "+ "included."+ },+ "estimated_cost_usd": {+ "help_text": "elapsed_seconds at the Depot CI list price for a 2-vCPU sandbox. Depot does not report "+ "the sandbox size of an attempt."+ },+ }++class RepoOverviewSerializer(DataclassSerializer):cost_series = CostPerMergeBucketSerializer(many=True,diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.pyindex 583feecff60e..0b9041c6f0e5 100644--- a/products/engineering_analytics/backend/presentation/views/workflows.py+++ b/products/engineering_analytics/backend/presentation/views/workflows.py@@ -17,6 +17,7 @@ from products.engineering_analytics.backend.presentation.serializers.workflows iCITimingContextQuerySerializer,CITimingContextSerializer,CurrentBranchHealthSerializer,+ DepotCIRepoUsageSerializer,JobLogInsightsQuerySerializer,JobLogInsightsSerializer,MasterFailureGroupSerializer,@@ -67,6 +68,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):"ci_data_freshness","ci_timing_context","repo_overview",+ "depot_ci_usage","current_branch_health","repo_run_activity","master_failures",@@ -533,6 +535,32 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):return _bad_request(exc, fallback="Invalid date_from, date_to, include_series, or source_id")return Response(RepoOverviewSerializer(instance=result).data)+ @extend_schema(+ operation_id="engineering_analytics_depot_ci_usage",+ parameters=[_DATE_FROM, _DATE_TO],+ responses={+ 200: DepotCIRepoUsageSerializer(many=True),+ 400: OpenApiResponse(description="Invalid date_from or date_to, or a window over 366 days."),+ },+ description=(+ "Depot CI run time and estimated cost over a window (default -7d), one entry per synced Depot "+ "source. Unlike the workflow and cost reads, it counts hand-off jobs, because Depot bills them. "+ "Empty when no Depot source is synced."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def depot_ci_usage(self, request: Request, **kwargs) -> Response:+ try:+ result = api.get_depot_ci_usage(+ team=self.team,+ date_from=request.query_params.get("date_from") or None,+ date_to=request.query_params.get("date_to") or None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid date_from or date_to")+ return Response(DepotCIRepoUsageSerializer(instance=result, many=True).data)+@extend_schema(operation_id="engineering_analytics_current_branch_health",parameters=[_SOURCE_ID, _REPO],diff --git a/products/engineering_analytics/backend/tests/test_depot_ci_usage.py b/products/engineering_analytics/backend/tests/test_depot_ci_usage.pynew file mode 100644index 000000000000..bdc629c8197e--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_depot_ci_usage.py@@ -0,0 +1,41 @@+import pytest++from products.engineering_analytics.backend.facade import api+from products.engineering_analytics.backend.tests._github_fixtures import _depot_attempt_row+from products.engineering_analytics.backend.tests._logic_helpers import _WarehouseMixin+++def _attempt(attempt_id: str, started_at: str, finished_at: str, **overrides: object) -> dict:+ return _depot_attempt_row(+ attempt_id=attempt_id, attempt_started_at=started_at, attempt_finished_at=finished_at, **overrides+ )+++class TestDepotCIUsage(_WarehouseMixin):+ def test_sums_finished_attempts_of_the_source_repository_in_the_window(self) -> None:+ self._create_depot_table(+ [+ _attempt("aaaaaaaaaa", "2026-10-27T10:00:00Z", "2026-10-27T10:10:00Z"),+ # The curated CI reads drop this hand-off job, but Depot bills it.+ _attempt(+ "bbbbbbbbbb",+ "2026-10-28T10:00:00.500Z",+ "2026-10-28T10:05:00Z",+ job_key="backend:wait-for-handoff",+ ),+ _attempt("cccccccccc", "2026-10-29T10:00:00Z", ""),+ _attempt("dddddddddd", "2026-10-25T23:59:00Z", "2026-10-26T00:30:00Z"),+ _attempt("eeeeeeeeee", "2026-11-02T00:00:00Z", "2026-11-02T00:30:00Z"),+ _attempt("ffffffffff", "2026-10-27T10:00:00Z", "2026-10-27T11:00:00Z", repo="PostHog/other"),+ ]+ )++ [usage] = api.get_depot_ci_usage(+ team=self.team, date_from="2026-10-26T00:00:00Z", date_to="2026-11-02T00:00:00Z"+ )++ assert (usage.repo, usage.elapsed_seconds) == ("posthog/posthog", 899.5)+ assert usage.estimated_cost_usd == pytest.approx(899.5 * 2 * 0.00005)++ def test_is_empty_without_a_depot_source(self) -> None:+ assert api.get_depot_ci_usage(team=self.team) == []diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex cc22a01d76ba..b504a31ec5de 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -908,6 +908,15 @@ export interface DeliverySummaryApi {push_count: number}+export interface DepotCIRepoUsageApi {+ /** Repository the Depot source syncs, as lowercase 'owner/name'. */+ repo: string+ /** Run time of the finished Depot CI job attempts that started in the window, hand-off jobs included. */+ elapsed_seconds: number+ /** elapsed_seconds at the Depot CI list price for a 2-vCPU sandbox. Depot does not report the sandbox size of an attempt. */+ estimated_cost_usd: number+}+export interface DeploymentFrequencyBucketApi {/** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). */bucket_start: string@@ -2972,6 +2981,17 @@ export type EngineeringAnalyticsDeliverySummaryParams = {source_id?: string}+export type EngineeringAnalyticsDepotCiUsageParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string+}+export type EngineeringAnalyticsDoraParams = {/*** Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 6a8f6f24a83e..fb52d3a08767 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -24,6 +24,7 @@ import type {CurrentBranchHealthApi,DeliveryComparisonApi,DeliverySummaryApi,+ DepotCIRepoUsageApi,DoraOverviewApi,EngineeringAnalyticsAttentionPullRequestsParams,EngineeringAnalyticsAuthorFrictionDetailParams,@@ -38,6 +39,7 @@ import type {EngineeringAnalyticsCurrentBranchHealthParams,EngineeringAnalyticsDeliveryComparisonParams,EngineeringAnalyticsDeliverySummaryParams,+ EngineeringAnalyticsDepotCiUsageParams,EngineeringAnalyticsDoraParams,EngineeringAnalyticsFlakyTestsParams,EngineeringAnalyticsJobAggregatesParams,@@ -556,6 +558,39 @@ export const engineeringAnalyticsDeliverySummary = async (})}+export const getEngineeringAnalyticsDepotCiUsageUrl = (+ projectId: string,+ params?: EngineeringAnalyticsDepotCiUsageParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/depot_ci_usage/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/depot_ci_usage/`+}++/**+ * Depot CI run time and estimated cost over a window (default -7d), one entry per synced Depot source. Unlike the workflow and cost reads, it counts hand-off jobs, because Depot bills them. Empty when no Depot source is synced.+ */+export const engineeringAnalyticsDepotCiUsage = async (+ projectId: string,+ params?: EngineeringAnalyticsDepotCiUsageParams,+ options?: RequestInit+): Promise<DepotCIRepoUsageApi[]> => {+ return apiMutator<DepotCIRepoUsageApi[]>(getEngineeringAnalyticsDepotCiUsageUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsDoraUrl = (projectId: string, params?: EngineeringAnalyticsDoraParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 99a36fec3ab1..555dbd7e9f51 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -58,6 +58,10 @@ tools:run/job metadata behind these logs. Jobs carry ci_engine; null means unknown historical provenance.hooks: engineeringAnalytics/redactFailureLogsHooksfeature_flag: engineering-analytics+ engineering-analytics-depot-ci-usage:+ operation: engineering_analytics_depot_ci_usage+ enabled: false+ disabled_reason: Billing totals for the weekly CI digest. Agents read cost per workflow or pull request.engineering-analytics-dora:operation: engineering_analytics_doraenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b8b40b491e6d..3936e278e218 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38368,6 +38368,15 @@ export namespace Schemas {deployment_count: number;}+ export interface DepotCIRepoUsage {+ /** Repository the Depot source syncs, as lowercase 'owner/name'. */+ repo: string;+ /** Run time of the finished Depot CI job attempts that started in the window, hand-off jobs included. */+ elapsed_seconds: number;+ /** elapsed_seconds at the Depot CI list price for a 2-vCPU sandbox. Depot does not report the sandbox size of an attempt. */+ estimated_cost_usd: number;+ }+export interface DeprovisionWarehouseResponse {/** Deprovisioning lifecycle message, e.g. 'deprovisioning started' */status: string;@@ -135986,6 +135995,17 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsDepotCiUsageParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string;+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string;+ };+export type EngineeringAnalyticsDoraParams = {/*** Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.