Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33911,9 +33911,13 @@ async function flushPending(): Promise<void> {
return;
}

const serialRemoteTurns = effectiveBackendType === 'remote-runner'
&& ((lastInitConfig?.backendConfig as import('./adapters/backend/remote-runner-config.js').RemoteRunnerConfig | undefined)
?.delegatedSlashCommands?.length ?? 0) > 0;
// The remote-runner backend serializes turns itself (its activeTurnId guard
// rejects a second in-flight turn with submitted:false). The flush FIFO gate
// must therefore apply to EVERY remote-runner session: tying it to
// delegatedSlashCommands made non-delegated sessions (the default) drain
// successor messages straight into the active turn, where the backend guard
// rejected them as submit_impossible and dropped the dequeued items (#3484).
const serialRemoteTurns = effectiveBackendType === 'remote-runner';
isFlushing = true;
const promptReadyAtFlushStart = isPromptReady;
let itemsWrittenInThisFlush = 0;
Expand Down
235 changes: 235 additions & 0 deletions test/worker-remote-runner-serial-fifo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
/**
* Regression for #3484: for a remote-runner session WITHOUT
* delegatedSlashCommands (the default), the flush FIFO gate
* (`serialRemoteTurns`) used to be switched off, so successor messages were
* written straight into the provider while the first turn was still active.
* RemoteRunnerBackend's activeTurnId guard rejected them with
* `{ submitted:false, reason:'remote runner turn ... is still active' }`, the
* worker emitted `submit_impossible` user notices and dropped the dequeued
* items — the 2nd/3rd rapid message were lost instead of queued and drained in
* order after the first turn settled.
*
* The test drives the REAL worker subprocess (via the shared ts-runner helper,
* same harness as worker-remote-runner.integration.test.ts) against a
* controllable fake provider that delays the first busy ACK and only emits
* finals when the test drops a release file. The exact FIFO order of provider
* turns after releasing each turn is the positive control that the queue drains.
*/
import { type ChildProcess } from 'node:child_process';
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { spawnTsScript } from './helpers/ts-runner.js';

const tempDirs: string[] = [];
const children: ChildProcess[] = [];

afterEach(() => {
for (const child of children.splice(0)) {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
}
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

async function waitFor(predicate: () => boolean, describeFailure: () => string, timeoutMs = 15_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise<void>(resolveDelay => setTimeout(resolveDelay, 50));
}
throw new Error(describeFailure());
}

function providerTurns(commandsPath: string): string[] {
if (!existsSync(commandsPath)) return [];
return readFileSync(commandsPath, 'utf8')
.trim()
.split('\n')
.filter(Boolean)
.map(line => { try { return JSON.parse(line); } catch { return null; } })
.filter((command): command is { type: string; turnId?: string } => !!command && command.type === 'turn')
.map(command => command.turnId ?? '');
}

describe('remote-runner serial FIFO for non-delegated sessions (#3484)', () => {
it('queues successor turns and drains them in order instead of rejecting busy successors', async () => {
const root = mkdtempSync(join(tmpdir(), 'botmux-rr-serial-3484-'));
tempDirs.push(root);
const dataDir = join(root, 'data');
const commandsPath = join(root, 'commands.jsonl');
const provider = join(root, 'provider.mjs');
const larkAppId = 'app_rr_serial_3484';
const turn1 = 'om_rrserial3484_m1';
const turn2 = 'om_rrserial3484_m2';
const turn3 = 'om_rrserial3484_m3';

// First turn's busy ACK is delayed so the successor messages are enqueued
// while the first drain is in flight; finals are release-file gated so the
// test controls drain order deterministically.
writeFileSync(provider, `#!/usr/bin/env node
import fs from 'node:fs';
import readline from 'node:readline';
import { join } from 'node:path';
const emit = event => process.stdout.write(JSON.stringify({ protocol: 'botmux.remote-runner', version: 1, ...event }) + String.fromCharCode(10));
const seen = ${JSON.stringify(commandsPath)};
const root = ${JSON.stringify(root)};
const PROVIDER = 'rr-serial-3484-provider';
let state = { version: 1, provider: PROVIDER, generation: 1, remoteSessionId: 'compute', agentThreadId: 'old' };
readline.createInterface({ input: process.stdin, crlfDelay: Infinity }).on('line', line => {
let command;
try { command = JSON.parse(line); } catch { return; }
fs.appendFileSync(seen, JSON.stringify(command) + '\\n');
if (command.type === 'hello') {
return emit({ type: 'hello', requestId: command.requestId, provider: PROVIDER,
capabilities: ['start', 'resume', 'turn', 'cancel', 'detach', 'reattach', 'status'] });
}
if (command.type === 'start' || command.type === 'resume') {
return emit({ type: 'ready', requestId: command.requestId, state });
}
if (command.type === 'turn') {
const sendBusy = () => emit({ type: 'status', requestId: command.requestId, status: 'busy', state });
if (command.turnId && command.turnId.endsWith('_m1')) setTimeout(sendBusy, 600);
else sendBusy();
const release = join(root, 'final-' + command.turnId);
const timer = setInterval(() => {
if (!fs.existsSync(release)) return;
clearInterval(timer);
state = { ...state, agentThreadId: 'done-' + command.turnId };
emit({ type: 'final', turnId: command.turnId, content: 'FINAL_' + command.turnId, state });
}, 10);
return;
}
if (command.type === 'cancel') return emit({ type: 'status', requestId: command.requestId, status: 'closed', state });
if (command.type === 'detach') return emit({ type: 'status', requestId: command.requestId, status: 'detached', state });
if (command.type === 'status') return emit({ type: 'status', requestId: command.requestId, status: 'ready', state });
});
`);
chmodSync(provider, 0o755);

// Deliberately NO delegatedSlashCommands: the default session shape that
// hit the bug.
const botsPath = join(root, 'bots.json');
writeFileSync(botsPath, JSON.stringify([{
larkAppId,
larkAppSecret: 'secret',
cliId: 'remote-runner',
backendType: 'remote-runner',
cliPathOverride: provider,
remoteRunner: {
expectedProvider: 'rr-serial-3484-provider',
requiredCapabilities: ['start', 'resume', 'turn', 'cancel', 'detach', 'reattach', 'status'],
},
}]));

const messages: any[] = [];
const logs: string[] = [];
const child = spawnTsScript(resolve('src/worker.ts'), [], {
cwd: resolve('.'),
env: {
...process.env,
HOME: root,
SESSION_DATA_DIR: dataDir,
BOTS_CONFIG: botsPath,
BOTMUX_SESSION_ID: 'sid-rr-serial-3484',
LARK_APP_ID: larkAppId,
LARK_APP_SECRET: 'secret',
},
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
});
children.push(child);
child.stdout?.on('data', chunk => logs.push(String(chunk)));
child.stderr?.on('data', chunk => logs.push(String(chunk)));
child.on('message', raw => {
messages.push(raw);
if (raw?.type === 'link_ref_restore_mode') {
child.send({ type: 'link_ref_restore_mode_result', requestId: raw.requestId, mode: 'enabled' });
}
});

child.send({
type: 'init',
sessionId: 'sid-rr-serial-3484',
chatId: 'oc_rr_serial_3484',
rootMessageId: 'om_root_rr_serial_3484',
workingDir: root,
cliId: 'remote-runner',
cliPathOverride: provider,
backendType: 'remote-runner',
backendConfig: {
expectedProvider: 'rr-serial-3484-provider',
requiredCapabilities: ['start', 'resume', 'turn', 'cancel', 'detach', 'reattach', 'status'],
},
prompt: '',
larkAppId,
larkAppSecret: 'secret',
});

await waitFor(
() => messages.some(message => message?.type === 'ready'),
() => `worker did not become ready\n${logs.join('')}\n${JSON.stringify(messages).slice(0, 2000)}`,
);
await new Promise(resolveDelay => setTimeout(resolveDelay, 500));

const sendMessage = (turnId: string, content: string) => {
child.send({
type: 'message',
content,
turnId,
trustedCaller: { requestUserOpenId: 'ou_rr_serial_user', requestLarkAppId: larkAppId, senderType: 'user' },
});
};

sendMessage(turn1, 'serial fifo message 1');
await waitFor(
() => providerTurns(commandsPath).includes(turn1),
() => `provider never saw m1\n${logs.join('')}\n${existsSync(commandsPath) ? readFileSync(commandsPath, 'utf8') : '(commands.jsonl missing)'}`,
);
// Let the first drain settle with m1 active before queuing successors.
await new Promise(resolveDelay => setTimeout(resolveDelay, 250));

sendMessage(turn2, 'serial fifo message 2');
sendMessage(turn3, 'serial fifo message 3');

// Observation window: on the old gate code m2/m3 are rejected within ~1s
// with submit_impossible notices; the fixed gate keeps them queued.
await new Promise(resolveDelay => setTimeout(resolveDelay, 4000));

const stillActiveNotices = messages
.filter(message => message?.type === 'user_notify' && typeof message.message === 'string'
&& message.message.includes('is still active'));
expect(stillActiveNotices, `busy-successor rejection notices:\n${JSON.stringify(stillActiveNotices, null, 2)}\n${logs.join('')}`)
.toHaveLength(0);
// Only m1 has reached the provider; m2/m3 are queued in the worker.
expect(providerTurns(commandsPath)).toEqual([turn1]);

// Release in FIFO order; each final re-arms the queue and drains the next.
writeFileSync(join(root, `final-${turn1}`), 'go');
await waitFor(
() => providerTurns(commandsPath).includes(turn2),
() => `m2 was not drained after m1 final\n${logs.join('')}`,
);

writeFileSync(join(root, `final-${turn2}`), 'go');
await waitFor(
() => providerTurns(commandsPath).includes(turn3),
() => `m3 was not drained after m2 final\n${logs.join('')}`,
);

writeFileSync(join(root, `final-${turn3}`), 'go');
for (const turnId of [turn1, turn2, turn3]) {
await waitFor(
() => messages.some(message => message?.type === 'turn_terminal'
&& message.turnId === turnId && message.status === 'completed'),
() => `turn ${turnId} did not complete\n${logs.join('')}\n${JSON.stringify(messages.filter(m => m?.turnId === turnId))}`,
20_000,
);
}

// The provider saw all three turns in exactly FIFO order.
expect(providerTurns(commandsPath)).toEqual([turn1, turn2, turn3]);
expect(messages
.filter(message => message?.type === 'user_notify' && typeof message.message === 'string'
&& message.message.includes('is still active'))).toHaveLength(0);
}, 90_000);
});
Loading