Skip to content

Commit f06ac35

Browse files
committed
fix(qa-lab): bound matrix probe re-polling by deadline
1 parent 01a23bc commit f06ac35

2 files changed

Lines changed: 87 additions & 47 deletions

File tree

‎extensions/qa-lab/src/live-transports/matrix/substrate/harness.runtime-internals.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ export const MATRIX_QA_SERVICE = "matrix-qa-homeserver";
1111
export const MATRIX_QA_CLEANUP_TIMEOUT_MS = 90_000;
1212
const MATRIX_QA_HEALTH_REQUEST_TIMEOUT_MS = 2_000;
1313

14+
class MatrixQaHarnessTimeoutError extends Error {}
15+
1416
export type MatrixQaHarnessFiles = {
1517
outputDir: string;
1618
composeFile: string;
@@ -27,12 +29,11 @@ export function buildVersionsUrl(baseUrl: string) {
2729
export async function isMatrixVersionsReachable(
2830
baseUrl: string,
2931
fetchImpl: FetchLike,
30-
timeoutMs = MATRIX_QA_HEALTH_REQUEST_TIMEOUT_MS,
32+
timeoutSignal = AbortSignal.timeout(MATRIX_QA_HEALTH_REQUEST_TIMEOUT_MS),
3133
signal?: AbortSignal,
3234
) {
3335
let response: Awaited<ReturnType<FetchLike>> | undefined;
3436
try {
35-
const timeoutSignal = AbortSignal.timeout(Math.max(1, timeoutMs));
3637
response = await fetchImpl(buildVersionsUrl(baseUrl), {
3738
signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal,
3839
});
@@ -57,7 +58,7 @@ export async function withMatrixQaHarnessTimeout<T>(
5758
task,
5859
new Promise<never>((_, reject) => {
5960
timeout = setTimeout(() => {
60-
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
61+
reject(new MatrixQaHarnessTimeoutError(`${label} timed out after ${timeoutMs}ms`));
6162
}, timeoutMs);
6263
}),
6364
]);
@@ -93,6 +94,7 @@ export async function waitForReachableMatrixBaseUrl(params: {
9394
const probeController = new AbortController();
9495
let reachableCandidate: string | undefined;
9596
let probeConsumedDeadline = false;
97+
const requestTimeoutMs = Math.min(MATRIX_QA_HEALTH_REQUEST_TIMEOUT_MS, remainingMs);
9698
try {
9799
// Race both network paths so neither stalled probe can starve or delay
98100
// a healthy peer. The outer deadline also bounds injected fetch fakes.
@@ -101,26 +103,28 @@ export async function waitForReachableMatrixBaseUrl(params: {
101103
remainingMs,
102104
Promise.any(
103105
candidateBaseUrls.map(async (baseUrl) => {
106+
const requestTimeoutSignal = AbortSignal.timeout(Math.max(1, requestTimeoutMs));
104107
if (
105108
await isMatrixVersionsReachable(
106109
baseUrl,
107110
params.fetchImpl,
108-
Math.min(MATRIX_QA_HEALTH_REQUEST_TIMEOUT_MS, remainingMs),
111+
requestTimeoutSignal,
109112
probeController.signal,
110113
)
111114
) {
112115
return baseUrl;
113116
}
117+
if (requestTimeoutMs === remainingMs && requestTimeoutSignal.aborted) {
118+
probeConsumedDeadline = true;
119+
}
114120
throw new Error("Matrix versions endpoint unreachable");
115121
}),
116122
),
117123
);
118124
} catch (error) {
119-
// A stalled probe consumed the entire remaining budget; its timeout can
120-
// fire marginally before Date.now() crosses the deadline, so re-polling
121-
// here would start a doomed extra probe. Fast candidate failures re-poll.
122-
probeConsumedDeadline =
123-
error instanceof Error && error.message.startsWith("Matrix health probes timed out");
125+
// The outer timeout covers injected fetches that ignore abort signals.
126+
// Request timeouts record the same deadline fact before rejecting.
127+
probeConsumedDeadline ||= error instanceof MatrixQaHarnessTimeoutError;
124128
} finally {
125129
probeController.abort();
126130
}

‎extensions/qa-lab/src/live-transports/matrix/substrate/harness.runtime.test.ts‎

Lines changed: 74 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,28 @@ function countMatching<T>(items: readonly T[], predicate: (item: T) => boolean):
8888
return count;
8989
}
9090

91+
function createStalledVersionsFetch() {
92+
const probeSignals: AbortSignal[] = [];
93+
const fetchImpl = vi.fn(
94+
async (_input: string, init?: Pick<RequestInit, "signal">) =>
95+
await new Promise<never>((_resolve, reject) => {
96+
const probeSignal = init?.signal ?? undefined;
97+
if (!probeSignal) {
98+
reject(new Error("versions probe signal missing"));
99+
return;
100+
}
101+
probeSignals.push(probeSignal);
102+
const rejectAborted = () => reject(new Error("versions probe aborted"));
103+
if (probeSignal.aborted) {
104+
rejectAborted();
105+
return;
106+
}
107+
probeSignal.addEventListener("abort", rejectAborted, { once: true });
108+
}),
109+
);
110+
return { fetchImpl, probeSignals };
111+
}
112+
91113
describe("matrix harness runtime", () => {
92114
it("writes a pinned Tuwunel compose file", async () => {
93115
const outputDir = await mkdtemp(path.join(os.tmpdir(), "matrix-qa-harness-"));
@@ -315,52 +337,66 @@ describe("matrix harness runtime", () => {
315337
});
316338

317339
it("bounds a stalled versions probe by the remaining discovery deadline", async () => {
318-
const probeSignals: AbortSignal[] = [];
319-
const fetchImpl = vi.fn(
320-
async (_input: string, init?: Pick<RequestInit, "signal">) =>
321-
await new Promise<never>((_resolve, reject) => {
322-
const probeSignal = init?.signal ?? undefined;
323-
if (!probeSignal) {
324-
reject(new Error("versions probe signal missing"));
325-
return;
326-
}
327-
probeSignals.push(probeSignal);
328-
const rejectAborted = () => reject(new Error("versions probe aborted"));
329-
if (probeSignal.aborted) {
330-
rejectAborted();
331-
return;
332-
}
333-
probeSignal.addEventListener("abort", rejectAborted, { once: true });
334-
}),
335-
);
336-
const sleepImpl = vi.fn(async (_ms: number) => {});
337-
const startedAt = Date.now();
340+
vi.useFakeTimers();
341+
const requestTimeout = new AbortController();
342+
const timeoutSpy = vi.spyOn(AbortSignal, "timeout").mockReturnValue(requestTimeout.signal);
343+
try {
344+
const { fetchImpl, probeSignals } = createStalledVersionsFetch();
345+
const sleepImpl = vi.fn(async () => {});
346+
const startedAt = Date.now();
347+
const waiting = testing.waitForReachableMatrixBaseUrl({
348+
composeFile: "/tmp/docker-compose.matrix-qa.yml",
349+
containerBaseUrl: null,
350+
fetchImpl,
351+
hostBaseUrl: "http://127.0.0.1:28008/",
352+
sleepImpl,
353+
timeoutMs: 25,
354+
pollMs: 1_000,
355+
});
356+
const rejection = expect(waiting).rejects.toThrow("did not become healthy");
338357

339-
await expect(
340-
testing.waitForReachableMatrixBaseUrl({
358+
await vi.advanceTimersByTimeAsync(25);
359+
await rejection;
360+
361+
expect(Date.now() - startedAt).toBe(25);
362+
expect(probeSignals).toHaveLength(1);
363+
expect(probeSignals[0]?.aborted).toBe(true);
364+
expect(sleepImpl).not.toHaveBeenCalled();
365+
} finally {
366+
timeoutSpy.mockRestore();
367+
vi.useRealTimers();
368+
}
369+
});
370+
371+
it("does not re-poll when the request timeout wins at the discovery deadline", async () => {
372+
vi.useFakeTimers();
373+
const requestTimeout = new AbortController();
374+
const timeoutSpy = vi.spyOn(AbortSignal, "timeout").mockReturnValue(requestTimeout.signal);
375+
try {
376+
const { fetchImpl } = createStalledVersionsFetch();
377+
const startedAt = Date.now();
378+
const sleepImpl = vi.fn(async (ms: number) => {
379+
vi.setSystemTime(Date.now() + ms);
380+
});
381+
const waiting = testing.waitForReachableMatrixBaseUrl({
341382
composeFile: "/tmp/docker-compose.matrix-qa.yml",
342383
containerBaseUrl: null,
343384
fetchImpl,
344385
hostBaseUrl: "http://127.0.0.1:28008/",
345386
sleepImpl,
346387
timeoutMs: 25,
347388
pollMs: 1_000,
348-
}),
349-
).rejects.toThrow("did not become healthy");
350-
351-
expect(Date.now() - startedAt).toBeLessThan(500);
352-
expect(probeSignals).not.toHaveLength(0);
353-
expect(probeSignals.length).toBeLessThanOrEqual(2);
354-
expect(probeSignals.every((signal) => signal.aborted)).toBe(true);
355-
// The inner AbortSignal.timeout (clamped to the remaining budget) and the
356-
// outer deadline timer race at ~timeoutMs. When the inner fires first the
357-
// loop takes one residual micro-sleep before Date.now() crosses the
358-
// deadline. The protected invariant is bounded exit, not zero sleeps:
359-
// allow at most one sleep and require it to be within the deadline budget.
360-
expect(sleepImpl.mock.calls.length).toBeLessThanOrEqual(1);
361-
const residualSleepMs = sleepImpl.mock.calls[0]?.[0];
362-
if (residualSleepMs !== undefined) {
363-
expect(residualSleepMs).toBeLessThanOrEqual(25);
389+
});
390+
391+
vi.setSystemTime(startedAt + 24);
392+
requestTimeout.abort(new DOMException("request timed out", "TimeoutError"));
393+
await expect(waiting).rejects.toThrow("did not become healthy");
394+
395+
expect(fetchImpl).toHaveBeenCalledTimes(1);
396+
expect(sleepImpl).not.toHaveBeenCalled();
397+
} finally {
398+
timeoutSpy.mockRestore();
399+
vi.useRealTimers();
364400
}
365401
});
366402

0 commit comments

Comments
 (0)