Skip to content

: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.

feat(ci): shadow per-team slices in weekly flaky report (#89677)

Raúl Negrón-Otero5632330080e6
diff --git a/.github/scripts/weekly-flaky-report.mjs b/.github/scripts/weekly-flaky-report.mjs
index cb70ac5fe667..0007d36650c3 100644
--- a/.github/scripts/weekly-flaky-report.mjs
+++ b/.github/scripts/weekly-flaky-report.mjs
@@ -391,6 +391,66 @@ function tableRows(items, ownerFor, extrasFor, statusFor = () => null) {
})
}
+// 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.
+function buildTeamDigests(entries) {
+ const byOwner = new Map()
+ for (const { owner, slack, row } of entries) {
+ if (owner === 'unowned' || !slack) {
+ continue
+ }
+ if (!byOwner.has(owner)) {
+ byOwner.set(owner, { owner, channel: slack, rows: [] })
+ }
+ byOwner.get(owner).rows.push(row)
+ }
+ return [...byOwner.values()].sort((a, b) => b.rows.length - a.rows.length)
+}
+
+function flakyTable(rows) {
+ return {
+ type: 'table',
+ column_settings: [
+ { align: 'left' },
+ { align: 'left' },
+ { align: 'left' },
+ { align: 'left' },
+ { align: 'right' },
+ { align: 'right' },
+ { align: 'right' },
+ { align: 'left' },
+ ],
+ rows: [
+ [
+ cell('test'),
+ cell('runner'),
+ cell('owner'),
+ cell('quarantined'),
+ cell('PRs'),
+ cell('rescued'),
+ cell('fails'),
+ cell('logs'),
+ ],
+ ...rows,
+ ],
+ }
+}
+
+function buildShadowBlocks({ owner, channel, rows }) {
+ return [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*${owner.replace(/^team-/, '')}* _(shadow: would post to ${channel})_`,
+ },
+ },
+ flakyTable(rows),
+ ]
+}
+
function buildBlocks(now, rows) {
const dateLabel = now.toISOString().slice(0, 10)
const blocks = [
@@ -401,32 +461,7 @@ function buildBlocks(now, rows) {
text: `*Weekly flaky tests - ${dateLabel}* _(CI, last 7 days, up to ${TOP_N} per runner)_`,
},
},
- {
- type: 'table',
- column_settings: [
- { align: 'left' },
- { align: 'left' },
- { align: 'left' },
- { align: 'left' },
- { align: 'right' },
- { align: 'right' },
- { align: 'right' },
- { align: 'left' },
- ],
- rows: [
- [
- cell('test'),
- cell('runner'),
- cell('owner'),
- cell('quarantined'),
- cell('PRs'),
- cell('rescued'),
- cell('fails'),
- cell('logs'),
- ],
- ...rows,
- ],
- },
+ flakyTable(rows),
]
const editBlock = editWorkflowBlock()
if (editBlock) {
@@ -450,19 +485,41 @@ async function main() {
return
}
const ownerFor = resolveOwners(reportCandidates, toRepoPaths)
- const rows = runnerReports.flatMap(({ candidates, extrasFor, statusFor }) =>
- tableRows(candidates, ownerFor, extrasFor, statusFor)
+ // Rendered once; the channel table and the per-team slices share the same rows.
+ const entries = runnerReports.flatMap(({ candidates, extrasFor, statusFor }) => {
+ const reportRows = tableRows(candidates, ownerFor, extrasFor, statusFor)
+ return candidates.map((item, index) => ({ ...ownerFor(item), row: reportRows[index] }))
+ })
+ const blocks = buildBlocks(
+ now,
+ entries.map(({ row }) => row)
)
- const blocks = buildBlocks(now, rows)
+ const teamDigests = buildTeamDigests(entries)
if (DRY_RUN) {
console.info(JSON.stringify(blocks, null, 2))
+ console.info(JSON.stringify(teamDigests.map(buildShadowBlocks), 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 flaky test report')
+ const digestTs = 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.`)
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
@@ -474,6 +531,8 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
export {
buildBlocks,
+ buildShadowBlocks,
+ buildTeamDigests,
buildRunnerReports,
CLUSTER_MIN_TESTS,
enrich,
diff --git a/.github/scripts/weekly-flaky-report.test.mjs b/.github/scripts/weekly-flaky-report.test.mjs
index 9c14cf306967..607b31ce8f9b 100644
--- a/.github/scripts/weekly-flaky-report.test.mjs
+++ b/.github/scripts/weekly-flaky-report.test.mjs
@@ -3,6 +3,8 @@ import { describe, it } from 'node:test'
import {
buildBlocks,
+ buildShadowBlocks,
+ buildTeamDigests,
buildRunnerReports,
CLUSTER_MIN_TESTS,
enrich,
@@ -392,6 +394,31 @@ describe('weekly flaky report', () => {
assert.deepEqual(clusterRow[4], { type: 'raw_text', text: '1+' })
})
+ it('groups shadow digests by owning team and drops teams it cannot route', () => {
+ const row = (name) => [{ type: 'raw_text', text: name }]
+ const entries = [
+ { owner: 'team-devex', slack: '#team-devex', row: row('test_one') },
+ { owner: 'team-devex', slack: '#team-devex', row: row('test_two') },
+ { owner: 'team-replay', slack: '#team-replay', row: row('renders') },
+ { owner: 'unowned', slack: null, row: row('test_orphan') },
+ // notifications: false, owned but the team declared no automation channel.
+ { owner: 'team-quiet', slack: null, row: row('test_silenced') },
+ ]
+
+ const digests = buildTeamDigests(entries)
+
+ assert.deepEqual(
+ digests.map(({ owner, channel, rows }) => [owner, channel, rows.length]),
+ [
+ ['team-devex', '#team-devex', 2],
+ ['team-replay', '#team-replay', 1],
+ ]
+ )
+ const [header, table] = buildShadowBlocks(digests[0])
+ assert.equal(header.text.text, '*devex* _(shadow: would post to #team-devex)_')
+ assert.equal(table.rows.length, 3)
+ })
+
it('matches a Jest selector reported from the package root against Trunk', async () => {
const trunkFor = await fetchTrunkQuarantined(
'jest',
diff --git a/.github/scripts/weekly-report-common.mjs b/.github/scripts/weekly-report-common.mjs
index ec74e249e6fa..b48ad0bb851a 100644
--- a/.github/scripts/weekly-report-common.mjs
+++ b/.github/scripts/weekly-report-common.mjs
@@ -105,6 +105,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()) {
const candidates = new Map()
for (const item of items) {
@@ -117,7 +118,7 @@ export function resolveOwners(items, toRepoPaths = repoPathResolver()) {
let resolved = {}
if (allPaths.length > 0) {
try {
- const out = execFileSync('python3', ['-m', 'posthog_owners'], {
+ const out = execFileSync('python3', ['-m', 'posthog_owners', '--purpose', 'notifications'], {
encoding: 'utf8',
input: allPaths.join('\n'),
env: { ...process.env, PYTHONPATH: 'tools/owners' },
@@ -133,7 +134,8 @@ export function resolveOwners(items, toRepoPaths = repoPathResolver()) {
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 }
+ const slack = owner === 'unowned' ? null : (resolved[paths[0]]?.slack ?? null)
+ return { owner, repoPath: paths.length === 1 ? paths[0] : null, slack }
}
}
@@ -164,15 +166,16 @@ export function editWorkflowBlock() {
return { type: 'context', elements: [{ type: 'mrkdwn', text: `<${editUrl}|edit this workflow>` }] }
}
-export async function postToSlack(blocks, text) {
+export async function postToSlack(blocks, text, { threadTs, channel = SLACK_CHANNEL } = {}) {
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,
+ channel,
blocks,
text, // notification fallback
unfurl_links: false,
+ thread_ts: threadTs || undefined,
}),
})
const data = await res.json()
@@ -182,4 +185,5 @@ export async function postToSlack(blocks, text) {
: ''
throw new Error(`Slack chat.postMessage failed: ${data.error}${validationDetails}`)
}
+ return data.ts
}
diff --git a/.github/workflows/weekly-flaky-report.yml b/.github/workflows/weekly-flaky-report.yml
index 3f2d71880026..5ed74b18601d 100644
--- a/.github/workflows/weekly-flaky-report.yml
+++ b/.github/workflows/weekly-flaky-report.yml
@@ -2,8 +2,9 @@ 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 one table to
-# Slack via the DevEx bot — it does not re-derive the flake signal. Owner
+# 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
# attribution runs in the script through the tools/owners resolver, which is why
# the sparse checkout includes the ownership files.
#
diff --git a/tools/owners/posthog_owners/__main__.py b/tools/owners/posthog_owners/__main__.py
index 728877400aa5..2ab4da2ae99f 100644
--- a/tools/owners/posthog_owners/__main__.py
+++ b/tools/owners/posthog_owners/__main__.py
@@ -5,6 +5,9 @@ JSON object keyed by normalized path to stdout::
{"<path>": {"owners": [...], "status": "...", "slack": "...|null", "source": "...|null"}}
+``--purpose notifications`` resolves ``slack`` to the team's automation channel
+(falls back to the people channel); the default is the people channel.
+
Kept off click on purpose (stdlib + pyyaml only) so a workflow can run it with
``python -m posthog_owners`` after installing just pyyaml — no hogli, no
project sync. The click CLI (``hogli owners:resolve --json``) emits the identical
@@ -15,16 +18,21 @@ from __future__ import annotations
import sys
import json
+import argparse
+from typing import cast
from .matcher import normalize_path
-from .resolver import OwnersResolver, read_stdin_paths, resolution_to_wire
+from .resolver import DEFAULT_PURPOSE, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wire
def main() -> None:
- args = sys.argv[1:]
- paths = args if args else read_stdin_paths()
+ parser = argparse.ArgumentParser(prog="python -m posthog_owners")
+ parser.add_argument("--purpose", choices=["slack", "notifications"], default=DEFAULT_PURPOSE)
+ parser.add_argument("paths", nargs="*")
+ ns = parser.parse_args()
+ paths = ns.paths or read_stdin_paths()
- resolver = OwnersResolver()
+ resolver = OwnersResolver(purpose=cast("Purpose", ns.purpose))
result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in paths}
json.dump(result, sys.stdout)
diff --git a/tools/owners/posthog_owners/cli.py b/tools/owners/posthog_owners/cli.py
index 9ba0c2ed4ecb..df4d2c97d016 100644
--- a/tools/owners/posthog_owners/cli.py
+++ b/tools/owners/posthog_owners/cli.py
@@ -6,11 +6,12 @@ import sys
import json
import subprocess
from collections import defaultdict
+from typing import cast
import click
from .matcher import compile_pattern, normalize_path
-from .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersResolver, read_stdin_paths, resolution_to_wire
+from .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wire
from .schema import is_simple_owners_file, normalize_product_owners
@@ -25,9 +26,15 @@ def _read_paths(paths: tuple[str, ...]) -> list[str]:
@click.command(name="owners:resolve", help="Resolve ownership for paths (args or newline-delimited stdin)")
@click.option("--json", "as_json", is_flag=True, help="Emit JSON keyed by path")
+ "--purpose",
+ type=click.Choice(["slack", "notifications"]),
+ default="slack",
+ help="Which team channel `slack` resolves to: where people are, or where automation posts",
+)
@click.argument("paths", nargs=-1)
-def cmd_resolve(as_json: bool, paths: tuple[str, ...]) -> None:
- resolver = OwnersResolver()
+def cmd_resolve(as_json: bool, purpose: str, paths: tuple[str, ...]) -> None:
+ resolver = OwnersResolver(purpose=cast(Purpose, purpose))
targets = _read_paths(paths)
result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in targets}
if as_json:
diff --git a/tools/owners/posthog_owners/fmt.py b/tools/owners/posthog_owners/fmt.py
index bc672ad6c0ea..d468f1daed90 100644
--- a/tools/owners/posthog_owners/fmt.py
+++ b/tools/owners/posthog_owners/fmt.py
@@ -572,9 +572,7 @@ class _InMemoryResolver(OwnersResolver):
disk — used to prove the proposed layout resolves identically."""
def __init__(self, repo_root: Path, files: dict[str, OwnersFile]) -> None:
- self.repo_root = repo_root
- self._dir_cache = {}
- self._teams_cache = None
+ super().__init__(repo_root)
self._files = files
def _load_dir_file(self, directory: str) -> OwnersFile | None: # type: ignore[override]
diff --git a/tools/owners/posthog_owners/resolver.py b/tools/owners/posthog_owners/resolver.py
index da234e01e8f3..5fd03a95f9d4 100644
--- a/tools/owners/posthog_owners/resolver.py
+++ b/tools/owners/posthog_owners/resolver.py
@@ -150,8 +150,9 @@ class OwnersResolver:
with ``repo_root`` for testing). Parsed files are cached per directory.
"""
- def __init__(self, repo_root: Path | None = None) -> None:
+ def __init__(self, repo_root: Path | None = None, purpose: Purpose = DEFAULT_PURPOSE) -> None:
self.repo_root = (repo_root or _git_repo_root()).resolve()
+ self.purpose = purpose
self._dir_cache: dict[str, OwnersFile | None] = {}
# The worktree is treated as immutable for the resolver's lifetime.
self._tracked_cache: dict[str | None, list[str]] = {}
@@ -273,7 +274,7 @@ class OwnersResolver:
(team slugs only), then the derived ``#<slug>``, else None. Only a team slug
(not an ``@handle``) carries a channel."""
if owners and not owners[0].startswith("@"):
- return team_channel(owners[0], self._teams_registry()).channel
+ return team_channel(owners[0], self._teams_registry(), self.purpose).channel
return None
def _build_resolution(self, path: str, merged: _Merged) -> Resolution:
diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.py
index 2cb1f8df4ca8..0886ed5b418a 100644
--- a/tools/owners/tests/test_owners.py
+++ b/tools/owners/tests/test_owners.py
@@ -232,26 +232,31 @@ def registry_repo(tmp_path: Path) -> Path:
"owners.yaml",
"version: 1\nowners: []\nteams:\n"
" team-registry:\n slack: '#registry-chan'\n"
- " team-silent:\n slack: false\n",
+ " team-silent:\n slack: false\n"
+ " team-split:\n slack: '#split-people'\n notifications: '#split-bots'\n",
)
_write(tmp_path, "reg/owners.yaml", "version: 1\nowners: [team-registry]\n")
_write(tmp_path, "silent/owners.yaml", "version: 1\nowners: [team-silent]\n")
_write(tmp_path, "derive/owners.yaml", "version: 1\nowners: [team-nonreg]\n")
_write(tmp_path, "indiv/owners.yaml", "version: 1\nowners: ['@alice', team-registry]\n")
+ _write(tmp_path, "split/owners.yaml", "version: 1\nowners: [team-split]\n")
return tmp_path
@pytest.mark.parametrize(
- "path,slack",
+ "path,purpose,slack",
[
- ("reg/x.py", "#registry-chan"), # registry hit for the primary owner beats derived
- ("silent/x.py", None), # registry false suppresses derivation
- ("derive/x.py", "#team-nonreg"), # no registry entry: derive #<primary owner>
- ("indiv/x.py", None), # primary owner is an @handle: registry ignored, no derive
+ ("reg/x.py", "slack", "#registry-chan"), # registry hit for the primary owner beats derived
+ ("silent/x.py", "slack", None), # registry false suppresses derivation
+ ("derive/x.py", "slack", "#team-nonreg"), # no registry entry: derive #<primary owner>
+ ("indiv/x.py", "slack", None), # primary owner is an @handle: registry ignored, no derive
+ ("split/x.py", "slack", "#split-people"), # a declared notifications channel stays off the people lookup
+ ("split/x.py", "notifications", "#split-bots"), # automation resolves to the declared bot channel
+ ("reg/x.py", "notifications", "#registry-chan"), # no notifications entry: automation follows the people
],
)
-def test_slack_registry_precedence(registry_repo: Path, path: str, slack: str | None) -> None:
- assert OwnersResolver(repo_root=registry_repo).resolve(path).slack == slack
+def test_slack_registry_precedence(registry_repo: Path, path: str, purpose: str, slack: str | None) -> None:
+ assert OwnersResolver(repo_root=registry_repo, purpose=purpose).resolve(path).slack == slack
def test_teams_registry_is_root_only(tmp_path: Path) -> None: