File size: 7,932 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
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { onAgentEventForRun, type AgentEventPayload } from "../../infra/agent-events.js";
import {
  clearAgentRunContext,
  getAgentRunContext,
  registerAgentRunContext,
  resetAgentRunRegistryForTest,
  resolveProjectedAgentRunModel,
} from "../../infra/agent-run-registry.js";
import type { AgentRunContext } from "../../infra/agent-run-registry.types.js";
import { createAssistantMessageEventStream } from "../../llm/utils/event-stream.js";
import {
  MODEL,
  PROVIDER,
  SESSION_ID,
  SESSION_KEY,
  finalMessage,
  params,
  request,
  sessionEntry,
  setup,
  type Execution,
} from "./inference-runtime.test-support.js";

const RUN_ID = request().runId;
const REROUTED_MODEL = "fixture-rerouted";
const runContext = {
  sessionId: SESSION_ID,
  sessionKey: SESSION_KEY,
  agentId: "runtime-agent",
  projectSessionActive: true,
} satisfies AgentRunContext;

function projectedModel() {
  return resolveProjectedAgentRunModel({ agentId: "runtime-agent", sessionId: SESSION_ID });
}

function startInference(
  options: {
    context?: AgentRunContext;
    afterModelPreparation?: () => void;
  } = {},
) {
  registerAgentRunContext(RUN_ID, options.context ?? runContext);
  const runtime = setup(sessionEntry, options);
  const stream = createAssistantMessageEventStream();
  const message = finalMessage();
  message.content = [{ type: "text", text: "Held response" }];
  runtime.stream.mockReturnValue(stream);
  const modelEvents: AgentEventPayload[] = [];
  const unsubscribe = onAgentEventForRun(RUN_ID, (event) => {
    if (event.stream === "lifecycle" && event.data.phase === "model") {
      modelEvents.push(event);
    }
  });
  const emit = vi.fn<Execution["emit"]>();
  const abort = new AbortController();
  let current = true;
  const execution = params(request(), emit);
  execution.signal = abort.signal;
  execution.isCurrent = () => current;
  const pending = runtime.executor(execution);
  onTestFinished(async () => {
    stream.end(message);
    await pending;
    unsubscribe();
  });
  return {
    runtime,
    stream,
    message,
    modelEvents,
    emit,
    abort,
    revoke: () => {
      current = false;
    },
    pending,
  };
}

afterEach(() => resetAgentRunRegistryForTest());

describe("worker.inference.start executing model", () => {
  it("publishes the configured model, then a responseModel reroute from a lean delta while held", async () => {
    const inference = startInference();
    inference.stream.push({ type: "start", partial: inference.message });
    await vi.waitFor(() => expect(projectedModel()).toEqual({ provider: PROVIDER, model: MODEL }));

    inference.message.responseModel = REROUTED_MODEL;
    inference.stream.push({ type: "text_delta", contentIndex: 0, delta: "Held response" });
    await vi.waitFor(() => expect(inference.emit).toHaveBeenCalledTimes(2));

    expect(projectedModel()).toEqual({ provider: PROVIDER, model: REROUTED_MODEL });
    expect(inference.modelEvents.map((event) => event.data)).toEqual([
      { phase: "model", provider: PROVIDER, model: MODEL },
      { phase: "model", provider: PROVIDER, model: REROUTED_MODEL },
    ]);
    expect(inference.modelEvents).toEqual([
      expect.objectContaining({ runId: RUN_ID, sessionId: SESSION_ID, sessionKey: SESSION_KEY }),
      expect.objectContaining({ runId: RUN_ID, sessionId: SESSION_ID, sessionKey: SESSION_KEY }),
    ]);
    expect(inference.runtime.releaseRuntime).not.toHaveBeenCalled();
    expect(inference.emit).toHaveBeenCalledWith({
      type: "text_delta",
      contentIndex: 0,
      delta: "Held response",
    });

    inference.stream.push({ type: "done", reason: "stop", message: inference.message });
    await expect(inference.pending).resolves.toMatchObject({
      type: "done",
      message: { model: MODEL, responseModel: REROUTED_MODEL },
    });
    expect(inference.modelEvents).toHaveLength(2);
    expect(projectedModel()).toEqual({ provider: PROVIDER, model: REROUTED_MODEL });
    clearAgentRunContext(RUN_ID);
    expect(projectedModel()).toBeUndefined();
  });

  it.each([
    { name: "session ID", mismatch: { sessionId: "foreign-session" } },
    { name: "session key", mismatch: { sessionKey: "agent:runtime-agent:foreign" } },
    { name: "agent", mismatch: { agentId: "foreign-agent" } },
  ])("ignores a run with a different $name", async ({ mismatch }) => {
    const inference = startInference({ context: { ...runContext, ...mismatch } });
    inference.message.responseModel = REROUTED_MODEL;
    inference.stream.push({ type: "start", partial: inference.message });
    inference.stream.push({ type: "done", reason: "stop", message: inference.message });

    await expect(inference.pending).resolves.toMatchObject({ type: "done" });
    expect(inference.modelEvents).toEqual([]);
    expect(getAgentRunContext(RUN_ID)?.activeModel).toBeUndefined();
  });

  it("does not bind to a replacement run context after model preparation awaits", async () => {
    let originalContext: AgentRunContext | undefined;
    const inference = startInference({
      afterModelPreparation: () => {
        originalContext = getAgentRunContext(RUN_ID);
        clearAgentRunContext(RUN_ID);
        registerAgentRunContext(RUN_ID, runContext);
      },
    });
    inference.stream.push({ type: "start", partial: inference.message });
    inference.stream.push({ type: "done", reason: "stop", message: inference.message });

    await expect(inference.pending).resolves.toMatchObject({ type: "done" });
    expect(originalContext).toBeDefined();
    expect(getAgentRunContext(RUN_ID)).not.toBe(originalContext);
    expect(inference.modelEvents).toEqual([]);
    expect(projectedModel()).toBeNull();
  });

  it("does not publish a held reroute into a replacement run with the same identifiers", async () => {
    const inference = startInference();
    inference.stream.push({ type: "start", partial: inference.message });
    await vi.waitFor(() => expect(projectedModel()).toEqual({ provider: PROVIDER, model: MODEL }));
    const originalContext = getAgentRunContext(RUN_ID);
    clearAgentRunContext(RUN_ID);
    registerAgentRunContext(RUN_ID, runContext);
    inference.message.responseModel = REROUTED_MODEL;
    inference.stream.push({ type: "text_delta", contentIndex: 0, delta: "Late response" });
    await vi.waitFor(() => expect(inference.emit).toHaveBeenCalledTimes(2));

    expect(getAgentRunContext(RUN_ID)).not.toBe(originalContext);
    expect(projectedModel()).toBeNull();
    expect(inference.modelEvents).toHaveLength(1);
    inference.stream.push({ type: "done", reason: "stop", message: inference.message });
    await expect(inference.pending).resolves.toMatchObject({ type: "done" });
    expect(projectedModel()).toBeNull();
    expect(inference.modelEvents).toHaveLength(1);
  });

  it.each(["revocation", "abort"] as const)(
    "stops held reroute publication after %s",
    async (cancellation) => {
      const inference = startInference();
      inference.stream.push({ type: "start", partial: inference.message });
      await vi.waitFor(() =>
        expect(projectedModel()).toEqual({ provider: PROVIDER, model: MODEL }),
      );
      if (cancellation === "abort") {
        inference.abort.abort();
      } else {
        inference.revoke();
      }
      inference.message.responseModel = REROUTED_MODEL;
      inference.stream.push({ type: "text_delta", contentIndex: 0, delta: "Late response" });

      await expect(inference.pending).resolves.toMatchObject({
        type: "error",
        reason: "cancelled",
      });
      expect(inference.modelEvents).toHaveLength(1);
      expect(projectedModel()).toEqual({ provider: PROVIDER, model: MODEL });
      expect(inference.emit.mock.calls.map(([event]) => event.type)).toEqual(["start"]);
      expect(inference.runtime.releaseRuntime).toHaveBeenCalledOnce();
    },
  );
});