Blog · · 10 min read
AI agent session branching without replaying side effects

AI agent session branching becomes dangerous when a product copies more than conversation history. A fork from an earlier checkpoint may inherit stale authorization, queued writes, and tool results that describe actions already completed in the real world. If both branches continue against live systems, the user can send the same message twice, create duplicate tickets, reserve inventory twice, or leave product state split between incompatible plans.
Treat a branch as a new speculative workflow derived from an immutable fork point. Copy context with provenance, keep completed effects as receipts, fence pending work, issue branch-scoped authority, and let only one selected branch commit new effects. This article defines that contract and shows how to test it.
Why a conversation fork is not a safe workflow fork
Conversation products already expose useful branching mechanics. The OpenAI Codex app server documents thread/fork, which copies stored history into a new thread with its own identifier. LangChain branching chat selects a parent checkpoint and creates a new branch by sending an alternate message. Visual Studio Code checkpoint guidance lets a user restore an earlier workspace and conversation state or fork an independent session.
Those mechanics answer which messages and workspace changes belong to a continuation. They leave out effects beyond the agent runtime. A checkpoint may say that the agent called create_ticket, but the ticket system decides whether ticket 4182 exists. Replaying the checkpoint does not undo or clone that ticket. It only repeats the evidence that a call happened.
A safe design separates five kinds of state before it allows a fork:
| State class | Example | Fork behavior |
|---|---|---|
| Conversation context | User messages, model responses, selected plan | Copy with parent and checkpoint provenance |
| Read snapshot | Account balance at version 41, inventory query result | Copy as historical evidence and mark its observed version |
| Completed effect | Ticket 4182 created, email delivered, refund submitted | Copy the receipt only and forbid replay under the old action ID |
| Pending work | Queued tool call, callback, approval, retry timer | Fence, cancel, or reconcile before the child can act |
| Authority | User session, delegated token, approval decision | Do not copy as standing permission; re-evaluate for the branch and current action |
Without this classification, a branch is a copy of implementation records, not a trustworthy alternate future.
The need is not limited to chat interfaces. A Pydantic AI Harness branching request asks for message-level forks to support debugging, comparison, and controlled experiments. Those uses are safer when branches stay speculative. The risk appears when a debugging or comparison branch still has access to the production tools inherited from its parent.
Define the branch manifest
Create one immutable manifest when the fork begins. It records what the child may trust, what it may observe, and what it may change. Do not infer this policy later from the copied transcript.
{
"branch_id": "br_02JY8A",
"parent_run_id": "run_02JXZT",
"fork_checkpoint_id": "cp_0047",
"forked_by": "user_184",
"forked_at": "2026-09-10T09:42:16Z",
"purpose": "compare_resolution_plan",
"parent_product_version": 8841,
"context_snapshot": {
"message_through": "msg_119",
"memory_version": 27,
"retrieval_snapshot": "ret_63"
},
"effect_boundary": {
"last_receipt_id": "eff_791",
"pending_effect_ids": ["eff_792"]
},
"authority": {
"mode": "speculative",
"allowed_tool_classes": ["read"],
"expires_at": "2026-09-10T10:12:16Z"
},
"status": "isolated"
}
parent_product_version is a precondition, not a promise that the product will remain unchanged. last_receipt_id fixes the effect history inherited from the parent. Every completed receipt remains visible to the branch as evidence, but the branch cannot turn it back into an executable request.
Make purpose operational. A branch created to compare plans should default to read-only tools and simulated writes. A branch created to correct a draft may permit branch-local artifact edits. A recovery fork can request production authority later, but it should pass a separate promotion gate first.
Freeze the fork point before copying context
Fork only from a durable checkpoint whose ownership is known. A visible message is not enough if a worker is still running tools behind it.
Use this sequence:
- Acquire a short fork lease on the parent run.
- Stop accepting new parent instructions at the chosen checkpoint.
- Drain, cancel, or mark every pending tool operation as
outcome_unknown. - Reconcile unknown operations against the authoritative product before continuing.
- Write the immutable effect boundary and current product version.
- Create the child manifest and branch-local state.
- Release the lease and expose the branch to the user.
The parent can resume after the fork, but the boundary must stay fixed. If a callback completes between steps three and five, reconciliation must add its receipt before the child is created. Otherwise the child can believe an effect is pending when it has already committed.
A short database transaction can own the control records, but it cannot make an external API call atomic. Record an operation ID before calling the external service, use an idempotency key where the service supports one, and reconcile the outcome before marking the fork point stable. When the outcome cannot be established, block production-capable branching and show the unresolved operation to an operator.
Give each branch less authority than its parent
Do not copy the parent's token, approval, or tool grant into the child. Authority may have expired, the user may no longer hold the same role, and the branch may propose an action that the original approval never covered.
Issue a branch-scoped capability with these claims:
- branch identifier and parent checkpoint
- current user and tenant
- allowed tool classes
- resource scope
- maximum cost or effect count
- environment, such as simulation or production
- expiry time
- policy version
The tool gateway should require the branch identifier on every call. It should deny a write from a speculative branch even if the underlying user could normally perform that write. This prevents a prompt or model decision from upgrading comparison mode into production mode.
A speculative adapter can return realistic receipts without touching the live system:
def call_tool(branch, tool, args):
capability = load_branch_capability(branch.id)
require_current_user_authority(capability.user_id, tool, args)
if tool.effect_class == "write" and capability.environment != "production":
return simulate_write(
branch_id=branch.id,
tool=tool.name,
arguments=args,
based_on_version=branch.parent_product_version,
)
if tool.effect_class == "read":
result = tool.execute(args)
return attach_observed_version(result)
raise BranchPolicyDenied(tool=tool.name, branch_id=branch.id)
Simulation must be explicit in tool results. A model should never confuse a simulated refund with a completed refund. Store environment, simulated, and authoritative_receipt_id as separate fields, and render them clearly in the interface.
Keep effects out of the merge model
Message text can be merged. External effects require explicit selection and execution.
Assume the parent branch drafted a replacement shipment while the child drafted a refund. You can compare both plans. You cannot merge the shipment and refund because both look useful. The selection unit is the branch outcome and its proposed effect plan, not a diff of assistant messages.
The OpenClawAI session-branching guide already covers visible fork points, context provenance, branch-local queued writes, stale-client protection, security, and recovery. For effects outside the session tree, completed effects remain immutable history, proposed effects stay branch-local, and only promotion can create new production work.
Represent each proposed write as an intent:
{
"intent_id": "int_553",
"branch_id": "br_02JY8A",
"tool": "issue_refund",
"arguments_hash": "sha256:normalized-request",
"resource": "order_9021",
"expected_product_version": 8841,
"expected_state": "eligible_for_refund",
"simulation_receipt": "sim_301",
"status": "proposed"
}
The intent contains no reusable credential. It cannot execute itself. Promotion turns a validated intent into a new action with a new action ID and current authorization.
Compare branches before promotion
Branch comparison needs declared criteria. Otherwise the product will select whichever response sounds more polished.
For a support workflow, compare:
- whether the branch satisfies the user's current request
- whether required facts come from authoritative reads
- unresolved assumptions and missing inputs
- policy eligibility
- projected cost and reversibility
- proposed effect count and effect class
- product version used by each read
- evaluation results relevant to the workflow
Show the user material differences. If one branch relies on inventory version 8841 and another refreshed against version 8850, that difference matters more than wording. If the selected branch contains a simulated write, show its exact proposed arguments and the product state it expects.
Do not let an evaluator auto-promote a high-impact branch unless product policy permits autonomous promotion for that action class. Comparison quality and execution authority are separate controls.
Promote exactly one branch
Promotion is a fresh transaction. It does not resume the child's simulated tool calls against production.
def promote(branch_id, user_id):
with database.transaction():
branch = lock_branch(branch_id)
parent = lock_parent_resolution(branch.parent_run_id)
require(branch.status == "isolated")
require(parent.selected_branch_id is None)
require_current_user_authority(user_id, branch.proposed_intents)
require_product_version(branch.parent_product_version)
require_no_unresolved_parent_effects(branch.parent_run_id)
promotion = create_promotion(
branch_id=branch.id,
idempotency_key=f"promote:{branch.id}",
policy_version=current_policy_version(),
)
parent.selected_branch_id = branch.id
branch.status = "selected"
archive_other_branches(parent.id, except_id=branch.id)
enqueue_fresh_execution_plan(promotion.id)
return promotion.id
The uniqueness constraint on selected_branch_id or the promotion key must make two concurrent promoters resolve to one winner. The loser receives the already-selected branch, not a retry invitation.
After the database transaction, execute the selected plan through the normal production tool path. Re-read mutable state, re-check preconditions, assign fresh action IDs, use idempotency controls, and store authoritative receipts. If the product version changed, return the branch to needs_refresh instead of forcing the stale plan through.
Promotion can fail after selection but before every effect completes. Keep the selected branch selected, record a typed partial outcome, and use the ordinary recovery or compensation path. Do not reopen losing branches automatically. That would turn a failed promotion into an undeclared second choice.
Handle the failure cases explicitly
| Failure | Required response |
|---|---|
| Parent has an unresolved external call | Block production-capable fork, reconcile, then establish the effect boundary |
| Branch capability expires | Keep the branch readable, require a fresh authorization decision before promotion |
| Product version changes | Refresh reads and re-evaluate preconditions; do not execute stale intents |
| Two users promote different branches | Commit one selection with compare-and-swap and return the winner to the other user |
| Losing branch tries to write | Deny at the tool gateway and record the policy failure |
| Promotion request repeats | Return the existing promotion receipt through its stable idempotency key |
| Selected plan partially commits | Preserve receipts, expose partial status, and run normal compensation or recovery |
| User restores an old checkpoint after promotion | Create a new speculative branch whose effect ledger includes the promoted receipts |
Restoring an old checkpoint after promotion must carry the promoted receipts forward. A user can rewind the conversation view, but the product cannot rewind a delivered email or completed transfer by hiding its receipt.
Verify AI agent session branching with adversarial fixtures
A happy-path test proves only that two chat histories can diverge. Test the effect boundary and promotion race.
Build fixtures for:
- a read-only branch that observes a versioned account record
- a reversible proposed write that stays simulated
- an irreversible completed effect before the fork
- a callback that finishes while the fork lease is held
- an external call whose outcome remains unknown
- a branch with expired user authority
- a product record changed after the fork
- two users promoting different branches concurrently
- a repeated promotion request
- a losing branch that calls the tool gateway directly
Assert these invariants:
- no child replays an action before its effect boundary
- completed receipts remain visible in every descendant
- pending or unknown work is reconciled before production promotion
- speculative branches cannot perform live writes
- exactly one branch becomes selected for a parent
- promotion uses current authorization and current product state
- every production effect maps to one selected branch and one fresh action ID
- archived branches remain inspectable but cannot regain authority implicitly
Also test the interface. Microsoft describes checkpoints as a way to restore changes and continue from an earlier point. Your product must tell the user which parts were restored, which real-world effects remain, whether the branch is speculative, and what promotion will do. A simple "forked" badge does not communicate that contract.
Common implementation mistakes
Copying credentials with the transcript. A credential is authority, not context. Re-issue it for the branch purpose and current user.
Replaying tools to reconstruct state. Reconstruct branch state from snapshots and receipts. Tool replay can create new external effects.
Letting every branch write with different idempotency keys. Idempotency protects duplicate representations of one intended action. It does not make two competing actions compatible.
Merging messages and assuming effects follow. Message trees can merge text. Product effects need selection, current preconditions, and explicit execution.
Promoting simulated receipts. A simulation supports comparison. Production execution needs a new action record and authoritative receipt.
Ignoring parent work still in flight. Establishing a fork point while callbacks are unresolved creates a moving effect boundary.
Using branch rank as the winner. Branch order is history, not quality. Compare declared outcomes and require the correct authority for the action class.
Implement the smallest safe branching contract
Start with one workflow where alternate plans are valuable and writes can remain simulated until selection. Add a branch manifest, immutable effect boundary, read-only capability, proposed-intent record, and single-winner promotion transaction. Run the ten adversarial fixtures before exposing the control.
Do not begin with arbitrary branch merging. First prove that a fork can copy context without copying execution authority, that no completed effect can replay, and that exactly one selected branch can create a verified future. Ship the branching control only after those invariants pass.