refactor(adapter-utils): replace the process-wide byte ledger with route-local byte bounds (#12465)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The adapter layer carries sandbox requests to host processes.
> - The HTTP/2 bridge used one process-wide byte ledger for all routes.
> - One busy route could exhaust that shared budget and move another
route to file transport.
> - This pull request gives each host retention site a fixed byte bound
and limits concurrent HTTP/2 streams.
> - The benefit is local protection: one route cannot consume the byte
budget of another route.

## Linked Issues or Issue Description

**What happened?**

The HTTP/2 bridge used one aggregate byte ledger for retained bytes
across all routes. A busy route could exhaust the shared budget and
force an unrelated route to use file transport.

**Expected behavior**

Each route should protect its own retained bytes. A reset on one HTTP/2
stream should cancel only that stream's host forward.

**Steps to reproduce**

1. Start the HTTP/2 bridge with multiple sandbox routes.
2. Send enough retained data through one route to reach the aggregate
byte limit.
3. Send a request through a sibling route.
4. Observe that the sibling route can fall back to file transport
because the first route used the shared ledger.

**Paperclip version or commit**

`47639e227e78e3c5e0dd1a3c0e2d792fe86895a3`

**Deployment mode**

Built from source with the adapter-utils and server test suites.

## What Changed

- Bound each host retention site with a fixed local byte limit.
- Limited concurrent live HTTP/2 streams with one built-in stream limit.
- Bound each host forward and response-body read to its own HTTP/2
stream lifetime.
- Removed the process-wide byte ledger, its environment override, its
metrics, and its file-transport fallbacks.
- Added tests for the stream limit, host body budget, and sibling-stream
cancellation.

## Verification

- Run `pnpm vitest run --project adapter-utils`.
- Confirm that 996 adapter-utils tests pass.
- Confirm that `test_live_forward_work_never_passes_the_stream_limit`
passes.
- Confirm that `test_the_host_body_budget_matches_the_stream_limit`
passes.
- Confirm that the sibling-stream cancellation test passes.
- Run `pnpm tsc --noEmit`.
- Confirm that all pull request checks pass.

## Risks

The bridge no longer uses a process-wide byte ledger. A local bound or
stream limit that is too low can reject or delay valid work. The tests
cover the new limits and stream cancellation behavior.

## Model Used

OpenAI GPT-5 Codex. Runtime model ID: GPT-5. The model used code
execution and repository tools. The runtime does not expose the context
window size.

## 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 `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
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:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-28 14:36:18 -07:00
1 parent a3b78f9d34
commit 64b7dce0ad
23 files changed
+806 -3365

No files matched your search

@@ -1,70 +0,0 @@
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,11 +21,6 @@ vi.mock("../services/plugin-environment-driver.js", async (importActual) => ({
}));
import type { EffectiveExecutionCapabilities } 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";
@@ -299,50 +294,6 @@ 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.
@@ -1,360 +0,0 @@
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[] = [];
// The session now streams raw `Uint8Array` chunks. Decode each one back
// to text, so the assertion below still compares the plain-text payload
// the fixture directive scripted.
session.onData((chunk) => chunks.push(new TextDecoder().decode(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[] = [];
// The session now streams raw `Uint8Array` chunks. Decode each one back
// to text, so the assertion below still compares the plain-text payload
// the fixture directive scripted.
session.onData((chunk) => chunks.push(new TextDecoder().decode(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 write reservation would pass the ceiling", async () => {
const telemetry = countingTelemetry();
// A four-byte ceiling. A serialized host-to-worker write frame cannot fit.
const ledger = new DuplexAggregateByteLedger({ ceilingBytes: 4, telemetry });
const handle = makeDuplexHandle({ duplexAggregateByteLedger: ledger });
try {
await handle.start();
// Open with no scripted data, so the fixture sends only the open reply.
// The route is bound and live by the time this line resolves.
const session = await handle.openDuplexChannel(duplexOpenInput({}));
// The write happens strictly after the bind, so the rejection is a genuine
// post-bind event, never a frame that races the open reply. The host makes
// two reservations for this write. The one raw payload byte fits the
// ceiling, so the pending-write reservation succeeds. The host then meters
// the serialized frame just before the stdin write. That frame is much
// larger than four bytes, so the transport reservation rejects, the host
// writes nothing, and the route ends fail-closed.
session.write(new TextEncoder().encode("a"));
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);
});
});
@@ -1,252 +0,0 @@
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" }),
);
const writeBytesEncoded = new TextEncoder().encode(writeData);
route.write(writeBytesEncoded);
route.write(writeBytesEncoded);
route.write(writeBytesEncoded);
// 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(new TextEncoder().encode("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(new TextEncoder().encode(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(new TextEncoder().encode("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);
});
});
@@ -1,300 +0,0 @@
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 the base64 wire inflation", 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,
}),
);
// The JSON-RPC hop carries the write payload as a base64 string, because JSON
// has no binary type (see `ChannelBytesWireValue` in protocol.ts). Base64
// encodes three raw bytes as four characters, so the serialized frame is
// larger than the raw payload by about that ratio, plus the small fixed cost
// of the surrounding JSON envelope (the method name and the route identifiers).
const rawBytes = 50_000;
const data = new Uint8Array(rawBytes).fill(0x22); // an arbitrary byte value
const encodedLength = Buffer.from(data).toString("base64").length;
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: at least the base64
// form of the raw payload, plus a bounded JSON envelope around it.
expect(transportBytes).toBeGreaterThan(rawBytes);
expect(transportBytes).toBeGreaterThanOrEqual(encodedLength);
expect(transportBytes).toBeLessThan(encodedLength + 5_000);
} 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(new TextEncoder().encode(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(new TextEncoder().encode(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 is near the per-write size. The JSON-RPC hop carries it as
// base64, so the reservation must count the encoded (larger) wire size, not
// the raw payload size.
const nearLimit = new Uint8Array(100_000).fill(0x22);
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);
});
});
@@ -423,6 +423,58 @@ describe("plugin worker manager duplex channel route", () => {
}
});
it("ends the route when the pending host-to-worker write bytes pass the route bound", async () => {
const handle = makeDuplexHandle({
duplexChannelLimits: { maxPendingWriteBytes: 10 },
});
try {
await handle.start();
const session = await handle.openDuplexChannel(
duplexOpenInput({ mode: "no-write-reply", workerSessionId: "ws-A" }),
);
const waitResult = session.wait();
// The worker never replies to a write, so each write's bytes stay charged
// against the route. The second write brings the cumulative bytes past
// the 10-byte bound and ends the route.
session.write(new TextEncoder().encode("aaaaa")); // 5 bytes → 5, under the bound
session.write(new TextEncoder().encode("bbbbbb")); // 6 bytes → 11 > 10, ends the route
await expect(waitResult).resolves.toEqual({ exitCode: null });
} finally {
await handle.stop().catch(() => undefined);
}
});
it("returns the pending write bytes to the route bound after a failed write", async () => {
const handle = makeDuplexHandle({
duplexChannelLimits: { maxPendingWriteBytes: 10, openTimeoutMs: 100 },
});
try {
await handle.start();
const session = await handle.openDuplexChannel(
duplexOpenInput({ mode: "no-write-reply", workerSessionId: "ws-A" }),
);
let routeEnded = false;
session.wait().then(() => {
routeEnded = true;
});
// The worker never replies, so each write's own request times out and
// rejects. The rejection must release this write's charged bytes, the
// same as a reply would. Wait past the first write's timeout before the
// second write sends.
session.write(new TextEncoder().encode("12345678")); // 8 bytes, under the 10-byte bound
await new Promise((resolve) => setTimeout(resolve, 200));
// If the first write's bytes had not released on its timeout, this
// second 8-byte write would bring the route to 16 bytes, past the
// 10-byte bound, and end the route at once, synchronously, in this call.
session.write(new TextEncoder().encode("87654321"));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(routeEnded).toBe(false);
await session.close();
} finally {
await handle.stop().catch(() => undefined);
}
});
it("ends the route when one host-to-worker write passes the size bound", async () => {
const handle = makeDuplexHandle({
duplexChannelLimits: { maxWriteChars: 8 },
@@ -701,6 +753,36 @@ describe("plugin worker manager duplex channel route", () => {
}
});
it("ends the route when the pre-bind hold bytes pass the route input bound", async () => {
const handle = makeDuplexHandle({
duplexChannelLimits: { maxPreBindBufferedChars: 10 },
});
try {
await handle.start();
// The worker batches the three data frames with the open reply, so all
// three frames arrive before the route binds and land in the pre-bind
// hold, not the post-bind buffered queue. The frame-count bound stays
// far above three frames, so only the byte bound can end the route
// here: this proves the hold itself counts bytes, not only frames. The
// hold ends the route before the bind completes, so the open call
// itself fails, the same way a malformed open reply fails it.
await expect(
handle.openDuplexChannel(
duplexOpenInput({
batchWithOpenReply: true,
data: [
{ chunk: "aaaaa" }, // total 5 → held
{ chunk: "bbbbb" }, // total 10 → held
{ chunk: "ccccc" }, // total 15 > 10 → end the route in the hold
],
}),
),
).rejects.toThrow("DUPLEX_CHANNEL_OPEN_FAILED");
} finally {
await handle.stop().catch(() => undefined);
}
});
it("ends the route on the frame count bound even when a caller raises that bound well past the module default", async () => {
// Regression test: the pre-open hold ceiling must track
// maxDuplexChannelPreBindFrames, not a fixed value. A fixed ceiling at or
@@ -1,32 +0,0 @@
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,
);
}
+2 -57
View File
@@ -87,13 +87,6 @@ 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-observability";
import { createStorageServiceFromConfig } from "./storage/index.js";
import { printStartupBanner } from "./startup-banner.js";
import { getBoardClaimWarningUrl, initializeBoardClaimChallenge } from "./board-claim.js";
@@ -784,57 +777,9 @@ export async function startServer(): Promise<StartedServer> {
databaseBackupInFlight = false;
}
};
// 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 pluginWorkerManager = createPluginWorkerManager();
const heartbeat = config.heartbeatSchedulerEnabled
? heartbeatService(db as any, { pluginWorkerManager, duplexAggregateByteLedger })
? heartbeatService(db as any, { pluginWorkerManager })
: null;
const decisionServiceOptions = {
wakeOriginAgent: createDecisionWakeOriginAgent(heartbeat?.wakeup ?? null),
@@ -6,7 +6,6 @@ import {
type AdapterExecutionTarget,
} from "@paperclipai/adapter-utils/execution-target";
import type { DuplexObservabilityRecorder } from "@paperclipai/adapter-utils/duplex-observability";
import type { DuplexAggregateByteLedger } from "@paperclipai/adapter-utils/duplex-aggregate-byte-ledger";
import {
clampSpanLabel,
getActiveStepContext,
@@ -208,10 +207,6 @@ 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.
duplexObservabilityRecorder?: DuplexObservabilityRecorder | 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 {
@@ -340,10 +335,6 @@ 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.
duplexObservabilityRecorder: input.duplexObservabilityRecorder ?? 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,
@@ -44,7 +44,6 @@ import {
type AdapterWorkspaceRealization,
} from "@paperclipai/adapter-utils/execution-target";
import type { DuplexObservabilityRecorder } from "@paperclipai/adapter-utils/duplex-observability";
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";
@@ -156,14 +155,6 @@ 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);
@@ -529,7 +520,6 @@ export function environmentRunOrchestrator(
lease,
environmentRuntime,
duplexObservabilityRecorder: input.duplexObservabilityRecorder ?? null,
duplexAggregateByteLedger: options.duplexAggregateByteLedger ?? null,
});
const realizationMode = workspaceRealization.mode === "in_place" ? "in_place" : "copy";
const authoritativeRoot =
-10
View File
@@ -73,7 +73,6 @@ import {
import { conflict, HttpError, notFound } from "../errors.js";
import { getStartupTraceContext, getStartupTracer } from "../instrumentation.js";
import { createHostDuplexObservabilityRecorder } from "./duplex-observability-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 {
@@ -6707,14 +6706,6 @@ 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 = {
@@ -6838,7 +6829,6 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const envOrchestrator = environmentRunOrchestrator(db, {
pluginWorkerManager: options.pluginWorkerManager,
environmentRuntime,
duplexAggregateByteLedger: options.duplexAggregateByteLedger,
});
const workspaceOperationsSvc = workspaceOperationService(db);
const liveRunExecutions = {
+152 -380
View File
@@ -59,12 +59,6 @@ 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 {
isLoginCommandKey,
validateLoginSessionHome,
@@ -73,21 +67,6 @@ import {
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
// ---------------------------------------------------------------------------
@@ -193,14 +172,21 @@ const LOGIN_PTY_OPEN_FAILED = "LOGIN_PTY_OPEN_FAILED";
// login pseudo-terminal route, but it carries no command allowlist and adds seven
// explicit bounds the pseudo-terminal route lacks. Each bound ends the route when
// it passes the limit, so a faulty or hostile worker cannot flood the host.
/** The default maximum characters for one duplex channel data notification. */
const MAX_DUPLEX_CHANNEL_CHUNK_CHARS = 1_000_000;
/** The default maximum characters for one duplex channel data notification. This
* matches the host duplex frame bound ({@link DEFAULT_MAX_DUPLEX_FRAME_BYTES} in
* `duplex-frame-codec.ts`), so one chunk always fits inside one frame. */
const MAX_DUPLEX_CHANNEL_CHUNK_CHARS = 262_144;
/**
* The default maximum cumulative characters the host buffers for one duplex
* channel route before a data listener attaches. A worker that streams data
* before the consumer binds cannot grow the host buffer without limit.
* The default maximum cumulative bytes the host retains, on one duplex channel
* route, for input the worker has not yet delivered: the pre-bind hold (before
* the worker session id binds), the post-bind buffered queue (bound, before a
* data listener attaches), and the terminal buffer (a route that ended before
* a listener attached). All three representations share this one route-local
* bound, so a worker cannot grow any of them past it. This bound is a fixed
* share of the fixed per-route byte budget the host now bounds every duplex
* retention site against; it holds no measurement of real traffic.
*/
const MAX_DUPLEX_CHANNEL_PRE_BIND_CHARS = 8 * 1024 * 1024;
export const DUPLEX_ROUTE_INPUT_MAX_BYTES = 393_216;
/**
* The default maximum number of data frames the host buffers for one duplex
* channel route before a data listener attaches.
@@ -229,8 +215,21 @@ const DUPLEX_CHANNEL_PRE_BIND_HOLD_MARGIN_FRAMES = 1;
* unbounded number of pending requests.
*/
const MAX_DUPLEX_CHANNEL_PENDING_REQUESTS = 256;
/** The default maximum characters for one host→worker duplex channel write. */
const MAX_DUPLEX_CHANNEL_WRITE_CHARS = 1_000_000;
/** The default maximum characters for one host→worker duplex channel write. This
* matches the host duplex frame bound, so one write always fits inside one
* frame. */
const MAX_DUPLEX_CHANNEL_WRITE_CHARS = 262_144;
/**
* The default maximum cumulative bytes the host retains, on one duplex channel
* route, for a host→worker write the worker has not yet acknowledged: the raw
* write payload and the serialized child-stdin frame the host built from it.
* This bound is route-local and independent of the pending-request count
* bound above; a worker that never replies still cannot make one route hold
* an unbounded number of write bytes, even under a raised pending-request
* count. This bound is a fixed share of the fixed per-route byte budget; it
* holds no measurement of real traffic.
*/
export const DUPLEX_ROUTE_PENDING_WRITE_MAX_BYTES = 393_216;
/**
* The default maximum number of protocol errors for one duplex channel route.
* A protocol error is one malformed or mismatched data frame. The route ends
@@ -428,14 +427,6 @@ 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
@@ -504,6 +495,9 @@ export interface WorkerStartOptions {
maxPendingRequests?: number;
/** Max characters for one host→worker duplex channel write. */
maxWriteChars?: number;
/** Max cumulative bytes the host retains, for one route, for a
* host→worker write pending the worker's acknowledgement. */
maxPendingWriteBytes?: number;
/** Max number of protocol errors for one route before the route ends. */
maxProtocolErrors?: number;
/** Max cumulative bytes the host forwards for one route over its whole life. */
@@ -935,7 +929,7 @@ export function createPluginWorkerHandle(
options.duplexChannelLimits?.maxChunkChars ?? MAX_DUPLEX_CHANNEL_CHUNK_CHARS;
const maxDuplexChannelPreBindChars =
options.duplexChannelLimits?.maxPreBindBufferedChars ??
MAX_DUPLEX_CHANNEL_PRE_BIND_CHARS;
DUPLEX_ROUTE_INPUT_MAX_BYTES;
const maxDuplexChannelPreBindFrames =
options.duplexChannelLimits?.maxPreBindBufferedFrames ??
MAX_DUPLEX_CHANNEL_PRE_BIND_FRAMES;
@@ -949,6 +943,8 @@ export function createPluginWorkerHandle(
MAX_DUPLEX_CHANNEL_PENDING_REQUESTS;
const maxDuplexChannelWriteChars =
options.duplexChannelLimits?.maxWriteChars ?? MAX_DUPLEX_CHANNEL_WRITE_CHARS;
const maxDuplexRoutePendingWriteBytes =
options.duplexChannelLimits?.maxPendingWriteBytes ?? DUPLEX_ROUTE_PENDING_WRITE_MAX_BYTES;
const maxDuplexChannelProtocolErrors =
options.duplexChannelLimits?.maxProtocolErrors ??
MAX_DUPLEX_CHANNEL_PROTOCOL_ERRORS;
@@ -1025,42 +1021,11 @@ export function createPluginWorkerHandle(
// JSON-RPC message sending
// -----------------------------------------------------------------------
function sendMessage(message: unknown, meterDuplexWrite = false): void {
function sendMessage(message: unknown): 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);
}
@@ -1784,27 +1749,22 @@ export function createPluginWorkerHandle(
// 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 bytes and the aggregate byte token that reserved its raw bytes. The
// token is `null` when no ledger is injected.
// chunk bytes.
interface BufferedDuplexChunk {
chunk: Uint8Array;
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.
// retains only these bounded scalar fields, 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: Uint8Array;
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 {
@@ -1825,18 +1785,32 @@ export function createPluginWorkerHandle(
// 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.
// hold. The host never retains the original arbitrary notification graph.
preBind: HeldDuplexEvent[];
// The cumulative raw bytes `preBind` holds. `DUPLEX_ROUTE_INPUT_MAX_BYTES`
// bounds this route-local counter, so a worker cannot flood the pre-bind
// hold with bytes the frame-count ceiling alone does not catch (a handful
// of large frames, each well under the frame-count limit). This counter
// covers only the hold; the post-bind buffered queue counts its own bytes
// in `bufferedChars`, against the same named bound.
preBindBytes: number;
// 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 cumulative raw payload bytes of every host→worker write this route
// has sent but the worker has not yet acknowledged. The window this
// counter tracks spans both retained representations of a pending write:
// the raw payload the pending request object holds, and the serialized
// child-stdin frame the host builds from it and writes before the request
// settles. `DUPLEX_ROUTE_PENDING_WRITE_MAX_BYTES` bounds this route-local
// counter, independent of `pendingRequests`: a worker that never replies
// cannot make one route hold an unbounded number of write bytes, even
// under a raised pending-request count. `sendBoundedRequest` increments it
// before the send and decrements it once the request settles, on every
// path: a reply, a rejection, a timeout, a worker exit, or a shutdown.
pendingWriteBytes: number;
}
// The live duplex routes on this worker, keyed by the exact
// `{ hostRouteId, workerSessionId }` pair. The host binds one pair once, at
@@ -1862,89 +1836,11 @@ 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.
// keeps the worker-exit sweep able to clear its still-buffered representations.
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.
@@ -2042,34 +1938,16 @@ export function createPluginWorkerHandle(
route.terminalized = true;
route.state = "closed";
route.listener = null;
// 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);
}
}
// Stop admission first. 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.
// Register the route in the terminal registry, so the worker-exit sweep can
// clear the still-buffered chunks later.
route.preBind = [];
route.preBindBytes = 0;
route.preBindExit = null;
if (route.buffered.length > 0) {
terminalDuplexRoutes.add(route);
@@ -2156,16 +2034,8 @@ export function createPluginWorkerHandle(
}
// 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 {
// the chunk transiently. On a live route with no listener, buffer the chunk.
function routeDuplexChannelData(notification: JsonRpcNotification): void {
const params = isRecord(notification.params) ? notification.params : {};
const hostRouteId = readNonEmptyString(params.hostRouteId);
const workerSessionId = readNonEmptyString(params.workerSessionId);
@@ -2200,15 +2070,13 @@ export function createPluginWorkerHandle(
const chunk = rawChunk instanceof Uint8Array ? rawChunk : decodeChannelBytes(rawChunk);
if (chunk === null || chunk.byteLength === 0) {
// The exact pair matches, but the chunk is malformed or empty. Count one
// per-route protocol error. Release a carried replay token first.
releaseRouteToken(route, carried?.token ?? null);
// per-route protocol error.
recordDuplexChannelProtocolError(route);
return;
}
if (chunk.byteLength > 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;
}
@@ -2217,16 +2085,13 @@ export function createPluginWorkerHandle(
// data past the cap.
const chunkBytes = chunk.byteLength;
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.
// A listener is attached. Deliver the chunk transiently.
deliverDuplexChannelChunk(route.listener, chunk);
releaseRouteToken(route, carried?.token ?? null);
return;
}
// No listener attached yet. Buffer the frame under the pre-bind bounds. End
@@ -2235,28 +2100,10 @@ export function createPluginWorkerHandle(
route.buffered.length + 1 > maxDuplexChannelPreBindFrames ||
route.bufferedChars + chunk.length > maxDuplexChannelPreBindChars
) {
releaseRouteToken(route, carried?.token ?? null);
void terminalizeDuplexChannelRoute(route);
return;
}
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.buffered.push({ chunk });
route.bufferedChars += chunk.length;
}
@@ -2319,23 +2166,10 @@ export function createPluginWorkerHandle(
return;
}
if (notification.method === DUPLEX_CHANNEL_EXIT_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.
// Normalize the exit to the narrow duplex-event schema. A replaced exit
// simply overwrites the earlier held exit.
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,
};
route.preBindExit = { workerSessionId, exitCode };
return;
}
// A data event. Validate and normalize it to the narrow duplex-event schema
@@ -2350,20 +2184,16 @@ export function createPluginWorkerHandle(
recordDuplexChannelProtocolError(route);
return;
}
// Reserve the exact retained raw byte count before the host holds the event.
const reserved = reserveRouteBytes(route, "pre_bind_event", chunk.byteLength);
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");
// The route-local input bound covers the pre-bind hold directly. A handful
// of large frames can pass the frame-count ceiling above while still
// flooding the host with bytes, so this route ends at once on the byte
// bound, the same way the post-bind buffered queue already does.
if (route.preBindBytes + chunk.byteLength > maxDuplexChannelPreBindChars) {
void terminalizeDuplexChannelRoute(route);
return;
}
route.preBind.push({
workerSessionId,
chunk,
token: reserved === "no-ledger" ? null : reserved,
});
route.preBind.push({ workerSessionId, chunk });
route.preBindBytes += chunk.byteLength;
}
// Replay the frames a route held before it bound. The route is live now, so the
@@ -2376,36 +2206,29 @@ export function createPluginWorkerHandle(
function replayPreBindDuplexFrames(route: DuplexChannelRoute): void {
const held = route.preBind;
route.preBind = [];
route.preBindBytes = 0;
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);
// The route ended mid-replay. The remaining held events are dropped.
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,
},
// routing step and discards it at once.
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) {
// 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);
// Resolve the wait through the exact-pair routing when the route still lives.
if (!route.terminalized) {
routeDuplexChannelExit({
jsonrpc: "2.0",
@@ -2448,10 +2271,14 @@ export function createPluginWorkerHandle(
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 route's retained buffers, exactly once. A route already drained
// by a late listener holds nothing, so this is harmless.
route.preBind = [];
route.preBindBytes = 0;
route.preBindExit = null;
route.buffered = [];
route.bufferedChars = 0;
terminalDuplexRoutes.delete(route);
}
// Clear the terminal registry. Every route in it was just discarded above.
terminalDuplexRoutes.clear();
@@ -2486,8 +2313,9 @@ export function createPluginWorkerHandle(
terminalized: false,
settleWait,
preBind: [],
preBindBytes: 0,
preBindExit: null,
retainedTokens: new Set<ReservationToken>(),
pendingWriteBytes: 0,
};
// 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
@@ -2579,58 +2407,30 @@ export function createPluginWorkerHandle(
void terminalizeDuplexChannelRoute(route);
return;
}
// Reserve the exact raw 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. 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) {
pendingWriteToken = duplexAggregateByteLedger.reserve("pending_write", writeByteCount ?? 0);
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;
}
// The route-local pending-write byte bound: a worker that never replies
// cannot make one route hold an unbounded number of write bytes, even
// under a raised pending-request count. A stop request carries no
// payload, so it never counts against this bound.
const pendingWriteBytesToCharge = method === "duplexChannelWrite" ? writeByteCount ?? 0 : 0;
if (route.pendingWriteBytes + pendingWriteBytesToCharge > maxDuplexRoutePendingWriteBytes) {
void terminalizeDuplexChannelRoute(route);
return;
}
route.pendingRequests += 1;
// 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);
}
})
route.pendingWriteBytes += pendingWriteBytesToCharge;
void callInternal(method, params, duplexChannelOpenTimeoutMs, undefined)
// A send failure, an RPC rejection, a timeout, or a worker exit ends up
// here. The route already handles a lost write through its own state
// (a worker exit or a stop rejects every pending request through the
// normal call machinery), so this fire-and-forget call swallows the
// rejection instead of leaving it unhandled.
.catch(() => {})
.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);
}
// Release the route-local pending-write bytes one time, after the RPC
// settles on any path: success, error, timeout, worker exit, or
// shutdown.
route.pendingWriteBytes -= pendingWriteBytesToCharge;
});
};
@@ -2642,11 +2442,9 @@ export function createPluginWorkerHandle(
route.buffered = [];
route.bufferedChars = 0;
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.
// Deliver each buffered record 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.
@@ -2664,8 +2462,8 @@ export function createPluginWorkerHandle(
}
// Encode the raw bytes to the wire-safe base64 form (JSON carries no
// binary type) and pass the exact raw byte count separately, so the
// pending-write ledger reservation charges the real payload bytes, not
// the inflated base64 string length.
// pending-write byte bound charges the real payload bytes, not the
// inflated base64 string length.
sendBoundedRequest(
"duplexChannelWrite",
{
@@ -2961,16 +2759,11 @@ 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.
// The `error` listener stops an unhandled EPIPE from a child that closed its
// stdin.
if (child.stdin) {
child.stdin.on("error", () => {
releaseAllPendingStdinWriteTokens();
});
child.stdin.on("close", () => {
releaseAllPendingStdinWriteTokens();
});
child.stdin.on("error", () => {});
child.stdin.on("close", () => {});
}
// Capture stderr for logging
@@ -3023,12 +2816,6 @@ 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(
@@ -3364,7 +3151,6 @@ 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) {
@@ -3438,26 +3224,19 @@ export function createPluginWorkerHandle(
...createRequest(method, params, id),
...(invocation ? { paperclipInvocation: invocation } : {}),
};
sendMessage(request, meterDuplexWrite);
sendMessage(request);
} catch (err) {
clearTimeout(timer);
pendingRequests.delete(id);
clearInvocation(invocation);
clearExecuteRoute(invocation?.id);
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)
}`,
),
);
}
reject(
new Error(
`Failed to send "${method}" to worker: ${
err instanceof Error ? err.message : String(err)
}`,
),
);
}
});
@@ -3630,20 +3409,20 @@ 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;
}
/**
* The default process-scoped aggregate ceiling for concurrent duplex channel
* routes. It caps the manager-wide resource, not one agent's run budget. The host
* reports an explicit route-busy outcome when the ceiling is full.
*
* Known aggregate behavior: this ceiling bounds route count only, not
* retained bytes. Each HTTP/2 bridge route bounds its own retained body
* bytes to 8,388,608 bytes (see `HTTP2_BRIDGE_MAX_CONCURRENT_STREAMS` in
* `http2-bridge-server.ts`), so this route ceiling caps the process's
* aggregate retained body bytes at 128 * 8,388,608 = 1,073,741,824 bytes
* (1 GiB). This is accepted, known behavior, not a defect: the process
* tracks no aggregate byte ledger across routes.
*/
export const DEFAULT_MAX_CONCURRENT_DUPLEX_ROUTES = 128;
@@ -3709,11 +3488,6 @@ 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(
@@ -3735,11 +3509,9 @@ export function createPluginWorkerManager(
}
const handle = createPluginWorkerHandle(pluginId, {
// 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).
// Inject the shared process-scoped route-slot controller, unless the
// caller already supplied its own (a test may inject its own).
duplexRouteSlots,
duplexAggregateByteLedger,
...options,
});
workers.set(pluginId, handle);