agent-zero icon indicating copy to clipboard operation
agent-zero copied to clipboard

Chat History File Size Bloat (`history.metadata`) in v2 causes A0 crashes and instability when the chat.json reaches ~127MB size

Open sumer-man opened this issue 5 months ago • 5 comments

Got this after thorough investigation with deep-wiki Reaching 127MB took but a ~4h of intense session with Claude 4.8, and this one's quite token-efficient. Affecting all, not just migrated chats. Someone's gotta take a look. Update: Temporary workaround provided in the comments (a0v2_chat_debloater) UPDATE 2: While the script will debloat your existing chats, you can patch /a0/helpers/history.py to prevent the bloat (history.metadata) from being serialized. See my other comment.

Problem Description

When a chat created in Agent Zero v1.17 is copied directly to v2's chats/ directory, the chat.json file experiences massive file size bloat (from ~2MB to 127MB in one reported case). This causes Agent Zero v2 to crash when attempting to write to the chat file, with no error logs generated. The crash appears to occur during the JSON serialization process, likely due to memory exhaustion.

Steps to Reproduce

  1. Create a chat in Agent Zero v1.17 with substantial conversation history
  2. Copy the chat directory from v1.17's usr/chats/<chat_id>/ to v2's usr/chats/<chat_id>/ using a file manager
  3. Open the chat in v2's WebUI
  4. Use the chat normally for a few days
  5. Observe that the chat.json file grows significantly (e.g., from 2MB to 127MB)
  6. Attempt to save the chat or perform any operation that writes to chat.json
  7. Agent Zero crashes without error logs

Root Cause Analysis

The bloat is caused by changes in the history serialization format between v1.17 and v2. When v2 loads a v1.17 chat and re-serializes it, it adds new fields that accumulate significant data:

1. Message Metadata Addition

v2's Message class includes a metadata field that stores LLM response information, tool call details, and execution context. This field is absent in v1.17:

v2 Topic.add_message() 1 :

def add_message(
    self,
    ai: bool,
    content: MessageContent,
    tokens: int = 0,
    id: str = "",
    metadata: dict[str, Any] | None = None,  # v2 addition
    sequence: int = 0,  # v2 addition
) -> Message:

v2 History.add_message() 2 :

def add_message(
    self,
    ai: bool,
    content: MessageContent,
    tokens: int = 0,
    id: str = "",
    metadata: dict[str, Any] | None = None,
) -> Message:
    self.counter += 1
    return self.current.add_message(
        ai,
        content=content,
        tokens=tokens,
        id=id,
        metadata=metadata,
        sequence=self.counter,
    )

The test file confirms that v2 messages include metadata like response IDs and provider model keys 3 .

2. Sequence Tracking

v2 added a sequence parameter to track message order within the history. Every message in v2 has a sequence number that v1.17 doesn't store, adding to the file size.

3. Agent Profile Serialization

v2's _serialize_agent() function includes an agent_profile field that v1.17 lacks:

v2 _serialize_agent() 4 :

def _serialize_agent(agent: Agent):
    data = {k: v for k, v in agent.data.items() if not k.startswith("_")}
    history = agent.history.serialize()
    return {
        "number": agent.number,
        "agent_profile": str(getattr(agent.config, "profile", "") or ""),  # v2 addition
        "data": data,
        "history": history,
    }

v1.17 _serialize_agent() (from user-provided code):

def _serialize_agent(agent: Agent):
    data = {k: v for k, v in agent.data.items() if not k.startswith("_")}
    history = agent.history.serialize()
    return {
        "number": agent.number,
        "data": data,
        "history": history,
    }

Evidence

When the bloated v2 chat was exported from v2 and re-imported into v1.17, then exported again from v1.17, the size reduction was dramatic:

  • Original v2 export: 127MB (120,169,902 chars)
  • After v1.17 re-export: 5.3MB (5,220,594 chars)
  • Size reduction: 95.66%

Diff analysis showed:

  • root.agents[0].agent_profile removed
  • root.agents[1].agent_profile removed
  • root.agents[0].history truncated from 16,753,035 to 324,725 chars
  • root.agents[1].history truncated from 99,481,181 to 960,227 chars

Workaround

The current workaround is to use v1.17 as a debloating tool:

  1. Export the bloated chat from v2
  2. Import it into v1.17
  3. Export it again from v1.17
  4. Import the cleaned version back into v2

This works because v1.17's serialization format doesn't include the metadata, sequence, and agent_profile fields that cause the bloat.

Suggested Fixes

  1. Add Migration Logic: Implement a migration function in v2 that detects v1.17 chat files and converts them to v2 format without adding excessive metadata to existing messages.

  2. Metadata Compression: Consider compressing or selectively storing metadata to reduce file size impact.

  3. Optional Metadata: Make metadata storage configurable or optional for users who don't need the detailed tracking.

  4. Backward Compatibility: Ensure that v2 can load and save v1.17 chats without automatically expanding them with the new serialization format.

  5. Add File Size Monitoring: Implement warnings or limits on chat file sizes to prevent this issue from occurring silently.

Impact

This issue affects users upgrading from v1.17 to v2 who manually migrate their chats by copying directories. The bloat can cause:

  • Application crashes during chat operations
  • Excessive disk space usage
  • Performance degradation
  • Data loss if crashes occur during writes

Related Code Files

  • helpers/history.py - Message, Topic, and History serialization
  • helpers/persist_chat.py - Agent and context serialization
  • tests/test_responses_architecture.py - Metadata serialization tests

sumer-man avatar Jun 29 '26 22:06 sumer-man

Update: Looking at all other chats/dev projects I had in A0v2 they all look MASSIVE in comparison to v1.17. Definitely an issue affecting all chats created in A0v2.

sumer-man avatar Jun 29 '26 23:06 sumer-man

Temporary workaround till (if ever) the bloat is addressed: a0v2_chat_debloater.py

#!/usr/bin/env python3  
"""  
Tool to strip metadata and sequence fields from Agent Zero v2 chat files.  
Reduces file size by removing verbose message metadata while preserving conversation content.  
Usage:

# debloat a single chat file (creates backup)  
python a0v2_chat_debloater.py usr/chats/<chat_id>/chat.json  
  
# debloat to a new file  
python a0v2_chat_debloater.py usr/chats/<chat_id>/chat.json cleaned_chat.json  
  
# debloat all chats in directory  
python a0v2_chat_debloater.py usr/chats --directory  
  
# Also remove agent_profile fields for ~v1.17 compatibility  
python a0v2_chat_debloater.py usr/chats/<chat_id>/chat.json --remove-agent-profiles

The script creates automatic backups when overwriting files. 
After migration, you can load the cleaned chats via the WebUI's "Load Chat" feature
The cleaned chats will be compatible with v2's deserialization logic, 
which handles missing metadata gracefully.

License:
MIT

"""  
  
import json  
import argparse  
import sys  
from pathlib import Path  
from typing import Any, Dict  
  
  
def strip_message_metadata(msg_dict: Dict[str, Any]) -> Dict[str, Any]:  
    """Remove metadata and sequence fields from a message dictionary."""  
    cleaned = msg_dict.copy()  
    cleaned.pop('metadata', None)  
    cleaned.pop('sequence', None)  
    return cleaned  
  
  
def strip_topic_metadata(topic_dict: Dict[str, Any]) -> Dict[str, Any]:  
    """Remove metadata from all messages in a topic."""  
    cleaned = topic_dict.copy()  
    if 'messages' in cleaned:  
        cleaned['messages'] = [strip_message_metadata(msg) for msg in cleaned['messages']]  
    return cleaned  
  
  
def strip_bulk_metadata(bulk_dict: Dict[str, Any]) -> Dict[str, Any]:  
    """Remove metadata from all records in a bulk (recursively handles nested topics/bulks)."""  
    cleaned = bulk_dict.copy()  
    if 'records' in cleaned:  
        cleaned_records = []  
        for record in cleaned['records']:  
            if record.get('_cls') == 'Topic':  
                cleaned_records.append(strip_topic_metadata(record))  
            elif record.get('_cls') == 'Bulk':  
                cleaned_records.append(strip_bulk_metadata(record))  
            elif record.get('_cls') == 'Message':  
                cleaned_records.append(strip_message_metadata(record))  
            else:  
                cleaned_records.append(record)  
        cleaned['records'] = cleaned_records  
    return cleaned  
  
  
def strip_history_metadata(history_dict: Dict[str, Any]) -> Dict[str, Any]:  
    """Remove metadata from entire history structure."""  
    cleaned = history_dict.copy()  
      
    # Clean topics  
    if 'topics' in cleaned:  
        cleaned['topics'] = [strip_topic_metadata(topic) for topic in cleaned['topics']]  
      
    # Clean bulks  
    if 'bulks' in cleaned:  
        cleaned['bulks'] = [strip_bulk_metadata(bulk) for bulk in cleaned['bulks']]  
      
    # Clean current topic  
    if 'current' in cleaned:  
        cleaned['current'] = strip_topic_metadata(cleaned['current'])  
      
    return cleaned  
  
  
def debloat_chat_file(input_file: Path, output_file: Path, remove_agent_profiles: bool = False) -> None:  
    """debloat a chat file by stripping metadata from history."""  
    try:  
        with open(input_file, 'r', encoding='utf-8') as f:  
            data = json.load(f)  
    except json.JSONDecodeError as e:  
        print(f"Error: Invalid JSON in {input_file}: {e}")  
        sys.exit(1)  
    except FileNotFoundError:  
        print(f"Error: File not found: {input_file}")  
        sys.exit(1)  
  
    original_size = input_file.stat().st_size  
  
    # Process each agent's history  
    if 'agents' in data:  
        for agent in data['agents']:  
            if 'history' in agent:  
                try:  
                    history_dict = json.loads(agent['history'])  
                    cleaned_history = strip_history_metadata(history_dict)  
                    agent['history'] = json.dumps(cleaned_history, ensure_ascii=False)  
                except json.JSONDecodeError:  
                    print(f"Warning: Could not parse history for agent {agent.get('number', 'unknown')}")  
      
    # Optionally remove agent_profile fields  
    if remove_agent_profiles:  
        for agent in data.get('agents', []):  
            agent.pop('agent_profile', None)  
  
    # Write cleaned output  
    with open(output_file, 'w', encoding='utf-8') as f:  
        json.dump(data, f, indent=2, ensure_ascii=False)  
  
    cleaned_size = output_file.stat().st_size  
    reduction = (1 - cleaned_size / original_size) * 100  
  
    print(f"Original size: {original_size / (1024*1024):.2f} MB")  
    print(f"Cleaned size: {cleaned_size / (1024*1024):.2f} MB")  
    print(f"Size reduction: {reduction:.1f}%")  
  
  
def debloat_chat_directory(chats_dir: Path, remove_agent_profiles: bool = False) -> None:  
    """debloat all chat.json files in a directory."""  
    if not chats_dir.exists():  
        print(f"Error: Directory not found: {chats_dir}")  
        sys.exit(1)  
  
    chat_files = list(chats_dir.glob("*/chat.json"))  
    if not chat_files:  
        print(f"No chat.json files found in {chats_dir}")  
        return  
  
    print(f"Found {len(chat_files)} chat files to debloat")  
      
    for chat_file in chat_files:  
        print(f"\nProcessing: {chat_file.parent.name}")  
        backup_file = chat_file.with_suffix('.json.backup')  
          
        # Create backup  
        import shutil  
        shutil.copy2(chat_file, backup_file)  
          
        # debloat  
        debloat_chat_file(chat_file, chat_file, remove_agent_profiles)  
  
  
def main():  
    parser = argparse.ArgumentParser(  
        description='Strip metadata from Agent Zero v2 chat files to reduce file size'  
    )  
    parser.add_argument(  
        'input',  
        type=Path,  
        help='Input chat.json file or chats directory'  
    )  
    parser.add_argument(  
        'output',  
        type=Path,  
        nargs='?',  
        help='Output file (default: overwrites input with backup)'  
    )  
    parser.add_argument(  
        '--remove-agent-profiles',  
        action='store_true',  
        help='Also remove agent_profile fields (v1.17 compatibility)'  
    )  
    parser.add_argument(  
        '--directory',  
        action='store_true',  
        help='Treat input as directory and debloat all chat.json files'  
    )  
  
    args = parser.parse_args()  
  
    if args.directory:  
        debloat_chat_directory(args.input, args.remove_agent_profiles)  
    else:  
        if args.output is None:  
            args.output = args.input  
          
        # Create backup if overwriting  
        if args.input == args.output:  
            backup_file = args.input.with_suffix('.json.backup')  
            import shutil  
            shutil.copy2(args.input, backup_file)  
            print(f"Backup created: {backup_file}")  
          
        debloat_chat_file(args.input, args.output, args.remove_agent_profiles)  
  
  
if __name__ == '__main__':  
    main()

Tested, working. Use at your own peril. Here's an idea - how about A0 stores the metadata in a separate file, and loads it selectively only when it actually needs it?

sumer-man avatar Jun 30 '26 00:06 sumer-man

Temp. Solution 2. Patch /a0/helpers/history.py:

STRIP_METADATA_ON_SERIALIZE = True  # Top of the file, with other constants. Can be set via environment or config.

# then find and replace this fn:
    def to_dict(self):
        data = {
            "_cls": "Message",
            "id": self.id,
            "ai": self.ai,
            "content": self.content,
            "sequence": self.sequence,
            "summary": self.summary,
            "tokens": self.tokens,
        }
        if not STRIP_METADATA_ON_SERIALIZE:  
            data["metadata"] = self.metadata  
            
        return data

sumer-man avatar Jul 01 '26 20:07 sumer-man

Thank you @sumer-man for both investigating this and for the script. We have reproduced the issue and prepared a permanent fix that will be in v2.5.

Every assistant message was persisting the complete accumulated prompt in responses.input_items, with duplicate response, reasoning, and raw provider data, so even more than just the observed metadata fields. For Chat Completions providers chat history the size was growing quadratically.

Synthetic 100-turns comparison:

  • Conversation content: 406,881 bytes
  • Previous history: 21,390,101 bytes — 52.57×
  • After fixing history: 644,871 bytes — 1.58×

sequence and agent_profile are retained because they are required functionality and are not material contributors to the bloat.

Fixed in commit https://github.com/3clyp50/agent-zero/commit/7b216c63437973592ee4d75c0d933d4f7493e43a

Existing chats that can still be loaded will be repaired automatically when loaded after updating to the new version. If a chat is too large to load or creates issues, the debloater remains a recovery path.

The fix is verified but only available on ready branch for now. We will update this issue when v2.5 lands on main.

Thank you again Alessandro

3clyp50 avatar Jul 14 '26 18:07 3clyp50

Closing due to inactivity of 90 days.

github-actions[bot] avatar Oct 13 '26 03:10 github-actions[bot]