: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
fix(ci): repair weekly flaky report (#73961)
Raúl Negrón-Oteroc45ba4e3750a
diff --git a/.github/scripts/weekly-flaky-report.mjs b/.github/scripts/weekly-flaky-report.mjsindex 40237a85cba7..e3b44326e074 100644--- a/.github/scripts/weekly-flaky-report.mjs+++ b/.github/scripts/weekly-flaky-report.mjs@@ -14,6 +14,7 @@// retry-enabled lanes. Master-burst breakage is filtered out client-side.import { execFileSync } from 'node:child_process'+import { pathToFileURL } from 'node:url'const HOST = (process.env.POSTHOG_HOST || 'https://us.posthog.com').replace(/\/$/, '')const PROJECT_ID = process.env.POSTHOG_PROJECT_ID || ''@@ -21,6 +22,7 @@ const API_KEY = process.env.POSTHOG_API_KEY || ''const SOURCE_ID = process.env.ENG_ANALYTICS_SOURCE_ID || ''// The synced runs table name carries the warehouse source prefix, which differs per project.const RUNS_TABLE = process.env.ENG_ANALYTICS_RUNS_TABLE || 'eng_analyticsgithub_workflow_runs'+const TRUNK_TABLE = process.env.TRUNK_QUARANTINE_TABLE || 'trunkio.quarantinedtests'const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN || ''const SLACK_CHANNEL = process.env.SLACK_CHANNEL || 'C09ADEV3AJD' // #flakey-testsconst DRY_RUN = ['1', 'true', 'yes'].includes((process.env.DRY_RUN || '').toLowerCase())@@ -33,6 +35,16 @@ const GITHUB_REF_NAME = process.env.GITHUB_REF_NAME || 'master'const TOP_N = 10const CANDIDATE_POOL = 40const CLUSTER_MIN_TESTS = 5+const REPORT_RUNNER = 'pytest'+const PARKED_NAMES_SHOWN = 5++// The endpoint's quarantine signal only covers `.test_quarantine.json`, where the pytest adapter+// xfails the test and the span records 'xfailed'. Trunk masks the job verdict instead, leaving a+// hard failure in the junit, so its quarantines reach the spans as plain failures.+// Same two variables the CI uploaders read: uploads decide whether the synced Trunk state is+// current, masking decides whether a quarantine actually keeps a failure from failing CI.+const TRUNK_UPLOADS_ON = process.env.TRUNK_UPLOAD_ENABLED === 'true'+const TRUNK_MASKS_CI = TRUNK_UPLOADS_ON && process.env.TRUNK_QUARANTINE_ENABLED === 'true'const RETRY_ATTEMPTS = 3const RETRY_DELAY_MS = 30_000@@ -84,10 +96,17 @@ function endpointUrl(action, params = {}) {const AUTH_HEADERS = { Authorization: `Bearer ${API_KEY}` }+function flakyTestsUrl() {+ return endpointUrl('flaky_tests', {+ date_from: '-7d',+ limit: 100,+ repo: GITHUB_REPOSITORY,+ runner: REPORT_RUNNER,+ })+}+function fetchFlakyTests() {- return withRetry(() =>- request(endpointUrl('flaky_tests', { date_from: '-7d', limit: 100 }), { headers: AUTH_HEADERS }, 'flaky_tests')- )+ return withRetry(() => request(flakyTestsUrl(), { headers: AUTH_HEADERS }, 'flaky_tests'))}// `values` bind through HogQL's {placeholder} syntax, escaped server-side — never@@ -106,16 +125,21 @@ function hogql(query, values) {)}-// One bad merge is breakage, not flakiness; keep it off the table. The endpoint's-// classification does not separate master bursts yet, so this stays client-side.+// A same-commit recovery proves a flake, so only suppress likely one-merge bursts+// when the endpoint has no recovery proof.function isMasterBurst(item) {return (+ item.classification === 'suspected_regression' &&item.failed_run_count > 0 &&item.master_failed_run_count / item.failed_run_count >= 0.5 &&item.failed_pr_count <= 3)}+function selectReportCandidates(items) {+ return items.filter((item) => item.runner === REPORT_RUNNER && !isMasterBurst(item)).slice(0, CANDIDATE_POOL)+}+// Product suites run from their product dir, so a selector path may be repo- or// product-relative — suffix-match the tracked index (full even under sparse checkout).function repoPathResolver() {@@ -187,7 +211,7 @@ function selectorVariants(selector) {// Rescue counts (failed at attempt N, run green at a later attempt) and the two most// recent failing (run, job) pairs, from the product's ci_failures view.-async function enrich(items) {+async function enrich(items, runHogql = hogql) {const bySelector = new Map()for (const item of items) {for (const variant of selectorVariants(item.selector)) {@@ -201,15 +225,17 @@ async function enrich(items) {}let rows = []try {- const result = await hogql(+ const result = await runHogql(`SELECT f.test_id AS test_id,uniqIf(f.run_id, r.run_attempt > f.run_attempt AND r.conclusion = 'success') AS runs_rescued,arraySlice(arrayReverseSort(x -> x.1, groupUniqArray(20)((toUnixTimestamp(f.timestamp), f.run_id, f.job_id))), 1, 6) AS recentFROM engineering_analytics_ci_failures fLEFT JOIN ${RUNS_TABLE} r ON r.id = f.run_id- WHERE f.timestamp >= now() - INTERVAL 7 DAY AND f.test_id IN {selectors}+ WHERE f.timestamp >= now() - INTERVAL 7 DAY+ AND lower(f.repo) = lower({repository})+ AND f.test_id IN {selectors}GROUP BY f.test_id`,- { selectors }+ { repository: GITHUB_REPOSITORY, selectors })rows = result.results || []} catch (err) {@@ -240,6 +266,78 @@ async function enrich(items) {return (item) => enriched.get(item.selector) || empty}+// Trunk keys a test by (file, classname, name), with the class inside `classname` rather than+// between file and name where a node id has it. `classname` is the file's module plus the class,+// so trimming the module prefix off it recovers the class and rebuilds the node id.+//+// The table carries no repository column, so this cannot be repo-scoped. It doesn't need to be:+// a row only annotates a selector the repo-scoped endpoint already returned, so another repo's+// rows would have to carry an identical node id to collide.+const TRUNK_QUARANTINED_QUERY = `+ SELECT concat(file, '::', if(cls = '', '', concat(cls, '::')), name) AS nodeid,+ quarantined_at+ FROM (+ SELECT file, name, quarantined_at,+ replaceAll(substring(file, 1, length(file) - 3), '/', '.') AS module,+ if(startsWith(classname, concat(module, '.')),+ replaceAll(substring(classname, length(module) + 2, length(classname)), '.', '::'),+ '') AS cls+ FROM __TRUNK_TABLE__+ WHERE parent = {runner}+ )`++// Uploads off, a missing table, or a query error all degrade to a report without Trunk state,+// never to a failed run or an empty table.+async function fetchTrunkQuarantined(runHogql = hogql, enabled = TRUNK_UPLOADS_ON) {+ const none = () => null+ if (!enabled) {+ return none+ }+ let rows = []+ try {+ const result = await runHogql(TRUNK_QUARANTINED_QUERY.replace('__TRUNK_TABLE__', TRUNK_TABLE), {+ runner: REPORT_RUNNER,+ })+ rows = result.results || []+ } catch (err) {+ console.warn(`Trunk quarantine lookup failed — reporting without Trunk state: ${err.message}`)+ return none+ }+ const byVariant = new Map()+ for (const [nodeid, quarantinedAt] of rows) {+ // Trunk reports repo-relative paths while a product suite's selector is product-relative,+ // so index both forms and look the selector up under both.+ for (const variant of selectorVariants(nodeid)) {+ byVariant.set(variant, { quarantinedAt })+ }+ }+ return (item) =>+ selectorVariants(item.selector)+ .map((variant) => byVariant.get(variant))+ .find(Boolean) || null+}++// Masking already stops these failures from failing CI, so they don't belong in a queue whose+// call to action is "park it". They stay listed below the table rather than dropped, so a+// long-lived auto-quarantine covering a real breakage still shows up somewhere.+function partitionParked(items, trunkFor, masksCi = TRUNK_MASKS_CI) {+ if (!masksCi) {+ return { queue: items, parked: [] }+ }+ return {+ queue: items.filter((item) => !trunkFor(item)),+ parked: items.filter((item) => trunkFor(item)).map((item) => ({ ...item, trunk: trunkFor(item) })),+ }+}++// Parking has to happen before clustering: a cluster's selector is a bare file path, which can+// never match a Trunk node id, so collapsing first buries quarantined tests in a row that then+// ranks as if CI still failed on them.+function buildQueue(items, trunkFor, masksCi = TRUNK_MASKS_CI) {+ const { queue, parked } = partitionParked(selectReportCandidates(items), trunkFor, masksCi)+ return { queue: collapseClusters(queue), parked }+}+// 5+ co-failing tests in one file are one shared-fixture incident, not N flakes.function collapseClusters(items) {const byFile = new Map()@@ -271,8 +369,12 @@ function cell(text) {return { type: 'raw_text', text }}-function mrkdwnCell(text) {- return { type: 'mrkdwn', text }+function linkedCell(links) {+ const elements = links.flatMap(({ url, text }, index) => [+ ...(index > 0 ? [{ type: 'text', text: ' ' }] : []),+ { type: 'link', url, text },+ ])+ return { type: 'rich_text', elements: [{ type: 'rich_text_section', elements }] }}function shortName(selector) {@@ -280,59 +382,88 @@ function shortName(selector) {return name.length > 36 ? `${name.slice(0, 35)}…` : name}-function tableRows(items, ownerFor, extrasFor) {+function tableRows(items, ownerFor, extrasFor, trunkFor = () => null) {return items.map((item) => {const { owner, repoPath } = ownerFor(item)const { runsRescued, evidence } = extrasFor(item)- const name = item.cluster_size ? `${item.selector.split('/').pop()} (${item.cluster_size} tests)` : shortName(item.selector)+ const name = item.cluster_size+ ? `${item.selector.split('/').pop()} (${item.cluster_size} tests)`+ : shortName(item.selector)const testCell = repoPath- ? mrkdwnCell(`<${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/master/${repoPath}|${name}>`)+ ? linkedCell([{ url: `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/master/${repoPath}`, text: name }]): cell(name)- const quarantined = item.classification === 'quarantined' || item.quarantined_failed_run_count > 0 ? ' (quarantined)' : ''- const logs = evidence- .map(({ runId, jobId }, i) => {- const url = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${runId}${jobId ? `/job/${jobId}` : ''}`- return `<${url}|${i + 1}>`- })- .join(' ')+ const quarantined =+ item.classification === 'quarantined' || item.quarantined_failed_run_count > 0 ? ' (quarantined)' : ''+ // Only reachable with masking off: masking on moves these rows out of the table entirely.+ // Trunk marked the test, but CI still fails on it, so it stays ranked.+ const trunkFlagged = trunkFor(item) ? ' (Trunk flagged)' : ''+ const logLinks = evidence.map(({ runId, jobId }, index) => ({+ url: `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${runId}${jobId ? `/job/${jobId}` : ''}`,+ text: String(index + 1),+ }))return [testCell,- cell(owner.replace(/^team-/, '') + quarantined),+ cell(owner.replace(/^team-/, '') + quarantined + trunkFlagged),cell(runsRescued == null ? '-' : String(runsRescued)),cell(String(item.failed_run_count)),- logs ? mrkdwnCell(logs) : cell('-'),+ logLinks.length > 0 ? linkedCell(logLinks) : cell('-'),]})}-function buildBlocks(now, rows) {+function parkedSummary(parked) {+ const shown = parked.slice(0, PARKED_NAMES_SHOWN).map((item) => shortName(item.selector))+ const remaining = parked.length - shown.length+ const names = remaining > 0 ? `${shown.join(', ')}, and ${remaining} more` : shown.join(', ')+ const oldest = parked+ .map((item) => item.trunk?.quarantinedAt)+ .filter(Boolean)+ .sort()[0]+ const since = oldest ? ` Oldest parked ${oldest.slice(0, 10)}.` : ''+ const count = parked.length === 1 ? '1 test is' : `${parked.length} tests are`+ return `${count} quarantined in Trunk, so CI no longer fails on them: ${names}.${since} Fix them or take them out of quarantine.`+}++function buildBlocks(now, rows, parked = []) {const dateLabel = now.toISOString().slice(0, 10)+ // Every candidate can be parked, which leaves the parked note as the whole report.+ const heading = rows.length > 0 ? `Top ${rows.length} flaky tests` : 'Flaky tests'const blocks = [{type: 'section',- text: { type: 'mrkdwn', text: `*Top ${rows.length} flaky tests — ${dateLabel}* _(backend CI, last 7 days)_` },- },- {- type: 'table',- column_settings: [- { align: 'left' },- { align: 'left' },- { align: 'right' },- { align: 'right' },- { align: 'left' },- ],- rows: [[cell('test'), cell('owner'), cell('rescued'), cell('fails'), cell('logs')], ...rows],- },- {- type: 'context',- elements: [- {- type: 'mrkdwn',- text: 'Fix: `/fixing-flaky-tests` · Park 14 days: `hogli test:quarantine add <test id>`',- },- ],+ text: {+ type: 'mrkdwn',+ text: `*${heading} — ${dateLabel}* _(backend CI, last 7 days)_`,+ },},]+ if (rows.length > 0) {+ blocks.push(+ {+ type: 'table',+ column_settings: [+ { align: 'left' },+ { align: 'left' },+ { align: 'right' },+ { align: 'right' },+ { align: 'left' },+ ],+ rows: [[cell('test'), cell('owner'), cell('rescued'), cell('fails'), cell('logs')], ...rows],+ },+ {+ type: 'context',+ elements: [+ {+ type: 'mrkdwn',+ text: 'Fix: `/fixing-flaky-tests` · Park 14 days: `hogli test:quarantine add <test id>`',+ },+ ],+ }+ )+ }+ if (parked.length > 0) {+ blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: parkedSummary(parked) }] })+ }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}`@@ -354,7 +485,10 @@ async function postToSlack(blocks) {})const data = await res.json()if (!data.ok) {- throw new Error(`Slack chat.postMessage failed: ${data.error}`)+ const validationDetails = Array.isArray(data.response_metadata?.messages)+ ? `: ${data.response_metadata.messages.join('; ')}`+ : ''+ throw new Error(`Slack chat.postMessage failed: ${data.error}${validationDetails}`)}}@@ -365,18 +499,23 @@ async function main() {}const now = new Date()const result = await fetchFlakyTests()- const pool = collapseClusters((result.items || []).filter((item) => !isMasterBurst(item)).slice(0, CANDIDATE_POOL))- const extrasFor = await enrich(pool.filter((item) => !item.cluster_size))+ const trunkFor = await fetchTrunkQuarantined()+ const { queue, parked } = buildQueue(result.items || [], trunkFor)+ const extrasFor = await enrich(queue.filter((item) => !item.cluster_size))// Rescued runs first (the strongest per-test signal), clusters and the rest by volume.- const flaky = pool- .sort((a, b) => (extrasFor(b).runsRescued ?? 0) - (extrasFor(a).runsRescued ?? 0) || b.failed_run_count - a.failed_run_count)+ const flaky = queue+ .sort(+ (a, b) =>+ (extrasFor(b).runsRescued ?? 0) - (extrasFor(a).runsRescued ?? 0) ||+ b.failed_run_count - a.failed_run_count+ ).slice(0, TOP_N)- if (flaky.length === 0) {+ if (flaky.length === 0 && parked.length === 0) {console.info('No qualifying flaky tests this week — nothing to post.')return}const ownerFor = resolveOwners(flaky)- const blocks = buildBlocks(now, tableRows(flaky, ownerFor, extrasFor))+ const blocks = buildBlocks(now, tableRows(flaky, ownerFor, extrasFor, trunkFor), parked)if (DRY_RUN) {console.info(JSON.stringify(blocks, null, 2))return@@ -388,7 +527,20 @@ async function main() {console.info(`Posted weekly flaky report to ${SLACK_CHANNEL}.`)}-main().catch((err) => {- console.error(err)- process.exit(1)-})+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((err) => {+ console.error(err)+ process.exit(1)+ })+}++export {+ buildBlocks,+ buildQueue,+ CLUSTER_MIN_TESTS,+ enrich,+ fetchTrunkQuarantined,+ flakyTestsUrl,+ selectReportCandidates,+ tableRows,+}diff --git a/.github/scripts/weekly-flaky-report.test.mjs b/.github/scripts/weekly-flaky-report.test.mjsnew file mode 100644index 000000000000..b78a826da557--- /dev/null+++ b/.github/scripts/weekly-flaky-report.test.mjs@@ -0,0 +1,235 @@+import assert from 'node:assert/strict'+import { describe, it } from 'node:test'++import {+ buildBlocks,+ buildQueue,+ CLUSTER_MIN_TESTS,+ enrich,+ fetchTrunkQuarantined,+ flakyTestsUrl,+ selectReportCandidates,+ tableRows,+} from './weekly-flaky-report.mjs'++describe('weekly flaky report', () => {+ it('requests pytest candidates for the current repository before the endpoint limit', () => {+ const url = flakyTestsUrl()++ assert.equal(url.searchParams.get('runner'), 'pytest')+ assert.equal(url.searchParams.get('repo'), 'PostHog/posthog')+ assert.equal(url.searchParams.get('limit'), '100')+ })++ it('builds a Slack table with supported cells and structured links', () => {+ const rows = tableRows(+ [+ {+ selector: 'posthog/test/test_example.py::TestExample::test_report',+ classification: 'confirmed_flake',+ quarantined_failed_run_count: 0,+ failed_run_count: 4,+ },+ ],+ () => ({ owner: 'team-devex', repoPath: 'posthog/test/test_example.py' }),+ () => ({+ runsRescued: 2,+ evidence: [+ { runId: 10, jobId: 20 },+ { runId: 11, jobId: 21 },+ ],+ })+ )+ const blocks = buildBlocks(new Date('2026-07-27T00:00:00Z'), rows)+ const table = blocks.find((block) => block.type === 'table')++ assert.ok(table)+ for (const tableCell of table.rows.flat()) {+ assert.ok(['raw_text', 'raw_number', 'rich_text'].includes(tableCell.type))+ }+ assert.deepEqual(rows[0][0], {+ type: 'rich_text',+ elements: [+ {+ type: 'rich_text_section',+ elements: [+ {+ type: 'link',+ url: 'https://github.com/PostHog/posthog/blob/master/posthog/test/test_example.py',+ text: 'test_report',+ },+ ],+ },+ ],+ })+ assert.deepEqual(rows[0][4], {+ type: 'rich_text',+ elements: [+ {+ type: 'rich_text_section',+ elements: [+ {+ type: 'link',+ url: 'https://github.com/PostHog/posthog/actions/runs/10/job/20',+ text: '1',+ },+ { type: 'text', text: ' ' },+ {+ type: 'link',+ url: 'https://github.com/PostHog/posthog/actions/runs/11/job/21',+ text: '2',+ },+ ],+ },+ ],+ })+ })++ it('keeps proved pytest flakes and excludes Jest and unproved master bursts', () => {+ const common = {+ failed_run_count: 4,+ failed_pr_count: 1,+ master_failed_run_count: 3,+ quarantined_failed_run_count: 0,+ }+ const candidates = selectReportCandidates([+ { ...common, runner: 'pytest', selector: 'test_proved.py::test_proved', classification: 'confirmed_flake' },+ {+ ...common,+ runner: 'pytest',+ selector: 'test_burst.py::test_burst',+ classification: 'suspected_regression',+ },+ { ...common, runner: 'jest', selector: 'test_report.ts', classification: 'confirmed_flake' },+ ])++ assert.deepEqual(+ candidates.map((candidate) => candidate.selector),+ ['test_proved.py::test_proved']+ )+ })++ it('scopes enrichment to the current repository', async () => {+ let request+ await enrich([{ selector: 'products/example/backend/test_report.py::test_report' }], async (query, values) => {+ request = { query, values }+ return { results: [] }+ })++ assert.match(request.query, /lower\(f\.repo\) = lower\(\{repository\}\)/)+ assert.equal(request.values.repository, 'PostHog/posthog')+ assert.deepEqual(request.values.selectors, [+ 'products/example/backend/test_report.py::test_report',+ 'backend/test_report.py::test_report',+ ])+ })++ it('reports without Trunk state when uploads are off, the table is missing, or it is empty', async () => {+ const item = { selector: 'posthog/test/test_example.py::test_report' }+ const cases = [+ {+ label: 'uploads off',+ enabled: false,+ runHogql: () => assert.fail('must not query Trunk while uploads are disabled'),+ },+ {+ label: 'table missing',+ enabled: true,+ runHogql: async () => {+ throw new Error('Unknown table trunkio.quarantinedtests')+ },+ },+ { label: 'no rows', enabled: true, runHogql: async () => ({ results: [] }) },+ ]++ for (const { label, enabled, runHogql } of cases) {+ const trunkFor = await fetchTrunkQuarantined(runHogql, enabled)++ assert.equal(trunkFor(item), null, label)+ }+ })++ it('matches Trunk rows to a product suite reported product-relative', async () => {+ const trunkFor = await fetchTrunkQuarantined(+ async () => ({+ results: [+ [+ 'products/example/backend/tests/test_migration.py::MigrationTest::test_backfill',+ '2026-07-29T09:14:22.000Z',+ 'AUTO_QUARANTINE',+ ],+ ],+ }),+ true+ )++ assert.equal(+ trunkFor({ selector: 'backend/tests/test_migration.py::MigrationTest::test_backfill' }).quarantinedAt,+ '2026-07-29T09:14:22.000Z'+ )+ assert.equal(trunkFor({ selector: 'backend/tests/test_migration.py::MigrationTest::test_other' }), null)+ })++ it('parks Trunk-quarantined tests only while masking is on, and labels them otherwise', () => {+ const items = [+ { runner: 'pytest', selector: 'masked.py::test_masked', failed_run_count: 9, failed_pr_count: 9 },+ { runner: 'pytest', selector: 'plain.py::test_plain', failed_run_count: 1, failed_pr_count: 1 },+ ]+ const trunkFor = (item) =>+ item.selector === 'masked.py::test_masked' ? { quarantinedAt: '2026-07-13T17:12:22.000Z' } : null+ const selectors = (list) => list.map((item) => item.selector)++ const masked = buildQueue(items, trunkFor, true)+ const unmasked = buildQueue(items, trunkFor, false)++ assert.deepEqual(selectors(masked.queue), ['plain.py::test_plain'])+ assert.deepEqual(selectors(masked.parked), ['masked.py::test_masked'])+ // Masking off leaves the failure reddening CI, so it stays ranked and carries a label.+ assert.deepEqual(selectors(unmasked.queue), selectors(items))+ assert.deepEqual(unmasked.parked, [])+ const [ownerCell] = tableRows(+ [items[0]],+ () => ({ owner: 'team-devex', repoPath: null }),+ () => ({ runsRescued: null, evidence: [] }),+ trunkFor+ ).map((row) => row[1])+ assert.equal(ownerCell.text, 'devex (Trunk flagged)')+ })++ it('parks a quarantined test that would otherwise be buried in a collapsed cluster', () => {+ // A cluster's selector is a bare file path, so it can never match a Trunk node id.+ const items = Array.from({ length: CLUSTER_MIN_TESTS }, (_, index) => ({+ runner: 'pytest',+ selector: `shared.py::test_${index}`,+ failed_run_count: 2,+ failed_pr_count: 2,+ }))++ const { queue, parked } = buildQueue(items, () => ({ quarantinedAt: '2026-07-13T17:12:22.000Z' }), true)++ assert.deepEqual(queue, [])+ assert.equal(parked.length, CLUSTER_MIN_TESTS)+ })++ it('keeps parked tests visible below the table instead of dropping them', () => {+ const blocks = buildBlocks(+ new Date('2026-07-27T00:00:00Z'),+ [],+ [{ selector: 'masked.py::test_masked', trunk: { quarantinedAt: '2026-07-13T17:12:22.000Z' } }]+ )+ // Actions always sets GITHUB_WORKFLOW_REF, which appends a block after the parked note,+ // so find the note by content rather than by position.+ const note = blocks+ .filter((block) => block.type === 'context')+ .map((block) => block.elements[0].text)+ .find((text) => text.includes('quarantined in Trunk'))++ assert.equal(+ blocks.find((block) => block.type === 'table'),+ undefined+ )+ assert.match(note, /1 test is quarantined in Trunk/)+ assert.match(note, /test_masked/)+ assert.match(note, /Oldest parked 2026-07-13\./)+ })+})diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex dcb4a9abc032..b119b8f6ae87 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -69,6 +69,10 @@ jobs:- name: CI report section tests (Node)run: node --test .github/scripts/post-ci-sections.test.mjs+ - name: Weekly flaky report tests (Node)+ if: ${{ hashFiles('.github/scripts/weekly-flaky-report.test.mjs') != '' }}+ run: node --test .github/scripts/weekly-flaky-report.test.mjs+- name: Turbo-discover dependent-cascade tests (Node)run: node --test .github/scripts/turbo-discover-cascade.test.jsdiff --git a/.github/workflows/weekly-flaky-report.yml b/.github/workflows/weekly-flaky-report.ymlindex 107e49d82ebd..c9ab6cb61166 100644--- a/.github/workflows/weekly-flaky-report.yml+++ b/.github/workflows/weekly-flaky-report.yml@@ -14,6 +14,9 @@ name: Weekly flaky test report# engineering_analytics:read + query:read for that project (the script also# reads the product's ci_failures view for rescue counts and job links).# - secrets.SLACK_DEVEX_BOT_TOKEN — the existing DevEx Slack bot.+#+# Trunk state is optional on top of that: with the TRUNK_* variables below unset, the report+# carries no Trunk state and never queries for it.on:schedule:@@ -67,6 +70,12 @@ jobs:ENG_ANALYTICS_SOURCE_ID: ${{ vars.ENG_ANALYTICS_SOURCE_ID }}# Optional: override the source-prefixed runs table name.ENG_ANALYTICS_RUNS_TABLE: ${{ vars.ENG_ANALYTICS_RUNS_TABLE }}+ # The same switches the CI uploaders read, so the report can only claim a test is+ # masked when Trunk is actually masking it. Unset means no Trunk section at all.+ TRUNK_UPLOAD_ENABLED: ${{ vars.TRUNK_UPLOAD_ENABLED }}+ TRUNK_QUARANTINE_ENABLED: ${{ vars.TRUNK_QUARANTINE_ENABLED }}+ # Optional: override the source-prefixed Trunk quarantine table name.+ TRUNK_QUARANTINE_TABLE: ${{ vars.TRUNK_QUARANTINE_TABLE }}SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEVEX_BOT_TOKEN }}DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}run: node .github/scripts/weekly-flaky-report.mjsdiff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 755fae699b07..8adaebcd0c57 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -82,7 +82,7 @@ graph LR- Job-level CI: per-job duration, queue time, runner tier, and dollar cost ride `workflow_jobs` (webhook stream plus bounded backfill).- One write surface: test quarantine. The UI files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App. Everything else is read-only.-- The test-health view is an active work queue, not a failure-rate leaderboard: the main pytest and Jest suites emit failures and same-job re-run recovery evidence. Jest writes a small marker beside JUnit when quarantine tolerates a failure, so masking it does not erase the signal. Evidence is counted per CI run, a test is called flaky only where one commit was seen both failing and passing it, and every other failure ranks as an honest suspected regression by blast radius.+- The test-health view is an active work queue, not a failure-rate leaderboard: the main pytest and Jest suites emit failures and same-job re-run recovery evidence. Jest writes a small marker beside JUnit when quarantine tolerates a failure, so masking it does not erase the signal. Evidence is counted per CI run, a test is called flaky only where one commit was seen both failing and passing it, and every other failure ranks as an honest suspected regression by blast radius. Callers can filter by `runner` before ranking and limiting when they need a runner-specific queue.- Access control: per-user warehouse RBAC at the source resolver, `engineering_analytics:read` scopes on tools, feature-flag gated.## The goal: CI Signals for PostHog Desktopdiff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 3c105b847792..8ba6029754c3 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -29,6 +29,7 @@ from products.engineering_analytics.backend.facade.contracts import (CICardSummary,CIFailureLogs,CISignalsConfig,+ CITestRunner,CurrentBranchHealth,FlakyTestList,GitHubSource,@@ -359,6 +360,7 @@ def list_flaky_tests(date_to: str | None = None,min_failed_prs: int | None = None,limit: int | None = None,+ runner: CITestRunner | None = None,source_id: str | None = None,repo: str | None = None,user_access_control: "UserAccessControl | None" = None,@@ -369,6 +371,7 @@ def list_flaky_tests(date_to=date_to,min_failed_prs=min_failed_prs,limit=limit,+ runner=runner,)diff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.pyindex a316d8293244..3a35ff025e97 100644--- a/products/engineering_analytics/backend/logic/queries/flaky_tests.py+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py@@ -46,6 +46,7 @@ _SELECT = """countIf(quarantined_in_run) AS quarantined_failed_run_count,max(run_signal_at) AS last_signal_atFROM (__RUN_EVIDENCE__)+ __RUNNER_FILTER__GROUP BY runner, nodeidHAVING same_commit_recovery_run_count > 0OR quarantined_failed_run_count > 0@@ -69,6 +70,7 @@ def query_flaky_tests(date_to: datetime | None,min_failed_prs: int,limit: int,+ runner: CITestRunner | None,) -> FlakyTestList:repository = curated.repository# Fail closed: the spans are scoped to the source's repository. Without a repository identity we@@ -79,11 +81,19 @@ def query_flaky_tests(placeholders = scan_placeholders(repository=repository, date_from=date_from, date_to=date_to)placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)+ runner_filter = ""+ if runner is not None:+ runner_filter = "WHERE runner = {runner}"+ placeholders["runner"] = ast.Constant(value=runner.value)# +1 so a full page tells us more tests qualified than returned.placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)+ query = _SELECT.replace("__RUN_EVIDENCE__", run_evidence(bounded=date_to is not None)).replace(+ "__RUNNER_FILTER__", runner_filter+ )+response = curated.run(- _SELECT.replace("__RUN_EVIDENCE__", run_evidence(bounded=date_to is not None)),+ query,query_type="engineering_analytics.flaky_tests",placeholders=placeholders,# trace_spans lives on the LOGS ClickHouse cluster, not the warehouse default.diff --git a/products/engineering_analytics/backend/logic/suite_health.py b/products/engineering_analytics/backend/logic/suite_health.pyindex c037661a13c8..506a0ad1ed00 100644--- a/products/engineering_analytics/backend/logic/suite_health.py+++ b/products/engineering_analytics/backend/logic/suite_health.py@@ -3,6 +3,7 @@from products.engineering_analytics.backend.facade.contracts import (BROKEN_TEST_SPARKLINE_HOURS,BrokenTestsResult,+ CITestRunner,FlakyTestList,)from products.engineering_analytics.backend.logic._shared import _parse_date, _parse_window@@ -33,6 +34,7 @@ def build_flaky_tests(date_to: str | None = None,min_failed_prs: int | None = None,limit: int | None = None,+ runner: CITestRunner | None = None,) -> FlakyTestList:parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_FLAKY_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS@@ -51,6 +53,7 @@ def build_flaky_tests(date_to=parsed_to,min_failed_prs=min_failed_prs,limit=limit,+ runner=runner,)diff --git a/products/engineering_analytics/backend/presentation/views/_base.py b/products/engineering_analytics/backend/presentation/views/_base.pyindex 9800df324006..7a1d1e497661 100644--- a/products/engineering_analytics/backend/presentation/views/_base.py+++ b/products/engineering_analytics/backend/presentation/views/_base.py@@ -1,6 +1,8 @@"""Shared OpenAPI parameter vocabulary, query-param helpers, and the viewset base."""from datetime import datetime+from enum import Enum+from typing import TypeVarfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter@@ -20,6 +22,8 @@ from products.engineering_analytics.backend.facade.contracts import (ENGINEERING_ANALYTICS_TAG = "engineering_analytics"+_EnumT = TypeVar("_EnumT", bound=Enum)+_DATE_FROM = OpenApiParameter(name="date_from",type=OpenApiTypes.STR,@@ -122,6 +126,18 @@ def _optional_datetime_param(request: Request, name: str) -> datetime | None:raise ValueError(f"{name} must be an ISO8601 datetime") from None+def _optional_enum_param(request: Request, name: str, choices: type[_EnumT]) -> _EnumT | None:+ """Optional enum query param; None when absent/blank, ValueError when present but not a member."""+ raw = request.query_params.get(name)+ if not raw:+ return None+ try:+ return choices(raw)+ except ValueError:+ allowed = ", ".join(member.value for member in choices)+ raise ValueError(f"{name} must be one of: {allowed}") from None++def _bool_param(request: Request, name: str, *, default: bool) -> bool:"""Optional boolean query param; the default when absent/blank, ValueError when present but not true/false."""raw = request.query_params.get(name)diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.pyindex a82e20ddba63..bf7d6833042d 100644--- a/products/engineering_analytics/backend/presentation/views/suite_health.py+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py@@ -10,7 +10,11 @@ from rest_framework.response import Responsefrom posthog.api.mixins import TypedRequest, validated_requestfrom products.engineering_analytics.backend.facade import api-from products.engineering_analytics.backend.facade.contracts import FLAKY_TEST_SIGNAL_CAVEAT, QuarantineRequest+from products.engineering_analytics.backend.facade.contracts import (+ FLAKY_TEST_SIGNAL_CAVEAT,+ CITestRunner,+ QuarantineRequest,+)from products.engineering_analytics.backend.presentation.serializers.suite_health import (BrokenTestsResultSerializer,FlakyTestListSerializer,@@ -24,6 +28,7 @@ from products.engineering_analytics.backend.presentation.views._base import (_SOURCE_ID,EngineeringAnalyticsViewSetBase,_bad_request,+ _optional_enum_param,_optional_int_param,)@@ -59,13 +64,21 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):required=False,description="Maximum number of tests to return (1-200). Defaults to 50.",),+ OpenApiParameter(+ name="runner",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ enum=[runner.value for runner in CITestRunner],+ description="Optional test runner to return: 'pytest' or 'jest'.",+ ),_SOURCE_ID,_REPO,],responses={200: FlakyTestListSerializer,400: OpenApiResponse(- description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."+ description="Invalid date, threshold, limit, runner, or source_id, or a window longer than 30 days."),},description=(@@ -88,12 +101,13 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):date_to=request.query_params.get("date_to") or None,min_failed_prs=_optional_int_param(request, "min_failed_prs"),limit=_optional_int_param(request, "limit"),+ runner=_optional_enum_param(request, "runner", CITestRunner),source_id=request.query_params.get("source_id") or None,repo=request.query_params.get("repo") or None,user_access_control=self.user_access_control,)except ValueError as exc:- return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")+ return _bad_request(exc, fallback="Invalid date, threshold, limit, runner, or source_id")return Response(FlakyTestListSerializer(instance=result).data)@extend_schema(diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.pyindex 4ce0ac328d8e..a2f532adad2c 100644--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py@@ -363,6 +363,13 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):assert data["truncated"] is Trueassert data["limit"] == 1+ def test_runner_filters_before_limit(self) -> None:+ data = self._get(runner="jest", limit="1")++ assert len(data["items"]) == 1+ assert data["items"][0]["runner"] == "jest"+ assert data["truncated"] is True+@parameterized.expand([("window_over_30_days", {"date_from": "-45d"}),@@ -371,6 +378,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):("zero_limit", {"limit": "0"}),("oversized_limit", {"limit": "201"}),("non_integer_threshold", {"min_failed_prs": "lots"}),+ ("unknown_runner", {"runner": "playwright"}),])def test_invalid_params_return_400(self, _name: str, params: dict) -> None:diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 59414b099806..e188b24f2c1f 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1313,12 +1313,24 @@ export type EngineeringAnalyticsFlakyTestsParams = {* 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/repo?: string+ /**+ * Optional test runner to return: 'pytest' or 'jest'.+ */+ runner?: EngineeringAnalyticsFlakyTestsRunner/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/source_id?: string}+export type EngineeringAnalyticsFlakyTestsRunner =+ (typeof EngineeringAnalyticsFlakyTestsRunner)[keyof typeof EngineeringAnalyticsFlakyTestsRunner]++export const EngineeringAnalyticsFlakyTestsRunner = {+ Jest: 'jest',+ Pytest: 'pytest',+} as const+export type EngineeringAnalyticsJobAggregatesParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3cf06f0f1e2a..cbc139166189 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -78175,12 +78175,24 @@ export namespace Schemas {* 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/repo?: string;+ /**+ * Optional test runner to return: 'pytest' or 'jest'.+ */+ runner?: EngineeringAnalyticsFlakyTestsRunner;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/source_id?: string;};+ export type EngineeringAnalyticsFlakyTestsRunner = typeof EngineeringAnalyticsFlakyTestsRunner[keyof typeof EngineeringAnalyticsFlakyTestsRunner];+++ export const EngineeringAnalyticsFlakyTestsRunner = {+ Jest: 'jest',+ Pytest: 'pytest',+ } as const;+export type EngineeringAnalyticsJobAggregatesParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.tsindex 4ac313609bd5..25d324a1774b 100644--- a/services/mcp/src/generated/engineering_analytics/api.ts+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -88,6 +88,7 @@ export const EngineeringAnalyticsFlakyTestsQueryParams = /* @__PURE__ */ zod.obj.describe("'owner\/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."),+ runner: zod.enum(['jest', 'pytest']).optional().describe("Optional test runner to return: 'pytest' or 'jest'."),source_id: zod.string().optional()diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsindex 2297d23d9694..e3c4edc688b5 100644--- a/services/mcp/src/tools/generated/engineering_analytics.ts+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -82,6 +82,7 @@ const engineeringAnalyticsFlakyTests = (): ToolBase<limit: params.limit,min_failed_prs: params.min_failed_prs,repo: params.repo,+ runner: params.runner,source_id: params.source_id,},})