{"record":{"id":"2295accf207a5c20","repo":"thedotmack/claude-mem","slug":"internalerror","errorCode":"InternalError","errorMessage":"Failed to persist event","messagePattern":"Failed to persist event","errorType":"http","errorClass":null,"httpStatus":500,"severity":"critical","filePath":"src/server/routes/v1/ServerV1PostgresRoutes.ts","lineNumber":1383,"sourceCode":"    const byTeam = await this.options.pool.query(\n      `DELETE FROM observations WHERE id = $1 AND team_id = $2`,\n      [id, teamId],\n    );\n    return (byTeam.rowCount ?? 0) > 0;\n  }\n\n  private handleDbError(error: unknown, res: Response, action: string): void {\n    const message = error instanceof Error ? error.message : String(error);\n    if (\n      message.includes('project_id must belong to team_id')\n      || message.includes('server_session_id must belong')\n      || message.includes('agent_event source_id must belong')\n    ) {\n      res.status(403).json({ error: 'Forbidden', message });\n      return;\n    }\n    logger.error('SYSTEM', `${action} failed`, { error: message });\n    res.status(500).json({ error: 'InternalError', message: 'Failed to persist event' });\n  }\n\n  private async auditWrite(\n    req: Request,\n    action: string,\n    targetId: string | null,\n    projectId: string | null,\n    details?: Record<string, unknown>,\n  ): Promise<void> {\n    const repo = new PostgresAuthRepository(this.options.pool);\n    const actorId = await this.resolveActorId(req);\n    // Phase 12 — every audit row carries request_id when one was minted\n    // so dashboards and incident triage can pivot from a single HTTP\n    // request to every ingest/job/audit row it produced. Caller-supplied\n    // details win on key conflict so explicit overrides still work.\n    const detailsWithRequestId: Record<string, unknown> = {\n      ...(req.requestId ? { requestId: req.requestId } : {}),\n      ...(details ?? {}),","sourceCodeStart":1365,"sourceCodeEnd":1401,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/d8bc9755e74915e5c3b999181e10a67c889bce2a/src/server/routes/v1/ServerV1PostgresRoutes.ts#L1365-L1401","documentation":"A 500 InternalError returned when persisting an agent/event fails for any reason other than the recognized tenant-scope violations handled at line 1379. The raw error is logged server-side (logger.error) and a generic message is returned so internal details are not leaked.","triggerScenarios":"Any DB failure during an event write that is not an ownership-constraint message: connection loss, constraint violation outside the three known messages, schema mismatch, pool exhaustion, serialization/deadlock failure during event INSERT.","commonSituations":"Postgres restart or network blip mid-request; schema migration mismatch between deployed code and DB; connection pool exhausted under load; invalid enum value for event type added by a newer client against an older schema.","solutions":["Check server logs for the `${action} failed` entry to get the underlying DB error.","Retry the request — transient connection/pool failures usually resolve on retry with backoff.","Verify the DB schema matches the deployed code version (run pending migrations).","If persistent, check Postgres health, connection limits, and pool configuration."],"exampleFix":"// client-side: retry transient 500s with backoff\nfor (const delay of [100, 500, 2000]) {\n  const res = await post('/v1/events', payload);\n  if (res.status !== 500) return res;\n  await sleep(delay);\n}","handlingStrategy":"retry","validationCode":"null","typeGuard":"null","tryCatchPattern":"async function postEventWithRetry(payload: unknown, attempts = 3) {\n  for (let i = 0; i < attempts; i++) {\n    const res = await post('/v1/events', payload);\n    if (res.status !== 500) return res;\n    await new Promise(r => setTimeout(r, 2 ** i * 250));\n  }\n  throw new Error('event persist failed after retries — check server logs for `${action} failed`');\n}","preventionTips":["Retry 500s with exponential backoff — many are transient DB/connection failures.","Alert on server-side `${action} failed` log entries to catch DB issues early.","Keep DB schema in sync with the deployed code version.","Monitor Postgres health and connection-pool saturation."],"tags":["http-500","database","internal-error"],"backgroundTag":"database-write-failed","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"}