perf(chat): stop polling provider action and session sync queues (#15822)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat stores pending provider actions in durable database rows.
> - Three action queues still scan every second when empty.
> - These scans keep idle databases active.
> - This pull request wakes those queues after a commit or at their next
deadline.
> - Empty queues stop querying while existing recovery rules remain in
place.

## Linked Issues or Issue Description

Refs #15808, #15802, #15625. Related sleep work: #15750, #15757.

**What existing behavior does this improve?**

Provider messages and notices, accepted GitHub webhook receipts, and
Slack session status synchronization.

**Current behavior**

Chat maintenance scans these three queues every second. It also rechecks
paused Slack sync rows every 30 seconds.

**Proposed behavior**

Reuse the transaction-aware action workers and existing chat_actions
rows. Wake after commits. Restore unfinished work on startup. Use stored
retry and stale-claim deadlines. Stop scanning when empty. Park paused
Slack sync rows until an endpoint change.

## What Changed

- Add three topics to the existing action worker registration. No
tables, migrations, triggers, or external services.
- Signal producers, claims, retry updates, terminal settlements, and
operator resolution inside their owning transaction. Provider I/O
remains outside transactions.
- Share pending-state and deadline predicates between dispatch and
scheduling. Exclude terminal history and uncertain provider sends.
- Preserve GitHub receipt attempt fences and provider-send quarantine.
Preserve Slack's 30-minute refresh while a session is processing.
- Remove these workers from periodic app maintenance. Update the sleep
inventory and add regression coverage.

## Verification

- Passed: 13 focused tests across scheduler, app wiring, and real
PostgreSQL integration. Covers actual commit wakes with deferred fast
paths disabled, GitHub retries and startup recovery, stale-send
quarantine, Slack publication-to-sync delivery, paused deadlines, and
idle queues.
- Passed: pnpm typecheck.
- Passed: full chat integration and related coordinator suites, **1,274
tests across five files**.
- Passed: pnpm build.
- Greptile: **5/5**, no actionable findings, completed on
`dc284cd275e5f6df624d60b27954421f2bcdbee2`.
- Hosted CI: **54 checks passed**, two intentionally skipped Storybook
checks, no failures or pending checks on
`dc284cd275e5f6df624d60b27954421f2bcdbee2`.

Provider responses are simulated. PostgreSQL, transactions, service
dispatch, and scheduling are real. No live Slack or GitHub App was used.

## Risks

- Writers must emit the existing process-local transaction signal.
Independent database clients and direct SQL still need explicit
integration or startup recovery.
- Accepted GitHub receipts are covered. Finding callbacks GitHub never
delivered still uses the separate provider recovery lane.
- Other chat maintenance and persistent transports still run. This does
not establish whole-instance sleep.
- Existing claim, revision, credential, and authorization checks remain
authoritative during concurrent foreground and scheduled dispatch.

## Model Used

OpenAI Codex (GPT-6), with repository inspection, code execution, and
automated tests.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-11 06:08:05 -05:00
1 parent 30e338fba6
commit e733bddc45
10 files changed
+382 -192

No files matched your search

@@ -106,6 +106,12 @@ describe("createChatReconciliationCoordinator", () => {
// The service integration tests hold real publication workers while this
// scheduled method returns; app shutdown must also join those workers.
expect(source).toContain("await chatChannels.shutdown()");
expect(source).not.toContain("chatChannels.processPendingSlackSessionSyncs()");
const service = readFileSync(new URL("../services/chat-channels.ts", import.meta.url), "utf8");
const actionMaintenance = service.slice(service.indexOf("async function processPendingChatMaintenance("),
service.indexOf("async function processPendingDeliveries("));
expect(actionMaintenance).not.toContain("processPendingProviderEffects(");
expect(actionMaintenance).not.toContain("processPendingGitHubWebhookIngress(");
});
it.each([false, true])(
@@ -19,6 +19,9 @@ function setup() {
const coordinator = createDeliveryWorkCoordinator({ owner, canRun: enabled, canReconcile: enabled, onError });
coordinators.push(coordinator);
const service = {
processPendingProviderEffects: vi.fn(async () => {}),
processPendingGitHubWebhookIngress: vi.fn(async () => {}),
processPendingSlackSessionSyncs: vi.fn(async () => {}),
processPendingSlackBoardMessages: vi.fn(async () => {}),
processPendingSlackTaskStarts: vi.fn(async () => {}),
processPendingReceiptReactions: vi.fn(async () => {}),
@@ -27,7 +30,7 @@ function setup() {
nextChatActionAt: vi.fn(async (): Promise<number | null> => null),
nextVerificationMessageAt: vi.fn(async (): Promise<number | null> => null),
};
const runs = [service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts,
const runs = [service.processPendingProviderEffects, service.processPendingGitHubWebhookIngress, service.processPendingSlackSessionSyncs, service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts,
service.processPendingReceiptReactions, service.processPendingSlackSessionStops, service.processPendingVerificationMessages];
return { owner, service, runs, coordinator, enabled, onError, start: () => registerChatActionWork(coordinator, service, enabled) };
}
@@ -37,7 +40,7 @@ describe("chat action scheduling", () => {
await s.start().ready;
await vi.advanceTimersByTimeAsync(3_600_000);
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(1);
expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(4);
expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(7);
expect(s.service.nextVerificationMessageAt).toHaveBeenCalledTimes(1);
expect(s.coordinator.nextWakeAt()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
@@ -13250,6 +13250,49 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
await service.shutdown();
});
it("drains accepted GitHub webhooks from commit wakes and durable retry deadlines", async () => {
const fixture = await seedCompany();
const { endpoint, runtime, service, webhookSecret } = await configuredGitHubEndpoint(fixture, {
deferWebhookProcessing: true, scheduleDeferredWork: () => undefined,
});
const providerRuntime = runtime.endpoints.get(endpoint.id)!;
let attempts = 0;
providerRuntime.webhookHook = async () => {
providerRuntime.webhookResponse = new Response("result", { status: ++attempts === 1 ? 503 : 202 });
};
const delivery = randomUUID();
const send = () => service.handleWebhook(endpoint.publicId, "github", signedGitHubWebhookRequest({
delivery, event: "installation_repositories", payload: { action: "added", installation: { id: 2468 } }, webhookSecret,
}));
const onError = vi.fn();
let coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
const receipt = () => db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, `github_webhook_ingress:${delivery}`))).then(rows => rows[0]);
try {
await registerChatActionWork(coordinator, service, () => true).ready;
expect((await send()).status).toBe(202);
await expect.poll(async () => (await receipt())?.status, { timeout: 10_000 }).toBe("processed");
expect(attempts).toBe(2);
expect((await receipt())?.result).toMatchObject({ attempts: 2, httpStatus: 202 });
// A duplicate callback wakes the lane but cannot repeat a settled effect.
await send();
await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 10_000 });
expect(attempts).toBe(2);
await coordinator.stop();
// Work committed while no worker exists is recovered by the next startup.
const restartDelivery = randomUUID();
await service.handleWebhook(endpoint.publicId, "github", signedGitHubWebhookRequest({
delivery: restartDelivery, event: "installation_repositories",
payload: { action: "added", installation: { id: 2468 } }, webhookSecret,
}));
expect(attempts).toBe(2);
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
await registerChatActionWork(coordinator, service, () => true).ready;
await expect.poll(() => attempts, { timeout: 10_000 }).toBe(3);
expect(onError).not.toHaveBeenCalled();
} finally { await coordinator.stop(); }
});
it("safely re-arms an exact terminal GitHub delivery after an operator redelivery", async () => {
const fixture = await seedCompany();
const { endpoint, runtime, service, webhookSecret } =
@@ -32819,7 +32862,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
.update(chatEndpoints)
.set({ status: "active" })
.where(eq(chatEndpoints.id, endpoint.id));
const channelId = `C-LANE-${endpoint.id}`;
const channelId = `C${endpoint.id.replaceAll("-", "").toUpperCase()}`;
await db.insert(chatEndpointResources).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
@@ -32892,6 +32935,45 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
return { ...fixture, storage, runtime, service, lanes, enqueue, cleanup };
}
it("wakes Slack session sync from publication commit and leaves settled action queues quiet", async () => {
const f = await publicationLaneFixture(1);
const lane = f.lanes[0]!;
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
try {
await registerChatActionWork(coordinator, f.service, () => true).ready;
await f.enqueue(0, "A completed answer");
await f.service.processPendingPublications();
await expect.poll(async () => db.select({ status: chatActions.status }).from(chatActions)
.where(and(eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "slack_session_sync"))),
{ timeout: 10_000 }).toEqual([{ status: "processed" }]);
await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 10_000 });
const scans = vi.spyOn(db, "select");
try {
await new Promise(resolve => setTimeout(resolve, 1200));
expect(scans).not.toHaveBeenCalled();
} finally { scans.mockRestore(); }
expect(onError).not.toHaveBeenCalled();
} finally { await coordinator.stop(); await f.cleanup(); }
});
it("recovers stale provider sends on startup without replaying uncertain effects", async () => {
const f = await publicationLaneFixture(1);
const lane = f.lanes[0]!;
const [action] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: lane.endpoint.id,
kind: "provider_effect", providerActionId: randomUUID(), status: "processing", result: { attempts: 1 },
updatedAt: new Date(Date.now() - 120_000), payload: {} }).returning();
const before = lane.providerRuntime.posts.length;
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true });
try {
await registerChatActionWork(coordinator, f.service, () => true).ready;
await expect.poll(async () => db.select({ status: chatActions.status }).from(chatActions)
.where(eq(chatActions.id, action!.id)), { timeout: 10_000 }).toEqual([{ status: "delivery_unknown" }]);
expect(await f.service.nextChatActionAt("provider_effect")).toBeNull();
expect(lane.providerRuntime.posts).toHaveLength(before);
} finally { await coordinator.stop(); await f.cleanup(); }
});
it("restores action retry and stale-claim deadlines and parks paused or uncertain work", async () => {
const f = await publicationLaneFixture(1);
const lane = f.lanes[0]!;
@@ -32929,6 +33011,21 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
await set("delivery_unknown");
expect(await f.service.nextChatActionAt(kind)).toBeNull();
expect(await due()).toBe(false);
} else if (kind === "slack_session_sync") {
expect(await due()).toBe(true);
await set("received", { retryAt: later.toISOString() });
expect(await f.service.nextChatActionAt(kind)).toBe(later.getTime());
expect(await due()).toBe(false);
await set("processing");
expect(await f.service.nextChatActionAt(kind)).toBe(at.getTime() + 60_000);
for (const status of ["paused", "attention"]) {
await db.update(chatEndpoints).set({ status }).where(eq(chatEndpoints.id, lane.endpoint.id));
expect(await f.service.nextChatActionAt(kind)).toBeNull();
expect(await due()).toBe(false);
}
await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, lane.endpoint.id));
await set("failed", { retryable: true });
expect(await f.service.nextChatActionAt(kind)).toBeNull();
} else {
expect(await due()).toBe(true);
await set("processing");
@@ -53999,6 +54096,75 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
);
});
it("delivers queued provider notices from commit wakes without the deferred fast path", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, service, runtime } =
await configuredSlackEndpoint(fixture, { scheduleDeferredWork: () => undefined });
if (!callbacks.onSlashCommand) {
throw new Error("Slack slash command callback was not registered");
}
await db.insert(chatEndpointResources).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
type: "channel",
providerResourceId: "C-CONTROL-GUIDANCE",
label: "control-guidance",
availability: "available",
enabled: true,
});
const command = endpoint.setup.command;
if (!command) throw new Error("Slack endpoint did not expose its command");
const post = vi.fn(async () => ({
id: "unexpected-channel-control-post",
threadId: "slack:C-CONTROL-GUIDANCE:root",
}));
const postEphemeral = vi.fn(async () => ({
id: "channel-control-guidance",
threadId: "slack:C-CONTROL-GUIDANCE:root",
}));
const providerRuntime = runtime.endpoints.get(endpoint.id)!;
vi.spyOn(providerRuntime, "thread").mockReturnValue({ post, postEphemeral } as never);
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true });
onTestFinished(async () => { await coordinator.stop(); });
await registerChatActionWork(coordinator, service, () => true).ready;
for (const control of ["status"] as const) {
await callbacks.onSlashCommand({
endpointId: endpoint.id,
provider: "slack",
event: {
channel: {
id: "slack:C-CONTROL-GUIDANCE",
name: "control-guidance",
isDM: false,
post,
postEphemeral,
} as never,
command,
text: control,
triggerId: `channel-control-${control}`,
user: {
userId: "U-CHANNEL-CONTROLLER",
userName: "channel-controller",
fullName: "Channel Controller",
isBot: false,
isMe: false,
isSystem: false,
},
raw: { command, text: control },
adapter: {} as never,
openModal: async () => undefined,
},
});
}
await expect.poll(async () => db.select({ status: chatActions.status }).from(chatActions)
.where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "provider_effect"))),
{ timeout: 10_000 }).toEqual([{ status: "processed" }]);
expect(postEphemeral).toHaveBeenCalledTimes(1);
expect(post).not.toHaveBeenCalled();
expect(await service.nextChatActionAt("provider_effect")).toBeNull();
await coordinator.stop();
});
it("returns ephemeral guidance for exact Slack controls in channels without creating tasks or actions", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, service } =
@@ -54438,6 +54604,9 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const fixture = await seedCompany();
const { callbacks, endpoint, runtime, service } =
await configuredTelegramEndpoint(fixture);
const workWake = vi.fn();
const stopWorkObserver = subscribeDeliveryWork(db, DELIVERY_QUEUES.chatProviderEffects, workWake);
onTestFinished(() => { stopWorkObserver(); expect(workWake).toHaveBeenCalled(); });
if (!callbacks.onSlashCommand) {
throw new Error("Telegram slash command callback was not registered");
}