Files
claude-mem/tests/services/queue/SessionQueueProcessor.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

369 lines
11 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach, mock, spyOn } from 'bun:test';
import { EventEmitter } from 'events';
import { SessionQueueProcessor, CreateIteratorOptions } from '../../../src/services/queue/SessionQueueProcessor.js';
import type { PendingMessageStore, PersistentPendingMessage } from '../../../src/services/sqlite/PendingMessageStore.js';
function createMockStore(): PendingMessageStore {
return {
claimNextMessage: mock(() => null),
toPendingMessage: mock((msg: PersistentPendingMessage) => ({
type: msg.message_type,
tool_name: msg.tool_name || undefined,
tool_input: msg.tool_input ? JSON.parse(msg.tool_input) : undefined,
tool_response: msg.tool_response ? JSON.parse(msg.tool_response) : undefined,
prompt_number: msg.prompt_number || undefined,
cwd: msg.cwd || undefined,
last_assistant_message: msg.last_assistant_message || undefined,
agentId: msg.agent_id ?? undefined,
agentType: msg.agent_type ?? undefined
}))
} as unknown as PendingMessageStore;
}
function createMockMessage(overrides: Partial<PersistentPendingMessage> = {}): PersistentPendingMessage {
return {
id: 1,
session_db_id: 123,
content_session_id: 'test-session',
message_type: 'observation',
tool_name: 'Read',
tool_input: JSON.stringify({ file: 'test.ts' }),
tool_response: JSON.stringify({ content: 'file contents' }),
cwd: '/test',
last_assistant_message: null,
prompt_number: 1,
status: 'pending',
created_at_epoch: Date.now(),
agent_type: null,
agent_id: null,
...overrides
};
}
describe('SessionQueueProcessor', () => {
let store: PendingMessageStore;
let events: EventEmitter;
let processor: SessionQueueProcessor;
let abortController: AbortController;
beforeEach(() => {
store = createMockStore();
events = new EventEmitter();
processor = new SessionQueueProcessor(store, events);
abortController = new AbortController();
});
afterEach(() => {
abortController.abort();
events.removeAllListeners();
});
describe('createIterator', () => {
describe('idle timeout behavior', () => {
it('should exit after idle timeout when no messages arrive', async () => {
const SHORT_TIMEOUT_MS = 50;
const onIdleTimeout = mock(() => {});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
onIdleTimeout,
idleTimeoutMs: SHORT_TIMEOUT_MS
};
const iterator = processor.createIterator(options);
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(0);
expect(onIdleTimeout).toHaveBeenCalled();
});
it('should invoke onIdleTimeout callback when idle timeout occurs', async () => {
const onIdleTimeout = mock(() => {
abortController.abort();
});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
onIdleTimeout,
idleTimeoutMs: 50
};
const iterator = processor.createIterator(options);
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(0);
});
it('should reset idle timer when message arrives', async () => {
const onIdleTimeout = mock(() => abortController.abort());
let callCount = 0;
(store.claimNextMessage as any) = mock(() => {
callCount++;
if (callCount === 1) {
return createMockMessage({ id: 1 });
}
return null;
});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
onIdleTimeout,
idleTimeoutMs: 50
};
const iterator = processor.createIterator(options);
const results: any[] = [];
setTimeout(() => abortController.abort(), 25);
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(1);
expect(results[0]._persistentId).toBe(1);
expect(callCount).toBeGreaterThanOrEqual(1);
});
});
describe('abort signal handling', () => {
it('should exit immediately when abort signal is triggered', async () => {
const onIdleTimeout = mock(() => {});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
onIdleTimeout
};
const iterator = processor.createIterator(options);
abortController.abort();
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(0);
expect(onIdleTimeout).not.toHaveBeenCalled();
});
it('should take precedence over timeout when both could fire', async () => {
const onIdleTimeout = mock(() => {});
(store.claimNextMessage as any) = mock(() => null);
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
onIdleTimeout
};
const iterator = processor.createIterator(options);
setTimeout(() => abortController.abort(), 10);
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(0);
expect(onIdleTimeout).not.toHaveBeenCalled();
});
});
describe('message event handling', () => {
it('should wake up when message event is emitted', async () => {
let callCount = 0;
const mockMessages = [
createMockMessage({ id: 1 }),
createMockMessage({ id: 2 })
];
(store.claimNextMessage as any) = mock(() => {
callCount++;
if (callCount === 1) {
return null;
} else if (callCount === 2) {
return mockMessages[0];
} else if (callCount === 3) {
return null;
}
return null;
});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal
};
const iterator = processor.createIterator(options);
const results: any[] = [];
setTimeout(() => events.emit('message'), 50);
setTimeout(() => abortController.abort(), 150);
for await (const message of iterator) {
results.push(message);
}
expect(results.length).toBeGreaterThanOrEqual(1);
if (results.length > 0) {
expect(results[0]._persistentId).toBe(1);
}
});
});
describe('event listener cleanup', () => {
it('should clean up event listeners on abort', async () => {
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal
};
const iterator = processor.createIterator(options);
const initialListenerCount = events.listenerCount('message');
abortController.abort();
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
const finalListenerCount = events.listenerCount('message');
expect(finalListenerCount).toBeLessThanOrEqual(initialListenerCount + 1);
});
it('should clean up event listeners when message received', async () => {
(store.claimNextMessage as any) = mock(() => createMockMessage({ id: 1 }));
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal
};
const iterator = processor.createIterator(options);
const firstResult = await iterator.next();
expect(firstResult.done).toBe(false);
expect(firstResult.value._persistentId).toBe(1);
abortController.abort();
for await (const _ of iterator) {
// Should not get here since we aborted
}
const finalListenerCount = events.listenerCount('message');
expect(finalListenerCount).toBeLessThanOrEqual(1);
});
});
describe('error handling', () => {
it('should retry after a transient store claim error', async () => {
let callCount = 0;
(store.claimNextMessage as any) = mock(() => {
callCount++;
if (callCount === 1) {
throw new Error('Database error');
}
return createMockMessage({ id: 7 });
});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal,
claimRetryDelayMs: 1
};
const iterator = processor.createIterator(options);
const result = await iterator.next();
abortController.abort();
expect(result.done).toBe(false);
expect(result.value._persistentId).toBe(7);
expect(callCount).toBe(2);
});
it('should exit cleanly if aborted during error backoff', async () => {
(store.claimNextMessage as any) = mock(() => {
throw new Error('Database error');
});
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal
};
const iterator = processor.createIterator(options);
setTimeout(() => abortController.abort(), 100);
const results: any[] = [];
for await (const message of iterator) {
results.push(message);
}
expect(results).toHaveLength(0);
});
});
describe('message conversion', () => {
it('should convert PersistentPendingMessage to PendingMessageWithId', async () => {
const mockPersistentMessage = createMockMessage({
id: 42,
message_type: 'observation',
tool_name: 'Grep',
tool_input: JSON.stringify({ pattern: 'test' }),
tool_response: JSON.stringify({ matches: ['file.ts'] }),
prompt_number: 5,
created_at_epoch: 1704067200000
});
(store.claimNextMessage as any) = mock(() => mockPersistentMessage);
const options: CreateIteratorOptions = {
sessionDbId: 123,
signal: abortController.signal
};
const iterator = processor.createIterator(options);
const result = await iterator.next();
abortController.abort();
expect(result.done).toBe(false);
expect(result.value).toMatchObject({
_persistentId: 42,
_originalTimestamp: 1704067200000,
type: 'observation',
tool_name: 'Grep',
prompt_number: 5
});
});
});
});
});