Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
176 changes: 167 additions & 9 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ import {
PROMPT_CANCEL_METHOD,
TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,
sessionCloseDrainBudgetMs,
} from './bridgeTypes.js';

function deferred<T>(): {
Expand Down Expand Up @@ -392,6 +393,147 @@ describe('createAcpSessionBridge', () => {
await bridge.shutdown();
});

it('honors a deferred spawn-owner kill for an incomplete child', async () => {
const handle = makeChannel({
initializeImpl: () =>
activeWorkInitializeResponse({
categories: [...ACTIVE_WORK_LEGACY_HOLD_CATEGORIES],
}),
});
const bridge = makeBridge({
channelFactory: async () => handle.channel,
sessionReapIntervalMs: 0,
});
try {
const owner = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const attacher = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
await sendActiveWorkSnapshot(handle, 1, [
{ sessionId: owner.sessionId, holds: [] },
]);

await expect(
bridge.killSession(owner.sessionId, {
requireZeroAttaches: true,
}),
).resolves.toBe(false);
await bridge.detachClient(attacher.sessionId, attacher.clientId);

expect(bridge.sessionCount).toBe(0);
} finally {
await bridge.shutdown();
}
});

it('defers a tombstoned kill while a conditional close probe is in flight', async () => {
// The reaper ignores clientIds, so it can start a conditional-close
// probe on a tombstoned entry whose stale attacher never detached. The
// probe holds the child's close gate for up to the round-trip timeout;
// a kill fired in that window reaches the child as 'Session close is
// already in progress' and `killSession` escalates any close error to a
// channel kill, taking every sibling session down with it.
const probe = deferred<Record<string, unknown>>();
let conditionalCloseCalls = 0;
let forcedCloseCalls = 0;
const handle = makeChannel({
initializeImpl: () => activeWorkInitializeResponse(),
extMethodImpl: async (method, params) => {
if (method !== SERVE_CONTROL_EXT_METHODS.sessionClose) return {};
if (params[ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM] === true) {
conditionalCloseCalls++;
return await probe.promise;
}
forcedCloseCalls++;
return { closed: true, holds: [] };
},
});
const bridge = makeBridge({
channelFactory: async () => handle.channel,
sessionReapIntervalMs: 10,
sessionIdleTimeoutMs: 10,
});
try {
const owner = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const attacher = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
await sendActiveWorkSnapshot(handle, 1, [
{ sessionId: owner.sessionId, holds: [] },
]);

await expect(
bridge.killSession(owner.sessionId, {
requireZeroAttaches: true,
}),
).resolves.toBe(false);
await vi.waitFor(() => expect(conditionalCloseCalls).toBe(1));

// The stale attacher's late teardown detach must not fire the
// deferred kill into the in-flight probe.
await bridge.detachClient(attacher.sessionId, attacher.clientId);
await new Promise((resolve) => setTimeout(resolve, 40));
expect(forcedCloseCalls).toBe(0);
expect(handle.killed).toBe(false);
expect(bridge.sessionCount).toBe(1);

// The probe refuses: the entry is retained and the in-flight flag
// clears, so the tombstone is not stuck — the next idle report
// completes the kill through the ordinary deferred path.
probe.resolve({ closed: false, holds: [agentHold('turn-1')] });
await new Promise((resolve) => setTimeout(resolve, 40));
expect(forcedCloseCalls).toBe(0);
expect(bridge.sessionCount).toBe(1);

await sendActiveWorkSnapshot(handle, 2, [
{ sessionId: owner.sessionId, holds: [] },
]);
await vi.waitFor(() => expect(bridge.sessionCount).toBe(0));
expect(forcedCloseCalls).toBe(1);
} finally {
await bridge.shutdown();
}
});

it('does not escalate a deferred kill while a force close is in flight', async () => {
// A close already under way holds `entry.closing`; a deferred kill
// fired into it takes killSession's closing branch, which force-kills
// the whole channel. The detach that completes the tombstone must
// leave the in-flight close alone.
const closeGate = deferred<Record<string, unknown>>();
let forcedCloseCalls = 0;
const handle = makeChannel({
extMethodImpl: async (method) => {
if (method !== SERVE_CONTROL_EXT_METHODS.sessionClose) return {};
forcedCloseCalls++;
return await closeGate.promise;
},
});
const bridge = makeBridge({
channelFactory: async () => handle.channel,
sessionReapIntervalMs: 0,
});
try {
const owner = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const attacher = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
await expect(
bridge.killSession(owner.sessionId, {
requireZeroAttaches: true,
}),
).resolves.toBe(false);

const close = bridge.closeSession(owner.sessionId);
await vi.waitFor(() => expect(forcedCloseCalls).toBe(1));

await bridge.detachClient(attacher.sessionId, attacher.clientId);
await new Promise((resolve) => setTimeout(resolve, 40));
expect(handle.killed).toBe(false);
expect(bridge.sessionCount).toBe(1);

closeGate.resolve({ closed: true, holds: [] });
await close;
expect(bridge.sessionCount).toBe(0);
} finally {
await bridge.shutdown();
}
});

it('accepts the aggregate shell hold as active work', async () => {
const handle = makeChannel({
initializeImpl: () => activeWorkInitializeResponse(),
Expand Down Expand Up @@ -743,7 +885,11 @@ describe('createAcpSessionBridge', () => {
await bridge.detachClient(session.sessionId, session.clientId);

await vi.waitFor(() => expect(closeCalls.length).toBe(1));
expect(closeCalls[0]?.['sessionId']).toBe(session.sessionId);
expect(closeCalls[0]).toMatchObject({
sessionId: session.sessionId,
[ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM]: true,
drainTimeoutMs: sessionCloseDrainBudgetMs(ACTIVE_WORK_CLOSE_TIMEOUT_MS),
});
await vi.waitFor(() => expect(bridge.sessionCount).toBe(0));

await bridge.shutdown();
Expand Down Expand Up @@ -10617,13 +10763,17 @@ describe('createAcpSessionBridge', () => {
vi.useFakeTimers();
const lateRestore = deferred<LoadSessionResponse>();
const first = makeChannel({
initializeImpl: () =>
activeWorkInitializeResponse({
categories: [...ACTIVE_WORK_LEGACY_HOLD_CATEGORIES],
}),
loadSessionImpl: () => lateRestore.promise,
extMethodImpl: (method, params) => {
if (
method === SERVE_CONTROL_EXT_METHODS.sessionClose &&
params['sessionId'] === 'restore-cleanup-fails'
) {
throw new Error('late close failed');
if (method === SERVE_CONTROL_EXT_METHODS.sessionClose) {
if (params['sessionId'] === 'restore-cleanup-fails') {
throw new Error('late close failed');
}
return { closed: true, holds: [] };
}
return {};
},
Expand Down Expand Up @@ -10653,7 +10803,7 @@ describe('createAcpSessionBridge', () => {
method: SERVE_CONTROL_EXT_METHODS.sessionClose,
params: {
sessionId: 'restore-cleanup-fails',
drainTimeoutMs: 8_000,
drainTimeoutMs: sessionCloseDrainBudgetMs(10_000),
},
});
// An uncertain cleanup is the outcome an operator most needs to see,
Expand Down Expand Up @@ -10699,8 +10849,16 @@ describe('createAcpSessionBridge', () => {
}),
).resolves.toMatchObject({ stopReason: 'end_turn' });

await bridge.closeSession(sibling.sessionId);
await bridge.detachClient(sibling.sessionId, sibling.clientId);
await vi.advanceTimersByTimeAsync(0);
expect(first.agent.extMethodCalls).toContainEqual({
method: SERVE_CONTROL_EXT_METHODS.sessionClose,
params: {
sessionId: sibling.sessionId,
drainTimeoutMs: sessionCloseDrainBudgetMs(10_000),
},
});
expect(bridge.sessionCount).toBe(0);
expect(first.killed).toBe(true);
await vi.advanceTimersByTimeAsync(0);
await expect(
Expand Down Expand Up @@ -23239,7 +23397,7 @@ describe('createAcpSessionBridge', () => {
method: 'qwen/control/session/close',
params: {
sessionId: session.sessionId,
drainTimeoutMs: 8_000,
drainTimeoutMs: sessionCloseDrainBudgetMs(10_000),
requireFlush: true,
},
});
Expand Down
31 changes: 26 additions & 5 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ import {
TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,
WORKTREE_MCP_DEFER_META_KEY,
isValidTrustedModelPrompt,
sessionCloseDrainBudgetMs,
} from './bridgeTypes.js';
import { getChannelStartupProfileAttributes } from './channel-startup-profile.js';
import type {
Expand Down Expand Up @@ -2499,17 +2500,34 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
entry: SessionEntry,
reason: string,
): Promise<void> {
if (!entryIsAutoCloseCandidate(entry)) return;
// Note the asymmetry, preserved from the call sites this replaces: the
// kill path keys off `attachCount`, the close path off `clientIds`. A
// spawn owner that asked for a kill gets one once nothing is attached,
// even if some client id is still registered.
if (entry.spawnOwnerWantedKill && entry.attachCount === 0) {
// even if some client id is still registered. This is a deferred explicit
// kill, so incomplete child reporting must not turn it into ordinary
// cleanup or leave it pending forever.
//
// `activeWorkCloseInFlight` must stay excluded (the auto-close candidacy
// gate used to cover it): the reaper can be mid-probe on this same entry,
// holding the child's close gate for up to `ACTIVE_WORK_CLOSE_TIMEOUT_MS`.
// A kill fired in that window reaches `beginClose()` as 'Session close is
// already in progress', and `killSession` escalates any close error to a
// channel kill — taking down every sibling session with it. The in-flight
// probe resolves this entry one way or the other; if it retains, the
// tombstone completes on the next settle event.
if (
byId.get(entry.sessionId) === entry &&
!entry.closing &&
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
!entry.activeWorkCloseInFlight &&
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
entry.spawnOwnerWantedKill &&
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
entry.attachCount === 0
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
) {
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
await bridgeApi.killSession(entry.sessionId).catch(() => {
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
/* best-effort; channel.exited will eventually reap anyway */
});
return;
}
if (!entryIsAutoCloseCandidate(entry)) return;
if (entry.clientIds.size > 0) return;
await closeIfChildUnheld(entry, {
trigger: reason,
Expand Down Expand Up @@ -2610,6 +2628,9 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
entry.connection.extMethod(SERVE_CONTROL_EXT_METHODS.sessionClose, {
sessionId: entry.sessionId,
[ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM]: true,
drainTimeoutMs: sessionCloseDrainBudgetMs(
ACTIVE_WORK_CLOSE_TIMEOUT_MS,
),
}),
ACTIVE_WORK_CLOSE_TIMEOUT_MS,
SERVE_CONTROL_EXT_METHODS.sessionClose,
Expand Down Expand Up @@ -5004,7 +5025,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
SERVE_CONTROL_EXT_METHODS.sessionClose,
{
sessionId: entry.sessionId,
drainTimeoutMs: Math.max(1, Math.floor(initTimeoutMs * 0.8)),
drainTimeoutMs: sessionCloseDrainBudgetMs(initTimeoutMs),
...(opts?.requireFlush === true ? { requireFlush: true } : {}),
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
},
);
Expand Down Expand Up @@ -6287,7 +6308,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
SERVE_CONTROL_EXT_METHODS.sessionClose,
{
sessionId: req.sessionId,
drainTimeoutMs: Math.max(1, Math.floor(initTimeoutMs * 0.8)),
drainTimeoutMs: sessionCloseDrainBudgetMs(initTimeoutMs),
},
),
initTimeoutMs,
Expand Down
12 changes: 12 additions & 0 deletions packages/acp-bridge/src/bridgeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,18 @@ export const ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM = 'onlyIfUnheld';
* longer buys nothing — an unanswered request is simply left for the next
* snapshot to settle. */
export const ACTIVE_WORK_CLOSE_TIMEOUT_MS = 10_000;

/**
* The child's drain budget for a `sessionClose` round trip: strictly under
* the daemon's outer wait so the child deadline always fires first, clamped
* to ≥1ms so a tiny outer wait still yields a usable budget. An outer wait
* that fires first leaves the close outcome unknown, which the close path
* recovers by killing the whole channel — the coupling lives here exactly
* once so the ratio cannot drift between call sites.
*/
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
export function sessionCloseDrainBudgetMs(outerWaitMs: number): number {
return Math.max(1, Math.floor(outerWaitMs * 0.8));
}
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
Comment on lines +228 to +230

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] R4-8: The docstring invariant — "strictly under the daemon's outer wait so the child deadline always fires first" — does not hold for outerWaitMs === 1: the clamp yields a budget equal to the outer wait (the new unit test even pins sessionCloseDrainBudgetMs(1) === 1 while its strictly-under loop starts at 2). initializeTimeoutMs is validated only as > 0 (bridge.ts:2220), so a 1ms outer wait is constructible and the two deadlines race — the failure mode the docstring says this function exists to prevent. Practical impact is negligible (a 1ms outer wait makes every close round trip an unknown outcome regardless of the budget), so scoping the doc is an adequate fix. — Failure scenario: initializeTimeoutMs: 1 → drainTimeoutMs: 1 against a 1ms outer wait → the outer fires first → close outcome unknown → the close path recovers by killing the whole channel.

Suggested fix: state the ≥2ms precondition in the doc comment (keeping the pinned test honest) — or, for outerWaitMs >= 2 where both invariants are satisfiable, return Math.max(1, Math.min(outerWaitMs - 1, Math.floor(outerWaitMs * 0.8))).

中文说明

docstring 断言的不变量——“严格小于 daemon 的外层等待,使 child 截止总是先触发”——在 outerWaitMs === 1 时不成立:clamp 使预算恰好等于外层等待(新的单元测试甚至钉住 sessionCloseDrainBudgetMs(1) === 1,而其“严格小于”的循环从 2 开始)。initializeTimeoutMs 只校验 > 0(bridge.ts:2220),因此 1ms 外层等待是可构造的,两个截止时间会竞速——正是 docstring 声称本函数要防止的失效形态。实际影响可忽略(1ms 外层等待下,无论预算多少,每次关闭往返都是结果未知),因此限定文档范围即为充分修复。失败场景:initializeTimeoutMs: 1 → 1ms 外层等待下发送 drainTimeoutMs: 1 → 外层先触发 → 关闭结果未知 → 关闭恢复路径杀掉整个 channel。

建议修复:在文档注释中注明 ≥2ms 前提(使被钉住的测试保持诚实)——或在 outerWaitMs >= 2(两个不变量可同时满足)时返回 Math.max(1, Math.min(outerWaitMs - 1, Math.floor(outerWaitMs * 0.8)))。

— qwen3.8-max via Qwen Code /review (v0.21.11)

/** Bounds on a single snapshot. Generous next to any real deployment — they
* exist so a version-skewed or buggy child cannot make the daemon walk an
* unbounded structure per report, not to constrain legitimate use. A packet
Expand Down
Loading
Loading