mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
feat(duplex): bound aggregate duplex route resource consumption with a process-owned byte ledger (#12003)
## Thinking Path > - Paperclip runs AI agents through adapters and sandboxed execution targets. > - Duplex routes retain bytes across route data, broker messages, decoder buffers, and readiness replay. > - Per-route limits bound each route but do not bound the total retained bytes across many routes. > - A process-owned ledger must charge each retained buffer before allocation and release the charge during cleanup. > - This pull request adds the aggregate ledger, connects it to host and sandbox duplex paths, and adds route coverage. > - The benefit is a fail-closed process-wide byte limit that keeps concurrent duplex work within a safe resource budget. ## Linked Issues or Issue Description **Subsystem affected** This change affects packages/adapter-utils and server duplex orchestration. **Problem or motivation** Many routes can each stay below their per-route limits while their combined retained bytes exceed a safe process budget. **Proposed solution** Add a process-owned aggregate byte ledger. Charge route data, broker bytes, decoder buffers, and readiness replay bytes before allocation. Release each charge during cleanup. Use a separate sandbox_process decoder cap for the in-sandbox path. **Alternatives considered** Keep only per-route limits. This does not bound the combined process use. Set a fixed limit at one call site. This misses retained bytes in other duplex paths. **Roadmap alignment** This is a tightly scoped reliability and resource-safety improvement. It does not duplicate a roadmap feature. **Additional context** The aggregate ceiling uses a safe 256 MiB default. An invalid override falls back to that default and reports the rejected value. ## What Changed - Add a process-owned aggregate byte ledger for duplex route resource use. - Charge and release route data, broker forward and response bytes, decoder buffers, and readiness replay bytes. - Bound host-to-worker pending writes and standard input transport bytes. - Add a separate decoder cap for the sandbox_process path. - Make invalid aggregate-ceiling overrides fall back to the safe default without host startup failure. - Add adapter-utils and server tests for charging, release, rejection, cleanup, and many-route aggregate limits. ## Verification - pnpm --filter @paperclipai/adapter-utils exec tsc --noEmit - pnpm --filter @paperclipai/server exec tsc --noEmit - Run the focused adapter-utils duplex ledger and execution-target tests. - Run the server aggregate-ledger route test. - Confirm all required pull request checks pass on this branch. ## Risks The ledger touches several duplex buffer paths. A missed release could reduce later capacity until process restart. The tests cover charge, release, rejection, cleanup, and route aggregation. The change uses a safe default when configuration input is invalid. ## Model Used OpenAI GPT-5 Codex. The runtime model ID and context window are not exposed to this task. The model used tool calls, shell commands, and code review workflow support. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with Fixes/Closes/Refs OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub issue references) - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
c5050396c7
commit
05b35d4669
23 files changed
+4087
-109
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES } from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { resolveDuplexAggregateCeilingBytesFromEnv } from "../duplex-aggregate-ceiling-env.js";
|
||||
|
||||
describe("resolveDuplexAggregateCeilingBytesFromEnv", () => {
|
||||
it("uses the safe default and reports nothing when the variable is absent", () => {
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv(undefined, onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES);
|
||||
expect(onRejectedOverride).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats a whitespace-only value as a present invalid override, not as absent", () => {
|
||||
const rawOverride = " ";
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
// The resolver must continue with the safe default. Startup does not fail.
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv(rawOverride, onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES);
|
||||
// The rejection reporter fires one time. A blank value is now visible as
|
||||
// invalid instead of silent as absent.
|
||||
expect(onRejectedOverride).toHaveBeenCalledTimes(1);
|
||||
// The reporter receives only the parsed number. The raw whitespace string
|
||||
// never reaches the reporter, so no operator-supplied text can reach a log
|
||||
// line.
|
||||
const reportedValue = onRejectedOverride.mock.calls[0]?.[0];
|
||||
expect(typeof reportedValue).toBe("number");
|
||||
expect(reportedValue).not.toBe(rawOverride);
|
||||
expect(Number.isFinite(reportedValue)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats an empty-string value as a present invalid override", () => {
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv("", onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES);
|
||||
expect(onRejectedOverride).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects a present non-numeric value and uses the safe default", () => {
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv("not-a-number", onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES);
|
||||
expect(onRejectedOverride).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("passes a valid override through unchanged", () => {
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv("1048576", onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(1048576);
|
||||
expect(onRejectedOverride).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a valid override that carries surrounding whitespace", () => {
|
||||
const onRejectedOverride = vi.fn();
|
||||
|
||||
const resolved = resolveDuplexAggregateCeilingBytesFromEnv(" 1048576 ", onRejectedOverride);
|
||||
|
||||
expect(resolved).toBe(1048576);
|
||||
expect(onRejectedOverride).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,11 @@ vi.mock("../services/plugin-environment-driver.js", async (importActual) => ({
|
||||
}));
|
||||
|
||||
import type { EffectiveSandboxCapabilities } from "@paperclipai/adapter-utils/execution-target";
|
||||
import { adapterExecutionTargetDuplexAggregateByteLedger } from "@paperclipai/adapter-utils/execution-target";
|
||||
import {
|
||||
DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES,
|
||||
DuplexAggregateByteLedger,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { createSshCommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/ssh";
|
||||
import type { Environment, EnvironmentLease } from "@paperclipai/shared";
|
||||
import { resolveEnvironmentExecutionTarget } from "../services/environment-execution-target.js";
|
||||
@@ -293,6 +298,50 @@ describe("EnvironmentRuntimeService.openDuplexChannel capability gate", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("sandbox execution target aggregate byte ledger stamp", () => {
|
||||
it("stamps the injected ledger on the target with object identity", async () => {
|
||||
const ledger = new DuplexAggregateByteLedger({
|
||||
ceilingBytes: DEFAULT_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES,
|
||||
});
|
||||
const target = await resolveEnvironmentExecutionTarget({
|
||||
db: {} as never,
|
||||
companyId: "company-1",
|
||||
adapterType: "codex_local",
|
||||
environment: { id: "env-1", driver: "sandbox", config: { provider: "daytona" } },
|
||||
leaseId: "lease-1",
|
||||
leaseMetadata: { remoteCwd: "/work" },
|
||||
lease: { id: "lease-1", leasePolicy: "reuse_by_environment" } as never,
|
||||
duplexAggregateByteLedger: ledger,
|
||||
});
|
||||
if (!target || target.kind !== "remote" || target.transport !== "sandbox") {
|
||||
throw new Error("expected a sandbox execution target");
|
||||
}
|
||||
// The stamped field and the accessor both return the one injected object, so
|
||||
// one process-owned ledger reaches the host bridge seam.
|
||||
expect(target.duplexAggregateByteLedger).toBe(ledger);
|
||||
expect(adapterExecutionTargetDuplexAggregateByteLedger(target)).toBe(ledger);
|
||||
});
|
||||
|
||||
it("leaves the ledger absent when the host injects none", async () => {
|
||||
const target = await resolveEnvironmentExecutionTarget({
|
||||
db: {} as never,
|
||||
companyId: "company-1",
|
||||
adapterType: "codex_local",
|
||||
environment: { id: "env-1", driver: "sandbox", config: { provider: "daytona" } },
|
||||
leaseId: "lease-1",
|
||||
leaseMetadata: { remoteCwd: "/work" },
|
||||
lease: { id: "lease-1", leasePolicy: "reuse_by_environment" } as never,
|
||||
});
|
||||
if (!target || target.kind !== "remote" || target.transport !== "sandbox") {
|
||||
throw new Error("expected a sandbox execution target");
|
||||
}
|
||||
// A run with no injected ledger keeps the seam null; the accessor never makes
|
||||
// a fresh ledger.
|
||||
expect(target.duplexAggregateByteLedger).toBeNull();
|
||||
expect(adapterExecutionTargetDuplexAggregateByteLedger(target)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Build a sandbox execution target with a fixed capability snapshot and a fake
|
||||
// environment runtime whose openDuplexChannel is a spy. The helper returns the
|
||||
// runner and the spy so a test reads the capability-gated member.
|
||||
|
||||
@@ -23,6 +23,18 @@
|
||||
// and never lets the exit crowd a data frame out of the pre-open hold.
|
||||
// - `echoInput`: when true, the fixture echoes each `duplexChannelWrite` back as
|
||||
// one data notification for the bound session.
|
||||
// - `writeReplyDelayMs`: when a positive number, the fixture delays each
|
||||
// `duplexChannelWrite` reply by that many milliseconds, so a test proves the
|
||||
// host holds the pending-write reservation until the RPC settles.
|
||||
// - `stopReadingStdinAfterOpen`: when true, the fixture stops reading its stdin
|
||||
// right after it sends the open reply. The host writes then stay in the host
|
||||
// stdin write buffer, so a test proves the host meters the transport buffer and
|
||||
// never releases the transport token on the write-RPC timeout.
|
||||
// - `exitAfterStopMs`: when a positive number, and the fixture stopped reading
|
||||
// stdin, the fixture exits after that many milliseconds. The worker exit
|
||||
// discards the stdin buffer, so a test proves the host releases every held
|
||||
// transport token on the worker exit. It gives a fast exit for a worker that no
|
||||
// longer reads its stdin and never sees the shutdown request.
|
||||
// - `closeMode`: "ack" | "bad-ack" | "no-ack" (default "ack"). It controls the
|
||||
// close reply, so a test proves the host retires the worker on an unconfirmed
|
||||
// close.
|
||||
@@ -134,6 +146,8 @@ rl.on("line", (line) => {
|
||||
closeMode,
|
||||
echoInput: directive.echoInput === true,
|
||||
noWriteReply: mode === "no-write-reply",
|
||||
writeReplyDelayMs:
|
||||
typeof directive.writeReplyDelayMs === "number" ? directive.writeReplyDelayMs : 0,
|
||||
emitAfterCloseChunk:
|
||||
typeof directive.emitAfterCloseChunk === "string" ? directive.emitAfterCloseChunk : null,
|
||||
});
|
||||
@@ -170,6 +184,20 @@ rl.on("line", (line) => {
|
||||
reply();
|
||||
}
|
||||
|
||||
if (directive.stopReadingStdinAfterOpen === true) {
|
||||
// Stop reading stdin, so every later host write stays in the host stdin
|
||||
// write buffer. The host meters the transport buffer and holds the transport
|
||||
// token until the stream flush, the stream error, or the worker exit.
|
||||
rl.pause();
|
||||
process.stdin.pause();
|
||||
if (typeof directive.exitAfterStopMs === "number" && directive.exitAfterStopMs >= 0) {
|
||||
// Exit after the delay, so a test observes the worker exit release the held
|
||||
// transport tokens without a slow shutdown drain on an unread stdin.
|
||||
setTimeout(() => process.exit(0), directive.exitAfterStopMs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit the scripted data and the exit after the open reply, so the host
|
||||
// binds the route first. Each frame echoes the exact pair; a test overrides
|
||||
// `sid` or `rid` to force a mismatch.
|
||||
@@ -205,7 +233,14 @@ rl.on("line", (line) => {
|
||||
},
|
||||
});
|
||||
}
|
||||
send({ jsonrpc: "2.0", id: message.id, result: null });
|
||||
const replyWrite = () => send({ jsonrpc: "2.0", id: message.id, result: null });
|
||||
if (entry.writeReplyDelayMs > 0) {
|
||||
// Delay the write reply, so the host holds the pending-write reservation for
|
||||
// a measurable time before the RPC settles.
|
||||
setTimeout(replyWrite, entry.writeReplyDelayMs);
|
||||
} else {
|
||||
replyWrite();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
||||
import {
|
||||
DuplexAggregateByteLedger,
|
||||
type DuplexAggregateByteLedgerTelemetry,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import {
|
||||
createDuplexRouteSlotController,
|
||||
createPluginWorkerHandle,
|
||||
} from "../services/plugin-worker-manager.js";
|
||||
|
||||
// This suite proves the plugin worker manager charges every retained duplex route
|
||||
// representation against the injected aggregate byte ledger, and releases each
|
||||
// token exactly once through the one cleanup path. The tests drive a real worker
|
||||
// fixture process, so they exercise the true frame order across the bind boundary.
|
||||
|
||||
const FIXTURES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures");
|
||||
const DUPLEX_CHANNEL_WORKER_ENTRYPOINT = path.join(
|
||||
FIXTURES_DIR,
|
||||
"plugin-worker-duplex-channel.cjs",
|
||||
);
|
||||
|
||||
const TEST_MANIFEST: PaperclipPluginManifestV1 = {
|
||||
id: "test.plugin",
|
||||
apiVersion: 1,
|
||||
version: "1.0.0",
|
||||
displayName: "Test plugin",
|
||||
description: "Test plugin",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: [],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
};
|
||||
|
||||
function makeDuplexHandle(extra?: Record<string, unknown>) {
|
||||
return createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: DUPLEX_CHANNEL_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: { instanceId: "instance-1", hostVersion: "1.0.0" },
|
||||
apiVersion: 1,
|
||||
hostHandlers: {},
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
// The test directive rides in `providerLeaseId`, an opaque field the manager
|
||||
// forwards to the worker unchanged.
|
||||
function duplexOpenInput(directive: unknown, companyId = "company-1") {
|
||||
return {
|
||||
driverKey: "daytona",
|
||||
companyId,
|
||||
environmentId: "env-1",
|
||||
providerLeaseId: JSON.stringify(directive),
|
||||
command: "bridge-callback",
|
||||
};
|
||||
}
|
||||
|
||||
// A counting telemetry surface. It records how many times the ledger rejected a
|
||||
// reservation and how many accounting defects it saw, so a test asserts a
|
||||
// fail-closed rejection and proves the cleanup never double-releases.
|
||||
function countingTelemetry(): DuplexAggregateByteLedgerTelemetry & {
|
||||
rejections: number;
|
||||
underflows: number;
|
||||
} {
|
||||
const state = {
|
||||
rejections: 0,
|
||||
underflows: 0,
|
||||
setBytesInUse() {},
|
||||
recordReservationRejection() {
|
||||
state.rejections += 1;
|
||||
},
|
||||
recordAccountingUnderflow() {
|
||||
state.underflows += 1;
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
describe("plugin worker manager duplex aggregate byte ledger", () => {
|
||||
it("keeps terminalized buffered bytes charged until a late listener drains them, then a worker exit is harmless", async () => {
|
||||
const telemetry = countingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
// Lower the per-chunk char bound, so the second chunk ends the route while the
|
||||
// first chunk stays buffered.
|
||||
const handle = makeDuplexHandle({
|
||||
duplexAggregateByteLedger: ledger,
|
||||
duplexChannelLimits: { maxChunkChars: 4 },
|
||||
});
|
||||
try {
|
||||
await handle.start();
|
||||
const session = await handle.openDuplexChannel(
|
||||
// No listener attaches, so "ok" buffers and charges its two raw bytes. The
|
||||
// "toolong" chunk passes the per-chunk bound, so the route terminalizes and
|
||||
// moves the still-buffered "ok" token to the terminal registry.
|
||||
duplexOpenInput({ data: [{ chunk: "ok" }, { chunk: "toolong" }] }),
|
||||
);
|
||||
// The buffered "ok" stays charged after the route leaves the live map.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(2);
|
||||
expect(ledger.liveTokenCount).toBe(1);
|
||||
});
|
||||
// A late listener drains the terminal buffered record and releases its token.
|
||||
const chunks: string[] = [];
|
||||
session.onData((chunk) => chunks.push(chunk));
|
||||
await vi.waitFor(() => {
|
||||
expect(chunks).toEqual(["ok"]);
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
// The over-bound chunk retained nothing, so no reservation ever rejected.
|
||||
expect(telemetry.rejections).toBe(0);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
// The worker exit sweep runs on stop. The ledger stays at zero, and the sweep
|
||||
// records no accounting defect, so the drain and the exit never double-release.
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("transfers pre-bind held bytes to the buffered representation across the bind, then releases them on drain", async () => {
|
||||
const telemetry = countingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
const session = await handle.openDuplexChannel(
|
||||
// The worker writes the open reply and the two data frames in one stdout
|
||||
// write, so both frames arrive before the route binds. The host holds them
|
||||
// as pre-bind events, then the bind replays and transfers each token to the
|
||||
// buffered representation.
|
||||
duplexOpenInput({ batchWithOpenReply: true, data: [{ chunk: "aa" }, { chunk: "bb" }] }),
|
||||
);
|
||||
// The two held events keep their exact reserved bytes across the transfer, so
|
||||
// the live-token count never grows and the gauge never re-admits.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(4);
|
||||
expect(ledger.liveTokenCount).toBe(2);
|
||||
});
|
||||
const chunks: string[] = [];
|
||||
session.onData((chunk) => chunks.push(chunk));
|
||||
await vi.waitFor(() => {
|
||||
expect(chunks).toEqual(["aa", "bb"]);
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("fails closed and retains nothing when a buffered reservation would pass the ceiling", async () => {
|
||||
const telemetry = countingTelemetry();
|
||||
// A four-byte ceiling. One five-byte chunk cannot fit.
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 4, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
await handle.openDuplexChannel(
|
||||
// No listener attaches, so "hello" tries to buffer. Its five raw bytes pass
|
||||
// the four-byte ceiling, so the reservation rejects and the route ends.
|
||||
duplexOpenInput({ data: [{ chunk: "hello" }] }),
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(telemetry.rejections).toBeGreaterThanOrEqual(1);
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// A telemetry surface that also tracks the peak gauge value. A test asserts the
|
||||
// peak never passes the ceiling, so it proves aggregate admission stops at the
|
||||
// ceiling instead of overshooting it.
|
||||
function peakTrackingTelemetry(): DuplexAggregateByteLedgerTelemetry & {
|
||||
gauge: number;
|
||||
peak: number;
|
||||
rejections: number;
|
||||
underflows: number;
|
||||
} {
|
||||
const state = {
|
||||
gauge: 0,
|
||||
peak: 0,
|
||||
rejections: 0,
|
||||
underflows: 0,
|
||||
setBytesInUse(bytes: number) {
|
||||
state.gauge = bytes;
|
||||
if (bytes > state.peak) state.peak = bytes;
|
||||
},
|
||||
recordReservationRejection() {
|
||||
state.rejections += 1;
|
||||
},
|
||||
recordAccountingUnderflow() {
|
||||
state.underflows += 1;
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
// The exact raw byte count of one buffered chunk each route retains.
|
||||
const LOAD_CHUNK_BYTES = 8;
|
||||
const LOAD_CHUNK = "x".repeat(LOAD_CHUNK_BYTES);
|
||||
|
||||
describe("plugin worker manager duplex aggregate byte ledger load across workers", () => {
|
||||
it("stops aggregate byte admission at the ceiling across many routes and workers while the route-count controller stays open", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
// The ceiling holds exactly six eight-byte buffered chunks.
|
||||
const fittingRoutes = 6;
|
||||
const ceilingBytes = fittingRoutes * LOAD_CHUNK_BYTES;
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes, telemetry });
|
||||
// The route-count controller has ample room, so the byte ledger binds first.
|
||||
const routeSlots = createDuplexRouteSlotController(100);
|
||||
const handleCount = 3;
|
||||
const routesPerHandle = 3;
|
||||
const totalRoutes = handleCount * routesPerHandle;
|
||||
const rejectedRoutes = totalRoutes - fittingRoutes;
|
||||
const handles: Array<ReturnType<typeof makeDuplexHandle>> = [];
|
||||
try {
|
||||
for (let h = 0; h < handleCount; h += 1) {
|
||||
const handle = makeDuplexHandle({
|
||||
duplexAggregateByteLedger: ledger,
|
||||
duplexRouteSlots: routeSlots,
|
||||
});
|
||||
await handle.start();
|
||||
handles.push(handle);
|
||||
}
|
||||
// Open every route in order. Each worker batches one data chunk with the open
|
||||
// reply, so the host holds the chunk as a pre-bind event and reserves its exact
|
||||
// raw bytes before the route binds. No listener attaches, so a bound route holds
|
||||
// the chunk. The first six chunks fit the ceiling. Each later reservation passes
|
||||
// the ceiling, so the ledger rejects it and the route fails closed with the open
|
||||
// marker (not the route-busy marker), because the route-count controller has room.
|
||||
let opened = 0;
|
||||
let failedClosed = 0;
|
||||
for (let h = 0; h < handleCount; h += 1) {
|
||||
for (let r = 0; r < routesPerHandle; r += 1) {
|
||||
try {
|
||||
await handles[h].openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: `ws-${h}-${r}`,
|
||||
batchWithOpenReply: true,
|
||||
data: [{ chunk: LOAD_CHUNK }],
|
||||
}),
|
||||
);
|
||||
opened += 1;
|
||||
} catch (err) {
|
||||
// A byte-ceiling rejection fails the route closed with the open marker.
|
||||
// The route-count controller had room, so this is never the route-busy
|
||||
// marker.
|
||||
expect(String(err)).toContain("DUPLEX_CHANNEL_OPEN_FAILED");
|
||||
expect(String(err)).not.toContain("DUPLEX_CHANNEL_ROUTE_BUSY");
|
||||
failedClosed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Six routes bound and hold their bytes; three failed closed at the ceiling.
|
||||
expect(opened).toBe(fittingRoutes);
|
||||
expect(failedClosed).toBe(rejectedRoutes);
|
||||
expect(opened + failedClosed).toBe(totalRoutes);
|
||||
// The aggregate gauge holds at the ceiling and the ledger recorded one rejection
|
||||
// per over-ceiling route.
|
||||
await vi.waitFor(() => {
|
||||
expect(telemetry.rejections).toBe(rejectedRoutes);
|
||||
expect(ledger.bytesInUse).toBe(ceilingBytes);
|
||||
expect(ledger.liveTokenCount).toBe(fittingRoutes);
|
||||
});
|
||||
// The gauge never passed the ceiling, so admission stopped at the ceiling and
|
||||
// never overshot it.
|
||||
expect(telemetry.peak).toBe(ceilingBytes);
|
||||
} finally {
|
||||
for (const handle of handles) await handle.stop().catch(() => undefined);
|
||||
}
|
||||
// Every worker exit sweep released its buffered tokens once, so the ledger ends
|
||||
// at zero with no accounting defect.
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("still bounds the route count for fixed per-route overhead when the byte ceiling has ample room", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
// A large byte ceiling, so retained bytes never bind admission.
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
// The route-count controller holds two slots for the whole process.
|
||||
const routeSlots = createDuplexRouteSlotController(2);
|
||||
const handleA = makeDuplexHandle({
|
||||
duplexAggregateByteLedger: ledger,
|
||||
duplexRouteSlots: routeSlots,
|
||||
});
|
||||
const handleB = makeDuplexHandle({
|
||||
duplexAggregateByteLedger: ledger,
|
||||
duplexRouteSlots: routeSlots,
|
||||
});
|
||||
let opened = 0;
|
||||
let busy = 0;
|
||||
try {
|
||||
await handleA.start();
|
||||
await handleB.start();
|
||||
// Attempt four routes across the two workers. The shared controller admits the
|
||||
// first two and rejects the last two with the fixed route-busy error.
|
||||
const attempts: Array<[ReturnType<typeof makeDuplexHandle>, string]> = [
|
||||
[handleA, "ws-a1"],
|
||||
[handleA, "ws-a2"],
|
||||
[handleB, "ws-b1"],
|
||||
[handleB, "ws-b2"],
|
||||
];
|
||||
for (const [handle, ws] of attempts) {
|
||||
try {
|
||||
await handle.openDuplexChannel(
|
||||
duplexOpenInput({ workerSessionId: ws, data: [{ chunk: "aa" }] }),
|
||||
);
|
||||
opened += 1;
|
||||
} catch (err) {
|
||||
expect(String(err)).toContain("DUPLEX_CHANNEL_ROUTE_BUSY");
|
||||
busy += 1;
|
||||
}
|
||||
}
|
||||
// The route-count controller admitted two routes and rejected the rest, so it
|
||||
// still bounds the fixed per-route overhead on its own.
|
||||
expect(opened).toBe(2);
|
||||
expect(busy).toBe(2);
|
||||
// The two open routes buffered four raw bytes, far under the byte ceiling, and
|
||||
// the byte ledger rejected nothing.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(4);
|
||||
expect(ledger.liveTokenCount).toBe(2);
|
||||
});
|
||||
expect(telemetry.rejections).toBe(0);
|
||||
} finally {
|
||||
await handleA.stop().catch(() => undefined);
|
||||
await handleB.stop().catch(() => undefined);
|
||||
}
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
||||
import {
|
||||
DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED,
|
||||
DuplexAggregateByteLedger,
|
||||
type DuplexAggregateByteLedgerTelemetry,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
|
||||
// Mock the shared logger, so a test reads the fixed rejection marker the manager
|
||||
// logs when a pending-write reservation fails. The child logger returns the same
|
||||
// object, so `log.warn` is this mock's `warn`.
|
||||
vi.mock("../middleware/logger.js", () => {
|
||||
const mockLogger: Record<string, unknown> = {
|
||||
trace: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
fatal: vi.fn(),
|
||||
child: vi.fn(() => mockLogger),
|
||||
};
|
||||
return { logger: mockLogger, httpLogger: vi.fn() };
|
||||
});
|
||||
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { createPluginWorkerHandle } from "../services/plugin-worker-manager.js";
|
||||
|
||||
// This suite proves the plugin worker manager charges every host→worker write raw
|
||||
// payload against the injected aggregate byte ledger under the `pending_write`
|
||||
// owner, and releases each token one time when the write RPC settles. The child
|
||||
// reads its stdin here, so the separate `stdin_write` transport token flushes and
|
||||
// releases at once. Each test waits for that flush, so the assertions isolate the
|
||||
// raw-payload token. The transport token has its own suite.
|
||||
|
||||
const FIXTURES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures");
|
||||
const DUPLEX_CHANNEL_WORKER_ENTRYPOINT = path.join(
|
||||
FIXTURES_DIR,
|
||||
"plugin-worker-duplex-channel.cjs",
|
||||
);
|
||||
|
||||
const TEST_MANIFEST: PaperclipPluginManifestV1 = {
|
||||
id: "test.plugin",
|
||||
apiVersion: 1,
|
||||
version: "1.0.0",
|
||||
displayName: "Test plugin",
|
||||
description: "Test plugin",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: [],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
};
|
||||
|
||||
function makeDuplexHandle(extra?: Record<string, unknown>) {
|
||||
return createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: DUPLEX_CHANNEL_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: { instanceId: "instance-1", hostVersion: "1.0.0" },
|
||||
apiVersion: 1,
|
||||
hostHandlers: {},
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
// The test directive rides in `providerLeaseId`, an opaque field the manager
|
||||
// forwards to the worker unchanged.
|
||||
function duplexOpenInput(directive: unknown, companyId = "company-1") {
|
||||
return {
|
||||
driverKey: "daytona",
|
||||
companyId,
|
||||
environmentId: "env-1",
|
||||
providerLeaseId: JSON.stringify(directive),
|
||||
command: "bridge-callback",
|
||||
};
|
||||
}
|
||||
|
||||
// A telemetry surface that tracks the peak gauge value and the two counters. A
|
||||
// test asserts the peak never passes the ceiling, so it proves aggregate admission
|
||||
// stops at the ceiling instead of overshooting it.
|
||||
function peakTrackingTelemetry(): DuplexAggregateByteLedgerTelemetry & {
|
||||
gauge: number;
|
||||
peak: number;
|
||||
rejections: number;
|
||||
underflows: number;
|
||||
} {
|
||||
const state = {
|
||||
gauge: 0,
|
||||
peak: 0,
|
||||
rejections: 0,
|
||||
underflows: 0,
|
||||
setBytesInUse(bytes: number) {
|
||||
state.gauge = bytes;
|
||||
if (bytes > state.peak) state.peak = bytes;
|
||||
},
|
||||
recordReservationRejection() {
|
||||
state.rejections += 1;
|
||||
},
|
||||
recordAccountingUnderflow() {
|
||||
state.underflows += 1;
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
// Return every reason string the manager logged through the mock `warn` sink.
|
||||
function loggedWarnReasons(): string[] {
|
||||
const calls = (logger.warn as unknown as { mock: { calls: unknown[][] } }).mock.calls;
|
||||
return calls
|
||||
.map((call) => {
|
||||
const first = call[0];
|
||||
return first && typeof first === "object"
|
||||
? (first as { reason?: unknown }).reason
|
||||
: undefined;
|
||||
})
|
||||
.filter((reason): reason is string => typeof reason === "string");
|
||||
}
|
||||
|
||||
describe("plugin worker manager duplex pending-write byte ledger", () => {
|
||||
it("charges each held raw payload and returns to zero after worker exit", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
// The ceiling has ample room, so a transient transport reservation never
|
||||
// rejects. Each write holds its raw payload until the RPC settles.
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
const writeBytes = 1000;
|
||||
const writeData = "x".repeat(writeBytes);
|
||||
try {
|
||||
await handle.start();
|
||||
// The worker reads its stdin but never replies to a write, so each write RPC
|
||||
// stays pending and holds its raw payload.
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({ workerSessionId: "ws-a", mode: "no-write-reply" }),
|
||||
);
|
||||
route.write(writeData);
|
||||
route.write(writeData);
|
||||
route.write(writeData);
|
||||
// The worker reads its stdin, so each transport token flushes and releases.
|
||||
// Only the three held raw payloads remain, so the gauge settles at three
|
||||
// times the payload byte count with three live tokens.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.liveTokenCount).toBe(3);
|
||||
expect(ledger.bytesInUse).toBe(3 * writeBytes);
|
||||
});
|
||||
expect(telemetry.peak).toBeLessThanOrEqual(ledger.ceilingBytes);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
// The worker exit settles each pending write, so each token releases one time
|
||||
// and the ledger ends at zero with no accounting defect.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("releases the raw-payload token after a delayed write RPC settles, with no worker exit", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
// The worker reads its stdin and delays its write reply, so the host holds the
|
||||
// raw-payload reservation for a measurable time before the RPC settles.
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({ workerSessionId: "ws-d", writeReplyDelayMs: 150 }),
|
||||
);
|
||||
const writeBytes = 1000;
|
||||
route.write("x".repeat(writeBytes));
|
||||
// The transport token flushes at once, so one raw-payload token stays held for
|
||||
// the full write byte count while the RPC is in flight.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.liveTokenCount).toBe(1);
|
||||
expect(ledger.bytesInUse).toBe(writeBytes);
|
||||
});
|
||||
// The delayed reply settles the RPC, and the `finally` releases the token.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("reserves the exact UTF-8 byte count of the raw payload, not the character length", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 1 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({ workerSessionId: "ws-u", mode: "no-write-reply" }),
|
||||
);
|
||||
// "a€" is two characters but four UTF-8 bytes (one plus three). The raw-payload
|
||||
// reservation must charge four bytes, so it uses the UTF-8 byte count.
|
||||
const data = "a€";
|
||||
expect(data.length).toBe(2);
|
||||
expect(Buffer.byteLength(data, "utf8")).toBe(4);
|
||||
route.write(data);
|
||||
// The transport token flushes, so one raw-payload token of four bytes remains.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.liveTokenCount).toBe(1);
|
||||
expect(ledger.bytesInUse).toBe(4);
|
||||
});
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("ends an over-ceiling single write fail-closed with the aggregate marker, not the route-busy marker", async () => {
|
||||
vi.mocked(logger.warn).mockClear();
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
// The ceiling is smaller than one raw payload, so the raw-payload reservation
|
||||
// fails before the frame reaches the transport. The manager retains nothing.
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 100, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({ workerSessionId: "ws-o", mode: "no-write-reply" }),
|
||||
);
|
||||
// The single write is larger than the ceiling. The raw-payload reservation
|
||||
// fails, so the manager ends the route with the aggregate marker, never the
|
||||
// route-busy marker, and never writes the frame.
|
||||
route.write("x".repeat(200));
|
||||
expect(telemetry.rejections).toBeGreaterThanOrEqual(1);
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(telemetry.peak).toBeLessThanOrEqual(ledger.ceilingBytes);
|
||||
const reasons = loggedWarnReasons();
|
||||
expect(reasons).toContain(DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED);
|
||||
expect(reasons).not.toContain("DUPLEX_CHANNEL_ROUTE_BUSY");
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
||||
import {
|
||||
DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED,
|
||||
DuplexAggregateByteLedger,
|
||||
type DuplexAggregateByteLedgerTelemetry,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
|
||||
// Mock the shared logger, so a test reads the fixed rejection marker the manager
|
||||
// logs when a transport reservation fails. The child logger returns the same
|
||||
// object, so `log.warn` is this mock's `warn`.
|
||||
vi.mock("../middleware/logger.js", () => {
|
||||
const mockLogger: Record<string, unknown> = {
|
||||
trace: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
fatal: vi.fn(),
|
||||
child: vi.fn(() => mockLogger),
|
||||
};
|
||||
return { logger: mockLogger, httpLogger: vi.fn() };
|
||||
});
|
||||
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { createPluginWorkerHandle } from "../services/plugin-worker-manager.js";
|
||||
|
||||
// This suite proves the plugin worker manager charges the child-stdin transport
|
||||
// buffer for every host→worker duplex write, under the `stdin_write` owner. The
|
||||
// worker completes the open, then stops reading its stdin. The host write then
|
||||
// stays in the host stdin write buffer. The tests prove the reservation covers the
|
||||
// serialized frame, holds until the flush or the worker exit, survives the write
|
||||
// RPC timeout and the route terminalization, and bounds the aggregate transport
|
||||
// bytes across several routes and workers.
|
||||
|
||||
const FIXTURES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures");
|
||||
const DUPLEX_CHANNEL_WORKER_ENTRYPOINT = path.join(
|
||||
FIXTURES_DIR,
|
||||
"plugin-worker-duplex-channel.cjs",
|
||||
);
|
||||
|
||||
const TEST_MANIFEST: PaperclipPluginManifestV1 = {
|
||||
id: "test.plugin",
|
||||
apiVersion: 1,
|
||||
version: "1.0.0",
|
||||
displayName: "Test plugin",
|
||||
description: "Test plugin",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: [],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
};
|
||||
|
||||
function makeDuplexHandle(extra?: Record<string, unknown>) {
|
||||
return createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: DUPLEX_CHANNEL_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: { instanceId: "instance-1", hostVersion: "1.0.0" },
|
||||
apiVersion: 1,
|
||||
hostHandlers: {},
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
// The test directive rides in `providerLeaseId`, an opaque field the manager
|
||||
// forwards to the worker unchanged.
|
||||
function duplexOpenInput(directive: unknown, companyId = "company-1") {
|
||||
return {
|
||||
driverKey: "daytona",
|
||||
companyId,
|
||||
environmentId: "env-1",
|
||||
providerLeaseId: JSON.stringify(directive),
|
||||
command: "bridge-callback",
|
||||
};
|
||||
}
|
||||
|
||||
// A telemetry surface that tracks the peak gauge value and the two counters. A
|
||||
// test asserts the peak never passes the ceiling, so it proves aggregate admission
|
||||
// stops at the ceiling instead of overshooting it.
|
||||
function peakTrackingTelemetry(): DuplexAggregateByteLedgerTelemetry & {
|
||||
gauge: number;
|
||||
peak: number;
|
||||
rejections: number;
|
||||
underflows: number;
|
||||
} {
|
||||
const state = {
|
||||
gauge: 0,
|
||||
peak: 0,
|
||||
rejections: 0,
|
||||
underflows: 0,
|
||||
setBytesInUse(bytes: number) {
|
||||
state.gauge = bytes;
|
||||
if (bytes > state.peak) state.peak = bytes;
|
||||
},
|
||||
recordReservationRejection() {
|
||||
state.rejections += 1;
|
||||
},
|
||||
recordAccountingUnderflow() {
|
||||
state.underflows += 1;
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
// Return every reason string the manager logged through the mock `warn` sink.
|
||||
function loggedWarnReasons(): string[] {
|
||||
const calls = (logger.warn as unknown as { mock: { calls: unknown[][] } }).mock.calls;
|
||||
return calls
|
||||
.map((call) => {
|
||||
const first = call[0];
|
||||
return first && typeof first === "object"
|
||||
? (first as { reason?: unknown }).reason
|
||||
: undefined;
|
||||
})
|
||||
.filter((reason): reason is string => typeof reason === "string");
|
||||
}
|
||||
|
||||
// A frame the host keeps in its stdin write buffer must pass the operating-system
|
||||
// pipe buffer (about 64 KiB), so the write callback stays pending while the child
|
||||
// does not read. Each write here is larger than that, so the host holds the
|
||||
// transport token until the worker exit.
|
||||
const HELD_WRITE_CHARS = 200_000;
|
||||
|
||||
describe("plugin worker manager duplex stdin transport byte ledger", () => {
|
||||
it("reserves the encoded serialized-frame size, larger than the raw payload, including JSON escaping", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 8 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: "ws-a",
|
||||
stopReadingStdinAfterOpen: true,
|
||||
exitAfterStopMs: 500,
|
||||
}),
|
||||
);
|
||||
// Every character is a quote. The JSON serialization escapes each quote to two
|
||||
// bytes, so the serialized frame is at least twice the raw payload byte count.
|
||||
const data = '"'.repeat(50_000);
|
||||
const rawBytes = Buffer.byteLength(data, "utf8");
|
||||
route.write(data);
|
||||
// The raw-payload token and the transport token both hold at once. The worker
|
||||
// does not read its stdin, so the transport token never flushes.
|
||||
expect(ledger.liveTokenCount).toBe(2);
|
||||
const transportBytes = ledger.bytesInUse - rawBytes;
|
||||
// The transport reservation covers the serialized frame, so it is larger than
|
||||
// the raw payload and it includes the doubled escaped quotes.
|
||||
expect(transportBytes).toBeGreaterThan(rawBytes);
|
||||
expect(transportBytes).toBeGreaterThanOrEqual(2 * rawBytes);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
// The worker exit discards the stdin buffer, so every token releases one time.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("holds the transport token across a write-RPC timeout and releases it on worker exit", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 8 << 20, telemetry });
|
||||
// The write RPC times out fast; the worker exits later. The gap lets a test
|
||||
// prove the timeout does not release the transport token.
|
||||
const handle = makeDuplexHandle({
|
||||
duplexAggregateByteLedger: ledger,
|
||||
duplexChannelLimits: { openTimeoutMs: 150 },
|
||||
});
|
||||
try {
|
||||
await handle.start();
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: "ws-t",
|
||||
stopReadingStdinAfterOpen: true,
|
||||
exitAfterStopMs: 900,
|
||||
}),
|
||||
);
|
||||
const data = "x".repeat(HELD_WRITE_CHARS);
|
||||
const rawBytes = Buffer.byteLength(data, "utf8");
|
||||
route.write(data);
|
||||
// Both tokens hold at first: the raw payload and the serialized frame.
|
||||
expect(ledger.liveTokenCount).toBe(2);
|
||||
const transportBytes = ledger.bytesInUse - rawBytes;
|
||||
expect(transportBytes).toBeGreaterThan(0);
|
||||
// The write RPC times out. The RPC settle releases the raw-payload token, so
|
||||
// one token remains: the transport token. The timeout never releases it.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.liveTokenCount).toBe(1);
|
||||
});
|
||||
expect(ledger.bytesInUse).toBe(transportBytes);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
// The worker exit releases the still-held transport token.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("does not release the transport token when the route terminalizes", async () => {
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 8 << 20, telemetry });
|
||||
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handle.start();
|
||||
const route = await handle.openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: "ws-c",
|
||||
stopReadingStdinAfterOpen: true,
|
||||
exitAfterStopMs: 700,
|
||||
}),
|
||||
);
|
||||
const data = "x".repeat(HELD_WRITE_CHARS);
|
||||
const rawBytes = Buffer.byteLength(data, "utf8");
|
||||
route.write(data);
|
||||
expect(ledger.liveTokenCount).toBe(2);
|
||||
const transportBytes = ledger.bytesInUse - rawBytes;
|
||||
// End the route. Route terminalization releases the route-owned tokens, but it
|
||||
// must never release the transport token, so at least the serialized frame
|
||||
// stays charged.
|
||||
void route.close();
|
||||
expect(ledger.bytesInUse).toBeGreaterThanOrEqual(transportBytes);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
|
||||
it("bounds the aggregate transport bytes across several routes and workers, ending an over-ceiling near-limit write with the aggregate marker", async () => {
|
||||
vi.mocked(logger.warn).mockClear();
|
||||
const telemetry = peakTrackingTelemetry();
|
||||
// The ceiling admits only a couple of held serialized frames, so a near-limit
|
||||
// write across the routes passes it and rejects.
|
||||
const ceilingBytes = 600_000;
|
||||
const ledger = new DuplexAggregateByteLedger({ ceilingBytes, telemetry });
|
||||
const handleA = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
const handleB = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
|
||||
try {
|
||||
await handleA.start();
|
||||
await handleB.start();
|
||||
const routeA = await handleA.openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: "ws-a",
|
||||
stopReadingStdinAfterOpen: true,
|
||||
exitAfterStopMs: 900,
|
||||
}),
|
||||
);
|
||||
const routeB = await handleB.openDuplexChannel(
|
||||
duplexOpenInput({
|
||||
workerSessionId: "ws-b",
|
||||
stopReadingStdinAfterOpen: true,
|
||||
exitAfterStopMs: 900,
|
||||
}),
|
||||
);
|
||||
// Each write mixes escaped quotes and multi-byte characters near the per-write
|
||||
// size. The serialized frame escapes each quote and keeps each euro sign as
|
||||
// three UTF-8 bytes, so the reservation must count the encoded size.
|
||||
const escaped = '"'.repeat(40_000);
|
||||
const multiByte = "€".repeat(20_000);
|
||||
const nearLimit = escaped + multiByte;
|
||||
const routes = [routeA, routeB, routeA, routeB];
|
||||
for (const route of routes) {
|
||||
route.write(nearLimit);
|
||||
// The aggregate bytes never pass the ceiling. Admission stops at the ceiling.
|
||||
expect(ledger.bytesInUse).toBeLessThanOrEqual(ceilingBytes);
|
||||
}
|
||||
// At least one near-limit write passed the ceiling and rejected. The manager
|
||||
// ended that route with the aggregate marker, never the route-busy marker.
|
||||
expect(telemetry.rejections).toBeGreaterThanOrEqual(1);
|
||||
expect(telemetry.peak).toBeLessThanOrEqual(ceilingBytes);
|
||||
const reasons = loggedWarnReasons();
|
||||
expect(reasons).toContain(DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED);
|
||||
expect(reasons).not.toContain("DUPLEX_CHANNEL_ROUTE_BUSY");
|
||||
} finally {
|
||||
await handleA.stop().catch(() => undefined);
|
||||
await handleB.stop().catch(() => undefined);
|
||||
}
|
||||
// Every worker exit releases its held transport tokens, so the ledger ends at
|
||||
// zero with no accounting defect.
|
||||
await vi.waitFor(() => {
|
||||
expect(ledger.bytesInUse).toBe(0);
|
||||
expect(ledger.liveTokenCount).toBe(0);
|
||||
});
|
||||
expect(telemetry.underflows).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
resolveDuplexAggregateCeilingBytes,
|
||||
type DuplexAggregateCeilingOverrideRejectionReporter,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
|
||||
/**
|
||||
* Resolve the aggregate duplex route byte ceiling from the raw operator override
|
||||
* string. The host reads the override from
|
||||
* PAPERCLIP_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES.
|
||||
*
|
||||
* This helper distinguishes an absent variable from a present blank value. An
|
||||
* absent variable is `undefined`. The helper then uses the documented default and
|
||||
* does not report a rejection. A present variable is a string, even when the
|
||||
* string holds only whitespace. The helper sends every present string through
|
||||
* `Number`, so a blank or whitespace-only value becomes `0`. The numeric
|
||||
* validation in {@link resolveDuplexAggregateCeilingBytes} rejects `0`, reports it
|
||||
* through `onRejectedOverride`, and returns the safe default. So a present blank
|
||||
* value is visible as invalid instead of silent as absent.
|
||||
*
|
||||
* `Number` ignores surrounding whitespace, so a valid value with surrounding
|
||||
* spaces still parses. The reporter receives only the parsed number, never the raw
|
||||
* string, so no operator-supplied text reaches a log line.
|
||||
*/
|
||||
export function resolveDuplexAggregateCeilingBytesFromEnv(
|
||||
rawOverride: string | undefined,
|
||||
onRejectedOverride?: DuplexAggregateCeilingOverrideRejectionReporter,
|
||||
): number {
|
||||
return resolveDuplexAggregateCeilingBytes(
|
||||
rawOverride === undefined ? undefined : Number(rawOverride),
|
||||
onRejectedOverride,
|
||||
);
|
||||
}
|
||||
+57
-2
@@ -83,6 +83,13 @@ import { createFeedbackTraceShareClientFromConfig } from "./services/feedback-sh
|
||||
import { buildRuntimeApiCandidateUrls, choosePrimaryRuntimeApiUrl } from "./runtime-api.js";
|
||||
import { isLoopbackHost, rewriteLoopbackUrlPort } from "./url-utils.js";
|
||||
import { createPluginWorkerManager } from "./services/plugin-worker-manager.js";
|
||||
import {
|
||||
createDuplexAggregateByteLedgerTelemetry,
|
||||
DuplexAggregateByteLedger,
|
||||
type DuplexAggregateByteLedgerMetricSink,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { resolveDuplexAggregateCeilingBytesFromEnv } from "./duplex-aggregate-ceiling-env.js";
|
||||
import { DUPLEX_COUNTER_AGGREGATE_BYTE_ACCOUNTING_UNDERFLOW_TOTAL } from "@paperclipai/adapter-utils/duplex-telemetry";
|
||||
import { createStorageServiceFromConfig } from "./storage/index.js";
|
||||
import { printStartupBanner } from "./startup-banner.js";
|
||||
import { getBoardClaimWarningUrl, initializeBoardClaimChallenge } from "./board-claim.js";
|
||||
@@ -754,9 +761,57 @@ export async function startServer(): Promise<StartedServer> {
|
||||
databaseBackupInFlight = false;
|
||||
}
|
||||
};
|
||||
const pluginWorkerManager = createPluginWorkerManager();
|
||||
// The process-owned aggregate byte ledger for the sandbox duplex channel. One
|
||||
// ledger per host process bounds the aggregate bytes that all live duplex routes
|
||||
// retain. The route-count controller bounds only the route count, so without this
|
||||
// ledger the per-route byte bounds multiply to many gigabytes at the maximum
|
||||
// route count. The manager injects this same object into every worker handle, so
|
||||
// one shared gauge bounds every host-side retention site.
|
||||
//
|
||||
// The optional operator override reads PAPERCLIP_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES.
|
||||
// An absent variable uses the documented default. A present invalid, blank,
|
||||
// whitespace-only, non-finite, zero, negative, non-integer, unsafe, or
|
||||
// over-maximum value does not fail startup. The host process is multi-tenant, so
|
||||
// one invalid environment value must not brick the whole host. The helper sends
|
||||
// the raw string to the resolver, so a present blank value is invalid, not
|
||||
// absent. The resolver rejects the invalid override and returns the safe default.
|
||||
// The reporter logs the rejection loudly at error, so the misconfiguration stays
|
||||
// visible while the host stays up. The log line carries only the rejected numeric
|
||||
// value, never the raw string.
|
||||
const duplexAggregateCeilingBytes = resolveDuplexAggregateCeilingBytesFromEnv(
|
||||
process.env.PAPERCLIP_MAX_AGGREGATE_DUPLEX_ROUTE_BYTES,
|
||||
(rejectedValue) => {
|
||||
logger.error(
|
||||
{ rejectedValue },
|
||||
"duplex aggregate byte ceiling override rejected; using the safe default",
|
||||
);
|
||||
},
|
||||
);
|
||||
// The server has no process metric pipeline yet, so the ledger telemetry maps to
|
||||
// the structured logger. The gauge logs at debug. A reservation rejection logs at
|
||||
// warn, because it marks an availability limit hit. An accounting-underflow defect
|
||||
// logs at error, because it marks a real cleanup bug. Each record carries only the
|
||||
// fixed metric name and the numeric value; no route, company, run, or payload
|
||||
// value reaches a log line.
|
||||
const duplexAggregateByteLedgerMetricSink: DuplexAggregateByteLedgerMetricSink = {
|
||||
setGauge(name, value) {
|
||||
logger.debug({ metric: name, value }, "duplex aggregate byte ledger gauge");
|
||||
},
|
||||
incrementCounter(name) {
|
||||
if (name === DUPLEX_COUNTER_AGGREGATE_BYTE_ACCOUNTING_UNDERFLOW_TOTAL) {
|
||||
logger.error({ metric: name }, "duplex aggregate byte ledger accounting underflow");
|
||||
return;
|
||||
}
|
||||
logger.warn({ metric: name }, "duplex aggregate byte ledger reservation rejected");
|
||||
},
|
||||
};
|
||||
const duplexAggregateByteLedger = new DuplexAggregateByteLedger({
|
||||
ceilingBytes: duplexAggregateCeilingBytes,
|
||||
telemetry: createDuplexAggregateByteLedgerTelemetry(duplexAggregateByteLedgerMetricSink),
|
||||
});
|
||||
const pluginWorkerManager = createPluginWorkerManager({ duplexAggregateByteLedger });
|
||||
const heartbeat = config.heartbeatSchedulerEnabled
|
||||
? heartbeatService(db as any, { pluginWorkerManager })
|
||||
? heartbeatService(db as any, { pluginWorkerManager, duplexAggregateByteLedger })
|
||||
: null;
|
||||
const decisionServiceOptions = {
|
||||
wakeOriginAgent: createDecisionWakeOriginAgent(heartbeat?.wakeup ?? null),
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type AdapterExecutionTarget,
|
||||
} from "@paperclipai/adapter-utils/execution-target";
|
||||
import type { DuplexTelemetryRecorder } from "@paperclipai/adapter-utils/duplex-telemetry";
|
||||
import type { DuplexAggregateByteLedger } from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import {
|
||||
clampSpanLabel,
|
||||
getActiveStepContext,
|
||||
@@ -206,6 +207,10 @@ export async function resolveEnvironmentExecutionTarget(input: {
|
||||
// enters the sandbox environment. Absent keeps the safe no-op default in the
|
||||
// bridge, so the surface stays inert until the host injects a real recorder.
|
||||
duplexTelemetryRecorder?: DuplexTelemetryRecorder | null;
|
||||
// The process-owned aggregate byte ledger. The seam stamps it onto the sandbox
|
||||
// target next to the runner, so the live object stays on the host and never
|
||||
// enters the sandbox environment. Absent keeps the bridge inert for this seam.
|
||||
duplexAggregateByteLedger?: DuplexAggregateByteLedger | null;
|
||||
}): Promise<AdapterExecutionTarget | null> {
|
||||
if (input.environment.driver === "local") {
|
||||
return {
|
||||
@@ -323,6 +328,10 @@ export async function resolveEnvironmentExecutionTarget(input: {
|
||||
// binds it to the fixed observability surface. Absent keeps the no-op
|
||||
// default, so the surface stays inert on a run with no injected recorder.
|
||||
duplexTelemetryRecorder: input.duplexTelemetryRecorder ?? null,
|
||||
// Attach the process-owned aggregate byte ledger next to the runner. The
|
||||
// bridge passes it to the broker, the decoder, and the response-body reader.
|
||||
// Absent keeps the bridge inert for this seam.
|
||||
duplexAggregateByteLedger: input.duplexAggregateByteLedger ?? null,
|
||||
...(effectiveCapabilities ? { effectiveCapabilities: Object.freeze({ ...effectiveCapabilities }) } : {}),
|
||||
environmentId: input.environment.id ?? null,
|
||||
leaseId: input.leaseId ?? null,
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
type AdapterWorkspaceRealization,
|
||||
} from "@paperclipai/adapter-utils/execution-target";
|
||||
import type { DuplexTelemetryRecorder } from "@paperclipai/adapter-utils/duplex-telemetry";
|
||||
import type { DuplexAggregateByteLedger } from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { buildWorkspaceRealizationRequest } from "./workspace-realization.js";
|
||||
import { executionWorkspaceService } from "./execution-workspaces.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
@@ -154,6 +155,14 @@ export function environmentRunOrchestrator(
|
||||
options: {
|
||||
pluginWorkerManager?: PluginWorkerManager;
|
||||
environmentRuntime?: EnvironmentRuntimeService;
|
||||
/**
|
||||
* The process-owned aggregate byte ledger for the sandbox duplex channel.
|
||||
* The server root creates one ledger per host process and injects the same
|
||||
* object here. The orchestrator stamps it onto the sandbox execution target,
|
||||
* so one shared gauge bounds the aggregate retained bytes across all live
|
||||
* duplex routes. Absent keeps the bridge inert for this seam.
|
||||
*/
|
||||
duplexAggregateByteLedger?: DuplexAggregateByteLedger | null;
|
||||
} = {},
|
||||
) {
|
||||
const environmentsSvc = environmentService(db);
|
||||
@@ -523,6 +532,7 @@ export function environmentRunOrchestrator(
|
||||
lease,
|
||||
environmentRuntime,
|
||||
duplexTelemetryRecorder: input.duplexTelemetryRecorder ?? null,
|
||||
duplexAggregateByteLedger: options.duplexAggregateByteLedger ?? null,
|
||||
});
|
||||
const realizationMode = workspaceRealization.mode === "in_place" ? "in_place" : "copy";
|
||||
const authoritativeRoot =
|
||||
|
||||
@@ -72,6 +72,7 @@ import {
|
||||
import { conflict, HttpError, notFound } from "../errors.js";
|
||||
import { getStartupTraceContext, getStartupTracer } from "../instrumentation.js";
|
||||
import { createHostDuplexTelemetryRecorder } from "./duplex-telemetry-recorder.js";
|
||||
import type { DuplexAggregateByteLedger } from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { incrementToolRuntimeMetricCounter } from "./tool-runtime-metrics.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import {
|
||||
@@ -6692,6 +6693,14 @@ export interface HeartbeatServiceOptions {
|
||||
pluginWorkerManager?: PluginWorkerManager;
|
||||
environmentRuntime?: HeartbeatEnvironmentRuntime;
|
||||
runtimeEnv?: Record<string, string | undefined>;
|
||||
/**
|
||||
* The process-owned aggregate byte ledger for the sandbox duplex channel. The
|
||||
* server root creates one ledger per host process and injects the same object
|
||||
* here. The heartbeat threads it into the environment run orchestrator, which
|
||||
* stamps it onto the sandbox execution target. Absent keeps the bridge inert
|
||||
* for this seam.
|
||||
*/
|
||||
duplexAggregateByteLedger?: DuplexAggregateByteLedger | null;
|
||||
}
|
||||
|
||||
type WorkspaceReadyCommentWriter = {
|
||||
@@ -6815,6 +6824,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
||||
const envOrchestrator = environmentRunOrchestrator(db, {
|
||||
pluginWorkerManager: options.pluginWorkerManager,
|
||||
environmentRuntime,
|
||||
duplexAggregateByteLedger: options.duplexAggregateByteLedger,
|
||||
});
|
||||
const workspaceOperationsSvc = workspaceOperationService(db);
|
||||
const liveRunExecutions = {
|
||||
|
||||
@@ -57,10 +57,31 @@ import type {
|
||||
InitializeParams,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
import { getActiveStepContext } from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
|
||||
import {
|
||||
DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED,
|
||||
type DuplexAggregateByteLedger,
|
||||
type DuplexAggregateTokenOwner,
|
||||
type ReservationToken,
|
||||
} from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
|
||||
import { CLAUDE_SETUP_TOKEN_COMMAND } from "@paperclipai/adapter-claude-local/server";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { traceparentFromContextToken } from "../instrumentation.js";
|
||||
|
||||
/**
|
||||
* The host raises this error when the child-stdin transport reservation for a
|
||||
* duplex write fails against the aggregate byte ledger. The host does not write
|
||||
* the frame. The write path throws it, `callInternal` rejects the RPC with it
|
||||
* unwrapped, and the duplex write caller ends the route fail-closed with the
|
||||
* {@link DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED} marker. Only a duplex write
|
||||
* meters the transport, so this error never reaches a non-duplex control message.
|
||||
*/
|
||||
class DuplexAggregateBytesExceededError extends Error {
|
||||
constructor() {
|
||||
super(DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED);
|
||||
this.name = "DuplexAggregateBytesExceededError";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -397,6 +418,14 @@ export interface WorkerStartOptions {
|
||||
* constructs a handle this way).
|
||||
*/
|
||||
duplexRouteSlots?: DuplexRouteSlotController | null;
|
||||
/**
|
||||
* The process-owned aggregate byte ledger for the duplex channel. The manager
|
||||
* injects one shared instance into every worker handle, so one gauge bounds the
|
||||
* aggregate retained bytes across every route in the process. When it is absent,
|
||||
* the worker retains duplex bytes unbounded (a unit test constructs a handle
|
||||
* this way). The manager never makes a fresh per-handle default.
|
||||
*/
|
||||
duplexAggregateByteLedger?: DuplexAggregateByteLedger | null;
|
||||
/**
|
||||
* Companies this worker may act on from proactive (no-invocation) worker→host
|
||||
* calls — the plugin's configured companies. Seeded onto the handle at
|
||||
@@ -966,11 +995,42 @@ export function createPluginWorkerHandle(
|
||||
// JSON-RPC message sending
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
function sendMessage(message: unknown): void {
|
||||
function sendMessage(message: unknown, meterDuplexWrite = false): void {
|
||||
if (!childProcess?.stdin?.writable) {
|
||||
throw new Error(`Worker process for plugin "${pluginId}" is not writable`);
|
||||
}
|
||||
const serialized = serializeMessage(message as any);
|
||||
const ledger = duplexAggregateByteLedger;
|
||||
if (meterDuplexWrite && ledger) {
|
||||
// Charge the child-stdin transport buffer for a duplex write. The host writes
|
||||
// the serialized frame to the child stdin without backpressure. When the child
|
||||
// stops reading its stdin, the frame stays in the host stdin write buffer.
|
||||
// Reserve the exact serialized-frame byte count. That count includes the JSON
|
||||
// escaping and the newline framing, so the ledger covers the retained transport
|
||||
// bytes, not only the raw payload. The RPC separately holds the raw payload
|
||||
// under a `pending_write` token, so the two tokens cover the peak of both
|
||||
// retentions at the same time.
|
||||
const bytes = Buffer.byteLength(serialized);
|
||||
const token = ledger.reserve("stdin_write", bytes);
|
||||
if (!token) {
|
||||
// The reservation would pass the aggregate ceiling. Fail closed before the
|
||||
// enqueue: do not write the frame. The duplex write caller ends the route.
|
||||
throw new DuplexAggregateBytesExceededError();
|
||||
}
|
||||
// Hold the token until the stream flushes the chunk. The write callback fires
|
||||
// when the stream hands the chunk to the operating system, so the bytes then
|
||||
// leave the host stream buffer. The RPC settle and the RPC timeout never
|
||||
// release this token. Only the flush, the stream error, the stream close, or
|
||||
// the worker exit releases it. Release through the outstanding-token set, so a
|
||||
// later stream-error or worker-exit sweep never double-releases the same token.
|
||||
pendingStdinWriteTokens.add(token);
|
||||
childProcess.stdin.write(serialized, () => {
|
||||
if (pendingStdinWriteTokens.delete(token)) {
|
||||
ledger.release(token);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
childProcess.stdin.write(serialized);
|
||||
}
|
||||
|
||||
@@ -1550,12 +1610,37 @@ export function createPluginWorkerHandle(
|
||||
// 6. total data bytes — the cumulative inbound bytes over the whole life,
|
||||
// counted before and after a data listener attaches;
|
||||
// 7. route lifetime — the milliseconds from the open to the terminal end.
|
||||
|
||||
// One buffered data chunk retained for a late listener drain. It carries the raw
|
||||
// chunk string and the aggregate byte token that reserved its raw bytes. The
|
||||
// token is `null` when no ledger is injected.
|
||||
interface BufferedDuplexChunk {
|
||||
chunk: string;
|
||||
token: ReservationToken | null;
|
||||
}
|
||||
// One pre-bind data event, normalized to the narrow duplex-event schema. The host
|
||||
// retains only these bounded scalar fields plus the reservation token, never the
|
||||
// original arbitrary notification graph. The bind re-resolves the pair from
|
||||
// `workerSessionId`, so a frame whose pair does not match the bound pair still
|
||||
// fails closed.
|
||||
interface HeldDuplexEvent {
|
||||
workerSessionId: string;
|
||||
chunk: string;
|
||||
token: ReservationToken | null;
|
||||
}
|
||||
// One pre-bind exit event, normalized to the narrow duplex-event schema.
|
||||
interface HeldDuplexExitEvent {
|
||||
workerSessionId: string;
|
||||
exitCode: number | null;
|
||||
token: ReservationToken | null;
|
||||
}
|
||||
|
||||
interface DuplexChannelRoute {
|
||||
hostRouteId: string;
|
||||
state: RouteState;
|
||||
workerSessionId: string | null;
|
||||
listener: ((chunk: string) => void) | null;
|
||||
buffered: string[];
|
||||
buffered: BufferedDuplexChunk[];
|
||||
bufferedChars: number;
|
||||
pendingRequests: number;
|
||||
protocolErrors: number;
|
||||
@@ -1563,18 +1648,23 @@ export function createPluginWorkerHandle(
|
||||
lifetimeTimer: ReturnType<typeof setTimeout> | null;
|
||||
terminalized: boolean;
|
||||
settleWait: (value: { exitCode: number | null; transportClosed?: boolean }) => void;
|
||||
// The data frames that arrived before the bind, held in order. The bind
|
||||
// replays them through the exact-pair routing, so an early frame is never
|
||||
// lost and a frame whose pair does not match the bound pair still fails
|
||||
// closed. The hold ceiling is `maxDuplexChannelPreBindHoldFrames`, one frame
|
||||
// above the buffered bound, so the replay's buffered-bound check ends the
|
||||
// route, not the hold.
|
||||
preBind: JsonRpcNotification[];
|
||||
// The single exit frame that arrived before the bind. An exit never consumes
|
||||
// a data hold slot, so a worker that batches an exit among enough data frames
|
||||
// to fill the hold cannot crowd out a data frame. The bind replays the held
|
||||
// data frames first, then this exit last.
|
||||
preBindExit: JsonRpcNotification | null;
|
||||
// The bounded raw data events that arrived before the bind, held in order. The
|
||||
// bind replays them through the exact-pair routing, so an early frame is never
|
||||
// lost and a frame whose pair does not match the bound pair still fails closed.
|
||||
// The hold ceiling is `maxDuplexChannelPreBindHoldFrames`, one frame above the
|
||||
// buffered bound, so the replay's buffered-bound check ends the route, not the
|
||||
// hold. Each held event carries the aggregate byte token that reserved its raw
|
||||
// bytes; the host never retains the original arbitrary notification graph.
|
||||
preBind: HeldDuplexEvent[];
|
||||
// The single bounded exit event that arrived before the bind. An exit never
|
||||
// consumes a data hold slot, so a worker that batches an exit among enough data
|
||||
// frames to fill the hold cannot crowd out a data frame. The bind replays the
|
||||
// held data events first, then this exit last.
|
||||
preBindExit: HeldDuplexExitEvent | null;
|
||||
// The authoritative registry of every aggregate byte token this route still
|
||||
// holds, across the pre-bind, buffered, and terminal-buffered representations.
|
||||
// The byte cleanup releases every token here exactly once.
|
||||
retainedTokens: Set<ReservationToken>;
|
||||
}
|
||||
// The live duplex routes on this worker, keyed by the exact
|
||||
// `{ hostRouteId, workerSessionId }` pair. The host binds one pair once, at
|
||||
@@ -1600,6 +1690,89 @@ export function createPluginWorkerHandle(
|
||||
// time per route, so a double terminalize never releases two slots.
|
||||
const duplexRouteSlotHolders = new Set<DuplexChannelRoute>();
|
||||
|
||||
// The process-owned aggregate byte ledger. The manager injects it, so one gauge
|
||||
// bounds the aggregate retained bytes across every route in the process. When it
|
||||
// is absent, the worker retains duplex bytes unbounded (a unit test constructs it
|
||||
// this way).
|
||||
const duplexAggregateByteLedger = options.duplexAggregateByteLedger ?? null;
|
||||
// The outstanding child-stdin transport tokens for duplex writes. Each token
|
||||
// covers one serialized frame the host stdin write buffer still retains. The
|
||||
// write callback releases a token on the flush; a stream error, a stream close,
|
||||
// or a worker exit releases every remaining token, because each of those
|
||||
// discards the stdin write buffer. The set is the release guard, so a token
|
||||
// releases one time across the two paths.
|
||||
const pendingStdinWriteTokens = new Set<ReservationToken>();
|
||||
// Release every outstanding child-stdin transport token. A stream error, a
|
||||
// stream close, or a worker exit calls this, because each discards the stdin
|
||||
// write buffer. The `delete` guard drops each token one time, so a later flush
|
||||
// callback or a second sweep releases nothing again.
|
||||
function releaseAllPendingStdinWriteTokens(): void {
|
||||
if (!duplexAggregateByteLedger) return;
|
||||
for (const token of pendingStdinWriteTokens) {
|
||||
duplexAggregateByteLedger.release(token);
|
||||
}
|
||||
pendingStdinWriteTokens.clear();
|
||||
}
|
||||
// The terminalized routes that still hold buffered bytes for a late listener
|
||||
// drain. A terminalized route leaves the opening and live maps, so this registry
|
||||
// keeps the worker-exit sweep able to release its still-charged buffered tokens.
|
||||
const terminalDuplexRoutes = new Set<DuplexChannelRoute>();
|
||||
|
||||
// Reserve `bytes` for one route retention against the aggregate ledger. Return
|
||||
// the held token, or `null` when the reservation would pass the ceiling. When no
|
||||
// ledger is present, return `"no-ledger"`, so the caller admits the retention
|
||||
// with no token. The helper adds a real token to `route.retainedTokens`.
|
||||
function reserveRouteBytes(
|
||||
route: DuplexChannelRoute,
|
||||
owner: DuplexAggregateTokenOwner,
|
||||
bytes: number,
|
||||
): ReservationToken | "no-ledger" | null {
|
||||
if (!duplexAggregateByteLedger) return "no-ledger";
|
||||
const token = duplexAggregateByteLedger.reserve(owner, bytes);
|
||||
if (!token) return null;
|
||||
route.retainedTokens.add(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
// Transfer a held route token to a new owner label. The token identity and the
|
||||
// reserved bytes stay the same, so no admission gap opens between two
|
||||
// representations of the same retained bytes.
|
||||
function transferRouteToken(
|
||||
token: ReservationToken | null,
|
||||
owner: DuplexAggregateTokenOwner,
|
||||
): void {
|
||||
if (!token) return;
|
||||
duplexAggregateByteLedger?.transfer(token, owner);
|
||||
}
|
||||
|
||||
// Release one held route token and drop it from the route registry, in one
|
||||
// synchronous step. A `null` token (no ledger) releases nothing.
|
||||
function releaseRouteToken(route: DuplexChannelRoute, token: ReservationToken | null): void {
|
||||
if (!token) return;
|
||||
route.retainedTokens.delete(token);
|
||||
duplexAggregateByteLedger?.release(token);
|
||||
}
|
||||
|
||||
// Release every token a route still holds and clear its retained representations,
|
||||
// exactly once. A later call finds an empty registry and releases nothing, so the
|
||||
// helper is idempotent. Every terminal-discard, open-failure, bind-replay
|
||||
// failure, close-acknowledgement failure, worker-exit, and shutdown path calls
|
||||
// it. Terminal map deletion is never treated as proof that retained bytes are
|
||||
// gone; this registry is authoritative for byte cleanup.
|
||||
function discardRouteRetained(route: DuplexChannelRoute): void {
|
||||
if (duplexAggregateByteLedger) {
|
||||
for (const token of route.retainedTokens) {
|
||||
duplexAggregateByteLedger.release(token);
|
||||
}
|
||||
}
|
||||
route.retainedTokens.clear();
|
||||
route.preBind = [];
|
||||
route.preBindExit = null;
|
||||
route.buffered = [];
|
||||
route.bufferedChars = 0;
|
||||
terminalDuplexRoutes.delete(route);
|
||||
}
|
||||
|
||||
// Try to reserve one aggregate route slot for a route. Return true when the
|
||||
// route holds a slot after the call. When no controller is present, the route
|
||||
// always holds a slot.
|
||||
@@ -1697,15 +1870,38 @@ export function createPluginWorkerHandle(
|
||||
route.terminalized = true;
|
||||
route.state = "closed";
|
||||
route.listener = null;
|
||||
// Keep the buffered chunks the host accepted before the route ended, so a
|
||||
// listener that attaches after the end still drains them. A frame can end the
|
||||
// route during the pre-bind replay, before a listener attaches, and the
|
||||
// chunks the host accepted before that frame are valid data the listener must
|
||||
// still receive. The buffered bytes stay bounded by the pre-bind buffered
|
||||
// bound, and `onData` clears them once it drains them. Drop the held pre-bind
|
||||
// frames, which never bound to a listener.
|
||||
// Stop admission first. Then move the byte cleanup. Keep the buffered chunks the
|
||||
// host accepted before the route ended, so a listener that attaches after the
|
||||
// end still drains them. A frame can end the route during the pre-bind replay,
|
||||
// before a listener attaches, and the chunks the host accepted before that frame
|
||||
// are valid data the listener must still receive. The buffered bytes stay
|
||||
// bounded by the pre-bind buffered bound, and `onData` clears and releases them
|
||||
// once it drains them.
|
||||
//
|
||||
// The buffered records keep their tokens; move each token to the terminal owner
|
||||
// label and register the route in the terminal registry, so the worker-exit
|
||||
// sweep can release the still-charged bytes later. Do not release a buffered
|
||||
// token at map deletion; terminal map deletion is never proof the bytes are
|
||||
// gone. Release every other token the route still holds (the pre-bind events,
|
||||
// the held exit, and any stranded token), because they never reach a listener.
|
||||
const bufferedTokens = new Set<ReservationToken>();
|
||||
for (const record of route.buffered) {
|
||||
if (record.token) {
|
||||
bufferedTokens.add(record.token);
|
||||
transferRouteToken(record.token, "terminal_buffered");
|
||||
}
|
||||
}
|
||||
for (const token of [...route.retainedTokens]) {
|
||||
if (!bufferedTokens.has(token)) {
|
||||
route.retainedTokens.delete(token);
|
||||
duplexAggregateByteLedger?.release(token);
|
||||
}
|
||||
}
|
||||
route.preBind = [];
|
||||
route.preBindExit = null;
|
||||
if (route.buffered.length > 0) {
|
||||
terminalDuplexRoutes.add(route);
|
||||
}
|
||||
clearDuplexChannelLifetimeTimer(route);
|
||||
// Remove the live binding and install the tombstone in one synchronous step,
|
||||
// before the worker close and before any reuse. A reserved route that never
|
||||
@@ -1787,14 +1983,26 @@ export function createPluginWorkerHandle(
|
||||
return "violation";
|
||||
}
|
||||
|
||||
function routeDuplexChannelData(notification: JsonRpcNotification): void {
|
||||
// Route one duplex channel data frame. On a live route with a listener, deliver
|
||||
// the chunk transiently. On a live route with no listener, buffer the chunk and
|
||||
// charge its raw bytes against the aggregate ledger. The `carried` argument marks
|
||||
// a bind-replay frame: it carries the pre-bind token the buffered record must
|
||||
// reuse, so the replay transfers the token to the buffered representation with no
|
||||
// decrement and no re-reserve. A live frame passes no `carried`, so it reserves a
|
||||
// fresh buffered token. A `carried.token` of `null` means no ledger is present.
|
||||
function routeDuplexChannelData(
|
||||
notification: JsonRpcNotification,
|
||||
carried?: { token: ReservationToken | null },
|
||||
): void {
|
||||
const params = isRecord(notification.params) ? notification.params : {};
|
||||
const hostRouteId = readNonEmptyString(params.hostRouteId);
|
||||
const workerSessionId = readNonEmptyString(params.workerSessionId);
|
||||
const resolved = resolveDuplexRouteByPair(hostRouteId, workerSessionId);
|
||||
if (resolved === "tombstoned") {
|
||||
// A late frame for a closed pair. It reaches no listener and changes no
|
||||
// state. Never log the raw frame content.
|
||||
// state. A bind replay never lands here, because the replayed route is live;
|
||||
// a carried token stays on its route and the terminal cleanup releases it.
|
||||
// Never log the raw frame content.
|
||||
return;
|
||||
}
|
||||
if (resolved === "violation") {
|
||||
@@ -1804,8 +2012,8 @@ export function createPluginWorkerHandle(
|
||||
return;
|
||||
}
|
||||
if (resolved === "opening") {
|
||||
// The frame arrived before the bind. Hold it; the bind replays it through the
|
||||
// exact-pair routing.
|
||||
// The frame arrived before the bind. A replay never lands here, because the
|
||||
// route is live during replay. Hold the live frame; the bind replays it.
|
||||
bufferPreBindDuplexFrame(hostRouteId, notification);
|
||||
return;
|
||||
}
|
||||
@@ -1813,13 +2021,15 @@ export function createPluginWorkerHandle(
|
||||
const chunk = params.chunk;
|
||||
if (typeof chunk !== "string" || chunk.length === 0) {
|
||||
// The exact pair matches, but the chunk is malformed. Count one per-route
|
||||
// protocol error.
|
||||
// protocol error. Release a carried replay token first.
|
||||
releaseRouteToken(route, carried?.token ?? null);
|
||||
recordDuplexChannelProtocolError(route);
|
||||
return;
|
||||
}
|
||||
if (chunk.length > maxDuplexChannelChunkChars) {
|
||||
// One inbound chunk is larger than the per-chunk limit. End the route at
|
||||
// once. Do not count the chunk as a protocol error.
|
||||
releaseRouteToken(route, carried?.token ?? null);
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
@@ -1828,12 +2038,16 @@ export function createPluginWorkerHandle(
|
||||
// bound listener cannot receive data past the cap.
|
||||
const chunkBytes = Buffer.byteLength(chunk);
|
||||
if (route.totalDataBytes + chunkBytes > maxDuplexChannelTotalDataBytes) {
|
||||
releaseRouteToken(route, carried?.token ?? null);
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
route.totalDataBytes += chunkBytes;
|
||||
if (route.listener) {
|
||||
// A listener is attached. Deliver the chunk transiently and release a carried
|
||||
// replay token after the synchronous delivery boundary.
|
||||
deliverDuplexChannelChunk(route.listener, chunk);
|
||||
releaseRouteToken(route, carried?.token ?? null);
|
||||
return;
|
||||
}
|
||||
// No listener attached yet. Buffer the frame under the pre-bind bounds. End
|
||||
@@ -1842,10 +2056,28 @@ export function createPluginWorkerHandle(
|
||||
route.buffered.length + 1 > maxDuplexChannelPreBindFrames ||
|
||||
route.bufferedChars + chunk.length > maxDuplexChannelPreBindChars
|
||||
) {
|
||||
releaseRouteToken(route, carried?.token ?? null);
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
route.buffered.push(chunk);
|
||||
let token: ReservationToken | null;
|
||||
if (carried) {
|
||||
// The bind replay transfers the pre-bind token to the buffered
|
||||
// representation. No decrement and no re-reserve, so no admission gap opens.
|
||||
token = carried.token;
|
||||
transferRouteToken(token, "buffered_chunk");
|
||||
} else {
|
||||
// A live frame reserves a fresh buffered token for its exact raw bytes.
|
||||
const reserved = reserveRouteBytes(route, "buffered_chunk", chunkBytes);
|
||||
if (reserved === null) {
|
||||
// The aggregate ceiling rejected the reservation. Retain nothing and fail
|
||||
// closed with the fixed marker.
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
token = reserved === "no-ledger" ? null : reserved;
|
||||
}
|
||||
route.buffered.push({ chunk, token });
|
||||
route.bufferedChars += chunk.length;
|
||||
}
|
||||
|
||||
@@ -1900,15 +2132,58 @@ export function createPluginWorkerHandle(
|
||||
if (!hostRouteId) return;
|
||||
const route = openingDuplexRoutes.get(hostRouteId);
|
||||
if (!route) return;
|
||||
const params = isRecord(notification.params) ? notification.params : {};
|
||||
const workerSessionId = readNonEmptyString(params.workerSessionId);
|
||||
if (!workerSessionId) {
|
||||
// A malformed pair. Count one per-route protocol error and hold nothing.
|
||||
recordDuplexChannelProtocolError(route);
|
||||
return;
|
||||
}
|
||||
if (notification.method === DUPLEX_CHANNEL_EXIT_NOTIFICATION) {
|
||||
route.preBindExit = notification;
|
||||
// Normalize the exit to the narrow duplex-event schema. An exit retains only
|
||||
// a bounded scalar, so reserve a zero-byte token that carries the record
|
||||
// through the one cleanup path. Release any earlier held exit token first, so
|
||||
// a replaced exit never leaks its reservation.
|
||||
const exitCode = typeof params.exitCode === "number" ? params.exitCode : null;
|
||||
if (route.preBindExit) releaseRouteToken(route, route.preBindExit.token);
|
||||
const reserved = reserveRouteBytes(route, "pre_bind_event", 0);
|
||||
if (reserved === null) {
|
||||
// The aggregate ceiling rejected the reservation. Fail closed.
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
route.preBindExit = {
|
||||
workerSessionId,
|
||||
exitCode,
|
||||
token: reserved === "no-ledger" ? null : reserved,
|
||||
};
|
||||
return;
|
||||
}
|
||||
// A data event. Validate and normalize it to the narrow duplex-event schema
|
||||
// before any retention.
|
||||
const chunk = params.chunk;
|
||||
if (typeof chunk !== "string" || chunk.length === 0) {
|
||||
recordDuplexChannelProtocolError(route);
|
||||
return;
|
||||
}
|
||||
if (route.preBind.length >= maxDuplexChannelPreBindHoldFrames) {
|
||||
recordDuplexChannelProtocolError(route);
|
||||
return;
|
||||
}
|
||||
route.preBind.push(notification);
|
||||
// Reserve the exact retained raw byte count before the host holds the event.
|
||||
const reserved = reserveRouteBytes(route, "pre_bind_event", Buffer.byteLength(chunk));
|
||||
if (reserved === null) {
|
||||
// The aggregate ceiling rejected the reservation. The caller retains nothing
|
||||
// and the route fails closed with the fixed marker.
|
||||
log.warn({ pluginId, reason: DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED }, "duplex pre-bind hold rejected");
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
route.preBind.push({
|
||||
workerSessionId,
|
||||
chunk,
|
||||
token: reserved === "no-ledger" ? null : reserved,
|
||||
});
|
||||
}
|
||||
|
||||
// Replay the frames a route held before it bound. The route is live now, so the
|
||||
@@ -1921,14 +2196,47 @@ export function createPluginWorkerHandle(
|
||||
function replayPreBindDuplexFrames(route: DuplexChannelRoute): void {
|
||||
const held = route.preBind;
|
||||
route.preBind = [];
|
||||
for (const notification of held) {
|
||||
if (route.terminalized) break;
|
||||
routeDuplexChannelData(notification);
|
||||
for (const event of held) {
|
||||
if (route.terminalized) {
|
||||
// The route ended mid-replay. Release the remaining held tokens, so the
|
||||
// unreplayed events retain nothing.
|
||||
releaseRouteToken(route, event.token);
|
||||
continue;
|
||||
}
|
||||
// Reconstruct a transient data notification for the exact-pair routing. The
|
||||
// host holds only the bounded event, so it builds this notification for the
|
||||
// routing step and discards it at once. The carried token moves to the
|
||||
// buffered representation without a decrement or a re-reserve.
|
||||
routeDuplexChannelData(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: DUPLEX_CHANNEL_DATA_NOTIFICATION,
|
||||
params: {
|
||||
hostRouteId: route.hostRouteId,
|
||||
workerSessionId: event.workerSessionId,
|
||||
chunk: event.chunk,
|
||||
},
|
||||
},
|
||||
{ token: event.token },
|
||||
);
|
||||
}
|
||||
const heldExit = route.preBindExit;
|
||||
route.preBindExit = null;
|
||||
if (heldExit && !route.terminalized) {
|
||||
routeDuplexChannelExit(heldExit);
|
||||
if (heldExit) {
|
||||
// The exit retains only a bounded scalar. Release its placeholder token, then
|
||||
// resolve the wait through the exact-pair routing when the route still lives.
|
||||
releaseRouteToken(route, heldExit.token);
|
||||
if (!route.terminalized) {
|
||||
routeDuplexChannelExit({
|
||||
jsonrpc: "2.0",
|
||||
method: DUPLEX_CHANNEL_EXIT_NOTIFICATION,
|
||||
params: {
|
||||
hostRouteId: route.hostRouteId,
|
||||
workerSessionId: heldExit.workerSessionId,
|
||||
exitCode: heldExit.exitCode,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1939,23 +2247,34 @@ export function createPluginWorkerHandle(
|
||||
// id never returns, so no closed pair can revive on a restart. The pending
|
||||
// channel calls reject through `rejectAllPending`.
|
||||
function closeDuplexChannelRouteOnWorkerExit(): void {
|
||||
const routes = [...openingDuplexRoutes.values(), ...liveDuplexRoutes.values()];
|
||||
// Enumerate the opening index, the live index, and the terminal registry. A
|
||||
// terminalized route left the opening and live maps but may still hold buffered
|
||||
// bytes for a late listener; the worker is gone, so the host releases them now.
|
||||
const routes = [
|
||||
...openingDuplexRoutes.values(),
|
||||
...liveDuplexRoutes.values(),
|
||||
...terminalDuplexRoutes,
|
||||
];
|
||||
openingDuplexRoutes.clear();
|
||||
liveDuplexRoutes.clear();
|
||||
duplexPairTombstones.clear();
|
||||
for (const route of routes) {
|
||||
if (route.terminalized) continue;
|
||||
route.terminalized = true;
|
||||
route.state = "closed";
|
||||
route.listener = null;
|
||||
route.buffered = [];
|
||||
route.bufferedChars = 0;
|
||||
route.preBind = [];
|
||||
route.preBindExit = null;
|
||||
clearDuplexChannelLifetimeTimer(route);
|
||||
releaseDuplexRouteSlot(route);
|
||||
settleRouteWait(route, { exitCode: null });
|
||||
if (!route.terminalized) {
|
||||
route.terminalized = true;
|
||||
route.state = "closed";
|
||||
route.listener = null;
|
||||
route.bufferedChars = 0;
|
||||
clearDuplexChannelLifetimeTimer(route);
|
||||
releaseDuplexRouteSlot(route);
|
||||
settleRouteWait(route, { exitCode: null });
|
||||
}
|
||||
// Release every token the route still holds and clear its retained
|
||||
// representations, exactly once. A route already drained by a late listener
|
||||
// holds no token, so this is harmless and leaves the ledger at zero.
|
||||
discardRouteRetained(route);
|
||||
}
|
||||
// Clear the terminal registry. Every route in it was just discarded above.
|
||||
terminalDuplexRoutes.clear();
|
||||
}
|
||||
|
||||
// Open one live generic duplex channel route. Reserve the route before the open
|
||||
@@ -1988,6 +2307,7 @@ export function createPluginWorkerHandle(
|
||||
settleWait,
|
||||
preBind: [],
|
||||
preBindExit: null,
|
||||
retainedTokens: new Set<ReservationToken>(),
|
||||
};
|
||||
// Reserve one aggregate route slot before any work. When the process-scoped
|
||||
// ceiling is full, reject with the fixed route-busy error and open nothing, so
|
||||
@@ -2074,11 +2394,61 @@ export function createPluginWorkerHandle(
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
// Reserve the exact UTF-8 byte count of a host→worker write against the
|
||||
// aggregate ledger before `callInternal` retains the payload. A pending write
|
||||
// RPC holds `params.data` until it settles, so this reservation bounds the
|
||||
// aggregate host→worker pending-write bytes across every route. Compute the
|
||||
// byte count with `Buffer.byteLength`, not `data.length`, because one
|
||||
// character can encode as several UTF-8 bytes. A stop request carries no
|
||||
// payload, so it reserves nothing. When no ledger is present, admit the write
|
||||
// with no token (a unit test constructs the handle this way).
|
||||
let pendingWriteToken: ReservationToken | null = null;
|
||||
if (method === "duplexChannelWrite" && duplexAggregateByteLedger) {
|
||||
const data = (params as HostToWorkerMethods["duplexChannelWrite"][0]).data;
|
||||
const bytes = Buffer.byteLength(data, "utf8");
|
||||
pendingWriteToken = duplexAggregateByteLedger.reserve("pending_write", bytes);
|
||||
if (!pendingWriteToken) {
|
||||
// The reservation would pass the aggregate ceiling. Retain nothing, do
|
||||
// not enqueue the RPC, and end the route fail-closed with the aggregate
|
||||
// marker, not the route-busy marker.
|
||||
log.warn(
|
||||
{ pluginId, reason: DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED },
|
||||
"duplex pending write reservation rejected",
|
||||
);
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
return;
|
||||
}
|
||||
}
|
||||
route.pendingRequests += 1;
|
||||
void callInternal(method, params, duplexChannelOpenTimeoutMs)
|
||||
.catch(() => {})
|
||||
// Meter the child-stdin transport buffer only for a duplex write. A stop
|
||||
// request carries a tiny fixed frame that the host never lets grow, so it
|
||||
// does not meter or reject. The write path reserves the serialized frame in
|
||||
// `sendMessage` right before the stdin write.
|
||||
const meterDuplexWrite = method === "duplexChannelWrite";
|
||||
void callInternal(method, params, duplexChannelOpenTimeoutMs, undefined, meterDuplexWrite)
|
||||
.catch((err: unknown) => {
|
||||
if (err instanceof DuplexAggregateBytesExceededError) {
|
||||
// The transport reservation failed. The host did not write the frame.
|
||||
// End the route fail-closed with the aggregate marker, not the
|
||||
// route-busy marker.
|
||||
log.warn(
|
||||
{ pluginId, reason: DUPLEX_CHANNEL_AGGREGATE_BYTES_EXCEEDED },
|
||||
"duplex stdin write reservation rejected",
|
||||
);
|
||||
void terminalizeDuplexChannelRoute(route);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
route.pendingRequests -= 1;
|
||||
// Release the pending-write token one time, after the RPC settles on any
|
||||
// path: success, error, timeout, worker exit, or shutdown. The token is
|
||||
// not in `route.retainedTokens`, so route terminalization never releases
|
||||
// it; only this settlement releases it. The separate `stdin_write` token
|
||||
// covers the serialized frame and releases on the stream flush, the
|
||||
// stream error, the stream close, or the worker exit, never here.
|
||||
if (pendingWriteToken) {
|
||||
duplexAggregateByteLedger?.release(pendingWriteToken);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2089,7 +2459,16 @@ export function createPluginWorkerHandle(
|
||||
const pending = route.buffered;
|
||||
route.buffered = [];
|
||||
route.bufferedChars = 0;
|
||||
for (const chunk of pending) deliverDuplexChannelChunk(listener, chunk);
|
||||
for (const record of pending) {
|
||||
// Deliver each buffered record, drop its retained buffer, and release
|
||||
// its exact token before the drain proceeds to the next record. A
|
||||
// terminal route drains through this same code.
|
||||
deliverDuplexChannelChunk(listener, record.chunk);
|
||||
releaseRouteToken(route, record.token);
|
||||
}
|
||||
// The buffered records are gone, so the route no longer holds terminal
|
||||
// bytes for a late listener.
|
||||
terminalDuplexRoutes.delete(route);
|
||||
}
|
||||
},
|
||||
write(data: string): void {
|
||||
@@ -2392,6 +2771,18 @@ export function createPluginWorkerHandle(
|
||||
readline.on("line", handleLine);
|
||||
}
|
||||
|
||||
// Release the outstanding child-stdin transport tokens when the stdin stream
|
||||
// errors or closes, because each discards the stdin write buffer. The `error`
|
||||
// listener also stops an unhandled EPIPE from a child that closed its stdin.
|
||||
if (child.stdin) {
|
||||
child.stdin.on("error", () => {
|
||||
releaseAllPendingStdinWriteTokens();
|
||||
});
|
||||
child.stdin.on("close", () => {
|
||||
releaseAllPendingStdinWriteTokens();
|
||||
});
|
||||
}
|
||||
|
||||
// Capture stderr for logging
|
||||
if (child.stderr) {
|
||||
stderrReadline = createInterface({ input: child.stderr });
|
||||
@@ -2442,6 +2833,12 @@ export function createPluginWorkerHandle(
|
||||
childProcess = null;
|
||||
startedAt = null;
|
||||
|
||||
// The worker exit discards the child-stdin write buffer, so release every
|
||||
// outstanding transport token. The RPC rejections below never release these
|
||||
// tokens; only this sweep, a stream flush, a stream error, or a stream close
|
||||
// releases them.
|
||||
releaseAllPendingStdinWriteTokens();
|
||||
|
||||
// Reject all pending requests
|
||||
rejectAllPending(
|
||||
new Error(formatWorkerFailureMessage(
|
||||
@@ -2777,6 +3174,7 @@ export function createPluginWorkerHandle(
|
||||
params: HostToWorkerMethods[M][0],
|
||||
timeoutMs?: number,
|
||||
executeLogSink?: ExecuteLogSink,
|
||||
meterDuplexWrite = false,
|
||||
): Promise<HostToWorkerMethods[M][1]> {
|
||||
const rpcPromise = new Promise<HostToWorkerMethods[M][1]>((resolve, reject) => {
|
||||
if (!childProcess?.stdin?.writable) {
|
||||
@@ -2850,19 +3248,26 @@ export function createPluginWorkerHandle(
|
||||
...createRequest(method, params, id),
|
||||
...(invocation ? { paperclipInvocation: invocation } : {}),
|
||||
};
|
||||
sendMessage(request);
|
||||
sendMessage(request, meterDuplexWrite);
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
pendingRequests.delete(id);
|
||||
clearInvocation(invocation);
|
||||
clearExecuteRoute(invocation?.id);
|
||||
reject(
|
||||
new Error(
|
||||
`Failed to send "${method}" to worker: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
),
|
||||
);
|
||||
if (err instanceof DuplexAggregateBytesExceededError) {
|
||||
// The transport reservation failed before the write. Reject with the
|
||||
// typed error unwrapped, so the duplex write caller ends the route
|
||||
// fail-closed with the aggregate marker.
|
||||
reject(err);
|
||||
} else {
|
||||
reject(
|
||||
new Error(
|
||||
`Failed to send "${method}" to worker: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3035,6 +3440,14 @@ export interface PluginWorkerManagerOptions {
|
||||
* stays upstream admission only.
|
||||
*/
|
||||
maxConcurrentDuplexRoutes?: number | null;
|
||||
/**
|
||||
* The process-owned aggregate byte ledger. The process root creates one ledger
|
||||
* from validated configuration and passes it here. The manager injects the same
|
||||
* object into every worker handle, so one gauge bounds the aggregate retained
|
||||
* bytes across every route in the process. When it is absent, the worker retains
|
||||
* duplex bytes unbounded. The manager never makes a fresh default ledger.
|
||||
*/
|
||||
duplexAggregateByteLedger?: DuplexAggregateByteLedger | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3106,6 +3519,11 @@ export function createPluginWorkerManager(
|
||||
const duplexRouteSlots = createDuplexRouteSlotController(
|
||||
managerOptions?.maxConcurrentDuplexRoutes,
|
||||
);
|
||||
// The one shared, process-owned aggregate byte ledger. The manager injects the
|
||||
// same object into every worker handle, so one gauge bounds the aggregate
|
||||
// retained bytes across every route in the process. It is `null` when the
|
||||
// process root injected no ledger.
|
||||
const duplexAggregateByteLedger = managerOptions?.duplexAggregateByteLedger ?? null;
|
||||
|
||||
return {
|
||||
async startWorker(
|
||||
@@ -3127,9 +3545,11 @@ export function createPluginWorkerManager(
|
||||
}
|
||||
|
||||
const handle = createPluginWorkerHandle(pluginId, {
|
||||
// Inject the shared process-scoped route-slot controller, unless the caller
|
||||
// already supplied one (a test may inject its own).
|
||||
// Inject the shared process-scoped route-slot controller and the shared
|
||||
// process-owned aggregate byte ledger, unless the caller already supplied
|
||||
// its own (a test may inject its own).
|
||||
duplexRouteSlots,
|
||||
duplexAggregateByteLedger,
|
||||
...options,
|
||||
});
|
||||
workers.set(pluginId, handle);
|
||||
|
||||
Reference in new issue
Block a user