From 72b35fa80ba0fd79cff1a1577aea8259cb774174 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 10 Nov 2026 20:03:00 -0600 Subject: [PATCH] Recover fenced Photon delivery while retaining physical cleanup debt Persist receiver allocation identity before construction, recover business from the current tagged admission prefix after close-to-commit loss, and retain unknown physical cleanup independently. Use the existing renewable lease for finite recovery and join its body before release. Preserve the actual old-source causal failure and explicit physical-proof test purpose; current green and assembled acceptance remain required. Co-Authored-By: Paperclip --- doc/connections/IMESSAGE-PHOTON.md | 11 ++ .../__tests__/photon/external-owner.test.ts | 107 ++++++++++++++++-- server/src/services/chat-channels.ts | 13 ++- .../imessage-photon/external-contract.ts | 13 ++- .../imessage-photon/external-owner.ts | 84 ++++++++++---- .../imessage-photon/external-runtime.ts | 68 +++++++++-- .../imessage-photon/external-store.ts | 6 + .../imessage-photon/resource-process.ts | 18 +++ .../chat-channels/runtime/ownership.ts | 60 ++++++++-- 9 files changed, 330 insertions(+), 50 deletions(-) create mode 100644 server/src/services/chat-channels/imessage-photon/resource-process.ts diff --git a/doc/connections/IMESSAGE-PHOTON.md b/doc/connections/IMESSAGE-PHOTON.md index f0961fe92ab..874b08d1e5d 100644 --- a/doc/connections/IMESSAGE-PHOTON.md +++ b/doc/connections/IMESSAGE-PHOTON.md @@ -194,6 +194,17 @@ handoff and publication identities rather than replacing uncertain work with a new send. An unknown retirement keeps its credential-cleanup responsibility until normal acceptance and resource closure are confirmed. +After process replacement, a current authorized receiver lease may recover useful +intake from the exact tagged durable checkpoint even while an old local resource +is physically unconfirmed. This restores business delivery, not a close receipt. +The old descriptor and retirement debt remain; a missing UUID, expired lease, or +controller fence never means that its SDK sockets closed. Newly allocated local +receivers save their real process birth and namespace before construction. Normal +Retry can join the same original resource or use actual matching-namespace +process-exit evidence. A foreign or older opaque descriptor stays in attention +without a recurring retry loop; current business recovery does not erase it or +permit credential cleanup to report complete. + ## Troubleshooting | State or symptom | Action | diff --git a/server/src/__tests__/photon/external-owner.test.ts b/server/src/__tests__/photon/external-owner.test.ts index f65c5691dfc..53d4b6f788d 100644 --- a/server/src/__tests__/photon/external-owner.test.ts +++ b/server/src/__tests__/photon/external-owner.test.ts @@ -1,3 +1,5 @@ +import { photonResourceProcessEnded } from "../../services/chat-channels/imessage-photon/resource-process.js"; +import type { ProcessProbe } from "../../services/owner-proof.js"; import { isDeepStrictEqual } from "node:util"; import { describe, expect, it } from "vitest"; import type { ChatSdkStatePersistence, ChatSdkStateRecord } from "../../services/chat-sdk-state.js"; @@ -13,7 +15,7 @@ const identity: PhotonExternalIdentity = { companyId: "company", endpointId: "en const config = { provider: "imessage-photon" as const, userName: "Photon", intakeAfter: 1, credentials: { projectId: "project", projectSecret: "controlled-project-secret", lineId: "line", phoneNumber: "+15555550101", allocation: "dedicated" as const } }; function fixture() { - let rows = new Map(), currentLease = "lease", currentGeneration = 1; + let rows = new Map(), currentLease = "lease", currentGeneration = 1, loseCloseCommit = false, allowed = true; const persistence: ChatSdkStatePersistence = { read: async (_scope, key) => structuredClone(rows.get(key) ?? null), compareAndSet: async input => { @@ -30,14 +32,19 @@ function fixture() { read: async () => read(), inspect: async () => read(), current: async (selected, lease, work) => { - if (selected.companyId !== identity.companyId || selected.runtimeGeneration !== currentGeneration || lease.token !== currentLease) throw new Error("current authority changed"); + if (!allowed || !isDeepStrictEqual(selected, identity) || selected.runtimeGeneration !== currentGeneration || lease.token !== currentLease) throw new Error("current authority changed"); const before = structuredClone(rows); - try { return await work(state, await read()); } catch (error) { rows = before; throw error; } + try { + if (loseCloseCommit && (await read())?.phase === "joining") { loseCloseCommit = false; throw new Error("lost close-to-external commit"); } + return await work(state, await read()); + } catch (error) { rows = before; throw error; } }, retained: async (expected, update) => state.update(PHOTON_EXTERNAL_STATE, raw => { const actual = readPhotonExternalState(raw); if (!actual || !isDeepStrictEqual(actual, expected)) throw new Error("retained CAS failed"); - return update(actual); + const next = update(actual); + if (loseCloseCommit && Object.hasOwn(next, "localClosureConfirmed")) { loseCloseCommit = false; throw new Error("lost close-to-external commit"); } + return next; }), noEffect: async () => { throw new Error("no revocation in this owner-port fixture"); }, }; @@ -64,7 +71,7 @@ function fixture() { const create = (selectedResources = resources) => createPhotonExternalOwner({ store, broker, resources: selectedResources, notify: () => {}, now: () => new Date("2099-01-01T00:00:00.000Z") }); const reconcile = () => create().reconcile({ identity, config, lease: { token: currentLease }, localResourceId: resourceId }); return { state, store, resources, resourceId, resource, requests, create, reconcile, read, - loseReply: () => { lostEnrollment = true; }, replaceGeneration: () => { currentGeneration++; }, replaceLease: () => { currentLease = "next-lease"; }, + loseReply: () => { lostEnrollment = true; }, loseCloseCommit: () => { loseCloseCommit = true; }, revoke: () => { allowed = false; }, replaceGeneration: () => { currentGeneration++; }, replaceLease: () => { currentLease = "next-lease"; }, finishRetirement: () => { retirement = "retired"; }, counts: () => ({ enrollments, joins }) }; } // Actual pinned protobuf: CatchUpEventsResponse.sequence=1/chat_changed=13; @@ -91,8 +98,62 @@ describe("Photon normal external-owner handoff (controlled owner ports, not real }); it("a replacement process cannot use absent local resources as physical-close proof", async () => { const f = fixture(); f.loseReply(); await expect(f.reconcile()).rejects.toThrow(); - await expect(f.create(new PhotonLocalResources()).reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId })).rejects.toThrow("closure is unknown"); - expect(await f.read()).toMatchObject({ phase: "joining", failure: { code: "local_join" } }); + const replacement = f.create(new PhotonLocalResources()); + const recovered = await replacement.reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId }); + expect(recovered).toMatchObject({ phase: "external", localResourceId: f.resourceId, localResourceDebt: { nextAttemptAt: null } }); + expect(recovered.localClosureConfirmed).toBeUndefined(); expect(recovered.joinedSequence).toBeNull(); + await expect(replacement.retire(recovered)).rejects.toThrow("closure is unknown"); + expect((await f.read())?.phase).not.toBe("retired"); + }); + it("recovers fenced business after actual close loses its commit without inventing old physical closure", async () => { + const f = fixture(); f.loseCloseCommit(); + await expect(f.reconcile()).rejects.toThrow("lost close-to-external commit"); + const original = await f.read(); expect(original?.phase).toBe("joining"); expect(f.counts().joins).toBe(1); + f.replaceLease(); const replacement = f.create(new PhotonLocalResources()); + const recovered = await replacement.reconcile({ identity, config, lease: { token: "next-lease" }, localResourceId: f.resourceId }); + expect(recovered.phase, "fenced business recovery must survive close-before-commit restart").toBe("external"); + expect(recovered.handoffId).toBe(original?.handoffId); expect(recovered.binding).toEqual(original?.binding); + expect(recovered.localResourceId).toBe(f.resourceId); expect(recovered.localClosureConfirmed).toBeUndefined(); + expect(recovered.joinedSequence).toBeNull(); expect(recovered.acceptedSequence).toBe(2); + expect(recovered.localResourceDebt).toMatchObject({ nextAttemptAt: null }); + let admitted = 0; const event = delivery(recovered); + await replacement.dispatch({ identity, lease: { token: "next-lease" }, delivery: event, admit: async () => { admitted++; } }); + await replacement.dispatch({ identity, lease: { token: "next-lease" }, delivery: event, admit: async () => { admitted++; } }); + expect(admitted).toBe(1); expect(f.counts().joins).toBe(1); + const current = await f.read(); if (!current) throw new Error("missing retained owner"); + await expect(replacement.retire(current)).rejects.toThrow("closure is unknown"); + expect(f.requests.filter(request => request.kind === "retire")).toHaveLength(0); + }); + it("current recovery rejects stale lease, generation, company and credential authority", async () => { + const f = fixture(); + await f.create().prepare({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId, + localResource: { id: f.resourceId, controller: { bootId: "old", hostHash: "different-space", pid: 45678, processStartedAt: "2090-01-01T00:00:00.000Z" }, + leaseDigest: photonHash("lease"), closed: false } }); + f.loseCloseCommit(); await expect(f.reconcile()).rejects.toThrow(); + const replacement = f.create(new PhotonLocalResources()); + await expect(replacement.reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId })).rejects.toThrow("lease has not been fenced"); + f.replaceLease(); + for (const selected of [{ ...identity, companyId: "foreign" }, { ...identity, runtimeGeneration: 2 }, + { ...identity, credentialReferences: "b".repeat(64) }]) + await expect(replacement.reconcile({ identity: selected, config, lease: { token: "next-lease" }, localResourceId: f.resourceId })).rejects.toThrow("authority"); + await expect(replacement.reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId })).rejects.toThrow("authority"); + f.revoke(); await expect(replacement.reconcile({ identity, config, lease: { token: "next-lease" }, localResourceId: f.resourceId })).rejects.toThrow("authority"); + expect((await f.read())?.phase).toBe("joining"); + }); + it("unknown checkpoint provenance cannot be promoted during replacement recovery", async () => { + const f = fixture(); f.loseCloseCommit(); await expect(f.reconcile()).rejects.toThrow(); f.replaceLease(); + await f.state.update("checkpoint-authority", () => ({ ...identity, subject: undefined, sequence: 999 })); + await expect(f.create(new PhotonLocalResources()).reconcile({ identity, config, lease: { token: "next-lease" }, localResourceId: f.resourceId })).rejects.toThrow("provenance"); + expect((await f.read())?.phase).toBe("joining"); + }); + it("same original resource repair cannot erase newer sender debt or alter business prefix", async () => { + const f = fixture(); f.loseCloseCommit(); await expect(f.reconcile()).rejects.toThrow(); f.replaceLease(); + const recovered = await f.create(new PhotonLocalResources()).reconcile({ identity, config, lease: { token: "next-lease" }, localResourceId: f.resourceId }); + const sender = await f.store.retained(recovered, value => ({ ...value, failure: { code: "sender_close", attempts: 3, nextAttemptAt: "2099-01-01T00:00:30.000Z" } })); + const repaired = await f.create().repair(sender); + expect(repaired.closed).toBe(true); expect(repaired.state.localClosureConfirmed).toBe(true); + expect(repaired.state.failure).toEqual(sender.failure); expect(repaired.state.businessHandoff).toEqual(sender.businessHandoff); + expect(repaired.state.localResourceDebt).toBeUndefined(); expect(f.counts().joins).toBe(1); }); it("unknown initialized legacy checkpoint provenance remains attention", async () => { const f = fixture(); await writePhotonCheckpoint(f.state, "line", 17); @@ -160,3 +221,35 @@ describe("Photon actual resource join and useful-channel owner", () => { await owner.drain(); expect({ opens, closes, sends }).toEqual({ opens: 1, closes: 2, sends: 1 }); await owner.close(); }); }); + +describe("Photon recorded allocation lifetime utility (controlled process probes, not OS/socket proof)", () => { + const controller = { bootId: "old-boot", hostHash: "f".repeat(32), pid: 45678, processStartedAt: "2090-01-01T00:00:00.000Z" }; + const probe = (overrides: Partial = {}): ProcessProbe => ({ bootId: "new-boot", host: "current-host", processSpace: controller.hostHash, + pidExists: () => false, processGroupExists: () => false, readStartedAt: async () => null, ...overrides }); + it("persists exact allocation identity before any enrollment or normal resource join", async () => { + const f = fixture(); const descriptor = { id: f.resourceId, controller, leaseDigest: photonHash("lease"), closed: false }; + const prepared = await f.create().prepare({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId, localResource: descriptor }); + expect(await f.read()).toMatchObject({ phase: "enrolling", localResource: descriptor }); + expect(prepared.localClosureConfirmed).toBeUndefined(); expect(f.counts()).toEqual({ enrollments: 0, joins: 0 }); + }); + it("accepts only actual same-space dead or definitely reused PID lifetime evidence", async () => { + const f = fixture(); const prepared = await f.create().prepare({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId, + localResource: { id: f.resourceId, controller, leaseDigest: photonHash("lease"), closed: false } }); + expect(await photonResourceProcessEnded(prepared, probe())).toBe(true); + expect(await photonResourceProcessEnded(prepared, probe({ pidExists: () => true, readStartedAt: async () => new Date("2090-01-01T00:00:03.000Z") }))).toBe(true); + expect(await photonResourceProcessEnded(prepared, probe({ pidExists: () => true, readStartedAt: async () => new Date(controller.processStartedAt) }))).toBe(false); + expect(await photonResourceProcessEnded(prepared, probe({ pidExists: () => true, readStartedAt: async () => null }))).toBe(false); + expect(prepared.localResource?.closed).toBe(false); // Read-only proof, never a forged receipt mutation. + }); + it("foreign/stopped/fenced namespaces and opaque legacy UUIDs never become physical receipts", async () => { + const f = fixture(); const prepared = await f.create().prepare({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId, + localResource: { id: f.resourceId, controller, leaseDigest: photonHash("lease"), closed: false } }); + for (const verdict of ["stopped", "fenced"] as const) { + expect(await photonResourceProcessEnded(prepared, probe({ processSpace: "different-space", controllerInstance: async () => verdict, + pidExists: () => { throw new Error("foreign PID must never be probed"); } }))).toBe(false); + } + const legacy = { ...prepared }; delete legacy.localResource; + expect(await photonResourceProcessEnded(legacy, probe())).toBe(false); + expect(legacy.localResourceId).toBe(f.resourceId); expect(legacy.localClosureConfirmed).toBeUndefined(); + }); +}); diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index c8e3356d4e5..17a01313d97 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -585,7 +585,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const discordGatewayStopTasks = new Set>(); let shuttingDown = false; let receiverWork: ReturnType | undefined; - const { discordGatewayNotOwnedError, isDiscordGatewayNotOwnedError, releaseDiscordGatewayLeaseRow, stopDiscordGatewayOwnership, renewDiscordGatewayOwnershipForMessageAdmission, ensureDiscordGatewayRuntimeIsCurrent, acquireDiscordGatewayOwnership, discordGatewayRuntimeIsCurrent } = createChatReceiverOwnership(db, { runtime, runtimeVersions, runtimeCallbackEndpoint, redactError, leasedChatProvider, discordGatewayOwnerships, discordGatewayStopTasks, isShuttingDown: () => shuttingDown, isRuntimeInitializing: (endpointId, context) => { const pending = runtimeInitializations.get(endpointId); return pending?.context === context && pending.discordGatewayOwned; }, onStopped: id => receiverWork?.changed(id), get discordGatewayLeaseTtlMs() { return options.discordGatewayLeaseTtlMs; }, get discordGatewayLeaseRenewalIntervalMs() { return options.discordGatewayLeaseRenewalIntervalMs; }, get discordGatewayLeaseWaitMs() { return options.discordGatewayLeaseWaitMs; }, get renewDiscordGatewayLease() { return options.renewDiscordGatewayLease; } }); + const { withReceiverLease, discordGatewayNotOwnedError, isDiscordGatewayNotOwnedError, releaseDiscordGatewayLeaseRow, stopDiscordGatewayOwnership, renewDiscordGatewayOwnershipForMessageAdmission, ensureDiscordGatewayRuntimeIsCurrent, acquireDiscordGatewayOwnership, discordGatewayRuntimeIsCurrent } = createChatReceiverOwnership(db, { runtime, runtimeVersions, runtimeCallbackEndpoint, redactError, leasedChatProvider, discordGatewayOwnerships, discordGatewayStopTasks, isShuttingDown: () => shuttingDown, isRuntimeInitializing: (endpointId, context) => { const pending = runtimeInitializations.get(endpointId); return pending?.context === context && pending.discordGatewayOwned; }, onStopped: id => receiverWork?.changed(id), get discordGatewayLeaseTtlMs() { return options.discordGatewayLeaseTtlMs; }, get discordGatewayLeaseRenewalIntervalMs() { return options.discordGatewayLeaseRenewalIntervalMs; }, get discordGatewayLeaseWaitMs() { return options.discordGatewayLeaseWaitMs; }, get renewDiscordGatewayLease() { return options.renewDiscordGatewayLease; } }); const { receiveSdkMessages } = createChatSdkMessageReceiver({ endpointRecord, processMessage, ingressOnly: (provider) => provider === "imessage-photon" @@ -913,6 +913,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const photonConnector = photonConnectorConfig ? createPaperclipCloudConnector({ config: photonConnectorConfig }) : undefined; const photonExternalRuntimeOwner = createPhotonExternalRuntimeOwner(db, { broker: () => photonConnector, + withReceiverLease: (record, work) => withReceiverLease(record.endpoint, runtimeContextForRecord(record), ownership => work({ token: ownership.token })), endpointRecord, runtimeFor, context: instance => runtimeContexts.get(instance), ownership: id => discordGatewayOwnerships.get(id), currentRuntime: id => runtime.get(id), release: ownership => stopDiscordGatewayOwnership(ownership, { removeRuntime: false, notifyStopped: false }), @@ -1089,16 +1090,15 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { recordChatWebhookStage("runtime_initializing", record.endpoint.id); const credentials = await resolveCredentials(record.endpoint); await prepareDiscordRuntimeCommand(db, record.endpoint, context); + const providerConfig = runtimeConfig(record.endpoint, record.endpoint.botUsername ?? record.assignedAgentName, credentials); + const photonAllocation = providerConfig.provider === "imessage-photon" && discordOwnership + ? await photonExternalRuntimeOwner.reserveLocalRuntime(record, context, discordOwnership, providerConfig) : null; instance = record.endpoint.provider === "speko" ? await replaceSpekoChannelRuntime(runtime, record, persistence) : await runtime.replaceEndpoint({ companyId: record.endpoint.companyId, endpointId: record.endpoint.id, - providerConfig: runtimeConfig( - record.endpoint, - record.endpoint.botUsername ?? record.assignedAgentName, - credentials, - ), + providerConfig, persistence, concurrency: record.endpoint.concurrencyPolicy, enableDiscordGateway: discordOwnership !== null, @@ -1166,6 +1166,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { : undefined, }, }); + if (photonAllocation) photonExternalRuntimeOwner.attachLocalRuntime(photonAllocation, instance); context.endpointRuntime = instance; runtimeContexts.set(instance as object, context); if (discordOwnership && !(await ensureDiscordGatewayRuntimeIsCurrent(endpoint.id, context, { renewLease: true }))) { diff --git a/server/src/services/chat-channels/imessage-photon/external-contract.ts b/server/src/services/chat-channels/imessage-photon/external-contract.ts index a9f8e9989d8..f3a26e01cf7 100644 --- a/server/src/services/chat-channels/imessage-photon/external-contract.ts +++ b/server/src/services/chat-channels/imessage-photon/external-contract.ts @@ -30,6 +30,10 @@ export function assertPhotonExternalBinding(identity: PhotonExternalIdentity, bi export const photonExternalStateSchema = z.object({ version: z.literal(1), identity: photonExternalIdentitySchema, handoffId: z.string().uuid(), localResourceId: z.string().uuid().nullable(), + localResource: z.object({ id: z.string().uuid(), controller: z.unknown(), leaseDigest: z.string().regex(/^[a-f0-9]{64}$/), closed: z.boolean() }).strict().optional(), + localResourceDebt: z.object({ attempts: sequence.positive(), nextAttemptAt: z.string().datetime().nullable() }).strict().optional(), + localClosureConfirmed: z.literal(true).optional(), + businessHandoff: z.object({ sequence: sequence.nullable(), leaseDigest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().optional(), phase: z.enum(["enrolling", "joining", "external", "retiring", "retired"]), // The complete non-secret enrollment input survives an ambiguous broker reply. binding: photonExternalBindingSchema, @@ -44,7 +48,14 @@ export function readPhotonExternalState(value: unknown): PhotonExternalState | n if (value === null) return null; const state = photonExternalStateSchema.parse(value); assertPhotonExternalBinding(state.identity, state.binding); - if (state.phase === "external" && state.joinedSequence === null && state.initialSequence !== null + if (state.localResource?.closed === true && state.localClosureConfirmed !== true + || state.localClosureConfirmed === true && state.localResource && state.localResource.closed !== true) + throw new Error("Photon physical close receipt and original descriptor disagree"); + if (state.localResource && state.localResource.id !== state.localResourceId) throw new Error("Photon resource descriptor identity changed"); + if (state.businessHandoff && (state.initialSequence !== null && (state.businessHandoff.sequence === null || state.businessHandoff.sequence < state.initialSequence) + || state.acceptedSequence !== null && state.businessHandoff.sequence !== null && state.acceptedSequence < state.businessHandoff.sequence)) + throw new Error("Photon current business admission prefix regressed"); + if (state.phase === "external" && !state.businessHandoff && state.joinedSequence === null && state.initialSequence !== null || state.pending && state.pending.sequence <= (state.acceptedSequence ?? -1)) throw new Error("Photon external custody invariant changed"); return state; } diff --git a/server/src/services/chat-channels/imessage-photon/external-owner.ts b/server/src/services/chat-channels/imessage-photon/external-owner.ts index cf3bacf0fd7..1136ee0bdf7 100644 --- a/server/src/services/chat-channels/imessage-photon/external-owner.ts +++ b/server/src/services/chat-channels/imessage-photon/external-owner.ts @@ -1,3 +1,5 @@ +import { readControllerProcess } from "../../controller-process-identity.js"; +import { photonResourceProcessEnded } from "./resource-process.js"; import { isDeepStrictEqual } from "node:util"; import { randomUUID } from "node:crypto"; import { z } from "zod"; @@ -10,6 +12,7 @@ import { PHOTON_EXTERNAL_STATE, type PhotonExternalStore, type PhotonExternalLea import { assertPhotonExternalBinding, photonExternalBindingSchema, photonHash, readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalBinding, type PhotonExternalIdentity, type PhotonExternalState } from "./external-contract.js"; +class PhotonPhysicalResourceUnknown extends Error {} const CHECKPOINT_AUTHORITY = "checkpoint-authority"; const checkpointIdentity = ({ subject: _subject, ...identity }: PhotonExternalIdentity) => identity; type Checkpoint = { schema: 1; lineId: string; sequence: number }; @@ -49,6 +52,10 @@ export class PhotonLocalResources { const existing = this.objects.get(object); if (existing) return existing; const id = randomUUID(); this.objects.set(object, id); this.resources.set(id, { close, closed: false }); return id; } + attach(id: string, object: object, close: () => Promise): void { + if (this.resources.has(id) || this.objects.has(object)) throw new Error("Photon allocation identity is already attached"); + this.objects.set(object, id); this.resources.set(id, { close, closed: false }); + } async join(id: string): Promise { const resource = this.resources.get(id); if (!resource) throw new Error("Photon original local resource closure is unknown"); @@ -59,45 +66,70 @@ export class PhotonLocalResources { known(id: string): boolean { return this.resources.has(id); } owns(id: string, object: object): boolean { return this.objects.get(object) === id && this.resources.has(id); } } +export type PhotonExternalHandoffInput = { identity: PhotonExternalIdentity; lease: PhotonExternalLease; config: ResolvedPhotonChatConfig; + localResourceId: string | null; localResource?: NonNullable }; export function createPhotonExternalOwner(options: { store: PhotonExternalStore; broker: PhotonExternalBroker; resources: PhotonLocalResources; notify(identity: PhotonExternalIdentity): void; now?: () => Date }) { const now = options.now ?? (() => new Date()); - async function failure(expected: PhotonExternalState, code: NonNullable["code"]) { + async function failure(expected: PhotonExternalState, code: NonNullable["code"], retryable = true) { const attempts = (expected.failure?.attempts ?? 0) + 1; // Existing receiver coordinator consumes this deadline/notification; no timer. - const nextAttemptAt = new Date(now().getTime() + Math.min(300_000, 30_000 * 2 ** Math.min(attempts - 1, 4))).toISOString(); + const nextAttemptAt = retryable ? new Date(now().getTime() + Math.min(300_000, 30_000 * 2 ** Math.min(attempts - 1, 4))).toISOString() : null; await options.store.retained(expected, value => ({ ...value, failure: { code, attempts, nextAttemptAt } })); options.notify(expected.identity); } - async function fail(expected: PhotonExternalState, code: NonNullable["code"], primary: unknown): Promise { - try { await failure(expected, code); } + async function fail(expected: PhotonExternalState, code: NonNullable["code"], primary: unknown, retryable = true): Promise { + try { await failure(expected, code, retryable); } catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon operation and responsibility persistence failed"); } throw primary; } - async function reconcile(input: { identity: PhotonExternalIdentity; lease: PhotonExternalLease; config: ResolvedPhotonChatConfig; - localResourceId: string | null }): Promise { - const { identity, lease, config } = input; + function bindingFor(identity: PhotonExternalIdentity, config: ResolvedPhotonChatConfig): PhotonExternalBinding { const instance = options.broker.instanceIdentity(); const fingerprint = photonHash([instance.instanceId, instance.environment, identity.companyId, identity.endpointId, identity.connectionId, identity.runtimeGeneration, config.credentials.projectId, config.credentials.lineId, config.credentials.phoneNumber, (config.credentials.allocation ?? "dedicated"), photonHash(config.credentials.projectSecret)]); - const binding = photonExternalBindingSchema.parse({ version: 1, ...instance, companyId: identity.companyId, endpointId: identity.endpointId, + return photonExternalBindingSchema.parse({ version: 1, ...instance, companyId: identity.companyId, endpointId: identity.endpointId, connectionId: identity.connectionId, runtimeGeneration: identity.runtimeGeneration, projectId: config.credentials.projectId, lineId: config.credentials.lineId, phoneNumber: config.credentials.phoneNumber, allocation: config.credentials.allocation ?? "dedicated", credentialFingerprint: fingerprint, bindingId: `photon-receiver:${photonHash([instance.instanceId, identity.companyId, identity.endpointId, identity.connectionId, identity.runtimeGeneration, fingerprint])}`, intakeAfter: new Date(config.intakeAfter).toISOString(), maxFrameBytes: MAX_ATTACHMENT_BYTES + 1024 * 1024 }); - let retained = await options.store.current(identity, lease, async (state, current) => { + } + async function prepare(input: PhotonExternalHandoffInput): Promise { + const { identity, lease } = input, binding = bindingFor(identity, input.config); + if (input.localResource && (input.localResource.id !== input.localResourceId || input.localResource.closed + || input.localResource.leaseDigest !== photonHash(lease.token) || !readControllerProcess(input.localResource.controller))) throw new Error("Photon new allocation descriptor is invalid"); + return options.store.current(identity, lease, async (state, current) => { if (current && current.phase !== "retired") { if (!isDeepStrictEqual(current.binding, binding)) throw new Error("Photon original enrollment must finish retirement"); + if (input.localResource && current.localResourceId !== input.localResource.id) + throw new Error("Photon retained resource must recover before another receiver allocation"); return current; } const initialSequence = await handoffCheckpoint(state, identity, binding.lineId); return state.update(PHOTON_EXTERNAL_STATE, raw => { if (!isDeepStrictEqual(readPhotonExternalState(raw), current)) throw new Error("Photon external intent was installed concurrently"); return { version: 1, identity, binding, handoffId: randomUUID(), localResourceId: input.localResourceId, + ...(input.localResource ? { localResource: input.localResource } : {}), phase: "enrolling", acceptedRetirement: current ? { binding: current.binding, handoffId: current.handoffId } : null, initialSequence, joinedSequence: null, acceptedSequence: null, pending: null, failure: null }; }); }); + } + async function repair(expected: PhotonExternalState): Promise<{ state: PhotonExternalState; closed: boolean }> { + if (expected.localResourceId === null || expected.localClosureConfirmed === true) return { state: expected, closed: true }; + let closed = false; + if (options.resources.known(expected.localResourceId)) { await options.resources.join(expected.localResourceId); closed = true; } + else closed = await photonResourceProcessEnded(expected); + if (!closed) return { state: expected, closed: false }; + const state = await options.store.retained(expected, value => { + const next: PhotonExternalState = { ...value, localClosureConfirmed: true, + ...(value.localResource ? { localResource: { ...value.localResource, closed: true } } : {}) }; + delete next.localResourceDebt; return next; + }); + return { state, closed: true }; + } + async function reconcile(input: PhotonExternalHandoffInput): Promise { + const { identity, lease, config } = input, binding = bindingFor(identity, config); + let retained = await prepare(input); if (retained.phase === "external") return retained; if (!["enrolling", "joining"].includes(retained.phase)) throw new Error("Photon receiver requires retirement reconciliation"); if (retained.phase === "enrolling") { @@ -116,13 +148,24 @@ export function createPhotonExternalOwner(options: { store: PhotonExternalStore; } catch (error) { return fail(retained, "enrollment", error); } } try { - if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId); + const physical = await repair(retained); retained = physical.state; + if (!physical.closed && retained.localResource?.leaseDigest === photonHash(lease.token)) + throw new Error("Photon original receiver lease has not been fenced"); const expected = retained; retained = await options.store.current(identity, lease, async (state, current) => { if (!current || !isDeepStrictEqual(current, expected)) throw new Error("Photon handoff changed while joining"); - const joinedSequence = await handoffCheckpoint(state, identity, binding.lineId); - if (expected.initialSequence !== null && (joinedSequence === null || joinedSequence < expected.initialSequence)) throw new Error("Photon joined checkpoint regressed"); - return state.update(PHOTON_EXTERNAL_STATE, () => ({ ...expected, phase: "external", joinedSequence, acceptedSequence: joinedSequence, failure: null })); + const prefix = await handoffCheckpoint(state, identity, binding.lineId); + if (expected.initialSequence !== null && (prefix === null || prefix < expected.initialSequence)) throw new Error("Photon current checkpoint regressed"); + // The current SQL lease fences old admission/checkpoint writes. This + // commits a tagged BUSINESS prefix, never an unknown physical receipt. + return state.update(PHOTON_EXTERNAL_STATE, () => { + const next: PhotonExternalState = { ...expected, phase: "external", + joinedSequence: physical.closed ? prefix : expected.joinedSequence, acceptedSequence: prefix, + businessHandoff: { sequence: prefix, leaseDigest: photonHash(lease.token) }, failure: null }; + if (physical.closed) delete next.localResourceDebt; + else next.localResourceDebt = { attempts: (expected.localResourceDebt?.attempts ?? 0) + 1, nextAttemptAt: null }; + return next; + }); }); options.notify(identity); return retained; @@ -135,13 +178,15 @@ export function createPhotonExternalOwner(options: { store: PhotonExternalStore; const decoded = parsePhotonExternalDelivery(input.delivery, retained); const pending = await options.store.current(input.identity, input.lease, async (state, current) => { if (!current || current.phase !== "external" || !isDeepStrictEqual(current.binding, retained.binding)) throw new Error("Photon delivery owner changed"); - // The joined checkpoint already admitted the complete local prefix. - if (decoded.packet.sequence <= (current.joinedSequence ?? -1)) return false; + const floor = current.businessHandoff ? current.businessHandoff.sequence : current.joinedSequence; + // A current tagged prefix can exclude duplicates without claiming that + // an unknown old process/socket has closed. + if (decoded.packet.sequence <= (floor ?? -1)) return false; if (decoded.packet.sequence <= (current.acceptedSequence ?? -1)) return false; if (current.pending && !isDeepStrictEqual(current.pending, decoded.receipt)) throw new Error("Photon earlier delivery admission remains outstanding"); const previous = decoded.packet.previousSequence; if (previous !== (current.acceptedSequence ?? null) - && !(current.acceptedSequence === current.joinedSequence && (previous ?? -1) <= (current.joinedSequence ?? -1))) + && !(current.acceptedSequence === floor && (previous ?? -1) <= (floor ?? -1))) throw new Error("Photon durable predecessor has not been admitted"); await state.update(PHOTON_EXTERNAL_STATE, () => ({ ...current, pending: decoded.receipt })); return true; @@ -162,7 +207,8 @@ export function createPhotonExternalOwner(options: { store: PhotonExternalStore; if (retained.phase === "retired") return; if (retained.phase !== "retiring") retained = await options.store.retained(retained, value => ({ ...value, phase: "retiring" })); try { - if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId); + const physical = await repair(retained); retained = physical.state; + if (!physical.closed) throw new PhotonPhysicalResourceUnknown("Photon original local resource closure is unknown; physical retirement remains held"); const request = { subject: retained.identity.subject, companyId: retained.identity.companyId }; await options.broker.photonReceiverOperation({ ...request, operation: { kind: "retire", binding: retained.binding } }); const response = z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid(), @@ -171,7 +217,7 @@ export function createPhotonExternalOwner(options: { store: PhotonExternalStore; if (response.phase !== "retired") throw new Error("Photon original physical close or queue drain remains outstanding"); await options.store.retained(retained, value => ({ ...value, phase: "retired", failure: null })); options.notify(retained.identity); - } catch (error) { return fail(retained, "retirement", error); } + } catch (error) { return fail(retained, "retirement", error, !(error instanceof PhotonPhysicalResourceUnknown)); } } - return { reconcile, dispatch, retire }; + return { prepare, repair, reconcile, dispatch, retire }; } diff --git a/server/src/services/chat-channels/imessage-photon/external-runtime.ts b/server/src/services/chat-channels/imessage-photon/external-runtime.ts index 33160c67ae3..fe8d1a16a30 100644 --- a/server/src/services/chat-channels/imessage-photon/external-runtime.ts +++ b/server/src/services/chat-channels/imessage-photon/external-runtime.ts @@ -13,8 +13,9 @@ import type { EndpointRecord, RuntimeContext, DiscordGatewayOwnership, InternalS import { credentialFingerprint } from "../credential-fingerprint.js"; import { createPhotonExternalStore, PHOTON_EXTERNAL_STATE } from "./external-store.js"; import { createPhotonExternalOwner, PhotonLocalResources, type PhotonExternalBroker } from "./external-owner.js"; -import { readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalIdentity } from "./external-contract.js"; -import { createHash } from "node:crypto"; +import { readPhotonExternalState, parsePhotonExternalDelivery, photonHash, type PhotonExternalIdentity } from "./external-contract.js"; +import { currentControllerProcess, UNKNOWN_PROCESS_SPACE } from "../../controller-process-identity.js"; +import { randomUUID, createHash } from "node:crypto"; export type PhotonCloudDelivery = { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: Record }; type Ingress = (event: PhotonCloudDelivery) => Promise; @@ -61,6 +62,7 @@ export async function readPhotonRetainedConsumer(db: Db, identity: { instanceId: } export function createPhotonExternalRuntimeOwner(db: Db, options: { broker(): PhotonExternalBroker | undefined; + withReceiverLease(record: EndpointRecord, work: (lease: { token: string }) => Promise): Promise; endpointRecord(id: string): Promise; runtimeFor(endpoint: EndpointRecord["endpoint"], input: { requireDiscordOwnership?: boolean }): Promise; context(runtime: ChatEndpointRuntime): RuntimeContext | undefined; @@ -89,6 +91,29 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { if (record.endpoint.provider !== "imessage-photon") return null; return selected(record); } + async function reserveLocalRuntime(record: EndpointRecord, context: RuntimeContext, lease: { token: string }, config: ResolvedPhotonChatConfig): Promise { + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject, broker = options.broker(); + if (!subject || !broker || record.endpoint.provider !== "imessage-photon") return null; + const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: record.endpoint.id, + connectionId: record.endpoint.connectionId, runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject }; + const prior = await store.read(identity); + if (prior && prior.phase !== "retired") { + if (prior.phase === "external") return null; // Normal lazy useful sender; no receiver allocation. + options.notify(record.endpoint.id); + throw conflict("Photon original handoff must recover before a replacement receiver allocation"); + } + const controller = await currentControllerProcess(); + if (controller.hostHash === UNKNOWN_PROCESS_SPACE || !controller.processStartedAt) + throw conflict("Photon local allocation requires its actual process birth and namespace"); + const id = randomUUID(); + // Durable descriptor precedes construction/initialize, not an after-crash backfill. + await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).prepare({ + identity, lease, config, localResourceId: id, localResource: { id, controller, leaseDigest: photonHash(lease.token), closed: false } }); + return id; + } + function attachLocalRuntime(id: string, runtime: ChatEndpointRuntime): void { + resources.attach(id, runtime, () => runtime.shutdown()); + } async function reconcile(id: string): Promise { const pending = active.get(id); if (pending) return pending; const run = (async () => { @@ -104,8 +129,23 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(previous); return; } - const external = await placement(record); + const optionsConfig = await options.config(record); + const originalRuntime = options.currentRuntime(id); + const originalResourceCurrent = previous?.localResourceId && originalRuntime + ? resources.owns(previous.localResourceId, originalRuntime) : false; + if (previous && ["enrolling", "joining"].includes(previous.phase) && !originalResourceCurrent) { + // Recover BUSINESS authority without constructing/capturing an ignored + // replacement receiver. The normal finite renewable lease fences old writes. + const originalResourceId = previous.localResourceId; + await options.withReceiverLease(record, lease => createPhotonExternalOwner({ store, broker, resources, + notify: value => options.notify(value.endpointId) }).reconcile({ identity, lease, config: optionsConfig, localResourceId: originalResourceId })); + return; + } + let external = await placement(record); if (external) { + if (external.localResourceId !== null && !external.localClosureConfirmed) { + external = (await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).repair(external)).state; + } const adapter = options.currentRuntime(id)?.getProviderAdapter(); if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient(); else if (external.failure?.code === "sender_close" && !await options.removeRuntime(id)) throw new Error("Photon original sender physical closure is unknown"); @@ -198,7 +238,9 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { } if (state.phase === "retired" || scope?.kind === "connection" && state.identity.connectionId !== scope.id) continue; values.push({ id: row.endpointId, companyId: row.companyId, connectionId: state.identity.connectionId, - dueAt: state.phase === "external" && !state.failure ? null : state.failure?.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : 0 }); + dueAt: state.failure ? (state.failure.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : null) + : state.localResourceDebt ? (state.localResourceDebt.nextAttemptAt ? Date.parse(state.localResourceDebt.nextAttemptAt) : null) + : state.phase === "external" ? null : 0 }); } return values; } @@ -209,8 +251,10 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { const state = await store.read({ companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId, runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject }); if (!state?.localResourceId || !resources.owns(state.localResourceId, context.endpointRuntime) - || !["joining", "retiring"].includes(state.phase)) return { kind: "obsolete" }; - await store.retained(state, value => ({ ...value, failure: { code: "local_join", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } })); + || !["joining", "external", "retiring"].includes(state.phase) || state.localClosureConfirmed) return { kind: "obsolete" }; + await store.retained(state, value => value.phase === "external" + ? { ...value, localResourceDebt: { attempts: (value.localResourceDebt?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } } + : { ...value, failure: { code: "local_join", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } }); options.notify(id); return { kind: "recorded" }; } @@ -228,12 +272,16 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { if (!state || state.handoffId !== actionId || state.binding.instanceId !== connector.instanceId || state.binding.environment !== connector.environment) throw conflict("Photon retained retry identity changed"); if (state.phase === "retired") return { actionId, state: "complete" as const }; - if (state.localResourceId !== null && !resources.known(state.localResourceId) && ["joining", "retiring"].includes(state.phase)) - throw conflict("Photon original stream closure is unknown; restore its owning process or establish real resource closure before retry"); + // Retry is real current-authorized business recovery/physical repair. An + // unknown old UUID remains debt; it is never certified closed by this action. + if (state.phase === "external" || state.phase === "retiring") + await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).repair(state); if (state.phase === "external") await broker.photonReceiverOperation({ subject: management.responsibleUserId, companyId: state.identity.companyId, operation: { kind: "retry", binding: state.binding } }); await management.reauthorize(); - await store.retained(state, value => ({ ...value, failure: value.failure ? { ...value.failure, nextAttemptAt: new Date().toISOString() } : null }), async tx => { + const current = await store.read(state.identity); + if (!current || current.handoffId !== state.handoffId || !isDeepStrictEqual(current.binding, state.binding)) throw conflict("Photon retry owner changed"); + await store.retained(current, value => ({ ...value, failure: value.failure ? { ...value.failure, nextAttemptAt: new Date().toISOString() } : null }), async tx => { await management.reauthorize(); await logActivity(tx, { ...management.audit, companyId: state.identity.companyId, action: "chat.photon_external_owner.retry", entityType: "chat_endpoint", entityId: endpointId, details: { handoffId: actionId, phase: state.phase } }); @@ -243,7 +291,7 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { return { actionId, state: "scheduled" as const }; } ingress.set(db, receive); - return { reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } }; + return { reserveLocalRuntime, attachLocalRuntime, reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } }; } /** Called by normal configuration SQL with its actual authorized actor. Existing diff --git a/server/src/services/chat-channels/imessage-photon/external-store.ts b/server/src/services/chat-channels/imessage-photon/external-store.ts index 325e59d0b51..afebfb20232 100644 --- a/server/src/services/chat-channels/imessage-photon/external-store.ts +++ b/server/src/services/chat-channels/imessage-photon/external-store.ts @@ -79,6 +79,12 @@ export function createPhotonExternalStore(db: Db) { || next.handoffId !== current.handoffId || next.localResourceId !== current.localResourceId || next.initialSequence !== current.initialSequence || next.phase === "external" && current.phase !== "external") throw new Error("Photon retained update cannot change authority"); + if (!isDeepStrictEqual(next.businessHandoff, current.businessHandoff) + || current.localClosureConfirmed === true && next.localClosureConfirmed !== true + || !isDeepStrictEqual(next.localResource ? { ...next.localResource, closed: false } : undefined, + current.localResource ? { ...current.localResource, closed: false } : undefined) + || current.localResource?.closed === true && next.localResource?.closed !== true) + throw new Error("Photon retained cleanup cannot rewrite business or allocation identity"); const parsed = readPhotonExternalState(next); if (!parsed) throw new Error("Photon retained result disappeared"); return parsed; diff --git a/server/src/services/chat-channels/imessage-photon/resource-process.ts b/server/src/services/chat-channels/imessage-photon/resource-process.ts new file mode 100644 index 00000000000..453f2a5c485 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/resource-process.ts @@ -0,0 +1,18 @@ +import { currentProcessSpaceHash, readControllerProcess, UNKNOWN_PROCESS_SPACE } from "../../controller-process-identity.js"; +import { proveOwnerGone, type ProcessProbe } from "../../owner-proof.js"; +import type { PhotonExternalState } from "./external-contract.js"; + +/** Only a descriptor saved before this allocation can prove its process lifetime. + * Controller fencing, platform replacement and TTL never certify socket closure. */ +export async function photonResourceProcessEnded(state: PhotonExternalState, probe?: ProcessProbe): Promise { + const resource = state.localResource; + if (!resource || resource.id !== state.localResourceId) return false; + const process = readControllerProcess(resource.controller); + const space = probe?.processSpace ?? currentProcessSpaceHash(); + if (!process || process.hostHash === UNKNOWN_PROCESS_SPACE || space === UNKNOWN_PROCESS_SPACE || process.hostHash !== space) return false; + const proof = await proveOwnerGone({ kind: "local", scope: `photon_receiver:${state.identity.endpointId}`, + generation: state.identity.runtimeGeneration, fenceToken: resource.id, host: null, processSpace: process.hostHash, + bootId: process.bootId, pid: process.pid, processStartedAt: process.processStartedAt, processGroupId: null, + requireRecordedProcessSpace: true }, probe); + return proof.verdict === "gone" && (proof.reason === "pid_dead" || proof.reason === "pid_reused"); +} diff --git a/server/src/services/chat-channels/runtime/ownership.ts b/server/src/services/chat-channels/runtime/ownership.ts index 1956a55beda..157c6a9aab0 100644 --- a/server/src/services/chat-channels/runtime/ownership.ts +++ b/server/src/services/chat-channels/runtime/ownership.ts @@ -30,6 +30,7 @@ const DISCORD_GATEWAY_LEASE_WAIT_MS = 20_000; const DISCORD_GATEWAY_LEASE_POLL_MS = 100; export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { const { runtime, runtimeVersions, runtimeCallbackEndpoint, redactError, leasedChatProvider, discordGatewayOwnerships, discordGatewayStopTasks } = options; + const finiteLeaseOwners = new Map>(); function discordGatewayNotOwnedError() { return conflict( "Another Paperclip server owns this Discord Gateway connection; retry shortly", @@ -83,7 +84,16 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { clearInterval(ownership.renewTimer); ownership.renewTimer = null; } + const finiteBody = finiteLeaseOwners.get(ownership); ownership.stopPromise = (async () => { + if (finiteBody) { + // Renewal loss can enter stop while this finite operation is still + // retaining a real provider result. Fence now, release only after its + // body and the already-started renewal have both settled. + await finiteBody; + const renewal = ownership.renewal; + if (renewal) await renewal; + } if ( stopOptions.removeRuntime !== false && ownership.context.endpointRuntime && @@ -108,13 +118,15 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { } if (!options.isShuttingDown() && stopOptions.notifyStopped !== false) options.onStopped?.(ownership.endpointId); })(); - discordGatewayStopTasks.add(ownership.stopPromise); - void ownership.stopPromise.finally(() => { - if (ownership.stopPromise) { - discordGatewayStopTasks.delete(ownership.stopPromise); - } + const attempt = ownership.stopPromise; + discordGatewayStopTasks.add(attempt); + void attempt.then(() => { discordGatewayStopTasks.delete(attempt); }, () => { + discordGatewayStopTasks.delete(attempt); + // Preserve this finite owner for an ordinary same-owner cleanup retry; + // never retain a rejected promise as a fake completed stop receipt. + if (finiteBody && ownership.stopPromise === attempt) ownership.stopPromise = null; }); - return ownership.stopPromise; + return attempt; } function canRenewLocalOwnership(ownership: DiscordGatewayOwnership): boolean { @@ -126,6 +138,7 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { ) { return false; } + if (finiteLeaseOwners.has(ownership)) return true; return ownership.context.endpointRuntime === undefined ? options.isRuntimeInitializing(ownership.endpointId, ownership.context) : runtime.get(ownership.endpointId) === ownership.context.endpointRuntime; @@ -321,6 +334,7 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { ): Promise { const receiverLeaseKey = leaseKeyForProvider(endpoint.provider)!; const local = discordGatewayOwnerships.get(endpoint.id); + if (local && finiteLeaseOwners.has(local)) return null; if ( local && !local.stopping && @@ -393,6 +407,38 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { } } + /** Normal renewable receiver lease for a finite, allocation-free operation. + * Never stops/replaces an existing local runtime merely to acquire authority. */ + async function withReceiverLease(endpoint: EndpointRow, context: RuntimeContext, + work: (ownership: DiscordGatewayOwnership) => Promise): Promise { + const previous = discordGatewayOwnerships.get(endpoint.id); + if (previous?.stopping && finiteLeaseOwners.has(previous)) { + // A failed cleanup still owns this exact token; finish that same stop + // before another normal operation can acquire new business authority. + await stopDiscordGatewayOwnership(previous, { removeRuntime: false, notifyStopped: false }); + finiteLeaseOwners.delete(previous); previous.context.discordGatewayOwned = false; + } + if (discordGatewayOwnerships.has(endpoint.id) || runtime.get(endpoint.id)) throw discordGatewayNotOwnedError(); + const owned = await acquireDiscordGatewayOwnership(endpoint, context, false); + if (!owned) throw discordGatewayNotOwnedError(); + let settled!: () => void; + finiteLeaseOwners.set(owned, new Promise(resolve => { settled = resolve; })); + context.discordGatewayOwned = true; + let result!: T; + let primary: { error: unknown } | undefined; + try { result = await work(owned); } + catch (error) { primary = { error }; } + finally { settled(); } + try { await stopDiscordGatewayOwnership(owned, { removeRuntime: false, notifyStopped: false }); } + catch (cleanup) { + if (primary) throw new AggregateError([primary.error, cleanup], "Receiver operation and exact lease cleanup failed"); + throw cleanup; + } + finiteLeaseOwners.delete(owned); context.discordGatewayOwned = false; + if (primary) throw primary.error; + return result; + } + function discordGatewayRuntimeIsCurrent( endpointId: string, context: RuntimeContext, @@ -408,5 +454,5 @@ export function createChatReceiverOwnership(db: Db, options: OwnershipOptions) { runtime.get(endpointId) === context.endpointRuntime ); } - return { discordGatewayNotOwnedError, isDiscordGatewayNotOwnedError, releaseDiscordGatewayLeaseRow, stopDiscordGatewayOwnership, renewDiscordGatewayOwnershipForMessageAdmission, ensureDiscordGatewayRuntimeIsCurrent, acquireDiscordGatewayOwnership, discordGatewayRuntimeIsCurrent }; + return { withReceiverLease, discordGatewayNotOwnedError, isDiscordGatewayNotOwnedError, releaseDiscordGatewayLeaseRow, stopDiscordGatewayOwnership, renewDiscordGatewayOwnershipForMessageAdmission, ensureDiscordGatewayRuntimeIsCurrent, acquireDiscordGatewayOwnership, discordGatewayRuntimeIsCurrent }; }