Skip to content

Studio: keep the tool results of the turn in progress when compaction resets mid-turn - #13951

Merged
Lyxot merged 4 commits into
unslothai:mainfrom
oobabooga:worktree-checkpoint-keep-current-turn
Oct 16, 2026
Merged

Lyxot merged 4 commits into
unslothai:mainfrom
oobabooga:worktree-checkpoint-keep-current-turn

Conversation

@oobabooga

@oobabooga oobabooga commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Problem

When a chat overflows during a tool loop, checkpoint compaction (the default UNSLOTH_CONTEXT_POLICY=checkpoint) evicts the tool results of the turn that is still running. Only the newest tool exchange survives. A model that ran cat main.py and then one more command loses the file it just read, so it reads it again, asks the user for it, or answers from nothing.

This matches a Reddit report on r/unsloth from a user running gemma-4-E2B with Tools on a 4 GB GPU: the model used cat, edited a script, then forgot it had done so.

Root cause

Phase two of fit_checkpoint_context starts a new epoch with truncate_oldest_messages(messages, 0.0), which evicts every unprotected group. group_turns puts each assistant tool_calls message and its results in its own group, and the primitive protects only system and developer turns, the newest user group, the final group, and explicit pins. The tool exchanges between the newest user message and the final group are therefore evicted with the old history, even when they fit. The rolling policy is not affected: it evicts oldest first and only reaches the current turn after all older history is gone.

Fix

The reset now also protects the turn in progress (_live_turn_groups: the groups after the newest user message, minus the final group the primitive already keeps). If the reset does not fit with all of them, they are released oldest first until it fits. This costs one extra exact token count per released exchange, only on the request that starts a new epoch.

Behavior that stays the same:

  • Older history is still reset in one step; the carried-forward block, archive write and forced recall are unchanged.
  • The persisted boundary is unchanged: _branch_boundary already counts only messages before the newest user turn.
  • A request with no tool exchanges after its newest user message, including every first fit of a request and /compact, takes the same path as before.
  • When only the newest exchange fits, the result and the fallback after it are the same as before.

Not addressed: the terminal tool's own output cap and repeated reads in longer tool loops, where answer quality showed no difference either way.

Verification

test_a_reset_inside_a_tool_loop_keeps_the_turn_in_progress covers everything fitting, releasing only the oldest exchange, and only the newest fitting. The first two fail on main; the third pins the fallback. The compaction, recall, archive, overflow and prefix-boundary suites pass (665 passed; 641 passed, 201 skipped).

Live A/B in Studio with a saved thread, the terminal tool and an 8192-token context. After 11 older exchanges, the model runs two commands and is asked about the first output without running anything else. That output ends in a sha256-derived value that appears nowhere in the prompt; the second output triggers the reset. In every trial reported here, main dropped 24 messages and this change 22, keeping the first command's call and result.

Model main this PR
Qwen3-30B-A3B-Instruct-2507 Q4_K_M 0/8, a different made-up hash every trial 8/8
gemma-4-E2B-it Q4_K_M 0/7 resets; 1 re-ran the first command 4/7 resets

A repeat with a random UUID per trial gave Qwen 0/5 vs 5/5 and gemma 0/4 vs 3/3. Answers are wording-sensitive: asked for the "last line printed by the first command", Qwen with the change quoted the last line of the seq part of the chain (0/8), while main still invented a hash.

Limitation: when the question names the value ("tell me the value of SECRET_TOKEN"), main already answers 8/8 because the forced recall finds the evicted chunk by similarity. Keeping the current turn's output removes the dependence on that retrieval.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T07:55:14.198530Z ab47bec Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@carlitogwapito

Copy link
Copy Markdown
Contributor

Here's a small test-only branch, if useful alongside the reset tests. It adds six _live_turn_groups boundary cases: empty/no-user histories, no extra exchange to hold, the newest-user boundary, and a batched call whose two results must stay together. It also checks input non-mutation and original message-object identity.

All six passed using your unchanged checkpoint/context helper modules in a small namespace fixture. Ruff 0.15.11 check/plain format checks pass with this branch's pyproject.toml; I haven't run the pinned custom formatting hook, full Studio CI, or a live model. These checks cover group selection, not token-budget fitting or answer quality.

I'd keep the newest-user boundary separate from the token-fit scenarios, and keep batched calls/results covered as one group. The branch only adds studio/backend/tests/test_checkpoint_live_turn_groups.py.

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#380.

@Lyxot Lyxot self-assigned this Oct 16, 2026
…ress

Holding the live tool exchanges up to the prompt budget left no room for the next tool result, so inside a tool loop every later call reset again and re-prefilled the whole held turn. The hold now stops at the rolling compaction headroom (headroom_ratio, default ROLLING_COMPACTION_HEADROOM_RATIO); acceptance still uses the full budget, and a reset that cannot meet the headroom falls back to keeping only the newest exchange as before.
@Lyxot

Lyxot commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

Pushed 7ff04b1 on top of this branch: the reset now holds the turn in progress only until it leaves the rolling compaction headroom free (headroom_ratio, default ROLLING_COMPACTION_HEADROOM_RATIO = 0.25), instead of filling the prompt budget to the brim.

Why: the GGUF tool loop carries each fit's result into the next iteration. Held right up to prompt_target, the next tool result overflowed again, so every later call reset and re-prefilled the whole held turn. In a simulated 8192-token loop with 30 calls: main 1 reset / 13.8k re-prefilled tokens, previous head 11 / 76k, now 3 / 25k. Acceptance still uses the full budget, and when the headroom cannot be met the result is the same as on main (newest exchange only).

Tests: added a case with two held exchanges (the existing cases each held at most one, so holding only the last exchange passed them), and a test that the next tool call after a reset does not reset again, with headroom_ratio 0.0 and 0.5 honoured.

Not addressed here: a mid-turn role=user nudge (re-prompt to act, deferred no-op nudge) becomes the newest user message, so the exchanges before it are not held and the real request is evicted too. That already happens on main and needs the request's own turn boundary passed in from the tool loop, so it is better as a follow-up. I also left the separate _live_turn_groups test branch out to keep the PR to its existing test file.

@Lyxot

Lyxot commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ff04b12b4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The request field and its client type still said the ratio was ignored for checkpoint compaction, but a checkpoint reset now leaves that share free when it keeps the tool calls of the turn in progress.
@Lyxot

Lyxot commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ab47bec6d6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot

Lyxot commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: ab47bec6d6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot

Lyxot commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

Codex review converged on ab47bec6d6: #13951 (comment)

CI, run on a staging copy (same head ab47bec6d6, base upstream main at 4a8b727dfd) because the upstream checks stayed queued: Lyxot#173 — 60 passed, 4 skipped, 2 failed, neither from this change:

What changed during this review:

  • 7ff04b12b4: the reset holds the turn in progress only until the rolling compaction headroom is free, so a tool loop no longer resets and re-prefills on every later call; two tests added (two held exchanges, and no second reset on the next tool call, with headroom_ratio 0.0 and 0.5 honoured).
  • ab47bec6d6: the compaction_headroom_ratio request description and client type no longer say the ratio is ignored for checkpoint compaction.
  • Declined, with reasons in the threads: reserving recall room on top of the headroom, a binary search for the release point, and anchoring on the request's own user turn past mid-turn nudges (already broken on main, and a separate change to the fit seam).

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Fixes the mid-turn reset losing the turn's earlier tool results, leaves headroom so the tool loop does not reset on every call, and Codex and CI (staging) are clean.

@Lyxot
Lyxot merged commit 08fb7bc into unslothai:main Oct 16, 2026
danielhanchen added a commit that referenced this pull request Oct 16, 2026
…13991)

## Summary

`Frontend build + bundle sanity` is red on main again. #13969 merged
with it red, and its run reported `over the startup budget: transfer
1995.0 KB > 1994.7 KB, raw 6633.8 KB > 6632.7 KB`. Main at 6106de9
measures 6,796,799 B raw / 2,044,202 B transfer, against limits of
6,792,425 / 2,042,777.

Measured commit by commit (one machine and build, Node 24, 95 chunks
throughout, `rm -rf dist` before each build):

| commit | raw B | transfer B |
|---|---|---|
| 1790106 (#13983, last raise from me) | 6,791,768 | 2,042,404 |
| 7d33eff (#13965) | 6,792,034 | 2,042,515 |
| cc0cb59 (#13966) | 6,792,447 | 2,042,693 |
| 7bee02d (#13969) | 6,793,737 | 2,043,138 |
| ce83dee (#13973) | 6,796,298 | 2,044,201 |
| 6106de9 (main, after #13974, #13972, #13951, #13945) | 6,796,799 |
2,044,202 |

The two largest steps:
- Inline chat markdown tables with hover controls and the expand dialog
(#13973): +2,561 B raw / +1,063 B transfer, in the eager chat chunk.
- Latest Unsloth Models ranking (#13969): +1,290 B raw / +445 B
transfer.

#13945 already raised the budget for its own 497 B.

## Change

The budget is set to the measured build plus the margin main had at
1790106 (160 B raw, 189 B transfer), with the per-commit numbers
recorded beside the limits as in the earlier raises. If #13973's expand
dialog should be lazy-loaded instead, that is a follow-up for its owner.
This only gets main and every open PR off a red that none of them
caused.

## Testing

- `npm run build && npm run bundle:check` on main with this change:
within budget (0.2 KB transfer, 0.2 KB raw to spare). Without it: over
by 4,374 B raw / 1,425 B transfer.
- `tests/bundle-budget-cli.test.ts` and
`tests/bundle-budget-closure.test.ts`: 43 passed.
- `prettier --check scripts/check-bundle-budget.ts`: clean.
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