Skip to content

Commit 3ee32fb

Browse files
authored
fix(matrix): drain monitor tasks before retiring clients (#134033)
* fix(matrix): drain monitor tasks before retiring clients * test(matrix): split monitor task lifecycle coverage * refactor(qa): pass prepared factories into suite children * test(agents): preserve prepared model identity in prompt fixture * test(node-host): serialize fake container state transitions
1 parent a7be8e5 commit 3ee32fb

16 files changed

Lines changed: 716 additions & 119 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Docs: https://docs.openclaw.ai
7171

7272
### Fixes
7373

74+
- Matrix lifecycle: drain in-flight monitor tasks without deadlocking shared-client retirement, and reject late acquisitions after their owning task closes.
7475
- Provider error handling: reuse prepared or already loaded provider hooks instead of cold-loading plugins during error classification, avoiding long stalls in failure reporting and model fallback.
7576
- **Subagent completion:** recognize visible final answers delivered to internal and nested parent sessions, preventing false delivery failures while preserving external channel delivery checks.
7677
- Codex/Linux: wait for a live app-server process to expose its startup command line within the existing inspection deadline, preserving process identity checks and preventing intermittent startup failures.
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
// Matrix tests cover shared plugin behavior.
2+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
3+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { createMatrixMonitorTaskRunner } from "../monitor/task-runner.js";
5+
import { authFor, createMockClient } from "./shared.test-support.js";
6+
import type { MatrixAuth } from "./types.js";
7+
8+
const resolveMatrixAuthMock = vi.hoisted(() => vi.fn());
9+
const resolveMatrixAuthContextMock = vi.hoisted(() => vi.fn());
10+
const createMatrixClientMock = vi.hoisted(() => vi.fn());
11+
12+
const TEST_CFG = {};
13+
14+
vi.mock("./config.js", () => ({
15+
resolveMatrixAuth: resolveMatrixAuthMock,
16+
resolveMatrixAuthContext: resolveMatrixAuthContextMock,
17+
}));
18+
19+
vi.mock("./create-client.js", () => ({
20+
createMatrixClient: createMatrixClientMock,
21+
}));
22+
23+
let acquireSharedMatrixClient: typeof import("./shared.js").acquireSharedMatrixClient;
24+
let stopSharedClientForAccount: typeof import("./shared.js").stopSharedClientForAccount;
25+
26+
describe("shared Matrix monitor task ownership", () => {
27+
beforeAll(async () => {
28+
({ acquireSharedMatrixClient, stopSharedClientForAccount } = await import("./shared.js"));
29+
});
30+
31+
beforeEach(() => {
32+
resolveMatrixAuthMock.mockReset();
33+
resolveMatrixAuthContextMock.mockReset();
34+
createMatrixClientMock.mockReset();
35+
resolveMatrixAuthContextMock.mockImplementation(
36+
({ accountId }: { accountId?: string | null } = {}) => ({
37+
cfg: TEST_CFG,
38+
env: undefined,
39+
accountId: accountId ?? "default",
40+
resolved: {},
41+
}),
42+
);
43+
});
44+
45+
afterEach(async () => {
46+
await Promise.allSettled([
47+
stopSharedClientForAccount(authFor("main")),
48+
stopSharedClientForAccount(authFor("ops")),
49+
]);
50+
vi.useRealTimers();
51+
vi.clearAllMocks();
52+
});
53+
54+
it.each(
55+
["monitor release", "account stop"].flatMap((retirementOwner) =>
56+
["release", "late acquisition"].map((operation) => ({ retirementOwner, operation })),
57+
),
58+
)(
59+
"drains monitor tasks during $retirementOwner with a transient $operation",
60+
async ({ retirementOwner, operation }) => {
61+
const client = createMockClient("main");
62+
createMatrixClientMock.mockResolvedValue(client);
63+
const auth = authFor("main");
64+
const monitor = await acquireSharedMatrixClient({
65+
auth,
66+
role: "monitor",
67+
startClient: false,
68+
});
69+
const transient =
70+
operation === "release"
71+
? await acquireSharedMatrixClient({ auth, role: "transient", startClient: false })
72+
: undefined;
73+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
74+
const tasks = createMatrixMonitorTaskRunner({ logger, logVerboseMessage: vi.fn() });
75+
const sendFinished = createDeferred<void>();
76+
const releaseTestDrain = createDeferred<void>();
77+
const taskAdmissionClosed = createDeferred<void>();
78+
const taskFinished = vi.fn();
79+
let lateLease: Awaited<ReturnType<typeof acquireSharedMatrixClient>> | undefined;
80+
let acquisitionError: unknown;
81+
const task = tasks.runDetachedTask("join introduction", async () => {
82+
await sendFinished.promise;
83+
if (transient) {
84+
await transient.release({ mode: "persist" });
85+
} else {
86+
try {
87+
lateLease = await acquireSharedMatrixClient({ auth, startClient: false });
88+
} catch (error) {
89+
acquisitionError = error;
90+
}
91+
}
92+
taskFinished();
93+
});
94+
monitor.registerMonitorRetirement({
95+
closeTaskAdmission: () => {
96+
tasks.close();
97+
taskAdmissionClosed.resolve();
98+
},
99+
detachListeners: vi.fn(),
100+
// The escape is only released in finally so a failing assertion still joins every task.
101+
waitForTasks: () => Promise.race([tasks.waitForIdle(), releaseTestDrain.promise]),
102+
cleanup: vi.fn(),
103+
});
104+
105+
const retirement =
106+
retirementOwner === "account stop"
107+
? stopSharedClientForAccount(auth)
108+
: monitor.release({ mode: "persist" });
109+
await taskAdmissionClosed.promise;
110+
sendFinished.resolve();
111+
try {
112+
await vi.waitFor(() => {
113+
expect(taskFinished).toHaveBeenCalledOnce();
114+
});
115+
await retirement;
116+
if (operation === "late acquisition") {
117+
expect(acquisitionError).toMatchObject({ name: "AbortError" });
118+
expect(lateLease).toBeUndefined();
119+
}
120+
expect(client.stopAndPersist).toHaveBeenCalledOnce();
121+
expect(client.stopWithoutPersist).not.toHaveBeenCalled();
122+
expect(logger.warn).not.toHaveBeenCalled();
123+
} finally {
124+
releaseTestDrain.resolve();
125+
await Promise.all([task, retirement]);
126+
await lateLease?.release();
127+
}
128+
},
129+
);
130+
131+
it("rejects retained async acquisitions after the owning monitor task settles", async () => {
132+
const client = createMockClient("main");
133+
createMatrixClientMock.mockResolvedValue(client);
134+
const auth = authFor("main");
135+
const monitor = await acquireSharedMatrixClient({ auth, role: "monitor", startClient: false });
136+
const tasks = createMatrixMonitorTaskRunner({
137+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
138+
logVerboseMessage: vi.fn(),
139+
});
140+
const resume = createDeferred<void>();
141+
let retained: Promise<unknown> | undefined;
142+
let retainedLease: Awaited<ReturnType<typeof acquireSharedMatrixClient>> | undefined;
143+
await tasks.runDetachedTask("retained continuation", async () => {
144+
retained = resume.promise.then(async () => {
145+
try {
146+
retainedLease = await acquireSharedMatrixClient({ auth, startClient: false });
147+
return null;
148+
} catch (error) {
149+
return error;
150+
}
151+
});
152+
});
153+
resume.resolve();
154+
try {
155+
await expect(retained).resolves.toMatchObject({ name: "AbortError" });
156+
const unrelated = await acquireSharedMatrixClient({ auth, startClient: false });
157+
expect(unrelated.client).toBe(client);
158+
await unrelated.release();
159+
} finally {
160+
await retained;
161+
await retainedLease?.release();
162+
await monitor.release();
163+
}
164+
});
165+
166+
it.each(
167+
["authentication", "client creation"].flatMap((phase) =>
168+
["monitor", "caller"].map((abortOwner) => ({ phase, abortOwner })),
169+
),
170+
)(
171+
"rejects $abortOwner cancellation during $phase before admitting a lease",
172+
async ({ phase, abortOwner }) => {
173+
const auth = authFor("main");
174+
const client = createMockClient("main");
175+
const authReady = createDeferred<MatrixAuth>();
176+
const clientReady = createDeferred<typeof client>();
177+
resolveMatrixAuthMock.mockReturnValue(
178+
phase === "authentication" ? authReady.promise : Promise.resolve(auth),
179+
);
180+
createMatrixClientMock.mockReturnValue(
181+
phase === "client creation" ? clientReady.promise : Promise.resolve(client),
182+
);
183+
const tasks = createMatrixMonitorTaskRunner({
184+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
185+
logVerboseMessage: vi.fn(),
186+
});
187+
const caller = new AbortController();
188+
let lease: Awaited<ReturnType<typeof acquireSharedMatrixClient>> | undefined;
189+
let acquisitionError: unknown;
190+
const task = tasks.runDetachedTask("pending acquisition", async () => {
191+
try {
192+
lease = await acquireSharedMatrixClient({
193+
cfg: TEST_CFG,
194+
accountId: "main",
195+
startClient: false,
196+
abortSignal: caller.signal,
197+
});
198+
} catch (error) {
199+
acquisitionError = error;
200+
}
201+
});
202+
try {
203+
await vi.waitFor(() => {
204+
expect(
205+
phase === "authentication" ? resolveMatrixAuthMock : createMatrixClientMock,
206+
).toHaveBeenCalledOnce();
207+
});
208+
if (abortOwner === "monitor") {
209+
tasks.close();
210+
} else {
211+
caller.abort();
212+
}
213+
authReady.resolve(auth);
214+
clientReady.resolve(client);
215+
await task;
216+
expect(acquisitionError).toMatchObject({ name: "AbortError" });
217+
expect(lease).toBeUndefined();
218+
expect(client.start).not.toHaveBeenCalled();
219+
if (phase === "authentication") {
220+
expect(createMatrixClientMock).not.toHaveBeenCalled();
221+
} else {
222+
expect(client.stopWithoutPersist).toHaveBeenCalledOnce();
223+
}
224+
} finally {
225+
authReady.resolve(auth);
226+
clientReady.resolve(client);
227+
await task;
228+
await lease?.release();
229+
}
230+
},
231+
);
232+
});
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { vi } from "vitest";
2+
import type { MatrixAuth } from "./types.js";
3+
4+
export function authFor(accountId: string): MatrixAuth {
5+
return {
6+
accountId,
7+
homeserver: "https://matrix.example.org",
8+
userId: `@${accountId}:example.org`,
9+
accessToken: `token-${accountId}`,
10+
password: "secret", // pragma: allowlist secret
11+
deviceId: `${accountId.toUpperCase()}-DEVICE`,
12+
deviceName: `${accountId} device`,
13+
initialSyncLimit: undefined,
14+
encryption: false,
15+
};
16+
}
17+
18+
export function createMockClient(name: string, callOrder: string[] = []) {
19+
return {
20+
name,
21+
start: vi.fn(async (_params?: { abortSignal?: AbortSignal }) => {
22+
callOrder.push("start");
23+
}),
24+
quiesceSync: vi.fn(async () => {
25+
callOrder.push("quiesce");
26+
}),
27+
stop: vi.fn(() => {
28+
callOrder.push("stop");
29+
}),
30+
stopAndPersist: vi.fn(async () => {
31+
callOrder.push("persist");
32+
}),
33+
stopWithoutPersist: vi.fn(async () => {
34+
callOrder.push("discard");
35+
}),
36+
drainPendingDecryptions: vi.fn(async (reason: string) => {
37+
callOrder.push(
38+
reason === "matrix monitor sync quiesce"
39+
? "drain-quiesce"
40+
: reason === "matrix shared client final shutdown"
41+
? "drain-final"
42+
: "drain-poison",
43+
);
44+
}),
45+
getJoinedRooms: vi.fn(async () => [] as string[]),
46+
crypto: undefined,
47+
};
48+
}

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

Lines changed: 1 addition & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Matrix tests cover shared plugin behavior.
22
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
33
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { authFor, createMockClient } from "./shared.test-support.js";
45
import type { MatrixAuth } from "./types.js";
56

67
const resolveMatrixAuthMock = vi.hoisted(() => vi.fn());
@@ -21,52 +22,6 @@ vi.mock("./create-client.js", () => ({
2122
let acquireSharedMatrixClient: typeof import("./shared.js").acquireSharedMatrixClient;
2223
let stopSharedClientForAccount: typeof import("./shared.js").stopSharedClientForAccount;
2324

24-
function authFor(accountId: string): MatrixAuth {
25-
return {
26-
accountId,
27-
homeserver: "https://matrix.example.org",
28-
userId: `@${accountId}:example.org`,
29-
accessToken: `token-${accountId}`,
30-
password: "secret", // pragma: allowlist secret
31-
deviceId: `${accountId.toUpperCase()}-DEVICE`,
32-
deviceName: `${accountId} device`,
33-
initialSyncLimit: undefined,
34-
encryption: false,
35-
};
36-
}
37-
38-
function createMockClient(name: string, callOrder: string[] = []) {
39-
return {
40-
name,
41-
start: vi.fn(async (_params?: { abortSignal?: AbortSignal }) => {
42-
callOrder.push("start");
43-
}),
44-
quiesceSync: vi.fn(async () => {
45-
callOrder.push("quiesce");
46-
}),
47-
stop: vi.fn(() => {
48-
callOrder.push("stop");
49-
}),
50-
stopAndPersist: vi.fn(async () => {
51-
callOrder.push("persist");
52-
}),
53-
stopWithoutPersist: vi.fn(async () => {
54-
callOrder.push("discard");
55-
}),
56-
drainPendingDecryptions: vi.fn(async (reason: string) => {
57-
callOrder.push(
58-
reason === "matrix monitor sync quiesce"
59-
? "drain-quiesce"
60-
: reason === "matrix shared client final shutdown"
61-
? "drain-final"
62-
: "drain-poison",
63-
);
64-
}),
65-
getJoinedRooms: vi.fn(async () => [] as string[]),
66-
crypto: undefined,
67-
};
68-
}
69-
7025
function createMonitorRetirement(callOrder: string[]) {
7126
return {
7227
closeTaskAdmission: vi.fn(() => callOrder.push("close-admission")),

0 commit comments

Comments
 (0)