Skip to content

Commit 1a946db

Browse files
authored
test(qa): cover repeated live restart recovery (#105126)
1 parent 1c9a2f6 commit 1a946db

5 files changed

Lines changed: 287 additions & 4 deletions

File tree

‎extensions/qa-lab/src/scenario-catalog.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ describe("qa scenario catalog", () => {
431431
"webchat-direct-reply-routing",
432432
"long-context-progress-watchdog",
433433
"gateway-restart-inflight-run",
434+
"gateway-restart-multi-live",
434435
"streaming-final-integrity",
435436
];
436437

@@ -448,6 +449,9 @@ describe("qa scenario catalog", () => {
448449
);
449450
const gatewayRestartFlow = readQaScenarioById("gateway-restart-inflight-run").execution.flow;
450451
const gatewayRestartContract = JSON.stringify(gatewayRestartFlow);
452+
expect(
453+
JSON.stringify(readQaScenarioById("gateway-restart-inflight-run").gatewayConfigPatch),
454+
).toContain('"alsoAllow":["qa_restart_wait","qa_restart_unsafe_probe"]');
451455
expect(gatewayRestartContract).toContain("plannedToolName === 'wait'");
452456
expect(gatewayRestartContract).toContain("lastAssistantToolNames?.includes('wait')");
453457
expect(gatewayRestartContract).toContain('"taskTracking":false');
@@ -457,6 +461,22 @@ describe("qa scenario catalog", () => {
457461
expect(gatewayRestartContract).toContain("dispatching restart-safe recovery");
458462
expect(gatewayRestartContract).toContain("[OpenClaw heartbeat poll]");
459463
expect(gatewayRestartContract).toContain("liveTurnTimeoutMs(env, 180000)");
464+
expect(gatewayRestartContract).toContain("dmScope: 'per-channel-peer'");
465+
const liveMultiRestart = readQaScenarioById("gateway-restart-multi-live");
466+
const liveMultiRestartContract = JSON.stringify(liveMultiRestart.execution.flow);
467+
expect(JSON.stringify(liveMultiRestart.gatewayConfigPatch)).toContain(
468+
'"alsoAllow":["qa_restart_wait","qa_restart_unsafe_probe"]',
469+
);
470+
expect(liveMultiRestartContract).toContain("assistantToolCallCounts.exec");
471+
expect(liveMultiRestartContract).toContain("checkpoint");
472+
expect(liveMultiRestartContract).toContain("restarts=3");
473+
expect(liveMultiRestartContract).toContain("dmScope: 'per-channel-peer'");
474+
expect(liveMultiRestartContract).toContain("dispatching restart-safe recovery");
475+
expect(readQaScenarioExecutionConfig("gateway-restart-multi-live")).toMatchObject({
476+
requiredProviderMode: "live-frontier",
477+
requiredProvider: "openai",
478+
requiredModel: "gpt-5.4",
479+
});
460480
const longContextFlow = JSON.stringify(
461481
readQaScenarioById("long-context-progress-watchdog").execution.flow,
462482
);

‎extensions/qa-lab/src/suite-runtime-agent-session.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ describe("qa suite runtime agent session helpers", () => {
209209
sessionKey,
210210
),
211211
).resolves.toEqual({
212+
assistantToolCallCounts: { message: 1 },
212213
finalText: "",
213214
hasDirectReplySelfMessage: false,
214215
lastAssistantContentTypes: ["tool_use"],
@@ -232,6 +233,7 @@ describe("qa suite runtime agent session helpers", () => {
232233
"agent:qa:webchat",
233234
),
234235
).resolves.toEqual({
236+
assistantToolCallCounts: { message: 1 },
235237
finalText: "Sent.",
236238
hasDirectReplySelfMessage: true,
237239
lastMessageRole: "assistant",
@@ -283,6 +285,7 @@ describe("qa suite runtime agent session helpers", () => {
283285
"agent:qa:stream",
284286
),
285287
).resolves.toEqual({
288+
assistantToolCallCounts: { message: 1 },
286289
finalText: "Sent.",
287290
hasDirectReplySelfMessage: true,
288291
lastAssistantErrorMessage: "Request was aborted",

‎extensions/qa-lab/src/suite-runtime-agent-session.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ function resolveSessionStoreLockRetryDelaysMs(): readonly number[] {
3434
}
3535

3636
type QaSessionTranscriptSummary = {
37+
assistantToolCallCounts: Record<string, number>;
3738
finalText: string;
3839
hasDirectReplySelfMessage: boolean;
3940
lastAssistantContentTypes?: string[];
@@ -81,6 +82,7 @@ function summarizeSessionTranscriptEvents(
8182
sessionKey: string,
8283
): QaSessionTranscriptSummary {
8384
const scanner = createDirectReplyTranscriptSentinelScanner();
85+
const assistantToolCallCounts: Record<string, number> = {};
8486
let finalText = "";
8587
let lastAssistantContentTypes: string[] = [];
8688
let lastAssistantErrorMessage: string | undefined;
@@ -110,6 +112,9 @@ function summarizeSessionTranscriptEvents(
110112
lastAssistantErrorMessage = readNonEmptyString(message.errorMessage);
111113
lastAssistantStopReason = readNonEmptyString(message.stopReason);
112114
lastAssistantToolNames = readAssistantToolNames(message);
115+
for (const toolName of lastAssistantToolNames) {
116+
assistantToolCallCounts[toolName] = (assistantToolCallCounts[toolName] ?? 0) + 1;
117+
}
113118
scanner.recordMessage(message);
114119
}
115120

@@ -118,6 +123,7 @@ function summarizeSessionTranscriptEvents(
118123
}
119124

120125
return {
126+
assistantToolCallCounts,
121127
finalText,
122128
hasDirectReplySelfMessage: scanner.findings().length > 0,
123129
...(lastAssistantContentTypes.length > 0 ? { lastAssistantContentTypes } : {}),

‎qa/scenarios/runtime/gateway-restart-inflight-run.yaml‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ scenario:
1212
- runtime.delivery
1313
gatewayConfigPatch:
1414
tools:
15-
allow:
16-
- exec
17-
- wait
15+
alsoAllow:
1816
- qa_restart_wait
1917
- qa_restart_unsafe_probe
2018
codeMode:
@@ -66,7 +64,7 @@ flow:
6664
expr: "`restart-inflight-${randomUUID().slice(0, 8)}`"
6765
- set: sessionKey
6866
value:
69-
expr: "buildAgentSessionKey({ agentId: 'qa', channel: 'qa-channel', accountId: transport.accountId, peer: { kind: 'direct', id: conversationId }, dmScope: env.cfg.session?.dmScope, identityLinks: env.cfg.session?.identityLinks })"
67+
expr: "buildAgentSessionKey({ agentId: 'qa', channel: 'qa-channel', accountId: transport.accountId, peer: { kind: 'direct', id: conversationId }, dmScope: 'per-channel-peer', identityLinks: env.cfg.session?.identityLinks })"
7068
- set: restartPatch
7169
value:
7270
expr: "({ gateway: { controlUi: { allowedOrigins: [`http://127.0.0.1:${64000 + Math.floor(Math.random() * 999)}`] } }, tools: { codeMode: { enabled: false } } })"
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
title: Live OpenAI multi-restart task recovery
2+
3+
scenario:
4+
id: gateway-restart-multi-live
5+
surface: runtime
6+
runtimeParityTier: live-only
7+
coverage:
8+
primary:
9+
- runtime.restart-recovery
10+
secondary:
11+
- runtime.gateway-restart
12+
- runtime.delivery
13+
gatewayRuntime:
14+
preserveDebugArtifacts: true
15+
gatewayConfigPatch:
16+
tools:
17+
alsoAllow:
18+
- qa_restart_wait
19+
- qa_restart_unsafe_probe
20+
codeMode:
21+
enabled: true
22+
timeoutMs: 60000
23+
objective: Verify one substantive live OpenAI task automatically resumes through three Gateway replacements and delivers exactly once.
24+
successCriteria:
25+
- The live model reaches three distinct replay-safe Code Mode wait checkpoints in one user turn.
26+
- The Gateway child and qa-channel recover after every replacement without a user follow-up.
27+
- Restart-safe policy remains active, the unsafe probe stays unavailable, and the completed audit is delivered exactly once.
28+
docsRefs:
29+
- docs/reference/code-mode.md
30+
- docs/channels/qa-channel.md
31+
codeRefs:
32+
- extensions/qa-lab/src/suite-runtime-agent-session.ts
33+
- extensions/qa-lab/src/suite-runtime-gateway.ts
34+
- src/agents/main-session-restart-recovery.ts
35+
execution:
36+
kind: flow
37+
summary: Run a fixture-backed audit with GPT-5.4 while replacing the Gateway child three times at durable wait checkpoints.
38+
suiteIsolation: isolated
39+
isolationReason: Replaces the Gateway child three times and inspects one persistent in-flight session.
40+
config:
41+
requiredProviderMode: live-frontier
42+
requiredProvider: openai
43+
requiredModel: gpt-5.4
44+
finalMarker: LIVE-MULTI-RESTART-OK
45+
restartNoticeNeedle: "couldn't safely resume"
46+
prompt: |-
47+
Perform a restart-resilience release audit. This is one task; do not ask me to follow up.
48+
49+
First, use OpenClaw Code Mode to create three sequential restart checkpoints. Count prior assistant `exec` calls in this transcript whose code contains `qa_restart_wait`. If the count is below three, make exactly the next checkpoint with an `exec` call whose `restartSafe` flag is true. Its JavaScript must search for `qa_restart_wait`, call the single match with `{}`, and return `CHECKPOINT-N`, where N is the next count. If `exec` reports waiting, call `wait` with its run id. A gateway restart will interrupt each checkpoint. On the recovery turn, count the transcript again and continue with the next checkpoint; do not repeat a completed checkpoint.
50+
51+
After three checkpoint calls are visible, use restart-safe Code Mode to search for `qa_restart_unsafe_probe` and record whether it is visible. Do not call it. Then read all five files under `restart-audit/` and calculate:
52+
- component total from services, workers, and jobs
53+
- risk total from low, medium, and high
54+
- deployment total across all regions
55+
- control checksum from approvals, rollbacks, and drills
56+
- the release recommendation from the evidence
57+
58+
Finish with exactly one concise report containing these exact lines:
59+
components=16
60+
risks=6
61+
deployments=27
62+
controls=21
63+
unsafeVisible=false
64+
recommendation=GO
65+
LIVE-MULTI-RESTART-OK
66+
67+
flow:
68+
steps:
69+
- name: verifies live OpenAI lane
70+
actions:
71+
- assert:
72+
expr: "env.providerMode === config.requiredProviderMode"
73+
message: scenario requires live-frontier provider mode
74+
- set: selected
75+
value:
76+
expr: splitModelRef(env.primaryModel)
77+
- assert:
78+
expr: "selected?.provider === config.requiredProvider && selected?.model === config.requiredModel"
79+
message:
80+
expr: "`expected ${config.requiredProvider}/${config.requiredModel}, got ${env.primaryModel}`"
81+
- assert:
82+
expr: "Boolean(env.gateway.runtimeEnv.OPENAI_API_KEY?.trim() || env.gateway.runtimeEnv.OPENCLAW_LIVE_OPENAI_KEY?.trim())"
83+
message: live OpenAI API key did not reach the Gateway child
84+
detailsExpr: "`provider=${selected?.provider} model=${selected?.model} auth=env-api-key`"
85+
86+
- name: resumes one substantive task through three restarts
87+
actions:
88+
- call: fs.mkdir
89+
args:
90+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit')"
91+
- recursive: true
92+
- call: fs.writeFile
93+
args:
94+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit', 'components.md')"
95+
- "services=4\nworkers=7\njobs=5\n"
96+
- utf8
97+
- call: fs.writeFile
98+
args:
99+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit', 'risks.md')"
100+
- "low=3\nmedium=2\nhigh=1\n"
101+
- utf8
102+
- call: fs.writeFile
103+
args:
104+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit', 'deployments.md')"
105+
- "us-west-2=12\nus-east-1=9\neu-west-1=6\n"
106+
- utf8
107+
- call: fs.writeFile
108+
args:
109+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit', 'controls.md')"
110+
- "approvals=8\nrollbacks=7\ndrills=6\n"
111+
- utf8
112+
- call: fs.writeFile
113+
args:
114+
- expr: "path.join(env.gateway.workspaceDir, 'restart-audit', 'recommendation.md')"
115+
- "Release only when components=16, risks=6, deployments=27, controls=21, and the unsafe probe is unavailable. Matching evidence means GO.\n"
116+
- utf8
117+
- call: waitForGatewayHealthy
118+
args:
119+
- ref: env
120+
- 180000
121+
- call: waitForQaChannelReady
122+
args:
123+
- ref: env
124+
- 180000
125+
- call: reset
126+
- set: startIndex
127+
value:
128+
expr: state.getSnapshot().messages.length
129+
- set: gatewayLogCursor
130+
value:
131+
expr: markGatewayLogCursor()
132+
- set: conversationId
133+
value:
134+
expr: "`restart-multi-live-${randomUUID().slice(0, 8)}`"
135+
- set: sessionKey
136+
value:
137+
expr: "buildAgentSessionKey({ agentId: 'qa', channel: 'qa-channel', accountId: transport.accountId, peer: { kind: 'direct', id: conversationId }, dmScope: 'per-channel-peer', identityLinks: env.cfg.session?.identityLinks })"
138+
- call: startAgentRun
139+
saveAs: started
140+
args:
141+
- ref: env
142+
- sessionKey:
143+
ref: sessionKey
144+
message:
145+
expr: config.prompt
146+
to:
147+
expr: "`dm:${conversationId}`"
148+
taskTracking: false
149+
timeoutMs:
150+
expr: liveTurnTimeoutMs(env, 180000)
151+
- forEach:
152+
items:
153+
- 1
154+
- 2
155+
- 3
156+
item: checkpoint
157+
actions:
158+
- call: waitForCondition
159+
saveAs: checkpointTranscript
160+
args:
161+
- lambda:
162+
async: true
163+
expr: "readSessionTranscriptSummary(env, sessionKey).then((summary) => (summary.assistantToolCallCounts.exec ?? 0) >= checkpoint && (summary.assistantToolCallCounts.wait ?? 0) >= checkpoint ? summary : undefined).catch(() => undefined)"
164+
- expr: liveTurnTimeoutMs(env, 180000)
165+
- 50
166+
- call: restartGatewayWithConfigPatch
167+
args:
168+
- env:
169+
ref: env
170+
patch:
171+
gateway:
172+
controlUi:
173+
allowedOrigins:
174+
- expr: "`http://127.0.0.1:${64000 + checkpoint}`"
175+
- call: waitForGatewayHealthy
176+
args:
177+
- ref: env
178+
- 180000
179+
- call: waitForQaChannelReady
180+
args:
181+
- ref: env
182+
- 180000
183+
- call: waitForCondition
184+
args:
185+
- lambda:
186+
expr: "readGatewayLogs().slice(gatewayLogCursor).split('dispatching restart-safe recovery').length - 1 >= checkpoint ? true : undefined"
187+
- expr: liveTurnTimeoutMs(env, 120000)
188+
- 50
189+
- call: waitForOutboundMessage
190+
saveAs: outbound
191+
args:
192+
- ref: state
193+
- lambda:
194+
params: [candidate]
195+
expr: "candidate.conversation.id === conversationId && candidate.text.includes(config.finalMarker)"
196+
- expr: liveTurnTimeoutMs(env, 300000)
197+
- sinceIndex:
198+
ref: startIndex
199+
- call: sleep
200+
args:
201+
- 3000
202+
- call: readSessionTranscriptSummary
203+
saveAs: finalTranscript
204+
args:
205+
- ref: env
206+
- ref: sessionKey
207+
- set: finalMatches
208+
value:
209+
expr: "state.getSnapshot().messages.slice(startIndex).filter((candidate) => candidate.direction === 'outbound' && candidate.conversation.id === conversationId && candidate.text.includes(config.finalMarker))"
210+
- set: restartNotices
211+
value:
212+
expr: "state.getSnapshot().messages.slice(startIndex).filter((candidate) => candidate.direction === 'outbound' && candidate.conversation.id === conversationId && candidate.text.includes(config.restartNoticeNeedle))"
213+
- assert:
214+
expr: "finalMatches.length === 1"
215+
message:
216+
expr: "`expected one recovered final delivery, got ${finalMatches.length}; outbound=${recentOutboundSummary(state)}`"
217+
- assert:
218+
expr: "restartNotices.length === 0"
219+
message:
220+
expr: "`automatic recovery emitted ${restartNotices.length} resend notice(s); outbound=${recentOutboundSummary(state)}`"
221+
- assert:
222+
expr: "(finalTranscript.assistantToolCallCounts.exec ?? 0) >= 4 && (finalTranscript.assistantToolCallCounts.wait ?? 0) >= 3"
223+
message:
224+
expr: "`expected three distinct checkpoint execs plus the audit exec; transcript=${JSON.stringify(finalTranscript)}`"
225+
- assert:
226+
expr: "['components=16', 'risks=6', 'deployments=27', 'controls=21', 'unsafeVisible=false', 'recommendation=GO'].every((needle) => outbound.text.includes(needle))"
227+
message:
228+
expr: "`substantive audit output was incomplete: ${outbound.text}`"
229+
- assert:
230+
expr: "finalTranscript.lastAssistantStopReason !== 'error' && finalTranscript.lastAssistantStopReason !== 'aborted'"
231+
message:
232+
expr: "`restart recovery left a terminal artifact: ${JSON.stringify(finalTranscript)}`"
233+
- set: recoveryLogs
234+
value:
235+
expr: readGatewayLogs().slice(gatewayLogCursor)
236+
- set: recoveryDispatches
237+
value:
238+
expr: "recoveryLogs.split('dispatching restart-safe recovery').length - 1"
239+
- set: retainedPolicies
240+
value:
241+
expr: "recoveryLogs.split('restart-safe recovery tool policy retained').length - 1"
242+
- assert:
243+
expr: "recoveryDispatches >= 3 && retainedPolicies >= 3"
244+
message:
245+
expr: "`expected restart-safe policy on all recoveries; dispatches=${recoveryDispatches} retained=${retainedPolicies}`"
246+
- assert:
247+
expr: "!recoveryLogs.includes('unsafe-probe-executed')"
248+
message: non-replay-safe QA probe executed during recovery
249+
- assert:
250+
expr: "!recoveryLogs.split(String.fromCharCode(10)).some((line) => line.includes('tool policy removed') && line.includes('qa_restart_wait'))"
251+
message: replay-safe QA checkpoint tool was removed before Code Mode catalog construction
252+
- call: assertNoGatewayLogSentinels
253+
args:
254+
- sinceIndex:
255+
ref: gatewayLogCursor
256+
detailsExpr: "`runId=${started.runId} session=${sessionKey} restarts=3 execs=${finalTranscript.assistantToolCallCounts.exec ?? 0} waits=${finalTranscript.assistantToolCallCounts.wait ?? 0} recoveryDispatches=${recoveryDispatches} retainedPolicies=${retainedPolicies} finalDeliveries=${finalMatches.length} resendNotices=${restartNotices.length}\n${outbound.text}`"

0 commit comments

Comments
 (0)