diff --git a/apps/server/src/provider/Layers/HermesAdapter.test.ts b/apps/server/src/provider/Layers/HermesAdapter.test.ts index 2230ac71f6..8110e5b63a 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.test.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.test.ts @@ -35,9 +35,19 @@ import { * The reconnect trigger is a broker status transition, so these tests drive the * broker's two streams directly and never touch a real socket or a clock. */ +let generationCounter = 0; +const nextGeneration = () => { + generationCounter += 1; + return generationCounter; +}; const statusFor = ( instanceId: ProviderInstanceId, status: HermesGatewayInstanceStatus["status"], + // Defaults to a fresh generation per connected status so a test that just + // wants "it reconnected" gets one; pass an explicit value to model a + // republish of the SAME connection (session counts, pings), which must not + // re-trigger the resume. + connectionGeneration: number | null = status === "connected" ? nextGeneration() : null, ): HermesGatewayInstanceStatus => ({ instanceId, nickname: "Hermes", @@ -50,6 +60,7 @@ const statusFor = ( activeSessionCount: 0, protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, capabilities: null, + connectionGeneration, }); const collectEvents = (adapter: { readonly streamEvents: Stream.Stream }) => @@ -509,8 +520,36 @@ const makeReconnectHarness = (options: { yield* PubSub.publish(brokerStatuses, statusFor(options.instanceId, "connected")); yield* drain; }); + // A plugin restart as it actually happens: the broker accepts the new + // socket and retires the old one in the same step, so the instance never + // observably goes offline and only one `connected` status is published. + const replaceConnection = Effect.gen(function* () { + state.connected = true; + yield* PubSub.publish(brokerStatuses, statusFor(options.instanceId, "connected")); + yield* drain; + }); + // The same live connection republishing (session counts, pings). Must NOT + // look like a new connection. + const republishSameConnection = (generation: number) => + Effect.gen(function* () { + state.connected = true; + yield* PubSub.publish( + brokerStatuses, + statusFor(options.instanceId, "connected", generation), + ); + yield* drain; + }); - return { adapter, sent, brokerEvents, state, disconnect, reconnect } as const; + return { + adapter, + sent, + brokerEvents, + state, + disconnect, + reconnect, + replaceConnection, + republishSameConnection, + } as const; }); it.effect("re-issues session.ensure on reconnect and keeps streaming a turn that survived", () => @@ -572,6 +611,82 @@ it.effect("re-issues session.ensure on reconnect and keeps streaming a turn that }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Regression: a plugin restart REPLACES the socket rather than leaving a gap. +// The broker accepts the new connection and retires the old one together, so +// the instance never observably goes offline and exactly one `connected` +// status is published. An edge detector watching connectedness therefore never +// fires, T3 keeps a session the new plugin process has never heard of, and its +// next turn.start comes back "Call session.ensure before starting a turn" — +// the thread is dead with no way to recover from the UI. +it.effect("re-issues session.ensure when the connection is replaced without going offline", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_replaced"); + const threadId = ThreadId.make("thread-replaced"); + const initialSessionId = HermesGatewaySessionId.make("session-before-restart"); + const harness = yield* makeReconnectHarness({ instanceId, threadId, initialSessionId }); + + // Production ordering: the plugin is already connected and the adapter has + // observed that connection before any thread exists. + yield* harness.republishSameConnection(7); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + + // No disconnect: the plugin restarted, so the broker retired the old socket + // and accepted the new one together. The instance never reports offline. + yield* harness.replaceConnection; + + const ensures = harness.sent.filter((message) => message.type === "session.ensure"); + assert.equal( + ensures.length, + 2, + "a replaced connection must re-ensure, or the next turn is rejected", + ); + const resume = ensures[1]; + assert.equal( + resume?.type === "session.ensure" ? resume.resumeSessionId : undefined, + initialSessionId, + ); + + // A later turn now targets a session the new plugin knows about. + yield* harness.adapter.sendTurn({ threadId, input: "after the restart" }); + const starts = harness.sent.filter((message) => message.type === "turn.start"); + assert.equal(starts.length, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("does not re-ensure when the same connection republishes its status", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_same_connection"); + const threadId = ThreadId.make("thread-same-connection"); + const harness = yield* makeReconnectHarness({ + instanceId, + threadId, + initialSessionId: HermesGatewaySessionId.make("session-stable"), + }); + + // Production ordering: the plugin connects first, so its generation is + // already known by the time a thread creates a session. + yield* harness.republishSameConnection(4242); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + + // Session-count reports and ping results republish the SAME connection. + // Re-ensuring on each would cancel pending approvals under a running turn. + yield* harness.republishSameConnection(4242); + yield* harness.republishSameConnection(4242); + + assert.equal(harness.sent.filter((message) => message.type === "session.ensure").length, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("settles the thread when a turn does not survive the reconnect", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("hermes_dead_turn"); diff --git a/apps/server/src/provider/Layers/HermesAdapter.ts b/apps/server/src/provider/Layers/HermesAdapter.ts index 85281eece4..281da70f4b 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.ts @@ -573,14 +573,28 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input * `turn.completed` arrived for a turn orchestration had written off, was * rejected by its conflict gate, and the thread never settled. */ - let connected = yield* broker.isConnected(input.instanceId); + // Track the connection identity, not merely whether we are connected. A + // plugin restart usually REPLACES the socket: the old one dies as the new + // one is accepted, so exactly one `connected` status is published and a + // connectedness edge never fires. The plugin's session map is per-process, + // so skipping the re-ensure there leaves T3 holding a session the new + // process has never heard of, and its next turn.start is rejected with + // "Call session.ensure before starting a turn" — a dead thread. + // + // Starts null rather than reading the current generation: sessions are only + // created after this point, so the first status we observe has nothing to + // resume, and treating it as new is harmless. + let seenGeneration: number | null = null; yield* broker.streamStatuses.pipe( Stream.filter((status) => status.instanceId === input.instanceId), Stream.runForEach((status) => Effect.gen(function* () { - const nowConnected = status.status === "connected"; - const reconnected = nowConnected && !connected; - connected = nowConnected; + const generation = status.connectionGeneration; + const reconnected = + status.status === "connected" && generation !== null && generation !== seenGeneration; + // Only advance on a live connection: holding the last generation + // through an offline gap means the reconnect still registers as new. + if (generation !== null) seenGeneration = generation; if (!reconnected) return; yield* Effect.forEach( Array.from(sessions.values()), diff --git a/apps/server/src/provider/Layers/HermesConnectionRegistry.ts b/apps/server/src/provider/Layers/HermesConnectionRegistry.ts index 944af98671..7e343a4a74 100644 --- a/apps/server/src/provider/Layers/HermesConnectionRegistry.ts +++ b/apps/server/src/provider/Layers/HermesConnectionRegistry.ts @@ -46,6 +46,10 @@ export const livenessStatusFields = ( protocolVersion: observed?.capabilities.protocolVersion ?? liveness?.upgradeRequired?.protocolVersion ?? null, capabilities: observed?.capabilities ?? null, + // Exposed so consumers can tell a replacement (old socket dies as a new + // one is accepted, publishing a single `connected` status) from a + // continuous connection. Watching connectedness alone cannot. + connectionGeneration: liveness?.connection?.generation ?? null, connected: liveness?.connection !== undefined, upgradeRequired: liveness?.upgradeRequired !== undefined, }; diff --git a/apps/server/src/provider/Services/HermesConnectionRegistry.ts b/apps/server/src/provider/Services/HermesConnectionRegistry.ts index a5a2cb7c06..fca36e208e 100644 --- a/apps/server/src/provider/Services/HermesConnectionRegistry.ts +++ b/apps/server/src/provider/Services/HermesConnectionRegistry.ts @@ -160,6 +160,7 @@ export type HermesLivenessStatusFields = Pick< | "activeSessionCount" | "protocolVersion" | "capabilities" + | "connectionGeneration" > & { readonly connected: boolean; readonly upgradeRequired: boolean; diff --git a/packages/contracts/src/hermesGateway.test.ts b/packages/contracts/src/hermesGateway.test.ts index 992e1c3d6c..f935c0cffd 100644 --- a/packages/contracts/src/hermesGateway.test.ts +++ b/packages/contracts/src/hermesGateway.test.ts @@ -70,6 +70,7 @@ describe("Hermes gateway management contracts", () => { pluginVersion: "0.2.0", hermesVersion: "1.2.3", model: "gpt-5.6-terra", + connectionGeneration: 3, activeSessionCount: 2, protocolVersion: 2, capabilities: { diff --git a/packages/contracts/src/hermesGateway.ts b/packages/contracts/src/hermesGateway.ts index 08d096ea39..cb92dc1737 100644 --- a/packages/contracts/src/hermesGateway.ts +++ b/packages/contracts/src/hermesGateway.ts @@ -130,6 +130,17 @@ export const HermesGatewayInstanceStatus = Schema.Struct({ * plugin predates the `model` field on `connection.hello`. */ model: Schema.NullOr(TrimmedNonEmptyString), + /** + * Monotonic id of the underlying connection, or null while offline. + * + * Consumers must key "this is a different plugin process now" off this + * rather than off `status` transitioning through `offline`. A replacement — + * the old socket dying as a new one is accepted — publishes a single + * `connected` status, so a connectedness edge detector never fires and + * anything that must be re-established per connection (notably + * `session.ensure`) is silently skipped. + */ + connectionGeneration: Schema.NullOr(NonNegativeInt), activeSessionCount: NonNegativeInt, protocolVersion: Schema.NullOr(PositiveInt), capabilities: Schema.NullOr(HermesGatewayCapabilities),