: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): add weekly slow tests report tagging recent editors (#86032)
Paul D'Ambra546124be3a24
diff --git a/.github/scripts/weekly-flaky-report.mjs b/.github/scripts/weekly-flaky-report.mjsindex c51e778f8a92..8a577bd2531f 100644--- a/.github/scripts/weekly-flaky-report.mjs+++ b/.github/scripts/weekly-flaky-report.mjs@@ -14,24 +14,33 @@// retry-enabled lanes. Master-burst breakage and branch-only tests are 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 || ''-const API_KEY = process.env.POSTHOG_API_KEY || ''+import {+ AUTH_HEADERS,+ cell,+ DRY_RUN,+ editWorkflowBlock,+ GITHUB_REPOSITORY,+ GITHUB_SERVER_URL,+ hogql,+ HOST,+ linkedCell,+ postToSlack,+ PROJECT_ID,+ API_KEY,+ repoPathResolver,+ requestPosthog,+ resolveOwners,+ shortName,+ SLACK_BOT_TOKEN,+ SLACK_CHANNEL,+} from './weekly-report-common.mjs'+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-tests-const DRY_RUN = ['1', 'true', 'yes'].includes((process.env.DRY_RUN || '').toLowerCase())--const GITHUB_SERVER_URL = process.env.GITHUB_SERVER_URL || 'https://github.com'-const GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY || 'PostHog/posthog'-const GITHUB_WORKFLOW_REF = process.env.GITHUB_WORKFLOW_REF || ''-const GITHUB_REF_NAME = process.env.GITHUB_REF_NAME || 'master'const TOP_N = 10const CANDIDATE_POOL = 40@@ -48,41 +57,6 @@ const RUNNER_LABELS = { pytest: 'pytest', jest: 'Jest' }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 = 3-const RETRY_DELAY_MS = 30_000--async function request(url, options, label) {- const res = await fetch(url, { ...options, signal: AbortSignal.timeout(150_000) })- const body = await res.text()- const fail = (detail, retryable) => {- throw Object.assign(new Error(`${label} -> ${res.status}: ${detail}`), { retryable })- }- let parsed- try {- parsed = JSON.parse(body)- } catch {- fail(`non-JSON response (${body.slice(0, 120)})`, true)- }- if (!res.ok) {- fail(parsed?.detail || body, res.status >= 500 || res.status === 429)- }- return parsed-}--async function withRetry(fn) {- for (let attempt = 1; ; attempt++) {- try {- return await fn()- } 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`)- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))- }- }-}-function endpointUrl(action, params = {}) {const url = new URL(`${HOST}/api/projects/${PROJECT_ID}/engineering_analytics/${action}/`)for (const [k, v] of Object.entries(params)) {@@ -96,8 +70,6 @@ function endpointUrl(action, params = {}) {return url}-const AUTH_HEADERS = { Authorization: `Bearer ${API_KEY}` }-function flakyTestsUrl(runner) {return endpointUrl('flaky_tests', {date_from: '-7d',@@ -108,23 +80,7 @@ function flakyTestsUrl(runner) {}function fetchFlakyTests(runner) {- return withRetry(() => request(flakyTestsUrl(runner), { headers: AUTH_HEADERS }, 'flaky_tests'))-}--// `values` bind through HogQL's {placeholder} syntax, escaped server-side — never-// concatenate attacker-controlled test ids into the query source.-function hogql(query, values) {- return withRetry(() =>- request(- `${HOST}/api/projects/${PROJECT_ID}/query/`,- {- method: 'POST',- headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },- body: JSON.stringify({ query: { kind: 'HogQLQuery', query, values } }),- },- 'query'- )- )+ return requestPosthog(flakyTestsUrl(runner), { headers: AUTH_HEADERS }, 'flaky_tests')}// A same-commit recovery proves a flake, so only suppress likely one-merge bursts@@ -171,69 +127,6 @@ async function fetchCandidatePools(runners, toRepoPaths, fetchTests = fetchFlaky)}-// 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 trackedTestPaths(runGit = execFileSync) {- // The tracked-file list is a few MB; the 1MB execFileSync default truncates it.- return runGit('git', ['ls-files', '*.py', '*.js', '*.jsx', '*.ts', '*.tsx'], {- encoding: 'utf8',- maxBuffer: 64 * 1024 * 1024,- })- .split('\n')- .filter(Boolean)-}--function repoPathResolver(trackedPaths = trackedTestPaths()) {- const trackedSet = new Set(trackedPaths)- const bySuffix = new Map()- for (const path of trackedPaths) {- const base = path.split('/').pop()- if (!bySuffix.has(base)) {- bySuffix.set(base, [])- }- bySuffix.get(base).push(path)- }- return (selectorPath) => {- if (trackedSet.has(selectorPath)) {- return [selectorPath]- }- return (bySuffix.get(selectorPath.split('/').pop()) || []).filter((p) => p.endsWith(`/${selectorPath}`))- }-}--// Ambiguous suffix matches only count when every candidate agrees on the owner.-function resolveOwners(items, toRepoPaths = repoPathResolver()) {- const candidates = new Map()- for (const item of items) {- const selectorPath = item.selector.split('::')[0]- if (!candidates.has(selectorPath)) {- candidates.set(selectorPath, toRepoPaths(selectorPath))- }- }- const allPaths = [...new Set([...candidates.values()].flat())]- let resolved = {}- if (allPaths.length > 0) {- try {- const out = execFileSync('python3', ['-m', 'posthog_owners'], {- encoding: 'utf8',- input: allPaths.join('\n'),- env: { ...process.env, PYTHONPATH: 'tools/owners' },- })- resolved = JSON.parse(out)- } catch (err) {- // Degrade to "unowned" rather than skipping the week's post.- console.warn(`owners resolution failed — reporting all tests as unowned: ${err.message}`)- }- }- return (item) => {- const selectorPath = item.selector.split('::')[0]- const paths = candidates.get(selectorPath) || []- const owners = new Set(paths.map((p) => (resolved[p]?.owners || [])[0] || 'unowned'))- const owner = owners.size === 1 ? [...owners][0] : 'unowned'- return { owner, repoPath: paths.length === 1 ? paths[0] : null }- }-}-// One test carries different leading path segments depending on who named it: a product suite// runs from its product dir, jest reports from its package root, and the endpoint reports// repo-relative. Matching on every path suffix lets either side hold the longer prefix, which a@@ -457,23 +350,6 @@ async function buildRunnerReports()}-function cell(text) {- return { type: 'raw_text', 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) {- const name = selector.split('::').pop()- return name.length > 36 ? `${name.slice(0, 35)}…` : name-}-function tableRows(items, ownerFor, extrasFor, statusFor = () => null) {return items.map((item) => {const { owner, repoPath } = ownerFor(item)@@ -537,34 +413,13 @@ function buildBlocks(now, rows) {],},]- 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>` }] })+ const editBlock = editWorkflowBlock()+ if (editBlock) {+ blocks.push(editBlock)}return blocks}-async function postToSlack(blocks) {- const res = await fetch('https://slack.com/api/chat.postMessage', {- method: 'POST',- headers: { 'Content-Type': 'application/json; charset=utf-8', Authorization: `Bearer ${SLACK_BOT_TOKEN}` },- body: JSON.stringify({- channel: SLACK_CHANNEL,- blocks,- text: 'Weekly flaky test report', // notification fallback- unfurl_links: false,- }),- })- const data = await res.json()- if (!data.ok) {- const validationDetails = Array.isArray(data.response_metadata?.messages)- ? `: ${data.response_metadata.messages.join('; ')}`- : ''- throw new Error(`Slack chat.postMessage failed: ${data.error}${validationDetails}`)- }-}-async function main() {if (!PROJECT_ID || !API_KEY) {console.warn('POSTHOG_PROJECT_ID / POSTHOG_API_KEY not set — skipping report. Wire them to enable.')@@ -591,7 +446,7 @@ async function main() {if (!SLACK_BOT_TOKEN) {throw new Error('SLACK_BOT_TOKEN not set on a non-dry run — refusing to silently skip.')}- await postToSlack(blocks)+ await postToSlack(blocks, 'Weekly flaky test report')console.info(`Posted weekly flaky report to ${SLACK_CHANNEL}.`)}@@ -613,9 +468,7 @@ export {fetchTrunkQuarantined,flakyTestsUrl,REPORT_RUNNERS,- repoPathResolver,selectReportCandidates,tableRows,testStatusFor,- trackedTestPaths,}diff --git a/.github/scripts/weekly-flaky-report.test.mjs b/.github/scripts/weekly-flaky-report.test.mjsindex a8ad7447e4cc..c896a37a2a31 100644--- a/.github/scripts/weekly-flaky-report.test.mjs+++ b/.github/scripts/weekly-flaky-report.test.mjs@@ -12,12 +12,11 @@ import {fetchTrunkQuarantined,flakyTestsUrl,REPORT_RUNNERS,- repoPathResolver,selectReportCandidates,tableRows,testStatusFor,- trackedTestPaths,} from './weekly-flaky-report.mjs'+import { repoPathResolver, trackedTestPaths } from './weekly-report-common.mjs'const onMasterResolver = (path) => [path]diff --git a/.github/scripts/weekly-report-common.mjs b/.github/scripts/weekly-report-common.mjsnew file mode 100644index 000000000000..ec74e249e6fa--- /dev/null+++ b/.github/scripts/weekly-report-common.mjs@@ -0,0 +1,185 @@+// Shared machinery for the weekly CI report scripts (weekly-flaky-report.mjs,+// weekly-slow-tests-report.mjs): PostHog API plumbing, HogQL, repo path and owner+// resolution, Slack table cells, and the Slack post. Everything here reads the same+// environment both workflows set, so each report owns only its signal and its table.++import { execFileSync } from 'node:child_process'++export const HOST = (process.env.POSTHOG_HOST || 'https://us.posthog.com').replace(/\/$/, '')+export const PROJECT_ID = process.env.POSTHOG_PROJECT_ID || ''+export const API_KEY = process.env.POSTHOG_API_KEY || ''+export const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN || ''+export const SLACK_CHANNEL = process.env.SLACK_CHANNEL || 'C09ADEV3AJD' // #flakey-tests+export const DRY_RUN = ['1', 'true', 'yes'].includes((process.env.DRY_RUN || '').toLowerCase())++export const GITHUB_SERVER_URL = process.env.GITHUB_SERVER_URL || 'https://github.com'+export const GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY || 'PostHog/posthog'+export const GITHUB_WORKFLOW_REF = process.env.GITHUB_WORKFLOW_REF || ''+export const GITHUB_REF_NAME = process.env.GITHUB_REF_NAME || 'master'++const RETRY_ATTEMPTS = 3+const RETRY_DELAY_MS = 30_000++async function request(url, options, label) {+ const res = await fetch(url, { ...options, signal: AbortSignal.timeout(150_000) })+ const body = await res.text()+ const fail = (detail, retryable) => {+ throw Object.assign(new Error(`${label} -> ${res.status}: ${detail}`), { retryable })+ }+ let parsed+ try {+ parsed = JSON.parse(body)+ } catch {+ fail(`non-JSON response (${body.slice(0, 120)})`, true)+ }+ if (!res.ok) {+ fail(parsed?.detail || body, res.status >= 500 || res.status === 429)+ }+ return parsed+}++async function withRetry(fn) {+ for (let attempt = 1; ; attempt++) {+ try {+ return await fn()+ } 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`)+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))+ }+ }+}++export const AUTH_HEADERS = { Authorization: `Bearer ${API_KEY}` }++// `values` bind through HogQL's {placeholder} syntax, escaped server-side — never+// concatenate attacker-controlled test ids into the query source.+export function hogql(query, values) {+ return withRetry(() =>+ request(+ `${HOST}/api/projects/${PROJECT_ID}/query/`,+ {+ method: 'POST',+ headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },+ body: JSON.stringify({ query: { kind: 'HogQLQuery', query, values } }),+ },+ 'query'+ )+ )+}++export function requestPosthog(url, options, label) {+ return withRetry(() => request(url, options, label))+}++// 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).+export function trackedTestPaths(runGit = execFileSync) {+ // The tracked-file list is a few MB; the 1MB execFileSync default truncates it.+ return runGit('git', ['ls-files', '*.py', '*.js', '*.jsx', '*.ts', '*.tsx'], {+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ })+ .split('\n')+ .filter(Boolean)+}++export function repoPathResolver(trackedPaths = trackedTestPaths()) {+ const trackedSet = new Set(trackedPaths)+ const bySuffix = new Map()+ for (const path of trackedPaths) {+ const base = path.split('/').pop()+ if (!bySuffix.has(base)) {+ bySuffix.set(base, [])+ }+ bySuffix.get(base).push(path)+ }+ return (selectorPath) => {+ if (trackedSet.has(selectorPath)) {+ return [selectorPath]+ }+ return (bySuffix.get(selectorPath.split('/').pop()) || []).filter((p) => p.endsWith(`/${selectorPath}`))+ }+}++// Ambiguous suffix matches only count when every candidate agrees on the owner.+export function resolveOwners(items, toRepoPaths = repoPathResolver()) {+ const candidates = new Map()+ for (const item of items) {+ const selectorPath = item.selector.split('::')[0]+ if (!candidates.has(selectorPath)) {+ candidates.set(selectorPath, toRepoPaths(selectorPath))+ }+ }+ const allPaths = [...new Set([...candidates.values()].flat())]+ let resolved = {}+ if (allPaths.length > 0) {+ try {+ const out = execFileSync('python3', ['-m', 'posthog_owners'], {+ encoding: 'utf8',+ input: allPaths.join('\n'),+ env: { ...process.env, PYTHONPATH: 'tools/owners' },+ })+ resolved = JSON.parse(out)+ } catch (err) {+ // Degrade to "unowned" rather than skipping the week's post.+ console.warn(`owners resolution failed — reporting all tests as unowned: ${err.message}`)+ }+ }+ return (item) => {+ const selectorPath = item.selector.split('::')[0]+ const paths = candidates.get(selectorPath) || []+ const owners = new Set(paths.map((p) => (resolved[p]?.owners || [])[0] || 'unowned'))+ const owner = owners.size === 1 ? [...owners][0] : 'unowned'+ return { owner, repoPath: paths.length === 1 ? paths[0] : null }+ }+}++export function cell(text) {+ return { type: 'raw_text', text }+}++export 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 }] }+}++export function shortName(selector) {+ const name = selector.split('::').pop()+ return name.length > 36 ? `${name.slice(0, 35)}…` : name+}++// Goals every report shares: one table, one footer link back to the workflow that posts it.+export function editWorkflowBlock() {+ const workflowPath = GITHUB_WORKFLOW_REF.split('@')[0].replace(`${GITHUB_REPOSITORY}/`, '')+ if (!GITHUB_REPOSITORY || !workflowPath) {+ return null+ }+ const editUrl = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/edit/${GITHUB_REF_NAME}/${workflowPath}`+ return { type: 'context', elements: [{ type: 'mrkdwn', text: `<${editUrl}|edit this workflow>` }] }+}++export async function postToSlack(blocks, text) {+ const res = await fetch('https://slack.com/api/chat.postMessage', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json; charset=utf-8', Authorization: `Bearer ${SLACK_BOT_TOKEN}` },+ body: JSON.stringify({+ channel: SLACK_CHANNEL,+ blocks,+ text, // notification fallback+ unfurl_links: false,+ }),+ })+ const data = await res.json()+ if (!data.ok) {+ const validationDetails = Array.isArray(data.response_metadata?.messages)+ ? `: ${data.response_metadata.messages.join('; ')}`+ : ''+ throw new Error(`Slack chat.postMessage failed: ${data.error}${validationDetails}`)+ }+}diff --git a/.github/scripts/weekly-slow-tests-report.mjs b/.github/scripts/weekly-slow-tests-report.mjsnew file mode 100644index 000000000000..6927ac6186ec--- /dev/null+++ b/.github/scripts/weekly-slow-tests-report.mjs@@ -0,0 +1,399 @@+// Weekly slow-test report, posted to #flakey-tests on Monday.+//+// Sibling of weekly-flaky-report.mjs: one HogQL read of the passing test spans the+// CI timing reporter (.github/scripts/report_test_timings.py) already ships, ranked by+// median wall time, with owner attribution through tools/owners and recent editors+// resolved through the GitHub commits API into Slack mentions. The report nudges the+// people best placed to speed a test up; it does not re-derive any span signal.+//+// GHA cron ──> HogQL over posthog.trace_spans + GitHub commits API ──> Slack+//+// Known data gap: frontend CI emits failing jest spans only (--signals-only), so the+// table is pytest-only until that emitter reports slow passing tests too.++import { pathToFileURL } from 'node:url'++import {+ API_KEY,+ cell,+ DRY_RUN,+ editWorkflowBlock,+ GITHUB_REPOSITORY,+ GITHUB_SERVER_URL,+ hogql,+ linkedCell,+ postToSlack,+ PROJECT_ID,+ repoPathResolver,+ resolveOwners,+ shortName,+ SLACK_BOT_TOKEN,+ GITHUB_REF_NAME,+} from './weekly-report-common.mjs'++const GITHUB_TOKEN = process.env.GITHUB_TOKEN || ''+const GITHUB_API_URL = process.env.GITHUB_API_URL || 'https://api.github.com'++const TOP_N = 10+const CANDIDATE_POOL = 30+const MIN_BUILDS = 3+const MAX_EDITORS = 2++// Passing tests only: failures belong to the flaky report. Master pushes and merge-queue+// gate runs are the landed-code population; PR runs add noise from code that may never+// land. One test can run in several matrix legs per build, so builds counts runs, not legs.+const SLOW_TESTS_QUERY = `+ SELECT+ if(attributes['test.runner'] = 'jest' OR service_name = 'ci-frontend', 'jest', 'pytest') AS runner,+ attributes['test.selector'] AS selector,+ any(attributes['test.file']) AS file,+ round(median(toFloat64(duration_nano)) / 1000000000, 1) AS p50_seconds,+ round(max(toFloat64(duration_nano)) / 1000000000, 1) AS max_seconds,+ uniq(resource_attributes['ci.run_id']) AS builds+ FROM posthog.trace_spans+ WHERE service_name IN {service_names}+ AND attributes['test.outcome'] = 'passed'+ AND attributes['test.selector'] != ''+ AND attributes['test.file'] != ''+ AND (resource_attributes['ci.branch'] = {for_branch} OR resource_attributes['ci.branch'] LIKE {merge_queue_glob})+ AND lower(resource_attributes['ci.repository']) = lower({repository})+ AND timestamp >= now() - INTERVAL 7 DAY+ GROUP BY runner, selector+ HAVING builds >= {min_builds}+ ORDER BY p50_seconds DESC+ LIMIT ${CANDIDATE_POOL}`++const SLOW_TEST_VALUES = {+ service_names: ['ci-backend', 'ci-frontend'],+ repository: GITHUB_REPOSITORY,+ for_branch: 'master',+ merge_queue_glob: 'trunk-merge/%',+ min_builds: MIN_BUILDS,+}++async function fetchSlowTests(runHogql = hogql) {+ const result = await runHogql(SLOW_TESTS_QUERY, SLOW_TEST_VALUES)+ return (result.results || []).map(([runner, selector, file, p50Seconds, maxSeconds, builds]) => ({+ runner,+ selector,+ file,+ p50_seconds: Number(p50Seconds),+ max_seconds: Number(maxSeconds),+ builds: Number(builds),+ }))+}++// A test whose file is not in the master checkout was added on a branch or deleted+// mid-week; in neither case is there a file to link or an editor to find.+function selectReportCandidates(items, toRepoPaths = repoPathResolver()) {+ const onMaster = []+ const dropped = []+ for (const item of items) {+ const repoPaths = toRepoPaths(item.file)+ if (repoPaths.length > 0) {+ onMaster.push({ ...item, repoPaths })+ } else {+ dropped.push(item)+ }+ }+ if (dropped.length > 0) {+ console.info(+ `dropped ${dropped.length} test(s) with no file in the checkout: ${dropped+ .map((item) => item.selector)+ .join(', ')}`+ )+ }+ return onMaster.slice(0, CANDIDATE_POOL)+}++function rankReportCandidates(items, limit = TOP_N) {+ return items+ .map((item, index) => ({ item, index }))+ .sort(+ (left, right) =>+ right.item.p50_seconds - left.item.p50_seconds ||+ right.item.max_seconds - left.item.max_seconds ||+ left.index - right.index+ )+ .slice(0, limit)+ .map(({ item }) => item)+}++// The newest unique human editors of a file, from the GitHub commits API response.+// Bots and anonymous commits are skipped: a dependency bump or a git-only identity is+// nobody to tag.+function buildEditors(commits) {+ const editors = []+ const seen = new Set()+ for (const commit of commits) {+ const login = commit.author?.login+ const email = commit.commit?.author?.email || null+ if (!login || login.endsWith('[bot]') || seen.has(login.toLowerCase())) {+ continue+ }+ seen.add(login.toLowerCase())+ editors.push({ login, email })+ if (editors.length >= MAX_EDITORS) {+ break+ }+ }+ return editors+}++async function defaultGithubFetch(url) {+ const res = await fetch(url, {+ headers: { Authorization: `Bearer ${GITHUB_TOKEN}`, Accept: 'application/vnd.github+json' },+ signal: AbortSignal.timeout(30_000),+ })+ const body = await res.text()+ if (!res.ok) {+ throw new Error(`GitHub ${url} -> ${res.status}: ${body.slice(0, 200)}`)+ }+ return JSON.parse(body)+}++async function buildEditorIndex(candidates, githubFetch = defaultGithubFetch) {+ const paths = [...new Set(candidates.flatMap((item) => (item.repoPaths?.length === 1 ? item.repoPaths : [])))]+ const editorIndex = new Map()+ await Promise.all(+ paths.map(async (path) => {+ const url = new URL(`${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/commits`)+ url.searchParams.set('path', path)+ url.searchParams.set('sha', GITHUB_REF_NAME)+ url.searchParams.set('per_page', String(MAX_EDITORS + 2)) // headroom for skipped bots+ try {+ editorIndex.set(path, buildEditors(await githubFetch(url.toString())))+ } catch (err) {+ // Editors decorate the table; a lookup failure must not sink the post.+ console.warn(`recent-editor lookup failed for ${path}: ${err.message}`)+ editorIndex.set(path, [])+ }+ })+ )+ return editorIndex+}++async function defaultSlackFetch(apiPath) {+ const res = await fetch(`https://slack.com/api/${apiPath}`, {+ headers: { Authorization: `Bearer ${SLACK_BOT_TOKEN}` },+ signal: AbortSignal.timeout(30_000),+ })+ const body = await res.text()+ if (!res.ok) {+ // The path can carry a commit author's email (lookupByEmail) - keep it out of logs.+ throw new Error(`Slack ${apiPath.split('?')[0]} -> ${res.status}: ${body.slice(0, 200)}`)+ }+ return JSON.parse(body)+}++// Slack mention ids for the editors, cheapest lookup first: one directory page-march+// matches GitHub logins against each member's Slack login field (which PostHog's profile+// convention sets), then users.lookupByEmail covers the rest. Both need scopes the DevEx+// bot may not have, so every miss degrades to a plain GitHub link, never a failed post.+async function resolveSlackUsers(editors, slackFetch = defaultSlackFetch) {+ const bySlackLogin = new Map()+ let cursor = ''+ for (;;) {+ const page = await slackFetch(`users.list${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`)+ if (!page.ok) {+ throw new Error(`Slack users.list failed: ${page.error}`)+ }+ for (const member of page.members || []) {+ if (member.deleted) {+ continue+ }+ // `login` is a custom profile field some workspaces set to the GitHub handle; `name`+ // is Slack's built-in username. Either earns a mention if it matches a GitHub login.+ for (const slackLogin of [member.profile?.login, member.name]) {+ if (slackLogin && !bySlackLogin.has(slackLogin.toLowerCase())) {+ bySlackLogin.set(slackLogin.toLowerCase(), member.id)+ }+ }+ }+ cursor = page.response_metadata?.next_cursor || ''+ if (!cursor) {+ break+ }+ }+ let emailLookupBroken = false+ return Promise.all(+ editors.map(async (editor) => {+ const slackId = bySlackLogin.get(editor.login.toLowerCase())+ if (slackId) {+ return { ...editor, slackId }+ }+ if (!editor.email || emailLookupBroken) {+ return { ...editor, slackId: null }+ }+ const byEmail = await slackFetch(`users.lookupByEmail?email=${encodeURIComponent(editor.email)}`)+ if (!byEmail.ok) {+ if (byEmail.error === 'missing_scope') {+ emailLookupBroken = true+ console.warn('Slack users.lookupByEmail missing_scope - remaining editors keep GitHub links')+ }+ return { ...editor, slackId: null }+ }+ return { ...editor, slackId: byEmail.user.id }+ })+ )+}++function buildEditorCell(editors) {+ if (editors.length === 0) {+ return cell('unknown')+ }+ const elements = editors.flatMap((editor, index) => [+ ...(index > 0 ? [{ type: 'text', text: ', ' }] : []),+ editor.slackId+ ? { type: 'user', user_id: editor.slackId }+ : { type: 'link', url: `${GITHUB_SERVER_URL}/${editor.login}`, text: `@${editor.login}` },+ ])+ return { type: 'rich_text', elements: [{ type: 'rich_text_section', elements }] }+}++function formatDurationSeconds(seconds) {+ const total = Math.round(seconds)+ if (total < 60) {+ return `${total}s`+ }+ const minutes = Math.floor(total / 60)+ const remainder = total % 60+ return `${minutes}m ${remainder}s`+}++function tableRows(items, ownerFor, editorsFor) {+ return items.map((item) => {+ const { owner, repoPath } = ownerFor(item)+ const name = shortName(item.selector)+ const testCell = repoPath+ ? linkedCell([{ url: `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/master/${repoPath}`, text: name }])+ : cell(name)+ return [+ testCell,+ cell(formatDurationSeconds(item.p50_seconds)),+ cell(formatDurationSeconds(item.max_seconds)),+ cell(String(item.builds)),+ cell(owner.replace(/^team-/, '')),+ buildEditorCell(editorsFor(item)),+ ]+ })+}++function buildBlocks(now, rows) {+ const dateLabel = now.toISOString().slice(0, 10)+ const blocks = [+ {+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*Weekly slow tests - ${dateLabel}* _(passing tests on master CI, last 7 days)_`,+ },+ },+ {+ type: 'table',+ column_settings: [+ { align: 'left' },+ { align: 'right' },+ { align: 'right' },+ { align: 'right' },+ { align: 'left' },+ { align: 'left' },+ ],+ rows: [+ [cell('test'), cell('p50'), cell('max'), cell('builds'), cell('owner'), cell('last edited by')],+ ...rows,+ ],+ },+ {+ type: 'context',+ elements: [+ {+ type: 'mrkdwn',+ text: "p50 is the median wall time across the week's CI builds. No slow Jest rows yet: frontend CI reports failing test spans only.",+ },+ ],+ },+ ]+ const editBlock = editWorkflowBlock()+ if (editBlock) {+ blocks.push(editBlock)+ }+ return blocks+}++// Per-item recent-editor lookup for the table. Editors come from GitHub commits per file,+// then get Slack ids where the workspace directory maps the GitHub login. Every failure+// degrades to fewer mentions, never to a skipped post.+async function resolveEditorsFor(candidates) {+ if (!GITHUB_TOKEN) {+ console.warn('GITHUB_TOKEN not set - editor mentions degrade to "unknown".')+ return () => []+ }+ const editorIndex = await buildEditorIndex(candidates)+ const editors = [...new Map([...editorIndex.values()].flat().map((e) => [e.login.toLowerCase(), e])).values()]+ let slackEditors = editors+ if (SLACK_BOT_TOKEN) {+ try {+ slackEditors = await resolveSlackUsers(editors)+ } catch (err) {+ console.warn(`Slack user resolution failed - keeping GitHub links: ${err.message}`)+ }+ }+ const slackByLogin = new Map(slackEditors.map((e) => [e.login.toLowerCase(), e]))+ return (item) =>+ item.repoPaths?.length === 1+ ? (editorIndex.get(item.repoPaths[0]) || []).map((e) => slackByLogin.get(e.login.toLowerCase()))+ : []+}++async function main() {+ if (!PROJECT_ID || !API_KEY) {+ console.warn('POSTHOG_PROJECT_ID / POSTHOG_API_KEY not set - skipping report. Wire them to enable.')+ return+ }+ const now = new Date()+ // Built once so candidate filtering and owner resolution share one git ls-files.+ const toRepoPaths = repoPathResolver()+ const candidates = selectReportCandidates(await fetchSlowTests(), toRepoPaths)+ const top = rankReportCandidates(candidates)+ if (top.length === 0) {+ console.info('No slow tests above the floor this week - nothing to post.')+ return+ }+ const ownerFor = resolveOwners(top, toRepoPaths)+ const editorsFor = await resolveEditorsFor(top)+ const rows = tableRows(top, ownerFor, editorsFor)+ const blocks = buildBlocks(now, rows)+ if (DRY_RUN) {+ console.info(JSON.stringify(blocks, null, 2))+ return+ }+ if (!SLACK_BOT_TOKEN) {+ throw new Error('SLACK_BOT_TOKEN not set on a non-dry run - refusing to silently skip.')+ }+ await postToSlack(blocks, 'Weekly slow tests report')+ console.info('Posted weekly slow tests report.')+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((err) => {+ console.error(err)+ process.exit(1)+ })+}++export {+ buildBlocks,+ buildEditorCell,+ buildEditorIndex,+ buildEditors,+ fetchSlowTests,+ formatDurationSeconds,+ rankReportCandidates,+ resolveEditorsFor,+ resolveSlackUsers,+ selectReportCandidates,+ SLOW_TEST_VALUES,+ SLOW_TESTS_QUERY,+ tableRows,+}diff --git a/.github/scripts/weekly-slow-tests-report.test.mjs b/.github/scripts/weekly-slow-tests-report.test.mjsnew file mode 100644index 000000000000..93590be75925--- /dev/null+++ b/.github/scripts/weekly-slow-tests-report.test.mjs@@ -0,0 +1,249 @@+import assert from 'node:assert/strict'+import { describe, it } from 'node:test'++import {+ buildBlocks,+ buildEditorCell,+ buildEditorIndex,+ buildEditors,+ fetchSlowTests,+ formatDurationSeconds,+ rankReportCandidates,+ resolveSlackUsers,+ selectReportCandidates,+ tableRows,+} from './weekly-slow-tests-report.mjs'++const ITEM = {+ runner: 'pytest',+ selector: 'posthog/api/test/test_slow_thing.py::TestSlow::test_it_crawls',+ file: 'posthog/api/test/test_slow_thing.py',+ p50_seconds: 95.2,+ max_seconds: 121.4,+ builds: 18,+ repoPath: 'posthog/api/test/test_slow_thing.py',+}++const onMasterResolver = (path) => [path]++describe('weekly slow tests report', () => {+ it('scopes the span query to passed tests on master-side branches in this repo', async () => {+ const { repoPath: _repoPath, ...expected } = ITEM+ let captured+ const items = await fetchSlowTests(async (query, values) => {+ captured = { query, values }+ return { results: [[ITEM.runner, ITEM.selector, ITEM.file, 95.2, 121.4, 18]] }+ })++ assert.deepEqual(items, [expected])++ assert.match(captured.query, /attributes\['test\.outcome'\] = 'passed'/)+ assert.match(captured.query, /lower\(resource_attributes\['ci\.repository'\]\) = lower\(\{repository\}\)/)+ assert.match(captured.query, /ci\.branch'\] = {for_branch} OR resource_attributes\['ci\.branch'\] LIKE {merge_queue_glob}/)+ assert.match(captured.query, /GROUP BY/)+ assert.equal(captured.values.repository, 'PostHog/posthog')+ assert.equal(captured.values.for_branch, 'master')+ assert.equal(captured.values.merge_queue_glob, 'trunk-merge/%')+ assert.equal(captured.values.min_builds, 3)+ })++ it('keeps only tests whose file exists in the master checkout and caps the pool', () => {+ const items = Array.from({ length: 35 }, (_, index) => ({+ ...ITEM,+ selector: `file_${index}.py::test_${index}`,+ file: `file_${index}.py`,+ p50_seconds: 100 - index,+ }))+ items[34] = { ...items[34], file: 'products/new/backend/test_unmerged.py', selector: 'x.py::test_x' }+ const toRepoPaths = (path) => (path === 'products/new/backend/test_unmerged.py' ? [] : [path])++ const kept = selectReportCandidates(items, toRepoPaths)++ assert.equal(kept.length, 30)+ assert.ok(kept.every((item) => item.file !== 'products/new/backend/test_unmerged.py'))+ assert.deepEqual(kept[0].repoPaths, [items[0].file])+ })++ it('ranks by median duration, breaking ties on the max', () => {+ const items = [+ { ...ITEM, selector: 'a.py::test_a', p50_seconds: 40, max_seconds: 999 },+ { ...ITEM, selector: 'b.py::test_b', p50_seconds: 60, max_seconds: 61 },+ { ...ITEM, selector: 'c.py::test_c', p50_seconds: 40, max_seconds: 41 },+ ]++ assert.deepEqual(+ rankReportCandidates(items, 10).map((item) => item.selector),+ ['b.py::test_b', 'a.py::test_a', 'c.py::test_c']+ )+ assert.deepEqual(rankReportCandidates(items, 2).map((item) => item.selector), ['b.py::test_b', 'a.py::test_a'])+ })++ it('dedupes editors newest-first, skips bots, and caps at two', () => {+ const commits = [+ { sha: '1', commit: { author: { email: '[email protected]' } }, author: { login: 'adalovelace' } },+ { sha: '2', commit: { author: { email: '[email protected]' } }, author: { login: 'dependabot[bot]' } },+ { sha: '3', commit: { author: { email: '[email protected]' } }, author: { login: 'adalovelace' } },+ { sha: '4', commit: { author: { email: '[email protected]' } }, author: { login: 'ghopper' } },+ { sha: '5', commit: { author: { email: '[email protected]' } }, author: { login: 'aturing' } },+ { sha: '6', commit: { author: { email: '[email protected]' } }, author: null },+ ]++ assert.deepEqual(buildEditors(commits), [+ { login: 'adalovelace', email: '[email protected]' },+ { login: 'ghopper', email: '[email protected]' },+ ])+ assert.deepEqual(buildEditors([]), [])+ })++ it('resolves Slack ids by the login field first, then by email, else keeps the GitHub mention', async () => {+ const calls = []+ const slackFetch = async (url) => {+ calls.push(url)+ if (url.startsWith('users.list')) {+ return {+ ok: true,+ members: [+ { id: 'U1', profile: { login: 'adalovelace' } },+ { id: 'U3', name: 'aturing' },+ ],+ }+ }+ if (url.startsWith('users.lookupByEmail')) {+ const email = new URL(`https://slack.com/api/${url}`).searchParams.get('email')+ return email === '[email protected]'+ ? { ok: true, user: { id: 'U2' } }+ : { ok: false, error: 'users_not_found' }+ }+ return assert.fail(`unexpected Slack call: ${url}`)+ }++ const resolved = await resolveSlackUsers(+ [+ { login: 'adalovelace', email: '[email protected]' },+ { login: 'ghopper', email: '[email protected]' },+ { login: 'aturing', email: '[email protected]' },+ ],+ slackFetch+ )++ assert.deepEqual(resolved, [+ { login: 'adalovelace', email: '[email protected]', slackId: 'U1' },+ { login: 'ghopper', email: '[email protected]', slackId: 'U2' },+ { login: 'aturing', email: '[email protected]', slackId: 'U3' },+ ])+ assert.deepEqual(+ calls,+ ['users.list', 'users.lookupByEmail?email=grace%40example.com'],+ 'the member directory is fetched once for everyone; email lookup only fires for users it missed'+ )+ })++ it('renders resolved users as Slack mentions and the rest as GitHub links', () => {+ const cell = buildEditorCell([+ { login: 'adalovelace', email: '[email protected]', slackId: 'U1' },+ { login: 'aturing', email: '[email protected]', slackId: null },+ ])++ assert.deepEqual(cell, {+ type: 'rich_text',+ elements: [+ {+ type: 'rich_text_section',+ elements: [+ { type: 'user', user_id: 'U1' },+ { type: 'text', text: ', ' },+ { type: 'link', url: 'https://github.com/aturing', text: '@aturing' },+ ],+ },+ ],+ })+ assert.deepEqual(buildEditorCell([]), { type: 'raw_text', text: 'unknown' })+ })++ it('queries each file once and caches the login directory across files', async () => {+ const candidates = [+ { ...ITEM, file: 'a.py', repoPaths: ['a.py'] },+ { ...ITEM, selector: 'a.py::test_other', file: 'a.py', repoPaths: ['a.py'] },+ { ...ITEM, file: 'b.py', repoPaths: ['b.py'] },+ ]+ const githubCalls = []+ const editorIndex = await buildEditorIndex(+ candidates,+ async (url) => {+ githubCalls.push(url)+ assert.match(url, /^https:\/\/api\.github\.com\/repos\/PostHog\/posthog\/commits\?/)+ const path = new URL(url).searchParams.get('path')+ return [{ sha: '1', commit: { author: { email: `${path}@example.com` } }, author: { login: `editor-of-${path}` } }]+ }+ )++ assert.equal(githubCalls.length, 2)+ assert.equal(editorIndex.get('a.py').length, 1)+ assert.equal(editorIndex.get('a.py')[0].login, 'editor-of-a.py')+ assert.equal(editorIndex.get('b.py')[0].email, '[email protected]')+ })++ it('reports unknown editors instead of failing when the GitHub lookup errors', async () => {+ const editorIndex = await buildEditorIndex([{ ...ITEM, file: 'a.py', repoPaths: ['a.py'] }], async () => {+ throw new Error('rate limited')+ })++ assert.deepEqual(editorIndex.get('a.py'), [])+ })++ it('formats durations compactly', () => {+ const cases = [+ [45.3, '45s'],+ [89.9, '1m 30s'],+ [121.4, '2m 1s'],+ [59.9, '1m 0s'],+ [3.2, '3s'],+ ]+ for (const [seconds, expected] of cases) {+ assert.equal(formatDurationSeconds(seconds), expected, `${seconds}s`)+ }+ })++ it('builds a six-column Slack table with supported cells and structured links', () => {+ const editorFor = () => [{ login: 'adalovelace', email: '[email protected]', slackId: 'U1' }]+ const rows = tableRows(+ [ITEM],+ () => ({ owner: 'team-observability', repoPath: ITEM.file }),+ editorFor+ )+ const blocks = buildBlocks(new Date('2026-08-03T00:00:00Z'), rows)+ const table = blocks.find((block) => block.type === 'table')++ assert.ok(table)+ assert.deepEqual(+ table.rows[0].map((tableCell) => tableCell.text),+ ['test', 'p50', 'max', 'builds', 'owner', 'last edited by']+ )+ 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/api/test/test_slow_thing.py',+ text: 'test_it_crawls',+ },+ ],+ },+ ],+ })+ assert.deepEqual(rows[0][1], { type: 'raw_text', text: '1m 35s' })+ assert.deepEqual(rows[0][2], { type: 'raw_text', text: '2m 1s' })+ assert.deepEqual(rows[0][3], { type: 'raw_text', text: '18' })+ assert.deepEqual(rows[0][4], { type: 'raw_text', text: 'observability' })+ assert.deepEqual(+ blocks[0].text.text,+ '*Weekly slow tests - 2026-08-03* _(passing tests on master CI, last 7 days)_'+ )+ })+})diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 8e285ba4d96f..15ccf460fbc8 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -78,6 +78,10 @@ jobs:if: ${{ hashFiles('.github/scripts/weekly-flaky-report.test.mjs') != '' }}run: node --test .github/scripts/weekly-flaky-report.test.mjs+ - name: Weekly slow tests report tests (Node)+ if: ${{ hashFiles('.github/scripts/weekly-slow-tests-report.test.mjs') != '' }}+ run: node --test .github/scripts/weekly-slow-tests-report.test.mjs+- name: CLI npm installer patch tests (Node)if: ${{ hashFiles('.github/scripts/patch-cli-npm-installer.test.mjs') != '' }}run: node --test .github/scripts/patch-cli-npm-installer.test.mjsdiff --git a/.github/workflows/weekly-flaky-report.yml b/.github/workflows/weekly-flaky-report.ymlindex c9ab6cb61166..9d5468a4c2cc 100644--- a/.github/workflows/weekly-flaky-report.yml+++ b/.github/workflows/weekly-flaky-report.yml@@ -47,6 +47,7 @@ jobs:with:sparse-checkout: |.github/scripts/weekly-flaky-report.mjs+ .github/scripts/weekly-report-common.mjs.nvmrctools/ownersowners.yamldiff --git a/.github/workflows/weekly-slow-tests-report.yml b/.github/workflows/weekly-slow-tests-report.ymlnew file mode 100644index 000000000000..ee4a2a4666c8--- /dev/null+++ b/.github/workflows/weekly-slow-tests-report.yml@@ -0,0 +1,72 @@+name: Weekly slow test report++# Posts the week's slowest passing tests to #flakey-tests every Monday, tagging the+# people who last edited each test. PULL model, sibling of weekly-flaky-report.yml:+# the script reads the passing test spans CI already ships to PostHog (see+# .github/scripts/report_test_timings.py), resolves owners through tools/owners and+# recent editors through the GitHub commits API, and relays one table to Slack via+# the DevEx bot.+#+# Requires (no-ops with a warning until set, so it never spams failures):+# - vars.ENG_ANALYTICS_PROJECT_ID — the PostHog project the CI timing spans land in.+# - secrets.ENG_ANALYTICS_POSTHOG_API_KEY — a personal API key scoped to query:read+# for that project (the script queries the trace_spans store directly).+# - secrets.SLACK_DEVEX_BOT_TOKEN — the existing DevEx Slack bot. The users.list and+# users.lookupByEmail lookups degrade to plain GitHub links if the bot lacks+# users:read / users:read.email.+# GITHUB_TOKEN is the default Actions token: it only lists commits by path+# (contents:read) to find each test file's recent editors.++on:+ schedule:+ - cron: '30 13 * * 1' # Mondays 13:30 UTC, staggered after the flaky report+ workflow_dispatch:+ inputs:+ dry_run:+ description: 'Print the report blocks instead of posting to Slack'+ type: boolean+ default: true++permissions:+ contents: read++jobs:+ report:+ runs-on: ubuntu-latest+ # Worst case mirrors the flaky report: 3 HogQL attempts x 150s abort plus 2 x 30s+ # backoffs (~8.5min), plus checkout, owner resolution, and the editor lookups.+ 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.+ if: >-+ github.repository == 'PostHog/posthog' &&+ (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/master')+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ sparse-checkout: |+ .github/scripts/weekly-slow-tests-report.mjs+ .github/scripts/weekly-report-common.mjs+ .nvmrc+ tools/owners+ owners.yaml+ **/owners.yaml+ **/product.yaml+ sparse-checkout-cone-mode: false++ - uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0+ with:+ node-version-file: .nvmrc++ - name: Install owners resolver dependency+ run: python3 -m pip install --quiet pyyaml++ - name: Build and post weekly slow tests report+ # POSTHOG_HOST and SLACK_CHANNEL (#flakey-tests) ride the script's defaults.+ env:+ POSTHOG_PROJECT_ID: ${{ vars.ENG_ANALYTICS_PROJECT_ID }}+ POSTHOG_API_KEY: ${{ secrets.ENG_ANALYTICS_POSTHOG_API_KEY }}+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEVEX_BOT_TOKEN }}+ DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}+ run: node .github/scripts/weekly-slow-tests-report.mjs