Files
claude-mem/tests/zombie-prevention.test.ts
T
Alex Newman 36b0929fae Server-beta: Postgres storage + independent runtime + BullMQ queue (Phases 1–3) (#2351)
* Add server beta runtime foundation

* Address server beta review findings

* Resolve server beta review comments

* Tighten server beta review follow-ups

* Harden server beta auth and search

* Avoid unnecessary FTS rebuilds

* Block scoped keys from creating projects

* Release BullMQ claims best effort on close

* Address server beta review blockers

* Reset BullMQ claims best effort

* Add Postgres observation storage foundation

* feat(server-beta): add independent runtime service

Introduce src/server/runtime/ as a self-contained server-beta runtime
that owns its lifecycle, Postgres bootstrap, and HTTP boundary without
depending on WorkerService.

ServerBetaService wraps the existing Server class, exposes
/healthz and /v1/info with runtime="server-beta", and persists state
to dedicated paths (.server-beta.pid|.port|.runtime.json). The four
boundary managers (queue, generation worker, provider registry, event
broadcaster) are intentionally disabled in this phase and report their
status through /v1/info; later phases activate them.

Adds plans/2026-05-07-finish-bullmq-branch-ship-plan.md to track the
remaining work for this branch.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): route CLI lifecycle and bundle separate runtime

scripts/build-hooks.js now produces plugin/scripts/server-beta-service.cjs
as a separate Node CJS bundle, alongside the existing worker-service
bundle. The server-beta runtime is now installable independently.

src/npx-cli/commands/server.ts routes start|stop|restart|status to the
server-beta lifecycle instead of the legacy worker. The worker keeps its
own start|stop|restart|status under the worker namespace; the two
runtimes can be operated independently.

src/services/worker-service.ts adds a server-* command parser branch
that delegates to the sibling server-beta-service.cjs bundle so
direct worker-service invocations still route to the right runtime.

tests/npx-cli-server-namespace.test.ts updated to expect server-beta
lifecycle routing.

Includes rebuilt plugin/scripts/*.cjs bundles produced by
build-and-sync.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): add BullMQ job queue primitives

Introduce src/server/jobs/ as the queue-side primitives that Phase 3 of
the server-beta runtime needs to operate.

types.ts defines a discriminated union over the four job kinds (event,
event-batch, summary, reindex) and maps each to a per-kind BullMQ queue
name and deterministic-ID prefix.

job-id.ts builds deterministic, colon-free BullMQ jobIds from
(kind, team, project, source). The colon ban exists because BullMQ uses
':' as a Redis key separator internally; embedding ':' in jobIds
breaks scan and state lookups.

ServerJobQueue.ts is a thin wrapper over BullMQ Queue + Worker that
enforces autorun:false, default concurrency 1, and an attached error
listener — all per BullMQ docs requirements. Test seams accept queue
and worker factories so unit tests do not need Redis.

outbox.ts publishes through the Postgres ObservationGenerationJob
repository as canonical history. enqueueOutbox writes the row first,
then publishes to BullMQ; if BullMQ throws, the row is transitioned to
failed and a failed event is appended. reconcileOnStartup re-enqueues
queued + processing rows after a restart, replacing terminal BullMQ
jobs that may still be holding the deterministic ID slot. markCompleted
and markFailed wrap transitionStatus and append the matching event row.

Includes 20 unit tests covering deterministic ID stability, colon-free
output, queue lifecycle, error-listener attachment, double-start
refusal, idempotent enqueue, BullMQ failure rollback, startup
reconciliation, max-attempts skipping, and completion / failure /
retry transitions.

Phase 3 commit 1 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): activate queue boundary in runtime service

Wire ActiveServerBetaQueueManager into the server-beta runtime graph.
The active manager owns one ServerJobQueue per generation kind (event,
event-batch, summary, reindex) and surfaces lane metadata through
boundary health.

Selection is opt-in and fail-fast: if CLAUDE_MEM_QUEUE_ENGINE is set to
bullmq the active manager is constructed (and any Redis/config error
throws — no silent fallback to SQLite, per Phase 3 anti-pattern guard).
For any other engine the disabled boundary remains so worker-era and
test setups stay compatible.

Widens ServerBetaBoundaryHealth.status to a discriminated union
('disabled' | 'active' | 'errored') with optional details. The disabled
adapter still emits status='disabled', which keeps the existing
server-beta-service test green.

ServerBetaService receives the manager through a new optional
queueManager field on CreateServerBetaServiceOptions so test graphs
and Phase 4 wiring can inject custom managers.

Adds tests/server/runtime/active-queue-manager.test.ts covering bullmq
guard, active health shape, per-kind queue access, close behavior, and
post-close errored health.

Phase 3 commit 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(server-beta): cap /v1/events/batch at 500 events

Prevents unbounded array DoS surface flagged in PR review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 01:20:07 -07:00

367 lines
13 KiB
TypeScript

import { describe, test, expect, beforeEach, afterEach, mock } from 'bun:test';
import { ClaudeMemDatabase } from '../src/services/sqlite/Database.js';
import { PendingMessageStore } from '../src/services/sqlite/PendingMessageStore.js';
import { createSDKSession } from '../src/services/sqlite/Sessions.js';
import type { ActiveSession, PendingMessage } from '../src/services/worker-types.js';
import type { Database } from 'bun:sqlite';
describe('Zombie Agent Prevention', () => {
let db: Database;
let pendingStore: PendingMessageStore;
beforeEach(() => {
db = new ClaudeMemDatabase(':memory:').db;
pendingStore = new PendingMessageStore(db);
});
afterEach(() => {
db.close();
});
function createMockSession(
sessionDbId: number,
overrides: Partial<ActiveSession> = {}
): ActiveSession {
return {
sessionDbId,
contentSessionId: `content-session-${sessionDbId}`,
memorySessionId: null,
project: 'test-project',
userPrompt: 'Test prompt',
pendingMessages: [],
abortController: new AbortController(),
generatorPromise: null,
lastPromptNumber: 1,
startTime: Date.now(),
cumulativeInputTokens: 0,
cumulativeOutputTokens: 0,
earliestPendingTimestamp: null,
claimedMessageIds: [],
conversationHistory: [],
currentProvider: null,
...overrides,
};
}
function createDbSession(contentSessionId: string, project: string = 'test-project'): number {
return createSDKSession(db, contentSessionId, project, 'Test user prompt');
}
function enqueueTestMessage(sessionDbId: number, contentSessionId: string): number {
const message: PendingMessage = {
type: 'observation',
tool_name: 'TestTool',
tool_input: { test: 'input' },
tool_response: { test: 'response' },
prompt_number: 1,
};
return pendingStore.enqueue(sessionDbId, contentSessionId, message);
}
test('should prevent concurrent spawns for same session', async () => {
const session = createMockSession(1);
session.generatorPromise = new Promise<void>((resolve) => {
setTimeout(resolve, 100);
});
expect(session.generatorPromise).not.toBeNull();
const shouldSkip = session.generatorPromise !== null;
expect(shouldSkip).toBe(true);
await session.generatorPromise;
session.generatorPromise = null;
const canSpawnNow = session.generatorPromise === null;
expect(canSpawnNow).toBe(true);
});
test('should prevent duplicate crash recovery spawns', async () => {
const sessionId1 = createDbSession('content-1');
const sessionId2 = createDbSession('content-2');
enqueueTestMessage(sessionId1, 'content-1');
enqueueTestMessage(sessionId2, 'content-2');
const orphanedSessions = pendingStore.getSessionsWithPendingMessages();
expect(orphanedSessions).toContain(sessionId1);
expect(orphanedSessions).toContain(sessionId2);
const session1 = createMockSession(sessionId1, {
contentSessionId: 'content-1',
generatorPromise: new Promise<void>(() => {}), // Active generator
});
const session2 = createMockSession(sessionId2, {
contentSessionId: 'content-2',
generatorPromise: null, // No active generator
});
const sessions = new Map<number, ActiveSession>();
sessions.set(sessionId1, session1);
sessions.set(sessionId2, session2);
const result = {
sessionsStarted: 0,
sessionsSkipped: 0,
startedSessionIds: [] as number[],
};
for (const sessionDbId of orphanedSessions) {
const existingSession = sessions.get(sessionDbId);
if (existingSession?.generatorPromise) {
result.sessionsSkipped++;
continue;
}
result.sessionsStarted++;
result.startedSessionIds.push(sessionDbId);
}
expect(result.sessionsSkipped).toBe(1);
expect(result.sessionsStarted).toBe(1);
expect(result.startedSessionIds).toContain(sessionId2);
expect(result.startedSessionIds).not.toContain(sessionId1);
});
test('should report accurate queueDepth from database', async () => {
const sessionId = createDbSession('content-queue-test');
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
const msgId1 = enqueueTestMessage(sessionId, 'content-queue-test');
expect(pendingStore.getPendingCount(sessionId)).toBe(1);
const msgId2 = enqueueTestMessage(sessionId, 'content-queue-test');
expect(pendingStore.getPendingCount(sessionId)).toBe(2);
const msgId3 = enqueueTestMessage(sessionId, 'content-queue-test');
expect(pendingStore.getPendingCount(sessionId)).toBe(3);
expect(pendingStore.hasAnyPendingWork()).toBe(true);
const claimed = pendingStore.claimNextMessage(sessionId);
expect(claimed).not.toBeNull();
expect(claimed?.id).toBe(msgId1);
expect(pendingStore.getPendingCount(sessionId)).toBe(3);
pendingStore.confirmProcessed(msgId1);
expect(pendingStore.getPendingCount(sessionId)).toBe(2);
const msg2 = pendingStore.claimNextMessage(sessionId);
pendingStore.confirmProcessed(msg2!.id);
expect(pendingStore.getPendingCount(sessionId)).toBe(1);
const msg3 = pendingStore.claimNextMessage(sessionId);
pendingStore.confirmProcessed(msg3!.id);
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
});
test('should track pending work across multiple sessions', async () => {
const session1Id = createDbSession('content-multi-1');
const session2Id = createDbSession('content-multi-2');
const session3Id = createDbSession('content-multi-3');
enqueueTestMessage(session1Id, 'content-multi-1');
enqueueTestMessage(session1Id, 'content-multi-1');
enqueueTestMessage(session2Id, 'content-multi-2');
expect(pendingStore.getPendingCount(session1Id)).toBe(2);
expect(pendingStore.getPendingCount(session2Id)).toBe(1);
expect(pendingStore.getPendingCount(session3Id)).toBe(0);
const sessionsWithPending = pendingStore.getSessionsWithPendingMessages();
expect(sessionsWithPending).toContain(session1Id);
expect(sessionsWithPending).toContain(session2Id);
expect(sessionsWithPending).not.toContain(session3Id);
expect(sessionsWithPending.length).toBe(2);
});
test('should reset AbortController when restarting after abort', async () => {
const session = createMockSession(1);
session.abortController.abort();
expect(session.abortController.signal.aborted).toBe(true);
if (session.abortController.signal.aborted) {
session.abortController = new AbortController();
}
expect(session.abortController.signal.aborted).toBe(false);
});
test('should recover processing messages through explicit restart reset', async () => {
const sessionId = createDbSession('content-restart-reset');
const msgId = enqueueTestMessage(sessionId, 'content-restart-reset');
const claimed = pendingStore.claimNextMessage(sessionId);
expect(claimed).not.toBeNull();
expect(claimed!.id).toBe(msgId);
expect(pendingStore.getPendingCount(sessionId)).toBe(1);
expect(pendingStore.claimNextMessage(sessionId)).toBeNull();
expect(pendingStore.resetProcessingToPending(sessionId)).toBe(1);
const recovered = pendingStore.claimNextMessage(sessionId);
expect(recovered).not.toBeNull();
expect(recovered!.id).toBe(msgId);
pendingStore.confirmProcessed(msgId);
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
});
test('should properly cleanup generator promise on session delete', async () => {
const session = createMockSession(1);
let generatorCompleted = false;
session.generatorPromise = new Promise<void>((resolve) => {
setTimeout(() => {
generatorCompleted = true;
resolve();
}, 50);
});
session.abortController.abort();
if (session.generatorPromise) {
await session.generatorPromise.catch(() => {});
}
expect(generatorCompleted).toBe(true);
session.generatorPromise = null;
expect(session.generatorPromise).toBeNull();
});
describe('Session Termination Invariant', () => {
test('should clear messages when session is terminated', () => {
const sessionId = createDbSession('content-terminate-1');
enqueueTestMessage(sessionId, 'content-terminate-1');
enqueueTestMessage(sessionId, 'content-terminate-1');
expect(pendingStore.getPendingCount(sessionId)).toBe(2);
expect(pendingStore.hasAnyPendingWork()).toBe(true);
const cleared = pendingStore.clearPendingForSession(sessionId);
expect(cleared).toBe(2);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
});
test('should handle terminate with zero pending messages', () => {
const sessionId = createDbSession('content-terminate-empty');
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
const cleared = pendingStore.clearPendingForSession(sessionId);
expect(cleared).toBe(0);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
});
test('should be idempotent — double terminate clears zero on second call', () => {
const sessionId = createDbSession('content-terminate-idempotent');
enqueueTestMessage(sessionId, 'content-terminate-idempotent');
const first = pendingStore.clearPendingForSession(sessionId);
expect(first).toBe(1);
const second = pendingStore.clearPendingForSession(sessionId);
expect(second).toBe(0);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
});
test('should remove session from Map via removeSessionImmediate', () => {
const sessionId = createDbSession('content-terminate-map');
const session = createMockSession(sessionId, {
contentSessionId: 'content-terminate-map',
});
const sessions = new Map<number, ActiveSession>();
sessions.set(sessionId, session);
expect(sessions.has(sessionId)).toBe(true);
sessions.delete(sessionId);
expect(sessions.has(sessionId)).toBe(false);
});
test('should return hasAnyPendingWork false after all sessions terminated', () => {
const sid1 = createDbSession('content-multi-term-1');
const sid2 = createDbSession('content-multi-term-2');
const sid3 = createDbSession('content-multi-term-3');
enqueueTestMessage(sid1, 'content-multi-term-1');
enqueueTestMessage(sid1, 'content-multi-term-1');
enqueueTestMessage(sid2, 'content-multi-term-2');
enqueueTestMessage(sid3, 'content-multi-term-3');
expect(pendingStore.hasAnyPendingWork()).toBe(true);
pendingStore.clearPendingForSession(sid1);
pendingStore.clearPendingForSession(sid2);
pendingStore.clearPendingForSession(sid3);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
});
test('should not affect other sessions when terminating one', () => {
const sid1 = createDbSession('content-isolate-1');
const sid2 = createDbSession('content-isolate-2');
enqueueTestMessage(sid1, 'content-isolate-1');
enqueueTestMessage(sid2, 'content-isolate-2');
pendingStore.clearPendingForSession(sid1);
expect(pendingStore.getPendingCount(sid1)).toBe(0);
expect(pendingStore.getPendingCount(sid2)).toBe(1);
expect(pendingStore.hasAnyPendingWork()).toBe(true);
});
test('should clear both pending and processing messages', () => {
const sessionId = createDbSession('content-mixed-status');
const msgId1 = enqueueTestMessage(sessionId, 'content-mixed-status');
enqueueTestMessage(sessionId, 'content-mixed-status');
const claimed = pendingStore.claimNextMessage(sessionId);
expect(claimed).not.toBeNull();
expect(claimed!.id).toBe(msgId1);
expect(pendingStore.getPendingCount(sessionId)).toBe(2);
const cleared = pendingStore.clearPendingForSession(sessionId);
expect(cleared).toBe(2);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
});
test('should enforce invariant: no pending work after terminate regardless of initial state', () => {
const sessionId = createDbSession('content-invariant');
enqueueTestMessage(sessionId, 'content-invariant');
enqueueTestMessage(sessionId, 'content-invariant');
enqueueTestMessage(sessionId, 'content-invariant');
pendingStore.claimNextMessage(sessionId);
expect(pendingStore.getPendingCount(sessionId)).toBe(3);
pendingStore.clearPendingForSession(sessionId);
expect(pendingStore.hasAnyPendingWork()).toBe(false);
expect(pendingStore.getPendingCount(sessionId)).toBe(0);
});
});
});