mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 15:52:22 +01:00
Merge scoped tool review notifications into interrupted recovery
Preserve execution ownership and register company-scoped work before settlement writes inside the existing transaction. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
800d00bc22
17 files changed
+370
-103
No files matched your search
@@ -13,9 +13,18 @@ approval can owe execution even when no agent run exists. Recovery uses the save
|
||||
origin and current authorization/target checks; the scheduler sees only whether
|
||||
another attempt is needed.
|
||||
|
||||
Recovery pages approved requests in ID order using a partial index. It does not
|
||||
Startup discovers companies with saved approved requests. Committed review
|
||||
signals carry the affected company ID; subsequent discovery and recovery reads
|
||||
filter by that company. The shared scoped worker coalesces changes and dispatches
|
||||
one company per pass with a one-second minimum spacing. A company writing reviews
|
||||
does not scan or lock another company's approved backlog.
|
||||
|
||||
Recovery pages that company's approved requests in ID order using a partial index. It does not
|
||||
let a full batch of unavailable approvals starve later work. A failed read or
|
||||
unresolved executable approval retains a 30-second retry. Once a pass leaves no
|
||||
unresolved executable approval retains a 30-second retry. New writes preserve
|
||||
that company's retry deadline, while other companies can run independently.
|
||||
A company pass still drains all its pages; this change does not cap provider
|
||||
calls within that pass or alter the provider's existing execution timeout. Once a pass leaves no
|
||||
such obligation, there is no recurring approved-recovery query. An empty system,
|
||||
configured idle tools, completed history, and deliberately inert approvals are
|
||||
quiet after reconciliation.
|
||||
@@ -29,7 +38,7 @@ queue invalidation, and the gateway's approval claims and managed-argument
|
||||
invalidation. The notification is awaited before SQL in the existing transaction;
|
||||
caller-owned outer transactions retain commit/rollback ownership.
|
||||
|
||||
A pending-only change can cause one empty approved-recovery pass. It does not
|
||||
A pending-only change can cause one empty company-scoped discovery read. It does not
|
||||
create a periodic scan. No per-route recovery bookkeeping or database listener
|
||||
is added. Signals use the existing database owner's single-active-writer model.
|
||||
Independent SQL writers or another process need a separate notification contract.
|
||||
@@ -57,7 +66,8 @@ replay an uncertain provider call.
|
||||
|
||||
The shared deadline worker coalesces notifications, preserves changes during a
|
||||
pass, and retains skipped work across idle drain/resume. Startup reconstructs
|
||||
saved approvals. Shutdown stops its coordinator registration. With heartbeat
|
||||
saved approvals. Company deletion invalidates cached recovery and retries through
|
||||
the same transactional notification boundary. Shutdown stops its coordinator registration. With heartbeat
|
||||
scheduling disabled, startup keeps the existing one-off recovery behavior.
|
||||
|
||||
Pending expiry is owned by the preceding slice. Interrupted execution and
|
||||
@@ -94,3 +104,14 @@ request to be executed and verifies exactly one provider call before asking for
|
||||
a new approval. Its full 469-test suite passes. The initial local command skipped
|
||||
its database cases; the suite now honors its supplied disposable database through
|
||||
the standard test-database guard independently of embedded Postgres support.
|
||||
|
||||
Company-scoping regression: a real signed/reviewed action in company A previously
|
||||
caused an unfiltered approved-request SELECT over company B's inert legacy action.
|
||||
The captured-SQL test fails before this repair and passes with scoped reads. Added
|
||||
lifecycle cases check retry preservation across committed writes, independent
|
||||
company progress, and disarming after the real company-deletion producer. These
|
||||
checks supplement the earlier execution, transaction, and paging evidence above.
|
||||
|
||||
After company scoping, the complete gateway-service and startup selection passes
|
||||
149 tests against a disposable PostgreSQL database, and server typecheck passes.
|
||||
Stack integration, workspace checks, and fresh remote CI remain separate gates.
|
||||
@@ -9,7 +9,7 @@ or change the one-hour review policy.
|
||||
|
||||
The tool gateway owns request signing and authorization. `toolReviewExpiryService`
|
||||
owns pending-expiry selection and settlement. `registerToolReviewExpiryWork`
|
||||
supplies those operations to the existing shared deadline worker. Startup wires
|
||||
supplies company-scoped operations to the existing shared scoped deadline worker. Startup wires
|
||||
that contract without interpreting tool or provider behavior.
|
||||
|
||||
The supported writers are:
|
||||
@@ -27,9 +27,15 @@ The supported writers are:
|
||||
- Administrative interaction resolution signals in the caller-owned transaction
|
||||
before resolving linked requests. Review-queue invalidation signals before
|
||||
invalidating unreadable or unsigned requests.
|
||||
- Company deletion signals its company before removing saved review obligations.
|
||||
- The expiry worker signals before its own settlement. A compare-and-set against
|
||||
pending status and the observed update time protects concurrent resolution.
|
||||
|
||||
Every notification requires the company ID. Normal commits reload only that
|
||||
company's saved minimum expiry; due cleanup selects only that company. Startup
|
||||
reconstructs all saved company deadlines once. A company with only unsigned
|
||||
null-expiry requests has no deadline.
|
||||
|
||||
Only the SQL mutation is wrapped. Signing, provider requests, telemetry, and
|
||||
interaction publication are not moved inside an enclosing recovery transaction.
|
||||
The database signal layer handles nested savepoints, outer commit/rollback, and
|
||||
@@ -59,7 +65,10 @@ worker active. The concurrent index migration uses the existing top-level
|
||||
executor and is safe to apply again after interruption.
|
||||
|
||||
The shared coordinator coalesces changes and preserves a write arriving during
|
||||
reconciliation. It retries failed or unfinished reconciliation after 30 seconds.
|
||||
reconciliation. Each due pass expires at most 100 rows for one company; companies
|
||||
rotate between passes until the backlog drains. Failed scopes retry independently
|
||||
with exponential backoff from 30 seconds to five minutes. Other companies retain
|
||||
their own deadlines. New writes do not erase a failed sweep's backoff.
|
||||
Once reconciliation completes with no deadline, it has no recurring SQL. Drain
|
||||
retains first writes without passive database scans; resume processes overdue
|
||||
reviews. Startup reconstructs persisted deadlines. Shutdown stops subscription
|
||||
@@ -70,7 +79,10 @@ With heartbeat scheduling disabled, startup-only expiry remains as before.
|
||||
|
||||
## Verification scope
|
||||
|
||||
Real PostgreSQL tests exercise normal gateway signing and human decisions,
|
||||
Real PostgreSQL tests record SQL to prove signing, human decisions, and due expiry
|
||||
remain company-scoped. They also verify five-second and earlier replacement
|
||||
deadlines, company deletion, and bounded multi-pass draining. Existing cases cover
|
||||
normal gateway signing and human decisions,
|
||||
configured idle and terminal history, outer commit/rollback, startup/restart,
|
||||
drain/resume, concurrent producer/read, unsigned rows, multi-page expiry, and
|
||||
injected invocation-write failure with atomic rollback and retry. Existing
|
||||
|
||||
@@ -69,9 +69,12 @@ const {
|
||||
settleInterruptedActionReviews: vi.fn(async () => ({ scanned: 0 })),
|
||||
nextActionReviewInterruptionAt: vi.fn(async () => null),
|
||||
recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })),
|
||||
approvedActionReviewCompanies: vi.fn(async () => []),
|
||||
sweepActionReviews: vi.fn(async () => ({ scanned: 0 })),
|
||||
sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })),
|
||||
nextActionReviewExpiryAt: vi.fn(async () => null),
|
||||
actionReviewExpiryDeadlines: vi.fn(async () => []),
|
||||
sweepExpiredActionReviewsForCompany: vi.fn(async () => ({ scanned: 0 })),
|
||||
cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })),
|
||||
nextCredentialExpiryAt: vi.fn(async () => null),
|
||||
},
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { registerToolReviewInterruptionWork } from "../services/tool-review-interruption-work.js";
|
||||
import { writeToolReviewChange } from "../services/tool-review-work-notifications.js";
|
||||
import { deleteCompany } from "../services/company-deletion.js";
|
||||
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
@@ -299,12 +300,15 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
expect(selects).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled();
|
||||
selects.mockRestore(); executes.mockRestore();
|
||||
}
|
||||
async function request(service = gateway, source = db) {
|
||||
const session = await service.createSession(runSessionInput(fixture.company, fixture.agent, fixture.run));
|
||||
async function request(service = gateway, source = db, context = fixture) {
|
||||
const before = new Set((await source.select({ id: toolActionRequests.id }).from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.companyId, context.company.id))).map(row => row.id));
|
||||
const session = await service.createSession(runSessionInput(context.company, context.agent, context.run));
|
||||
const noteId = randomUUID();
|
||||
await expect(service.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note",
|
||||
parameters: { noteId, body: "Awaiting a human" } })).rejects.toMatchObject({ reasonCode: "approval_required" });
|
||||
const rows = await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, fixture.company.id));
|
||||
const rows = (await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, context.company.id)))
|
||||
.filter(row => !before.has(row.id));
|
||||
expect(rows).toHaveLength(1);
|
||||
return rows[0];
|
||||
}
|
||||
@@ -356,7 +360,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
async function savedClaim(source = db, age = 0) {
|
||||
const pending = await request();
|
||||
const claimedAt = new Date(Date.now() - age);
|
||||
await writeToolReviewChange(source, async tx => {
|
||||
await writeToolReviewChange(source, fixture.company.id, async tx => {
|
||||
await tx.update(toolInvocations).set({ status: "executing", startedAt: claimedAt, updatedAt: claimedAt })
|
||||
.where(eq(toolInvocations.id, pending.invocationId));
|
||||
await tx.update(toolActionRequests).set({ status: "executing", updatedAt: claimedAt })
|
||||
@@ -426,7 +430,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const aborted = new Error("fixture rollback");
|
||||
const running = db.transaction(async tx => {
|
||||
await writeToolReviewChange(tx as unknown as typeof db, async nested => {
|
||||
await writeToolReviewChange(tx as unknown as typeof db, fixture.company.id, async nested => {
|
||||
await nested.update(toolActionRequests).set({ status: "executing", updatedAt: new Date() })
|
||||
.where(eq(toolActionRequests.id, pending.id));
|
||||
});
|
||||
@@ -479,7 +483,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
await ready;
|
||||
const updatedAt = new Date();
|
||||
try {
|
||||
await writeToolReviewChange(db, tx => tx.update(toolActionRequests).set({ updatedAt })
|
||||
await writeToolReviewChange(db, fixture.company.id, tx => tx.update(toolActionRequests).set({ updatedAt })
|
||||
.where(eq(toolActionRequests.id, pending.id)));
|
||||
} finally { release(); }
|
||||
await sweep; intercepted.mockRestore();
|
||||
@@ -519,6 +523,43 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not scan another company's approved backlog after review writes", async () => {
|
||||
const other = await createRunFixture(db);
|
||||
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
|
||||
const foreign = await request(gateway, db, other);
|
||||
await db.update(toolActionRequests).set({ signedArguments: signToolArguments({
|
||||
invocationId: foreign.invocationId, toolName: "mcp-remote-fixture:update_note",
|
||||
canonicalArguments: canonicalToolArguments({ noteId: "legacy", body: "inert" }),
|
||||
signingSecret: testToolActionSigningSecret,
|
||||
}) }).where(eq(toolActionRequests.id, foreign.id));
|
||||
await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id,
|
||||
decision: "approved", actor: { userId: "board" } });
|
||||
await startRecovery(); await quiet();
|
||||
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('"tool_action_requests"') &&
|
||||
query.includes('"tool_action_requests"."status" =') && params.includes("approved"))
|
||||
reads.push({ query, params: [...params] });
|
||||
};
|
||||
try {
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const pending = await request(); await settle(1500);
|
||||
await approve(pending); await settle(1500); await executed(pending);
|
||||
}
|
||||
} finally { db.$client.options.debug = debug; }
|
||||
expect(reads.length).toBeGreaterThan(0);
|
||||
for (const read of reads) {
|
||||
expect(read.query).toContain('"tool_action_requests"."company_id" =');
|
||||
expect(read.params).toContain(fixture.company.id);
|
||||
expect(read.params).not.toContain(other.company.id);
|
||||
}
|
||||
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("approved");
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, foreign.invocationId)))[0].status).toBe("awaiting_approval");
|
||||
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3);
|
||||
await quiet();
|
||||
});
|
||||
|
||||
it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for an agent action through %s approval", async mode => {
|
||||
await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed note",
|
||||
policyType: "rate_limit", priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" },
|
||||
@@ -549,6 +590,45 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
recover.mockRestore(); await settle(); await executed(pending); await quiet();
|
||||
});
|
||||
|
||||
it("preserves a failed company's retry across writes while another company executes", async () => {
|
||||
const pending = await request(); await approve(pending);
|
||||
const original = gateway.approveActionRequest.bind(gateway);
|
||||
const dispatch = vi.spyOn(gateway, "approveActionRequest").mockImplementation(async input => {
|
||||
if (input.companyId === fixture.company.id) throw new Error("Company dependency unavailable");
|
||||
return original(input);
|
||||
});
|
||||
await startRecovery();
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
const retryAt = coordinator!.nextWakeAt();
|
||||
expect(retryAt).not.toBeNull();
|
||||
const later = await request(); await approve(later);
|
||||
const other = await createRunFixture(db);
|
||||
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
|
||||
const foreign = await request(gateway, db, other);
|
||||
await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id,
|
||||
decision: "approved", actor: { userId: "board" } });
|
||||
await settle(5000); await executed(foreign);
|
||||
expect(dispatch.mock.calls.filter(([input]) => input.companyId === fixture.company.id)).toHaveLength(1);
|
||||
expect(coordinator!.nextWakeAt()).toBe(retryAt);
|
||||
dispatch.mockRestore();
|
||||
await settle(); await executed(pending); await executed(later); await quiet();
|
||||
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("disarms a failed company's recovery after company deletion commits", async () => {
|
||||
const pending = await request(); await approve(pending);
|
||||
const dispatch = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Company dependency unavailable"));
|
||||
await startRecovery(); expect(coordinator!.nextWakeAt()).not.toBeNull();
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
|
||||
.where(eq(heartbeatRuns.id, fixture.run.id));
|
||||
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" })
|
||||
.where(eq(agents.id, fixture.agent.id));
|
||||
await deleteCompany(db, fixture.company.id);
|
||||
await settle(1500);
|
||||
expect(coordinator!.nextWakeAt()).toBeNull();
|
||||
expect(dispatch).toHaveBeenCalledTimes(1); await quiet();
|
||||
});
|
||||
|
||||
it.each([null, "unreadable-old-signature"])("settles an approved invalid signature (%s) without recurring recovery", async signedArguments => {
|
||||
const pending = await request(); await approve(pending);
|
||||
await db.update(toolActionRequests).set({ signedArguments }).where(eq(toolActionRequests.id, pending.id));
|
||||
@@ -821,6 +901,92 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
});
|
||||
});
|
||||
|
||||
async function requestWithExpiry(expiresAt: Date, context = fixture) {
|
||||
return db.transaction(async tx => {
|
||||
const source = tx as unknown as typeof db;
|
||||
const pending = await request(createTestToolGatewayService(source), source, context);
|
||||
const [saved] = await tx.update(toolActionRequests).set({ expiresAt })
|
||||
.where(eq(toolActionRequests.id, pending.id)).returning();
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps signing and human resolution reads scoped to their company", async () => {
|
||||
const other = await createRunFixture(db);
|
||||
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
|
||||
const foreign = await request(gateway, db, other);
|
||||
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('"tool_action_requests"') &&
|
||||
(query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] });
|
||||
};
|
||||
try {
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const pending = await request(); await settle(1000);
|
||||
await commitToolActionReview(db, { companyId: fixture.company.id, actionRequestId: pending.id,
|
||||
decision: "rejected", actor: { userId: "reviewer" } });
|
||||
await settle(1000);
|
||||
}
|
||||
} finally { db.$client.options.debug = debug; }
|
||||
expect(reads.length).toBeGreaterThan(0);
|
||||
for (const read of reads) {
|
||||
expect(read.query).toContain('"tool_action_requests"."company_id" =');
|
||||
expect(read.params).toContain(fixture.company.id);
|
||||
expect(read.params).not.toContain(other.company.id);
|
||||
}
|
||||
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending");
|
||||
expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime());
|
||||
});
|
||||
|
||||
it("preserves a five-second deadline and an earlier committed replacement", async () => {
|
||||
await start(); await quiet();
|
||||
const later = await requestWithExpiry(new Date(Date.now() + 120_000)); await settle(1);
|
||||
expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime());
|
||||
const earlier = await requestWithExpiry(new Date(Date.now() + 5000)); await settle(1);
|
||||
expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt!.getTime());
|
||||
await settle(6000); await expectExpired(earlier.id, earlier.invocationId);
|
||||
expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime());
|
||||
await settle(120_000); await expectExpired(later.id, later.invocationId); await quiet();
|
||||
});
|
||||
|
||||
it("limits due expiry reads to the company whose deadline arrived", async () => {
|
||||
const other = await createRunFixture(db);
|
||||
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
|
||||
const foreign = await request(gateway, db, other);
|
||||
const due = await requestWithExpiry(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('"tool_action_requests"') &&
|
||||
(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('"tool_action_requests"."company_id" =');
|
||||
expect(read.params).toContain(fixture.company.id);
|
||||
expect(read.params).not.toContain(other.company.id);
|
||||
}
|
||||
await expectExpired(due.id, due.invocationId);
|
||||
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending");
|
||||
expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime());
|
||||
});
|
||||
|
||||
it("removes cached review deadlines after company deletion commits", async () => {
|
||||
await request(); 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.run.id));
|
||||
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" })
|
||||
.where(eq(agents.id, fixture.agent.id));
|
||||
expect(await deleteCompany(db, fixture.company.id)).toMatchObject({ id: fixture.company.id });
|
||||
await quiet();
|
||||
expect(await gateway.actionReviewExpiryDeadlines()).toEqual([]);
|
||||
});
|
||||
|
||||
it("is quiet when configured idle, wakes on signing, expires the review and card, then stays quiet with history", async () => {
|
||||
await start(); await quiet();
|
||||
const pending = await request();
|
||||
@@ -891,8 +1057,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
let release!: () => void, reading!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const ready = new Promise<void>(resolve => { reading = resolve; });
|
||||
const actual = gateway.nextActionReviewExpiryAt.bind(gateway);
|
||||
vi.spyOn(gateway, "nextActionReviewExpiryAt").mockImplementationOnce(async () => {
|
||||
const actual = gateway.actionReviewExpiryDeadlines.bind(gateway);
|
||||
vi.spyOn(gateway, "actionReviewExpiryDeadlines").mockImplementationOnce(async () => {
|
||||
const deadline = await actual(); reading(); await gate; return deadline;
|
||||
});
|
||||
const starting = start(); await ready;
|
||||
@@ -917,7 +1083,11 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
await db.insert(toolActionRequests).values(Array.from({ length: 101 }, () => ({
|
||||
...pending, id: randomUUID(), interactionId: null, expiresAt: past,
|
||||
})));
|
||||
const passes = vi.spyOn(gateway, "sweepExpiredActionReviewsForCompany");
|
||||
await start(); await quiet();
|
||||
const results = await Promise.all(passes.mock.results.map(result => result.value));
|
||||
expect(results.length).toBeGreaterThan(1);
|
||||
expect(results.every(result => result.scanned <= 100)).toBe(true);
|
||||
const rows = await db.select().from(toolActionRequests);
|
||||
expect(rows).toHaveLength(102);
|
||||
expect(rows.every(row => row.status === "expired")).toBe(true);
|
||||
@@ -934,7 +1104,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("pending");
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].status).toBe("awaiting_approval");
|
||||
await db.execute(sql`drop trigger sleep_review_fail on tool_invocations`);
|
||||
expect(errors.every(error => (error as { cause?: Error }).cause?.message === "expiry settlement fixture failure")).toBe(true);
|
||||
expect(errors.every(error => error instanceof AggregateError && error.errors.every(
|
||||
failure => (failure as { cause?: Error }).cause?.message === "expiry settlement fixture failure"))).toBe(true);
|
||||
errors.length = 0;
|
||||
await settle(); await expectExpired(pending.id, pending.invocationId); await quiet();
|
||||
});
|
||||
|
||||
@@ -17,9 +17,10 @@ export function approvalRecords(db: Db) {
|
||||
|
||||
// Tool reviews waiting for a formal decision stay parked until this producer
|
||||
// commits. The shared record owner retains approval validation and CAS rules.
|
||||
function resolveApproval(id: string, status: "approved" | "rejected", userId: string,
|
||||
async function resolveApproval(id: string, status: "approved" | "rejected", userId: string,
|
||||
note: string | null | undefined, database: Db = db) {
|
||||
return writeToolReviewChange(database, tx => resolveApprovalRecord(id, status, userId, note, tx));
|
||||
const existing = await getExistingApproval(id, database);
|
||||
return writeToolReviewChange(database, existing.companyId, tx => resolveApprovalRecord(id, status, userId, note, tx));
|
||||
}
|
||||
|
||||
function redactApprovalComment<T extends { body: string }>(comment: T, censorUsernameInLogs: boolean): T {
|
||||
@@ -72,7 +73,9 @@ export function approvalRecords(db: Db) {
|
||||
// cleanup. Idempotent: a no-op on already-resolved approvals.
|
||||
cancel: async (id: string, reason?: string | null) => {
|
||||
const now = new Date();
|
||||
const updated = await writeToolReviewChange(db, tx => tx
|
||||
const [existing] = await db.select({ companyId: approvals.companyId }).from(approvals).where(eq(approvals.id, id));
|
||||
if (!existing) return null;
|
||||
const updated = await writeToolReviewChange(db, existing.companyId, tx => tx
|
||||
.update(approvals)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { agentObservabilityService } from "./agent-observability.js";
|
||||
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
|
||||
@@ -62,6 +63,7 @@ export async function deleteCompany(db: Db, id: string) {
|
||||
if (!existing) return null;
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id);
|
||||
await notifyToolReviewChange(tx, 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.
|
||||
|
||||
@@ -1084,7 +1084,7 @@ async function resolveLinkedToolActionRequests(
|
||||
},
|
||||
) {
|
||||
if (interaction.kind !== "request_confirmation") return;
|
||||
await notifyToolReviewChange(db);
|
||||
await notifyToolReviewChange(db, interaction.companyId);
|
||||
await db
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
|
||||
@@ -87,7 +87,7 @@ listActionRequests: async (
|
||||
if (!readable) invalidRequestIds.push(request.id);
|
||||
}
|
||||
if (invalidRequestIds.length > 0) {
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
|
||||
@@ -141,7 +141,7 @@ export async function commitToolActionReview(
|
||||
throw conflict("This review has already been resolved");
|
||||
}
|
||||
const now = new Date();
|
||||
await notifyToolReviewChange(tx);
|
||||
await notifyToolReviewChange(tx, current.companyId);
|
||||
const [updated] = await tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { toolReviewInterruptionService } from "./tool-review-interruption.js";
|
||||
import { claimToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js";
|
||||
import { prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js";
|
||||
import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js";
|
||||
import { toolReviewExpiryService } from "./tool-review-expiry.js";
|
||||
import { writeToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
import { notifyToolReviewChange, writeToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
import { restConnectorFor } from "./connectors/rest-registry.js";
|
||||
import type { runPromptInjectionProvider } from "./prompt-injection-provider.js";
|
||||
import { promptInjectionPreventionService } from "./prompt-injection-prevention.js";
|
||||
@@ -2511,7 +2511,7 @@ export function createToolGatewayService(
|
||||
signingSecret: options.toolActionSigningSecret,
|
||||
});
|
||||
} catch (error) {
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
@@ -2670,7 +2670,7 @@ export function createToolGatewayService(
|
||||
// an expired row. When the guard matches no row, the row is already resolved.
|
||||
// Do not emit an approval card for a dead row; throw a retriable conflict so
|
||||
// the retry finds the live request or creates a fresh, signable one.
|
||||
const signedRows = await writeToolReviewChange(db, tx => tx
|
||||
const signedRows = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
interactionId: interaction.id,
|
||||
@@ -7768,7 +7768,7 @@ export function createToolGatewayService(
|
||||
const message =
|
||||
input.error instanceof Error ? input.error.message : String(input.error);
|
||||
const now = new Date();
|
||||
const settled = await writeToolReviewChange(db, async (tx) => {
|
||||
const settled = await db.transaction(async (tx) => {
|
||||
// Lock in the same invocation -> request order used by the normal
|
||||
// execution settlement path. The claim timestamp is the ownership token:
|
||||
// a consumer that merely read an approved row cannot settle another
|
||||
@@ -7784,6 +7784,7 @@ export function createToolGatewayService(
|
||||
|
||||
const [actionRequest] = await tx
|
||||
.select({
|
||||
companyId: toolActionRequests.companyId,
|
||||
status: toolActionRequests.status,
|
||||
updatedAt: toolActionRequests.updatedAt,
|
||||
})
|
||||
@@ -7798,6 +7799,7 @@ export function createToolGatewayService(
|
||||
return false;
|
||||
}
|
||||
|
||||
await notifyToolReviewChange(tx, actionRequest.companyId);
|
||||
await tx
|
||||
.update(toolInvocations)
|
||||
.set({
|
||||
@@ -7842,6 +7844,7 @@ export function createToolGatewayService(
|
||||
}
|
||||
|
||||
async function expireApprovedActionForManagedArgumentDrift(input: {
|
||||
companyId: string;
|
||||
actionRequestId: string;
|
||||
invocationId: string;
|
||||
toolName: string;
|
||||
@@ -7859,7 +7862,7 @@ export function createToolGatewayService(
|
||||
);
|
||||
const now = new Date();
|
||||
await options.beforeManagedArgumentDriftExpiry?.();
|
||||
const [expired] = await writeToolReviewChange(db, tx => tx
|
||||
const [expired] = await writeToolReviewChange(db, input.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({ status: "expired", resolvedAt: now, updatedAt: now })
|
||||
.where(
|
||||
@@ -7979,7 +7982,7 @@ export function createToolGatewayService(
|
||||
);
|
||||
}
|
||||
|
||||
const [claimed] = await writeToolReviewChange(db, tx => tx
|
||||
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({ status: "executing", updatedAt: new Date() })
|
||||
.where(
|
||||
@@ -8190,6 +8193,7 @@ export function createToolGatewayService(
|
||||
}
|
||||
if (!managedArgumentsRemainCurrent) {
|
||||
throw await expireApprovedActionForManagedArgumentDrift({
|
||||
companyId: claimed.companyId,
|
||||
actionRequestId: claimed.id,
|
||||
invocationId: invocation.id,
|
||||
toolName: invocation.toolName,
|
||||
@@ -8289,7 +8293,7 @@ export function createToolGatewayService(
|
||||
})
|
||||
.where(eq(toolInvocations.id, invocation.id));
|
||||
void emitConnectionInvoked(db, invocation.id);
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, claimed.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({ status: "executed", resolvedAt: now, updatedAt: now })
|
||||
.where(eq(toolActionRequests.id, claimed.id)));
|
||||
@@ -8420,7 +8424,7 @@ export function createToolGatewayService(
|
||||
pendingRequest.expiresAt.getTime() <= Date.now();
|
||||
if (pendingUnsigned || pendingExpired) {
|
||||
const now = new Date();
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, pendingRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({ status: "expired", resolvedAt: now, updatedAt: now })
|
||||
.where(
|
||||
@@ -9460,7 +9464,7 @@ export function createToolGatewayService(
|
||||
signingSecret: options.toolActionSigningSecret,
|
||||
});
|
||||
} catch (error) {
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
@@ -9501,7 +9505,7 @@ export function createToolGatewayService(
|
||||
tool,
|
||||
argumentsSummary: argumentValidation.summary,
|
||||
});
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
canonicalArgumentsHash,
|
||||
@@ -9658,8 +9662,12 @@ export function createToolGatewayService(
|
||||
nextActionReviewInterruptionAt: reviewInterruption.next,
|
||||
sweepExpiredActionReviews: reviewExpiry.sweep,
|
||||
nextActionReviewExpiryAt: reviewExpiry.next,
|
||||
actionReviewExpiryDeadlines: reviewExpiry.deadlines,
|
||||
sweepExpiredActionReviewsForCompany: reviewExpiry.sweepForCompany,
|
||||
|
||||
async recoverApprovedActionReviews() {
|
||||
approvedActionReviewCompanies: (companyId?: string) => approvedToolReviewCompanies(db, companyId),
|
||||
|
||||
async recoverApprovedActionReviews(companyId?: string) {
|
||||
return recoverApprovedToolReviews(db, async row => {
|
||||
try {
|
||||
const prepared = await prepareApprovedToolReview(db, { actionRequestId: row.request.id,
|
||||
@@ -9680,7 +9688,7 @@ export function createToolGatewayService(
|
||||
logger.warn({ err, actionRequestId: row.request.id }, "Could not recover approved tool action");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}, companyId);
|
||||
},
|
||||
|
||||
async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean; includeInterrupted?: boolean } = {}) {
|
||||
@@ -9826,7 +9834,7 @@ export function createToolGatewayService(
|
||||
}
|
||||
if (!signedPayload) {
|
||||
if (actionRequest.status === "pending") {
|
||||
await writeToolReviewChange(db, tx => tx
|
||||
await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
@@ -10399,7 +10407,7 @@ export function createToolGatewayService(
|
||||
actionRequest.expiresAt.getTime() <= Date.now()
|
||||
) {
|
||||
const expiredAt = new Date();
|
||||
const [expired] = await writeToolReviewChange(db, tx => tx
|
||||
const [expired] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "expired",
|
||||
@@ -10447,7 +10455,7 @@ export function createToolGatewayService(
|
||||
interaction?.kind === "request_confirmation" &&
|
||||
interaction.status === "accepted"
|
||||
) {
|
||||
const [approved] = await writeToolReviewChange(db, tx => tx
|
||||
const [approved] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "approved",
|
||||
@@ -10543,7 +10551,7 @@ export function createToolGatewayService(
|
||||
);
|
||||
await options.beforeLegacyApprovedActionClaim?.();
|
||||
const claimedAt = new Date();
|
||||
const [claimed] = await writeToolReviewChange(db, tx => tx
|
||||
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "executing",
|
||||
@@ -10636,13 +10644,14 @@ export function createToolGatewayService(
|
||||
))
|
||||
) {
|
||||
throw await expireApprovedActionForManagedArgumentDrift({
|
||||
companyId: actionRequest.companyId,
|
||||
actionRequestId: actionRequest.id,
|
||||
invocationId: storedInvocation.id,
|
||||
toolName: storedInvocation.toolName,
|
||||
});
|
||||
}
|
||||
const claimedAt = new Date();
|
||||
const [claimed] = await writeToolReviewChange(db, tx => tx
|
||||
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "executing",
|
||||
@@ -10921,7 +10930,7 @@ export function createToolGatewayService(
|
||||
.where(eq(toolInvocations.id, invocationId));
|
||||
if (input.approvedActionRequestId) {
|
||||
const actionRequestId = input.approvedActionRequestId;
|
||||
const [executedRequest] = await writeToolReviewChange(db, tx => tx
|
||||
const [executedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "executed",
|
||||
@@ -11055,7 +11064,7 @@ export function createToolGatewayService(
|
||||
void emitConnectionInvoked(db, invocationId);
|
||||
if (input.approvedActionRequestId) {
|
||||
const actionRequestId = input.approvedActionRequestId;
|
||||
const [failedRequest] = await writeToolReviewChange(db, tx => tx
|
||||
const [failedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: "failed",
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
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 { createToolGatewayService } from "./tool-gateway.js";
|
||||
|
||||
export function registerToolReviewExpiryWork(
|
||||
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
|
||||
gateway: Pick<ReturnType<typeof createToolGatewayService>, "sweepExpiredActionReviews" | "nextActionReviewExpiryAt">,
|
||||
gateway: Pick<ReturnType<typeof createToolGatewayService>, "sweepExpiredActionReviewsForCompany" | "actionReviewExpiryDeadlines">,
|
||||
canRun: () => boolean,
|
||||
) {
|
||||
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewExpiry, {
|
||||
retryMs: 30_000, canRun,
|
||||
run: () => gateway.sweepExpiredActionReviews(),
|
||||
next: () => gateway.nextActionReviewExpiryAt(),
|
||||
});
|
||||
return registerScopedDeadlineWork(coordinator, {
|
||||
queue: DELIVERY_QUEUES.toolReviewExpiry,
|
||||
batchSize: 1,
|
||||
minimumPassIntervalMs: 0,
|
||||
decodeScope: hint => hint === "*" ? undefined : hint,
|
||||
matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId,
|
||||
load: async (companyId?: string) => (await gateway.actionReviewExpiryDeadlines(companyId))
|
||||
.map(row => ({ ...row, id: row.companyId })),
|
||||
check: async entry => {
|
||||
await gateway.sweepExpiredActionReviewsForCompany(entry.companyId);
|
||||
const [next] = await gateway.actionReviewExpiryDeadlines(entry.companyId);
|
||||
return next ? { ...next, id: next.companyId } : null;
|
||||
},
|
||||
}, canRun);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, eq, gt, lte, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, isNotNull, lte, sql } from "drizzle-orm";
|
||||
import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db";
|
||||
import { writeToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
|
||||
@@ -15,36 +15,48 @@ export function toolReviewExpiryService(db: Db, onExpired: (input: {
|
||||
.from(toolActionRequests).where(eq(toolActionRequests.status, "pending"));
|
||||
return row?.at == null ? null : new Date(row.at).getTime();
|
||||
},
|
||||
async sweep(now = new Date()) {
|
||||
let cursor: string | undefined;
|
||||
let scanned = 0;
|
||||
for (;;) {
|
||||
const rows = await db.select().from(toolActionRequests).where(and(
|
||||
eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now),
|
||||
cursor ? gt(toolActionRequests.id, cursor) : undefined,
|
||||
)).orderBy(asc(toolActionRequests.id)).limit(100);
|
||||
for (const row of rows) {
|
||||
const errorCode = "action_expired";
|
||||
const errorMessage = "The approval request expired before a decision.";
|
||||
const changed = await writeToolReviewChange(db, async tx => {
|
||||
const [updated] = await tx.update(toolActionRequests)
|
||||
.set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and(
|
||||
eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"),
|
||||
eq(toolActionRequests.updatedAt, row.updatedAt),
|
||||
)).returning({ id: toolActionRequests.id });
|
||||
if (!updated) return false;
|
||||
await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage,
|
||||
completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId));
|
||||
return true;
|
||||
});
|
||||
if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId,
|
||||
status: "expired", errorCode, errorMessage });
|
||||
}
|
||||
scanned += rows.length;
|
||||
if (rows.length < 100) break;
|
||||
cursor = rows[rows.length - 1].id;
|
||||
}
|
||||
return { scanned };
|
||||
sweep,
|
||||
sweepForCompany: (companyId: string) => sweep(new Date(), companyId, 1),
|
||||
async deadlines(companyId?: string) {
|
||||
const rows = await db.select({ companyId: toolActionRequests.companyId,
|
||||
at: sql<string | Date>`min(${toolActionRequests.expiresAt})` })
|
||||
.from(toolActionRequests).where(and(eq(toolActionRequests.status, "pending"),
|
||||
isNotNull(toolActionRequests.expiresAt),
|
||||
companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId)))
|
||||
.groupBy(toolActionRequests.companyId);
|
||||
return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() }));
|
||||
},
|
||||
};
|
||||
async function sweep(now = new Date(), companyId?: string, maxPages = Infinity) {
|
||||
let cursor: string | undefined;
|
||||
let scanned = 0;
|
||||
for (let page = 0; page < maxPages; page++) {
|
||||
const rows = await db.select().from(toolActionRequests).where(and(
|
||||
eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now),
|
||||
cursor ? gt(toolActionRequests.id, cursor) : undefined,
|
||||
companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId),
|
||||
)).orderBy(asc(toolActionRequests.id)).limit(100);
|
||||
for (const row of rows) {
|
||||
const errorCode = "action_expired";
|
||||
const errorMessage = "The approval request expired before a decision.";
|
||||
const changed = await writeToolReviewChange(db, row.companyId, async tx => {
|
||||
const [updated] = await tx.update(toolActionRequests)
|
||||
.set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and(
|
||||
eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"),
|
||||
eq(toolActionRequests.updatedAt, row.updatedAt),
|
||||
)).returning({ id: toolActionRequests.id });
|
||||
if (!updated) return false;
|
||||
await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage,
|
||||
completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId));
|
||||
return true;
|
||||
});
|
||||
if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId,
|
||||
status: "expired", errorCode, errorMessage });
|
||||
}
|
||||
scanned += rows.length;
|
||||
if (rows.length < 100) break;
|
||||
cursor = rows[rows.length - 1].id;
|
||||
}
|
||||
return { scanned };
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export function toolReviewInterruptionService(db: Db, onSettled: (input: {
|
||||
cursor ? gt(toolActionRequests.id, cursor) : undefined,
|
||||
)).orderBy(asc(toolActionRequests.id)).limit(100);
|
||||
for (const row of rows) {
|
||||
const settled = await writeToolReviewChange(db, async tx => {
|
||||
const settled = await writeToolReviewChange(db, row.companyId, async tx => {
|
||||
const [invocation] = await tx.select().from(toolInvocations)
|
||||
.where(eq(toolInvocations.id, row.invocationId)).for("update");
|
||||
const [request] = await tx.select().from(toolActionRequests)
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
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 { createToolGatewayService } from "./tool-gateway.js";
|
||||
|
||||
export function registerToolReviewRecoveryWork(
|
||||
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
|
||||
gateway: Pick<ReturnType<typeof createToolGatewayService>, "recoverApprovedActionReviews">,
|
||||
gateway: Pick<ReturnType<typeof createToolGatewayService>, "recoverApprovedActionReviews" | "approvedActionReviewCompanies">,
|
||||
canRun: () => boolean,
|
||||
) {
|
||||
let next: number | null = null;
|
||||
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewRecovery, {
|
||||
retryMs: 30_000, canRun,
|
||||
run: async () => {
|
||||
const result = await gateway.recoverApprovedActionReviews();
|
||||
next = result.retry ? Date.now() + 30_000 : null;
|
||||
// Dispatch failures are reported by the domain owner, not thrown. Preserve
|
||||
// their retry deadline when another write reloads the same company's work.
|
||||
const retries = new Map<string, number>();
|
||||
return registerScopedDeadlineWork(coordinator, {
|
||||
queue: DELIVERY_QUEUES.toolReviewRecovery,
|
||||
batchSize: 1,
|
||||
decodeScope: hint => hint === "*" ? undefined : hint,
|
||||
matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId,
|
||||
load: async (companyId?: string) => {
|
||||
const rows = await gateway.approvedActionReviewCompanies(companyId);
|
||||
const retained = new Set(rows.map(row => row.companyId));
|
||||
for (const id of retries.keys()) if ((companyId === undefined || id === companyId) && !retained.has(id)) retries.delete(id);
|
||||
return rows.map(row => ({ ...row, id: row.companyId, dueAt: retries.get(row.companyId) ?? Date.now() }));
|
||||
},
|
||||
next: async () => next,
|
||||
});
|
||||
check: async entry => {
|
||||
const result = await gateway.recoverApprovedActionReviews(entry.companyId);
|
||||
if (!result.retry) { retries.delete(entry.companyId); return null; }
|
||||
const dueAt = Date.now() + 30_000;
|
||||
retries.set(entry.companyId, dueAt);
|
||||
return { ...entry, dueAt };
|
||||
},
|
||||
}, canRun);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export async function prepareApprovedToolReview(db: Db, input: {
|
||||
errorCode: string;
|
||||
errorMessage: string;
|
||||
}) {
|
||||
await notifyToolReviewChange(tx);
|
||||
await notifyToolReviewChange(tx, request.companyId);
|
||||
if (failure) await tx.update(toolInvocations).set({ ...failure, completedAt: now, updatedAt: now })
|
||||
.where(eq(toolInvocations.id, invocation.id));
|
||||
await tx.update(toolActionRequests).set({ status: projection.status,
|
||||
@@ -89,16 +89,26 @@ export async function prepareApprovedToolReview(db: Db, input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function approvedToolReviewCompanies(db: Db, companyId?: string) {
|
||||
return db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests)
|
||||
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
|
||||
.where(and(eq(toolActionRequests.status, "approved"),
|
||||
companyId ? eq(toolActionRequests.companyId, companyId) : undefined))
|
||||
.groupBy(toolActionRequests.companyId);
|
||||
}
|
||||
|
||||
export async function recoverApprovedToolReviews(db: Db, recover: (input: {
|
||||
request: typeof toolActionRequests.$inferSelect;
|
||||
invocation: typeof toolInvocations.$inferSelect;
|
||||
}) => Promise<boolean>) {
|
||||
}) => Promise<boolean>, companyId?: string) {
|
||||
let cursor: string | undefined;
|
||||
let scanned = 0, retry = false;
|
||||
for (;;) {
|
||||
const rows = await db.select({ request: toolActionRequests, invocation: toolInvocations })
|
||||
.from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
|
||||
.where(and(eq(toolActionRequests.status, "approved"), cursor ? gt(toolActionRequests.id, cursor) : undefined))
|
||||
.where(and(eq(toolActionRequests.status, "approved"),
|
||||
companyId ? eq(toolActionRequests.companyId, companyId) : undefined,
|
||||
cursor ? gt(toolActionRequests.id, cursor) : undefined))
|
||||
.orderBy(asc(toolActionRequests.id)).limit(100);
|
||||
for (const row of rows) retry = await recover(row) || retry;
|
||||
scanned += rows.length;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
|
||||
export async function notifyToolReviewChange(transaction: object) {
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption);
|
||||
export async function notifyToolReviewChange(transaction: object, companyId: string) {
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery, companyId);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption, companyId);
|
||||
}
|
||||
|
||||
export function writeToolReviewChange<T>(db: Db, write: (transaction: Db) => Promise<T>): Promise<T> {
|
||||
export function writeToolReviewChange<T>(db: Db, companyId: string, write: (transaction: Db) => Promise<T>): Promise<T> {
|
||||
return db.transaction(async transaction => {
|
||||
await notifyToolReviewChange(transaction);
|
||||
await notifyToolReviewChange(transaction, companyId);
|
||||
return write(transaction as unknown as Db);
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db";
|
||||
import type { ToolRedactedValueSummary } from "@paperclipai/shared";
|
||||
import { writeToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
|
||||
export type ToolTestApprovalClaim = { actionRequestId: string; invocationId: string; claimedAt: Date };
|
||||
export type ToolTestOutcome = {
|
||||
@@ -12,12 +12,13 @@ export type ToolTestOutcome = {
|
||||
};
|
||||
|
||||
export async function claimToolTestApproval(db: Db, actionRequestId: string, invocationId: string): Promise<ToolTestApprovalClaim | null> {
|
||||
return writeToolReviewChange(db, async tx => {
|
||||
return db.transaction(async tx => {
|
||||
const [invocation] = await tx.select().from(toolInvocations)
|
||||
.where(eq(toolInvocations.id, invocationId)).for("update");
|
||||
const [request] = await tx.select().from(toolActionRequests)
|
||||
.where(and(eq(toolActionRequests.id, actionRequestId), eq(toolActionRequests.invocationId, invocationId))).for("update");
|
||||
if (!invocation || request?.status !== "approved") return null;
|
||||
await notifyToolReviewChange(tx, request.companyId);
|
||||
const now = new Date();
|
||||
if (invocation.status !== "awaiting_approval") {
|
||||
if (["succeeded", "failed", "denied", "timed_out", "rate_limited"].includes(invocation.status)) {
|
||||
@@ -65,13 +66,14 @@ export async function persistToolTestOutcome(db: Db, invocationId: string, outco
|
||||
await db.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId));
|
||||
return true;
|
||||
}
|
||||
return writeToolReviewChange(db, async tx => {
|
||||
return db.transaction(async tx => {
|
||||
const [invocation] = await tx.select({ status: toolInvocations.status }).from(toolInvocations)
|
||||
.where(eq(toolInvocations.id, invocationId)).for("update");
|
||||
const [request] = await tx.select().from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.id, claim.actionRequestId)).for("update");
|
||||
if (!invocation || !["awaiting_approval", "executing"].includes(invocation.status) ||
|
||||
request?.status !== "executing" || request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false;
|
||||
await notifyToolReviewChange(tx, request.companyId);
|
||||
await tx.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId));
|
||||
await tx.update(toolActionRequests).set({ status: outcome.status === "succeeded" ? "executed" : "failed",
|
||||
resolvedAt: now, updatedAt: now }).where(eq(toolActionRequests.id, claim.actionRequestId));
|
||||
|
||||
Reference in new issue
Block a user