perf(db): add partial indexes for chat_actions run publications and pending work (#23811)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - External chat connectors (GitHub, Slack, Telegram, voice) store
webhook ingress, publication receipts, and scheduled background work in
`chat_actions`
> - On large instances (~325k rows in `chat_actions`, mostly processed
`github_webhook_ingress`), two hot query families fall back to full
sequential scans because existing partial indexes do not cover their
predicates
> - `githubRunReplyState` queries `kind = 'github_review_publication'`
across all statuses (including unsettled
`received`/`processing`/`failed` rows), so PostgreSQL cannot use
`chat_actions_github_task_publications_idx` (`WHERE kind =
'github_review_publication' AND status = 'processed'`)
> - Scheduled work polling (`nextChatActionAt`, `dueChatAction`, and
pending GitHub publication/response sweeps) filters active non-terminal
statuses (`received`, `processing`, `queued`, etc.) and retryable
failures across kinds that have no matching partial work index
> - This pull request adds two concurrent, idempotent, online-compatible
partial indexes on `chat_actions`
(`chat_actions_github_run_publications_idx` and
`chat_actions_pending_work_idx`) and adds PostgreSQL `EXPLAIN (ANALYZE,
BUFFERS)` regression coverage
> - The benefit is eliminating repeated full-table sequential scans on
`chat_actions` without locking writes during migration or altering query
semantics

## Linked Issues or Issue Description

**What happened?**
On a PostgreSQL instance with ~325k `chat_actions` rows (mostly
processed `github_webhook_ingress`), `chat_actions` incurred ~103 full
sequential scans per 5 seconds (20.6 scans/s):
- `githubRunReplyState` (`server/src/services/chat-run-publications.ts`)
ran a `Parallel Seq Scan on chat_actions` (218.6 ms, 100,595 shared
buffer hits for 1 row) because
`chat_actions_github_task_publications_idx` restricts `status =
'processed'` while `githubRunReplyState` must also inspect unsettled
rows.
- Scheduled action polling (`nextChatActionAt` and `dueChatAction` in
`server/src/services/chat-action-work.ts`, plus
`nextPendingAt`/`processPending` in
`server/src/services/chat-github-reviews.ts` and
`server/src/services/chat-github-response-comments.ts`) ran full
sequential scans (62.4 ms, 25,212 shared buffer hits) because no partial
work index covered `status IN ('received', 'processing', ...) OR (status
= 'failed' AND result->>'retryable' = 'true')` by `kind`. (Existing
`review-check-work.ts` and `acknowledgement-work.ts` do not include
`'processing'` and already use `chat_actions_github_check_work_idx` and
`chat_actions_github_ack_work_idx`.)

**Expected behavior**
PostgreSQL should resolve `githubRunReplyState` and scheduled
`chat_actions` work polling through small partial indexes in
sub-millisecond time with minimal shared buffer hits and zero full
sequential scans over completed webhook history.

**Steps to reproduce**
1. Populate `chat_actions` with ~10k+ processed `github_webhook_ingress`
and `github_review_publication` rows plus active target rows, then run
`VACUUM ANALYZE chat_actions`.
2. Run `EXPLAIN (ANALYZE, BUFFERS)` on `githubRunReplyState(...)` and on
`nextChatActionAt(db, "github_webhook_ingress")` /
`dueChatAction("github_webhook_ingress")`.
3. Observe full `Seq Scan on chat_actions` scanning all table pages
before this migration.

**Paperclip version or commit**
`master` (`6a5dfc0288`)

**Deployment mode**
Self-hosted server

## What Changed

- Added `chat_actions_github_run_publications_idx` in
`packages/db/src/schema/chat_channels.ts` on `(company_id, endpoint_id,
(payload->'session'->>'issueId'), (payload->'session'->>'runId')) WHERE
kind = 'github_review_publication'`.
- Added `chat_actions_pending_work_idx` in
`packages/db/src/schema/chat_channels.ts` on `(kind, created_at, id)
WHERE status IN ('received', 'processing', 'queued',
'provider_confirmed', 'admitting', 'resolving', 'validating',
'dispatching') OR (kind = 'failed_run_retry' AND status IN ('issued',
'processing')) OR (status = 'failed' AND result->>'retryable' =
'true')`. (Excludes permanently `'issued'` kinds such as
`task_control_authorization` and completed/cancelled/non-retryable
history so the index stays minimal at rest.)
- Generated migration
`packages/db/src/migrations/0516_exotic_spectrum.sql` with idempotent
`CREATE INDEX CONCURRENTLY IF NOT EXISTS`, registered it in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` in `packages/db/src/client.ts`,
and pruned schema snapshots to the 5 newest (`0512`–`0516`).
- Extended `server/src/__tests__/chat-admission-condition.test.ts` with
embedded PostgreSQL regression coverage verifying result behavior and
`EXPLAIN (ANALYZE, BUFFERS)` partial index usage (zero `Seq Scan` on
`chat_actions`) for `githubRunReplyState`, every `ScheduledChatAction`
in `CHAT_ACTION_QUEUES` (`nextChatActionAt`), `dueChatAction`
(`github_webhook_ingress`, `failed_run_retry`),
`githubChatReviewService.nextPendingAt`/`processPending`,
`githubResponseCommentService.processPending`, and
`speko_voice_reply_push` (`dispatching`).

## Verification

- Local red/green `EXPLAIN (ANALYZE, BUFFERS)` against embedded
PostgreSQL 18 with 10,003 `chat_actions` rows (8,000 processed
`github_webhook_ingress`, 1,000 processed `github_review_publication`,
500 processed `inbound_wakeup`, 500 issued `task_control_authorization`,
3 target rows) with strict result equality verified before and after
applying the concurrent partial-index migration SQL (and verified 2x
idempotent replay + `indisvalid = true`, `indisready = true`, index
sizes 152 kB and 16 kB):

| Query | Before | After (`0516`) |
| --- | --- | --- |
| `githubRunReplyState` | `Seq Scan` (0.900 ms, 2,204 buffer hits) |
`Index Scan(chat_actions_github_run_publications_idx)` (0.018 ms, 7
buffer hits) |
| `nextChatActionAt(github_webhook_ingress)` | `Seq Scan` (1.169 ms,
2,200 buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)`
(0.011 ms, 2 buffer hits) |
| `nextChatActionAt(provider_effect)` | `Seq Scan` (0.891 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.005 ms, 1
buffer hit) |
| `nextChatActionAt(failed_run_retry)` | `Index
Scan(chat_actions_company_issue_kind_idx)` (0.028 ms, 11 buffer hits) |
`Index Scan(chat_actions_pending_work_idx)` (0.006 ms, 2 buffer hits) |
| `nextChatActionAt(slash_task_start)` | `Seq Scan` (0.839 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.007 ms, 1
buffer hit) |
| `dueChatAction(github_webhook_ingress)` | `Seq Scan` (1.148 ms, 2,200
buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)` (0.010
ms, 2 buffer hits) |
| `chat-github-reviews.nextPendingAt()` | `Seq Scan` (0.807 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.004 ms, 2
buffer hits) |

- Verified prepared-statement execution (`PREPARE` + 10 `EXECUTE` runs)
keeps custom partial-index plans on the 10th execution (`0.004–0.010
ms`) and does not regress `githubLatestTaskResponseUrl`
(`chat_actions_github_task_publications_idx`) or `review-check-work`
(`chat_actions_github_check_work_idx`).
- Ran local checks on commit `97f0f7294262aa129dd283072108ce6932f3a447`:
  - `pnpm --filter @paperclipai/db build` — PASS
- `pnpm --filter @paperclipai/db check:migrations` — PASS (1 new
migration, `online_compatible`, none blocked)
  - `pnpm check:module-boundaries` — PASS
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 1 test file checked)
- `pnpm --filter @paperclipai/db typecheck` & `pnpm --filter
@paperclipai/server typecheck` — PASS
- `pnpm exec vitest run packages/db/src/check-migration-safety.test.ts
packages/db/src/migration-compatibility.test.ts
packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/chat-admission-condition.test.ts` — 4 files, 149
tests passed

## Risks

- Low risk: purely additive migration creating two partial indexes with
`CREATE INDEX CONCURRENTLY IF NOT EXISTS` in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. Writes are not blocked during
index build, existing indexes
(`chat_actions_github_task_publications_idx`,
`chat_actions_github_check_work_idx`,
`chat_actions_github_ack_work_idx`) remain untouched, and previous
releases continue serving safely during rolling deploy.
- Small write-amplification trade-off: active `chat_actions` rows enter
`chat_actions_pending_work_idx` while non-terminal and leave once
settled; `chat_actions_github_run_publications_idx` tracks
`github_review_publication` rows only (excluding high-volume
`github_webhook_ingress` history).

## Model Used

- Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and
code execution)

## 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
- [ ] 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-12-04 20:38:15 -06:00
1 parent 84ca111c78
commit 83d80b431b
6 files changed
+1831 -4

No files matched your search

@@ -1,9 +1,14 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { and, eq } from "drizzle-orm";
import { and, asc, eq } from "drizzle-orm";
import { agentWakeupRequests, agents, chatActions, chatConversations, createDb, issues, type Db } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { seedGitHubReviewWait } from "./helpers/github-review-wait.js";
import { dueChatAction, nextChatActionAt } from "../services/chat-action-work.js";
import { githubResponseCommentService } from "../services/chat-github-response-comments.js";
import { githubChatReviewService } from "../services/chat-github-reviews.js";
import { githubRunReplyState } from "../services/chat-run-publications.js";
import { CHAT_ACTION_QUEUES, type ScheduledChatAction } from "../services/chat-work-notifications.js";
import { unadmittedChatWakeupCondition } from "../services/durable-chat-wakeup.js";
// Pins which saved chat input holds an issue as "not admitted". Recovery skips
@@ -168,4 +173,209 @@ describe("unadmitted chat wakeup condition", () => {
expect(scans.length).toBeGreaterThan(0);
for (const scan of scans) expect(scan).toMatch(/Index.*Scan:chat_actions_company_issue_kind_idx/);
});
it("uses chat_actions partial indexes for GitHub run reply state and scheduled work polling", async () => {
const s = await seed();
const runId = randomUUID();
const explainChatActions = async (querySql: string, params: unknown[]) => {
const [row] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${querySql}`, params as never[]);
const seqScans: string[] = [];
const indexScans: string[] = [];
const walk = (node: Record<string, unknown>) => {
const nodeType = String(node["Node Type"] ?? "");
const relation = node["Relation Name"];
const indexName = node["Index Name"];
if (relation === "chat_actions" && nodeType.includes("Seq Scan")) seqScans.push(nodeType);
if (typeof indexName === "string" && indexName.startsWith("chat_actions_")) {
indexScans.push(`${nodeType}:${indexName}`);
}
for (const child of (node.Plans as Array<Record<string, unknown>> | undefined) ?? []) walk(child);
};
walk((row!["QUERY PLAN"] as Array<{ Plan: Record<string, unknown> }>)[0]!.Plan);
return { seqScans, indexScans };
};
const captureSelects = async (fn: () => Promise<void>) => {
const captured: Array<{ sql: string; params: unknown[] }> = [];
const previousDebug = db.$client.options.debug;
db.$client.options.debug = (_conn: number, text: string, params: unknown[]) => {
if (/^select\b/i.test(text.trim()) && text.includes('"chat_actions"')) {
captured.push({ sql: text, params: [...params] });
}
};
try {
await fn();
} finally {
db.$client.options.debug = previousDebug;
}
return captured;
};
try {
await db.$client.unsafe(
`insert into chat_actions (company_id, endpoint_id, kind, provider_action_id, status, payload, result)
select $1::uuid, $2::uuid, 'github_webhook_ingress', 'hist-ingress-' || g, 'processed',
jsonb_build_object('deliveryId', 'd-' || g, 'body', repeat('x', 500)),
jsonb_build_object('httpStatus', 200, 'retryable', false)
from generate_series(1, 4000) g`,
[s.companyId, s.endpointId],
);
await db.$client.unsafe(
`insert into chat_actions (company_id, endpoint_id, conversation_id, kind, provider_action_id, status, payload, result)
select $1::uuid, $2::uuid, $3::uuid, 'github_review_publication', 'hist-pub-' || g, 'processed',
jsonb_build_object('operation', 'comment', 'session', jsonb_build_object('companyId', $1::text, 'issueId', gen_random_uuid()::text, 'runId', gen_random_uuid()::text, 'agentId', $4::text)),
jsonb_build_object('id', 'c-' || g, 'url', 'https://github.com/o/r/pull/1#issuecomment-' || g)
from generate_series(1, 500) g`,
[s.companyId, s.endpointId, s.conversationId, s.agentId],
);
await db.$client.unsafe(
`insert into chat_actions (company_id, endpoint_id, kind, provider_action_id, status, payload)
select $1::uuid, $2::uuid, 'task_control_authorization', 'hist-auth-' || g, 'issued',
jsonb_build_object('publicationId', gen_random_uuid()::text)
from generate_series(1, 500) g`,
[s.companyId, s.endpointId],
);
const pubId = randomUUID();
const ingressId = randomUUID();
const retryId = randomUUID();
await db.insert(chatActions).values([
{
id: pubId,
companyId: s.companyId,
endpointId: s.endpointId,
conversationId: s.conversationId,
kind: "github_review_publication",
providerActionId: `pub-target-${pubId}`,
status: "processing",
payload: {
operation: "comment",
session: { companyId: s.companyId, issueId: s.issueId, runId, agentId: s.agentId },
},
result: { replyWriteStarted: true },
},
{
id: ingressId,
companyId: s.companyId,
endpointId: s.endpointId,
kind: "github_webhook_ingress",
providerActionId: `ingress-target-${ingressId}`,
status: "received",
payload: { deliveryId: "target" },
},
{
id: retryId,
companyId: s.companyId,
endpointId: s.endpointId,
kind: "failed_run_retry",
providerActionId: `retry-target-${retryId}`,
status: "issued",
payload: { issueId: s.issueId },
},
]);
await db.$client.unsafe("analyze chat_actions");
let replyState: Awaited<ReturnType<typeof githubRunReplyState>> | undefined;
const replyQueries = await captureSelects(async () => {
replyState = await githubRunReplyState(db, {
companyId: s.companyId,
endpointId: s.endpointId,
issueId: s.issueId,
runId,
});
});
expect(replyState).toBe("unsettled");
expect(replyQueries).toHaveLength(1);
const replyPlan = await explainChatActions(replyQueries[0]!.sql, replyQueries[0]!.params);
expect(replyPlan.seqScans).toEqual([]);
expect(replyPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_github_run_publications_idx"))).toBe(true);
await db.update(chatActions)
.set({ status: "processed", result: { id: "c-target", url: "https://github.com/o/r/pull/1#issuecomment-target" } })
.where(eq(chatActions.id, pubId));
await expect(githubRunReplyState(db, {
companyId: s.companyId,
endpointId: s.endpointId,
issueId: s.issueId,
runId,
})).resolves.toBe("confirmed");
let ingressNext: number | null = null;
const scheduledKinds = Object.keys(CHAT_ACTION_QUEUES) as ScheduledChatAction[];
const workQueries = await captureSelects(async () => {
for (const kind of scheduledKinds) {
const at = await nextChatActionAt(db, kind);
if (kind === "github_webhook_ingress") ingressNext = at;
}
});
expect(ingressNext).toBe(0);
expect(workQueries).toHaveLength(scheduledKinds.length);
for (const query of workQueries) {
const plan = await explainChatActions(query.sql, query.params);
expect(plan.seqScans).toEqual([]);
expect(plan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
}
const noProviderFetch: typeof fetch = async () => {
throw new Error("unexpected provider call");
};
const githubReviewQueries = await captureSelects(async () => {
const reviews = githubChatReviewService(db, noProviderFetch);
await reviews.nextPendingAt();
await reviews.processPending();
});
expect(githubReviewQueries).toHaveLength(2);
for (const query of githubReviewQueries) {
const plan = await explainChatActions(query.sql, query.params);
expect(plan.seqScans).toEqual([]);
expect(plan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
}
const githubResponseQueries = await captureSelects(async () => {
await githubResponseCommentService(db, noProviderFetch).processPending();
});
expect(githubResponseQueries.length).toBeGreaterThanOrEqual(1);
const pendingResponsePlan = await explainChatActions(githubResponseQueries[0]!.sql, githubResponseQueries[0]!.params);
expect(pendingResponsePlan.seqScans).toEqual([]);
expect(pendingResponsePlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
const voiceDispatchSql = db
.select({ id: chatActions.id })
.from(chatActions)
.where(and(eq(chatActions.kind, "speko_voice_reply_push"), eq(chatActions.status, "dispatching")))
.orderBy(asc(chatActions.id))
.limit(100)
.toSQL();
const voiceDispatchPlan = await explainChatActions(voiceDispatchSql.sql, voiceDispatchSql.params);
expect(voiceDispatchPlan.seqScans).toEqual([]);
expect(voiceDispatchPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
const dueIngressQuery = db
.select({ id: chatActions.id })
.from(chatActions)
.where(dueChatAction("github_webhook_ingress", Date.now()))
.orderBy(asc(chatActions.createdAt))
.limit(25);
const dueIngressRows = await dueIngressQuery;
expect(dueIngressRows.map((row) => row.id)).toContain(ingressId);
const dueIngressSql = dueIngressQuery.toSQL();
const dueIngressPlan = await explainChatActions(dueIngressSql.sql, dueIngressSql.params);
expect(dueIngressPlan.seqScans).toEqual([]);
expect(dueIngressPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
const dueRetryQuery = db
.select({ id: chatActions.id })
.from(chatActions)
.where(dueChatAction("failed_run_retry", Date.now()))
.orderBy(asc(chatActions.createdAt), asc(chatActions.id))
.limit(20);
const dueRetryRows = await dueRetryQuery;
expect(dueRetryRows.map((row) => row.id)).toContain(retryId);
const dueRetrySql = dueRetryQuery.toSQL();
const dueRetryPlan = await explainChatActions(dueRetrySql.sql, dueRetrySql.params);
expect(dueRetryPlan.seqScans).toEqual([]);
expect(dueRetryPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true);
} finally {
await db.delete(chatActions).where(eq(chatActions.companyId, s.companyId));
}
});
});