Files
PaperClipAI/scripts
DottaandPaperclip a91f78e7e0 perf(chat): reduce inbound queue discovery cost (#17971)
## Thinking Path

> - Paperclip helps people manage companies of AI agents.
> - External chat messages enter a durable delivery queue.
> - Queue reads must preserve pending wake ownership and conversation
order.
> - Retained processed history increases the estimated cost of a
correlated pending-action test.
> - PostgreSQL 17 enables JIT for these small selectors and reads extra
JSON in deadline discovery.
> - This pull request uses a scoped pending-action set for open-work
discovery.
> - The benefit is less database work with the same selected deliveries
and deadlines.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Inbound delivery deadline discovery and conversation-head selection.

**Subsystem affected**

Server chat queue discovery.

**Current behavior**

A correlated `EXISTS` inside an `OR` has a high cost estimate on
retained completed history. PostgreSQL 17 already hashes its
pending-action read, but the estimate still enables JIT. Deadline
discovery also reads JSON from completed deliveries that have no pending
wake.

**Proposed behavior**

Use `(company_id, endpoint_id, delivery_id)` membership in the
pending-action set for the two open-work selectors. Keep ready-only
evaluation on its original scoped `EXISTS`. Keep retry, lease, ordering,
lifecycle and endpoint rules.

**Reason and benefit**

The local retained-history fixture reduces deadline selection time. The
small control and the final head selection are neutral. Ready-only
selection remains an unchanged control.

**Breaking changes**

None. No API, schema, migration, stored history, worker, timer or
notification changes.

Related work: #17647 and #15927 change inbound wake-notice scheduling
and selection. This PR changes the separate conversation queue ownership
predicate.

## What Changed

- Use a fully scoped pending-action set for open-work discovery. Exclude
null delivery IDs to preserve exact boolean results. Keep duplicate
actions from multiplying deliveries.
- Preserve the original ready-only query.
- Add five real PostgreSQL tests and a reproducible baseline/treatment
benchmark. Capture the complete real service SQL, parameters, positional
rows and execution plans.
- Document the query cause, rejected hypotheses, test results and limits
in `doc/plans/2026-10-27-inbound-queue-query-proof.md`.

## Verification

Pinned pre-fix baseline: `09ad9adce2cf4742944353a3707a2f908e9bb35e`.

Local fixture: Linux ARM64 PostgreSQL 17.11, Node 26.4.0. It has 1500
completed deliveries and actions, two open deliveries, and 32 KiB of
synthetic incompressible JSON per historical delivery. A separate
control has 20 completed rows. The normal settings use JIT on with a
100000 cost threshold, 128 MiB shared buffers and 4 MiB work_mem.

The final quiet retained-history pair measured these local SQL medians.
Each
arm has two warmups and five alternating samples. The small control is
neutral.

| Actual selector | Baseline | Treatment | Complete positional output |
| --- | ---: | ---: | --- |
| Next inbound deadline | 18.78 ms | 1.58 ms | Equal |
| Conversation head | 5.71 ms | 6.18 ms | Equal |
| Ordinary ready control | 9.23 ms | 8.33 ms | Equal ; unchanged |

The deadline plan uses fewer shared buffers. Head physical reads remain
unchanged. Deadline discovery avoids JIT on this fixture. The pristine
head estimate is below the JIT threshold in both arms, and its timing is
neutral. With JIT disabled, deadline discovery still improves; head and
ready timings overlap.

- Red: the unchanged baseline fails the explicit local fixture work
budget for JIT and deadline buffer reads. Green: the treatment passes.
There is no timing threshold in ordinary CI.
- Five new PostgreSQL tests and six existing assembled chat tests pass.
They cover scoped/null/duplicate pending actions, boolean results,
payloads, head barriers, reactions, paused/attention/AgentMail
exclusions, retry/processing deadlines, provider ordering, lease loss,
lifecycle retry and edit/admission races.
- Actual old/new ready selectors have equal error outcomes for unrelated
malformed retry timestamps. An initial AND-only oracle comparison was
inconclusive and is not defect evidence.
- `pnpm -r typecheck` passes.
- `pnpm build` passes.
- Final head `f3cac298d8a8a5377127b0db7057c52019bbe426` passes the
complete [CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/40625611887).
Greptile is 5/5 on that head with no unresolved review threads. The
earlier end-to-end cleanup lock-timeout failure passed on this revision.
- The complete local suite was not run. The host's known native
PostgreSQL startup failure exhausts SysV semaphores. Focused integration
tests use a disposable Docker PostgreSQL constructor through the
existing test seam. Complete final-head CI is required.

Reproduce the real SQL comparison:

```sh
pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-inbound-queue-discovery.ts --baseline-ref=09ad9adce2cf4742944353a3707a2f908e9bb35e --require-work-budget --retained-only
```

Use `--jit-off` for the diagnostic control. The default command uses the
repository's bundled PostgreSQL version and records it in output. The
reported 17.11 run used the existing test constructor seam with a
disposable `postgres:17` container. Raw samples, complete queries,
parameters and plans are emitted as JSON. The benchmark uses disposable
synthetic data and does not read a live database URL.

## Risks

- Query plans depend on data and PostgreSQL settings. These local
measurements do not prove deployed speed or request latency.
- Head selection still reads historical JSON. Action history remains
stored and scanned. This is not a constant-time queue implementation.
- The changed false branch has no retry timestamp cast. Ready-only
parsing, claims and retries stay on their existing query.
- Background SQL totals can overlap. Do not add these savings into an
HTTP latency claim. The largest possible saving for an affected
selection is bounded by its observed SQL time, about 49–53 ms on average
in discovery.

## Model Used

OpenAI Codex, GPT-6 family, with tool use and code execution. The
runtime does not expose the exact model ID or context-window size. Three
parallel agents own separate performance fixes; this PR contains only
the inbound queue fix.

## 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>
2026-10-28 07:19:22 -05:00
..
2026-04-09 06:14:12 -05:00