Skip to content

Commit c1622d0

Browse files
authored
fix(qa): stop shutdown from leaving bus poll timers (#124463)
* fix(qa): settle bus polls during shutdown * fix(qa): fence late bus waiters during shutdown * fix(qa): reject writes after bus shutdown
1 parent f43544f commit c1622d0

6 files changed

Lines changed: 133 additions & 14 deletions

File tree

‎extensions/qa-lab/src/bus-server.test.ts‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Qa Lab tests cover bus server plugin behavior.
22
import { Agent, createServer, request } from "node:http";
3+
import { setTimeout as sleep } from "node:timers/promises";
34
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
45
import { closeQaHttpServer, handleQaBusRequest, startQaBusServer } from "./bus-server.js";
56
import { createQaBusState } from "./bus-state.js";
@@ -111,10 +112,15 @@ describe("qa-bus server", () => {
111112
await Promise.all(stops.splice(0).map((stop) => stop()));
112113
});
113114

114-
it("wakes stale-cursor long polls as soon as matching account traffic arrives", async () => {
115+
it("wakes matching polls and fences late polls and writes during shutdown", async () => {
115116
const state = createQaBusState();
116117
const bus = await startQaBusServer({ state });
117-
stops.push(bus["stop"]);
118+
let stopped = false;
119+
stops.push(async () => {
120+
if (!stopped) {
121+
await bus.stop();
122+
}
123+
});
118124

119125
const pending = pollQaBus({
120126
baseUrl: bus.baseUrl,
@@ -137,6 +143,69 @@ describe("qa-bus server", () => {
137143
cursor: 1,
138144
kind: "inbound-message",
139145
});
146+
147+
const waitForCursorAdvance = state.waitForCursorAdvance.bind(state);
148+
let pollWaitersStarted = 0;
149+
let pollWaitersSettled = 0;
150+
state.waitForCursorAdvance = async (...args) => {
151+
pollWaitersStarted += 1;
152+
try {
153+
return await waitForCursorAdvance(...args);
154+
} finally {
155+
pollWaitersSettled += 1;
156+
}
157+
};
158+
const activePoll = fetch(`${bus.baseUrl}/v1/poll`, {
159+
method: "POST",
160+
headers: { "content-type": "application/json" },
161+
body: JSON.stringify({ accountId: "active", cursor: 1, timeoutMs: 30_000 }),
162+
}).catch(() => undefined);
163+
await vi.waitFor(() => expect(pollWaitersStarted).toBe(1));
164+
const body = JSON.stringify({ accountId: "late-body", cursor: 0, timeoutMs: 30_000 });
165+
const slowPoll = request({
166+
host: "127.0.0.1",
167+
port: bus.port,
168+
path: "/v1/poll",
169+
method: "POST",
170+
headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
171+
});
172+
slowPoll.on("response", (response) => response.resume());
173+
slowPoll.on("error", () => undefined);
174+
slowPoll.write(body.slice(0, 1));
175+
const inboundBody = JSON.stringify({
176+
conversation: { id: "late-room", kind: "direct" },
177+
senderId: "late-sender",
178+
text: "must not survive shutdown",
179+
});
180+
const slowInbound = request({
181+
host: "127.0.0.1",
182+
port: bus.port,
183+
path: "/v1/inbound/message",
184+
method: "POST",
185+
headers: {
186+
"content-type": "application/json",
187+
"content-length": Buffer.byteLength(inboundBody),
188+
},
189+
});
190+
slowInbound.on("response", (response) => response.resume());
191+
slowInbound.on("error", () => undefined);
192+
slowInbound.write(inboundBody.slice(0, 1));
193+
await sleep(10);
194+
195+
stopped = true;
196+
const startedAt = Date.now();
197+
const stopping = bus.stop();
198+
setTimeout(() => {
199+
slowPoll.end(body.slice(1));
200+
slowInbound.end(inboundBody.slice(1));
201+
}, 50);
202+
await stopping;
203+
await activePoll;
204+
205+
expect(Date.now() - startedAt).toBeLessThan(1_000);
206+
expect(pollWaitersStarted).toBe(1);
207+
expect(pollWaitersSettled).toBe(1);
208+
expect(state.getSnapshot()).toMatchObject({ events: [], messages: [] });
140209
});
141210

142211
it("resumes an account after its last acknowledged cursor when the client restarts", async () => {

‎extensions/qa-lab/src/bus-server.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,11 +287,12 @@ function normalizeQaBusSearchInput(input: Record<string, unknown>): QaBusSearchM
287287
} as QaBusSearchMessagesInput;
288288
}
289289

290-
export async function closeQaHttpServer(server: Server): Promise<void> {
290+
export async function closeQaHttpServer(server: Server, state?: QaBusState): Promise<void> {
291291
let forceCloseTimer: NodeJS.Timeout | undefined;
292292
try {
293293
await new Promise<void>((resolve, reject) => {
294294
server.close((error) => (error ? reject(error) : resolve()));
295+
state?.reset(true); // Fence first so late request bodies cannot add waiter timers.
295296
server.closeIdleConnections?.();
296297
forceCloseTimer = setTimeout(() => {
297298
server.closeAllConnections?.();
@@ -471,7 +472,7 @@ export async function startQaBusServer(params: { state: QaBusState; port?: numbe
471472
port: address.port,
472473
baseUrl: `http://127.0.0.1:${address.port}`,
473474
async stop() {
474-
await closeQaHttpServer(server);
475+
await closeQaHttpServer(server, params.state);
475476
},
476477
};
477478
}

‎extensions/qa-lab/src/bus-state.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
requireQaBusMessageForAccount,
1111
searchQaBusMessages,
1212
} from "./bus-queries.js";
13-
import { createQaBusWaiterStore } from "./bus-waiters.js";
13+
import { createQaBusWaiterStore, throwQaBusClosed } from "./bus-waiters.js";
1414
import { sanitizeQaBusToolCalls } from "./qa-bus-protocol.js";
1515
import type {
1616
QaBusAttachment,
@@ -86,6 +86,7 @@ export function createQaBusState() {
8686
const events: QaBusEvent[] = [];
8787
const acknowledgedPollCursors = new Map<string, number>();
8888
let cursor = 0;
89+
let assertWritable = () => {};
8990
const waiters = createQaBusWaiterStore(() =>
9091
buildQaBusSnapshot({
9192
cursor,
@@ -125,6 +126,7 @@ export function createQaBusState() {
125126
const requireActiveMessageForAccount = (
126127
input: Pick<QaBusReadMessageInput, "accountId" | "messageId">,
127128
): QaBusMessage => {
129+
assertWritable();
128130
const message = requireQaBusMessageForAccount({ messages, input });
129131
if (message.deleted) {
130132
throw new Error(`qa-bus message was deleted: ${input.messageId}`);
@@ -149,6 +151,7 @@ export function createQaBusState() {
149151
nativeCommand?: QaBusInboundMessageInput["nativeCommand"];
150152
toolCalls?: QaBusToolCall[];
151153
}): QaBusMessage => {
154+
assertWritable();
152155
const thread = params.threadId ? threads.get(params.threadId) : undefined;
153156
if (
154157
thread &&
@@ -192,14 +195,15 @@ export function createQaBusState() {
192195
};
193196

194197
return {
195-
reset() {
198+
reset(terminal = false) {
199+
assertWritable = terminal ? throwQaBusClosed : assertWritable;
196200
conversations.clear();
197201
threads.clear();
198202
messages.clear();
199203
events.length = 0;
200204
// Keep the cursor monotonic across resets so long-poll clients do not
201-
// miss fresh events and retained restart acknowledgements remain valid.
202-
waiters.reset();
205+
// miss events; terminal reset also fences late waiter timers.
206+
waiters.reset(undefined, terminal);
203207
},
204208
getSnapshot() {
205209
return buildQaBusSnapshot({
@@ -263,6 +267,7 @@ export function createQaBusState() {
263267
return cloneMessage(message);
264268
},
265269
createThread(input: QaBusCreateThreadInput) {
270+
assertWritable();
266271
const accountId = normalizeAccountId(input.accountId);
267272
const thread: QaBusThread = {
268273
id: `thread-${randomUUID()}`,
@@ -340,6 +345,7 @@ export function createQaBusState() {
340345
return searchQaBusMessages({ messages, input });
341346
},
342347
resolvePollCursor(input: QaBusPollInput = {}) {
348+
assertWritable();
343349
const accountId = normalizeAccountId(input.accountId);
344350
const requestedCursor = input.cursor ?? 0;
345351
const acknowledgedCursor = acknowledgedPollCursors.get(accountId) ?? 0;

‎extensions/qa-lab/src/bus-waiters.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import type {
1010

1111
export const DEFAULT_WAIT_TIMEOUT_MS = 5_000;
1212

13+
export function throwQaBusClosed(): never {
14+
throw new Error("qa-bus closed");
15+
}
16+
1317
export type QaBusWaitMatch = QaBusEvent | QaBusMessage | QaBusThread;
1418

1519
type Waiter = {
@@ -51,9 +55,11 @@ function createQaBusMatcher(
5155
export function createQaBusWaiterStore(getSnapshot: () => QaBusStateSnapshot) {
5256
const waiters = new Set<Waiter>();
5357
const cursorWaiters = new Set<CursorWaiter>();
58+
let readSnapshot = getSnapshot;
5459

5560
return {
56-
reset(reason = "qa-bus reset") {
61+
reset(reason = "qa-bus reset", terminal = false) {
62+
readSnapshot = terminal ? throwQaBusClosed : readSnapshot;
5763
for (const waiter of waiters) {
5864
clearTimeout(waiter.timer);
5965
waiter.reject(new Error(reason));
@@ -69,7 +75,7 @@ export function createQaBusWaiterStore(getSnapshot: () => QaBusStateSnapshot) {
6975
if (waiters.size === 0 && cursorWaiters.size === 0) {
7076
return;
7177
}
72-
const snapshot = getSnapshot();
78+
const snapshot = readSnapshot();
7379
for (const waiter of Array.from(waiters)) {
7480
const match = waiter.matcher(snapshot);
7581
if (!match) {
@@ -93,7 +99,7 @@ export function createQaBusWaiterStore(getSnapshot: () => QaBusStateSnapshot) {
9399
},
94100
async waitFor(input: QaBusWaitForInput) {
95101
const matcher = createQaBusMatcher(input);
96-
const immediate = matcher(getSnapshot());
102+
const immediate = matcher(readSnapshot());
97103
if (immediate) {
98104
return immediate;
99105
}
@@ -116,7 +122,7 @@ export function createQaBusWaiterStore(getSnapshot: () => QaBusStateSnapshot) {
116122
timeoutMs: number,
117123
shouldResolve?: (snapshot: QaBusStateSnapshot) => boolean,
118124
) {
119-
const snapshot = getSnapshot();
125+
const snapshot = readSnapshot();
120126
if (snapshot.cursor > afterCursor && (!shouldResolve || shouldResolve(snapshot))) {
121127
return;
122128
}

‎extensions/qa-lab/src/lab-server.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// QA Lab tests cover lab server plugin behavior.
22
import fs, { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3-
import { createServer } from "node:http";
3+
import { createServer, request as httpRequest } from "node:http";
44
import os from "node:os";
55
import path from "node:path";
66
import { setTimeout as sleep } from "node:timers/promises";
@@ -926,14 +926,51 @@ describe("qa-lab server", () => {
926926
);
927927

928928
const lab = await startQaLabServer({ host: "127.0.0.1", port: 0 });
929+
const waitForCursorAdvance = lab.state.waitForCursorAdvance.bind(lab.state);
930+
let pollWaiterStarted = false;
931+
let pollWaiterSettled = false;
932+
lab.state.waitForCursorAdvance = async (...args) => {
933+
pollWaiterStarted = true;
934+
try {
935+
return await waitForCursorAdvance(...args);
936+
} finally {
937+
pollWaiterSettled = true;
938+
}
939+
};
940+
const poll = fetch(`${lab.listenUrl}/v1/poll`, {
941+
method: "POST",
942+
headers: { "content-type": "application/json" },
943+
body: JSON.stringify({ accountId: "cleanup", cursor: 0, timeoutMs: 30_000 }),
944+
}).catch(() => undefined);
945+
const inboundBody = JSON.stringify({
946+
conversation: { id: "late-room", kind: "direct" },
947+
senderId: "late-sender",
948+
text: "must not survive shutdown",
949+
});
950+
const slowInbound = httpRequest(new URL("/api/inbound/message", lab.listenUrl), {
951+
method: "POST",
952+
headers: {
953+
"content-type": "application/json",
954+
"content-length": Buffer.byteLength(inboundBody),
955+
},
956+
});
957+
slowInbound.on("response", (response) => response.resume());
958+
slowInbound.on("error", () => undefined);
959+
slowInbound.write(inboundBody.slice(0, 1));
960+
await vi.waitFor(() => expect(pollWaiterStarted).toBe(true));
929961
const stopping = lab.stop();
930962
await gatewayStopping;
931963
try {
932964
await expect(fetch(`${lab.baseUrl}/healthz`)).resolves.toMatchObject({ status: 200 });
965+
expect(pollWaiterSettled).toBe(false);
933966
} finally {
934967
finishGatewayStop();
968+
setTimeout(() => slowInbound.end(inboundBody.slice(1)), 50);
935969
await stopping;
936970
}
971+
await poll;
972+
expect(pollWaiterSettled).toBe(true);
973+
expect(lab.state.getSnapshot()).toMatchObject({ events: [], messages: [] });
937974
await expect(fetch(`${lab.baseUrl}/healthz`)).rejects.toThrow();
938975
});
939976

‎extensions/qa-lab/src/lab-server.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -957,7 +957,7 @@ export async function startQaLabServer(
957957
cleanupError = toQaError(error);
958958
}
959959
const results = await Promise.allSettled([
960-
Promise.resolve().then(() => (serverListening ? closeQaHttpServer(server) : undefined)),
960+
serverListening ? closeQaHttpServer(server, state) : undefined,
961961
Promise.resolve().then(releaseCaptureStore),
962962
]);
963963
const failed = results.find((result) => result.status === "rejected");

0 commit comments

Comments
 (0)