Skip to content

Commit b307b44

Browse files
PR Batch Testerclaude
andcommitted
fix(pi): settle background work only once a session switch succeeds
Dropping the outgoing work before the switch outcome was known closed the run that listened for it, so a vetoed switch restored work nobody tracked. The work now stays put until Pi answers. A replacement drops the outgoing session's keys after draining Pi's earlier events, so a progress update an old job sent mid-switch no longer lands on the new session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c8ce2e3 commit b307b44

2 files changed

Lines changed: 84 additions & 88 deletions

File tree

‎packages/provider-pi/src/server/adapter.test.ts‎

Lines changed: 61 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1311,74 +1311,72 @@ describe("PiAdapterV2", () => {
13111311
[providerThread.id, "t3:background:tests", "Tests running"],
13121312
]);
13131313

1314-
// A vetoed switch keeps the outgoing session, so its unfinished jobs are
1315-
// listed again; a job that ended while the switch was in flight is not.
1316-
yield* setStatus("t3:background:build", "Build running");
1314+
// While a switch waits on Pi's hooks, the outgoing session still owns its
1315+
// jobs: they stay listed and keep the run listening for their updates.
1316+
const switchSession = Effect.fnUntraced(function* (
1317+
duringSwitch: Effect.Effect<void>,
1318+
cancelled: boolean,
1319+
) {
1320+
fake.deferNextLifecycle("new_session");
1321+
const switching = yield* runtime
1322+
.ensureThread({
1323+
threadId: THREAD_ID,
1324+
modelSelection: modelSelection("default"),
1325+
runtimePolicy,
1326+
})
1327+
.pipe(Effect.result, Effect.forkScoped);
1328+
const newSession = yield* fake.takeRequest("new_session");
1329+
assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread));
1330+
yield* duringSwitch;
1331+
yield* fake.emit({
1332+
type: "response",
1333+
id: newSession["id"],
1334+
command: "new_session",
1335+
success: true,
1336+
data: { cancelled },
1337+
});
1338+
return yield* Fiber.join(switching);
1339+
});
1340+
1341+
// A vetoed switch keeps the outgoing session and every job it still runs.
13171342
yield* setStatus("t3:background:docs", "Docs building");
13181343
assert.lengthOf(yield* takeRoster(), 2);
1319-
assert.lengthOf(yield* takeRoster(), 3);
1320-
fake.deferNextLifecycle("new_session");
1321-
const vetoing = yield* runtime
1322-
.ensureThread({
1323-
threadId: THREAD_ID,
1324-
modelSelection: modelSelection("default"),
1325-
runtimePolicy,
1326-
})
1327-
.pipe(Effect.flip, Effect.forkScoped);
1328-
const newSession = yield* fake.takeRequest("new_session");
1329-
assert.lengthOf(yield* takeRoster(), 0);
1330-
yield* setStatus("t3:background:build");
1331-
// Pi's events are handled in order, so an answered dialog proves the clear landed.
1332-
yield* fake.emit({
1333-
type: "extension_ui_request",
1334-
id: "switch-hook-dialog",
1335-
method: "confirm",
1336-
title: "Switch sessions?",
1337-
});
1338-
const dialog = yield* takeEvent((event) => event.type === "runtime_request.updated");
1339-
if (dialog.type !== "runtime_request.updated") return;
1340-
yield* runtime.respondToRuntimeRequest({
1341-
requestId: dialog.runtimeRequest.id,
1342-
decision: "accept",
1343-
});
1344-
yield* fake.takeRequest("extension_ui_response");
1345-
yield* fake.emit({
1346-
type: "response",
1347-
id: newSession["id"],
1348-
command: "new_session",
1349-
success: true,
1350-
data: { cancelled: true },
1351-
});
1352-
assert.equal((yield* Fiber.join(vetoing))._tag, "ProviderAdapterEnsureThreadError");
1353-
assert.deepStrictEqual(yield* takeRoster(), [
1354-
[providerThread.id, "t3:background:tests", "Tests running"],
1355-
[providerThread.id, "t3:background:docs", "Docs building"],
1356-
]);
1344+
const vetoed = yield* switchSession(
1345+
Effect.gen(function* () {
1346+
yield* setStatus("t3:background:docs");
1347+
assert.lengthOf(yield* takeRoster(), 1);
1348+
}),
1349+
true,
1350+
);
1351+
assert.equal(vetoed._tag, "Failure");
13571352
// The veto left no bound thread, but the roster still follows the work.
1358-
yield* setStatus("t3:background:docs");
1359-
assert.lengthOf(yield* takeRoster(), 1);
1360-
assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1353+
yield* setStatus("t3:background:docs", "Docs building");
1354+
assert.lengthOf(yield* takeRoster(), 2);
13611355

1362-
// A replaced session invalidates the job's context, so it can never clear.
1363-
const replacement = yield* runtime.ensureThread({
1364-
threadId: THREAD_ID,
1365-
modelSelection: modelSelection("default"),
1366-
runtimePolicy,
1367-
});
1368-
// The vetoed switch already unbound the thread; its roster still empties.
1369-
assert.lengthOf(yield* takeRoster(), 0);
1370-
const registered = yield* takeEvent((event) => event.type === "provider_thread.updated");
1371-
assert.isTrue(
1372-
registered.type === "provider_thread.updated" &&
1373-
registered.providerThread.id === replacement.id &&
1374-
replacement.id !== providerThread.id,
1356+
// A replaced session invalidates the old jobs' context, so they can never
1357+
// clear. A job's progress update that Pi sent mid-switch is still old work;
1358+
// a key first set mid-switch comes from the new session's start hooks.
1359+
fake.queueState({ sessionFile: "/fake/replaced.jsonl" });
1360+
const replaced = yield* switchSession(
1361+
Effect.gen(function* () {
1362+
yield* setStatus("t3:background:tests", "Tests 50%");
1363+
yield* setStatus("t3:background:deploy", "Deploying");
1364+
}),
1365+
false,
1366+
);
1367+
assert.equal(replaced._tag, "Success");
1368+
if (replaced._tag !== "Success") return;
1369+
assert.deepStrictEqual(
1370+
replaced.success.pendingBackgroundTasks?.map((task) => task.taskId),
1371+
["t3:background:deploy"],
1372+
);
1373+
yield* setStatus("t3:background:deploy");
1374+
yield* takeEvent(
1375+
(event) =>
1376+
event.type === "provider_thread.updated" &&
1377+
event.providerThread.id === replaced.success.id &&
1378+
event.providerThread.pendingBackgroundTasks?.length === 0,
13751379
);
1376-
assert.deepStrictEqual(replacement.pendingBackgroundTasks, []);
1377-
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1378-
yield* setStatus("t3:background:deploy", "Deploying");
1379-
assert.lengthOf(yield* takeRoster(), 1);
1380-
yield* setStatus("t3:background:deploy", "");
1381-
assert.lengthOf(yield* takeRoster(), 0);
13821380
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
13831381
}).pipe(Effect.scoped, Effect.provide(layerTest)),
13841382
);

‎packages/provider-pi/src/server/adapter.ts‎

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -552,8 +552,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
552552
// The last bound thread, whose roster lists backgroundWork. Unlike
553553
// threadState it survives a failed or vetoed session switch.
554554
let backgroundWorkState: PiThreadState | null = null;
555-
// Work dropped by an in-flight lifecycle request, restored if it is vetoed.
556-
let outgoingBackgroundWork: Map<string, string> | null = null;
557555
let rollbackBarrier: Deferred.Deferred<
558556
void,
559557
ProviderAdapter.ProviderAdapterProtocolError
@@ -679,15 +677,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
679677
const syncBackgroundWork = (state: PiThreadState) =>
680678
updateProviderThread(state, { pendingBackgroundTasks: pendingBackgroundTasks() });
681679

682-
const lifecycleRequest = Effect.fnUntraced(function* (record: PiRpcRecord) {
683-
// Pi invalidates the outgoing session's extension context, so its jobs
684-
// can no longer clear their statuses. Pi's own TUI drops them here too.
685-
const outgoingWork = new Map(backgroundWork);
686-
const outgoingState = backgroundWorkState;
687-
outgoingBackgroundWork = outgoingWork;
688-
backgroundWork.clear();
689-
if (outgoingState !== null && outgoingWork.size > 0)
690-
yield* syncBackgroundWork(outgoingState);
680+
const lifecycleRequest = Effect.fn("PiAdapter.lifecycleRequest")(function* (
681+
record: PiRpcRecord,
682+
) {
683+
const outgoingKeys = new Set(backgroundWork.keys());
691684
const result = yield* request(record, PI_SESSION_TIMEOUT_MS).pipe(
692685
// A local timeout does not cancel Pi's lifecycle hook. Retire the
693686
// process before fallback can race its eventual switch/new-session.
@@ -703,18 +696,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
703696
connection.terminate.pipe(Effect.andThen(Effect.fail(error))),
704697
}),
705698
Effect.onInterrupt(() => connection.terminate),
706-
Effect.ensuring(
707-
Effect.sync(() => {
708-
outgoingBackgroundWork = null;
709-
}),
710-
),
711699
);
712-
if (recordField(result, "cancelled") === true && outgoingState !== null) {
713-
// A job may have cleared its status while the switch was in flight.
714-
for (const [key, description] of outgoingWork) {
715-
if (!backgroundWork.has(key)) backgroundWork.set(key, description);
716-
}
717-
if (backgroundWork.size > 0) yield* syncBackgroundWork(outgoingState);
700+
if (recordField(result, "cancelled") !== true && outgoingKeys.size > 0) {
701+
// Pi invalidates the outgoing session's extension context, so its
702+
// jobs can no longer clear their statuses; Pi's own TUI drops them
703+
// here too. Responses bypass the pump, so first apply every status
704+
// Pi sent before replying. Keys first set during the switch belong
705+
// to the replacement session's start hooks.
706+
const drained = yield* Deferred.make<void>();
707+
if (yield* Queue.offer(connection.events, { type: "t3.drain", drained }))
708+
yield* Deferred.await(drained);
709+
for (const key of outgoingKeys) backgroundWork.delete(key);
710+
if (backgroundWorkState !== null) yield* syncBackgroundWork(backgroundWorkState);
718711
}
719712
return result;
720713
});
@@ -1296,9 +1289,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
12961289
if (description.length > 0) {
12971290
if (backgroundWork.get(statusKey) === description) return;
12981291
backgroundWork.set(statusKey, description);
1299-
} else {
1300-
outgoingBackgroundWork?.delete(statusKey);
1301-
if (!backgroundWork.delete(statusKey)) return;
1292+
} else if (!backgroundWork.delete(statusKey)) {
1293+
return;
13021294
}
13031295
if (backgroundWorkState !== null) yield* syncBackgroundWork(backgroundWorkState);
13041296
return;
@@ -2120,6 +2112,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
21202112
}
21212113
return;
21222114
}
2115+
case "t3.drain": {
2116+
const drained = event["drained"];
2117+
if (Deferred.isDeferred<void, never>(drained))
2118+
yield* Deferred.succeed(drained, undefined);
2119+
return;
2120+
}
21232121
case "t3.rollback_barrier": {
21242122
if (rollbackBarrier !== null && event["barrier"] === rollbackBarrier)
21252123
yield* Deferred.succeed(rollbackBarrier, undefined);

0 commit comments

Comments
 (0)