Files
claude-mem/tests/sqlite/transactions.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

310 lines
11 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { ClaudeMemDatabase } from '../../src/services/sqlite/Database.js';
import {
storeObservations,
storeObservationsAndMarkComplete,
} from '../../src/services/sqlite/transactions.js';
import { getObservationById } from '../../src/services/sqlite/Observations.js';
import { getSummaryForSession } from '../../src/services/sqlite/Summaries.js';
import {
createSDKSession,
updateMemorySessionId,
} from '../../src/services/sqlite/Sessions.js';
import type { ObservationInput } from '../../src/services/sqlite/observations/types.js';
import type { SummaryInput } from '../../src/services/sqlite/summaries/types.js';
import type { Database } from 'bun:sqlite';
describe('Transactions Module', () => {
let db: Database;
beforeEach(() => {
db = new ClaudeMemDatabase(':memory:').db;
});
afterEach(() => {
db.close();
});
function createObservationInput(overrides: Partial<ObservationInput> = {}): ObservationInput {
return {
type: 'discovery',
title: 'Test Observation',
subtitle: 'Test Subtitle',
facts: ['fact1', 'fact2'],
narrative: 'Test narrative content',
concepts: ['concept1', 'concept2'],
files_read: ['/path/to/file1.ts'],
files_modified: ['/path/to/file2.ts'],
...overrides,
};
}
function createSummaryInput(overrides: Partial<SummaryInput> = {}): SummaryInput {
return {
request: 'User requested feature X',
investigated: 'Explored the codebase',
learned: 'Discovered pattern Y',
completed: 'Implemented feature X',
next_steps: 'Add tests and documentation',
notes: 'Consider edge case Z',
...overrides,
};
}
function createSessionWithMemoryId(contentSessionId: string, memorySessionId: string, project: string = 'test-project'): { memorySessionId: string; sessionDbId: number } {
const sessionDbId = createSDKSession(db, contentSessionId, project, 'initial prompt');
updateMemorySessionId(db, sessionDbId, memorySessionId);
return { memorySessionId, sessionDbId };
}
describe('storeObservations', () => {
it('should store multiple observations atomically and return result', () => {
const { memorySessionId } = createSessionWithMemoryId('content-atomic-123', 'atomic-session-123');
const project = 'test-project';
const observations = [
createObservationInput({ title: 'Obs 1' }),
createObservationInput({ title: 'Obs 2' }),
createObservationInput({ title: 'Obs 3' }),
];
const result = storeObservations(db, memorySessionId, project, observations, null);
expect(result.observationIds).toHaveLength(3);
expect(result.observationIds.every((id) => typeof id === 'number')).toBe(true);
expect(result.summaryId).toBeNull();
expect(typeof result.createdAtEpoch).toBe('number');
});
it('should store all observations with same timestamp', () => {
const { memorySessionId } = createSessionWithMemoryId('content-ts', 'timestamp-session');
const project = 'test-project';
const observations = [
createObservationInput({ title: 'Obs A' }),
createObservationInput({ title: 'Obs B' }),
];
const fixedTimestamp = 1600000000000;
const result = storeObservations(
db,
memorySessionId,
project,
observations,
null,
1,
0,
fixedTimestamp
);
expect(result.createdAtEpoch).toBe(fixedTimestamp);
for (const id of result.observationIds) {
const obs = getObservationById(db, id);
expect(obs?.created_at_epoch).toBe(fixedTimestamp);
}
});
it('should store observations with summary', () => {
const { memorySessionId } = createSessionWithMemoryId('content-with-sum', 'with-summary-session');
const project = 'test-project';
const observations = [createObservationInput({ title: 'Main Obs' })];
const summary = createSummaryInput({ request: 'Test request' });
const result = storeObservations(db, memorySessionId, project, observations, summary);
expect(result.observationIds).toHaveLength(1);
expect(result.summaryId).not.toBeNull();
expect(typeof result.summaryId).toBe('number');
const storedSummary = getSummaryForSession(db, memorySessionId);
expect(storedSummary).not.toBeNull();
expect(storedSummary?.request).toBe('Test request');
});
it('should handle empty observations array', () => {
const { memorySessionId } = createSessionWithMemoryId('content-empty', 'empty-obs-session');
const project = 'test-project';
const observations: ObservationInput[] = [];
const result = storeObservations(db, memorySessionId, project, observations, null);
expect(result.observationIds).toHaveLength(0);
expect(result.summaryId).toBeNull();
});
it('should handle summary-only (no observations)', () => {
const { memorySessionId } = createSessionWithMemoryId('content-sum-only', 'summary-only-session');
const project = 'test-project';
const summary = createSummaryInput({ request: 'Summary-only request' });
const result = storeObservations(db, memorySessionId, project, [], summary);
expect(result.observationIds).toHaveLength(0);
expect(result.summaryId).not.toBeNull();
const storedSummary = getSummaryForSession(db, memorySessionId);
expect(storedSummary?.request).toBe('Summary-only request');
});
it('should return correct createdAtEpoch', () => {
const { memorySessionId } = createSessionWithMemoryId('content-epoch', 'session-epoch');
const before = Date.now();
const result = storeObservations(
db,
memorySessionId,
'project',
[createObservationInput()],
null
);
const after = Date.now();
expect(result.createdAtEpoch).toBeGreaterThanOrEqual(before);
expect(result.createdAtEpoch).toBeLessThanOrEqual(after);
});
it('should apply promptNumber to all observations', () => {
const { memorySessionId } = createSessionWithMemoryId('content-pn', 'prompt-num-session');
const project = 'test-project';
const observations = [
createObservationInput({ title: 'Obs 1' }),
createObservationInput({ title: 'Obs 2' }),
];
const promptNumber = 5;
const result = storeObservations(
db,
memorySessionId,
project,
observations,
null,
promptNumber
);
for (const id of result.observationIds) {
const obs = getObservationById(db, id);
expect(obs?.prompt_number).toBe(promptNumber);
}
});
});
describe('storeObservationsAndMarkComplete', () => {
it('should store observations, summary, and remove completed queue message', () => {
const { memorySessionId, sessionDbId } = createSessionWithMemoryId('content-complete', 'complete-session');
const project = 'test-project';
const observations = [createObservationInput({ title: 'Complete Obs' })];
const summary = createSummaryInput({ request: 'Complete request' });
const insertStmt = db.prepare(`
INSERT INTO pending_messages
(session_db_id, content_session_id, message_type, created_at_epoch, status)
VALUES (?, ?, 'observation', ?, 'processing')
`);
const msgResult = insertStmt.run(sessionDbId, 'content-complete', Date.now());
const messageId = Number(msgResult.lastInsertRowid);
const result = storeObservationsAndMarkComplete(
db,
memorySessionId,
project,
observations,
summary,
messageId
);
expect(result.observationIds).toHaveLength(1);
expect(result.summaryId).not.toBeNull();
const msgStmt = db.prepare('SELECT id FROM pending_messages WHERE id = ?');
const msg = msgStmt.get(messageId) as { id: number } | null;
expect(msg).toBeNull();
});
it('should maintain atomicity - all operations share same timestamp', () => {
const { memorySessionId, sessionDbId } = createSessionWithMemoryId('content-atomic-ts', 'atomic-timestamp-session');
const project = 'test-project';
const observations = [
createObservationInput({ title: 'Obs 1' }),
createObservationInput({ title: 'Obs 2' }),
];
const summary = createSummaryInput();
const fixedTimestamp = 1700000000000;
db.prepare(`
INSERT INTO pending_messages
(session_db_id, content_session_id, message_type, created_at_epoch, status)
VALUES (?, ?, 'observation', ?, 'processing')
`).run(sessionDbId, 'content-atomic-ts', Date.now());
const messageId = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
const result = storeObservationsAndMarkComplete(
db,
memorySessionId,
project,
observations,
summary,
messageId.id,
1,
0,
fixedTimestamp
);
expect(result.createdAtEpoch).toBe(fixedTimestamp);
for (const id of result.observationIds) {
const obs = getObservationById(db, id);
expect(obs?.created_at_epoch).toBe(fixedTimestamp);
}
const storedSummary = getSummaryForSession(db, memorySessionId);
expect(storedSummary?.created_at_epoch).toBe(fixedTimestamp);
});
it('should handle null summary', () => {
const { memorySessionId, sessionDbId } = createSessionWithMemoryId('content-no-sum', 'no-summary-session');
const project = 'test-project';
const observations = [createObservationInput({ title: 'Only Obs' })];
db.prepare(`
INSERT INTO pending_messages
(session_db_id, content_session_id, message_type, created_at_epoch, status)
VALUES (?, ?, 'observation', ?, 'processing')
`).run(sessionDbId, 'content-no-sum', Date.now());
const messageId = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
const result = storeObservationsAndMarkComplete(
db,
memorySessionId,
project,
observations,
null,
messageId.id
);
expect(result.observationIds).toHaveLength(1);
expect(result.summaryId).toBeNull();
});
it('should roll back stored observations when the pending message is not completed', () => {
const { memorySessionId } = createSessionWithMemoryId('content-missing-pending', 'missing-pending-session');
const observations = [createObservationInput({ title: 'Rollback Obs' })];
expect(() => storeObservationsAndMarkComplete(
db,
memorySessionId,
'test-project',
observations,
null,
99999
)).toThrow('storeObservationsAndMarkComplete: failed to complete pending message 99999');
const count = db.prepare(`
SELECT COUNT(*) AS count
FROM observations
WHERE title = ?
`).get('Rollback Obs') as { count: number };
expect(count.count).toBe(0);
});
});
});