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): monitor setup-action offload rate-limit bucket (#61424)

Raúl Negrón-Otero08907d93a3a2
diff --git a/.github/scripts/monitor-github-rate-limit.js b/.github/scripts/monitor-github-rate-limit.js
index 59f2460914ba..231ecdfd3509 100644
--- a/.github/scripts/monitor-github-rate-limit.js
+++ b/.github/scripts/monitor-github-rate-limit.js
@@ -10,6 +10,7 @@
const POSTHOG_HOST = 'https://us.i.posthog.com'
const EVENT_NAME = 'github_rate_limit_observed'
+const DEFAULT_SOURCE = 'github_token'
async function captureEvent({ fetchImpl, posthogToken, event, distinctId, properties, timestamp }) {
const res = await fetchImpl(`${POSTHOG_HOST}/capture/`, {
@@ -52,7 +53,11 @@ function buildTrigger(context) {
}
}
-function buildProperties({ resource, snapshot, observedAt, observedAtSeconds, repo, runId, trigger }) {
+// `source` identifies which rate-limit bucket the snapshot came from: the
+// per-repo default GITHUB_TOKEN, or a dedicated GitHub App installation bucket
+// (e.g. posthog-devex-general, the setup-action offload bucket). The two are
+// separate 15k buckets, so downstream they're a per-bucket time series.
+function buildProperties({ resource, snapshot, observedAt, observedAtSeconds, repo, runId, trigger, source = DEFAULT_SOURCE }) {
const used = typeof snapshot.used === 'number' ? snapshot.used : snapshot.limit - snapshot.remaining
const utilization = snapshot.limit > 0 ? used / snapshot.limit : 0
return {
@@ -64,14 +69,15 @@ function buildProperties({ resource, snapshot, observedAt, observedAtSeconds, re
utilization,
reset_at: new Date(snapshot.reset * 1000).toISOString(),
reset_in_seconds: Math.max(0, snapshot.reset - observedAtSeconds),
- source: 'github_token',
+ source,
observed_at: observedAt,
workflow_run_id: runId || null,
...trigger,
}
}
-module.exports = async ({ github, context, core }, { now: _now, fetch: _fetch } = {}) => {
+module.exports = async ({ github, context, core }, { now: _now, fetch: _fetch, source: _source } = {}) => {
+ const source = _source || DEFAULT_SOURCE
const fetchImpl = _fetch || fetch
const observedAtDate = _now ? _now() : new Date()
const observedAt = observedAtDate.toISOString()
@@ -95,8 +101,8 @@ module.exports = async ({ github, context, core }, { now: _now, fetch: _fetch }
let failures = 0
for (const [resource, snapshot] of Object.entries(resources)) {
if (!snapshot || typeof snapshot.limit !== 'number' || typeof snapshot.remaining !== 'number') continue
- const properties = buildProperties({ resource, snapshot, observedAt, observedAtSeconds, repo, runId, trigger })
- core.info(`${resource}: ${properties.remaining}/${properties.limit} remaining (resets ${properties.reset_at})`)
+ const properties = buildProperties({ resource, snapshot, observedAt, observedAtSeconds, repo, runId, trigger, source })
+ core.info(`[${source}] ${resource}: ${properties.remaining}/${properties.limit} remaining (resets ${properties.reset_at})`)
try {
await captureEvent({
fetchImpl,
diff --git a/.github/scripts/monitor-github-rate-limit.test.js b/.github/scripts/monitor-github-rate-limit.test.js
index 32b88a4e7c8b..94dced6001e8 100644
--- a/.github/scripts/monitor-github-rate-limit.test.js
+++ b/.github/scripts/monitor-github-rate-limit.test.js
@@ -1,3 +1,8 @@
+// Run with: node --test .github/scripts/monitor-github-rate-limit.test.js
+
+const { describe, it, beforeEach } = require('node:test')
+const assert = require('node:assert/strict')
+
const monitor = require('./monitor-github-rate-limit')
const T_BASE = new Date('2026-04-27T18:00:00Z')
@@ -10,32 +15,54 @@ const snapshot = ({ remaining, limit, resetSecondsFromBase = 1800 }) => ({
reset: T_BASE_SECONDS + resetSecondsFromBase,
})
+// Minimal call-recording mock (no jest in the node:test runner).
+function recordingFn(impl) {
+ const fn = (...args) => {
+ fn.calls.push(args)
+ return impl ? impl(...args) : undefined
+ }
+ fn.calls = []
+ return fn
+}
+
+// Subset match: every key in `expected` must deep-equal the same key in
+// `actual` (node:test has no jest-style toMatchObject).
+function assertMatch(actual, expected, path = '') {
+ for (const [key, want] of Object.entries(expected)) {
+ const got = actual == null ? undefined : actual[key]
+ const at = path ? `${path}.${key}` : key
+ if (want && typeof want === 'object') {
+ assertMatch(got, want, at)
+ } else {
+ assert.equal(got, want, `mismatch at ${at}`)
+ }
+ }
+}
+
+const calledWith = (fn, ...expected) =>
+ fn.calls.some((args) => args.length === expected.length && args.every((a, i) => a === expected[i]))
+const calledWithStringContaining = (fn, sub) =>
+ fn.calls.some((args) => args.some((a) => typeof a === 'string' && a.includes(sub)))
+
const createGithubMock = (resources) => ({
- rest: { rateLimit: { get: jest.fn(() => Promise.resolve({ data: { resources } })) } },
+ rest: { rateLimit: { get: () => Promise.resolve({ data: { resources } }) } },
})
-const createCore = () => ({ info: jest.fn(), warning: jest.fn(), setOutput: jest.fn() })
+const createCore = () => ({ info: recordingFn(), warning: recordingFn(), setOutput: recordingFn() })
const fetchOk = () => Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('ok') })
const context = { repo: { owner: 'PostHog', repo: 'posthog' } }
describe('monitor-github-rate-limit', () => {
- const ORIGINAL_ENV = process.env
-
beforeEach(() => {
- process.env = { ...ORIGINAL_ENV }
delete process.env.POSTHOG_DEVEX_PROJECT_API_TOKEN
})
- afterAll(() => {
- process.env = ORIGINAL_ENV
- })
-
- test('emits one event per resource with the expected payload shape', async () => {
+ it('emits one event per resource with the expected payload shape', async () => {
process.env.POSTHOG_DEVEX_PROJECT_API_TOKEN = 'devex-key'
const captured = []
- const fetchMock = jest.fn((_url, opts) => {
+ const fetchMock = recordingFn((_url, opts) => {
captured.push(JSON.parse(opts.body))
return fetchOk()
})
@@ -47,8 +74,8 @@ describe('monitor-github-rate-limit', () => {
await monitor({ github, context, core }, { now: () => T_BASE, fetch: fetchMock })
- expect(captured).toHaveLength(2)
- expect(captured[0]).toMatchObject({
+ assert.equal(captured.length, 2)
+ assertMatch(captured[0], {
api_key: 'devex-key',
event: 'github_rate_limit_observed',
distinct_id: 'PostHog/posthog',
@@ -61,14 +88,34 @@ describe('monitor-github-rate-limit', () => {
reset_in_seconds: 600,
},
})
- expect(captured[0].properties.utilization).toBeCloseTo(12000 / 15000)
- expect(core.setOutput).toHaveBeenCalledWith('emitted', '2')
+ assert.ok(Math.abs(captured[0].properties.utilization - 12000 / 15000) < 1e-9)
+ assert.ok(calledWith(core.setOutput, 'emitted', '2'))
+ })
+
+ it('tags emissions with the offload bucket source when overridden', async () => {
+ process.env.POSTHOG_DEVEX_PROJECT_API_TOKEN = 'devex-key'
+ const captured = []
+ const fetchMock = recordingFn((_url, opts) => {
+ captured.push(JSON.parse(opts.body))
+ return fetchOk()
+ })
+ const github = createGithubMock({ core: snapshot({ remaining: 14500, limit: 15000 }) })
+ const core = createCore()
+
+ await monitor({ github, context, core }, { now: () => T_BASE, fetch: fetchMock, source: 'posthog-devex-general' })
+
+ assertMatch(captured[0].properties, {
+ resource: 'core',
+ remaining: 14500,
+ limit: 15000,
+ source: 'posthog-devex-general',
+ })
})
- test('counts capture failures without aborting later emissions', async () => {
+ it('counts capture failures without aborting later emissions', async () => {
process.env.POSTHOG_DEVEX_PROJECT_API_TOKEN = 'devex-key'
let calls = 0
- const fetchMock = jest.fn(() =>
+ const fetchMock = recordingFn(() =>
++calls === 1
? Promise.resolve({ ok: false, status: 500, text: () => Promise.resolve('boom') })
: fetchOk()
@@ -81,15 +128,15 @@ describe('monitor-github-rate-limit', () => {
await monitor({ github, context, core }, { now: () => T_BASE, fetch: fetchMock })
- expect(core.setOutput).toHaveBeenCalledWith('emitted', '1')
- expect(core.setOutput).toHaveBeenCalledWith('failures', '1')
- expect(core.warning).toHaveBeenCalledWith(expect.stringContaining('capture 500'))
+ assert.ok(calledWith(core.setOutput, 'emitted', '1'))
+ assert.ok(calledWith(core.setOutput, 'failures', '1'))
+ assert.ok(calledWithStringContaining(core.warning, 'capture 500'))
})
- test('captures the triggering event context on each sample', async () => {
+ it('captures the triggering event context on each sample', async () => {
process.env.POSTHOG_DEVEX_PROJECT_API_TOKEN = 'devex-key'
const captured = []
- const fetchMock = jest.fn((_url, opts) => {
+ const fetchMock = recordingFn((_url, opts) => {
captured.push(JSON.parse(opts.body))
return fetchOk()
})
@@ -113,7 +160,7 @@ describe('monitor-github-rate-limit', () => {
await monitor({ github, context: prContext, core }, { now: () => T_BASE, fetch: fetchMock })
- expect(captured[0].properties).toMatchObject({
+ assertMatch(captured[0].properties, {
trigger_event: 'pull_request',
trigger_action: 'synchronize',
head_ref: 'feature/foo',
@@ -125,31 +172,33 @@ describe('monitor-github-rate-limit', () => {
})
})
- test.each([
+ for (const [eventName, payload, expectedRef] of [
['push', { ref: 'refs/heads/master' }, 'master'],
['schedule', {}, null],
['workflow_dispatch', {}, null],
- ])('buildTrigger nulls PR fields and resolves head_ref for non-PR event %s', (eventName, payload, expectedRef) => {
- expect(monitor.buildTrigger({ eventName, payload })).toMatchObject({
- trigger_event: eventName,
- trigger_action: null,
- head_ref: expectedRef,
- pr_number: null,
- pr_author: null,
- pr_changed_files: null,
- pr_additions: null,
- pr_deletions: null,
+ ]) {
+ it(`buildTrigger nulls PR fields and resolves head_ref for non-PR event ${eventName}`, () => {
+ assertMatch(monitor.buildTrigger({ eventName, payload }), {
+ trigger_event: eventName,
+ trigger_action: null,
+ head_ref: expectedRef,
+ pr_number: null,
+ pr_author: null,
+ pr_changed_files: null,
+ pr_additions: null,
+ pr_deletions: null,
+ })
})
- })
+ }
- test('skips emission when devex token is not configured', async () => {
- const fetchMock = jest.fn(fetchOk)
+ it('skips emission when devex token is not configured', async () => {
+ const fetchMock = recordingFn(fetchOk)
const github = createGithubMock({ core: snapshot({ remaining: 1, limit: 15000 }) })
const core = createCore()
await monitor({ github, context, core }, { now: () => T_BASE, fetch: fetchMock })
- expect(fetchMock).not.toHaveBeenCalled()
- expect(core.warning).toHaveBeenCalledWith(expect.stringContaining('POSTHOG_DEVEX_PROJECT_API_TOKEN'))
+ assert.equal(fetchMock.calls.length, 0)
+ assert.ok(calledWithStringContaining(core.warning, 'POSTHOG_DEVEX_PROJECT_API_TOKEN'))
})
})
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index d29dd146559a..7b339ea4b932 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -48,3 +48,6 @@ jobs:
- name: Master CI alerts tests (Node)
run: node --test .github/scripts/ci-alerts-devex.test.js
+
+ - name: Rate-limit monitor tests (Node)
+ run: node --test .github/scripts/monitor-github-rate-limit.test.js
diff --git a/.github/workflows/monitor-github-rate-limit.yml b/.github/workflows/monitor-github-rate-limit.yml
index 7d4ee4db7436..037bc4e5c77a 100644
--- a/.github/workflows/monitor-github-rate-limit.yml
+++ b/.github/workflows/monitor-github-rate-limit.yml
@@ -49,11 +49,36 @@ jobs:
.github/scripts/monitor-github-rate-limit.js
sparse-checkout-cone-mode: false
- - name: Poll /rate_limit and emit to PostHog
+ - name: Poll GITHUB_TOKEN bucket and emit to PostHog
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
with:
script: |
const script = require('./.github/scripts/monitor-github-rate-limit.js')
- await script({ github, context, core })
+ await script({ github, context, core }, { source: 'github_token' })
+
+ # The setup-action offload bucket (posthog-devex-general) is a
+ # separate 15k installation bucket from GITHUB_TOKEN. Mint its token
+ # and poll /rate_limit through it so its core budget is observable as
+ # its own series. /rate_limit reads don't consume the budget they
+ # report, so this doesn't distort the measurement. No-ops until the
+ # org secret exists (continue-on-error mint + empty-token guard).
+ - name: Mint posthog-devex-general token
+ id: devex-token
+ continue-on-error: true
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
+
+ - name: Poll posthog-devex-general bucket and emit to PostHog
+ if: steps.devex-token.outputs.token != ''
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
+ env:
+ POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
+ with:
+ github-token: ${{ steps.devex-token.outputs.token }}
+ script: |
+ const script = require('./.github/scripts/monitor-github-rate-limit.js')
+ await script({ github, context, core }, { source: 'posthog-devex-general' })