: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): start master-red agent via webhook (#91720)
Raúl Negrón-Oteroc69460397f06
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.jsindex 43ff26686a32..85bb95fa700d 100644--- a/.github/scripts/ci-alerts-devex.js+++ b/.github/scripts/ci-alerts-devex.js@@ -62,6 +62,12 @@ const SCHEDULED_RUN_INDEX_MAX_LAG_MINUTES = 360const SCHEDULED_LANE_LABEL = '(scheduled)'const STALE_PAGE_RETRIES = 2const STALE_PAGE_RETRY_DELAY_MS = 15000+// The workflow behind the webhook reads `properties.channel` and `properties.ts` to reply in the+// alert thread, so dropping either from the payload leaves the agent's answer with nowhere to land.+const INCIDENT_OPENED_EVENT = 'master_ci_incident_opened'+const WEBHOOK_ATTEMPTS = 3+const WEBHOOK_RETRY_DELAY_MS = 2000+const WEBHOOK_TIMEOUT_MS = 10000const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))@@ -337,6 +343,33 @@ function defaultSlackClient(token, fetchImpl) {}}+// Only an incident's first tick calls this, so a start lost here is never retried by a later tick.+async function startDiagnosisAgent({ url, fetchImpl, sleep, core }, payload) {+ if (!url) {return false}+ // The url is the only thing guarding the endpoint, and a variable is not masked in this public+ // repo's logs, so register it before any code path can print it.+ core.setSecret(url)+ const doFetch = fetchImpl || fetch+ let lastError = 'unknown'+ for (let attempt = 1; attempt <= WEBHOOK_ATTEMPTS; attempt++) {+ try {+ const res = await doFetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),+ })+ if (res.ok) {return true}+ lastError = `HTTP ${res.status}`+ } catch (err) {+ lastError = err.message+ }+ if (attempt < WEBHOOK_ATTEMPTS) {await sleep(WEBHOOK_RETRY_DELAY_MS * attempt)}+ }+ core.setFailed(`Could not start the diagnosis agent after ${WEBHOOK_ATTEMPTS} attempts: ${lastError}`)+ return false+}+// The bot's own open incident, identified purely by message metadata — no other// app sets this event_type, so it is unambiguous without knowing our bot id.async function findActiveIncident(slack, channel) {@@ -601,6 +634,22 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fthread_ts: posted.ts,text: buildThreadReply({ created: workflows, commitStarted: commitActive }),})+ await startDiagnosisAgent(+ { url: process.env.DIAGNOSIS_WEBHOOK_URL, fetchImpl: _fetch, sleep, core },+ {+ event: INCIDENT_OPENED_EVENT,+ distinct_id: 'ci-alerts-devex',+ properties: {+ channel,+ ts: posted.ts,+ workflows: workflows.map((w) => w.name),+ commit_streak: commitActive ? commitStreakCount : 0,+ since,+ latest_commit_sha: latestCommit?.sha || '',+ all_failing_runs_url: allFailingRunsUrl,+ },+ }+ )action = 'create'} else {await slack.update({ channel, ts: active.ts, ...message, metadata, unfurl_links: false })diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.jsindex 345d036d3f90..a74519b6a03a 100644--- a/.github/scripts/ci-alerts-devex.test.js+++ b/.github/scripts/ci-alerts-devex.test.js@@ -133,9 +133,25 @@ const commitsAt = (ageMins) => [},]-function run(github, { history = [], now = minutes(0), env = {} } = {}) {+// Stand-in for the diagnosis webhook endpoint, one status per attempt.+function makeWebhook(statuses = [200]) {+ let call = 0+ return recordingFn(() => {+ const status = statuses[Math.min(call++, statuses.length - 1)]+ return Promise.resolve({ ok: status >= 200 && status < 300, status })+ })+}++function run(github, { history = [], now = minutes(0), env = {}, fetch: fetchImpl } = {}) {const outputs = {}- const core = { setOutput: (k, v) => (outputs[k] = v), info: () => {}, warning: () => {} }+ const failures = []+ const core = {+ setOutput: (k, v) => (outputs[k] = v),+ info: () => {},+ warning: () => {},+ setFailed: (m) => failures.push(m),+ setSecret: () => {},+ }const slack = makeSlack(history)Object.assign(process.env, {SLACK_CHANNEL: 'C0AS64N6DJL',@@ -148,12 +164,13 @@ function run(github, { history = [], now = minutes(0), env = {} } = {}) {SCHEDULED_FAILURE_MINUTES_THRESHOLD: '150',ACTIVITY_WINDOW_MINUTES: '120',COMMIT_FAILURE_STREAK_THRESHOLD: '10',+ DIAGNOSIS_WEBHOOK_URL: '',...env,})return ciAlertsDevex({ context: { repo: { owner: 'PostHog', repo: 'posthog' } }, github, core },- { now, slack, sleep: () => Promise.resolve() }- ).then(() => ({ slack, outputs }))+ { now, slack, fetch: fetchImpl, sleep: () => Promise.resolve() }+ ).then(() => ({ slack, outputs, failures }))}describe('ci-alerts-devex', () => {@@ -201,6 +218,72 @@ describe('ci-alerts-devex', () => {})}+ describe('diagnosis agent start', () => {+ const webhookEnv = { DIAGNOSIS_WEBHOOK_URL: 'https://webhooks.test/start' }+ const fiveFailures = () =>+ createGithubMock({+ 'ci-backend.yml': runs('Backend CI', Array(5).fill('failure')),+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ })++ it('posts the incident and the anchor thread it must answer in', async () => {+ const fetch = makeWebhook()+ const { outputs, failures } = await run(fiveFailures(), { env: webhookEnv, fetch })++ assert.equal(outputs.action, 'create')+ assert.deepEqual(failures, [])+ assert.equal(fetch.calls.length, 1)++ const [url, init] = fetch.calls[0]+ assert.equal(url, 'https://webhooks.test/start')+ const body = JSON.parse(init.body)+ assert.equal(body.event, 'master_ci_incident_opened')+ assert.equal(body.properties.channel, 'C0AS64N6DJL')+ assert.equal(body.properties.ts, '111.222') // the anchor, so the agent replies under it+ assert.deepEqual(body.properties.workflows, ['Backend CI'])+ })++ it('retries a failed start rather than losing it', async () => {+ const fetch = makeWebhook([502, 200])+ const { failures } = await run(fiveFailures(), { env: webhookEnv, fetch })++ assert.equal(fetch.calls.length, 2)+ assert.deepEqual(failures, [])+ })++ it('fails the run when the start never lands', async () => {+ const fetch = makeWebhook([500])+ const { outputs, failures } = await run(fiveFailures(), { env: webhookEnv, fetch })++ assert.equal(fetch.calls.length, 3)+ assert.equal(failures.length, 1)+ assert.match(failures[0], /HTTP 500/)+ // The alert itself still posted; only the agent start is missing.+ assert.equal(outputs.action, 'create')+ })++ it('stays quiet when no webhook is configured', async () => {+ const fetch = makeWebhook()+ const { outputs, failures } = await run(fiveFailures(), { fetch })++ assert.equal(outputs.action, 'create')+ assert.equal(fetch.calls.length, 0)+ assert.deepEqual(failures, [])+ })++ it('does not start a second agent while the incident stays open', async () => {+ const fetch = makeWebhook()+ const github = createGithubMock({+ 'ci-backend.yml': runs('Backend CI', Array(8).fill('failure')),+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ })+ const { outputs } = await run(github, { history: [activeAnchor()], env: webhookEnv, fetch })++ assert.equal(outputs.action, 'update')+ assert.equal(fetch.calls.length, 0)+ })+ })+it('updates the existing anchor instead of posting a duplicate (regression)', async () => {const github = createGithubMock({'ci-backend.yml': runs('Backend CI', Array(8).fill('failure')),diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.ymlindex 6f1969b7c7e7..7387e977b8bf 100644--- a/.github/workflows/ci-alerts-devex.yml+++ b/.github/workflows/ci-alerts-devex.yml@@ -107,6 +107,11 @@ jobs:uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0env:SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEVEX_BOT_TOKEN }}+ # Incoming-webhook trigger of the master-red diagnosis workflow. Unset skips the+ # call and still posts the Slack alert; set and unreachable fails this run. A+ # variable rather than a secret, because this repo sits two under GitHub's cap of+ # 100 secrets; the script masks the value so a public log cannot leak it.+ DIAGNOSIS_WEBHOOK_URL: ${{ vars.MASTER_RED_DIAGNOSIS_WEBHOOK_URL }}with:github-token: ${{ steps.app-token.outputs.token || github.token }}script: |