mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## 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>