fix(planning): accept one job message and one cancel per planning socket

A socket could send any number of messages after its first: each extra
plan started another calculation in the same worker, and a waiting
socket buffered without limit, so one client could exhaust the server's
memory. A socket now carries its job message and, for a plan, at most
one cancel; anything else closes it with 1008. Only a plan can be
promoted by a cancel, since other jobs ignore it and would run in full
beyond PLANNING_WORKERS.

A worker that exits on its own now closes its socket with 1011 and
frees its slot instead of holding it until the client gives up.

Refs #323, #324

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 authored and Nessar committed 2026-10-30 19:10:45 +01:00
1 parent 6e28939e26
commit a12e27bfdc
3 files changed
+126 -21

No files matched your search

+1 -1
View File
@@ -264,7 +264,7 @@ The server answers `GET` and `HEAD` only (other methods get 405), except at `/ap
The client sends its build identifier in the `build` query parameter; the server closes a socket from a different build (or without one) with code 4409 before sending any message, so that tab calculates locally with its own engine. Each client IP may hold five planning sockets at once. The IP is the `CF-Connecting-IP` header, or the address of the connection when the header is absent. The server closes a sixth socket from the same IP with code 4429 before sending any message, so that tab calculates locally with its own engine; closing a socket frees its place. The server also closes a socket whose incoming message exceeds about 1 MB (WebSocket code 1009, or an abnormal close) without running a calculation. The per-IP limit holds only if the origin accepts traffic from Cloudflare alone: anyone who can reach the origin directly can forge `CF-Connecting-IP` and bypass it.
At most `PLANNING_WORKERS` calculations run at once, each in its own worker; it defaults to half the CPU threads the container reports, which assumes two threads per core, so set it to the physical core count (throughput stops growing there). Other calculations wait in arrival order and the server sends a heartbeat every second so the client keeps waiting; no queue position is shown. A socket joins the line with its first message, so an idle open socket holds no worker. Cancel, or closing the socket, removes a waiting calculation, and a running one frees its place when it ends or its socket closes. Each calculation takes roughly 60 to 150 MB, and the production Compose file (`compose.prod.yml`) sets an 8 GB memory limit with no CPU limit.
At most `PLANNING_WORKERS` calculations run at once, each in its own worker; it defaults to half the CPU threads the container reports, which assumes two threads per core, so set it to the physical core count (throughput stops growing there). Other calculations wait in arrival order and the server sends a heartbeat every second so the client keeps waiting; no queue position is shown. A socket joins the line with its first message, so an idle open socket holds no worker. Closing the socket removes a waiting calculation. A waiting plan that its client cancels starts at once, even beyond `PLANNING_WORKERS`, and stops at its first yield with the worker's own cancelled outcome. A running calculation frees its place when it ends, fails or its socket closes. A client may send one job message and, for a plan, one `cancel`; any other message closes the socket with code 1008. Each calculation takes roughly 60 to 150 MB, and the production Compose file (`compose.prod.yml`) sets an 8 GB memory limit with no CPU limit.
Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host.
+103 -8
View File
@@ -25,12 +25,19 @@ let server: ReturnType<typeof createServer>;
let emptyServer: ReturnType<typeof createServer>;
const workers: CountingWorker[] = [];
// Set by a test to make the next server worker fail: it throws on construction, or runs a
// script that throws or exits instead of the planner.
let nextFault: 'throw' | 'error' | 'exit' | undefined;
// Records each server worker so a test can tell whether its own was terminated.
class CountingWorker extends BunWorker {
terminated = false;
constructor(...args: ConstructorParameters<typeof Worker>) {
super(...args);
constructor(entry: string | URL, options?: WorkerOptions) {
const fault = nextFault;
nextFault = undefined;
if (fault === 'throw') throw new Error('cannot start worker');
super(fault ? join(workdir, `fault-${fault}.js`) : entry, options);
workers.push(this);
}
@@ -391,6 +398,15 @@ describe('planning socket', () => {
return socket;
};
// Resolves with how a socket that just opened ends: planned by the server, or its close code.
const fate = (socket: ReturnType<typeof planningSocket>) => {
socket.send({ type: 'plan', request: PLAN });
return Promise.race([
socket.until('artifacts').then(() => 'admitted' as const),
socket.closed.then(({ code }) => code),
]);
};
it('refuses a sixth job from one IP, admits another IP, and frees a place on close', async () => {
const before = workers.length;
const held = [];
@@ -406,22 +422,24 @@ describe('planning socket', () => {
expect(refused.received).toEqual([]);
expect(workers).toHaveLength(before);
const other = await open('203.0.113.8');
other.send({ type: 'plan', request: PLAN });
expect((await other.until('result')).at(-1)?.['outcome']).toBeDefined();
// Refusals must not free places: the IP stays full however often it is refused.
for (let i = 0; i < PLANNING_JOBS_PER_CLIENT + 1; i++)
expect(await fate(await open('203.0.113.7'))).toBe(PLANNING_CLIENT_LIMIT);
expect(await fate(await open('203.0.113.8'))).toBe('admitted');
held[0].socket.close();
await held[0].closed;
// The server frees the place when it sees the close, shortly after the client does.
await vi.waitFor(
async () => {
const freed = client('203.0.113.7');
await freed.opened;
const freed = await open('203.0.113.7');
expect(await fate(freed)).toBe('admitted');
held.push(freed);
},
{ timeout: 5000 },
);
for (const socket of [...held, other]) socket.socket.close();
for (const socket of held) socket.socket.close();
}, 20_000);
it('closes an oversized first message without running a calculation', async () => {
@@ -483,6 +501,8 @@ describe('planning queue', () => {
socket.received.filter((message) => message.type === type).length;
beforeAll(() => {
writeFileSync(join(workdir, 'fault-error.js'), "throw new Error('boom');");
writeFileSync(join(workdir, 'fault-exit.js'), 'process.exit(0);');
queueServer = createServer({
root: join(workdir, 'empty'),
port: 0,
@@ -568,6 +588,81 @@ describe('planning queue', () => {
expect(count(first, 'result')).toBe(0);
}, 20_000);
it('closes a running plan socket with 1008 on a second plan and starts no second calculation', async () => {
const before = workers.length;
const first = await startPlan(loadedYear);
first.send({ type: 'plan', request: loadedYear });
expect((await first.closed).code).toBe(1008);
expect(workers.length - before).toBe(1);
}, 20_000);
it.each([
['a second plan', { type: 'plan', request: PLAN }],
['an unknown type', { type: 'heartbeat' }],
])(
'closes a waiting socket with 1008 on %s and buffers nothing',
async (_name, extra) => {
const before = workers.length;
const first = await startPlan(loadedYear);
const second = await startPlan(PLAN);
second.send(extra);
expect((await second.closed).code).toBe(1008);
first.socket.close();
await first.closed;
// Only the first calculation ever got a worker.
await new Promise((resolve) => setTimeout(resolve, 300));
expect(workers.length - before).toBe(1);
},
20_000,
);
it('closes a plan socket with 1008 on a second cancel', async () => {
const first = await startPlan(loadedYear);
const second = await startPlan(PLAN);
second.send({ type: 'cancel' });
second.send({ type: 'cancel' });
expect((await second.closed).code).toBe(1008);
first.socket.close();
}, 20_000);
it.each(['counterfactual', 'explain-checkpoint'])(
'closes a waiting %s socket with 1008 on a cancel, which only a plan takes',
async (type) => {
const before = workers.length;
const first = await startPlan(loadedYear);
const second = client();
await second.opened;
second.send({ type });
await vi.waitFor(() => expect(count(second, 'heartbeat')).toBeGreaterThan(0));
second.send({ type: 'cancel' });
expect((await second.closed).code).toBe(1008);
// It did not jump the line: no worker beyond the first one's.
expect(workers.length - before).toBe(1);
first.socket.close();
},
20_000,
);
it.each(['throw', 'error', 'exit'] as const)(
'closes with 1011, frees the slot and starts the next job when a worker fails by %s',
async (fault) => {
const first = await startPlan(loadedYear);
const failing = await startPlan(PLAN);
const next = await startPlan(PLAN);
nextFault = fault;
first.socket.close();
expect((await failing.closed).code).toBe(1011);
await next.until('artifacts');
expect(count(next, 'result')).toBe(1);
},
20_000,
);
it('lets an idle open socket neither start a worker nor hold a slot', async () => {
const before = workers.length;
const idle = client();
+22 -12
View File
@@ -90,8 +90,8 @@ class PlanningQueue {
}
}
// A cancelled calculation stops at its first yield, so it runs at once instead of waiting for a
// slot to learn the client gave up.
// A cancelled plan stops at its first yield, so it runs at once instead of waiting for a slot
// to report the client gave up. Only plans take a cancel.
promote(job: PlanningJob) {
this.leave(job);
this.run(job);
@@ -115,12 +115,13 @@ class PlanningQueue {
/**
* One planning socket = one worker job. Its first message fixes the kind and puts it in the
* queue; later messages are buffered until its worker starts. A job holds its slot only while
* 'running', released exactly once by a terminal message, a failure or the socket closing.
* queue; a single allowed cancel is buffered until its worker starts. A job holds its slot only
* while 'running', released exactly once by a terminal message, a failure or the socket closing.
*/
class PlanningJob {
private state: 'idle' | 'waiting' | 'running' | 'done' = 'idle';
private kind = '';
private cancelled = false;
private worker?: Worker;
private buffered: unknown[] = [];
private heartbeat?: ReturnType<typeof setInterval>;
@@ -156,6 +157,10 @@ class PlanningJob {
if (TERMINAL[this.kind]?.includes(event.data?.type)) this.stop();
});
worker.addEventListener('error', () => this.fail(1011, 'Planner worker failed'));
// A worker that exits on its own sends nothing else; stop() sets 'done' before terminating.
worker.addEventListener('close', () => {
if (this.state === 'running') this.fail(1011, 'Planner worker exited');
});
for (const message of this.buffered.splice(0)) worker.postMessage(message);
}
@@ -170,16 +175,21 @@ class PlanningJob {
}
const type = parsed?.type;
if (this.state === 'done') return;
if (this.state === 'idle') {
if (typeof type !== 'string' || !Object.hasOwn(TERMINAL, type))
return this.fail(1008, 'Unknown first message');
this.kind = type;
this.buffered.push(parsed);
return this.queue.submit(this);
}
// A client sends one job message and at most one cancel, and only for a plan: more would
// start extra calculations or grow the buffer without bound.
if (type !== 'cancel' || this.kind !== 'plan' || this.cancelled)
return this.fail(1008, 'Unexpected message');
this.cancelled = true;
if (this.state === 'running') return this.worker?.postMessage(parsed);
this.buffered.push(parsed);
if (this.state === 'waiting') {
if (type === 'cancel') this.queue.promote(this);
return;
}
if (typeof type !== 'string' || !Object.hasOwn(TERMINAL, type))
return this.fail(1008, 'Unknown first message');
this.kind = type;
this.queue.submit(this);
this.queue.promote(this);
}
// Safe to call after the socket closed or the job ended.