Skip to content

Commit 784a228

Browse files
bdjbenBenjamin Badejo
andauthored
fix(matrix): recover after late leases drain (#126712)
Co-authored-by: Benjamin Badejo <[email protected]>
1 parent d00cbd1 commit 784a228

3 files changed

Lines changed: 319 additions & 27 deletions

File tree

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

Lines changed: 130 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,34 @@ describe("shared Matrix client generations", () => {
318318
]);
319319
});
320320

321+
it("retries admission when retirement starts after state resolution", async () => {
322+
const retiringClient = createMockClient("retiring");
323+
const replacementClient = createMockClient("replacement");
324+
createMatrixClientMock
325+
.mockResolvedValueOnce(retiringClient)
326+
.mockResolvedValueOnce(replacementClient);
327+
const auth = authFor("main");
328+
const monitor = await acquireSharedMatrixClient({
329+
auth,
330+
role: "monitor",
331+
startClient: false,
332+
});
333+
monitor.registerMonitorRetirement(createMonitorRetirement([]));
334+
335+
const racingAcquire = acquireSharedMatrixClient({ auth, startClient: false });
336+
let retirement: Promise<void> | undefined;
337+
queueMicrotask(() => {
338+
retirement = monitor.release({ mode: "discard" });
339+
});
340+
341+
const racingLease = await racingAcquire;
342+
await racingLease.release({ mode: "discard" });
343+
await retirement;
344+
345+
expect(racingLease.client).toBe(replacementClient);
346+
expect(createMatrixClientMock).toHaveBeenCalledTimes(2);
347+
});
348+
321349
it("signals cooperative transient work and persists after it drains", async () => {
322350
const callOrder: string[] = [];
323351
const client = createMockClient("main", callOrder);
@@ -360,18 +388,24 @@ describe("shared Matrix client generations", () => {
360388
expect(client.stopWithoutPersist).not.toHaveBeenCalled();
361389
});
362390

363-
it("bounds non-cooperative transient drain and makes late release harmless", async () => {
391+
it("bounds non-cooperative transient drain and replaces after every late release", async () => {
364392
vi.useFakeTimers();
365393
const callOrder: string[] = [];
366394
const client = createMockClient("main", callOrder);
367-
createMatrixClientMock.mockResolvedValue(client);
395+
const replacementClient = createMockClient("replacement");
396+
createMatrixClientMock.mockResolvedValueOnce(client).mockResolvedValueOnce(replacementClient);
368397
const auth = authFor("main");
369398
const monitor = await acquireSharedMatrixClient({
370399
auth,
371400
role: "monitor",
372401
startClient: false,
373402
});
374-
const transient = await acquireSharedMatrixClient({
403+
const firstTransient = await acquireSharedMatrixClient({
404+
auth,
405+
role: "transient",
406+
startClient: false,
407+
});
408+
const finalTransient = await acquireSharedMatrixClient({
375409
auth,
376410
role: "transient",
377411
startClient: false,
@@ -390,20 +424,109 @@ describe("shared Matrix client generations", () => {
390424
await expect(retirementError).resolves.toMatchObject({
391425
message: "Matrix transient leases did not drain within 5000ms",
392426
});
393-
expect(transient.abortSignal.aborted).toBe(true);
427+
expect(firstTransient.abortSignal.aborted).toBe(true);
428+
expect(finalTransient.abortSignal.aborted).toBe(true);
394429
expect(client.stopWithoutPersist).toHaveBeenCalledTimes(1);
395430
expect(client.stopAndPersist).not.toHaveBeenCalled();
396431
await expect(acquireSharedMatrixClient({ auth })).rejects.toMatchObject({
397432
message: "Matrix transient leases did not drain within 5000ms",
398433
});
399434
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
400435

401-
const firstLateRelease = transient.release({ mode: "persist" });
402-
const secondLateRelease = transient.release({ mode: "persist" });
403-
expect(secondLateRelease).toBe(firstLateRelease);
436+
const firstLateRelease = firstTransient.release({ mode: "persist" });
437+
const duplicateLateRelease = firstTransient.release({ mode: "persist" });
438+
expect(duplicateLateRelease).toBe(firstLateRelease);
404439
await firstLateRelease;
405440
expect(client.stopWithoutPersist).toHaveBeenCalledTimes(1);
406441
expect(client.stopAndPersist).not.toHaveBeenCalled();
442+
await expect(acquireSharedMatrixClient({ auth })).rejects.toMatchObject({
443+
message: "Matrix transient leases did not drain within 5000ms",
444+
});
445+
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
446+
447+
await finalTransient.release({ mode: "persist" });
448+
449+
const [firstReplacement, secondReplacement] = await Promise.all([
450+
acquireSharedMatrixClient({ auth, startClient: false }),
451+
acquireSharedMatrixClient({ auth, startClient: false }),
452+
]);
453+
expect(firstReplacement.client).toBe(replacementClient);
454+
expect(secondReplacement.client).toBe(replacementClient);
455+
expect(createMatrixClientMock).toHaveBeenCalledTimes(2);
456+
await firstReplacement.release({ mode: "discard" });
457+
await secondReplacement.release({ mode: "discard" });
458+
});
459+
460+
it("keeps monitor cleanup poison after every late transient releases", async () => {
461+
vi.useFakeTimers();
462+
const cause = new Error("monitor cleanup failed");
463+
const client = createMockClient("main");
464+
createMatrixClientMock.mockResolvedValue(client);
465+
const auth = authFor("main");
466+
const monitor = await acquireSharedMatrixClient({
467+
auth,
468+
role: "monitor",
469+
startClient: false,
470+
});
471+
const transient = await acquireSharedMatrixClient({
472+
auth,
473+
role: "transient",
474+
startClient: false,
475+
});
476+
const monitorRetirement = createMonitorRetirement([]);
477+
monitorRetirement.cleanup.mockRejectedValue(cause);
478+
monitor.registerMonitorRetirement(monitorRetirement);
479+
480+
const retirementError = monitor.release({ mode: "persist" }).then(
481+
() => null,
482+
(error: unknown) => error,
483+
);
484+
await vi.advanceTimersByTimeAsync(5_000);
485+
await expect(retirementError).resolves.toBe(cause);
486+
await transient.release();
487+
488+
await expect(acquireSharedMatrixClient({ auth })).rejects.toBe(cause);
489+
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
490+
});
491+
492+
it("keeps poison when the poisoned decryption drain fails before a late release", async () => {
493+
vi.useFakeTimers();
494+
const cause = new Error("poisoned decryption drain failed");
495+
const client = createMockClient("main");
496+
client.drainPendingDecryptions.mockImplementation(async (reason: string) => {
497+
if (reason === "matrix poisoned client shutdown") {
498+
throw cause;
499+
}
500+
});
501+
createMatrixClientMock.mockResolvedValue(client);
502+
const auth = authFor("main");
503+
const monitor = await acquireSharedMatrixClient({
504+
auth,
505+
role: "monitor",
506+
startClient: false,
507+
});
508+
const transient = await acquireSharedMatrixClient({
509+
auth,
510+
role: "transient",
511+
startClient: false,
512+
});
513+
monitor.registerMonitorRetirement(createMonitorRetirement([]));
514+
515+
const retirementError = monitor.release({ mode: "persist" }).then(
516+
() => null,
517+
(error: unknown) => error,
518+
);
519+
await vi.advanceTimersByTimeAsync(5_000);
520+
await expect(retirementError).resolves.toMatchObject({
521+
message: "Matrix transient leases did not drain within 5000ms",
522+
});
523+
await transient.release();
524+
525+
await expect(acquireSharedMatrixClient({ auth })).rejects.toMatchObject({
526+
message: "Matrix transient leases did not drain within 5000ms",
527+
});
528+
expect(client.stopWithoutPersist).toHaveBeenCalledTimes(1);
529+
expect(createMatrixClientMock).toHaveBeenCalledTimes(1);
407530
});
408531

409532
it("quiesces and cleans up the monitor before waiting for an existing transient lease", async () => {

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

Lines changed: 58 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,14 @@ export type SharedMatrixClientLease = {
3636
release: (params?: { mode?: MatrixClientReleaseMode }) => Promise<void>;
3737
};
3838

39-
type SharedMatrixClientPhase = "open" | "quiescing" | "closing";
39+
type SharedMatrixClientPhase =
40+
| "open"
41+
| "quiescing"
42+
| "closing"
43+
| "late-drain"
44+
| "late-drain-stopped";
45+
46+
type PoisonDisposition = "replace-after-stop" | "replace-after-late-drain" | "retain";
4047

4148
type SharedMatrixClientLeaseState = {
4249
abortController: AbortController;
@@ -133,6 +140,12 @@ function deleteSharedClientState(state: SharedMatrixClientState): void {
133140
sharedClientPromises.delete(state.key);
134141
}
135142

143+
function deleteSharedClientStateAfterLateDrain(state: SharedMatrixClientState): void {
144+
if (state.phase === "late-drain-stopped" && state.leases.size === 0) {
145+
deleteSharedClientState(state);
146+
}
147+
}
148+
136149
async function ensureSharedClientStarted(
137150
state: SharedMatrixClientState,
138151
abortSignal?: AbortSignal,
@@ -319,6 +332,10 @@ async function waitForLeaseDrain(state: SharedMatrixClientState): Promise<void>
319332
state.noLeases.promise,
320333
new Promise<never>((_, reject) => {
321334
deadline = setTimeout(() => {
335+
if (state.leases.size === 0) {
336+
return;
337+
}
338+
state.phase = "late-drain";
322339
reject(
323340
new Error(
324341
`Matrix transient leases did not drain within ${MATRIX_TRANSIENT_LEASE_DRAIN_TIMEOUT_MS}ms`,
@@ -345,30 +362,30 @@ function beginGenerationRetirement(params: {
345362
}
346363
state.phase = "quiescing";
347364
state.retirementPromise = Promise.resolve().then(async () => {
348-
let canReplacePoisonedGeneration = false;
365+
let poisonDisposition: PoisonDisposition = "replace-after-stop";
349366
try {
350367
await state.client.quiesceSync();
351368
state.started = false;
352369
await state.client.drainPendingDecryptions("matrix monitor sync quiesce");
353370
} catch (error) {
354371
state.poisonError = toRetirementError(error);
355-
canReplacePoisonedGeneration = true;
356372
}
357373

358374
try {
359375
await retireMonitorLeases(state, params.monitorLeases ?? []);
360376
} catch (error) {
361377
state.poisonError ??= toRetirementError(error);
362-
canReplacePoisonedGeneration = false;
378+
poisonDisposition = "retain";
363379
}
364380

365381
state.phase = "closing";
366382
try {
367383
await waitForLeaseDrain(state);
368384
} catch (error) {
369385
state.poisonError ??= toRetirementError(error);
370-
canReplacePoisonedGeneration = false;
371-
forceReleaseLeases(state);
386+
if (poisonDisposition !== "retain") {
387+
poisonDisposition = "replace-after-late-drain";
388+
}
372389
}
373390

374391
if (state.poisonError) {
@@ -379,10 +396,15 @@ function beginGenerationRetirement(params: {
379396
() => false,
380397
);
381398
state.client.stopWithoutPersist();
382-
// Only sync/decryption poison is replaceable, after every other owner retired
383-
// and the discarded client conclusively drained and stopped.
384-
if (canReplacePoisonedGeneration && decryptionsDrained) {
385-
deleteSharedClientState(state);
399+
if (decryptionsDrained) {
400+
if (poisonDisposition === "replace-after-stop") {
401+
deleteSharedClientState(state);
402+
} else if (poisonDisposition === "replace-after-late-drain") {
403+
// The timeout cannot revoke ownership. Keep the stopped generation keyed
404+
// until every operation that crossed the deadline genuinely returns.
405+
state.phase = "late-drain-stopped";
406+
deleteSharedClientStateAfterLateDrain(state);
407+
}
386408
}
387409
throw state.poisonError;
388410
}
@@ -417,7 +439,12 @@ function beginGenerationRetirement(params: {
417439
function createSharedMatrixClientLease(
418440
state: SharedMatrixClientState,
419441
role: MatrixClientLeaseRole,
420-
): SharedMatrixClientLease {
442+
): SharedMatrixClientLease | null {
443+
// Resolution awaits auth/retirement and can yield after observing an open state.
444+
// Recheck synchronously at admission so retirement cannot miss a late-added owner.
445+
if (state.phase !== "open" || state.poisonError) {
446+
return null;
447+
}
421448
const leaseState: SharedMatrixClientLeaseState = {
422449
abortController: new AbortController(),
423450
monitorRetirement: null,
@@ -465,6 +492,12 @@ function createSharedMatrixClientLease(
465492
state.noLeases.resolve();
466493
}
467494

495+
if (state.phase === "late-drain" || state.phase === "late-drain-stopped") {
496+
leaseState.releasePromise = Promise.resolve();
497+
deleteSharedClientStateAfterLateDrain(state);
498+
return leaseState.releasePromise;
499+
}
500+
468501
const finalMonitor =
469502
role === "monitor" && !Array.from(state.leases).some((lease) => lease.role === "monitor");
470503
if (role === "monitor" && !finalMonitor) {
@@ -488,17 +521,22 @@ function createSharedMatrixClientLease(
488521
export async function acquireSharedMatrixClient(
489522
params: SharedMatrixClientParams = {},
490523
): Promise<SharedMatrixClientLease> {
491-
const state = await resolveOpenSharedMatrixClientState(params);
492-
const lease = createSharedMatrixClientLease(state, params.role ?? "transient");
493-
if (params.startClient !== false) {
494-
try {
495-
await lease.start(params.abortSignal);
496-
} catch (error) {
497-
await lease.release({ mode: "stop" }).catch(() => undefined);
498-
throw error;
524+
while (true) {
525+
const state = await resolveOpenSharedMatrixClientState(params);
526+
const lease = createSharedMatrixClientLease(state, params.role ?? "transient");
527+
if (!lease) {
528+
continue;
529+
}
530+
if (params.startClient !== false) {
531+
try {
532+
await lease.start(params.abortSignal);
533+
} catch (error) {
534+
await lease.release({ mode: "stop" }).catch(() => undefined);
535+
throw error;
536+
}
499537
}
538+
return lease;
500539
}
501-
return lease;
502540
}
503541

504542
async function forceRetireState(state: SharedMatrixClientState): Promise<void> {

0 commit comments

Comments
 (0)