Merge rate admission and plugin reservation fixes into sleep-23-voice-inbound-cleanup

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* codex/sleep-22-voice-reply-delivery:
  Preserve plugin dispatch reservations and retained completions
  Persist changed rate admission before approved tool execution
This commit is contained in:
DottaandPaperclip committed 2026-10-27 04:02:41 -05:00
commit 43015e2394
9 files changed
+407 -43

No files matched your search

+45 -1
View File
@@ -48,7 +48,7 @@ Independent SQL writers or another process need a separate notification contract
Agent actions retain their existing approved-to-executing claim. Test-tab
foreground approval and recovery now share an equivalent claim before provider
dispatch. The invocation then starts only if the request still holds that claim.
Provider calls and target/policy lookup remain outside SQL transactions.
Provider calls and target discovery remain outside SQL transactions. Current rate-policy admission and its receipt commit together in a short database transaction.
The Test-tab invocation outcome and terminal request status commit together.
Claim timestamps fence late settlement. A later audit failure cannot overwrite
@@ -187,3 +187,47 @@ proves the old owner cannot dispatch; the surviving approval later executes once
A provider-error case proves that an already-started call is not requeued as a
preparation failure. The existing Test-tab timeout and ownership cases exercise
the other consumer of the shared boundary.
## New or edited rate rules during approval
A reviewed invocation already has durable `consumedRateAdmissions` in its policy
explanation. The original read-only recheck retained unchanged rules correctly,
but new or edited rules only inspected their counters. Two approved actions could
therefore both execute against one available slot. The real recovery regression
failed for both a newly added limit and an increased limit before this repair.
The policy service now owns `admitInvocation`: lock the company-scoped invocation,
validate its exact actor/task/tool/argument binding, recheck current policy, spend
only admissions not already recorded for that policy generation, and save the
receipt atomically. The gateway supplies its execution claim; that claim is locked
and checked by ID, invocation, company, executing status and timestamp. This also
supports historical approved requests whose invocation still says pending, without
accepting a stale claimant. Existing claim/start/settlement owners still control
provider execution. No queue table, periodic query, or per-route wrapper is added.
Counter updates preserve the number of already spent slots when the limit changes.
A rejection by a later policy or failure to save the receipt rolls back new charges.
A retry of a committed admission retains the saved receipt, including concurrent
rechecks. Read-only approval preflight and browser authority probes stay read-only;
trust-rule usage is not counted again during execution revalidation. The policy
service and its metric helper accept only the database capabilities they use, so
transaction clients do not require a cast to a root connection.
The owning gateway and policy suites pass all 181 cases against disposable real
PostgreSQL databases. Coverage includes two competing invocations, concurrent
retries of one invocation, changed limits, failed receipt writes, rejection after
an earlier rate charge, unchanged admissions, historical approvals, scope mismatch,
claim loss, quiet recovery and unknown provider outcomes. Server typechecking
passes after preparing current runner dependencies.
Earlier verification failures remain part of this evidence: the first full run
was stopped because an old claim-loss fixture held the policy table while trying
to revoke the newly locked invocation. It now pauses discovery before admission
and retains the no-provider-dispatch assertion. A new receipt assertion was fixed
to permit the intended additional receipt while preserving original fields. The
next full run exposed an overly strict historical-approval check; exact execution-
claim validation fixed it. Typechecking then exposed root-client-only signatures,
which were narrowed to their actual database capabilities. The final complete
suites and TypeScript check pass; stack integration and current-head CI remain
separate gates. This proves worker and admission behavior, not deployed host sleep.
+27
View File
@@ -127,3 +127,30 @@ below. No production timeout or quiet assertion was relaxed.
The post-cleanup retry run passes all 48 shutdown/plugin cases (28 plugin and
20 shutdown). Together with the unchanged consumer selection this covers 76
unique cases. Server typecheck and build pass on the final round-two repair.
## Reservation and unregister races
A scheduled refresh can yield after selecting eligible jobs while a manual trigger
reserves one of those jobs. Previously the stale scheduled attempt reused the
same set entry, found the manual run under its row lock, and removed that entry.
The manual provider call was still running but no longer consumed scheduler
capacity. Dispatch now performs the synchronous reservation check and insertion
at one boundary; callers cannot remove a reservation they did not create. Refresh
also rechecks active and retained-settlement state after its database read.
Unregister now preserves runs whose real result is retained for settlement. For
other unfinished runs, it locks and rereads the current run before cancelling, so
a completion committed since discovery cannot be overwritten. The existing job
store still owns mutation notifications. Provider calls stay outside transactions;
no new periodic work or durable storage is introduced.
Real PostgreSQL regressions first reproduced both incorrect cancellation of saved
success/failure results and loss of a manual reservation after a delayed query
result. The corrected suite also checks concurrent completion during unregister,
manual/scheduled capacity, retries without another provider call, drain/resume,
startup, shutdown and quiet states. All 33 complete scheduler cases and server
TypeScript checks pass on the owning slice. The first full run crossed the next
hourly cron boundary during a retry fixture and legitimately produced extra runs;
its fixed clock now isolates that test from wall-clock start time while preserving
its assertions. Stack integration and latest-head CI are separate gates.
@@ -34,6 +34,8 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: pluginId, version: "1.0.0", manifestJson: {} as never });
await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`)));
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
// Retry tests must not accidentally cross the next real hourly cron tick.
vi.setSystemTime(new Date("2026-10-27T12:05:00Z"));
});
afterEach(async () => {
await scheduler?.stop(); await coordinator?.stop(); scheduler = undefined; coordinator = undefined;
@@ -249,6 +251,102 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await completed(2); await settled(); errors.length = 0;
}
});
it.each(["succeeded", "failed"] as const)("retains a completed %s result when unregistering during a settlement failure", async outcome => {
await db.execute(sql`create function plugin_settlement_failure() returns trigger language plpgsql as $$ begin if new.status in ('succeeded', 'failed') then raise exception 'settlement unavailable'; end if; return new; end $$`);
await db.execute(sql`create trigger plugin_settlement_failure before update on plugin_job_runs for each row execute function plugin_settlement_failure()`);
if (outcome === "failed") rpc.mockRejectedValueOnce(new Error("Plugin failed before unregister"));
await due(); await start();
await vi.waitFor(async () => {
await vi.advanceTimersByTimeAsync(1000);
expect(errors.length).toBeGreaterThan(0);
expect(scheduler!.diagnostics().activeJobCount).toBe(0);
}, { timeout: 5000 });
try {
await scheduler!.unregisterPlugin(pluginId);
expect((await runs())[0].status).toBe("running");
} finally {
await db.execute(sql`drop trigger plugin_settlement_failure on plugin_job_runs`);
errors.length = 0;
await scheduler!.tick(); await settled(); errors.length = 0;
}
expect((await runs())[0].status).toBe(outcome);
expect(rpc).toHaveBeenCalledOnce();
await quiet();
});
it("preserves a completion committed while unregister waits on the discovered run", async () => {
const row = await job("finishing", "");
const run = await pluginJobStore(db).createRun({ jobId: row.id, pluginId, trigger: "manual" });
await pluginJobStore(db).markRunning(run.id);
await start(); await quiet();
let release!: () => void, locked!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const acquired = new Promise<void>(resolve => { locked = resolve; });
const finishing = db.transaction(async tx => {
await pluginJobStore(tx).completeRun(run.id, { status: "succeeded" });
locked(); await gate;
});
await acquired;
const unregistering = scheduler!.unregisterPlugin(pluginId);
try {
await vi.waitFor(async () => {
const [waiting] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
where datname = current_database() and state = 'active' and wait_event_type = 'Lock'
and query like '%plugin_job_runs%'`);
expect(waiting.count).toBeGreaterThan(0);
});
} finally { release(); await finishing; await unregistering; }
expect((await runs())[0].status).toBe("succeeded");
expect(rpc).not.toHaveBeenCalled();
await quiet();
});
it("retains the manual reservation when a refresh read finishes after manual dispatch", async () => {
await start(2); await quiet();
const row = await due("raced");
let resumeRead!: () => void, enteredRead!: () => void, releaseCall!: () => void;
const readGate = new Promise<void>(resolve => { resumeRead = resolve; });
const readEntered = new Promise<void>(resolve => { enteredRead = resolve; });
const callGate = new Promise<void>(resolve => { releaseCall = resolve; });
rpc.mockImplementation(() => callGate);
const select = db.select.bind(db);
let held = false;
// Hold delivery of one real outstanding-run query result. The manual run
// commits after this snapshot, before the scheduled dispatch resumes.
const readSpy = vi.spyOn(db, "select").mockImplementation((fields) => {
const builder = select(fields);
if (fields?.jobId !== pluginJobRuns.jobId || held) return builder;
held = true;
const from = builder.from.bind(builder);
vi.spyOn(builder, "from").mockImplementation((table) => {
const query = from(table);
const then = query.then.bind(query);
query.then = ((fulfilled, rejected) => then(async rows => {
enteredRead(); await readGate; return rows;
}).then(fulfilled, rejected)) as typeof query.then;
return query;
});
return builder;
});
const refreshing = scheduler!.tick();
try {
await readEntered;
await scheduler!.triggerJob(row.id);
await vi.waitFor(() => expect(rpc).toHaveBeenCalledOnce());
resumeRead(); await refreshing;
expect(scheduler!.diagnostics().activeJobIds).toEqual([row.id]);
await due("waiting-one"); await due("waiting-two"); await scheduler!.tick();
await vi.waitFor(() => expect(rpc).toHaveBeenCalledTimes(2));
expect(scheduler!.diagnostics().activeJobCount).toBe(2);
} finally {
resumeRead(); readSpy.mockRestore();
await pluginJobStore(db).updateJobStatus(row.id, "paused");
releaseCall(); await refreshing; await settled();
}
await completed(3);
expect(rpc).toHaveBeenCalledTimes(3);
});
it("preserves a deadline advanced during a concurrent unchanged declaration update", async () => {
const row = await due();
const advanced = new Date(Date.now() + 600_000);
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
@@ -34,7 +34,9 @@ import { toolAccessService } from "../services/tool-access.js";
import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js";
import { canonicalToolArguments, signToolArguments } from "../services/tool-content-guards.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_POLICY_TEST_DATABASE_URL");
const embeddedPostgresSupport = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
function legacySideEffectKey(invocation: typeof toolInvocations.$inferSelect, argumentsHash: string) {
@@ -215,8 +217,11 @@ describeEmbeddedPostgres("tool access policy service", () => {
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-");
db = createDb(tempDb.connectionString);
if (externalDatabaseUrl) db = createDb(externalDatabaseUrl);
else {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-");
db = createDb(tempDb.connectionString);
}
}, 20_000);
afterEach(async () => {
@@ -244,6 +249,7 @@ describeEmbeddedPostgres("tool access policy service", () => {
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
@@ -1112,11 +1118,90 @@ describeEmbeddedPostgres("tool access policy service", () => {
expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true });
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
expect((await db.select().from(toolRateLimitCounters))[0].remaining).toBe(0);
// Neither a new invocation nor an accidental consuming recheck can borrow
// another invocation's already-spent slot.
// A fresh invocation cannot borrow another invocation's already-spent slot.
// Execution revalidation retains its own durable admission.
expect(await svc.decide(input, { admittedInvocationId: randomUUID() })).toMatchObject({ decision: "rate_limited" });
expect(await svc.decide({ ...input, consumeRateLimit: true }, { admittedInvocationId: invocation.id }))
.toMatchObject({ decision: "rate_limited" });
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
});
it("atomically charges a new rule once across concurrent retries of the same invocation", async () => {
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
const added = await svc.createPolicy(company.id, { name: "New admission", policyType: "rate_limit", priority: 0,
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
const oldCounters = await db.select().from(toolRateLimitCounters);
expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true });
expect(await db.select().from(toolRateLimitCounters)).toEqual(oldCounters);
const results = await Promise.all(Array.from({ length: 4 }, () => svc.admitInvocation(input, invocation.id)));
expect(results.every(result => result.allowed)).toBe(true);
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
.toMatchObject([{ limit: 1, remaining: 0 }]);
const [saved] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id));
expect(saved.policyExplanation?.consumedRateAdmissions).toHaveLength(2);
const { consumedRateAdmissions: oldAdmissions, ...oldExplanation } = invocation.policyExplanation!;
expect(saved.policyExplanation).toMatchObject(oldExplanation);
expect(saved.policyExplanation?.consumedRateAdmissions).toEqual(expect.arrayContaining(oldAdmissions as unknown[]));
});
it("allows only one of two admitted invocations to spend a newly added final slot", async () => {
const { company, input, invocation, svc } = await admittedRateLimitedInvocation(2);
const initial = await svc.decide({ ...input, consumeRateLimit: true });
expect(initial.allowed).toBe(true);
const { invocation: second } = await svc.recordInvocation(input, initial);
await db.update(toolInvocations).set({ status: "executing" }).where(eq(toolInvocations.id, second.id));
const added = await svc.createPolicy(company.id, { name: "One competing slot", policyType: "rate_limit", priority: 0,
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
const results = await Promise.all([invocation.id, second.id].map(id => svc.admitInvocation(input, id)));
expect(results.filter(result => result.allowed)).toHaveLength(1);
expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1);
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
.toMatchObject([{ limit: 1, remaining: 0 }]);
});
it("rolls back new rate charges when a later policy rejects the invocation", async () => {
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
await svc.createPolicy(company.id, { name: "Before rejection", policyType: "rate_limit", priority: 0,
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
await svc.createPolicy(company.id, { name: "Later rejection", policyType: "block", priority: 10,
selectors: { toolName: "send_email" } });
const counters = await db.select().from(toolRateLimitCounters);
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ decision: "deny" });
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation)
.toEqual(invocation.policyExplanation);
});
it("rolls back rate charges when saving the admission receipt fails and admits a retry once", async () => {
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
const added = await svc.createPolicy(company.id, { name: "Receipt failure", policyType: "rate_limit", priority: 0,
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
await db.execute(sql`create function sleep_admission_fail() returns trigger language plpgsql as $$ begin
raise exception 'receipt write unavailable'; end $$`);
await db.execute(sql`create trigger sleep_admission_fail before update of policy_explanation on tool_invocations
for each row execute function sleep_admission_fail()`);
try {
await expect(svc.admitInvocation(input, invocation.id)).rejects.toThrow();
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))).toEqual([]);
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation)
.toEqual(invocation.policyExplanation);
} finally {
await db.execute(sql`drop trigger sleep_admission_fail on tool_invocations`);
await db.execute(sql`drop function sleep_admission_fail()`);
}
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
.toMatchObject([{ limit: 1, remaining: 0 }]);
});
it.each([2, 4])("preserves spent slots when a rate limit changes from three to %s", async limit => {
const { company, input, ratePolicy, svc } = await admittedRateLimitedInvocation(3);
await svc.updatePolicy({ companyId: company.id, policyId: ratePolicy.id,
body: { config: { limit, windowSeconds: 3600, keyBy: ["agent", "tool"] } } });
const results = await Promise.all(Array.from({ length: limit }, () => svc.decide({ ...input, consumeRateLimit: true })));
expect(results.filter(result => result.allowed)).toHaveLength(limit - 1);
expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1);
expect(await db.select().from(toolRateLimitCounters)).toMatchObject([{ limit, remaining: 0 }]);
});
it.each(["pending", "approved"] as const)("retains a waiting invocation's consumed slot without bypassing %s approval policy", async approvalState => {
@@ -1188,10 +1273,13 @@ describeEmbeddedPostgres("tool access policy service", () => {
for (const mutation of mutations) {
await db.update(toolInvocations).set(mutation).where(eq(toolInvocations.id, invocation.id));
expect(await svc.decide(input, options), JSON.stringify(mutation)).toMatchObject({ decision: "rate_limited" });
expect(await svc.admitInvocation(input, invocation.id), JSON.stringify(mutation)).toMatchObject({ decision: "deny" });
await db.update(toolInvocations).set({ ...invocation, status: "executing" }).where(eq(toolInvocations.id, invocation.id));
}
expect(await svc.decide({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, options))
.toMatchObject({ decision: "rate_limited" });
expect(await svc.admitInvocation({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, invocation.id))
.toMatchObject({ decision: "deny" });
});
it("rejects unsupported policy semantics at create and update time", async () => {
@@ -883,6 +883,31 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
});
it.each(["new", "increased"] as const)("spends the newly available slot of a %s rate rule during approved recovery", async change => {
const rate = { companyId: fixture.company.id, name: "Changed reviewed-note limit",
policyType: "rate_limit" as const, priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" },
config: { limit: 2, windowSeconds: 3600, keyBy: ["agent", "tool"] } };
const original = change === "increased" ? (await db.insert(toolPolicies).values(rate).returning())[0] : null;
const first = await request(), second = await request();
if (original) {
await db.update(toolPolicies).set({ config: { ...rate.config, limit: 3 }, updatedAt: new Date() })
.where(eq(toolPolicies.id, original.id));
} else {
await db.insert(toolPolicies).values({ ...rate, config: { ...rate.config, limit: 1 } });
}
await approve(first); await approve(second);
await startRecovery(); await settle(); await quiet();
const requests = await db.select().from(toolActionRequests);
expect(requests.filter(row => row.status === "executed")).toHaveLength(1);
expect(requests.filter(row => row.status === "failed")).toHaveLength(1);
const invocations = await db.select().from(toolInvocations);
expect(invocations.filter(row => row.errorCode === "rate_limited")).toHaveLength(1);
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
const counters = await db.select().from(toolRateLimitCounters);
expect(counters).toHaveLength(1);
expect(counters[0]).toMatchObject({ limit: change === "increased" ? 3 : 1, remaining: 0 });
});
it("reconstructs a saved approved action after restart", async () => {
const pending = await request(); await approve(pending);
await startRecovery(); await settle(); await executed(pending); await quiet();
@@ -1194,7 +1219,9 @@ describeEmbeddedPostgres("tool gateway service", () => {
const gate = new Promise<void>(resolve => { unlock = resolve; });
const acquired = new Promise<void>(resolve => { locked = resolve; });
const lock = db.transaction(async tx => {
await tx.execute(sql`lock table tool_policies in access exclusive mode`);
// Pause tool discovery before admission locks the invocation. Revocation
// cannot legitimately take that lock from an in-flight admission.
await tx.execute(sql`lock table tool_catalog_entries in access exclusive mode`);
locked(); await gate;
});
await acquired;
+26 -16
View File
@@ -108,6 +108,13 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
}
async function dispatch(job: Job, trigger: Trigger, signal?: AbortSignal): Promise<TriggerJobResult | null> {
// Reserve synchronously at the one dispatch boundary. A refresh may have
// yielded since filtering its snapshot; it cannot borrow a manual run's slot.
if (activeJobs.has(job.id) || pendingSettlements.has(job.id)) {
if (trigger !== "schedule") throw new Error(`Job "${job.jobKey}" is already running`);
return null;
}
if (trigger === "schedule" && activeJobs.size >= maxConcurrentJobs) return null;
activeJobs.add(job.id);
try {
const run = await db.transaction(async tx => {
@@ -148,7 +155,7 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
next = null;
for (const job of runnable) {
if (!canRun() || signal?.aborted) break;
if (blocked.has(job.id)) continue;
if (blocked.has(job.id) || activeJobs.has(job.id) || pendingSettlements.has(job.id)) continue;
if (!job.nextRunAt) {
const deadline = nextCron(job.schedule, now);
if (!deadline) continue;
@@ -219,10 +226,16 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
eq(pluginJobRuns.pluginId, pluginId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
));
for (const run of runs) {
if (!activeJobs.has(run.jobId) && ["running", "queued", "pending"].includes(run.status)) {
await jobStore.completeRun(run.id, { status: "cancelled", error: "Plugin unregistered",
durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : null });
}
if (activeJobs.has(run.jobId) || pendingSettlements.has(run.jobId)) continue;
await db.transaction(async tx => {
const [current] = await tx.select().from(pluginJobRuns).where(eq(pluginJobRuns.id, run.id)).for("update");
// A completion may have committed after the discovery read. Never
// overwrite its result, or the result still retained for persistence.
if (!current || !["running", "queued", "pending"].includes(current.status)
|| activeJobs.has(current.jobId) || pendingSettlements.has(current.jobId)) return;
await pluginJobStore(tx).completeRun(current.id, { status: "cancelled", error: "Plugin unregistered",
durationMs: current.startedAt ? Date.now() - current.startedAt.getTime() : null });
});
}
},
triggerJob(jobId, trigger = "manual") {
@@ -232,17 +245,14 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
if (!job) throw new Error(`Job not found: ${jobId}`);
if (job.status !== "active") throw new Error(`Job "${job.jobKey}" is not active (status: ${job.status})`);
if (activeJobs.has(jobId) || pendingSettlements.has(jobId)) throw new Error(`Job "${job.jobKey}" is already running`);
activeJobs.add(jobId);
try {
const runs = await db.select({ id: pluginJobRuns.id }).from(pluginJobRuns).where(and(
eq(pluginJobRuns.jobId, jobId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
)).limit(1);
if (runs.length) throw new Error(`Job "${job.jobKey}" already has a running execution`);
if (unregistered.has(job.pluginId) || !workerManager.isRunning(job.pluginId)) throw new Error(`Worker for plugin "${job.pluginId}" is not running`);
const result = await dispatch(job, trigger);
if (!result) throw new Error(`Job "${job.jobKey}" is no longer available`);
return result;
} catch (err) { activeJobs.delete(jobId); throw err; }
const runs = await db.select({ id: pluginJobRuns.id }).from(pluginJobRuns).where(and(
eq(pluginJobRuns.jobId, jobId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
)).limit(1);
if (runs.length) throw new Error(`Job "${job.jobKey}" already has a running execution`);
if (unregistered.has(job.pluginId) || !workerManager.isRunning(job.pluginId)) throw new Error(`Worker for plugin "${job.pluginId}" is not running`);
const result = await dispatch(job, trigger);
if (!result) throw new Error(`Job "${job.jobKey}" is no longer available`);
return result;
})());
},
tick,
+79 -11
View File
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { boundRunIssueIdSql } from "./run-task-binding.js";
import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm";
import type { ToolApprovalClaim } from "./tool-approval-execution.js";
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
@@ -51,6 +52,12 @@ import {
import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js";
import { canonicalToolArguments, readSignedToolArgumentsPayload, toolRequestIdentityHash } from "./tool-content-guards.js";
class RejectedInvocationAdmission extends Error {
constructor(readonly decision: ToolAccessDecision) {
super(decision.explanation);
}
}
type ToolAccessContext = {
companyId: string;
actorType: "agent" | "user" | "system" | "plugin";
@@ -715,7 +722,7 @@ function assertSupportedGenericPolicyShape(
}
}
async function getGenericPolicyRow(db: Db, companyId: string, policyId: string) {
async function getGenericPolicyRow(db: Pick<Db, "select">, companyId: string, policyId: string) {
const [policy] = await db
.select()
.from(toolPolicies)
@@ -783,7 +790,7 @@ function scopeAllowsTool(scope: Record<string, unknown> | null, ctx: ToolAccessC
return selectorMatches(selectors, ctx);
}
export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecret?: string } = {}) {
export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "update" | "delete" | "transaction">, options: { toolActionSigningSecret?: string } = {}) {
async function listPolicies(companyId: string) {
return db
.select()
@@ -1285,11 +1292,12 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
],
set: {
limit: rule.limit,
remaining: sql`greatest(0, least(${toolRateLimitCounters.remaining}, ${rule.limit}) - 1)`,
// Preserve the number already spent when an operator changes the limit.
remaining: sql`greatest(0, ${rule.limit} - (${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining}) - 1)`,
resetAt,
updatedAt: now,
},
setWhere: gt(toolRateLimitCounters.remaining, 0),
setWhere: sql`${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining} < ${rule.limit}`,
})
.returning({ remaining: toolRateLimitCounters.remaining });
if (!counter) {
@@ -1360,7 +1368,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
});
}
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise<ConsumedRateAdmission[]> {
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise<ConsumedRateAdmission[] | null> {
const [invocation] = await db.select({
actorType: toolInvocations.actorType, actorId: toolInvocations.actorId, agentId: toolInvocations.agentId,
runId: toolInvocations.runId, issueId: toolInvocations.issueId, gatewayId: toolInvocations.gatewayId,
@@ -1387,12 +1395,66 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
&& invocation.providerType === ctx.providerType && invocation.applicationKey === ctx.applicationKey
&& invocation.upstreamToolName === ctx.upstreamToolName
&& invocation.argumentsHash === ctx.argumentsHash;
const stored = authorized ? invocation.policyExplanation?.consumedRateAdmissions : null;
if (!authorized) return null;
const stored = invocation.policyExplanation?.consumedRateAdmissions;
return Array.isArray(stored) ? stored.filter((item): item is ConsumedRateAdmission => isRecord(item)
&& typeof item.policyId === "string" && CANONICAL_UUID_RE.test(item.policyId)
&& typeof item.versionHash === "string" && /^[a-f0-9]{64}$/.test(item.versionHash)) : [];
}
/** Revalidate claimed work and persist new rate charges before provider dispatch. */
async function admitInvocation(
input: ToolAccessDecisionInput,
invocationId: string,
claim?: ToolApprovalClaim,
): Promise<ToolAccessDecision> {
try {
return await db.transaction(async tx => {
const [invocation] = await tx.select().from(toolInvocations)
.where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId)))
.for("update");
// Historical reviewed requests can still have a pending invocation.
// Accept that state only with the exact executing claim owned by the
// gateway, locked in the same invocation-then-request order as dispatch.
let ownsClaim = false;
if (claim && claim.invocationId === invocationId) {
const [request] = await tx.select().from(toolActionRequests).where(and(
eq(toolActionRequests.id, claim.actionRequestId),
eq(toolActionRequests.invocationId, invocationId),
eq(toolActionRequests.companyId, input.companyId),
)).for("update");
ownsClaim = request?.status === "executing" && request.updatedAt.getTime() === claim.claimedAt.getTime();
}
if (!invocation || (claim && !ownsClaim)
|| !(invocation.status === "executing" && invocation.policyDecision === "allow"
|| ["awaiting_approval", "executing"].includes(invocation.status)
&& invocation.policyDecision === "require_approval" && invocation.approvalState === "approved"
|| invocation.status === "awaiting_approval" && invocation.policyDecision === "require_approval"
&& invocation.approvalState === "pending" && ownsClaim)) {
return decision("deny", "deny_policy_block", "Tool invocation admission is unavailable.", [], []);
}
const result = await toolAccessPolicyService(tx, options).decide(
{ ...input, consumeRateLimit: true }, { admittedInvocationId: invocationId },
);
if (!result.allowed && result.decision !== "require_approval") {
// A later policy can reject after an earlier rate rule spent a slot.
// Roll back both the new charges and their receipt on any rejection.
throw new RejectedInvocationAdmission(result);
}
const admissions = result.policyExplanation?.consumedRateAdmissions;
if (Array.isArray(admissions) && admissions.length) {
await tx.update(toolInvocations).set({
policyExplanation: { ...invocation.policyExplanation, consumedRateAdmissions: admissions },
}).where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId)));
}
return result;
});
} catch (error) {
if (error instanceof RejectedInvocationAdmission) return error.decision;
throw error;
}
}
/**
* Decides one tool access request. Pass the same `cache` to every call of a
* batch that shares one actor and run context (for example, one tools/list
@@ -1423,9 +1485,14 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
// A final handoff rechecks current permissions for work already admitted by
// the gateway. Its own last consumed slot cannot reject that same work.
// Only durable consumption of an unchanged rule retains that slot; new or
// edited rules still apply. This option never approves or consumes a call.
const admittedRates = input.consumeRateLimit === false && options.admittedInvocationId
// edited rules still apply. admitInvocation owns atomic consuming rechecks;
// ordinary preflight and browser handoff callers remain read-only.
const admittedRates = options.admittedInvocationId
? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId) : [];
if (options.admittedInvocationId && input.consumeRateLimit === true && admittedRates === null) {
return decision("deny", "deny_policy_block", "Tool invocation no longer matches this admission.", [], []);
}
if (input.consumeRateLimit === true) consumedRateAdmissions.push(...(admittedRates ?? []));
const profileState = await effectiveProfiles(ctx, cache);
const effectiveProfileIds = profileState.profiles.map((profile) => profile.id);
const permittedByProfile = profileState.profiles.some((profile) => {
@@ -1498,7 +1565,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
);
}
const versionHash = ratePolicyVersionHash(policy);
if (admittedRates.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue;
if (admittedRates?.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue;
const state = await enforceRateLimit(policy, ctx, input.consumeRateLimit === true);
if (state?.limited) {
return decision("rate_limited", "rate_limited", "Tool access rate limit exceeded.", effectiveProfileIds, [policy.id], { rateLimitState: state, redactionPlan: redaction.redactionPlan, policyExplanation });
@@ -1524,7 +1591,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
{ redactionPlan: redaction.redactionPlan, policyExplanation },
);
}
if (input.consumeRateLimit === true) {
if (input.consumeRateLimit === true && !options.admittedInvocationId) {
await recordTrustRuleHit(policy, ctx, redaction);
}
return decision("allow", "allow_trust_rule", policy.description ?? "Tool access allowed by trust rule.", effectiveProfileIds, [policy.id], { redactionPlan: redaction.redactionPlan, policyExplanation });
@@ -2151,6 +2218,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
return {
decide,
admitInvocation,
writeAudit,
recordInvocation,
summarizeAndRedact,
+6 -4
View File
@@ -7667,9 +7667,10 @@ export function createToolGatewayService(
if (!(await approvedManagedArgumentsRemainCurrent(session, tool, signedPayload.arguments))) {
throw new ToolGatewayHttpError(409, "Approved tool action managed arguments changed after review", "approved_tool_managed_arguments_changed");
}
const access = await policyService.decide(
const access = await policyService.admitInvocation(
policyInputForTool({ session, tool, parameters: signedPayload.arguments, consumeRateLimit: false }),
{ admittedInvocationId: invocation.id },
invocation.id,
claim,
);
if (!access.allowed && access.decision !== "require_approval") {
throw new ToolGatewayHttpError(403, access.explanation, access.reasonCode);
@@ -8102,14 +8103,15 @@ export function createToolGatewayService(
session,
tool,
);
const currentAccess = await policyService.decide(
const currentAccess = await policyService.admitInvocation(
policyInputForTool({
session,
tool,
parameters: signedPayload.arguments,
consumeRateLimit: false,
}),
{ admittedInvocationId: invocation.id },
invocation.id,
claim,
);
if (
!currentAccess.allowed &&
+2 -2
View File
@@ -11,7 +11,7 @@ function minuteBucket(date: Date): Date {
}
export async function incrementToolRuntimeMetricCounter(
db: Db,
db: Pick<Db, "insert">,
input: {
companyId: string;
metric: string;
@@ -42,7 +42,7 @@ export async function incrementToolRuntimeMetricCounter(
});
}
export async function recordToolRuntimeAuditWriteFailure(db: Db, companyId: string) {
export async function recordToolRuntimeAuditWriteFailure(db: Pick<Db, "insert">, companyId: string) {
try {
await incrementToolRuntimeMetricCounter(db, {
companyId,