Skip to content

Commit 251cf2f

Browse files
committed
fix(matrix): bound startup retirement
1 parent c07afa2 commit 251cf2f

2 files changed

Lines changed: 123 additions & 16 deletions

File tree

‎extensions/matrix/src/matrix/client/shared.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -866,7 +866,7 @@ describe("shared Matrix client generations", () => {
866866
await replacement.release({ mode: "discard" });
867867
});
868868

869-
it("aborts a first starter and waiter during forced retirement without late reuse", async () => {
869+
it("joins an in-flight startup during forced retirement", async () => {
870870
const start = createDeferred<void>();
871871
const firstClient = createMockClient("first");
872872
const replacementClient = createMockClient("replacement");
@@ -914,6 +914,60 @@ describe("shared Matrix client generations", () => {
914914
await replacement.release({ mode: "discard" });
915915
});
916916

917+
it("bounds forced retirement while startup remains stuck and fences late cleanup", async () => {
918+
vi.useFakeTimers();
919+
const start = createDeferred<void>();
920+
const discard = createDeferred<void>();
921+
const firstClient = createMockClient("first");
922+
const replacementClient = createMockClient("replacement");
923+
firstClient.start.mockReturnValue(start.promise);
924+
firstClient.stopWithoutPersist.mockReturnValue(discard.promise);
925+
createMatrixClientMock
926+
.mockResolvedValueOnce(firstClient)
927+
.mockResolvedValueOnce(replacementClient);
928+
const auth = authFor("main");
929+
const lease = await acquireSharedMatrixClient({ auth, startClient: false });
930+
const startup = lease.start();
931+
await vi.waitFor(() => {
932+
expect(firstClient.start).toHaveBeenCalledTimes(1);
933+
});
934+
935+
const retirementError = stopSharedClientForAccount(auth).then(
936+
() => null,
937+
(error: unknown) => error,
938+
);
939+
await expectMatrixStartupAbort(startup);
940+
await vi.advanceTimersByTimeAsync(4_999);
941+
expect(firstClient.stopWithoutPersist).not.toHaveBeenCalled();
942+
943+
await vi.advanceTimersByTimeAsync(1);
944+
await expect(retirementError).resolves.toMatchObject({
945+
message: "Matrix client startup did not settle within 5000ms during retirement",
946+
});
947+
await expect(acquireSharedMatrixClient({ auth, startClient: false })).rejects.toMatchObject({
948+
message: "Matrix client startup did not settle within 5000ms during retirement",
949+
});
950+
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
951+
952+
start.resolve();
953+
await vi.waitFor(() => {
954+
expect(firstClient.stopWithoutPersist).toHaveBeenCalledTimes(1);
955+
});
956+
expect(firstClient.stopAndPersist).not.toHaveBeenCalled();
957+
await expect(acquireSharedMatrixClient({ auth, startClient: false })).rejects.toMatchObject({
958+
message: "Matrix client startup did not settle within 5000ms during retirement",
959+
});
960+
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
961+
962+
discard.resolve();
963+
await discard.promise;
964+
await Promise.resolve();
965+
const replacement = await acquireSharedMatrixClient({ auth, startClient: false });
966+
expect(replacement.client).toBe(replacementClient);
967+
expect(createMatrixClientMock).toHaveBeenCalledTimes(2);
968+
await replacement.release({ mode: "discard" });
969+
});
970+
917971
it("does not let one aborted startup waiter remove another lease", async () => {
918972
const client = createMockClient("main");
919973
const start = createDeferred<void>();

‎extensions/matrix/src/matrix/client/shared.ts‎

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const loadMatrixCreateClientDeps = createLazyRuntimeModule(() =>
1515
createMatrixClient: runtime.createMatrixClient,
1616
})),
1717
);
18-
const MATRIX_TRANSIENT_LEASE_DRAIN_TIMEOUT_MS = 5_000;
18+
const MATRIX_RETIREMENT_DRAIN_TIMEOUT_MS = 5_000;
1919

2020
export type MatrixClientLeaseRole = "monitor" | "transient";
2121
export type MatrixClientReleaseMode = "stop" | "persist" | "discard";
@@ -323,26 +323,27 @@ function forceReleaseLeases(
323323
state.noLeases.resolve();
324324
}
325325

326-
async function waitForLeaseDrain(state: SharedMatrixClientState): Promise<void> {
327-
if (state.leases.size === 0) {
326+
async function waitForRetirementDrain(params: {
327+
state: SharedMatrixClientState;
328+
task: Promise<unknown>;
329+
isPending: () => boolean;
330+
timeoutMessage: string;
331+
}): Promise<void> {
332+
if (!params.isPending()) {
328333
return;
329334
}
330335
let deadline: NodeJS.Timeout | undefined;
331336
try {
332337
await Promise.race([
333-
state.noLeases.promise,
338+
params.task,
334339
new Promise<never>((_, reject) => {
335340
deadline = setTimeout(() => {
336-
if (state.leases.size === 0) {
341+
if (!params.isPending()) {
337342
return;
338343
}
339-
state.phase = "late-drain";
340-
reject(
341-
new Error(
342-
`Matrix transient leases did not drain within ${MATRIX_TRANSIENT_LEASE_DRAIN_TIMEOUT_MS}ms`,
343-
),
344-
);
345-
}, MATRIX_TRANSIENT_LEASE_DRAIN_TIMEOUT_MS);
344+
params.state.phase = "late-drain";
345+
reject(new Error(params.timeoutMessage));
346+
}, MATRIX_RETIREMENT_DRAIN_TIMEOUT_MS);
346347
deadline.unref?.();
347348
}),
348349
]);
@@ -353,6 +354,34 @@ async function waitForLeaseDrain(state: SharedMatrixClientState): Promise<void>
353354
}
354355
}
355356

357+
async function waitForLeaseDrain(state: SharedMatrixClientState): Promise<void> {
358+
await waitForRetirementDrain({
359+
state,
360+
task: state.noLeases.promise,
361+
isPending: () => state.leases.size > 0,
362+
timeoutMessage: `Matrix transient leases did not drain within ${MATRIX_RETIREMENT_DRAIN_TIMEOUT_MS}ms`,
363+
});
364+
}
365+
366+
async function continueLateGenerationRetirement(
367+
state: SharedMatrixClientState,
368+
startup: Promise<void>,
369+
monitorLeases: SharedMatrixClientLeaseState[],
370+
): Promise<void> {
371+
await startup.catch(() => undefined);
372+
try {
373+
await state.client.stopWithoutPersist();
374+
state.started = false;
375+
await retireMonitorLeases(state, monitorLeases);
376+
} catch (error) {
377+
state.poisonError = toRetirementError(error);
378+
return;
379+
}
380+
state.phase = "late-drain-stopped";
381+
state.startPromise = null;
382+
deleteSharedClientStateAfterLateDrain(state);
383+
}
384+
356385
function beginGenerationRetirement(params: {
357386
state: SharedMatrixClientState;
358387
monitorLeases?: SharedMatrixClientLeaseState[];
@@ -364,9 +393,27 @@ function beginGenerationRetirement(params: {
364393
state.phase = "quiescing";
365394
state.retirementPromise = Promise.resolve().then(async () => {
366395
let poisonDisposition: PoisonDisposition = "replace-after-stop";
367-
// Startup owns SDK initialization until its underlying task settles. Joining
368-
// it prevents a canceled generation from starting or persisting after stop.
369-
await state.startPromise?.catch(() => undefined);
396+
const startup = state.startPromise;
397+
if (startup) {
398+
try {
399+
await waitForRetirementDrain({
400+
state,
401+
task: startup.catch(() => undefined),
402+
isPending: () => state.startPromise === startup,
403+
timeoutMessage: `Matrix client startup did not settle within ${MATRIX_RETIREMENT_DRAIN_TIMEOUT_MS}ms during retirement`,
404+
});
405+
} catch (error) {
406+
state.poisonError = toRetirementError(error);
407+
// The SDK cannot cancel crypto initialization. Keep this generation keyed
408+
// and stop it without persistence as soon as the owned startup settles.
409+
state.startPromise = continueLateGenerationRetirement(
410+
state,
411+
startup,
412+
params.monitorLeases ?? [],
413+
);
414+
throw state.poisonError;
415+
}
416+
}
370417
try {
371418
await state.client.quiesceSync();
372419
state.started = false;
@@ -544,6 +591,9 @@ export async function acquireSharedMatrixClient(
544591
}
545592

546593
async function forceRetireState(state: SharedMatrixClientState): Promise<void> {
594+
if (state.phase === "late-drain" && state.startPromise) {
595+
throw state.poisonError ?? new Error("Matrix client generation is still retiring");
596+
}
547597
state.releaseMode = mergeReleaseMode(state.releaseMode, "stop");
548598
const retirementPromise = beginGenerationRetirement({
549599
state,
@@ -556,6 +606,9 @@ async function forceRetireState(state: SharedMatrixClientState): Promise<void> {
556606
return;
557607
}
558608
await retirementPromise.catch((error: unknown) => {
609+
if (state.phase === "late-drain" && state.startPromise) {
610+
throw error;
611+
}
559612
if (!state.poisonError) {
560613
throw error;
561614
}

0 commit comments

Comments
 (0)