Skip to content

[BUG] Composite multi-document cache key incorrectly stored as document_id in ChatMessage table #735

Description

@vipul674

Description of the Bug

In backend/app/routes/chat.py, when a user queries across multiple documents, the code creates a composite cache key:

cache_doc_key = "multi:" + ",".join(sorted(payload.document_ids))

This composite string (e.g., "multi:doc1,doc2,doc3") is then passed directly to _save_message() as the document_id parameter:

msg = _save_message(
    db=db,
    user_id=user_id,
    document_id=cache_doc_key,  # ← composite key, not a real document ID
    ...
)

This value is stored in the ChatMessage.document_id column, which is supposed to be a foreign key referencing the Document table. By storing a fabricated composite string:

  • The foreign key contract is broken
  • Queries filtering by document_id won't find these messages
  • Any UI that looks up document title/metadata using document_id will fail
  • Chat history for multi-document queries is effectively orphaned from document records

Steps to Reproduce

  1. Upload at least two documents
  2. Send a multi-document query (selecting both documents)
  3. Check the chat_messages table in the database
  4. Observe that document_id contains "multi:doc1,doc2" instead of a valid document UUID

Expected Behavior

Multi-document queries should store document_id as None (since there is no single document). The cache key should be stored separately, perhaps in a new field or as part of a cache subsystem, not in the document_id column.

Affected File

backend/app/routes/chat.py (lines ~259-260 and ~374)

Suggested Fix

Pass document_id=None for multi-document queries and maintain the cache key separately. Add a cache_key field to the ChatMessage model for this purpose, or use a separate cache data structure.

GSSoC '26

  • Yes, I am participating in GirlScript Summer of Code and would like to fix this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    gssocGirlScript Summer of Code 2026 issue/PR

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions