From dc2f58f0b975c364769decceb2d9cc890b8cf3d5 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Sat, 24 Oct 2026 16:33:35 -0400 Subject: [PATCH 1/5] fix(storage): cap concurrent Merges per process Every first restore of an unmerged entry and, with EAGER_MERGE, every finalize started a Merge with no global limit. Each Merge holds storage connections, a Merge Lease and stream buffers for its whole duration, and a lazy Merge is paced by the restoring client's read speed. A burst of first restores or of finalizes therefore grew Merges, sockets and memory without bound. Start a Merge only while fewer than MAX_CONCURRENT_MERGES (default 16) run in this process. Beyond that, startMerge returns false: a restore streams the parts directly, exactly as when another worker holds the Merge Lease, an Eager Merge is left to the first download, and a later download merges the entry. The slot is reserved before the first await, so concurrent callers cannot overshoot it. tests/merge-concurrency.test.ts covers a first restore and an Eager Merge beyond the limit. Signed-off-by: Rui Chen --- README.md | 1 + lib/schemas.ts | 1 + lib/storage.ts | 40 ++++++++---- tests/merge-concurrency.test.ts | 111 ++++++++++++++++++++++++++++++++ tests/setup.ts | 1 + 5 files changed, 143 insertions(+), 11 deletions(-) create mode 100644 tests/merge-concurrency.test.ts diff --git a/README.md b/README.md index 856f1e5..85ebc36 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ All optional. | `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. | | `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | | `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. | +| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | ## Documentation diff --git a/lib/schemas.ts b/lib/schemas.ts index e64c979..c0e2f0d 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -87,6 +87,7 @@ export const envBaseSchema = type({ 'DEBUG?': 'unknown', 'ENABLE_DIRECT_DOWNLOADS': 'boolean = false', 'EAGER_MERGE': 'boolean = false', + 'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16', 'BENCHMARK': 'boolean = false', 'SKIP_TOKEN_VALIDATION': 'boolean = false', 'MANAGEMENT_API_KEY?': 'string', diff --git a/lib/storage.ts b/lib/storage.ts index 8d54138..a2520fd 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -141,6 +141,7 @@ export class Storage { private db private mergeStreamPromises = new Set>() + private activeMerges = 0 adapter private constructor({ db, adapter }: { adapter: StorageAdapter; db: Kysely }) { @@ -297,19 +298,35 @@ export class Storage { /** * Runs a Merge under a Merge Lease. `write` produces `${folderName}/merged`; * a lease-fenced transaction then marks the Merge complete. Returns false - * when another worker holds the lease. Writing straight to the final object - * is safe (ADR-0004). The returned promise never rejects: failures are logged - * and the merge state rolled back. + * when another worker holds the lease or this process already runs + * MAX_CONCURRENT_MERGES Merges; a skipped Merge is retried by a later + * download. Writing straight to the final object is safe (ADR-0004). The + * returned promise never rejects: failures are logged and the merge state + * rolled back. */ private async startMerge(location: StorageLocation, write: () => Promise) { - const mergeToken = await acquireMergeLease(this.db, location.id) - if (!mergeToken) return false - - await this.db - .updateTable('storage_locations') - .set({ mergeStartedAt: Date.now() }) - .where('id', '=', location.id) - .execute() + // Each Merge holds storage connections and buffers for its whole duration; + // unbounded, a burst of first restores or finalizes exhausts them. + if (this.activeMerges >= env.MAX_CONCURRENT_MERGES) return false + // Reserve the slot before the first await so concurrent callers cannot overshoot it. + this.activeMerges++ + let mergeToken: string | undefined + try { + mergeToken = await acquireMergeLease(this.db, location.id) + if (mergeToken) + await this.db + .updateTable('storage_locations') + .set({ mergeStartedAt: Date.now() }) + .where('id', '=', location.id) + .execute() + } catch (err) { + this.activeMerges-- + throw err + } + if (!mergeToken) { + this.activeMerges-- + return false + } const renewalTimer = setInterval(() => { void renewMergeLease(this.db, location.id, mergeToken) @@ -357,6 +374,7 @@ export class Storage { }) .finally(async () => { clearInterval(renewalTimer) + this.activeMerges-- await releaseMergeLease(this.db, location.id, mergeToken) }) this.mergeStreamPromises.add(mergePromise) diff --git a/tests/merge-concurrency.test.ts b/tests/merge-concurrency.test.ts new file mode 100644 index 0000000..85e3e71 --- /dev/null +++ b/tests/merge-concurrency.test.ts @@ -0,0 +1,111 @@ +import { createHash, randomUUID } from 'node:crypto' +import { Readable } from 'node:stream' + +import { afterEach, describe, expect, test } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' +import { Storage } from '~/lib/storage' + +const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' } +const parts = [Buffer.alloc(256 * 1024, 'a'), Buffer.alloc(256 * 1024, 'b')] +const expected = createHash('sha256').update(Buffer.concat(parts)).digest('hex') + +async function uploadEntry(storage: Storage) { + const key = `merge-cap-${randomUUID()}` + const upload = await storage.createUpload({ key, ...scope }) + for (const [index, part] of parts.entries()) + await storage.uploadPart(upload.id, index, Readable.from(part)) + await storage.completeUpload({ key, ...scope }) + const db = await getDatabase() + return db + .selectFrom('cache_entries') + .innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId') + .where('cache_entries.key', '=', key) + .select(['storage_locations.id as locationId', 'folderName']) + .executeTakeFirstOrThrow() +} + +async function download(storage: Storage, locationId: string) { + const result = await storage.download(locationId) + if (!result) throw new Error(`location ${locationId} not found`) + return result.stream +} + +async function sha256(stream: Readable) { + const hash = createHash('sha256') + for await (const chunk of stream) hash.update(chunk) + return hash.digest('hex') +} + +async function mergeState(locationId: string) { + const db = await getDatabase() + return db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select(['mergedAt', 'mergeStartedAt']) + .executeTakeFirstOrThrow() +} + +describe('merge concurrency limit', () => { + const originalMaxMerges = env.MAX_CONCURRENT_MERGES + const originalEagerMerge = env.EAGER_MERGE + afterEach(() => { + env.MAX_CONCURRENT_MERGES = originalMaxMerges + env.EAGER_MERGE = originalEagerMerge + }) + + test('a first restore beyond the limit is served from parts without merging', async () => { + env.EAGER_MERGE = false + env.MAX_CONCURRENT_MERGES = 1 + const storage = await Storage.fromEnv() + const first = await uploadEntry(storage) + const second = await uploadEntry(storage) + + try { + // The first restore's Merge is paced by its unread stream, so it still + // holds the only slot when the second restore starts. + const firstStream = await download(storage, first.locationId) + const secondStream = await download(storage, second.locationId) + expect(await sha256(secondStream)).toBe(expected) + expect(await sha256(firstStream)).toBe(expected) + await storage.waitForOngoingMerges() + + expect(await mergeState(first.locationId)).not.toMatchObject({ mergedAt: null }) + expect(await mergeState(second.locationId)).toMatchObject({ mergedAt: null }) + + // With the slot free again, the next restore merges the skipped entry. + expect(await sha256(await download(storage, second.locationId))).toBe(expected) + await storage.waitForOngoingMerges() + expect(await mergeState(second.locationId)).not.toMatchObject({ mergedAt: null }) + } finally { + await storage.adapter.deleteFolder(first.folderName) + await storage.adapter.deleteFolder(second.folderName) + } + }) + + test('an eager merge beyond the limit leaves the entry to a later download', async () => { + env.EAGER_MERGE = false + env.MAX_CONCURRENT_MERGES = 1 + const storage = await Storage.fromEnv() + const busy = await uploadEntry(storage) + // An unread first restore keeps its Merge, and the only slot, busy. + const busyStream = await download(storage, busy.locationId) + + env.EAGER_MERGE = true + const eager = await uploadEntry(storage) + try { + // Upload completion awaits the Merge Lease, so a started Merge would have + // stamped mergeStartedAt by now. + expect(await mergeState(eager.locationId)).toEqual({ mergedAt: null, mergeStartedAt: null }) + + expect(await sha256(busyStream)).toBe(expected) + await storage.waitForOngoingMerges() + expect(await sha256(await download(storage, eager.locationId))).toBe(expected) + await storage.waitForOngoingMerges() + expect(await mergeState(eager.locationId)).not.toMatchObject({ mergedAt: null }) + } finally { + await storage.adapter.deleteFolder(busy.folderName) + await storage.adapter.deleteFolder(eager.folderName) + } + }) +}) diff --git a/tests/setup.ts b/tests/setup.ts index 5c6dde0..e56e60d 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -45,6 +45,7 @@ const TESTING_ENV_BASE = { | 'ORPHANED_STORAGE_GRACE_PERIOD_HOURS' | 'ENABLE_DIRECT_DOWNLOADS' | 'EAGER_MERGE' + | 'MAX_CONCURRENT_MERGES' | 'BENCHMARK' | 'SKIP_TOKEN_VALIDATION' | 'ACTIONS_TOKEN_ISSUER' From 0aea480225093266f095dea35fad19aece814f76 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Sat, 24 Oct 2026 16:43:36 -0400 Subject: [PATCH 2/5] fix(download): close downloads whose client stopped reading Node's HTTP server has no idle timeout for a response in progress and the download route set none. A client that stays connected but stops reading parks the pipe forever: the backend read keeps its storage socket, the Storage Reader Lease keeps renewing, and on the first restore of an unmerged entry the Merge it paces never finishes and keeps its Merge Lease. Each such client permanently removes one socket from the storage pool. Destroy the download when no bytes have moved for DOWNLOAD_IDLE_TIMEOUT_MS (default 300000, 0 disables). The timer is refreshed on every chunk, so slow but progressing clients are unaffected. It covers whole and Range responses and the first restore of an unmerged entry, whose Merge keeps going after the client's side of the tee is closed. tests/proxy-backpressure.test.ts parks a client after the first chunk of a 200, a 206 and an unmerged first restore, and checks that the storage read is released, the response closed, and the Merge completed. Signed-off-by: Rui Chen --- README.md | 13 ++-- lib/schemas.ts | 1 + routes/download/[locationId].ts | 22 +++++++ tests/proxy-backpressure.test.ts | 110 +++++++++++++++++++++++++++++++ tests/setup.ts | 1 + 5 files changed, 141 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 85ebc36..df6bc91 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,13 @@ volumes: All optional. -| Variable | Default | Effect | -| ------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. | -| `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | -| `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. | -| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | +| Variable | Default | Effect | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. | +| `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | +| `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. | +| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | +| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose client has not read a byte for this long; `0` disables. | ## Documentation diff --git a/lib/schemas.ts b/lib/schemas.ts index c0e2f0d..493e5bd 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -88,6 +88,7 @@ export const envBaseSchema = type({ 'ENABLE_DIRECT_DOWNLOADS': 'boolean = false', 'EAGER_MERGE': 'boolean = false', 'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16', + 'DOWNLOAD_IDLE_TIMEOUT_MS': 'number.integer >= 0 = 300000', 'BENCHMARK': 'boolean = false', 'SKIP_TOKEN_VALIDATION': 'boolean = false', 'MANAGEMENT_API_KEY?': 'string', diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index 4d0dc02..fd39409 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -1,6 +1,7 @@ import type { RangeRequest } from '~/lib/storage' import { pipeline } from 'node:stream/promises' import { z } from 'zod' +import { env } from '~/lib/env' import { logger } from '~/lib/logger' import { getStorage, RangeNotSatisfiableError } from '~/lib/storage' @@ -78,6 +79,21 @@ export default defineEventHandler(async (event) => { // and destroys the source, which releases its reader lease. `_handled` is an h3 v1 internal. event._handled = true const { res } = event.node + // The HTTP server has no idle timeout, so a client that stops reading but keeps + // the connection open would hold the backend read, its reader lease and, on a + // first restore, the Merge it paces forever. Bytes moving at any rate keep the + // download alive. + let idleTimer: NodeJS.Timeout | undefined + if (env.DOWNLOAD_IDLE_TIMEOUT_MS > 0) { + idleTimer = setTimeout(() => { + download.stream.destroy( + Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }), + ) + }, env.DOWNLOAD_IDLE_TIMEOUT_MS).unref() + download.stream.on('data', () => idleTimer?.refresh()) + } try { await pipeline(download.stream, res) } catch (err) { @@ -86,6 +102,10 @@ export default defineEventHandler(async (event) => { // read waited for a socket) without taking ownership of the source. download.stream.destroy() const { code, message } = err as NodeJS.ErrnoException + if (code === 'ERR_DOWNLOAD_IDLE_TIMEOUT') { + logger.warn(`Download /download/${locationId} closed: ${message}`) + return + } // Client went away. Expected on cancelled jobs and parallel runners. if (code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'ERR_STREAM_UNABLE_TO_PIPE') { logger.debug(`Client aborted /download/${locationId}: ${message}`) @@ -97,5 +117,7 @@ export default defineEventHandler(async (event) => { return } throw err + } finally { + clearTimeout(idleTimer) } }) diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts index 9a7ff4f..72cff49 100644 --- a/tests/proxy-backpressure.test.ts +++ b/tests/proxy-backpressure.test.ts @@ -9,6 +9,8 @@ import { setTimeout as sleep } from 'node:timers/promises' import * as h3 from 'h3' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' import { getStorage } from '~/lib/storage' const MiB = 1024 * 1024 @@ -167,4 +169,112 @@ describe('proxy routes apply backpressure', () => { await vi.waitFor(() => expect(source.destroyed).toBe(true), { timeout: 5000, interval: 50 }) }, 20_000) + + describe('download idle timeout', () => { + const originalIdleTimeout = env.DOWNLOAD_IDLE_TIMEOUT_MS + beforeAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = 500 + }) + afterAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout + }) + + test.each([ + { response: 'a whole entry', status: 200, range: undefined }, + { response: 'a Range', status: 206, range: { start: 0, end: ENTRY_BYTES - 1 } }, + ])( + 'releases the storage read of a client that stopped reading $response', + async ({ status, range }) => { + // Real timers and sockets on purpose: the stall comes from TCP flow control, + // which fake timers cannot drive. + let pulled = 0 + function* entry() { + while (pulled < ENTRY_BYTES) { + pulled += CHUNK_BYTES + yield Buffer.alloc(CHUNK_BYTES) + } + } + const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES }) + const storage = await getStorage() + vi.spyOn(storage, 'download').mockResolvedValue({ + stream: source, + size: ENTRY_BYTES, + range, + }) + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${randomUUID()}`, { + headers: range ? { range: `bytes=${range.start}-${range.end}` } : {}, + }) + req.on('error', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(status) + res.once('data', () => res.pause()) // stops reading, keeps the connection open + const [, serverRes] = await serverSide + const serverClosed = once(serverRes, 'close') + + // Without an idle timeout neither ever happens: the pipe just stays parked. + await expect(once(source, 'close')).rejects.toMatchObject({ + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }) + await serverClosed + expect(pulled).toBeLessThan(ENTRY_BYTES) + req.destroy() + }, + 20_000, + ) + + test('a stalled first restore is closed and its Merge still completes', async () => { + const storage = await getStorage() + const db = await getDatabase() + const reservation = { + key: `idle-unmerged-${randomUUID()}`, + version: 'v1', + scope: 'refs/heads/main', + repoId: '123', + } + const upload = await storage.createUpload(reservation) + // Far more than loopback socket buffers hold, so the stalled client really blocks the tee. + for (let i = 0; i < 4; i++) + await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(8 * MiB, i)])) + await storage.completeUpload(reservation) + const { locationId } = await db + .selectFrom('cache_entries') + .where('key', '=', reservation.key) + .select('locationId') + .executeTakeFirstOrThrow() + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${locationId}`) + req.on('error', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(200) + res.once('data', () => res.pause()) + const [, serverRes] = await serverSide + await once(serverRes, 'close') + req.destroy() + + // The pump keeps feeding the merge once the client's side of the tee is gone. + await storage.waitForOngoingMerges() + const location = await db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select('mergedAt') + .executeTakeFirstOrThrow() + expect(location.mergedAt).not.toBeNull() + await vi.waitFor( + async () => { + const leases = await db + .selectFrom('storage_reader_leases') + .where('storageLocationId', '=', locationId) + .select('id') + .execute() + expect(leases, 'reader leases left behind').toHaveLength(0) + }, + { timeout: 5000, interval: 50 }, + ) + }, 30_000) + }) }) diff --git a/tests/setup.ts b/tests/setup.ts index e56e60d..009f771 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -46,6 +46,7 @@ const TESTING_ENV_BASE = { | 'ENABLE_DIRECT_DOWNLOADS' | 'EAGER_MERGE' | 'MAX_CONCURRENT_MERGES' + | 'DOWNLOAD_IDLE_TIMEOUT_MS' | 'BENCHMARK' | 'SKIP_TOKEN_VALIDATION' | 'ACTIONS_TOKEN_ISSUER' From fa908a8affda9b6a27e2deb10bc8adabd79035f7 Mon Sep 17 00:00:00 2001 From: Louis Haftmann <30736553+LouisHaftmann@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:37:12 +0100 Subject: [PATCH 3/5] chore(helm): expose MAX_CONCURRENT_MERGES and DOWNLOAD_IDLE_TIMEOUT_MS Co-Authored-By: Claude Opus 5.5 --- .../github-actions-cache-server/templates/_helpers.tpl | 4 ++++ install/kubernetes/github-actions-cache-server/values.yaml | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/install/kubernetes/github-actions-cache-server/templates/_helpers.tpl b/install/kubernetes/github-actions-cache-server/templates/_helpers.tpl index 4f394b5..52a86c0 100644 --- a/install/kubernetes/github-actions-cache-server/templates/_helpers.tpl +++ b/install/kubernetes/github-actions-cache-server/templates/_helpers.tpl @@ -127,6 +127,10 @@ Generate environment variables from config values. value: {{ .Values.config.enableDirectDownloads | quote }} - name: EAGER_MERGE value: {{ .Values.config.eagerMerge | quote }} +- name: MAX_CONCURRENT_MERGES + value: {{ .Values.config.maxConcurrentMerges | quote }} +- name: DOWNLOAD_IDLE_TIMEOUT_MS + value: {{ .Values.config.downloadIdleTimeoutMs | quote }} - name: CACHE_CLEANUP_OLDER_THAN_DAYS value: {{ .Values.config.cacheCleanupOlderThanDays | quote }} {{- if .Values.config.cacheMaxSizeBytes }} diff --git a/install/kubernetes/github-actions-cache-server/values.yaml b/install/kubernetes/github-actions-cache-server/values.yaml index 497ba55..feaa98d 100644 --- a/install/kubernetes/github-actions-cache-server/values.yaml +++ b/install/kubernetes/github-actions-cache-server/values.yaml @@ -45,6 +45,12 @@ config: # bucket. Doubles storage per entry until the parts cleanup job runs. eagerMerge: false + # -- Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. + maxConcurrentMerges: 16 + + # -- Closes a download whose client has not read a byte for this long. Set to 0 to disable. + downloadIdleTimeoutMs: 300000 + # -- Number of days to keep stale cache data before deleting it. Set to 0 to disable. cacheCleanupOlderThanDays: 90 From 32a6e5f131ed915c3501ebd3a033a8df3878f6a4 Mon Sep 17 00:00:00 2001 From: Louis Haftmann <30736553+LouisHaftmann@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:40:36 +0100 Subject: [PATCH 4/5] refactor: simplify Merge cap and idle timeout after review Release the Merge slot in one finally, cap DOWNLOAD_IDLE_TIMEOUT_MS at setTimeout's maximum, describe the timeout by what it measures, and drop tests that repeat coverage of the merge pump. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../github-actions-cache-server/values.yaml | 2 +- lib/schemas.ts | 2 +- lib/storage.ts | 16 ++- routes/download/[locationId].ts | 22 ++-- tests/merge-concurrency.test.ts | 39 ++---- tests/proxy-backpressure.test.ts | 113 ++++-------------- 7 files changed, 53 insertions(+), 143 deletions(-) diff --git a/README.md b/README.md index df6bc91..fbb5cbb 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ All optional. | `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | | `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. | | `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | -| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose client has not read a byte for this long; `0` disables. | +| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose storage read has not moved for this long (client stopped reading); `0` disables. | ## Documentation diff --git a/install/kubernetes/github-actions-cache-server/values.yaml b/install/kubernetes/github-actions-cache-server/values.yaml index feaa98d..18bb10e 100644 --- a/install/kubernetes/github-actions-cache-server/values.yaml +++ b/install/kubernetes/github-actions-cache-server/values.yaml @@ -48,7 +48,7 @@ config: # -- Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. maxConcurrentMerges: 16 - # -- Closes a download whose client has not read a byte for this long. Set to 0 to disable. + # -- Closes a download whose storage read has not moved for this long (client stopped reading). Set to 0 to disable. downloadIdleTimeoutMs: 300000 # -- Number of days to keep stale cache data before deleting it. Set to 0 to disable. diff --git a/lib/schemas.ts b/lib/schemas.ts index 493e5bd..d71e2d2 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -88,7 +88,7 @@ export const envBaseSchema = type({ 'ENABLE_DIRECT_DOWNLOADS': 'boolean = false', 'EAGER_MERGE': 'boolean = false', 'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16', - 'DOWNLOAD_IDLE_TIMEOUT_MS': 'number.integer >= 0 = 300000', + 'DOWNLOAD_IDLE_TIMEOUT_MS': '0 <= number.integer <= 2147483647 = 300000', 'BENCHMARK': 'boolean = false', 'SKIP_TOKEN_VALIDATION': 'boolean = false', 'MANAGEMENT_API_KEY?': 'string', diff --git a/lib/storage.ts b/lib/storage.ts index a2520fd..17ad217 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -312,21 +312,19 @@ export class Storage { this.activeMerges++ let mergeToken: string | undefined try { - mergeToken = await acquireMergeLease(this.db, location.id) - if (mergeToken) + const token = await acquireMergeLease(this.db, location.id) + if (token) { await this.db .updateTable('storage_locations') .set({ mergeStartedAt: Date.now() }) .where('id', '=', location.id) .execute() - } catch (err) { - this.activeMerges-- - throw err - } - if (!mergeToken) { - this.activeMerges-- - return false + mergeToken = token + } + } finally { + if (!mergeToken) this.activeMerges-- } + if (!mergeToken) return false const renewalTimer = setInterval(() => { void renewMergeLease(this.db, location.id, mergeToken) diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index fd39409..7080c11 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -83,17 +83,17 @@ export default defineEventHandler(async (event) => { // the connection open would hold the backend read, its reader lease and, on a // first restore, the Merge it paces forever. Bytes moving at any rate keep the // download alive. - let idleTimer: NodeJS.Timeout | undefined - if (env.DOWNLOAD_IDLE_TIMEOUT_MS > 0) { - idleTimer = setTimeout(() => { - download.stream.destroy( - Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { - code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', - }), - ) - }, env.DOWNLOAD_IDLE_TIMEOUT_MS).unref() - download.stream.on('data', () => idleTimer?.refresh()) - } + const idleTimer = + env.DOWNLOAD_IDLE_TIMEOUT_MS > 0 + ? setTimeout(() => { + download.stream.destroy( + Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }), + ) + }, env.DOWNLOAD_IDLE_TIMEOUT_MS) + : undefined + if (idleTimer) download.stream.on('data', () => idleTimer.refresh()) try { await pipeline(download.stream, res) } catch (err) { diff --git a/tests/merge-concurrency.test.ts b/tests/merge-concurrency.test.ts index 85e3e71..971b60a 100644 --- a/tests/merge-concurrency.test.ts +++ b/tests/merge-concurrency.test.ts @@ -37,13 +37,14 @@ async function sha256(stream: Readable) { return hash.digest('hex') } -async function mergeState(locationId: string) { +async function mergedAt(locationId: string) { const db = await getDatabase() - return db + const location = await db .selectFrom('storage_locations') .where('id', '=', locationId) - .select(['mergedAt', 'mergeStartedAt']) + .select('mergedAt') .executeTakeFirstOrThrow() + return location.mergedAt } describe('merge concurrency limit', () => { @@ -70,42 +71,16 @@ describe('merge concurrency limit', () => { expect(await sha256(firstStream)).toBe(expected) await storage.waitForOngoingMerges() - expect(await mergeState(first.locationId)).not.toMatchObject({ mergedAt: null }) - expect(await mergeState(second.locationId)).toMatchObject({ mergedAt: null }) + expect(await mergedAt(first.locationId)).not.toBeNull() + expect(await mergedAt(second.locationId)).toBeNull() // With the slot free again, the next restore merges the skipped entry. expect(await sha256(await download(storage, second.locationId))).toBe(expected) await storage.waitForOngoingMerges() - expect(await mergeState(second.locationId)).not.toMatchObject({ mergedAt: null }) + expect(await mergedAt(second.locationId)).not.toBeNull() } finally { await storage.adapter.deleteFolder(first.folderName) await storage.adapter.deleteFolder(second.folderName) } }) - - test('an eager merge beyond the limit leaves the entry to a later download', async () => { - env.EAGER_MERGE = false - env.MAX_CONCURRENT_MERGES = 1 - const storage = await Storage.fromEnv() - const busy = await uploadEntry(storage) - // An unread first restore keeps its Merge, and the only slot, busy. - const busyStream = await download(storage, busy.locationId) - - env.EAGER_MERGE = true - const eager = await uploadEntry(storage) - try { - // Upload completion awaits the Merge Lease, so a started Merge would have - // stamped mergeStartedAt by now. - expect(await mergeState(eager.locationId)).toEqual({ mergedAt: null, mergeStartedAt: null }) - - expect(await sha256(busyStream)).toBe(expected) - await storage.waitForOngoingMerges() - expect(await sha256(await download(storage, eager.locationId))).toBe(expected) - await storage.waitForOngoingMerges() - expect(await mergeState(eager.locationId)).not.toMatchObject({ mergedAt: null }) - } finally { - await storage.adapter.deleteFolder(busy.folderName) - await storage.adapter.deleteFolder(eager.folderName) - } - }) }) diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts index 72cff49..a9e313e 100644 --- a/tests/proxy-backpressure.test.ts +++ b/tests/proxy-backpressure.test.ts @@ -9,7 +9,6 @@ import { setTimeout as sleep } from 'node:timers/promises' import * as h3 from 'h3' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' -import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { getStorage } from '~/lib/storage' @@ -179,102 +178,40 @@ describe('proxy routes apply backpressure', () => { env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout }) - test.each([ - { response: 'a whole entry', status: 200, range: undefined }, - { response: 'a Range', status: 206, range: { start: 0, end: ENTRY_BYTES - 1 } }, - ])( - 'releases the storage read of a client that stopped reading $response', - async ({ status, range }) => { - // Real timers and sockets on purpose: the stall comes from TCP flow control, - // which fake timers cannot drive. - let pulled = 0 - function* entry() { - while (pulled < ENTRY_BYTES) { - pulled += CHUNK_BYTES - yield Buffer.alloc(CHUNK_BYTES) - } + test('releases the storage read of a client that stopped reading', async () => { + // Real timers and sockets on purpose: the stall comes from TCP flow control, + // which fake timers cannot drive. + let pulled = 0 + function* entry() { + while (pulled < ENTRY_BYTES) { + pulled += CHUNK_BYTES + yield Buffer.alloc(CHUNK_BYTES) } - const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES }) - const storage = await getStorage() - vi.spyOn(storage, 'download').mockResolvedValue({ - stream: source, - size: ENTRY_BYTES, - range, - }) - - const { port } = server.address() as AddressInfo - const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> - const req = http.get(`http://localhost:${port}/download/${randomUUID()}`, { - headers: range ? { range: `bytes=${range.start}-${range.end}` } : {}, - }) - req.on('error', () => undefined) - const [res] = (await once(req, 'response')) as [IncomingMessage] - expect(res.statusCode).toBe(status) - res.once('data', () => res.pause()) // stops reading, keeps the connection open - const [, serverRes] = await serverSide - const serverClosed = once(serverRes, 'close') - - // Without an idle timeout neither ever happens: the pipe just stays parked. - await expect(once(source, 'close')).rejects.toMatchObject({ - code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', - }) - await serverClosed - expect(pulled).toBeLessThan(ENTRY_BYTES) - req.destroy() - }, - 20_000, - ) - - test('a stalled first restore is closed and its Merge still completes', async () => { - const storage = await getStorage() - const db = await getDatabase() - const reservation = { - key: `idle-unmerged-${randomUUID()}`, - version: 'v1', - scope: 'refs/heads/main', - repoId: '123', } - const upload = await storage.createUpload(reservation) - // Far more than loopback socket buffers hold, so the stalled client really blocks the tee. - for (let i = 0; i < 4; i++) - await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(8 * MiB, i)])) - await storage.completeUpload(reservation) - const { locationId } = await db - .selectFrom('cache_entries') - .where('key', '=', reservation.key) - .select('locationId') - .executeTakeFirstOrThrow() + const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES }) + const storage = await getStorage() + vi.spyOn(storage, 'download').mockResolvedValue({ + stream: source, + size: ENTRY_BYTES, + }) const { port } = server.address() as AddressInfo const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> - const req = http.get(`http://localhost:${port}/download/${locationId}`) + const req = http.get(`http://localhost:${port}/download/${randomUUID()}`) req.on('error', () => undefined) const [res] = (await once(req, 'response')) as [IncomingMessage] expect(res.statusCode).toBe(200) - res.once('data', () => res.pause()) + res.once('data', () => res.pause()) // stops reading, keeps the connection open const [, serverRes] = await serverSide - await once(serverRes, 'close') + const serverClosed = once(serverRes, 'close') + + // Without an idle timeout neither ever happens: the pipe just stays parked. + await expect(once(source, 'close')).rejects.toMatchObject({ + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }) + await serverClosed + expect(pulled).toBeLessThan(ENTRY_BYTES) req.destroy() - - // The pump keeps feeding the merge once the client's side of the tee is gone. - await storage.waitForOngoingMerges() - const location = await db - .selectFrom('storage_locations') - .where('id', '=', locationId) - .select('mergedAt') - .executeTakeFirstOrThrow() - expect(location.mergedAt).not.toBeNull() - await vi.waitFor( - async () => { - const leases = await db - .selectFrom('storage_reader_leases') - .where('storageLocationId', '=', locationId) - .select('id') - .execute() - expect(leases, 'reader leases left behind').toHaveLength(0) - }, - { timeout: 5000, interval: 50 }, - ) - }, 30_000) + }, 20_000) }) }) From f328e3a9ed2e803ee278e59c9faf30c7f02c5b2e Mon Sep 17 00:00:00 2001 From: Louis Haftmann <30736553+LouisHaftmann@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:47:29 +0100 Subject: [PATCH 5/5] docs(adr): record that Eager Merges share the Merge cap Name the idle timeout error like the other route errors and cover a slow download staying open. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- ...-composes-server-side-on-object-storage.md | 2 +- .../github-actions-cache-server/values.yaml | 2 +- routes/download/[locationId].ts | 14 +++++----- tests/proxy-backpressure.test.ts | 27 ++++++++++++++++--- 5 files changed, 35 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index fbb5cbb..4a5156f 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ All optional. | `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. | | `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | | `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. | -| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | +| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once, eager or lazy. Beyond it, restores stream the parts and a later download merges. | | `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose storage read has not moved for this long (client stopped reading); `0` disables. | ## Documentation diff --git a/docs/adr/0009-eager-merge-is-opt-in-and-composes-server-side-on-object-storage.md b/docs/adr/0009-eager-merge-is-opt-in-and-composes-server-side-on-object-storage.md index ff8faed..ee7b0fc 100644 --- a/docs/adr/0009-eager-merge-is-opt-in-and-composes-server-side-on-object-storage.md +++ b/docs/adr/0009-eager-merge-is-opt-in-and-composes-server-side-on-object-storage.md @@ -2,7 +2,7 @@ Direct downloads need a merged object, and the Merge runs lazily on first download, so the first Cache Hit of every entry is proxied through the server even with `ENABLE_DIRECT_DOWNLOADS`. `EAGER_MERGE=true` runs the Merge right after upload completion instead. It stays off by default because lazy merging never pays merge traffic for entries that are never downloaded. -Both paths share one merge runner. Merge Lease, renewal, lease-fenced completion, and rollback are identical, so eager and lazy merges race safely against each other and against `cleanup:merges`. Upload completion picks the strategy up front from the Part sizes it already lists to record `sizeBytes`. When the adapter offers `composeParts` and every Part satisfies its limits, the Merge is a Server-side Merge with no bytes passing through the server. On S3 that is `CreateMultipartUpload`, one `UploadPartCopy` per Part, `CompleteMultipartUpload`; the limits are every Part but the last at least 5 MiB, none above 5 GiB, at most 10,000 Parts. On GCS it is `compose`, folding 32 sources at a time into a top-level temp object and composing `merged` in one final call; there is no minimum Part size. Otherwise the existing streaming merge runs immediately. Buildx uploads 1 MiB blocks, so its entries always take the streaming path. A backend that rejects the copy call fails the Merge like any other merge failure; the entry then merges lazily on first download. +Both paths share one merge runner. Merge Lease, renewal, lease-fenced completion, and rollback are identical, so eager and lazy merges race safely against each other and against `cleanup:merges`. Upload completion picks the strategy up front from the Part sizes it already lists to record `sizeBytes`. When the adapter offers `composeParts` and every Part satisfies its limits, the Merge is a Server-side Merge with no bytes passing through the server. On S3 that is `CreateMultipartUpload`, one `UploadPartCopy` per Part, `CompleteMultipartUpload`; the limits are every Part but the last at least 5 MiB, none above 5 GiB, at most 10,000 Parts. On GCS it is `compose`, folding 32 sources at a time into a top-level temp object and composing `merged` in one final call; there is no minimum Part size. Otherwise the existing streaming merge runs immediately. Buildx uploads 1 MiB blocks, so its entries always take the streaming path. A backend that rejects the copy call fails the Merge like any other merge failure; the entry then merges lazily on first download. Eager and lazy Merges share the per-process `MAX_CONCURRENT_MERGES` cap; an Eager Merge past it is skipped the same way, and the entry merges lazily on first download. This does not reopen ADR-0004. The 5 GiB cap it cites applies to `CopyObject` used as a promote step. `UploadPartCopy` writes `merged` directly under the same lease fence, and Parts are immutable, so a merger that lost its lease can only write identical bytes. diff --git a/install/kubernetes/github-actions-cache-server/values.yaml b/install/kubernetes/github-actions-cache-server/values.yaml index 18bb10e..061eb29 100644 --- a/install/kubernetes/github-actions-cache-server/values.yaml +++ b/install/kubernetes/github-actions-cache-server/values.yaml @@ -45,7 +45,7 @@ config: # bucket. Doubles storage per entry until the parts cleanup job runs. eagerMerge: false - # -- Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. + # -- Merges one process runs at once, eager or lazy. Beyond it, restores stream the parts and a later download merges. maxConcurrentMerges: 16 # -- Closes a download whose storage read has not moved for this long (client stopped reading). Set to 0 to disable. diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index 7080c11..8cb888c 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -24,6 +24,12 @@ function parseRange(header: string | undefined): RangeRequest | undefined { return { start, end } } +class DownloadIdleTimeoutError extends Error { + constructor() { + super(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`) + } +} + export default defineEventHandler(async (event) => { const parsedPathParams = pathParamsSchema.safeParse(event.context.params) if (!parsedPathParams.success) @@ -86,11 +92,7 @@ export default defineEventHandler(async (event) => { const idleTimer = env.DOWNLOAD_IDLE_TIMEOUT_MS > 0 ? setTimeout(() => { - download.stream.destroy( - Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { - code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', - }), - ) + download.stream.destroy(new DownloadIdleTimeoutError()) }, env.DOWNLOAD_IDLE_TIMEOUT_MS) : undefined if (idleTimer) download.stream.on('data', () => idleTimer.refresh()) @@ -102,7 +104,7 @@ export default defineEventHandler(async (event) => { // read waited for a socket) without taking ownership of the source. download.stream.destroy() const { code, message } = err as NodeJS.ErrnoException - if (code === 'ERR_DOWNLOAD_IDLE_TIMEOUT') { + if (err instanceof DownloadIdleTimeoutError) { logger.warn(`Download /download/${locationId} closed: ${message}`) return } diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts index a9e313e..2928e10 100644 --- a/tests/proxy-backpressure.test.ts +++ b/tests/proxy-backpressure.test.ts @@ -178,6 +178,29 @@ describe('proxy routes apply backpressure', () => { env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout }) + test('keeps a download open while bytes keep moving', async () => { + const chunks = 8 + // Slower in total than the idle timeout, but never idle for that long. + const source = Readable.from( + (async function* () { + for (let i = 0; i < chunks; i++) { + await sleep(200) + yield Buffer.alloc(CHUNK_BYTES) + } + })(), + ) + const storage = await getStorage() + vi.spyOn(storage, 'download').mockResolvedValue({ + stream: source, + size: chunks * CHUNK_BYTES, + }) + + const { port } = server.address() as AddressInfo + const res = await fetch(`http://localhost:${port}/download/${randomUUID()}`) + const body = await res.arrayBuffer() + expect(body.byteLength).toBe(chunks * CHUNK_BYTES) + }, 20_000) + test('releases the storage read of a client that stopped reading', async () => { // Real timers and sockets on purpose: the stall comes from TCP flow control, // which fake timers cannot drive. @@ -206,9 +229,7 @@ describe('proxy routes apply backpressure', () => { const serverClosed = once(serverRes, 'close') // Without an idle timeout neither ever happens: the pipe just stays parked. - await expect(once(source, 'close')).rejects.toMatchObject({ - code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', - }) + await expect(once(source, 'close')).rejects.toThrow('No bytes sent') await serverClosed expect(pulled).toBeLessThan(ENTRY_BYTES) req.destroy()