Skip to content

Commit 1cbbda1

Browse files
authored
perf(logging): flush file transport asynchronously off the request path (#114769)
* perf(logging): flush file transport asynchronously off the request path * fix(ci): record flushLogger surface growth and drain before log reads - +1 public export/callable budget with annotation: logger file-transport flush for graceful shutdown drains; regenerate SDK API baseline - three tests that read the log file right after logging now drain the async file transport first (flushLogger) instead of racing the flusher * test: drain async log transport before reading talk and request-trace logs * test: drain async log transport in CLI logger file tests * test: drop unused withTempDirSync import
1 parent 313daad commit 1cbbda1

19 files changed

Lines changed: 614 additions & 114 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ c5ff317bb7957d0870cb806e7989c1d48877e3bed583c173ce2f8e9cfe57ee36 module/status-
133133
1b5b9a4532db991fce807ba736b550de27aa5f9de2e1f508a8f4f09cae76ea29 module/telegram-account
134134
110944726884fca94f38c9c329b5950629438b9a719f4782c4beeade8bd67746 module/temp-path
135135
0e230313a7a27a915a7aa399c0afd94c4c3e10d485c7b513e757f41bfc362dbe module/text-chunking
136-
3077a10d6c535152c8d4b1c65450cab10b204130d81a19a34667b14b36d8338e module/text-runtime
136+
25b5366f5d0f5826f520f847e0ae701936e97302d5ac62042d65f5be0f6974d2 module/text-runtime
137137
a94c9ff59cc361b04f8731a47d722c4bc88cfabf942221369a8cb67bdcda7249 module/tool-plugin
138138
9d6ab352913a573b226e054e1dc8c6d088493aea9954950c65585923b5b6895a module/tool-send
139139
541df9dea799f25e83ea483d481ecebc5b91c016effab593c54d3efe3ee6517b module/web-media

‎scripts/plugin-sdk-surface-report.mjs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,8 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
185185
// +3: channel prompt-context entry/compat types and channel metadata builder.
186186
// +4: focused CLI root-option constants and parsers.
187187
// +6: model-picker action/capability and authoritative session-apply contracts.
188-
4737,
188+
// +1: logger file-transport flush for graceful shutdown drains.
189+
4738,
189190
env,
190191
),
191192
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -213,7 +214,8 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
213214
// +1: channel metadata builder.
214215
// +3: focused CLI root-option parsers.
215216
// +1: authoritative model-picker session-apply operation.
216-
2867,
217+
// +1: logger file-transport flush for graceful shutdown drains.
218+
2868,
217219
env,
218220
),
219221
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

‎src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type { AssistantMessage } from "openclaw/plugin-sdk/llm";
77
import { describe, expect, it, vi } from "vitest";
88
import { HEARTBEAT_RESPONSE_TOOL_NAME } from "../auto-reply/heartbeat-tool-response.js";
99
import * as agentEvents from "../infra/agent-events.js";
10-
import { resetLogger, setLoggerOverride } from "../logging/logger.js";
10+
import { flushLogger, resetLogger, setLoggerOverride } from "../logging/logger.js";
1111
import { parseLogLine } from "../logging/parse-log-line.js";
1212
import {
1313
THINKING_TAG_CASES,
@@ -170,6 +170,8 @@ describe("subscribeEmbeddedAgentSession", () => {
170170
result: { ok: true },
171171
});
172172

173+
// The file transport appends asynchronously; drain it before reading.
174+
await flushLogger();
173175
const logText = await fs.readFile(logFile, "utf8");
174176
const subsystems: string[] = [];
175177
for (const line of logText.trim().split(/\n+/)) {

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ const gatewayLog = {
133133
warn: vi.fn(),
134134
error: vi.fn(),
135135
};
136+
const flushLogger = vi.fn(async () => {});
136137

137138
vi.mock("../../infra/gateway-lock.js", () => ({
138139
acquireGatewayLock: (opts?: { port?: number }) => acquireGatewayLock(opts),
@@ -251,6 +252,10 @@ vi.mock("../../logging/subsystem.js", () => ({
251252
createSubsystemLogger: () => gatewayLog,
252253
}));
253254

255+
vi.mock("../../logging/logger.js", () => ({
256+
flushLogger: () => flushLogger(),
257+
}));
258+
254259
vi.mock("../../gateway/server-reload-handlers.js", () => ({
255260
abortPendingChannelReloads: () => abortPendingChannelReloads(),
256261
}));
@@ -474,6 +479,9 @@ describe("runGatewayLoop", () => {
474479
await withIsolatedSignals(async ({ captureSignal }) => {
475480
const { close, start, runtime, exited } = await createSignaledLoopHarness();
476481
const sigterm = captureSignal("SIGTERM");
482+
flushLogger.mockImplementationOnce(async () => {
483+
expect(runtime.exit).not.toHaveBeenCalled();
484+
});
477485

478486
sigterm();
479487

@@ -487,6 +495,30 @@ describe("runGatewayLoop", () => {
487495
requestHotReloadRecovery: requestGatewayRestartWithSignalAdmission,
488496
});
489497
expect(runtime.exit).toHaveBeenCalledWith(0);
498+
expect(flushLogger).toHaveBeenCalledOnce();
499+
});
500+
});
501+
502+
it("bounds the file-log flush before a graceful SIGTERM exit", async () => {
503+
vi.clearAllMocks();
504+
505+
await withIsolatedSignals(async ({ captureSignal }) => {
506+
const { runtime, exited } = await createSignaledLoopHarness();
507+
const sigterm = captureSignal("SIGTERM");
508+
flushLogger.mockReturnValueOnce(new Promise<void>(() => {}));
509+
vi.useFakeTimers();
510+
try {
511+
sigterm();
512+
await vi.advanceTimersByTimeAsync(4_000);
513+
514+
await expect(exited).resolves.toBe(0);
515+
expect(runtime.exit).toHaveBeenCalledWith(0);
516+
expect(gatewayLog.warn).toHaveBeenCalledWith(
517+
"log flush did not settle within 4000ms; continuing shutdown",
518+
);
519+
} finally {
520+
vi.useRealTimers();
521+
}
490522
});
491523
});
492524

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { formatErrorMessage } from "../../infra/errors.js";
1515
import type { GatewayBootLifecycleCompletion } from "../../infra/gateway-boot-lifecycle.js";
1616
import { acquireGatewayLock } from "../../infra/gateway-lock.js";
1717
import type { GatewayRestartEmitter } from "../../infra/restart.js";
18+
import { flushLogger } from "../../logging/logger.js";
1819
import { createSubsystemLogger } from "../../logging/subsystem.js";
1920
import type { RuntimeEnv } from "../../runtime.js";
2021
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
@@ -26,6 +27,7 @@ const RESTART_DRAIN_STILL_PENDING_WARN_MS = 30_000;
2627
const RESTART_CLOSE_REPLY_DRAIN_SHUTDOWN_RESERVE_MS = 10_000;
2728
const UPDATE_RESPAWN_HEALTH_TIMEOUT_MS = 10_000;
2829
const UPDATE_RESPAWN_HEALTH_POLL_MS = 200;
30+
const LOG_FLUSH_EXIT_TIMEOUT_MS = 4_000;
2931

3032
type GatewayRunSignalAction = "stop" | "restart";
3133
type RestartDrainTimeoutMs = number | undefined;
@@ -162,6 +164,25 @@ export async function runGatewayLoop(params: {
162164
cleanupSignals();
163165
params.runtime.exit(code);
164166
};
167+
const exitProcessAfterLogFlush = async (code: number) => {
168+
// Graceful signal/restart paths call process.exit(), which skips beforeExit.
169+
let flushTimer: ReturnType<typeof setTimeout> | undefined;
170+
const flushed = await Promise.race([
171+
flushLogger().then(() => true),
172+
new Promise<false>((resolve) => {
173+
flushTimer = setTimeout(() => resolve(false), LOG_FLUSH_EXIT_TIMEOUT_MS);
174+
}),
175+
]);
176+
if (flushTimer) {
177+
clearTimeout(flushTimer);
178+
}
179+
if (!flushed) {
180+
gatewayLog.warn(
181+
`log flush did not settle within ${LOG_FLUSH_EXIT_TIMEOUT_MS}ms; continuing shutdown`,
182+
);
183+
}
184+
exitProcess(code);
185+
};
165186
const completeForcedStop = (reason: string) => {
166187
params.completeBoot?.({ outcome: "forced_stop", reason });
167188
};
@@ -238,7 +259,7 @@ export async function runGatewayLoop(params: {
238259
gatewayLog.info(
239260
`restart mode: update process respawn (spawned pid ${respawn.pid ?? "unknown"})`,
240261
);
241-
exitProcess(0);
262+
await exitProcessAfterLogFlush(0);
242263
return;
243264
}
244265
gatewayLog.warn(
@@ -309,7 +330,7 @@ export async function runGatewayLoop(params: {
309330
return;
310331
}
311332
activeRestartRequest = null;
312-
exitProcess(0);
333+
await exitProcessAfterLogFlush(0);
313334
return;
314335
}
315336
if (respawn.mode === "failed") {
@@ -389,7 +410,7 @@ export async function runGatewayLoop(params: {
389410
return;
390411
}
391412
activeRestartRequest = null;
392-
exitProcess(0);
413+
await exitProcessAfterLogFlush(0);
393414
return;
394415
}
395416
if (respawn.mode === "failed") {
@@ -420,7 +441,7 @@ export async function runGatewayLoop(params: {
420441
const handleStopAfterServerClose = async () => {
421442
params.completeBoot?.({ outcome: "clean_stop", reason: "gateway.stop" });
422443
await releaseLockIfHeld();
423-
exitProcess(0);
444+
await exitProcessAfterLogFlush(0);
424445
};
425446

426447
const SUPERVISOR_STOP_TIMEOUT_MS = 30_000;

‎src/commands/onboard-guided.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { createWizardPrompter } from "../../test/helpers/wizard-prompter.js";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
55
import type { CallGatewayCliOptions } from "../gateway/call.js";
66
import { createSuiteLogPathTracker } from "../logging/log-test-helpers.js";
7-
import { resetLogger, setLoggerOverride } from "../logging/logger.js";
7+
import { flushLogger, resetLogger, setLoggerOverride } from "../logging/logger.js";
88
import { loggingState } from "../logging/state.js";
99
import { createSubsystemLogger } from "../logging/subsystem.js";
1010
import type { RuntimeEnv } from "../runtime.js";
@@ -545,6 +545,8 @@ describe("runGuidedOnboarding", () => {
545545

546546
transportLog.info("after activation");
547547
expect(consoleLog).toHaveBeenCalledOnce();
548+
// The file transport appends asynchronously; drain it before reading.
549+
await flushLogger();
548550
const fileLog = fs.readFileSync(file, "utf8");
549551
expect(fileLog).toContain("[model-fetch] response status=401");
550552
expect(fileLog).toContain("after activation");

‎src/gateway/server-http.request-trace.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
type DiagnosticTraceContext,
1515
} from "../infra/diagnostic-trace-context.js";
1616
import { getLogger, resetLogger, setLoggerOverride } from "../logging.js";
17+
import { flushLogger } from "../logging/logger.js";
1718
import type { ResolvedGatewayAuth } from "./auth.js";
1819
import { createGatewayHttpServer } from "./server-http.js";
1920
import { withTempConfig } from "./test-temp-config.js";
@@ -87,6 +88,8 @@ describe("gateway HTTP request trace scope", () => {
8788
expect(activeTraceInHandler?.spanId).toMatch(/^[0-9a-f]{16}$/);
8889
expect(events).toEqual([{ trace: activeTraceInHandler, type: "message.queued" }]);
8990

91+
// The file transport appends asynchronously; drain it before reading.
92+
await flushLogger();
9093
const traceRecord = fs
9194
.readFileSync(logPath, "utf8")
9295
.trim()

‎src/infra/device-bootstrap.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
33
import path from "node:path";
44
import { afterEach, describe, expect, it, vi } from "vitest";
55
import { resetLogger, setLoggerOverride } from "../logging.js";
6+
import { flushLogger } from "../logging/logger.js";
67
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
78
import { createTrackedTempDirs } from "../test-utils/tracked-temp-dirs.js";
89
import {
@@ -438,6 +439,8 @@ describe("device bootstrap tokens", () => {
438439
},
439440
});
440441

442+
// The file transport appends asynchronously; drain it before reading.
443+
await flushLogger();
441444
const content = await fs.readFile(logPath, "utf8");
442445
expect(content).toContain("bootstrap_token_scopes_stripped");
443446
expect(content).toContain("node.exec");

‎src/infra/regular-file.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import "./fs-safe-defaults.js";
44
// Regular-file IO helpers reject symlinks and non-file targets before reads or
55
// appends touch user-controlled paths.
66
export {
7+
appendRegularFile,
78
appendRegularFileSync,
89
readRegularFile,
910
readRegularFileSync,

‎src/logger.test.ts‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@ import {
1010
setLoggerOverride,
1111
stripRedundantSubsystemPrefixForConsole,
1212
} from "./logging.js";
13+
import { flushLogger } from "./logging/logger.js";
1314
import type { RuntimeEnv } from "./runtime.js";
14-
import { withTempDirSync } from "./test-helpers/temp-dir.js";
15+
import { withTempDir } from "./test-helpers/temp-dir.js";
1516

1617
describe("logger helpers", () => {
1718
afterEach(() => {
@@ -48,31 +49,35 @@ describe("logger helpers", () => {
4849
logVerboseLocal.mockRestore();
4950
});
5051

51-
it("writes to configured log file at configured level", () => {
52-
withTempDirSync({ prefix: "openclaw-log-test-" }, (dir) => {
52+
it("writes to configured log file at configured level", async () => {
53+
await withTempDir({ prefix: "openclaw-log-test-" }, async (dir) => {
5354
const logPath = path.join(dir, "openclaw.log");
5455
setLoggerOverride({ level: "info", file: logPath });
5556
fs.writeFileSync(logPath, "");
5657
logInfo("hello");
5758
logDebug("debug-only"); // may be filtered depending on level mapping
59+
// The file transport appends asynchronously; drain it before reading.
60+
await flushLogger();
5861
const content = fs.readFileSync(logPath, "utf-8");
5962
expect(content.length).toBeGreaterThan(0);
6063
});
6164
});
6265

63-
it("filters messages below configured level", () => {
64-
withTempDirSync({ prefix: "openclaw-log-test-" }, (dir) => {
66+
it("filters messages below configured level", async () => {
67+
await withTempDir({ prefix: "openclaw-log-test-" }, async (dir) => {
6568
const logPath = path.join(dir, "openclaw.log");
6669
setLoggerOverride({ level: "warn", file: logPath });
6770
logInfo("info-only");
6871
logWarn("warn-only");
72+
// The file transport appends asynchronously; drain it before reading.
73+
await flushLogger();
6974
const content = fs.readFileSync(logPath, "utf-8");
7075
expect(content).toContain("warn-only");
7176
});
7277
});
7378

74-
it("uses daily rolling log files and prunes old ones", () => {
75-
withTempDirSync({ prefix: "openclaw-log-test-" }, (dir) => {
79+
it("uses daily rolling log files and prunes old ones", async () => {
80+
await withTempDir({ prefix: "openclaw-log-test-" }, async (dir) => {
7681
resetLogger();
7782
const today = localDateString(new Date());
7883
const todayPath = path.join(dir, `openclaw-${today}.log`);
@@ -84,6 +89,8 @@ describe("logger helpers", () => {
8489
fs.utimesSync(oldPath, new Date(0), new Date(0));
8590

8691
logInfo("roll-me");
92+
// The file transport appends asynchronously; drain it before reading.
93+
await flushLogger();
8794

8895
expect(fs.existsSync(todayPath)).toBe(true);
8996
expect(fs.readFileSync(todayPath, "utf-8")).toContain("roll-me");

0 commit comments

Comments
 (0)