Skip to content

Commit 95163cb

Browse files
committed
fix(qa): reject writes after bus shutdown
1 parent 8bfe42b commit 95163cb

4 files changed

Lines changed: 63 additions & 11 deletions

File tree

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

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ describe("qa-bus server", () => {
112112
await Promise.all(stops.splice(0).map((stop) => stop()));
113113
});
114114

115-
it("wakes matching long polls and settles late polls during shutdown", async () => {
115+
it("wakes matching polls and fences late polls and writes during shutdown", async () => {
116116
const state = createQaBusState();
117117
const bus = await startQaBusServer({ state });
118118
let stopped = false;
@@ -145,16 +145,22 @@ describe("qa-bus server", () => {
145145
});
146146

147147
const waitForCursorAdvance = state.waitForCursorAdvance.bind(state);
148-
let lateWaiterStarted = false;
149-
let lateWaiterSettled = false;
148+
let pollWaitersStarted = 0;
149+
let pollWaitersSettled = 0;
150150
state.waitForCursorAdvance = async (...args) => {
151-
lateWaiterStarted = true;
151+
pollWaitersStarted += 1;
152152
try {
153153
return await waitForCursorAdvance(...args);
154154
} finally {
155-
lateWaiterSettled = true;
155+
pollWaitersSettled += 1;
156156
}
157157
};
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));
158164
const body = JSON.stringify({ accountId: "late-body", cursor: 0, timeoutMs: 30_000 });
159165
const slowPoll = request({
160166
host: "127.0.0.1",
@@ -166,17 +172,40 @@ describe("qa-bus server", () => {
166172
slowPoll.on("response", (response) => response.resume());
167173
slowPoll.on("error", () => undefined);
168174
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));
169193
await sleep(10);
170194

171195
stopped = true;
172196
const startedAt = Date.now();
173197
const stopping = bus.stop();
174-
setTimeout(() => slowPoll.end(body.slice(1)), 50);
198+
setTimeout(() => {
199+
slowPoll.end(body.slice(1));
200+
slowInbound.end(inboundBody.slice(1));
201+
}, 50);
175202
await stopping;
203+
await activePoll;
176204

177205
expect(Date.now() - startedAt).toBeLessThan(1_000);
178-
expect(lateWaiterStarted).toBe(true);
179-
expect(lateWaiterSettled).toBe(true);
206+
expect(pollWaitersStarted).toBe(1);
207+
expect(pollWaitersSettled).toBe(1);
208+
expect(state.getSnapshot()).toMatchObject({ events: [], messages: [] });
180209
});
181210

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

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

Lines changed: 7 additions & 1 deletion
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 &&
@@ -193,6 +196,7 @@ export function createQaBusState() {
193196

194197
return {
195198
reset(terminal = false) {
199+
assertWritable = terminal ? throwQaBusClosed : assertWritable;
196200
conversations.clear();
197201
threads.clear();
198202
messages.clear();
@@ -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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import type {
1010

1111
export const DEFAULT_WAIT_TIMEOUT_MS = 5_000;
1212

13-
function throwQaBusClosed(): never {
13+
export function throwQaBusClosed(): never {
1414
throw new Error("qa-bus closed");
1515
}
1616

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

Lines changed: 18 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";
@@ -942,6 +942,21 @@ describe("qa-lab server", () => {
942942
headers: { "content-type": "application/json" },
943943
body: JSON.stringify({ accountId: "cleanup", cursor: 0, timeoutMs: 30_000 }),
944944
}).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));
945960
await vi.waitFor(() => expect(pollWaiterStarted).toBe(true));
946961
const stopping = lab.stop();
947962
await gatewayStopping;
@@ -950,10 +965,12 @@ describe("qa-lab server", () => {
950965
expect(pollWaiterSettled).toBe(false);
951966
} finally {
952967
finishGatewayStop();
968+
setTimeout(() => slowInbound.end(inboundBody.slice(1)), 50);
953969
await stopping;
954970
}
955971
await poll;
956972
expect(pollWaiterSettled).toBe(true);
973+
expect(lab.state.getSnapshot()).toMatchObject({ events: [], messages: [] });
957974
await expect(fetch(`${lab.baseUrl}/healthz`)).rejects.toThrow();
958975
});
959976

0 commit comments

Comments
 (0)