# Time

**What you will learn:** how a run waits for a time (a reminder, a deadline, a day for a
person to answer) without any machine reading a clock, when the Governor sleeps and when it
lets a run park, and how a stage of a workflow gets a hard deadline.

**Read first:** [Actors and events](actors-and-events.md), [The Governor](governor.md),
[Asking a person](asking-a-person.md) and, for the deeper part, [Workflows](workflows.md).
**Time:** about 20 minutes.

## Where this sits

Time touches three boxes of [the big picture](index.md#picture-1-the-loop-that-runs). An
actor in the harness layer (most simply the `Timer` below) asks for the time or to be woken,
as a request. The Governor, in the runtime layer, answers those requests through the
**Clock port**, the interface every clock implements (`SystemClock` in production,
`ManualClock` in tests). And when a wait is long, the run parks and something outside the
process, a scheduler, wakes it later:

```text
actor (e.g. a Timer)  --read_clock / wake_at-->  Governor  --reads, sleeps-->  Clock port
        ^                                           |
        +---------- clock_read / woke --------------+   (journaled, like every event)
                                                    |
               scheduler  --wake(actor)-->  ------- +   (for a run that parked)
```

The page first explains why a machine may not read a clock, then the two request kinds, the
`Timer`, the Governor's rule for sleeping or parking, and schedulers. Deadlines on workflow
stages come last.

## The problem: clocks break replay

Runs wait. A reviewer has a day to sign off a draft. A reminder fires in an hour. Evidence
is due by a fixed time. The obvious code calls `time.time()` inside the logic and compares.
That breaks two promises gvn makes:

- **Recovery.** If the process dies and the run is recovered from its journal (the
  append-only record of everything that happened to it), a fresh `time.time()` gives a new
  answer, so a deadline could move or be lost.
- **Replay.** Replaying a journal later should see exactly what the run saw. A clock read in
  the middle of the logic sees today instead.

**Clock readings enter a run as journaled events.** A machine asks the runtime for the time
or asks to be woken at a deadline. The runtime records the answers, so a recovered run
keeps its deadline and replay sees exactly the times the run saw.

There are three pieces:

- two standard request kinds, `read_clock` and `wake_at`;
- a `Timer` actor that waits until a time;
- **stage deadlines** on a workflow's `Host`, `FanOut`, `ForEach`, and `Parallel` (in the
  deeper part of this page).

The Governor handles both request kinds itself, and decides whether to sleep in-process or
let the run park until a scheduler wakes it.

## Step 1: the two request kinds

An actor that needs time emits one of two requests. Each is answered by an event:

| Request | Payload | Answered by | Answer |
|---|---|---|---|
| `read_clock` | `{}` | the Governor, with a `ClockFulfiller` (the built-in fulfiller that reads its Clock port) | `clock_read {"now": float}` |
| `wake_at` | `{"at": float}` | the Governor, sleeping on its clock, or a scheduler | `woke {}` |

`at` is absolute: seconds since the epoch. A machine never reads a clock. It either takes
`at` from trusted data (for example a `respond_by` time in the data the run was started
with), or asks `read_clock` once and computes from
the **journaled** answer. Either way the time it waits for is data, held in its [Dto](durable-objects.md) (its saved form) and in
the `wake_at` request, whose id is stable. A run recovered after a crash asks for the same
wake-up at the same time.

You rarely emit these yourself. The `Timer` does it for you.

## Step 2: the Timer

`gvn.harness.timer.Timer(name, at=None, after=None)` waits until a time and ends `elapsed`.
Give it exactly one of `at` (an absolute time) or `after` (seconds from when it starts, read
once from the clock).

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> scheduling : started
    scheduling --> waiting : known
    scheduling --> reading : unknown
    reading --> waiting : clock_read
    reading --> suspended : interrupted
    waiting --> elapsed : woke
    waiting --> suspended : interrupted
    suspended --> scheduling : resumed
    elapsed --> [*]
```

`scheduling` is an internal decision: `known` when the timer already has its `at`, `unknown`
when it must first read the clock to turn `after` into an absolute time.

Here is a reminder one hour after it starts. The Governor runs on a `ManualClock`, a fake
clock for tests that only moves when you tell it to. It starts at 1000.0 seconds:

```python
import asyncio

from gvn.harness.events import Event
from gvn.harness.timer import Timer
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput

clock = ManualClock(start=1000.0)
governor = Governor(
    fulfillers={},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=clock,
)

reminder = Timer(name="reminder", after=3600)
result = asyncio.run(governor.deliver(actor=reminder, event=Event("started")))
print(result.status(), result.due(), [request.request_id() for request in result.pending()])
```

```text
waiting 4600.0 ['reminder/wake_at']
```

What happened: the timer read the clock (1000.0, journaled as `clock_read`), computed
4600.0, and asked to be woken then. An hour is more than the Governor will sleep for (Step
3), so the run **parked**: `deliver` returned with status `waiting`, and `Result.due()` says
when someone should wake it. Nothing runs while a run is parked.

A **scheduler** is whatever wakes a parked run at its due time. It calls
`Governor.wake(actor)`, which answers every pending `wake_at` that is due and drives on. Move
the fake clock forward an hour and wake the timer:

```python
clock.advance(3600)
woken = asyncio.run(governor.wake(actor=reminder))
print(woken.outcome())
```

```text
Outcome('elapsed', {'at': 4600.0})
```

A timer given an absolute `at` skips the clock read, because its time is already `known`:

```python
deadline_timer = Timer(name="evidence_due", at=9000.0)
result = asyncio.run(governor.deliver(actor=deadline_timer, event=Event("started")))
print(result.due(), [request.request_id() for request in result.pending()])
```

```text
9000.0 ['evidence_due/wake_at']
```

## Step 3: sleep or park, the Governor's rule

When a run wants a `wake_at`, the Governor has two choices. It can **sleep** in-process: a
task sleeps on the Clock port and answers `woke` when the time comes. Or it can **park** the
run: return at once, leaving the `wake_at` among the pending requests for a scheduler.

`Governor(..., sleep_within=60.0)` sets the line between the two. Each time its loop goes
round, every wanted `wake_at` is either slept on or parked:

1. **Already due:** answered at once, whatever `sleep_within` says.
2. **Other work in flight** (a model call, a tool): slept on, however far away. The process
   is occupied anyway, and this is what lets a deadline cut off work that never returns.
3. **Nothing else in flight:** slept on if it is due within `sleep_within` seconds;
   otherwise the run parks, with the `wake_at` among its pending requests.

That is why the one-hour reminder parked: nothing else was running, and 3600 seconds is more
than 60.

`sleep_within=float("inf")` always sleeps; `sleep_within=0` parks every wake-up not yet due
once nothing else runs. A sleeper's `woke` is journaled once, when it fires, and only if its
request is still wanted.

**Due wake-ups come first.** Every way of driving a run (`deliver`, `answer`, `resume`,
`wake`) first applies the wake-ups already due. The deadline wins when an answer and a
deadline are due at the same moment. The Governor journals the wake and any resulting
work, then raises `TooLate` if the request has ended. The late answer itself is refused.

## Step 4: a scheduler

A parked run costs nothing until something wakes it. In production that is a scheduler:
store each run's `Result.due()`, and when the time comes, call `Governor.wake(actor)` (or
`Launcher.wake(run_id)` of `gvn.runtime.launching`, taught in [Domains](../domains/index.md#the-launcher)) in whatever process holds the run, after recovering it from the
journal if need be. A wake that comes early answers nothing; a wake that comes late is
applied before anything else that arrives. gvn-domains ships one: the `Worker`, which keeps
that schedule in the lease store (where processes record which one owns a run, see
[lease](../reference/glossary.md#lease)) and wakes
each due run once, however many processes share the journal
([Running as a service](../guides/running-as-a-service.md)).

In tests, `ManualClock` stands in for time: `advance(seconds)`, `sleepers()`, `earliest()`
(the earliest time anything sleeps until) and `await sleeping(n=1)`. No test ever waits for
real time.

## What is journaled

The journal records `clock_read` and `woke` events in the run's event history. A parked run's
wake-ups are pending requests owned by the actor. Recovery recreates the pending requests
with the same IDs and times.

That is the 80% you need. The rest of this page puts a deadline on a stage of a workflow, so
it builds on [Workflows](workflows.md).

## Deeper: stage deadlines {#stage-deadlines}

A [workflow](workflows.md) runs a plan of stages, and each stage hosts one or more child
actors. `Host`, `FanOut`, `ForEach` and `Parallel` stages can have deadlines:

- `deadline(memo)` takes the workflow's [`Memo`](workflows.md#step-2-a-stage-with-one-child-host)
  and returns `At(at=t)` (an absolute time from trusted data), `After(seconds=...)`
  (from when the stage is entered; the workflow reads the clock once), or `None` (no deadline
  for this visit);
- `expired` names the internal symbol the stage ends with when the deadline passes. The plan
  must route it, and `deadline` and `expired` come together or not at all.

When the Governor applies the deadline, the workflow drops the children still running and
cancels their pending work. Finished children keep their results. A `ForEach` stage also
leaves any queued items unstarted. An external effect may already have taken place, as
described in [What a deadline leaves behind](#what-a-deadline-leaves-behind).

Here a reviewer has a day to sign off a draft. First the control machine: from `asking`, the
answer, a withdrawal, or the timeout each lead to their own final state.

```python
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.symbols import Alphabet

SIGN_OFF = (
    MooreBlueprint(name="signoff")
    .inputs("started", "answered", "withdrawn", "timed_out")
    .outputs("idle", "ask", "done", "dropped", "late")
    .state(name="idle", output="idle")
    .state(name="asking", output="ask")
    .state(name="done", output="done", final=True)
    .state(name="dropped", output="dropped", final=True)
    .state(name="late", output="late", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="asking")
    .branch(
        source="asking",
        outcomes=Alphabet.of("answered", "withdrawn", "timed_out"),
        routes={"answered": "done", "withdrawn": "dropped", "timed_out": "late"},
    )
    .otherwise_stay()
    .build()
)
```

Next the plan. The `asking` stage hosts an `Inquiry` to the reviewer, with a deadline 24 hours
after the stage is entered; when it passes, the stage ends with `timed_out`:

```python
from gvn.harness.inquiry import Inquiry
from gvn.harness.workflow import After, Host, Plan, Report, Workflow

PLAN = Plan(
    definition=SIGN_OFF,
    stages={
        "asking": Host(
            actor_class=Inquiry,
            make=lambda name, memo: Inquiry(name=name, audience="reviewer"),
            start=lambda memo: Event("started", payload={"question": "Sign off the draft?"}),
            routes={"answered": "answered", "withdrawn": "withdrawn"},
            deadline=lambda memo: After(seconds=24 * 3600),
            expired="timed_out",
        )
    },
)


class SignOff(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return PLAN
```

Start it on a fresh clock. `external=["request_input"]` tells the Governor that questions to
people are answered from outside:

```python
clock = ManualClock(start=0.0)
governor = Governor(
    fulfillers={},
    external=["request_input"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=clock,
)
draft = SignOff(name="doc-1")
result = asyncio.run(governor.deliver(actor=draft, event=Event("started")))
print(result.due(), [request.request_id() for request in result.pending()])
```

```text
86400.0 ['doc-1/asking.1/1', 'doc-1/asking#1/wake_at']
```

The run parked on two things: the question to the reviewer and the stage's wake-up (id
`"<workflow>/<stage>#<visit>/wake_at"`). The reviewer answers a day and a minute later, too
late:

```python
question = result.pending()[0]
clock.advance(24 * 3600 + 60)


async def answer_late() -> None:
    try:
        await governor.answer(
            actor=draft, request=question, event=Event("answered", payload={"text": "Yes."})
        )
    except ValueError as error:
        print("refused:", error)


asyncio.run(answer_late())
```

```text
refused: request 'doc-1/asking.1/1' is no longer pending: a deadline already past was applied first, so this answer came too late
```

The due wake-up was applied first, so the stage had already ended. The workflow finished in
`late`. [`Report`](workflows.md#step-5-run-it), the reader for a finished workflow's outcome,
says which visits of a stage expired and which children were abandoned:

```python
report = Report(outcome=draft.outcome())
print(draft.state(), report.expired("asking"), report.abandoned("asking"))
```

```text
State('late') (1,) ((Abandoned(0, 'doc-1/asking.1', 'asking', ['request_input']),),)
```

### What a deadline leaves behind

`Memo.expired(stage)` and `Report.expired(stage)` list the visits that ended at their
deadline. `Memo.abandoned(stage)` and `Report.abandoned(stage)` give, per expired visit, each
child that was still running: its index, name, state and the **kinds of work it still
wanted**. That is what lets a plan route "possibly happened": a child abandoned while it
wanted `invoke_tools` may have acted, one abandoned while it wanted `request_input` did not.

!!! warning "Cancelled work may have happened"
    Cancelled work is like interrupted work: a tool call cut off at the deadline may or may
    not have happened. An effect that must happen at most once is keyed by trusted data (the
    dispute, the run), not by the call, so a repeat after a deadline is harmless.

A [relayed](workflows.md#step-4-tie-machine-and-stages-together-plan-and-workflow)
`interrupted` pauses a deadline: its wake-up is withdrawn and its time kept, and
`resumed` asks again for the same time. A deadline is never moved.

## Recap

- Time enters a run only as journaled events: `clock_read` answers `read_clock`, and `woke`
  answers `wake_at`. No machine reads a clock.
- A `Timer` waits until an absolute `at`, or `after` seconds from when it starts.
- The Governor sleeps in-process on a wake-up when other work is in flight or the wake-up is
  within `sleep_within` (60 seconds by default); otherwise the run parks and `Result.due()`
  says when to call `Governor.wake`.
- Due wake-ups are applied before anything else, so a late answer is refused.
- Workflow stages can have hard deadlines (`deadline` plus `expired`); a report says which
  visits expired and which children were abandoned with what work still wanted.

**Next:** [Workflows in depth](workflows-in-depth.md): judges, loops, joins, retries,
deadlines in long loops, compensation and nesting.
