Skip to content

[Bug] Agent history loads every turn's saved prompt for the whole conversation, so API memory grows quadratically #44528

Open

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 bb1522067623c81a5bb266b205aac8d5953b0c46 (2026-10-22).

Cloud or Self Hosted

Self Hosted (Source)

Steps to reproduce

This is the agent-app counterpart of #44520, which covers chat history and the chatflow thread-length helper.

On every agent reply, BaseAgentRunner.organize_agent_history (api/core/agent/base_agent_runner.py) loads every Message row of the conversation, with no limit, as whole rows. A whole row includes Message.message. The FC and CoT runners publish their final prompt_messages in QueueMessageEndEvent, and EasyUIBasedGenerateTaskPipeline._save_message stores that prompt there. It holds the system prompt, every earlier turn, the query and that turn's tool calls and results. So the row of turn n holds a copy of the previous n − 1 turns, and building history reads about n²/2 turns of text. The method does not use this column. It rebuilds history from query, answer and the agent thoughts, and needs only id, conversation_id, parent_message_id, query and answer from Message.

To reproduce:

  1. Create an Agent 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.

I measured it in isolation by calling the real organize_agent_history from main against PostgreSQL 15. The setup is the same as in #44520: one chain of turns, each with a 40-character query and a 411-character answer in Japanese, plus a 152-character system prompt. Saved prompts hold the earlier turns with no cap and no tool output, so real agent rows are larger. Each measurement runs in a fresh process: one call, measuring RSS growth and duration. The environment was Python 3.13, SQLAlchemy 2.0.49, psycopg2 2.9.12 and an Apple M5 Max.

Turns in conversation RSS growth Time
100 26.5 MB 0.19 s
200 106.7 MB 0.49 s
300 240.6 MB 0.93 s
500 692.8 MB 2.13 s
700 1,355.6 MB 4.17 s
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_agent.py setup, then grow 100 and measure, then increase the turns.

"""Measure memory used by BaseAgentRunner.organize_agent_history as one agent conversation grows.

Usage (Dify api venv, PYTHONPATH=dify/api, Postgres from the chat benchmark on :55432):
  python bench_agent.py setup
  python bench_agent.py grow <total_turns>
  python bench_agent.py measure
"""

import json
import os
import resource
import sys
import time
import tracemalloc
import 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,
    MessageAgentThought,
    MessageFile,
)

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


def saved_prompt(turn: int) -> list[dict]:
    # What an agent app stores in messages.message: system + every earlier turn (no cap) + query.
    # Tool calls and observations would make it larger; this keeps the same text as the chat benchmark.
    prompt = [{"role": "system", "text": SYSTEM, "files": []}]
    for _ in range(turn - 1):
        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, MessageAgentThought]
    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-agent",
                mode=AppMode.AGENT_CHAT,
                enable_site=False,
                enable_api=False,
            )
        )
        s.add(
            Conversation(
                id=conv_id,
                app_id=app_id,
                mode=AppMode.AGENT_CHAT,
                name="bench-agent",
                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: int):
    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",
                    agent_based=True,
                    created_at=at,
                    updated_at=at,
                )
            )
            st["last_id"] = mid
    st["turns"] = total
    json.dump(st, open(STATE, "w"))


def measure(engine):
    from core.agent.base_agent_runner import BaseAgentRunner

    st = json.load(open(STATE))
    # The newest row plays the message being generated; organize_agent_history skips it.
    current = Message(id=st["last_id"], conversation_id=st["conversation_id"])
    runner = BaseAgentRunner.__new__(BaseAgentRunner)
    runner.message = current
    runner.tenant_id = str(uuid.uuid4())
    with Session(engine, expire_on_commit=False) as s:
        rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        tracemalloc.start()
        started = time.perf_counter()
        history = runner.organize_agent_history([], session=s)
        elapsed = time.perf_counter() - started
        peak = tracemalloc.get_traced_memory()[1]
        tracemalloc.stop()
        rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    # macOS reports ru_maxrss in bytes
    print(
        json.dumps(
            {
                "turns": st["turns"],
                "prompts": len(history),
                "py_peak_mb": round(peak / 1e6, 1),
                "rss_growth_mb": round((rss_after - rss_before) / 1e6, 1),
                "seconds": round(elapsed, 3),
            }
        )
    )


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

✔️ Expected Behavior

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

❌ Actual Behavior

Each reply in a long agent conversation decodes every earlier turn's saved prompt. At 700 turns, one reply's history build adds about 1.36 GB of RSS and takes 4.2 s.

Selecting only the needed columns with load_only produces the same history. With that change, RSS growth falls to 10.3 MB and the time to 0.80 s at 700 turns. The remaining time is the existing per-message MessageFile and MessageAgentThought queries. I'll open a PR with this change.

Activity

  1. added
    1.17.1
    on Nov 20, 2026
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

    1.17.1

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions