mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 10:04:50 +00:00
* fix(hopper): report a cancel after send as pending with an unknown outcome HopperCancelledError always reported cleanup "complete", including when the caller cancelled after Hopper had received the request. Hopper's bridge runs one request at a time and still applies it, so binary_session showed the request active while the error claimed cleanup had finished. The queue already records whether a request was transmitted. Cancellation now carries that fact: a request Hopper received reports cleanup "pending" and outcome "unknown", and its message says Hopper may still apply it; a request that was never sent still reports cleanup "complete". Refs #15322 * fix(hopper)!: derive cancel and timeout outcomes from one request stage HopperRequestQueue tracked how far a request got with a `transmitted` boolean and a separate `callerSettled` flag, and labelled every abandoned caller "cancelled". The timeout path read `transmitted` to choose providerState while the cancel path read it again separately. Each request now has one stage (queued, sent, replied) and one caller state (waiting, settled, cancelled, timed_out). A single #abandon derives both the cancellation and the deadline error from the stage: a queued request never reached Hopper, while a sent one keeps the wire until Hopper replies and its effect is unknown. binary_session analysis_activity now reports `timed_out` for a caller whose deadline expired instead of `cancelled`. The caller-state values are defined once in the domain. Refs #15322 BREAKING CHANGE: binary_session `analysis_activity.providers[].active.caller_state` can now be `timed_out`. Previously a caller whose deadline expired while Hopper still ran its request was reported as `cancelled`. Clients that validate the output against the previous schema must accept `timed_out`; `cancelled` now means only an explicit cancellation. * fix(hopper): tell every caller a sent cancellation may still apply The sent-request warning and its recovery are now part of the cancelled error's presentation, so CLI and MCP callers see them instead of the generic "start it again" text. A zero deadline is expired by the queue's one deadline check instead of a second early return, and failActive is pinned to refuse a request that has not been sent. * fix(hopper): keep the session-only step out of a one-shot caller's recovery
336 lines
11 KiB
TypeScript
336 lines
11 KiB
TypeScript
import { getEventListeners } from "node:events";
|
|
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { HopperProtocolError } from "./HopperErrors.js";
|
|
import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js";
|
|
import { ok } from "../domain/result.js";
|
|
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
|
import { HopperRequestQueue } from "./HopperRequestQueue.js";
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
describe("HopperRequestQueue deadlines", () => {
|
|
it("expires queued work but keeps an expired active request on the wire until its reply", async () => {
|
|
vi.useFakeTimers();
|
|
const sent: number[] = [];
|
|
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
|
|
const controller = new AbortController();
|
|
const active = queue.run(
|
|
1,
|
|
"analyze_function",
|
|
{},
|
|
{ timeoutMs: 25, signal: controller.signal },
|
|
);
|
|
const expired = queue.run(2, "set_comment", {}, { timeoutMs: 10 });
|
|
const next = queue.run(3, "echo", {}, {});
|
|
|
|
await vi.advanceTimersByTimeAsync(10);
|
|
await expect(expired).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "HopperTimeoutError",
|
|
requestId: 2,
|
|
providerState: "not_started",
|
|
},
|
|
});
|
|
expect(queue.hasQueued(2)).toBe(false);
|
|
await vi.advanceTimersByTimeAsync(15);
|
|
controller.abort("too late to change the timeout");
|
|
await expect(active).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "HopperTimeoutError",
|
|
timeoutMs: 25,
|
|
operation: "analyze_function",
|
|
requestId: 1,
|
|
providerState: "busy",
|
|
},
|
|
});
|
|
expect(sent).toEqual([1]);
|
|
// The deadline elapsed before the abort, so the caller timed out.
|
|
expect(queue.activity()).toMatchObject({
|
|
callerState: "timed_out",
|
|
queuedRequests: 1,
|
|
});
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
expect(queue.accept(1, ok("late"))).toBe(true);
|
|
expect(sent).toEqual([1, 3]);
|
|
queue.accept(3, ok("next"));
|
|
await expect(next).resolves.toEqual(ok("next"));
|
|
expect(queue.activity()).toBeNull();
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("cleans deadline and abort observers on success before the deadline", async () => {
|
|
vi.useFakeTimers();
|
|
const queue = new HopperRequestQueue(() => {});
|
|
const controller = new AbortController();
|
|
const pending = queue.run(
|
|
1,
|
|
"echo",
|
|
{},
|
|
{ timeoutMs: 25, signal: controller.signal },
|
|
);
|
|
queue.accept(1, ok(42));
|
|
expect(getEventListeners(controller.signal, "abort")).toEqual([]);
|
|
controller.abort();
|
|
await expect(pending).resolves.toEqual(ok(42));
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("keeps the exact active cancellation distinct from a later timeout", async () => {
|
|
vi.useFakeTimers();
|
|
const queue = new HopperRequestQueue(() => {});
|
|
const controller = new AbortController();
|
|
const pending = queue.run(
|
|
1,
|
|
"echo",
|
|
{},
|
|
{ timeoutMs: 25, signal: controller.signal },
|
|
);
|
|
const reason = { source: "active caller" };
|
|
controller.abort(reason);
|
|
const result = await pending;
|
|
if (result.ok) throw new Error("Expected cancellation");
|
|
expect(result.error._tag).toBe("HopperCancelledError");
|
|
expect(result.error.cause).toBe(reason);
|
|
// Hopper received the request and still runs it: the outcome is unknown.
|
|
expect(result.error.ownPresentation()).toMatchObject({
|
|
code: "cancelled",
|
|
details: { operation: "hopper", cleanup: "pending", outcome: "unknown" },
|
|
});
|
|
// The projected outcome every CLI and MCP caller reads says so too.
|
|
const projected = projectAnalysisError(result.error);
|
|
expect(projected.message).toMatch(
|
|
/after Hopper received it.*may still apply/u,
|
|
);
|
|
expect(projected.message).not.toMatch(/Start it again/u);
|
|
// Only a caller that keeps the session is sent to watch the request.
|
|
expect(projected.remediation.action).toMatch(
|
|
/binary_session\.analysis_activity.*read the current state/u,
|
|
);
|
|
const oneShot = projectAnalysisError(result.error, "invocation");
|
|
expect(oneShot.remediation.action).toMatch(/read the current state/iu);
|
|
expect(oneShot.remediation.action).not.toMatch(/binary_session/u);
|
|
expect(queue.activity()?.callerState).toBe("cancelled");
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
expect(queue.accept(1, ok("late"))).toBe(true);
|
|
expect(queue.activity()).toBeNull();
|
|
});
|
|
|
|
it("does not recreate timers when a progress observer cancels synchronously", async () => {
|
|
vi.useFakeTimers();
|
|
const send = vi.fn();
|
|
const queue = new HopperRequestQueue(send);
|
|
const controller = new AbortController();
|
|
const reason = { source: "progress" };
|
|
const pending = queue.run(
|
|
1,
|
|
"echo",
|
|
{},
|
|
{
|
|
timeoutMs: 100,
|
|
signal: controller.signal,
|
|
progress: {
|
|
report: () => {
|
|
controller.abort(reason);
|
|
return Promise.resolve();
|
|
},
|
|
},
|
|
},
|
|
);
|
|
const result = await pending;
|
|
if (result.ok) throw new Error("Expected cancellation");
|
|
expect(result.error.cause).toBe(reason);
|
|
// The slot was reserved but nothing was sent, so nothing reached Hopper.
|
|
expect(result.error.ownPresentation()?.details).toEqual({
|
|
operation: "hopper",
|
|
cleanup: "complete",
|
|
});
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
expect(send).not.toHaveBeenCalled();
|
|
expect(queue.activity()).toBeNull();
|
|
const next = queue.run(2, "next", {}, {});
|
|
expect(send).toHaveBeenCalledExactlyOnceWith(
|
|
{ id: 2, method: "next", params: {} },
|
|
expect.any(Function),
|
|
);
|
|
queue.accept(2, ok(null));
|
|
await next;
|
|
});
|
|
|
|
it("cleans all deadlines on teardown, including after an active timeout", async () => {
|
|
vi.useFakeTimers();
|
|
const queue = new HopperRequestQueue(() => {});
|
|
const result = vi.fn();
|
|
const active = queue.run(1, "active", {}, { timeoutMs: 10 }).then(result);
|
|
const queued = queue.run(2, "queued", {}, { timeoutMs: 100 });
|
|
await vi.advanceTimersByTimeAsync(10);
|
|
const failure = new HopperProtocolError("closed");
|
|
queue.failAll(failure);
|
|
await active;
|
|
await expect(queued).resolves.toEqual({ ok: false, error: failure });
|
|
expect(result).toHaveBeenCalledTimes(1);
|
|
expect(queue.activity()).toBeNull();
|
|
expect(queue.hasQueued(2)).toBe(false);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("HopperRequestQueue deadline admission and races", () => {
|
|
it("removes queued cancelled work and honours cancellation before admission", async () => {
|
|
vi.useFakeTimers();
|
|
const sent: number[] = [];
|
|
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
|
|
const active = queue.run(1, "active", {}, {});
|
|
const controller = new AbortController();
|
|
const queued = queue.run(
|
|
2,
|
|
"queued",
|
|
{},
|
|
{ timeoutMs: 100, signal: controller.signal },
|
|
);
|
|
const reason = { source: "waiting caller" };
|
|
controller.abort(reason);
|
|
const preAborted = queue.run(
|
|
3,
|
|
"pre-aborted",
|
|
{},
|
|
{ timeoutMs: 100, signal: controller.signal },
|
|
);
|
|
for (const result of await Promise.all([queued, preAborted])) {
|
|
if (result.ok) throw new Error("Expected cancellation");
|
|
expect(result.error._tag).toBe("HopperCancelledError");
|
|
expect(result.error.cause).toBe(reason);
|
|
// Never sent, so nothing reached Hopper and cleanup is complete.
|
|
expect(result.error.ownPresentation()?.details).toEqual({
|
|
operation: "hopper",
|
|
cleanup: "complete",
|
|
});
|
|
}
|
|
expect(queue.hasQueued(2)).toBe(false);
|
|
expect(queue.hasQueued(3)).toBe(false);
|
|
expect(queue.activity()?.queuedRequests).toBe(0);
|
|
queue.accept(1, ok(null));
|
|
await active;
|
|
expect(sent).toEqual([1]);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it.each([NaN, Infinity, -1, 0.5, 2_147_483_648])(
|
|
"rejects invalid deadline %s without sending",
|
|
async (timeoutMs) => {
|
|
vi.useFakeTimers();
|
|
const send = vi.fn();
|
|
const queue = new HopperRequestQueue(send);
|
|
await expect(
|
|
queue.run(1, "echo", {}, { timeoutMs }),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "HopperProtocolError" },
|
|
});
|
|
expect(send).not.toHaveBeenCalled();
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
},
|
|
);
|
|
|
|
it("expires zero deadlines without sending", async () => {
|
|
vi.useFakeTimers();
|
|
const send = vi.fn();
|
|
const queue = new HopperRequestQueue(send);
|
|
await expect(
|
|
queue.run(1, "echo", {}, { timeoutMs: 0 }),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "HopperTimeoutError",
|
|
timeoutMs: 0,
|
|
providerState: "not_started",
|
|
},
|
|
});
|
|
expect(send).not.toHaveBeenCalled();
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("does not fail a request that has not been sent yet", async () => {
|
|
const send = vi.fn();
|
|
const queue = new HopperRequestQueue(send);
|
|
const failedBeforeSend: boolean[] = [];
|
|
const pending = queue.run(
|
|
1,
|
|
"echo",
|
|
{},
|
|
{
|
|
progress: {
|
|
report: () => {
|
|
// An unattributed bridge rejection during the "started" report
|
|
// cannot belong to a request that never reached Hopper.
|
|
failedBeforeSend.push(
|
|
queue.failActive(new HopperProtocolError("unattributed")),
|
|
);
|
|
return Promise.resolve();
|
|
},
|
|
},
|
|
},
|
|
);
|
|
expect(failedBeforeSend).toEqual([false]);
|
|
expect(send).toHaveBeenCalledOnce();
|
|
expect(queue.accept(1, ok("sent"))).toBe(true);
|
|
await expect(pending).resolves.toEqual(ok("sent"));
|
|
});
|
|
|
|
it("admits the largest Node timer delay as a deadline", async () => {
|
|
vi.useFakeTimers();
|
|
const sent: number[] = [];
|
|
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
|
|
const running = queue.run(
|
|
1,
|
|
"echo",
|
|
{},
|
|
{
|
|
timeoutMs: MAX_NODE_TIMER_DELAY_MS,
|
|
},
|
|
);
|
|
expect(sent).toEqual([1]);
|
|
const teardown = new HopperProtocolError("test teardown");
|
|
queue.failAll(teardown);
|
|
await expect(running).resolves.toEqual({ ok: false, error: teardown });
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
});
|
|
|
|
it("honors elapsed deadlines on reply and dequeue before their timers run", async () => {
|
|
vi.useFakeTimers();
|
|
const clock = vi.spyOn(performance, "now").mockReturnValue(0);
|
|
const sent: number[] = [];
|
|
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
|
|
const active = queue.run(1, "echo", {}, { timeoutMs: 10 });
|
|
const queued = queue.run(2, "set_comment", {}, { timeoutMs: 10 });
|
|
const next = queue.run(3, "echo", {}, {});
|
|
clock.mockReturnValue(20);
|
|
|
|
expect(queue.accept(1, ok("late"))).toBe(true);
|
|
await expect(active).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "HopperTimeoutError", requestId: 1, providerState: "busy" },
|
|
});
|
|
expect(sent).toEqual([1, 3]);
|
|
await expect(queued).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "HopperTimeoutError",
|
|
operation: "set_comment",
|
|
requestId: 2,
|
|
providerState: "not_started",
|
|
},
|
|
});
|
|
queue.accept(3, ok("next"));
|
|
await expect(next).resolves.toEqual(ok("next"));
|
|
expect(queue.activity()).toBeNull();
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|