Files
rea/src/hopper/HopperRequestQueue.test.ts
T
morluto 47353e494d feat(config): make the bridge request ceiling configurable (#6376)
* fix(reconstruction): dedupe residual unknown ids with uniqueSorted

Current main calls uniqueBy, which is not defined, so typecheck fails.
Residual unknown ids are strings, and the adjacent lists already use
uniqueSorted.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* feat(config): make the bridge request ceiling configurable

REA_BRIDGE_MAX_REQUEST_BYTES replaces the hard-coded 16 MiB Hopper and
Cutter request payload ceiling. The default stays 16777216 bytes. Values
outside 7464 to 268435456 bytes are configuration_invalid.

Part of #6176.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): keep cleanup ownership when a sent command's reply is oversized

An authenticated command may already have changed the Cutter document
when its reply exceeds the frame ceiling. Return the existing unknown
execution, with the ceiling diagnostic in the message, so receipt
cleanup still waits. A frame that overflows before the command is sent
remains a resource constraint.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style: format the bridge request ceiling sources

oxfmt --check failed on the five files that set and test
REA_BRIDGE_MAX_REQUEST_BYTES. Formatting only; an oversized Cutter
reply still stays an unknown execution.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): exclude the LF from the response frame budget

REA_BRIDGE_MAX_REQUEST_BYTES counts payload bytes. The Cutter response
reader and authenticated encoder were reserving one byte for the
terminating LF, so an exact-limit response was rejected. A reply that
exceeds the ceiling after the command was sent still stays an unknown
execution.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(bridge): measure escaped JSON before allocating the request

A command of U+0001 characters can expand sixfold. JSON.stringify of
that expansion can throw past Node's string ceiling before the payload
check. Count the escaped size within REA_BRIDGE_MAX_REQUEST_BYTES
first and refuse it as a resource constraint.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(config): derive the bridge request maximum from JSON expansion

A 256 MiB ceiling still lets a shorter U+0001 command expand past Node's
536870888-character string limit. The maximum is now
floor((536870888 - 296) / 7) = 76695798, the longest such command whose
authenticated frame fits in one string. Requests are still measured
before JSON.stringify.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(bridge): size the Cutter frame deadline and send the measured Hopper payload

The authenticated Cutter command is encoded after the challenge, so a
one-second read rejected an in-budget frame. That read now allows one
second per mebibyte of the ceiling and never waits longer than 25
seconds. Hello stays at one second. Hopper writes the payload it already
measured instead of serializing the same request again.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(config): bound the bridge request maximum by the serialized string

The ceiling already measures escaped JSON, so dividing Node's string limit by the seven-byte expansion rejected encoded payloads that still fit. The maximum is 536870887, one byte under that string ceiling, leaving room for the framing LF.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(hopper): serialize a bridge request when it reaches the wire

The queue kept each encoded frame, plus the caller's params, until Hopper finished the active request. A raised ceiling made a few waiting calls enough to exhaust the heap. The FIFO now keeps the params, and the frame is encoded only for the request being written.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): hash the bridge proof prefix and payload separately

An exact-limit Cutter frame plus the HMAC prefix exceeds Node's single-string ceiling, so the client threw before sending an admitted command. The prefix and payload are now separate HMAC updates, including the response proof.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): keep recovery fields when a status path exceeds the frame

A long current_file made the status reply miss the ceiling, and the fallback then dropped session_id and the completion receipts. The status now omits the path and version and still returns the session, connection proof, and up to 64 receipts. That required recovery frame is smaller than the 7464 floor.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): report an unknown path when status identity does not fit

A bounded status kept the new document generation and omitted the path, so the client filled in the descriptor's older path. The observed path is sent when it fits. When it does not, current_file is null and is not replaced with that stale path.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): count structured replies by their encoded JSON size

The response guard charged 16 bytes per primitive and two bytes per list slot, so a dense array under the configured ceiling was replaced with output_truncated. Numbers, booleans, null, and container punctuation now use their JSON lengths.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): stream authenticated responses in bounded chunks

A fitting reply was signed from retained raw bytes, escaped bytes, and a
joined frame, so a ceiling near 512 MiB could exhaust Cutter before send.
Measure and sign JSON pieces, then write the same frame in 64 KiB chunks.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(bridge): keep Cutter admission from stalling or hiding sessions

Read an unauthenticated frame off the accept loop. A command reply that
does not fit keeps completion and generation and reports an oversized path
as null. Discovery reports a ceiling mismatch instead of an absent session.
The maximum HMAC proof is opt-in, and both bridges reject non-ASCII digits.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): bound frame scans and client response copies

Search only newly read bytes for the framing LF. Unescape each socket
chunk into one response string, check the proof, and then parse it.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): keep completion, admission, and dense replies bounded

Report completed_connection only through connections that have
terminated. Cap connection threads and keep the listener up if one
fails to start. Batch scalar JSON and fail discovery when any ceiling
mismatches.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): hash requests in parts and scan escapes once

Update the client-proof prefix and request separately. Stop the response
decoder at the first quote or backslash instead of rescanning the tail.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cutter): confirm live ceiling mismatches and omitted output

A stale descriptor from a previous ceiling is not a discovery mismatch
until its hello proves a live authenticated bridge. A response discarded
for the frame ceiling after dispatch reports output_truncated.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(cutter): close the unauthenticated ceiling-mismatch fixture

The listener that fails the hello proof is destroyed after its challenge
so discovery cleanup does not wait on that socket.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-10-23 06:11:21 +08:00

369 lines
12 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import {
HopperCancelledError,
HopperProtocolError,
} from "../domain/hopperErrors.js";
import { ok } from "../domain/result.js";
import { HopperRequestQueue } from "./HopperRequestQueue.js";
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe("HopperRequestQueue deadlines", () => {
it("times out active callers while retaining the wire until the late reply", async () => {
vi.useFakeTimers();
const sent: number[] = [];
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
const result = vi.fn();
const pending = queue
.run(1, "analyze_function", {}, { timeoutMs: 25 })
.then(result);
const next = queue.run(2, "echo", {}, {});
await vi.advanceTimersByTimeAsync(25);
expect(result).toHaveBeenCalledWith({
ok: false,
error: expect.objectContaining({
_tag: "HopperTimeoutError",
timeoutMs: 25,
operation: "analyze_function",
requestId: 1,
providerState: "busy",
}),
});
expect(sent).toEqual([1]);
expect(queue.activity()).toMatchObject({
callerState: "cancelled",
queuedRequests: 1,
});
expect(vi.getTimerCount()).toBe(0);
expect(queue.accept(1, ok("late"))).toBe(true);
expect(sent).toEqual([1, 2]);
queue.accept(2, ok("next"));
await pending;
await expect(next).resolves.toEqual(ok("next"));
expect(result).toHaveBeenCalledTimes(1);
expect(queue.activity()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
});
it("expires a queued request without transmitting it", async () => {
vi.useFakeTimers();
const sent: number[] = [];
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
const active = queue.run(1, "active", {}, {});
const settled = vi.fn();
const queued = queue.run(2, "queued", {}, { timeoutMs: 10 }).then(settled);
await vi.advanceTimersByTimeAsync(10);
expect(settled).toHaveBeenCalledWith(
expect.objectContaining({
ok: false,
error: expect.objectContaining({
_tag: "HopperTimeoutError",
requestId: 2,
providerState: "not_started",
}),
}),
);
expect(queue.hasQueued(2)).toBe(false);
queue.accept(1, ok(null));
await Promise.all([active, queued]);
expect(sent).toEqual([1]);
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 remove = vi.spyOn(controller.signal, "removeEventListener");
const settled = vi.fn();
const pending = queue
.run(1, "echo", {}, { timeoutMs: 25, signal: controller.signal })
.then(settled);
queue.accept(1, ok(42));
controller.abort();
await vi.advanceTimersByTimeAsync(100);
await pending;
expect(settled).toHaveBeenCalledExactlyOnceWith(ok(42));
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
expect(vi.getTimerCount()).toBe(0);
});
it("keeps explicit 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 },
);
controller.abort();
await expect(pending).resolves.toMatchObject({
ok: false,
error: { cause: controller.signal.reason },
});
expect(vi.getTimerCount()).toBe(0);
queue.accept(1, ok(null));
await vi.advanceTimersByTimeAsync(100);
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();
},
},
},
);
await expect(pending).resolves.toMatchObject({
ok: false,
error: { cause: reason },
});
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.queuedCount()).toBe(0);
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 },
);
controller.abort();
await expect(queued).resolves.toMatchObject({
ok: false,
error: { _tag: "HopperCancelledError" },
});
await expect(
queue.run(
3,
"pre-aborted",
{},
{ timeoutMs: 100, signal: controller.signal },
),
).resolves.toMatchObject({
ok: false,
error: { _tag: "HopperCancelledError" },
});
expect(queue.queuedCount()).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 and settles only once if aborted afterward", 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();
const controller = new AbortController();
const settled = vi.fn();
const pending = queue
.run(2, "echo", {}, { timeoutMs: 10, signal: controller.signal })
.then(settled);
await vi.advanceTimersByTimeAsync(10);
controller.abort();
queue.accept(2, ok("late"));
await pending;
expect(settled).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
ok: false,
error: expect.objectContaining({ _tag: "HopperTimeoutError" }),
}),
);
expect(vi.getTimerCount()).toBe(0);
});
});
describe("Hopper deadlines before timer dispatch", () => {
it("does not transmit overdue queued work when the event loop delays its timer", 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, "active", {}, {});
const expired = queue.run(2, "set_comment", {}, { timeoutMs: 10 });
clock.mockReturnValue(20);
queue.accept(1, ok(null));
await expect(expired).resolves.toMatchObject({
ok: false,
error: {
_tag: "HopperTimeoutError",
operation: "set_comment",
providerState: "not_started",
},
});
await active;
expect(sent).toEqual([1]);
expect(queue.activity()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
});
it("accepts an overdue active reply without turning elapsed timeout into success", async () => {
vi.useFakeTimers();
const clock = vi.spyOn(performance, "now").mockReturnValue(0);
const sent: number[] = [];
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
const expired = queue.run(1, "active", {}, { timeoutMs: 10 });
const next = queue.run(2, "next", {}, {});
clock.mockReturnValue(20);
expect(queue.accept(1, ok("late"))).toBe(true);
await expect(expired).resolves.toMatchObject({
ok: false,
error: { _tag: "HopperTimeoutError" },
});
expect(sent).toEqual([1, 2]);
queue.accept(2, ok(null));
await next;
expect(queue.activity()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
});
});
describe("HopperRequestQueue caller abort reasons", () => {
const reason = { source: "caller", opaque: 7 };
it("retains an opaque reason for a signal aborted before admission", async () => {
const queue = new HopperRequestQueue(() => {});
const controller = new AbortController();
controller.abort(reason);
const result = await queue.run(
1,
"echo",
{},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error).toBeInstanceOf(HopperCancelledError);
expect(result.error.cause).toBe(reason);
});
it("retains an opaque reason when the active caller aborts", async () => {
const sent: number[] = [];
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
const controller = new AbortController();
const pending = queue.run(1, "echo", {}, { signal: controller.signal });
controller.abort(reason);
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error.cause).toBe(reason);
expect(sent).toEqual([1]);
expect(queue.accept(1, ok(null))).toBe(true);
expect(result.error.cause).toBe(reason);
expect(queue.activity()).toBeNull();
});
it("retains an opaque reason for a queued caller without transmitting it", async () => {
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", {}, { signal: controller.signal });
controller.abort(reason);
const result = await queued;
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error.cause).toBe(reason);
expect(queue.hasQueued(2)).toBe(false);
queue.accept(1, ok(null));
await active;
expect(sent).toEqual([1]);
});
});
it("does not hand a waiting request to the sender until it reaches the wire", async () => {
const sent: number[] = [];
const queue = new HopperRequestQueue(({ id }) => sent.push(id));
const active = queue.run(1, "active", { value: "A" }, {});
const queued = queue.run(2, "queued", { value: "B" }, {});
expect(sent).toEqual([1]);
expect(queue.queuedCount()).toBe(1);
queue.accept(1, ok(null));
expect(sent).toEqual([1, 2]);
queue.accept(2, ok(null));
await active;
await queued;
});