File size: 8,592 Bytes
5cb63c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Oversized process deadlines must never wrap into immediate Node timers.
import { performance } from "node:perf_hooks";
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createDeferred } from "../../../test/helpers/promise.js";
import { createProcessSupervisor } from "./supervisor.js";
import type { SpawnProcessAdapter } from "./types.js";

const { createChildAdapterMock, createPtyAdapterMock } = vi.hoisted(() => ({
  createChildAdapterMock: vi.fn(),
  createPtyAdapterMock: vi.fn(),
}));

vi.mock("./adapters/child.js", () => ({
  createChildAdapter: async (
    ...args: Parameters<typeof import("./adapters/child.js").createChildAdapter>
  ) => ({
    adapter: await createChildAdapterMock(...args),
    ready: Promise.resolve(),
  }),
}));

vi.mock("./adapters/pty.js", () => ({
  createPtyAdapter: createPtyAdapterMock,
}));

type TimeoutTestAdapter = SpawnProcessAdapter<NodeJS.Signals | null> & {
  emitStdout: (chunk: string) => void;
  killMock: ReturnType<typeof vi.fn>;
  disposeMock: ReturnType<typeof vi.fn>;
  settle: () => void;
};

function createTimeoutTestAdapter(): TimeoutTestAdapter {
  const completion = createDeferred<{ code: number | null; signal: NodeJS.Signals | null }>();
  let stdoutListener: ((chunk: string) => void) | undefined;
  const killMock = vi.fn((signal?: NodeJS.Signals) => {
    completion.resolve({ code: null, signal: signal ?? null });
  });
  const disposeMock = vi.fn();

  return {
    pid: 1234,
    supportsRawOutput: false,
    onStdout: (listener) => {
      stdoutListener = listener;
    },
    onStderr: () => undefined,
    wait: async () => completion.promise,
    kill: killMock,
    dispose: disposeMock,
    emitStdout: (chunk) => stdoutListener?.(chunk),
    killMock,
    disposeMock,
    settle: () => completion.resolve({ code: 0, signal: null }),
  };
}

const oversizedTimeouts = [
  { durationName: "the first overflowing Node delay", durationMs: 2 ** 31 },
  { durationName: "the maximum safe integer", durationMs: Number.MAX_SAFE_INTEGER },
] as const;

const deadlineCases = [
  {
    deadlineName: "overall deadline",
    timeoutField: "timeoutMs",
    reason: "overall-timeout",
    refreshOutput: false,
  },
  {
    deadlineName: "silent-output deadline",
    timeoutField: "noOutputTimeoutMs",
    reason: "no-output-timeout",
    refreshOutput: false,
  },
  {
    deadlineName: "refreshed output deadline",
    timeoutField: "noOutputTimeoutMs",
    reason: "no-output-timeout",
    refreshOutput: true,
  },
] as const;

describe("process supervisor oversized timer deadlines", () => {
  beforeEach(() => {
    createChildAdapterMock.mockReset();
    createPtyAdapterMock.mockReset();
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.clearAllTimers();
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  for (const mode of ["child", "pty"] as const) {
    describe(`${mode} processes`, () => {
      for (const { durationName, durationMs } of oversizedTimeouts) {
        describe(durationName, () => {
          it.each(deadlineCases)(
            "bounds the $deadlineName",
            async ({ timeoutField, reason, refreshOutput }) => {
              const adapter = createTimeoutTestAdapter();
              const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
              const adapterMock = mode === "child" ? createChildAdapterMock : createPtyAdapterMock;
              adapterMock.mockResolvedValue(adapter);

              const supervisor = createProcessSupervisor();
              const run = await supervisor.spawn({
                [timeoutField]: durationMs,
                mode,
                argv: [process.execPath, "-e", ""],
              });

              try {
                expect(setTimeoutSpy.mock.calls.map(([, delay]) => delay)).toEqual([
                  MAX_TIMER_TIMEOUT_MS,
                ]);

                await vi.advanceTimersByTimeAsync(1);
                expect(adapter.killMock).not.toHaveBeenCalled();

                if (refreshOutput) {
                  adapter.emitStdout("still running");
                  expect(setTimeoutSpy.mock.calls.map(([, delay]) => delay)).toEqual([
                    MAX_TIMER_TIMEOUT_MS,
                    MAX_TIMER_TIMEOUT_MS,
                  ]);
                }

                await vi.advanceTimersByTimeAsync(
                  refreshOutput ? MAX_TIMER_TIMEOUT_MS - 1 : MAX_TIMER_TIMEOUT_MS - 2,
                );
                expect(adapter.killMock).not.toHaveBeenCalled();

                await vi.advanceTimersByTimeAsync(1);
                expect(adapter.killMock).not.toHaveBeenCalled();

                const remainingIntervalMs = Math.min(
                  durationMs - MAX_TIMER_TIMEOUT_MS,
                  MAX_TIMER_TIMEOUT_MS,
                );
                expect(setTimeoutSpy.mock.calls.map(([, delay]) => delay)).toEqual(
                  refreshOutput
                    ? [MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_MS, remainingIntervalMs]
                    : [MAX_TIMER_TIMEOUT_MS, remainingIntervalMs],
                );

                if (durationMs === Number.MAX_SAFE_INTEGER) {
                  adapter.settle();
                  await expect(run.wait()).resolves.toMatchObject({
                    reason: "exit",
                    timedOut: false,
                    noOutputTimedOut: false,
                  });
                  expect(adapter.killMock).not.toHaveBeenCalled();
                  expect(adapter.disposeMock).toHaveBeenCalledTimes(1);
                  expect(vi.getTimerCount()).toBe(0);
                  return;
                }

                await vi.advanceTimersByTimeAsync(remainingIntervalMs - 1);
                expect(adapter.killMock).not.toHaveBeenCalled();
                await vi.advanceTimersByTimeAsync(1);
                await expect(run.wait()).resolves.toMatchObject({
                  reason,
                  timedOut: true,
                  noOutputTimedOut: reason === "no-output-timeout",
                });
                expect(adapter.killMock).toHaveBeenCalledTimes(1);
                expect(adapter.disposeMock).toHaveBeenCalledTimes(1);
                expect(vi.getTimerCount()).toBe(0);
              } finally {
                adapter.settle();
                await run.wait();
              }
            },
          );
        });
      }

      it.each(deadlineCases)(
        "preserves the $deadlineName when an intermediate timer fires late",
        async ({ timeoutField, reason, refreshOutput }) => {
          const initialNowMs = 1_000;
          const trailingDurationMs = 10 * 60_000;
          const callbackLatenessMs = 9 * 60_000;
          const nowSpy = vi.spyOn(performance, "now").mockReturnValue(initialNowMs);
          const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
          const adapter = createTimeoutTestAdapter();
          const adapterMock = mode === "child" ? createChildAdapterMock : createPtyAdapterMock;
          adapterMock.mockResolvedValue(adapter);

          const run = await createProcessSupervisor().spawn({
            [timeoutField]: MAX_TIMER_TIMEOUT_MS + trailingDurationMs,
            mode,
            argv: [process.execPath, "-e", ""],
          });

          try {
            if (refreshOutput) {
              adapter.emitStdout("still running");
            }

            nowSpy.mockReturnValue(initialNowMs + MAX_TIMER_TIMEOUT_MS + callbackLatenessMs);
            await vi.advanceTimersByTimeAsync(MAX_TIMER_TIMEOUT_MS);
            expect(adapter.killMock).not.toHaveBeenCalled();
            expect(setTimeoutSpy.mock.calls.map(([, delay]) => delay)).toEqual(
              refreshOutput
                ? [MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_MS, 60_000]
                : [MAX_TIMER_TIMEOUT_MS, 60_000],
            );

            nowSpy.mockReturnValue(initialNowMs + MAX_TIMER_TIMEOUT_MS + trailingDurationMs);
            await vi.advanceTimersByTimeAsync(60_000);
            await expect(run.wait()).resolves.toMatchObject({
              reason,
              timedOut: true,
              noOutputTimedOut: reason === "no-output-timeout",
            });
            expect(adapter.killMock).toHaveBeenCalledTimes(1);
            expect(adapter.disposeMock).toHaveBeenCalledTimes(1);
            expect(vi.getTimerCount()).toBe(0);
          } finally {
            adapter.settle();
            await run.wait();
          }
        },
      );
    });
  }
});