Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12320,6 +12320,14 @@ def handle_post(handler, parsed) -> bool:
branch_title = f"{source_title} (fork)"

# Create new session inheriting workspace/model/profile
from api.session_ops import truncate_context_for_display_keep

fork_keep = keep_count if keep_count is not None else len(source_messages)
forked_context = truncate_context_for_display_keep(
getattr(source, "context_messages", None),
source_messages,
fork_keep,
)
branch = Session(
workspace=source.workspace,
model=source.model,
Expand All @@ -12332,8 +12340,8 @@ def handle_post(handler, parsed) -> bool:
enabled_toolsets=getattr(source, "enabled_toolsets", None),
context_length=getattr(source, "context_length", None),
threshold_tokens=getattr(source, "threshold_tokens", None),
# context_messages — deep copy so the branch has independent context
context_messages=copy.deepcopy(getattr(source, "context_messages", None) or []),
# context_messages — truncated to fork prefix (not full parent copy)
context_messages=copy.deepcopy(forked_context),
# Gateway routing — inherit from source
gateway_routing=copy.deepcopy(getattr(source, "gateway_routing", None)),
# Context engine — inherit state so branch's context engine starts correctly
Expand Down
23 changes: 23 additions & 0 deletions api/session_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,29 @@ def _truncation_watermark_for(messages):
return 0.0


def truncate_context_for_display_keep(
context_messages: list | None,
full_messages: list | None,
keep: int,
) -> list:
"""Align model context with display prefix ``full_messages[:keep]``."""
if keep <= 0:
return []
ctx = context_messages if isinstance(context_messages, list) else []
msgs = full_messages if isinstance(full_messages, list) else []
if not ctx:
return []
if len(ctx) == len(msgs):
return ctx[:keep]
if len(msgs) == 0:
return []
# Context tail aligns with full display transcript; preserve leading-only rows.
prefix_len = max(0, len(ctx) - len(msgs))
Comment on lines +82 to +87

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Unhandled alignment when len(ctx) < len(msgs). When context_messages is shorter than the display transcript (e.g. after partial context pruning or a future compaction strategy that drops old LLM-only rows), prefix_len becomes 0, so the function returns ctx[:keep] treating context as front-aligned with msgs. But the code's own comment says "Context tail aligns with full display transcript", meaning the correct slice for the shorter case would be ctx[len(ctx) - min(len(ctx), keep):]. As written, a fork at keep=1 with a 2-item ctx and 3-item msgs returns ctx[0] instead of ctx[-2] (the entry that actually corresponds to msgs[0]). Adding an explicit branch or at minimum a guard assertion would prevent silent mistruncation if this case is ever reachable.

Suggested change
if len(ctx) == len(msgs):
return ctx[:keep]
if len(msgs) == 0:
return []
# Context tail aligns with full display transcript; preserve leading-only rows.
prefix_len = max(0, len(ctx) - len(msgs))
if len(ctx) == len(msgs):
return ctx[:keep]
if len(msgs) == 0:
return []
if len(ctx) < len(msgs):
# Context is shorter than display — tail-aligned; slice from the aligned end.
aligned_keep = max(0, keep - (len(msgs) - len(ctx)))
return ctx[:aligned_keep]
# Context tail aligns with full display transcript; preserve leading-only rows.
prefix_len = len(ctx) - len(msgs)

prefix = ctx[:prefix_len]
suffix = ctx[prefix_len:]
return prefix + suffix[:keep]
Comment on lines +86 to +90

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Compaction prefix always survives the fork regardless of keep — When prefix_len > 0, prefix + suffix[:keep] always includes all leading compaction-only rows even if keep=1. If a compaction summary was generated after the fork point (i.e. it summarises turns that include post-fork content), those rows will silently leak post-fork knowledge into the branch, which is the exact class of bug this PR targets. The PR notes this as a follow-up for context_engine_state, but the same window exists in the compaction prefix. Consider at minimum adding a test that asserts the expected behaviour so the contract is visible and a future compaction-aware truncation can be slotted in without regression.



def retry_last(session_id: str) -> dict[str, Any]:
"""Truncate the session to before the last user message, return its text.

Expand Down
34 changes: 34 additions & 0 deletions tests/test_issue_branch_context_at_fork.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Branch must not inherit full parent context_messages (#5096 A)."""

import copy

from api.session_ops import truncate_context_for_display_keep


def test_truncate_context_for_display_keep_drops_parent_tail():
msgs = [
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
{"role": "user", "content": "after-fork"},
]
# Same-length context as display — fork at keep=2 matches messages[:2]
ctx = copy.deepcopy(msgs)
out = truncate_context_for_display_keep(ctx, msgs, 2)
assert len(out) == 2
assert out[-1]["content"] == "a1"
assert "after-fork" not in [m["content"] for m in out]


def test_truncate_context_preserves_leading_compaction_row():
msgs = [
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
]
ctx = [
{"role": "user", "content": "compaction-ref-only"},
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
]
out = truncate_context_for_display_keep(ctx, msgs, 2)
assert len(out) == 3
assert out[0]["content"] == "compaction-ref-only"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Missing newline at end of file — most linters and git diff warn about this.

Suggested change
assert out[0]["content"] == "compaction-ref-only"
assert out[0]["content"] == "compaction-ref-only"

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Loading