Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Never carry the opening request without the turn that follows it (#9424)

Daniel Han6392e25983fb
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.py
index 9a71b3ea4d2..a3443757a4c 100644
--- a/studio/backend/core/inference/checkpoint.py
+++ b/studio/backend/core/inference/checkpoint.py
@@ -111,6 +111,193 @@ def _neutralise(text: str) -> str:
return _DELIMITERS.sub(lambda match: match.group(0).replace("<", "‹"), text)
+def _pick(
+ entries: list[Optional[tuple[str, int]]],
+ *,
+ max_tokens: int,
+ max_items: int,
+ reserve_oldest: bool = False,
+ reserve_leading: int = 0,
+) -> list[str]:
+ """The selection itself, over positions that are either (text, cost) or not an item.
+
+ Shared by the two paths that select, so the pair rule cannot hold on one and not the
+ other: the fresh walk over evicted TURNS (`_select_items`) and the re-cap of a merged
+ list of already-rendered STRINGS (`_recap`). It was written against turns only, and
+ the merged path then re-capped with a plain newest-first walk that could take the
+ opening and drop the successor the fresh walk had paired it with -- the abandoned
+ request carried with its correction dropped, reached through the second compaction
+ instead of the first.
+
+ `reserve_oldest` takes the opening item before the newest-first walk. It is for the
+ thread of short prompts, where the FIRST turn is the one that says what is being
+ built: newest-first alone would spend all eight slots on the increments nearest the
+ end ("add music", "now the score", "fix the pipes") and evict the statement of the
+ task itself, which is the loss this pass exists to stop. The walk still runs
+ newest-first afterwards, so a later change of direction is kept too, and rendering is
+ oldest-first either way.
+
+ It reserves the opening item TOGETHER WITH the next one, both or neither, because the
+ turn right after the opening is the one that can contradict it without any newer turn
+ showing that it did. See `_reserved_order` for why.
+
+ `reserve_leading` is the same rule for a list whose first N entries arrived as one
+ already-rendered block, where WHICH of them is the successor cannot be recovered. The
+ block is oldest-first by the position of each item's NEWEST copy, so a successor the
+ user restated later renders after the turns that came between: a perfectly valid block
+ reads [opening, intervening rule, successor, newest], and reserving its first two
+ entries pairs the opening with the intervening rule and lets the walk drop the actual
+ correction ("Build Tetris", "Dark theme", "Add music!" carried at a 60-token cap while
+ "Actually scrap that and build a Flappy Bird clone instead" was dropped). So the whole
+ block is reserved as ONE unit instead of guessing: the successor is somewhere in it,
+ whichever entry it is, and an abandoned opening is always the FIRST entry, since an
+ opening the user restated is not abandoned and renders at the restatement. Keep the
+ unit whole or drop its first entry -- no bullet has to be identified.
+ """
+
+ def _item(index: int) -> Optional[tuple[str, int]]:
+ return entries[index]
+
+ # Where each instruction renders: the position of its NEWEST copy in the transcript,
+ # whether or not the walk reaches that copy. The later-wins header makes position the
+ # meaning, and reading it off the transcript keeps it independent of the walk order:
+ # the reserved pair can fill the cap before a newer copy is reached, which rendered
+ # "metric", "imperial", "metric", "add a table" at max_items 3 as metric, imperial,
+ # table -- imperial current just after the user restored metric.
+ newest_position: dict[str, int] = {}
+ for index in range(len(entries)):
+ found = _item(index)
+ if found is not None:
+ newest_position[found[0]] = index
+
+ def _walk(order: list[int]) -> list[str]:
+ # (position, text) so the render can sort by position: with a reserved item the
+ # selection order is no longer the reverse of the transcript order, and
+ # `reversed(chosen)` put the oldest turn LAST, inverting supersession.
+ picked: list[tuple[int, str]] = []
+ seen: set[str] = set()
+ spent = 0
+ for index in order:
+ if len(picked) >= max_items:
+ break
+ found = _item(index)
+ if found is None:
+ continue
+ item, cost = found
+ if item in seen:
+ # One restated rule used to take all eight slots. Checked before the cost
+ # is charged, so a repeat cannot exhaust the budget; every copy renders at
+ # `newest_position` anyway, so which one the walk saw first is moot.
+ continue
+ if spent + cost > max_tokens:
+ # Skipped, not truncated: an older instruction that fits beats nothing.
+ continue
+ picked.append((newest_position[item], item))
+ seen.add(item)
+ spent += cost
+ return [item for _, item in sorted(picked)]
+
+ plain = list(reversed(range(len(entries))))
+
+ def _takeable(index: int) -> bool:
+ found = _item(index)
+ return found is not None and found[1] <= max_tokens
+
+ # `unit` is oldest-first, how the tail reads it: an abandoned opening can only be its
+ # first entry. `spend` is the order the walk charges it in, newest-first for a carried
+ # block, so a budget that shrank mid-thread keeps the block's newest bullets rather
+ # than filling up on its oldest ones.
+ if reserve_leading > 0:
+ # The already-rendered block in full, not just its first two entries.
+ unit = [index for index in range(reserve_leading) if _item(index) is not None]
+ spend = list(reversed(unit))
+ elif reserve_oldest:
+ oldest = next((i for i in range(len(entries)) if _item(i)), None)
+ # The turn the user sent RIGHT AFTER the opening one, reserved with it.
+ successor = (
+ None
+ if oldest is None
+ else next((i for i in range(oldest + 1, len(entries)) if _item(i)), None)
+ )
+ unit = [] if oldest is None else [oldest] if successor is None else [oldest, successor]
+ # Charged opening first, as always: the tail takes both entries or neither.
+ spend = unit
+ else:
+ unit = []
+ spend = unit
+ if not unit:
+ return _walk(plain)
+
+ def _reserved_order() -> list[int]:
+ """The walk order with the opening PAIR slotted in behind the newest usable turn.
+
+ The opening turn is reserved because it is where the task is stated, but on its
+ own that reservation states the task WRONG whenever the user changed direction
+ early: the reserved turn was carried and the turn immediately after it was the
+ one the slot cap dropped, so "Build Flappy Bird", "Actually build Tetris instead",
+ "Add music" carried Flappy Bird and the music at max_items 2, and the same three
+ with seven increments carried Flappy Bird and all seven at max_items 8. Both
+ blocks tell the model to build the game the user abandoned and then apply every
+ later increment to it.
+
+ Reserving the opening turn together with its successor is the fix that needs no
+ reading of the English: whatever the user said next about the opening request is
+ carried alongside it. The pair costs one more slot than the single reservation,
+ paid by the oldest turn the newest-first walk would have taken.
+
+ It moves the hole rather than closing it, and only the TOKEN cap is really fixed.
+ Against the SLOT cap, reserving the opening leaves a contiguous run of n -
+ max_items turns dropped whatever the order, so a change of direction inside that
+ run is lost either way: the single reservation drops [1, n-k] and the pair drops
+ [2, n-k+1]. The pair therefore wins at index 1, which is the case above, and loses
+ at index n-k+1. Fuzzed over 40,000 threads it is a net 18% fewer blocks that state
+ the abandoned task, fixing about 2.5 for every one it breaks. Closing the class
+ outright means not carrying the opening at all once it does not fit, which is the
+ loss #9379 landed to stop.
+
+ Placed behind the newest turn that CAN BE TAKEN, not merely the newest one that
+ qualifies, exactly as the single reservation was. A turn costing more than the
+ whole cap is skipped by the walk without spending anything, so reserving behind it
+ puts the opening pair ahead of every usable recent turn: "Build Flappy Bird",
+ "Actually build Tetris", then an oversized pasted request carried only Flappy Bird
+ at a 153-token cap.
+ """
+ held = set(unit)
+ rest = [index for index in plain if index not in held]
+ newest = next((index for index in rest if _takeable(index)), None)
+ if newest is None:
+ return spend + rest
+ at = rest.index(newest) + 1
+ return rest[:at] + spend + rest[at:]
+
+ chosen = _walk(_reserved_order())
+ if len(unit) < 2:
+ # Nothing followed the opening turn, so nothing can be hidden behind it.
+ return chosen
+ opening_text = _item(unit[0])[0]
+ if opening_text not in chosen:
+ return chosen
+ missing = [index for index in unit[1:] if _item(index)[0] not in chosen]
+ if not missing:
+ return chosen
+ if not any(_takeable(index) for index in missing):
+ # What is missing costs more than the whole budget, so there was never a unit to
+ # take. Dropping the opening buys nothing here: it is usually the ONLY turn that
+ # fits, so the block would go out empty, which is the failure this pass exists to
+ # stop (a 43-token instruction then eight 160-token sections under 100 tokens).
+ return chosen
+ # Whole or nothing: something affordable was left behind and the unit still did not fit,
+ # and half a unit is the bug itself -- the abandoned request carried with its correction
+ # dropped. So the reservation is abandoned and the newest-first walk decides.
+ #
+ # The opening is excluded from that walk, or the fallback picks it up again whenever it
+ # is the cheaper of the two (a 10-token "Build Tetris", a 30-token correction and a
+ # 25-token newest turn under 40 tokens dropped the correction). By position, not by
+ # text: a user who RESTATES the opening has not abandoned it, and that newer copy stays
+ # selectable. Kept only if it says something, since `chosen` already refused to be empty.
+ return _walk([index for index in plain if index != unit[0]]) or chosen
+
+
def _select_items(
evicted: list[dict],
*,
@@ -119,21 +306,11 @@ def _select_items(
min_chars: int,
reserve_oldest: bool = False,
) -> list[str]:
- """The instruction turns out of `evicted`, oldest first, under both caps.
-
- `reserve_oldest` takes the oldest qualifying turn before the newest-first walk. It is
- for the thread of short prompts, where the FIRST turn is
- the one that says what is being built: newest-first alone would spend all eight slots
- on the increments nearest the end ("add music", "now the score", "fix the pipes") and
- evict the statement of the task itself, which is the loss this pass exists to stop.
- The walk still runs newest-first afterwards, so a later change of direction is kept
- too, and rendering is oldest-first either way.
- """
- groups = list(group_turns(evicted))
+ """The instruction turns out of `evicted`, oldest first, under both caps."""
- def _item(index: int) -> Optional[tuple[str, int]]:
- """`groups[index]` as (text, cost) if it is an instruction, else None."""
- head = groups[index][0]
+ def _entry(group: list[dict]) -> Optional[tuple[str, int]]:
+ """`group` as (text, cost) if its head is an instruction, else None."""
+ head = group[0]
if not is_substantive(head, min_chars = min_chars):
return None
text = _text_of(head).strip()
@@ -141,76 +318,12 @@ def _select_items(
return None
return _neutralise(text), estimate_message_tokens(head)
- order = list(reversed(range(len(groups))))
- if reserve_oldest:
- oldest = next((i for i in range(len(groups)) if _item(i)), None)
- if oldest is not None:
- # The opening task is reserved, but it must never DISPLACE the newest
- # instruction. Placing it first exhausted a tight cap before the
- # newest-first walk began: at MAX_ITEMS=1, "Build a Flappy Bird game"
- # then "Actually build Tetris instead" carried only the abandoned
- # request, so the block stated the opposite of the user's latest
- # direction. Slotting it in behind the newest qualifying turn keeps
- # both whenever there is room for two, and keeps the correction when
- # there is room for only one.
- #
- # The slot goes behind the newest turn that CAN BE TAKEN, not merely the
- # newest one that qualifies. A turn costing more than the whole cap is
- # skipped by the walk below without spending anything, so reserving behind
- # it puts the opening task ahead of every usable recent turn and restores
- # the bug this slotting exists to fix: "Build Flappy Bird", "Actually build
- # Tetris", then an oversized pasted request carried only Flappy Bird at a
- # 153-token cap.
- def _takeable(index: int) -> bool:
- found = _item(index)
- return found is not None and found[1] <= max_tokens
-
- rest = [index for index in order if index != oldest]
- newest = next((index for index in rest if _takeable(index)), None)
- if newest is None:
- order = [oldest] + rest
- else:
- at = rest.index(newest) + 1
- order = rest[:at] + [oldest] + rest[at:]
-
- # Kept as (position, text) so the render can sort by position: with a reserved item
- # the selection order is no longer simply the reverse of the transcript order, and
- # `reversed(chosen)` put the oldest turn LAST, inverting the supersession the header
- # promises.
- picked: list[tuple[int, str]] = []
- seen: dict[str, int] = {}
- spent = 0
- for index in order:
- if len(picked) >= max_items:
- break
- found = _item(index)
- if found is None:
- continue
- item, cost = found
- if item in seen:
- # Users restate a standing rule, and each copy used to take a slot out of
- # eight: one rule repeated eight times crowded out the user's other rule.
- # Checked before the cost is charged, so a repeat cannot exhaust the budget.
- #
- # The surviving copy keeps the NEWEST position. `reserve_oldest` walks the
- # oldest qualifying turn first, so without this a restatement was dropped in
- # favour of its own older copy: "metric", "imperial", "metric" rendered as
- # metric then imperial, and the header's later-wins rule then told the model
- # imperial was current when the user had just restored metric. In the plain
- # newest-first walk the first sighting is already the newest, so nothing
- # moves there.
- slot = seen[item]
- if index > picked[slot][0]:
- picked[slot] = (index, item)
- continue
- if spent + cost > max_tokens:
- # Skipped, not truncated, and the loop continues: an older instruction that
- # still fits beats nothing.
- continue
- picked.append((index, item))
- seen[item] = len(picked) - 1
- spent += cost
- return [item for _, item in sorted(picked)]
+ return _pick(
+ [_entry(group) for group in group_turns(evicted)],
+ max_tokens = max_tokens,
+ max_items = max_items,
+ reserve_oldest = reserve_oldest,
+ )
def carried_forward_items(
@@ -314,25 +427,37 @@ def _block_items(text: str) -> list[str]:
return [item for item in (item.strip() for item in items) if item]
-def _recap(items: list[str], *, max_tokens: int, max_items: int) -> list[str]:
- """Re-apply the caps to a merged list. Newest-first selection, oldest-first render."""
- chosen: list[str] = []
- seen: set[str] = set()
- spent = 0
- for item in reversed(items):
- if len(chosen) >= max_items:
- break
- if item in seen:
- # An instruction can be carried, evicted, and re-selected; newest wins, which
- # is the order this loop already walks.
- continue
- cost = estimate_message_tokens({"role": "user", "content": item})
- if spent + cost > max_tokens:
- continue
- chosen.append(item)
- seen.add(item)
- spent += cost
- return list(reversed(chosen))
+def _recap(
+ items: list[str],
+ *,
+ max_tokens: int,
+ max_items: int,
+ carried: int = 0,
+) -> list[str]:
+ """Re-apply the caps to a merged list. Newest-first selection, oldest-first render.
+
+ Repeats collapse to their newest copy: an instruction can be carried, evicted and
+ re-selected, and newest wins, which is the order the walk already runs in.
+
+ `carried` is how many of the leading entries arrived as one already-rendered block, so
+ this walk owes them the same rule the fresh walk owes the opening pair. Without it the
+ merge re-created the exact output the pair exists to prevent, one compaction later: a
+ block holding "Build Flappy Bird" and its "actually build Tetris" correction, merged
+ with the increments evicted since, spends the budget newest-first, skips the long
+ correction and then still affords the short opening, so the block tells the model to
+ build the game the user cancelled and to apply every later increment to it.
+
+ A COUNT rather than a pair, because which two bullets were the pair does not survive
+ the render: the block is ordered by each item's newest copy, so the successor of a
+ restated correction sits behind the turns that came between. The block is held whole
+ or its first bullet is dropped, which needs no bullet to be identified. See `_pick`.
+ """
+ return _pick(
+ [(item, estimate_message_tokens({"role": "user", "content": item})) for item in items],
+ max_tokens = max_tokens,
+ max_items = max_items,
+ reserve_leading = carried,
+ )
def _without_block(messages: list[dict]) -> list[dict]:
@@ -434,7 +559,15 @@ def fit_checkpoint_context(
)
)
if prior:
- items = _recap(prior + items, max_tokens = budget, max_items = MAX_ITEMS)
+ # The pair rule travels with the merge: a plain newest-first re-cap could take
+ # the opening request and drop the correction to it. Which bullets were the
+ # pair is not recoverable from rendered text, so the block goes in as one unit.
+ items = _recap(
+ prior + items,
+ max_tokens = budget,
+ max_items = MAX_ITEMS,
+ carried = len(prior),
+ )
if not items:
# Nothing to carry, so nothing to claim: do not pay for the probe. The old
# block still has to GO, though: `_append_to_system` returns early on an empty
diff --git a/studio/backend/tests/test_checkpoint_compaction.py b/studio/backend/tests/test_checkpoint_compaction.py
index 7c5ea78ad6e..e04aa98c6b1 100644
--- a/studio/backend/tests/test_checkpoint_compaction.py
+++ b/studio/backend/tests/test_checkpoint_compaction.py
@@ -1981,6 +1981,208 @@ def test_a_short_correction_survives_a_long_earlier_instruction():
assert items[-1] == "Actually make it Tetris", "the correction must read as current"
+def _user_turns(*texts):
+ """One user turn per text, each answered, as a real thread arrives."""
+ messages = []
+ for text in texts:
+ messages += [
+ {"role": "user", "content": text},
+ {"role": "assistant", "content": "ok"},
+ ]
+ return messages
+
+
+def test_the_opening_request_is_never_carried_without_the_turn_that_follows_it():
+ """The reservation used to spend its slot on the abandoned request and let the slot
+ cap drop the correction to it, which is the exact statement of the task the
+ reservation exists to prevent.
+
+ "Build Flappy Bird", "Actually build Tetris instead", "Add music" at max_items 2
+ carried ["Build Flappy Bird", "Add music"]: the model is told to build the game the
+ user walked away from, and to add music to it.
+ """
+ messages = _user_turns("Build Flappy Bird", "Actually build Tetris instead", "Add music")
+
+ items = carried_forward_items(messages, max_tokens = 4096, max_items = 2)
+
+ assert "Build Flappy Bird" not in items, "the abandoned request must not be carried alone"
+ assert items == ["Actually build Tetris instead", "Add music"]
+
+
+def test_a_correction_is_not_buried_by_the_increments_that_follow_it():
+ """The same bug with room to spare: nine turns into eight slots dropped the ONE turn
+ that changed direction, since the reservation is spent before the walk reaches it.
+
+ The measured output was ["Build Flappy Bird", "Add feature 1" ... "Add feature 7"].
+ """
+ messages = _user_turns(
+ "Build Flappy Bird",
+ "Actually build Tetris instead",
+ *[f"Add feature {index}" for index in range(1, 8)],
+ )
+
+ items = carried_forward_items(messages, max_tokens = 4096, max_items = 8)
+
+ assert "Actually build Tetris instead" in items, "the correction must survive"
+ assert items.index("Build Flappy Bird") < items.index("Actually build Tetris instead")
+ # Paid for by the OLDEST turn, so the newest increments are all still there.
+ assert items[-1] == "Add feature 7"
+
+
+def test_the_opening_task_survives_a_long_run_of_increments_with_no_correction():
+ """The case the reservation was added for, which the pair must not regress: a real
+ session states the task once at the front and then says nothing but increments, so a
+ plain newest-first walk carries eight ways to change a game it never names."""
+ messages = _user_turns(
+ "Build a Flappy Bird game",
+ *[f"increment {index}" for index in range(1, 20)],
+ )
+
+ items = carried_forward_items(messages, max_tokens = 4096, max_items = 8)
+
+ assert items[0] == "Build a Flappy Bird game", "the statement of the task must survive"
+ assert items[-1] == "increment 19", "and so must the newest increment"
+
+
+def test_the_opening_pair_is_taken_whole_or_not_at_all():
+ """The boundary of the rule. The pair needs two slots behind the newest usable turn,
+ so three slots is where it starts fitting. At two it is abandoned rather than
+ half-taken, because half of it is the abandoned request without its correction.
+ """
+ messages = _user_turns(
+ "Build Flappy Bird",
+ "Actually build Tetris instead",
+ "Add feature 1",
+ "Add feature 2",
+ )
+
+ two = carried_forward_items(messages, max_tokens = 4096, max_items = 2)
+ three = carried_forward_items(messages, max_tokens = 4096, max_items = 3)
+
+ # Two slots: the plain newest-first walk decides. Nothing wrong, only missing.
+ assert two == ["Add feature 1", "Add feature 2"]
+ # Three: the opening request and the correction to it, plus the newest turn.
+ assert three == ["Build Flappy Bird", "Actually build Tetris instead", "Add feature 2"]
+
+
+def test_a_token_budget_too_small_for_the_pair_keeps_the_correction():
+ """The same both-or-neither rule against the token cap rather than the slot cap.
+
+ A budget with room for the newest turn and ONE of the two opening turns used to buy
+ the abandoned request, because the reservation was charged first.
+ """
+ opening = (
+ "Build a Flappy Bird game in a single HTML file with canvas rendering, gravity, "
+ "pipes and a score counter."
+ )
+ correction = (
+ "Actually scrap that and build Tetris instead, same single HTML file, no "
+ "libraries at all."
+ )
+ messages = _user_turns(opening, correction, "add music")
+
+ # 45 tokens: the newest turn (10) plus either opening turn (34 or 30), never both.
+ items = carried_forward_items(messages, max_tokens = 45)
+
+ assert items == [correction, "add music"]
+
+
+def test_abandoning_the_reservation_does_not_reselect_the_opening_on_its_own():
+ """The fallback walk must exclude the opening turn, or it recreates the bug.
+
+ Abandoning the reservation is not enough on its own: the plain newest-first fallback
+ simply picked the opening up again whenever it was the cheaper of the two. A 10-token
+ "Build Tetris", a 27-token correction and a 17-token newest turn under a 40-token
+ budget carried ["Build Tetris", "Add music ..."] -- the abandoned game with the
+ correction to it dropped, which is the bug this pass exists to fix, reached by another
+ route.
+ """
+ opening = "Build Tetris"
+ correction = "Actually scrap that and build Flappy Bird instead, same single HTML file please."
+ newest = "Add music and a score counter to it now."
+ messages = _user_turns(opening, correction, newest)
+
+ items = carried_forward_items(messages, max_tokens = 40)
+
+ assert opening not in items, "the abandoned opening must not come back through the fallback"
+ assert items == [newest]
+
+
+def test_a_successor_nobody_could_afford_does_not_empty_the_block():
+ """The boundary of that exclusion, and the reason it is not unconditional.
+
+ When the successor costs more than the whole budget, no ordering carries it and there
+ was never a pair to take. Dropping the opening then buys nothing, because on these
+ threads the opening is the only affordable turn: the campaign's headline case is a
+ 43-token standing instruction followed by eight 160-token sections under a 100-token
+ budget, and excluding the opening sends the block out EMPTY, which is the failure the
+ whole pass exists to stop.
+
+ The same shape with a correction (a 10-token opening, a 56-token correction and a
+ 60-token newest turn under a 50-token cap) is indistinguishable from it by anything
+ but the English, so the two get the same answer and it is this one.
+ """
+ instruction = {"role": "user", "content": INSTRUCTION}
+ sections = []
+ for index in range(8):
+ sections += [
+ {"role": "user", "content": f"Section {index}. " + "x" * 600},
+ {"role": "assistant", "content": f"Section {index} noted."},
+ ]
+
+ assert carried_forward_items([instruction, *sections], max_tokens = 100) == [INSTRUCTION]
+
+ opening = "Build Tetris"
+ unaffordable = "Actually build Flappy Bird instead " + "x " * 80
+ newest = "Add music " + "y " * 100
+ items = carried_forward_items(_user_turns(opening, unaffordable, newest), max_tokens = 50)
+
+ assert items == [opening]
+
+
+def test_a_newer_restatement_still_wins_when_the_reserved_pair_fills_the_cap():
+ """Position is meaning, so it is read off the transcript, not off the walk.
+
+ The reserved pair can fill the slot cap before the walk reaches a newer copy of an
+ instruction at all, and the surviving copy then rendered at the position of the older
+ one: "metric", "imperial", "metric", "add a table" at max_items 3 came back as metric,
+ imperial, table, and the header's later-wins rule told the model imperial was current
+ at the moment the user had just restored metric.
+ """
+ messages = _user_turns(
+ "Use metric units",
+ "Use imperial units",
+ "Use metric units",
+ "Add a table",
+ )
+
+ items = carried_forward_items(messages, max_items = 3)
+
+ assert items == ["Use imperial units", "Use metric units", "Add a table"]
+ assert items.index("Use imperial units") < items.index("Use metric units")
+
+
+def test_an_opening_turn_with_nothing_after_it_is_still_reserved():
+ """Nothing can be hidden behind a turn that nothing followed, so the pair rule costs
+ the single-turn thread nothing: the reservation still applies at a cap of one."""
+ messages = [
+ {"role": "user", "content": INSTRUCTION},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "continue"},
+ {"role": "assistant", "content": "sure"},
+ ]
+
+ items = _select_items(
+ messages,
+ max_tokens = 4096,
+ max_items = 1,
+ min_chars = 0,
+ reserve_oldest = True,
+ )
+
+ assert items == [INSTRUCTION]
+
+
def test_a_nudge_is_still_excluded_without_the_length_floor():
"""`_CONTINUATIONS`, not the character count, is what keeps filler out."""
messages = [
@@ -1995,3 +2197,247 @@ def test_a_nudge_is_still_excluded_without_the_length_floor():
items = carried_forward_items(messages, max_tokens = 4096)
assert items == [INSTRUCTION]
+
+
+def test_the_carried_opening_pair_survives_the_next_compaction():
+ """The pair rule has to hold on the MERGED path, not only on the fresh walk.
+
+ The block arrives in the system turn (the ordinary case in a tool loop, and on every
+ request of an epoch already in force) holding the opening request and the correction
+ to it. The turns that produced them are long gone, so the merge is the only copy. The
+ plain newest-first re-cap then spent the budget on the increments evicted since,
+ skipped the long correction for cost, and STILL afforded the short opening: measured
+ at a 4096-token context, the block came back as "Build Flappy Bird" plus four Tetris
+ increments, which is the abandoned-request-plus-increments output the pair exists to
+ prevent, reached one compaction later.
+ """
+ opening = "Build Flappy Bird in one HTML file."
+ correction = (
+ "Actually scrap Flappy Bird and build Tetris instead: same single HTML file, no "
+ "libraries at all, keyboard controls for rotate and drop, a next-piece preview, a "
+ "score counter that scales with the number of lines cleared at once, and a pause key. "
+ "Keep the whole thing under three hundred lines and comment the collision routine. "
+ "Use a ten by twenty well, the standard seven tetrominoes with the standard colours, "
+ "wall kicks on rotation, a hold slot that can only be used once per piece, a ghost "
+ "piece showing where the current one will land, gravity that speeds up every ten "
+ "lines, and a game over overlay with the final score and a restart button. Draw "
+ "everything on a canvas element, no DOM nodes for the board, and keep the render loop "
+ "on requestAnimationFrame rather than a timer."
+ )
+ increments = [
+ "Add background music and a mute toggle in the corner, and make the score font bigger "
+ "so it can be read from across the room during a demo.",
+ "Give the well a subtle grid so the columns are easy to count, and dim the ghost piece "
+ "a little more than it is now, it reads as a real piece.",
+ "Add a short sound for a line clear and a different one for a tetris, generated with "
+ "the WebAudio oscillator so there are no asset files to ship.",
+ "Remember the high score in localStorage and show it beside the current score, and "
+ "make the restart button focusable so the keyboard alone can replay.",
+ ]
+ block = checkpoint.render_checkpoint([opening, correction])
+ assert checkpoint._block_items(block) == [opening, correction]
+
+ messages = [{"role": "system", "content": "you are helpful\n\n" + block}]
+ for text in increments:
+ messages += [
+ {"role": "user", "content": text},
+ {"role": "assistant", "content": "Done. " + "d " * 1400},
+ ]
+ messages += [{"role": "user", "content": "Here is the console trace. " + "z " * 2000}]
+
+ fitted, truncation = _fit(messages, context_length = 4096, max_tokens = 512)
+ items = checkpoint._block_items(fitted[0]["content"])
+
+ assert truncation["fits"] is True
+ assert correction in items, "the correction must not be dropped while the opening stays"
+ assert items.index(opening) < items.index(correction)
+ # Paid by the OLDEST increment, as the fresh walk pays, so the newest direction stays.
+ assert items[-1] == increments[-1]
+ assert increments[0] not in items
+
+
+def test_the_merged_recap_abandons_the_pair_the_same_way_the_fresh_walk_does():
+ """When the merged budget cannot hold the pair, half of it is still the bug.
+
+ Same shape as `test_abandoning_the_reservation_does_not_reselect_the_opening_on_its
+ _own`, one compaction later: a 10-token "Build Tetris", its 27-token correction and a
+ 17-token increment under a 40-token budget re-capped to ["Build Tetris", the
+ increment], the abandoned game with its correction dropped. The merge must reach the
+ same answer the fresh walk does, which is to drop the opening and keep the newest.
+ """
+ opening = "Build Tetris"
+ correction = "Actually scrap that and build Flappy Bird instead, same single HTML file please."
+ newest = "Add music and a score counter to it now."
+
+ merged = checkpoint._recap([opening, correction, newest], max_tokens = 40, max_items = 8, carried = 2)
+
+ assert merged == [newest], "the abandoned opening must not outlive the correction"
+ assert merged == carried_forward_items(_user_turns(opening, correction, newest), max_tokens = 40)
+ # Never at the cost of the newest direction: the pair is reserved BEHIND the newest
+ # affordable item, so the newest is taken before the pair is priced.
+ assert newest in merged
+
+
+def test_the_merged_recap_never_empties_a_block_it_could_have_filled():
+ """The both-or-neither rule must not answer "neither" with nothing left to say.
+
+ A block holding only the pair, re-capped under a budget that no longer holds both (the
+ user switched to a shorter context mid-thread), still goes out with one of them: the
+ correction where the correction is affordable, and the opening where it is not, which
+ is the `_takeable` escape hatch the fresh walk already had.
+ """
+ opening = "Build Tetris"
+ correction = "Actually scrap that and build Flappy Bird instead, same single HTML file please."
+
+ assert checkpoint._recap([opening, correction], max_tokens = 30, max_items = 8, carried = 2) == [
+ correction
+ ]
+ assert checkpoint._recap([opening, correction], max_tokens = 20, max_items = 8, carried = 2) == [
+ opening
+ ]
+
+
+def test_a_one_bullet_block_is_not_paired_with_a_turn_it_never_preceded():
+ """The unit is the BLOCK, so a one-bullet block is never held to a partner.
+
+ A block with a single bullet says nothing about what followed that instruction, and a
+ rule that reached past it into the freshly evicted turns for a partner would invent a
+ relationship the transcript never had, then drop the bullet whenever the invented
+ partner did not fit. That bullet is the only copy of it left anywhere in the request.
+ """
+ carried = (
+ "Build Tetris as a single HTML file with canvas rendering, keyboard controls for "
+ "rotate, drop and hold, a next piece preview, a ghost piece, a pause key and a "
+ "score counter, and keep the whole thing under three hundred lines so it stays "
+ "readable in one screen of a review."
+ )
+ spec = (
+ "Here is the spec for the scoring rules, please follow it exactly and do not round "
+ "anything off. A single line is one hundred points, a double is three hundred, a "
+ "triple is five hundred and a tetris is eight hundred, all multiplied by the "
+ "current level. A soft drop adds one point per cell travelled and a hard drop adds "
+ "two points per cell. Back to back tetrises get a fifty percent bonus on the second "
+ "and every one after it, and a combo adds fifty points per chained clear on top of "
+ "that. The level goes up every ten lines cleared and the gravity interval shortens "
+ "by ten percent each level, down to a floor of fifty milliseconds, and the level "
+ "number is shown beside the score at all times so the player can see when the next "
+ "speed up is due to arrive. A perfect clear is worth two thousand points at level "
+ "one and scales with the level like everything else, a t spin single is eight "
+ "hundred, a t spin double is twelve hundred and a t spin triple is sixteen hundred, "
+ "and every one of those is announced in the corner for one second so the player "
+ "learns which move earned which score."
+ )
+ newest = (
+ "Add background music with a mute toggle in the corner, a short sound for a line "
+ "clear and a different one for a tetris, all generated with the WebAudio oscillator "
+ "so there are no asset files to ship with the page. The music should start muted on "
+ "first load, remember the mute state in localStorage and fade rather than cut when "
+ "it is toggled off."
+ )
+ block = checkpoint.render_checkpoint([carried])
+ messages = [{"role": "system", "content": "you are helpful\n\n" + block}]
+ messages += _user_turns(spec, newest)
+ messages += [{"role": "user", "content": "Here is the console trace. " + "z " * 6000}]
+
+ fitted, truncation = _fit(messages, context_length = 4096, max_tokens = 512)
+ items = checkpoint._block_items(fitted[0]["content"])
+
+ assert truncation["fits"] is True
+ # 358 tokens: the newest turn (94) and the carried bullet (75), never the 279-token
+ # spec. Pairing the bullet with the spec would drop it too.
+ assert items == [carried, newest]
+
+
+def _restated_correction_block():
+ """A VALID block whose bullets are not [opening, successor, ...].
+
+ The user restated the correction after an intervening rule, and the block renders each
+ item at its newest copy, so the correction sits behind the rule that came between it
+ and the opening. Nothing here is malformed: the fresh walk reserved the pair and took
+ it whole, and this is what that looks like once rendered.
+ """
+ opening = "Build Tetris"
+ correction = "Actually scrap that and build a Flappy Bird clone instead, please now."
+ intervening = "Dark theme"
+ newest = "Add music!"
+ prior = carried_forward_items(
+ _user_turns(opening, correction, intervening, correction, newest), max_tokens = 60
+ )
+ assert prior == [opening, intervening, correction, newest]
+ return opening, correction, prior
+
+
+def test_a_correction_restated_out_of_order_is_not_dropped_by_the_merge():
+ """The merge must not decide which bullets were the pair by counting from the front.
+
+ The block reads [opening, intervening rule, correction, newest], so reserving its
+ first TWO bullets reserves the opening and the intervening rule and lets the walk drop
+ the correction: measured at a 60-token budget with two 10-token instructions evicted
+ since, the block came back as "Build Tetris", "Dark theme", "Add music!", "Add a
+ menu", "Add a timer" -- the abandoned game carried, the correction to it gone, and
+ WORSE than no reservation at all, which keeps the correction here.
+ """
+ opening, correction, prior = _restated_correction_block()
+ messages = [
+ {"role": "system", "content": "you are helpful\n\n" + checkpoint.render_checkpoint(prior)}
+ ]
+ for text in ("Add a menu", "Add a timer"):
+ messages += [
+ {"role": "user", "content": text},
+ {"role": "assistant", "content": "ok. " + "r " * 260},
+ ]
+ messages += [{"role": "user", "content": "Here is the console trace. " + "z " * 600}]
+
+ fitted, truncation = _fit(messages, context_length = 800, max_tokens = 200)
+ items = checkpoint._block_items(fitted[0]["content"])
+
+ assert truncation["fits"] is True
+ assert items == ["Dark theme", correction, "Add music!", "Add a timer"]
+ assert opening not in items, "the abandoned request must not outlive its correction"
+ # Paid for by an older increment, never by the newest direction the user gave.
+ assert items[-1] == "Add a timer"
+
+
+def test_the_merge_never_states_the_abandoned_task_whichever_bullet_corrects_it():
+ """The invariant, stated without naming the successor: the block's first bullet is
+ never carried while any affordable bullet beside it is dropped.
+
+ Both positional readings fail this on their own. The plain newest-first re-cap keeps
+ the cheap opening and the cheap intervening rule and drops the 25-token correction
+ ("Build Tetris", "Dark theme", "Add music!" plus three increments at a 60-token
+ budget), and reserving the first two bullets does the same thing one increment
+ earlier. Holding the block WHOLE or dropping its first bullet needs neither reading.
+ """
+ opening, correction, prior = _restated_correction_block()
+ fresh = ["Add a menu", "Add a timer", "Add a pause"]
+
+ merged = checkpoint._recap(prior + fresh, max_tokens = 60, max_items = 8, carried = len(prior))
+
+ assert merged == ["Dark theme", correction, "Add music!", fresh[-1]]
+ assert opening not in merged, "the abandoned request must not outlive its correction"
+ # Never at the cost of the newest direction, and never empty.
+ assert merged[-1] == fresh[-1]
+ # The plain walk is no safe fallback: it states the abandoned task itself, so "stop
+ # reserving on the merged path" would not have fixed this.
+ plain = checkpoint._recap(prior + fresh, max_tokens = 60, max_items = 8)
+ assert opening in plain and correction not in plain
+
+
+def test_holding_the_block_whole_does_not_freeze_it_on_the_first_epoch():
+ """The unit is reserved BEHIND the newest usable item and abandoned when it will not
+ fit whole, so a block cannot take every slot forever and starve the newer rules.
+
+ Without that the merge would be sticky-oldest: eight carried bullets would hold all
+ eight slots on every later compaction and no instruction the user gave afterwards
+ could ever enter the block the model is shown.
+ """
+ block = [f"standing rule {index} " + "w " * 20 for index in range(1, 5)]
+ seen_rounds = []
+ for round_index in range(1, 7):
+ fresh = [f"new rule {round_index}{side} " + "w " * 20 for side in ("a", "b")]
+ block = checkpoint._recap(block + fresh, max_tokens = 200, max_items = 8, carried = len(block))
+ assert block[-1] == fresh[-1], "the newest rule is always carried"
+ seen_rounds.append(sum(1 for item in block if item.startswith("standing rule")))
+
+ assert seen_rounds[0] == 4, "the carried block survives while it fits"
+ assert seen_rounds[-1] == 0, "and ages out instead of holding every slot forever"