Skip to content

Commit 75aa830

Browse files
authored
fix: canonicalize single-flight promise caching (#118245)
* fix: canonicalize promise single-flight caches * fix: make TUI refresh outcome explicit * fix: satisfy single-flight lint contracts
1 parent b93fc7e commit 75aa830

24 files changed

Lines changed: 405 additions & 290 deletions

‎src/agents/workspace.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ const TRANSIENT_WORKSPACE_READ_ERRNOS = new Set([-11, -4]);
7272
const TRANSIENT_WORKSPACE_READ_MESSAGE = /Unknown system error -(?:11|4)\b/i;
7373

7474
const workspaceTemplateCache = new Map<string, Promise<string>>();
75+
// Git availability is process-stable; cache the probe result, including failure, until restart.
7576
let gitAvailabilityPromise: Promise<boolean> | null = null;
7677

7778
// File content cache keyed by stable file identity to avoid stale reads.

‎src/cli/deps.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,24 @@ describe("createDefaultDeps", () => {
106106
expect(runtimeFactories.discord).toHaveBeenCalledTimes(1);
107107
expect(sendFns.discord).toHaveBeenCalledTimes(2);
108108
});
109+
110+
it("retries a channel runtime after a transient load failure", async () => {
111+
runtimeFactories.telegram.mockImplementationOnce(() => {
112+
throw new Error("transient channel load");
113+
});
114+
const createDefaultDeps = await loadCreateDefaultDeps("module-retry");
115+
const deps = createDefaultDeps();
116+
const sendTelegram = deps.telegram as (...args: unknown[]) => Promise<unknown>;
117+
118+
await expect(sendTelegram("chat", "first", { verbose: false })).rejects.toThrow(
119+
"transient channel load",
120+
);
121+
await expect(sendTelegram("chat", "second", { verbose: false })).resolves.toEqual({
122+
messageId: "t1",
123+
chatId: "telegram:1",
124+
});
125+
126+
expect(runtimeFactories.telegram).toHaveBeenCalledTimes(2);
127+
expect(sendFns.telegram).toHaveBeenCalledOnce();
128+
});
109129
});

‎src/cli/deps.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Default CLI dependency surface with lazy outbound channel send adapters.
22
import { normalizeChannelId } from "../channels/registry.js";
3-
import { createLazyRuntimeSurface } from "../shared/lazy-runtime.js";
3+
import { getOrCreatePromise } from "../shared/lazy-promise.js";
44
import type { CliDeps } from "./deps.types.js";
55
import { CLI_OUTBOUND_SEND_FACTORY } from "./outbound-send-mapping.js";
66

@@ -60,14 +60,13 @@ function createLazySender(
6060
channelId: string,
6161
loader: () => Promise<RuntimeSendModule>,
6262
): (...args: unknown[]) => Promise<unknown> {
63-
const loadRuntimeSend = createLazyRuntimeSurface(loader, ({ runtimeSend }) => runtimeSend);
6463
return async (...args: unknown[]) => {
65-
let cached = senderCache.get(channelId);
66-
if (!cached) {
67-
cached = loadRuntimeSend();
68-
senderCache.set(channelId, cached);
69-
}
70-
const runtimeSend = await cached;
64+
const runtimeSend = await getOrCreatePromise(
65+
senderCache,
66+
channelId,
67+
async () => (await loader()).runtimeSend,
68+
{ cacheRejections: false },
69+
);
7170
return await runtimeSend.sendMessage(...args);
7271
};
7372
}

‎src/config/doc-baseline.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ const DEFAULT_CHANNEL_OUTPUT = "docs/.generated/config-baseline.channel.json";
105105
const DEFAULT_PLUGIN_OUTPUT = "docs/.generated/config-baseline.plugin.json";
106106
const DEFAULT_HASH_OUTPUT = "docs/.generated/config-baseline.sha256";
107107
const DEFAULT_COUNTS_OUTPUT = "docs/.generated/config-baseline.counts.json";
108+
// A successful schema snapshot is process-stable; failures clear below so tooling can retry.
108109
let cachedConfigDocBaselinePromise: Promise<ConfigDocBaseline> | null = null;
109110
const uiHintIndexCache = new WeakMap<
110111
ConfigSchemaResponse["uiHints"],

‎src/gateway/control-ui-static.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs";
33
import type { IncomingMessage, ServerResponse } from "node:http";
44
import path from "node:path";
55
import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
6+
import { getOrCreatePromise } from "../shared/lazy-promise.js";
67

78
const CONTROL_UI_IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
89
const CONTROL_UI_HTML_COMPRESSION_CACHE_MAX_ENTRIES = 4;
@@ -296,13 +297,12 @@ function cachedCompressedControlUiHtml(
296297
// Index HTML is process-stable for a configured root. Keep its few rewritten
297298
// variants single-flight and bounded so unauthenticated requests cannot fan
298299
// out zlib work; large hashed assets use build-time sidecars instead.
299-
const compression = compressControlUiBody(Buffer.from(body), encoding);
300-
controlUiHtmlCompressionCache.set(key, compression);
301-
void compression.catch(() => {
302-
if (controlUiHtmlCompressionCache.get(key) === compression) {
303-
controlUiHtmlCompressionCache.delete(key);
304-
}
305-
});
300+
const compression = getOrCreatePromise(
301+
controlUiHtmlCompressionCache,
302+
key,
303+
() => compressControlUiBody(Buffer.from(body), encoding),
304+
{ cacheRejections: false },
305+
);
306306
while (controlUiHtmlCompressionCache.size > CONTROL_UI_HTML_COMPRESSION_CACHE_MAX_ENTRIES) {
307307
const oldestKey = controlUiHtmlCompressionCache.keys().next().value;
308308
if (oldestKey === undefined) {

‎src/gateway/dashboard-session-title.ts‎

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { updateSessionEntry } from "../config/sessions/session-accessor.js";
99
import type { SessionEntry } from "../config/sessions/types.js";
1010
import type { OpenClawConfig } from "../config/types.openclaw.js";
1111
import { parseAgentSessionKey } from "../sessions/session-key-utils.js";
12+
import { getOrCreatePromise } from "../shared/lazy-promise.js";
1213

1314
type DashboardSessionTitleModelEntry = Pick<
1415
SessionEntry,
@@ -179,39 +180,39 @@ export async function maybeGenerateSessionTitle(params: {
179180
if (existing) {
180181
return { kind: "in-flight", settled: existing };
181182
}
182-
const request = (async () => {
183-
const displayName = await generateDashboardSessionTitle({
184-
cfg: params.cfg,
185-
agentId: params.agentId,
186-
entry: params.entry,
187-
userMessage: sourceText,
188-
});
189-
if (!displayName) {
190-
return false;
191-
}
192-
193-
let persisted = false;
194-
await updateSessionEntry(
195-
{
183+
const request = getOrCreatePromise(
184+
sessionTitleRequests,
185+
requestKey,
186+
async () => {
187+
const displayName = await generateDashboardSessionTitle({
188+
cfg: params.cfg,
196189
agentId: params.agentId,
197-
sessionKey: params.sessionKey,
198-
storePath: params.storePath,
199-
},
200-
(current) => {
201-
if (current.sessionId !== params.sessionId || hasExplicitSessionName(current)) {
202-
return null;
203-
}
204-
persisted = true;
205-
return { displayName };
206-
},
207-
{ requireWriteSuccess: true },
208-
);
209-
return persisted;
210-
})();
211-
sessionTitleRequests.set(requestKey, request);
212-
try {
213-
return (await request) ? { kind: "persisted" } : { kind: "skipped" };
214-
} finally {
215-
sessionTitleRequests.delete(requestKey);
216-
}
190+
entry: params.entry,
191+
userMessage: sourceText,
192+
});
193+
if (!displayName) {
194+
return false;
195+
}
196+
197+
let persisted = false;
198+
await updateSessionEntry(
199+
{
200+
agentId: params.agentId,
201+
sessionKey: params.sessionKey,
202+
storePath: params.storePath,
203+
},
204+
(current) => {
205+
if (current.sessionId !== params.sessionId || hasExplicitSessionName(current)) {
206+
return null;
207+
}
208+
persisted = true;
209+
return { displayName };
210+
},
211+
{ requireWriteSuccess: true },
212+
);
213+
return persisted;
214+
},
215+
{ evictOnSettled: true },
216+
);
217+
return (await request) ? { kind: "persisted" } : { kind: "skipped" };
217218
}

‎src/gateway/mcp-app-reconstruction.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "../agents/mcp-ui-resource.js";
1212
import type { OpenClawConfig } from "../config/types.openclaw.js";
1313
import { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
14+
import { getOrCreatePromise } from "../shared/lazy-promise.js";
1415
import { visitSessionMessagesAsync } from "./session-transcript-readers.js";
1516
import { loadSessionEntryReadOnly } from "./session-utils.js";
1617

@@ -345,15 +346,7 @@ export async function restoreMcpAppView(params: {
345346
}): Promise<ReconstructionResult | undefined> {
346347
const key = `${params.sessionKey}\0${params.viewId}`;
347348
const inFlight = getRestoreInFlight();
348-
const existing = inFlight.get(key);
349-
if (existing) {
350-
return await existing;
351-
}
352-
const pending = restoreMcpAppViewOnce(params).finally(() => {
353-
if (inFlight.get(key) === pending) {
354-
inFlight.delete(key);
355-
}
349+
return await getOrCreatePromise(inFlight, key, () => restoreMcpAppViewOnce(params), {
350+
evictOnSettled: true,
356351
});
357-
inFlight.set(key, pending);
358-
return await pending;
359352
}

‎src/gateway/node-pairing-ssh-verify.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import net from "node:net";
88
import os from "node:os";
99
import type { GatewayNodePairingConfig } from "../config/types.gateway.js";
1010
import { normalizeDevicePublicKeyBase64Url } from "../infra/device-identity.js";
11+
import { getOrCreatePromise } from "../shared/lazy-promise.js";
1112
import { isLoopbackAddress, isPrivateOrLoopbackAddress, isTrustedProxyAddress } from "./net.js";
1213
import {
1314
isEligibleFreshNodePairingRequest,
@@ -238,9 +239,6 @@ export function startNodePairingSshVerify(params: {
238239
return { ok: true, user: params.plan.policy.user, host: params.plan.host };
239240
})();
240241

241-
const tracked = done.finally(() => {
242-
inFlightByKey.delete(key);
243-
});
244-
inFlightByKey.set(key, tracked);
242+
const tracked = getOrCreatePromise(inFlightByKey, key, () => done, { evictOnSettled: true });
245243
return { done: tracked, alreadyInFlight: false };
246244
}

‎src/gateway/server-maintenance.ts‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { OpenClawConfig } from "../config/types.openclaw.js";
1111
import { sweepStaleRunContexts } from "../infra/agent-run-registry.js";
1212
import { pruneOrphanedDeliveryQueueMedia } from "../infra/outbound/delivery-queue-media-spool.js";
1313
import { cleanOldMedia } from "../media/store.js";
14+
import { createLazyPromiseLoader } from "../shared/lazy-promise.js";
1415
import { startSkillCuratorMaintenance } from "../skills/workshop/curator.js";
1516
import {
1617
abortTrackedChatRunById,
@@ -135,24 +136,21 @@ export function startGatewayMaintenanceTimers(params: {
135136
// the general media TTL sweep is disabled.
136137
const runDeliveryQueueMediaGc =
137138
params.runDeliveryQueueMediaGc ?? (() => pruneOrphanedDeliveryQueueMedia());
138-
let deliveryQueueMediaGcInFlight: Promise<void> | null = null;
139139
let deliveryQueueMediaGcStartedAtMs = 0;
140+
const deliveryQueueMediaGcLoader = createLazyPromiseLoader(async () => {
141+
try {
142+
await runDeliveryQueueMediaGc();
143+
} catch (error) {
144+
params.logHealth.error(`delivery queue media cleanup failed: ${formatError(error)}`);
145+
} finally {
146+
deliveryQueueMediaGcLoader.clear();
147+
}
148+
});
140149
const performDeliveryQueueMediaGc = () => {
141-
if (deliveryQueueMediaGcInFlight) {
142-
return deliveryQueueMediaGcInFlight;
150+
if (!deliveryQueueMediaGcLoader.peek()) {
151+
deliveryQueueMediaGcStartedAtMs = Date.now();
143152
}
144-
deliveryQueueMediaGcStartedAtMs = Date.now();
145-
deliveryQueueMediaGcInFlight = Promise.resolve()
146-
.then(async () => {
147-
await runDeliveryQueueMediaGc();
148-
})
149-
.catch((err: unknown) => {
150-
params.logHealth.error(`delivery queue media cleanup failed: ${formatError(err)}`);
151-
})
152-
.finally(() => {
153-
deliveryQueueMediaGcInFlight = null;
154-
});
155-
return deliveryQueueMediaGcInFlight;
153+
return deliveryQueueMediaGcLoader.load();
156154
};
157155
void performDeliveryQueueMediaGc();
158156

‎src/gateway/server-methods/skills.ts‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { redactConfigObject } from "../../config/redact-snapshot.js";
3030
import { fetchClawHubSkillDetail } from "../../infra/clawhub.js";
3131
import { formatErrorMessage } from "../../infra/errors.js";
3232
import { normalizeAgentId } from "../../routing/session-key.js";
33+
import { getOrCreatePromise } from "../../shared/lazy-promise.js";
3334
import { updateSkillConfigEntry } from "../../skills/config/mutations.js";
3435
import { collectSkillBins } from "../../skills/discovery/bins.js";
3536
import { buildWorkspaceSkillStatus } from "../../skills/discovery/status.js";
@@ -91,20 +92,9 @@ function installClawHubSkillDeduped(params: ClawHubInstallParams): Promise<ClawH
9192
params.force ?? false,
9293
params.acknowledgeClawHubRisk ?? false,
9394
]);
94-
const active = clawHubInstallsInFlight.get(key);
95-
if (active) {
96-
return active;
97-
}
98-
const install = installSkillFromClawHub(params);
99-
clawHubInstallsInFlight.set(key, install);
100-
void install
101-
.finally(() => {
102-
if (clawHubInstallsInFlight.get(key) === install) {
103-
clawHubInstallsInFlight.delete(key);
104-
}
105-
})
106-
.catch(() => undefined);
107-
return install;
95+
return getOrCreatePromise(clawHubInstallsInFlight, key, () => installSkillFromClawHub(params), {
96+
evictOnSettled: true,
97+
});
10898
}
10999

110100
function buildRemoteAwareWorkspaceSkillStatus(resolved: ResolvedSkillsWorkspace) {

0 commit comments

Comments
 (0)