From 635ed5a36480dc1886e6d18ee7eeb96f7486a81b Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Fri, 27 Nov 2026 07:08:10 +0000 Subject: [PATCH] fix(skills): start skill package transfer deadlines after the I/O queue admits them (#22615) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Before a run starts, Paperclip copies each selected skill version from skill package storage into a local cache. > - Skill package reads share small I/O queues for each process. Each queue has 2 active permits and 32 waiting slots. > - Each read started its 180-second deadline before it waited for a permit. A read that waited behind other transfers used up its deadline in the queue. > - On a busy host, a run then failed before its agent started with "Failed to materialize the selected skill version: The operation was aborted due to timeout". The next run did the same cold read and failed the same way. > - This pull request starts each transfer deadline when the queue grants the permit. > - The benefit is that a cold skill read under load waits for its turn and then gets its full transfer deadline. ## Linked Issues or Issue Description **What happened?** A staging host had a burst of 21 run failures in 15 minutes. All runs were in one company, and each failed with "Failed to materialize the selected skill version: The operation was aborted due to timeout". The runs woke at the same time after a provider usage limit reset. The skill cache was cold. **Expected behavior** A run that waits for a skill package I/O permit gets the full 180-second deadline for its own transfer. Time spent in the queue must not count against that deadline. **Steps to reproduce** 1. Make the skill package cache cold for three companies. 2. Stall the archive reads of two companies, so that they hold both storage permits. 3. Resolve the runtime skills of the third company. Its reads now wait in the queue. 4. Wait longer than the transfer deadline, then release the stalled reads. 5. On `master`, the third company's skill resolves as missing with the timeout message. Its own transfer would take milliseconds. **Paperclip version or commit** `master` at 7a2ee0da1c. ## What Changed - `withPackageIo` now creates the transfer deadline after it grants the permit, and gives the action that signal. A queued wait stops only when the caller cancels. - Manifest loads, isolated package reads, warm package materialization, durable verification, cached version reads and single-file reads no longer start a deadline before they queue. Each transfer still has the same 180-second deadline. - The cold-response permit gets no deadline of its own. That permit only bounds decoded responses until cleanup. The storage transfer inside it still has its deadline. - An isolated read now gives its consumer the transfer signal. The cached file reads inside that consumer use it. - Package uploads (`prepare`) are not changed. - Added the regression test `starts package transfer deadlines after queued storage waits`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/skill-package-store.test.ts -t "starts package transfer deadlines"` - With this change: passes. - With `master`'s `skill-package-store.ts`: fails. The skill resolves as missing with "Failed to materialize the selected skill version: The operation was aborted due to timeout". - Related suites: `skill-package-store`, `skill-package-upload`, `skill-version-cache`, `skill-version-retention`, `runtime-skill-cache`, `company-skills-runtime-concurrency`, `company-skills-runtime-selection`, `managed-skill-content`, `skill-repository-package`, `skill-version-cache-lock`, `skill-package-work`, `skill-package-storage-migration`, `skill-package-storage-migration-postgres` and `skill-package-recovery`. 235 of 236 tests pass. - The only failure is `bounds and validates archives, binaries, paths, executable modes, and corruption`. It also fails on unchanged `master` in the same sandbox, because the sandbox `umask` is `077`. It is not related to this change. - A timing probe with 20 concurrent cold resolves in one company and 4 other cold companies failed on `master` and passed with this change. ## Risks - A queued read can now wait longer before it fails. The wait is still bounded, because each queue has at most 32 waiting reads and every active transfer has its own deadline. A full queue still returns "Skill package storage is busy; retry shortly." immediately. - After a cold fill is published, cache trimming is no longer bounded by the fill's deadline. Trimming keeps its own 10-second limit, and each storage check inside it has its own transfer deadline. - If a manifest read times out, the store now tries the saved legacy contents or the restore recipe before it fails. Before, the timeout stopped it before those fallbacks. Both fallbacks are already authoritative sources for the same manifest. - Low risk otherwise. The change is limited to `skill-package-store.ts`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Related: #22310 changes `skill-package-runtime.ts` and the same test file. It does not change these deadlines. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/__tests__/skill-package-store.test.ts | 33 +++++++ server/src/services/skill-package-store.ts | 89 ++++++++++--------- 2 files changed, 78 insertions(+), 44 deletions(-) diff --git a/server/src/__tests__/skill-package-store.test.ts b/server/src/__tests__/skill-package-store.test.ts index cd1bb86f700..5b0b2b29824 100644 --- a/server/src/__tests__/skill-package-store.test.ts +++ b/server/src/__tests__/skill-package-store.test.ts @@ -1047,4 +1047,37 @@ describe.skipIf(!support.supported)("external skill packages", () => { expect(converted!.packageSnapshotId).toBe(id); expect(skillSnapshotHash(await store.versionFiles(converted!))).toBe(skillSnapshotHash(large)); }, 90_000); + + it("starts package transfer deadlines after queued storage waits", async () => { + const timeout = AbortSignal.timeout.bind(AbortSignal); + vi.spyOn(AbortSignal, "timeout").mockImplementation(ms => timeout(ms === 180_000 ? 1_000 : ms)); + const busy = [await fixture(), await fixture()]; + const target = await fixture(); + for (const f of [...busy, target]) await fs.rm(skillPackagePaths(f.companyId, f.id).directory, { recursive: true, force: true }); + const stalled = new Set(await Promise.all(busy.map(async f => (await f.store.descriptor(f.companyId, f.id)).storage!.archiveKey))); + const get = storage.getObject.bind(storage); + let entered = 0; + let bothEntered!: () => void; + const started = new Promise(resolve => { bothEntered = resolve; }); + let release!: () => void; + const blocked = new Promise(resolve => { release = resolve; }); + vi.spyOn(storage, "getObject").mockImplementation(async (...args) => { + if (stalled.has(args[1])) { + if (++entered === 2) bothEntered(); + await blocked; + } + return get(...args); + }); + const occupied = busy.map(f => f.resolve()); + let herd: ReturnType[] = []; + try { + await started; + herd = Array.from({ length: 5 }, () => target.resolve()); + await new Promise(resolve => setTimeout(resolve, 1_500)); + release(); + for (const entries of await Promise.all(herd)) { + expect(entries.map(entry => entry.missingDetail ?? entry.sourceStatus)).toEqual(["available", "available"]); + } + } finally { release(); await Promise.allSettled([...occupied, ...herd]); } + }); }); diff --git a/server/src/services/skill-package-store.ts b/server/src/services/skill-package-store.ts index 56b3cdaf104..69cd9ab37e2 100644 --- a/server/src/services/skill-package-store.ts +++ b/server/src/services/skill-package-store.ts @@ -105,23 +105,29 @@ const inventoryIo: PackageIoQueue = { active: 0, waiting: [] }; export function skillPackageStorageIoDepth() { return { active: storageIo.active, waiting: storageIo.waiting.length }; } -async function withPackageIo(action: () => Promise, signal: AbortSignal, queue = storageIo): Promise { - signal.throwIfAborted(); +const PACKAGE_IO_DEADLINE_MS = 180_000; +async function withPackageIo(action: (signal: AbortSignal) => Promise, cancellation: AbortSignal | undefined, + queue = storageIo, deadlineMs: number | null = null): Promise { + cancellation?.throwIfAborted(); if (queue.active >= 2) { if (queue.waiting.length >= 32) throw conflict("Skill package storage is busy; retry shortly."); await new Promise((resolve, reject) => { - const ready = () => { signal.removeEventListener("abort", aborted); resolve(); }; + const ready = () => { cancellation?.removeEventListener("abort", aborted); resolve(); }; const aborted = () => { const index = queue.waiting.indexOf(ready); if (index >= 0) queue.waiting.splice(index, 1); - reject(signal.reason); + reject(cancellation!.reason); }; queue.waiting.push(ready); - signal.addEventListener("abort", aborted, { once: true }); + cancellation?.addEventListener("abort", aborted, { once: true }); }); } else queue.active++; - try { signal.throwIfAborted(); return await action(); } - finally { const next = queue.waiting.shift(); if (next) next(); else queue.active--; } + try { + cancellation?.throwIfAborted(); + const deadline = deadlineMs === null ? null : AbortSignal.timeout(deadlineMs); + const signal = deadline && cancellation ? AbortSignal.any([cancellation, deadline]) : deadline ?? cancellation ?? new AbortController().signal; + return await action(signal); + } finally { const next = queue.waiting.shift(); if (next) next(); else queue.active--; } } const manifests = new Map(); let manifestBytes = 0; @@ -250,8 +256,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach const key = `${paths.manifest}:${row.storage?.manifestSha256 ?? row.contentHash}`; const cached = manifests.get(key); if (cached) return cached.manifest; - const load = async (sharedSignal: AbortSignal) => { - const signal = AbortSignal.any([sharedSignal, AbortSignal.timeout(180_000)]); + const load = async (signal: AbortSignal) => { await ensureSkillCacheDirectory(paths.parent, true); // Legacy manifests have no independently stored checksum. Derive them once // per process from the authoritative row until the operator migrates it. @@ -271,8 +276,8 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach if (!bytes || packageSha256(bytes) !== row.storage.manifestSha256) { try { if (row.storage.provider !== storage().provider) throw new Error("Skill package storage provider changed"); - bytes = await withPackageIo(() => readBoundedObject(storage(), row.companyId, row.storage!.manifestKey, - row.storage!.manifestBytes, row.storage!.manifestSha256, signal), signal); + bytes = await withPackageIo(io => readBoundedObject(storage(), row.companyId, row.storage!.manifestKey, + row.storage!.manifestBytes, row.storage!.manifestSha256, io), signal, storageIo, PACKAGE_IO_DEADLINE_MS); } catch (error) { signal.throwIfAborted(); const saved = await withPackageIo(() => withDedicatedDbConnection(cacheOwner, async database => { @@ -349,29 +354,29 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach // Archive reads and verification own private scratch space outside the warm // preparation lock. Administrative reads briefly try that lock to publish. async function withIsolatedPackage(companyId: string, id: string, - consume: (root: string, manifest: SkillPackageManifest) => Promise, allowRecovery = true, cancellation?: AbortSignal, cacheRead = false) { - const signal = cancellation ? AbortSignal.any([cancellation, AbortSignal.timeout(180_000)]) : AbortSignal.timeout(180_000); - signal.throwIfAborted(); + consume: (root: string, manifest: SkillPackageManifest, signal: AbortSignal) => Promise, allowRecovery = true, cancellation?: AbortSignal, cacheRead = false) { + cancellation?.throwIfAborted(); // Preserve the caller's transaction view before taking an I/O permit. All // later SQL uses a private connection, so a queued transaction cannot hold // the ordinary pool connection needed by an active cold response. const row = await descriptor(companyId, id); - const manifest = await manifestFor(row, signal); - const read = () => readIsolatedPackage(row, manifest, consume, allowRecovery, signal, cacheRead); - return cacheRead ? withPackageIo(read, signal, coldResponses) : read(); + const manifest = await manifestFor(row, cancellation); + const read = () => readIsolatedPackage(row, manifest, consume, allowRecovery, cancellation, cacheRead); + return cacheRead ? withPackageIo(read, cancellation, coldResponses) : read(); } async function readIsolatedPackage(row: Descriptor, manifest: SkillPackageManifest, - consume: (root: string, manifest: SkillPackageManifest) => Promise, allowRecovery: boolean, signal: AbortSignal, cacheRead: boolean) { + consume: (root: string, manifest: SkillPackageManifest, signal: AbortSignal) => Promise, allowRecovery: boolean, + cancellation: AbortSignal | undefined, cacheRead: boolean) { const { companyId, id } = row; let published = false; - const result = await withPackageIo(() => withDedicatedDbConnection(cacheOwner, async database => { + const result = await withPackageIo(signal => withDedicatedDbConnection(cacheOwner, async database => { const parent = skillPackagePaths(companyId, id).parent; await ensureSkillCacheDirectory(parent, true); const staging = await fs.mkdtemp(path.join(parent, ".verify-")); const archive = `${staging}.tar.gz`; try { await restoreInto(row, manifest, staging, archive, signal, allowRecovery, database); - const result = await consume(staging, manifest); + const result = await consume(staging, manifest, signal); if (cacheRead) { // Network, extraction, hashing and response reads all happen before // this short publication lock. Busy preparation keeps its priority. @@ -393,7 +398,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach } return result; } finally { await fs.rm(staging, { recursive: true, force: true }); await fs.rm(archive, { force: true }); } - }, { admitWithoutWaiting: true }), signal); + }, { admitWithoutWaiting: true }), cancellation, storageIo, PACKAGE_IO_DEADLINE_MS); if (published) await withDedicatedDbConnection(cacheOwner, async database => { // Verify possible eviction candidates outside both the preparation lock // and the storage slot used for this fill; take the lock only to remove. @@ -403,9 +408,9 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach async remove => { try { await withSkillVersionCacheLock(cacheOwner, companyId, remove, true); } catch (error) { if (!(error instanceof SkillCacheBusy)) throw error; } - }, signal); + }, cancellation); }, { admitWithoutWaiting: cacheRead }); - signal.throwIfAborted(); + cancellation?.throwIfAborted(); return result; } async function materialize(row: Descriptor, manifest: SkillPackageManifest) { @@ -413,8 +418,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach return flight(db, `files:${paths.directory}`, async () => { await ensureSkillCacheDirectory(paths.parent, true); if (await verifySkillPackageDirectory(paths.directory, manifest.files)) return { directory: paths.directory, created: false }; - const signal = AbortSignal.timeout(180_000); - return withPackageIo(async () => { + return withPackageIo(async signal => { const staging = await fs.mkdtemp(path.join(paths.parent, ".package-")); const archivePath = `${staging}.tar.gz`; try { @@ -425,7 +429,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach relocateSkillPackageVerification(staging, paths.directory, manifest.files); return { directory: paths.directory, created: true }; } finally { await fs.rm(staging, { recursive: true, force: true }); await fs.rm(archivePath, { force: true }); } - }, signal); + }, undefined, storageIo, PACKAGE_IO_DEADLINE_MS); }); } async function withPackage(companyId: string, id: string, consume: (root: string, manifest: SkillPackageManifest) => Promise) { @@ -578,8 +582,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach if (!row.storage) return validate ? withIsolatedPackage(companyId, id, validate, false, cancellation) : true; } if (row.storage.provider !== storage().provider) throw new Error("Skill package storage provider changed; migrate its objects before switching storage"); - const signal = cancellation ? AbortSignal.any([cancellation, AbortSignal.timeout(180_000)]) : AbortSignal.timeout(180_000); - return withPackageIo(async () => { + return withPackageIo(async signal => { const receipt = row.storage!; const bytes = await readBoundedObject(storage(), companyId, receipt.manifestKey, receipt.manifestBytes, receipt.manifestSha256, signal); const manifest = validateSkillPackageManifest(JSON.parse(bytes.toString("utf8"))); @@ -599,7 +602,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach await extractSkillPackageArchive(archive, restored, manifest, signal); return validate ? await validate(restored, manifest) : true; } finally { await fs.rm(staging, { recursive: true, force: true }); } - }, signal); + }, cancellation, storageIo, PACKAGE_IO_DEADLINE_MS); }; const context = readScope.getStore(); const key = `${companyId}:${id}`; @@ -628,17 +631,16 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach } finally { await handle.close(); } } async function versionFiles(version: StoredSkillVersion, allowRecovery = true, cancellation?: AbortSignal): Promise { - const signal = cancellation ? AbortSignal.any([cancellation, AbortSignal.timeout(180_000)]) : AbortSignal.timeout(180_000); - signal.throwIfAborted(); + cancellation?.throwIfAborted(); if (!version.packageSnapshotId) { const [row] = await db.select({ ...skillVersionMetadataColumns, files: companySkillVersions.fileInventory }).from(companySkillVersions).where(and( eq(companySkillVersions.companyId, version.companyId), eq(companySkillVersions.id, version.id))); - if (row?.packageSnapshotId) return versionFiles(row, allowRecovery, signal); + if (row?.packageSnapshotId) return versionFiles(row, allowRecovery, cancellation); return row?.files ?? []; } const id = version.packageSnapshotId; - const manifest = await manifestFor(await descriptor(version.companyId, id), signal); - const read = async (root: string) => { + const manifest = await manifestFor(await descriptor(version.companyId, id), cancellation); + const read = async (root: string, signal: AbortSignal) => { const byPath = new Map(manifest.files.map(file => [file.path, file])); const result: CompanySkillVersionFileInventoryEntry[] = []; for (const mapping of version.packageFileMap ?? manifest.files.map(file => ({ ...file, sourcePath: file.path }))) { @@ -656,15 +658,15 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach // Verify bytes as they are read, without holding the warm preparation lock. // A descriptor survives eviction; a missing/racing file falls back to storage. const root = skillPackagePaths(version.companyId, id).directory; - const result = await withPackageIo(() => read(root).catch(() => null), signal, inventoryIo); + const result = await withPackageIo(signal => read(root, signal).catch(() => null), cancellation, inventoryIo, PACKAGE_IO_DEADLINE_MS); if (result) { touchSkillPackage(root); return result; } - signal.throwIfAborted(); + cancellation?.throwIfAborted(); const acquire = async () => { - const cached = await withPackageIo(() => read(root).catch(() => null), signal, inventoryIo); - return cached ?? withIsolatedPackage(version.companyId, id, read, allowRecovery, signal, true); + const cached = await withPackageIo(signal => read(root, signal).catch(() => null), cancellation, inventoryIo, PACKAGE_IO_DEADLINE_MS); + return cached ?? withIsolatedPackage(version.companyId, id, (root, _manifest, signal) => read(root, signal), allowRecovery, cancellation, true); }; return cancellation ? acquire() : flight(db, `version-read:${version.companyId}:${version.id}:${allowRecovery}`, acquire); } @@ -689,8 +691,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach const entry = manifest.files.find(file => file.path === (mapping?.sourcePath ?? relativePath)); if (!entry) return undefined; assertSkillPackageFileSize(entry.size, maxBytes); - const signal = AbortSignal.timeout(180_000); - const read = async (root: string) => { + const read = async (root: string, signal: AbortSignal) => { const bytes = await readPackageFile(root, entry, signal); const encoding = mapping?.encoding ?? entry.encoding; return { path: relativePath, kind: mapping?.kind ?? entry.kind, content: bytes.toString(encoding), @@ -698,13 +699,13 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach }; // Immutable cache files can be read without the preparation lock. An open // descriptor survives eviction; missing/racing files fall back to storage. - const cached = await withPackageIo(() => read(skillPackagePaths(version.companyId, id).directory).catch(() => null), signal, inventoryIo); + const directory = skillPackagePaths(version.companyId, id).directory; + const cached = await withPackageIo(signal => read(directory, signal).catch(() => null), undefined, inventoryIo, PACKAGE_IO_DEADLINE_MS); if (cached) return cached; - signal.throwIfAborted(); return flight(db, `file-read:${version.companyId}:${version.id}:${relativePath}:${allowRecovery}`, async () => { - const cached = await withPackageIo(() => read(skillPackagePaths(version.companyId, id).directory).catch(() => null), signal, inventoryIo); - return cached ?? withIsolatedPackage(version.companyId, id, read, allowRecovery, signal, true); + const cached = await withPackageIo(signal => read(directory, signal).catch(() => null), undefined, inventoryIo, PACKAGE_IO_DEADLINE_MS); + return cached ?? withIsolatedPackage(version.companyId, id, (root, _manifest, signal) => read(root, signal), allowRecovery, undefined, true); }); } async function versionInventory(version: StoredSkillVersion): Promise> {