# Durable objects

**What you will learn:** how gvn saves an object that keeps its state private, sends it to
another process, and brings it back exactly as it was. You will write a small durable class of
your own.

**Read first:** [Machines](machines.md). **Time:** about 15 minutes.

**Where this sits.** In the [loop that runs](index.md#picture-1-the-loop-that-runs), an
actor is a verified machine *plus its data*: an agent's conversation so far, what it has
spent, which tool calls it is waiting on. This page is about that data: how an object that
hides its state is saved and brought back exactly. It is part of the
[kernel](index.md#picture-2-the-layers-of-code), and it is what later lets the Governor
snapshot a run and rebuild it after a crash.

## The problem: saving objects that hide their state

In gvn, state lives inside the object that maintains it. A transcript (the agent's list of
messages exchanged with the model) appends messages, a budget (the number of model turns an
agent may still take) counts down, an agent handles events. You reach that state only through the object's
methods. Stateful classes expose behavior through methods; messages and stored forms may
contain plain data, but callers do not mutate an object's live state through those records.

That raises an obvious question. A run may take hours, and the process may die halfway. How
do you save such an object, send it to another process, and bring it back? Reading private
attributes would couple the saver to its implementation, and pickling ties you to a Python
class layout.

The answer is the **Dto protocol**. A **Dto** ("data transfer object") is a small, validated,
read-only record of an object's state that turns into plain JSON and back. An object that can
produce one and be rebuilt from one is **durable**.

## Step 1: a class with private state

Here is the running example: a tally of support tickets handled, with a label per ticket. It
keeps its state in private members and exposes one method.

```python
class PlainTally:
    def __init__(self) -> None:
        self._count = 0
        self._labels = []

    def add(self, label: str) -> int:
        self._count += 1
        self._labels.append(label)
        return self._count


print(PlainTally().add(label="refund"))
```

```text
1
```

The leading underscore marks `_count` and `_labels` as private by Python convention; Python
does not prevent another object from reading them. The contract is that callers use `add`,
so the tally can change its representation without making its callers change too. Saving
must respect that same boundary, which is why we need an explicit protocol.

## Step 2: make it durable

A durable class subclasses `Durable` and adds three things:

- an inner class named `Dto` describing its saveable state, with an explicit `schema` (a
  description of what each field must look like, checked at run time);
- an instance method `to_dto()` that captures the complete state without changing the
  object;
- a class method `from_dto(dto)` that creates the object with `cls.__new__(cls)` and fills in
  its members. It does not call `__init__`.

```python
import json
import typing

from gvn.kernel.durable import Dto, Durable
from gvn.kernel.schema import Integer, ListOf, Record, Text


class Tally(Durable):
    class Dto(Dto):
        schema = Record(fields={"count": Integer(minimum=0), "labels": ListOf(Text())})

    def __init__(self) -> None:
        self._count = 0
        self._labels = []

    def add(self, label: str) -> int:
        self._count += 1
        self._labels.append(label)
        return self._count

    def to_dto(self) -> Dto:
        return Tally.Dto(count=self._count, labels=self._labels)

    @classmethod
    def from_dto(cls, dto: Dto) -> typing.Self:
        if type(dto) is not cls.Dto:
            raise TypeError(f"expected Tally.Dto, got {type(dto).__name__}")
        self = cls.__new__(cls)
        self._count = dto.count
        self._labels = list(dto.labels)
        return self
```

`Durable` is the base class that marks a class as durable. The schema is built from small
schema objects: `Record` describes a dict with exactly the named fields, `Integer(minimum=0)`
a whole number that is not negative, and `ListOf(Text())` a list of strings. The full list is
in [Deeper: schemas](#deeper-schemas) below.

The behaviour is unchanged; the class just learned to describe itself. If a class defines
`to_dto` or `from_dto` without its own inner `Dto`, Python raises `TypeError` when the class
is defined.

## Step 3: save it as JSON and bring it back

Now save a tally to JSON text, as you would store it in a file or a database, and rebuild a
twin from that text:

```python
original = Tally()
original.add(label="refund")

saved_text = json.dumps(original.to_dto().to_plain())
print(saved_text)

twin = Tally.from_dto(Tally.Dto.from_plain(json.loads(saved_text)))
print(twin.add(label="billing"), original.add(label="billing"))
print(twin.to_dto() == original.to_dto())
```

```text
{"count": 1, "labels": ["refund"]}
2 2
True
```

Notice that the twin and the original keep behaving the same after the restore: both answer
`2` to the next `add`, and their Dtos are equal.

## The durability law

That is the one law every durable class must satisfy: `from_dto(to_dto(x))` behaves exactly
like `x` through its public interface, now and after any further sequence of calls. The same
must hold when the Dto travels through JSON text on the way, as it did above.

gvn tests this law for every durable class it ships, and you should test it for yours (see
[Testing your harness](testing.md)).

Actors keep **ports** (the connections to the outside world, such as a model client or
database) out of their saved state. A stored actor names its tools by [identity](tools.md)
and its models by role. To drive it after a restore, wire the Governor with implementations
that match those names.

## Step 4: a Dto checks what goes into it

A Dto is validated when you build it. A bad field raises `SchemaViolation`, listing every
problem with a path to where it is:

```python
from gvn.kernel.schema import SchemaViolation

try:
    Tally.Dto(count=-1, labels=["ok", 3])
except SchemaViolation as violation:
    for problem in violation.problems():
        print(problem)
```

```text
$.count: -1 is below the minimum 0
$.labels[1]: expected a string, got int
```

A Dto is also read-only. To change a field, you make a new Dto:

```python
tally_dto = Tally.Dto(count=1, labels=["refund"])
print(tally_dto.labels)
print(tally_dto.replace(count=2).count, tally_dto.count)
```

```text
('refund',)
2 1
```

Lists come back as tuples, and `replace` returned a new Dto while the old one kept `count=1`.

That is the 80% you need. The rest of this page is reference detail.

## Deeper: what a Dto is

A Dto is the one sanctioned plain-data shape in gvn. It is:

- **validated on construction** against its schema; a bad field raises `SchemaViolation`
  listing every problem, each with a path;
- **immutable**: lists are stored as tuples, dicts as read-only mappings, and setting a
  field raises `AttributeError`;
- **comparable**: two Dtos are equal when they are the same class with equal plain forms.

Its methods:

- `to_plain()` returns JSON-compatible data (dicts, lists, str, int, float, bool, None).
- `Dto.from_plain(plain)` validates and rebuilds; it raises `SchemaViolation` if the data
  does not fit.
- `replace(**changes)` returns a new, validated Dto.

## Deeper: schemas

A schema is an object that says what a value must look like and checks it at run time.
Nothing in gvn reads type hints; hints are for readers. Schemas validate data that crosses a
boundary, convert values to and from their plain form, and render JSON Schema for vendors
that need it (tool arguments, for example).

| Schema | Admits |
|---|---|
| `Text(pattern=None)` | a `str`, optionally matching a regular expression |
| `Integer(minimum=None, maximum=None)` | an `int` that is not a `bool`, within inclusive bounds |
| `Number()` | an `int` or a finite `float` |
| `Boolean()` | `True` or `False` |
| `OneOf(*literals)` | one of a fixed set of strings |
| `Nullable(inner)` | `None`, or whatever `inner` admits |
| `ListOf(item)` | a list or tuple whose items satisfy `item`; decodes to a tuple |
| `MapOf(value)` | a dict with `str` keys whose values satisfy `value` |
| `Json()` | any plain value |
| `Record(fields, optional=())` | a dict with exactly the named fields |
| `DtoOf(dto_class)` | an instance of one Dto class (in `gvn.kernel.durable`) |

All live in `gvn.kernel.schema` except `DtoOf`. Every schema offers `problems(value)`,
`admits(value)`, `require(value)`, `encode(value)`, `decode(plain)` and `to_json_schema()`.

Here a search query has a required `text` and an optional `limit`:

```python
from gvn.kernel.schema import OneOf

search_query = Record(
    fields={"text": Text(), "limit": Integer(minimum=1)},
    optional=["limit"],
)
print(search_query.admits({"text": "moore"}))
print(search_query.problems({"text": 3, "extra": True}))
print(OneOf("low", "high").to_json_schema())
```

```text
True
('$.text: expected a string, got int', '$.extra: unknown field')
{'enum': ['low', 'high']}
```

`DtoOf` nests one Dto inside another, which is how composite objects save their parts. Here a
pair of tallies, one per shift, survives a JSON round trip:

```python
from gvn.kernel.durable import DtoOf


class ShiftTallies(Dto):
    schema = Record(fields={"morning": DtoOf(Tally.Dto), "evening": DtoOf(Tally.Dto)})


shifts = ShiftTallies(morning=Tally().to_dto(), evening=original.to_dto())
print(ShiftTallies.from_plain(json.loads(json.dumps(shifts.to_plain()))) == shifts)
```

```text
True
```

To write your own schema, subclass `Schema` and implement `check`, `plain`, `build` and
`to_json_schema`. The `Schema` class docstring in `gvn.kernel.schema` is the full contract.

## Deeper: durable classes gvn ships

Every stateful class in gvn follows this protocol, including several you meet on later
pages: `Definition`, `Machine`,
`Message`, `ToolCall`, `ToolResult`, `Transcript`, `Budget`, `Event`, `Request`, `Outcome`,
the reference `Agent` and every `Workflow`. An agent's Dto holds its machine position, its
transcript, its budget and its pending tool calls; a workflow's Dto holds each of its
children's Dtos. One `to_dto().to_plain()` call gives you the whole tree as JSON.

## Recap

- State stays private inside objects; the Dto protocol is how such objects are saved.
- A durable class has an inner `Dto` with a `schema`, `to_dto()` and `from_dto(dto)`.
- The durability law: a restored object behaves exactly like the original, also after a trip
  through JSON.
- Dtos are validated on construction, immutable and comparable.
- Restore the actor's state from its Dto and supply its ports through the Governor.

**Next:** [Actors and events](actors-and-events.md), the objects that own a machine and its
data together.
