Files
PaperClipAI/ui/src/lib/query-invalidation-batcher.ts
T
DottaandClaude Opus 4.8 3e348b96b9 perf(ui): cut live-updates churn that inflates tab memory (#9624)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Its web UI keeps live views (issue threads, run transcripts,
dashboard) fresh via React Query polling plus a live-events websocket,
coordinated across tabs with a `BroadcastChannel` layer
> - Long-lived tabs viewing live agent runs grew to multi-GB memory
footprints while their JS heap stayed ~60–200 MB — so the memory is
off-heap (Blink/native + committed allocator arenas), not a classic JS
leak
> - Live profiling of a reproduced 2.7 GB / 66 MB tab showed 15–30% idle
CPU, ~3 fetches/sec across overlapping poll loops, and ~8 `setInterval`
create/clear cycles per second whose rate grew ~7× as the tab aged —
relentless allocation churn that inflates committed memory the OS never
reclaims, amplified across tabs by the cross-tab fan-out
> - This pull request cuts that churn at its four largest sources
(invalidation storm, per-instance 1 s timers, redundant polling,
unbounded streamed-run set)
> - The benefit is that idle tabs do far less periodic work, so their
off-heap footprint stops ballooning over a long session

## Linked Issues or Issue Description

No public GitHub issue exists; describing inline per CONTRIBUTING.md →
"Link Issues or Describe Them In-PR", following the bug report template.

**What happened?**

Browser tabs viewing live agent runs grew to 8–16 GB memory footprint
over a long session (multiple tabs open), while each tab's "live" JS
heap stayed only ~150–250 MB. Every idle tab also burned 15–30% CPU.
Tabs eventually approached the ~4 GB V8 heap ceiling / OS pressure and
could crash.

**Expected behavior**

Tabs viewing live runs should hold a bounded footprint and do minimal
work while idle, regardless of how long they stay open or how many tabs
are open.

**Steps to reproduce**

Open several issue/run tabs that have agents actively streaming and
leave them open for a while. Watch Chrome's Task Manager: Memory
Footprint climbs into the GBs while "JavaScript Memory" stays small, and
CPU stays high on idle tabs. Reproduced in ~90 minutes: a tab reached
2.7 GB footprint on a 66 MB JS heap, and the per-second timer-churn rate
was ~7× higher on a 90-minute-old tab than a fresh one.

**Paperclip version or commit**

Branch `fix/live-updates-churn`, off `master`.

**Deployment mode**

Local dev (`pnpm dev`), web UI. Not adapter-specific — core UI
live-updates plumbing (observed with `claude_local` / `codex_local`
runs).

## What Changed

- **`ui/src/lib/query-invalidation-batcher.ts` (new)** —
`createInvalidationBatcher` throttles + de-dupes React Query
invalidations into one flush per ~300 ms, and
`createCoalescingQueryClient` wraps the client via a `Proxy` so only
`invalidateQueries` is batched (optimistic `setQueryData` writes stay
immediate). Wired into `LiveUpdatesProvider`, which previously
invalidated synchronously on every websocket event.
- **`ui/src/hooks/useSecondTick.ts` (new)** — one shared, ref-counted,
page-wide 1 s ticker. `useLiveElapsed` in `IssueChatThread` now uses it
instead of a per-instance `setInterval` that forced a full-thread
re-render every second per live element.
- **`ui/src/components/transcript/useLiveRunTranscripts.ts`** — when the
realtime websocket is enabled, the recurring log poll backs off to a 30
s safety-net cadence instead of polling every 2 s on top of the live
stream. Added a marker for the durable poll→push rearchitecture.
- **`ui/src/lib/issueChatTranscriptRuns.ts`** —
`resolveIssueChatTranscriptRuns` now caps the streamed run set
(live/active runs always kept; most-recent linked runs fill up to 20) so
a large run history can't open a live-transcript poll per historical
run.
- **`ui/src/main.tsx`** — explicit `gcTime` so cross-tab-published cache
entries for unobserved resources are collected promptly.
- Tests for the batcher, shared ticker, and run cap.

## Verification

- `vitest`: new suites `query-invalidation-batcher.test.ts` (batcher
collapses 20 invalidations → 1 flush; keeps distinct keys/variants;
dispose cancels; proxy passes non-invalidate methods through),
`useSecondTick.test.tsx` (single ref-counted timer, stops when idle),
`issueChatTranscriptRuns.test.ts` (cap keeps newest + live). All pass.
- Existing affected suites pass: `LiveUpdatesProvider` (23),
`IssueChatThread` (), `useLiveRunTranscripts`,
`AgentDetail.instructions` — 109 tests across affected files.
- `tsc -b` clean.
- Behavior confirmed by live profiling before the change (2.7 GB / 66 MB
tab, ~8 interval churns/sec growing 7× with age). Runtime churn
reduction should be re-measured against a rebuilt bundle with the same
instrumentation.

## Risks

Low-to-moderate; all changes reduce work rather than add features.
- **Invalidation batching** delays live-driven refetches by up to ~300
ms. Optimistic `setQueryData` writes (e.g. the visible issue's new
comment) remain immediate, so foreground updates still feel instant;
only the safety-net refetch is throttled. Non-live invalidations (user
actions, mutations) are unaffected — they use the real client.
- **Poll back-off** relies on the websocket as the live source when
realtime is enabled; a 30 s fallback poll still covers gaps/reconnects
(both the transcript hook and `LiveUpdatesProvider` also
auto-reconnect).
- **Run cap (20)** means an issue with a very large run history streams
live transcripts only for its live/active + 20 most-recent runs; older
runs still open normally via their run pages.
- Downstream test fallout (timing-sensitive tests around
invalidation/polling) may need adjustment — flagged intentionally for
follow-up.

Durable follow-up (out of scope, marked in code): replace transcript/run
polling with server push (SSE/websocket deltas) so idle tabs do no
periodic work at all.

## Model Used

- **Provider:** Anthropic, via the Claude Code CLI.
- **Model:** Claude Opus 4.8 (`claude-opus-4-8`).
- **Reasoning mode:** Extended thinking enabled.
- **Capabilities used:** tool use (shell, file editing), sub-agent
fan-out for codebase analysis, and the Chrome DevTools MCP to reproduce
and profile the memory/CPU churn on a live instance.

## 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 (a bug/perf fix, not planned core feature work)
- [x] I have searched GitHub for duplicate or related PRs and linked
them above (none found)
- [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 considered and documented any risks above
- [ ] I have updated relevant documentation to reflect my changes (N/A —
no user-facing docs; rationale documented inline)
- [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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 14:17:37 -05:00

145 lines
5.1 KiB
TypeScript

import type { InvalidateQueryFilters, QueryClient } from "@tanstack/react-query";
/**
* Coalesces React Query invalidations triggered by the live-events stream.
*
* `LiveUpdatesProvider` used to call `queryClient.invalidateQueries(...)`
* synchronously for every websocket event. During an active agent run these
* fire many times per second, and each invalidation cascades into refetches
* and re-renders — the dominant source of steady-state CPU churn (and, over a
* long-lived tab, off-heap allocation growth).
*
* The batcher collects invalidation filters over a short window, de-duplicates
* identical ones, and flushes them in a single pass at most once per interval.
* A trailing-throttle (not a pure debounce) is used deliberately: during a
* continuous event stream a pure debounce would never flush, so UI updates
* would stall; throttling guarantees the buffered invalidations flush every
* `intervalMs`.
*/
export interface InvalidationBatcher {
/** Schedule an invalidation; resolves once the batched flush has run. */
schedule: (filters: InvalidateQueryFilters) => Promise<void>;
/** Flush any buffered invalidations immediately (e.g. before teardown). */
flush: () => Promise<void>;
dispose: () => void;
}
export const DEFAULT_INVALIDATION_INTERVAL_MS = 300;
type Deferred = { promise: Promise<void>; resolve: () => void };
function createDeferred(): Deferred {
let resolve!: () => void;
const promise = new Promise<void>((r) => {
resolve = r;
});
return { promise, resolve };
}
export function createInvalidationBatcher(
queryClient: Pick<QueryClient, "invalidateQueries">,
intervalMs: number = DEFAULT_INVALIDATION_INTERVAL_MS,
): InvalidationBatcher {
// Keyed by a stable serialization of the filters so repeated invalidations of
// the same key (the common case) collapse to one entry.
const pending = new Map<string, InvalidateQueryFilters>();
let timer: ReturnType<typeof setTimeout> | null = null;
// Resolves when the currently-buffered window has been flushed. `schedule`
// hands this back so callers that await it observe the real invalidation.
let windowDeferred: Deferred | null = null;
const flush = async (): Promise<void> => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
const deferred = windowDeferred;
windowDeferred = null;
if (pending.size === 0) {
deferred?.resolve();
return;
}
const filtersList = [...pending.values()];
pending.clear();
try {
await Promise.all(filtersList.map((filters) => queryClient.invalidateQueries(filters)));
} finally {
deferred?.resolve();
}
};
const schedule = (filters: InvalidateQueryFilters): Promise<void> => {
pending.set(serializeFilters(filters), filters);
if (windowDeferred === null) {
windowDeferred = createDeferred();
}
if (timer === null) {
timer = setTimeout(() => void flush(), intervalMs);
}
return windowDeferred.promise;
};
const dispose = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
pending.clear();
// Release any awaiters so they don't hang forever after teardown.
windowDeferred?.resolve();
windowDeferred = null;
};
return { schedule, flush, dispose };
}
let uniqueFilterCounter = 0;
function serializeFilters(filters: InvalidateQueryFilters): string {
// A predicate is an opaque function — two predicate-based filters can never be
// proven equal, so never coalesce them (that would silently drop one). Give
// each its own key.
if (typeof filters.predicate === "function") {
return `__predicate__:${(uniqueFilterCounter += 1)}`;
}
// queryKey drives the identity; refetchType/exact/type change the behavior, so
// keep them distinct while still collapsing exact repeats.
try {
return JSON.stringify([
filters.queryKey ?? null,
filters.refetchType ?? null,
filters.exact ?? null,
filters.type ?? null,
]);
} catch {
// Non-serializable filter (shouldn't happen for our query keys) — fall back
// to a unique key so it is never dropped.
return `__nonserializable__:${(uniqueFilterCounter += 1)}`;
}
}
/**
* Wrap a QueryClient so `invalidateQueries` is routed through `batcher` while
* every other method (reads, `setQueryData`, …) passes straight through to the
* real client. Returned value is a `QueryClient` and can be used anywhere one
* is expected. Private class fields keep working because methods are bound to
* the real client via `Reflect.get(target, prop, target)`.
*
* The batched `invalidateQueries` returns a promise that resolves only after the
* flush actually runs, so callers that await it still observe completion.
*/
export function createCoalescingQueryClient(
queryClient: QueryClient,
batcher: InvalidationBatcher,
): QueryClient {
return new Proxy(queryClient, {
get(target, prop) {
if (prop === "invalidateQueries") {
return (filters?: InvalidateQueryFilters) => batcher.schedule(filters ?? {});
}
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
}