From bad22d99b15a40fff8d525d8cb29dbe363b69c62 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 17:40:34 -0500 Subject: [PATCH] fix(server): scope secret expiry to committed company changes Preserve saved deadlines, bounded company expiry, independent retry backoffs, and deletion invalidation. Move shared deadline dispatch earlier in the stack so expiry and later workers use one owner. Co-Authored-By: Paperclip --- doc/idle-secret-proposal-expiry.md | 45 ++++-- .../src/__tests__/company-work-batch.test.ts | 29 ++++ .../delivery-work-coordinator.test.ts | 52 +++++++ .../__tests__/scoped-deadline-work.test.ts | 39 +++++ .../__tests__/secret-proposals-routes.test.ts | 141 +++++++++++++++++- server/src/services/company-deletion.ts | 1 + server/src/services/company-work-batch.ts | 28 ++++ .../src/services/delivery-work-coordinator.ts | 16 +- .../src/services/issue-thread-interactions.ts | 4 +- server/src/services/scoped-deadline-work.ts | 99 ++++++++++++ .../services/secret-proposal-expiry-work.ts | 28 ++-- server/src/services/secret-proposals.ts | 26 +++- 12 files changed, 469 insertions(+), 39 deletions(-) create mode 100644 server/src/__tests__/company-work-batch.test.ts create mode 100644 server/src/__tests__/scoped-deadline-work.test.ts create mode 100644 server/src/services/company-work-batch.ts create mode 100644 server/src/services/scoped-deadline-work.ts diff --git a/doc/idle-secret-proposal-expiry.md b/doc/idle-secret-proposal-expiry.md index a9ca93c11bb..a66747421fb 100644 --- a/doc/idle-secret-proposal-expiry.md +++ b/doc/idle-secret-proposal-expiry.md @@ -7,7 +7,10 @@ values. This worker uses those records; it adds no queue table or migration. `secret-proposals.ts` still owns quotas, authority checks, approval, expiry, ciphertext scrubbing, dependent binding rejection, audit records, and interaction -reflection. `nextExpiryAt()` returns the earliest pending proposal expiry. +reflection. `expiryDeadlines(companyId?)` returns one saved deadline per pending +company. Normal write notifications reload only the affected company. Startup +reconstruction loads all companies once. The manual `nextExpiryAt()` query remains +available to existing callers. Terminal history does not create a deadline. Approval still rejects an expired proposal synchronously, even when maintenance is paused. @@ -19,9 +22,10 @@ writes in the owning transaction: - `transition`: rejection, withdrawal, expiry, and dependent binding rejection. - Interaction resolution: rejection, withdrawal/cancellation, expiry, and failed acceptance execution that resolves a linked pending binding. +- Company deletion: a company hint removes its cached deadline after deletion commits. -The remaining proposal write only attaches an interaction ID and does not change -expiry eligibility. Company deletion removes obligations. Independent SQL writers +Each producer includes its company ID. The remaining proposal write only attaches +an interaction ID and does not change expiry eligibility. Independent SQL writers or another DB root are not supported live producers of these process-local signals; startup reconstructs their persisted rows, but it is not a live replica contract. @@ -35,17 +39,26 @@ existing protocol. Callers do not pass recovery counters or reconnect the databa is enabled. It replaces the secret-proposal sweep in the aggregate maintenance tick. Disabled heartbeat scheduling keeps its existing behavior. -The worker reconciles committed changes and registers the earliest saved expiry. -A failed pass or an overdue batch retries after 30 seconds. Each pass retains the -existing bounded 100-row sweep. Completed batches publish their changes; further -overdue rows retain a deadline until drained. Own writes are coalesced to avoid -an immediate self-triggering scan loop. No pending proposal, unresolved write, or -failed reconciliation means no recurring query. +The worker reloads the affected company's saved minimum expiry after a committed +change. It does not sweep future work. At a due deadline it sweeps at most 100 +expired proposals for that company, then reads that company's next deadline. +Companies rotate fairly between bounded passes. Retained history creates no work. +No pending proposal, unresolved write, or failed reconciliation means no recurring +query. Unscoped legacy hints still reconstruct all companies. -`deadline-work.ts` shares only generation tracking, bounded re-entry, and scheduler -registration with custom-image expiry. Each service supplies its own operation and -next deadline. Neither shared code nor startup wiring interprets secret proposals -or provider protocols. Custom-image expiry retains its existing behavior. +`scoped-deadline-work.ts` owns scope invalidation, cached deadlines, fair dispatch, +and failure backoff. It owns no SQL or proposal policy. Failed loads and failed +company sweeps back off independently from 30 seconds to five minutes. A new +write reloads that company without erasing its failed sweep's backoff. Other +companies keep their own deadlines, including already-due work. The coordinator's +optional `nextRunAtOnError` contract permits immediate eligible work only after +the worker has recorded per-item backoffs. Failed transaction reconciliation and +failed pending-state inspection retain the coordinator's normal retry. + +Secret expiry opts out of the shared helper's default one-second pass spacing so +newly learned short deadlines are not clamped. Other scoped consumers retain that +default. Custom-image expiry continues to use `deadline-work.ts` unchanged. No +shared scheduler or startup wiring interprets secret-proposal policy. A request stays pending until reconciliation succeeds. Changes arriving during a pass, first writes during drain, and failures followed by drain retain a request. @@ -60,7 +73,11 @@ and rollback, quiet empty and terminal states, quiet future deadlines, automatic ciphertext scrubbing and dependent-card resolution, startup reconstruction, withdrawal, interaction rejection/failed execution, failure retry, and drain/resume. It also verifies that expired approval fails while cleanup is paused. The existing -custom-image lifecycle suite checks the other consumer of the shared helper. +coordinator suite verifies fallback retry and uncertainty boundaries. New cases +record actual SQL to prove normal writes and due expiry stay company-scoped; they +also cover five-second deadlines, earlier replacement deadlines, company deletion, +and another company making progress while one sweep fails. A deterministic +shared-worker test covers a 250ms replacement deadline. The worker tests use a controlled clock and a real PostgreSQL database. Existing route tests cover quotas, isolation, authorization, concurrency, and lifecycle diff --git a/server/src/__tests__/company-work-batch.test.ts b/server/src/__tests__/company-work-batch.test.ts new file mode 100644 index 00000000000..9fe1abc5a1d --- /dev/null +++ b/server/src/__tests__/company-work-batch.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { takeCompanyWorkBatch } from "../services/company-work-batch.js"; + +describe("company work batch", () => { + it("shares capacity while preserving the owner's order within each company", () => { + const entries = [ + { companyId: "a", id: "a-oldest" }, { companyId: "a", id: "a-next" }, + { companyId: "a", id: "a-later" }, { companyId: "b", id: "b-due" }, + ]; + expect(takeCompanyWorkBatch(entries, 3)).toEqual({ + entries: [entries[0], entries[3], entries[1]], lastCompany: "a", + }); + }); + it("rotates between batches when more companies are due than fit in one batch", () => { + const entries = ["a", "b", "c", "d"].flatMap(companyId => [ + { companyId, id: `${companyId}-first` }, { companyId, id: `${companyId}-second` }, + ]); + const first = takeCompanyWorkBatch(entries, 2); + const remaining = entries.filter(entry => !first.entries.includes(entry)); + const second = takeCompanyWorkBatch(remaining, 2, first.lastCompany); + expect([...first.entries, ...second.entries].map(entry => entry.companyId)).toEqual(["a", "b", "c", "d"]); + expect(takeCompanyWorkBatch(remaining, 1, "z").entries[0].companyId).toBe("a"); + }); + it("finishes an empty or exhausted batch without inventing work", () => { + expect(takeCompanyWorkBatch([], 25, "gone")).toEqual({ entries: [], lastCompany: "gone" }); + const entry = { companyId: "only" }; + expect(takeCompanyWorkBatch([entry], 25).entries).toEqual([entry]); + }); +}); diff --git a/server/src/__tests__/delivery-work-coordinator.test.ts b/server/src/__tests__/delivery-work-coordinator.test.ts index 805aa3db4c4..2ec8054336f 100644 --- a/server/src/__tests__/delivery-work-coordinator.test.ts +++ b/server/src/__tests__/delivery-work-coordinator.test.ts @@ -59,6 +59,58 @@ describe("delivery work coordinator", () => { expect(s.onError).not.toHaveBeenCalled(); } finally { clock.mockRestore(); } }); + it("honors a future backlog deadline after failure while preserving the fallback retry", async () => { + const s = setup(), t = task(); + let next: number | null = Date.now() + 1000; + t.run.mockRejectedValueOnce(new Error("One item failed")); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAt: () => next }).ready; + expect(s.coordinator.nextWakeAt()).toBe(next); + expect(s.onError).toHaveBeenCalledOnce(); + next = null; + await vi.advanceTimersByTimeAsync(1000); + expect(t.run).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); + it("dispatches another due item after a worker records scoped failure backoffs", async () => { + const s = setup(), t = task(), now = Date.now(); + t.run.mockRejectedValueOnce(new Error("One scoped item failed")); + const nextRunAtOnError = vi.fn(() => now); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAtOnError }).ready; + expect(nextRunAtOnError).toHaveBeenCalledOnce(); + expect(s.coordinator.nextWakeAt()).toBe(now); + await vi.advanceTimersByTimeAsync(1); + expect(t.run).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); + it.each(["reconcile", "pending"])("does not consume scoped retry deadlines for a %s failure", async mode => { + const s = setup(), t = task(), now = Date.now(); + if (mode === "reconcile") { + s.failCommit(); + await expect(s.enqueue()).rejects.toThrow("lost commit reply"); + s.execute.mockRejectedValueOnce(new Error("Database unavailable")); + } else t.hasPending.mockRejectedValueOnce(new Error("Pending state unavailable")); + const nextRunAtOnError = vi.fn(() => now); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAtOnError }).ready; + expect(nextRunAtOnError).not.toHaveBeenCalled(); + expect(s.coordinator.nextWakeAt()).toBe(now + 5000); + expect(s.onError).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(4999); + expect(s.onError).toHaveBeenCalledOnce(); + }); + it.each(["overdue", "later", "unreadable", "draining"])("keeps failure backoff for a %s deadline", async mode => { + const s = setup(), t = task(), now = Date.now(); + t.run.mockImplementation(async () => { + if (mode === "draining") { s.canRun.mockReturnValue(false); s.canReconcile.mockReturnValue(true); } + throw new Error("Unavailable"); + }); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAt: () => { + if (mode === "unreadable") throw new Error("Deadline unavailable"); + return mode === "overdue" ? now : now + (mode === "later" ? 60_000 : 1000); + } }).ready; + expect(s.coordinator.nextWakeAt()).toBe(now + 5000); + await vi.advanceTimersByTimeAsync(4999); + expect(t.run).toHaveBeenCalledOnce(); + }); it("schedules maintenance without holding idle intent, and lets new work preempt it", async () => { const s = setup(), t = task(); let next: number | null = Date.now() + 60_000; diff --git a/server/src/__tests__/scoped-deadline-work.test.ts b/server/src/__tests__/scoped-deadline-work.test.ts new file mode 100644 index 00000000000..fda914dd13e --- /dev/null +++ b/server/src/__tests__/scoped-deadline-work.test.ts @@ -0,0 +1,39 @@ +import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; +import { afterEach, expect, it, vi } from "vitest"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { registerScopedDeadlineWork } from "../services/scoped-deadline-work.js"; + +let coordinator: ReturnType | undefined; +afterEach(async () => { await coordinator?.stop(); vi.useRealTimers(); }); + +it("preserves a subsecond replacement deadline when the owner does not require pass spacing", async () => { + vi.useFakeTimers(); + const onError = vi.fn(); + const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []) }); + coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError }); + const now = Date.now(); + let dueAt = now + 60_000; + const check = vi.fn(async () => null); + const worker = registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.secretProposalExpiry, + minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async () => [{ id: "company", companyId: "company", dueAt }], + check, + }, () => true); + await worker.ready; + dueAt = now + 250; + worker.invalidate("company"); + await vi.advanceTimersByTimeAsync(1); + expect(coordinator.nextWakeAt()).toBe(dueAt); + await vi.advanceTimersByTimeAsync(248); + expect(check).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(check).toHaveBeenCalledOnce(); + expect(coordinator.nextWakeAt()).toBeNull(); + await vi.advanceTimersByTimeAsync(60_000); + expect(check).toHaveBeenCalledOnce(); + expect(onError).not.toHaveBeenCalled(); +}); diff --git a/server/src/__tests__/secret-proposals-routes.test.ts b/server/src/__tests__/secret-proposals-routes.test.ts index 5d24de6dbb2..935fdb84f89 100644 --- a/server/src/__tests__/secret-proposals-routes.test.ts +++ b/server/src/__tests__/secret-proposals-routes.test.ts @@ -1,5 +1,6 @@ import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { registerSecretProposalExpiryWork } from "../services/secret-proposal-expiry-work.js"; +import { deleteCompany } from "../services/company-deletion.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; import { randomUUID } from "node:crypto"; @@ -87,8 +88,7 @@ describeEmbeddedPostgres("secret proposal routes", () => { rmSync(secretsTmpDir, { recursive: true, force: true }); }); - async function seedRun() { - const companyId = randomUUID(); + async function seedRun(identifier = "SEC-1", companyId = randomUUID()) { const agentId = randomUUID(); const heartbeatRunId = randomUUID(); const issueId = randomUUID(); @@ -120,7 +120,7 @@ describeEmbeddedPostgres("secret proposal routes", () => { id: issueId, companyId, title: "Needs credential", - identifier: "SEC-1", + identifier, status: "in_progress", responsibleUserId: "user-1", executionRunId: heartbeatRunId, @@ -275,6 +275,135 @@ describeEmbeddedPostgres("secret proposal routes", () => { bindingTargetPolicy: "self_and_reports", }); + async function createWithExpiry(expiresAt: Date) { + return db.transaction(async tx => { + const proposal = await create(createSecretProposalsService(tx as unknown as typeof db)); + const [updated] = await tx.update(companySecretProposals).set({ expiresAt }) + .where(eq(companySecretProposals.id, proposal.id)).returning(); + return updated; + }); + } + + it("honors a saved five-second expiry without clamping it to recovery spacing", async () => { + const delay = 5000; + await start(); await quiet(); + const expiresAt = new Date(Date.now() + delay); + const proposal = await createWithExpiry(expiresAt); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(expiresAt.getTime()); + await settle(delay / 2); + expect(await proposals.getById(fixture.companyId, proposal.id)).toMatchObject({ status: "pending" }); + await settle(delay); + expect(await proposals.getById(fixture.companyId, proposal.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + await quiet(); + }); + + it("moves to an earlier committed proposal deadline without losing the later one", async () => { + await start(); await quiet(); + const later = await createWithExpiry(new Date(Date.now() + 120_000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt.getTime()); + const earlier = await createWithExpiry(new Date(Date.now() + 5000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt.getTime()); + await settle(6000); + expect(await proposals.getById(fixture.companyId, earlier.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(fixture.companyId, later.id)).toMatchObject({ status: "pending" }); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt.getTime()); + await settle(120_000); await quiet(); + }); + + it("keeps sequential tenant writes from scanning another company's proposals", async () => { + const other = await seedRun("OTHER-1"); + const foreign = await proposals.createSecret({ ...other, registerForRedaction: () => {} }, { + name: "dev/other/secret", value: "other-expiry-only", justification: "Another company's deadline", + }); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"company_secret_proposals"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { + for (let i = 0; i < 3; i++) { await create(); await settle(1000); } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"company_secret_proposals"."company_id" ='); + expect(read.params).toContain(fixture.companyId); + expect(read.params).not.toContain(other.companyId); + } + expect(await proposals.getById(other.companyId, foreign.id)).toMatchObject({ status: "pending", valueCiphertext: foreign.valueCiphertext }); + }); + + it("expires only the company whose saved deadline is due", async () => { + const other = await seedRun("OTHER-1"); + const foreign = await proposals.createSecret({ ...other, registerForRedaction: () => {} }, { + name: "dev/other/secret", value: "other-expiry-only", justification: "Another company's deadline", + }); + const due = await createWithExpiry(new Date(Date.now() + 5000)); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"company_secret_proposals"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { await settle(6000); } finally { db.$client.options.debug = debug; } + expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true); + for (const read of reads) { + expect(read.query).toContain('"company_secret_proposals"."company_id" ='); + expect(read.params).toContain(fixture.companyId); + expect(read.params).not.toContain(other.companyId); + } + expect(await proposals.getById(fixture.companyId, due.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(other.companyId, foreign.id)).toMatchObject({ status: "pending", valueCiphertext: foreign.valueCiphertext }); + expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt.getTime()); + }); + + it.each([0, 3000])("keeps a failed company on backoff while another company expires on time (offset %s)", async offset => { + // Make the failing company first in the fair dispatch order. + const other = await seedRun("OTHER-1", "ffffffff-ffff-ffff-ffff-ffffffffffff"); + const failing = await createWithExpiry(new Date(Date.now() + 5000)); + const healthy = await db.transaction(async tx => { + const proposal = await createSecretProposalsService(tx as unknown as typeof db).createSecret( + { ...other, registerForRedaction: () => {} }, + { name: "dev/other/secret", value: "other-expiry-only", justification: "Independent expiry" }); + const [saved] = await tx.update(companySecretProposals).set({ expiresAt: new Date(failing.expiresAt.getTime() + offset) }) + .where(eq(companySecretProposals.id, proposal.id)).returning(); + return saved; + }); + const sweep = proposals.sweepExpiredForCompany; + let unavailable = true; + const attempts = vi.spyOn(proposals, "sweepExpiredForCompany").mockImplementation(async companyId => { + if (unavailable && companyId === fixture.companyId) throw new Error("company expiry unavailable"); + return sweep(companyId); + }); + await start(); await settle(10_000); + expect(errors).toHaveLength(1); errors.length = 0; + expect(await proposals.getById(other.companyId, healthy.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(fixture.companyId, failing.id)).toMatchObject({ status: "pending" }); + // A new write must refresh this company without erasing its failed sweep's backoff. + await create(); await settle(1000); + expect(attempts.mock.calls.filter(([id]) => id === fixture.companyId)).toHaveLength(1); + unavailable = false; await settle(30_000); + expect(await proposals.getById(fixture.companyId, failing.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + await settle(expiryMs); await quiet(); + }); + + it("removes the cached expiry when the company deletion owner commits", async () => { + await create(); await start(); await settle(1); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.heartbeatRunId)); + await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, fixture.issueId)); + // The deletion fixture has no live resources; its agent has already + // finished termination before entering the company deletion transaction. + await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }) + .where(eq(agents.id, fixture.agentId)); + expect(await deleteCompany(db, fixture.companyId)).toMatchObject({ id: fixture.companyId }); + await quiet(); + expect(await proposals.expiryDeadlines()).toEqual([]); + }); + it("stays quiet until the real proposal deadline, scrubs ciphertext, and leaves terminal history quiet", async () => { await start(); await quiet(); const secret = await create(); @@ -321,8 +450,8 @@ describeEmbeddedPostgres("secret proposal routes", () => { let release!: () => void, reading!: () => void; const gate = new Promise(resolve => { release = resolve; }); const entered = new Promise(resolve => { reading = resolve; }); - const readDeadline = proposals.nextExpiryAt; - vi.spyOn(proposals, "nextExpiryAt").mockImplementationOnce(async () => { + const readDeadline = proposals.expiryDeadlines; + vi.spyOn(proposals, "expiryDeadlines").mockImplementationOnce(async () => { const stale = await readDeadline(); reading(); await gate; return stale; @@ -352,7 +481,7 @@ describeEmbeddedPostgres("secret proposal routes", () => { if (mode === "first_write") { await quiet(); draining = true; } const secret = await create(); if (mode === "failed_pass") { - vi.spyOn(proposals, "sweepExpired").mockRejectedValueOnce(new Error("database unavailable")); + vi.spyOn(proposals, "expiryDeadlines").mockRejectedValueOnce(new Error("database unavailable")); await vi.advanceTimersByTimeAsync(30_000); await vi.waitFor(() => expect(errors).toHaveLength(1)); errors.length = 0; draining = true; diff --git a/server/src/services/company-deletion.ts b/server/src/services/company-deletion.ts index 432cad76e7a..7e4a41a95d7 100644 --- a/server/src/services/company-deletion.ts +++ b/server/src/services/company-deletion.ts @@ -61,6 +61,7 @@ export async function deleteCompany(db: Db, id: string) { .where(eq(companies.id, id)).for("no key update"); if (!existing) return null; await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id); await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id); // Finance can reference costs and both can reference runs. Incidents // reference policies and approvals; delete these dependents first. diff --git a/server/src/services/company-work-batch.ts b/server/src/services/company-work-batch.ts new file mode 100644 index 00000000000..f83d2dcd5a5 --- /dev/null +++ b/server/src/services/company-work-batch.ts @@ -0,0 +1,28 @@ +export function takeCompanyWorkBatch( + ordered: readonly T[], + limit: number, + afterCompany: string | null = null, +): { entries: T[]; lastCompany: string | null } { + const grouped = new Map(); + for (const entry of ordered) { + const group = grouped.get(entry.companyId); + if (group) group.push(entry); else grouped.set(entry.companyId, [entry]); + } + const companies = [...grouped.keys()].sort(); + const next = afterCompany === null ? 0 : companies.findIndex(id => id > afterCompany); + const start = next < 0 ? 0 : next; + const rotation = [...companies.slice(start), ...companies.slice(0, start)]; + const entries: T[] = []; + let lastCompany = afterCompany; + for (let round = 0; entries.length < limit; round++) { + let added = false; + for (const companyId of rotation) { + const entry = grouped.get(companyId)![round]; + if (!entry) continue; + entries.push(entry); lastCompany = companyId; added = true; + if (entries.length === limit) break; + } + if (!added) break; + } + return { entries, lastCompany }; +} diff --git a/server/src/services/delivery-work-coordinator.ts b/server/src/services/delivery-work-coordinator.ts index 0284e06aba2..0d1a88c9f59 100644 --- a/server/src/services/delivery-work-coordinator.ts +++ b/server/src/services/delivery-work-coordinator.ts @@ -26,6 +26,9 @@ export function createDeliveryWorkCoordinator(input: { onSettled?: (hints?: ReadonlySet) => void; // Optional maintenance/retry deadline restored from durable state. nextRunAt?: () => number | null; + // Opt in only when run has recorded per-item failure backoffs. Other + // eligible items may already be due, unlike an unchanged failed deadline. + nextRunAtOnError?: () => number | null; // An empty queue's maintenance may wait until dispatch admission reopens. // Notifications and unresolved producer writes still reconcile in drain. pausePassiveMaintenance?: boolean; @@ -65,9 +68,10 @@ export function createDeliveryWorkCoordinator(input: { dirty = false; const finish = beginIdleTrackedWork(); const attempt = new AbortController(); + let runFailed = false; controller = attempt; running = Promise.resolve().then(() => reconcileDatabaseWork(input.owner, queue)) - .then(() => workerStopped || !(input.canRun() || (task.runDuringDrain && input.canReconcile?.())) ? undefined : task.run(attempt.signal)).then(() => workerStopped ? false : task.hasPending()).then(pending => { + .then(() => workerStopped || !(input.canRun() || (task.runDuringDrain && input.canReconcile?.())) ? undefined : task.run(attempt.signal).catch(error => { runFailed = true; throw error; })).then(() => workerStopped ? false : task.hasPending()).then(pending => { pendingWork = pending || databaseWorkPending(input.owner, queue); if (pendingWork) schedule(task.retryMs); else { finishIntent?.(); finishIntent = undefined; } @@ -78,9 +82,17 @@ export function createDeliveryWorkCoordinator(input: { } }).catch(error => { schedule(task.retryMs); + let failure = error; + try { + const scopedRetry = runFailed && task.nextRunAtOnError; + const next = input.canRun() ? (scopedRetry ? scopedRetry() : task.nextRunAt?.()) : null; + if (next != null && (scopedRetry || next > Date.now())) schedule(0, Math.max(Date.now(), next)); + } catch (deadlineError) { + failure = new AggregateError([error, deadlineError], "Delivery failure deadline could not be read"); + } // Logging must never turn a recoverable sweep failure into an // unhandled rejection or prevent other queues from running. - try { if (!workerStopped) input.onError(error, queue); } catch { /* Recovery remains scheduled. */ } + try { if (!workerStopped) input.onError(failure, queue); } catch { /* Recovery remains scheduled. */ } }).finally(() => { running = null; controller = null; diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index f43cd2839b9..88aafe43dc7 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -1159,7 +1159,7 @@ async function resolveLinkedSecretProposal( ) { const proposalId = linkedSecretProposalId(interaction); if (!proposalId) return; - await notifyDeliveryWork(db, DELIVERY_QUEUES.secretProposalExpiry); + await notifyDeliveryWork(db, DELIVERY_QUEUES.secretProposalExpiry, interaction.companyId); const [proposal] = await db .update(companySecretProposals) .set({ @@ -3169,7 +3169,7 @@ export function issueThreadInteractionService( : execution.status; if (executionStatus === "failed" && proposal.status === "pending") { const resolutionReason = `Interaction acceptance failed: ${execution.errorCode ?? "secret_proposal_execution_failed"}`; - await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, proposal.companyId); await tx .update(companySecretProposals) .set({ diff --git a/server/src/services/scoped-deadline-work.ts b/server/src/services/scoped-deadline-work.ts new file mode 100644 index 00000000000..6de9d3895da --- /dev/null +++ b/server/src/services/scoped-deadline-work.ts @@ -0,0 +1,99 @@ +import { takeCompanyWorkBatch } from "./company-work-batch.js"; +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import type { DeliveryQueue } from "./delivery-work-notifications.js"; + +type ScheduledEntry = { id: string; companyId: string; dueAt: number }; + +/** Coalesced scope reconstruction and fair deadline dispatch. Domain owners + * supply persistence, eligibility, and execution; this helper owns no SQL. */ +export function registerScopedDeadlineWork( + coordinator: ReturnType, + options: { + queue: DeliveryQueue; + batchSize?: number; + minimumPassIntervalMs?: number; + decodeScope(hint: string): Scope | undefined; + matches(entry: Entry, scope?: Scope): boolean; + load(scope?: Scope, signal?: AbortSignal): Promise; + check(entry: Entry, signal?: AbortSignal): Promise; + }, + canRun: () => boolean, +) { + const dirty = new Set(["*"]); + const entries = new Map(); + const failures = new Map(); + const scopeFailures = new Map(); + let earliest = 0; + let lastCompany: string | null = null; + function failed(map: typeof failures, id: string) { + const count = Math.min((map.get(id)?.count ?? 0) + 1, 5); + map.set(id, { count, retryAt: Date.now() + Math.min(300_000, 30_000 * 2 ** (count - 1)) }); + } + function dirtyScopes() { + return [...dirty].map(hint => { try { return options.decodeScope(hint); } catch { return undefined; } }); + } + function next() { + if (!canRun()) return dirty.size > 0 || entries.size > 0 ? Date.now() + 30_000 : null; + let nextAt: number | null = null; + const take = (at: number) => { nextAt = nextAt === null ? at : Math.min(nextAt, at); }; + for (const hint of dirty.has("*") ? ["*"] : dirty) take(Math.max(earliest, scopeFailures.get(hint)?.retryAt ?? 0)); + const unavailable = dirtyScopes(); + for (const entry of entries.values()) if (!unavailable.some(scope => options.matches(entry, scope))) + take(Math.max(earliest, entry.dueAt, failures.get(entry.id)?.retryAt ?? 0)); + return nextAt; + } + const worker = coordinator.register(options.queue, { + retryMs: 30_000, + pausePassiveMaintenance: true, + onSettled: hints => { for (const hint of hints ?? ["*"]) dirty.add(hint); }, + run: async signal => { + if (!canRun() || Date.now() < earliest) return; + earliest = Date.now() + (options.minimumPassIntervalMs ?? 1000); + const errors: unknown[] = []; + const requested = (dirty.has("*") ? ["*"] : [...dirty]).filter(hint => (scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now()); + const covered = requested.includes("*") ? [...dirty] : requested; + for (const hint of covered) dirty.delete(hint); + for (let index = 0; index < requested.length; index++) { + if (signal.aborted || !canRun()) { for (const hint of requested.includes("*") ? covered : requested.slice(index)) dirty.add(hint); return; } + const hint = requested[index]; + let scope: Scope | undefined; + let decoded = false; + try { + scope = options.decodeScope(hint); decoded = true; + const rows = await options.load(scope, signal), retained = new Set(rows.map(row => row.id)); + for (const entry of entries.values()) if (options.matches(entry, scope) && !retained.has(entry.id)) { + entries.delete(entry.id); failures.delete(entry.id); + } + for (const entry of rows) entries.set(entry.id, entry); + if (!scope) scopeFailures.clear(); else scopeFailures.delete(hint); + } catch (error) { + const retryHint = decoded ? hint : "*"; + dirty.add(retryHint); failed(scopeFailures, retryHint); errors.push(error); + } + } + const unavailable = dirtyScopes(); + const due = [...entries.values()].filter(entry => !unavailable.some(scope => options.matches(entry, scope)) + && Math.max(entry.dueAt, failures.get(entry.id)?.retryAt ?? 0) <= Date.now()) + .sort((a, b) => a.dueAt - b.dueAt || a.id.localeCompare(b.id)); + const batch = takeCompanyWorkBatch(due, options.batchSize ?? 25, lastCompany); lastCompany = batch.lastCompany; + for (const entry of batch.entries) { + if (signal.aborted || !canRun()) break; + try { + const current = await options.check(entry, signal); + if (current) entries.set(entry.id, current); else entries.delete(entry.id); + failures.delete(entry.id); + } catch (error) { failed(failures, entry.id); errors.push(error); } + } + if (errors.length) throw new AggregateError(errors, `${options.queue} could not settle`); + }, + // Retain scopes/deadlines for resume without retaining a settled write's + // idle hold during drain. The coordinator still fences unresolved XIDs. + hasPending: async () => canRun() && dirty.size > 0, + nextRunAt: next, + nextRunAtOnError: next, + }); + return { ...worker, invalidate(hint = "*") { + dirty.add(hint); + worker.wake(); + } }; +} diff --git a/server/src/services/secret-proposal-expiry-work.ts b/server/src/services/secret-proposal-expiry-work.ts index f4bf8d0f073..1a019047c92 100644 --- a/server/src/services/secret-proposal-expiry-work.ts +++ b/server/src/services/secret-proposal-expiry-work.ts @@ -1,21 +1,29 @@ import { logger } from "../middleware/logger.js"; import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; -import { registerDeadlineWork } from "./deadline-work.js"; +import { registerScopedDeadlineWork } from "./scoped-deadline-work.js"; import type { createSecretProposalsService } from "./secret-proposals.js"; export function registerSecretProposalExpiryWork( coordinator: ReturnType, - service: Pick, "sweepExpired" | "nextExpiryAt">, + service: Pick, "sweepExpiredForCompany" | "expiryDeadlines">, canRun: () => boolean, ) { - return registerDeadlineWork(coordinator, DELIVERY_QUEUES.secretProposalExpiry, { - retryMs: 30_000, - canRun, - run: async () => { - const expired = await service.sweepExpired(); - if (expired > 0) logger.warn({ expired }, "secret proposal expiry scrubbed proposals"); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.secretProposalExpiry, + batchSize: 1, + // Saved expiry deadlines are authoritative, including deadlines less than + // a second away. Only actual failures require a recovery backoff. + minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => (await service.expiryDeadlines(companyId)) + .map(row => ({ ...row, id: row.companyId })), + check: async entry => { + const expired = await service.sweepExpiredForCompany(entry.companyId); + if (expired > 0) logger.warn({ companyId: entry.companyId, expired }, "secret proposal expiry scrubbed proposals"); + const [next] = await service.expiryDeadlines(entry.companyId); + return next ? { ...next, id: next.companyId } : null; }, - next: () => service.nextExpiryAt(), - }); + }, canRun); } diff --git a/server/src/services/secret-proposals.ts b/server/src/services/secret-proposals.ts index e5efbbf7124..05f5af71d91 100644 --- a/server/src/services/secret-proposals.ts +++ b/server/src/services/secret-proposals.ts @@ -145,7 +145,7 @@ export function createSecretProposalsService(db: Db) { }); return { denial, value: null }; } - await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry); + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry, input.companyId); return { denial: null, value: await create(txDb) }; }); if (result.denial) throw unprocessable(result.denial.message); @@ -621,7 +621,7 @@ export function createSecretProposalsService(db: Db) { appliedBindingConfigPath?: string | null; }) { const now = new Date(); - await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry); + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry, proposal.companyId); const updated = await txDb.update(companySecretProposals).set({ status: "approved", resolvedByUserId: input.resolvedByUserId, @@ -797,7 +797,7 @@ export function createSecretProposalsService(db: Db) { const now = new Date(); return db.transaction(async (tx) => { const txDb = tx as unknown as Db; - await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, companyId); const updated = await tx.update(companySecretProposals).set({ status, resolvedByUserId: input.resolvedByUserId ?? null, @@ -872,10 +872,12 @@ export function createSecretProposalsService(db: Db) { limit = DEFAULT_EXPIRY_SWEEP_LIMIT, expireProposal: (companyId: string, proposalId: string) => Promise = (companyId, proposalId) => transition(companyId, proposalId, "expired", { reason: "Pending proposal expired" }), + companyId?: string, ) { const expired = await db.select({ id: companySecretProposals.id, companyId: companySecretProposals.companyId }) .from(companySecretProposals) - .where(and(eq(companySecretProposals.status, "pending"), lte(companySecretProposals.expiresAt, now))) + .where(and(eq(companySecretProposals.status, "pending"), lte(companySecretProposals.expiresAt, now), + companyId === undefined ? undefined : eq(companySecretProposals.companyId, companyId))) .orderBy(companySecretProposals.expiresAt) .limit(limit); let expiredCount = 0; @@ -891,11 +893,25 @@ export function createSecretProposalsService(db: Db) { return expiredCount; } + async function sweepExpiredForCompany(companyId: string) { + return sweepExpired(new Date(), DEFAULT_EXPIRY_SWEEP_LIMIT, undefined, companyId); + } + + async function expiryDeadlines(companyId?: string) { + const rows = await db.select({ companyId: companySecretProposals.companyId, + at: sql`min(${companySecretProposals.expiresAt})` }) + .from(companySecretProposals) + .where(and(eq(companySecretProposals.status, "pending"), + companyId === undefined ? undefined : eq(companySecretProposals.companyId, companyId))) + .groupBy(companySecretProposals.companyId); + return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() })); + } + async function nextExpiryAt(): Promise { const [row] = await db.select({ at: sql`min(${companySecretProposals.expiresAt})` }) .from(companySecretProposals).where(eq(companySecretProposals.status, "pending")); return row?.at == null ? null : new Date(row.at).getTime(); } - return { getById, view: enrich, createSecret, createBinding, listForAgent, listForBoard, assertBindingSnapshotCurrent, approve, transition, sweepExpired, nextExpiryAt }; + return { getById, view: enrich, createSecret, createBinding, listForAgent, listForBoard, assertBindingSnapshotCurrent, approve, transition, sweepExpired, sweepExpiredForCompany, expiryDeadlines, nextExpiryAt }; }