From 21ff2bd913d7df22159341179af49ff7bfec68cd Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Sat, 24 Oct 2026 16:33:35 -0400 Subject: [PATCH] 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 | 8 +++ lib/schemas.ts | 1 + lib/storage.ts | 40 ++++++++---- tests/merge-concurrency.test.ts | 111 ++++++++++++++++++++++++++++++++ tests/setup.ts | 1 + 5 files changed, 150 insertions(+), 11 deletions(-) create mode 100644 tests/merge-concurrency.test.ts diff --git a/README.md b/README.md index 90307017..612116f8 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,14 @@ volumes: cache-data: ``` +## Resource limits + +All optional. + +| Variable | Default | Effect | +| ----------------------- | ------- | -------------------------------------------------------------------------------------------------- | +| `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 bbae5f53..456ecf35 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -84,6 +84,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 d40ce618..c154124e 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -130,6 +130,7 @@ export class Storage { private db private mergeStreamPromises = new Set>() + private activeMerges = 0 adapter private constructor({ db, adapter }: { adapter: StorageAdapter; db: Kysely }) { @@ -281,19 +282,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) @@ -341,6 +358,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 00000000..85e3e71f --- /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 5ca471ec..f982fd79 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -44,6 +44,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'