diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts index 076dce2aa3a89..3be4ae372773f 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -24,6 +24,7 @@ import { ClaudeMcpProfileError, EVERY_MCP_SERVER, type FindThread, + __testing as ClaudeMcpProfileTesting, type LineageThread, checkClaudeSession, claudeMcpCallOutsideProfile, @@ -232,6 +233,7 @@ describe("makeClaudeMcpProfiles", () => { () => Effect.gen(function* () { T3ToolSets.__testing.clear(); + ClaudeMcpProfileTesting.clearOpenedPlanKeys(); const lean = (t3Tools: unknown) => ({ mcpProfile: "lean", mcpProfiles: { lean: { servers: "all", t3Tools } }, @@ -279,6 +281,7 @@ describe("makeClaudeMcpProfiles", () => { () => Effect.gen(function* () { T3ToolSets.__testing.clear(); + ClaudeMcpProfileTesting.clearOpenedPlanKeys(); const lean = { mcpProfile: "lean", mcpProfiles: { lean: { servers: "all", t3Tools: [] } } }; const service = yield* ServerSettingsService.ServerSettingsService; const plan = yield* makeClaudeMcpProfiles.pipe( @@ -288,7 +291,7 @@ describe("makeClaudeMcpProfiles", () => { }), ); const before: T3ToolSets.T3ToolSet = { _tag: "Groups", name: "all", groups: "all" }; - T3ToolSets.fixT3ToolSet("t", before); + T3ToolSets.fixT3ToolSet("t", before, T3ToolSets.nextT3ToolSetTurn()); const planned = yield* plan(thread("t"), {}); // Planned, not opened (a continuation, or background work blocks the replacement). assert.strictEqual(planned.name, "lean"); @@ -315,10 +318,106 @@ describe("makeClaudeMcpProfiles", () => { ), ); + /** A planner over settings the test changes between turns, from no opened process. */ + const planner = Effect.gen(function* () { + T3ToolSets.__testing.clear(); + ClaudeMcpProfileTesting.clearOpenedPlanKeys(); + const service = yield* ServerSettingsService.ServerSettingsService; + const settings: { current: object } = { current: {} }; + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provideService(ServerSettingsService.ServerSettingsService, { + ...service, + getSettings: Effect.suspend(() => Effect.succeed(fromFile(settings.current))), + }), + ); + return { plan, settings }; + }); + const lean = (t3Tools: unknown) => ({ + mcpProfile: "lean", + mcpProfiles: { lean: { servers: "all", t3Tools } }, + }); + const groupsOf = (threadId: string) => { + const set = T3ToolSets.t3ToolSetFor(threadId); + return set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag; + }; + const withSettings = (effect: Effect.Effect) => + effect.pipe( + Effect.provide( + Layer.mergeAll( + ServerSettingsService.ServerSettingsService.layerTest(), + ManagedPolicy.layerTest(), + Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-mcp-profile-" })), + ).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ); + + it.effect( + "never wider: a process opened with one plan meets a different, wider one (fork issue #986)", + () => + withSettings( + Effect.gen(function* () { + const { plan, settings } = yield* planner; + const self = thread("t"); + // Empty state (as after a restart): no process opened, so a plan fixes nothing yet. + settings.current = lean(["threads"]); + const first = yield* plan(self, {}); + assert.isUndefined(T3ToolSets.t3ToolSetFor(self.id)); + void first.options; + assert.deepStrictEqual(groupsOf(self.id), ["threads"]); + // A refused turn keeps the process, and only the ungrouped tools. + settings.current = { mcpProfile: "gone" }; + assert.isTrue(isRefusal(yield* Effect.flip(plan(self, {})))); + assert.strictEqual(groupsOf(self.id), "Refused"); + // The profile is widened: a different plan, and its process has not opened, so the + // thread keeps the refusal, never the wider set on the narrower process. + settings.current = lean(["threads", "orchestration"]); + yield* plan(self, {}); + assert.strictEqual(groupsOf(self.id), "Refused"); + // Runs again: the same plan as the process opened with gets that process's set back. + settings.current = lean(["threads"]); + yield* plan(self, {}); + assert.deepStrictEqual(groupsOf(self.id), ["threads"]); + }), + ), + ); + + it.effect( + "the cap drops the thread whose process was used longest ago, not the first opened (#986)", + () => + withSettings( + Effect.gen(function* () { + const { plan, settings } = yield* planner; + settings.current = lean(["threads"]); + const first = thread("first"); + void (yield* plan(first, {})).options; + for (let index = 1; index < T3ToolSets.MAX_T3_TOOL_SETS; index += 1) { + ClaudeMcpProfileTesting.keepOpenedPlanKey(ThreadId.make(`other-${index}`), "other-key"); + } + // The first thread's process is used again (the same plan, no new process). + yield* plan(first, {}); + // One more thread opens a process: the cap drops the one used longest ago. + void (yield* plan(thread("last"), {})).options; + assert.isTrue(ClaudeMcpProfileTesting.hasOpenedPlanKey(first.id)); + assert.isFalse(ClaudeMcpProfileTesting.hasOpenedPlanKey(ThreadId.make("other-1"))); + // So a turn after a refused one still gets the first thread's set back. + settings.current = { mcpProfile: "gone" }; + yield* Effect.flip(plan(first, {})); + assert.strictEqual(groupsOf(first.id), "Refused"); + settings.current = lean(["threads"]); + yield* plan(first, {}); + assert.deepStrictEqual(groupsOf(first.id), ["threads"]); + }), + ), + ); + it.effect("a profile that cannot be worked out fixes no T3 tool but the ungrouped ones", () => Effect.gen(function* () { T3ToolSets.__testing.clear(); - T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.fixT3ToolSet( + "t", + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); // The thread names a profile that is gone: the turn refuses, and the old `all` set is gone. assert.include( (yield* plansFor([{ mcpProfile: "gone" }]))[0], @@ -333,7 +432,11 @@ describe("makeClaudeMcpProfiles", () => { () => Effect.gen(function* () { T3ToolSets.__testing.clear(); - T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.fixT3ToolSet( + "t", + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); const reading = yield* Deferred.make(); const service = yield* ServerSettingsService.ServerSettingsService; const plan = yield* makeClaudeMcpProfiles.pipe( diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index a5fd9aecbc38c..b7abc1c6b47d0 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -47,6 +47,7 @@ import { MAX_T3_TOOL_SETS, type T3ToolSet, fixT3ToolSet, + nextT3ToolSetTurn, refusedT3ToolSet, t3ToolSetOf, } from "./mcpT3ToolSets.ts"; @@ -728,6 +729,7 @@ const withAgentModelPolicy = ( */ const openedPlanKeys = new Map(); +/** Keeps the thread's key as its most recently used; beyond the cap, the least recently used goes. */ const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => { openedPlanKeys.delete(threadId); openedPlanKeys.set(threadId, key); @@ -737,6 +739,15 @@ const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => { } }; +export const __testing = { + /** Forgets every process's plan key, as after a restart. */ + clearOpenedPlanKeys: () => openedPlanKeys.clear(), + /** Records that the thread's process opened with `key`, as its options read does. */ + keepOpenedPlanKey, + /** True while the thread's opened plan key is kept. */ + hasOpenedPlanKey: (threadId: ThreadId) => openedPlanKeys.has(threadId), +}; + /** * The plan with its T3 tool set fixed when its `options` are first read: ClaudeAdapterV2 reads * them only to open a new process, after the old one closed. A turn that keeps the live process (a @@ -747,12 +758,13 @@ const fixedWhenOpened = ( plan: ClaudeMcpProfilePlan, threadId: ThreadId, set: T3ToolSet, + turn: number, ): ClaudeMcpProfilePlan => { const { options, ...rest } = plan; return Object.defineProperty({ ...rest }, "options", { enumerable: true, get: () => { - fixT3ToolSet(threadId, set); + fixT3ToolSet(threadId, set, turn); keepOpenedPlanKey(threadId, planKey(plan)); return options; }, @@ -768,28 +780,33 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { thread: LineageThread, overrides: McpOverrides, ) { + // Drawn before the read: a later turn's set stands over this one's, whichever finishes first. + const turn = nextT3ToolSetTurn(); // A profile that cannot apply refuses the turn and keeps only the tools every profile keeps, // at once: narrowing never waits. A profile that applies is fixed as its process opens. const resolved: McpProfileResolved = yield* profileFor(thread).pipe( Effect.tapError((refusal) => - Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason))), + Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason), turn)), ), ); const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); const plan = claudeMcpProfilePlan(resolved.name, resolved.profile, t3ServerNames); if (isRefusal(plan)) { - fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason)); + fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason), turn); return yield* plan; } const set = t3ToolSetOf(resolved); // The same plan as the thread's process opened with: the adapter keeps that process without // reading the options, so its set is fixed here, the one that process has (never wider). This // is how a good turn after a refused one gets its set back on the process the refusal kept. - if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === planKey(plan)) { - fixT3ToolSet(thread.id, set); + // The thread counts as just used, so the cap drops threads not used for longest first. + const key = planKey(plan); + if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === key) { + keepOpenedPlanKey(thread.id, key); + fixT3ToolSet(thread.id, set, turn); } // The policy hook goes in before the options are made lazy, so adding it reads nothing early. - return fixedWhenOpened(withAgentModelPolicy(plan, yield* agentPolicy), thread.id, set); + return fixedWhenOpened(withAgentModelPolicy(plan, yield* agentPolicy), thread.id, set, turn); }); return Effect.fn("ClaudeMcpProfile.plan")(function* ( diff --git a/apps/server/src/fork/codexMcpProfile.test.ts b/apps/server/src/fork/codexMcpProfile.test.ts index 0cd3af2c257f7..e0f590c1b190b 100644 --- a/apps/server/src/fork/codexMcpProfile.test.ts +++ b/apps/server/src/fork/codexMcpProfile.test.ts @@ -1478,6 +1478,150 @@ describe("follow-ups: holds, sub-agents, unknown threads, per-call checks (fork const drive = (fiber: Fiber.Fiber, millis: number) => TestClock.adjust(millis).pipe(Effect.andThen(Fiber.join(fiber))); +describe("a newer turn's T3 tool set is never overwritten by an older one (fork issue #986)", () => { + /** + * The thread's profile reads, in order: each is `all` once the queue is empty, or waits for its + * gate and then gives its profile. + */ + const scripted = () => { + const queue: Array> = []; + const profileFor: ProfileById = () => queue.shift() ?? Effect.succeed(ALL); + const gated = (profile: McpProfileResolved) => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const open = yield* Deferred.make(); + queue.push( + Deferred.succeed(reached, undefined).pipe( + Effect.andThen(Deferred.await(open)), + Effect.as(profile), + ), + ); + return { reached, open }; + }); + const next = (profile: McpProfileResolved) => void queue.push(Effect.succeed(profile)); + return { profileFor, gated, next }; + }; + /** + * The thread's hold, for its `done`: done once every check holding it has released, which each + * does after fixing (or not) its set. A check whose profile read is not gated runs inside `emit` + * (forked to start at once, nothing to wait on), so only a gated read's end needs awaiting. + */ + const holdOf = (threadId: string) => T3ToolSets.t3ToolSetHold(threadId, 0)!.done; + const TIMED_OUT = T3ToolSets.refusedT3ToolSet("timed out"); + /** What the T3 tool rule does as a request's wait on the hold reaches its bound. */ + const dropAtBound = (threadId: string) => + T3ToolSets.dropT3ToolSetHold( + threadId, + T3ToolSets.t3ToolSetHold(threadId, Number.MAX_SAFE_INTEGER)!, + TIMED_OUT, + ); + const LEAN = resolved("lean", "all", ["waits"]); + + it.effect("two checks finishing out of order: the later turn's set stands", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profileFor, gated, next } = scripted(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + // goal-2's check reads `all` slowly; the profile is narrowed; goal-3's check reads lean. + const slow = yield* gated(ALL); + next(LEAN); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* Deferred.await(slow.reached); + yield* fake.emit("turn/started", turnStarted(id, "goal-3")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + // goal-2's check finishes last: it must not widen the thread back to `all`. + const done = holdOf("t"); + yield* Deferred.succeed(slow.open, undefined); + yield* Deferred.await(done); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + assert.isUndefined(T3ToolSets.__testing.asked("t")); + // Runs again: the thread's next turn fixes its set as usual. + next(resolved("threads", "all", ["threads"])); + yield* fake.emit("turn/started", turnStarted(id, "goal-4")); + assert.deepStrictEqual(groupsOf("t"), ["threads"]); + }), + ); + + it.effect("a joining turn fixed its set while the first is stuck: the drop keeps it", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profileFor, gated, next } = scripted(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + const stuck = yield* gated(ALL); + next(LEAN); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* Deferred.await(stuck.reached); + // goal-3 joins goal-2's hold (and its bound), and fixes its set; goal-2's check still runs. + yield* fake.emit("turn/started", turnStarted(id, "goal-3")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + assert.isDefined(T3ToolSets.__testing.asked("t")); + // The bound passes: the hold goes, but goal-3's set stands (not Refused over it). + const done = holdOf("t"); + assert.isFalse(dropAtBound("t")); + assert.isUndefined(T3ToolSets.__testing.asked("t")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + // goal-2's late check gives nothing either. + yield* Deferred.succeed(stuck.open, undefined); + yield* Deferred.await(done); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + }), + ); + + it.effect( + "a turn T3 starts itself while a Codex turn's hold is stuck: the drop keeps its set", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profileFor, gated, next } = scripted(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + const stuck = yield* gated(ALL); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* Deferred.await(stuck.reached); + // T3's own turn does not touch the hold, but it is later than goal-2: its set stands. + next(LEAN); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + const done = holdOf("t"); + assert.isFalse(dropAtBound("t")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + yield* Deferred.succeed(stuck.open, undefined); + yield* Deferred.await(done); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + }), + ); + + it.effect("a hold whose check never fixes a set: the drop still refuses (fails closed)", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profileFor, gated } = scripted(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + T3ToolSets.fixT3ToolSet( + "t", + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); + const stuck = yield* gated(LEAN); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* Deferred.await(stuck.reached); + const done = holdOf("t"); + assert.isTrue(dropAtBound("t")); + assert.strictEqual(groupsOf("t"), "Refused"); + // The stuck check is that turn's: when it finishes late, its set replaces the refusal. + yield* Deferred.succeed(stuck.open, undefined); + yield* Deferred.await(done); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + }), + ); +}); + describe("profiledClientFactory (settings and thread store)", () => { const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z"); const PROJECT = ProjectId.make("project"); diff --git a/apps/server/src/fork/codexMcpProfile.ts b/apps/server/src/fork/codexMcpProfile.ts index 626abccf4fe12..31d1098b6b04f 100644 --- a/apps/server/src/fork/codexMcpProfile.ts +++ b/apps/server/src/fork/codexMcpProfile.ts @@ -23,7 +23,13 @@ import { type McpProfileSet, builtinToolsNoneRefusal, } from "./mcpProfile.ts"; -import { fixT3ToolSet, holdT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { + fixT3ToolSet, + holdT3ToolSet, + nextT3ToolSetTurn, + refusedT3ToolSet, + t3ToolSetOf, +} from "./mcpT3ToolSets.ts"; import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; type Client = CodexClient.CodexAppServerClient["Service"]; @@ -360,19 +366,22 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* }); /** - * The thread's profile, with its T3 tool groups fixed when `fix` (a turn of the thread itself, - * not of a sub-agent, and not a goal set while a turn may run): fixed until the next turn, and - * only the tools every profile keeps when the profile cannot apply. + * The thread's profile, with its T3 tool groups fixed when `turn` is given (a turn of the thread + * itself, not of a sub-agent, and not a goal set while a turn may run): fixed until the next + * turn, and only the tools every profile keeps when the profile cannot apply. `turn` is drawn + * before the profile is read, so a check that finishes after a later turn's fixes nothing. */ - const profileStep = (method: string, threadId: ThreadId, fix: boolean) => + const profileStep = (method: string, threadId: ThreadId, turn: number | undefined) => workedOut(threadId).pipe( Effect.tap((resolved) => - fix ? Effect.sync(() => fixT3ToolSet(threadId, t3ToolSetOf(resolved))) : Effect.void, + turn === undefined + ? Effect.void + : Effect.sync(() => fixT3ToolSet(threadId, t3ToolSetOf(resolved), turn)), ), Effect.tapError((cause) => - fix - ? Effect.sync(() => fixT3ToolSet(threadId, refusedT3ToolSet(cause.reason))) - : Effect.void, + turn === undefined + ? Effect.void + : Effect.sync(() => fixT3ToolSet(threadId, refusedT3ToolSet(cause.reason), turn)), ), Effect.mapError((cause) => refusal(method, cause)), ); @@ -442,7 +451,8 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* if (!narrowed) return; return yield* notLoadedHere(method); } - const resolved = yield* profileStep(method, threadId, fix && !children.has(nativeId)); + const turn = fix && !children.has(nativeId) ? nextT3ToolSetTurn() : undefined; + const resolved = yield* profileStep(method, threadId, turn); yield* serverStep(method, nativeId, resolved); }); @@ -564,19 +574,21 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* Effect.asVoid, ); } - const own = !children.has(nativeId); + // The turn's place among the thread's turns, in the order Codex reports them started. + const turn = children.has(nativeId) ? undefined : nextT3ToolSetTurn(); // Held inside the check, which starts before this handler returns, and released however it // ends: a closed scope never starts it, so no hold is left. Only the profile step is held; // T3's tools carry the new set while the server step runs. - const held = own - ? Effect.acquireUseRelease( - Effect.flatMap(Clock.currentTimeMillis, (now) => - Effect.sync(() => holdT3ToolSet(threadId, now)), - ), - () => profileStep("turn/started", threadId, own), - (release) => Effect.sync(release), - ) - : profileStep("turn/started", threadId, own); + const held = + turn === undefined + ? profileStep("turn/started", threadId, undefined) + : Effect.acquireUseRelease( + Effect.flatMap(Clock.currentTimeMillis, (now) => + Effect.sync(() => holdT3ToolSet(threadId, now, turn)), + ), + () => profileStep("turn/started", threadId, turn), + (release) => Effect.sync(release), + ); return held.pipe( Effect.flatMap((resolved) => serverStep("turn/started", nativeId, resolved)), Effect.catch(stop(nativeId, turnId)), diff --git a/apps/server/src/fork/mcpProfileTurnCheck.test.ts b/apps/server/src/fork/mcpProfileTurnCheck.test.ts index 8253c040d84d7..73020b8edb1e2 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.test.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.test.ts @@ -367,7 +367,11 @@ describe("mcpProfileTurnCheck", () => { assert.match(yield* start(own, OPENCODE), /"lean" leaves out some outside MCP servers/); T3ToolSets.__testing.clear(); for (const how of ["start", "resume", "compact"] as const) { - T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.fixT3ToolSet( + own.id, + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); assert.strictEqual(yield* start(own, CODEX, how), "ok"); assert.deepStrictEqual(groupsOf(own.id), ["threads", "waits"]); } @@ -462,7 +466,11 @@ describe("mcpProfileTurnCheck", () => { Effect.gen(function* () { const own = appThread("own"); for (const id of [CODEX, OPENCODE]) { - T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.fixT3ToolSet( + own.id, + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); assert.include(yield* start(own, id, "compact"), 'MCP profile "gone" is not set up'); assert.strictEqual(T3ToolSets.t3ToolSetFor(own.id)?._tag, "Refused"); } @@ -611,7 +619,11 @@ describe("mcpProfileTurnCheck", () => { ({ calls, start }) => Effect.gen(function* () { const own = appThread("own"); - T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.fixT3ToolSet( + own.id, + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); const fiber = yield* Effect.forkChild(start(own, OPENCODE)); yield* Deferred.await(reading); yield* Fiber.interrupt(fiber); @@ -627,6 +639,91 @@ describe("mcpProfileTurnCheck", () => { }), ); + /** + * Settings whose first read takes what they hold as it starts and gives it only once released, + * so the turn reading them finishes after a later turn's. + */ + const slowFirstRead = Effect.gen(function* () { + const reading = yield* Deferred.make(); + const release = yield* Deferred.make(); + let reads = 0; + const layer = Layer.effect( + ServerSettingsService.ServerSettingsService, + Effect.gen(function* () { + const service = yield* ServerSettingsService.ServerSettingsService; + return ServerSettingsService.ServerSettingsService.of({ + ...service, + getSettings: Effect.suspend(() => + reads++ === 0 + ? service.getSettings.pipe( + Effect.tap(() => Deferred.succeed(reading, undefined)), + Effect.tap(() => Deferred.await(release)), + ) + : service.getSettings, + ), + }); + }), + ).pipe(Layer.provide(ServerSettingsService.ServerSettingsService.layerTest())); + return { reading, release, layer }; + }); + /** The thread's profile narrowed to the threads group. */ + const LEAN = { + mcpProfile: "lean", + mcpProfiles: { lean: { servers: "all", t3Tools: ["threads"] } }, + } as never; + + it.effect("two turns' checks finishing out of order: the later turn's set stands (#986)", () => + Effect.gen(function* () { + const slow = yield* slowFirstRead; + yield* withCheck( + {}, + [], + ({ start }) => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const own = appThread("own"); + // The first turn reads `all`, then is slow; the profile is narrowed meanwhile. + const first = yield* Effect.forkChild(start(own, OPENCODE)); + yield* Deferred.await(slow.reading); + const settings = yield* ServerSettingsService.ServerSettingsService; + yield* settings.updateSettings(LEAN); + assert.strictEqual(yield* start(own, OPENCODE), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + // The first turn's check finishes last: it does not widen the thread back to all. + yield* Deferred.succeed(slow.release, undefined); + assert.strictEqual(yield* Fiber.join(first), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + }), + slow.layer, + ); + }), + ); + + it.effect("stopped half-way after a later turn fixed its set: that set stands (#986)", () => + Effect.gen(function* () { + const slow = yield* slowFirstRead; + yield* withCheck( + {}, + [], + ({ start }) => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const own = appThread("own"); + const settings = yield* ServerSettingsService.ServerSettingsService; + yield* settings.updateSettings(LEAN); + const first = yield* Effect.forkChild(start(own, OPENCODE)); + yield* Deferred.await(slow.reading); + assert.strictEqual(yield* start(own, OPENCODE), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + // The first turn's start is stopped: the later turn's set is not cleared. + yield* Fiber.interrupt(first); + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + }), + slow.layer, + ); + }), + ); + it.effect("a failed settings read: own threads get all, a narrower carried task refuses", () => Effect.gen(function* () { const failing = Layer.effect( diff --git a/apps/server/src/fork/mcpProfileTurnCheck.ts b/apps/server/src/fork/mcpProfileTurnCheck.ts index 3f5f895f36fcc..e4ba30484cb74 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.ts @@ -22,7 +22,13 @@ import { type McpProfileResolved, builtinToolsNoneRefusal, } from "./mcpProfile.ts"; -import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { + fixT3ToolSet, + forgetT3ToolSet, + nextT3ToolSetTurn, + refusedT3ToolSet, + t3ToolSetOf, +} from "./mcpT3ToolSets.ts"; import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; type ProfileFor = Effect.Success; @@ -87,14 +93,16 @@ const checkTurnProfile = Effect.fn("McpProfileTurnCheck.check")(function* ( instance: ProviderInstance, thread: LineageThread, ) { + // Drawn before the read: a later turn's set stands over this one's, whichever finishes first. + const turn = nextT3ToolSetTurn(); const resolved = yield* profileFor(thread).pipe( Effect.tapError((refusal) => - Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason))), + Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason), turn)), ), // Stopped half-way: no set stands, so the next request works it out again. - Effect.onInterrupt(() => Effect.sync(() => forgetT3ToolSet(thread.id))), + Effect.onInterrupt(() => Effect.sync(() => forgetT3ToolSet(thread.id, turn))), ); - fixT3ToolSet(thread.id, t3ToolSetOf(resolved)); + fixT3ToolSet(thread.id, t3ToolSetOf(resolved), turn); if (resolved.profile.builtinTools === MCP_BUILTIN_TOOLS_NONE) { return yield* new ClaudeMcpProfileError({ reason: builtinToolsNoneRefusal(resolved.name, instance.driverKind), diff --git a/apps/server/src/fork/mcpT3ToolFilter.test.ts b/apps/server/src/fork/mcpT3ToolFilter.test.ts index 01a04c3092dc6..3362a4fb7d4bd 100644 --- a/apps/server/src/fork/mcpT3ToolFilter.test.ts +++ b/apps/server/src/fork/mcpT3ToolFilter.test.ts @@ -493,16 +493,24 @@ describe("a set worked out by a request, not a turn (fork issues #812, #918)", ( it.effect("while a turn's set is being fixed, a request waits for it", () => withServer(({ list }) => Effect.gen(function* () { - const release = T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const release = T3ToolSets.holdT3ToolSet( + "thread-prs", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); const listing = yield* Effect.forkChild(list("prs")); yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); expect(listing.pollUnsafe()).toBeUndefined(); // The turn's check fixes the thread's new set, then releases: the request gets that one. - T3ToolSets.fixT3ToolSet("thread-prs", { - _tag: "Groups", - name: "waits", - groups: new Set(["waits"]), - }); + T3ToolSets.fixT3ToolSet( + "thread-prs", + { + _tag: "Groups", + name: "waits", + groups: new Set(["waits"]), + }, + T3ToolSets.nextT3ToolSetTurn(), + ); release(); release(); expect(grouped(yield* Fiber.join(listing))).toEqual({ waits: WAIT_TOOLS, prs: false }); @@ -514,8 +522,16 @@ describe("a set worked out by a request, not a turn (fork issues #812, #918)", ( it.effect("a hold never released: the request is refused, not given the set before", () => withServer(({ call }) => Effect.gen(function* () { - T3ToolSets.fixT3ToolSet("thread-all", { _tag: "Groups", name: "all", groups: "all" }); - T3ToolSets.holdT3ToolSet("thread-all", yield* Clock.currentTimeMillis); + T3ToolSets.fixT3ToolSet( + "thread-all", + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); + T3ToolSets.holdT3ToolSet( + "thread-all", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); const calling = yield* Effect.forkChild(call("all", "wait_list")); yield* Deferred.await(T3ToolSets.__testing.asked("thread-all")!); const refused = yield* drive(calling, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS); @@ -612,11 +628,11 @@ describe("the T3 tool sets in memory", () => { it.effect("a set worked out for a request never replaces one a turn fixed", () => Effect.sync(() => { T3ToolSets.__testing.clear(); - T3ToolSets.fixT3ToolSet("t", groups("turn")); + T3ToolSets.fixT3ToolSet("t", groups("turn"), T3ToolSets.nextT3ToolSetTurn()); expect(T3ToolSets.rememberT3ToolSet("t", groups("request"))).toEqual(groups("turn")); expect(T3ToolSets.rememberT3ToolSet("u", groups("request"))).toEqual(groups("request")); // A later turn start does replace it. - T3ToolSets.fixT3ToolSet("u", groups("turn")); + T3ToolSets.fixT3ToolSet("u", groups("turn"), T3ToolSets.nextT3ToolSetTurn()); expect(T3ToolSets.t3ToolSetFor("u")).toEqual(groups("turn")); }), ); @@ -624,13 +640,73 @@ describe("the T3 tool sets in memory", () => { it.effect("keeps at most MAX_T3_TOOL_SETS threads, dropping the oldest", () => Effect.sync(() => { T3ToolSets.__testing.clear(); - for (let index = 0; index <= T3ToolSets.MAX_T3_TOOL_SETS; index += 1) { - T3ToolSets.fixT3ToolSet(`thread-${index}`, groups("p")); + // thread-0's older turn is still checking (it read a wider profile) as a newer turn fixes. + const older = T3ToolSets.nextT3ToolSetTurn(); + T3ToolSets.fixT3ToolSet("thread-0", groups("newer"), T3ToolSets.nextT3ToolSetTurn()); + for (let index = 1; index <= T3ToolSets.MAX_T3_TOOL_SETS; index += 1) { + T3ToolSets.fixT3ToolSet(`thread-${index}`, groups("p"), T3ToolSets.nextT3ToolSetTurn()); } expect(T3ToolSets.__testing.size()).toBe(T3ToolSets.MAX_T3_TOOL_SETS); // The dropped thread has no set: its next request works it out again, never `all`. expect(T3ToolSets.t3ToolSetFor("thread-0")).toBeUndefined(); expect(T3ToolSets.t3ToolSetFor(`thread-${T3ToolSets.MAX_T3_TOOL_SETS}`)).toBeDefined(); + // The order outlives the drop: the older turn's late check writes nothing, nor replaces + // the set a request works out from the settings; a later turn fixes as usual. + T3ToolSets.fixT3ToolSet("thread-0", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("thread-0")).toBeUndefined(); + expect(T3ToolSets.rememberT3ToolSet("thread-0", groups("request"))).toEqual( + groups("request"), + ); + T3ToolSets.fixT3ToolSet("thread-0", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("thread-0")).toEqual(groups("request")); + T3ToolSets.fixT3ToolSet("thread-0", groups("next"), T3ToolSets.nextT3ToolSetTurn()); + expect(T3ToolSets.t3ToolSetFor("thread-0")).toEqual(groups("next")); + }), + ); + + it.effect("a check that finishes after a later turn's fixes nothing (fork issue #986)", () => + Effect.sync(() => { + T3ToolSets.__testing.clear(); + const older = T3ToolSets.nextT3ToolSetTurn(); + const newer = T3ToolSets.nextT3ToolSetTurn(); + T3ToolSets.fixT3ToolSet("t", groups("newer"), newer); + T3ToolSets.fixT3ToolSet("t", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("newer")); + // The same turn fixing again (a refusal after its set, as Claude's plan does) still writes. + T3ToolSets.fixT3ToolSet("t", groups("newer again"), newer); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("newer again")); + }), + ); + + it.effect("stopped half-way: an older turn's stop leaves a newer set; its own clears it", () => + Effect.sync(() => { + T3ToolSets.__testing.clear(); + const older = T3ToolSets.nextT3ToolSetTurn(); + const newer = T3ToolSets.nextT3ToolSetTurn(); + T3ToolSets.fixT3ToolSet("t", groups("newer"), newer); + T3ToolSets.forgetT3ToolSet("t", older); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("newer")); + const stopped = T3ToolSets.nextT3ToolSetTurn(); + T3ToolSets.forgetT3ToolSet("t", stopped); + expect(T3ToolSets.t3ToolSetFor("t")).toBeUndefined(); + // No set stands, but the older turn's late check still may not write one. + T3ToolSets.fixT3ToolSet("t", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("t")).toBeUndefined(); + // A request may remember the one it works out; a later turn replaces it. + expect(T3ToolSets.rememberT3ToolSet("t", groups("request"))).toEqual(groups("request")); + T3ToolSets.fixT3ToolSet("t", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("request")); + T3ToolSets.fixT3ToolSet("t", groups("next"), T3ToolSets.nextT3ToolSetTurn()); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("next")); + }), + ); + + it.effect("empty state (after a restart): any check writes", () => + Effect.sync(() => { + T3ToolSets.__testing.clear(); + const older = T3ToolSets.nextT3ToolSetTurn(); + T3ToolSets.fixT3ToolSet("t", groups("older"), older); + expect(T3ToolSets.t3ToolSetFor("t")).toEqual(groups("older")); }), ); }); @@ -662,9 +738,13 @@ describe("the hold bound, without a socket (fork issue #918)", () => { Effect.gen(function* () { T3ToolSets.__testing.clear(); McpT3ToolRule.__testing.clearRefused(); - T3ToolSets.fixT3ToolSet("thread-prs", prs); + T3ToolSets.fixT3ToolSet("thread-prs", prs, T3ToolSets.nextT3ToolSetTurn()); expect(yield* checkAll("prs", "tools/list", [PR_TOOL])).toEqual([[PR_TOOL, true]]); - T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + T3ToolSets.holdT3ToolSet( + "thread-prs", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); const listing = yield* Effect.forkChild( checkAll("prs", "tools/list", [...WAIT_TOOLS, PR_TOOL]), ); @@ -686,8 +766,12 @@ describe("the hold bound, without a socket (fork issue #918)", () => { Effect.gen(function* () { T3ToolSets.__testing.clear(); McpT3ToolRule.__testing.clearRefused(); - T3ToolSets.fixT3ToolSet("thread-prs", prs); - T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + T3ToolSets.fixT3ToolSet("thread-prs", prs, T3ToolSets.nextT3ToolSetTurn()); + T3ToolSets.holdT3ToolSet( + "thread-prs", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); const first = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); expect(yield* drive(first, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS)).toEqual([ @@ -698,12 +782,90 @@ describe("the hold bound, without a socket (fork issue #918)", () => { expect(T3ToolSets.__testing.asked("thread-prs")).toBeUndefined(); expect(yield* checkAll("prs", "tools/call", [PR_TOOL])).toEqual([[PR_TOOL, false]]); // The next turn's hold starts fresh, and its check's set applies once it releases. - const release = T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const release = T3ToolSets.holdT3ToolSet( + "thread-prs", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); const second = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); - T3ToolSets.fixT3ToolSet("thread-prs", prs); + T3ToolSets.fixT3ToolSet("thread-prs", prs, T3ToolSets.nextT3ToolSetTurn()); release(); expect(yield* Fiber.join(second)).toEqual([[PR_TOOL, true]]); }), ); + + it.effect( + "a check fixed its set but has not released yet as the bound passes: its set stands (#986)", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); + T3ToolSets.fixT3ToolSet( + "thread-prs", + { _tag: "Groups", name: "all", groups: "all" }, + T3ToolSets.nextT3ToolSetTurn(), + ); + T3ToolSets.holdT3ToolSet( + "thread-prs", + yield* Clock.currentTimeMillis, + T3ToolSets.nextT3ToolSetTurn(), + ); + const waiting = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + // The turn's check fixes its set; the wait ends before it releases. + T3ToolSets.fixT3ToolSet("thread-prs", prs, T3ToolSets.nextT3ToolSetTurn()); + expect(yield* drive(waiting, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS)).toEqual([ + [PR_TOOL, true], + ]); + expect(T3ToolSets.t3ToolSetFor("thread-prs")).toEqual(prs); + expect(T3ToolSets.__testing.asked("thread-prs")).toBeUndefined(); + }), + ); + + it.effect("the hold's own turn fixes its set as the bound passes: the drop keeps it (#986)", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); + const turn = T3ToolSets.nextT3ToolSetTurn(); + const release = T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis, turn); + const waiting = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + T3ToolSets.fixT3ToolSet("thread-prs", prs, turn); + expect(yield* drive(waiting, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS)).toEqual([ + [PR_TOOL, true], + ]); + // The release that comes after the drop does nothing. + release(); + expect(T3ToolSets.t3ToolSetFor("thread-prs")).toEqual(prs); + }), + ); + + it.effect( + "a joined turn still checking as the bound passes: the first's late check cannot widen (#986)", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); + // Turn A's check read the wide profile and is stuck; the profile is narrowed; turn B joins + // A's hold, and B's check is still running too as the bound passes. + const a = T3ToolSets.nextT3ToolSetTurn(); + const b = T3ToolSets.nextT3ToolSetTurn(); + const now = yield* Clock.currentTimeMillis; + T3ToolSets.holdT3ToolSet("thread-prs", now, a); + T3ToolSets.holdT3ToolSet("thread-prs", now, b); + const waiting = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + expect(yield* drive(waiting, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS)).toEqual([ + [PR_TOOL, false], + ]); + expect(T3ToolSets.t3ToolSetFor("thread-prs")?._tag).toBe("Refused"); + // The refusal stands for B: A's late check, with its wide read, writes nothing. + T3ToolSets.fixT3ToolSet("thread-prs", { _tag: "Groups", name: "all", groups: "all" }, a); + expect(T3ToolSets.t3ToolSetFor("thread-prs")?._tag).toBe("Refused"); + // B's own late check replaces it. + T3ToolSets.fixT3ToolSet("thread-prs", prs, b); + expect(T3ToolSets.t3ToolSetFor("thread-prs")).toEqual(prs); + }), + ); }); diff --git a/apps/server/src/fork/mcpT3ToolSets.ts b/apps/server/src/fork/mcpT3ToolSets.ts index 73ade63125f1d..8958a504028aa 100644 --- a/apps/server/src/fork/mcpT3ToolSets.ts +++ b/apps/server/src/fork/mcpT3ToolSets.ts @@ -39,24 +39,62 @@ export const refusedT3ToolSet = (reason: string): T3ToolSet => ({ _tag: "Refused */ export const MAX_T3_TOOL_SETS = 4096; -const sets = new Map(); +/** + * A turn's place among the thread's turns: drawn as its check starts, so a later turn has a higher + * one whatever order the checks finish in. One counter for every thread; only order matters. + */ +let lastTurn = 0; + +/** The next turn's place, drawn as its check starts (before it reads the profile). */ +export const nextT3ToolSetTurn = (): number => ++lastTurn; + +/** + * Each thread's set, with the turn that fixed it (`undefined` set: that turn stopped half-way, so + * none stands, but an older turn's late check still may not write). + */ +const sets = new Map(); + +/** + * The latest turn of any thread dropped at the cap. A thread with no entry may have been dropped + * with a turn up to this one, so a check older than it writes nothing: the thread's next request + * works its set out again from the settings instead. + */ +let droppedTurn = 0; -const keep = (threadId: string, set: T3ToolSet) => { +const keep = (threadId: string, turn: number, set: T3ToolSet | undefined) => { sets.delete(threadId); - sets.set(threadId, set); - for (const oldest of sets.keys()) { + sets.set(threadId, { turn, set }); + for (const [oldest, entry] of sets) { if (sets.size <= MAX_T3_TOOL_SETS) break; + droppedTurn = Math.max(droppedTurn, entry.turn); sets.delete(oldest); } }; -/** A turn of the thread starts: its set from now until the next turn starts. */ -export const fixT3ToolSet = (threadId: string, set: T3ToolSet): void => keep(threadId, set); +/** The latest turn that fixed the thread's set (or stopped half-way), or may have, if dropped. */ +const lastFixed = (threadId: string) => sets.get(threadId)?.turn ?? droppedTurn; -/** A turn start stopped half-way: no set stands, so the next request works it out again. */ -export const forgetT3ToolSet = (threadId: string): void => void sets.delete(threadId); +/** True when no turn after `turn` has fixed the thread's set (or stopped half-way). */ +const newest = (threadId: string, turn: number) => lastFixed(threadId) <= turn; + +/** + * A turn of the thread starts: its set from now until the next turn starts. A check that finishes + * after a later turn's has fixed its set writes nothing: the later turn's set stands. `turn` is + * the one drawn before the profile was read (a number drawn after would rank a stale read newest). + */ +export const fixT3ToolSet = (threadId: string, set: T3ToolSet, turn: number): void => { + if (newest(threadId, turn)) keep(threadId, turn, set); +}; + +/** + * A turn start stopped half-way: no set stands, so the next request works it out again (unless a + * later turn fixed one meanwhile, which stands). + */ +export const forgetT3ToolSet = (threadId: string, turn: number): void => { + if (newest(threadId, turn)) keep(threadId, turn, undefined); +}; -export const t3ToolSetFor = (threadId: string): T3ToolSet | undefined => sets.get(threadId); +export const t3ToolSetFor = (threadId: string): T3ToolSet | undefined => sets.get(threadId)?.set; /** * A set worked out for a request before any turn fixed one (a provider that lists tools as its @@ -64,8 +102,9 @@ export const t3ToolSetFor = (threadId: string): T3ToolSet | undefined => sets.ge */ export const rememberT3ToolSet = (threadId: string, set: T3ToolSet): T3ToolSet => { const fixed = sets.get(threadId); - if (fixed !== undefined) return fixed; - keep(threadId, set); + if (fixed?.set !== undefined) return fixed.set; + // As old as the last turn: that turn's late check, or any later turn, still replaces it. + keep(threadId, lastFixed(threadId), set); return set; }; @@ -85,6 +124,8 @@ const holds = new Map< readonly asked: Deferred.Deferred; /** When the hold stops holding: requests then stop waiting, and it is dropped. */ readonly until: number; + /** The latest turn holding it: a drop stands for that turn's set, not yet fixed. */ + turn: number; count: number; } >(); @@ -92,20 +133,23 @@ const holds = new Map< /** * Holds the thread's T3 requests (mcpT3ToolRule.ts) until the returned release runs, so a turn * Codex started gets the set its check fixes. Release always; a second release does nothing. A hold - * taken while one is in force joins it; one taken after the last one's bound starts afresh. + * taken while one is in force joins it (keeping its bound); one taken after that bound starts + * afresh. `turn` is the turn whose check takes it, drawn before that check reads the profile. */ -export const holdT3ToolSet = (threadId: string, now: number): (() => void) => { +export const holdT3ToolSet = (threadId: string, now: number, turn: number): (() => void) => { let hold = holds.get(threadId); if (hold === undefined || hold.until <= now) { hold = { done: Deferred.makeUnsafe(), asked: Deferred.makeUnsafe(), until: now + T3_TOOL_SET_HOLD_WAIT_MS, + turn, count: 0, }; holds.set(threadId, hold); } const held = hold; + held.turn = Math.max(held.turn, turn); held.count += 1; let released = false; return () => { @@ -134,17 +178,20 @@ export const t3ToolSetHold = (threadId: string, now: number): T3ToolSetHold | un /** * A hold its bound passed: dropped, and the thread keeps `set` (never the one before the hold) - * until a turn, or the late check, fixes one. False when it was released meanwhile: the set its - * check fixed stands. + * until a turn, or the late check, fixes one. False when it was released meanwhile, or when the + * hold's latest turn or a later one has fixed its set (or may have, if dropped at the cap). */ export const dropT3ToolSetHold = ( threadId: string, hold: T3ToolSetHold, set: T3ToolSet, ): boolean => { - if (holds.get(threadId)?.done !== hold.done) return false; + const held = holds.get(threadId); + if (held?.done !== hold.done) return false; holds.delete(threadId); - keep(threadId, set); + if (lastFixed(threadId) >= held.turn) return false; + // As the hold's latest turn: that turn's late check still replaces it; an older one does not. + keep(threadId, held.turn, set); return true; }; @@ -152,6 +199,7 @@ export const __testing = { clear: () => { sets.clear(); holds.clear(); + droppedTurn = 0; }, size: () => sets.size, /** Done once a request waits on the thread's hold; `undefined` when none is held. */