Files
PaperClipAI/server/src/realtime/live-event-delivery.test.ts
T
DottaandClaude 6505538fc5 fix(realtime): limit a shared live-event read set to 100 events and 250 ms (#20632)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server sends the output of a running agent to the browser on the
company WebSocket.
> - #20624 lets the events that are already in the queue share one set
of permission and redaction reads.
> - That set could serve a full queue of 1,000 events for one second.
> - If access is revoked during that time, the principal still receives
the queued output. The security scan on #20624 reported this.
> - This pull request limits one set to 100 events and 250 ms.
> - The benefit is a small, stated limit on output that a revoked
principal can receive, with the same delivery speed.

## Linked Issues or Issue Description

Refs #20624

**What happened?**

After #20624, one set of permission reads can authorize each event that
was in the queue when the set opened. The queue holds at most 1,000
events or 1 MiB. The set stays in use for one second. If a membership,
an API key or a task grant is revoked in that time, the server still
sends the remaining queued events.

**Expected behavior**

A revocation stops delivery after a small, fixed quantity of queued
output. The documentation states that quantity.

**Steps to reproduce**

1. Open a company WebSocket as a user who can read a private task.
2. Publish 1,000 transcript events for a run of that task in one burst.
3. Revoke the task grant while the server delivers the burst.
4. The server delivers the remaining queued events.

**Paperclip version or commit**

`master` at 90dd864bff.

## What Changed

- `live-event-delivery.ts` replaces a shared read set after 100 events
or 250 ms. Before, the limit was one second with no event limit.
- `live-event-delivery.test.ts` pins the exact limits. One set serves
events 2 to 101 and event 102 opens a new set. Access is revoked during
that set, and event 102 is not delivered. A set is kept at 249 ms and
replaced at 250 ms.
- `doc/live-transcript-delivery.md` states the limit and that queued
output from before a revocation can still be sent up to that limit.

## Verification

- `npx vitest run src/realtime
src/__tests__/live-events-run-read.test.ts` in `server/`. 66 tests pass.
- The boundary tests fail when either limit changes by one in either
direction (99, 101 events; 249, 251 ms).
- The 200-event burst test against PostgreSQL issues 22 statements with
this limit. Separate reads issued 1,401.
- Not run locally: a clean server typecheck. The local worktree reports
type errors in `server/src/services/chat-channels/slack/adapter.ts`,
which this change does not touch. CI supplies the typecheck.
- Not verified: delivery delay on a hosted instance after deployment.

## Risks

- More permission reads for large bursts: one set for each 100 queued
events. A burst of 1,000 events uses 10 sets, not 1,000.
- Output produced before a revocation and already in the queue can still
be sent, up to 100 events or 250 ms. Before #20624 the limit was the one
event in flight.
- No schema, API or protocol change.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude, model ID `claude-fable-5-2`, in Claude Code 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
- [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 <noreply@anthropic.com>
2026-11-10 14:18:20 -06:00

306 lines
17 KiB
TypeScript

import { afterEach, expect, it, vi } from "vitest";
import type { LiveEvent } from "@paperclipai/shared";
import { createLiveEventDelivery, LIVE_DELIVERY_MAX_BYTES, LIVE_DELIVERY_MAX_ITEMS, sharedDeliveryRead, type LiveDeliveryReads } from "./live-event-delivery.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const event = (seq = 1, runId = "run-1"): LiveEvent => ({ id: seq, companyId: "company", type: "heartbeat.run.log",
createdAt: "2026-10-24T00:00:00Z", payload: { runId, agentId: "agent", seq, chunk: "output" } });
function fixture(authorize = vi.fn(async (value: LiveEvent, _reads?: LiveDeliveryReads) => value as LiveEvent | null)) {
const frames: any[] = [];
const socket = { readyState: 1, bufferedAmount: 0, send: vi.fn((text: string, callback?: (error?: Error) => void) => {
frames.push(JSON.parse(text)); callback?.();
}), close: vi.fn() };
const decorate = vi.fn(async (value: LiveEvent) => ({ ...value, toastEligible: true }));
const onError = vi.fn();
const delivery = createLiveEventDelivery({ socket, authorize, decorate, onError });
const subscribe = (runIds: string[], revision = 1) => delivery.receive(JSON.stringify({ type: "live.interests", version: 1, revision, runIds }));
return { socket, frames, delivery, subscribe, authorize, decorate, onError };
}
const settle = async () => { for (let n = 0; n < 12; n++) await Promise.resolve(); };
afterEach(() => vi.useRealTimers());
it("leaves older clients on the full stream and negotiates only after a client hello", async () => {
const f = fixture();
expect(f.frames).toEqual([]);
f.delivery.enqueue(event()); await settle();
expect(f.frames[0].payload.chunk).toBe("output");
f.delivery.receive(JSON.stringify({ type: "live.hello", version: 1 }));
expect(f.frames.at(-1)).toMatchObject({ type: "live.capabilities", capabilities: ["run-interests"] });
f.delivery.dispose();
});
it("filters full transcripts before authorization while keeping bounded authorized activity and lifecycle", async () => {
const f = fixture(); f.subscribe([]);
const original = event();
for (let i = 0; i < 512; i++) f.delivery.enqueue({ ...original, id: i });
f.delivery.enqueue({ ...event(), type: "heartbeat.run.status", payload: { runId: "run-1", status: "succeeded" } });
await settle();
expect(f.authorize).toHaveBeenCalledTimes(2);
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toEqual([]);
expect(f.frames.find(frame => frame.type === "heartbeat.run.activity").payload).toEqual({ runId: "run-1", agentId: "agent", lastOutputAt: original.createdAt });
expect(f.frames.at(-1)).toMatchObject({ type: "heartbeat.run.status", toastEligible: true });
expect(original.payload.chunk).toBe("output");
f.delivery.dispose();
});
it("reauthorizes each interested delivery and rechecks interests after an asynchronous permission lookup", async () => {
let release!: (event: LiveEvent) => void;
const f = fixture(vi.fn(() => new Promise<LiveEvent>(resolve => { release = resolve; })));
f.subscribe(["run-1"]); f.delivery.enqueue(event());
f.subscribe([], 2); release(event()); await settle();
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toEqual([]);
expect(f.frames.at(-1)).toMatchObject({ type: "live.subscribed", revision: 2 });
f.delivery.dispose();
});
it("cannot turn run interest into authorization or bypass delivery redaction", async () => {
const f = fixture(vi.fn(async value => value.payload.seq === 1 ? { ...value, payload: { ...value.payload, chunk: "redacted" } } : null));
f.subscribe(["run-1"]); f.delivery.enqueue(event()); f.delivery.enqueue(event(2)); await settle();
expect(f.authorize).toHaveBeenCalledTimes(2);
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log").map(frame => frame.payload.chunk)).toEqual(["redacted"]);
f.delivery.dispose();
});
it.each(["items", "bytes"])("bounds queued %s, notifies resynchronization and resumes only after a new revision", async kind => {
let release!: (event: LiveEvent) => void;
const f = fixture(vi.fn(() => new Promise<LiveEvent>(resolve => { release = resolve; })));
f.subscribe(["run-1"]); f.delivery.enqueue(event());
if (kind === "items") for (let i = 0; i < LIVE_DELIVERY_MAX_ITEMS; i++) f.delivery.enqueue(event(i + 2));
else f.delivery.enqueue({ ...event(2), payload: { ...event(2).payload, chunk: "x".repeat(LIVE_DELIVERY_MAX_BYTES) } });
expect(f.delivery.metrics()).toMatchObject({ needsResync: true });
expect(f.delivery.metrics().retainedBytes).toBeLessThanOrEqual(LIVE_DELIVERY_MAX_BYTES);
expect(f.delivery.metrics().retainedItems).toBeLessThanOrEqual(LIVE_DELIVERY_MAX_ITEMS);
expect(f.frames.filter(frame => frame.type === "live.resync")).toHaveLength(1);
release(event()); await settle();
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toHaveLength(0);
f.subscribe(["run-1"], 2);
expect(f.delivery.metrics().needsResync).toBe(false);
f.delivery.dispose();
});
it("closes persistent congestion on its pending-work deadline without another source event", async () => {
vi.useFakeTimers();
const f = fixture(); f.subscribe(["run-1"]); f.socket.bufferedAmount = LIVE_DELIVERY_MAX_BYTES;
f.delivery.enqueue(event()); await vi.advanceTimersByTimeAsync(5_000);
expect(f.socket.close).toHaveBeenCalledWith(1013, "persistent event backlog");
f.delivery.dispose();
expect(vi.getTimerCount()).toBe(0);
});
it("keeps an unsent gap notice through unrelated interest changes after the socket drains", async () => {
vi.useFakeTimers();
const f = fixture();
try {
f.subscribe(["run-1"]);
f.socket.bufferedAmount = LIVE_DELIVERY_MAX_BYTES;
f.delivery.enqueue(event());
expect(f.frames.some(frame => frame.type === "live.resync")).toBe(false);
await vi.advanceTimersByTimeAsync(4_000);
f.socket.bufferedAmount = 0;
f.subscribe(["run-1", "run-2"], 2);
expect(f.frames.at(-1)).toMatchObject({ type: "live.resync", revision: 2 });
expect(f.delivery.metrics().needsResync).toBe(true);
f.delivery.enqueue(event(2)); await settle();
expect(f.frames.some(frame => frame.type === "heartbeat.run.log")).toBe(false);
await vi.advanceTimersByTimeAsync(1_000);
expect(f.socket.close).toHaveBeenCalledWith(1013, "persistent event backlog");
} finally { f.delivery.dispose(); }
expect(vi.getTimerCount()).toBe(0);
});
it.each([false, true])("preserves the overflow deadline across resubscription until delivery settles: %s", async settled => {
vi.useFakeTimers();
let release!: (event: LiveEvent) => void;
const f = fixture(vi.fn(() => new Promise<LiveEvent>(resolve => { release = resolve; })));
try {
f.subscribe(["run-1"]); f.delivery.enqueue(event());
f.delivery.enqueue({ ...event(2), payload: { ...event(2).payload, chunk: "x".repeat(LIVE_DELIVERY_MAX_BYTES) } });
expect(f.frames.at(-1)).toMatchObject({ type: "live.resync", revision: 1 });
await vi.advanceTimersByTimeAsync(4_000);
f.subscribe(["run-1"], 2);
expect(f.frames.at(-1)).toMatchObject({ type: "live.subscribed", revision: 2 });
expect(f.delivery.metrics().needsResync).toBe(false);
if (settled) { release(event()); await settle(); }
await vi.advanceTimersByTimeAsync(1_000);
if (settled) expect(f.socket.close).not.toHaveBeenCalled();
else expect(f.socket.close).toHaveBeenCalledWith(1013, "persistent event backlog");
} finally { f.delivery.dispose(); release(event()); await settle(); }
expect(vi.getTimerCount()).toBe(0);
});
it("recovers failed delivery reads through resync rather than silently claiming healthy streaming", async () => {
const f = fixture(vi.fn(async () => { throw new Error("permission database unavailable"); }));
f.subscribe(["run-1"]); f.delivery.enqueue(event()); await settle();
expect(f.frames.at(-1)).toMatchObject({ type: "live.resync" });
expect(f.onError).toHaveBeenCalledOnce(); f.delivery.dispose();
});
it("keeps older clients connected after a failed permission read and authorizes the next event", async () => {
const authorize = vi.fn(async (value: LiveEvent) => value);
authorize.mockRejectedValueOnce(new Error("permission database unavailable"));
const f = fixture(authorize);
f.delivery.enqueue(event()); f.delivery.enqueue(event(2)); await settle();
expect(f.frames.map(frame => frame.payload.seq)).toEqual([2]);
expect(f.socket.close).not.toHaveBeenCalled();
expect(f.onError).toHaveBeenCalledOnce();
f.delivery.dispose();
});
it("rejects unbounded interest sets and stale revision commands", () => {
const f = fixture(); f.subscribe(["run-1"]); f.subscribe([], 1);
expect(f.socket.close).toHaveBeenCalledWith(1008, "invalid run interests");
const other = fixture(); other.subscribe(Array.from({ length: 1001 }, (_, i) => `run-${i}`));
expect(other.socket.close).toHaveBeenCalled();
f.delivery.dispose(); other.delivery.dispose();
});
it.each([false, true].flatMap(negotiated => ["authorize", "decorate"].map(stage => ({ negotiated, stage }))))(
"closes a stalled $stage read below the queue bound (negotiated=$negotiated)", async ({ negotiated, stage }) => {
vi.useFakeTimers();
const baseline = idleWorkSnapshot().active;
let release!: (value: LiveEvent) => void;
const pending = new Promise<LiveEvent>(resolve => { release = resolve; });
const f = fixture(stage === "authorize" ? vi.fn(() => pending) : undefined);
const other = fixture();
try {
if (stage === "decorate") f.decorate.mockImplementationOnce(async () => ({ ...await pending, toastEligible: true }));
if (negotiated) f.subscribe(["run-1"]);
const source = stage === "authorize" ? event() : { ...event(), type: "heartbeat.run.status" as const };
f.delivery.enqueue(source);
f.delivery.enqueue(event(2));
other.delivery.enqueue(event());
await settle();
expect(other.frames).toHaveLength(1);
expect(f.delivery.metrics()).toMatchObject({ retainedItems: 2, needsResync: false });
await vi.advanceTimersByTimeAsync(4_000);
if (negotiated) f.subscribe(["run-1"], 2);
await vi.advanceTimersByTimeAsync(999);
expect(f.socket.close).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(f.socket.close).toHaveBeenCalledWith(1013, "persistent event backlog");
expect(f.delivery.metrics().retainedItems).toBe(1);
expect(vi.getTimerCount()).toBe(0);
expect(idleWorkSnapshot().active).toBe(baseline + 1);
release(source); await settle();
expect(idleWorkSnapshot().active).toBe(baseline);
expect(f.delivery.metrics()).toMatchObject({ retainedItems: 0, retainedBytes: 0 });
expect(f.frames.filter(frame => frame.type.startsWith("heartbeat."))).toEqual([]);
expect(f.authorize).toHaveBeenCalledOnce();
} finally { f.delivery.dispose(); other.delivery.dispose(); release(event()); await settle(); }
});
it.each(["resolve", "dispose"])("clears a pending-read deadline on %s without idle work", async ending => {
vi.useFakeTimers();
let release!: (value: LiveEvent) => void;
const f = fixture(vi.fn(() => new Promise<LiveEvent>(resolve => { release = resolve; })));
try {
f.subscribe(["run-1"]); f.delivery.enqueue(event());
await vi.advanceTimersByTimeAsync(4_999);
if (ending === "dispose") f.delivery.dispose();
release(event()); await settle();
expect(vi.getTimerCount()).toBe(0);
await vi.advanceTimersByTimeAsync(5_001);
expect(f.socket.close).not.toHaveBeenCalled();
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toHaveLength(ending === "resolve" ? 1 : 0);
} finally { f.delivery.dispose(); }
});
it("cannot restart recovery timers when a timed-out read later rejects", async () => {
vi.useFakeTimers();
let reject!: (error: Error) => void;
const f = fixture(vi.fn(() => new Promise<LiveEvent>((_resolve, rejectRead) => { reject = rejectRead; })));
try {
f.subscribe(["run-1"]); f.delivery.enqueue(event());
await vi.advanceTimersByTimeAsync(5_000);
expect(f.socket.close).toHaveBeenCalledOnce();
reject(new Error("late permission failure")); await settle();
expect(vi.getTimerCount()).toBe(0);
expect(f.frames.some(frame => frame.type === "live.resync")).toBe(false);
expect(f.authorize).toHaveBeenCalledOnce();
} finally { f.delivery.dispose(); }
});
const flush = async () => { for (let n = 0; n < 600; n++) await Promise.resolve(); };
it("shares one permission read among events queued behind it, never with an event that arrived after it began", async () => {
const releases: Array<() => void> = [];
const read = vi.fn(() => new Promise<boolean>(resolve => { releases.push(() => resolve(true)); }));
const f = fixture(vi.fn(async (value: LiveEvent, reads?: LiveDeliveryReads) =>
await sharedDeliveryRead(reads, "permission", read) ? value : null));
f.subscribe(["run-1"]);
f.delivery.enqueue(event(1));
for (let seq = 2; seq <= 40; seq++) f.delivery.enqueue(event(seq));
await flush();
expect(read).toHaveBeenCalledTimes(1);
releases[0](); await flush();
expect(read).toHaveBeenCalledTimes(2);
f.delivery.enqueue(event(41));
releases[1](); await flush();
expect(read).toHaveBeenCalledTimes(3);
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toHaveLength(40);
releases[2](); await flush();
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log").map(frame => frame.payload.seq))
.toEqual(Array.from({ length: 41 }, (_, index) => index + 1));
expect(f.authorize).toHaveBeenCalledTimes(41);
f.delivery.enqueue(event(42)); await flush();
expect(read).toHaveBeenCalledTimes(4);
f.delivery.dispose();
});
it("stops sharing a read after 250 ms and never reuses a failed read", async () => {
let now = 1_000_000;
const clock = vi.spyOn(Date, "now").mockImplementation(() => now);
try {
const read = vi.fn(async () => true);
const f = fixture(vi.fn(async (value: LiveEvent, reads?: LiveDeliveryReads) => {
const allowed = await sharedDeliveryRead(reads, "permission", read);
now += 100;
return allowed ? value : null;
}));
f.subscribe(["run-1"]);
for (let seq = 1; seq <= 7; seq++) f.delivery.enqueue(event(seq));
await flush();
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toHaveLength(7);
expect(read).toHaveBeenCalledTimes(3);
f.delivery.dispose();
const failing = vi.fn(async () => true).mockResolvedValueOnce(true).mockRejectedValueOnce(new Error("permission database unavailable"));
const g = fixture(vi.fn(async (value: LiveEvent, reads?: LiveDeliveryReads) =>
await sharedDeliveryRead(reads, "permission", failing) ? value : null));
g.delivery.enqueue(event(1)); g.delivery.enqueue(event(2)); g.delivery.enqueue(event(3)); await flush();
expect(failing).toHaveBeenCalledTimes(3);
expect(g.frames.map(frame => frame.payload.seq)).toEqual([1, 3]);
g.delivery.dispose();
} finally { clock.mockRestore(); }
});
it("serves exactly 100 events from one read set, so the 101st sees a revocation", async () => {
let allowed = true;
const read = vi.fn(async () => allowed);
const sets = new Map<number, LiveDeliveryReads | undefined>();
const f = fixture(vi.fn(async (value: LiveEvent, reads?: LiveDeliveryReads) => {
sets.set(value.payload.seq as number, reads);
const visible = await sharedDeliveryRead(reads, "permission", read);
if (value.payload.seq === 2) allowed = false;
return visible ? value : null;
}));
f.subscribe(["run-1"]);
for (let seq = 1; seq <= 102; seq++) f.delivery.enqueue(event(seq));
await flush();
expect(read).toHaveBeenCalledTimes(3);
expect(sets.get(2)).not.toBe(sets.get(1));
for (let seq = 3; seq <= 101; seq++) expect(sets.get(seq)).toBe(sets.get(2));
expect(sets.get(102)).not.toBe(sets.get(101));
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log").map(frame => frame.payload.seq))
.toEqual(Array.from({ length: 101 }, (_, index) => index + 1));
f.delivery.dispose();
});
it("keeps a read set at 249 ms and replaces it at 250 ms", async () => {
let now = 1_000_000;
const clock = vi.spyOn(Date, "now").mockImplementation(() => now);
try {
const steps = new Map([[2, 249], [3, 1]]);
const sets = new Map<number, LiveDeliveryReads | undefined>();
const f = fixture(vi.fn(async (value: LiveEvent, reads?: LiveDeliveryReads) => {
const seq = value.payload.seq as number;
sets.set(seq, reads);
now += steps.get(seq) ?? 0;
return value;
}));
f.subscribe(["run-1"]);
for (let seq = 1; seq <= 4; seq++) f.delivery.enqueue(event(seq));
await flush();
expect(sets.get(3)).toBe(sets.get(2));
expect(sets.get(4)).not.toBe(sets.get(3));
expect(f.frames.filter(frame => frame.type === "heartbeat.run.log")).toHaveLength(4);
f.delivery.dispose();
} finally { clock.mockRestore(); }
});