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
7 changes: 5 additions & 2 deletions bin/claude-code-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,9 @@ const chains = new Map();
const enqueue = (key, job) => {
const prev = chains.get(key) || Promise.resolve();
const run = prev.then(job, job);
chains.set(key, run.catch(() => {}));
const stored = run.catch(() => {});
chains.set(key, stored);
stored.then(() => { if (chains.get(key) === stored) chains.delete(key); });
return run;
};

Expand Down Expand Up @@ -700,7 +702,8 @@ const server = http.createServer((req, res) => {
endpoint: '/v1/chat/completions',
sessions: {
live: [...liveSessions.values()].filter(s => !s.dead).length,
stored: sessionStore.size
stored: sessionStore.size,
chains: chains.size
}
}, null, 2));
return;
Expand Down
38 changes: 38 additions & 0 deletions bin/claude-code-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,41 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t
assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies');
await alive.text();
});

test('chain map self-deletes settled entries; same-key turns stay ordered (#2407)', async (t) => {
const { base, child, logPath } = await startProxy();
t.after(() => child.kill('SIGKILL'));
const chainsNow = async () => (await (await fetch(base + '/health')).json()).sessions.chains;
const waitChainsEmpty = async () => {
const deadline = Date.now() + 5000;
for (;;) {
const n = await chainsNow();
if (n === 0) return;
if (Date.now() > deadline) assert.fail('chains map must be empty after settle, got ' + n);
await new Promise(r => setTimeout(r, 50));
}
};

// Two distinct keys through enqueue: both settle, map must empty.
for (const id of ['leak-a', 'leak-b']) {
const r = await chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'hello ' + id }] }, { 'x-session-id': id });
assert.equal(r.status, 200);
await r.json();
}
await waitChainsEmpty();

// Same key: second turn enqueued while the first is in flight must run
// after it, in order, and the map must empty afterwards.
const headers = { 'x-session-id': 'order-key' };
const p1 = chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'order first' }] }, headers);
await new Promise(r => setTimeout(r, 100));
const p2 = chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'order second' }] }, headers);
const [r1, r2] = await Promise.all([p1, p2]);
assert.equal(r1.status, 200); await r1.json();
assert.equal(r2.status, 200); await r2.json();
const received = fs.readFileSync(logPath, 'utf-8');
const i1 = received.indexOf('order first');
const i2 = received.indexOf('order second');
assert.ok(i1 !== -1 && i2 !== -1 && i1 < i2, 'same-key turns must reach the engine in enqueue order');
await waitChainsEmpty();
});
5 changes: 4 additions & 1 deletion bin/commandcode-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,9 @@ const acp = {
() => this.runChatLocked({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency, lockKey }),
() => this.runChatLocked({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency, lockKey })
);
this.locks.set(lockKey, run.catch(() => {}));
const stored = run.catch(() => {});
this.locks.set(lockKey, stored);
stored.then(() => { if (this.locks.get(lockKey) === stored) this.locks.delete(lockKey); });
return run;
},

Expand Down Expand Up @@ -870,6 +872,7 @@ const server = http.createServer((req, res) => {
pid: acp.proc ? acp.proc.pid : null,
starts: acp.starts,
liveThreads: acp.liveSessions.size,
locks: acp.locks.size,
storedMappings: sessionStore.size
}
}, null, 2));
Expand Down
60 changes: 60 additions & 0 deletions bin/commandcode-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,63 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t
assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies');
await alive.text();
});

test('ACP lock map self-deletes settled entries (#2407)', async (t) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-locks-test-'));
const stubHome = path.join(tmp, 'home');
const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin');
fs.mkdirSync(stubBin, { recursive: true });
fs.writeFileSync(path.join(stubBin, 'commandcode'), ACP_STUB, { mode: 0o755 });

const port = 18950;
const env = {
...process.env,
HOME: stubHome,
COMMANDCODE_PROXY_PORT: String(port),
COMMANDCODE_PROXY_HOST: '127.0.0.1',
COMMANDCODE_PROXY_EGRESS: '',
COMMANDCODE_PROXY_TIMEOUT_MS: '30000',
COMMANDCODE_PROXY_WORKDIR: path.join(tmp, 'work'),
};
const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
t.after(() => { try { child.kill('SIGKILL'); } catch {} });
await waitFor('http://127.0.0.1:' + port + '/health');

const chatH = async (body, headers = {}) => {
const res = await fetch('http://127.0.0.1:' + port + '/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
});
const text = await res.text();
assert.equal(res.status, 200, 'expected 200, got ' + res.status + ': ' + text.slice(0, 300));
return JSON.parse(text);
};
const locksNow = async () => (await (await fetch('http://127.0.0.1:' + port + '/health')).json()).acp.locks;
const waitLocksEmpty = async () => {
const deadline = Date.now() + 5000;
for (;;) {
const n = await locksNow();
if (n === 0) return;
if (Date.now() > deadline) assert.fail('locks map must be empty after settle, got ' + n);
await new Promise(r => setTimeout(r, 50));
}
};

// Two distinct session keys through runChat's lock chain.
for (const id of ['cc-leak-a', 'cc-leak-b']) {
const res = await chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi ' + id }], stream: false }, { 'x-session-id': id });
assert.equal(res.choices[0].message.content, 'ACP-OK');
}
await waitLocksEmpty();

// Same key back-to-back: both complete and the map empties afterwards.
const h = { 'x-session-id': 'cc-order-key' };
const [r1, r2] = await Promise.all([
chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'first' }], stream: false }, h),
chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'second' }], stream: false }, h),
]);
assert.equal(r1.choices[0].message.content, 'ACP-OK');
assert.equal(r2.choices[0].message.content, 'ACP-OK');
await waitLocksEmpty();
});
7 changes: 5 additions & 2 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,9 @@ const warmChains = new Map();
const enqueueWarm = (key, job) => {
const prev = warmChains.get(key) || Promise.resolve();
const run = prev.then(job, job);
warmChains.set(key, run.catch(() => {}));
const stored = run.catch(() => {});
warmChains.set(key, stored);
stored.then(() => { if (warmChains.get(key) === stored) warmChains.delete(key); });
return run;
};

Expand Down Expand Up @@ -1428,7 +1430,8 @@ const server = http.createServer((req, res) => {
enabled: WARM_ENABLED,
hostGen: warmHost.gen,
hostUp: Boolean(warmHost.child),
sessions: warmStore.map.size
sessions: warmStore.map.size,
chains: warmChains.size
},
direct: {
enabled: DIRECT_ENABLED,
Expand Down
42 changes: 42 additions & 0 deletions bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -958,3 +958,45 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t
assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies');
await alive.text();
});

test('warm chain map self-deletes settled entries; same-key turns stay ordered (#2407)', async (t) => {
const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' });
t.after(stop);
const chainsNow = async () => (await (await fetch('http://127.0.0.1:' + port + '/health')).json()).warm.chains;
const waitChainsEmpty = async () => {
const deadline = Date.now() + 5000;
for (;;) {
const n = await chainsNow();
if (n === 0) return;
if (Date.now() > deadline) assert.fail('warmChains map must be empty after settle, got ' + n);
await new Promise(r => setTimeout(r, 50));
}
};

// Two distinct conversation keys through enqueueWarm.
for (const first of ['leak alpha', 'leak gamma']) {
const res = JSON.parse(await chat(port, { model: 'muse-spark-1.3', messages: [{ role: 'user', content: first }] }));
assert.equal(res.choices[0].message.content, 'RE:' + first);
}
await waitChainsEmpty();

// Same key: turn 2 enqueued while turn 1 is in flight runs after it, on
// the same single MSP session, in order.
const p1 = chat(port, { model: 'muse-spark-1.3', messages: [{ role: 'user', content: 'order one' }] });
await new Promise(r => setTimeout(r, 50));
const p2 = chat(port, {
model: 'muse-spark-1.3',
messages: [
{ role: 'user', content: 'order one' },
{ role: 'assistant', content: 'RE:order one' },
{ role: 'user', content: 'order two' }
]
});
const [t1, t2] = await Promise.all([p1.then(r => JSON.parse(r)), p2.then(r => JSON.parse(r))]);
assert.equal(t1.choices[0].message.content, 'RE:order one');
assert.equal(t2.choices[0].message.content, 'RE:order two');
const log = fs.readFileSync(logFile, 'utf-8').trim().split('\n');
const turns = log.filter(l => l.startsWith('TURN')).map(l => l.slice(5));
assert.deepEqual(turns.slice(-2), ['order one', 'order two'], 'same-key turns must run in enqueue order');
await waitChainsEmpty();
});