Skip to content

[Bug]: Decision continuations keep only the last segment's context lifecycle, dropping earlier steps, cache usage and mutations #1668

Open

Description

@chen-ran

Author

Agent

Type

bug

Bug Description

A run that waits for a decision (tool approval or ask_user) and then continues keeps the context lifecycle of its last segment only. Everything recorded before the pause is missing from the run's context_lifecycles row: per-step snapshots, cache usage records, cache totals, and mutations.

How it happens on main (e4af880):

  1. Each continuation starts a fresh record. continueUserInputSession and continueToolApprovalSession rebuild the run config through ResolveRunConfig. That creates a new LifecycleHolder and a new MutationLedger. The continuation's snapshot therefore starts again at step 1, with empty mutations and cache usage.
  2. A run gets exactly one row, and the newest snapshot wins. context_lifecycles is keyed by run_id. stageContextLifecycleCandidate replaces a candidate of equal quality. UpsertTerminalContextLifecycle writes it with replace_snapshot.
  3. Nothing merges the segments. The earlier segments survive only in the context_lifecycle metadata of their own assistant messages in bot_history_messages.

Who sees it:

  • GET /bots/{bot_id}/sessions/{session_id}/context-lifecycle returns turns[].snapshot.steps, cache_usage and mutations for the last segment only. Its aggregates (total_cache_read_tokens, total_cache_write_tokens, mutation_kinds) under-count by the same amount.
  • The Context Inspector reads the same row. It currently draws only the occupancy of the final request, so its chart does not look wrong, but the step and mutation history behind it is incomplete.
  • Compaction Logs (bot_history_message_compacts) and the server logs are not affected and still show every pass.

Steps to Reproduce

The runs below came from a deployment of main dc24ba2da with the open compaction stack (#1620, #1650, #1651, #1654, #1661) merged on top. The stack does not touch any of the lifecycle code linked above: those files are identical on main a568a4b80 (the stack's base) and e4af880. The loss of steps and cache records in the approval scenario does not depend on any stack feature. A pure-main deployment has not been run separately.

Tool approval (main behavior):

  1. Set the bot's exec tool approval to Ask.
  2. Ask the bot to run a command repeatedly, one exec call per step, for about 14 steps. Approve each request.
  3. When the run completes, compare the number of assistant messages for the run with turns[0].snapshot.steps from the context-lifecycle API.

ask_user mid-run:

  1. Ask the bot to run about 6 tool steps, then call ask_user once, then continue for about 6 more steps.
  2. Answer the question and let the run complete.
  3. Compare the snapshot on the last assistant message before the pause with the run's context_lifecycles row:
select 'msg' src, m.created_at,
       jsonb_array_length(coalesce(m.metadata->'context_lifecycle'->'steps','[]')) steps,
       m.metadata->'context_lifecycle'->>'cache_read_tokens' cache_read,
       (select string_agg(x->>'kind', ',') from jsonb_array_elements(coalesce(m.metadata->'context_lifecycle'->'mutations','[]')) x) kinds
from bot_history_messages m
where m.run_id = :run and m.role = 'assistant' and m.metadata ? 'context_lifecycle'
union all
select 'row', l.created_at,
       jsonb_array_length(coalesce(l.snapshot->'steps','[]')),
       l.snapshot->>'cache_read_tokens',
       (select string_agg(x->>'kind', ',') from jsonb_array_elements(coalesce(l.snapshot->'mutations','[]')) x)
from context_lifecycles l where l.run_id = :run
order by 2;

With the stack's in-run compaction (#1651), make the first segment long enough to fold before ask_user is called. The fold's context_switch mutation is then dropped too.

Expected and Actual Behavior

Expected: the run's lifecycle row describes the whole run, from admission to the terminal state: every step and its cache usage across all segments, cache totals summed over all segments, and every mutation, including those recorded before a pause.

Actual: only the last segment is kept.

Run Ground truth context_lifecycles row
Tool approval on every exec, run 6e94b598… 14 assistant steps in 14 segments 1 step, 1 cache_usage record (27,136 cache-read tokens)
ask_user after 6 steps, run fbfe3c83… Segment 1: 7 steps, 148,992 cache-read tokens, 1 context_switch. Segment 2: 8 steps, renumbered from 1, 1 context_switch. Compaction Logs: 2 passes. 8 steps, 206,080 cache-read tokens, 1 context_switch. Everything comes from segment 2.

The ask_user case reproduced in 10 of 10 QA rounds: every round logged 2 context compacted (trigger=in_run) lines and recorded 1 context_switch.

Version

Environment

  • Self-hosted Docker Compose deployment in split mode (memoh-server and memoh-channel).
  • containerd workspaces, PostgreSQL.
  • Web UI on port 8082.

Logs

GET /bots/{bot_id}/sessions/{session_id}/context-lifecycle for the ask_user run (fbfe3c83…):

{"turns": 1, "total_cache_read_tokens": 206080, "total_cache_write_tokens": 0, "mutation_kinds": {"context_switch": 1}}

Per-message snapshots compared with the run row for the same run. The step counter restarts at the continuation:

 src |    at    |     kinds      | steps | cache_read
-----+----------+----------------+-------+------------
 msg | 09:31:15 |                |     1 | 0
 ...
 msg | 09:31:29 |                |     6 | 115584
 msg | 09:31:50 | context_switch |     7 | 148992   <- last message before ask_user
 msg | 09:31:53 |                |     1 | 0        <- continuation starts a new ledger
 ...
 msg | 09:32:24 | context_switch |     6 | 136576
 msg | 09:32:33 | context_switch |     8 | 178688
 row | 09:32:33 | context_switch |     8 | 206080   <- context_lifecycles keeps segment 2 only

compaction passes for the session: ok 09:31:30 (level 0), ok 09:32:07 (level 1)

Screenshots / Recordings

Compaction Logs (qa-lane-d). The two newest entries, 9:31:29 and 9:32:07, are the two passes of the ask_user run above: one before the pause and one after the continuation. Compaction Logs is correct and lists both.

Compaction Logs shows two passes

Context Inspector for the same session. It shows one turn, backed by the single context_lifecycles row. The occupancy shown is that of the final request, which is correct. The steps, cache records and mutations from the segment before the pause are absent from the row behind it; the per-segment numbers are under Logs above. Model names are redacted. This screenshot shows which record the UI reads. It does not show the loss itself, which is in the API payload.

Context Inspector reads one row for the run

The evidence is agent-collected: the screenshots come from the running deployment, and the database and API output are quoted above. No human QA has been done.

Additional Context

History

When Change Effect on this bug
2026-04-28, #410 Tool call approval workflow Approving a call resumes the run by resolving a new run config.
2026-06-03, #554 ask_user pause and resume Same continuation pattern for user input.
2026-08-15, #969 Run-keyed context lifecycle persistence: context_lifecycles (migration 0134, run_id primary key), candidate staging and the terminal upsert The continuation stores its snapshot under the original run id. From here on, the row of a decision run describes only one segment. Before #969, lifecycle data lived only in per-assistant-message metadata, where every segment kept its own snapshot. That metadata still exists, so the lost data can be recovered.
2026-08-20, #1041 Added per-step snapshots (steps) and cache usage records to the ledger The loss now also covers step history and cache totals.
2026-09-09, #1105 Moved continuations onto runNativeDecisionContinuation under the original run handle; candidates are keyed by run and fencing token No change in outcome: the last segment still replaces the earlier ones.
Open, #1651 (compaction stack) Records each in-run fold as a context_switch mutation in the same per-segment ledger A fold before the pause is dropped as well, so the lifecycle under-counts in-run compactions. QA of the stack found this; it is not a regression introduced by the stack.

Possible fix directions

  • Give the continuation the run's existing record to build on: seed its ledger from the run's latest staged or persisted snapshot, carrying the mutations, step snapshots (keeping step indices running across segments) and cache usage records.
  • Alternatively, merge segment snapshots when writing the terminal row, instead of replacing them.
  • For already-stored rows, rebuild the run-level history from the per-message context_lifecycle metadata.
  • Acceptance check:
    • an approval-per-step run records every step;
    • an ask_user run with a fold before the pause records both folds;
    • the API aggregates equal the sum over all segments.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugFixes a bug or unexpected behavior

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions