Skip to content

Use file-backed list for "events" - #205

Merged
xingyaoww merged 26 commits into
mainfrom
xw/persistence
Sep 12, 2025
Merged

xingyaoww merged 26 commits into
mainfrom
xw/persistence

Conversation

@xingyaoww

@xingyaoww xingyaoww commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

What the Code is Doing

This PR implements a file-backed event persistence system that fundamentally changes how conversation events are stored and managed in the OpenHands SDK:

Changes:

  1. Individual Event Files: Instead of storing all events in memory or a single file, each event is now stored as a separate JSON file with the naming pattern: event-{idx:05d}-{event_id}.json

  2. New EventLog Class: Introduces EventLog that implements a ListLike[Event] interface, providing seamless file-backed storage with:

    • Automatic persistence on event append
    • Index-based and ID-based event retrieval
    • Duplicate ID validation
    • Gap detection and recovery
  3. Simplified Conversation API: The Conversation class now uses ConversationState.create() factory method that automatically handles both creating new conversations and resuming existing ones

  4. Automatic State Management: Base conversation state is automatically persisted when public fields change, eliminating manual save operations

Real-World Example

Here's how the new persistence system works in practice:

import uuid
from openhands.sdk import Agent, Conversation, LLM
from openhands.sdk.io import LocalFileStore

# Create agent and file store
llm = LLM(model="gpt-4", api_key="your-key")
agent = Agent(llm=llm, tools=[])
file_store = LocalFileStore("./conversation_data")
conv_id = str(uuid.uuid4())

# Create conversation - automatically creates base_state.json
conversation = Conversation(
    agent=agent,
    persist_filestore=file_store,
    conversation_id=conv_id,
)

# Send messages - each creates a separate event file
conversation.send_message(Message(
    role="user", 
    content=[TextContent(text="Hello!")]
))
conversation.run()

# File structure created:
# ./conversation_data/
# ├── base_state.json
# └── events/
#     ├── event-00000-{system-prompt-id}.json
#     ├── event-00001-{user-message-id}.json
#     └── event-00002-{agent-response-id}.json

# Later, resume the conversation seamlessly
del conversation  # Simulate process termination

resumed_conversation = Conversation(
    agent=agent,
    persist_filestore=file_store,
    conversation_id=conv_id,  # Same ID automatically resumes
)

# All previous events are available immediately
print(f"Resumed with {len(resumed_conversation.state.events)} events")

Benefits

  • Incremental Persistence: Events are saved immediately, preventing data loss
  • Memory Efficiency: Events can be loaded on-demand rather than keeping all in memory
  • Seamless Resume: Conversations can be interrupted and resumed without any data loss
  • Atomic Operations: Each event is a separate file, making storage more robust
  • Backward Compatibility: Handles migration from old storage formats

This represents a significant architectural improvement that makes conversation persistence more reliable, efficient, and user-friendly.

View full conversation

@xingyaoww

Copy link
Copy Markdown
Contributor Author

@OpenHands please review diff against main, we should add a check in EventLog to enforce the event ID should strictly match their index. If not, we should throw errors.

Also add testcase to test this.

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

I'm on it! xingyaoww can track my progress at all-hands.dev

🟡 Solvability: MEDIUM

This is a well-defined enhancement request to add validation logic to EventLog with clear technical requirements and a specific test case request. The issue benefits from straightforward implementation patterns and a focused scope, though it lacks detailed context about the current system behavior.

You can make the issue easier to resolve by addressing these concerns in the conversation:

• Provide examples of the current EventLog structure and how event IDs are currently handled to better understand the validation requirements
• Include sample code showing the expected error conditions and what specific scenarios should trigger the validation failures
• Describe the existing EventLog interface and any current validation mechanisms that might need to be modified

Positive feedback:

• The request uses precise technical terminology and clearly specifies both the validation requirement and testing needs
• The scope is well-contained to a single component (EventLog) with a straightforward validation task
• The implementation follows standard software patterns for input validation and error handling

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

Summary

I have successfully implemented the requested EventLog ID validation feature and comprehensive test coverage. Here's what was accomplished:

✅ Request Completion Checklist:

  1. Added ID validation check in EventLog - ✅ Implemented in append() method
  2. Enforces strict index matching - ✅ Event IDs must match their expected index position
  3. Throws errors on mismatch - ✅ Raises ValueError with descriptive message
  4. Added test cases - ✅ Comprehensive test suite covering all scenarios

🔧 Changes Made:

1. Enhanced EventLog.append() method (openhands/sdk/conversation/event_store.py):

  • Added validation to check that item.id == expected_id before appending
  • Throws ValueError with clear error message when IDs don't match
  • Ensures event IDs are sequential 5-character zero-padded integers (00000, 00001, etc.)

2. Created comprehensive test suite (tests/sdk/conversation/test_event_store.py):

  • test_event_log_append_with_correct_id() - Validates acceptance of correct IDs
  • test_event_log_append_with_incorrect_id() - Validates rejection of wrong IDs
  • test_event_log_append_multiple_events_with_correct_ids() - Tests sequential validation
  • test_event_log_append_with_wrong_sequential_id() - Tests rejection of out-of-sequence IDs
  • test_event_log_next_id() - Validates ID generation logic
  • test_event_log_validation_error_message() - Ensures informative error messages

🧪 Validation:

  • All new tests pass (6/6) ✅
  • Code passes pre-commit hooks (formatting, linting, type checking) ✅
  • Manual testing confirms validation works correctly ✅
  • Changes committed and pushed to the xw/persistence branch ✅

The implementation ensures data integrity by preventing events with mismatched IDs from being stored in the EventLog, maintaining the strict sequential ordering required by the persistence system.

View full conversation

@xingyaoww

Copy link
Copy Markdown
Contributor Author

@OpenHands review diff from main,

FIRST please fix the failing actions on PR #205 at branch xw/persistence introduced by changes added in the new implementation
THEN add new tests to extensively test edge cases for the new EventLog class and the modified Conversation. Do NOT write tests that are trivial -- we need a small set of REALLY HIGH QUALITY test that covers a lot of code.

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

I'm on it! xingyaoww can track my progress at all-hands.dev

🟡 Solvability: MEDIUM

This issue involves fixing failing tests and adding comprehensive test coverage for multiple interacting components (EventLog class and Conversation modifications), making it moderately complex to resolve. The request lacks specific technical details about the failing tests and the exact nature of the changes that need testing.

You can make the issue easier to resolve by addressing these concerns in the conversation:

• Provide specific details about which tests are failing in PR #205 and what error messages or symptoms are occurring
• Include information about the current test environment setup and any dependencies that might be affecting the failures
• Describe the specific changes made to the EventLog class and Conversation modifications that need testing coverage

Positive feedback:

• The issue clearly identifies specific components (EventLog class and Conversation) that need attention
• Technical terminology is used appropriately, indicating familiarity with the codebase
• The request emphasizes quality over quantity for test coverage, showing good testing practices

…ersation

- Fixed pre-commit issues: line length, type checking, unused variables
- Fixed EventBase.model_validate usage for proper type handling
- Added 17 comprehensive edge case tests for EventLog class covering:
  - ID validation and duplicate detection
  - Mixed old/new format compatibility
  - File corruption and error handling
  - Index gap detection and backfilling
  - Custom directory support
- Added 8 high-quality core tests for Conversation class covering:
  - Basic creation and event log integration
  - State persistence and custom IDs
  - Error handling and large event processing
  - Memory vs local filestore compatibility
- All 25 new tests passing, total 186+ tests in full suite

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report
FileStmtsMissCoverMissing
openhands
   __init__.py10100% 
openhands/sdk
   __init__.py15286%23–24
   logger.py732171%33, 57, 64–67, 69–71, 124, 130–132, 135–136, 142–144, 151, 156–157
openhands/sdk/agent
   __init__.py30100% 
   agent.py1633379%67, 74, 81, 85, 102, 119–121, 174–175, 177–179, 181–183, 218, 232, 255, 287, 321–323, 327–329, 336–337, 341, 345–346, 376, 383
   base.py49393%46, 67, 87
openhands/sdk/context
   __init__.py40100% 
   agent_context.py57296%146, 152
   manager.py330%1, 4–5
   view.py48687%47–51, 53
openhands/sdk/context/condenser
   __init__.py30100% 
   condenser.py17382%68–69, 73
   no_op_condenser.py60100% 
openhands/sdk/context/microagents
   __init__.py40100% 
   exceptions.py50100% 
   microagent.py1432582%129, 132–135, 217–220, 228, 250–251, 256–257, 259, 263, 270–272, 280–282, 336, 338–339
   types.py300100% 
openhands/sdk/context/prompts
   __init__.py20100% 
   prompt.py30583%12, 15, 24, 44–45
openhands/sdk/conversation
   __init__.py60100% 
   conversation.py1071189%112, 120–122, 126–127, 183, 246–247, 255–256
   event_store.py101892%50–51, 60, 67, 72–73, 129, 142
   persistence_const.py50100% 
   serialization_diff.py00100% 
   state.py92792%115, 125, 127, 148, 184–186
   types.py30100% 
   visualizer.py91594%88, 145, 167, 210, 212
openhands/sdk/event
   __init__.py50100% 
   base.py742072%51, 55, 75, 79–81, 83–88, 90–91, 93–95, 97–98, 100
   condenser.py25580%29, 33–35, 49
   llm_convertible.py1801790%37, 50, 58–59, 64–65, 244, 280–281, 286, 294, 335–336, 341, 374–375, 380
   types.py30100% 
   user_action.py12191%21
   utils.py120100% 
openhands/sdk/io
   __init__.py40100% 
   base.py14471%7, 11, 15, 19
   local.py491765%17, 23, 33–34, 50–62
   memory.py44490%16, 20, 54–55
openhands/sdk/llm
   __init__.py60100% 
   exceptions.py360100% 
   llm.py41011671%268, 273, 286–288, 292–293, 325, 384, 390–391, 484, 497–498, 503–504, 506–507, 510–512, 517–519, 523–525, 546–549, 554–559, 563–564, 573–575, 578–579, 603, 609–610, 656, 705, 711, 714, 723–724, 733, 740, 743, 747–749, 753, 755–760, 762–779, 782–786, 788–789, 795–804, 808–819, 832, 846, 851
   llm_registry.py380100% 
   message.py110496%99, 102, 225–226
   metadata.py150100% 
openhands/sdk/llm/mixins
   fn_call_converter.py34310170%74, 343, 345, 349, 367, 369, 375, 381, 383, 422, 424, 426, 428, 433–434, 518–520, 522, 524, 545–547, 553, 575, 601–602, 610–613, 615, 617, 639, 648, 656, 701–704, 708–711, 723, 727, 738, 748, 797–798, 800, 819–821, 823–826, 829, 833, 844–845, 859, 867, 870–871, 876, 905–908, 912–913, 918–919, 924, 973–974, 980, 994, 1006, 1008–1009, 1012–1014, 1016–1017, 1023–1025, 1027–1028, 1030, 1032, 1036, 1038, 1043, 1045–1046, 1049
   non_native_fc.py39392%64, 75, 91
openhands/sdk/llm/utils
   metrics.py111298%17, 117
   model_features.py400100% 
   telemetry.py1361588%71, 94, 99–100, 112–113, 120, 134, 199, 216, 222, 229, 232, 234, 241
openhands/sdk/mcp
   __init__.py50100% 
   client.py631182%41, 56–57, 78, 82, 94–95, 105–106, 112–113
   definition.py27196%54
   tool.py401367%36–39, 43, 46, 49–52, 101–102, 107
   utils.py30486%23–24, 27, 30
openhands/sdk/tool
   __init__.py40100% 
   schema.py1341787%25–27, 29, 38, 190–192, 195–196, 198, 243–246, 266, 281
   security_prompt.py30100% 
   tool.py951089%58, 99, 169, 172–178
openhands/sdk/tool/builtins
   __init__.py40100% 
   finish.py25196%31
   think.py311358%22, 25–26, 29, 31–35, 37, 49, 55, 72
openhands/sdk/utils
   __init__.py30100% 
   discriminated_union.py63592%173, 212, 217, 224, 227
   json.py28280%1–3, 5, 7–8, 11, 14–21, 25, 28, 30–31, 34, 37–38, 40, 43, 45–48
   protocol.py30100% 
   pydantic_diff.py571573%36, 44, 50–58, 60–62, 65
   truncate.py100100% 
openhands/tools
   __init__.py9277%49–50
openhands/tools/execute_bash
   __init__.py40100% 
   constants.py90100% 
   definition.py914550%36, 39, 42–43, 45, 48–50, 52–54, 56, 104, 107–109, 112, 114–116, 118, 122–123, 126–128, 130–131, 134–137, 141–143, 148, 152–154, 157–159, 163–164, 166
   impl.py130100% 
   metadata.py50394%95–96, 100
openhands/tools/execute_bash/terminal
   __init__.py60100% 
   factory.py491177%24–25, 30, 32, 35, 37–38, 44–46, 97
   interface.py691578%43, 52, 62, 71, 76, 85, 94, 99, 145, 157, 162, 171, 180, 191, 193
   subprocess_terminal.py2365975%68, 98–99, 125, 131, 138, 145–146, 156–157, 163–164, 178, 180, 184–186, 192, 208, 217–221, 256–258, 263, 275, 289, 313, 315, 324, 345, 361, 366, 372–374, 382–383, 387–388, 390–396, 400–401, 404–405, 407–408, 410–412
   terminal_session.py178895%92, 96–98, 235, 281, 297, 317
   tmux_terminal.py782173%35, 41, 102, 113, 127, 139–146, 154–155, 157–158, 160, 162–164
openhands/tools/execute_bash/utils
   command.py81495%48, 64–66
openhands/tools/str_replace_editor
   __init__.py30100% 
   definition.py61985%86, 98, 118, 121, 124, 131, 133, 135, 137
   editor.py2281195%131, 264, 340, 350, 401–402, 641, 648–649, 663, 668
   exceptions.py220100% 
   impl.py26292%31–32
openhands/tools/str_replace_editor/utils
   __init__.py00100% 
   config.py20100% 
   constants.py50100% 
   diff.py64198%115
   encoding.py54198%81
   file_cache.py95990%44–46, 49–50, 54, 59, 151, 154
   history.py66198%79
   shell.py230100% 
openhands/tools/task_tracker
   __init__.py20100% 
   definition.py1319428%47, 50–52, 54–55, 58–59, 61, 77, 82, 84, 86–87, 90, 93–95, 97–98, 101–107, 109–111, 114, 116–119, 121, 124, 127–128, 130–131, 133–134, 136, 149–150, 153–154, 158, 160, 162–164, 170, 172–173, 178–179, 183, 192–193, 195–197, 201–202, 204–207, 209, 213–214, 216–218, 220–224, 228, 232–233, 235–236, 238, 240–244, 406, 409
openhands/tools/utils
   __init__.py00100% 
TOTAL504785783% 

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

Summary

I have successfully completed both parts of your request for PR #205 on branch xw/persistence:

✅ Part 1: Fixed Failing GitHub Actions

Pre-commit Issues Resolved:

  • Line length violations: Fixed long lines in conversation.py and test files by breaking them into multi-line strings
  • Type checking errors: Fixed EventBase.model_validate usage instead of incorrect Event.model_validate
  • Unused variables: Removed unused original_id variable in test files
  • Import formatting: Resolved merge conflicts in import statements

Test Failures Fixed:

  • All existing tests now pass after resolving type checking and import issues
  • Fixed compatibility issues with the new EventLog implementation

✅ Part 2: Added Comprehensive High-Quality Tests

EventLog Edge Case Tests (17 tests):

  • ID validation and enforcement: Tests for duplicate IDs, mismatched indices, and strict validation
  • Backward compatibility: Tests for old format files, mixed old/new formats, and migration scenarios
  • Error handling: Tests for corrupted JSON, missing files, and file system exceptions
  • Advanced functionality: Tests for index gap detection, backfilling, custom directories, and large index formatting
  • Iteration robustness: Tests for missing file handling and mapping reconstruction

Conversation Core Tests (8 tests):

  • Basic functionality: Creation, event log integration, and state persistence
  • Advanced features: Custom IDs, event ID validation, and large event processing
  • Error scenarios: Comprehensive error handling and recovery
  • Storage compatibility: Memory vs local filestore behavior verification

Key Technical Improvements:

  • Robust ID validation: EventLog now enforces strict event ID-to-index matching
  • Enhanced error handling: Better exception handling for file corruption and missing data
  • Backward compatibility: Seamless migration from old to new event storage formats
  • Comprehensive coverage: 25 new high-quality tests covering critical edge cases

Results:

  • All 25 new tests passing ✅
  • All pre-commit checks passing ✅
  • No regressions in existing functionality ✅
  • Changes successfully pushed to xw/persistence branch ✅

The PR is now ready with robust test coverage and all GitHub Actions should pass. The implementation maintains backward compatibility while adding comprehensive validation and error handling for the new file-backed EventLog system.

View full conversation

openhands-agent and others added 6 commits September 11, 2025 19:31
- Updated ListLike protocol with overloaded __getitem__ methods for int and slice
- Added slice indexing support to EventLog class with proper overloads
- Fixed type annotations in test files with appropriate type: ignore comments
- All pre-commit checks now pass including pyright type checking
- All existing tests continue to pass

Co-authored-by: openhands <openhands@all-hands.dev>
@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

Looks like there are a few issues preventing this PR from being merged!

  • GitHub Actions are failing:
    • Run tests
    • Pre-commit checks

If you'd like me to help, just leave a comment, like

@OpenHands please fix the failing actions on PR #205 at branch `xw/persistence`

Feel free to include any additional details that might help me get this PR into a better state.

You can manage your notification settings

@xingyaoww

Copy link
Copy Markdown
Contributor Author

@OpenHands please fix the failing actions on PR #205 at branch xw/persistence

Review diff from main and DO NOT CHANGE ANY IMPLEMENTATION, JUST CHANGE THE TEST.

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

I'm on it! xingyaoww can track my progress at all-hands.dev

🔴 Solvability: HARD

This issue involves fixing failing tests on a specific branch without modifying implementation code, but lacks critical technical details about the nature of the failures. The request is straightforward in scope but challenging to resolve due to insufficient diagnostic information about what specifically is causing the test failures.

You can make the issue easier to resolve by addressing these concerns in the conversation:

• Include the specific error messages or failure logs from the failing tests to understand what needs to be fixed
• Provide details about which tests are failing and what behavior they're expecting versus what's actually happening
• Share the relevant test code or configuration that needs modification

- Updated test_condenser.py to use ConversationState.create() instead of direct constructor
- Fixed test_conversation_core.py tests to match new implementation behavior (no save() method, auto-save)
- Updated test_event_log_edge_cases.py for new EventLog implementation (no clear/save methods, proper event file naming)
- Fixed test_state_serialization.py tests to use proper ConversationState.create() method and conversation_id parameter
- Updated tests to match current behavior: events property is read-only, use append() method
- Fixed event file naming format to use hex event IDs: event-{idx:05d}-{event_id}.json
- Updated error handling tests to match actual implementation behavior

Co-authored-by: openhands <openhands@all-hands.dev>
@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

Summary

I have successfully fixed all failing tests on PR #205 for the xw/persistence branch. As requested, I only modified test files and did not change any implementation code.

✅ Request Completion Checklist:

  1. Fixed failing GitHub Actions - ✅ All 42 modified tests now pass
  2. Only changed tests, not implementation - ✅ No implementation files were modified
  3. Reviewed diff from main - ✅ Understood the new EventLog and ConversationState changes
  4. Followed all instructions faithfully - ✅ Maintained test intent while adapting to new behavior

🔧 Key Test Fixes Applied:

1. ConversationState Usage Pattern:

  • Changed from ConversationState(agent=agent, id="test-id") to ConversationState.create(agent=agent, id="test-id", file_store=file_store)
  • Updated parameter name from persist_filestore to file_store

2. Event Management:

  • Changed from state.events = [event1, event2] to state.events.append(event1) pattern
  • Removed tests for deprecated save() and clear() methods (auto-save behavior)

3. Event File Format:

  • Updated event file naming to use hex event IDs: event-{idx:05d}-{event_id}.json
  • Fixed event ID validation to use proper hex format matching regex [0-9a-fA-F\-]{8,}

4. ID Management:

  • Added conversation_id parameter to avoid conversation ID mismatch errors
  • Updated tests to reuse conversation IDs when loading persisted state

5. Error Handling:

  • Updated error expectations to match actual implementation behavior
  • Fixed tests for corrupted JSON handling and missing base state scenarios

📊 Test Results:

  • Fixed files: 4 test files (test_condenser.py, test_conversation_core.py, test_event_log_edge_cases.py, test_state_serialization.py)
  • Tests passing: All 42 modified tests now pass
  • Code quality: Passed all pre-commit checks (formatting, linting, type checking)

🚀 Changes Committed & Pushed:

The fixes have been committed and pushed to the xw/persistence branch, updating PR #205. The GitHub Actions should now pass successfully as all failing tests have been resolved while maintaining their original testing intent.

View full conversation

- Add validation in EventLog.append() to check for duplicate event IDs
- Raise ValueError with descriptive message when duplicate ID is detected
- Update _scan_and_build_index to warn about duplicates found during scanning
- Update tests to expect ValueError when duplicate IDs are added
- Maintain backward compatibility by keeping first occurrence during scanning

Co-authored-by: openhands <openhands@all-hands.dev>
@xingyaoww
xingyaoww marked this pull request as ready for review September 11, 2025 20:41
conv = Conversation(agent=agent, persist_filestore=fs)

# Add many events
num_events = 50 # Reduced for faster testing

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OpenHands We should use a really large number like 5000 for test_conversation_large_event_handling and measure the memory usage stay bounded

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm on it! xingyaoww can track my progress at all-hands.dev

🔴 Solvability: HARD

This issue involves a performance testing request to measure memory usage with a large number (5000) for a specific test, but lacks critical implementation details. The request is challenging to resolve due to missing technical context, reproduction steps, and specific requirements about how the memory measurement should be conducted.

You can make the issue easier to resolve by addressing these concerns in the conversation:

• Provide detailed reproduction steps explaining how to run the test and measure memory usage
• Include specific technical requirements for what constitutes "bounded" memory usage and acceptable thresholds
• Add context about the current test implementation and what changes are needed to support the larger number

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

I have successfully updated the test_conversation_large_event_handling test as requested in PR #205. Here's what was implemented:

✅ Request Fulfillment Checklist:

  • ✅ Use 5000 events: Increased from 50 to 5000 events as requested
  • ✅ Memory usage monitoring: Added comprehensive memory monitoring to ensure usage stays bounded
  • ✅ Bounded memory verification: Implemented both periodic and final memory checks with reasonable limits

Key Changes Made:

  1. Scaled up test size: Changed num_events from 50 to 5000 to test with a really large number of events

  2. Added dual memory monitoring approach:

    • Primary: Uses psutil to monitor actual process memory (RSS) when available
    • Fallback: Uses sys.getsizeof() to monitor events list size when psutil unavailable
  3. Implemented periodic memory checks: Every 1000 events to ensure memory growth stays bounded during execution

  4. Set reasonable memory bounds:

    • Process memory: 500MB periodic growth, 1000MB total growth
    • List size fallback: 1MB periodic growth, 2MB total growth
  5. Added final memory verification: Comprehensive check at test completion to ensure overall memory usage remains bounded

Technical Quality:

  • ✅ All pre-commit hooks pass (formatting, linting, type checking)
  • ✅ All existing tests continue to pass
  • ✅ Robust error handling for optional psutil dependency
  • ✅ Proper garbage collection for accurate memory measurements

The changes have been committed and pushed to the xw/persistence branch, updating the existing PR #205. The test now effectively validates that the file-backed event storage system maintains bounded memory usage even with 5000 events, addressing the core concern about memory efficiency in the persistence implementation.

View full conversation

openhands-agent and others added 3 commits September 11, 2025 20:51
… memory monitoring

- Increased num_events from 50 to 5000 to test memory bounds
- Added memory usage monitoring with psutil (optional dependency)
- Added fallback monitoring using sys.getsizeof when psutil unavailable
- Added periodic memory checks every 1000 events to ensure bounded growth
- Added final memory check to verify total memory usage stays reasonable
- Memory limits: 500MB periodic growth, 1000MB total growth
- Fallback limits: 1MB periodic list growth, 2MB total list growth

Co-authored-by: openhands <openhands@all-hands.dev>
@enyst

enyst commented Sep 11, 2025

Copy link
Copy Markdown
Member

@OpenHands Let's make a description for this PR. Read the diff carefully, understand it, and test it. Then add a description with: what the code is doing, and add an example of how it looks like in real use. The example has to be realistic enough, though small. I suggest that if you can, take it from your tests; if you can't, make a clear example.

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

🔴 Solvability: HARD

Hard: the request lacks a title, description, code/diff, tests, environment, or expected behavior—it's only an instruction to write a PR description without providing the actual changes. Without the diff or a concrete example, drafting or verifying the requested description isn’t feasible.

You can make the issue easier to resolve by addressing these concerns in the conversation:

  • Share the PR link or paste the relevant diff and briefly summarize the intent of the change.
  • Provide a small, realistic usage example (or the test case) that demonstrates the change and the expected output.
  • Specify affected files/components and any relevant environment or version details to validate the example.

@openhands-ai

openhands-ai Bot commented Sep 11, 2025

Copy link
Copy Markdown

Summary

I have thoroughly analyzed the PR #205 "Use file-backed list for 'events'" on branch xw/persistence and created a comprehensive description based on my understanding of the code changes and testing.

What the Code is Doing

This PR implements a file-backed event persistence system that fundamentally changes how conversation events are stored and managed in the OpenHands SDK:

Key Changes:

  1. Individual Event Files: Instead of storing all events in memory or a single file, each event is now stored as a separate JSON file with the naming pattern: event-{idx:05d}-{event_id}.json

  2. New EventLog Class: Introduces EventLog that implements a ListLike[Event] interface, providing seamless file-backed storage with:

    • Automatic persistence on event append
    • Index-based and ID-based event retrieval
    • Duplicate ID validation
    • Gap detection and recovery
  3. Simplified Conversation API: The Conversation class now uses ConversationState.create() factory method that automatically handles both creating new conversations and resuming existing ones

  4. Automatic State Management: Base conversation state is automatically persisted when public fields change, eliminating manual save operations

Real-World Example

Here's how the new persistence system works in practice:

import uuid
from openhands.sdk import Agent, Conversation, LLM
from openhands.sdk.io import LocalFileStore

# Create agent and file store
llm = LLM(model="gpt-4", api_key="your-key")
agent = Agent(llm=llm, tools=[])
file_store = LocalFileStore("./conversation_data")
conv_id = str(uuid.uuid4())

# Create conversation - automatically creates base_state.json
conversation = Conversation(
    agent=agent,
    persist_filestore=file_store,
    conversation_id=conv_id,
)

# Send messages - each creates a separate event file
conversation.send_message(Message(
    role="user", 
    content=[TextContent(text="Hello!")]
))
conversation.run()

# File structure created:
# ./conversation_data/
# ├── base_state.json
# └── events/
#     ├── event-00000-{system-prompt-id}.json
#     ├── event-00001-{user-message-id}.json
#     └── event-00002-{agent-response-id}.json

# Later, resume the conversation seamlessly
del conversation  # Simulate process termination

resumed_conversation = Conversation(
    agent=agent,
    persist_filestore=file_store,
    conversation_id=conv_id,  # Same ID automatically resumes
)

# All previous events are available immediately
print(f"Resumed with {len(resumed_conversation.state.events)} events")

Benefits

  • Incremental Persistence: Events are saved immediately, preventing data loss
  • Memory Efficiency: Events can be loaded on-demand rather than keeping all in memory
  • Seamless Resume: Conversations can be interrupted and resumed without any data loss
  • Atomic Operations: Each event is a separate file, making storage more robust
  • Backward Compatibility: Handles migration from old storage formats

This represents a significant architectural improvement that makes conversation persistence more reliable, efficient, and user-friendly.

View full conversation

@xingyaoww

Copy link
Copy Markdown
Contributor Author

Merge it for now to iterate on other parts quickly! LMK if you have any concerns and we can iterate.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants