The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
perf(ci): wake listeners on demand and reduce capacity reads (#3138)
kekxy5f76ccf214ff
diff --git a/apps/github-ci-runner/src/self-host.spec.ts b/apps/github-ci-runner/src/self-host.spec.tsindex 660beaa9a..6e4323ad6 100644--- a/apps/github-ci-runner/src/self-host.spec.ts+++ b/apps/github-ci-runner/src/self-host.spec.ts@@ -314,17 +314,59 @@ describe('Standalone App binding and HTTP ingress', () => {await expect(host.scan(claim, AbortSignal.timeout(3000))).rejects.toThrow('account type denied')expect(global.fetch).not.toHaveBeenCalled()})- it.each(['valid', 'owner', 'repository', 'public', 'changed'])(- 'discovers and fences an independent PAT repository: %s',+ const patScenarios = [+ 'valid',+ 'owner',+ 'repository',+ 'public',+ 'changed',+ 'cancelled notice',+ 'replacement notice',+ 'unconfirmed notice',+ ]+ it.each(patScenarios)(+ 'discovers and fences an independent PAT repository and its job notices: %s',async (scenario) => {const patDb = new SqliteStateDatabase(join(directory, 'pat-state'))const patState = new ListenerState(patDb, 'pat')let changed = false+ let scannedEmpty = false+ let emptyPasses = 0+ let confirmJob: (() => Promise<void>) | undefined+ let jobChecks = 0const previousFetch = global.fetchglobal.fetch = jest.fn(async (input, options) => {const url = new URL(String(input))if (url.origin === 'https://box.test') return previousFetch(input, options)expect(new Headers(options?.headers).get('authorization')).toBe('Bearer private-pat')+ if (url.pathname.endsWith('/actions/jobs/55')) {+ jobChecks+++ await confirmJob?.()+ if (scenario === 'replacement notice' && jobChecks > 1)+ return Response.json({+ id: 55,+ run_id: 99,+ status: 'queued',+ conclusion: null,+ completed_at: null,+ labels: ['boxlite'],+ runner_id: null,+ })+ if (scenario === 'unconfirmed notice') return new Response(null, { status: 404 })+ return Response.json({+ id: 55,+ run_id: 99,+ status: 'completed',+ conclusion: 'cancelled',+ completed_at: '2026-01-01T00:00:00Z',+ labels: ['boxlite'],+ runner_id: null,+ })+ }+ if (scannedEmpty && url.pathname.endsWith('/actions/runs')) {+ if (url.searchParams.get('status') === 'queued') emptyPasses+++ return Response.json({ total_count: 0, workflow_runs: [] })+ }if (url.pathname.endsWith('/actions/runs'))return new Response(JSON.stringify({@@ -386,7 +428,7 @@ describe('Standalone App binding and HTTP ingress', () => {} finally {await backend.close()}- if (scenario === 'valid') {+ if (scenario === 'valid' || scenario.endsWith('notice')) {const claim = (await patState.scans().claim('pat-follower'))!const scanner = await patHost.scan(claim, AbortSignal.timeout(3000))try {@@ -394,6 +436,43 @@ describe('Standalone App binding and HTTP ingress', () => {expect(jobs).toHaveLength(1)await scanner.publish(jobs, AbortSignal.timeout(3000))expect((await patState.read(['notice/0/55']))[0].payload).toMatchObject({ repositoryId: 21 })+ if (scenario.endsWith('notice')) {+ await scanner.close()+ await patState.scans().finish(claim, { success: true, intervalMs: 1 })+ scannedEmpty = true+ const [original] = await patState.read(['notice/0/55'])+ if (scenario === 'replacement notice')+ confirmJob = async () => {+ await patState.commit(lease, [+ { key: original.key, expected: original.version, payload: original.payload },+ ])+ confirmJob = undefined+ }+ const controller = new AbortController()+ const follower = new Listener({+ state: patState,+ host: patHost,+ worker: config.worker,+ capacity: { resolve: async () => testCapacity({ account: 0, tenant: 0 }) },+ timing: { tickMs: 5, compensationMs: 50 },+ })+ const task = follower.run(controller.signal)+ try {+ const deadline = Date.now() + 3000+ while (emptyPasses < 2 && Date.now() < deadline) await new Promise((done) => setTimeout(done, 5))+ const rows = await patState.read([original.key])+ if (scenario === 'cancelled notice') expect(rows).toHaveLength(0)+ else if (scenario === 'replacement notice') {+ expect(rows).toHaveLength(1)+ expect(rows[0].version).not.toBe(original.version)+ } else expect(rows[0]?.version).toBe(original.version)+ expect(jobChecks).toBeGreaterThan(0)+ } finally {+ controller.abort()+ await task+ }+ return+ }const [root] = await patState.read(['backend/github'])await patState.commit(lease, [{diff --git a/apps/libs/ci-listener/README.md b/apps/libs/ci-listener/README.mdindex aa3d3026f..d4a6d0478 100644--- a/apps/libs/ci-listener/README.md+++ b/apps/libs/ci-listener/README.md@@ -403,11 +403,40 @@ points use this kernel; runtime acceptance remains a separate deployment check.## GitHub runner scale sets-Hosted CI and the standalone Listener Box use the same TypeScript Scale Set client for every installation. The elected listener opens one cancellable session per binding, execution scope and worker specification. Each session sends its available capacity to GitHub and explicitly acquires eligible job requests.+Hosted CI and the standalone Listener Box use the same TypeScript Scale Set client for every installation. The elected listener opens a cancellable session for a scope and worker specification when a queued job or recoverable work needs it. Each session sends its available capacity to GitHub and explicitly acquires eligible job requests.-An authenticated queued-job observation can seed an additional supported resource label, with up to 64 open sessions per scope. When more specifications are waiting, an empty poll on an idle set gives another specification a turn. An active set keeps its session.+Before a poll or charged retry, one lease-fenced read validates the journal format, scope, activity index and original App mapping. A second read validates the global, organization and account counters.-A failed session releases its lane during backoff. Other specifications can start while the failed one waits for its retry deadline.+The journal computes the margin from that batch, including validation of domains with+no configured limit. A new reservation checks current counter versions when it commits.++A signed queued webhook or an authorized repository scan wakes its matching label. The inbox retains one record per installation and workflow job ID while that job is queued. Empty polls and scale-set acquisitions preserve those records across takeover.++A signed job lifecycle event or an authorized job-status check clears its matching job. A newer notice arriving during a poll or session close gets its own poll.++```mermaid+sequenceDiagram+ participant Inbox as Durable job notices+ participant L as Listener+ participant G as GitHub Actions+ Inbox->>L: Queued notice A+ L->>G: Poll for A+ G-->>L: Empty response, keep A pending+ G-->>Inbox: Job A completed+ Inbox->>L: No remaining demand+ L->>G: Close idle session+ Inbox->>L: Queued notice B during close+ G-->>L: Session closed+ L->>G: Open and poll for B+```++Each scope admits up to 64 concurrent sessions in waiting order. After a poll reconciles outstanding work, the session advertises its updated capacity. An empty poll on an idle set can then close the session when no acquisition or worker, including a worker awaiting cleanup, remains.++Takeover restores saved assignments and acquisitions and the labels of outstanding workers.++An idle repository incurs no per-label capacity reads or Actions polls. Lease renewal, inbox discovery and bounded repository scans continue; a missed webhook can delay the first job until compensation finds it.++A failed session releases its lane during backoff. At the retry deadline only outstanding notices or recovery work reopen it. A cancellation during backoff leaves a cold label asleep.A workflow can request a new specification directly:@@ -415,7 +444,7 @@ A workflow can request a new specification directly:runs-on: boxlite-1vcpu-1gbmem-10gbdisk```-Each binding starts with `boxlite`. A signed queued webhook opens a set for this label in the authorized runner group.+A workflow using `runs-on: boxlite` wakes the default label. The example above wakes only its resource label in the authorized runner group.A standalone PAT listener can also discover the specification through its authorized repository scan. Once GitHub assigns the work, the Box requests 1 vCPU, 1,024 MiB of memory and 10 GiB of disk.@@ -573,7 +602,13 @@ binding record versions. A deleted connection or superseded snapshot rejects latresults. Repeated jobs converge with webhook ingress; repository, run, account orinstallation conflicts fail closed.-Scanned jobs publish resource labels. The owner persists the specification before settling the notice. Only GitHub Scale Set messages can trigger a new quota reservation.+Claiming a due repository scan adds one indexed read of at most eight inbox records for its installation. The existing claim transaction saves the cursor with the task so another replica can continue the sweep. An empty page adds no GitHub requests.++When the queued inventory omits a job, the scanner checks its status by job ID. A confirmed in-progress or completed job clears only the version checked. Missing or inaccessible jobs keep their notices.++A delayed queued snapshot cannot restore a job whose departure was confirmed.++Scanned jobs publish resource labels. The owner persists the specification before opening the matching scale set. Only GitHub Scale Set messages can trigger a new quota reservation.Stopping the Listener cancels and awaits both lanes and retires their credentials;failed retirement retains its handle for retry and reports the cleanup failure.@@ -672,7 +707,9 @@ commit can omit a line, while the journal still retains the recovery state.`GitHubExecutionBackend` ties the original scope, Scale Set, executor and GitHub credentials to the live execution lease. The host rechecks authority at admission and cleanup.-`Listener.receive` records a verified notification before acknowledging it. A signed event or authorized repository scan discovers resource labels. The elected owner opens the corresponding Scale Set and settles each notice against the version it observed.+`Listener.receive` records a verified notification before acknowledging it. A signed event or authorized repository scan discovers resource labels. The elected owner opens the corresponding Scale Set.++A confirmed status change clears the matching job notice and preserves concurrent replacements during compensation.`InstallationCatalog` enumerates a complete, bounded installation inventory usinga metadata-only token. Personal accounts receive one repository scope per eligiblediff --git a/apps/libs/ci-listener/src/compensation/queue.spec.ts b/apps/libs/ci-listener/src/compensation/queue.spec.tsindex 217edd1fc..fbf5147f0 100644--- a/apps/libs/ci-listener/src/compensation/queue.spec.ts+++ b/apps/libs/ci-listener/src/compensation/queue.spec.ts@@ -9,6 +9,7 @@ import { LeaseLost, StateConflict, StateCorrupt, StateDatabase } from '../state/import { PostgresStateDatabase, postgresStateTable } from '../state/postgres'import { SqliteStateDatabase } from '../state/sqlite'import { ExecutionLease, ListenerState } from '../state/store'+import { ListenerInbox } from '../webhook'import { RepositoryScanQueue } from './queue'for (const backend of ['sqlite', 'postgres'] as const) {@@ -120,6 +121,62 @@ for (const backend of ['sqlite', 'postgres'] as const) {expect((await state.read(['notice/1/55']))[0].payload).toMatchObject({ repositoryId: 21 })expect(await state.read(['usage/global'])).toEqual([])})+ it('continues notice pages on another replica and retires only versions still current under its live claim', async () => {+ await sync()+ pages = []+ const claim = await owner()+ expect(pages.filter((page) => page.prefix.startsWith('notice/'))).toEqual([{ prefix: 'notice/1/', limit: 8 }])+ const jobs = Array.from({ length: 9 }, (_, i) => ({ ...job(), job: 100 + i }))+ await queue.publish(claim, jobs, ['boxlite'])+ expect(claim.notices).toEqual([])+ await queue.finish(claim, { success: true, intervalMs: 1 })+ now += 2+ const nextClaim = (await second.claim('next-scanner'))!+ const first = nextClaim.notices+ await second.finish(nextClaim, { success: true, intervalMs: 1 })+ now += 2+ const lastClaim = await owner()+ const last = lastClaim.notices+ expect(first.map((entry) => entry.job)).toEqual(jobs.slice(0, 8).map((entry) => entry.job))+ expect(last.map((entry) => entry.job)).toEqual([108])+ const [unchanged, replaced] = await state.read(first.slice(0, 2).map((entry) => 'notice/1/' + entry.job))+ const [newer] = await state.commit(main, [+ { key: replaced.key, expected: replaced.version, payload: replaced.payload },+ ])+ const observations = jobs.slice(0, 2).map((job, i) => ({+ ...job,+ status: 'completed' as const,+ noticeVersion: first[i].version,+ }))+ await expect(queue.publish(claim, observations, ['boxlite'])).rejects.toBeInstanceOf(LeaseLost)+ await expect(queue.publish(lastClaim, [{ ...observations[0], run: 999 }], ['boxlite'])).rejects.toBeInstanceOf(+ StateCorrupt,+ )+ await queue.publish(lastClaim, observations, ['boxlite'])+ expect(await state.read([unchanged.key, replaced.key])).toEqual([newer])+ await queue.publish(lastClaim, jobs.slice(0, 2), ['boxlite'])+ expect(await state.read([unchanged.key, replaced.key])).toEqual([newer])+ })+ it('keeps a delayed queued scan from restoring a job already completed by webhook', async () => {+ await sync()+ const claim = await owner()+ const queued = job()+ const hint = {+ installationId: 1,+ accountId: 7,+ repositoryId: queued.repository,+ job: { id: queued.job, runId: queued.run },+ }+ await new ListenerInbox(state).receive({+ delivery: randomUUID(),+ digest: 'a'.repeat(64),+ event: 'workflow_job',+ hint,+ observation: { status: 'completed', labels: queued.labels, runner: null },+ })+ await queue.publish(claim, [queued], ['boxlite'])+ expect(await state.read(['notice/1/55'])).toEqual([])+ })it('publishes custom resource demand while skipping invalid and conflicting labels', async () => {await sync()const claim = await owner()diff --git a/apps/libs/ci-listener/src/compensation/queue.ts b/apps/libs/ci-listener/src/compensation/queue.tsindex 2ec26e80a..68cc283fc 100644--- a/apps/libs/ci-listener/src/compensation/queue.ts+++ b/apps/libs/ci-listener/src/compensation/queue.ts@@ -1,8 +1,9 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */import { createHash, randomUUID } from 'node:crypto'import { decodeScope, ExecutionScope, object, positive, scopeKey } from '../execution/model'-import { jobMatches, WorkflowJob } from '../jobs'-import { repositories } from '../scheduling'+import { jobObservationChanges } from '../job-observation'+import { jobMatches, JobNotice, WorkflowJob } from '../jobs'+import { matches, pendingJob, repositories } from '../scheduling'import {Json,LeaseLost,@@ -20,7 +21,10 @@ export interface ScanClaim extends ExecutionLease {application: stringscope: ExecutionScoperepository: number+ notices: (JobNotice & { version: string })[]}+export type ScannedJob = WorkflowJob & { noticeVersion?: string }+interface Catalog {revision: stringfingerprint: string@@ -41,6 +45,7 @@ interface Task {epoch: numberuntil: numberfailures: number+ noticeAfter?: string}interface Installation {owner: string@@ -49,6 +54,7 @@ interface Installation {until: numberretryAt: number}+const noticePageSize = 8const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')const json = (value: unknown) => value as Jsonconst record = (key: string, payload: unknown): StateRecord => ({@@ -322,7 +328,10 @@ export class RepositoryScanQueue {return undefined}if (task.epoch === Number.MAX_SAFE_INTEGER) throw new StateCorrupt()- const next = { ...task, owner, epoch: task.epoch + 1, until: now + ttlMs }+ const scope = await this.scope(tx, task)+ const rows = await tx.page(task.noticeAfter ?? '', noticePageSize, `notice/${scope.installation.id}/`)+ const noticeAfter = rows.length === noticePageSize ? rows[rows.length - 1].key : ''+ const next = { ...task, owner, epoch: task.epoch + 1, until: now + ttlMs, noticeAfter }await this.reschedule(tx, entry.id, row, next, next.until)await this.put(tx,@@ -337,8 +346,12 @@ export class RepositoryScanQueue {id: entry.id,revision: catalog.revision,application: task.application,- scope: await this.scope(tx, task),+ scope,repository: task.repository,+ notices: rows+ .map(pendingJob)+ .filter((entry) => matches(scope, entry) && entry.notice.repository === task.repository)+ .map(({ notice, record }) => ({ ...notice, version: record.version })),}})if (claim) return claim@@ -353,7 +366,7 @@ export class RepositoryScanQueue {async publish(original: ScanClaim,- jobs: readonly WorkflowJob[],+ jobs: readonly ScannedJob[],labels: readonly string[],checks: readonly StateCheck[] = [],): Promise<void> {@@ -368,11 +381,39 @@ export class RepositoryScanQueue {if ((await tx.get(check.key, true))?.version !== check.version) throw new StateConflict()}await this.assert(tx, claim)+ // Webhook ingress takes this same repository lock, including for an absent job fact or notice.+ if (tx.lock) await tx.lock(`ingress/${claim.scope.installation.id}/${claim.repository}`)+ else await tx.get('@anchor', true)for (const job of captured) {if (job.repository !== claim.repository || !positive(job.job) || !positive(job.run)) throw new StateCorrupt()- if (!jobMatches(job, supported)) continue- const key = `notice/${claim.scope.installation.id}/${job.job}`+ const confirmed = job.status === 'in_progress' || job.status === 'completed'+ if (!confirmed && !jobMatches(job, supported)) continue+ const installation = claim.scope.installation+ const key = `notice/${installation.id}/${job.job}`let prior = await tx.get(key, true)+ const factKey = `job-fact/${installation.id}/${job.job}`+ const fact = await tx.get(factKey)+ if (job.status === 'completed' || job.status === 'in_progress') {+ if (!prior || prior.version !== job.noticeVersion) continue+ const original = pendingJob(prior)+ if (+ !matches(claim.scope, original) ||+ original.notice.repository !== job.repository ||+ original.notice.run !== job.run+ )+ throw new StateCorrupt()+ const hint = {+ installationId: installation.id,+ accountId: installation.account.id,+ repositoryId: job.repository,+ job: { id: job.job, runId: job.run },+ }+ const [change] = jobObservationChanges(fact, hint, { ...job, status: job.status })+ if (change) await this.put(tx, factKey, change.payload, fact)+ await this.remove(tx, prior)+ continue+ }+ if (fact && (!object(fact.payload) || fact.payload.status !== 'queued')) continueif (!prior) {const next = record(key, {installationId: claim.scope.installation.id,diff --git a/apps/libs/ci-listener/src/compensation/scanner.spec.ts b/apps/libs/ci-listener/src/compensation/scanner.spec.tsindex 95a2aff18..5f2bfdd12 100644--- a/apps/libs/ci-listener/src/compensation/scanner.spec.ts+++ b/apps/libs/ci-listener/src/compensation/scanner.spec.ts@@ -6,7 +6,7 @@ import { ExecutionScope } from '../execution/model'import { GitHubRequestError } from '../github'import { SqliteStateDatabase } from '../state/sqlite'import { ListenerState } from '../state/store'-import { RepositoryCompensation, RepositoryScanSession } from './scanner'+import { GitHubRepositoryScanner, RepositoryCompensation, RepositoryScanSession } from './scanner'import { RepositoryScanQueue, ScanClaim } from './queue'const deferred = () => {@@ -54,6 +54,85 @@ describe('CI independent compensation lanes', () => {const run = (open: (claim: ScanClaim, signal: AbortSignal) => Promise<RepositoryScanSession>) =>new RepositoryCompensation({ queue, open, report, wake: jest.fn(), tickMs: 1, intervalMs: 300000 })+ it('confirms only departed jobs and keeps unknown jobs for another scan', async () => {+ const pat = new ListenerState(database, 'pat')+ await pat.initialize()+ const main = (await pat.acquire('scheduler', 300000))!+ const repository = { id: 21, owner: { id: 7, login: 'owner' }, name: 'repo', private: true }+ const scope: ExecutionScope = {+ binding: 'personal-token',+ generation: 1,+ organization: 'tenant',+ actor: 'actor',+ installation: { id: 0, account: { ...repository.owner, type: 'User' } },+ runners: { kind: 'repository', repository, allowPrivate: true, allowPublic: false },+ }+ const scans = pat.scans()+ await scans.synchronize(main, 'personal-token', scope.binding, [scope])+ const jobs = [100, 101, 102, 103, 104].map((job) => ({+ repository: repository.id,+ run: 55,+ job,+ labels: ['boxlite'],+ runner: null,+ status: 'queued' as const,+ }))+ const initial = (await scans.claim('seed-scanner'))!+ await scans.publish(initial, jobs, ['boxlite'])+ await scans.finish(initial, { success: true, intervalMs: 1 })+ await new Promise((done) => setTimeout(done, 5))+ const claim = (await scans.claim('scanner'))!+ const scanner = new GitHubRepositoryScanner({+ queue: scans,+ claim,+ source: { kind: 'pat', repository: repository.id, token: () => 'test-pat' },+ authorize: async () => {},+ publish: (jobs) => scans.publish(claim, jobs, ['boxlite']),+ })+ const checked: number[] = []+ let hiddenStatus = 404+ const fetch = jest.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {+ const path = new URL(String(input)).pathname+ if (path === '/repositories/21') return Response.json(repository)+ const match = /^\/repos\/owner\/repo\/actions\/jobs\/(\d+)$/.exec(path)+ if (!match) throw new Error('Unexpected GitHub request ' + path)+ const id = Number(match[1])+ checked.push(id)+ if (id === 104) return new Response(null, { status: hiddenStatus })+ const status = id === 101 ? 'in_progress' : id === 102 ? 'completed' : 'queued'+ return Response.json({+ id,+ run_id: 55,+ labels: ['boxlite'],+ runner_id: null,+ status,+ conclusion: status === 'completed' ? 'cancelled' : null,+ completed_at: status === 'completed' ? '2026-01-01T00:00:00Z' : null,+ })+ })+ try {+ await scanner.reconcile(jobs, stop.signal)+ expect(fetch).not.toHaveBeenCalled()+ await scanner.reconcile(jobs.slice(0, 1), stop.signal)+ expect(checked.sort()).toEqual([101, 102, 103, 104])+ const keys = jobs.map(({ job }) => 'notice/0/' + job)+ const remaining = await pat.read(keys)+ expect(remaining.map((row) => row.key)).toEqual([keys[0], keys[3], keys[4]])+ expect((await pat.read(['job-fact/0/101', 'job-fact/0/102'])).map((row) => row.payload)).toMatchObject([+ { status: 'in_progress' },+ { status: 'completed' },+ ])+ hiddenStatus = 429+ await expect(scanner.reconcile([jobs[0], jobs[3]], stop.signal)).rejects.toMatchObject({ status: 429 })+ expect(await pat.read(keys)).toEqual(remaining)+ hiddenStatus = 404+ await scanner.reconcile([jobs[0], jobs[3]], stop.signal)+ expect(await pat.read(keys)).toEqual(remaining)+ } finally {+ await scanner.close()+ fetch.mockRestore()+ }+ })it('holds at most two scans, claims the third only after release, and closes all sessions on stop', async () => {const entered = deferred(),third = deferred(),diff --git a/apps/libs/ci-listener/src/compensation/scanner.ts b/apps/libs/ci-listener/src/compensation/scanner.tsindex defdefb72..9a5a79463 100644--- a/apps/libs/ci-listener/src/compensation/scanner.ts+++ b/apps/libs/ci-listener/src/compensation/scanner.ts@@ -4,14 +4,16 @@ import { setTimeout as delay } from 'node:timers/promises'import { CredentialSource, ListenerCredentials } from '../credentials'import { GitHubRequestError } from '../github'import { readRepositoryJobs } from '../job-reader'-import { WorkflowJob } from '../jobs'+import { GitHubJobs, WorkflowJob } from '../jobs'+import { parallelReads } from '../parallel-reads'import { LeaseLost, StateConflict } from '../state/database'import type { ListenerState } from '../state/store'-import { RepositoryScanQueue, ScanClaim } from './queue'+import { RepositoryScanQueue, ScanClaim, ScannedJob } from './queue'export interface RepositoryScanSession {queued(signal: AbortSignal): Promise<WorkflowJob[]>publish(jobs: readonly WorkflowJob[], signal: AbortSignal): Promise<void>+ reconcile?(queued: readonly WorkflowJob[], signal: AbortSignal): Promise<void>close(): Promise<void>}export interface RepositoryScannerOptions {@@ -20,7 +22,7 @@ export interface RepositoryScannerOptions {source: CredentialSourcecredentials?: Pick<ListenerState, 'commit'>authorize(signal?: AbortSignal): Promise<void>- publish(jobs: readonly WorkflowJob[], signal: AbortSignal): Promise<void>+ publish(jobs: readonly ScannedJob[], signal: AbortSignal): Promise<void>}/** GitHub jobs only: no worker, runner-registration or capacity capability. */@@ -37,6 +39,37 @@ export class GitHubRepositoryScanner implements RepositoryScanSession {)}queued(signal: AbortSignal): Promise<WorkflowJob[]> {+ return this.read((jobs) => jobs.queued(signal), signal)+ }+ async reconcile(queued: readonly WorkflowJob[], signal: AbortSignal): Promise<void> {+ const present = new Set(queued.map((job) => job.job))+ const missing = this.claim.notices.filter((notice) => !present.has(notice.job))+ if (missing.length) {+ const results = await this.read(+ (jobs) =>+ parallelReads(+ missing,+ async (notice, signal) => {+ try {+ const current = await jobs.job(notice, signal)+ if (current.status === 'completed' || current.status === 'in_progress')+ return { ...current, noticeVersion: notice.version }+ } catch (error) {+ // A hidden or missing job supplies no positive evidence of completion.+ if (!(error instanceof GitHubRequestError && error.status === 404)) throw error+ }+ return undefined+ },+ signal,+ ),+ signal,+ )+ const departed = results.filter((job) => job !== undefined)+ signal.throwIfAborted()+ if (departed.length) await this.options.publish(departed, signal)+ }+ }+ private read<T>(read: (jobs: GitHubJobs) => Promise<T>, signal: AbortSignal): Promise<T> {return readRepositoryJobs(this.claim.scope,this.credentials,@@ -47,7 +80,7 @@ export class GitHubRepositoryScanner implements RepositoryScanSession {signal?.throwIfAborted()},this.claim.repository,- (jobs) => jobs.queued(signal),+ read,signal,)}@@ -124,6 +157,7 @@ export class RepositoryCompensation {this.options.wake()}signal.throwIfAborted()+ await reader.reconcile?.(jobs, signal)success = true} catch (error) {failure = errordiff --git a/apps/libs/ci-listener/src/credential-retirement.spec.ts b/apps/libs/ci-listener/src/credential-retirement.spec.tsindex fa26cb94a..5d900c415 100644--- a/apps/libs/ci-listener/src/credential-retirement.spec.ts+++ b/apps/libs/ci-listener/src/credential-retirement.spec.ts@@ -158,6 +158,11 @@ for (const backend of ['sqlite', 'postgres'] as const) {expect(await future.superseded()).toBe(false)expect(await roots()).toEqual(activated)})+ it('skips the separate clock read on an empty credential page', async () => {+ const now = jest.spyOn(state, 'now')+ await new CredentialCollector(state).step(lease)+ expect(now).not.toHaveBeenCalled()+ })it('uses database time and collects at the exact expiry boundary after takeover', async () => {const row = await issue()await takeover()diff --git a/apps/libs/ci-listener/src/credential-retirement.ts b/apps/libs/ci-listener/src/credential-retirement.tsindex 76161e360..257de81ca 100644--- a/apps/libs/ci-listener/src/credential-retirement.ts+++ b/apps/libs/ci-listener/src/credential-retirement.ts@@ -1,5 +1,5 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */-import { ExecutionLease, ListenerState, StateChange } from './state/store'+import { ExecutionLease, ListenerState } from './state/store'import { StateCorrupt, StateRecord } from './state/database'const object = (value: unknown): value is Record<string, unknown> =>@@ -16,14 +16,15 @@ export class CredentialCollector {async step(original: ExecutionLease): Promise<void> {const lease = { ...original }const rows = await this.state.scan(lease, { prefix: 'credential/', after: this.after, limit: 16 })- const now = await this.state.now(lease)- const changes: StateChange[] = []- for (const row of rows) {- // Scan credentials have independent claims, due indices and collection.- if (row.key.startsWith('credential/scan/')) continue- if (this.expired(row, lease, now)) changes.push({ key: row.key, expected: row.version })+ // Scan credentials use their own claim and expiration index.+ const candidates = rows.filter((row) => !row.key.startsWith('credential/scan/'))+ if (candidates.length) {+ const now = await this.state.now(lease)+ const changes = candidates+ .filter((row) => this.expired(row, lease, now))+ .map(({ key, version }) => ({ key, expected: version }))+ if (changes.length) await this.state.commit(lease, changes)}- if (changes.length) await this.state.commit(lease, changes)this.after = rows.length === 16 ? rows[rows.length - 1].key : ''}diff --git a/apps/libs/ci-listener/src/execution/journal.spec.ts b/apps/libs/ci-listener/src/execution/journal.spec.tsindex f20c88cde..b1e10c878 100644--- a/apps/libs/ci-listener/src/execution/journal.spec.ts+++ b/apps/libs/ci-listener/src/execution/journal.spec.ts@@ -243,6 +243,21 @@ for (const backend of ['sqlite', 'postgres'] as const) {expect(removed).toBe(true)observed.mockRestore()})+ it('reads scope metadata in one fenced batch when computing capacity', async () => {+ const reads = jest.spyOn(state, 'read')+ expect(await journal.remainingCapacity(lease, key, limits)).toBe(1)+ const metadata = reads.mock.calls.filter(([keys]) => !keys.some((item) => item.startsWith('usage/')))+ expect(metadata).toHaveLength(1)+ expect(metadata[0][0]).toEqual(expect.arrayContaining(['journal/format', key, 'app-scope/' + key.slice(6)]))+ expect(metadata[0][1]).toEqual(lease)+ })+ it.each(['remainingCapacity', 'permitsChargedRetry'] as const)('%s reads usage in one batch', async (probe) => {+ const reads = jest.spyOn(state, 'read')+ const result = await journal[probe](lease, key, limits)+ expect(result).toBe(probe === 'remainingCapacity' ? 1 : true)+ const usageBatches = reads.mock.calls.filter(([keys]) => keys.some((key) => key.startsWith('usage/')))+ expect(usageBatches).toHaveLength(1)+ })it('keeps unlimited domains out of the minimum when a finite domain is full', async () => {const policy = {limits: [@@ -254,6 +269,11 @@ for (const backend of ['sqlite', 'postgres'] as const) {await journal.reserve(lease, key, null, policy, { labels: ['boxlite'], scaleSet: 9 })expect(await journal.remainingCapacity(lease, key, policy)).toBe(0)expect(await journal.permitsChargedRetry(lease, key, policy)).toBe(true)+ await journal.reserve(lease, key, null, testCapacity({ tenant: 2, account: null }), {+ labels: ['boxlite'],+ scaleSet: 9,+ })+ expect(await journal.permitsChargedRetry(lease, key, policy)).toBe(false)})it.each([[null, undefined],@@ -506,6 +526,8 @@ for (const backend of ['sqlite', 'postgres'] as const) {it.each(['domain/global', 'usage/global'])('does not recreate a missing established %s', async (missing) => {const [row] = await state.read([missing])await state.commit(lease, [{ key: row.key, expected: row.version }])+ await expect(journal.scope(lease, key)).rejects.toBeInstanceOf(StateCorrupt)+ await expect(journal.remainingCapacity(lease, key, limits)).rejects.toBeInstanceOf(StateCorrupt)await expect(journal.define(lease, definition)).rejects.toBeInstanceOf(StateCorrupt)await expect(journal.define(lease, { ...definition, generation: 2 })).rejects.toBeInstanceOf(StateCorrupt)await expect(journal.reserve(lease, key, demand, limits)).rejects.toBeInstanceOf(StateCorrupt)diff --git a/apps/libs/ci-listener/src/execution/journal.ts b/apps/libs/ci-listener/src/execution/journal.tsindex 12c1a785f..d1f983f5f 100644--- a/apps/libs/ci-listener/src/execution/journal.ts+++ b/apps/libs/ci-listener/src/execution/journal.ts@@ -93,16 +93,25 @@ export class ExecutionJournal {async check(lease?: ExecutionLease): Promise<void> {const [row] = await this.state.read(['journal/format'], lease)+ this.validateFormat(row)+ }++ private validateFormat(row?: StateRecord): void {if (!row || !object(row.payload) || row.payload.version !== 2) throw new StateCorrupt()}async scope(lease: ExecutionLease, key: string): Promise<ScopeRow> {lease = { ...lease }+ const row = await this.readScopeMetadata(lease, key)+ await this.usage(Object.values(domains(row.scope)), lease)+ return row+ }++ private async readScopeMetadata(lease: ExecutionLease, key: string): Promise<ScopeRow> {const id = scopeId(key)- await this.check(lease)- const records = new Map(- (await this.state.read([key, 'scope-state/' + id, 'active-scope/' + id], lease)).map((row) => [row.key, row]),- )+ const keys = ['journal/format', key, 'scope-state/' + id, 'active-scope/' + id, 'app-scope/' + id]+ const records = new Map((await this.state.read(keys, lease)).map((row) => [row.key, row]))+ this.validateFormat(records.get('journal/format'))const record = records.get(key)if (!record || !object(record.payload)) throw new StateCorrupt()const scope = decodeScope(record.payload.scope)@@ -114,10 +123,9 @@ export class ExecutionJournal {const application = record.payload.applicationif (application !== null) {if (typeof application !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(application)) throw new StateCorrupt()- const [mapping] = await this.state.read(['app-scope/' + id], lease)+ const mapping = records.get('app-scope/' + id)if (!mapping || !object(mapping.payload) || mapping.payload.application !== application) throw new StateCorrupt()}- await this.usage(Object.values(domains(scope)), lease)return { record, scope, activity: activity!, index, active }}@@ -250,7 +258,7 @@ export class ExecutionJournal {}private async capacityMargin(lease: ExecutionLease, scope: string, policy: CapacityPolicy): Promise<number> {lease = { ...lease }- const ids = domains((await this.scope(lease, scope)).scope)+ const ids = domains((await this.readScopeMetadata(lease, scope)).scope)const usage = await this.usage(Object.values(ids), lease)let free = 2_147_483_647for (const { maximum, domain } of policy.limits) {diff --git a/apps/libs/ci-listener/src/job-observation.ts b/apps/libs/ci-listener/src/job-observation.tsindex 5b36ac6f5..50162a2cf 100644--- a/apps/libs/ci-listener/src/job-observation.ts+++ b/apps/libs/ci-listener/src/job-observation.ts@@ -1,6 +1,6 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */-import { Json, StateCorrupt } from './state/database'-import { IngressTransaction, StateChange } from './state/store'+import { Json, StateCorrupt, StateRecord } from './state/database'+import { StateChange } from './state/store'import { object, positive } from './execution/model'import type { WakeHint } from './webhook'@@ -12,11 +12,11 @@ export interface JobObservation {const rank = { queued: 0, in_progress: 1, completed: 2 }export class JobIdentityConflict extends Error {}-export async function recordJobObservation(- tx: IngressTransaction,+export function jobObservationChanges(+ prior: StateRecord | undefined,hint: WakeHint,supplied: JobObservation,-): Promise<StateChange[]> {+): StateChange[] {if (!hint.job) throw new StateCorrupt()if (!['queued', 'in_progress', 'completed'].includes(supplied.status) ||@@ -29,7 +29,6 @@ export async function recordJobObservation(if (observation.runner !== null && !positive(observation.runner)) throw new StateCorrupt()const jobId = hint.job.idconst factKey = `job-fact/${hint.installationId}/${jobId}`- const [prior] = await tx.read([factKey])let previous: JobObservation | undefinedif (prior) {const value = prior.payloaddiff --git a/apps/libs/ci-listener/src/listener.spec.ts b/apps/libs/ci-listener/src/listener.spec.tsindex ade84a061..c977fc7e6 100644--- a/apps/libs/ci-listener/src/listener.spec.ts+++ b/apps/libs/ci-listener/src/listener.spec.ts@@ -208,6 +208,21 @@ describe('CI shared Listener orchestration', () => {])expect(host.backend).not.toHaveBeenCalled()})+ it("settles an unsupported platform notice without opening a backend or consuming another installation's notice", async () => {+ await listener.receive(notification(55, 1, 7, 21, 33, ['boxlite', 'windows']))+ await listener.receive(notification(56, 9))+ const settled = deferred()+ const recover = state.recover.bind(state)+ jest.spyOn(state, 'recover').mockImplementation(async (...args) => {+ const rows = await recover(...args)+ if (args[2]?.includes('notice/') && !rows.some((row) => row.key === 'notice/1/55')) settled.resolve()+ return rows+ })+ expect(await state.read(['notice/1/55', 'notice/9/56'])).toHaveLength(2)+ await runUntil(settled.promise)+ expect((await state.read(['notice/1/55', 'notice/9/56'])).map((row) => row.key)).toEqual(['notice/9/56'])+ expect(host.backend).not.toHaveBeenCalled()+ })it('does not turn a notice for another installation into an authorized job', async () => {await listener.receive(notification(55, 9))const scanned = deferred()@@ -227,6 +242,8 @@ describe('CI shared Listener orchestration', () => {organization: 'other-tenant',installation: { ...scope.installation, id: 2 },}+ await listener.receive(notification(55, 2))+ await listener.receive(notification(56))jest.mocked(host.discover).mockResolvedValue({ scopes: [first, scope], completed: [], pending: false, ready: true })jest.mocked(host.backend).mockImplementation(async (current) => {if (current.binding === first.binding) throw new Error('Scope credentials unavailable')@@ -284,22 +301,37 @@ describe('CI shared Listener orchestration', () => {expect(await journal.used(scope.organization)).toBe(1)expect(backend.workers.create).not.toHaveBeenCalled()})- it('propagates a corrupt scale set registration without polling or provisioning', async () => {- const failure = new StateCorrupt()- const failed = deferred()- const scan = state.scan.bind(state)- jest.spyOn(state, 'scan').mockImplementation(async (owner, range) => {- if (range.prefix.startsWith('scale-set/')) throw failure- return scan(owner, range)- })- jest.mocked(host.report).mockImplementation((error) => {- if (error === failure) failed.resolve()- })- await runUntil(failed.promise)- expect(host.report).not.toHaveBeenCalledWith(failure, 'scope-backend')- expect(backend.workers.create).not.toHaveBeenCalled()- })+ it.each(['invalid-scope/boxlite', 'a'.repeat(64) + '/ubuntu-latest'])(+ 'rejects a persisted scale set with an invalid scope or resource label (%s)',+ async (suffix) => {+ jest.mocked(host.discover).mockImplementationOnce(async (owner) => {+ await state.commit(owner, [+ {+ key: 'scale-set/' + suffix,+ expected: null,+ payload: {+ name: 'boxlite-' + randomUUID().replaceAll('-', ''),+ set: 12,+ assigned: 1,+ held: 0,+ pending: [],+ message: null,+ },+ },+ ])+ return { scopes: [scope], completed: [], pending: false, ready: true }+ })+ const failed = deferred()+ jest.mocked(host.report).mockImplementation((error, operation) => {+ if (error instanceof StateCorrupt && operation !== 'scope-backend') failed.resolve()+ })+ await runUntil(failed.promise)+ expect(host.backend).not.toHaveBeenCalled()+ expect(backend.workers.create).not.toHaveBeenCalled()+ },+ )it('closes the active scale set backend when discovery removes an idle scope', async () => {+ await listener.receive(notification())const closed = deferred()jest.mocked(host.discover).mockImplementation(async () => ({scopes: jest.mocked(host.backend).mock.calls.length ? [] : [scope],@@ -312,6 +344,41 @@ describe('CI shared Listener orchestration', () => {expect(backend.close).toHaveBeenCalledTimes(1)expect(backend.workers.create).not.toHaveBeenCalled()})+ it('closes a revoked scale set and releases its outstanding reservation before retiring the backend', async () => {+ const journal = new ExecutionJournal(state)+ const retired = deferred()+ let controllerSignal: AbortSignal | undefined+ let usedAtRetirement: number | undefined+ let reserved = false+ backend.scaleSetAuthority = async (signal) => {+ controllerSignal = signal+ return new Set(['repo'])+ }+ jest.mocked(host.discover).mockImplementation(async (owner) => {+ lease = owner+ if (controllerSignal && !reserved) {+ const key = await journal.define(owner, scope)+ const allocation = await journal.reserve(owner, key, null, testCapacity({ account: 1, tenant: 1 }), {+ labels: ['boxlite'],+ scaleSet: 9,+ })+ expect(allocation).toBeDefined()+ reserved = true+ }+ return { scopes: reserved ? [] : [scope], completed: [], pending: true, ready: true }+ })+ jest.mocked(backend.close).mockImplementation(async () => {+ if (controllerSignal?.aborted && !abort.signal.aborted) {+ usedAtRetirement = await journal.used(scope.organization)+ retired.resolve()+ }+ })+ await listener.receive(notification())+ await runUntil(retired.promise)+ expect(reserved).toBe(true)+ expect(usedAtRetirement).toBe(0)+ expect(backend.workers.create).not.toHaveBeenCalled()+ })it('retains an undispatched worker when discovery restores its scope during a drain', async () => {const journal = new ExecutionJournal(state)const restored = deferred()@@ -449,6 +516,29 @@ describe('CI shared Listener orchestration', () => {await running.catch(() => {})}})+ it('keeps multiple idle repository scopes cold across scheduler cycles', async () => {+ const other = structuredClone(scope)+ if (other.runners.kind !== 'repository') throw new Error('Expected repository scope')+ other.runners.repository.id = 22+ other.runners.repository.name = 'another-repo'+ jest.mocked(host.discover).mockResolvedValue({ scopes: [scope, other], completed: [], pending: false, ready: true })+ const cycles = deferred()+ const recover = state.recover.bind(state)+ let count = 0+ jest.spyOn(state, 'recover').mockImplementation(async (...args) => {+ const result = await recover(...args)+ if (args[2]?.includes('notice/') && ++count === 4) cycles.resolve()+ return result+ })+ const capacity = jest.spyOn(ExecutionJournal.prototype, 'remainingCapacity')+ try {+ await runUntil(cycles.promise)+ expect(host.backend).not.toHaveBeenCalled()+ expect(capacity).not.toHaveBeenCalled()+ } finally {+ capacity.mockRestore()+ }+ })it('does not scan idle repositories or refresh the directory on every scheduler tick', async () => {const observed = deferred(),recover = state.recover.bind(state)diff --git a/apps/libs/ci-listener/src/listener.ts b/apps/libs/ci-listener/src/listener.tsindex f3b41b532..0a14fbe16 100644--- a/apps/libs/ci-listener/src/listener.ts+++ b/apps/libs/ci-listener/src/listener.ts@@ -54,11 +54,13 @@ export interface ListenerHost {}interface Runtime {sets?: ScaleSetController+ workersRestored?: booleanbackend: ListenerBackendpool: WorkerPool}interface Session {setWork: ScaleSetWork+ savedSets?: Map<string, string[]>planning: WorkQueueexecution: WorkQueuelease: ExecutionLease@@ -467,14 +469,38 @@ export class Listener {await this.settle(lease, wake)}}+ session.savedSets ??= await ScaleSetController.recover(this.options.state, lease)+ const jobs = records.filter((row) => row.key.startsWith('notice/')).map(pendingJob)const scopes = new Map(recovery.rows.map((row) => [row.record.key, row.scope]))const recovering = new Set(scopes.keys())- for (const [key, scope] of session.current) scopes.set(key, scope)+ for (const key of [...session.savedSets.keys(), ...session.runtimes.keys()]) {+ const current = session.current.get(key)+ if (current) scopes.set(key, current)+ }+ for (const [key, scope] of jobs.length ? session.current : []) {+ if (jobs.some((job) => matches(scope, job))) scopes.set(key, scope)+ }for (const [key, scope] of scopes) {signal.throwIfAborted()try {+ const notices: { row: StateRecord; label: string }[] = []+ if (session.current.has(key)) {+ for (const job of jobs) {+ if (!matches(scope, job)) continue+ const row = job.record+ const labels = object(row.payload) ? row.payload.labels : undefined+ const selection =+ Array.isArray(labels) && labels.every((label): label is string => typeof label === 'string')+ ? selectRunnerLabels(labels, this.worker.labels)+ : undefined+ if (selection) notices.push({ row, label: selection.label })+ else await this.settle(lease, row)+ }+ }+ const saved = session.savedSets?.get(key) ?? []+ if (!recovering.has(key) && !saved.length && !notices.length && !session.runtimes.has(key)) continueconst runtime = await this.runtime(session, key, scope)- await this.scheduleScaleSets(session, key, scope, runtime, records, signal, recovering.has(key))+ await this.scheduleScaleSets(session, key, scope, runtime, notices, saved, signal, recovering.has(key))} catch (error) {signal.throwIfAborted()if (error instanceof LeaseLost || error instanceof StateCorrupt) throw error@@ -497,7 +523,10 @@ export class Listener {}for (const [key, runtime] of session.runtimes) {if (session.current.has(key) || (await this.journal.scope(lease, key)).active) continue- await runtime.sets?.close()+ if (runtime.sets) {+ await runtime.sets.close()+ session.savedSets = undefined+ }await runtime.pool.close()await runtime.backend.close()session.runtimes.delete(key)@@ -508,7 +537,8 @@ export class Listener {key: string,scope: ExecutionScope,runtime: Runtime,- records: readonly StateRecord[],+ notices: readonly { row: StateRecord; label: string }[],+ saved: readonly string[],signal: AbortSignal,recovering: boolean,) {@@ -536,29 +566,22 @@ export class Listener {},signal,)- try {- await controller.restore()- } catch (error) {- await controller.close()- throw error- }runtime.sets = controller}if (!current && runtime.sets) {await runtime.sets.close()runtime.sets = undefined+ runtime.workersRestored = false+ session.savedSets = undefined}if (current && runtime.sets) {- // Authenticated job observations seed classes. Only Actions messages admit work.- for (const row of records) {- if (!row.key.startsWith('notice/') || !matches(scope, pendingJob(row))) continue- const labels = object(row.payload) ? row.payload.labels : undefined- if (Array.isArray(labels) && labels.every((label): label is string => typeof label === 'string')) {- const selection = selectRunnerLabels(labels, this.worker.labels)- if (selection) await runtime.sets.observe(selection.label)- }- await this.settle(session.lease, row)+ for (const label of saved) runtime.sets.restoreLabel(label)+ session.savedSets?.delete(key)+ if (recovering && !runtime.workersRestored) {+ await runtime.sets.restoreWorkers()+ runtime.workersRestored = true}+ runtime.sets.observe(notices)}const targets = runtime.sets?.targets() ?? []const demand = targets.some((target) => target.assigned > 0)diff --git a/apps/libs/ci-listener/src/scale-set-controller.ts b/apps/libs/ci-listener/src/scale-set-controller.tsindex 90f4eb4d8..ecf7262d1 100644--- a/apps/libs/ci-listener/src/scale-set-controller.ts+++ b/apps/libs/ci-listener/src/scale-set-controller.ts@@ -4,7 +4,7 @@ import { CapacityPolicy } from './capacity'import { AllocationRow, ExecutionJournal } from './execution/journal'import { ExecutionScope, object, positive, retryCapacity, scopeKey } from './execution/model'import { GitHubRequestError } from './github'-import { DEFAULT_RESOURCE_LABEL, selectRunnerLabels } from './resource-labels'+import { parseResourceLabels, selectRunnerLabels } from './resource-labels'import { ScaleSetDiagnostics, ScaleSetEvent, ScaleSetFailure } from './scale-set-diagnostics'import { ActionsScaleSets, isRequestIdText, ScaleSetRemoved, ScaleSetSession } from './scale-set-client'import { LeaseLost, StateCorrupt, StateRecord } from './state/database'@@ -139,7 +139,8 @@ export class ScaleSetController {private readonly stop = new AbortController()private readonly lanes = new Map<string, Lane>()private readonly confirmed = new Map<string, ScaleTarget>()- private readonly persisted = new Set<string>()+ private demand = new Set<string>()+ private readonly recovering = new Set<string>()private readonly waiting = new Map<string, number>()private readonly cooling = new Map<string, NodeJS.Timeout>()private readonly prefix: string@@ -169,25 +170,58 @@ export class ScaleSetController {}return active}- async restore(): Promise<void> {- const occupied: string[] = [],- idle: string[] = []+ /** Recover service commitments once per owner. Idle registrations retain their identities in storage. */+ static async recover(state: ListenerState, lease: ExecutionLease): Promise<Map<string, string[]>> {+ const occupied = new Map<string, string[]>()let after = ''for (;;) {- const page = await this.state.scan(this.lease, { prefix: this.prefix, after, limit: 100 })+ const page = await state.scan(lease, { prefix: 'scale-set/', after, limit: 100 })for (const row of page) {const record = readRecord(row)- const list = record.held || record.assigned ? occupied : idle- const label = row.key.slice(this.prefix.length)- list.push(label)- this.persisted.add(label)+ const match = /^scale-set\/([a-f0-9]{64})\/([^/]+)$/.exec(row.key)+ if (!match || !selectRunnerLabels([match[2]], [])) throw new StateCorrupt()+ if (!record.held && !record.assigned && !record.pending.length) continue+ const key = 'scope/' + match[1]+ const labels = occupied.get(key) ?? []+ labels.push(match[2])+ occupied.set(key, labels)}- if (page.length < 100) break+ if (page.length < 100) return occupiedafter = page[page.length - 1].key}- for (const label of [...occupied, DEFAULT_RESOURCE_LABEL, ...idle]) this.watch(label)}- watch(label: string, failures = 0) {+ private async workerLabels(): Promise<Map<number, string>> {+ const labels = new Map<number, string>()+ let after = ''+ do {+ const page = await this.journal.workers(this.lease, scopeKey(this.scope), after)+ for (const { value } of page.rows) {+ const supply = value.supply+ if (!supply?.scaleSet) continue+ const selected = parseResourceLabels(supply.labels)+ if (!selected) throw new StateCorrupt()+ labels.set(supply.scaleSet, selected.label)+ }+ after = page.after+ } while (after)+ return labels+ }+ async restoreWorkers(): Promise<void> {+ for (const label of (await this.workerLabels()).values()) this.restoreLabel(label)+ }+ /** Workflow job observations own the durable inbox. Scale-set request IDs only identify acquisitions. */+ observe(notices: readonly { row: StateRecord; label: string }[]): void {+ const previous = this.demand+ this.demand = new Set(notices.map(({ label }) => label))+ for (const label of this.demand) if (!previous.has(label)) this.queue(label)+ for (const label of this.waiting.keys())+ if (!this.demand.has(label) && !this.recovering.has(label)) this.waiting.delete(label)+ }+ restoreLabel(label: string): void {+ this.recovering.add(label)+ this.queue(label)+ }+ private queue(label: string, failures = 0) {if (this.lanes.has(label) || this.waiting.has(label) || this.cooling.has(label) || this.signal.aborted) returnthis.waiting.set(label, failures)this.openNext()@@ -213,18 +247,21 @@ export class ScaleSetController {},this.host.observe,)+ let parked = falselane.task = this.listen(lane, [...selection.labels], failures, log)- .then((rotate) => {- if (rotate) {- this.confirmed.delete(label)- if (!this.signal.aborted) this.waiting.set(label, 0)- }+ .then((idle) => {+ parked = idle}).catch((error) => {if (!this.signal.aborted) this.host.report(error, log.failure(error))}).finally(() => {this.lanes.delete(label)+ if (parked) {+ this.confirmed.delete(label)+ // A notice can arrive while the old HTTP session is closing.+ if (!this.signal.aborted && this.demand.has(label)) this.waiting.set(label, 0)+ }this.openNext()})}@@ -237,7 +274,8 @@ export class ScaleSetController {setTimeout(() => {if (Date.now() < deadline) return schedule()this.cooling.delete(label)- this.watch(label, failures)+ // A canceled job can disappear during backoff. Its provider cooldown still applies to a later wake.+ if (this.recovering.has(label) || this.demand.has(label)) this.queue(label, failures)}, wait),)}@@ -367,13 +405,6 @@ export class ScaleSetController {])return row}- async observe(label: string): Promise<void> {- if (!this.persisted.has(label)) {- await this.registration(this.prefix + label)- this.persisted.add(label)- }- this.watch(label)- }private async start(key: string, labels: string[], signal: AbortSignal, log: ScaleSetDiagnostics) {await log.during('authority', () => this.host.authority(signal))let row = await this.registration(key)@@ -431,6 +462,15 @@ export class ScaleSetController {const pendingRequests = new Map(previous.pending.map(({ id, phase }) => [id, phase]))let freshStatistics = trueconst publish = (assigned: number, held: number, previous: SetRecord) => {+ if (+ assigned ||+ held ||+ pendingRequests.size ||+ previous.assigned ||+ previous.held ||+ this.host.charged(start.id)+ )+ this.recovering.add(lane.label)const delivery = !freshStatistics && lane.target?.assigned === assigned ? lane.target.delivery : undefinedlane.target = {id: start.id,@@ -555,9 +595,17 @@ export class ScaleSetController {}),)log.emit({ event: 'ci-scale-set-poll-started', capacity })+ const reconciling = !!(+ lane.target!.held ||+ lane.target!.assigned ||+ pendingRequests.size ||+ this.host.charged(start.id)+ )const message = await log.during('poll', () => start.session.poll(capacity, last, signal))log.context.messageId = message?.id ?? null- if (message)+ if (message) {+ // An unacknowledged service message can outlive the original job notice.+ this.recovering.add(lane.label)log.emit({event: 'ci-scale-set-message-received',offered: message.available.length,@@ -565,6 +613,7 @@ export class ScaleSetController {assigned: message.assigned,held: lane.target!.held,})+ }failures = 0// On reconnect a lost acquire may never be redelivered. Compare any// missing request with service statistics, keeping explicit reoffers charged.@@ -611,8 +660,16 @@ export class ScaleSetController {})}if (!message) {- if (this.waiting.size && !lane.target!.held && !lane.target!.assigned && !this.host.charged(start.id))- return true+ // A poll that reconciled outstanding work used the old capacity. Advertise the released slots once.+ if (reconciling || (!this.waiting.size && this.demand.has(lane.label))) continue+ if (!lane.target!.held && !lane.target!.assigned && !pendingRequests.size && !this.host.charged(start.id)) {+ // Local charges may be empty before a recovered or retiring worker reaches pool planning.+ const workers = await this.work.run(signal, () => this.workerLabels())+ if (!workers.has(start.id)) {+ this.recovering.delete(lane.label)+ return true+ }+ }continue}await this.work.run(signal, async () => {diff --git a/apps/libs/ci-listener/src/scale-set-listener.spec.ts b/apps/libs/ci-listener/src/scale-set-listener.spec.tsindex fe9dbf1a0..0e73629f1 100644--- a/apps/libs/ci-listener/src/scale-set-listener.spec.ts+++ b/apps/libs/ci-listener/src/scale-set-listener.spec.ts@@ -249,7 +249,35 @@ class ActionsFixture {}}+function signedJob(job: number, status: 'queued' | 'completed' = 'queued', labels = ['boxlite']) {+ const secret = Buffer.alloc(32, 1)+ const raw = Buffer.from(+ JSON.stringify({+ action: status,+ installation: { id: 1 },+ repository: { id: 21, owner: { id: 7 } },+ workflow_job: { id: job, run_id: 31, status, labels },+ }),+ )+ return verifyWebhook(+ {+ raw,+ event: 'workflow_job',+ delivery: randomUUID(),+ signature: 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex'),+ },+ secret,+ )!+}+const scenarios = [+ 'retains both queued notices when one slot accepts only one offer',+ 'keeps a queued job across an empty poll with spare capacity',+ 'keeps a queued wake when a zero-capacity poll reports another job completed',+ 'keeps a replacement job awake when the original job completes during its poll',+ 'parks an empty session and wakes on a new signed notice during close',+ 'does not retry registration after the only queued job completes during backoff',+ 'replays a queued notice after takeover interrupts its first poll','subtracts assigned jobs from acquired holds on an idle poll','subtracts assigned jobs from acquired holds on reconnect','reconciles acquired and replayed demand',@@ -285,7 +313,8 @@ const scenarios = ['holds accepted quota through idle polls and an owner restart','reuses a held slot after cancellation between statistics samples','returns an undispatched reservation for a deleted set',- 'rotates idle sessions through every page of restored specifications',+ 'gives every queued specification a turn beyond the session limit',+ 'recovers an occupied label past a full page of sleeping registrations','credits work only to the original JIT runner','rejects conflicting persisted request identities on restore','opens a healthy specification while 64 sessions back off',@@ -350,6 +379,9 @@ for (const storage of ['sqlite', 'postgres'])}let source: CredentialSource = { kind: 'pat', repository: 21, token: () => 'local-token' }if (+ scenario === 'keeps a replacement job awake when the original job completes during its poll' ||+ scenario === 'parks an empty session and wakes on a new signed notice during close' ||+ scenario === 'does not retry registration after the only queued job completes during backoff' ||scenario === 'checks an organization runner group' ||scenario === 'starts an organization worker with the custom resource label') {@@ -432,7 +464,23 @@ for (const storage of ['sqlite', 'postgres'])let maximum = 2let policyOwner: ExecutionLease | undefinedlet policyChecks: StateCheck[] | undefined- const start = () => {+ const seedNotice = async (job: number, label: string) => {+ await state.ingest([+ {+ key: 'notice/' + scope.installation.id + '/' + job,+ expected: null,+ payload: {+ installationId: scope.installation.id,+ accountId: 7,+ repositoryId: 21,+ job: { id: job, runId: 31 },+ labels: [label],+ },+ },+ ])+ }+ let started = false+ const start = (queued = true) => {const controller = new AbortController()listener = new Listener({state,@@ -446,7 +494,12 @@ for (const storage of ['sqlite', 'postgres'])},timing: { tickMs: 5, leaseMs: 450 },})- const task = listener.run(controller.signal)+ const initial = !started+ started = true+ const task = (async () => {+ if (initial && queued && !fixture.discoverCustom) await seedNotice(99999, 'boxlite')+ await listener.run(controller.signal)+ })()return async () => {controller.abort()await task@@ -510,7 +563,7 @@ for (const storage of ['sqlite', 'postgres'])['boxlite'],).scaleSets,authority: async () => new Set(['repo']),- charged: () => 0,+ charged: () => 1,releaseSupply: () => {},creationReady: () => true,policy: async () => ({ limits: [{ domain: 'organization' as const, maximum: 2 }] }),@@ -538,14 +591,14 @@ for (const storage of ['sqlite', 'postgres'])if (rest) return Response.json({ message: 'You have exceeded a secondary rate limit.' }, { status })return new Response(null, { status, headers: limited ? { 'retry-after': '60' } : undefined })})- await controller.restore()+ controller.restoreLabel('boxlite')await until(() => errors.length > 0)const peer = jest.fn(async () => 'fresh')expect(await work.refreshStatistics(peer, peer)).toBe(limited ? undefined : 'fresh')expect(peer).toHaveBeenCalledTimes(limited ? 0 : 1)return}- await controller.restore()+ controller.restoreLabel('boxlite')await until(() => calls('/messages') > 0)const stats = () => calls('/tenant/_apis/runtime/runnerscalesets/9')const initial = stats()@@ -635,7 +688,7 @@ for (const storage of ['sqlite', 'postgres'])new AbortController().signal,)stop = () => controller.close()- await controller.restore()+ controller.restoreLabel('boxlite')await until(() => fixture.requests.includes('GET /messages'))fixture.publish(1, 1, [123])await until(() => fixture.sessions.length === 2)@@ -704,6 +757,167 @@ for (const storage of ['sqlite', 'postgres'])expect([...fixture.throttledSets.values()]).toEqual(Array(64).fill(1))return}+ if (scenario === 'keeps a queued wake when a zero-capacity poll reports another job completed') {+ const polls = () => fixture.requests.filter((request) => request === 'GET /messages').length+ maximum = 0+ await seedNotice(903, 'boxlite')+ stop = start(false)+ await until(() => polls() === 1)+ fixture.publish(1, 0, [], [{ messageType: 'JobCompleted', runnerRequestId: 902 }])+ await until(() => polls() === 2)+ maximum = 1+ fixture.idle()+ await until(+ () =>+ polls() >= 3 ||+ fixture.requests.some((request) => request.startsWith('DELETE ') && request.includes('/sessions/')),+ )+ expect(polls()).toBe(3)+ fixture.publish(2, 0, [903])+ await until(() => fixture.acknowledged.includes(2))+ expect(fixture.acquired).toEqual([[903]])+ return+ }+ if (scenario === 'keeps a queued job across an empty poll with spare capacity') {+ await seedNotice(501, 'boxlite')+ stop = start(false)+ await until(() => fixture.requests.includes('GET /messages'))+ fixture.idle()+ await until(+ () =>+ fixture.requests.filter((request) => request === 'GET /messages').length > 1 ||+ fixture.requests.some((request) => request.startsWith('DELETE ') && request.includes('/sessions/')),+ )+ expect((await state.read(['notice/0/501'])).map((row) => row.key)).toEqual(['notice/0/501'])+ fixture.publish(1, 0, [901])+ await until(() => fixture.acknowledged.includes(1))+ expect(fixture.acquired).toEqual([[901]])+ return+ }+ if (scenario === 'retains both queued notices when one slot accepts only one offer') {+ maximum = 1+ await seedNotice(501, 'boxlite')+ await seedNotice(502, 'boxlite')+ const cycles = jest.spyOn(state, 'recover')+ stop = start(false)+ fixture.publish(1, 0, [901, 902])+ await until(() => fixture.acknowledged.includes(1))+ const observed = cycles.mock.calls.length+ await until(() => cycles.mock.calls.length >= observed + 3)+ expect(fixture.acquired).toEqual([[901]])+ expect((await state.read(['notice/0/501', 'notice/0/502'])).map((row) => row.key)).toEqual([+ 'notice/0/501',+ 'notice/0/502',+ ])+ return+ }+ if (scenario === 'replays a queued notice after takeover interrupts its first poll') {+ await seedNotice(903, 'boxlite')+ stop = start(false)+ await until(() => fixture.requests.includes('GET /messages'))+ await stop()+ expect(await state.read(['notice/0/903'])).toHaveLength(1)+ stop = start(false)+ await until(() => fixture.sessions.length === 2)+ fixture.publish(1, 0, [903])+ await until(() => fixture.acknowledged.includes(1))+ expect(await state.read(['notice/0/903'])).toHaveLength(1)+ expect(fixture.acquired).toEqual([[903]])+ expect(await journal.used(scope.organization)).toBe(1)+ return+ }+ if (scenario === 'does not retry registration after the only queued job completes during backoff') {+ let registrations = 0+ fetch.mockImplementation(async (input, options = {}) => {+ if (new URL(String(input)).pathname.endsWith('/registration-token')) {+ registrations+++ return new Response(null, { status: 503 })+ }+ return fixture.fetch(input, options)+ })+ stop = start(false)+ await listener!.receive(signedJob(904))+ await until(() => report.mock.calls.some(([, , context]) => context?.retryAt !== undefined))+ const deadline = report.mock.calls.find(([, , context]) => context?.retryAt !== undefined)![2]!.retryAt!+ const before = registrations+ expect(before).toBeGreaterThan(0)+ await listener!.receive(signedJob(904, 'completed'))+ expect(await state.read(['notice/1/904'])).toEqual([])+ await until(() => Date.now() >= deadline + 100)+ expect(registrations).toBe(before)+ return+ }+ if (scenario === 'keeps a replacement job awake when the original job completes during its poll') {+ const observed = jest.spyOn(ScaleSetController.prototype, 'observe')+ try {+ stop = start(false)+ await listener!.receive(signedJob(901))+ const polls = () => fixture.requests.filter((request) => request === 'GET /messages').length+ await until(() => polls() === 1)+ await listener!.receive(signedJob(901, 'completed'))+ await listener!.receive(signedJob(902))+ await until(() =>+ observed.mock.calls.some(([notices]) => notices.length === 1 && notices[0].row.key === 'notice/1/902'),+ )+ fixture.idle()+ await until(() => polls() === 2)+ expect((await state.read(['notice/1/901', 'notice/1/902'])).map((row) => row.key)).toEqual([+ 'notice/1/902',+ ])+ expect(fixture.sessions).toHaveLength(1)+ fixture.publish(1, 0, [902])+ await until(() => fixture.acknowledged.includes(1))+ expect(fixture.acquired).toEqual([[902]])+ } finally {+ observed.mockRestore()+ }+ return+ }+ if (scenario === 'parks an empty session and wakes on a new signed notice during close') {+ let closing = false+ let resume!: () => void+ const release = new Promise<void>((resolve) => {+ resume = resolve+ })+ fetch.mockImplementation(async (input, options = {}) => {+ if (options.method === 'DELETE' && new URL(String(input)).pathname.includes('/sessions/')) {+ closing = true+ await release+ }+ return fixture.fetch(input, options)+ })+ try {+ stop = start(false)+ const first = signedJob(901)+ expect(await listener!.receive(first)).toBe('stored')+ expect(await listener!.receive(first)).toBe('duplicate')+ await until(() => fixture.requests.includes('GET /messages'))+ const observed = jest.spyOn(ScaleSetController.prototype, 'observe')+ try {+ await listener!.receive(signedJob(901, 'completed'))+ await until(() => observed.mock.calls.some(([notices]) => notices.length === 0))+ } finally {+ observed.mockRestore()+ }+ fixture.idle()+ await until(() => closing || fixture.requests.filter((request) => request === 'GET /messages').length > 1)+ expect(closing).toBe(true)+ expect(fixture.sessions).toHaveLength(1)+ expect(await listener!.receive(signedJob(902))).toBe('stored')+ await until(() =>+ observe.mock.calls.some(([event]) => event.event === 'ci-job-notification' && event.jobId === 902),+ )+ resume()+ await until(() => fixture.sessions.length === 2)+ fixture.publish(1, 0, [902])+ await until(() => fixture.acknowledged.includes(1))+ expect(fixture.acquired).toEqual([[902]])+ expect(await journal.used(scope.organization)).toBe(1)+ } finally {+ resume()+ }+ return+ }if (scenario === 'rejects conflicting persisted request identities on restore') {const owner = (await state.acquire(randomUUID(), 30000))!const key = await journal.define(owner, scope)@@ -746,14 +960,19 @@ for (const storage of ['sqlite', 'postgres'])new AbortController().signal,)stop = () => controller.close()- await expect(controller.restore()).rejects.toBeInstanceOf(StateCorrupt)+ await expect(ScaleSetController.recover(state, owner)).rejects.toBeInstanceOf(StateCorrupt)expect(fixture.requests).toEqual([])return}- if (scenario === 'rotates idle sessions through every page of restored specifications') {+ if (+ scenario === 'gives every queued specification a turn beyond the session limit' ||+ scenario === 'recovers an occupied label past a full page of sleeping registrations'+ ) {const owner = (await state.acquire(randomUUID(), 600))!const key = await journal.define(owner, scope)const labels = Array.from({ length: 101 }, (_, index) => 'boxlite-1vcpu-1gbmem-' + (index + 1) + 'gbdisk')+ const recoveryLabel = [...labels].sort().at(-1)!+ const recovering = scenario === 'recovers an occupied label past a full page of sleeping registrations'for (const label of labels) {await state.commit(owner, [{@@ -763,14 +982,26 @@ for (const storage of ['sqlite', 'postgres'])name: 'boxlite-' + randomUUID().replaceAll('-', ''),set: null,assigned: 0,- held: 0,- pending: [],+ held: recovering && label === recoveryLabel ? 1 : 0,+ pending: recovering && label === recoveryLabel ? [{ id: '123', phase: 'verify' }] : [],message: null,session: null,},},])}+ if (recovering) {+ expect(await ScaleSetController.recover(state, owner)).toEqual(new Map([[key, [recoveryLabel]]]))+ stop = start(false)+ await until(() => fixture.requests.includes('GET /messages'))+ expect(+ observe.mock.calls+ .filter(([event]) => event.event === 'ci-scale-set-session-opened')+ .map(([event]) => event.label),+ ).toEqual([recoveryLabel])+ return+ }+ for (const [index, label] of labels.entries()) await seedNotice(1000 + index, label)for (let i = 0; i < 64; i++) fixture.idle()stop = start()const opened = () =>@@ -822,13 +1053,13 @@ for (const storage of ['sqlite', 'postgres'])const former = (await state.acquire(randomUUID(), 600))!,scans = state.scans()await scans.synchronize(former, 'personal-token', scope.binding, [scope])- const claim = (await scans.claim('label-scanner'))!- await scans.publish(- claim,- [{ repository: 21, job: 55, run: 33, status: 'queued', labels: fixture.labels, runner: null }],- ['boxlite'],- )- await scans.finish(claim, { success: true, intervalMs: 60_000 })+ jest.mocked(host.scan).mockImplementation(async (claim) => ({+ queued: async () => [+ { repository: 21, job: 55, run: 33, status: 'queued', labels: fixture.labels, runner: null },+ ],+ publish: (jobs) => scans.publish(claim, jobs, ['boxlite']),+ close: async () => {},+ }))}if (scenario === 'retries an offline assignment after a statless cancellation releases the other candidate') {let reject!: () => void@@ -1005,29 +1236,14 @@ for (const storage of ['sqlite', 'postgres'])}stop = start()if (fixture.discoverCustom && !scanOnly) {- await until(() => fixture.requests.includes('GET /messages/default'))+ expect(fixture.defaultSet).toBeUndefined()expect(fixture.definition).toBeUndefined()- const secret = Buffer.alloc(32, 1),- raw = Buffer.from(- JSON.stringify({- action: 'queued',- installation: { id: 1 },- repository: { id: 21, owner: { id: 7 } },- workflow_job: { id: 51, run_id: 31, status: 'queued', labels: fixture.labels },- }),- )- const webhook = verifyWebhook(- {- raw,- event: 'workflow_job',- delivery: randomUUID(),- signature: 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex'),- },- secret,- )!+ const webhook = signedJob(51, 'queued', fixture.labels)expect(await listener!.receive(webhook)).toBe('stored')}await until(() => fixture.sessions.length > 0)+ if (fixture.discoverCustom) expect(fixture.defaultSet).toBeUndefined()+ if (scanOnly) expect(host.scan).toHaveBeenCalledTimes(1)if (scenario === 'traces a failed poll with its scale set and HTTP status') {await until(() => fixture.sessions.length === 2)expect(report).toHaveBeenCalledWith(@@ -1817,7 +2033,7 @@ it('reserves one shared global slot for concurrent offers to two tenants', asynclifetime.signal,)controllers.push(controller)- await controller.restore()+ controller.restoreLabel('boxlite')}await until(() => fixtures.every((f) => f.requests.includes('GET /messages')))for (const fixture of fixtures) fixture.publish(0, 0, [123])diff --git a/apps/libs/ci-listener/src/webhook.ts b/apps/libs/ci-listener/src/webhook.tsindex ba6140ad4..5e0de3ca9 100644--- a/apps/libs/ci-listener/src/webhook.ts+++ b/apps/libs/ci-listener/src/webhook.ts@@ -3,7 +3,7 @@ import { createHash, createHmac, timingSafeEqual } from 'node:crypto'import { ListenerState } from './state/store'import { Json, StateConflict, StateCorrupt } from './state/database'import { parseResourceLabels } from './resource-labels'-import { JobIdentityConflict, JobObservation, recordJobObservation } from './job-observation'+import { JobIdentityConflict, JobObservation, jobObservationChanges } from './job-observation'export interface WakeHint {installationId: number@@ -197,7 +197,10 @@ export class ListenerInbox {wake = `wake/${hint.installationId}/${hint.repositoryId}`,notice = hint.job ? `notice/${hint.installationId}/${hint.job.id}` : undefinedreturn this.state.ingress(`${hint.installationId}/${hint.repositoryId}`, async (tx) => {- const rows = new Map((await tx.read([receipt, wake, ...(notice ? [notice] : [])])).map((row) => [row.key, row]))+ const fact = hint.job ? `job-fact/${hint.installationId}/${hint.job.id}` : undefined+ const rows = new Map(+ (await tx.read([receipt, wake, ...(notice && fact ? [notice, fact] : [])])).map((row) => [row.key, row]),+ )const previous = rows.get(receipt)if (previous) {if (@@ -233,7 +236,7 @@ export class ListenerInbox {throw new WebhookError(409, 'Job identity conflicts with a previous notification')let changestry {- changes = observation && hint.job ? await recordJobObservation(tx, hint, observation) : []+ changes = observation && fact ? jobObservationChanges(rows.get(fact), hint, observation) : []} catch (error) {if (error instanceof JobIdentityConflict) throw new WebhookError(409, error.message)throw error