The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* Copyright 2026 BoxLite AI
* SPDX-License-Identifier: AGPL-3.0
*/
import { Logger } from '@nestjs/common'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { GoogleError } from 'google-gax'
import { DataSource } from 'typeorm'
import { Runner } from '../entities/runner.entity'
import { RunnerDiskExpansion } from '../entities/runner-disk-expansion.entity'
import { RunnerDiskUsageSample } from '../entities/runner-disk-usage-sample.entity'
import { RunnerState } from '../enums/runner-state.enum'
import { RunnerUnschedulableReason } from '../enums/runner-unschedulable-reason.enum'
import { RunnerDiskExpansionStatus } from '../enums/runner-disk-expansion-status.enum'
import { RunnerDataDiskRef } from '../common/runner-data-disk-ref'
import { RedisLockProvider } from '../common/redis-lock.provider'
import { metrics, type Meter } from '@opentelemetry/api'
import { TypedConfigService } from '../../config/typed-config.service'
import {
BASELINE_READ_DEADLINE_MS,
CONFIRM_TOLERANCE_RATIO,
EXPANSION_ERROR,
HYPERDISK_BALANCED_MAX_GIB,
MAX_PATCHES_PER_ROUND,
RunnerDiskExpansionService,
headroomGiB,
maxGrowthWithinWindow,
nextSizeGiB,
performanceTarget,
resolveCapGiB,
resolveEffectiveCapGiB,
sampleBucketAt,
shouldTrigger,
} from './runner-disk-expansion.service'
import { GcpDiskClientLike, GcpDiskSnapshot, GcpZoneOperation } from './gcp-disk-client'
import { runnerDiskConfig } from '../../config/configuration'
const HOUR = 3600_000
const ref: RunnerDataDiskRef = { provider: 'gcp', project: 'proj', zone: 'z1', diskName: 'disk-1' }
describe('water-level planning functions', () => {
describe('maxGrowthWithinWindow', () => {
// The signature anti-simplification case: the spike sat five hours ago, so
// it has already left any trailing 4h window, but it is inside the 48h
// retention — an implementation that only compares against the newest
// sample reports 0 and sizes the resize for nothing.
it('captures a spike that has rolled out of the trailing window but stays in retention', () => {
const now = new Date('2026-11-09T12:00:00Z')
const samples = [
{ bucketAt: new Date(now.getTime() - 6 * HOUR), usedGiB: 10 },
{ bucketAt: new Date(now.getTime() - 5 * HOUR), usedGiB: 100 },
{ bucketAt: new Date(now.getTime() - 1 * HOUR), usedGiB: 100 },
]
expect(maxGrowthWithinWindow(samples, 4 * HOUR, now)).toBe(90)
})
it('excludes pairs spanning more than the window', () => {
const now = new Date('2026-11-09T12:00:00Z')
const samples = [
{ bucketAt: new Date(now.getTime() - 10 * HOUR), usedGiB: 10 },
{ bucketAt: new Date(now.getTime() - 5 * HOUR), usedGiB: 500 },
]
expect(maxGrowthWithinWindow(samples, 4 * HOUR, now)).toBe(0)
})
it('counts a pair exactly as long as the window', () => {
const now = new Date('2026-11-09T12:00:00Z')
const samples = [
{ bucketAt: new Date(now.getTime() - 2 * HOUR), usedGiB: 10 },
{ bucketAt: new Date(now.getTime() - 2 * HOUR + 4 * HOUR), usedGiB: 30 },
]
expect(maxGrowthWithinWindow(samples, 4 * HOUR, now)).toBe(20)
})
it('degenerates to zero on insufficient history', () => {
const now = new Date('2026-11-09T12:00:00Z')
expect(maxGrowthWithinWindow([], 4 * HOUR, now)).toBe(0)
expect(maxGrowthWithinWindow([{ bucketAt: now, usedGiB: 5 }], 4 * HOUR, now)).toBe(0)
// Two samples, but the oldest one is younger than 30 minutes: the
// runner may just have booted, and one bucket says nothing about growth.
const young = [
{ bucketAt: new Date(now.getTime() - 20 * 60_000), usedGiB: 5 },
{ bucketAt: new Date(now.getTime() - 10 * 60_000), usedGiB: 30 },
]
expect(maxGrowthWithinWindow(young, 4 * HOUR, now)).toBe(0)
})
})
it('headroomGiB takes the larger of scaled growth and floor', () => {
expect(headroomGiB(30, 2.0, 20)).toBe(60)
expect(headroomGiB(5, 2.0, 20)).toBe(20)
})
it('resolveCapGiB prefers the expansion cap, then the admission limit, then reports none', () => {
expect(resolveCapGiB(4096, 2048)).toBe(4096)
expect(resolveCapGiB(undefined, 2048)).toBe(2048)
expect(resolveCapGiB(undefined, undefined)).toBeUndefined()
})
it('resolveEffectiveCapGiB prefers explicit caps, then defaults to twice the baseline size', () => {
// Explicit cap and admission limit keep their precedence over the default.
expect(resolveEffectiveCapGiB(4096, 2048, 200)).toBe(4096)
expect(resolveEffectiveCapGiB(undefined, 2048, 200)).toBe(2048)
// No explicit cap: twice the fixed baseline.
expect(resolveEffectiveCapGiB(undefined, undefined, 200)).toBe(400)
// Clamped to the Hyperdisk ceiling for large disks.
expect(resolveEffectiveCapGiB(undefined, undefined, 100_000)).toBe(HYPERDISK_BALANCED_MAX_GIB)
// A nonsensical disk size yields no cap — the uncapped gauge's only way in.
expect(resolveEffectiveCapGiB(undefined, undefined, 0)).toBeUndefined()
expect(resolveEffectiveCapGiB(undefined, undefined, -5)).toBeUndefined()
})
describe('shouldTrigger', () => {
const capacity = 200
it('triggers below the percentage line when it dominates', () => {
// 20% of 200 = 40; H = 20 is below it.
expect(shouldTrigger(39.9, capacity, 20, 20)).toBe(true)
expect(shouldTrigger(40, capacity, 20, 20)).toBe(false)
})
it('triggers below the headroom target when it dominates', () => {
// H = 80 beats the 40 percentage line.
expect(shouldTrigger(79, capacity, 80, 20)).toBe(true)
expect(shouldTrigger(80, capacity, 80, 20)).toBe(false)
})
})
it('nextSizeGiB grows by the larger step, clamps to the cap and rounds up', () => {
// step share = 25% of 200 = 50 > H = 20
expect(nextSizeGiB(200, 20, 25, 4096)).toBe(250)
// H = 60 beats the 50 step share
expect(nextSizeGiB(200, 60, 25, 4096)).toBe(260)
// cap clamps below the natural step
expect(nextSizeGiB(200, 20, 25, 240)).toBe(240)
// a fractional H above the step share rounds up to a whole GiB: 200 + 55.5 = 255.5
expect(nextSizeGiB(200, 55.5, 25, 4096)).toBe(256)
})
it('sampleBucketAt truncates down to the interval', () => {
expect(sampleBucketAt(new Date('2026-11-09T12:17:31Z'), 10)).toEqual(new Date('2026-11-09T12:10:00Z'))
expect(sampleBucketAt(new Date('2026-11-09T12:00:00Z'), 10)).toEqual(new Date('2026-11-09T12:00:00Z'))
})
})
/** Unit harness: every repository/client call is scripted, decisions asserted. */
function makeService(opts: {
expansion?: Record<string, unknown>
expandLimitGiB?: number
readyRunners?: Runner[]
pendingExpansions?: RunnerDiskExpansion[]
zoneOperation?: GcpZoneOperation
acceptedCount?: number
hasPending?: boolean
hasRecentRateLimit?: boolean
hasRecentPerformance?: boolean
/** The disks.get answer; the empty object is the size-only default. */
diskSnapshot?: GcpDiskSnapshot
/** When set, getDisk rejects with this error. */
getDiskError?: Error
/** When set, getDisk never settles: the deadline must win the race. */
diskReadNeverResolves?: boolean
/** When set, the performance-cooldown gate query rejects with this error. */
perfGateQueryError?: Error
/** When set, resizeDisk rejects with this error (mapped through toExpansionClientError). */
resizeError?: Error
samples?: RunnerDiskUsageSample[]
acquireLease?: boolean
/** The MIN(fromGiB) the cap-baseline query reports; null (default) means no attempts yet. */
minFromGiB?: number | null
}) {
const expansion = {
...runnerDiskConfig({ RUNNER_DISK_EXPANSION_ENABLED: 'true' }).expansion,
capGiB: 4096,
...opts.expansion,
}
const values: Record<string, unknown> = {
runnerDisk: { expandLimitGiB: opts.expandLimitGiB },
'runnerDisk.expansion': expansion,
'runnerDisk.expansion.enabled': expansion.enabled,
'runnerDisk.expansion.sampleIntervalMinutes': expansion.sampleIntervalMinutes,
'runnerDisk.expansion.sampleRetentionHours': expansion.sampleRetentionHours,
'runnerDisk.expansion.confirmTimeoutMinutes': expansion.confirmTimeoutMinutes,
}
const configService = { getOrThrow: (key: string) => values[key] } as unknown as TypedConfigService
const baselineQuery = {
select: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getRawOne: jest.fn(async () => ({ min: opts.minFromGiB === undefined ? null : opts.minFromGiB })),
}
const expansions = {
find: jest.fn(async () => opts.pendingExpansions ?? []),
count: jest.fn(async () => opts.acceptedCount ?? 0),
exist: jest.fn(async (criteria: { where: Partial<RunnerDiskExpansion> }) => {
const where = criteria.where as Record<string, unknown>
if (opts.perfGateQueryError && where.performanceUpdated === true) throw opts.perfGateQueryError
if (where.status === RunnerDiskExpansionStatus.PENDING) return opts.hasPending ?? false
if (where.performanceUpdated === true) return opts.hasRecentPerformance ?? false
return opts.hasRecentRateLimit ?? false
}),
insert: jest.fn(async () => ({ identifiers: [{ id: 'inserted-row' }], generatedMaps: [], raw: [] })),
update: jest.fn(async () => ({ affected: 1, raw: [], generatedMaps: [] })),
createQueryBuilder: jest.fn(() => baselineQuery),
}
const samplesRepository = {
find: jest.fn(async () => opts.samples ?? []),
delete: jest.fn(),
}
const runnerRepository = {
find: jest.fn(async () => opts.readyRunners ?? [gcpRunner()]),
findOne: jest.fn(async () => opts.readyRunners?.[0] ?? null),
count: jest.fn(async () => 0),
update: jest.fn(async () => ({ affected: 1, raw: [], generatedMaps: [] })),
}
const gcpDiskClient: GcpDiskClientLike = {
resizeDisk: opts.resizeError
? jest.fn(() => Promise.reject(opts.resizeError))
: jest.fn(async () => ({ operation: 'op-1' })),
getDisk: opts.diskReadNeverResolves
? jest.fn(() => new Promise<never>(() => {}))
: opts.getDiskError
? jest.fn(() => Promise.reject(opts.getDiskError))
: jest.fn(async () => opts.diskSnapshot ?? {}),
getZoneOperation: jest.fn(async () => opts.zoneOperation ?? { status: 'PENDING' as const }),
}
const lease = { signal: new AbortController().signal, release: jest.fn() }
const redisLockProvider = {
acquireLease: jest.fn(async () => (opts.acquireLease === false ? null : lease)),
} as unknown as RedisLockProvider
const dataSource = { query: jest.fn(), queryResultCache: undefined } as unknown as DataSource
const eventEmitter = { emit: jest.fn() } as unknown as EventEmitter2
const service = new RunnerDiskExpansionService(
expansions as never,
samplesRepository as never,
runnerRepository as never,
gcpDiskClient,
redisLockProvider,
configService,
dataSource,
eventEmitter,
)
return { service, expansions, samplesRepository, runnerRepository, gcpDiskClient, redisLockProvider, eventEmitter }
}
function gcpRunner(overrides: Partial<Runner> = {}): Runner {
const runner = new Runner({
region: 'us',
name: 'runner-1',
apiKey: 'key',
apiVersion: '2',
cpu: 8,
memoryGiB: 32,
diskGiB: 200,
})
runner.id = '11111111-1111-4111-8111-111111111111'
runner.state = RunnerState.READY
runner.availabilityScore = 100
// 10 GiB free on a 200 GiB disk: below the 20% line (40) and H (20) both.
runner.currentAllocatedDiskGiB = 190
runner.currentDiskUsagePercentage = 95
runner.dataDiskRef = { ...ref }
Object.assign(runner, overrides)
return runner
}
describe('performanceTarget', () => {
it('scales both fields at the measured slope, nothing clipped', () => {
expect(performanceTarget('3600', '240', '200', 300)).toEqual({
iops: '5400',
throughput: '360',
ceilingHit: false,
ceilingFields: [],
})
})
it('accepts numeric baseline values from the gRPC-typed snapshot identically', () => {
expect(performanceTarget(3600, 240, 200, 300)).toEqual({
iops: '5400',
throughput: '360',
ceilingHit: false,
ceilingFields: [],
})
})
it('rounds each field independently', () => {
expect(performanceTarget('3601', '241', '200', 300)).toMatchObject({ iops: '5402', throughput: '362' })
})
it('drops same-value fields in a degenerate ratio<1 round', () => {
expect(performanceTarget('3600', '240', 300, 250)).toEqual({
ceilingHit: false,
ceilingFields: [],
})
})
it('clips IOPS to the flat ceiling when the slope target outgrows it', () => {
expect(performanceTarget('99000', '200', '200', 400)).toEqual({
iops: '160000',
throughput: '400',
ceilingHit: true,
ceilingFields: ['iops'],
})
})
it('drops same-value fields already parked on the ceiling', () => {
expect(performanceTarget('160000', '2400', '320', 400)).toEqual({
ceilingHit: true,
ceilingFields: ['iops', 'throughput'],
})
})
it('clips throughput at the P/4 coupling ceiling to an integer', () => {
// iopsTarget=3750 puts the coupling ceiling at 937.5; a fractional wire
// value would be rejected by the int64 field and drag the bundled
// capacity change down with it, so the bound is floored to 937.
expect(performanceTarget('3000', '750', '200', 250)).toEqual({
iops: '3750',
throughput: '937',
ceilingHit: true,
ceilingFields: ['throughput'],
})
})
it('clips IOPS at the per-GiB ceiling when the flat ceiling is not binding', () => {
// slope 600/GiB × 220 = 132000 vs per-GiB bound 500×220 = 110000 < 160000:
// the per-GiB bound is the one that clips.
expect(performanceTarget('120000', '100', '200', 220)).toEqual({
iops: '110000',
throughput: '110',
ceilingHit: true,
ceilingFields: ['iops'],
})
})
it('pulls a boosted baseline down to the new ceiling and still sends the repair value', () => {
// curIops 160000 > iopsMax(100 GiB) = 50000: max-before-min keeps the
// field sent at the lowered legal value — the anti-deadlock repair path.
expect(performanceTarget('160000', '2400', '320', 100)).toEqual({
iops: '50000',
ceilingHit: true,
ceilingFields: ['iops'],
})
})
it('returns undefined on any missing or non-positive baseline input', () => {
expect(performanceTarget(undefined, '240', '200', 300)).toBeUndefined()
expect(performanceTarget('3600', undefined, '200', 300)).toBeUndefined()
expect(performanceTarget('3600', '240', undefined, 300)).toBeUndefined()
expect(performanceTarget('3600', '240', '0', 300)).toBeUndefined()
expect(performanceTarget('-5', '240', '200', 300)).toBeUndefined()
})
})
describe('RunnerDiskExpansionService round', () => {
it('stays dormant while disabled', async () => {
const { service, expansions, redisLockProvider } = makeService({ expansion: { enabled: false } })
await service.evaluateAndConfirm()
expect(expansions.find).not.toHaveBeenCalled()
expect(redisLockProvider.acquireLease).not.toHaveBeenCalled()
})
it('does nothing without the lease', async () => {
const { service, expansions } = makeService({ acquireLease: false })
await service.evaluateAndConfirm()
expect(expansions.find).not.toHaveBeenCalled()
})
it('grows a runner below the water level and records the pending attempt', async () => {
const { service, expansions, gcpDiskClient } = makeService({})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
// The intent row lands before the cloud call and carries no operation yet;
// the accepted update follows a successful resize.
expect(expansions.insert).toHaveBeenCalledWith(
expect.objectContaining({
runnerId: '11111111-1111-4111-8111-111111111111',
fromGiB: 200,
toGiB: 250,
accepted: false,
operation: null,
status: RunnerDiskExpansionStatus.PENDING,
}),
)
expect(expansions.update).toHaveBeenCalledWith('inserted-row', { accepted: true, operation: 'op-1' })
})
it('leaves a runner alone above the water level', async () => {
const runner = gcpRunner({ currentAllocatedDiskGiB: 100 }) // 100 free > 40
const { service, gcpDiskClient } = makeService({ readyRunners: [runner] })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
it('skips runners without a usable disk identity', async () => {
const runner = gcpRunner({ dataDiskRef: null })
const { service, gcpDiskClient } = makeService({ readyRunners: [runner] })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
it('holds back while an attempt is pending', async () => {
const { service, gcpDiskClient } = makeService({ hasPending: true })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
it('holds back during the throttle cooldown', async () => {
const { service, gcpDiskClient } = makeService({ hasRecentRateLimit: true })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
describe('budget', () => {
it('marks unschedulable once the window budget is spent', async () => {
const runner = gcpRunner()
const { service, runnerRepository, gcpDiskClient } = makeService({ readyRunners: [runner], acceptedCount: 2 })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
expect(runnerRepository.update).toHaveBeenCalledWith(
{ id: runner.id, unschedulable: false, state: expect.anything() },
{ unschedulable: true, unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED },
)
})
it('lifts the mark once usage drops, budget frees up and the cap has room', async () => {
const runner = gcpRunner({
unschedulable: true,
unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED,
currentDiskUsagePercentage: 50,
currentAllocatedDiskGiB: 100, // recovered: 100 free, no new growth needed
})
const { service, runnerRepository, gcpDiskClient } = makeService({
readyRunners: [runner],
acceptedCount: 0,
})
await service.evaluateAndConfirm()
// Lift keys on the reason being ours, so an operator's boolean-only
// mark (reason NULL) is never touched by this controller.
expect(runnerRepository.update).toHaveBeenCalledWith(
{ id: runner.id, unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED },
{ unschedulable: false, unschedulableReason: null },
)
// The lifted runner is back in the pool and, having plenty of free
// space, is not resized this round.
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
it('does not lift while usage stays above the lift line', async () => {
const runner = gcpRunner({
unschedulable: true,
unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED,
currentDiskUsagePercentage: 80,
})
const { service, runnerRepository } = makeService({ readyRunners: [runner], acceptedCount: 0 })
await service.evaluateAndConfirm()
expect(runnerRepository.update).not.toHaveBeenCalledWith(
expect.objectContaining({ unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED }),
expect.objectContaining({ unschedulable: false }),
)
})
})
describe('cap', () => {
it('falls back to twice the disk size when no cap is configured', async () => {
const { service, gcpDiskClient, expansions } = makeService({ expansion: { capGiB: undefined } })
await service.evaluateAndConfirm()
// Default ceiling = 2 × baseline 200 = 400 (no attempts yet, so the
// baseline is the current size); the natural step (250) fits under it.
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
expect(expansions.update).toHaveBeenCalledWith('inserted-row', { accepted: true, operation: 'op-1' })
expect((service as unknown as { gaugeValues: { uncapped: number } }).gaugeValues.uncapped).toBe(0)
})
it('anchors the default cap to the first attempt, not the grown size', async () => {
// The first attempt grew the disk toward 200 GiB and the filesystem now
// reports 380. A cap recomputed from the live size would be 760 and let
// growth double forever in generations; anchored to the first attempt
// it stays 400, and the next request clamps to exactly that ceiling.
const runner = gcpRunner({ diskGiB: 380, currentAllocatedDiskGiB: 370 })
const { service, gcpDiskClient } = makeService({
readyRunners: [runner],
expansion: { capGiB: undefined },
minFromGiB: 200,
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 400)
})
it('skips and gauges only for a nonsensical disk size', async () => {
const runner = gcpRunner({ diskGiB: 0 })
const { service, gcpDiskClient } = makeService({ readyRunners: [runner], expansion: { capGiB: undefined } })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
expect((service as unknown as { gaugeValues: { uncapped: number } }).gaugeValues.uncapped).toBe(1)
})
it('marks unschedulable at the cap and never resizes past it', async () => {
const runner = gcpRunner()
const { service, runnerRepository, gcpDiskClient } = makeService({
readyRunners: [runner],
expansion: { capGiB: 200 },
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
expect(runnerRepository.update).toHaveBeenCalledWith(
{ id: runner.id, unschedulable: false, state: expect.anything() },
{ unschedulable: true, unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED },
)
})
it('marks exhausted when the filesystem sits within the ext4-overhead zone of the cap', async () => {
// Device 200 parked on cap 200 reports ~195.8 (0.979): a raw
// comparison would leave the gate open and re-request the device's
// current size — a GCP 400 — every round instead of marking exhausted.
const runner = gcpRunner({ diskGiB: 200 * 0.979 })
const { service, runnerRepository, gcpDiskClient } = makeService({
readyRunners: [runner],
expansion: { capGiB: 200 },
})
await service.evaluateAndConfirm()
expect(runnerRepository.update).toHaveBeenCalledWith(
{ id: runner.id, unschedulable: false, state: expect.anything() },
{ unschedulable: true, unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED },
)
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
})
it('holds the exhausted mark while the filesystem sits within the overhead zone of the cap', async () => {
// The lift gate shares the tolerance: a device parked on the cap must
// not be lifted back into the pool just because its filesystem reads
// ~2% low, only for the next round to re-mark it.
const runner = gcpRunner({
unschedulable: true,
unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED,
diskGiB: 200 * 0.979,
currentDiskUsagePercentage: 50,
currentAllocatedDiskGiB: 100,
})
const { service, runnerRepository } = makeService({
readyRunners: [runner],
expansion: { capGiB: 200 },
})
await service.evaluateAndConfirm()
expect(runnerRepository.update).not.toHaveBeenCalledWith(
{ id: runner.id, unschedulableReason: RunnerUnschedulableReason.DISK_EXPAND_EXHAUSTED },
{ unschedulable: false, unschedulableReason: null },
)
})
it('falls back to the admission expandLimit as the cap', async () => {
const runner = gcpRunner()
// resolveCapGiB(undefined, 240) = 240: capacity 200 under it, so the
// natural 250 clamps to 240 — the two cap keys resolve as one chain.
const { service, gcpDiskClient } = makeService({
readyRunners: [runner],
expansion: { capGiB: undefined },
expandLimitGiB: 240,
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 240)
})
})
it('stops issuing PATCHes after the per-round limit', async () => {
const runners = Array.from({ length: MAX_PATCHES_PER_ROUND + 5 }, (_, i) =>
gcpRunner({ id: `runner-${i}`, dataDiskRef: { ...ref, diskName: `disk-${i}` } }),
)
const { service, gcpDiskClient } = makeService({ readyRunners: runners })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledTimes(MAX_PATCHES_PER_ROUND)
})
it('sizes by observed growth, not just the floor', async () => {
const now = new Date()
const samples = [
{ runnerId: 'r', bucketAt: new Date(now.getTime() - 6 * HOUR), usedGiB: 60 },
{ bucketAt: new Date(now.getTime() - 5 * HOUR), usedGiB: 160 },
] as RunnerDiskUsageSample[]
// Growth 100 in-window → H = 200 > step share 50 → 200 + 200 = 400.
const { service, gcpDiskClient } = makeService({ samples })
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 400)
})
describe('resize failures', () => {
it('records a rate-limited rejection on the intent row and does not spend the budget', async () => {
const { service, expansions, gcpDiskClient } = makeService({})
// Rejected lazily: an eagerly-created rejected promise can surface as an
// unhandled rejection before the service awaits it. The rejection shape
// is the one google-gax's REST fallback actually produces: GoogleError
// with a gRPC status (RESOURCE_EXHAUSTED), not a raw HTTP code.
;(gcpDiskClient.resizeDisk as jest.Mock).mockImplementationOnce(() =>
Promise.reject(
GoogleError.parseHttpError({
error: {
code: 429,
errors: [
{ domain: 'global', message: 'Quota exceeded for requests per minute', reason: 'rateLimitExceeded' },
],
message: 'Quota exceeded for requests per minute',
status: 'RESOURCE_EXHAUSTED',
},
}),
),
)
await service.evaluateAndConfirm()
// The intent row was written first, then closed on this runner as a
// cloud-side rejection; `accepted` stays false, so the budget is intact.
expect(expansions.insert).toHaveBeenCalledWith(
expect.objectContaining({ accepted: false, status: RunnerDiskExpansionStatus.PENDING, operation: null }),
)
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.RATE_LIMITED }),
)
})
it('records any other rejection as not accepted', async () => {
const { service, expansions, gcpDiskClient } = makeService({})
;(gcpDiskClient.resizeDisk as jest.Mock).mockImplementationOnce(() =>
Promise.reject(GoogleError.parseHttpError({ error: { code: 404, message: 'disk not found' } })),
)
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.NOT_ACCEPTED }),
)
})
it('records a genuine request-validation 400 as not accepted, not rate limited', async () => {
// HTTP 400 surfaces as gRPC INVALID_ARGUMENT (3): a real validation
// rejection (for example "new size must be larger") that must open no
// cooldown. Only the throttle signal (RESOURCE_EXHAUSTED) does.
const { service, expansions, gcpDiskClient } = makeService({})
;(gcpDiskClient.resizeDisk as jest.Mock).mockImplementationOnce(() =>
Promise.reject(GoogleError.parseHttpError({ error: { code: 400, message: 'New size must be larger' } })),
)
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.NOT_ACCEPTED }),
)
})
it('does not classify a persistence failure as a GCP rejection', async () => {
// The intent-row insert failing means no request was ever issued: the
// cloud client must not have been called, and nothing may be recorded
// as not_accepted or rate_limited.
const { service, expansions, gcpDiskClient } = makeService({})
;(expansions.insert as jest.Mock).mockRejectedValueOnce(new Error('db down'))
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).not.toHaveBeenCalled()
expect(expansions.insert).toHaveBeenCalledTimes(1)
expect(expansions.update).not.toHaveBeenCalled()
})
it('survives a lost accepted-update after a successful resize', async () => {
// GCP accepted and grew the disk, but writing accepted=true back failed.
// The round must not crash and must not label the accepted resize a
// rejection; the intent row stays pending without an operation and the
// confirm timeout closes it as unconfirmed on a later round.
const { service, expansions, gcpDiskClient } = makeService({})
;(expansions.update as jest.Mock).mockRejectedValueOnce(new Error('db down'))
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledTimes(1)
expect(expansions.insert).toHaveBeenCalledTimes(1)
expect(expansions.update).toHaveBeenCalledTimes(1)
})
})
describe('confirmation', () => {
const pendingRow = () =>
({
id: 'row-1',
runnerId: '11111111-1111-4111-8111-111111111111',
fromGiB: 200,
toGiB: 250,
accepted: true,
operation: 'op-1',
status: RunnerDiskExpansionStatus.PENDING,
error: null,
requestedAt: new Date(Date.now() - 2 * 60_000),
confirmedAt: null,
}) as RunnerDiskExpansion
it('confirms once the runner reports the new filesystem size', async () => {
// 0.979 sits between the 0.975 tolerance and 1.0 — the measured ext4
// overhead zone. A confirmation that only passed on exact equality
// would flag every real resize as unconfirmed.
const runner = gcpRunner({ diskGiB: 250 * 0.979 })
const { service, expansions } = makeService({
readyRunners: [runner],
pendingExpansions: [pendingRow()],
zoneOperation: { status: 'DONE' },
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.CONFIRMED, confirmedAt: expect.any(Date) }),
)
})
it('fails immediately when the zone operation failed', async () => {
const { service, expansions } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [pendingRow()],
zoneOperation: { status: 'DONE', error: 'ZONE_CAPACITY: no room' },
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: 'ZONE_CAPACITY: no room' }),
)
})
it('fails as unconfirmed past the confirm timeout even when the operation is done', async () => {
const row = pendingRow()
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const runner = gcpRunner({ diskGiB: 200 }) // never grew
const { service, expansions } = makeService({
readyRunners: [runner],
pendingExpansions: [row],
zoneOperation: { status: 'DONE' },
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.UNCONFIRMED }),
)
})
it('logs terminal failures at error severity and confirmations at info', async () => {
// The failing alarm's log filter is severity>=ERROR, and this close-out
// is that alarm's only notice for the two failure modes it must report
// (operation FAILED, never confirmed). Logging them at info would leave
// the alarm silent exactly when it matters. confirmed stays informational.
const errorSpy = jest.spyOn(Logger.prototype, 'error')
const logSpy = jest.spyOn(Logger.prototype, 'log')
// unconfirmed: op DONE but the filesystem never grew, past the timeout.
const row = pendingRow()
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const failed = makeService({
readyRunners: [gcpRunner({ diskGiB: 200 })],
pendingExpansions: [row],
zoneOperation: { status: 'DONE' },
})
await failed.service.evaluateAndConfirm()
// confirmed: op DONE and the runner reports the grown size.
const confirmed = makeService({
readyRunners: [gcpRunner({ diskGiB: 250 * 0.979 })],
pendingExpansions: [pendingRow()],
zoneOperation: { status: 'DONE' },
})
await confirmed.service.evaluateAndConfirm()
expect(errorSpy).toHaveBeenCalledWith(
expect.stringContaining('failed'),
expect.objectContaining({ 'event.name': 'runner.disk_expansion' }),
)
expect(logSpy).toHaveBeenCalledWith(
expect.stringContaining('confirmed'),
expect.objectContaining({ 'event.name': 'runner.disk_expansion' }),
)
errorSpy.mockRestore()
logSpy.mockRestore()
})
it('leaves in-flight operations pending', async () => {
const { service, expansions } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [pendingRow()],
zoneOperation: { status: 'RUNNING' },
})
await service.evaluateAndConfirm()
// The evaluation half of this round issues an accepted-update for the
// resize it makes; scope the assertion to the pending row's close.
expect(expansions.update).not.toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.anything(),
)
})
it('closes an attempt stuck RUNNING past the confirm timeout', async () => {
// A zone operation may stay RUNNING well past its expected lifetime;
// the deadline is the only thing keeping the runner's next request
// unblocked.
const row = pendingRow()
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const { service, expansions } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [row],
zoneOperation: { status: 'RUNNING' },
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.UNCONFIRMED }),
)
})
it('closes an attempt past the confirm timeout even when every poll fails', async () => {
// Persistent poll failures must not park the row: the deadline closes it
// the same as any other unresolved state.
const row = pendingRow()
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const { service, expansions, gcpDiskClient } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [row],
})
;(gcpDiskClient.getZoneOperation as jest.Mock).mockRejectedValue(new Error('network down'))
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.UNCONFIRMED }),
)
})
it('does not poll an intent row that never received its operation', async () => {
// initiate() writes the intent row before the cloud call; a row without
// an operation has nothing to poll. The confirm timeout is its only way
// out.
const row = pendingRow()
row.operation = null
const { service, expansions, gcpDiskClient } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [row],
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.getZoneOperation).not.toHaveBeenCalled()
expect(expansions.update).not.toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.anything(),
)
})
it('closes an intent row past the confirm timeout without polling', async () => {
const row = pendingRow()
row.operation = null
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const { service, expansions, gcpDiskClient } = makeService({
readyRunners: [gcpRunner()],
pendingExpansions: [row],
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.getZoneOperation).not.toHaveBeenCalled()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.UNCONFIRMED }),
)
})
it('still waits out the timeout when the runner identity disappeared', async () => {
const runner = gcpRunner({ dataDiskRef: null })
const row = pendingRow()
row.requestedAt = new Date(Date.now() - 11 * 60_000)
const { service, expansions } = makeService({
readyRunners: [runner],
pendingExpansions: [row],
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
{ id: 'row-1', status: RunnerDiskExpansionStatus.PENDING },
expect.objectContaining({ status: RunnerDiskExpansionStatus.FAILED, error: EXPANSION_ERROR.UNCONFIRMED }),
)
})
})
it('confirm tolerance covers the measured ext4 overhead', () => {
// 200 GiB disk: statfs total is ~195.8 GiB (4.18 GiB overhead, measured).
// 195.8 / 200 = 0.979 > 0.975, so a correct resize confirms.
expect(195.8 / 200).toBeGreaterThan(CONFIRM_TOLERANCE_RATIO)
})
it('carries performance fields when the baseline is present and the cooldown is clear', async () => {
const { service, gcpDiskClient, expansions } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250, { iops: '4500', throughput: '300' })
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({ accepted: true, operation: 'op-1', performanceUpdated: true }),
)
})
it('logs the full identity, operation, and perf before/after on a bundled request', async () => {
const logSpy = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => {})
const { service } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
})
try {
await service.evaluateAndConfirm()
const logged = logSpy.mock.calls.find((call) => String(call[0]).includes('expansion requested'))?.[1]
expect(logged).toBeDefined()
expect(logged).toEqual(
expect.objectContaining({
'runner.id': '11111111-1111-4111-8111-111111111111',
'runner.name': 'runner-1',
'disk.name': 'disk-1',
'disk.zone': 'z1',
'disk.project': 'proj',
'disk.operation': 'op-1',
'disk.from_gib': 200,
'disk.to_gib': 250,
'disk.perf_from_iops': '3600',
'disk.perf_from_throughput': '240',
'disk.perf_from_size_gib': '200',
'disk.perf_to_iops': '4500',
'disk.perf_to_throughput': '300',
}),
)
} finally {
logSpy.mockRestore()
}
})
it('sends size only while the performance cooldown is active', async () => {
const { service, gcpDiskClient, expansions } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
hasRecentPerformance: true,
})
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
expect(expansions.update).toHaveBeenCalledWith('inserted-row', { accepted: true, operation: 'op-1' })
// the cooldown gate runs before the read: only gate-passing runners pay it
expect(gcpDiskClient.getDisk).not.toHaveBeenCalled()
})
it('still grows the disk when the baseline read fails', async () => {
const warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {})
const { service, gcpDiskClient } = makeService({ getDiskError: new Error('read boom') })
await service.evaluateAndConfirm()
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('disk read failed, expanding size only'),
expect.objectContaining({ 'disk.expansion_result': 'perf_read_failed' }),
)
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
warnSpy.mockRestore()
})
it('still grows the disk when the baseline read hangs past the deadline', async () => {
// The SDK's default Get config is a 600s timeout with retries; the
// deadline races it so one black-holed read cannot stall the sequential
// round or outlive the 60s cron lease. Expiry takes the same size-only
// fallback as a failed read; the next cron round retries naturally.
jest.useFakeTimers()
try {
const { service, gcpDiskClient } = makeService({ diskReadNeverResolves: true })
const round = service.evaluateAndConfirm()
await jest.advanceTimersByTimeAsync(BASELINE_READ_DEADLINE_MS + 100)
await round
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledTimes(1)
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
} finally {
jest.useRealTimers()
}
})
it('marks performanceUpdated on a rejected performance-carrying attempt', async () => {
const { service, expansions } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
resizeError: GoogleError.parseHttpError({ error: { code: 400, message: 'bad' } }),
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({
status: RunnerDiskExpansionStatus.FAILED,
error: EXPANSION_ERROR.NOT_ACCEPTED,
performanceUpdated: true,
}),
)
})
it('credits a performance-carrying throttle to the performance budget, not the capacity cooldown', async () => {
// A bundled PATCH that draws a GCP 429 cannot tell which budget tripped.
// performanceUpdated already opens the 4h performance cooldown; recording
// rate_limited would also freeze capacity for the whole rate-limit
// cooldown, which the design promises capacity is never subject to. The
// rejection is credited to performance and capacity goes size-only on the
// next round immediately; an actually capacity-caused throttle
// self-identifies when that size-only attempt records its own rate_limited.
const { service, expansions } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
resizeError: GoogleError.parseHttpError({
error: { code: 429, message: 'rate', status: 'RESOURCE_EXHAUSTED' },
}),
})
await service.evaluateAndConfirm()
expect(expansions.update).toHaveBeenCalledWith(
'inserted-row',
expect.objectContaining({
status: RunnerDiskExpansionStatus.FAILED,
error: EXPANSION_ERROR.NOT_ACCEPTED,
performanceUpdated: true,
}),
)
})
it('keeps capacity moving after a performance throttle and lets a capacity throttle self-identify', async () => {
// Round 1: a bundled PATCH drawing a 429 is credited to the performance
// budget (not_accepted + performanceUpdated). Round 2: the performance
// cooldown holds, capacity retries size-only immediately — the 30-minute
// rate-limit gate must not block it. If the throttle was capacity-caused,
// the size-only retry draws its own 429 and records rate_limited then.
const options = {
diskSnapshot: { sizeGb: '200', provisionedIops: '3600', provisionedThroughput: '240' },
resizeError: GoogleError.parseHttpError({ error: { code: 429, message: 'rate', status: 'RESOURCE_EXHAUSTED' } }),
hasRecentPerformance: false,
}
const { service, gcpDiskClient, expansions } = makeService(options)
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenNthCalledWith(1, ref, 250, { iops: '4500', throughput: '300' })
expect(expansions.update).toHaveBeenNthCalledWith(
1,
'inserted-row',
expect.objectContaining({ error: EXPANSION_ERROR.NOT_ACCEPTED, performanceUpdated: true }),
)
// the ledger row written by round 1 is what the cooldown gate reads
options.hasRecentPerformance = true
await service.evaluateAndConfirm()
expect(gcpDiskClient.resizeDisk).toHaveBeenNthCalledWith(2, ref, 250)
// size-only round: no performance fields carried, so the ledger row does
// not carry the performance marker — only the self-identified throttle
expect(expansions.update).toHaveBeenNthCalledWith(
2,
'inserted-row',
expect.objectContaining({ error: EXPANSION_ERROR.RATE_LIMITED }),
)
})
it('warns when the disk snapshot lacks provisioned values and still grows size-only', async () => {
const warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {})
const { service, gcpDiskClient } = makeService({ diskSnapshot: { sizeGb: '200' } })
await service.evaluateAndConfirm()
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('lacks provisioned performance values'),
expect.objectContaining({ 'disk.expansion_result': 'perf_baseline_missing' }),
)
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
warnSpy.mockRestore()
})
it('counts and warns on ceiling-clipped targets, sending the integer-clipped bundle', async () => {
const counterAdd = jest.fn()
const meterSpy = jest.spyOn(metrics, 'getMeter').mockReturnValue({
createCounter: () => ({ add: counterAdd }),
createObservableGauge: () => ({ addCallback: () => {} }),
} as unknown as Meter)
const warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {})
const { service, gcpDiskClient, expansions } = makeService({
diskSnapshot: { sizeGb: '200', provisionedIops: '160000', provisionedThroughput: '2400' },
})
await service.evaluateAndConfirm()
expect(counterAdd).toHaveBeenCalledWith(1, { field: 'iops' })
expect(counterAdd).toHaveBeenCalledWith(1, { field: 'throughput' })
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('clipped to the per-disk ceiling'),
expect.objectContaining({ 'disk.expansion_result': 'perf_ceiling' }),
)
// 160000→125000 differs and is sent; 2400→2400 is a same-value drop
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250, { iops: '125000' })
expect(expansions.update).toHaveBeenCalledWith('inserted-row', {
accepted: true,
operation: 'op-1',
performanceUpdated: true,
})
meterSpy.mockRestore()
warnSpy.mockRestore()
})
it('still grows the disk size-only when the performance cooldown gate query fails', async () => {
const warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {})
const { service, gcpDiskClient } = makeService({
perfGateQueryError: new Error('db blip'),
diskSnapshot: { sizeGb: '100', provisionedIops: '50000', provisionedThroughput: '250' },
})
await service.evaluateAndConfirm()
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('cooldown gate query failed'),
expect.objectContaining({ 'disk.expansion_result': 'perf_gate_query_failed' }),
)
expect(gcpDiskClient.resizeDisk).toHaveBeenCalledWith(ref, 250)
expect(gcpDiskClient.getDisk).not.toHaveBeenCalled()
warnSpy.mockRestore()
})
})