Skip to content

Commit d634520

Browse files
committed
fix(agents): prove raw stream rejection containment
Punchcard-Session: brisk-cedar-brook-w3
1 parent 17206b3 commit d634520

2 files changed

Lines changed: 66 additions & 62 deletions

File tree

Lines changed: 64 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,86 @@
1-
/**
2-
* Tests for raw-stream write failure handling.
3-
* Verifies that both synchronous throws and async rejections are contained
4-
* without crashing the process.
5-
*/
61
import fs from "node:fs";
7-
import path from "node:path";
8-
import { randomUUID } from "node:crypto";
92
import os from "node:os";
10-
import { beforeEach, describe, expect, it, vi } from "vitest";
11-
12-
// Mock appendRegularFile before importing the module under test so we
13-
// control whether it resolves, rejects, or throws synchronously.
14-
const mockAppendRegularFile = vi.fn<(...args: unknown[]) => Promise<void>>();
15-
16-
vi.mock("../infra/fs-safe.js", () => ({
17-
appendRegularFile: (...args: unknown[]) => mockAppendRegularFile(...args),
18-
}));
19-
20-
// Reload the module with our mock in place.
21-
const { appendRawStream } = await import(
22-
"./embedded-agent-subscribe.raw-stream.js"
23-
);
3+
import path from "node:path";
4+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { appendRawStream } from "./embedded-agent-subscribe.raw-stream.js";
246

257
describe("appendRawStream", () => {
268
let tmpDir: string;
9+
const unhandledRejections: unknown[] = [];
10+
const onUnhandledRejection = (reason: unknown) => {
11+
unhandledRejections.push(reason);
12+
};
13+
14+
beforeAll(() => {
15+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-raw-stream-test-"));
16+
});
2717

2818
beforeEach(() => {
2919
vi.stubEnv("OPENCLAW_RAW_STREAM", "true");
30-
tmpDir = path.join(
31-
os.tmpdir(),
32-
`openclaw-raw-stream-test-${randomUUID()}`,
33-
);
34-
vi.stubEnv("OPENCLAW_RAW_STREAM_PATH", path.join(tmpDir, "raw.jsonl"));
35-
mockAppendRegularFile.mockReset();
20+
process.on("unhandledRejection", onUnhandledRejection);
3621
});
3722

38-
it("survives a rejected write without throwing", async () => {
39-
mockAppendRegularFile.mockRejectedValue(
40-
new Error("ENOSPC: no space left on device"),
41-
);
42-
expect(() => appendRawStream({ event: "test", ts: 1 })).not.toThrow();
43-
// Let the microtask queue flush so the rejection reaches the catch handler.
44-
await vi.waitFor(() => {
45-
expect(mockAppendRegularFile).toHaveBeenCalledTimes(1);
46-
});
23+
afterEach(() => {
24+
process.off("unhandledRejection", onUnhandledRejection);
25+
unhandledRejections.length = 0;
26+
vi.unstubAllEnvs();
4727
});
4828

49-
it("survives a synchronous throw from the dependency", () => {
50-
mockAppendRegularFile.mockImplementation(() => {
51-
throw new Error("synchronous construction failure");
29+
afterAll(() => {
30+
fs.rmSync(tmpDir, { recursive: true, force: true });
31+
});
32+
33+
async function drainAsyncWrites(): Promise<void> {
34+
await Promise.resolve();
35+
await new Promise<void>((resolve) => {
36+
setImmediate(resolve);
5237
});
38+
}
39+
40+
it("contains a real rejected append without leaking an unhandled rejection", async () => {
41+
const directoryTarget = path.join(tmpDir, "directory-target");
42+
fs.mkdirSync(directoryTarget);
43+
vi.stubEnv("OPENCLAW_RAW_STREAM_PATH", directoryTarget);
44+
5345
expect(() => appendRawStream({ event: "test", ts: 1 })).not.toThrow();
54-
expect(mockAppendRegularFile).toHaveBeenCalledTimes(1);
46+
await drainAsyncWrites();
47+
48+
expect(unhandledRejections).toHaveLength(0);
5549
});
5650

57-
it("writes successfully in the normal case", async () => {
58-
fs.mkdirSync(tmpDir, { recursive: true });
59-
try {
60-
mockAppendRegularFile.mockResolvedValue(undefined);
61-
expect(() => appendRawStream({ event: "test", ts: 1 })).not.toThrow();
62-
await vi.waitFor(() => {
63-
expect(mockAppendRegularFile).toHaveBeenCalledTimes(1);
64-
});
65-
expect(
66-
mockAppendRegularFile,
67-
).toHaveBeenCalledWith({
68-
filePath: path.join(tmpDir, "raw.jsonl"),
69-
content: '{"event":"test","ts":1}\n',
70-
rejectSymlinkParents: true,
71-
});
72-
} finally {
73-
fs.rmSync(tmpDir, { recursive: true, force: true });
74-
}
51+
it("appends exact JSONL through the real dependency", async () => {
52+
const rawStreamPath = path.join(tmpDir, "raw.jsonl");
53+
vi.stubEnv("OPENCLAW_RAW_STREAM_PATH", rawStreamPath);
54+
55+
appendRawStream({ event: "test", ts: 1 });
56+
await vi.waitFor(() => {
57+
expect(fs.existsSync(rawStreamPath)).toBe(true);
58+
});
59+
60+
expect(fs.readFileSync(rawStreamPath, "utf8")).toBe('{"event":"test","ts":1}\n');
61+
expect(unhandledRejections).toHaveLength(0);
7562
});
7663

77-
it("is a no-op when OPENCLAW_RAW_STREAM is not set", () => {
64+
it("does nothing when raw streaming is disabled", async () => {
65+
const rawStreamPath = path.join(tmpDir, "disabled.jsonl");
7866
vi.stubEnv("OPENCLAW_RAW_STREAM", "");
67+
vi.stubEnv("OPENCLAW_RAW_STREAM_PATH", rawStreamPath);
68+
7969
appendRawStream({ event: "test", ts: 1 });
80-
expect(mockAppendRegularFile).not.toHaveBeenCalled();
70+
await drainAsyncWrites();
71+
72+
expect(fs.existsSync(rawStreamPath)).toBe(false);
73+
expect(unhandledRejections).toHaveLength(0);
74+
});
75+
76+
it("contains synchronous JSON serialization failures", () => {
77+
const rawStreamPath = path.join(tmpDir, "cyclic.jsonl");
78+
const payload: Record<string, unknown> = {};
79+
payload.self = payload;
80+
vi.stubEnv("OPENCLAW_RAW_STREAM_PATH", rawStreamPath);
81+
82+
expect(() => appendRawStream(payload)).not.toThrow();
83+
expect(fs.existsSync(rawStreamPath)).toBe(false);
84+
expect(unhandledRejections).toHaveLength(0);
8185
});
8286
});

‎src/agents/embedded-agent-subscribe.raw-stream.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ export function appendRawStream(payload: Record<string, unknown>) {
3939
content: `${JSON.stringify(payload)}\n`,
4040
rejectSymlinkParents: true,
4141
}).catch(() => {
42-
// ignore raw stream write failures
42+
// Raw diagnostics are best-effort; filesystem failures must not terminate agent runs.
4343
});
4444
} catch {
45-
// ignore synchronous failures before the promise is returned
45+
// JSON serialization can fail synchronously, for example with cyclic payloads.
4646
}
4747
}

0 commit comments

Comments
 (0)