File size: 9,724 Bytes
3144483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Regression coverage for lifecycle-owned cleanup of ephemeral command lanes.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createDeferred } from "../../test/helpers/promise.js";
import {
  enqueueCommandInLane,
  getCommandLaneSnapshot,
  getTotalQueueSize,
  resetCommandLane,
  setCommandLaneConcurrency,
} from "./command-queue.js";
import { createLaneQueue, type LaneState } from "./command-queue.state.js";
import { resetCommandQueueStateForTest } from "./command-queue.test-support.js";
import { CommandLane } from "./lanes.js";

vi.mock("../logging/diagnostic-runtime.js", () => ({
  logLaneEnqueue: vi.fn(),
  logLaneDequeue: vi.fn(),
  diagnosticLogger: {
    debug: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
  },
}));

function getCommandLaneRegistryForTest(): Map<string, unknown> {
  const state = (globalThis as Record<PropertyKey, unknown>)[
    Symbol.for("openclaw.commandQueueState")
  ];
  const lanes = (state as { lanes?: unknown } | undefined)?.lanes;
  if (!(lanes instanceof Map)) {
    throw new Error("Expected the shared command lane registry to be initialized");
  }
  return lanes as Map<string, unknown>;
}

describe("scoped command lane lifecycle", () => {
  beforeEach(() => {
    vi.useRealTimers();
    resetCommandQueueStateForTest();
    setCommandLaneConcurrency(CommandLane.Main, 1);
  });

  afterEach(() => {
    vi.useRealTimers();
    resetCommandQueueStateForTest();
  });

  it.each(["session:", "nested:", "context-engine-turn-maintenance:"])(
    "retires ten independently completed %s lanes from the shared registry",
    async (prefix) => {
      const lanes = getCommandLaneRegistryForTest();
      const baselineSize = lanes.size;
      const allRunsStarted = createDeferred();
      let activeRuns = 0;
      let peakActiveRuns = 0;
      const laneNames = Array.from(
        { length: 10 },
        (_, index) => `${prefix}agent:main:autoqa-${index}`,
      );

      const results = await Promise.all(
        laneNames.map((lane, index) =>
          enqueueCommandInLane(lane, async () => {
            activeRuns += 1;
            peakActiveRuns = Math.max(peakActiveRuns, activeRuns);
            if (activeRuns === laneNames.length) {
              allRunsStarted.resolve();
            }
            await allRunsStarted.promise;
            activeRuns -= 1;
            return index;
          }),
        ),
      );

      expect(results).toEqual(Array.from({ length: 10 }, (_, index) => index));
      expect(peakActiveRuns).toBe(10);
      expect(activeRuns).toBe(0);
      expect(getTotalQueueSize()).toBe(0);
      expect(lanes.size).toBe(baselineSize);
      for (const lane of laneNames) {
        expect(lanes.has(lane)).toBe(false);
      }
    },
  );

  it("keeps a session lane until its queued successor finishes", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "session:agent:main:autoqa-queued";
    const firstGate = createDeferred();
    const secondGate = createDeferred();

    const first = enqueueCommandInLane(lane, async () => {
      await firstGate.promise;
      return "first";
    });
    const second = enqueueCommandInLane(lane, async () => {
      await secondGate.promise;
      return "second";
    });

    expect(lanes.has(lane)).toBe(true);
    firstGate.resolve();
    await expect(first).resolves.toBe("first");
    expect(lanes.has(lane)).toBe(true);
    expect(getCommandLaneSnapshot(lane)).toMatchObject({ activeCount: 1, queuedCount: 0 });

    secondGate.resolve();
    await expect(second).resolves.toBe("second");
    expect(lanes.has(lane)).toBe(false);
  });

  it("preserves explicitly configured and paused dynamic lanes", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const configuredLane = "session:agent:main:autoqa-configured";
    const pausedLane = "nested:agent:main:autoqa-paused";

    setCommandLaneConcurrency(configuredLane, 2);
    await Promise.all([
      enqueueCommandInLane(configuredLane, async () => "first"),
      enqueueCommandInLane(configuredLane, async () => "second"),
    ]);

    expect(lanes.has(configuredLane)).toBe(true);
    expect(getCommandLaneSnapshot(configuredLane)).toMatchObject({
      activeCount: 0,
      queuedCount: 0,
      maxConcurrent: 2,
    });

    setCommandLaneConcurrency(pausedLane, 0);
    let pausedRunStarted = false;
    const pausedRun = enqueueCommandInLane(pausedLane, async () => {
      pausedRunStarted = true;
      return "resumed";
    });

    expect(pausedRunStarted).toBe(false);
    expect(lanes.has(pausedLane)).toBe(true);
    expect(getCommandLaneSnapshot(pausedLane)).toMatchObject({
      activeCount: 0,
      queuedCount: 1,
      maxConcurrent: 0,
    });

    setCommandLaneConcurrency(pausedLane, 1);
    await expect(pausedRun).resolves.toBe("resumed");
    expect(lanes.has(pausedLane)).toBe(false);
    expect(lanes.has(configuredLane)).toBe(true);
  });

  it("does not let stale session completion retire a replacement-generation run", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "session:agent:main:autoqa-replacement";
    const staleGate = createDeferred();
    const replacementGate = createDeferred();
    const staleRun = enqueueCommandInLane(lane, async () => {
      await staleGate.promise;
      return "stale";
    });

    expect(resetCommandLane(lane)).toBe(1);
    const replacementRun = enqueueCommandInLane(lane, async () => {
      await replacementGate.promise;
      return "replacement";
    });
    const replacementState = lanes.get(lane);

    staleGate.resolve();
    await expect(staleRun).resolves.toBe("stale");
    expect(lanes.get(lane)).toBe(replacementState);
    expect(getCommandLaneSnapshot(lane)).toMatchObject({ activeCount: 1, queuedCount: 0 });

    replacementGate.resolve();
    await expect(replacementRun).resolves.toBe("replacement");
    expect(lanes.has(lane)).toBe(false);
  });

  it("preserves gateway-managed fixed lanes while scoped lanes finish", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const fixedLanes = [
      CommandLane.Main,
      CommandLane.SystemAgent,
      CommandLane.Cron,
      CommandLane.CronNested,
      CommandLane.Subagent,
      CommandLane.Nested,
    ];

    for (const lane of fixedLanes) {
      setCommandLaneConcurrency(lane, 1);
    }

    const scopedLanes = [
      "session:agent:main:autoqa-fixed",
      "nested:agent:main:autoqa-fixed",
      "context-engine-turn-maintenance:agent:main:autoqa-fixed",
    ];
    await Promise.all(scopedLanes.map((lane) => enqueueCommandInLane(lane, async () => lane)));

    for (const lane of fixedLanes) {
      expect(lanes.has(lane)).toBe(true);
      expect(getCommandLaneSnapshot(lane)).toMatchObject({
        activeCount: 0,
        queuedCount: 0,
        maxConcurrent: 1,
      });
    }
    for (const lane of scopedLanes) {
      expect(lanes.has(lane)).toBe(false);
    }
  });

  it("recreates a maintenance lane for deferred same-session follow-up work", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "context-engine-turn-maintenance:agent:main:autoqa-rerun";
    const replacementGate = createDeferred();
    const firstRun = enqueueCommandInLane(lane, async () => "first");
    const originalState = lanes.get(lane);
    const replacementRun = firstRun.then(() =>
      enqueueCommandInLane(lane, async () => {
        await replacementGate.promise;
        return "replacement";
      }),
    );

    await expect(firstRun).resolves.toBe("first");
    expect(lanes.has(lane)).toBe(true);
    expect(lanes.get(lane)).not.toBe(originalState);
    expect(getCommandLaneSnapshot(lane)).toMatchObject({ activeCount: 1, queuedCount: 0 });

    replacementGate.resolve();
    await expect(replacementRun).resolves.toBe("replacement");
    expect(lanes.has(lane)).toBe(false);
  });

  it("does not retire a newer lane state when stale work finishes", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "session:agent:main:autoqa-recreated-state";
    const staleGate = createDeferred();
    const staleRun = enqueueCommandInLane(lane, async () => {
      await staleGate.promise;
      return "stale";
    });
    const replacementState = {
      lane,
      queue: createLaneQueue(),
      activeTaskIds: new Set<number>(),
      maxConcurrent: 1,
      draining: false,
      generation: 0,
    } satisfies LaneState;

    lanes.set(lane, replacementState);
    staleGate.resolve();
    await expect(staleRun).resolves.toBe("stale");

    expect(lanes.get(lane)).toBe(replacementState);
    lanes.delete(lane);
  });

  it("retires a scoped lane after its active task rejects", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "nested:agent:main:autoqa-rejected";

    await expect(
      enqueueCommandInLane(lane, async () => {
        throw new Error("scoped task failed");
      }),
    ).rejects.toThrow("scoped task failed");

    expect(lanes.has(lane)).toBe(false);
  });

  it("retires a scoped lane after its active task times out", async () => {
    const lanes = getCommandLaneRegistryForTest();
    const lane = "session:agent:main:autoqa-timed-out";

    vi.useFakeTimers();
    try {
      const timedOut = enqueueCommandInLane(lane, async () => new Promise<never>(() => {}), {
        taskTimeoutMs: 5,
      });
      const rejection = expect(timedOut).rejects.toMatchObject({
        name: "CommandLaneTaskTimeoutError",
      });

      await vi.advanceTimersByTimeAsync(5);
      await rejection;

      expect(lanes.has(lane)).toBe(false);
    } finally {
      vi.useRealTimers();
    }
  });
});