From 27aa98c269d374aead868dd26473a65d4ea9046d Mon Sep 17 00:00:00 2001 From: Rajiv Sinclair Date: Tue, 27 Jan 2026 10:44:42 -0800 Subject: [PATCH] fix: wait for database initialization before processing session-init requests Fixes a race condition where the UserPromptSubmit hook could call /api/sessions/init before the database is fully initialized, resulting in a 500 error with "Database not initialized". Root cause: - Worker starts HTTP server immediately for fast startup - Health endpoint (/api/health) returns OK when server is listening - session-init hook waits for health check, then calls /api/sessions/init - Database initialization happens in background, creating a race window Solution: - Add early handler for /api/sessions/init that waits for initialization - Uses same pattern as existing /api/context/inject handler - Returns 503 with retry message if initialization times out The fix ensures hooks receive proper responses even during the brief startup window when the server is listening but DB isn't ready yet. Co-Authored-By: Claude Code --- src/services/worker-service.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/services/worker-service.ts b/src/services/worker-service.ts index b784d419..065fb8ee 100644 --- a/src/services/worker-service.ts +++ b/src/services/worker-service.ts @@ -250,6 +250,27 @@ export class WorkerService { next(); // Delegate to SearchRoutes handler }); + + // Early handler for /api/sessions/init to wait for database initialization + // Fixes race condition where session-init hook is called before DB is ready + // See: https://github.com/thedotmack/claude-mem/issues/XXX + this.server.app.post('/api/sessions/init', async (req, res, next) => { + const timeoutMs = 30000; // 30 second timeout for session init + const timeoutPromise = new Promise((_, reject) => + setTimeout(() => reject(new Error('Database initialization timeout')), timeoutMs) + ); + + try { + await Promise.race([this.initializationComplete, timeoutPromise]); + next(); // Delegate to SessionRoutes handler + } catch (error) { + logger.error('HTTP', 'Session init failed waiting for initialization', {}, error as Error); + res.status(503).json({ + error: 'Service initializing', + message: 'Database is still initializing, please retry' + }); + } + }); } /**