{"record":{"id":"5859b4eda9ff99c5","repo":"Crosstalk-Solutions/project-nomad","slug":"failed-to-add-message","errorCode":null,"errorMessage":"Failed to add message","messagePattern":"Failed to add message","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"admin/app/services/chat_service.ts","lineNumber":211,"sourceCode":"\n      // Update session's updated_at timestamp\n      const session = await ChatSession.findOrFail(sessionId)\n      session.updated_at = DateTime.now()\n      await session.save()\n\n      return {\n        id: message.id.toString(),\n        role: message.role,\n        content: message.content,\n        timestamp: message.created_at.toJSDate(),\n      }\n    } catch (error) {\n      logger.error(\n        `[ChatService] Failed to add message to session ${sessionId}: ${\n          error instanceof Error ? error.message : error\n        }`\n      )\n      throw new Error('Failed to add message')\n    }\n  }\n\n  async deleteSession(sessionId: number) {\n    try {\n      const session = await ChatSession.findOrFail(sessionId)\n      await session.delete()\n      return { success: true }\n    } catch (error) {\n      logger.error(\n        `[ChatService] Failed to delete session ${sessionId}: ${\n          error instanceof Error ? error.message : error\n        }`\n      )\n      throw new Error('Failed to delete chat session')\n    }\n  }\n","sourceCodeStart":193,"sourceCodeEnd":229,"githubUrl":"https://github.com/Crosstalk-Solutions/project-nomad/blob/0bd1c6f4f9888d577fe232de06ac144bb8337131/admin/app/services/chat_service.ts#L193-L229","documentation":"ChatService.addMessage rethrows this after logging when ChatMessage.create fails — i.e. inserting a row into chat_messages rejected. Common root causes are a missing/truncated foreign key to chat_sessions, oversized content exceeding a TEXT/VARCHAR limit, or DB unavailability.","triggerScenarios":"Adding a message to a sessionId that doesn't exist in chat_sessions (FK violation), inserting message content larger than the column allows, or inserting while the DB connection pool is exhausted.","commonSituations":"Posting to a session deleted in another request, very long pasted content or base64 payloads blowing past column size, migrations not run in a new deploy, or connection pool exhaustion under concurrent chat traffic.","solutions":["Check logs for '[ChatService] Failed to add message to session <id>: <cause>' for the exact DB error","Verify the session exists before adding (or catch FK errors and surface 'session not found')","If content can be large, ensure the column is TEXT/MEDIUMTEXT (or truncate before insert)","Run pending migrations and confirm FK constraints match the model","Increase/verify DB pool sizing if failures correlate with concurrency"],"exampleFix":"// before\nconst message = await ChatMessage.create({ ... })\n// (throws 'Failed to add message' on FK violation)\n\n// after\nconst session = await ChatSession.find(sessionId)\nif (!session) throw new Error('Chat session not found')\nconst message = await ChatMessage.create({ ... })","handlingStrategy":"validation","validationCode":"if (!(await ChatSession.find(sessionId))) throw new Error('Chat session not found')\nconst content = body.slice(0, MAX_MESSAGE_LEN)","typeGuard":"async function canAddMessage(sessionId: number, content: string): Promise<boolean> {\n  return (await ChatSession.find(sessionId)) !== null && content.length <= MAX_MESSAGE_LEN\n}","tryCatchPattern":"try { await chat.addMessage(...) } catch (e) { if (e.message === 'Failed to add message') { showRetryToast(); return } throw e }","preventionTips":["Validate session existence before inserting messages","Truncate/limit message content to the column size","Use ON DELETE CASCADE so orphaned inserts can't happen after session deletion","Run migrations on deploy"],"tags":["chat","database","insert","foreign-key","adonisjs"],"backgroundTag":"database-query-failed","analyzedSha":"0bd1c6f4f9888d577fe232de06ac144bb8337131","analyzedAt":"2026-08-27T05:34:15.424Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}