From 8633bd57f7d3fec293ca2463840b1df2952e9182 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 10 Nov 2026 18:05:58 -0600 Subject: [PATCH] Retain Photon teardown failures through normal SDK shutdown Attempt the independent SDK teardown after receiver failure, then observe the same adapter disconnect attempt without a hidden retry. Keep the retired lifecycle owner until all required joins succeed. The real-SDK lifecycle regression fails before the repair and all 41 focused cases now pass with the normal complete typecheck. Co-Authored-By: Paperclip --- .../__tests__/photon/runtime-shutdown.test.ts | 57 +++++++++++++++++++ server/src/services/chat-sdk-runtime.ts | 14 ++++- server/src/services/photon/adapter.ts | 16 ++++++ 3 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 server/src/__tests__/photon/runtime-shutdown.test.ts diff --git a/server/src/__tests__/photon/runtime-shutdown.test.ts b/server/src/__tests__/photon/runtime-shutdown.test.ts new file mode 100644 index 00000000000..3f7c1aa6456 --- /dev/null +++ b/server/src/__tests__/photon/runtime-shutdown.test.ts @@ -0,0 +1,57 @@ +import { expect, it, vi } from "vitest"; +import { createChatSdkRuntime, type CreateChatSdkEndpointRuntimeOptions } from "../../services/chat-sdk-runtime.js"; +import { PhotonChatAdapter } from "../../services/photon/adapter.js"; +import { PhotonReceiver } from "../../services/photon/receiver.js"; +import { memoryPersistence } from "./fixture.js"; + +it("receiver failure still attempts independent SDK close and swallowed adapter failure retains the same runtime for retry", async () => { + // Controlled receiver/resource faults and memory state ports. Real installed + // Chat4.39 initialize/shutdown and the actual Runtime/registry remain intact; + // this proves lifecycle ownership, not network/provider physical closure. + const adapters: PhotonChatAdapter[] = []; + vi.spyOn(PhotonChatAdapter.prototype, "initialize").mockImplementation(async function(this:PhotonChatAdapter) { adapters.push(this); }); + vi.spyOn(PhotonReceiver.prototype, "start").mockImplementation(() => undefined); + const receiverFailure = new Error("controlled receiver close responsibility failure"); + const receiverClose = vi.spyOn(PhotonReceiver.prototype,"close").mockRejectedValueOnce(receiverFailure).mockResolvedValue(undefined); + const registry = createChatSdkRuntime(); + const options = (endpointId:string):CreateChatSdkEndpointRuntimeOptions => ({ companyId:"company",endpointId,logger:"silent",persistence:memoryPersistence(), + providerConfig:{provider:"imessage-photon",userName:"Agent",intakeAfter:0,credentials:{allocation:"dedicated",projectId:"project",projectSecret:"controlled-project-secret",lineId:"line",phoneNumber:"+15555550100"}}, + callbacks:{onMessage:async()=>{},onPhotonEvent:async()=>{},onPhotonAssertOwned:async()=>{},onPhotonCheckpoint:async()=>{},onPhotonFailure:async()=>{}} }); + let repairAdapter: (()=>void)|undefined; + try { + const first=await registry.replaceEndpoint(options("receiver-fault"));await first.initialize(); + const firstAdapter=adapters[0];if(!firstAdapter)throw new Error("normal Photon adapter absent"); + const firstPhysicalClose=vi.spyOn(firstAdapter.client,"close"); + await expect(registry.removeEndpoint("receiver-fault")).rejects.toBe(receiverFailure); + expect(registry.get("receiver-fault")).toBeNull();expect(registry.hasUnsettledLifecycle()).toBe(true); + await expect(first.initialize()).rejects.toThrow("retired"); + expect(firstPhysicalClose.mock.calls.length,"independent Photon SDK close must run even when receiver close rejects").toBeGreaterThan(0); + await expect(registry.removeEndpoint("receiver-fault")).resolves.toBe(true); + expect(registry.hasUnsettledLifecycle()).toBe(false); + + const second=await registry.replaceEndpoint(options("adapter-fault"));await second.initialize(); + const secondAdapter=adapters[1];if(!secondAdapter)throw new Error("second normal Photon adapter absent"); + const client=secondAdapter.client,normalClose=client.close.bind(client); + const adapterFailure=new Error("controlled independent SDK close failure"); + const physicalClose=vi.spyOn(client,"close").mockRejectedValue(adapterFailure); + repairAdapter=()=>{physicalClose.mockImplementation(normalClose);}; + // Real Chat.shutdown logs/swallow this rejection. Runtime must observe the + // SAME failed disconnect attempt and keep its retired cleanup owner. + const failedClose=await registry.removeEndpoint("adapter-fault").then(()=>null,error=>error); + expect(failedClose).toBeInstanceOf(AggregateError); + if(!(failedClose instanceof AggregateError))throw new Error("normal adapter failure was swallowed"); + expect(failedClose.errors).toEqual([adapterFailure]); + expect(physicalClose).toHaveBeenCalledTimes(1); // join is observation, not hidden retry. + expect(registry.get("adapter-fault")).toBeNull();expect(registry.hasUnsettledLifecycle()).toBe(true); + await expect(second.initialize()).rejects.toThrow("retired"); + repairAdapter(); + await expect(registry.removeEndpoint("adapter-fault")).resolves.toBe(true); + expect(physicalClose).toHaveBeenCalledTimes(2);expect(registry.hasUnsettledLifecycle()).toBe(false); + expect(receiverClose).toHaveBeenCalledTimes(4); + } finally { + // The original expected baseline assertion failure still reaches all owned + // cleanup. Repair only controlled faults, then join the normal registry. + repairAdapter?.();receiverClose.mockResolvedValue(undefined); + try { await registry.shutdown(); } finally { vi.restoreAllMocks(); } + } +}); diff --git a/server/src/services/chat-sdk-runtime.ts b/server/src/services/chat-sdk-runtime.ts index 6c69018e3e2..34cf181d5d6 100644 --- a/server/src/services/chat-sdk-runtime.ts +++ b/server/src/services/chat-sdk-runtime.ts @@ -3163,8 +3163,18 @@ export class ChatSdkEndpointRuntime { await this.initialization?.catch(() => undefined); await this.discordGatewayTask?.catch(() => undefined); this.discordGatewayAbort = null; - await this.photonReceiver?.close(); - await this.chat.shutdown(); + const failures: unknown[] = []; + try { await this.photonReceiver?.close(); } catch (error) { failures.push(error); } + // Receiver admission has joined (including its failure path) before the + // independently owned normal SDK/adapter teardown is attempted. + try { await this.chat.shutdown(); } catch (error) { failures.push(error); } + if (this.adapter instanceof PhotonChatAdapter) { + // Chat4.39 logs/swallow disconnect rejections. Observe the SAME normal + // adapter attempt, never an implicit second physical-close retry. + try { await this.adapter.joinDisconnectAttempt(); } catch (error) { failures.push(error); } + } + if (failures.length === 1) throw failures[0]; + if (failures.length) throw new AggregateError(failures, "Chat SDK runtime shutdown remains incomplete"); this.shutdownCompleted = true; })(); this.shutdownTask = task; diff --git a/server/src/services/photon/adapter.ts b/server/src/services/photon/adapter.ts index fd7354ffc27..09cbcfe0d8d 100644 --- a/server/src/services/photon/adapter.ts +++ b/server/src/services/photon/adapter.ts @@ -144,7 +144,23 @@ export class PhotonChatAdapter implements Adapter { async initialize(_chat: ChatInstance): Promise { await this.authentication.token(); } + private disconnectAttempt?: Promise; + private disconnectRunning = false; + /** Observe exactly the normal Chat SDK's last disconnect invocation. This + * does not start another close or convert missing ownership into success. */ + async joinDisconnectAttempt(): Promise { + if (!this.disconnectAttempt) throw new Error("Photon normal adapter disconnect was not attempted"); + await this.disconnectAttempt; + } async disconnect(): Promise { + if (this.disconnectRunning) return await this.disconnectAttempt; + const attempt = this.disconnectResources(); + this.disconnectAttempt = attempt; + this.disconnectRunning = true; + try { await attempt; } + finally { if (this.disconnectAttempt === attempt) this.disconnectRunning = false; } + } + private async disconnectResources(): Promise { this.closed = true; for (const timer of this.typing.values()) clearTimeout(timer); this.typing.clear();