AI AgentsAI Agent Execution & Lifecycle

How do AI agents support forking, steering, and selecting execution paths?

Question 273 of 280 · Updated

On this page

AI agents often face situations where more than one reasonable action is possible. A coding agent may discover two plausible fixes. A research agent may need to test competing hypotheses. A support agent may need to compare several remedies before committing to one.

Instead of committing immediately to a single trajectory, a production agent system can fork execution from a saved state, steer each alternative, evaluate the resulting paths, and select one path to continue.

This is different from simply routing to one next node, retrying a failed step, or pausing for human approval. Forking creates alternative histories from a common point. Steering changes what a particular branch does next. Selection compares the branches against explicit criteria and chooses which one is allowed to become the authoritative continuation.

1. What do forking, steering, and selecting mean?#

These are three related but distinct operations:

  • Forking: Create a new execution path from a known checkpoint or state snapshot while preserving the original path and its history.
  • Steering: Change the instructions, constraints, tool choices, parameters, or state of one branch so it explores a different approach.
  • Selecting: Compare completed or partially completed branches and designate one as the chosen continuation, while retaining the others for audit or later analysis.

Think of a navigation app that saves a route at a junction. You can explore Route A and Route B from the same starting point, compare travel time and road closures, and choose one. The original starting point remains available; exploring an alternative does not rewrite history.

In an agent system, the “route” is a sequence of model decisions, tool calls, observations, state transitions, and results.

2. Why fork an agent execution?#

Forking is useful when the system has genuine uncertainty and the alternatives can be evaluated independently.

Common use cases include:

  1. Coding: Try two isolated fixes from the same repository state and compare tests, maintainability, and patch size.
  2. Research: Explore competing explanations using different evidence strategies.
  3. Planning: Compare alternative schedules, resource allocations, or action sequences.
  4. Customer support: Evaluate multiple remedies against policy, eligibility, and customer impact before taking an irreversible action.
  5. Incident response: Explore diagnostic hypotheses without changing production infrastructure.
  6. Prompt or tool strategy experiments: Compare alternative instructions, retrieval settings, or tool sequences against the same initial task.

Forking is usually unnecessary when a deterministic workflow already specifies the correct next step, when the alternatives cannot be evaluated, or when the extra cost and complexity exceed the value of exploration.

3. How does a fork work?#

A reliable implementation needs a durable state boundary.

A typical sequence is:

  1. Persist the current execution state at a checkpoint.
  2. Record the source run, checkpoint identifier, state version, and workflow or graph version.
  3. Create one or more child branches referencing that exact parent checkpoint.
  4. Give each branch an independent execution identity and isolated mutable state.
  5. Apply branch-specific steering instructions or state changes.
  6. Execute each branch under bounded resource and permission limits.
  7. collect evidence and evaluate branch results.
  8. Select a branch, reject all branches, or request another controlled exploration.
  9. Resume the selected branch under the current authorization and freshness rules.

A checkpoint should contain enough information to reconstruct the agent's operational state: task objective, messages or relevant context, completed steps, pending work, tool results, routing position, constraints, and version metadata.

A branch record should also preserve lineage:

  • branch_id and parent_branch_id
  • parent_checkpoint_id
  • source run and tenant/workspace identity
  • creation time and creator
  • workflow, prompt, model, and tool versions
  • steering instructions and state delta
  • status, resource usage, and evaluation result
  • selected/rejected decision and decision evidence

This creates a branch tree rather than an ambiguous collection of runs.

4. Checkpoints, replay, and forks are not the same#

These concepts are easy to confuse:

OperationWhat it doesDoes it create an alternative history?
ResumeContinues unfinished work from the latest saved stateUsually no
RetryRe-executes a failed operation according to retry policyNot necessarily
ReplayRe-executes steps after a historical checkpointIt can produce a new execution history
State updateChanges state and persists a new checkpointCan establish a different continuation
ForkStarts an alternative trajectory from a historical checkpointYes
RouteChooses one next node or toolNot by itself

A particularly important implementation detail is that replay is not necessarily a cache read. Re-executed model calls, API requests, and interrupt points can produce different results. A replay may therefore diverge from the original run.

LangGraph provides checkpoint-based time travel: inspect state history, choose a checkpoint, and resume from it; modifying state at a historical checkpoint creates a new fork in execution history. The source history is retained. See the official time-travel and persistence documentation in the references.

5. How should an agent steer a branch?#

Steering should be explicit, typed, and scoped to the branch being changed. Avoid silently mutating shared conversation state.

Typical steering inputs include:

  • Objective: Change what the branch is trying to accomplish.
  • Constraints: Add a budget, deadline, policy restriction, or quality threshold.
  • Strategy: Prefer a particular algorithm, tool, evidence source, or sequence.
  • State correction: Replace a stale or incorrect assumption with verified information.
  • Tool permissions: Restrict the branch to read-only tools or a defined allowlist.
  • Stopping rule: Stop after a fixed number of steps, tokens, tool calls, or elapsed time.

For example, a coding agent may fork from the same clean commit:

  • Branch A: Fix the null-handling bug with a minimal conditional.
  • Branch B: Fix it by validating the input at the API boundary.
  • Branch C: Investigate whether the issue is caused by a broader schema mismatch.

Each branch receives a different steering instruction, but all branches retain the same baseline commit and test requirements.

Steering should not silently change the original branch or another branch. Store the steering delta and its author so the result is reproducible and reviewable.

6. How should branches be isolated?#

A forked state snapshot does not automatically isolate the outside world.

This is one of the most important production safety rules: branch-local state can be copied, but external side effects cannot be rolled back merely by creating a new checkpoint.

Suppose two branches both call a payment API. Even if their internal states are separate, both payments may execute.

Use these safeguards:

  1. Immutable parent snapshots: Never overwrite the source checkpoint when creating a branch.
  2. Copy-on-write state: Branches receive independent mutable state; immutable evidence can be shared by reference.
  3. Separate execution IDs: Logs, traces, caches, and tool outputs must be attributable to the correct branch.
  4. Read-only exploration by default: Exploratory branches should normally inspect, calculate, draft, or simulate rather than mutate production systems.
  5. Side-effect gateway: Require explicit authorization before sending messages, issuing refunds, changing records, deploying code, or performing other irreversible actions.
  6. Idempotency keys: If a permitted side effect is retried, ensure the external system can recognize the same logical operation.
  7. Tenant and user isolation: Never allow a branch to inherit access to another tenant's state or credentials.
  8. Secret minimization: Pass only the credentials and scopes needed by that branch.

A branch is not a security boundary by itself. Enforce authorization in the tool gateway and external service, not only in the agent prompt.

7. How do you select the best execution path?#

Do not choose a branch merely because its final answer sounds more confident or is longer.

Define an evaluation contract before launching branches. Depending on the task, it may include:

  • correctness against authoritative evidence
  • satisfaction of the user's objective
  • policy and safety compliance
  • test results or verified postconditions
  • completeness and quality
  • latency and token/tool cost
  • reversibility and operational risk
  • freshness of evidence
  • maintainability and complexity

A simple weighted score can help rank candidates:

Score = 0.35C + 0.25S + 0.20Q + 0.10E + 0.10F

Where each factor is normalized to 0–100:

  • C = correctness
  • S = safety and policy compliance
  • Q = task quality
  • E = efficiency
  • F = freshness or evidence quality

However, safety and correctness should often be hard gates, not merely weighted factors. A branch that violates a policy or fails a critical test must not win just because it is cheap or fast.

A robust selection sequence is:

  1. Reject branches that violate hard constraints.
  2. Check evidence and required postconditions.
  3. Compare quality among eligible branches.
  4. Consider latency, cost, and operational complexity.
  5. Select the best eligible branch or declare that none is acceptable.
  6. Record why the chosen branch won and why alternatives were rejected.

For high-impact actions, require human approval before committing the selected branch's side effects.

8. Beginner-friendly numerical example#

Imagine a software agent investigating a checkout failure.

The agent starts from checkpoint CP-104. Three hypotheses are plausible:

  • Branch A: A null value is not handled.
  • Branch B: A tax calculation uses a stale configuration.
  • Branch C: A recent API schema change is incompatible.

The agent forks three read-only branches from the same checkpoint. Each branch runs targeted inspection and tests.

MeasureBranch ABranch BBranch C
Focused tests passed18/2020/2017/20
Regression tests passed96/10099/10092/100
Evidence confidence (reviewed)72/10094/10068/100
Runtime42 sec55 sec61 sec
Tool/model cost$0.08$0.11$0.13

Branch B has the strongest test and evidence results. The system then performs a clean validation run against the selected patch, checks that no prohibited files changed, and asks for approval before merging.

The important point is that the agent did not deploy three fixes. It explored three alternatives in isolated, read-only branches, selected one based on evidence, and only then requested permission for the consequential action.

If each branch costs $0.08, $0.11, and $0.13, exploration costs $0.32 in total. If a single-path attempt would cost $0.10, the extra $0.22 is justified only if the higher probability of finding a correct fix is worth it.

9. How many branches should an agent create?#

More branches do not automatically produce better decisions. They increase inference cost, tool traffic, evaluation effort, and the chance of inconsistent evidence.

A practical policy is:

  • Start with two alternatives when uncertainty is meaningful.
  • Allow a third branch only when it explores a materially different hypothesis.
  • Set a maximum branch count per task.
  • Set per-branch token, tool-call, wall-clock, and monetary budgets.
  • Stop early when one branch satisfies all hard gates and is clearly superior.
  • Avoid duplicating branches that share the same assumptions and strategy.

For example, if three branches each use 8,000 tokens, total exploration consumes 24,000 tokens before selection. A branch budget of 10,000 tokens and a task budget of 25,000 tokens prevent uncontrolled expansion.

Use adaptive branching: start small, inspect evidence, and expand only if the current candidates remain inconclusive.

10. Common failure scenarios and prevention#

A. Stale parent checkpoint#

A branch is created from an old checkpoint after the source execution has already changed.

Prevention: Bind the fork to an immutable checkpoint ID and state version. Check freshness before committing.

B. Cross-branch state leakage#

One branch reads another branch's intermediate result or overwrites shared mutable state.

Prevention: Use isolated namespaces, copy-on-write state, explicit artifact sharing, and branch-scoped access controls.

C. Duplicate external side effects#

Two branches both issue a refund, send a customer email, or deploy a change.

Prevention: Keep exploration read-only. Use an authorized commit gateway, idempotency keys, and unique operation IDs.

D. Replay is mistaken for deterministic reproduction#

A branch is expected to reproduce the exact original result, but an LLM or external API returns a different output.

Prevention: Persist model and tool versions, prompts, inputs, retrieved evidence, and relevant outputs. Treat replay as re-execution unless the operation is explicitly deterministic or its result is recorded and reused.

E. Selection favors a misleading score#

A branch receives a high model-judge score but fails a real-world postcondition.

Prevention: Use deterministic checks and authoritative external evidence as hard gates. Calibrate model judges and use human review for high-impact decisions.

F. Branch explosion#

The agent keeps generating alternatives without convergence.

Prevention: Enforce maximum branch count, depth, cost, runtime, and a clear stopping condition.

G. The chosen branch cannot safely resume#

The selected branch references an expired credential, changed API, stale resource, or incompatible workflow version.

Prevention: Revalidate permissions, external state, schemas, and workflow compatibility immediately before resuming or committing.

H. A rejected branch still has running workers#

A losing branch continues consuming resources or attempts a late write.

Prevention: Cancel branch workers, revoke branch-scoped leases, and ensure cancellation is acknowledged before finalizing selection.

11. How does this relate to human-in-the-loop steering?#

Forking and human approval solve different problems.

  • Human-in-the-loop pause: A run is paused at a defined point; a person approves, rejects, or edits a pending action before the run resumes.
  • Forking: The system creates alternative execution histories from a shared checkpoint.
  • Human steering of a fork: A person changes the objective, constraints, or strategy of one specific alternative.
  • Branch selection: A person or policy chooses which alternative should continue.

A human can inspect multiple branches and select one, but selection must not automatically authorize every side effect in that branch. Approval should be bound to the exact branch, checkpoint, action, and state version being approved.

This is related to, but distinct from, the paused-agent inspection and steering pattern covered in Question 271.

12. How can LangGraph support this pattern?#

LangGraph's persistence and time-travel features provide useful building blocks:

  • Compile a graph with a checkpointer so state is persisted at super-step boundaries.
  • Use state-history inspection to locate a checkpoint.
  • Resume from a historical checkpoint to replay the subsequent steps.
  • Update state at a historical checkpoint to explore an alternative trajectory.
  • Preserve checkpoint lineage so the execution history can be inspected.

In Python, the conceptual pattern is:

PYTHON
# Inspect saved states for a thread history = list(graph.get_state_history(config)) # Choose a checkpoint that precedes the decision chosen_snapshot = history[checkpoint_index] # Create a new continuation by applying a state update fork_config = graph.update_state( chosen_snapshot.config, values={"strategy": "alternative_B"}, ) # Continue from the forked state result = graph.invoke(None, fork_config)

The exact state keys and update behavior depend on the graph's schema and reducers. In particular, reducers may merge or append values rather than replace them.

For a multi-branch product experience, maintain explicit branch metadata and authorization around the graph. A framework's checkpoint mechanism is not, by itself, a complete branch-management, isolation, or side-effect-control system.

Also remember that replayed nodes can execute again. API requests, model calls, and interrupt points after the selected checkpoint may be triggered again. Design side-effecting nodes with idempotency and safe retry behavior.

13. What should you monitor?#

Measure the branch lifecycle, not just the final answer.

Useful metrics include:

  • branches created per task
  • branch depth and lifetime
  • percentage of tasks requiring a fork
  • branch completion and cancellation rates
  • cost and latency per branch and per selected outcome
  • percentage of branches rejected by hard gates
  • selection rate by strategy or model version
  • selected-branch success rate after independent verification
  • duplicate side-effect attempts
  • stale-checkpoint and resume failures
  • human override and approval rates
  • resource usage by abandoned branches

Track branch IDs and parent checkpoint IDs in traces so an operator can reconstruct which evidence and actions led to the selected result.

14. When should you use forking?#

Use forking when:

  • uncertainty is real and alternatives are meaningfully different;
  • alternatives can be evaluated independently;
  • the system can isolate branch state and side effects;
  • the value of better selection exceeds the extra cost;
  • the task has a clear comparison and stopping rule.

Prefer a single path when the task is routine, deterministic, low-risk, or when alternatives cannot be meaningfully compared.

Key takeaway#

Forking explores alternatives, steering changes an alternative, and selection chooses which path should continue.

Production-grade branching requires immutable checkpoints, clear parent-child lineage, isolated branch state, bounded budgets, evidence-based evaluation, and strict control of external side effects. Without these safeguards, branching can multiply cost and risk instead of improving agent reliability.

References

  1. 1.
  2. 2.
    LangGraph — Persistencedocs.langchain.com
  3. 3.
    LangGraph — Checkpointersdocs.langchain.com
  4. 4.
    LangGraph — Graph APIdocs.langchain.com
  5. 5.

Related questions

Explore other topics:Large Language ModelsRetrieval-Augmented GenerationMLOps