Files
PaperClipAI/packages/shared
DottaandPaperclip 0960dd464d perf(chat): eliminate activity_log seq scans, chat load waterfalls, and transcript storms (#23750)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Persistent agent chat pages (`/:companyPrefix/chats/:agentRef`) are
a primary surface for collaborating with an agent across many tasks and
turns.
> - Opening an active agent chat page was slow: multiple endpoints
scanned the full `activity_log` table, the page bypassed the
single-request chat bootstrap, the native transcript hook aborted and
retried historical run fetches across multiple waves, and pending task
questions triggered N+1 per-task interaction requests.
> - These bottlenecks blocked the initial chat reveal for several
seconds and saturated server and database capacity during page open.
> - This pull request eliminates the `activity_log` sequential scans
with index-backed predicates (no schema migrations), batches
pending-question interaction hydration, defers completed saved-reply run
transcripts in persistent agent chats, stabilizes per-run transcript
lifecycles, and enables parallel chat resolution and chat-bootstrap
adoption on agent chat pages.
> - The benefit is dramatically faster agent chat page loads with far
fewer HTTP requests, zero `activity_log` full-table scans on hot chat
paths, and no schema migrations.

## Linked Issues or Issue Description

Related: #18461, #20355, #21650, #21671.

**What happened?**

Opening a persistent agent chat page with accumulated history and active
tasks took multiple seconds before the conversation became visible and
triggered dozens of concurrent API requests:

1. `decisionHistoryService.list` (`handledForBySource`) scanned all rows
of `activity_log` because `(details ->> 'handledForUserId') IS NOT NULL`
alone did not bind the second key of
`activity_log_company_handled_for_created_idx`, and `decisions` used
`NOT IN (SELECT id FROM issues ...)` which planned a full-company
privacy subquery even when no settled decisions existed.
2. `activityService.forIssue` scanned all rows of `activity_log` because
the `project.created` and `company.skill_created` branches omitted
`entity_type`, preventing index scans.
3. `attentionService.taskQuestions` executed steady-state write
transactions in `decision-retention` and unnecessary plan-document reads
on read paths, and `CoordinatorChatPendingQuestion` mounted an
`AttentionInteractionResolver` per question that fired one `GET
/api/issues/:taskId/interactions` request per pending question.
4. `TaskChatThread` disabled saved-reply transcript deferral in
`conversationMode`, fetching `/events` (and legacy `/log` fallbacks) for
every historical completed run in the comment window, while
`useNativeRunTranscripts` used a single shared `AbortController` that
aborted and restarted in-flight sibling reads whenever run membership or
live-stream state changed.
5. `AgentChat` waited serially for the agent roster and session before
fetching the chat by `:agentRef`, `IssueDetail` skipped
`startIssueChatBootstrap` for conversations, and the HTML preload plugin
omitted the `AgentChat` chunk on `/chats/:ref` hard loads.

**Expected behavior**

Opening an agent chat page resolves the conversation and its first-frame
data in parallel via `chat-bootstrap`, avoids sequential scans on
`activity_log`, avoids fetching completed run transcripts when a saved
reply is already visible, avoids aborting sibling in-flight transcript
reads, and renders pending task questions without per-task N+1
interaction requests.

**Steps to reproduce**

1. Create a company with a persistent agent chat that has 20+ historical
replies from completed native runs, several hundred tasks assigned to
that agent, pending `ask_user_questions` interactions across multiple
tasks, and a large `activity_log` table.
2. Open `/:companyPrefix/chats/:agentRef` directly or from the sidebar
and inspect the network waterfall and PostgreSQL query plans for
`/activity`, `/decision-receipts`, `/pending-questions`, and
`/heartbeat-runs/:id/events`.
3. Observe full-table `Seq Scan` plans on `activity_log`, bypassed
`chat-bootstrap`, repeated aborted `/events` requests, and N+1
`/issues/:taskId/interactions` calls.

**Paperclip version or commit**

Reproduced on `ca21075837` (rebased onto `a3719da3ca`, final head
`2995820afe`).

## What Changed

- **Eliminate `activity_log` sequential scans (zero migrations)**:
- `server/src/services/activity.ts`, `server/src/routes/activity.ts`,
`server/src/routes/issues.ts`: Scope `forIssue` secondary branches by
their canonical `entity_type` (`project` for `project.created`,
`company_skill` for `company.skill_created`) and accept `companyId` from
routes so PostgreSQL uses `BitmapOr` index scans instead of a full-table
`Seq Scan`.
- `server/src/services/decision-history.ts`: Add `(details ->>
'handledForUserId') >= ''` alongside `IS NOT NULL` in
`handledForBySource` so PostgreSQL binds the partial index
`activity_log_company_handled_for_created_idx`; replace
`decision_target_issues.issue_id NOT IN (...)` with correlated `NOT
EXISTS (...)`; add a `LIMIT 1` index probe before planning the full
`decisions` privacy query when no settled decisions exist.
- `server/src/services/conversation-decision-receipts.ts`,
`server/src/routes/issues.ts`: Reuse the route's already-authorized
conversation record instead of re-querying `source()`.
- **Batch pending-question hydration and avoid steady-state retention
writes**:
- `packages/shared/src/types/attention.ts`,
`server/src/services/issue-thread-interactions.ts`,
`server/src/services/attention.ts`: Add optional `interaction?:
IssueThreadInteraction | null` on `AttentionItem`, batch-hydrate
interactions in `issueThreadInteractionService.listByIds` (grouping by
`issueId` for acceptance readiness and skipping only `z.ZodError` legacy
payloads), restrict `planDocumentMap` to actual plan confirmation
interactions, and parallelize `decisionQueueItems` and `decisionTriage`
reads in `enrichAttentionItems`.
- `server/src/services/decision-retention.ts`: Add a read-only fast path
in `syncItems` so steady-state reads skip opening a write transaction
when retention rows are already current, while still syncing and bumping
versions whenever `activityAt` changes.
- `ui/src/components/AttentionInteractionResolver.tsx`,
`ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx`:
Accept optional `initialInteraction` so inline pending-question cards
render immediately without N+1 `GET /issues/:taskId/interactions`
requests while still honoring cache updates after mutations.
- **Remove agent chat load waterfalls and transcript abort storms**:
- `ui/src/components/TaskChatThread.tsx`,
`ui/src/lib/run-answer-visibility.ts`: Defer completed `succeeded` run
transcripts that already have a visible saved reply in
`conversationMode` while preserving immediate hydration for live,
failed, yielded, pending-interaction, and unanswered runs; precompute
visible-answer lookups in linear time (`O(comments + runs)`) instead of
quadratic scans.
- `ui/src/components/transcript/useNativeRunTranscripts.ts`: Manage
`AbortController`s and poll timers per run instead of one shared
controller so adding sibling runs or transitioning stream health never
aborts in-flight reads or refetches already-hydrated terminal runs;
clear aborted in-flight tracking cleanly so expanding compact history
refetches immediately.
- `ui/src/pages/AgentChat.tsx`, `ui/src/pages/IssueDetail.tsx`,
`ui/src/lib/vite-issue-detail-preload.ts`: Start `agentChatsApi.get` by
`:agentRef` in parallel with roster/session reads on cold loads, enable
`startIssueChatBootstrap` for conversations with an existing issue ID,
and preload the `AgentChat` chunk alongside `IssueDetail` on
`/chats/:ref` hard loads.
- **Tests & SDK pin**:
- Added/updated tests in
`server/src/__tests__/activity-service.test.ts`,
`server/src/__tests__/activity-routes.test.ts`,
`server/src/__tests__/decision-history.test.ts`,
`server/src/__tests__/issue-thread-interaction-routes.test.ts`,
`ui/src/components/AttentionInteractionResolver.initial.test.tsx`,
`ui/src/components/TaskChatThread.test.tsx`,
`ui/src/components/transcript/useNativeRunTranscripts.test.tsx`,
`ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx`,
and `ui/src/lib/vite-issue-detail-preload.test.ts`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for
`packages/shared/src/types/attention.ts`.

## Verification

Local disposable PostgreSQL 18.1 benchmark (`200,000` `activity_log`
rows, `455` tasks, `82` interactions, alternating baseline/treatment
samples, `ANALYZE` run, positional `.values()` output equality verified
on both empty and populated `handledForUserId` sets):

| Caller/query | Before median | After median | Samples/spread |
Complete output/contract check | Scope |
| --- | --- | --- | --- | --- | --- |
| `activityService.forIssue(50)` | `53.66 ms` (`50.78 ms` SQL exec,
`11,147` buffers, `Seq Scan`) | `1.84 ms` (`0.31 ms` SQL exec, `23`
buffers, `BitmapOr` index scans) | 7 alternating samples (before
`48.03–62.79 ms`, after `1.34–3.18 ms`, `29.2x` speedup) | Pass (50
positional rows equal) | SQL |
| `decisionHistory.handledForBySource` (40 ids, 0 rows) | `13.71 ms`
(`11,193` buffers, `Seq Scan`) | `0.73 ms` (`2` buffers, `Bitmap Index
Scan` on partial index) | 7 alternating samples (before `11.56–15.45
ms`, after `0.64–0.99 ms`, `18.8x` speedup) | Pass (empty + populated
non-empty positional rows equal) | SQL |
| `decisionHistory.handledForBySource` (40 ids, 1 matching row) | `40.35
ms` SQL exec (`11,193` buffers, `Seq Scan`) | `0.04 ms` SQL exec (`2`
buffers, `Bitmap Index Scan` on partial index) | `EXPLAIN (ANALYZE,
BUFFERS)` | Pass (1 positional row equal) | SQL |

CI and reviews on final head `2995820afe`:
- **GitHub Actions CI (`ci / verify`)**: **PASS** (all 86 check runs
completed with 0 failures; `mergeStateStatus: CLEAN`).
- **Greptile Review**: **5/5** (`SUCCESS`, 0 unresolved findings).
- **Ponytail Paperclip Review**: **5/5** ("No actionable defects found
in the reviewed paths. Verdict: Ship.").
- **Feynman Nuclear Review**: **4/5** ("no confirmed defect in the new
commits").

Tests and builds also verified locally:
- `pnpm --filter @paperclipai/shared build` — pass
- `cd server && node scripts/typecheck-layers.mjs` — pass (all 7 layers)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/ui build` — pass
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/approval-queue-seeding-work.test.ts
src/__tests__/decision-history.test.ts` — pass (28/28 and 14/14 on real
embedded PostgreSQL)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/activity-service.test.ts
src/__tests__/openapi-routes.test.ts` — pass
- Focused UI suites (`TaskChatThread.test.tsx`,
`useNativeRunTranscripts.test.tsx`,
`useNativeRunTranscripts.streaming.test.tsx`,
`AttentionInteractionResolver.initial.test.tsx`,
`AttentionInteractionResolver.replace.test.ts`,
`IssueDetail.agentChatPanel.test.tsx`,
`vite-issue-detail-preload.test.ts`) — pass

## Risks

- **No schema migrations**: All SQL improvements use existing indexes.
- **Completed chat run transcripts**: Persistent agent chats now defer
completed `succeeded` runs that already have a visible saved reply,
matching compact task behavior. Live, failed, yielded,
pending-interaction, placeholder, progress-only, and hash-targeted runs
still hydrate immediately.
- **Inline interaction hydration**: `AttentionInteractionResolver` uses
`initialInteraction` when provided and valid, skipping the mount-time
`listInteractions` read; mutations and live updates continue to
update/invalidate `queryKeys.issues.interactions(issueId)` and
`["issues", "pending-questions"]`. Unparseable legacy interaction rows
(`z.ZodError`) are omitted from the batch map and fall back cleanly to
the per-issue read.
- **Synthetic local proof vs production**: Local PostgreSQL benchmarks
prove query plan and buffer reductions on synthetic data (`200k` rows);
deployed latency improvements depend on production dataset size and
cache warmth.

## Model Used

Google Antigravity (Gemini) with tool use, terminal execution, and local
embedded PostgreSQL profiling.

## 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-12-04 12:28:02 -06:00
..
2026-03-12 13:09:22 -05:00