Skip to content

[Bug] Chat history loading reads every turn's saved prompt, so API memory grows quadratically with conversation length #44520

Closed

Description

@Takuya-ops

Self Checks

  • I have read the Contributing Guide and Language Policy.
  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.

Dify version

1.17.1, and still present on main at 5c59b9cbf649c3fffd52c980e11ea85670c0891c (2026-10-22).

Cloud or Self Hosted

Self Hosted (Source)

Steps to reproduce

Every reply in a chat app loads the conversation history from messages. Two queries on that path select whole Message rows:

  • TokenBufferMemory.load_history (api/core/memory/token_buffer_memory.py) loads up to 500 rows on every turn.
  • get_thread_messages_length (api/core/prompt/utils/get_thread_messages_length.py) loads every row of the conversation, with no limit, on every chatflow turn.

A whole row includes Message.message. For chatbot, agent and completion apps, EasyUIBasedGenerateTaskPipeline._save_message stores the full prompt of that turn there: the system prompt, every earlier turn and the query. So the row of turn n holds a copy of the previous n − 1 turns, and loading the last n rows reads about n²/2 turns of text. Neither query uses this column. History is rebuilt from query and answer, and the length helper only needs id, parent_message_id and answer.

PLUGIN_BASED_TOKEN_COUNTING_ENABLED is false by default, so get_llm_num_tokens returns 0 and history is never pruned by tokens. Saved prompts therefore keep growing until the 500-message cap.

To reproduce:

  1. Create a basic Chatbot app and keep chatting in the same conversation for a few hundred turns.
  2. Watch the RSS of the API worker that serves each new reply. It jumps on each turn and keeps rising as the conversation grows. Python rarely returns this memory to the OS.

I measured it in isolation by calling the real TokenBufferMemory.load_history and get_thread_messages_length from main against PostgreSQL 15. The test conversation has one chain of turns, each with a 40-character query and a 411-character answer in Japanese, plus a 152-character system prompt. The saved prompts have the shape described above. Each measurement runs in a fresh process: one call, measuring RSS growth and the tracemalloc peak. The environment was Python 3.13, SQLAlchemy 2.0.49, psycopg2 2.9.12 and an Apple M5 Max.

Turns in conversation load_history RSS growth load_history time get_thread_messages_length RSS growth
100 24.7 MB 0.09 s 24.4 MB
200 107.7 MB 0.28 s 107.4 MB
300 243.2 MB 0.67 s 242.1 MB
500 693.8 MB 1.71 s 691.5 MB
700 1,088.5 MB 2.87 s 1,257.3 MB

The messages table was only 6.5 MB on disk at 500 turns. The cost comes from decoding the JSON into Python objects, and concurrent replies each pay it.

Measurement script

Run with the api virtualenv and PYTHONPATH=api, against a throwaway database such as docker run -d -e POSTGRES_PASSWORD=bench -e POSTGRES_DB=bench -p 55432:5432 postgres:15-alpine. Commands: python bench_history.py setup, then grow 100 and measure load_history, measure thread_length, then increase the turns.

import json, os, resource, sys, time, tracemalloc, uuid
from datetime import datetime, timedelta

os.environ.setdefault("STORAGE_TYPE", "opendal")
os.environ.setdefault("OPENDAL_SCHEME", "fs")
os.environ.setdefault("OPENDAL_FS_ROOT", "/tmp/dify-storage")

from sqlalchemy import create_engine, insert, text
from sqlalchemy.orm import Session

from models.base import TypeBase
from models.enums import ConversationFromSource
from models.model import App, AppMode, AppModelConfig, Conversation, Message, MessageFile

DSN = "postgresql+psycopg2://postgres:bench@localhost:55432/bench"
STATE = "state.json"
SYSTEM = "あなたは社内のヘルプデスク担当です。丁寧に、手順は番号付きで答えてください。" * 4
QUERY = "経費精算の申請で、領収書の写真をどこから添付すればいいですか? 前回の続きです。"
ANSWER = (
    "経費精算の画面で領収書を添付する手順は次のとおりです。1. 申請一覧から対象の申請を開きます。"
    "2. 明細の右側にある「添付」ボタンを押します。3. 写真を選ぶか、その場で撮影します。"
    "4. 金額と日付が読み取れるか確認し、保存を押します。読み取れない場合は撮り直してください。"
) * 3


def saved_prompt(turn):
    # What a chatbot stores in messages.message: system + earlier turns (500-message cap) + query.
    prompt = [{"role": "system", "text": SYSTEM, "files": []}]
    for _ in range(max(0, min(turn - 1, 500))):
        prompt += [{"role": "user", "text": QUERY, "files": []}, {"role": "assistant", "text": ANSWER, "files": []}]
    return prompt + [{"role": "user", "text": QUERY, "files": []}]


def setup(engine):
    with engine.begin() as conn:
        conn.execute(text('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'))
    tables = [App, AppModelConfig, Conversation, Message, MessageFile]
    TypeBase.metadata.create_all(engine, tables=[t.__table__ for t in tables])
    app_id, conv_id = str(uuid.uuid4()), str(uuid.uuid4())
    with Session(engine) as s:
        s.add(App(id=app_id, tenant_id=str(uuid.uuid4()), name="bench", mode=AppMode.CHAT,
                  enable_site=False, enable_api=False))
        s.add(Conversation(id=conv_id, app_id=app_id, mode=AppMode.CHAT, name="bench", override_model_configs="{}",
                           _inputs={}, from_source=ConversationFromSource.API))
        s.commit()
    json.dump({"app_id": app_id, "conversation_id": conv_id, "turns": 0, "last_id": None}, open(STATE, "w"))


def grow(engine, total):
    st = json.load(open(STATE))
    with engine.begin() as conn:
        for turn in range(st["turns"] + 1, total + 1):
            mid = str(uuid.uuid4())
            at = datetime(2026, 1, 1) + timedelta(minutes=turn)
            conn.execute(insert(Message.__table__).values(
                id=mid, app_id=st["app_id"], conversation_id=st["conversation_id"], inputs={}, query=QUERY,
                message=saved_prompt(turn), message_tokens=0, message_unit_price=0, answer=ANSWER,
                answer_tokens=300, answer_unit_price=0,
                parent_message_id=st["last_id"] or "00000000-0000-0000-0000-000000000000",
                currency="USD", from_source="api", created_at=at, updated_at=at))
            st["last_id"] = mid
    st["turns"] = total
    json.dump(st, open(STATE, "w"))


def measure(engine, target):
    from core.memory.token_buffer_memory import TokenBufferMemory
    from core.prompt.utils.get_thread_messages_length import get_thread_messages_length

    st = json.load(open(STATE))
    with Session(engine, expire_on_commit=False) as s:
        conv = s.get(Conversation, st["conversation_id"])
        s.expunge_all()
        rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        tracemalloc.start()
        started = time.perf_counter()
        if target == "load_history":
            TokenBufferMemory.load_history(conversation=conv, app_record=None, session=s, message_limit=None)
        else:
            get_thread_messages_length(st["conversation_id"], session=s)
        elapsed = time.perf_counter() - started
        peak = tracemalloc.get_traced_memory()[1]
        rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    # ru_maxrss is bytes on macOS and kilobytes on Linux.
    print(st["turns"], target, f"rss_growth={(rss_after - rss_before) / 1e6:.1f}MB",
          f"py_peak={peak / 1e6:.1f}MB", f"{elapsed:.3f}s")


if __name__ == "__main__":
    engine = create_engine(DSN)
    {"setup": lambda: setup(engine), "grow": lambda: grow(engine, int(sys.argv[2])),
     "measure": lambda: measure(engine, sys.argv[2])}[sys.argv[1]]()

✔️ Expected Behavior

The memory needed to build history should grow with the history that is actually used, not quadratically. Neither query needs Message.message or the other large columns.

❌ Actual Behavior

Each turn of a long conversation decodes every earlier turn's saved prompt. At 500 turns, one reply's history load adds about 690 MB of RSS to the worker and takes 1.7 s. At 700 turns, the chatflow length helper alone adds about 1.26 GB.

Selecting only the needed columns with load_only produces the same history. With that change, RSS growth falls to 3.9 MB and the time to 0.04 s at 500 turns. At 700 turns, both functions stay under 4.2 MB. I'll open a PR with this change.

BaseAgentRunner.organize_agent_history (api/core/agent/base_agent_runner.py) loads whole rows for the entire conversation in the same way. I left it out of the PR to keep it small and can follow up separately.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions