: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): post the weekly flaky report to team channels (#113971)
Raúl Negrón-Oteroef48dfe2d048
diff --git a/.github/scripts/weekly-flaky-report.mjs b/.github/scripts/weekly-flaky-report.mjsindex 6d16d4dc47a4..2c40ac0042e4 100644--- a/.github/scripts/weekly-flaky-report.mjs+++ b/.github/scripts/weekly-flaky-report.mjs@@ -33,11 +33,17 @@ import {shortName,SLACK_BOT_TOKEN,SLACK_CHANNEL,+ slackPermalink,} from './weekly-report-common.mjs'+// Off, each team's slice stays in the digest thread, labeled with the channel it would go to.+const TEAM_CHANNEL_POSTS = process.env.FLAKY_REPORT_TEAM_CHANNELS === 'true'+const FEEDBACK_CHANNEL = '<#C09G8QA6740>' // #team-devex+// The name a team uses under `notifications:` in owners.yaml to redirect or silence this report.+const OWNERS_PRODUCER = 'flaky_report'+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 DEPOT_ORG = 'ntsdt08fpt'const REPORT_WINDOW_DAYS = 7const TOP_N = 10@@ -151,9 +157,19 @@ function selectorVariants(selector) {return variants.length > 0 ? variants : [selector]}+// A Depot CI run has no page on GitHub, so each engine links to its own job page.+function failedJobUrl(engine, { runId, jobId, workflowId, nativeJobId }) {+ if (engine === 'depot_ci') {+ return workflowId && nativeJobId+ ? `https://depot.dev/orgs/${DEPOT_ORG}/workflows/${workflowId}?job=${nativeJobId}`+ : null+ }+ return `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${runId}${jobId ? `/job/${jobId}` : ''}`+}+// The two most recent failing (run, job) pairs, from the product's ci_failures view. That view-// holds fewer runs than the endpoint counts, so it supplies links and never a number. A run on-// another CI engine has no page on GitHub, so only the runs GitHub synced get a link.+// holds fewer runs than the endpoint counts, so it supplies links and never a number. The job+// history join keeps only the runs a warehouse source synced, and supplies each engine's own ids.async function enrich(items, runHogql = hogql) {const bySelector = new Map()for (const item of items) {@@ -170,19 +186,29 @@ async function enrich(items, runHogql = hogql) {try {const result = await runHogql(`SELECT f.test_id AS test_id,- arraySlice(arraySort(x -> -x.1, groupUniqArray((toUnixTimestamp(f.timestamp), f.run_id, f.job_id))), 1, 6) AS recent+ arraySlice(arraySort(x -> -x.1, groupUniqArray((+ toUnixTimestamp(f.timestamp), f.ci_engine, f.run_id, f.job_id,+ h.native_workflow_run_id, h.native_job_id+ ))), 1, 6) AS recentFROM engineering_analytics_ci_failures f+ INNER JOIN (+ SELECT ci_engine, run_id, job_name, run_attempt, native_workflow_run_id, native_job_id+ FROM engineering_analytics_ci_job_history+ WHERE created_at_raw >= {jobsFloor}+ ) h ON h.ci_engine = f.ci_engine AND h.run_id = f.run_id+ AND h.job_name = f.job_name AND h.run_attempt = f.run_attemptWHERE f.timestamp >= now() - INTERVAL ${REPORT_WINDOW_DAYS} DAYAND lower(f.repo) = lower({repository})AND f.test_id IN {selectors}- AND (f.ci_engine = 'github_actions' OR f.ci_engine IS NULL)- AND f.run_id IN (- SELECT id FROM ${RUNS_TABLE}- WHERE created_at >= toString(toDate(now() - INTERVAL 30 DAY))- )GROUP BY f.test_idLIMIT ${selectors.length}`,- { repository: GITHUB_REPOSITORY, selectors }+ {+ repository: GITHUB_REPOSITORY,+ selectors,+ // The job history view has no scan floor of its own. A re-run's job rows can+ // predate the window, so the floor sits a week before it.+ jobsFloor: new Date(Date.now() - 2 * REPORT_WINDOW_DAYS * 86_400_000).toISOString().slice(0, 10),+ })rows = result.results || []} catch (err) {@@ -198,12 +224,15 @@ async function enrich(items, runHogql = hogql) {}const seen = new Set()const evidence = []- for (const [, runId, jobId] of [...recent].sort((a, b) => b[0] - a[0])) {- if (seen.has(runId)) {+ for (const [, engine, runId, jobId, workflowId, nativeJobId] of [...recent].sort((a, b) => b[0] - a[0])) {+ // The two engines number their runs independently, so a bare integer can name one in each.+ const runKey = `${engine}:${runId}`+ const url = failedJobUrl(engine, { runId, jobId, workflowId, nativeJobId })+ if (seen.has(runKey) || !url) {continue}- seen.add(runId)- evidence.push({ runId, jobId })+ seen.add(runKey)+ evidence.push({ url })if (evidence.length === 2) {break}@@ -271,6 +300,7 @@ async function fetchTrunkQuarantined(runner, fetchQuarantine = fetchTrunkQuarantquarantinedAt: test.quarantined_at,overdue: Boolean(test.overdue),fixBy: trunkFixBy(test.quarantined_at, debt.ttl_days),+ url: test.trunk_url || null,}for (const variant of selectorVariants(test.nodeid)) {byVariant.set(variant, entry)@@ -406,7 +436,12 @@ async function buildRunnerReports()const queue = collapseClusters(ranked.slice(0, CANDIDATE_POOL), masksCi)const extrasFor = await getEnrichment(runner, queue)- return { runner, candidates: rankByReportedCounts(queue).slice(0, TOP_N), extrasFor }+ return {+ runner,+ candidates: rankByReportedCounts(queue).slice(0, TOP_N),+ extrasFor,+ trunkResolved: Boolean(trunkFor),+ }}))}@@ -421,15 +456,13 @@ function tableRows(items, ownerFor, extrasFor, statusFor = quarantineStatusFor)const testCell = repoPath? linkedCell([{ url: `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/master/${repoPath}`, text: name }]): cell(name)- const logLinks = evidence.map(({ runId, jobId }, index) => ({- url: `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${runId}${jobId ? `/job/${jobId}` : ''}`,- text: String(index + 1),- }))+ const logLinks = evidence.map(({ url }, index) => ({ url, text: String(index + 1) }))+ const status = statusFor(item) || '-'return [testCell,cell(RUNNER_LABELS[item.runner] || item.runner),- cell(owner.replace(/^team-/, '')),- cell(statusFor(item) || '-'),+ cell(teamLabel(owner)),+ item.trunk?.url ? linkedCell([{ url: item.trunk.url, text: status }]) : cell(status),cell(countCell(item, item.failed_pr_count)),cell(countCell(item, item.failed_run_count)),cell(countCell(item, item.same_commit_recovery_run_count)),@@ -438,10 +471,8 @@ function tableRows(items, ownerFor, extrasFor, statusFor = quarantineStatusFor)})}-// Shadow mode for per-team routing: the per-team slices carry the same rows as the-// channel digest, but posted as thread replies under it, labeled with the channel-// they would go to. Validates attribution and volume per team before any team-// channel receives a message. Takes [{owner, slack, row}] and groups by owner.+// The per-team slices carry the same rows as the channel digest. Takes [{owner, slack, row}]+// and groups by owner.function buildTeamDigests(entries) {const byOwner = new Map()for (const { owner, slack, row } of entries) {@@ -477,7 +508,7 @@ function flakyTable(rows) {cell('quarantine'),cell('PRs'),cell('failed runs'),- cell('recovered runs'),+ cell('passed on retry'),cell('logs'),],...rows,@@ -485,54 +516,122 @@ function flakyTable(rows) {}}-const COLUMN_LEGEND = {- type: 'context',- elements: [- {- type: 'mrkdwn',- text: [- '*Failed runs* counts each CI run where the test failed, including runs that a quarantine kept green.',- '*Recovered runs* counts each run where the same commit failed and passed the test.',- '*Quarantine* shows the Trunk repair deadline (fix by), a missed deadline (overdue since), or the quarantine start date (since). Yes means quarantined with no date available. Quarantine continues until removed. Flagged means Trunk lists the test but CI failures are not masked. A fraction counts masked cluster members.',- 'A count with a + covers several tests in one file and is a minimum.',- 'Tests with only expected failures (xfail), including file quarantines, are omitted.',- ].join(' '),- },- ],+const teamLabel = (owner) => owner.replace(/^team-/, '')++function titledTable(title, rows) {+ return [{ type: 'section', text: { type: 'mrkdwn', text: title } }, flakyTable(rows)]+}++function reportTitle(now, scope) {+ return `*Weekly flaky tests - ${now.toISOString().slice(0, 10)}* _(${scope})_`+}++// A slice kept in the digest thread. `reason` says why it is not in the team's channel.+function buildThreadSliceBlocks({ owner, channel, rows }, reason) {+ return titledTable(`*${teamLabel(owner)}* _(${reason} ${channel})_`, rows)}-function buildShadowBlocks({ owner, channel, rows }) {+function buildBlocks(now, rows) {+ const blocks = titledTable(+ reportTitle(now, `CI, last ${REPORT_WINDOW_DAYS} days, up to ${TOP_N} per runner`),+ rows+ )+ const editBlock = editWorkflowBlock()+ return editBlock ? [...blocks, editBlock] : blocks+}++function buildTeamBlocks(now, { owner, rows }, digestUrl) {+ const footer = [+ ...(digestUrl ? [`<${digestUrl}|Report for all teams>`] : []),+ `Wrong owner, wrong numbers, general feedback? Tell ${FEEDBACK_CHANNEL}!`,+ ]return [- {- type: 'section',- text: {- type: 'mrkdwn',- text: `*${owner.replace(/^team-/, '')}* _(shadow: would post to ${channel})_`,- },- },- flakyTable(rows),- COLUMN_LEGEND,+ ...titledTable(reportTitle(now, `owned by ${teamLabel(owner)}, CI, last ${REPORT_WINDOW_DAYS} days`), rows),+ { type: 'context', elements: [{ type: 'mrkdwn', text: footer.join(' · ') }] },]}-function buildBlocks(now, rows) {- const dateLabel = now.toISOString().slice(0, 10)- const blocks = [+function buildTeamIndexBlocks(posted) {+ return [{- type: 'section',- text: {- type: 'mrkdwn',- text: `*Weekly flaky tests - ${dateLabel}* _(CI, last ${REPORT_WINDOW_DAYS} days, up to ${TOP_N} per runner)_`,- },+ type: 'table',+ column_settings: [{ align: 'left' }, { align: 'right' }, { align: 'left' }],+ rows: [+ [cell('team'), cell('tests'), cell('post')],+ ...posted.map(({ owner, channel, rows, url }) => [+ cell(teamLabel(owner)),+ cell(String(rows.length)),+ url ? linkedCell([{ url, text: channel }]) : cell(channel),+ ]),+ ],},- flakyTable(rows),- COLUMN_LEGEND,]- const editBlock = editWorkflowBlock()- if (editBlock) {- blocks.push(editBlock)+}++const SLACK = {+ post: postToSlack,+ permalink: slackPermalink,+ // chat.postMessage allows about one message per second per channel.+ pause: () => new Promise((resolve) => setTimeout(resolve, 1100)),+}++async function postToTeamChannel(team, { now, digestUrl, slack }) {+ try {+ const post = await slack.post(buildTeamBlocks(now, team, digestUrl), 'Weekly flaky test report', {+ channel: team.channel,+ })+ return { ...team, url: await slack.permalink(post).catch(() => null) }+ } catch (err) {+ console.warn(`team digest for ${team.owner} failed: ${err.message}`)+ return null+ }+}++// Sends each team its slice, then indexes those posts in the digest thread. A slice that cannot+// go to its channel stays in the thread, so no team's rows are lost. `withheld` names a reason to+// keep every slice in the thread.+async function deliverTeamDigests(teamDigests, { now, digest, withheld = null, slack = SLACK }) {+ const digestUrl = withheld ? null : await slack.permalink(digest).catch(() => null)+ const posted = []+ for (const [index, team] of teamDigests.entries()) {+ if (index > 0) {+ await slack.pause()+ }+ const sent = withheld ? null : await postToTeamChannel(team, { now, digestUrl, slack })+ if (sent) {+ posted.push(sent)+ continue+ }+ // A failed slice must not sink the slices behind it; the digest itself already landed.+ try {+ await slack.post(+ buildThreadSliceBlocks(team, withheld || 'not delivered to'),+ `Flaky tests owned by ${team.owner}`,+ { threadTs: digest.ts }+ )+ } catch (err) {+ console.warn(`thread slice for ${team.owner} failed: ${err.message}`)+ }+ }+ if (posted.length > 0) {+ // The team posts already landed. A failed run would invite a re-dispatch that repeats them.+ try {+ await slack.post(buildTeamIndexBlocks(posted), 'Team posts for the weekly flaky test report', {+ threadTs: digest.ts,+ })+ } catch (err) {+ console.warn(`team post index failed: ${err.message}`)+ }+ }+ return posted+}++// A report built without Trunk state keeps unproven failures, which a team channel must not receive.+function teamPostsWithheld(runnerReports, enabled = TEAM_CHANNEL_POSTS) {+ if (!enabled) {+ return 'shadow: would post to'}- return blocks+ return runnerReports.every(({ trunkResolved }) => trunkResolved) ? null : 'Trunk state unavailable, not sent to'}async function main() {@@ -549,7 +648,7 @@ async function main() {console.info('No qualifying flaky tests this week — nothing to post.')return}- const ownerFor = resolveOwners(reportCandidates, toRepoPaths)+ const ownerFor = resolveOwners(reportCandidates, toRepoPaths, OWNERS_PRODUCER)// Rendered once; the channel table and the per-team slices share the same rows.const entries = runnerReports.flatMap(({ candidates, extrasFor }) => {const reportRows = tableRows(candidates, ownerFor, extrasFor)@@ -560,31 +659,27 @@ async function main() {entries.map(({ row }) => row))const teamDigests = buildTeamDigests(entries)+ const withheld = teamPostsWithheld(runnerReports)if (DRY_RUN) {console.info(JSON.stringify(blocks, null, 2))- console.info(JSON.stringify(teamDigests.map(buildShadowBlocks), null, 2))+ console.info(+ JSON.stringify(+ teamDigests.map((team) =>+ withheld ? buildThreadSliceBlocks(team, withheld) : buildTeamBlocks(now, team, null)+ ),+ null,+ 2+ )+ )return}if (!SLACK_BOT_TOKEN) {throw new Error('SLACK_BOT_TOKEN not set on a non-dry run — refusing to silently skip.')}- const digestTs = await postToSlack(blocks, 'Weekly flaky test report')+ const digest = await postToSlack(blocks, 'Weekly flaky test report')console.info(`Posted weekly flaky report to ${SLACK_CHANNEL}.`)- let postedSlices = 0- for (const [index, digest] of teamDigests.entries()) {- if (index > 0) {- // chat.postMessage allows about one message per second per channel.- await new Promise((resolve) => setTimeout(resolve, 1100))- }- // A failed slice must not sink the slices behind it; the digest itself already landed.- try {- await postToSlack(buildShadowBlocks(digest), `Flaky tests owned by ${digest.owner}`, { threadTs: digestTs })- postedSlices += 1- } catch (err) {- console.warn(`shadow digest for ${digest.owner} failed: ${err.message}`)- }- }- console.info(`Posted ${postedSlices}/${teamDigests.length} shadow team digest(s) in thread.`)+ const posted = await deliverTeamDigests(teamDigests, { now, digest, withheld })+ console.info(`Posted ${posted.length}/${teamDigests.length} team digest(s) to team channels.`)}if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {@@ -596,8 +691,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)export {buildBlocks,- buildShadowBlocks,buildTeamDigests,+ buildThreadSliceBlocks,+ deliverTeamDigests,+ teamPostsWithheld,buildRunnerReports,CLUSTER_MIN_TESTS,enrich,diff --git a/.github/scripts/weekly-flaky-report.test.mjs b/.github/scripts/weekly-flaky-report.test.mjsindex b8a56d98c432..99950827d42f 100644--- a/.github/scripts/weekly-flaky-report.test.mjs+++ b/.github/scripts/weekly-flaky-report.test.mjs@@ -3,8 +3,10 @@ import { describe, it } from 'node:test'import {buildBlocks,- buildShadowBlocks,buildTeamDigests,+ buildThreadSliceBlocks,+ deliverTeamDigests,+ teamPostsWithheld,buildRunnerReports,CLUSTER_MIN_TESTS,enrich,@@ -51,8 +53,8 @@ describe('weekly flaky report', () => {() => ({ owner: 'team-devex', repoPath: 'posthog/test/test_example.py' }),() => ({evidence: [- { runId: 10, jobId: 20 },- { runId: 11, jobId: 21 },+ { url: 'https://github.com/PostHog/posthog/actions/runs/10/job/20' },+ { url: 'https://github.com/PostHog/posthog/actions/runs/11/job/21' },],}))@@ -62,7 +64,7 @@ describe('weekly flaky report', () => {assert.ok(table)assert.deepEqual(table.rows[0].map((tableCell) => tableCell.text),- ['test', 'runner', 'owner', 'quarantine', 'PRs', 'failed runs', 'recovered runs', 'logs']+ ['test', 'runner', 'owner', 'quarantine', 'PRs', 'failed runs', 'passed on retry', 'logs'])// The edit-workflow context block may still render when Actions env vars are set;// only the action footer has to be gone.@@ -88,6 +90,16 @@ describe('weekly flaky report', () => {})assert.deepEqual(rows[0][1], { type: 'raw_text', text: 'pytest' })assert.deepEqual(rows[0][3], { type: 'raw_text', text: '-' })+ const trunkUrl = 'https://app.trunk.io/posthog/flaky-tests/test/abc?repo=PostHog/posthog'+ const [quarantinedRow] = tableRows(+ [{ runner: 'pytest', selector: 'posthog/test/test_example.py::test_masked', trunk: { url: trunkUrl } }],+ () => ({ owner: 'team-devex', repoPath: null }),+ () => ({ evidence: [] }),+ () => 'fix by 2026-08-13'+ )+ assert.deepEqual(quarantinedRow[3].elements[0].elements, [+ { type: 'link', url: trunkUrl, text: 'fix by 2026-08-13' },+ ])assert.deepEqual(rows[0][4], { type: 'raw_text', text: '3' })assert.deepEqual(rows[0][5], { type: 'raw_text', text: '4' })assert.deepEqual(rows[0][6], { type: 'raw_text', text: '2' })@@ -251,12 +263,14 @@ describe('weekly flaky report', () => {const candidatePools = await fetchCandidatePools(['pytest'], onMasterResolver, async () => ({items: [...plainRegressions, trunked, confirmed, expectedFailure, master, trunkedMaster],}))- const [{ candidates }] = await buildRunnerReports(+ const withTrunk = await buildRunnerReports(candidatePools,getEnrichment,async () => (item) =>item === trunked || item === trunkedMaster ? { quarantinedAt: '2026-07-13T17:12:22.000Z' } : null)+ const [{ candidates }] = withTrunk+ assert.equal(teamPostsWithheld(withTrunk, true), null)assert.deepEqual(candidates.map((candidate) => [candidate.selector, candidate.failed_run_count]),@@ -268,15 +282,17 @@ describe('weekly flaky report', () => {)assert.ok(logs.mock.calls.some(({ arguments: [message] }) => message.includes(expectedFailure.selector)))- const [{ candidates: candidatesWithoutTrunk }] = await buildRunnerReports(+ const withoutTrunk = await buildRunnerReports([{ runner: 'pytest', candidates: [plainRegressions[0], expectedFailure, master] }],getEnrichment,async () => null)assert.deepEqual(- candidatesWithoutTrunk.map((candidate) => candidate.selector),+ withoutTrunk[0].candidates.map((candidate) => candidate.selector),[plainRegressions[0].selector])+ // The unproven regression above is why this report must stay out of team channels.+ assert.equal(teamPostsWithheld(withoutTrunk, true), 'Trunk state unavailable, not sent to')})it('ranks and limits each runner independently', async () => {@@ -368,10 +384,10 @@ describe('weekly flaky report', () => {[item.selector,[- [100, 10, 20],- [300, 12, 22],- [250, 12, 23],- [200, 11, 21],+ [100, 'github_actions', 10, 20, '10', '20'],+ [300, 'depot_ci', 12, 22, 'wf12', 'job22'],+ [250, 'depot_ci', 12, 23, 'wf12', 'job23'],+ [200, 'github_actions', 11, 21, '11', '21'],],],],@@ -380,8 +396,8 @@ describe('weekly flaky report', () => {assert.deepEqual(extrasFor(item), {evidence: [- { runId: 12, jobId: 22 },- { runId: 11, jobId: 21 },+ { url: 'https://depot.dev/orgs/ntsdt08fpt/workflows/wf12?job=job22' },+ { url: 'https://github.com/PostHog/posthog/actions/runs/11/job/21' },],})assert.match(request.query, /lower\(f\.repo\) = lower\(\{repository\}\)/)@@ -477,6 +493,7 @@ describe('weekly flaky report', () => {quarantinedAt: '2026-07-29T09:14:22Z',overdue: true,fixBy: '2026-08-13',+ url: null,})assert.equal(pytestFor({ selector: 'backend/tests/test_migration.py::MigrationTest::test_other' }), null)assert.equal(@@ -600,11 +617,65 @@ describe('weekly flaky report', () => {['team-replay', '#team-replay', 1],])- const [header, table] = buildShadowBlocks(digests[0])+ const [header, table] = buildThreadSliceBlocks(digests[0], 'shadow: would post to')assert.equal(header.text.text, '*devex* _(shadow: would post to #team-devex)_')assert.equal(table.rows.length, 3)})+ it('keeps a team slice in the thread when its channel rejects the post and links the rest', async (context) => {+ context.mock.method(console, 'warn', () => {})+ const row = (name) => [{ type: 'raw_text', text: name }]+ const teams = [+ { owner: 'team-private', channel: '#team-private', rows: [row('test_one')] },+ { owner: 'team-replay', channel: '#team-replay', rows: [row('renders'), row('plays')] },+ ]+ const posts = []+ const slack = {+ pause: async () => {},+ permalink: async ({ channel, ts }) => `https://slack.test/${channel}/${ts}`,+ post: async (blocks, text, target) => {+ if (target.channel === '#team-private') {+ throw new Error('not_in_channel')+ }+ posts.push({ blocks, target })+ return { ts: String(posts.length), channel: target.channel ? 'C_REPLAY' : 'C_DIGEST' }+ },+ }++ const posted = await deliverTeamDigests(teams, {+ now: new Date('2026-10-05T13:10:00Z'),+ digest: { ts: '0', channel: 'C_DIGEST' },+ slack,+ })++ assert.deepEqual(+ posted.map(({ owner, url }) => [owner, url]),+ [['team-replay', 'https://slack.test/C_REPLAY/2']]+ )+ const [fallback, teamPost, index] = posts+ assert.deepEqual(fallback.target, { threadTs: '0' })+ assert.equal(fallback.blocks[0].text.text, '*private* _(not delivered to #team-private)_')+ assert.equal(teamPost.target.channel, '#team-replay')+ assert.equal(+ teamPost.blocks.at(-1).elements[0].text,+ '<https://slack.test/C_DIGEST/0|Report for all teams> · Wrong owner, wrong numbers, general feedback? Tell <#C09G8QA6740>!'+ )+ assert.deepEqual(index.target, { threadTs: '0' })+ assert.deepEqual(index.blocks[0].rows[1], [+ { type: 'raw_text', text: 'replay' },+ { type: 'raw_text', text: '2' },+ {+ type: 'rich_text',+ elements: [+ {+ type: 'rich_text_section',+ elements: [{ type: 'link', url: 'https://slack.test/C_REPLAY/2', text: '#team-replay' }],+ },+ ],+ },+ ])+ })+it('matches a Jest selector reported from the package root against Trunk', async () => {const trunkFor = await fetchTrunkQuarantined('jest',@@ -630,7 +701,7 @@ describe('weekly flaky report', () => {selector:'frontend/src/lib/components/ActivityLog/activityLogLogic.person.test.tsx::the activity log logic humanizing persons can handle addition of a property',}),- { quarantinedAt: '2026-07-11T16:45:09.000Z', overdue: false, fixBy: null }+ { quarantinedAt: '2026-07-11T16:45:09.000Z', overdue: false, fixBy: null, url: null })})})diff --git a/.github/scripts/weekly-report-common.mjs b/.github/scripts/weekly-report-common.mjsindex cf3efd8a0ab0..ff2e45113bee 100644--- a/.github/scripts/weekly-report-common.mjs+++ b/.github/scripts/weekly-report-common.mjs@@ -106,7 +106,7 @@ export function repoPathResolver(trackedPaths = trackedTestPaths()) {// Ambiguous suffix matches only count when every candidate agrees on the owner.// `slack` is the owning team's notifications channel, only set when the owner is unambiguous.-export function resolveOwners(items, toRepoPaths = repoPathResolver()) {+export function resolveOwners(items, toRepoPaths = repoPathResolver(), producer = null) {const candidates = new Map()for (const item of items) {const selectorPath = item.selector.split('::')[0]@@ -118,7 +118,8 @@ export function resolveOwners(items, toRepoPaths = repoPathResolver()) {let resolved = {}if (allPaths.length > 0) {try {- const out = execFileSync('python3', ['-m', 'owners_yaml', '--purpose', 'notifications'], {+ const producerArgs = producer ? ['--producer', producer] : []+ const out = execFileSync('python3', ['-m', 'owners_yaml', '--purpose', 'notifications', ...producerArgs], {encoding: 'utf8',input: allPaths.join('\n'),env: { ...process.env, PYTHONPATH: 'packages/owners-yaml' },@@ -185,5 +186,18 @@ export async function postToSlack(blocks, text, { threadTs, channel = SLACK_CHAN: ''throw new Error(`Slack chat.postMessage failed: ${data.error}${validationDetails}`)}- return data.ts+ // `channel` is the resolved channel ID, which chat.getPermalink needs when the post was addressed by name.+ return { ts: data.ts, channel: data.channel }+}++export async function slackPermalink({ channel, ts }) {+ const url = new URL('https://slack.com/api/chat.getPermalink')+ url.searchParams.set('channel', channel)+ url.searchParams.set('message_ts', ts)+ const res = await fetch(url, { headers: { Authorization: `Bearer ${SLACK_BOT_TOKEN}` } })+ const data = await res.json()+ if (!data.ok) {+ throw new Error(`Slack chat.getPermalink failed: ${data.error}`)+ }+ return data.permalink}diff --git a/.github/workflows/weekly-flaky-report.yml b/.github/workflows/weekly-flaky-report.ymlindex dd935c39cc2b..f4a2c3d0538a 100644--- a/.github/workflows/weekly-flaky-report.yml+++ b/.github/workflows/weekly-flaky-report.yml@@ -3,8 +3,10 @@ name: Weekly flaky test report# Posts the week's top flaky tests to #flakey-tests every Monday morning. PULL# model, sibling of eng-analytics-weekly-digest.yml: the script reads the# engineering_analytics product's flaky_tests endpoint and relays a channel-# table plus per-team thread slices to Slack via the DevEx bot — it does not-# re-derive the flake signal. Owner+# table to Slack via the DevEx bot — it does not re-derive the flake signal.+# Each owning team's rows go to that team's channel when+# vars.FLAKY_REPORT_TEAM_CHANNELS is 'true', and stay in the digest thread+# otherwise. Owner# attribution runs in the script through the packages/owners-yaml resolver, which is why# the sparse checkout includes the ownership files.#@@ -70,12 +72,13 @@ jobs:POSTHOG_API_KEY: ${{ secrets.ENG_ANALYTICS_POSTHOG_API_KEY }}# Optional: pin a specific GitHub source if the project has more than one.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 state at all.TRUNK_UPLOAD_ENABLED: ${{ vars.TRUNK_UPLOAD_ENABLED }}TRUNK_QUARANTINE_ENABLED: ${{ vars.TRUNK_QUARANTINE_ENABLED }}+ # 'true' posts each team's rows to that team's channel and links the posts from the+ # digest thread. Any other value keeps the rows in the thread.+ FLAKY_REPORT_TEAM_CHANNELS: ${{ vars.FLAKY_REPORT_TEAM_CHANNELS }}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/owners.yaml b/owners.yamlindex 111b9d960867..8c7134526f2f 100644--- a/owners.yaml+++ b/owners.yaml@@ -3,7 +3,7 @@ owners: []# Team slugs below are GitHub teams in this organization.github_org: PostHog# Automation that a team can redirect or silence under `notifications:`.-producers: [stamphog, visual_review]+producers: [stamphog, visual_review, flaky_report]# services/mcp generate-tools reads every YAML file in a product's mcp/ directory.reserved_dirs: ['products/**/mcp/**']# A product manifest already lists its owners, so it counts as an ownership file.diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 7c535d4f1ecc..7b768e94e520 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 `quarantine/request` endpoint files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App; it is reachable via the API and MCP only, with no in-app UI. Everything else is read-only.-- The Tests tab is the Trunk quarantine debt scoreboard: every test Trunk currently quarantines, attributed to the team that owns its file in the repository today, aged against a TTL, and rolled up per team. A quarantine masks a failure without fixing it, so the board is the standing work queue of masked tests. The flaky-test queue itself (failures plus same-commit recovery evidence from the pytest and Jest suites, counted per CI run, ranked by blast radius) remains an endpoint and MCP tool; the weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. Logs-based rescue counts and links remain pytest-only.+- The Tests tab is the Trunk quarantine debt scoreboard: every test Trunk currently quarantines, attributed to the team that owns its file in the repository today, aged against a TTL, and rolled up per team. A quarantine masks a failure without fixing it, so the board is the standing work queue of masked tests. The flaky-test queue itself (failures plus same-commit recovery evidence from the pytest and Jest suites, counted per CI run, ranked by blast radius) remains an endpoint and MCP tool; the weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. With the `FLAKY_REPORT_TEAM_CHANNELS` repository variable set to `true`, each owning team also gets its rows in its own notifications channel, linked from the report thread; a week without Trunk state keeps those rows in the thread. Logs-based rescue counts and links remain pytest-only.- 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 Desktop