: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
chore(ci): refactor reviewer assignment with footprint-based filtering (#60648)
Julian Bez05f82e27df10
diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.jsindex 25d706e35c2b..b66875564ae9 100644--- a/.github/scripts/assign-reviewers.js+++ b/.github/scripts/assign-reviewers.js@@ -2,6 +2,38 @@const fs = require('fs')+// Tunable knobs for how aggressively we trim the reviewer list. Kept in one+// place so adjusting noise levels doesn't require re-reading the logic. All+// "lines" values are GitHub's `changes` (additions + deletions) for the files+// an owner actually owns in this diff.+const CONFIG = {+ // Files whose changes are generated or mechanical. They never count toward+ // ownership matching or footprint — a team gains nothing from reviewing a+ // regenerated client or a lockfile bump.+ excludedPatterns: [+ 'frontend/src/generated/**',+ 'products/*/frontend/generated/**',+ 'services/mcp/src/**/generated/**',+ 'pnpm-lock.yaml',+ 'Cargo.lock',+ 'uv.lock',+ '**/*.lock',+ '**/*.snap',+ '**/*.ambr',+ ],+ // An owner is formally requested for review only if their footprint clears+ // one of these bars; otherwise they are demoted to the explanation comment+ // (still visible, can self-assign, but no review request / queue entry).+ substantiveLines: 10,+ substantiveFiles: 3,+ // Hard ceiling on teams formally requested. If more clear the bar, the+ // smallest-footprint teams are demoted to the comment so a sweeping change+ // can never request a wall of teams.+ maxTeamsRequested: 5,+ // Marker so we update our own comment in place instead of stacking copies.+ commentMarker: '<!-- auto-assign-reviewers -->',+}+function parseCodeowners(codeownersPath) {if (!fs.existsSync(codeownersPath)) {throw new Error(`No CODEOWNERS file found at "${codeownersPath}"`)@@ -134,6 +166,10 @@ function fileMatchesPattern(filePath, pattern) {return regex.test(filePath)}+function isExcludedFile(filePath, excludedPatterns = CONFIG.excludedPatterns) {+ return excludedPatterns.some((pattern) => fileMatchesPattern(filePath, pattern))+}+function getNextPageUrl(linkHeader) {if (!linkHeader) {return null@@ -169,7 +205,12 @@ async function getChangedFiles() {const data = await response.json()for (const file of data.files || []) {- allFiles.push(file.filename)+ allFiles.push({+ filename: file.filename,+ // Binary files and pure renames report null counts — treat as 0.+ additions: file.additions || 0,+ deletions: file.deletions || 0,+ })}url = getNextPageUrl(response.headers.get('Link'))@@ -178,78 +219,162 @@ async function getChangedFiles() {return allFiles}-function parseOwners(owners) {- const teams = new Set()- const users = new Set()-- for (const owner of owners) {- if (owner.startsWith('@PostHog/')) {- const teamName = owner.replace('@PostHog/', '')- teams.add(teamName)- } else if (owner.startsWith('@')) {- const username = owner.replace('@', '')- users.add(username)- }+// Resolve a raw CODEOWNERS owner token to a kind we can act on, or null if it's+// something we don't assign (e.g. a malformed entry).+function classifyOwner(owner) {+ if (owner.startsWith('@PostHog/')) {+ return { type: 'team', name: owner.replace('@PostHog/', ''), owner }}+ if (owner.startsWith('@')) {+ return { type: 'user', name: owner.replace('@', ''), owner }+ }+ return null+}- return {- teams: Array.from(teams),- users: Array.from(users),+// Build a footprint per owner: which rule patterns matched, which (non-excluded)+// files they own in this diff, and the total lines changed across those files.+// Pure function — takes already-fetched files so it's trivially testable.+function computeOwnerFootprints(rules, changedFiles, config = CONFIG) {+ const relevantFiles = changedFiles.filter((file) => !isExcludedFile(file.filename, config.excludedPatterns))+ const footprints = new Map()++ for (const rule of rules) {+ const matched = relevantFiles.filter((file) => fileMatchesPattern(file.filename, rule.pattern))+ if (matched.length === 0) {+ continue+ }++ for (const owner of rule.owners) {+ const resolved = classifyOwner(owner)+ if (!resolved) {+ continue+ }++ let footprint = footprints.get(owner)+ if (!footprint) {+ footprint = {+ owner,+ type: resolved.type,+ name: resolved.name,+ patterns: new Set(),+ files: new Map(), // filename -> changed lines, deduped across rules+ }+ footprints.set(owner, footprint)+ }++ footprint.patterns.add(rule.pattern)+ for (const file of matched) {+ footprint.files.set(file.filename, file.additions + file.deletions)+ }+ }}++ return Array.from(footprints.values()).map((footprint) => ({+ owner: footprint.owner,+ type: footprint.type,+ name: footprint.name,+ patterns: Array.from(footprint.patterns),+ fileCount: footprint.files.size,+ lines: Array.from(footprint.files.values()).reduce((sum, n) => sum + n, 0),+ }))}-async function getReviewersForChangedFiles() {- const codeownersPath = '.github/CODEOWNERS-soft'- // products/<name>/product.yaml is the source of truth for product team- // ownership; we layer those rules on top of CODEOWNERS-soft so the file- // only needs to carry sub-folder overrides and secondary reviewers.- const rules = [...parseCodeowners(codeownersPath), ...loadProductYamlRules()]- const changedFiles = await getChangedFiles()+function isSubstantive(footprint, config = CONFIG) {+ return footprint.lines >= config.substantiveLines || footprint.fileCount >= config.substantiveFiles+}- console.info(`Found ${changedFiles.length} changed files:`)- changedFiles.forEach((file) => console.info(` ${file}`))- console.info()+// Split matched owners into those we formally request review from vs those we+// only mention in the comment. Rules:+// - a single matched owner is always requested (never go from 1 owner to 0)+// - otherwise only owners with a substantive footprint are requested+// - at least one owner (the largest footprint) is always requested+// - teams are capped at maxTeamsRequested; the smallest overflow is demoted+function classifyOwners(footprints, config = CONFIG) {+ if (footprints.length === 0) {+ return { requested: [], demoted: [] }+ }- const allTeams = new Set()- const allUsers = new Set()+ const byFootprintDesc = (a, b) => b.lines - a.lines || b.fileCount - a.fileCount- console.info('Processing CODEOWNERS rules...')+ if (footprints.length === 1) {+ return { requested: [...footprints], demoted: [] }+ }- for (const rule of rules) {- const { pattern, owners } = rule- console.info(`Checking pattern: ${pattern}`)+ const requested = []+ const demoted = []+ for (const footprint of footprints) {+ if (isSubstantive(footprint, config)) {+ requested.push(footprint)+ } else {+ demoted.push({ ...footprint, reason: 'minor' })+ }+ }- let patternMatches = false+ // Guarantee at least one reviewer: promote the largest demoted owner.+ if (requested.length === 0) {+ demoted.sort(byFootprintDesc)+ const { reason, ...promoted } = demoted.shift()+ requested.push(promoted)+ }- for (const file of changedFiles) {- if (fileMatchesPattern(file, pattern)) {- console.info(` ✓ File ${file} matches pattern ${pattern}`)- patternMatches = true- break+ // Cap teams: keep the largest, demote the rest. Users are explicit, rare,+ // and intentional, so they're never capped.+ const requestedTeams = requested.filter((f) => f.type === 'team').sort(byFootprintDesc)+ if (requestedTeams.length > config.maxTeamsRequested) {+ const overflow = requestedTeams.slice(config.maxTeamsRequested)+ const overflowOwners = new Set(overflow.map((f) => f.owner))+ for (let i = requested.length - 1; i >= 0; i--) {+ if (overflowOwners.has(requested[i].owner)) {+ demoted.push({ ...requested.splice(i, 1)[0], reason: 'capped' })}}+ }- if (patternMatches) {- const { teams, users } = parseOwners(owners)+ requested.sort(byFootprintDesc)+ demoted.sort(byFootprintDesc)+ return { requested, demoted }+}- console.info(` Adding owners: ${owners.join(', ')}`)+function formatPatterns(patterns, max = 3) {+ const shown = patterns.slice(0, max).map((p) => `\`${p}\``)+ if (patterns.length > max) {+ shown.push(`(+${patterns.length - max} more)`)+ }+ return shown.join(', ')+}- teams.forEach((team) => {- allTeams.add(team)- console.info(` Team: ${team}`)- })+// Owners are rendered as inline code so the comment is informational and+// doesn't fire a round of @-mention notifications. The matched rule is the only+// locator worth showing — it tells the owner which area pulled them in. Raw+// file/line counts are intentionally omitted: without the actual file list (too+// long to include) a bare "10 files" tells the reader nothing actionable.+function formatSkippedOwner(footprint) {+ return `\`${footprint.owner}\` (${formatPatterns(footprint.patterns, 2)})`+}- users.forEach((user) => {- allUsers.add(user)- console.info(` User: ${user}`)- })- }+// Produce the explanation comment body, or null if no owner was dropped. We+// only post when we actually skipped someone GitHub's "Reviewers" sidebar would+// otherwise have hidden — so the comment carries signal, not noise.+function buildReviewerComment(requested, demoted, config = CONFIG) {+ if (demoted.length === 0) {+ return null}- return {- teams: Array.from(allTeams),- users: Array.from(allUsers),- }+ const allMinor = demoted.every((f) => f.reason === 'minor')+ const reason = allMinor+ ? 'they only have minor changes here'+ : 'their changes are minor or the reviewer list was getting long'++ return [+ config.commentMarker,+ '### 👥 Auto-assigned reviewers',+ '',+ `Skipped a review request for ${demoted.map(formatSkippedOwner).join(', ')} because ${reason}. ` ++ 'These are soft owners ' ++ '([`CODEOWNERS-soft`](https://github.com/PostHog/posthog/blob/master/.github/CODEOWNERS-soft) / ' ++ "each product's `product.yaml`), so nothing blocks merge — self-assign if you'd like a look. " ++ '(Generated files and lockfiles are ignored when deciding ownership.)',+ ].join('\n')}async function assignReviewers(teams, users) {@@ -331,9 +456,84 @@ async function assignReviewers(teams, users) {console.info('✅ Reviewers assigned successfully')}+async function findExistingComment(marker) {+ const { GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER } = process.env+ let url = `https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments?per_page=100`++ while (url) {+ const response = await fetch(url, {+ headers: {+ Authorization: `token ${GITHUB_TOKEN}`,+ Accept: 'application/vnd.github.v3+json',+ },+ })+ if (!response.ok) {+ throw new Error(`GitHub API error listing comments: ${response.status} ${response.statusText}`)+ }++ const comments = await response.json()+ const existing = comments.find((comment) => comment.body && comment.body.includes(marker))+ if (existing) {+ return existing+ }++ url = getNextPageUrl(response.headers.get('Link'))+ }++ return null+}++// Best-effort: posts/updates the explanation comment. Never throws — the+// reviewer assignment is the critical path and must not fail because the app+// token lacks `issues: write` or the comments API hiccups.+async function upsertReviewerComment(body) {+ const { GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER } = process.env++ try {+ const existing = await findExistingComment(CONFIG.commentMarker)+ const url = existing+ ? `https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/comments/${existing.id}`+ : `https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments`++ const method = existing ? 'PATCH' : 'POST'+ const response = await fetch(url, {+ method,+ headers: {+ Authorization: `token ${GITHUB_TOKEN}`,+ Accept: 'application/vnd.github.v3+json',+ 'Content-Type': 'application/json',+ },+ // oxlint-disable-next-line no-invalid-fetch-options -- method is always PATCH/POST, never GET+ body: JSON.stringify({ body }),+ })++ if (response.status === 403) {+ console.warn(+ '⚠️ Could not post the reviewer explanation comment (403). ' ++ 'The assign-reviewers GitHub App needs `issues: write` permission.'+ )+ return+ }+ if (!response.ok) {+ console.warn(`⚠️ Could not post reviewer comment: ${response.status} ${response.statusText}`)+ return+ }++ console.info(existing ? '✅ Reviewer comment updated' : '✅ Reviewer comment posted')+ } catch (error) {+ console.warn(`⚠️ Skipping reviewer comment: ${error.message}`)+ }+}+async function main() {const { BASE_SHA, HEAD_SHA, GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER } = process.env- const requiredEnvVars = { BASE_SHA, HEAD_SHA, GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER }+ const requiredEnvVars = {+ BASE_SHA,+ HEAD_SHA,+ GITHUB_TOKEN,+ GITHUB_REPOSITORY,+ PR_NUMBER,+ }const missing = Object.entries(requiredEnvVars).filter(([, value]) => !value).map(([name]) => name)@@ -344,18 +544,51 @@ async function main() {}try {- const { teams, users } = await getReviewersForChangedFiles()-+ const codeownersPath = '.github/CODEOWNERS-soft'+ // products/<name>/product.yaml is the source of truth for product team+ // ownership; we layer those rules on top of CODEOWNERS-soft so the file+ // only needs to carry sub-folder overrides and secondary reviewers.+ const rules = [...parseCodeowners(codeownersPath), ...loadProductYamlRules()]+ const changedFiles = await getChangedFiles()++ console.info(`Found ${changedFiles.length} changed files:`)+ changedFiles.forEach((file) => console.info(` ${file.filename} (+${file.additions} -${file.deletions})`))console.info()- console.info(`Teams to add: ${teams.join(', ') || 'none'}`)- console.info(`Users to add: ${users.join(', ') || 'none'}`)++ const footprints = computeOwnerFootprints(rules, changedFiles)+ const { requested, demoted } = classifyOwners(footprints)++ const teams = requested.filter((f) => f.type === 'team').map((f) => f.name)+ const users = requested.filter((f) => f.type === 'user').map((f) => f.name)++ console.info(`Teams to request: ${teams.join(', ') || 'none'}`)+ console.info(`Users to request: ${users.join(', ') || 'none'}`)+ console.info(`Demoted to comment: ${demoted.map((f) => f.owner).join(', ') || 'none'}`)console.info()await assignReviewers(teams, users)++ const commentBody = buildReviewerComment(requested, demoted)+ if (commentBody) {+ await upsertReviewerComment(commentBody)+ }} catch (error) {console.error('Error:', error.message)process.exit(1)}}-main()+if (require.main === module) {+ main()+}++module.exports = {+ CONFIG,+ isExcludedFile,+ classifyOwner,+ computeOwnerFootprints,+ isSubstantive,+ classifyOwners,+ buildReviewerComment,+ fileMatchesPattern,+}diff --git a/.github/scripts/assign-reviewers.test.js b/.github/scripts/assign-reviewers.test.jsnew file mode 100644index 000000000000..34df79979d26--- /dev/null+++ b/.github/scripts/assign-reviewers.test.js@@ -0,0 +1,220 @@+const {+ CONFIG,+ isExcludedFile,+ classifyOwner,+ computeOwnerFootprints,+ isSubstantive,+ classifyOwners,+ buildReviewerComment,+} = require('./assign-reviewers')++const file = (filename, additions = 0, deletions = 0) => ({+ filename,+ additions,+ deletions,+})+const rule = (pattern, ...owners) => ({ pattern, owners })++describe('assign-reviewers', () => {+ describe('isExcludedFile', () => {+ test.each([+ ['frontend/src/generated/core/api.ts', true],+ ['frontend/src/generated/core/api.schemas.ts', true],+ ['products/surveys/frontend/generated/api.zod.ts', true],+ ['services/mcp/src/tools/generated/surveys.ts', true],+ ['pnpm-lock.yaml', true],+ ['rust/Cargo.lock', true],+ ['uv.lock', true],+ ['posthog/api/test/__snapshots__/test_survey.ambr', true],+ ['frontend/src/scenes/x/Component.test.tsx.snap', true],+ ['posthog/api/survey.py', false],+ ['frontend/src/scenes/surveys/Survey.tsx', false],+ ])('%s -> %s', (filename, expected) => {+ expect(isExcludedFile(filename)).toBe(expected)+ })+ })++ describe('classifyOwner', () => {+ test.each([+ ['@PostHog/team-surveys', { type: 'team', name: 'team-surveys', owner: '@PostHog/team-surveys' }],+ ['@rafaeelaudibert', { type: 'user', name: 'rafaeelaudibert', owner: '@rafaeelaudibert' }],+ ['not-an-owner', null],+ ])('%s', (input, expected) => {+ expect(classifyOwner(input)).toEqual(expected)+ })+ })++ describe('computeOwnerFootprints', () => {+ test('ignores generated/excluded files when matching ownership', () => {+ const rules = [+ rule('posthog/api/survey.py', '@PostHog/team-surveys'),+ rule('frontend/src/generated/**', '@PostHog/team-devex'),+ ]+ const files = [file('posthog/api/survey.py', 40, 10), file('frontend/src/generated/core/api.ts', 999, 999)]++ const footprints = computeOwnerFootprints(rules, files)++ expect(footprints).toHaveLength(1)+ expect(footprints[0]).toMatchObject({+ owner: '@PostHog/team-surveys',+ type: 'team',+ fileCount: 1,+ lines: 50,+ })+ })++ test('dedupes a file owned via multiple rules and sums lines once', () => {+ const rules = [+ rule('posthog/hogql/**', '@PostHog/team-data-tools'),+ rule('posthog/hogql/printer.py', '@PostHog/team-data-tools'),+ ]+ const files = [file('posthog/hogql/printer.py', 5, 3)]++ const [footprint] = computeOwnerFootprints(rules, files)++ expect(footprint.fileCount).toBe(1)+ expect(footprint.lines).toBe(8)+ expect(footprint.patterns).toEqual(expect.arrayContaining(['posthog/hogql/**', 'posthog/hogql/printer.py']))+ })+ })++ describe('isSubstantive', () => {+ test.each([+ [{ lines: 50, fileCount: 1 }, true],+ [{ lines: 2, fileCount: 5 }, true],+ [{ lines: 2, fileCount: 1 }, false],+ [{ lines: CONFIG.substantiveLines, fileCount: 1 }, true],+ [{ lines: 0, fileCount: CONFIG.substantiveFiles }, true],+ ])('%o -> %s', (footprint, expected) => {+ expect(isSubstantive(footprint)).toBe(expected)+ })+ })++ describe('classifyOwners', () => {+ const fp = (owner, lines, fileCount = 1, type = 'team') => ({+ owner,+ type,+ name: owner.replace('@PostHog/', '').replace('@', ''),+ patterns: [owner],+ fileCount,+ lines,+ })++ test('a single matched owner is always requested, even when tiny', () => {+ const { requested, demoted } = classifyOwners([fp('@PostHog/team-a', 1)])+ expect(requested).toHaveLength(1)+ expect(demoted).toHaveLength(0)+ })++ test('demotes owners below the substantive bar but keeps substantive ones', () => {+ const { requested, demoted } = classifyOwners([fp('@PostHog/team-big', 120), fp('@PostHog/team-small', 2)])+ expect(requested.map((f) => f.owner)).toEqual(['@PostHog/team-big'])+ expect(demoted.map((f) => f.owner)).toEqual(['@PostHog/team-small'])+ expect(demoted[0].reason).toBe('minor')+ })++ test('promotes the largest owner when all are below the bar', () => {+ const { requested, demoted } = classifyOwners([+ fp('@PostHog/team-a', 1),+ fp('@PostHog/team-b', 4),+ fp('@PostHog/team-c', 2),+ ])+ expect(requested.map((f) => f.owner)).toEqual(['@PostHog/team-b'])+ // The promoted owner is a clean request, not a demotion.+ expect(requested[0].reason).toBeUndefined()+ expect(demoted.map((f) => f.owner)).toEqual(['@PostHog/team-c', '@PostHog/team-a'])+ })++ test('caps requested teams at maxTeamsRequested, demoting the smallest', () => {+ const footprints = Array.from({ length: CONFIG.maxTeamsRequested + 3 }, (_, i) =>+ fp(`@PostHog/team-${i}`, 50 + i)+ )+ const { requested, demoted } = classifyOwners(footprints)++ expect(requested.filter((f) => f.type === 'team')).toHaveLength(CONFIG.maxTeamsRequested)+ expect(demoted).toHaveLength(3)+ // Largest footprints are kept; the three smallest are demoted as capped.+ expect(requested.some((f) => f.owner === `@PostHog/team-${footprints.length - 1}`)).toBe(true)+ expect(demoted.map((f) => f.owner)).toEqual(+ expect.arrayContaining(['@PostHog/team-0', '@PostHog/team-1', '@PostHog/team-2'])+ )+ expect(demoted.every((f) => f.reason === 'capped')).toBe(true)+ })++ test('never caps explicit users even when teams overflow the cap', () => {+ // All substantive, so the cap (teams-only) is the only thing that can demote.+ const teams = Array.from({ length: CONFIG.maxTeamsRequested + 2 }, (_, i) =>+ fp(`@PostHog/team-${i}`, 50 + i)+ )+ const users = [fp('@user-a', 20, 1, 'user'), fp('@user-b', 20, 1, 'user')]+ const { requested, demoted } = classifyOwners([...teams, ...users])++ // Both users survive the cap...+ expect(+ requested+ .filter((f) => f.type === 'user')+ .map((f) => f.owner)+ .sort()+ ).toEqual(['@user-a', '@user-b'])+ // ...while the smallest teams beyond the cap are demoted.+ expect(requested.filter((f) => f.type === 'team')).toHaveLength(CONFIG.maxTeamsRequested)+ expect(demoted.map((f) => f.owner)).toEqual(expect.arrayContaining(['@PostHog/team-0', '@PostHog/team-1']))+ expect(demoted.every((f) => f.type === 'team')).toBe(true)+ })+ })++ describe('buildReviewerComment', () => {+ const requested = [+ {+ owner: '@PostHog/team-surveys',+ fileCount: 2,+ lines: 135,+ patterns: ['products/surveys/**'],+ },+ ]+ const demoted = [+ {+ owner: '@PostHog/team-data-tools',+ fileCount: 1,+ lines: 2,+ patterns: ['posthog/hogql/**'],+ reason: 'minor',+ },+ ]++ test('returns null when no owner was dropped', () => {+ expect(buildReviewerComment(requested, [])).toBeNull()+ expect(buildReviewerComment([...requested, requested[0]], [])).toBeNull()+ })++ test('names each skipped owner with its matched rule, not raw counts', () => {+ const body = buildReviewerComment(requested, demoted)+ expect(body).toContain(CONFIG.commentMarker)+ expect(body).toContain('Skipped a review request for `@PostHog/team-data-tools` (`posthog/hogql/**`)')+ expect(body).toContain('they only have minor changes here')+ // No count theater: file/line numbers are internal-only.+ expect(body).not.toMatch(/\d+ files/)+ expect(body).not.toContain('| Lines |')+ })++ test('explains the reviewer cap when an owner was capped out', () => {+ const cappedDemoted = [{ ...demoted[0], reason: 'capped' }]+ const body = buildReviewerComment(requested, cappedDemoted)+ expect(body).toContain('the reviewer list was getting long')+ })++ test('truncates long pattern lists', () => {+ const manyDemoted = [+ {+ owner: '@PostHog/team-x',+ fileCount: 1,+ lines: 1,+ patterns: ['a/**', 'b/**', 'c/**', 'd/**', 'e/**'],+ reason: 'minor',+ },+ ]+ const body = buildReviewerComment(requested, manyDemoted)+ expect(body).toContain('(+3 more)')+ })+ })+})