Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): answer a duplicate delivery from the record admission read
Alfredo Lopezf853e52c3fb8
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex c7556a8e4..4b9125622 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.454",+ "version": "0.1.455","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.454",+ "version": "0.1.455","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex c1799ee55..ab5f7752e 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.454",+ "version": "0.1.455","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/messageHandler.duplicate.test.ts b/mcp-host/src/__tests__/messageHandler.duplicate.test.tsindex 69fdc4993..c83ae2369 100644--- a/mcp-host/src/__tests__/messageHandler.duplicate.test.ts+++ b/mcp-host/src/__tests__/messageHandler.duplicate.test.ts@@ -443,9 +443,9 @@ describe('IncomingMessageHandler — duplicate delivery keeps acceptedFileRefereexpect('acceptedFileReferenceIds' in second).toBe(false)})- it('logs a missing lifecycle record and replays the outcome without ids', async () => {+ it('answers from the record admission read, even when it is evicted right after', async () => {const deps = createMockDeps()- const message = resolvedMessage('msg-ref-record-missing')+ const message = resolvedMessage('msg-ref-evicted-after-admission')const first = new IncomingMessageHandler(message, deps)first.executeAsync()const task = deps.messageQueue.dequeue()!@@ -453,25 +453,26 @@ describe('IncomingMessageHandler — duplicate delivery keeps acceptedFileReferedeps.messageQueue.completeTask(task)await task.responseCallback!({ response: 'first answer' })- const warn = vi.spyOn(logger, 'warn')- const get = vi.spyOn(deps.taskLifecycle, 'get').mockReturnValue(null)+ // The first read of the prior record returns it; any later read finds it+ // evicted by the lifecycle TTL.+ const realGet = deps.taskLifecycle.get.bind(deps.taskLifecycle)+ let priorReads = 0+ const get = vi.spyOn(deps.taskLifecycle, 'get').mockImplementation(id => {+ if (id !== task.id) return realGet(id)+ priorReads += 1+ return priorReads === 1 ? realGet(id) : null+ })const second = new IncomingMessageHandler(message, deps).executeAsync()- // Witnesses: the duplicate replayed the completed task, and the missing- // record was logged.- expect(second).toMatchObject({ success: true, status: 'completed', taskId: task.id })- expect(warn).toHaveBeenCalledWith(- {- event: 'duplicate_delivery_record_missing',- taskId: expect.any(String),- priorTaskId: task.id,- priorStatus: 'completed',- },- 'Duplicate delivery record missing'- )- expect('acceptedFileReferenceIds' in second).toBe(false)+ expect(priorReads).toBe(1)+ expect(second).toMatchObject({+ success: true,+ status: 'completed',+ taskId: task.id,+ response: 'first answer',+ acceptedFileReferenceIds: [available.id, stale.id],+ })get.mockRestore()- warn.mockRestore()})it('records only resolutions, never the raw references a caller sent', async () => {diff --git a/mcp-host/src/messageHandler.ts b/mcp-host/src/messageHandler.tsindex 16802e971..2a42db7c9 100644--- a/mcp-host/src/messageHandler.ts+++ b/mcp-host/src/messageHandler.ts@@ -2,9 +2,10 @@ import { AgentStateMachine } from './agent'import { LlmErrorCode } from './core/errors'import type { Attachment } from './core/types'import type { TaskLifecycle } from './lifecycle/taskLifecycle'+import type { TaskRecord } from './lifecycle/types'import { logger } from './logger'import { MessageQueue, Task, TaskResponsePayload } from './queue'-import type { TaskError, TaskStatus } from './queue'+import type { TaskError } from './queue'import { ResultStore } from './resultStore'import type { IncomingMessage, MessageResponse } from './server'import { parseBackgroundPrefix, serializeSessionKey } from './session'@@ -317,53 +318,39 @@ export class IncomingMessageHandler {private duplicateSuppressedResponse(admission: {reason: 'duplicate_task_id' | 'duplicate_delivery'priorTaskId: string- priorStatus: TaskStatus+ prior: TaskRecord}): MessageResponse {- const { reason, priorTaskId, priorStatus } = admission+ const { reason, priorTaskId, prior } = admission+ const priorStatus = prior.statuslogger.warn({ taskId: this.task.id, reason, priorTaskId, priorStatus },'Duplicate delivery suppressed')- const record = this.deps.taskLifecycle.get(priorTaskId)// #666 — a success names the attachments and file references the first// delivery admitted, as the first response did; without them a client reads- // a Host that dropped them.- let accepted: Pick<MessageResponse, 'acceptedAttachmentIds' | 'acceptedFileReferenceIds'> = {}- if (record) {- accepted = {- ...(record.acceptedAttachmentIds.length- ? { acceptedAttachmentIds: [...record.acceptedAttachmentIds] }- : {}),- ...(record.acceptedFileReferenceIds.length- ? { acceptedFileReferenceIds: [...record.acceptedFileReferenceIds] }- : {}),- }- } else {- // The queue knows the prior task but the lifecycle holds no record of it,- // so this answer cannot name what the first delivery accepted.- logger.warn(- {- event: 'duplicate_delivery_record_missing',- taskId: this.task.id,- priorTaskId,- priorStatus,- },- 'Duplicate delivery record missing'- )+ // a Host that dropped them. `prior` is the record admission read, so a TTL+ // eviction since then cannot remove them.+ const accepted: Pick<MessageResponse, 'acceptedAttachmentIds' | 'acceptedFileReferenceIds'> = {+ ...(prior.acceptedAttachmentIds.length+ ? { acceptedAttachmentIds: [...prior.acceptedAttachmentIds] }+ : {}),+ ...(prior.acceptedFileReferenceIds.length+ ? { acceptedFileReferenceIds: [...prior.acceptedFileReferenceIds] }+ : {}),}if (priorStatus === 'completed') {return {success: true,status: 'completed',- response: record?.response,- attachments: this.deps.sanitizeAttachments(record?.attachments),+ response: prior.response,+ attachments: this.deps.sanitizeAttachments(prior.attachments),model: this.deps.getModel(),taskId: priorTaskId,...accepted,}}if (priorStatus === 'failed' || priorStatus === 'cancelled') {- const error: TaskError = record?.error ?? {+ const error: TaskError = prior.error ?? {code: 'TASK_ALREADY_TERMINAL',message: `Duplicate delivery suppressed — original task ${priorTaskId} is ${priorStatus}`,retryable: false,diff --git a/mcp-host/src/queue/__tests__/duplicateAdmission.test.ts b/mcp-host/src/queue/__tests__/duplicateAdmission.test.tsindex f01afcab0..597c35424 100644--- a/mcp-host/src/queue/__tests__/duplicateAdmission.test.ts+++ b/mcp-host/src/queue/__tests__/duplicateAdmission.test.ts@@ -72,7 +72,7 @@ describe('MessageQueue.admit — duplicate suppression sink', () => {admitted: false,reason: 'duplicate_task_id',priorTaskId: task.id,- priorStatus: 'pending',+ prior: expect.objectContaining({ id: task.id, status: 'pending' }),})// No re-registration, no second created transition, no second queue entry.expect(created).toBe(0)@@ -97,7 +97,7 @@ describe('MessageQueue.admit — duplicate suppression sink', () => {admitted: false,reason: 'duplicate_delivery',priorTaskId: first.id,- priorStatus: 'processing',+ prior: expect.objectContaining({ id: first.id, status: 'processing' }),})// No new queue entry, and the never-to-run duplicate Task is not leaked// in the instance index (it has no lifecycle record to evict it later).@@ -124,7 +124,7 @@ describe('MessageQueue.admit — duplicate suppression sink', () => {admitted: false,reason: 'duplicate_delivery',priorTaskId: first.id,- priorStatus: 'completed',+ prior: expect.objectContaining({ id: first.id, status: 'completed' }),})// The recorded outcome stays available for replay by the caller.expect(lifecycle.get(first.id)?.response).toBe('first answer')@@ -213,7 +213,7 @@ describe('MessageQueue.admit — duplicate suppression sink', () => {admitted: false,reason: 'duplicate_delivery',priorTaskId: overflow.id,- priorStatus: 'pending',+ prior: expect.objectContaining({ id: overflow.id, status: 'pending' }),})// The retry never registered — no second execution path.expect(lifecycle.getStatus(retry.id)).toBeNull()diff --git a/mcp-host/src/queue/messageQueue.ts b/mcp-host/src/queue/messageQueue.tsindex 45e04995a..8ceda4454 100644--- a/mcp-host/src/queue/messageQueue.ts+++ b/mcp-host/src/queue/messageQueue.ts@@ -238,22 +238,29 @@ export class MessageQueue extends EventEmitter {const deliveryKey = MessageQueue.deliveryKeyOf(task.sourceMessage)if (this.lifecycle) {- const priorStatus = this.lifecycle.getStatus(task.id)- if (priorStatus !== null) {+ // Each prior record is read once and handed to the caller, which answers+ // the duplicate from it without a second lifecycle read.+ const prior = this.lifecycle.get(task.id)+ if (prior !== null) {logger.warn(- { taskId: task.id, priorStatus },+ { taskId: task.id, priorStatus: prior.status },'duplicate delivery suppressed: task already registered')- return { admitted: false, reason: 'duplicate_task_id', priorTaskId: task.id, priorStatus }+ return {+ admitted: false,+ reason: 'duplicate_task_id',+ priorTaskId: task.id,+ prior,+ }}if (deliveryKey) {const priorTaskId = this.deliveryIndex.get(deliveryKey)if (priorTaskId && priorTaskId !== task.id) {- const priorDeliveryStatus = this.lifecycle.getStatus(priorTaskId)- if (priorDeliveryStatus !== null) {+ const priorDelivery = this.lifecycle.get(priorTaskId)+ if (priorDelivery !== null) {logger.warn(- { taskId: task.id, priorTaskId, priorStatus: priorDeliveryStatus },+ { taskId: task.id, priorTaskId, priorStatus: priorDelivery.status },'duplicate delivery suppressed: delivery already admitted')// The duplicate Task object will never run — drop its instance-index@@ -263,7 +270,7 @@ export class MessageQueue extends EventEmitter {admitted: false,reason: 'duplicate_delivery',priorTaskId,- priorStatus: priorDeliveryStatus,+ prior: priorDelivery,}}// The prior record was TTL-evicted — the mapping is stale. Purge itdiff --git a/mcp-host/src/queue/types.ts b/mcp-host/src/queue/types.tsindex 52c20d42b..a2eb46f15 100644--- a/mcp-host/src/queue/types.ts+++ b/mcp-host/src/queue/types.ts@@ -3,6 +3,7 @@*/import type { BudgetVerdict } from '../budget/types'import type { Attachment, TraceContextV1 } from '../core/types'+import type { TaskRecord } from '../lifecycle/types'import { IncomingMessage } from '../server'/**@@ -193,5 +194,11 @@ export type AdmissionOutcome =admitted: falsereason: 'duplicate_task_id' | 'duplicate_delivery'priorTaskId: string- priorStatus: TaskStatus+ /**+ * The prior task's live lifecycle record, read once by admission. The+ * duplicate's answer is built from it, status included, so a TTL eviction+ * after admission cannot leave that answer without the ids the first+ * delivery accepted.+ */+ prior: TaskRecord}