{"record":{"id":"3a704d7772c45163","repo":"thedotmack/claude-mem","slug":"context-requested-before-initialization-complete","errorCode":null,"errorMessage":"Context requested before initialization complete, returning empty","messagePattern":"Context requested before initialization complete, returning empty","errorType":"console","errorClass":null,"httpStatus":null,"severity":"info","filePath":"src/services/worker-service.ts","lineNumber":374,"sourceCode":"  private startDeferredSessionEndReplay(): void {\n    if (this.deferredSessionEndReplayTimer !== null) return;\n\n    this.deferredSessionEndReplayTimer = setInterval(() => {\n      void this.drainDeferredSessionEndQueue().catch((error: unknown) => {\n        logger.warn('SESSION', 'Deferred SessionEnd replay loop failed', {},\n          error instanceof Error ? error : new Error(String(error)));\n      });\n    }, 30_000);\n    this.deferredSessionEndReplayTimer.unref?.();\n  }\n\n  private registerRoutes(): void {\n\n    this.server.registerRoutes(new ChromaRoutes());\n\n    this.server.app.get('/api/context/inject', async (req, res, next) => {\n      if (!this.initializationCompleteFlag || !this.searchRoutes) {\n        logger.warn('SYSTEM', 'Context requested before initialization complete, returning empty');\n        res.status(200).json({ content: [{ type: 'text', text: '' }] });\n        return;\n      }\n\n      next(); \n    });\n\n    this.server.app.use(['/api', '/v1'], async (req, res, next) => {\n      if (\n        req.path === '/chroma/status' ||\n        req.path === '/health' ||\n        req.path === '/readiness' ||\n        req.path === '/version' ||\n        req.path === '/settings/dependency-health'\n      ) {\n        next();\n        return;\n      }","sourceCodeStart":356,"sourceCodeEnd":392,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/d8bc9755e74915e5c3b999181e10a67c889bce2a/src/services/worker-service.ts#L356-L392","documentation":"The worker's /api/context/inject route is registered before background initialization finishes. If a request arrives while initializationCompleteFlag is false or searchRoutes is not yet set, the worker answers immediately with an empty text content block (HTTP 200) instead of serving real injected context.","triggerScenarios":"registerRoutes (constructor) sets up the /api/context/inject middleware; any client request hitting that endpoint during worker startup — or if searchRoutes never initialized (background init crashed) — triggers the empty response.","commonSituations":"MCP client or script starts a query the instant the worker port opens; slow Chroma/DB initialization after restart; background init failure leaving searchRoutes unset so every request returns empty.","solutions":["Retry the request after a short delay until initialization completes (add client-side retry with backoff).","Check worker logs for background-initialization errors — if init failed, searchRoutes will never be set; fix the underlying init failure.","Wait for a worker health/ready signal before sending /api/context/inject requests.","If it persists on every request, restart the worker and watch for init errors."],"exampleFix":"// before: fire immediately after spawn\nawait fetch('http://127.0.0.1:37777/api/context/inject', ...)\n// after: poll readiness first\nawait waitFor(() => fetch('http://127.0.0.1:37777/api/health').ok, { intervalMs: 250 });\nawait fetch('http://127.0.0.1:37777/api/context/inject', ...)","handlingStrategy":"retry","validationCode":"async function isWorkerReady(base) {\n  const r = await fetch(base + '/api/health');\n  return r.ok;\n}","typeGuard":null,"tryCatchPattern":"try {\n  const res = await fetch(base + '/api/context/inject');\n  const body = await res.json();\n  if (body.content?.[0]?.text === '') {\n    await sleep(500); // init likely incomplete; retry\n  }\n} catch (err) { /* handle */ }","preventionTips":["Wait for a readiness signal before sending early requests","Add client-side retry with backoff for the first seconds after worker spawn","Check worker logs if empty responses persist — background init may have failed"],"tags":["initialization","race-condition","http"],"backgroundTag":"invalid-state-transition","analyzedSha":"d8bc9755e74915e5c3b999181e10a67c889bce2a","analyzedAt":"2026-09-17T16:40:26.182Z","contentChangedAt":"2026-09-17T16:40:26.182Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}