diff --git a/server/src/__tests__/company-skills-runtime-concurrency.test.ts b/server/src/__tests__/company-skills-runtime-concurrency.test.ts index db6b464e4f8..121480f9b96 100644 --- a/server/src/__tests__/company-skills-runtime-concurrency.test.ts +++ b/server/src/__tests__/company-skills-runtime-concurrency.test.ts @@ -1,13 +1,15 @@ import { randomUUID } from "node:crypto"; +import { AsyncLocalStorage } from "node:async_hooks"; import { promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, companies, companyMemberships, companySkills, companySkillSources, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, +import { agents, companies, companyMemberships, companySkills, companySkillSources, companySkillVersions, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, projectAccessMembers, projects, projectSkillSources } from "@paperclipai/db"; -import { and, eq } from "drizzle-orm"; +import { and, eq, isNotNull } from "drizzle-orm"; +import { PgDialect } from "drizzle-orm/pg-core"; import { PAPERCLIP_FEEDBACK_SKILL_KEYS, PAPERCLIP_OPERATIONAL_SKILL_KEY } from "@paperclipai/adapter-utils/server-utils"; -import { companySkillService } from "../services/company-skills.js"; +import { companySkillService, ONBOARDING_FIRST_TASK_SKILL_KEY, PAPERCLIP_CORE_SKILL_KEYS } from "../services/company-skills.js"; import { withSkillActor } from "../services/skill-access.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -35,6 +37,21 @@ describeDatabase("concurrent runtime skill preparation", () => { if (home) await fs.rm(home, { recursive: true, force: true }); }); + function observeTransactionStatements(observe: (query: { sql: string; params: unknown[] }) => void) { + const transaction = db.transaction.bind(db); + const dialect = new PgDialect(); + return vi.spyOn(db, "transaction").mockImplementation((action, config) => transaction(async tx => { + const execute = tx.execute.bind(tx); + const spy = vi.spyOn(tx, "execute").mockImplementation(query => { + const result = execute(query); + observe(typeof query === "string" ? { sql: query, params: [] } : dialect.sqlToQuery(query.getSQL())); + return result; + }); + try { return await action(tx); } + finally { spy.mockRestore(); } + }, config)); + } + it("shares an in-flight inventory refresh across service instances before snapshot locking", async () => { const companyId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Concurrent skill readers", issuePrefix: `SC${companyId.slice(0, 6)}` }); @@ -77,4 +94,133 @@ describeDatabase("concurrent runtime skill preparation", () => { await db.delete(projectAccessMembers).where(and(eq(projectAccessMembers.projectId, project!.id), eq(projectAccessMembers.subjectId, readers[0]!.id))); expect(await read(readers[0]!.id)).toEqual([]); }); + + it.each(["commit", "rollback"] as const)("resolves first-agent skills while a competing installer will %s", async outcome => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "First-agent skill race", issuePrefix: `ST${companyId.slice(0, 6)}` }); + await companySkillService(db).listFull(companyId); + await db.delete(companySkills).where(eq(companySkills.companyId, companyId)); + const previousStorage = process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED; + process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED = "false"; + const operation = new AsyncLocalStorage<"install" | "assign">(); + const installing = Promise.withResolvers(); + const continueInstall = Promise.withResolvers(); + const installerReady = Promise.withResolvers(); + const publicationAttempt = Promise.withResolvers(); + const finishTransaction = Promise.withResolvers(); + const rollback = new Error("Roll back the competing installation"); + const readFile = fs.readFile.bind(fs); + let paused = false; + let publicationAttempted = false; + const transaction = observeTransactionStatements(query => { + if (operation.getStore() === "assign" && query.sql.includes("pg_advisory_xact_lock") + && query.params.includes(`${companyId}:agentmail`)) { + publicationAttempted = true; + publicationAttempt.resolve(); + } + }); + const read = vi.spyOn(fs, "readFile").mockImplementation(async (file, options) => { + if (String(file).endsWith("/first-task/SKILL.md")) { + if (operation.getStore() === "assign") await installerReady.promise; + if (operation.getStore() === "install" && !paused) { + paused = true; + installing.resolve(); + await continueInstall.promise; + } + } + return readFile(file, options); + }); + const installation = operation.run("install", () => db.transaction(async tx => { + await companySkillService(tx as unknown as typeof db).listFull(companyId); + installerReady.resolve(); + await finishTransaction.promise; + if (outcome === "rollback") throw rollback; + })).catch(error => { + if (error !== rollback) throw error; + }); + let assignment: Promise | undefined; + try { + await installing.promise; + const requested = [...PAPERCLIP_CORE_SKILL_KEYS, ONBOARDING_FIRST_TASK_SKILL_KEY]; + assignment = operation.run("assign", () => companySkillService(db).resolveRequestedSkillEntries(companyId, requested)) + .then(value => ({ value }), error => ({ error })); + continueInstall.resolve(); + await Promise.race([assignment, publicationAttempt.promise]); + finishTransaction.resolve(); + await installation; + expect(await assignment).toEqual({ value: { + resolved: requested.map(key => ({ key, versionId: null })), unresolved: [], + } }); + expect(publicationAttempted).toBe(true); + const installed = await db.select({ key: companySkills.key }).from(companySkills).where(eq(companySkills.companyId, companyId)); + for (const key of requested) expect(installed.filter(skill => skill.key === key)).toHaveLength(1); + } finally { + continueInstall.resolve(); + finishTransaction.resolve(); + await Promise.allSettled([installation, assignment]); + read.mockRestore(); + transaction.mockRestore(); + if (previousStorage === undefined) delete process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED; + else process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED = previousStorage; + } + }, 30_000); + + it.each([false, true])("rechecks a missing release after its competing installer commits (corrupt=%s)", async corrupt => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Concurrent release setup", issuePrefix: `SR${companyId.slice(0, 6)}` }); + const initial = await companySkillService(db).listFull(companyId); + const skill = initial.find(entry => entry.key === PAPERCLIP_OPERATIONAL_SKILL_KEY)!; + const [release] = await db.select().from(companySkillVersions).where(and( + eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skill.id), + isNotNull(companySkillVersions.releaseId))).limit(1); + expect(release?.releaseId).toBeTruthy(); + await db.delete(companySkillVersions).where(eq(companySkillVersions.id, release!.id)); + const installerReady = Promise.withResolvers(); + const finishTransaction = Promise.withResolvers(); + const publicationAttempt = Promise.withResolvers(); + const operation = new AsyncLocalStorage<"install" | "read">(); + let publicationAttempted = false; + const transaction = observeTransactionStatements(query => { + if (operation.getStore() === "read" && query.sql.includes("for update") && query.params.includes(skill.id)) { + publicationAttempted = true; + publicationAttempt.resolve(); + } + }); + const installation = operation.run("install", () => db.transaction(async tx => { + await companySkillService(tx as unknown as typeof db).listFull(companyId); + if (corrupt) await tx.update(companySkillVersions).set({ fileInventory: [{ + path: "SKILL.md", kind: "skill", content: "Corrupted release snapshot", + }] }).where(and(eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.releaseId, release!.releaseId!))); + installerReady.resolve(); + await finishTransaction.promise; + })); + let reading: Promise<{ value?: typeof initial; error?: unknown }> | undefined; + try { + await installerReady.promise; + reading = operation.run("read", () => companySkillService(db).listFull(companyId)) + .then(value => ({ value }), error => ({ error })); + await Promise.race([reading, publicationAttempt.promise]); + finishTransaction.resolve(); + await installation; + const result = await reading; + if (corrupt) expect(result).toMatchObject({ error: { + message: `Bundled skill release ${release!.releaseId} does not match its seeded snapshot.`, + } }); + else { + expect(result.error).toBeUndefined(); + expect(result.value?.map(entry => ({ key: entry.key, currentVersionId: entry.currentVersionId }))) + .toEqual(initial.map(entry => ({ key: entry.key, currentVersionId: entry.currentVersionId }))); + } + expect(publicationAttempted).toBe(true); + const versions = await db.select().from(companySkillVersions).where(and( + eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.releaseId, release!.releaseId!))); + expect(versions).toHaveLength(1); + expect(versions[0]!.fileInventory).toEqual(corrupt + ? [{ path: "SKILL.md", kind: "skill", content: "Corrupted release snapshot" }] : release!.fileInventory); + } finally { + finishTransaction.resolve(); + await Promise.allSettled([installation, reading]); + transaction.mockRestore(); + } + }, 30_000); }); diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts index d94bd419018..3f10ab7b36a 100644 --- a/server/src/services/company-skills.ts +++ b/server/src/services/company-skills.ts @@ -464,7 +464,7 @@ type RuntimeSkillSourceResolution = | { status: "available"; source: string } | { status: "missing"; source: string; detail: string }; -const skillInventoryRefreshPromises = new Map>(); +const skillInventoryRefreshPromises = new WeakMap>>(); function selectCompanySkillColumns() { return { @@ -617,6 +617,16 @@ function buildInventoryContentHash(entries: Array<{ path: string; sha256: string return `sha256:${sha256Buffer(Buffer.from(JSON.stringify(hashInput)))}`; } +function bundledSkillReleaseInventoryHash(inventory: CompanySkillVersionFileInventoryEntry[]) { + return buildInventoryContentHash(inventory.map(entry => ({ path: entry.path, sha256: sha256Buffer(entry.content) }))); +} + +function assertBundledSkillReleaseInventory(releaseId: string, expectedHash: string, existing: CompanySkillVersionRow) { + if (bundledSkillReleaseInventoryHash(toCompanySkillVersion(existing).fileInventory) !== expectedHash) { + throw new Error(`Bundled skill release ${releaseId} does not match its seeded snapshot.`); + } +} + function uniqueSkillSlug(baseSlug: string, usedSlugs: Set) { if (!usedSlugs.has(baseSlug)) return baseSlug; let attempt = 2; @@ -3153,21 +3163,10 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo const fileInventory = serializeVersionFileInventory( await collectVersionFileInventoryFromDirectory(release.releaseDir), ); - const registryHash = buildInventoryContentHash(fileInventory.map((entry) => ({ - path: entry.path, - sha256: sha256Buffer(entry.content), - }))); + const registryHash = bundledSkillReleaseInventoryHash(fileInventory); if (await verifyExistingBundledSkillRelease({ db, companyId, skillId: paperclipSkill.id, releaseId: release.id, - expectedInventoryHash: registryHash, validateInventory: existing => { - const existingInventory = toCompanySkillVersion(existing).fileInventory; - const existingHash = buildInventoryContentHash(existingInventory.map((entry) => ({ - path: entry.path, - sha256: sha256Buffer(entry.content), - }))); - if (existingHash !== registryHash) { - throw new Error(`Bundled skill release ${release.id} does not match its seeded snapshot.`); - } - }, + expectedInventoryHash: registryHash, + validateInventory: existing => assertBundledSkillReleaseInventory(release.id, registryHash, existing), })) continue; const releasedAt = new Date(release.releasedAt); if (Number.isNaN(releasedAt.getTime())) { @@ -3299,7 +3298,12 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo async function ensureSkillInventoryCurrent(companyId: string) { // Denied reads must not perform the lazy bundled-skill reconciliation. if (!visibility().canReadCompany(companyId)) return; - const existingRefresh = skillInventoryRefreshPromises.get(companyId); + let refreshes = skillInventoryRefreshPromises.get(db); + if (!refreshes) { + refreshes = new Map(); + skillInventoryRefreshPromises.set(db, refreshes); + } + const existingRefresh = refreshes.get(companyId); if (existingRefresh) { await measureRunPhase("skills.inventory.wait", () => existingRefresh); return; @@ -3320,12 +3324,12 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo await measureRunPhase("skills.inventory.local_sources", () => reconcileLocalPathSkillSources(companyId)); })(); - skillInventoryRefreshPromises.set(companyId, refreshPromise); + refreshes.set(companyId, refreshPromise); try { await refreshPromise; } finally { - if (skillInventoryRefreshPromises.get(companyId) === refreshPromise) { - skillInventoryRefreshPromises.delete(companyId); + if (refreshes.get(companyId) === refreshPromise) { + refreshes.delete(companyId); } } } @@ -3864,6 +3868,15 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo and ${companySkills.companyId} = ${companyId} for update `); + if (options.release) { + const [existing] = await tx.select().from(companySkillVersions).where(and( + eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skillId), + eq(companySkillVersions.releaseId, options.release.id))).limit(1); + if (existing) { + assertBundledSkillReleaseInventory(options.release.id, bundledSkillReleaseInventoryHash(fileInventory), existing); + return existing; + } + } // File edits already own the skill lock when a dedicated connection saves // their package. Never hold a package lock while waiting for that skill. if (packageSnapshotId) { @@ -6519,15 +6532,25 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo ? await collectVersionFileInventoryFromDirectory(normalizeSourceLocatorDirectory(skill.sourceLocator)!) : undefined); if (files) { const candidate = await managedContent.prepare(companyId, files); - const saved = existing - ? await managedContent.publish(existing, candidate, values, { type: "system" }, { - ...options.publication, reuseCurrentVersion: true, validate: async tx => { - await visibility(tx).assertSkill(companyId, existing.id); - await options.publication?.validate?.(tx); - }, + const publish = (database: DbOrTransaction, base: CompanySkill | null) => { + const content = database === db ? managedContent : managedSkillContent(database as Db, packageDb); + return base + ? content.publish(base, candidate, values, { type: "system" }, { + ...options.publication, reuseCurrentVersion: true, validate: async tx => { + await visibility(tx).assertSkill(companyId, base.id); + await options.publication?.validate?.(tx); + }, + }) + : content.create(values, candidate, { type: "system" }, options.publication); + }; + const saved = !existing && incomingKind === "paperclip_bundled" + ? await database.transaction(async tx => { + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${companyId}:${skill.slug}`}, 0))`); + const concurrent = await getByKey(companyId, skill.key, tx, options); + return concurrent?.currentVersionId ? concurrent : toCompanySkill((await publish(tx, concurrent)).skill); }) - : await managedContent.create(values, candidate, { type: "system" }, options.publication); - out.push(toCompanySkill(saved.skill)); + : toCompanySkill((await publish(database, existing)).skill); + out.push(saved); continue; } if (existing && importedSkillPersistValuesMatchExisting(existing, values)) {