SIGN IN SIGN UP

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

0 0 83 Python

fix(backend/copilot): back-fill in-memory sequences from actual batch start (#13057)

## Why

\`add_chat_messages_batch\` retries from \`get_next_sequence\` when the
unique constraint on \`(sessionId, sequence)\` trips (peer race between
the streaming loop and a long-running callback). On retry, the rows land
at a different offset than the caller passed in. But the helper's return
value was always \`start_sequence + len(messages)\` regardless of which
offset was actually used, so the caller in \`_save_session_to_db\`
back-filled in-memory \`ChatMessage.sequence\` with the original (stale)
\`existing_message_count\`. After that, the in-memory rows pointed at
sequences that a peer process had already written, and any subsequent
\`update_message_content_by_sequence\` call updated the wrong row.

Sentry flagged this as HIGH on PR #13047; surfacing it independently
here so the perf PR can ship without the unrelated change.

## What

- \`add_chat_messages_batch\` now returns the **actual**
\`start_sequence\` used (equal to the input on the no-collision common
path; differs after a retry).
- \`_save_session_to_db\` back-fills in-memory \`ChatMessage.sequence\`
from the returned value rather than from \`existing_message_count\`.
- New regression test
\`test_save_session_to_db_uses_actual_start_after_collision\` mocks the
helper returning a different start than the caller passed in and asserts
the in-memory rows follow.

## How

Two-line return-value change + caller update; back-fill loop now reads
from \`actual_start = await db.add_chat_messages_batch(...)\` instead of
\`existing_message_count\`. Existing collision-detection integration
test \`test_concurrent_saves_collision_detection\` still passes — it
only asserts the DB-side outcome, which was always correct; this PR
fixes the in-memory side.

## Tests

- New unit test
\`test_save_session_to_db_uses_actual_start_after_collision\`.
- Existing integration tests for the batch helper continue to pass.

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my own code
- [x] I have made corresponding changes to the documentation (n/a)
- [x] My changes generate no new warnings (black/ruff/pyright clean)
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] Any dependent changes have been merged and published in downstream
modules
Z
Zamil Majdy committed
cea8fdfda9f85391bcafdefb22da1a6a5f1c91b1
Parent: b2719fd
Committed by GitHub <noreply@github.com> on 5/8/2026, 11:24:01 AM