# Forking a run

This guide answers "what would this run have done if it had gone differently from here?"
for a run you have already recorded. At the end you have the original run and a second one
that took the other path, each in its own journal, and you can compare how they ended.

A **fork** is that second run: it shares a recorded run's history up to a position, and then
goes its own way, in another journal (the durable record of a run's events). The guide forks
a run at the point where a person answered, gives the other answer, and sees what the run
would have done; forks at a model call and asks the model again; forks a workflow; and says
what a fork shares with the run it came from.

- **You will be able to:** fork a recorded run at any position into another journal, drive
  the fork with a Governor (the object that drives a run) of its own, compare its outcome with the original's, and decide
  what the fork's tools may reach.
- **Read first:** the tutorials [5. A policy, and approval by a person](../tutorials/agent-with-approval.md)
  and [6. The journal: crash and resume](../tutorials/durability.md), and the guide
  [Replay and evaluation](replay-and-evaluation.md), which a fork is the counterpart of.
- **Time:** about 20 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), the **journal** holds a run: the
snapshot of its actor at birth and one record per event, in order. The **actor** is a state
machine that does no I/O, so handing it the same events again rebuilds it exactly as it
stood. That is how [recovery](../tutorials/durability.md) works after a crash, and it means
the run as it stood after *any* number of records can be rebuilt.

`Fork` (in `gvn.runtime.fork`) builds on that. `Fork(journal).at(run_id, position,
actor_class, into=other_journal)` copies the birth snapshot and the records below `position`
into another journal, and hands back the actor as it stood there. From then on the fork is
an ordinary run: a **Governor** built over the other journal drives it, and it records its
own events after the shared ones. The original journal is only read.

```mermaid
flowchart LR
    original[("Original journal<br/>records 0 … n-1")]
    fork["Fork(original).at(run, position, …)"]
    copy[("Other journal<br/>records 0 … position-1")]
    actor["The actor as it stood<br/>at that position"]
    governor["A Governor over<br/>the other journal"]
    original -- "read" --> fork
    fork -- "copy of the prefix" --> copy
    fork --> actor
    actor --> governor
    governor -- "new records" --> copy
```

### A fork and a replay

Both start from a recorded run, and they answer different questions:

- [Replay](replay-and-evaluation.md) feeds the recorded events, as they were, to an actor
  you changed. Nothing is fulfilled: no model, tool or person is asked. It shows how changed
  **code** handles the same history.
- A fork keeps the code and changes the **history** from one point on. After that point,
  real work is fulfilled: the model is asked again, a tool runs, a person answers.

So a fork answers "what would this run have done had one thing gone differently": a
person's answer, a model's reply, a tool's result, from the exact point where it happened,
without running everything before it again and without touching the original.

### Positions

A position counts records. A fork at `position` holds the records at positions below it, so:

- `0` is the run at birth, before its first event;
- `await journal.length(run_id)` is the run as it stands now;
- anything between is the run right after that many records.

Every position is a point where the run could have crashed and been recovered, so every
position is a valid place to fork.

## Step 1: record a run

The run to fork is an agent that wants to search, is stopped by a policy that asks a person
first, is approved, searches and answers. The model is a `ScriptedModel` (a test fake that
answers from a list), the tool a `StubTool`, and the policy `AskFirst` asks a person about
every call. `governor_over` builds a Governor over a given journal, with a given script, so
the fork can get one of its own later.

```python
import asyncio
from collections.abc import Callable

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Exchange, Journal, Reply
from gvn.harness.tools import Tool, Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel, StubTool


class AskFirst(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("needs_approval")


def search_tool() -> StubTool:
    return StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})


def governor_over(journal: Journal, script: list[Reply], search: Tool) -> Governor:
    toolbox = Toolbox(tools=[search])
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=ScriptedModel(script=script), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=AskFirst()),
        },
        external=["request_approval"],
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
    )


def helper() -> Agent:
    return Agent(name="helper", instructions="Be brief.", tools=[search_tool()], turns=5)


SEARCH = ToolCall(call_id="c1", name="search", arguments={"query": "Moore"})
original = MemoryJournal()
search = search_tool()
first = governor_over(
    journal=original,
    script=[
        Reply(message=Message.assistant(text="", calls=[SEARCH])),
        Reply(message=Message.assistant(text="Three hits.")),
    ],
    search=search,
)


async def record() -> Result:
    actor = helper()
    waiting = await first.deliver(actor=actor, event=Event("started", payload={"prompt": "Look up Moore."}))
    (request,) = waiting.pending()
    return await first.answer(actor=actor, request=request, event=Event("approved"))


done = asyncio.run(record())
print(done.outcome().payload()["text"])  # Three hits.
records = asyncio.run(original.read("helper"))
for position, record in enumerate(records):
    print(position, record["event"]["name"])
# 0 started
# 1 model_replied
# 2 needs_approval
# 3 approved
# 4 tools_returned
# 5 model_replied
```

The run has six records. Position 3 is the run right after the policy asked for a person and
before the person's answer; position 1 is the run right after `started`, before the model
replied.

## Step 2: fork before the approval

Fork at position 3 into a second `MemoryJournal`. The actor that comes back is the agent as
it stood there, waiting for a person:

```python
from gvn.runtime.fork import Fork

what_if = MemoryJournal()
forked = asyncio.run(Fork(original).at("helper", 3, Agent, into=what_if))
print(forked.state())  # State('awaiting_approval')
(request,) = forked.pending()
print(request.kind(), request.request_id())  # Symbol('request_approval') helper/6
```

`at` takes the run id, the position, the actor class the run was started with (it rebuilds
the actor from the birth snapshot, as recovery does) and the journal to copy into. It wrote
three records and a snapshot of the actor at position 3 into `what_if`, so
`Recovery(what_if).recover("helper", Agent)` gives the same actor, in this process or
another.

## Step 3: give the other answer

The fork is driven by a Governor over `what_if`. Here the person denies the search, so the
model is asked what to say instead; its script holds that one reply:

```python
search_in_fork = search_tool()
second = governor_over(
    journal=what_if,
    script=[Reply(message=Message.assistant(text="I did not search."))],
    search=search_in_fork,
)
other = asyncio.run(
    second.answer(actor=forked, request=request, event=Event("denied", payload={"reason": "too risky"}))
)
print(other.status(), other.outcome().payload()["text"])  # finished I did not search.
print(search_in_fork.calls())  # ()
print([record["event"]["name"] for record in asyncio.run(what_if.read("helper"))])
# ['started', 'model_replied', 'needs_approval', 'denied', 'model_replied']
print(asyncio.run(original.read("helper")) == records)  # True
```

Both outcomes now exist side by side: the original finished with "Three hits." after
searching, the fork finished with "I did not search." without searching. The fork's journal
holds the three shared records and then its own two. The original is untouched.

## Step 4: ask the model again

A fork at a position where the run was waiting for work, here position 1, where the agent
had asked the model and not yet heard back, is resumed with `governor.resume`. The model is
asked again, and a model scripted differently answers differently:

```python
again = MemoryJournal()
asked = asyncio.run(Fork(original).at("helper", 1, Agent, into=again))
print(asked.state(), [(wanted.kind(), wanted.request_id()) for wanted in asked.pending()])
# State('thinking') [(Symbol('invoke_model'), 'helper/3')]
third = governor_over(
    journal=again,
    script=[Reply(message=Message.assistant(text="No search needed."))],
    search=search_tool(),
)
answered = asyncio.run(third.resume(asked))
print(answered.status(), answered.outcome().payload()["text"])  # finished No search needed.
```

With a real model, this is how to see the range of what a run could have done from one
point: fork it several times at the same position, into several journals, and resume each.

## Forking a workflow

A [workflow](../concepts/workflows.md) is an actor whose children live inside it, and its
whole tree is one run in one journal. So a workflow is forked exactly like an agent, with
the workflow's class as `actor_class`, and the fork keeps every child as it stood.

`Brief` has two stages: a researcher agent, then a writer agent that writes up the
researcher's note. The model is a `FunctionModel`, a fake whose reply is a function of the
question; `plain` wraps the prompt in `note<...>`, so the result shows who read what:

```python
from gvn.harness.workflow import Host, Memo, Plan, Report, Workflow
from gvn.kernel.blueprint import MooreBlueprint
from gvn.testing.fakes import FunctionModel

BRIEF_MACHINE = (
    MooreBlueprint(name="brief")
    .inputs("started", "researched", "research_failed", "written", "write_failed")
    .outputs("idle", "research", "write", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="researching", output="research")
    .state(name="writing", output="write")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="researching")
    .branch(
        source="researching",
        outcomes=Alphabet.of("researched", "research_failed"),
        routes={"researched": "writing", "research_failed": "failed"},
    )
    .branch(
        source="writing",
        outcomes=Alphabet.of("written", "write_failed"),
        routes={"written": "done", "write_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)


def stage(role: str, prompt: Callable[[Memo], str], reached: str, missed: str) -> Host:
    return Host(
        actor_class=Agent,
        make=lambda name, memo: Agent(name=name, instructions=f"You {role}.", turns=3),
        start=lambda memo: Event("started", payload={"prompt": prompt(memo)}),
        routes={"completed": reached, "failed": missed, "overflowed": missed},
    )


STAGES = {
    "researching": stage("research", lambda memo: memo.input()["topic"], "researched", "research_failed"),
    "writing": stage(
        "write", lambda memo: memo.results("researching")[0].payload()["text"], "written", "write_failed"
    ),
}


class Brief(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(definition=BRIEF_MACHINE, stages=STAGES, relay=["interrupted", "resumed"])


def workflow_governor(respond: Callable[[Exchange], Reply], journal: Journal) -> Governor:
    return Governor(
        fulfillers={"invoke_model": ModelFulfiller(model=FunctionModel(respond=respond), toolbox=Toolbox())},
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
    )


def plain(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text=f"note<{exchange.messages()[0].text()}>"))


briefs = MemoryJournal()
brief = asyncio.run(
    workflow_governor(plain, briefs).deliver(
        actor=Brief(name="brief"), event=Event("started", payload={"topic": "Moore machines"})
    )
)
print(Report(outcome=brief.outcome()).results("writing")[0].payload()["text"])
# note<note<Moore machines>>
for position, record in enumerate(asyncio.run(briefs.read("brief"))):
    print(position, record["event"]["name"], record["event"]["to"])
# 0 started None
# 1 model_replied brief/researching.1
# 2 model_replied brief/writing.1
```

Position 2 is the workflow after the researcher finished and while the writer waits for the
model. Fork there and resume under a model that writes differently (`loud` wraps the prompt
in `NOTE<...>`):

```python
def loud(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text=f"NOTE<{exchange.messages()[0].text()}>"))


rewritten = MemoryJournal()
forked_brief = asyncio.run(Fork(briefs).at("brief", 2, Brief, into=rewritten))
print([(wanted.kind(), wanted.origin()) for wanted in forked_brief.pending()])
# [(Symbol('invoke_model'), 'brief/writing.1')]
result = asyncio.run(workflow_governor(loud, rewritten).resume(forked_brief))
print(Report(outcome=result.outcome()).results("writing")[0].payload()["text"])
# NOTE<note<Moore machines>>
```

Only the writer was asked again. The researcher's note is the one the original run
recorded: the fork never asked the model for it.

## What the fork shares with the original

A run is identified by its actor's name, and a fork is the same actor, so **the fork has the
same run id** as the original. That is why it lives in another journal: one journal never
holds two runs of one name. gvn does not rename it, since the name is in the actor's
snapshot, in its request ids and in the addresses of its events.

The fork's **request ids** are the original's too: the approval request above was
`helper/6` in both. And so are the **idempotency keys** its tools are given
(`invocation.key()`, which is `"<request id>#<tool call id>"`; see
[at-least-once and request ids](../concepts/governor.md#at-least-once-and-request-ids)). Fork
at position 3 once more, and this time approve:

```python
approved_again = MemoryJournal()
replayed = asyncio.run(Fork(original).at("helper", 3, Agent, into=approved_again))
search_approved = search_tool()
fourth = governor_over(
    journal=approved_again,
    script=[Reply(message=Message.assistant(text="Three hits, again."))],
    search=search_approved,
)
(approval,) = replayed.pending()
asyncio.run(fourth.answer(actor=replayed, request=approval, event=Event("approved")))
print(search.keys(), search_approved.keys())  # ('helper/7#c1',) ('helper/7#c1',)
```

The fork's search carried the key the original's search carried. That is what makes a
repeat harmless: a call the original already issued, issued again by the fork, reaches the
service with the same key, and a service that honours idempotency keys does not repeat its
effect. It also means that a call the fork makes *after* it diverged may carry a key the
original used for a different call, and such a service would then answer it with the
original call's result.

So whoever forks a run with tools that change things decides what those tools reach. The
fork's Governor is yours to build: give it tools bound to a test service, or fakes, unless
repeating the original's effects is what you want. The model, the policy and the people who
answer are yours to choose in the same way.

## What a fork refuses

`at` checks everything before it writes, and in every refusal nothing was written to the
other journal:

```python
from gvn.harness.ports import PositionTaken
from gvn.runtime.recovery import UnknownRun


async def refusals() -> None:
    fork = Fork(original)
    attempts = [
        ("helper", 3, what_if),  # what_if already holds run 'helper'
        ("nobody", 0, MemoryJournal()),  # the original holds no run 'nobody'
        ("helper", 7, MemoryJournal()),  # the run has 6 records
        ("helper", 2, original),  # a fork goes into another journal
    ]
    for run_id, position, into in attempts:
        try:
            await fork.at(run_id, position, Agent, into=into)
        except (PositionTaken, UnknownRun, ValueError) as error:
            print(type(error).__name__, error)


asyncio.run(refusals())
# PositionTaken the target journal already holds run 'helper'
# UnknownRun the journal holds no snapshot of run 'nobody'
# ValueError position must be between 0 and 6, the length of run 'helper'; got 7
# ValueError into must not be the journal the run is forked from
```

- `PositionTaken` (from `gvn.harness.ports`): the other journal already holds a record or a
  snapshot of that run, for a fork at position 0 too.
- `UnknownRun` (from `gvn.runtime.recovery`): the journal forked from holds no run of that
  name.
- `ValueError`: a position below 0 or past the end of the run (the message names the run's
  length), the journal forked from given as `into`, or a stored record that does not fit the
  actor class, reported as recovery reports it.

A fork at position 0 writes nothing: the actor that comes back is the run at birth, and the
first event a Governor over the other journal hands it begins the run there.

The copy is not one atomic step. If it fails part-way (the other journal raises, or the call
is cancelled), the other journal holds a shorter prefix of the run, which is itself a valid
run, and nothing is cleaned up: fork again into a fresh journal. The copy's writes carry no
[lease](running-as-a-service.md#step-2-a-lease-so-that-one-process-drives-a-run) fence.

## On SQLite

The journals are any `Journal`. Forking a run kept in one SQLite file into another is the
same call:

```python
from gvn.adapters.sqlite import SqliteJournal


async def fork_on_disk() -> str:
    kept = SqliteJournal(path="runs.db")
    first_on_disk = governor_over(
        journal=kept, script=[Reply(message=Message.assistant(text="Hello."))], search=search_tool()
    )
    await first_on_disk.deliver(actor=helper(), event=Event("started", payload={"prompt": "Hi."}))
    trial = SqliteJournal(path="what-if.db")
    actor = await Fork(kept).at("helper", 1, Agent, into=trial)
    rerun = governor_over(
        journal=trial, script=[Reply(message=Message.assistant(text="Hi there."))], search=search_tool()
    )
    return (await rerun.resume(actor)).outcome().payload()["text"]


print(asyncio.run(fork_on_disk()))  # Hi there.
```

`what-if.db` now holds the fork, and `runs.db` the original, unchanged. Both can be read
back with [Replay](replay-and-evaluation.md) and graded with the same checks, which is how
to compare the two runs side by side.

## Recap

- `Fork(journal).at(run_id, position, actor_class, into=other)` copies a run's birth
  snapshot and its records below `position` into another journal and returns the actor as
  it stood there. Position 0 is birth; the run's length is now.
- The fork is an ordinary run: a Governor over the other journal answers its pending
  request differently, resumes it so the model is asked again, or delivers something else.
  The original journal is only read.
- Replay changes the code and keeps the history; a fork keeps the code and changes the
  history from one point on, with real work after it.
- A workflow is forked like any actor, its children with it.
- The fork has the original's run id, request ids and idempotency keys, so the person who
  forks decides what its tools reach.
- `PositionTaken`, `UnknownRun` and `ValueError` refuse a fork before anything is written.

**Next:** to read the fork and the original side by side, actor by actor, read
[Inspecting a run](inspecting-a-run.md); to grade both with the same checks, read
[Replay and evaluation](replay-and-evaluation.md#step-6-evaluations-and-scorecards).
