Skip to content

Session DB turn-end flush drops assistant after repair_message_sequence compacts list (orphan user → \n\n merge) #44837

@JerryLiu369

Description

@JerryLiu369

Summary

Gateway warm sessions can accumulate merged \n\n-joined user blobs in the model payload while platform inbound stays single-message per turn.

Observed behavior (reporter session 20260612_085708_c4403c61, 2026-06-12 weixin)

Layer Evidence
Gateway inbound Single message each turn
Agent turn_context history=N msg='…' single string
AxonHub requests Last user content grows: 2 → 3 → … → 6 segments joined with \n\n
Alternation repair Repaired N message-alternation violations monotonically increasing

Minimal repro segment 13:15–13:17 CST:

Cache eviction after ~1h idle was an amplifier, not the root cause (blob already 5 segments before evict).

Root cause chain

  1. turn_context early-persists inbound user at turn start → _last_flushed_db_idx advances past pre-turn length.
  2. First API call runs repair_message_sequence() which merges consecutive users (orphan + new) and shrinks messages in place.
  3. Flush cursor stays at the pre-compaction index → turn-end _flush_messages_to_session_db computes flush_from past the first post-repair assistant row and skips persisting the assistant/tool chain.
  4. Next turn loads orphan user → new user → repair merges again → blob grows.

#44327 (reset _last_flushed_db_idx on cached-agent fresh turns) is necessary but not sufficient when step 2 compacts within the same turn.

Proposed fix

Community PR incoming from @JerryLiu369 fork.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1High — major feature broken, no workaroundcomp/agentCore agent loop, run_agent.py, prompt buildercomp/gatewayGateway runner, session dispatch, deliverytype/bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions