Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): report only unexpected db worker exits and log worker errors
Alfredo Lopez74b1e7722835
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 8424c1378..69690c41b 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.563",+ "version": "0.1.564","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.563",+ "version": "0.1.564","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 7dc5ae1aa..91a32d40e 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.563",+ "version": "0.1.564","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/conversation/persistence/__tests__/conversationStoreFactory.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/conversationStoreFactory.test.tsindex 22a202791..c09573472 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/conversationStoreFactory.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/conversationStoreFactory.test.ts@@ -1,7 +1,8 @@-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import * as fs from 'node:fs'import * as os from 'node:os'import * as path from 'node:path'+import { logger } from '../../../../logger'import { createConversationStore } from '../conversationStoreFactory'const roots: string[] = []@@ -64,4 +65,44 @@ describe('createConversationStore persist failure', () => {await expect(failure).resolves.toMatchObject({ message: 'db worker exited (code=3)' })expect(() => queue.enqueueAsync('s1', { kind: 'ping' })).toThrow(/db worker exited/)})++ it('logs no error when the worker exits after a graceful shutdown', async () => {+ const script = workerScript(`+ const { parentPort } = require('node:worker_threads')+ parentPort.on('message', msg => {+ if (msg.op.kind === 'ping') parentPort.postMessage({ id: msg.id, ok: true, result: 'pong' })+ if (msg.op.kind === 'shutdown') {+ parentPort.postMessage({ id: msg.id, ok: true, result: { ok: true } })+ process.exit(0)+ }+ })+ `)+ const errors = vi.spyOn(logger, 'error')+ try {+ const failures: Error[] = []+ const handle = createConversationStore({+ mode: 'sqlite',+ dbPath: path.join(path.dirname(script), 'state.db'),+ cacheSize: 10,+ syncTimeoutMs: 2000,+ asyncTimeoutMs: 2000,+ checkpointEveryWrites: 100,+ heartbeatMs: 60_000,+ workerScriptPath: script,+ onPersistFailure: err => failures.push(err),+ })+ const worker = handle.worker+ if (!worker || !handle.persistQueue) throw new Error('sqlite mode returned no worker')+ const exited = new Promise<number>(resolve => worker.once('exit', resolve))+ await expect(handle.persistQueue.enqueueSync({ kind: 'ping' })).resolves.toBe('pong')++ await handle.shutdown()+ // Liveness witness: the worker really exited after the shutdown ACK.+ await expect(exited).resolves.toBe(0)+ expect(failures).toHaveLength(0)+ expect(errors).not.toHaveBeenCalled()+ } finally {+ errors.mockRestore()+ }+ })})diff --git a/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.tsindex 5ea1e61f9..e10b34a45 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts@@ -138,13 +138,15 @@ describe('PersistQueue', () => {expect(() => q.enqueueAsync('s2', { kind: 'ping' })).toThrow(/database or disk is full/)})- it('calls onFailure once when the worker exits unexpectedly', async () => {+ it('calls onExit and onFailure once when the worker exits unexpectedly', async () => {const worker = new FakeWorker()const failures: Error[] = []+ const exits: number[] = []const q = new PersistQueue(worker, {syncTimeoutMs: 500,asyncTimeoutMs: 500,onFailure: err => failures.push(err),+ onExit: code => exits.push(code),})// Liveness witness: with the worker alive a write is acknowledged and// onFailure has not fired.@@ -158,6 +160,7 @@ describe('PersistQueue', () => {expect(failures).toHaveLength(0)worker.emit('exit', 1)+ expect(exits).toEqual([1])expect(failures.map(e => e.message)).toEqual(['db worker exited (code=1)'])// A later rejected write does not report a second failure.expect(() => q.enqueueAsync('s1', { kind: 'ping' })).toThrow(/db worker exited/)@@ -201,15 +204,17 @@ describe('PersistQueue', () => {expect(failures).toHaveLength(1)})- it('does not call onFailure for the worker exit that follows a shutdown ACK', async () => {+ it('reports neither onFailure nor onExit for the worker exit that follows a shutdown ACK', async () => {const worker = new FakeWorker()const failures: Error[] = []- const exits: number[] = []+ const reportedExits: number[] = []+ const observedExits: number[] = []+ worker.on('exit', code => observedExits.push(code))const q = new PersistQueue(worker, {syncTimeoutMs: 500,asyncTimeoutMs: 500,onFailure: err => failures.push(err),- onExit: code => exits.push(code),+ onExit: code => reportedExits.push(code),})const closing = q.close()await new Promise(r => setImmediate(r))@@ -219,7 +224,8 @@ describe('PersistQueue', () => {// FakeWorker.terminate() emits the exit.await closing// Liveness witness: the exit was observed.- expect(exits).toEqual([0])+ expect(observedExits).toEqual([0])+ expect(reportedExits).toHaveLength(0)expect(failures).toHaveLength(0)})diff --git a/mcp-host/src/core/conversation/persistence/persistQueue.ts b/mcp-host/src/core/conversation/persistence/persistQueue.tsindex 2f9f7c97e..133db702e 100644--- a/mcp-host/src/core/conversation/persistence/persistQueue.ts+++ b/mcp-host/src/core/conversation/persistence/persistQueue.ts@@ -42,8 +42,9 @@ export interface PersistQueueOptions {/** Called on transport-level errors (worker crashed, message channel broke). */onTransportError?: (err: Error) => void/**- * Called when the worker exits, for logging. An exit before the `shutdown`- * ACK is also reported through `onFailure`, which ends the process.+ * Called with the exit code when the worker exits before ACKing `shutdown`,+ * for logging. The same exit is reported through `onFailure`, which ends+ * the process. The exit that follows a `shutdown` ACK is not reported.*/onExit?: (code: number) => void/**@@ -91,8 +92,9 @@ export class PersistQueue {)}this.pending.clear()+ if (this.shutdownAcked) returnif (this.opts.onExit) this.opts.onExit(code)- if (!this.shutdownAcked) this.recordFailure(new Error(`db worker exited (code=${code})`))+ this.recordFailure(new Error(`db worker exited (code=${code})`))})}diff --git a/mcp-host/src/db/worker/dbWorker.ts b/mcp-host/src/db/worker/dbWorker.tsindex ce3c57a1c..3e3747a67 100644--- a/mcp-host/src/db/worker/dbWorker.ts+++ b/mcp-host/src/db/worker/dbWorker.ts@@ -75,7 +75,7 @@ async function main(): Promise<void> {try {db.pragma('wal_checkpoint(PASSIVE)')} catch (err) {- logger.warn({ err: (err as Error).message }, '[dbWorker] PASSIVE checkpoint failed')+ logger.warn({ err }, '[dbWorker] PASSIVE checkpoint failed')}writesSinceCheckpoint = 0}@@ -126,7 +126,7 @@ async function main(): Promise<void> {main().catch(err => {// The main thread does not read `__fatal__`; this line is the only record// of why the worker stopped (for example an orphan-WAL refusal).- logger.error({ err: (err as Error).message }, '[dbWorker] fatal; exiting with code 1')+ logger.error({ err }, '[dbWorker] fatal; exiting with code 1')if (parentPort) {parentPort.postMessage({id: '__fatal__',