Skip to content

Commit c6f2dda

Browse files
cliffhallclaude
andcommitted
fix(filesystem): wake calls waiting on a replaced roots refresh
Tool calls waited on the refresh promise itself, so a call that started waiting on refresh A stayed blocked on A's roots/list even after a newer refresh B had installed itself and applied the client's current roots; a slow or unanswered A stalled calls until its request timed out. The barrier is now separate from the refresh: each refresh installs a new barrier before it sends roots/list and settles it when it finishes, and installing one settles the barrier it replaces, so waiting calls wake and move on to the newest. This also makes the microtask deferral from the previous commits unnecessary (the barrier is installed synchronously). New test: a call waiting on an unanswered older refresh completes once a newer one finishes; it times out with the previous barrier (Copilot on #5103). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 4d2d9e5 commit c6f2dda

2 files changed

Lines changed: 87 additions & 42 deletions

File tree

‎src/filesystem/__tests__/server-roots.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,48 @@ describe("roots/list_changed", () => {
660660
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
661661
});
662662

663+
// A call waiting on an older refresh must not stay blocked on it once a newer
664+
// refresh has applied the client's current roots (#5101).
665+
it("wakes a call waiting on an older refresh once a newer one finishes (#5101)", async () => {
666+
await fs.writeFile(path.join(rootDir, "a.txt"), "a");
667+
let calls = 0;
668+
let releaseOlder!: () => void;
669+
const olderHeld = new Promise<void>((resolve) => (releaseOlder = resolve));
670+
const { client } = await connectTracked([], {
671+
capabilities: ROOTS,
672+
listRoots: async () => {
673+
calls += 1;
674+
if (calls === 1) return [rootOf(rootDir)];
675+
if (calls === 2) {
676+
await olderHeld; // not answered until the end of the test
677+
return [];
678+
}
679+
return [rootOf(rootDir)];
680+
},
681+
});
682+
await vi.waitFor(async () =>
683+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]),
684+
);
685+
686+
await client.sendRootsListChanged();
687+
await vi.waitFor(() => expect(calls).toBe(2));
688+
const pending = call(client, "list_directory", { path: rootDir });
689+
await new Promise((resolve) => setTimeout(resolve, 50));
690+
await client.sendRootsListChanged();
691+
692+
expect(textOf(await pending)).toBe("[FILE] a.txt");
693+
expect(calls).toBe(3);
694+
695+
// Cleanup: the older answer arrives last and is discarded as stale.
696+
releaseOlder();
697+
await vi.waitFor(() =>
698+
expect(stderr).toHaveBeenCalledWith(
699+
"Discarded a stale roots/list answer: a newer roots update has started",
700+
),
701+
);
702+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]);
703+
});
704+
663705
it("logs and keeps the current directories when the re-fetch fails", async () => {
664706
let fail = false;
665707
const { client } = await connectTracked([], {

‎src/filesystem/server.ts‎

Lines changed: 45 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -189,31 +189,37 @@ export function createServer(
189189
version: SERVER_VERSION,
190190
});
191191

192-
// Settles once the newest roots refresh has finished, successfully or not; it
193-
// never rejects. Every tool call waits for it, so a call that arrives while
194-
// roots are being fetched is checked against the roots that come back rather
195-
// than the ones being replaced: the command-line directories while the
196-
// initial roots/list is outstanding (#3204), or a root the client has just
197-
// withdrawn while a roots/list_changed refresh is pending (#5101). The
198-
// initial load (oninitialized, which the SDK runs before any request sent
199-
// after notifications/initialized) and every refresh replace it, and a
200-
// waiting call follows each replacement until it stops changing (#5097).
201-
// Each one is installed before its roots/list is sent: a transport that
202-
// delivers that request synchronously can let the client announce a newer
203-
// change at once, and that newer barrier must not be overwritten by this one.
204-
let initialization: Promise<void> = Promise.resolve();
192+
// The barrier every tool call waits on, so a call that arrives while roots are
193+
// being fetched is checked against the roots that come back rather than the
194+
// ones being replaced: the command-line directories while the initial
195+
// roots/list is outstanding (#3204), or a root the client has just withdrawn
196+
// while a roots/list_changed refresh is pending (#5101). Each refresh (the
197+
// initial load included) installs a new barrier before it sends roots/list,
198+
// and settles it when it finishes, successfully or not. Installing one also
199+
// settles the barrier it replaces, so calls waiting on an older refresh wake
200+
// at once and move on to the newer one instead of waiting for the older
201+
// one's answer (#5097, #5101).
202+
let barrier = { settled: Promise.resolve(), settle: () => {} };
203+
function installBarrier(): () => void {
204+
let settle!: () => void;
205+
const settled = new Promise<void>((resolve) => (settle = resolve));
206+
const replaced = barrier;
207+
barrier = { settled, settle };
208+
replaced.settle();
209+
return settle;
210+
}
205211
const registerTool = server.registerTool.bind(server);
206212
server.registerTool = ((
207213
name: string,
208214
config: Parameters<typeof registerTool>[1],
209215
handler: (...args: unknown[]) => unknown,
210216
) =>
211217
registerTool(name, config, (async (...args: unknown[]) => {
212-
let awaited: Promise<void>;
218+
let awaited: typeof barrier;
213219
do {
214-
awaited = initialization;
215-
await awaited;
216-
} while (awaited !== initialization);
220+
awaited = barrier;
221+
await awaited.settled;
222+
} while (awaited !== barrier);
217223
return handler(...args);
218224
}) as never)) as typeof server.registerTool;
219225

@@ -813,38 +819,35 @@ export function createServer(
813819
RootsListChangedNotificationSchema,
814820
async () => {
815821
const generation = ++rootsGeneration;
816-
// Deferred a microtask, so the barrier below is installed before
817-
// roots/list is sent (see `initialization` above).
818-
const refresh = Promise.resolve().then(async () => {
819-
try {
820-
// Request the updated roots list from the client
821-
const response = await server.server.listRoots();
822-
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
823-
if (response && "roots" in response) {
824-
await updateAllowedDirectoriesFromRoots(response.roots, generation);
825-
}
826-
} catch (error) {
827-
console.error(
828-
"Failed to request roots from client:",
829-
error instanceof Error ? error.message : String(error),
830-
);
822+
const settle = installBarrier();
823+
try {
824+
// Request the updated roots list from the client
825+
const response = await server.server.listRoots();
826+
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
827+
if (response && "roots" in response) {
828+
await updateAllowedDirectoriesFromRoots(response.roots, generation);
831829
}
832-
});
833-
// Tool calls wait for this refresh, so none runs against a root the
834-
// client has just withdrawn while its answer is pending (#5101).
835-
initialization = refresh;
836-
await refresh;
830+
} catch (error) {
831+
console.error(
832+
"Failed to request roots from client:",
833+
error instanceof Error ? error.message : String(error),
834+
);
835+
} finally {
836+
settle();
837+
}
837838
},
838839
);
839840

840841
// Handles post-initialization setup, specifically checking for and fetching
841-
// MCP roots. Tool calls wait for it (see `initialization` above), which is
842-
// installed before initialize() sends its roots/list. The initial load claims
843-
// its generation here, synchronously, so a roots/list_changed handled before
844-
// the deferred request runs takes a newer one and is not discarded as stale.
842+
// MCP roots. The initial load claims its generation and installs its barrier
843+
// here, synchronously, before any roots/list_changed handled afterwards can
844+
// claim a newer one.
845845
server.server.oninitialized = () => {
846846
const generation = ++rootsGeneration;
847-
initialization = Promise.resolve().then(() => initialize(generation));
847+
const settle = installBarrier();
848+
// Not awaited: oninitialized is synchronous. Tool calls wait on the
849+
// barrier, which settles when initialize() finishes; it never rejects.
850+
void initialize(generation).finally(settle);
848851
};
849852

850853
async function initialize(generation: number): Promise<void> {

0 commit comments

Comments
 (0)