Skip to content

Clean up orphaned messages when deleting a branch#3478

Open
Doondi-Ashlesh wants to merge 1 commit into
openai:mainfrom
Doondi-Ashlesh:fix/sessions-delete-branch-orphans-clean
Open

Clean up orphaned messages when deleting a branch#3478
Doondi-Ashlesh wants to merge 1 commit into
openai:mainfrom
Doondi-Ashlesh:fix/sessions-delete-branch-orphans-clean

Conversation

@Doondi-Ashlesh
Copy link
Copy Markdown

Summary

delete_branch was removing rows from turn_usage and message_structure but leaving behind the corresponding rows in the messages table that belonged exclusively to the deleted branch. Those rows were invisible to any query since get_items joins through message_structure, but they kept accumulating on disk with each branch deletion.

The existing _cleanup_orphaned_messages_sync helper already does the right thing: it finds messages with no remaining references in message_structure and removes them. This just calls it inside the same transaction before the final commit, so shared messages (referenced by other branches) are preserved and exclusive ones are removed atomically.

Test plan

Added test_delete_branch_removes_orphaned_messages which:

  • Creates two messages on main and one message exclusively on a side branch
  • Verifies all three rows exist in the messages table before deletion
  • Deletes the side branch
  • Checks only two rows remain (the branch-only message is gone)
  • Checks the shared message is still readable from main

All 38 tests in test_advanced_sqlite_session.py pass. No regressions in the wider suite.

Issue number

Closes #3346

Checks

  • I've added new tests (if relevant)
  • I've added/updated the relevant documentation
  • I've run make lint and make format
  • I've made sure tests pass

delete_branch was removing rows from turn_usage and message_structure
but leaving behind message rows in the messages table that belonged
exclusively to the deleted branch. Those rows were invisible to queries
since get_items joins through message_structure, but they kept accumulating
on disk with each branch deletion.

The existing _cleanup_orphaned_messages_sync helper already handles this
correctly by checking for messages with no remaining structure references.
This just calls it as part of the delete transaction before committing.

Added a regression test that verifies branch-only messages are removed
and shared messages are preserved after deletion.
@seratch seratch added duplicate This issue or pull request already exists feature:sessions labels May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

duplicate This issue or pull request already exists feature:sessions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AdvancedSQLiteSession.delete_branch() leaves branch-only messages in the base table

2 participants