GeezerVison is showing github.com — fix(pi): restoring a Pi session no longer deadlocks on an extension's… · pingdotgg/t3code@3161c5b
File treeExpand file treeCollapse file tree Open diff view settings apps/server/src/orchestration-v2 packages/provider-pi/src/server
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/EffectOutbox.ts +6Lines changed: 6 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -325,6 +325,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La | 325 | 325 | Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined), | 326 | 326 | ).pipe(Effect.asVoid); | 327 | 327 | // Retry backoff must block later effects so turns cannot race a pending rollback. | | 328 | + // A request answer alone passes its thread's running turn start, which can be waiting for it. | 328 | 329 | const claimableCandidatePredicate = ( | 329 | 330 | availableBefore?: string, | 330 | 331 | excludeRestartContinuations = false, | @@ -353,6 +354,11 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La | 353 | 354 | } | 354 | 355 | ) | 355 | 356 | ) | | 357 | + AND NOT ( | | 358 | + candidate.effect_type = 'runtime-request.respond' | | 359 | + AND active.status = 'running' | | 360 | + AND active.effect_type = 'provider-turn.start' | | 361 | + ) | 356 | 362 | AND ( | 357 | 363 | ( | 358 | 364 | candidate.effect_type = 'thread-title.generate' | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/FoundationPersistence.test.ts +67Lines changed: 67 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,6 +21,7 @@ import { | 21 | 21 | ProviderInstanceId, | 22 | 22 | ProviderSessionId, | 23 | 23 | ProviderThreadId, | | 24 | + RuntimeRequestId, | 24 | 25 | RunAttemptId, | 25 | 26 | RunId, | 26 | 27 | ThreadId, | @@ -2702,6 +2703,72 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { | 2702 | 2703 | }), | 2703 | 2704 | ); | 2704 | 2705 |
| | 2706 | + it.effect("claims a request answer past its thread's running turn start only", () => | | 2707 | + Effect.gen(function* () { | | 2708 | + const outbox = yield* EffectOutbox.EffectOutboxV2; | | 2709 | + const workerId = "answer-order-worker"; | | 2710 | + const commandId = CommandId.make("command:foundation-answer-order"); | | 2711 | + const threadId = ThreadId.make("thread:foundation-answer-order"); | | 2712 | + const providerSessionId = ProviderSessionId.make("provider-session:foundation-answer-order"); | | 2713 | + const answer = (name: string) => ({ | | 2714 | + id: `effect:foundation-answer-order:${name}`, | | 2715 | + commandId, | | 2716 | + threadId, | | 2717 | + request: { | | 2718 | + type: "runtime-request.respond" as const, | | 2719 | + providerSessionId, | | 2720 | + requestId: RuntimeRequestId.make(`request:foundation-answer-order:${name}`), | | 2721 | + decision: "accept" as const, | | 2722 | + }, | | 2723 | + }); | | 2724 | + const claimId = outbox | | 2725 | + .claimNext({ workerId }) | | 2726 | + .pipe(Effect.map(Option.map((effect) => effect.id))); | | 2727 | + yield* outbox.enqueue([ | | 2728 | + { | | 2729 | + id: "effect:foundation-answer-order:start", | | 2730 | + commandId, | | 2731 | + threadId, | | 2732 | + request: { | | 2733 | + type: "provider-turn.start", | | 2734 | + runId: RunId.make("run:foundation-answer-order"), | | 2735 | + }, | | 2736 | + }, | | 2737 | + ]); | | 2738 | + assert.deepEqual(yield* claimId, Option.some("effect:foundation-answer-order:start")); | | 2739 | + | | 2740 | + yield* outbox.enqueue([ | | 2741 | + answer("first"), | | 2742 | + answer("second"), | | 2743 | + { | | 2744 | + id: "effect:foundation-answer-order:cleanup", | | 2745 | + commandId, | | 2746 | + threadId, | | 2747 | + request: { type: "terminal.cleanup" }, | | 2748 | + }, | | 2749 | + ]); | | 2750 | + assert.isTrue(Option.isSome(yield* outbox.nextClaimableAt())); | | 2751 | + assert.deepEqual(yield* claimId, Option.some(answer("first").id)); | | 2752 | + // Answers stay serialized, and nothing else passes the running start. | | 2753 | + assert.deepEqual(yield* claimId, Option.none()); | | 2754 | + yield* outbox.succeed({ effectId: answer("first").id, workerId }); | | 2755 | + assert.deepEqual(yield* claimId, Option.some(answer("second").id)); | | 2756 | + yield* outbox.succeed({ effectId: answer("second").id, workerId }); | | 2757 | + assert.deepEqual(yield* claimId, Option.none()); | | 2758 | + | | 2759 | + yield* outbox.succeed({ effectId: "effect:foundation-answer-order:start", workerId }); | | 2760 | + assert.deepEqual(yield* claimId, Option.some("effect:foundation-answer-order:cleanup")); | | 2761 | + yield* outbox.enqueue([answer("behind-cleanup")]); | | 2762 | + assert.deepEqual(yield* claimId, Option.none()); | | 2763 | + yield* outbox.succeed({ effectId: "effect:foundation-answer-order:cleanup", workerId }); | | 2764 | + yield* outbox.cancelUnsettled({ | | 2765 | + threadId, | | 2766 | + effectTypes: ["runtime-request.respond"], | | 2767 | + reason: "Test cleanup.", | | 2768 | + }); | | 2769 | + }), | | 2770 | + ); | | 2771 | + | 2705 | 2772 | it.effect("prunes settled effects past retention in batches and keeps the rest", () => | 2706 | 2773 | Effect.gen(function* () { | 2707 | 2774 | const outbox = yield* EffectOutbox.EffectOutboxV2; | |
Collapse file Copy file name to clipboardExpand all lines: packages/provider-pi/src/server/adapter.test.ts +110-1Lines changed: 110 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -33,6 +33,7 @@ import * as Schema from "effect/Schema"; | 33 | 33 | import * as Scope from "effect/Scope"; | 34 | 34 | import * as Sink from "effect/Sink"; | 35 | 35 | import * as Stream from "effect/Stream"; | | 36 | +import * as TestClock from "effect/testing/TestClock"; | 36 | 37 | import * as ChildProcess from "effect/process/ChildProcess"; | 37 | 38 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; | 38 | 39 |
| @@ -54,7 +55,7 @@ import { | 54 | 55 | } from "./adapter.ts"; | 55 | 56 | import { makePiRpcConnection, type PiRpcRecord } from "./rpc.ts"; | 56 | 57 | import { loadMcpBridge } from "./mcpBridge.testkit.ts"; | 57 | | -import { PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts"; | | 58 | +import { PI_T3_RUN_ADMISSION_TITLE, PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts"; | 58 | 59 | import { turnItemOutputText } from "../../../client-runtime/src/work-log/itemDetail.ts"; | 59 | 60 |
| 60 | 61 | const layerTest = Layer.mergeAll( | @@ -2170,6 +2171,114 @@ describe("PiAdapterV2", () => { | 2170 | 2171 | }).pipe(Effect.scoped, Effect.provide(layerTest)), | 2171 | 2172 | ); | 2172 | 2173 |
| | 2174 | + it.effect.each([ | | 2175 | + { name: "completes a switch whose hook finishes", hookSeconds: 2, completes: true }, | | 2176 | + { name: "times out a switch whose hook stalls", hookSeconds: 60, completes: false }, | | 2177 | + ])("$name after a dialog answered late", ({ hookSeconds, completes }) => | | 2178 | + Effect.gen(function* () { | | 2179 | + const fake = yield* makeFakePi; | | 2180 | + const { runtime, takeEvent } = yield* openRuntime(fake); | | 2181 | + const providerThread = yield* runtime.ensureThread({ | | 2182 | + threadId: THREAD_ID, | | 2183 | + modelSelection: modelSelection("default"), | | 2184 | + runtimePolicy, | | 2185 | + }); | | 2186 | + fake.deferNextLifecycle("switch_session"); | | 2187 | + const switching = yield* runtime | | 2188 | + .resumeThread({ providerThread }) | | 2189 | + .pipe(Effect.exit, Effect.forkScoped); | | 2190 | + const request = yield* fake.takeRequest("switch_session"); | | 2191 | + yield* fake.emit({ | | 2192 | + type: "extension_ui_request", | | 2193 | + id: "resume-goal", | | 2194 | + method: "confirm", | | 2195 | + title: "Resume paused goal?", | | 2196 | + }); | | 2197 | + const dialog = yield* takeEvent((event) => event.type === "runtime_request.updated"); | | 2198 | + assert(dialog.type === "runtime_request.updated"); | | 2199 | + // One second short of two whole lifecycle windows: the answer lands just before a deadline check. | | 2200 | + yield* TestClock.adjust("119 seconds"); | | 2201 | + yield* runtime.respondToRuntimeRequest({ | | 2202 | + requestId: dialog.runtimeRequest.id, | | 2203 | + decision: "accept", | | 2204 | + }); | | 2205 | + yield* fake.takeRequest("extension_ui_response"); | | 2206 | + yield* TestClock.adjust(`${hookSeconds} seconds`); | | 2207 | + if (completes) | | 2208 | + yield* fake.emit({ | | 2209 | + type: "response", | | 2210 | + id: request["id"], | | 2211 | + command: "switch_session", | | 2212 | + success: true, | | 2213 | + data: { cancelled: false }, | | 2214 | + }); | | 2215 | + const exit = yield* Fiber.join(switching); | | 2216 | + assert.equal(Exit.isSuccess(exit), completes); | | 2217 | + if (!completes) | | 2218 | + assert.include( | | 2219 | + Cause.pretty((exit as Exit.Failure<never, unknown>).cause), | | 2220 | + "timed out after 60000ms", | | 2221 | + ); | | 2222 | + }).pipe(Effect.scoped, Effect.provide(layerTest)), | | 2223 | + ); | | 2224 | + | | 2225 | + it.effect("holds a resumed session's first run until a turn owns the session", () => | | 2226 | + Effect.gen(function* () { | | 2227 | + const fake = yield* makeFakePi; | | 2228 | + const { runtime, takeEvent } = yield* openRuntime(fake); | | 2229 | + const providerThread = yield* runtime.ensureThread({ | | 2230 | + threadId: THREAD_ID, | | 2231 | + modelSelection: modelSelection("default"), | | 2232 | + runtimePolicy, | | 2233 | + }); | | 2234 | + fake.deferNextLifecycle("switch_session"); | | 2235 | + const switching = yield* runtime.resumeThread({ providerThread }).pipe(Effect.forkScoped); | | 2236 | + const request = yield* fake.takeRequest("switch_session"); | | 2237 | + const askAdmission = (id: string) => | | 2238 | + fake.emit({ | | 2239 | + type: "extension_ui_request", | | 2240 | + id, | | 2241 | + method: "confirm", | | 2242 | + title: PI_T3_RUN_ADMISSION_TITLE, | | 2243 | + message: "", | | 2244 | + }); | | 2245 | + yield* askAdmission("restored-run"); | | 2246 | + // The status update is an observable milestone after the admission request. | | 2247 | + yield* fake.emit({ | | 2248 | + type: "extension_ui_request", | | 2249 | + method: "setStatus", | | 2250 | + statusKey: "goal", | | 2251 | + statusText: "Resuming", | | 2252 | + }); | | 2253 | + yield* takeEvent( | | 2254 | + (event) => | | 2255 | + event.type === "provider_session.updated" && | | 2256 | + event.providerSession.extensionStatuses?.[0]?.key === "goal", | | 2257 | + ); | | 2258 | + yield* fake.emit({ | | 2259 | + type: "response", | | 2260 | + id: request["id"], | | 2261 | + command: "switch_session", | | 2262 | + success: true, | | 2263 | + data: { cancelled: false }, | | 2264 | + }); | | 2265 | + const resumed = yield* Fiber.join(switching); | | 2266 | + assert.isFalse(fake.allRequests().some((sent) => sent["type"] === "extension_ui_response")); | | 2267 | + | | 2268 | + yield* startTurn(runtime, resumed); | | 2269 | + const admitted = yield* fake.takeRequest("extension_ui_response"); | | 2270 | + assert.deepEqual( | | 2271 | + { id: admitted["id"], confirmed: admitted["confirmed"] }, | | 2272 | + { id: "restored-run", confirmed: true }, | | 2273 | + ); | | 2274 | + // Requests are taken in the order Pi read them: the turn's prompt follows the admission. | | 2275 | + assert.equal((yield* fake.takeRequest("prompt"))["message"], "Hello pi"); | | 2276 | + | | 2277 | + yield* askAdmission("owned-run"); | | 2278 | + assert.equal((yield* fake.takeRequest("extension_ui_response"))["id"], "owned-run"); | | 2279 | + }).pipe(Effect.scoped, Effect.provide(layerTest)), | | 2280 | + ); | | 2281 | + | 2173 | 2282 | it.effect("retires an interrupted switch before accepting further requests", () => | 2174 | 2283 | Effect.gen(function* () { | 2175 | 2284 | const fake = yield* makeFakePi; | |
Collapse file Copy file name to clipboardExpand all lines: packages/provider-pi/src/server/adapter.ts +52-6Lines changed: 52 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -61,6 +61,7 @@ import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/sel | 61 | 61 | import { | 62 | 62 | findReportedPiModel, | 63 | 63 | makePiRpcConnection, | | 64 | + PiRpcTimeoutError, | 64 | 65 | resolvePiModelSlug, | 65 | 66 | piRecordField as recordField, | 66 | 67 | piRecordNumber as recordNumber, | @@ -73,7 +74,11 @@ import { | 73 | 74 | materializePiT3McpExtension, | 74 | 75 | resolvePiLaunchArgs, | 75 | 76 | } from "./mcpInjection.ts"; | 76 | | -import { PI_FILE_CHANGE_TOOLS, PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts"; | | 77 | +import { | | 78 | + PI_FILE_CHANGE_TOOLS, | | 79 | + PI_T3_RUN_ADMISSION_TITLE, | | 80 | + PI_T3_SERVICE_TIER_COMMAND, | | 81 | +} from "./mcpExtensionSource.ts"; | 77 | 82 | import { PI_STANDARD_SERVICE_TIER } from "./modelCapabilities.ts"; | 78 | 83 |
| 79 | 84 | export const PI_PROVIDER = ProviderDriverKind.make("pi"); | @@ -543,6 +548,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 543 | 548 | ProviderAdapter.ProviderAdapterV2Error | Cause.Done | 544 | 549 | >(); | 545 | 550 | const pendingPrompts = new Map<string, PendingPiPrompt>(); | | 551 | + // Lifecycle deadlines restart when a dialog closes: the time a user spends answering is not Pi's. | | 552 | + let lastPromptClosedAt = 0; | | 553 | + const forgetPrompt = (requestId: string, closedAt: DateTime.Utc) => { | | 554 | + pendingPrompts.delete(requestId); | | 555 | + lastPromptClosedAt = DateTime.toEpochMillis(closedAt); | | 556 | + }; | 546 | 557 | const sessionApprovals = new Set<string>(); | 547 | 558 | // Pi can settle immediately after dialog response; serialize so terminal cannot overtake request resolution. | 548 | 559 | const sessionEventPermit = yield* Semaphore.make(1); | @@ -554,6 +565,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 554 | 565 | // Turn failures can leave Pi alive; pump termination retires the runtime. | 555 | 566 | let runtimeRetired = false; | 556 | 567 | let pendingWake: PiWake | null = null; | | 568 | + // A resumed session's first run asks before it starts; the next owned turn answers it. | | 569 | + let heldRunAdmission: string | null = null; | 557 | 570 | let extensionStatusReset: { | 558 | 571 | previous: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>; | 559 | 572 | readonly touched: Set<string>; | @@ -800,7 +813,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 800 | 813 | ) | 801 | 814 | return yield* protocolError("Pi transport closed during status reset"); | 802 | 815 | yield* Deferred.await(reset.ready); | 803 | | - const result = yield* request(record, PI_SESSION_TIMEOUT_MS); | | 816 | + // Session hooks can wait on the user, so Pi gets the whole window after the last dialog. | | 817 | + const deadline = Effect.gen(function* () { | | 818 | + let wait = PI_SESSION_TIMEOUT_MS; | | 819 | + while (wait > 0) { | | 820 | + yield* Effect.sleep(Duration.millis(wait)); | | 821 | + wait = | | 822 | + pendingPrompts.size > 0 | | 823 | + ? PI_SESSION_TIMEOUT_MS | | 824 | + : lastPromptClosedAt + | | 825 | + PI_SESSION_TIMEOUT_MS - | | 826 | + DateTime.toEpochMillis(yield* DateTime.now); | | 827 | + } | | 828 | + return yield* new PiRpcTimeoutError({ | | 829 | + operation: String(record["type"]), | | 830 | + timeoutMs: PI_SESSION_TIMEOUT_MS, | | 831 | + }); | | 832 | + }); | | 833 | + const result = yield* Effect.raceFirst(request(record, Infinity), deadline); | 804 | 834 | if (recordField(result, "cancelled") === true) { | 805 | 835 | yield* sessionEventPermit.withPermits(1)( | 806 | 836 | Effect.gen(function* () { | @@ -1430,6 +1460,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 1430 | 1460 | ) { | 1431 | 1461 | const pending = Array.from(pendingPrompts.values()); | 1432 | 1462 | pendingPrompts.clear(); | | 1463 | + if (pending.length > 0) lastPromptClosedAt = DateTime.toEpochMillis(resolvedAt); | 1433 | 1464 | yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), { | 1434 | 1465 | discard: true, | 1435 | 1466 | }); | @@ -1488,6 +1519,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 1488 | 1519 | ); | 1489 | 1520 | }); | 1490 | 1521 |
| | 1522 | + const admitRun = (nativeRequestId: string) => | | 1523 | + connection.send({ type: "extension_ui_response", id: nativeRequestId, confirmed: true }); | | 1524 | + | 1491 | 1525 | const handleExtensionUiRequest = Effect.fnUntraced(function* (event: PiRpcRecord) { | 1492 | 1526 | const method = recordString(event, "method"); | 1493 | 1527 | const nativeRequestId = recordString(event, "id"); | @@ -1514,6 +1548,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 1514 | 1548 | return; | 1515 | 1549 | } | 1516 | 1550 | if (nativeRequestId === undefined) return; | | 1551 | + if (method === "confirm" && recordString(event, "title") === PI_T3_RUN_ADMISSION_TITLE) { | | 1552 | + if (threadState?.activeTurn == null) heldRunAdmission = nativeRequestId; | | 1553 | + else yield* admitRun(nativeRequestId); | | 1554 | + return; | | 1555 | + } | 1517 | 1556 | const approvalTitle = recordString(event, "title") ?? ""; | 1518 | 1557 | const approvalKey = `${approvalTitle.length}:${approvalTitle}${recordString(event, "message") ?? ""}`; | 1519 | 1558 | if (method === "confirm" && sessionApprovals.has(approvalKey)) { | @@ -2370,8 +2409,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 2370 | 2409 | if (requestId === undefined) return; | 2371 | 2410 | const pending = pendingPrompts.get(requestId); | 2372 | 2411 | if (pending === undefined || pending !== event["pending"]) return; | 2373 | | - pendingPrompts.delete(requestId); | 2374 | | - yield* cancelPrompt(pending, yield* DateTime.now); | | 2412 | + const expiredAt = yield* DateTime.now; | | 2413 | + forgetPrompt(requestId, expiredAt); | | 2414 | + yield* cancelPrompt(pending, expiredAt); | 2375 | 2415 | return; | 2376 | 2416 | } | 2377 | 2417 | case "t3.flush_extension_errors": { | @@ -2578,6 +2618,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 2578 | 2618 | lastNativeThreadId = resumeId ?? lastNativeThreadId; | 2579 | 2619 | // Failed lifecycle operations can still change native sessions; invalidate bindings and defaults. | 2580 | 2620 | threadState = null; | | 2621 | + heldRunAdmission = null; | 2581 | 2622 | appliedModel = null; | 2582 | 2623 | appliedThinking = null; | 2583 | 2624 | appliedSessionName = null; | @@ -2947,6 +2988,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 2947 | 2988 | state.providerThread = turnInput.providerThread; | 2948 | 2989 | state.activeTurn = activeTurn; | 2949 | 2990 | activeTurn.adoptedWake = wake !== null && !continuation; | | 2991 | + // The selection is applied and this turn owns the session, so the held run may start. | | 2992 | + if (heldRunAdmission !== null && !continuation) { | | 2993 | + yield* admitRun(heldRunAdmission); | | 2994 | + heldRunAdmission = null; | | 2995 | + } | 2950 | 2996 | if (compactCommand !== null) { | 2951 | 2997 | yield* connection.send(compactRpcRecord(compactCommand)); | 2952 | 2998 | pendingCompactResponses.push({ | @@ -3148,7 +3194,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 3148 | 3194 | pending.expiresAt !== null && | 3149 | 3195 | DateTime.toEpochMillis(answeredAt) >= pending.expiresAt | 3150 | 3196 | ) { | 3151 | | - pendingPrompts.delete(String(requestInput.requestId)); | | 3197 | + forgetPrompt(String(requestInput.requestId), answeredAt); | 3152 | 3198 | yield* cancelPrompt(pending, answeredAt); | 3153 | 3199 | return yield* protocolError( | 3154 | 3200 | `Pi extension request ${requestInput.requestId} has expired`, | @@ -3160,7 +3206,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( | 3160 | 3206 | id: pending.nativeRequestId, | 3161 | 3207 | ...response, | 3162 | 3208 | }); | 3163 | | - pendingPrompts.delete(String(requestInput.requestId)); | | 3209 | + forgetPrompt(String(requestInput.requestId), answeredAt); | 3164 | 3210 | if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber); | 3165 | 3211 | if (pending.method === "confirm" && requestInput.decision === "acceptForSession") { | 3166 | 3212 | sessionApprovals.add(pending.approvalKey); | |
|