# 9. A deadline

**At the end you can:** give a stage of a workflow a time limit, let the run wait for it
without a process, wake the run when the time comes, and tell what a late answer or an
expired stage left behind.

**What you will learn:** how to give a workflow stage a **deadline**, how a run waiting for a
far-off time **parks** (returns, leaving no process holding it) instead of sleeping, how a
scheduler wakes it, and what happens to an
answer that comes too late.

**Before this:** [8. A workflow of two actors](workflow.md). The approval of
[tutorial 5](agent-with-approval.md) comes back too.

**Time:** about 15 minutes.

## Where this sits in the big picture

In the quickstart's [big picture](../quickstart.md#the-big-picture), everything an actor
needs from outside comes back to it as an event through the **Governor**. Time is no
exception: a stage that must end by a deadline asks the Governor to be woken, and the
wake-up is an event in the **journal** like any other. This page adds that to the workflow
of tutorial 8 and the approval of tutorial 5.

## Where you are

In tutorial 8 a `SupportCase` workflow ran an investigator and a writer, one after the other.
Now the investigator may also refund a damaged order, which, as in tutorial 5, needs a
person's approval. The question this page answers: what if nobody ever approves? The case
should not wait for ever. If the investigation is not finished within a day, the case is
escalated to a senior agent.

**Start a new file for this page, and begin it with the block below.** The block holds
everything from the earlier pages that this page uses, imports included: the refund tool
and its policy from tutorial 5, and the stage functions of tutorial 8. Then add each block
of the page below it, in order.

??? example "Tools, policy and stage functions from tutorials 5 and 8"

    ```python
    import asyncio
    import typing

    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 Reply
    from gvn.harness.tools import Invocation, Tool, Toolbox
    from gvn.harness.workflow import Host, Memo, Plan, Report, Workflow
    from gvn.kernel.blueprint import MooreBlueprint
    from gvn.kernel.decision import Decision
    from gvn.kernel.schema import Number, Record, Text
    from gvn.kernel.symbols import Alphabet, Symbol
    from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
    from gvn.runtime.governor import Governor
    from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


    class IssueRefund(Tool):
        def __init__(self, refunds: list[dict[str, typing.Any]]) -> None:
            self._refunds = refunds

        def name(self) -> str:
            return "issue_refund"

        def description(self) -> str:
            return "Refund an amount on an order. Money leaves the shop."

        def arguments(self) -> Record:
            return Record({"order_id": Text(), "amount": Number()})

        async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
            self._refunds.append(dict(arguments))
            return {"refund": len(self._refunds)}


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

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


    refunds = []
    issue_refund = IssueRefund(refunds=refunds)
    toolbox = Toolbox([issue_refund])


    def make_investigator(name: str, memo: Memo) -> Agent:
        return Agent(
            name=name,
            instructions="Find the facts about the customer's order. Refund damaged orders.",
            tools=[issue_refund],
        )


    def start_investigator(memo: Memo) -> Event:
        return Event(name="started", payload={"prompt": memo.input()["complaint"]})


    def make_writer(name: str, memo: Memo) -> Agent:
        return Agent(name=name, instructions="Write a short, kind reply to the customer.")


    def start_writer(memo: Memo) -> Event:
        facts = memo.results("investigating")[0].payload()["text"]
        return Event(name="started", payload={"prompt": f"Facts: {facts}"})


    replying = Host(
        actor_class=Agent,
        make=make_writer,
        start=start_writer,
        routes={"completed": "replied", "failed": "reply_failed", "overflowed": "reply_failed"},
    )


    def asks_for(
        short_name: str, arguments: dict[str, typing.Any], call_id: str = "call-1"
    ) -> Reply:
        call = ToolCall(call_id=call_id, name=short_name, arguments=arguments)
        return Reply(message=Message.assistant(calls=[call]))
    ```

## How time works in gvn

A machine never reads a clock: a run that did would behave differently when replayed. Time
enters a run only as **journaled events**. A stage with a deadline asks the Governor for a
`wake_at` request ("wake me at this time"); when the time comes, the answer, `woke`, is
journaled like any other event. A crash therefore neither loses nor moves a deadline, and a
replay sees exactly the times the run saw. [Time](../concepts/time.md) has the whole story.

## Step 1: route the way a stage times out

A deadline is one more way the investigating stage can end, so it is one more input of the
workflow's machine, `timed_out`, routed to a new final state, `escalated`:

```python
CASE_MACHINE = (
    MooreBlueprint(name="case")
    .inputs(
        "started", "investigated", "investigation_failed", "timed_out", "replied", "reply_failed"
    )
    .outputs("idle", "investigate", "reply", "done", "failed", "escalate")
    .state(name="idle", output="idle")
    .state(name="investigating", output="investigate")
    .state(name="replying", output="reply")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .state(name="escalated", output="escalate", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="investigating")
    .branch(
        source="investigating",
        outcomes=Alphabet.of("investigated", "investigation_failed", "timed_out"),
        routes={
            "investigated": "replying",
            "investigation_failed": "failed",
            "timed_out": "escalated",
        },
    )
    .branch(
        source="replying",
        outcomes=Alphabet.of("replied", "reply_failed"),
        routes={"replied": "done", "reply_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)
```

## Step 2: give the stage its deadline

`Host` takes two more arguments, which always come together:

- `deadline(memo)`: when the stage must be over. `After(seconds)` counts from when the stage
  is entered (the workflow reads the clock once, as a journaled event); `At(time)` is an
  absolute time, in seconds since the epoch, taken from trusted data.
- `expired`: the input the stage ends with when the deadline passes. The plan checks that the
  machine routes it, as it checks the other routes.

```python
from gvn.harness.workflow import After

ONE_DAY = 24 * 3600

investigating = Host(
    actor_class=Agent,
    make=make_investigator,
    start=start_investigator,
    routes={
        "completed": "investigated",
        "failed": "investigation_failed",
        "overflowed": "investigation_failed",
    },
    deadline=lambda memo: After(seconds=ONE_DAY),
    expired="timed_out",
)
CASE_PLAN = Plan(
    definition=CASE_MACHINE,
    stages={"investigating": investigating, "replying": replying},
    tools=[issue_refund],
)


class SupportCase(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return CASE_PLAN
```

As in tutorial 8, the plan declares with `tools=` the tool its investigator is given, here
the refund, so the Governor can check its toolbox before the run starts.

Deadlines are **hard**: when one passes, the child still running is dropped and its work is
cancelled.

## Step 3: run until the run parks

Each test below needs a fresh model and a clock it controls, so a function builds both into a
Governor. `ManualClock(start=0.0)` starts the fake time at zero:

```python
def build_governor(clock: ManualClock) -> Governor:
    model = ScriptedModel(
        script=[
            asks_for("issue_refund", {"order_id": "A-17", "amount": 40.0}),
            Reply(message=Message.assistant(text="A-17 arrived broken; refunded 40.00.")),
            Reply(message=Message.assistant(text="We are sorry. Your 40.00 is on its way back.")),
        ]
    )
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=RefundPolicy()),
        },
        external=["request_approval"],
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=clock,
    )


BROKEN = Event(name="started", payload={"complaint": "Order A-17 arrived broken."})

clock = ManualClock(start=0.0)
governor = build_governor(clock=clock)
case = SupportCase(name="case-2")
result = asyncio.run(governor.deliver(actor=case, event=BROKEN))

print(result.status(), result.due())  # waiting 86400.0
for request in result.pending():
    print(request.request_id(), request.kind().name())
# case-2/investigating.1/6 request_approval
# case-2/investigating#1/wake_at wake_at
```

The run is waiting on two things: the approval the investigator asked for, and the stage's
wake-up a day from now. `result.due()` says when the earliest wake-up is due.

The Governor did not sleep for a day. Its rule: with nothing else in flight, it sleeps
in-process only for a wake-up due within `sleep_within` seconds (60 by default, a
`Governor` argument); anything later **parks** the run. The call returns and the process
holds nothing, as with an approval.

## Step 4: the approval arrives in time

An hour later, someone approves. The investigation finishes, the deadline is withdrawn, and
the case goes on to the writer:

```python
clock.advance(3600)
approval = result.pending()[0]
result = asyncio.run(
    governor.answer(actor=case, request=approval, event=Event(name="approved"))
)
print(result.outcome().state())  # State('done')
print(Report(result.outcome()).results("replying")[0].payload()["text"])
# We are sorry. Your 40.00 is on its way back.
```

The approval was for a child of the workflow (its request id starts with
`case-2/investigating.1`), yet you answer it on the workflow: `answer` routes the event to
the child that asked.

## Step 5: the approval arrives too late

Run a second case, and let a day and a minute pass before anyone answers:

```python
from gvn.harness import TooLate

clock = ManualClock(start=0.0)
governor = build_governor(clock=clock)
late_case = SupportCase(name="case-3")
waiting = asyncio.run(governor.deliver(actor=late_case, event=BROKEN))
approval = waiting.pending()[0]

clock.advance(ONE_DAY + 60)
try:
    asyncio.run(governor.answer(actor=late_case, request=approval, event=Event(name="approved")))
except TooLate as too_late:
    print("refused:", too_late)
    print(too_late.result().outcome().state())  # State('escalated')
```

```text
refused: request 'case-3/investigating.1/6' is no longer pending: a deadline already past was applied first, so this answer came too late
State('escalated')
```

Every way of driving a run first applies the wake-ups already due. So the deadline won: the
stage ended `timed_out`, the case went to `escalated`, and the late approval was refused.
`TooLate` is a `ValueError`, and `too_late.result()` is how the run ended. The journal
records the `woke` event and any events after it. The refused approval is absent.

The report says what the deadline cut off:

```python
report = Report(late_case.outcome())
print(report.expired("investigating"))  # (1,)
for dropped in report.abandoned("investigating")[0]:
    print(dropped.name(), dropped.state().name(), [kind.name() for kind in dropped.kinds()])
# case-3/investigating.1 awaiting_approval ['request_approval']
print(len(refunds))  # 1
```

`expired` lists the visits of the stage that ended at their deadline (visit 1). `abandoned`
gives, for each, the children still running and the **kinds of work they still wanted**.
That tells you whether something may have happened: a child dropped while it wanted
`request_approval` had not refunded anything, one dropped while it wanted `invoke_tools`
might have. Only the first case's refund is in the list.

## Step 6: a scheduler wakes a parked run

Nobody answered at all in a third case. Something must notice the time has come. In
production that is a scheduler: it stores each parked run's `due()` time, and when that time
comes, calls `governor.wake(actor=...)` in a process that holds the run (after recovering it
from the journal, as in tutorial 6). `wake` answers every wake-up that is due and drives on:

```python
clock = ManualClock(start=0.0)
governor = build_governor(clock=clock)
silent_case = SupportCase(name="case-4")
asyncio.run(governor.deliver(actor=silent_case, event=BROKEN))

clock.advance(ONE_DAY)
result = asyncio.run(governor.wake(actor=silent_case))
print(result.status(), result.outcome().state())  # finished State('escalated')
```

A wake that comes early answers nothing; one that comes late is applied before anything else
that arrives. In tests, `ManualClock.advance(seconds)` stands in for time, so no test ever
waits for real.

For a run that simply needs to wait until a time, with no stage around it, gvn has a
ready-made actor, `Timer`; the [Time](../concepts/time.md) page shows it.

## Change it and run again

Predict the answer first, then run the code and open the block.

**1. Wake the run early.** Start a fourth case, let one hour pass, and call `wake`. What is
the status, when is the run due, and what is it still waiting for?

```python
clock = ManualClock(start=0.0)
governor = build_governor(clock=clock)
early_case = SupportCase(name="case-5")
asyncio.run(governor.deliver(actor=early_case, event=BROKEN))

clock.advance(3600)
result = asyncio.run(governor.wake(actor=early_case))
print(result.status(), result.due(), early_case.state())
print([request.kind().name() for request in result.pending()])
```

??? note "What happens"

    ```text
    waiting 86400.0 State('investigating')
    ['request_approval', 'wake_at']
    ```

    Nothing was due, so `wake` answered nothing and the run is as it was: same deadline,
    same two pending requests. A scheduler may therefore call `wake` as often as it likes.

**2. Ask the report about a stage that finished in time.** The first case, `case-2`, was
approved after an hour. What do `expired` and `abandoned` say for its investigating stage?

```python
on_time = Report(case.outcome())
print(on_time.expired("investigating"), on_time.abandoned("investigating"))
```

??? note "What happens"

    ```text
    () ()
    ```

    Both are empty: no visit of the stage ended at its deadline, so no child was dropped.
    When the approval arrived, the stage ended `investigated` and its wake-up was withdrawn.

## Recap

- A workflow asks for time through `read_clock` and `wake_at` requests. The answers are
  journaled as `clock_read` and `woke` events.
- `Host(..., deadline=lambda memo: After(seconds=...), expired="...")` gives a stage a hard
  deadline, and the machine must route the `expired` input.
- With no other work in flight, a run **parks** if its wake-up is more than `sleep_within`
  seconds away. `result.due()` gives the scheduled time and `governor.wake(actor=...)`
  handles the wake-up when due.
- A deadline that has passed is applied before any answer; a late answer raises `TooLate`.
  `Report.abandoned(stage)` says what the dropped children still wanted.

**Next:** [10. A conversation](conversation.md) lets the help desk talk with the customer
over several turns.
