The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
fix(ci): retry webhook admission after concurrent wake settlement (#3220)
kekxy949cd53d6f8c
diff --git a/apps/libs/ci-listener/README.md b/apps/libs/ci-listener/README.mdindex 1e6970539..ae9685259 100644--- a/apps/libs/ci-listener/README.md+++ b/apps/libs/ci-listener/README.md@@ -229,6 +229,10 @@ duplicates converge; conflicting bodies/events or job identities are rejected.A new delivery updates record versions, so settlement using an older capturedversion fails rather than removing newer work. The API uses the same inbox through its binding-authorized PostgreSQL adapter.+If the scheduler settles a wake during webhook admission, the inbox retries the+whole transaction up to three times. Each attempt rechecks the binding and reads+the current receipt, wake and job state.+`ListenerState` stores durable records through either the host's PostgreSQL poolor the Node 24 SQLite adapter. PostgreSQL uses the single `ci_listener_state` table;the API migration creates it. SQLite keeps `listener.sqlite` and its WAL/SHM filesdiff --git a/apps/libs/ci-listener/src/webhook.spec.ts b/apps/libs/ci-listener/src/webhook.spec.tsindex 2a6740fff..7c819716a 100644--- a/apps/libs/ci-listener/src/webhook.spec.ts+++ b/apps/libs/ci-listener/src/webhook.spec.ts@@ -203,11 +203,72 @@ for (const backend of ['sqlite', 'postgres'] as const) {}})const records = async () => state.recover((await state.acquire(randomUUID(), 10000))!)+ if (backend === 'postgres') {+ it('stores a new delivery when the scheduler settles the wake read by ingress', async () => {+ await inbox.receive(verifyWebhook(signed(), secret)!)+ const lease = (await state.acquire(randomUUID(), 30000))!+ const [wake] = await state.read(['wake/9/21'])+ const transaction = db.transaction.bind(db)+ jest.spyOn(db, 'transaction').mockImplementation((namespace, work, mode) =>+ transaction(+ namespace,+ async (tx) => {+ const put = tx.put.bind(tx)+ tx.put = async (record, expected) => {+ if (record.key === wake.key && expected === wake.version) {+ await state.commit(lease, [{ key: wake.key, expected: wake.version }])+ }+ return put(record, expected)+ }+ return work(tx)+ },+ mode,+ ),+ )+ const replacement = verifyWebhook(+ signed({ ...payload(), workflow_job: { ...payload().workflow_job, id: 56 } }),+ secret,+ )!+ expect(await inbox.receive(replacement)).toBe('stored')+ expect(await inbox.receive(replacement)).toBe('duplicate')+ const rows = await state.read([wake.key, 'notice/9/56', `receipt/${replacement.delivery}`])+ expect(rows.map((row) => row.key).sort()).toEqual(+ [wake.key, 'notice/9/56', `receipt/${replacement.delivery}`].sort(),+ )+ expect(rows.find((row) => row.key === wake.key)!.version).not.toBe(wake.version)+ })+ }+ it.each([+ [new StateConflict(), 4],+ [new StateCorrupt(), 1],+ ] as const)('limits ingress attempts for %s', async (error, attempts) => {+ const ingress = jest.spyOn(state, 'ingress').mockRejectedValue(error)+ await expect(inbox.receive(verifyWebhook(signed(), secret)!)).rejects.toBe(error)+ expect(ingress).toHaveBeenCalledTimes(attempts)+ })it('requires labels from a verified observation before publishing job demand', async () => {const { observation: _observation, ...notification } = verifyWebhook(signed(), secret)!await expect(inbox.receive(notification)).rejects.toMatchObject({ status: 400 })expect(await records()).toEqual([])})+ it('restores the installation inventory wake when settlement races a refresh', async () => {+ const identity = { installationId: 9, accountId: 19 }+ const lease = (await state.acquire(randomUUID(), 10000))!+ await inbox.inventory(identity)+ const [wake] = await state.read(['wake/9/0'])+ const ingest = state.ingest.bind(state)+ jest.spyOn(state, 'ingest').mockImplementationOnce(async (changes) => {+ await state.commit(lease, [{ key: wake.key, expected: wake.version }])+ return ingest(changes)+ })++ await inbox.inventory(identity)++ const rows = await state.recover(lease)+ expect(rows).toHaveLength(1)+ expect(rows[0]).toMatchObject({ key: wake.key, payload: { ...identity, repositoryId: 0 } })+ expect(rows[0].version).not.toBe(wake.version)+ })it('stores installation inventory without job facts, demand or executable notices', async () => {const notification = verifyWebhook(signed(diff --git a/apps/libs/ci-listener/src/webhook.ts b/apps/libs/ci-listener/src/webhook.tsindex 58b4cce33..0f317ffe7 100644--- a/apps/libs/ci-listener/src/webhook.ts+++ b/apps/libs/ci-listener/src/webhook.ts@@ -1,6 +1,6 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */import { createHash, createHmac, timingSafeEqual } from 'node:crypto'-import { ListenerState } from './state/store'+import { IngressTransaction, ListenerState } from './state/store'import { Json, StateConflict, StateCorrupt } from './state/database'import { parseResourceLabels } from './resource-labels'import { JobIdentityConflict, JobObservation, jobObservationChanges } from './job-observation'@@ -156,6 +156,16 @@ export function verifyWebhook(return { ...verified, observation, jobTiming: jobTiming(job, observation) }}+async function retryStateConflict<T>(operation: () => Promise<T>): Promise<T> {+ for (let retries = 0; ; retries++) {+ try {+ return await operation()+ } catch (error) {+ if (!(error instanceof StateConflict) || retries === 3) throw error+ }+ }+}+/** Both hosts use this inbox. Its database adapter must enforce the live binding in the ingress transaction. */export class ListenerInbox {constructor(private readonly state: ListenerState) {}@@ -164,7 +174,7 @@ export class ListenerInbox {const { installationId, accountId } = suppliedif (!id(installationId) || !id(accountId)) throw new WebhookError(400, 'Invalid inventory identity')const key = `wake/${installationId}/0`- for (let attempt = 0; attempt < 4; attempt++) {+ await retryStateConflict(async () => {const [prior] = await this.state.read([key])if (prior &&@@ -174,15 +184,10 @@ export class ListenerInbox {prior.payload.repositoryId !== 0))throw new StateCorrupt()- try {- await this.state.ingest([- { key, expected: prior?.version ?? null, payload: { installationId, accountId, repositoryId: 0 } },- ])- return- } catch (error) {- if (!(error instanceof StateConflict) || attempt === 3) throw error- }- }+ await this.state.ingest([+ { key, expected: prior?.version ?? null, payload: { installationId, accountId, repositoryId: 0 } },+ ])+ })}async receive(notification: VerifiedWebhook): Promise<'stored' | 'duplicate'> {const observation = notification.observation@@ -217,7 +222,7 @@ export class ListenerInbox {const receipt = `receipt/${delivery}`,wake = `wake/${hint.installationId}/${hint.repositoryId}`,notice = hint.job ? `notice/${hint.installationId}/${hint.job.id}` : undefined- return this.state.ingress(`${hint.installationId}/${hint.repositoryId}`, async (tx) => {+ const persist = async (tx: IngressTransaction): Promise<'stored' | 'duplicate'> => {const fact = hint.job ? `job-fact/${hint.installationId}/${hint.job.id}` : undefinedconst rows = new Map((await tx.read([receipt, wake, ...(notice && fact ? [notice, fact] : [])])).map((row) => [row.key, row]),@@ -287,6 +292,7 @@ export class ListenerInbox {: []),])return 'stored'- })+ }+ return retryStateConflict(() => this.state.ingress(`${hint.installationId}/${hint.repositoryId}`, persist))}}