Skip to content

Commit d98e984

Browse files
authored
fix(qa): isolate Matrix live validation state (#116071)
* fix(qa): isolate Matrix live scenario routing * fix(qa): preserve Matrix mention filenames * fix(qa): reset Matrix transport scenario state * test(qa): isolate stateful Matrix scenario partitions * test(qa): match numbered Matrix isolation * test(qa): reject stale Matrix progress results * fix(qa): bound Matrix scenario prompt ownership * fix(qa): bound mock scenario ownership * test(qa): satisfy Matrix validation gates * refactor(qa): remove stale prompt helper * fix(qa): preserve tool-result ownership after rebase
1 parent fc3f114 commit d98e984

36 files changed

Lines changed: 1010 additions & 141 deletions
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { waitForMatrixQaObserverEvent } from "./adapter.runtime.js";
3+
import type { MatrixQaRoomObserver } from "./substrate/sync.js";
4+
5+
function makeObserver(
6+
waitForOptionalRoomEvent: MatrixQaRoomObserver["waitForOptionalRoomEvent"],
7+
): MatrixQaRoomObserver {
8+
return {
9+
prime: vi.fn(async () => "s0"),
10+
waitForOptionalRoomEvent,
11+
waitForRoomEvent: vi.fn(),
12+
};
13+
}
14+
15+
describe("Matrix QA adapter observer recovery", () => {
16+
it("retries a sync failure only during the explicit transport interruption window", async () => {
17+
let interrupted = true;
18+
const waitForOptionalRoomEvent = vi
19+
.fn<MatrixQaRoomObserver["waitForOptionalRoomEvent"]>()
20+
.mockRejectedValueOnce(new Error("homeserver unavailable"))
21+
.mockResolvedValueOnce({ matched: false, since: "s1" });
22+
const sleepImpl = vi.fn(async () => {
23+
interrupted = false;
24+
});
25+
26+
await expect(
27+
waitForMatrixQaObserverEvent({
28+
isExpectedInterruption: () => interrupted,
29+
observer: makeObserver(waitForOptionalRoomEvent),
30+
predicate: () => true,
31+
readInterruptionGeneration: () => 1,
32+
roomId: "!room:matrix.test",
33+
sleepImpl,
34+
timeoutMs: 1_000,
35+
}),
36+
).resolves.toEqual({ matched: false, since: "s1" });
37+
expect(waitForOptionalRoomEvent).toHaveBeenCalledTimes(2);
38+
expect(sleepImpl).toHaveBeenCalledOnce();
39+
});
40+
41+
it("preserves terminal observer failures outside the interruption window", async () => {
42+
const failure = new Error("sync failed");
43+
const waitForOptionalRoomEvent = vi
44+
.fn<MatrixQaRoomObserver["waitForOptionalRoomEvent"]>()
45+
.mockRejectedValue(failure);
46+
const sleepImpl = vi.fn(async () => undefined);
47+
48+
await expect(
49+
waitForMatrixQaObserverEvent({
50+
isExpectedInterruption: () => false,
51+
observer: makeObserver(waitForOptionalRoomEvent),
52+
predicate: () => true,
53+
readInterruptionGeneration: () => 0,
54+
roomId: "!room:matrix.test",
55+
sleepImpl,
56+
timeoutMs: 1_000,
57+
}),
58+
).rejects.toBe(failure);
59+
expect(waitForOptionalRoomEvent).toHaveBeenCalledOnce();
60+
expect(sleepImpl).not.toHaveBeenCalled();
61+
});
62+
63+
it("retries a poll that started during interruption after readiness closes the window", async () => {
64+
let interrupted = true;
65+
const waitForOptionalRoomEvent = vi
66+
.fn<MatrixQaRoomObserver["waitForOptionalRoomEvent"]>()
67+
.mockImplementationOnce(async () => {
68+
interrupted = false;
69+
throw new Error("stale outage response");
70+
})
71+
.mockResolvedValueOnce({ matched: false, since: "s2" });
72+
73+
await expect(
74+
waitForMatrixQaObserverEvent({
75+
isExpectedInterruption: () => interrupted,
76+
observer: makeObserver(waitForOptionalRoomEvent),
77+
predicate: () => true,
78+
readInterruptionGeneration: () => 1,
79+
roomId: "!room:matrix.test",
80+
sleepImpl: vi.fn(async () => undefined),
81+
timeoutMs: 1_000,
82+
}),
83+
).resolves.toEqual({ matched: false, since: "s2" });
84+
expect(waitForOptionalRoomEvent).toHaveBeenCalledTimes(2);
85+
});
86+
87+
it("retries a poll that spans the complete interruption window", async () => {
88+
let interruptionGeneration = 0;
89+
const waitForOptionalRoomEvent = vi
90+
.fn<MatrixQaRoomObserver["waitForOptionalRoomEvent"]>()
91+
.mockImplementationOnce(async () => {
92+
// The poll began before restart and rejected only after begin/end both ran.
93+
interruptionGeneration = 2;
94+
throw new Error("pre-restart poll rejected after recovery");
95+
})
96+
.mockResolvedValueOnce({ matched: false, since: "s3" });
97+
98+
await expect(
99+
waitForMatrixQaObserverEvent({
100+
isExpectedInterruption: () => false,
101+
observer: makeObserver(waitForOptionalRoomEvent),
102+
predicate: () => true,
103+
readInterruptionGeneration: () => interruptionGeneration,
104+
roomId: "!room:matrix.test",
105+
sleepImpl: vi.fn(async () => undefined),
106+
timeoutMs: 1_000,
107+
}),
108+
).resolves.toEqual({ matched: false, since: "s3" });
109+
expect(waitForOptionalRoomEvent).toHaveBeenCalledTimes(2);
110+
});
111+
});

‎extensions/qa-lab/src/live-transports/matrix/adapter.runtime.ts‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Qa Lab plugin module implements Matrix live transport adapter behavior.
22
import { randomUUID } from "node:crypto";
33
import path from "node:path";
4+
import { setTimeout as sleep } from "node:timers/promises";
45
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
56
import { buildQaTarget } from "openclaw/plugin-sdk/qa-channel-protocol";
67
import type { QaRunnerCliRegistration } from "openclaw/plugin-sdk/qa-runner-runtime";
@@ -10,7 +11,11 @@ import { createMatrixQaClient, provisionMatrixQaRoom } from "./substrate/client.
1011
import { buildMatrixQaConfig } from "./substrate/config.js";
1112
import type { MatrixQaObservedEvent } from "./substrate/events.js";
1213
import { startMatrixQaHarness } from "./substrate/harness.runtime.js";
13-
import { createMatrixQaRoomObserver } from "./substrate/sync.js";
14+
import {
15+
createMatrixQaRoomObserver,
16+
type MatrixQaRoomEventWaitResult,
17+
type MatrixQaRoomObserver,
18+
} from "./substrate/sync.js";
1419
import {
1520
mergeMatrixQaTopologySpecs,
1621
resolveMatrixQaRoomObserverRole,
@@ -54,6 +59,44 @@ const MATRIX_SHARED_FLOW_TOPOLOGY = {
5459
],
5560
} satisfies MatrixQaTopologySpec;
5661

62+
const MATRIX_EXPECTED_INTERRUPTION_RETRY_MS = 250;
63+
64+
export async function waitForMatrixQaObserverEvent(params: {
65+
isExpectedInterruption: () => boolean;
66+
observer: MatrixQaRoomObserver;
67+
predicate: (event: MatrixQaObservedEvent) => boolean;
68+
readInterruptionGeneration: () => number;
69+
roomId: string;
70+
sleepImpl?: (ms: number) => Promise<unknown>;
71+
timeoutMs: number;
72+
}): Promise<MatrixQaRoomEventWaitResult> {
73+
const sleepImpl = params.sleepImpl ?? sleep;
74+
for (;;) {
75+
const expectedInterruptionAtStart = params.isExpectedInterruption();
76+
const interruptionGenerationAtStart = params.readInterruptionGeneration();
77+
try {
78+
return await params.observer.waitForOptionalRoomEvent({
79+
predicate: params.predicate,
80+
roomId: params.roomId,
81+
timeoutMs: params.timeoutMs,
82+
});
83+
} catch (error) {
84+
// The homeserver restart scenario owns this narrow recovery window. The
85+
// generation also catches a poll that spans the complete interruption
86+
// before rejecting. The observer clears its failed pollPromise in finally,
87+
// so the same cursor can safely retry.
88+
if (
89+
!expectedInterruptionAtStart &&
90+
!params.isExpectedInterruption() &&
91+
interruptionGenerationAtStart === params.readInterruptionGeneration()
92+
) {
93+
throw error;
94+
}
95+
await sleepImpl(MATRIX_EXPECTED_INTERRUPTION_RETRY_MS);
96+
}
97+
}
98+
}
99+
57100
function readMatrixQaScenarioTopology(scenarioId: string): MatrixQaTopologySpec | undefined {
58101
const value = readQaScenarioExecutionConfig(scenarioId)?.matrixTopology;
59102
if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -203,9 +246,17 @@ export async function createMatrixQaTransportAdapter(
203246
);
204247
const nativeEventIds = new Map<string, string>();
205248
const busMessageIds = new Map<string, string>();
249+
let expectedTransportInterruption = false;
250+
let transportInterruptionGeneration = 0;
206251
const scenarioEnvironment = createMatrixQaScenarioEnvironment({
207252
accountId,
208253
harness,
254+
onTransportInterruptionStateChange: (active) => {
255+
if (expectedTransportInterruption !== active) {
256+
transportInterruptionGeneration += 1;
257+
}
258+
expectedTransportInterruption = active;
259+
},
209260
observedEvents,
210261
provisioning,
211262
});
@@ -215,8 +266,11 @@ export async function createMatrixQaTransportAdapter(
215266
if (stopped) {
216267
return;
217268
}
218-
const observed = await observer.waitForOptionalRoomEvent({
269+
const observed = await waitForMatrixQaObserverEvent({
270+
isExpectedInterruption: () => expectedTransportInterruption,
271+
observer,
219272
predicate: (event) => event.sender === provisioning.sut.userId && Boolean(event.body),
273+
readInterruptionGeneration: () => transportInterruptionGeneration,
220274
roomId,
221275
timeoutMs: 1_000,
222276
});

‎extensions/qa-lab/src/live-transports/matrix/matrix-scenario-flows.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
readQaScenarioById,
55
readQaScenarioExecutionConfig,
66
} from "../../scenario-catalog.js";
7+
import { requireFlowScenario } from "../../scenario-catalog.test-utils.js";
78

89
const MATRIX_MENTION_GATE_PRIMARY_SCENARIOS = [
910
"matrix-allowbots-default-block",
@@ -16,6 +17,12 @@ const MATRIX_MENTION_GATE_PRIMARY_SCENARIOS = [
1617
"matrix-mention-metadata-spoof-block",
1718
] as const;
1819

20+
const MATRIX_ISOLATED_ALLOWBOTS_ADMISSION_SCENARIOS = [
21+
"matrix-allowbots-mentions-mentioned-room",
22+
"matrix-allowbots-room-override-enables-account-off",
23+
"matrix-allowbots-true-unmentioned-open-room",
24+
] as const;
25+
1926
function readModuleBinding(
2027
scenario: ReturnType<typeof readQaBootstrapScenarioCatalog>["scenarios"][number],
2128
) {
@@ -124,6 +131,65 @@ describe("Matrix QA Lab scenario flows", () => {
124131
});
125132
});
126133

134+
it("isolates scenarios that assert fresh thread and DM session routing", () => {
135+
const expectedReasons = {
136+
"dm-shared-session": "pristine per-user DM session routing",
137+
"thread-isolation": "fresh session boundary",
138+
"thread-reply-override": "must not inherit an existing room session",
139+
} as const;
140+
141+
for (const [scenarioId, reason] of Object.entries(expectedReasons)) {
142+
const execution = requireFlowScenario(readQaScenarioById(scenarioId)).execution;
143+
expect(execution.suiteIsolation, scenarioId).toBe("isolated");
144+
expect(execution.isolationReason, scenarioId).toContain(reason);
145+
}
146+
});
147+
148+
it("isolates the homeserver restart from the shared Matrix sync streams", () => {
149+
expect(readQaScenarioById("matrix-homeserver-restart-resume").execution).toMatchObject({
150+
kind: "flow",
151+
channel: "matrix",
152+
suiteIsolation: "isolated",
153+
isolationReason:
154+
"Restarts the disposable homeserver process and its active Matrix sync streams.",
155+
});
156+
});
157+
158+
it("isolates the DM thread override from session-scope bindings", () => {
159+
expect(readQaScenarioById("matrix-dm-thread-reply-override").execution).toMatchObject({
160+
kind: "flow",
161+
channel: "matrix",
162+
suiteIsolation: "isolated",
163+
isolationReason:
164+
"Asserts fresh DM native-thread routing after session-scope scenarios and cannot inherit their DM session binding.",
165+
});
166+
});
167+
168+
it("isolates channel and DM approval fan-out from shared routing state", () => {
169+
expect(readQaScenarioById("matrix-approval-channel-target-both").execution).toMatchObject({
170+
kind: "flow",
171+
channel: "matrix",
172+
suiteIsolation: "isolated",
173+
isolationReason:
174+
"Asserts fresh channel and DM approval fan-out and cannot inherit shared Matrix approval routing state.",
175+
});
176+
});
177+
178+
it("isolates only model-driven allowBots admission scenarios", () => {
179+
const isolatedScenarioIds = MATRIX_MENTION_GATE_PRIMARY_SCENARIOS.filter(
180+
(scenarioId) =>
181+
requireFlowScenario(readQaScenarioById(scenarioId)).execution.suiteIsolation === "isolated",
182+
);
183+
184+
expect(isolatedScenarioIds).toEqual(MATRIX_ISOLATED_ALLOWBOTS_ADMISSION_SCENARIOS);
185+
for (const scenarioId of MATRIX_ISOLATED_ALLOWBOTS_ADMISSION_SCENARIOS) {
186+
expect(
187+
requireFlowScenario(readQaScenarioById(scenarioId)).execution.isolationReason,
188+
scenarioId,
189+
).toContain("fresh model-driven configured-bot admission");
190+
}
191+
});
192+
127193
it("runs the allowlist scenario through its config-file reload owner", () => {
128194
const scenario = catalog.scenarios.find((entry) => entry.id === "matrix-allowlist-hot-reload");
129195
expect(scenario?.execution.kind).toBe("flow");

0 commit comments

Comments
 (0)