Skip to content

Commit 3bfe821

Browse files
authored
fix(gateway): unbreak cloud session creation — stale chat metadata, unbounded tunnel hangs, swallowed dispatch errors (#120926)
* fix(gateway): rebuild chat metadata when auth-profile snapshots change chat.metadata cached a prepared generation built before the runtime auth-profile store snapshot was published (empty-store fallback) and generationFactsMatch never compared auth state, so the Control UI showed "No models available" after a gateway restart until an unrelated config edit. Capture per-agent auth snapshot revisions in the generation facts, subscribe the metadata lifecycle to auth-store mutations, and run one awaited revision-aware catch-up refresh after listener registration so publications that precede registration are still observed. * fix(gateway): bound cloud worker tunnel startup and surface dispatch failure detail Live stress-testing the Control UI cloud flow found sessions.dispatch hanging unbounded (observed 12+ min) when the worker SSH tunnel could not connect: the runner's exited promise settled only on "close" (a spawn error never settled it), the reconnect loop swallowed every failure with no logging, the poisoned ready promise was re-handed to every later dispatch, and dispatch errors dropped the actionable reason recorded in worker_environments.last_error. - settle exited on the real "exit" event, wire the owner abort signal into spawn, bound stop()'s post-SIGKILL wait, and fail stop honestly when termination is unconfirmed instead of fabricating an exit - add a 60s per-attempt readiness deadline and log each failed connect attempt (bounded, redacted); keep an unconfirmed child tracked and wait for its real exit before retrying - add a 3-minute epoch-fenced startTunnel deadline with a typed, actionable error; detach its cleanup so the deadline holds - append the bounded recorded reason to the five dispatch-visible worker environment error messages (docs already promise these) - remote socket setup: drop "--" from chmod (BSD/macOS chmod treats it as a filename), which blocked every tunnel to a macOS worker host - workspace quiescence: tolerate EPERM without crashing the protocol while keeping unsignalable freeze targets counted as live so quiescence fails closed * test(gateway): type worker child kill mock
1 parent bb799ae commit 3bfe821

12 files changed

Lines changed: 482 additions & 30 deletions

‎src/agents/auth-profiles.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ export {
6363
ensureAuthProfileStoreWithoutExternalProfiles,
6464
getPreparedRuntimeAuthProfileStoreSnapshot,
6565
getRuntimeAuthProfileStoreSnapshot,
66+
getRuntimeAuthProfileStoreSnapshotRevision,
6667
hasAuthProfileStoreSourceForProvider,
6768
hasAnyAuthProfileStoreSource,
6869
hasLocalAuthProfileStoreSource,

‎src/agents/auth-profiles/store.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,6 +1326,8 @@ export function getPreparedRuntimeAuthProfileStoreSnapshot(
13261326
return getPreparedRuntimeAuthProfileStoreSnapshotImpl(agentDir, inheritedAuthDir);
13271327
}
13281328

1329+
export { getRuntimeAuthProfileStoreSnapshotRevision };
1330+
13291331
/** Replace runtime auth-profile snapshots, used by tests and prepared runtimes. */
13301332
export function replaceRuntimeAuthProfileStoreSnapshots(
13311333
entries: Array<{ agentDir?: string; store: AuthProfileStore }>,

‎src/gateway/server-chat-metadata-lifecycle.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,15 @@ export async function createGatewayChatMetadataLifecycle(params: {
4646
if (params.minimalTestGateway) {
4747
return undefined;
4848
}
49-
const [{ registerPreparedModelRuntimePublicationListener }, { registerSkillsChangeListener }] =
50-
await Promise.all([
51-
import("../agents/prepared-model-runtime.js"),
52-
import("../skills/runtime/refresh.js"),
53-
]);
49+
const [
50+
{ registerRuntimeAuthProfileStoreMutationListener },
51+
{ registerPreparedModelRuntimePublicationListener },
52+
{ registerSkillsChangeListener },
53+
] = await Promise.all([
54+
import("../agents/auth-profiles/runtime-snapshots.js"),
55+
import("../agents/prepared-model-runtime.js"),
56+
import("../skills/runtime/refresh.js"),
57+
]);
5458
const unregisterPreparedModelRuntimePublication =
5559
registerPreparedModelRuntimePublicationListener((event) => {
5660
if (event.phase === "invalidated") {
@@ -67,8 +71,14 @@ export async function createGatewayChatMetadataLifecycle(params: {
6771
runtime.invalidate();
6872
refreshLogged();
6973
});
74+
const unregisterRuntimeAuthProfileStoreMutation =
75+
registerRuntimeAuthProfileStoreMutationListener(() => {
76+
runtime.invalidate();
77+
refreshLogged();
78+
});
7079
return {
7180
stop: async () => {
81+
unregisterRuntimeAuthProfileStoreMutation();
7282
unregisterPreparedModelRuntimePublication();
7383
unregisterSkillsChange();
7484
},
@@ -85,6 +95,13 @@ export async function createGatewayChatMetadataLifecycle(params: {
8595
if (sidecar) {
8696
sidecars.push(sidecar);
8797
}
98+
// Auth/model snapshots published before listener registration are otherwise never
99+
// observed; one awaited catch-up refresh reconciles facts (revision-aware, no-op when
100+
// fresh) so post-attach reads cannot serve a pre-publication generation. Failures are
101+
// logged, not thrown: startup must not die on a metadata build error.
102+
await runtime.refresh().catch((error: unknown) => {
103+
params.log.warn(`chat metadata catch-up refresh failed: ${String(error)}`);
104+
});
88105
},
89106
read: runtime.read,
90107
readStartup: runtime.readStartup,

‎src/gateway/server-methods/chat-metadata-runtime.test.ts‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,22 @@ function createHarness(
3737
let owner = createOwner(config, "first");
3838
let skillsVersion = 1;
3939
let pluginRegistryVersion = 1;
40-
const authStore: AuthProfileStore = { version: 1, profiles: {} };
40+
let authStore: AuthProfileStore | undefined = { version: 1, profiles: {} };
41+
let authStoreRevision = 1;
4142
const getPreparedOwner = vi.fn(() => owner);
4243
const getPreparedAuthStore = vi.fn(() => authStore);
44+
const getAuthStoreRevision = vi.fn(() => authStoreRevision);
4345
const getSkillsVersion = vi.fn(() => skillsVersion);
4446
const getPluginRegistryVersion = vi.fn(() => pluginRegistryVersion);
4547
const buildCommands = vi.fn(async () => ({
4648
commands: [{ name: `command-${skillsVersion}-${pluginRegistryVersion}` }],
4749
}));
4850
const buildProjection = vi.fn(
49-
async ({ facts }: { facts: { owner: PreparedModelRuntimeSnapshot } }) => ({
51+
async ({
52+
facts,
53+
}: {
54+
facts: { authStore: AuthProfileStore; owner: PreparedModelRuntimeSnapshot };
55+
}) => ({
5056
modelCatalog: facts.owner.modelCatalog.entries,
5157
models: facts.owner.modelCatalog.entries,
5258
}),
@@ -67,6 +73,7 @@ function createHarness(
6773
deps: {
6874
getPreparedOwner,
6975
getPreparedAuthStore,
76+
getAuthStoreRevision,
7077
getSkillsVersion,
7178
getPluginRegistryVersion,
7279
buildCommands,
@@ -77,13 +84,20 @@ function createHarness(
7784
buildCommands,
7885
buildProjection,
7986
getPluginRegistryVersion,
87+
getAuthStoreRevision,
8088
getPreparedAuthStore,
8189
getPreparedOwner,
8290
getSkillsVersion,
8391
runtime,
8492
setConfig(next: OpenClawConfig) {
8593
config = next;
8694
},
95+
setAuthStore(next: AuthProfileStore | undefined) {
96+
authStore = next;
97+
},
98+
setAuthStoreRevision(next: number) {
99+
authStoreRevision = next;
100+
},
87101
setOwner(next: PreparedModelRuntimeSnapshot) {
88102
owner = next;
89103
},
@@ -130,6 +144,7 @@ describe("gateway chat metadata runtime", () => {
130144
await harness.runtime.refresh();
131145
harness.getPreparedOwner.mockClear();
132146
harness.getPreparedAuthStore.mockClear();
147+
harness.getAuthStoreRevision.mockClear();
133148
harness.getSkillsVersion.mockClear();
134149
harness.getPluginRegistryVersion.mockClear();
135150

@@ -139,6 +154,7 @@ describe("gateway chat metadata runtime", () => {
139154
expect(first).toBe(second);
140155
expect(harness.getPreparedOwner).not.toHaveBeenCalled();
141156
expect(harness.getPreparedAuthStore).not.toHaveBeenCalled();
157+
expect(harness.getAuthStoreRevision).not.toHaveBeenCalled();
142158
expect(harness.getSkillsVersion).not.toHaveBeenCalled();
143159
expect(harness.getPluginRegistryVersion).not.toHaveBeenCalled();
144160
});
@@ -148,6 +164,7 @@ describe("gateway chat metadata runtime", () => {
148164
await harness.runtime.refresh();
149165
harness.getPreparedOwner.mockClear();
150166
harness.getPreparedAuthStore.mockClear();
167+
harness.getAuthStoreRevision.mockClear();
151168
harness.getSkillsVersion.mockClear();
152169
harness.getPluginRegistryVersion.mockClear();
153170

@@ -169,6 +186,7 @@ describe("gateway chat metadata runtime", () => {
169186
expect(harness.buildProjection).toHaveBeenCalledTimes(1);
170187
expect(harness.getPreparedOwner).not.toHaveBeenCalled();
171188
expect(harness.getPreparedAuthStore).not.toHaveBeenCalled();
189+
expect(harness.getAuthStoreRevision).not.toHaveBeenCalled();
172190
expect(harness.getSkillsVersion).not.toHaveBeenCalled();
173191
expect(harness.getPluginRegistryVersion).not.toHaveBeenCalled();
174192
});
@@ -322,6 +340,50 @@ describe("gateway chat metadata runtime", () => {
322340
expect(harness.buildProjection).toHaveBeenCalledTimes(1);
323341
});
324342

343+
test("rebuilds after an auth store publishes a newer revision", async () => {
344+
const harness = createHarness();
345+
harness.setAuthStore(undefined);
346+
harness.buildProjection.mockImplementation(async ({ facts }) => ({
347+
modelCatalog: facts.owner.modelCatalog.entries,
348+
models: facts.owner.modelCatalog.entries.map((model) => ({
349+
...model,
350+
available: Object.keys(facts.authStore.profiles).length > 0,
351+
})),
352+
}));
353+
354+
await harness.runtime.refresh();
355+
await expect(harness.runtime.read({ agentId: "main" })).resolves.toMatchObject({
356+
models: [expect.objectContaining({ available: false })],
357+
});
358+
359+
harness.setAuthStore({
360+
version: 1,
361+
profiles: { "test:default": { type: "api_key", provider: "test" } },
362+
});
363+
harness.setAuthStoreRevision(2);
364+
await harness.runtime.refresh();
365+
366+
await expect(harness.runtime.read({ agentId: "main" })).resolves.toMatchObject({
367+
models: [expect.objectContaining({ available: true })],
368+
});
369+
expect(harness.buildProjection).toHaveBeenCalledTimes(2);
370+
});
371+
372+
test("retains a generation while auth store revisions are unchanged", async () => {
373+
const harness = createHarness();
374+
harness.getPreparedAuthStore.mockImplementation(() => ({ version: 1, profiles: {} }));
375+
await harness.runtime.refresh();
376+
const first = await harness.runtime.read({ agentId: "main" });
377+
378+
await harness.runtime.refresh();
379+
const second = await harness.runtime.read({ agentId: "main" });
380+
381+
expect(second).toBe(first);
382+
expect(harness.buildProjection).toHaveBeenCalledTimes(1);
383+
expect(harness.getAuthStoreRevision).toHaveBeenCalledWith("/tmp/first/agent");
384+
expect(harness.getAuthStoreRevision).toHaveBeenCalledWith(undefined);
385+
});
386+
325387
test("refreshes config, catalog-auth, skills, and plugin generations", async () => {
326388
const harness = createHarness();
327389
await harness.runtime.refresh();

‎src/gateway/server-methods/chat-metadata-runtime.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
} from "../../agents/agent-scope.js";
66
import {
77
getPreparedRuntimeAuthProfileStoreSnapshot,
8+
getRuntimeAuthProfileStoreSnapshotRevision,
89
type AuthProfileStore,
910
} from "../../agents/auth-profiles.js";
1011
import type { ModelCatalogEntry } from "../../agents/model-catalog.types.js";
@@ -40,6 +41,7 @@ type PreparedAgentFacts = {
4041
agentId: string;
4142
owner: PreparedModelRuntimeSnapshot;
4243
authStore: AuthProfileStore;
44+
authStoreRevision: string;
4345
skillsVersion: number;
4446
};
4547

@@ -85,6 +87,7 @@ type ChatMetadataRuntimeDeps = {
8587
agentDir?: string,
8688
inheritedAuthDir?: string,
8789
) => AuthProfileStore | undefined;
90+
getAuthStoreRevision: (agentDir?: string) => number;
8891
getSkillsVersion: (workspaceDir?: string) => number;
8992
getPluginRegistryVersion: () => number;
9093
buildCommands: (params: {
@@ -150,6 +153,7 @@ function captureGenerationFacts(deps: ChatMetadataRuntimeDeps): PreparedGenerati
150153
version: 1,
151154
profiles: {},
152155
},
156+
authStoreRevision: `${deps.getAuthStoreRevision(owner.agentDir)}:${deps.getAuthStoreRevision(owner.inheritedAuthDir)}`,
153157
skillsVersion: deps.getSkillsVersion(workspaceDir),
154158
};
155159
});
@@ -177,6 +181,7 @@ function generationFactsMatch(
177181
return (
178182
candidate?.agentId === agent.agentId &&
179183
candidate.owner === agent.owner &&
184+
candidate.authStoreRevision === agent.authStoreRevision &&
180185
candidate.skillsVersion === agent.skillsVersion
181186
);
182187
});
@@ -277,6 +282,7 @@ export function createGatewayChatMetadataRuntime(params: {
277282
getContext: params.getContext,
278283
getPreparedOwner: getPreparedModelCatalogOwnerSnapshot,
279284
getPreparedAuthStore: getPreparedRuntimeAuthProfileStoreSnapshot,
285+
getAuthStoreRevision: getRuntimeAuthProfileStoreSnapshotRevision,
280286
getSkillsVersion: getSkillsSnapshotVersion,
281287
getPluginRegistryVersion: getActivePluginRegistryVersion,
282288
buildCommands: defaultBuildCommands,

‎src/gateway/worker-environments/service.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1164,6 +1164,7 @@ describe("worker environment service", () => {
11641164
workerService.create("development", "request-preparation-failure"),
11651165
).rejects.toMatchObject({
11661166
code: "bootstrap_failure",
1167+
message: expect.stringContaining("npm install requires a released gateway package"),
11671168
} satisfies Partial<WorkerEnvironmentServiceError>);
11681169

11691170
expect(provision).not.toHaveBeenCalled();
@@ -1589,6 +1590,7 @@ describe("worker environment service", () => {
15891590

15901591
await expect(workerService.create("development", "request-malformed")).rejects.toMatchObject({
15911592
code: "provider_failure",
1593+
message: expect.stringContaining(error),
15921594
} satisfies Partial<WorkerEnvironmentServiceError>);
15931595
expect(store.list()[0]).toMatchObject({
15941596
state: "provisioning",
@@ -1621,6 +1623,7 @@ describe("worker environment service", () => {
16211623

16221624
await expect(workerService.create("development", "request-invalid")).rejects.toMatchObject({
16231625
code: "invalid_profile",
1626+
message: expect.stringContaining("region is required"),
16241627
} satisfies Partial<WorkerEnvironmentServiceError>);
16251628
const record = expectDefined(store.list()[0], "store.list()[0] test invariant");
16261629
expect(record).toMatchObject({ state: "failed", lastError: "region is required" });
@@ -2258,6 +2261,45 @@ describe("worker environment service", () => {
22582261
expect(order).toEqual(["tunnel-stop", "provider-destroy"]);
22592262
});
22602263

2264+
it("stops a poisoned tunnel start and returns a typed deadline error", async () => {
2265+
vi.useFakeTimers();
2266+
seedReady("worker-tunnel-timeout");
2267+
let signalStarted!: () => void;
2268+
const started = new Promise<void>((resolve) => {
2269+
signalStarted = resolve;
2270+
});
2271+
let rejectStart!: (error: Error) => void;
2272+
const pendingStart = new Promise<never>((_resolve, reject) => {
2273+
rejectStart = reject;
2274+
});
2275+
const tunnelManager = {
2276+
status: () => "connecting" as const,
2277+
start: vi.fn(() => {
2278+
signalStarted();
2279+
return pendingStart;
2280+
}),
2281+
stop: vi.fn(async () => {
2282+
rejectStart(new Error("tunnel stopped"));
2283+
}),
2284+
stopAll: vi.fn(async () => {}),
2285+
} as unknown as WorkerTunnelManager;
2286+
const workerService = createService(createProvider(), { tunnelManager });
2287+
2288+
const starting = workerService.startTunnel({
2289+
environmentId: "worker-tunnel-timeout",
2290+
ownerEpoch: 1,
2291+
});
2292+
const rejected = expect(starting).rejects.toMatchObject({
2293+
code: "provider_failure",
2294+
message: expect.stringContaining("did not connect within 3 minutes"),
2295+
} satisfies Partial<WorkerEnvironmentServiceError>);
2296+
await started;
2297+
await vi.advanceTimersByTimeAsync(3 * 60_000);
2298+
2299+
await rejected;
2300+
expect(tunnelManager.stop).toHaveBeenCalledWith("worker-tunnel-timeout", 1);
2301+
});
2302+
22612303
it("adopts an unpersisted provision result before destroying", async () => {
22622304
const intent = store.createIntent({
22632305
environmentId: "worker-pending-destroy",

‎src/gateway/worker-environments/service.ts‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ class WorkerEnvironmentServiceError extends Error {
9292
const serviceError = (code: WorkerEnvironmentServiceErrorCode, message: string) =>
9393
new WorkerEnvironmentServiceError(code, message);
9494
const ORPHANED_LEASE_ERROR = "Worker provider no longer recognizes the lease";
95+
// One poisoned SSH attempt must not hold every later dispatch on the same owner epoch forever.
96+
const TUNNEL_START_TIMEOUT_MS = 3 * 60_000;
9597

9698
function workerEnvironmentIdempotencyDigest(idempotencyKey: string): string {
9799
return createHash("sha256").update(idempotencyKey).digest("hex");
@@ -614,15 +616,16 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
614616
),
615617
);
616618
} catch (error) {
619+
const detail = boundedError(error);
617620
if (
618621
error instanceof WorkerProviderError ||
619622
(error instanceof WorkerEnvironmentServiceError && error.code === "invalid_profile")
620623
) {
621-
move(record, "failed", { lastError: boundedError(error) });
622-
throw serviceError("invalid_profile", "Worker provider rejected profile");
624+
move(record, "failed", { lastError: detail });
625+
throw serviceError("invalid_profile", `Worker provider rejected profile: ${detail}`);
623626
}
624627
saveError(record, error);
625-
throw serviceError("provider_failure", "Worker provider operation failed");
628+
throw serviceError("provider_failure", `Worker provider operation failed: ${detail}`);
626629
}
627630
// A timeout can happen after allocation; retain the same operation id for safe replay.
628631
const patch = { leaseId: lease.leaseId, sshEndpoint: lease.ssh };
@@ -654,8 +657,12 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
654657
// must happen first because the previous response may have been lost after allocation.
655658
installation = await prepareInstallation(record);
656659
} catch (error) {
657-
move(record, "failed", { lastError: boundedError(error) });
658-
throw serviceError("bootstrap_failure", "Worker installation preparation failed");
660+
const detail = boundedError(error);
661+
move(record, "failed", { lastError: detail });
662+
throw serviceError(
663+
"bootstrap_failure",
664+
`Worker installation preparation failed: ${detail}`,
665+
);
659666
}
660667
}
661668
const provisioning = record.state === "requested" ? move(record, "provisioning") : record;
@@ -1101,7 +1108,24 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
11011108
if (!startup) {
11021109
throw serviceError("invalid_state", "Worker tunnel failed to start");
11031110
}
1104-
return await startup;
1111+
const timeoutError = serviceError(
1112+
"provider_failure",
1113+
"Worker tunnel did not connect within 3 minutes; check worker SSH reachability and retry",
1114+
);
1115+
try {
1116+
return await withTimeout(startup, TUNNEL_START_TIMEOUT_MS, {
1117+
createError: () => timeoutError,
1118+
});
1119+
} catch (error) {
1120+
if (error !== timeoutError) {
1121+
throw error;
1122+
}
1123+
// Stop can itself block on an unkillable SSH child; detach it (rejection observed,
1124+
// entry stays manager-tracked) so the deadline error is returned on time. Epoch-fenced
1125+
// so a stale timed-out attempt can never tear down a newer owner's tunnel.
1126+
void tunnels.stop(request.environmentId, request.ownerEpoch).catch(() => undefined);
1127+
throw timeoutError;
1128+
}
11051129
};
11061130

11071131
const stopTunnel = async (environmentId: string, ownerEpoch?: number): Promise<void> => {

0 commit comments

Comments
 (0)