Skip to content

Commit 2a69e58

Browse files
committed
fix(logging): flush exit warnings synchronously
1 parent 5c10220 commit 2a69e58

2 files changed

Lines changed: 45 additions & 22 deletions

File tree

‎src/logging/logger-file-transport.test.ts‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Logger file transport tests cover async ordering, overflow, and exit durability.
2+
import { spawnSync } from "node:child_process";
23
import fs from "node:fs";
4+
import { fileURLToPath } from "node:url";
35
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
46
import { appendRegularFile } from "../infra/regular-file.js";
57
import { createSuiteLogPathTracker } from "./log-test-helpers.js";
@@ -169,17 +171,35 @@ describe("async logger file transport", () => {
169171
expect(fs.readFileSync(secondPath, "utf8")).toContain("second-file-recovery");
170172
});
171173

172-
it("warns when the synchronous exit drain drops a record", () => {
174+
it("writes a piped append warning before process exit", () => {
173175
const logPath = logPathTracker.nextPath();
174176
fs.mkdirSync(logPath);
175-
const stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
176-
setLoggerOverride({ level: "info", file: logPath });
177-
178-
getLogger().info("sync-dropped-record");
179-
testApi.drainFileLogQueueSyncForTests();
177+
const loaderPath = fileURLToPath(new URL("../../scripts/tsx.mjs", import.meta.url));
178+
const loggerUrl = new URL("./logger.ts", import.meta.url).href;
179+
const script = `
180+
import { getLogger, setLoggerOverride } from ${JSON.stringify(loggerUrl)};
181+
const writeStderr = process.stderr.write.bind(process.stderr);
182+
process.stderr.write = (chunk, ...args) => {
183+
setImmediate(() => writeStderr(chunk, ...args));
184+
return true;
185+
};
186+
setLoggerOverride({ level: "info", file: ${JSON.stringify(logPath)}, consoleStyle: "compact" });
187+
getLogger().info("exit-dropped-record");
188+
process.exit(0);
189+
`;
190+
191+
const result = spawnSync(
192+
process.execPath,
193+
["--import", loaderPath, "--input-type=module", "--eval", script],
194+
{
195+
encoding: "utf8",
196+
env: { ...process.env, VITEST: "false" },
197+
},
198+
);
180199

181-
const warnings = stderrSpy.mock.calls.map(([line]) => String(line));
182-
expect(warnings.filter((line) => line.includes(`file=${logPath}`))).toHaveLength(1);
200+
expect(result.error).toBeUndefined();
201+
expect(result.status).toBe(0);
202+
expect(result.stderr).toContain("log file append failed; record dropped");
183203
});
184204

185205
it("retries the warning after stderr rejects it", async () => {

‎src/logging/logger-file-transport.ts‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,29 +107,32 @@ function buildDroppedMarker(target: FileLogQueueEntry, count: number): FileLogQu
107107
};
108108
}
109109

110-
function writeFileTransportWarning(message: string): boolean {
110+
function writeFileTransportWarning(message: string, synchronous: boolean): boolean {
111111
try {
112112
const redactedMessage = redactSensitiveText(message);
113-
process.stderr.write(
114-
`${formatConsoleDiagnosticLine({ level: "warn", message: redactedMessage })}\n`,
115-
);
113+
const line = `${formatConsoleDiagnosticLine({ level: "warn", message: redactedMessage })}\n`;
114+
if (synchronous) {
115+
fs.writeSync(process.stderr.fd, line);
116+
} else {
117+
process.stderr.write(line);
118+
}
116119
return true;
117120
} catch {
118121
// Logging diagnostics must not stop the file queue.
119122
return false;
120123
}
121124
}
122125

123-
function warnAboutRotationFailure(entry: FileLogQueueEntry): void {
126+
function warnAboutRotationFailure(entry: FileLogQueueEntry, synchronous: boolean): void {
124127
if (warnedRotationFiles.get(entry.file) === entry.maxFileBytes) {
125128
return;
126129
}
127130
warnedRotationFiles.set(entry.file, entry.maxFileBytes);
128131
const message = `[openclaw] log file rotation failed; continuing writes file=${entry.file} maxFileBytes=${entry.maxFileBytes}`;
129-
writeFileTransportWarning(message);
132+
writeFileTransportWarning(message, synchronous);
130133
}
131134

132-
function warnAboutAppendFailure(entry: FileLogQueueEntry): void {
135+
function warnAboutAppendFailure(entry: FileLogQueueEntry, synchronous: boolean): void {
133136
if (warnedAppendFiles.has(entry.file)) {
134137
return;
135138
}
@@ -140,7 +143,7 @@ function warnAboutAppendFailure(entry: FileLogQueueEntry): void {
140143
const message = saturated
141144
? "[openclaw] log file append failure diagnostics saturated; suppressing new file targets"
142145
: `[openclaw] log file append failed; record dropped; check that the path is a writable regular file; file=${entry.file}`;
143-
if (!writeFileTransportWarning(message)) {
146+
if (!writeFileTransportWarning(message, synchronous)) {
144147
return;
145148
}
146149
if (saturated) {
@@ -169,7 +172,7 @@ function claimQueuedEntries(): FileLogQueueEntry[] {
169172
return entries;
170173
}
171174

172-
function rotateIfNeeded(entry: FileLogQueueEntry, cursor: FileCursor): void {
175+
function rotateIfNeeded(entry: FileLogQueueEntry, cursor: FileCursor, synchronous: boolean): void {
173176
const payloadBytes = Buffer.byteLength(entry.payload, "utf8");
174177
if (cursor.bytes === 0 || cursor.bytes + payloadBytes <= entry.maxFileBytes) {
175178
return;
@@ -178,7 +181,7 @@ function rotateIfNeeded(entry: FileLogQueueEntry, cursor: FileCursor): void {
178181
cursor.bytes = 0;
179182
warnedRotationFiles.delete(entry.file);
180183
} else {
181-
warnAboutRotationFailure(entry);
184+
warnAboutRotationFailure(entry, synchronous);
182185
}
183186
}
184187

@@ -201,7 +204,7 @@ async function writeEntries(entries: FileLogQueueEntry[], generation: number): P
201204
}
202205
cursors.set(entry.file, cursor);
203206
}
204-
rotateIfNeeded(entry, cursor);
207+
rotateIfNeeded(entry, cursor, false);
205208
const payloadBytes = Buffer.byteLength(entry.payload, "utf8");
206209
activeAppendInFlight = true;
207210
try {
@@ -210,7 +213,7 @@ async function writeEntries(entries: FileLogQueueEntry[], generation: number): P
210213
clearAppendFailure(entry);
211214
} catch {
212215
// Match the old best-effort transport: a failed append must not stop later records.
213-
warnAboutAppendFailure(entry);
216+
warnAboutAppendFailure(entry, false);
214217
} finally {
215218
activeAppendInFlight = false;
216219
}
@@ -232,15 +235,15 @@ function writeEntriesSync(entries: FileLogQueueEntry[]): void {
232235
cursor = { bytes: getCurrentLogFileBytesSync(entry.file) };
233236
cursors.set(entry.file, cursor);
234237
}
235-
rotateIfNeeded(entry, cursor);
238+
rotateIfNeeded(entry, cursor, true);
236239
const payloadBytes = Buffer.byteLength(entry.payload, "utf8");
237240
try {
238241
appendRegularFileSync({ filePath: entry.file, content: entry.payload });
239242
cursor.bytes += payloadBytes;
240243
clearAppendFailure(entry);
241244
} catch {
242245
// Match the old best-effort transport: a failed append must not stop later records.
243-
warnAboutAppendFailure(entry);
246+
warnAboutAppendFailure(entry, true);
244247
}
245248
index += 1;
246249
}

0 commit comments

Comments
 (0)