Browse documentation
Python API
View Markdown
On this page

gvn.runtime

The Governor and everything around a run: fulfilling requests, journaling, recovery, replay, forks, leases, memory, spending and throttles. It drives the actors the harness defines.

The ideas behind it are explained in The Governor, 6. Crash and resume, Runtime guarantees. This page is generated from the source, so it lists every public name with its signature and docstring. Python API has the other packages and an index of every name.

Modules

Module What it holds Names
gvn.runtime.evaluation Evaluation: judging traces against explicit expectations Check, Finishes, Parks, Either, Visits, Avoids, Within, Gated, By, ApprovedFirst, ModelAsked, Sensed, AnsweredBy, NoRejections, Grade, Evaluation, Scorecard
gvn.runtime.fork Fork: a second run that shares a recorded run's history up to a point, and then goes its own way Fork
gvn.runtime.forms Stored forms: the version of every journal record and snapshot, and how older ones are read qualified_tool_names, sensorless_actors, NewerForm, NoUpgrade, Forms
gvn.runtime.fulfillers The built-in Fulfillers for the standard requests ModelFulfiller, FallbackModel, ToolFulfiller, SensorFulfiller, PolicyFulfiller, ClockFulfiller
gvn.runtime.governor The Governor: drives actors by fulfilling the work they request Unfulfillable, Busy, Result, Governor
gvn.runtime.harnesses Harnesses: what a packaged job is Harness
gvn.runtime.inspection Inspection: a recorded run read back actor by actor Movement, Moment, Inspection, Inspector
gvn.runtime.launching Running a harness: the wiring between a Harness and a Governor NotLive, Launcher
gvn.runtime.leasing Leasing: one process at a time drives a run RunHeld, Driven, Leaseholder
gvn.runtime.memory Memory in a run: where a scope comes from, the two tools a model uses, and the fulfiller of an actor's own remember and recall requests EmbedderFailure, Embedder, embedded, cosine_similarity, fused_ranking, MemoryScope, RecallTool, RememberTool, MemoryFulfiller
gvn.runtime.outputs Ready-made Outputs Fanout, StreamOutput
gvn.runtime.recovery Recovery: rebuilding an actor from its journal after a process has died UnknownRun, Recovery
gvn.runtime.replay Replay: reading a recorded run back as a trace, and trying its events on a changed actor error_text, Frame, Trace, Entry, Replay
gvn.runtime.spending Spending: what a run has spent on model calls, and the allowance it may not exceed Unpriced, Rates, Spend, Allowance
gvn.runtime.throttles Throttles: shared limits on how fast and how many calls are made at once ConcurrencyThrottle, RateThrottle, Throttles, ThrottledModel

gvn.runtime.evaluation

Evaluation: judging traces against explicit expectations.

A Check looks at one Trace and reports problems; an Evaluation is a named set of Checks; a Scorecard is the result of grading many traces. Together with Replay.against this closes the improvement loop: propose a change, replay recorded runs against it, grade the traces, and adopt the change only if the scorecard did not get worse. Everything here is deterministic and fulfils no I/O; checks see only what a Trace holds (states, events, steps, the requests wanted after each event, outcome).

Constants: ABC.

Check

from gvn.runtime.evaluation import Check
Check()

Helper class that provides a standard way to create an ABC using inheritance.

Check.name

name() -> str

A short str identifying the check in reports.

Check.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Finishes

from gvn.runtime.evaluation import Finishes
Finishes(*states: str) -> None

The run finished, in one of states if any are given (else in any final state).

Finishes() accepts any final state, Finishes("completed") only that one, Finishes("escalated", "resolved") either. Each state is a non-empty str; a state given twice is a ValueError. Names: "finishes", "finishes in completed", "finishes in escalated or resolved" (states sorted, joined with " or ").

Finishes.name

name() -> str

A short str identifying the check in reports.

Finishes.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Parks

from gvn.runtime.evaluation import Parks
Parks(*states: str) -> None

The run ended waiting, not finished, with its top actor in one of states.

A correctly parked scenario (waiting for a person, a delivery, a wake-up) passes here and fails Finishes. Parks("awaiting_approval"); at least one state is required, each a non-empty str, none twice. A run that finished fails, naming the final state. Names: "parks in awaiting_approval", "parks in a or b" (sorted). The state checked is trace.state(), the top actor's state after the last event.

Parks.name

name() -> str

A short str identifying the check in reports.

Parks.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Either

from gvn.runtime.evaluation import Either
Either(*checks: Check) -> None

Passes when at least one of checks passes.

checks: at least two Checks (any kind), none the same object twice and no two with the same name. Name: "either <name> or <name>" in the order given (three or more: "either a or b or c"). When every member fails, the problems are each member's reasons, prefixed with its name ("<name>: <reason>"). A member that raises propagates its error unchanged (the Evaluation then names this check). Either(Finishes("signed"), Parks("negotiating")) is "finished signed, or parked negotiating".

Either.name

name() -> str

A short str identifying the check in reports.

Either.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Visits

from gvn.runtime.evaluation import Visits
Visits(state: str) -> None

The run passed through state at least once.

Visits.name

name() -> str

A short str identifying the check in reports.

Visits.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Avoids

from gvn.runtime.evaluation import Avoids
Avoids(state: str) -> None

The run never entered state.

Avoids.name

name() -> str

A short str identifying the check in reports.

Avoids.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Within

from gvn.runtime.evaluation import Within
Within(events: int | Callable[[Trace], int]) -> None

The run took at most events events (frames).

events is an int >= 0, or a callable (trace) -> int computing the limit from the trace being examined (e.g. from the brief in the first frame's event); a computed limit that is not an int >= 0 is a TypeError or ValueError when examined. Names: "within 12 events", or "within: computed" for a callable.

Within.name

name() -> str

A short str identifying the check in reports.

Within.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Gated

from gvn.runtime.evaluation import Gated
Gated(
    tools: Toolbox | Iterable[Tool],
    when: Callable[[ToolCall, dict[str, typing.Any]], bool] | None = None,
) -> None

No call to one of tools succeeded without a person approving that call first.

tools: the Tools, a non-empty iterable of Tool or a Toolbox (a str is a TypeError saying to pass the tool; the same tool twice counts once). Calls are matched by identity (the "identities" of the standard requests), so a call to another tool with the same short name is not gated. when: None, or a callable (call, context) -> bool taking the gvn ToolCall and the run context (a dict; {} when the request carried none); only calls for which it returns True are gated (amount thresholds, "production only"). Anything but a bool from when is a TypeError. Names: "gated: <tool identities sorted, comma-separated>", with " when <function name>" appended when when is given. A request that carries calls without one identity per call makes examine raise ValueError, which Evaluation.grade (like any exception a check raises) turns into a TypeError naming the check.

The check follows the request side of the run (Frame.requests()), so it sees every actor that uses the standard kinds and payloads, whatever its class (Agent, Errand, domain actors) and however deeply it is nested. Per origin (Request.origin(), the requesting actor's name):

  • a new consult_policy request starts a batch: nothing is approved;
  • a consult_policy or invoke_tools request (each read once, when its id first appears) gives the batch's calls and the run context ("calls" and "context" in its payload); invoke_tools wins;
  • a pending request_approval request says which calls a person is asked about (the ids in its "calls": every call of the batch in a trace recorded before per-call approval, which asked about the whole batch);
  • an accepted approved event addressed to the origin approves the calls it was asked about, except those its payload denies ({"denied": [{"call_id", ...}]}); an unaddressed one does so for every origin that was awaiting approval (had a request_approval request pending) when it arrived;
  • an accepted tools_returned addressed to the origin (unaddressed: to every origin that had invoke_tools pending) holding a successful result for a gated call is a problem unless that call was approved, naming the frame, the origin and the tool. The approvals are then used up.

Rejected and failed events changed nothing and are skipped. A trace with no calls to the named tools passes. A result whose call the check never saw requested (a trace that starts mid-batch) cannot be named and is ignored.

Gated.name

name() -> str

A short str identifying the check in reports.

Gated.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

By

from gvn.runtime.evaluation import By
By(tool: Tool, when: Callable[[dict[str, typing.Any]], float]) -> None

Every request for tool was journaled at or before when(context).

tool: the Tool (a str is a TypeError saying to pass the tool), matched by identity. when: a callable (context) -> at taking a copy of the run context of the request (a dict, {} when it carried none) and returning a finite number comparable with Frame.at() (anything else is a TypeError/ValueError). Follows the request side like Gated: every invoke_tools request, from any actor using the standard kinds, whose calls include tool is judged once, by the frame in which its id first appears (a call the request marks refused, which does not run, is not a request for its tool); a request that returns after an interrupt keeps its first time. Late requests are problems naming the frame, the origin and both times. A run that never requests the tool passes vacuously (use Visits or a state check to demand that it is asked for). Name: "by: <tool identity> when <function name>".

By.name

name() -> str

A short str identifying the check in reports.

By.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

ApprovedFirst

from gvn.runtime.evaluation import ApprovedFirst
ApprovedFirst(
    label: str,
    tools: Toolbox | Iterable[Tool],
    when: Callable[[ToolCall, dict[str, typing.Any]], bool] | None = None,
) -> None

A labelled approval was granted before any of tools was requested.

label: a non-empty str, the "approve" of a request_approval payload (what an Approval actor asks). tools: the Tools, a non-empty iterable of Tool or a Toolbox (a str is a TypeError saying to pass the tool), matched by identity. when: None (every call), or a callable (call, context) -> bool as in Gated; only calls for which it returns True need the gate (anything but a bool is a TypeError). Names: "approved first: <label> before <tool identities sorted, comma-separated>", with " when <function name>" appended when when is given.

It is a gate, not a per-call approval: once an accepted approved answer to a request carrying that label has been journaled, every LATER matching tool request is covered (Gated remains the per-call check). Like Gated it follows the request side of the run, so it sees every actor that uses the standard kinds, however deeply nested. In order, frame by frame:

  • an accepted approved event addressed to an origin that had a request_approval with this label pending grants the gate (unaddressed: it grants it if any origin with this label was pending when it arrived);
  • only after that, each invoke_tools request first appearing in the frame (read once, by id) with a matching call that it lets run (a call it marks refused does not run, so it needs no gate) is a problem unless the gate is already granted: the message names the frame, the origin and the tool. An approval journaled in the same frame as the request counts only if it comes from the event, i.e. it is earlier than the request that the frame's event produced.

A denied answer, a rejected or failed approved, an approval of another label and one still pending do not grant. A trace with no matching tool request passes vacuously. Replay.recorded rebuilds from the run's FIRST snapshot, so a recorded trace holds the whole run, a crash and recovery included. A trace built by hand to start mid-run only knows what it contains: an approval granted before it is not seen.

ApprovedFirst.name

name() -> str

A short str identifying the check in reports.

ApprovedFirst.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

ModelAsked

from gvn.runtime.evaluation import ModelAsked
ModelAsked(label: str, accepts: Callable[[Request], bool]) -> None

Every model call of the run asked what accepts allows.

label: a non-empty str, the rule in words ("no learner text in instructions"). accepts: a callable (request) -> bool taking one invoke_model Request: read request.origin() (the asking actor's name) and request.payload() (a fresh dict: "instructions" str, "messages" a list of plain message dicts, "tools", "context", and "model_role" when the actor names one). Anything but a bool from it is a TypeError; an exception it raises propagates. Name: "model asked: <label>".

A recorded run holds every request, so this check reads exactly what each model was told. It follows the request side like Gated: every invoke_model request, from any actor using the standard kinds (an Agent, a Conversation, a Choice, a summarising call, however deeply nested), is judged once, by the frame in which its id first appears (Frame.requests() lists what is still pending, so a request that waits across several events is not judged again). Each refused request is one problem naming the label, the frame and the origin. A run that makes no model call passes.

ModelAsked.name

name() -> str

A short str identifying the check in reports.

ModelAsked.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Sensed

from gvn.runtime.evaluation import Sensed
Sensed(
    label: str,
    sensor_name: str,
    accepts: Callable[[dict[str, typing.Any]], bool],
) -> None

Every reading the sensor sensor_name took in the run is one accepts allows.

label: a non-empty str, the rule in words ("lint ends clean"). sensor_name: the sensor's name (gvn.harness.sensors.Sensor), a non-empty str. accepts: a callable (reading) -> bool taking one reading as journaled with sensed, a fresh dict: {"sensor", "clean": bool, "text": str} for a reading taken, or {"sensor", "failed": str} for one that failed. Anything but a bool from it is a TypeError; an exception it raises propagates. Name: "sensed &lt;sensor_name>: &lt;label>".

It reads the recorded sensed events (pattern of ModelAsked, on the answer side): every reading of that sensor, from any actor (a hosted one included), is judged once, in the frame that journaled it. A rejected sensed was never taken and is not judged. Each refused reading is one problem naming the label, the frame and the actor it was addressed to. A run in which the sensor read nothing passes.

Sensed.name

name() -> str

A short str identifying the check in reports.

Sensed.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

AnsweredBy

from gvn.runtime.evaluation import AnsweredBy
AnsweredBy(kind: str, accepts: Callable[[Principal, Request], bool]) -> None

Every accepted answer to a request of kind was given by a principal that accepts.

kind: a non-empty str, a request kind ("request_approval", "request_input", a harness's own). accepts: a callable (principal, request) -> bool taking the gvn.harness.events.Principal the answer came from (Event.by()) and the Request that was answered; anything but a bool from it is a TypeError. Name: "answered by: <kind> <function name>".

Like Gated it follows the request side of the run, so it sees every actor that asks for kind, however deeply nested. Frame by frame, the requests of kind wanted after the previous frame are the ones the next event may answer; an accepted event answers one of them when it is addressed to that request's origin, and an unaddressed one answers every one of them. For a kind listed in gvn.harness.events.ANSWERS only the events listed there for it are answers (approved and denied for request_approval); for a kind not listed, any accepted event so addressed is, except interrupted and resumed: those are control inputs any actor takes, never someone's answer. Each answer is a problem when it came from nobody ("answered by nobody named") or from a principal accepts refuses; the message names the frame, the origin and the principal's subject and issuer (never its claims). Rejected and failed events are skipped. A run with no such answer passes.

AnsweredBy.name

name() -> str

A short str identifying the check in reports.

AnsweredBy.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

NoRejections

from gvn.runtime.evaluation import NoRejections
NoRejections()

No event was rejected or failed; one problem per offending frame.

NoRejections.name

name() -> str

A short str identifying the check in reports.

NoRejections.examine

examine(trace: Trace) -> tuple[str, ...]

Tuple of problems (str), empty when the trace satisfies the check.

Grade

from gvn.runtime.evaluation import Grade
Grade(run_id: str, problems: Mapping[str, tuple[str, ...]]) -> None

The result of one Evaluation on one Trace. Immutable.

Grade.run_id

run_id() -> str

Grade.passed

passed() -> bool

Grade.problems

problems() -> dict[str, tuple[str, ...]]

A fresh dict of check name -> tuple of problems.

Evaluation

from gvn.runtime.evaluation import Evaluation
Evaluation(name: str, checks: Iterable[Check]) -> None

Evaluation.name

name() -> str

Evaluation.grade

grade(trace: Trace) -> Grade

A Grade. A check that raises or returns something other than a tuple of str is a TypeError naming the check.

Evaluation.score

score(traces: Iterable[Trace]) -> Scorecard

A Scorecard over an iterable of Traces (run names must be distinct).

Scorecard

from gvn.runtime.evaluation import Scorecard
Scorecard(evaluation: str, grades: Iterable[Grade]) -> None

Grades of many runs. Immutable.

Scorecard.evaluation

evaluation() -> str

Scorecard.grades

grades() -> tuple[Grade, ...]

Scorecard.total

total() -> int

Scorecard.passed

passed() -> int

How many runs passed.

Scorecard.failures

failures() -> tuple[Grade, ...]

Tuple of the failing Grades.

Scorecard.regressions

regressions(baseline: Scorecard) -> tuple[str, ...]

Tuple of run names that pass in baseline (a Scorecard) but fail here.

Runs present in only one of the two are not regressions. TypeError unless a Scorecard.

Scorecard.summary

summary() -> str

Readable text: "<evaluation>: <passed>/<total> passed" then one line per problem.

gvn.runtime.fork

Fork: a second run that shares a recorded run's history up to a point, and then goes its own way.

A run is its journal: the birth snapshot of its actor and one record per event. Actors are deterministic, so the run as it stood after any number of records can be rebuilt exactly. A fork copies that prefix into ANOTHER journal and hands back the actor as it stood there. From then on the fork is an ordinary run: drive it with a Governor built over the journal it was copied into, and it records its own events after the shared ones.

fork = Fork(journal)
actor = await fork.at("helper", 12, Agent, into=SqliteJournal("what-if.db"))
actor.pending()                    # what the run was waiting for at that point
await governor.resume(actor)       # ask again: the model may answer differently
await governor.answer(actor, request, Event("denied", {"reason": "too risky"}))
                                   # or give the other answer to what a person was asked

What this is for: seeing what a run would 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. Replay (gvn.runtime.replay) feeds recorded events to a changed actor and so shows how changed CODE handles the same history; a fork keeps the code and changes the HISTORY from a point on, with real work fulfilled after it.

Positions. position counts records: the fork holds the records at positions below it, so 0 is the run at birth (before its first event) and await journal.length(run) is the run as it stands now. Every position is a point where the run could have crashed and been recovered, so every position is a valid place to fork.

The same name. A run is identified by its actor's name, and a fork is the same actor, so the fork has the same run id and lives in another journal: one journal never holds two runs of one name. Its request ids are those of the original too, and so are the idempotency keys its tools are given (Invocation.key()): a call the original had already issued, issued again by the fork, carries the key it carried before, which is what makes a repeat harmless. A call the fork makes AFTER it diverges may carry a key the original used for a different call. Whoever forks a run with effectful tools therefore decides what those tools reach: point the fork's Governor at tools bound to a test service, or at fakes.

Nothing in this module fulfils work or emits signals; like Recovery, it only reads a journal, calls actor.handle, and writes the copy.

Constants: JOURNAL_RECORD, SNAPSHOT.

Fork

from gvn.runtime.fork import Fork
Fork(journal: Journal, forms: Forms | None = None) -> None

Fork.at

async def at(
    run_id: str,
    position: int,
    actor_class: type[Actor],
    into: Journal,
) -> Actor

Copy run_id as it stood after position records into into and return its actor as it stood there.

run_id: a non-empty str. position: an int (not a bool) with 0 <= position <= await journal.length(run_id). actor_class: the Actor subclass the run was started with. into: the Journal that receives the fork; it must not be the journal forked from (the same object), and must hold nothing for run_id.

What is read: the run's first snapshot, which must be its birth (taken after 0 records), and its records at positions below position. The snapshot and every record are brought to the current form (Forms.read) and every record is turned into its Event before anything is handled or written, exactly as Recovery.recover does; the actor is rebuilt from the birth snapshot and handed those events in order (a rejected reaction is expected and ignored).

What is written, only after the actor was rebuilt without error, for position >= 1: into.begin(run_id, <birth snapshot>, <record 0>), then each later record with into.append(run_id, record, position=<its position>), then into.save_snapshot(run_id, position, <the rebuilt actor's snapshot>). The birth snapshot and the records are copied exactly as the source journal stores them (their own "form" included, nothing rewritten); the last snapshot is the actor's to_dto().to_plain() stamped with the current form, as the Governor writes one. So Recovery(into).recover(run_id, actor_class) gives an actor equal to the one returned, and a Governor over into continues the run at position. Every write is unfenced. For position == 0 nothing is written: the returned actor is the run at birth, and the first event a Governor over into hands it begins the run there.

The copy is not one atomic step: if it fails part-way (into raises, the call is cancelled), into holds a shorter prefix of the run, which is itself a valid run; nothing is cleaned up.

Raises: TypeError run_id not a str, position not an int, actor_class not an Actor subclass, into not a Journal ValueError run_id empty; position negative or past the end of the run (the message names the run's length); into is the journal forked from; the run's first snapshot was not taken at its birth; a stored snapshot or record is malformed, or a record does not fit the actor (as Recovery.recover reports them); NewerForm / NoUpgrade for a stored form that cannot be read UnknownRun (gvn.runtime.recovery.UnknownRun) the journal holds no snapshot of run_id PositionTaken (gvn.harness.ports.PositionTaken) into already holds a record or a snapshot for run_id; checked before anything is written, for position == 0 too In every one of these cases nothing was written to into.

gvn.runtime.forms

Stored forms: the version of every journal record and snapshot, and how older ones are read.

A run lives on in its journal: one record per event, plus snapshots of the actor. Those stored shapes change as gvn changes. So every one of them carries the number of the form it was written in, under the key "form":

{"form": 4, "sequence": 0, "at": 0.0, "event": {...}}   # a journal record
{"form": 4, "name": "helper", "machine": {...}, ...}    # a snapshot: the actor's Dto

Forms is the registry that writes that number and reads it back. Writing stamps the current form. Reading a stored dict gives its body in the current form, without the "form" key:

  • written in the current form: returned as it is;
  • written in an older form: passed through the registered upgrade functions, one step per version (0 -> 1, 1 -> 2, ...), before anyone builds an object from it;
  • written in a newer form than this registry knows: NewerForm;
  • older, but some step of the chain is not registered: NoUpgrade.

Both errors name what was found and what is supported, and are raised before any upgrade function runs, so nothing is half-read.

A stored dict without "form" was written before stored forms were versioned (gvn before 0.1.0, whose forms changed from build to build). It is read as form 0, for which gvn registers no upgrade: it is refused with NoUpgrade unless you register an upgrade from 0 yourself, knowing which build wrote your data.

An upgrade function takes the body of one stored dict (plain JSON: dicts, lists, str, numbers, bool, None; no "form" key) in form n and returns the body in form n + 1. It must be pure: no I/O, no clock, the same answer every time. It may build a new dict or change the one it is given and return it. What it returns is checked by the code that reads it, as any stored data is: an actor's Dto.from_plain and Event.Dto.from_plain refuse what does not fit.

Kinds. JOURNAL_RECORD is the shape of one journal record (its event included); SNAPSHOT is the shape of a snapshot, which is the plain form of the actor's Dto (an upgrade for it sees whatever actor class the run used, and hosted actors nested inside a workflow's state). Both kinds share one form number: a release that changes either bumps it, and registers an upgrade for each kind (the identity function where that kind did not change).

forms = Forms().upgrade(JOURNAL_RECORD, 0, add_missing_usage)
actor = await Recovery(journal, forms=forms).recover("helper", Agent)

The Governor writes with forms.current(); Recovery and Replay read with forms.read. The journals themselves store plain JSON and know nothing about forms, so any Journal implementation gets versioning for free.

gvn's forms. Form 1 was gvn's form from 0.1.0. Form 2 records tools by identity (gvn.harness.tools): an Agent's and a Conversation's "tools" hold identities, an Errand holds "identities" beside its "calls", every attempt (and every "tools" entry of an agent's outcome) holds "identity", and a Conversation's tally counts by identity. Journal records did not change (identity upgrade). A form-1 snapshot holds only short names, and nothing in it says which tool a name meant, so the snapshot upgrade needs the tools the deployment offered: Forms(tools=...) qualifies each name with the identity of the given tool of that short name (qualified_tool_names). The tools may share short names (a deployment's toolbox may): only a record that holds such a name is refused, since it cannot say which tool it meant. Forms() qualifies nothing: a form-1 snapshot that names no tool upgrades, and one that names a tool is refused with a ValueError that names the tools, before anything is built.

forms = Forms(tools=toolbox)           # the tools the form-1 runs were offered
actor = await Recovery(journal, forms=forms).recover("helper", Agent)

Form 3 gives the Agent and the Conversation sensors (gvn.harness.sensors): each Dto holds "sensors" (a SensorReadings.Dto), and their machines gained the states checking_sensors and sensing. A form-2 record has no sensors, so the snapshot upgrade (sensorless_actors) is total: it gives every Agent and Conversation an empty "sensors" and moves its machine's position from the form-2 definition to the form-3 one (every form-2 state is a form-3 state, with the same meaning, and the step count is kept). Journal records did not change (identity upgrade).

Form 4 records exposure and who answered, each under an optional key that is absent unless used: an Agent's and a Conversation's Dto hold "untrusted" (the identities of their untrusted tools) and "exposure" (the untrusted sources their model has read, gvn.harness.tools), and a Conversation's "thread_exposure" (the sources that came with its thread); an Event holds "by" (the Principal that answered), and an Approval's and an Inquiry's Dto "answered_by"; a model_replied or model_failed payload, and each of its retry entries, holds "provider". Each key is absent from data written before, so both upgrades are the identity.

Constants: JOURNAL_RECORD, SNAPSHOT, KINDS, FORM, GVN_FORM.

qualified_tool_names

from gvn.runtime.forms import qualified_tool_names
qualified_tool_names(
    tools: Toolbox | Iterable[Tool],
) -> Callable[[dict[str, typing.Any]], dict[str, typing.Any]]

The snapshot upgrade from gvn's form 1 to form 2, qualifying short names with the identities of tools (an iterable of Tool or a Toolbox: a deployment's tools, which may hold several tools of one short name from different places). A pure function of the body.

It walks the whole snapshot, hosted actors included, and rewrites the shapes gvn's own actors stored: an actor's "tools" list of names (beside "instructions" and "machine": an Agent, a Conversation), a Conversation's "tally" keys, an Errand's "calls" (it adds "identities"), and every attempt ({"name", "arguments", "status", "detail"}) and "tools" entry ({"name", "arguments", "content"}), to which it adds "identity": None for an unoffered attempt and for close. A name none of tools has is a ValueError naming it (and saying to pass the tools the run was offered); so is a shape it recognises but cannot qualify. A name several of tools share is a ValueError only when a record holds it, since the record cannot say which it meant: the error names the short name and the candidate identities, and says to give Forms only the tools the old data was written with. A name that is already an identity (it has a dot, which no short name has) is kept, so the upgrade leaves form-2 data as it is. Shapes of your own actors are yours to upgrade.

sensorless_actors

from gvn.runtime.forms import sensorless_actors
sensorless_actors(body: dict[str, typing.Any]) -> dict[str, typing.Any]

The snapshot upgrade from gvn's form 2 to form 3, a pure function of the body.

It walks the whole snapshot, hosted actors included, and gives every Agent and Conversation (a dict with "instructions", "machine", "tools" and "recall_limit", and no "sensors") the state of an actor without sensors: an empty "sensors". Its machine position on a form-2 definition (by fingerprint) is moved to the same actor's form-3 definition, with the same state and step count. A position on any other definition is left as it is (reading it then refuses it, as for any machine that changed). Shapes of your own actors are yours to upgrade.

NewerForm

from gvn.runtime.forms import NewerForm

Stored data is in a form newer than the registry reads: a newer build wrote it.

NoUpgrade

from gvn.runtime.forms import NoUpgrade

Stored data is in an older form and the chain of upgrades to the current one has a gap.

Forms

from gvn.runtime.forms import Forms
Forms(current: int = 4, tools: Toolbox | Iterable[Tool] = ()) -> None

The current stored form, and the upgrades from older ones. Immutable.

Forms() is gvn's own registry: form 4 (GVN_FORM), with gvn's upgrades from forms 1, 2 and 3 (see the module docstring). upgrade returns a new registry with one more step; the one it is called on is unchanged.

Forms.current

current() -> int

The form number this registry writes and reads without upgrading (an int).

Forms.upgrade

upgrade(
    kind: str,
    from_version: int,
    function: Callable[[dict[str, typing.Any]], dict[str, typing.Any]],
) -> typing.Self

A new registry that also upgrades kind from form from_version to the next.

kind: JOURNAL_RECORD or SNAPSHOT. from_version: an int, 0 (data with no version) up to current() - 1. function: a callable taking the body in form from_version and returning it in form from_version + 1. TypeError for wrong types; ValueError for an unknown kind, a from_version that is not below current(), or a step already registered.

Forms.upgrades

upgrades(kind: str) -> tuple[int, ...]

Tuple of the forms kind is upgraded from, in order (ints).

Forms.stored

stored(kind: str, body: dict[str, typing.Any]) -> dict[str, typing.Any]

The dict to store for body (a dict of plain JSON): body with "form": current() added. body is not changed. TypeError unless a dict; ValueError if it already has a "form" key.

Forms.read

read(kind: str, stored: Mapping[str, typing.Any]) -> dict[str, typing.Any]

The body of stored (a dict as stored wrote it) in the current form.

Returns a new dict without the "form" key. A missing "form" is form 0. Raises NewerForm when the form is above current(), NoUpgrade when some step from it up to current() is not registered (both before any upgrade runs), TypeError when stored is not a mapping or an upgrade returns something other than a dict, ValueError when "form" is not an int >= 0.

gvn.runtime.fulfillers

The built-in Fulfillers for the standard requests.

Each turns one kind of Request into the Event that answers it, using ports. Payload shapes of the reference agent's kinds are documented in gvn.harness.agent; the time kinds in gvn.harness.events; sense in gvn.harness.sensors.

Constants: VERDICTS, CLOCK_READ, READING, REFUSALS, SKIPPED_DETAIL, TOOL_REJECTED, TOOL_UNAVAILABLE.

ModelFulfiller

from gvn.runtime.fulfillers import ModelFulfiller
ModelFulfiller(
    model: Model,
    toolbox: Toolbox,
    retry: Retry | None = None,
    roles: Mapping[str, Model] | None = None,
) -> None

Fulfils invoke_model.

Builds an Exchange from the request, calls model.generate passing progress through, and returns model_replied with the reply message (its sealed content included, see Message) and the tokens the reply reports, {"message": ..., "usage": reply.usage()}: {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}, with the meanings Reply gives them (input_tokens counts every input token, cached or not; the two cache figures are parts of it). Always present, 0 where the model reports none, so the journal records what each call cost. "context_window" is added when the model knows its own (Model.context_window()), and "model", the name of the model that answered: the Reply's own (Reply.model(), what the vendor reported), else Model.name(), and no key when neither is known. "provider", the service that answered, is given the same way: the Reply's own (Reply.provider()), else Model.provider(), and no key when neither is known. A ModelFailure becomes model_failed with its reason. Any other exception propagates. A model name or provider that is not a non-empty str is a TypeError/ValueError, since it is journaled.

The request's context (the agent's run context) is never sent to the model.

Tools. The payload's "tools" lists the identities of the tools offered; each is resolved through the toolbox by identity (UnknownTool if absent), and the model is given its spec, which carries the short name. A request may also carry "provided": the specs of tools the requesting actor provides itself (plain forms, see gvn.harness.tools.spec_plain; a Conversation's close). Carried specs are used as they are. The offered tools must have distinct short names (ValueError otherwise: the toolbox may hold same-named tools, one request may not). A carried name that one of the offered tools also has is a ValueError: the actor's own tool must not shadow a real one, nor the other way round. The Exchange lists the specs in name order.

unmet(actor) also names the identities in actor.tool_identities() that the toolbox does not hold, since a request offering them could not be served.

Structured answers. A request may carry "answer": an answer schema's JSON Schema (gvn.harness.replies.answer_plain). It is rebuilt into the Record and given to the model as Exchange.answer; the actor checks the reply against it (the fulfiller does not).

Failures. model_failed carries {"reason"}, plus "retryable": true when the failure was retryable, "retry_after" when the vendor asked for a delay and "usage" when the vendor reported what the failed call spent, "exceeded_context": true when the conversation did not fit the model's context window, "model" when Model.name() is not None and "provider" when Model.provider() is not None (gvn.harness.replies). A failure's provider is the serving model's own, never guessed: a FallbackModel has none, so a failure from one names no provider, while its replies name the provider of the member that answered (FallbackModel).

Retries (retry=). None (the default) makes one attempt per request, as before. A Retry makes up to attempts calls for one request, sleeping on its Clock between them, when a call fails retryably; a failure that is not retryable, or that asks to wait longer than the Retry allows, ends the request at once. Whatever answers the request (a reply or the last failure) carries "retries": one entry per attempt given up on, {"reason", "waited", "retry_after"?, "usage"?, "model"?, "provider"?} ("model" and "provider" as on a failure), so the journal shows every retry, what it cost, on which model and at which service. Nothing else is journaled for them: the actor sees one event, so a retried call never doubles an effect (a model call has none beyond what it bills). Text a failed attempt already streamed to progress is not withdrawn; the next attempt streams its own. A crash during the retries loses them: after recovery the request is fulfilled again from its first attempt.

A model per role (roles=). None (the default), or a mapping of role name (as gvn.harness.context_window.model_role_checked accepts) to Model, copied. A request whose payload carries "model_role" (an actor built with model_role=, or a Summarise step with one) is served by that role's model; a request without it (or with None) by model, exactly as before. A role the mapping lacks (or any role when there is no mapping) is a ValueError naming the request and the role: a wiring error, not a model failure. Retries are made on the model that serves the request, and "context_window" is that model's.

unmet(actor) names the roles in actor.model_roles() this fulfiller has no model for, so the Governor refuses to drive an actor that would reach that ValueError before the actor handles anything (gvn.runtime.governor.Unfulfillable).

ModelFulfiller.unmet

unmet(actor: Actor) -> str | None

None when this fulfiller has a model for every role in actor.model_roles() and a tool for every identity in actor.tool_identities(); else a str naming what it lacks (the roles it has; the identities missing).

ModelFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

FallbackModel

from gvn.runtime.fulfillers import FallbackModel
FallbackModel(models: Iterable[Model]) -> None

A Model that asks each of models in turn, moving on when one fails retryably.

models: a non-empty sequence of Model, in order of preference. A reply from any of them is the reply. A failure that is not retryable (a refused or invalid request, a cut-off reply) is raised at once: another model would be asked the same thing. When every model failed retryably, the last failure is raised, its reason naming each. Each model's own sealed content stays with its vendor (gvn.harness.messages), so a conversation may move between vendors. Text a failed model already streamed is not withdrawn. Combine with Retry on the ModelFulfiller to retry the whole list.

name() is None: which model answered is the Reply's to say (Reply.model()). provider() is None too, since no one service answers for the list. The Reply it returns names the service that answered: a member's Reply that names its own provider (Reply.provider()) is returned unchanged; one that names none is returned as an equal Reply (same message, token counts and model) naming that member's provider(), or unchanged when that is None too. A failure names no provider: it is raised as the member raised it, or as one failure for the whole list, and the ModelFulfiller journals a failure's provider from FallbackModel.provider(), which is None, so a model_failed (or a retry entry) from a fallback never names a service that may not be the one that failed.

FallbackModel.context_window

context_window() -> int | None

The smallest context window among the models that know theirs, or None when none does: whichever model answers, a conversation within it fits.

FallbackModel.models

models() -> tuple[Model, ...]

FallbackModel.generate

async def generate(exchange: Exchange, progress: Progress) -> Reply

Run one model call and return the complete Reply.

Text fragments are reported to progress as they arrive; their concatenation equals the reply message's text. Raises ModelFailure for any failure. Must honour cancellation (asyncio.CancelledError) promptly.

ToolFulfiller

from gvn.runtime.fulfillers import ToolFulfiller
ToolFulfiller(toolbox: Toolbox) -> None

Fulfils invoke_tools: runs the calls and returns tools_returned.

Order. The calls run in the order the model gave them, one at a time, each starting only after the one before it has finished; except that a maximal run of consecutive calls whose tools all declare themselves independent (Tool.independent()) runs concurrently, as one step of that order. A call naming a tool the toolbox does not have is not independent.

Which tool. The payload carries "identities", one per call (gvn.harness.tools.identified_calls; a request without them, or with one that does not name its call's tool, is a ValueError and nothing runs). Each call runs the toolbox's tool of that identity, never one found by its short name.

Results are in the order of the calls. A call fails, without affecting the others (later calls still run), when its tool is unknown (no tool of that identity), its arguments do not satisfy the tool's schema, the tool raises, or it returns something that is neither plain JSON nor a ToolOutput; the failed ToolResult's content is {"error": &lt;kind>, "detail": str} with kind one of gvn.harness.tools.TOOL_ERRORS: unknown_tool, invalid_arguments, tool_rejected (the tool raised a ToolFailure that is not retryable: the service said no), tool_unavailable (a retryable ToolFailure, with "retry_after" when the last one asked for a delay: the service could not be reached), tool_raised (any other exception: a defect in the tool) or invalid_result. A ToolOutput becomes a result with its content and its attachments (journaled inline with the tools_returned event, like a user message's attachments). Cancellation is not a failure: it cancels the call (or the concurrent run of independent calls) in flight, starts none of the rest, and propagates.

Refused calls. The payload may carry "refused" (gvn.harness.tools invoke_payload): one entry per call, None when it runs, else {"status": "forbidden" | "denied" | "skipped", "reason": str or None}. A refused call is never run: its result is failed, with the refusal's detail as content (gvn.harness.tools.refusal_detail). Once a call of the request has been refused, every later call whose tool is not independent is not run either, since it may depend on the refused one: its result is failed with content SKIPPED_DETAIL. Independent calls still run, and calls before the first refusal run as usual. A "refused" that is not such a list is a ValueError, and nothing runs. Every call gets a result, in call order, even when none runs.

Each tool is run with an Invocation whose key is "<request id>#<tool call id>" (stable when the same request is re-issued after a crash, distinct for every other call), whose origin is the request's origin, and whose context is the request payload's context ({} when the payload has none).

Retries: a property of each tool (Tool.retry()), since only the tool knows whether repeating a call is safe; one request may hold a call retried five times and one never retried. A tool whose retry() is None makes one attempt per call. One whose retry() is a Retry has a call that raised a retryable ToolFailure run again, sleeping retry.delay(attempt, failure.retry_after(), random.random) seconds on retry.clock() between attempts, until it succeeds, fails another way, or the Retry gives up (attempts used up, or a retry_after longer than it allows); then the last failure is tool_unavailable. A retry() returning anything else is a TypeError naming the tool, which propagates (a broken tool definition, not a failed call). Every attempt of one call uses the same Invocation, so the same idempotency key: a tool already tolerates a repeat under one key, since a request re-issued after a crash repeats it too. Nothing else is retried: not a refused or skipped call, an unknown tool, invalid arguments, a ToolFailure that is not retryable, any other exception or an invalid result. Independent calls that run together retry independently of each other, each by its own tool's Retry; the order of the results is unchanged. Cancellation during a sleep between attempts cancels at once and propagates. The answer carries "retries" when some call was retried: call id -> one entry per attempt given up on, oldest first, {"reason", "waited", "retry_after"?} (see gvn.harness.tools.TOOLS_RETURNED), so the journal shows every retry; the actor sees one result per call. A crash during the retries loses them: after recovery the request is fulfilled again from each call's first attempt.

ToolFulfiller.unmet

unmet(actor: Actor) -> str | None

None when the toolbox holds a tool for every identity in actor.tool_identities(); else a str naming the identities missing (and any the toolbox holds under the same short name with another identity).

ToolFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

SensorFulfiller

from gvn.runtime.fulfillers import SensorFulfiller
SensorFulfiller(toolbox: Toolbox) -> None

Fulfils sense (gvn.harness.sensors): takes each reading an actor's sensors owe, from the measuring tools of its OWN toolbox, and answers sensed.

The sensor toolbox is separate from the model's: a measuring tool is never offered to a model, and its call goes to no policy and no person. So put only read-only measurements in it (a linter, a test run in a sandbox, a size check): a sensor runs each time a watched tool succeeds, whoever asked for that tool.

Each entry of the payload's "readings" ({"sensor", "tool", "arguments"}) is run, in order, one at a time, by the toolbox's tool of that identity, with an Invocation whose key is "<request id>#<sensor>", whose origin is the request's and whose context is the payload's context, exactly as ToolFulfiller runs a call (its retries, its failures). A result that is READING ({"clean": bool, "text": str}) is a reading taken: {"sensor", "clean", "text"}. Anything else is a reading that failed, {"sensor", "failed": <why>}: an unknown tool, invalid arguments, a tool that failed or raised, or a result that is not a READING. A failed reading does not fail the others, so the answer is always sensed, one entry per sensor asked, in order, each text and reason cut as gvn.harness.sensors.kept_text keeps it (at most STORED_READING characters, marked when cut). sense_failed is for a fulfiller that cannot serve the request at all. A payload that is not a sense payload is a ValueError and nothing runs.

unmet(actor) names the identities in actor.sensor_identities() the toolbox does not hold, so the Governor refuses the actor before anything is journaled.

SensorFulfiller.unmet

unmet(actor: Actor) -> str | None

None when the toolbox holds a tool for every identity in actor.sensor_identities(); else a str naming the measuring tools missing.

SensorFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

PolicyFulfiller

from gvn.runtime.fulfillers import PolicyFulfiller
PolicyFulfiller(decision: Decision) -> None

Fulfils consult_policy by asking a Decision about each call.

decision is a gvn.kernel.decision.Decision whose outcomes equal gvn.harness.agent.VERDICTS (ValueError otherwise; TypeError if not a Decision). It is asked once per call, in call order, to decide on a gvn.harness.tools.Consultation holding that one call and its tool's identity, the requesting actor's name (the request's origin), the request payload's context ({} when the payload has none), the payload's "exposure" (the sources of untrusted content the actor's model had read; none when the payload has no such key), and the whole reply with the call's position in it (reply(), reply_identities(), position()), all built from the one request (whose "identities" must be one per call: ValueError otherwise). When every call gets the same verdict, the returned Event is that symbol with no payload (as for a one-call request); otherwise it is the route (gvn.harness.tools.route) carrying {"verdicts": [<verdict name per call>]}. A decision that raises propagates, and nothing is answered.

PolicyFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

ClockFulfiller

from gvn.runtime.fulfillers import ClockFulfiller
ClockFulfiller(clock: Clock) -> None

Fulfils read_clock: returns clock_read {"now": clock.now()}.

The reading is journaled with the event, so a machine that computes a time from it gets the same time on replay and after a crash. The Governor fulfils read_clock with one of these over its own clock unless told otherwise.

ClockFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

gvn.runtime.governor

The Governor: drives actors by fulfilling the work they request.

An actor may want several things at once (Actor.pending() is a tuple). The Governor fulfils all of them concurrently, one task per request, and feeds their results back one at a time:

deliver(actor, event):         take(due); take(event); then run()
answer(actor, request, event, by): ask the entitlement (if any) whether ``by``
                               may answer; take(due); refuse if request went
                               away; take(event addressed to request.origin(),
                               stamped with ``by``); then run()
resume(actor):                 take(due); run()
wake(actor):                   take(woke) for each pending wake_at now due; then run()

Each of them first asks every fulfiller ``unmet(actor)``; a str answer raises
Unfulfillable before anything is handled, journaled or signalled.

take(due): every pending built-in wake_at already due (at <= clock.now()) is
           answered ``woke`` first, in pending order (``wake``: every wake_at,
           however handled). A deadline already past is never beaten by an event
           that arrives after it.

take(event): reaction = actor.handle(event)  (an invalid event raises here:
             nothing is journaled and the actor is unchanged); append the
             event to the journal (run = actor.name()); snapshot if due;
             then emit ``event`` (or ``rejected``) signals.

run(): loop
  actor finished          -> cancel and await all work in flight; finished
  wanted = actor.pending()
  work in flight whose request is no longer wanted is cancelled and awaited
  allowance reached       -> (at most once per call, and only when some wanted
                             request is work this Governor would start or keep
                             running) cancel and await all work in flight;
                             take(Event("interrupted")); loop. See "Allowance"
  each wanted request not yet started in this call, in order:
      external kind       -> nothing to start
      fulfilled kind      -> emit ``request``, start its task
      wake_at (built in)  -> sleep on it or park it, by the rule under
                             "Time" below
      neither             -> cancel and await all work in flight, Unfulfillable
  interruption pending    -> cancel and await all work in flight;
                             take(Event("interrupted")); loop
  nothing in flight       -> waiting; pending = the external wanted requests
                             and the wanted built-in wake_at requests
  wait until a task finishes or an interruption arrives
  take(due) first: a wake-up due by now beats any result finishing in the
  same wait (its sleeper is cancelled and awaited if it had not finished);
  then each finished task, in the order of its request in ``wanted``, if its
  request is still wanted: its Event, addressed to ``request.origin()``,
  is taken. A rejected result is signalled ``rejected`` and is otherwise
  harmless.

A task is started at most once per call while its request stays wanted; a request that disappears and reappears later is new work. Work that is cancelled is always awaited before the call moves on, so no work outlives the call that started it, whatever ends the call (an error, Unfulfillable, outside cancellation). Results and progress of work whose request is no longer wanted are discarded.

Snapshots. A run's first snapshot is its birth: the actor as it was when the call that journals the run's first event began, before it handled anything. It is written together with that first record, in one Journal.begin, so a run never has a birth snapshot without its opening record, and a call that journals nothing (resume or wake of an actor that never started) writes nothing at all. (A run journaled before birth snapshots, with records but no snapshot, is snapshotted as it is when a call begins, sequence = the journal's length.) After a snapshot taken when the run had n journaled events, the next is due once

max(snapshot_every, ceil(n * snapshot_growth))

more events have been journaled (defaults 20 and 0.5: snapshots at 20, 40, 60, 90, 135, 203, ...). The spacing grows with the run, so the total work of taking snapshots stays linear in the run's length even though each snapshot holds the whole actor; the price is that recovery replays more events: at most about snapshot_growth / (1 + snapshot_growth) of the run (a third with the default), and never fewer than snapshot_every would allow. snapshot_growth=0 restores the fixed cadence of one snapshot every snapshot_every events. A snapshot is actor.to_dto().to_plain() with the stored form added ("form": 4, Forms.current(); gvn.runtime.forms) and is taken right after the event it follows was journaled, so snapshot plus later records always reproduce the actor; Recovery needs nothing but the latest one.

Request ids. Every request carries an id of the form "&lt;actor name>/&lt;step count>", so the same request re-issued after a crash has the same id: work is delivered at least once, and the id lets whoever fulfils it make a repeat harmless (ToolFulfiller passes "<request id>#<tool call id>" to each tool as its key). Ids are unique within a run, and a run is identified by its actor's name (it is the journal's run_id), so two runs must not share a name in one journal.

Time. read_clock and wake_at (gvn.harness.events) need no registered fulfiller. read_clock is fulfilled by a ClockFulfiller over the Governor's clock. wake_at {"at": t} is handled by the Governor itself. Each time the loop goes round, every wanted wake_at is either slept on (a sleeper task sleeps on the clock until t and returns woke {}) or parked, by this rule:

  1. due already (t <= clock.now()): slept on, so answered at once, whatever sleep_within is;
  2. other work in flight (anything but sleepers; the process is occupied anyway): slept on, however far away t is, so a deadline fires even while a model or tool call never returns;
  3. nothing else in flight: slept on if t - now <= sleep_within (and sleep_within > 0); otherwise parked, and a sleeper already running for it is cancelled and awaited.

When nothing is left in flight the call returns waiting, with the parked wake_at requests among pending (Result.due() is the earliest such t). sleep_within=float("inf") always sleeps; sleep_within=0 parks every wake_at not yet due once nothing else runs. A sleeper's woke is taken like any work's result: journaled once, when it fires, and only if its request is still wanted. Nothing else about time is journaled.

Governor.wake(actor) (what a scheduler calls, from any process) answers woke to every pending wake_at whose t <= clock.now(), then drives on. A sleeper is work like any other: when its request disappears (the stage that asked ended, the actor was interrupted) it is cancelled and awaited, and its woke is never journaled; a woke for a request no longer pending is refused by answer with nothing journaled. A wake_at re-issued after a crash carries the same id and at (they are actor data), so a deadline is neither lost nor moved. Registering a fulfiller for either kind, or declaring it external, replaces the built-in handling of that kind.

Answers. answer refuses an event whose name the request's kind does not admit, for the kinds in gvn.harness.events.ANSWERS (the agent's kinds, remember included, request_approval, request_input, read_clock and wake_at); a kind not listed there (a harness's own) is not checked.

Who answered is part of the answer. answer(..., by=principal) takes the gvn.harness.events.Principal the deployment's entry point authenticated and vouches for (None: it named nobody); gvn authenticates nobody itself. Only answer says who answered: an event that already carries a by() is refused by answer and by deliver (ValueError). The event handed to the actor, journaled and signalled is event.addressed(request.origin()).answered_by(by), so the principal is journaled with the event ("by" in its plain form, present only when there is one) and the actor, a hosted child, Recovery, Replay and evaluation (gvn.runtime.evaluation.AnsweredBy) all see it. A Governor built with entitlement= (a Decision over gvn.harness.answering.Answering with the outcomes ENTITLEMENTS) asks it, after every other check of answer and before anything is driven, for every answer except one to a built-in wake_at: not_entitled raises gvn.harness.answering.NotEntitled with nothing journaled or signalled and the actor unchanged, still waiting; a Decision that raises propagates the same way (the answer is refused). An answer that comes too late (TooLate) is judged first too: a refused one drives nothing.

Allowance. Governor(allowance=...) (a gvn.runtime.spending.Allowance) limits what each run driven here may spend on model calls. Reaching it is delivered to the actor as interrupted, so under an allowance every driving call first asks actor.interruptible() and refuses an actor that does not take interrupted (Unfulfillable; TypeError for an answer that is not a bool), before anything is handled, journaled or signalled: a Workflow takes it when its Plan lists it in relay (or its own machine declares it). Each driving call (deliver, answer, resume, wake) then builds the run's tally when it begins: allowance.tally(), shown every event already in the run's journal (read from position 0, each record brought to the current form with this Governor's Forms exactly as Recovery reads records; a record that cannot be read raises as Recovery raises, before the actor handles anything). The tally is then shown every event the call takes, right after that event is journaled. Nothing is stored anywhere else: the journal is the only record of what was spent, so the tally is the same in any process, after a crash, and under any lease. Each time the loop goes round, after wanted is read and work no longer wanted is cancelled, and before anything is started: if the call has not done so already, allowance.reached(tally) is not None, and some wanted request is work this Governor would itself start or keep running (its kind is neither external nor a built-in wake_at: waiting for a time spends nothing, whether it is slept on or parked; a wake_at served by a registered fulfiller is ordinary work; work already in flight counts), then all work in flight is cancelled and awaited and Event("interrupted") is taken exactly as a caller's interruption is taken (handled, journaled, signalled). No request signal is emitted for work not started. This happens at most once per driving call: what the actor does with an interruption is its own declared behaviour (the reference agent suspends; another actor may ask for more work, compensation say, which then runs), and an actor that rejects interrupted in its state is not interrupted again in that call either. A run that only waits on the outside or on a deadline is not interrupted until it wants work. The Result carries overspent(), and the waiting and finished signals carry "spent". Under an allowance with rates, with a cost limit or without one (priced, not limited), a model call the rates hold no price for raises gvn.runtime.spending.Unpriced from the call. For an event the call takes, after that event was journaled (its event signal is not emitted), with work in flight cancelled and awaited; for a record already in the journal, as the call begins, before the actor handles anything. Without an allowance no tally is built, interruptible() is not asked and the journal is not read for one.

Leases. Each driving method takes lease=None. With a Lease, every journal write of the call (records and snapshots) is fenced with lease.fence(): the journal refuses it, writing nothing, once the run's lease has passed to another holder, and the call ends with LeaseLost after cancelling its work. Taking, renewing and releasing leases is gvn.runtime.leasing's job, not the Governor's.

Journal records are {"form": 4, "sequence": n, "at": time, "event": <Event.Dto plain>} ("form" is the stored form, Forms.current(); gvn.runtime.forms) with sequence counting per run from the number of records already present. A rejected event is still journaled (it was delivered); replay rejects it again.

One driver per run. Every record names its place in the journal (Journal, "One writer at a time"): the run's opening record is written with begin, every other with append(..., position=sequence). A call that finds, when it writes, that the run is no longer where it was when the call began (another driver, in this process or another, recorded meanwhile) raises PositionTaken with nothing written; the actor object, which handled an event the journal never took, must be discarded. An event is recorded before any work it calls for is started, so nothing is fulfilled for a driver whose record was refused.

Signals, for each handled event: event (or rejected), then request for each piece of work started; delta signals while work is fulfilled; and finally waiting or finished when the call returns. Data:

event     {"event": name, "to": address or None, "steps": [...]}; for an event
          that came from a Principal (``answer(..., by=)``), also "by":
          {"subject": str, "issuer": str or None} (never its claims); for a
          ``model_replied`` or ``model_failed`` whose payload has "usage", also
          "usage": {"input_tokens": int, "output_tokens": int,
          "cache_read_tokens": int, "cache_write_tokens": int}, the tokens the
          model call reported (gvn.harness.ports.Reply; for a failure, what the
          failed call spent, when the vendor said); a figure the payload lacks (a
          journal from before it was recorded) is 0. For either, also the
          payload's "retries" when it has them (the attempts given up on before
          this answer, each with its own "usage" when known;
          gvn.harness.replies), the payload's "model" when it names one (the
          model that answered), the payload's "provider" when it names one, and
          for a ``model_replied`` whose message has
          citations, "citations": the message's citation records. For a
          ``sensed``, "readings": each reading as journaled (gvn.harness.sensors),
          its text cut to ``SIGNALLED_READING`` characters, so a terminal can show
          what the sensors read
rejected  {"event": name, "state": name}
request   {"request_id": str, "kind": name}; for ``invoke_tools``, also
          "tools": [{"call_id": str, "name": short name, "identity": tool
          identity}, ...], one per call that will run, in call order, read from
          the payload's "calls", "identities" and "refused" (a refused call is
          left out; a payload not shaped so adds nothing)
delta     {"request": id, "text": str}
waiting   {"state": name, "pending": [kind names of the external requests],
           "requests": [<Request.Dto plain> of each external request],
           "due": earliest ``at`` of a pending wake_at, or None}
finished  {"state": name, "payload": ...}

Under an allowance only, ``waiting`` and ``finished`` also carry "spent": the
tally's ``usage()`` ({"input_tokens", "output_tokens", "cache_read_tokens",
"cache_write_tokens", "calls"}), plus "cost": float when the allowance has rates;
and "overspent": the str ``Allowance.reached`` gives, only when it is not None.

Constants: ANSWERS, READ_CLOCK, WAKE_AT, WOKE, JOURNAL_RECORD, SNAPSHOT, FINISHED, WAITING, SIGNALLED_READING.

Unfulfillable

from gvn.runtime.governor import Unfulfillable

An actor requested a kind of work that is neither fulfilled nor declared external, or a fulfiller lacks something the actor needs.

The first is found when the request is made: the message names the kind, the actor that asked (the request's origin, which may be a child deep in a workflow) and the run. The second is found before the actor handles anything: on every call that drives an actor (deliver, answer, resume, wake), the Governor asks each fulfiller unmet(actor) (gvn.harness.ports.Fulfiller), and a str answer (a model role the ModelFulfiller has no model for, or a tool identity in actor.tool_identities() the ToolFulfiller's toolbox does not hold, say, which is how a toolbox holding a same-named tool of another identity is refused, or a measuring tool the SensorFulfiller's toolbox does not hold) refuses the call, and so does an actor with sensors when nothing serves sense; the message names the actor, the kind of that fulfiller and what is unmet. Under an allowance (Governor(allowance=...)), so is an actor whose interruptible() is not True: reaching the allowance is delivered as interrupted, so a run under one must take it (a Workflow takes it when its Plan lists it in relay); the message names the actor and says so. Nothing is journaled, no snapshot is written, no signal is emitted and the actor is unchanged.

Busy

from gvn.runtime.governor import Busy

An event was delivered to an actor that is already being driven by this Governor.

Result

from gvn.runtime.governor import Result
Result(
    status: str,
    pending: tuple[Request, ...] = (),
    outcome: Outcome | None = None,
    rejected: bool = False,
    overspent: str | None = None,
) -> None

How a deliver, answer, resume or wake call ended. Immutable value.

pending is a tuple of the external Requests the actor is waiting on (empty when none); a finished Result has none. Parked wake_at requests are among them, and due() is the earliest of their times.

overspent: None, or the non-empty str Allowance.reached gave for the run's tally when the call returned (TypeError/ValueError otherwise); always None from a Governor without an allowance.

Result.status

status() -> str

FINISHED or WAITING.

Result.pending

pending() -> tuple[Request, ...]

The tuple of external Requests the actor is waiting on (empty when none).

Result.outcome

outcome() -> Outcome | None

The actor's Outcome when finished, else None.

Result.due

due() -> float | None

The earliest at (a float) of the wake_at requests in pending(), or None when there are none: when a scheduler should call Governor.wake.

Result.rejected

rejected() -> bool

True when the delivered event itself was rejected by the actor.

Result.overspent

overspent() -> str | None

None, or the str Allowance.reached gave for the run's tally when the call returned (which limit was reached, with both figures). Always None from a Governor without an allowance.

Governor

from gvn.runtime.governor import Governor
Governor(
    fulfillers: Mapping[str, Fulfiller],
    journal: Journal,
    output: Output,
    clock: Clock,
    external: Iterable[str] = (),
    snapshot_every: int = 20,
    snapshot_growth: float = 0.5,
    sleep_within: float = 60.0,
    forms: Forms | None = None,
    allowance: Allowance | None = None,
    entitlement: Decision | None = None,
) -> None

Governor.deliver

async def deliver(actor: Actor, event: Event, lease: Lease | None = None) -> Result

Hand event to actor and drive it until it finishes or must wait.

The event is journaled and signalled even when the actor rejects it; the call then carries on as resume would, and the Result has rejected=True. All of the actor's wanted, fulfillable requests are fulfilled concurrently (see the module docstring).

An event that carries a by() is a ValueError, raised before anything happens (nothing journaled or signalled, actor unchanged): who answered is said only through answer(..., by=), where it is checked.

Returns a Result. Raises: Busy if this Governor is already driving that actor (by name) Unfulfillable if the actor requests an unknown kind; the actor has already taken the step, and the signal for it was emitted; other work in flight is cancelled and awaited first. Also, before anything else happens (nothing journaled or signalled, actor unchanged), if a fulfiller's unmet(actor) names something missing, or, with an allowance, if actor.interruptible() is not True (Unfulfillable) TypeError if a fulfiller's unmet(actor) answers neither None nor a str, or (with an allowance) actor.interruptible() answers something other than a bool (nothing journaled or signalled, actor unchanged) whatever actor.handle raises for an invalid event (actor unchanged; nothing journaled) whatever a Fulfiller raises unexpectedly (other work in flight is cancelled and awaited first; the actor stays as it was before that result) TypeError if a Fulfiller returns something other than an Event ValueError if a Fulfiller returns an Event addressed to an actor other than the request's origin LeaseLost (with lease) if the journal refused a write because the run's lease passed to another holder; work in flight is cancelled and awaited first, and the actor object, which handled an event the journal never took, must be discarded PositionTaken if the journal refused a record because another driver recorded for the run since this call began (module docstring, "One driver per run"); as for LeaseLost, work in flight is cancelled and awaited first and the actor object must be discarded Unpriced (with an allowance that has rates, with or without a cost limit) if a model call no price applies to is counted: from a record already in the journal, as the call begins and before the actor handles anything; or from an event of this call, after that event was journaled, with work in flight cancelled and awaited first NewerForm, NoUpgrade, ValueError (with an allowance) if a record already in the journal cannot be read for the tally, as Recovery raises, before the actor handles anything Cancelling the call cancels and awaits all work in flight, then propagates the CancelledError.

lease: None, or the gvn.harness.ports.Lease under which this call drives the run (its run_id must be the actor's name: ValueError otherwise). Every journal write of the call is then fenced with lease.fence() (Journal's docstring). The Governor neither takes, renews nor releases leases: gvn.runtime.leasing.Leaseholder does. The same parameter, with the same meaning, is on answer, resume and wake.

With an allowance (module docstring, "Allowance"), the run's tally is built from its journal as the call begins and grows with each event the call takes; a run that has reached the allowance is interrupted, at most once in the call, before more work starts, and the Result's overspent() says which limit was reached. answer, resume and wake do the same.

Governor.answer

async def answer(
    actor: Actor,
    request: Request,
    event: Event,
    lease: Lease | None = None,
    by: Principal | None = None,
) -> Result

Deliver event as the answer to request, an external request actor awaits.

This ties an outside answer to the request it answers: request must be among actor.pending() (equal by id, kind and payload) and its kind must be external here (or wake_at handled by this Governor), event.to() must be None or request.origin(), and, for a kind listed in gvn.harness.events.ANSWERS, the event's name must be one that kind admits (woke for wake_at, approved/denied for request_approval, ...). The event is addressed to request.origin() and then handled exactly as deliver handles an event (journal, signals, the loop, the Result, including rejected=True if the actor rejects it). deliver stays for unsolicited events.

by: None, or the gvn.harness.events.Principal the entry point authenticated and vouches for as the one answering (TypeError otherwise). The event handed to the actor, journaled and signalled is event.addressed(request.origin()).answered_by(by); an event that already carries a by() is a ValueError (who answered is said through by, where it is checked). With an entitlement (Governor(entitlement=...)), after every check above and before anything is driven, the entitlement decides on gvn.harness.answering.Answering(request, event, by), unless the request is a built-in wake_at: not_entitled raises NotEntitled, naming the request, its kind and the principal's subject and issuer (or that nobody was named), never its claims; nothing is journaled or signalled and the actor is unchanged. A Decision that raises propagates, with the same effect. This comes before the deadlines below: an answer that would be too late is judged first.

Before the answer, every built-in wake_at already due is answered woke (as on every entry). If that makes request no longer pending (its stage expired), the answer is refused as too late, but the run is not left undriven: it is driven on exactly as wake would drive it (work started, signals emitted, events journaled) until it waits or finishes, and then TooLate (a ValueError) is raised carrying that drive's Result (error.result()). This is the one refusal that leaves the journal changed: the deadline had passed before the answer arrived, so its woke and whatever followed from it stand. If that drive itself raises (a fulfiller error, Unfulfillable), that error propagates instead.

Raises TypeError for an argument of the wrong type; Busy if the actor is being driven (checked first); ValueError if request is not pending, not external, event is addressed elsewhere, already carries a by(), or its name is not one the request's kind admits (nothing is journaled or signalled), or if a deadline already past made the request go away (see above); NotEntitled if the entitlement refuses the answer. Otherwise raises as deliver does.

Governor.resume

async def resume(actor: Actor, lease: Lease | None = None) -> Result

Continue driving actor from where it stands, without a new event.

For an actor rebuilt by Recovery (or simply held in memory): if it is finished, returns the finished Result; if none of its pending() requests is fulfilled here, returns waiting (pending = the external ones); otherwise fulfils them all and carries on exactly as deliver would. Re-issued work carries the same request id as before the crash, so it may run a second time (at least once delivery) and a fulfiller can use the id to make that harmless. Request ids are unique within a run; a run is identified by its actor's name, so two runs must not share a name in one journal.

Raises as deliver does (Busy, Unfulfillable, fulfiller errors). Emits a request signal for each piece of re-issued work and ends with waiting/finished.

Governor.wake

async def wake(actor: Actor, lease: Lease | None = None) -> Result

Answer every pending wake_at that is due, then drive on: what a scheduler calls.

Every request in actor.pending() of kind wake_at whose at is at or before clock.now() is answered woke {}, addressed to its origin, in pending order; one that an earlier answer made the actor drop is skipped. Each answer is journaled and signalled as answer would. Then the call carries on as resume does. With nothing due it is resume. Result.rejected() is True if the actor rejected one of the answers.

Raises TypeError for a non-Actor, Busy if the actor is being driven, ValueError (nothing journaled) if a pending wake_at has no finite at; otherwise as resume does.

Governor.interrupt

interrupt(name: str) -> bool

Interrupt the actor called name if this Governor is driving it.

Cancels and awaits all the work in flight and delivers an interrupted event (unaddressed) in its place; the pending call then continues from there and returns normally. If no work is in flight, the interruption is delivered before the next work starts, or just before the actor would start waiting. It is dropped only if the actor finishes first. Repeated interruptions before it is delivered make one interrupted event.

The actor must accept the interrupted symbol; if handle raises for it, the call raises.

Returns True if an interruption was scheduled, False if that actor is not being driven (deliver an interrupted event yourself in that case). Synchronous; safe to call from the event loop thread.

Governor.output_errors

output_errors() -> int

How many times the Output raised (those exceptions were swallowed).

gvn.runtime.harnesses

Harnesses: what a packaged job is.

A harness is a packaged way of doing one kind of job: the actor that does it (an Agent, a Workflow or any other Actor), the tools it may use, the policy over those tools, the shape of the brief it accepts, and an evaluation saying what a good run looks like. A harness holds configuration and injected ports only; every run is a new actor, and all run state lives in that actor (and so in the journal).

Harness is the interface everything that works on whole harnesses reads: whoever launches runs wires a Governor from it, an eval runs versions of it, and a tool that draws a harness starts from actor_class(), its entry actor.

Constants: ABC.

Harness

from gvn.runtime.harnesses import Harness
Harness()

One packaged job. Implementations are immutable after construction and receive the ports their tools need through their constructor.

Harness.name

name() -> str

A name of lowercase letters, digits and underscores starting with a letter ([a-z][a-z0-9_]*), unique among its siblings. (Stricter than a kernel symbol name, which also allows capitals, . and -: a harness name is a path segment.)

Harness.summary

summary() -> str

One sentence: what job this harness does.

Harness.brief

brief() -> Schema

A gvn.kernel.schema Schema (a Record) describing the brief a run is started with.

Harness.actor_class

actor_class() -> type[Actor]

The Actor subclass of this harness's runs (what Recovery and Replay rebuild).

Harness.start

start(run_id: str, brief: dict[str, typing.Any]) -> tuple[Actor, Event]

(actor, event): a fresh actor named run_id and the Event that starts it.

brief is a plain dict admitted by brief() (ValueError otherwise). Deterministic: the same arguments always give equal actors and events.

Harness.toolbox

toolbox() -> Toolbox

A gvn.harness.tools.Toolbox holding every tool any agent of this harness may call.

Harness.policy

policy() -> Decision

A kernel Decision over a gvn.harness.tools.Consultation whose outcomes are gvn.harness.agent.VERDICTS: which calls run freely, which need a person's approval, which are forbidden.

Harness.evaluation

evaluation() -> Evaluation

A gvn.runtime.evaluation.Evaluation: what a good run of this harness looks like.

Harness.external

external() -> tuple[str, ...]

Extra request kind names (beyond request_approval and request_input) that this harness's actors ask the outside world for. Default: none. read_clock and wake_at need no declaring (the Governor handles them); naming one here replaces that handling.

Harness.fulfillers

fulfillers() -> dict[str, Fulfiller]

Extra request kind -> Fulfiller that this harness's actors need fulfilled (beyond the reference agent's kinds and the time kinds). Default: none.

A harness with a memory takes its gvn.harness.ports.Memory like any other port (its Entry names it) and puts here "remember" -> gvn.runtime.memory.MemoryFulfiller over that memory, when its actors hand what their context reductions drop to it (remember_dropped), and the same fulfiller under "recall" when its actors recall by themselves (recall=True); a model's RecallTool / RememberTool over it go in its toolbox().

Harness.model_roles

model_roles() -> tuple[str, ...]

The model roles this harness's actors name (model_role= of an Agent, Conversation or Choice, or of a Summarise step): a tuple of distinct role names. Whoever launches it supplies a Model for each (Launcher(..., model_roles=)), and a launch missing one is refused before any run starts. Default: none (every call is served by the launcher's one model).

gvn.runtime.inspection

Inspection: a recorded run read back actor by actor.

gvn.runtime.replay reads a run back as a Trace: for every event, the steps it caused and the state of the run's own actor. That is enough to grade a run. It is not enough to look into one: a workflow hosts actors, those may host others, and one event moves several of them at once (an answer finishes a child, and its finishing moves the workflow).

An Inspection says, for every recorded event, what each actor did:

  • which actor took which step (Reaction.attributed);
  • where every actor of the run stood before and after (Actor.standings);
  • which actors started on that event and which are no longer hosted after it;
  • which actors started and finished within it (Reaction.passed: a child that decides at once, or a chain of such stages, stands neither before nor after), and the final state each ended in;
  • which requests began with it and which ended.

So a diagram of any actor in the run can be drawn in the state it had at any journal position, and a journal record can be traced to every transition it caused.

Inspector.recorded reads a run as it happened. Inspector.against feeds the same events to a changed actor, and Inspection.divergence names the first journal position at which the two differ.

Like Replay, inspecting only calls actor.handle: it fulfils nothing, journals nothing and emits nothing, and stored forms are read through gvn.runtime.forms.Forms exactly as Replay reads them.

Movement

from gvn.runtime.inspection import Movement
Movement(
    name: str,
    definition: Definition,
    before: State | None,
    after: State | None,
    steps: tuple[Step, ...] = (),
    end: State | None = None,
) -> None

What one actor did on one event. Immutable value.

An actor has a Movement in a Moment when it took at least one step, when it started on that event, when it is no longer hosted after it, or when it did both (it passed: it started and finished within the event, so before() and after() are None and ended() is the final state it ended in).

Movement.name

name() -> str

Movement.definition

definition() -> Definition

Movement.before

before() -> State | None

Movement.after

after() -> State | None

Movement.steps

steps() -> tuple[Step, ...]

Movement.started

started() -> bool

True when the actor was not hosted before this event (before() is None). An actor that passed both started and left.

Movement.left

left() -> bool

True when the actor is no longer hosted after this event (after() is None). Its last step, when it took one, says where it ended.

Movement.ended

ended() -> State | None

The State the actor was in when the event had been handled: after(); for an actor that passed, the final state it ended in; for one that left, the target of its last step (before() when it took none). Never None.

Moment

from gvn.runtime.inspection import Moment
Moment(
    sequence: int,
    at: float,
    event: Event,
    movements: tuple[Movement, ...],
    standings: tuple[Standing, ...],
    pending: tuple[Request, ...] = (),
    began: tuple[Request, ...] = (),
    ended: tuple[Request, ...] = (),
    error: str | None = None,
) -> None

One journal record and everything it did, actor by actor. Immutable value.

Moment.sequence

sequence() -> int

Moment.at

at() -> float

Moment.event

event() -> Event

Moment.movements

movements() -> tuple[Movement, ...]

The actors that moved, passed, started or left, each once. Order: the actors that took steps, by their first step; then the actors that passed (started and finished within the event, Reaction.passed), in the order they finished; then the actors that started, in standing order; then the actors that left without taking a step, in the order they stood before. Empty for a rejected event and for one that raised.

Moment.movement

movement(name: str) -> Movement | None

The Movement of the actor called name, or None when it has none here.

Moment.standings

standings() -> tuple[Standing, ...]

Where every actor of the run stood once the event had been handled.

Moment.pending

pending() -> tuple[Request, ...]

Every Request the run wanted once the event had been handled.

Moment.began

began() -> tuple[Request, ...]

The Requests wanted after the event that were not wanted before it (told apart by id), in pending() order.

Moment.ended

ended() -> tuple[Request, ...]

The Requests wanted before the event and no longer after it, in the order they were pending.

Moment.rejected

rejected() -> bool

True when the event changed nothing: no step was taken, or the event's own step was not a declared transition (Reaction.rejected), or it raised.

Moment.error

error() -> str | None

What handle raised for this event, as text; None when it did not raise. A recorded run has none unless the actor's code changed since.

Inspection

from gvn.runtime.inspection import Inspection
Inspection(
    run_id: str,
    start: tuple[Standing, ...],
    moments: tuple[Moment, ...],
    finished: bool,
    outcome: Outcome | None,
) -> None

A whole run, moment by moment. Immutable value.

Inspection.run_id

run_id() -> str

Inspection.start

start() -> tuple[Standing, ...]

Inspection.moments

moments() -> tuple[Moment, ...]

Inspection.moment

moment(sequence: int) -> Moment

The Moment of the record at journal position sequence. LookupError when the inspection holds none.

Inspection.finished

finished() -> bool

Inspection.outcome

outcome() -> Outcome | None

Inspection.standings

standings() -> tuple[Standing, ...]

Where every actor stands after the last moment (start() when there is none).

Inspection.at

at(sequence: int) -> tuple[Standing, ...]

Where every actor stood once the record at sequence had been handled. LookupError when the inspection holds no such record.

Inspection.actors

actors() -> tuple[str, ...]

The name of every actor that ever stood in this run, or passed through it (started and finished within one event), in order of first appearance: the run's own actor first, then, moment by moment, the actors that passed in that moment, then those that stand after it.

Inspection.of

of(name: str, beneath: bool = False) -> tuple[Moment, ...]

The Moments in which the actor called name has a Movement, in order. With beneath=True, also those in which an actor hosted beneath it has one (an actor whose name starts with name and /).

Inspection.divergence

divergence(other: Inspection) -> int | None

The first journal position at which this inspection and other differ, or None when they do not.

Two inspections differ at a position when one holds a moment there and the other does not, or when their moments there differ in rejected(), in whether handle raised (whether error() is None; not its text, which can hold actor names), the movements (actor names relative to each run's own actor, states, steps and where each ended, so an actor that passed and ended elsewhere differs) or the kinds of the requests that began and ended. Actor names are compared relative to the run's actor, so a run and the same events fed to an actor of another name do not differ by name alone. Only moments are compared, never start(). TypeError unless other is an Inspection.

Inspector

from gvn.runtime.inspection import Inspector
Inspector(journal: Journal, forms: Forms | None = None) -> None

Reads runs from a journal as Inspections.

Inspector.recorded

async def recorded(run_id: str, actor_class: type[Actor]) -> Inspection

The Inspection of run_id as it happened.

Rebuilds the actor from the run's first snapshot with actor_class and feeds it every record, exactly as Replay.recorded does, with the same errors (UnknownRun, TypeError, ValueError, NewerForm, NoUpgrade). An event that makes handle raise becomes a moment with an error and the inspection goes on.

Inspector.against

async def against(run_id: str, actor: Actor) -> Inspection

The Inspection of feeding the recorded events of run_id to actor.

actor is a fresh Actor built by the caller and is mutated. Events are re-addressed and errors raised exactly as Replay.against documents. recorded(...).divergence(against(...)) is then the first journal position at which the changed actor does something else.

gvn.runtime.launching

Running a harness: the wiring between a Harness and a Governor.

launcher = Launcher(harness, model, journal, output, clock)
result = await launcher.start("ticket-4711", {"question": "..."})
while result.status() == "waiting":            # a person is being asked
    result = await launcher.approve("ticket-4711", result.pending()[0])

Errors: NotLive when this launcher holds no live actor of the run named; gvn.runtime.recovery.UnknownRun when the journal holds nothing for it; gvn.harness.ports.PositionTaken when another driver wrote to the run while this launcher drove it without leases: nothing of this call was journaled, the launcher no longer holds the run live, and recover brings it back as the journal has it.

The Launcher builds one Governor with the harness's toolbox and policy: invoke_model is fulfilled by the given Model (and a call naming a model role by that role's Model, from model_roles: every role Harness.model_roles() names must be given, or the Launcher is refused), invoke_tools by the toolbox, consult_policy by the policy, and request_approval and request_input are external (a person answers). A harness's own kinds come from Harness.fulfillers(): a harness with a memory (a Memory port it was built with) fulfils remember (and recall, when its actors recall by themselves) there, with a gvn.runtime.memory.MemoryFulfiller. Time is the Governor's own: read_clock is fulfilled from the clock and wake_at is slept on (due within sleep_within seconds) or parks the run (later), so a scheduler calls wake once Result.due() has passed. It keeps the live actors it started or recovered, by run name; everything durable is in the journal, so a new Launcher over the same journal can recover any run.

Turns. One call at a time drives a run. reply, approve, deny, wake, resume (and interrupt of a run not being driven) called while another call drives the run wait their turn, first come first served, instead of failing; each is checked when its turn comes, so an answer that a call ahead of it made stale is refused then (ValueError, nothing journaled). A caller cancelled while it waits leaves the queue as if it had never joined.

scheduler:   if result.due() is not None and result.due() <= clock.now():
                 result = await launcher.wake("ticket-4711")

Leases. Given leases (a gvn.harness.ports.Leases sharing the journal's storage) and a holder name, every call that drives a run does it through a gvn.runtime.leasing.Leaseholder: it takes the run's lease (RunHeld if another process has it, or waits up to wait_for_lease seconds), drives with every journal write fenced, renews while driving, and releases when the run parks or ends, with its next due time (the pool is the harness's name), so a worker can find it. In this mode the journal is the run: reply, approve, deny, wake, resume and interrupt work for any run the journal holds, not only live ones, and a live actor is used only if no other process has driven the run since (otherwise the run is recovered first). NotLive is then raised only by actor and forget.

NotLive

from gvn.runtime.launching import NotLive

This launcher holds no live actor of that name (start or recover it first).

Launcher

from gvn.runtime.launching import Launcher
Launcher(
    harness: Harness,
    model: Model,
    journal: Journal,
    output: Output,
    clock: Clock,
    snapshot_every: int = 20,
    fulfillers: Mapping[str, Fulfiller] | None = None,
    external: Iterable[str] = (),
    snapshot_growth: float = 0.5,
    sleep_within: float = 60.0,
    forms: Forms | None = None,
    leases: Leases | None = None,
    holder: str | None = None,
    lease_for: float = 30.0,
    wait_for_lease: float = 0.0,
    model_roles: Mapping[str, Model] | None = None,
    allowance: Allowance | None = None,
    entitlement: Decision | None = None,
) -> None

Launcher.harness

harness() -> Harness

Launcher.leased

leased() -> bool

True when this launcher drives runs under leases (built with leases).

Launcher.start

async def start(run_id: str, brief: dict[str, typing.Any]) -> Result

Start a new run and drive it until it finishes or waits. Returns the Governor's Result.

ValueError if this launcher already holds a run of that name or the journal already has records for it, and equally when another launcher (in this process or another) begins a run of that name at the same moment: exactly one of them runs, and each other gets this ValueError having written nothing, started no work and kept no actor of the run.

Launcher.reply

async def reply(
    run_id: str,
    request: Request,
    event: Event,
    by: Principal | None = None,
) -> Result

Deliver event as the answer to request, an external request of a waiting run, and drive on. Returns the Result.

request is one of the Requests in the last Result's pending(), of any external kind (approval, request_input, a harness's own). The answer goes through Governor.answer: ValueError, with nothing journaled, unless the request is pending and external and event is unaddressed or addressed to request.origin() and its name is one the request's kind admits; it is then addressed there. A woke for a pending wake_at is accepted too. An answer that comes after a deadline already past raises gvn.harness.TooLate (a ValueError): the deadline was applied first and the run driven on from there, so the live actor is already where error.result() says (finished, or waiting on what comes next), and the run's turn is released for the next caller. If another call is driving the run, this waits its turn (module docstring) and those checks are made then. TypeError for a request that is not a Request or an event that is not an Event; NotLive if the run is not live here (both checked at once).

by: None, or the gvn.harness.events.Principal the caller's entry point authenticated and vouches for as the one answering (TypeError otherwise, checked at once). It goes to Governor.answer(..., by=by), which stamps it on the journaled answer, and is checked there against the Governor's entitlement: gvn.harness.answering.NotEntitled (nothing journaled) when it may not answer. An event that already carries a by() is a ValueError there.

Launcher.approve

async def approve(
    run_id: str,
    request: Request,
    except_calls: Mapping[str, str | None] | None = None,
    by: Principal | None = None,
) -> Result

Approve an approval request of a waiting run and drive on: reply with approved.

except_calls names the calls NOT approved: None (the default) or a mapping of call id (str, a ToolCall.call_id()) -> reason (str, or None for no reason) for each call asked about that the person denies. Every other call asked about is approved. The answer journaled is approved {"denied": [{"call_id", "reason"}, ...]} (gvn.harness.agent). None or an empty mapping approves every call. A call id that the request did not ask about is a ValueError from the run's actor, with nothing journaled. ValueError if request is not an approval request the run is waiting on (when its turn comes, as reply). NotLive if the run is not live here. by: who approves, as reply takes it.

Launcher.deny

async def deny(
    run_id: str,
    request: Request,
    reason: str | None = None,
    by: Principal | None = None,
) -> Result

Deny an approval request of a waiting run and drive on: reply with denied, carrying {"reason": reason} when a reason is given.

Every call asked about is denied, and nothing in the reply runs. reason is None or a str. ValueError if request is not an approval request the run is waiting on (when its turn comes, as reply). NotLive if the run is not live here. by: who denies, as reply takes it.

Launcher.recover

async def recover(run_id: str) -> Result

Rebuild a run from the journal (after a crash) and drive on. Returns the Result.

gvn.runtime.recovery.UnknownRun if the journal holds nothing for the run, which is also what a run whose starting event never reached the journal left (its first snapshot is written together with that event): start it again. ValueError if this launcher already holds it live. A journal written before that held a snapshot alone for such a run: it recovers in its initial state and waits with nothing pending, and start still accepts the name.

Launcher.wake

async def wake(run_id: str) -> Result

Answer woke to every pending wake_at of the run whose time has come (at <= clock.now()) and drive on: what a scheduler calls once Result.due() has passed. With nothing due it is resume without an event. Returns the Result.

Waits its turn if another call is driving the run (module docstring). NotLive if the run is not live here; ValueError (nothing journaled) if a pending wake_at has no finite at.

Launcher.interrupt

async def interrupt(run_id: str) -> Result | None

Interrupt a live run. NotLive if it is not live here.

If the Governor is driving the run (a start, reply, approve, deny, wake, recover or resume call is in progress), it is asked to interrupt it: the work in flight is cancelled, interrupted is delivered, and that call returns as usual; this returns None. Otherwise (the run waits, for example for a person) this takes its turn like reply and then delivers Event("interrupted") and drives on; it returns that Result. A finished run rejects the event (Result.rejected()).

Launcher.resume

async def resume(run_id: str) -> Result

Continue a suspended run: deliver Event("resumed") and drive on.

Returns the Result; a run that is not suspended rejects the event (Result.rejected()) and is otherwise unchanged. NotLive if the run is not live here. Waits its turn if another call is driving the run.

Launcher.forget

forget(run_id: str) -> None

Release run_id from this launcher's memory; actor(run_id) is NotLive afterwards.

Everything durable stays in the journal (trace, grade and recover still work). A long-lived launcher should forget each run once it has finished, or it holds every actor it ever drove. NotLive if the run is not live here; ValueError while a call is driving it or waiting its turn.

Launcher.actor

actor(run_id: str) -> Actor

The live actor of run_id (for inspection). NotLive otherwise.

Launcher.trace

async def trace(run_id: str) -> Trace

The recorded Trace of run_id (gvn.runtime.replay), read from the journal.

Launcher.grade

async def grade(run_id: str) -> Grade

The harness's evaluation applied to the recorded trace of run_id: a Grade.

gvn.runtime.leasing

Leasing: one process at a time drives a run.

Two processes over one journal must never drive the same run at once: both would append events, and the run would no longer be any actor's history. A Leaseholder prevents it with the gvn.harness.ports.Leases port:

holder = Leaseholder(leases=leases, journal=journal, holder="worker-1", clock=clock)
driven = await holder.drive(
    run_id="ticket-7",
    actor_class=Agent,
    drive=lambda actor, lease: governor.wake(actor, lease=lease),
)
driven.actor(), driven.result(), driven.position()

drive does, in order:

  1. Takes the run's lease (Leases.acquire) for lease_for seconds. If another holder has it, raises RunHeld at once (wait_for=0, the default), or retries on the Clock for up to wait_for seconds, then raises RunHeld.
  2. Makes sure it drives the run as the journal has it. The caller's actor is used only if the journal holds exactly position records now that the lease is held (position: how many records that actor reflects; 0 for a new run). Otherwise the run is rebuilt with Recovery (after taking the lease, so nothing can be appended behind its back).
  3. Calls drive(actor, lease) (normally a Governor method with lease=lease, so that every write is fenced), renewing the lease every lease_for / 3 seconds on the Clock while it runs. If a renewal finds the lease gone, the drive is cancelled and LeaseLost raised.
  4. Releases the lease, recording when the run next needs driving: the Result's due() for a waiting run (None when it waits only on people), None for a finished one. This is the index Leases.due answers from.

On the way out by an error: a TooLate (its drive completed) releases with its result's due(); a cancellation, or an error before drive was called (other than UnknownRun), releases with due = now, as acquire left it, so a worker looks at the run again and puts its schedule right; LeaseLost releases nothing (it is not ours); UnknownRun and any error raised by drive release with due = None (the error goes to the caller, and the run is not retried behind its back). If the process dies instead, nothing is released: the lease expires after lease_for seconds, the run is claimable from then (acquire had set its due to the time it was taken), and whoever takes it next recovers from the journal.

The fencing argument. A holder that stops (a long pause, a partition) may resume believing it still holds the run. Its writes carry its fence; acquire by anyone else raised the fence first; the journal checks the fence in the same transaction as each write. So once a new holder has the run, the old one cannot add one record, and the new holder read the journal only after taking the lease, so it saw every record the old one managed to write. Clocks decide only when a takeover may happen, never whether two holders can both write.

RunHeld

from gvn.runtime.leasing import RunHeld
RunHeld(message: str, lease: Lease) -> None

Another holder has the run's lease, and this caller would not (or could no longer) wait. lease() is that holder's Lease.

RunHeld.lease

lease() -> Lease

Driven

from gvn.runtime.leasing import Driven
Driven(actor: Actor, result: Result, position: int) -> None

How a leased drive ended. Immutable value.

actor(): the actor driven (the caller's own, or one rebuilt from the journal). result(): what drive returned. position(): how many records the journal held for the run when the drive ended, which is what the actor now reflects: pass both back to the next Leaseholder.drive of this run.

Driven.actor

actor() -> Actor

Driven.result

result() -> Result

Driven.position

position() -> int

Leaseholder

from gvn.runtime.leasing import Leaseholder
Leaseholder(
    leases: Leases,
    journal: Journal,
    holder: str,
    clock: Clock,
    pool: str = 'default',
    lease_for: float = 30.0,
    wait_for: float = 0.0,
    forms: Forms | None = None,
) -> None

Drives runs while holding their leases. See the module docstring.

Leaseholder.holder

holder() -> str

Leaseholder.pool

pool() -> str

Leaseholder.drive

async def drive(
    run_id: str,
    actor_class: type[Actor],
    drive: Callable[[Actor, Lease], Awaitable[Result]],
    actor: Actor | None = None,
    position: int = 0,
    recover: bool = True,
) -> Driven

Take the run's lease, drive it with drive(actor, lease), release it.

actor_class: the Actor subclass the run was started with (for recovery). drive: an async callable taking the actor and the Lease and returning the Governor's Result (TypeError otherwise, after releasing with no due). actor/position: the caller's copy of the run and how many journal records it reflects (module docstring, step 2); None always recovers. recover: False to refuse, with ValueError before driving, a run whose journal does not hold exactly position records (Launcher.start uses it: a new run must still be new once its lease is held). Returns a Driven.

Raises RunHeld (step 1); gvn.runtime.recovery.UnknownRun if the run must be recovered and the journal has nothing of it; LeaseLost if the lease was lost while driving; whatever drive raises. The lease is released as the module docstring says.

gvn.runtime.memory

Memory in a run: where a scope comes from, the two tools a model uses, and the fulfiller of an actor's own remember and recall requests.

A gvn.harness.ports.Memory keeps text under a scope. This module decides nothing about how text is kept or found; it wires a Memory into a run so that:

  • the scope is trusted configuration. MemoryScope says where it comes from (a fixed name, a key of the run context, either narrowed to the asking actor). A model never names, chooses or widens a scope: neither tool takes one as an argument, and an argument the schema does not list is refused before the tool runs.
  • the model decides when to remember and recall, through two ordinary tools, RememberTool and RecallTool. Policy, approval and the journal apply to them like any tool; their results are journaled, so replay never touches the memory; a MemoryFailure (or a scope that cannot be resolved) is raised from run, which the ToolFulfiller turns into a failed tool result. Recalled text is a tool result: untrusted content, never an instruction. RecallTool.untrusted() is True, so an actor whose model was handed what it recalled records the tool's identity in its exposure (gvn.harness.tools); RememberTool only writes, returns nothing from outside, and stays trusted (False).
  • an actor whose context budget hands its losses to memory (ContextBudget(..., remember_dropped=True)) has its remember request served by MemoryFulfiller, and an actor built with recall=True has its own recall request (entries matching each user message it takes, before its model is called) served by the same fulfiller. What that recall finds is untrusted too: the actor appends it as one user message under a fixed header, never as an instruction, and adds gvn.harness.tools.RECALLED_SOURCE to its exposure.

The tools are not added to any toolbox by themselves: pass them like any other tool.

Recall by meaning. How a memory finds text is its own business: the Memory port says nothing about it, and a memory of your own (over a search service, a vector database, a file) implements the port and nothing here. For the memories gvn ships, this module names the one thing a memory needs from outside to match by meaning as well as by words: an Embedder, which turns texts into vectors. It is optional everywhere it is taken (SqliteMemory(path, embedder=...), ListMemory(embedder=...)): without one a memory matches by words, as before; with one it also keeps a vector for each entry and finds entries whose meaning is near the query's. No actor, tool, fulfiller or Governor ever sees an embedder. The two pure functions the shipped memories rank with are here too (cosine_similarity, fused_ranking), for a memory of your own that wants the same behaviour.

Constants: ABC.

EmbedderFailure

from gvn.runtime.memory import EmbedderFailure
EmbedderFailure(reason: str) -> None

An embedder could not turn texts into vectors. reason is a non-empty str for people and logs (TypeError/ValueError otherwise). A memory that uses an embedder raises MemoryFailure (with this reason) in its place, so callers of a Memory meet one kind of failure.

EmbedderFailure.reason

reason() -> str

Embedder

from gvn.runtime.memory import Embedder
Embedder()

Turns texts into vectors whose closeness stands for closeness of meaning. What a memory that recalls by meaning needs from outside; an embedding service's adapter, or a model run locally, implements it.

A memory keeps the vector of each entry beside it and compares it with the vector of a query. Vectors made by different embedders mean nothing to each other, so a memory records name() with every vector and only ever compares vectors of one name.

Embedder.name

name() -> str

A non-empty str naming this embedding: the same for every object whose vectors may be compared with each other (the same model with the same settings), and different otherwise. Constant for the object's life; no I/O.

Embedder.embed

async def embed(texts: list[str]) -> list[list[float]]

The vectors of texts (a non-empty list of non-empty str), one per text, in the same order: a list of lists of float, each finite, every vector of the same length (>= 1) on every call, none all zeros. A fresh list. The same text gives the same vector, or one close enough that nothing depends on the difference.

Raises EmbedderFailure when it cannot (the service is unreachable, refuses, or answers with something that is not such a list). Must honour cancellation promptly.

embedded

from gvn.runtime.memory import embedded
embedded(
    embedder: Embedder,
    vectors: list[Sequence[float]],
    count: int,
) -> list[tuple[float, ...]]

vectors as embedder.embed must return them for count texts, checked: a list of count tuples of float. A memory calls this on what an embedder returned before it keeps or compares anything.

Raises EmbedderFailure naming embedder.name() when vectors is not a list of exactly count lists (or tuples) of numbers (int or float, never bool), when a number is not finite, when a vector is empty or all zeros, or when the vectors differ in length. TypeError when embedder is not an Embedder or count not an int >= 1.

cosine_similarity

from gvn.runtime.memory import cosine_similarity
cosine_similarity(left: Sequence[float], right: Sequence[float]) -> float

The cosine of the angle between two vectors: 1.0 for the same direction, 0.0 for unrelated, -1.0 for opposite; a float in [-1.0, 1.0] (clamped against rounding).

left and right: sequences of finite numbers (not bool), of the same length

= 1, neither all zeros. TypeError/ValueError otherwise. Pure.

fused_ranking

from gvn.runtime.memory import fused_ranking
fused_ranking(rankings: Sequence[Sequence[Hashable]], limit: int) -> list[Hashable]

One ranking out of several, by reciprocal rank fusion: the ids of rankings, best first, at most limit.

rankings: a sequence of rankings, each a sequence of distinct ids (any hashable values), best first; it may be empty, and so may any ranking. limit: an int >= 1. TypeError/ValueError otherwise, including for a ranking that repeats an id.

An id's score is the sum, over the rankings that hold it, of 1 / (60 + rank) with rank counted from 1. Ids are ordered by score, highest first; ids of equal score keep the order in which they first appear when the rankings are read one after another. So an id that several rankings place high comes before an id only one of them holds, a single ranking comes back as it is (cut to limit), and the result never depends on how the rankings scored their entries, only on their order. Pure.

MemoryScope

from gvn.runtime.memory import MemoryScope
MemoryScope(name: str) -> None

Where a memory scope comes from. Immutable value, equal by content.

MemoryScope(name): always name (a non-empty str). MemoryScope.from_context(key): the value of context[key] in the run context of the actor asking (harness code writes the context; a model never does). scope.per_actor(): the same scope narrowed to the asking actor, "<scope>/<actor name>"; narrowing a narrowed scope changes nothing.

resolve(context, origin) gives the str. TypeError/ValueError for bad arguments.

MemoryScope.from_context

from_context(key: str) -> MemoryScope

A scope read from context[key] when it is resolved.

MemoryScope.per_actor

per_actor() -> MemoryScope

A new scope: this one, narrowed to the actor that asks.

MemoryScope.resolve

resolve(context: Mapping[str, typing.Any] | None, origin: str) -> str

The scope as a str, for a run context context (None or a mapping) and the asking actor origin (a non-empty str).

For a scope read from the context: ValueError when the context is None, lacks the key, or holds something there other than a non-empty str. The message names the key, never the context's other content. TypeError for a context that is neither None nor a mapping, or an origin that is not a str.

RecallTool

from gvn.runtime.memory import RecallTool
RecallTool(
    memory: Memory | None = None,
    scope: MemoryScope | None = None,
    limit: int = 5,
    name: str = 'recall',
    namespace: str | None = None,
) -> None

The tool a model uses to recall: {"query": str} gives {"entries": [{"id", "text"}, ...]}, best first, at most limit.

memory: a Memory, or None. scope: a MemoryScope, resolved for each call from the invocation's context and origin; given exactly when memory is (ValueError otherwise). Built without them, the tool only names itself (identity, arguments, description) for a plan, a policy or a check, and refuses to run (RuntimeError, a failed result): build the one the toolbox holds over a Memory and its scope. Its identity is the same. limit: an int >= 1. name: the tool's name. namespace: None (this module, gvn.runtime.memory) or a dotted identifier; give one when a deployment holds two recall tools of one name over different memories, so their identities differ. Independent (a pure read) and untrusted (untrusted() is True). A blank query is refused (ValueError, a failed result); a MemoryFailure or a scope that cannot be resolved is raised, which the runtime turns into a failed result. TypeError/ValueError at construction.

RecallTool.name

name() -> str

The short name the model sees and calls. Matches [A-Za-z][A-Za-z0-9_-]*. Unique among the tools one actor is offered; a Toolbox may hold same-named tools of different identities.

RecallTool.namespace

namespace() -> str

Where the tool comes from, a dotted identifier: the module that defines the tool's class (type(self).__module__) unless a tool overrides it. A tool class that backs many tools (one per configuration) takes a namespace at construction, so tools of one class configured apart have different identities.

RecallTool.description

description() -> str

What the tool does, written for the model.

RecallTool.arguments

arguments() -> Record

A gvn.kernel.schema.Record describing the arguments dict.

RecallTool.independent

independent() -> bool

True when a call to this tool neither depends on nor affects any other call in the same reply (a pure read). Independent calls next to each other may run at the same time; everything else runs in the order the model asked.

False unless a tool overrides it. Must return a bool (the Toolbox checks).

RecallTool.untrusted

untrusted() -> bool

True: what a memory holds is untrusted content, whoever wrote it (a person, a model that had read a web page, an earlier run). A call to this tool that ran adds its identity to the calling actor's exposure (Tool.untrusted).

RecallTool.run

async def run(
    arguments: dict[str, typing.Any],
    invocation: Invocation,
) -> dict[str, list[dict[str, str]]]

Do the work. arguments already satisfies arguments(). Returns plain JSON, or a ToolOutput when the model should also see images or documents (a screenshot): its content is the result's JSON and its attachments go to the model after it.

invocation is the Invocation: which run asked (invocation.origin()), with what trusted data (invocation.context()), under which idempotency key (invocation.key()). A tool that must stay within the run's data (only this alert's hosts, only this customer) checks invocation.context() and raises rather than act outside it.

invocation.key() is a non-empty str that identifies this call: it is the same every time the same call of the same run is (re)issued, and different for every other call. Work is delivered at least once, so after a crash the same call may run again with the same key. A tool with side effects should use the key to make repeats harmless, for example by passing it to the service it calls as that service's idempotency key, or by remembering the keys it has completed (in storage that outlives the process) and not repeating them.

What the key does not cover. An Agent that is interrupted after a tool acted, and then resumed, asks its model again: the next call is a new call with a new key, even when it asks for the same thing. (An Errand's batch is fixed, so its keys stay the same across interrupt and resume.) An effect that must happen at most once whatever happens to the run (a payment, a deployment, a signature) should therefore be keyed by what it is, built from the trusted invocation.context() (for example "promote:<service>:<version>"), not by invocation.key() alone.

Failure. A tool that understands why a call failed raises ToolFailure: retryable=True when the service could not be reached or asked to wait (an outage, a timeout, a rate limit; pass its retry_after when it gave one), retryable=False (the default) when it answered and refused (not found, not permitted, invalid for the service, a business rule). The runtime turns it into a failed ToolResult of kind tool_rejected or tool_unavailable, and may run a retryable call again under the same invocation.key() (when the tool declares a retry()), which a tool already tolerates. Any other exception is reported as tool_raised: a defect in the tool, never retried. See TOOL_ERRORS.

RememberTool

from gvn.runtime.memory import RememberTool
RememberTool(
    memory: Memory | None = None,
    scope: MemoryScope | None = None,
    name: str = 'remember',
    namespace: str | None = None,
) -> None

The tool a model uses to remember: {"text": str} gives {"id": str}.

memory, scope: a Memory and a MemoryScope, resolved for each call from the invocation's context and origin; or neither, as RecallTool's (the tool then only names itself and refuses to run). name: the tool's name. namespace: as RecallTool's. Not independent (it writes), and not untrusted: it returns only the id the memory gave the entry, nothing written outside the deployment. The memory's key is invocation.key(), so a call re-issued after a crash keeps nothing new and answers with the first entry's id. A blank text is refused (ValueError, a failed result); a MemoryFailure or a scope that cannot be resolved is raised, which the runtime turns into a failed result. TypeError/ValueError at construction.

RememberTool.name

name() -> str

The short name the model sees and calls. Matches [A-Za-z][A-Za-z0-9_-]*. Unique among the tools one actor is offered; a Toolbox may hold same-named tools of different identities.

RememberTool.namespace

namespace() -> str

Where the tool comes from, a dotted identifier: the module that defines the tool's class (type(self).__module__) unless a tool overrides it. A tool class that backs many tools (one per configuration) takes a namespace at construction, so tools of one class configured apart have different identities.

RememberTool.description

description() -> str

What the tool does, written for the model.

RememberTool.arguments

arguments() -> Record

A gvn.kernel.schema.Record describing the arguments dict.

RememberTool.run

async def run(
    arguments: dict[str, typing.Any],
    invocation: Invocation,
) -> dict[str, str]

Do the work. arguments already satisfies arguments(). Returns plain JSON, or a ToolOutput when the model should also see images or documents (a screenshot): its content is the result's JSON and its attachments go to the model after it.

invocation is the Invocation: which run asked (invocation.origin()), with what trusted data (invocation.context()), under which idempotency key (invocation.key()). A tool that must stay within the run's data (only this alert's hosts, only this customer) checks invocation.context() and raises rather than act outside it.

invocation.key() is a non-empty str that identifies this call: it is the same every time the same call of the same run is (re)issued, and different for every other call. Work is delivered at least once, so after a crash the same call may run again with the same key. A tool with side effects should use the key to make repeats harmless, for example by passing it to the service it calls as that service's idempotency key, or by remembering the keys it has completed (in storage that outlives the process) and not repeating them.

What the key does not cover. An Agent that is interrupted after a tool acted, and then resumed, asks its model again: the next call is a new call with a new key, even when it asks for the same thing. (An Errand's batch is fixed, so its keys stay the same across interrupt and resume.) An effect that must happen at most once whatever happens to the run (a payment, a deployment, a signature) should therefore be keyed by what it is, built from the trusted invocation.context() (for example "promote:<service>:<version>"), not by invocation.key() alone.

Failure. A tool that understands why a call failed raises ToolFailure: retryable=True when the service could not be reached or asked to wait (an outage, a timeout, a rate limit; pass its retry_after when it gave one), retryable=False (the default) when it answered and refused (not found, not permitted, invalid for the service, a business rule). The runtime turns it into a failed ToolResult of kind tool_rejected or tool_unavailable, and may run a retryable call again under the same invocation.key() (when the tool declares a retry()), which a tool already tolerates. Any other exception is reported as tool_raised: a defect in the tool, never retried. See TOOL_ERRORS.

MemoryFulfiller

from gvn.runtime.memory import MemoryFulfiller
MemoryFulfiller(memory: Memory, scope: MemoryScope) -> None

Fulfils an actor's own two memory requests: remember (an actor hands a memory what its context reduction is about to drop: remember_dropped) and recall (an actor built with recall=True asks for entries matching a user message it just took). It dispatches on the request's kind; any other kind is a ValueError naming it. Wire it under both: {"remember": fulfiller, "recall": fulfiller}.

Both payloads carry the run context ("context": the run context or None; it may be absent) and never a scope: the scope is resolved here, from trusted wiring, as scope.resolve(context, request.origin()).

remember {"text": str, "context"}: the text is kept with memory.remember(scope, text, key=request.request_id()), so the same request fulfilled again keeps nothing new. Answers remembered {"entry": <id>}, or remember_failed {"reason"} when the memory raises MemoryFailure or the text is blank (nothing to keep).

recall {"query": str, "limit": int >= 1, "context"}: answers recalled {"entries": [{"id", "text"}, ...]} with what memory.recall(scope, query, limit) found, best first, or recall_failed {"reason"} when the memory raises MemoryFailure or the query is blank (nothing to look for). The query is the user's text: data for the memory, never a scope. What the memory returns is checked: a list of at most limit mappings with exactly a str "id" and a str "text"; anything else is a TypeError/ValueError that propagates (a broken memory adapter, not a failure the actor should route on). A recall is a read: fulfilled again, it asks the memory again.

The answers are gvn.harness.replies' REMEMBERED / REMEMBER_FAILED and RECALLED_REPLY / RECALL_FAILED. A scope that cannot be resolved (the run context lacks the key) is a wiring error, not a failure of the memory: its ValueError propagates, as does a payload of another shape. Cancellation propagates.

MemoryFulfiller.fulfil

async def fulfil(request: Request, progress: Progress) -> Event

Fulfil request and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour cancellation promptly.

gvn.runtime.outputs

Ready-made Outputs.

Fanout

from gvn.runtime.outputs import Fanout
Fanout(outputs: Iterable[Output]) -> None

Sends every Signal to several Outputs, in order.

If one raises, the others still receive the signal; afterwards the first exception is re-raised (the Governor swallows and counts it).

Fanout.emit

emit(signal: Signal) -> None

Take one Signal. Synchronous; must return promptly and must not block on I/O.

The Governor swallows and counts any exception raised here: an observer can never break a run.

StreamOutput

from gvn.runtime.outputs import StreamOutput
StreamOutput() -> None

An Output you can async for over: the user-facing stream.

emit never blocks (the buffer is unbounded). Iteration yields Signals in emission order and ends after close() once the buffer is drained. emit after close raises RuntimeError. Must be created and consumed on one event loop.

StreamOutput.emit

emit(signal: Signal) -> None

Take one Signal. Synchronous; must return promptly and must not block on I/O.

The Governor swallows and counts any exception raised here: an observer can never break a run.

StreamOutput.close

close() -> None

No more signals will come. Idempotent.

gvn.runtime.recovery

Recovery: rebuilding an actor from its journal after a process has died.

The Governor journals every event it hands an actor, and snapshots the actor at the run's birth (written together with the run's first record, so a run exists in the journal only once that record does) and every few events after that. Actors are deterministic, so the latest snapshot plus the events recorded after it reproduce the actor exactly as it was when the last event was journaled. A run whose first record never reached the journal left nothing: recovering it raises UnknownRun, and it is started again.

actor = await Recovery(journal).recover("helper", Agent)
result = await governor.resume(actor)      # re-issues whatever it was waiting for

Replaying only calls actor.handle; it fulfils no work and emits nothing.

Stored forms are read through gvn.runtime.forms.Forms: the snapshot and every record are brought to the current form (or refused with NewerForm or NoUpgrade) before the actor is built, so a refused journal loads nothing.

Times survive too: a clock reading (clock_read) is a journaled event, and a wake_at request is rebuilt from actor data, so the recovered actor asks for the same wake-up (same id, same at) it was waiting on: a deadline is neither lost nor moved by a crash. Governor.resume then sleeps on it or parks, and Governor.wake answers it once due.

Constants: JOURNAL_RECORD, SNAPSHOT.

UnknownRun

from gvn.runtime.recovery import UnknownRun

The journal holds no snapshot for that run, so there is nothing to recover from.

Recovery

from gvn.runtime.recovery import Recovery
Recovery(journal: Journal, forms: Forms | None = None) -> None

Recovery.recover

async def recover(run_id: str, actor_class: type[Actor]) -> Actor

The actor of run_id, rebuilt.

actor_class is the Actor subclass the run was started with; it is rehydrated with actor_class.from_dto(actor_class.Dto.from_plain(state)) from the latest snapshot, then every journal record from the snapshot's sequence onwards is replayed through handle. The snapshot and every record are read in the current form first (Forms.read), and every record is turned into its Event before any is handled.

Raises UnknownRun if there is no snapshot, TypeError if actor_class is not an Actor subclass, NewerForm or NoUpgrade (both ValueError) if a stored form cannot be read, and ValueError if the rebuilt actor's name() is not run_id or a journal record is malformed.

gvn.runtime.replay

Replay: reading a recorded run back as a trace, and trying its events on a changed actor.

A journal holds everything that happened to an actor: its first snapshot (the actor at its birth, written together with the run's first record) and every event delivered afterwards. Actors are deterministic, so feeding those events to the actor again reproduces the run exactly, step by step, without fulfilling any work. That gives two things:

  • recorded: the history of a run as a Trace, to inspect or evaluate (including what its model calls cost: Trace.usage()).
  • against: what a different actor (a changed machine, a new plan, other instructions) would have done with the same events. This is how a proposed change is tried on real history before it is adopted: a change that makes recorded events rejected, or ends runs elsewhere, shows up as a divergence.

Replaying only calls actor.handle. It fulfils nothing, journals nothing and emits nothing. Stored forms are read through gvn.runtime.forms.Forms, as Recovery reads them: every record (and the snapshot) is brought to the current form, or refused with NewerForm or NoUpgrade, before any is replayed.

Constants: JOURNAL_RECORD, SNAPSHOT.

error_text

from gvn.runtime.replay import error_text
error_text(error: Exception) -> str

What a replay records when handle raised error: its class name, a colon and its message, trimmed to 200 characters (ending in ... when trimmed). The text of Frame.error(), and of gvn.runtime.inspection.Moment.error(). TypeError unless error is an Exception.

Frame

from gvn.runtime.replay import Frame
Frame(
    sequence: int,
    at: float,
    event: Event,
    steps: tuple[Step, ...],
    state: str,
    requests: tuple[Request, ...],
    error: str | None = None,
) -> None

One recorded event and what the actor did with it. Immutable; equal by content.

Equality covers every part, the requests included (two frames are equal only if the actor wanted exactly the same work, ids and payloads alike); the hash leaves the requests out, which keeps it cheap for wide runs. Trace.divergence compares behaviour instead: states, rejected flags and the kinds in wanted(), so an actor under another name, whose request ids differ, can agree with the recorded run.

Frame.sequence

sequence() -> int

Frame.at

at() -> float

Frame.event

event() -> Event

Frame.steps

steps() -> tuple[Step, ...]

Frame.state

state() -> str

Frame.requests

requests() -> tuple[Request, ...]

Tuple of the Requests the actor wanted after the event (shared, not copied).

Frame.wanted

wanted() -> tuple[str, ...]

Tuple of the kind names (str) of requests(), in order.

Frame.error

error() -> str | None

Frame.rejected

rejected() -> bool

True when the event changed nothing: no declared step was taken, or it raised.

Trace

from gvn.runtime.replay import Trace
Trace(
    run_id: str,
    start: str,
    frames: tuple[Frame, ...],
    finished: bool,
    outcome: Outcome | None = None,
) -> None

A run as a sequence of Frames. Immutable; equal by content.

Trace.run_id

run_id() -> str

Trace.start

start() -> str

Trace.frames

frames() -> tuple[Frame, ...]

Trace.finished

finished() -> bool

Trace.outcome

outcome() -> Outcome | None

Trace.state

state() -> str

The state at the end: the last frame's, or start when there are no frames.

Trace.states

states() -> tuple[str, ...]

Tuple of state names in order: start, then each frame's state.

Trace.visited

visited(state: str) -> bool

Whether state (a str) is among states().

Trace.rejections

rejections() -> tuple[Frame, ...]

Tuple of the frames that were rejected.

Trace.divergence

divergence(other: Trace) -> int | None

Where this trace and other first differ, or None when they agree throughout.

Compares frame by frame, by position: the first index (an int, counted from 0) at which the states, the rejected flags or the wanted kinds differ (request ids and payloads are not compared: an actor under another name agrees with the run it replays). If one trace is a prefix of the other, the length of the shorter. Differing start states diverge at 0. TypeError unless a Trace.

Trace.usage

usage() -> dict[str, int]

What the run's model calls cost: {"input_tokens": int, "output_tokens": int, "cache_read_tokens": int, "cache_write_tokens": int, "calls": int}.

Counts every model call the journal records: each model_replied and each model_failed frame (rejected ones too: the call was made), and each attempt listed in their "retries" (attempts a ModelFulfiller gave up on before that answer). calls is the number of those calls, so a reply that came after two retried attempts counts 3. The tokens are the sum of their "usage". The token figures mean what they mean in gvn.harness.ports.Reply: input_tokens is every input token, and cache_read_tokens/cache_write_tokens are the parts of it read from and written to the prompt cache. A call without usage (a journal written before usage was recorded, or a failure the vendor reported no usage for) counts as a call of 0 tokens, and usage that lacks the cache figures (written before they were recorded) counts them as 0. Model calls whose answer never reached the journal (cancelled, no longer wanted, or lost to a crash during retries) are not counted. A call an actor makes to summarise its own conversation (gvn.harness.context_window) is a model call like any other, counted the same way.

Trace.usage_by_origin

usage_by_origin() -> dict[str, dict[str, int]]

usage() split by the actor each model answer was addressed to: a dict mapping the address (an unaddressed event counts under run_id()) to its totals, for the addresses that had at least one model_replied or model_failed.

Trace.usage_by_model

usage_by_model() -> dict[str | None, dict[str, int]]

usage() split by the model that made each call: a dict mapping the model's name, as journaled with the call ("model"; gvn.harness.replies), to its totals, in the shape usage() gives, for the names that made at least one call. Calls that recorded no name (a model without one, or a journal written before names were recorded) count under None. The same calls are counted as in usage(), each retried attempt under its own entry's name, so the totals over every name add up to usage().

Entry

from gvn.runtime.replay import Entry
Entry(sequence: int, at: float, event: Event) -> None

One journal record read and checked: its position, its time and its Event. Immutable value.

Entry.sequence

sequence() -> int

Entry.at

at() -> float

Entry.event

event() -> Event

Replay

from gvn.runtime.replay import Replay
Replay(journal: Journal, forms: Forms | None = None) -> None

Replay.opening

async def opening(
    run_id: str,
    actor_class: type[Actor],
) -> tuple[Actor, tuple[Entry, ...]]

What recorded replays: the actor of run_id rebuilt from its first snapshot with actor_class, not yet fed anything, and the Entries from that snapshot's sequence onwards, every one read and checked. Feeding them to the actor in order reproduces the run. Raises what recorded raises.

Replay.entries

async def entries(run_id: str, name: str | None = None) -> tuple[Entry, ...]

What against replays: every Entry of run_id from position 0, read and checked. With name (a non-empty str), each event addressed to the recorded run or beneath it is addressed to the same place beneath name, as against documents. Raises UnknownRun when the run has no records and no snapshot; TypeError / ValueError for a bad run_id or name and for a record that does not hold together.

Replay.recorded

async def recorded(run_id: str, actor_class: type[Actor]) -> Trace

The Trace of run_id as it happened.

Rebuilds the actor from the run's FIRST snapshot (Journal.first_snapshot) with actor_class and feeds it every record from that snapshot's sequence onwards. Raises gvn.runtime.recovery.UnknownRun when there is no snapshot, TypeError for a non-Actor class, ValueError when the snapshot rebuilds an actor with another name or a record does not hold an event; NewerForm or NoUpgrade (both ValueError) when a stored form cannot be read. An event that makes handle raise does not stop the replay: it becomes a frame with an error (a recorded run never has one unless the actor's code has changed since).

Replay.against

async def against(run_id: str, actor: Actor) -> Trace

The Trace of feeding the recorded events of run_id to actor instead.

actor is a fresh Actor built by the caller (typically a changed version of the one that ran); it is mutated by the replay. All records of the run are used, from position 0. Events are re-addressed: an event addressed to the recorded run's name or beneath it is addressed to the same place beneath actor.name(); unaddressed events stay unaddressed. Events that raise become frames with an error; replay continues, so the trace shows everything that no longer fits. Raises UnknownRun when the run has no records and no snapshot, TypeError unless an Actor.

gvn.runtime.spending

Spending: what a run has spent on model calls, and the allowance it may not exceed.

Every model call a run makes is journaled with what it cost: model_replied and model_failed carry "usage" and "model" (gvn.harness.replies), and each attempt a fulfiller gave up on is listed in "retries". So what a run has spent is a function of its journal, and it survives whatever the journal survives: a crash, a move to another process, a fork.

Three classes, each owning one thing:

  • Rates: what tokens cost, per model. Prices are the deployer's to supply: gvn ships none.
  • Spend: the tally of one run. It counts journaled events; it is the only thing that knows how.
  • Allowance: the limits of one run, and the judgement of a Spend against them.

The Governor applies an Allowance (Governor(allowance=...)). A run that has reached its allowance is not killed and raises nothing: the Governor hands its actor the interrupted input, the one input every state of every actor already routes, instead of starting more work. What that means is the actor's own declared behaviour: the reference agent suspends, keeps everything it has, and resumes on resumed under a Governor with a larger allowance, in any process.

A reply is counted when it arrives, so an allowance is exceeded by at most the calls that were in flight when it was reached. Calls whose answer never reached the journal (cancelled, or lost to a crash) are not counted, as in Trace.usage().

This module does no I/O and reads no clock.

Unpriced

from gvn.runtime.spending import Unpriced

A model call was made by a model that Rates holds no price for, so what it cost is unknown. The message names the model (None for a call that recorded no name) and the names priced.

Rates

from gvn.runtime.spending import Rates
Rates(prices: Mapping[str | None, Mapping[str, float]], per: int = 1000000) -> None

What model calls cost: the price of tokens, per model. Immutable value.

prices: a non-empty mapping. Each key is a model's name (a non-empty str, as journaled with a call: Model.name() or what the vendor reported) or None (the price of any call no other key matches, a call that recorded no name included). Each value is a mapping with exactly the keys "input" and "output" and optionally "cache_read" and "cache_write": the price of per tokens of that kind, a finite number >= 0 (not a bool). "cache_read" and "cache_write" default to the "input" price. Copied.

per: how many tokens each price is quoted for, an int >= 1 (default 1,000,000: prices per million tokens, as vendors publish them).

The currency is whatever the prices are in; gvn only multiplies.

Which price applies to a call made by the model named name: the key equal to name; else the longest key that name starts with (a vendor may report a dated id, "model-2026-10-01", for a model asked for as "model"); else the None key; else Unpriced. A call that recorded no name is priced by the None key only.

TypeError/ValueError for anything malformed.

Rates.cost

cost(usage: Mapping[str, int], model: str | None) -> float

What one call cost. usage: a mapping with the int counts "input_tokens", "output_tokens", "cache_read_tokens" and "cache_write_tokens" as gvn.harness.ports.Reply defines them (the cache figures are parts of input_tokens); a missing or malformed figure counts as 0. model: the model's name (a str) or None. Returns a float:

((input - cache_read - cache_write) * price["input"]
 + cache_read * price["cache_read"] + cache_write * price["cache_write"]
 + output * price["output"]) / per

(the uncached part is never taken below 0). Raises Unpriced when no price applies; TypeError if usage is not a mapping or model neither a str nor None.

Rates.priced

priced() -> tuple[str | None, ...]

Tuple of the keys of prices: the names sorted, then None if it is one.

Spend

from gvn.runtime.spending import Spend
Spend(rates: Rates | None = None) -> None

What one run has spent on model calls so far. A tally: it starts at nothing and grows as it is shown the run's events.

rates: None (tokens and calls are counted; cost() is None) or a Rates (every call is also priced). TypeError otherwise.

What is counted is exactly what gvn.runtime.replay.Trace.usage() counts: for each model_replied and model_failed event, the call it answers and each attempt listed in its "retries", each one call with its own "usage" (a call without usage is a call of 0 tokens; a figure that is missing or malformed is 0) and its own "model". Law, tested as a property: after count was called with every event of a run in order, usage() equals that run's Trace.usage() and by_model() its Trace.usage_by_model().

Spend.count

count(event: Event) -> None

Add what event records. An Event that is neither model_replied nor model_failed adds nothing; so does one whose payload is not shaped as expected, beyond the call itself. TypeError unless event is an Event. With rates, raises Unpriced for a call no price applies to, and then nothing of the event was counted (errors change nothing).

Spend.calls

calls() -> int

How many model calls were counted (retried attempts included).

Spend.tokens

tokens() -> int

input_tokens + output_tokens over every call counted: every token the models processed or generated, cached or not.

Spend.cost

cost() -> float | None

What the calls counted cost, a float in the currency of the rates; None for a Spend built without rates.

Spend.usage

usage() -> dict[str, int]

{"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "calls"}: a fresh dict of the totals, in the shape of Trace.usage().

Spend.by_model

by_model() -> dict[str | None, dict[str, int]]

The totals split by the model that made each call: a fresh dict mapping the model's name (None for calls that recorded none) to a dict shaped as usage(), in the shape of Trace.usage_by_model().

Allowance

from gvn.runtime.spending import Allowance
Allowance(
    tokens: int | None = None,
    calls: int | None = None,
    cost: float | None = None,
    rates: Rates | None = None,
) -> None

What one run may spend on model calls. Immutable value.

tokens: None, or an int >= 1: the most tokens (Spend.tokens()). calls: None, or an int >= 1: the most model calls (Spend.calls()). cost: None, or a finite number > 0: the most money (Spend.cost()), in the currency of rates. rates: None or a Rates; required with cost (ValueError without), and allowed without it (the run is then priced, not limited by price). At least one of tokens, calls and cost must be given (ValueError otherwise). TypeError/ValueError for anything malformed (a bool is never a number here).

A limit is REACHED once what was spent is equal to or above it: a run allowed 3 calls makes 3.

Allowance.tokens

tokens() -> int | None

Allowance.calls

calls() -> int | None

Allowance.cost

cost() -> float | None

Allowance.rates

rates() -> Rates | None

The Rates, or None.

Allowance.tally

tally() -> Spend

A new, empty Spend that counts what this allowance limits: built with this allowance's rates.

Allowance.reached

reached(spend: Spend) -> str | None

None while spend (a Spend: TypeError otherwise) is below every limit; else a str for people naming the first limit reached, in the order tokens, calls, cost, with both figures:

"tokens: 120431 spent of 100000 allowed"
"calls: 3 made of 3 allowed"
"cost: 5.0312 spent of 5.0 allowed"

A cost limit judged against a Spend built without rates is a ValueError.

gvn.runtime.throttles

Throttles: shared limits on how fast and how many calls are made at once.

A Throttle (gvn.harness.ports.Throttle) decides when a call may start. This module holds the in-process ones and the one way they are applied:

  • ConcurrencyThrottle(limit): at most limit calls at once.
  • RateThrottle(calls, per, clock): at most calls calls started in any per seconds.
  • Throttles([...]): several limits as one.
  • ThrottledModel(model, throttle): a Model whose every call goes through a throttle.

A limit holds across whatever shares the object. A deployment with ten thousand agents gives every model object of one vendor account the SAME throttle, and no more calls are ever in flight, or started per minute, than the account allows, however many actors and runs ask at once:

account = Throttles([ConcurrencyThrottle(50), RateThrottle(2000, 60.0, clock)])
main = ThrottledModel(AnthropicModel(client, "..."), account)
small = ThrottledModel(AnthropicModel(client, "..."), account)
ModelFulfiller(main, toolbox, roles={"summariser": small})

Composition, not configuration: a throttled model is a Model, so it goes wherever a Model goes (a role, a member of a FallbackModel, the model of a domain harness), and no fulfiller or actor knows it is there.

When a vendor answers "wait" (a ModelFailure with retry_after), ThrottledModel tells the throttle (hold_off) before it passes the failure on, so every caller that shares the throttle waits, not only the one that was told: ten thousand agents back off together instead of each finding the limit for itself.

Everything here waits on the Clock it is given and on asyncio; nothing reads the system clock, so a test with a manual clock is instant.

ConcurrencyThrottle

from gvn.runtime.throttles import ConcurrencyThrottle
ConcurrencyThrottle(limit: int) -> None

At most limit calls at once: acquire returns while fewer than limit acquired calls are unreleased, and otherwise waits for a release.

limit: an int >= 1 (not a bool); TypeError/ValueError otherwise. Waiters are admitted in the order they asked. A wait that is cancelled holds nothing and does not lose anyone else's turn. release without a matching acquire is a RuntimeError and changes nothing. hold_off is the port's default.

ConcurrencyThrottle.acquire

async def acquire() -> None

Return once one more call may start under the limit. A caller that returns from here must call release exactly once when its call has ended, however it ended. Must honour cancellation promptly, and a wait that is cancelled holds nothing: no release is owed for it.

ConcurrencyThrottle.release

release() -> None

The call admitted by one earlier acquire has ended. Synchronous, no I/O, never blocks.

ConcurrencyThrottle.limit

limit() -> int

ConcurrencyThrottle.in_flight

in_flight() -> int

How many acquired calls are unreleased now.

RateThrottle

from gvn.runtime.throttles import RateThrottle
RateThrottle(calls: int, per: float, clock: Clock) -> None

At most calls calls started in any window of per seconds.

calls: an int >= 1. per: a finite number of seconds > 0. clock: the Clock that tells the time and is slept on. TypeError/ValueError otherwise (a bool is never a number here).

acquire returns at once while fewer than calls calls were admitted in the last per seconds (the window (now - per, now]); otherwise it sleeps on the clock until the oldest of them leaves the window, and tries again. The limit is exact over every window, not an average. Waiters are admitted in the order they asked. A wait that is cancelled admits nothing and does not lose anyone else's turn. release does nothing: a rate limits starts, not calls in flight.

hold_off(seconds): nothing is admitted before clock.now() + seconds; a later call never brings that time forward. Waiters already sleeping stay asleep at least until then.

RateThrottle.acquire

async def acquire() -> None

Return once one more call may start under the limit. A caller that returns from here must call release exactly once when its call has ended, however it ended. Must honour cancellation promptly, and a wait that is cancelled holds nothing: no release is owed for it.

RateThrottle.release

release() -> None

The call admitted by one earlier acquire has ended. Synchronous, no I/O, never blocks.

RateThrottle.hold_off

hold_off(seconds: float) -> None

The service asked its callers to wait seconds (a finite number >= 0, not a bool: TypeError/ValueError otherwise; a retry-after): admit nothing new before that much time has passed. Calls already admitted are not affected, and a later, shorter request never shortens a longer one in force. The default checks seconds and does nothing more: a limit on how many calls run at once has no notion of time.

RateThrottle.calls

calls() -> int

RateThrottle.per

per() -> float

The window in seconds, a float.

Throttles

from gvn.runtime.throttles import Throttles
Throttles(throttles: Iterable[Throttle]) -> None

Several throttles as one: a call starts only when every one of them admits it.

throttles: a non-empty sequence of Throttle (a str or a single Throttle is a TypeError; an empty one a ValueError). acquire acquires each in the order given; if it is cancelled, or one of them raises, part-way, those already acquired are released (in reverse order) before the error propagates, so nothing is held. release releases each in reverse order. hold_off is passed to each. Put the concurrency limit first: a call then waits for its slot before it takes a place in the rate window.

Throttles.acquire

async def acquire() -> None

Return once one more call may start under the limit. A caller that returns from here must call release exactly once when its call has ended, however it ended. Must honour cancellation promptly, and a wait that is cancelled holds nothing: no release is owed for it.

Throttles.release

release() -> None

The call admitted by one earlier acquire has ended. Synchronous, no I/O, never blocks.

Throttles.hold_off

hold_off(seconds: float) -> None

The service asked its callers to wait seconds (a finite number >= 0, not a bool: TypeError/ValueError otherwise; a retry-after): admit nothing new before that much time has passed. Calls already admitted are not affected, and a later, shorter request never shortens a longer one in force. The default checks seconds and does nothing more: a limit on how many calls run at once has no notion of time.

Throttles.throttles

throttles() -> tuple[Throttle, ...]

The tuple of throttles, in order.

ThrottledModel

from gvn.runtime.throttles import ThrottledModel
ThrottledModel(model: Model, throttle: Throttle) -> None

A Model whose every call waits for a Throttle first.

model: the Model served. throttle: the Throttle. TypeError otherwise.

generate acquires the throttle, calls model.generate(exchange, progress) and releases the throttle when that call has ended: with a Reply, a ModelFailure, any other exception, or cancellation. Cancelled while still waiting for the throttle, it made no call and holds nothing. A ModelFailure whose retry_after() is not None is first reported to the throttle (throttle.hold_off(retry_after)) and then raised unchanged. Whatever the model returns or raises passes through unchanged.

Each attempt is throttled by itself: a Retry on the ModelFulfiller calls generate again for each attempt, and a FallbackModel over throttled models throttles each member under its own limit.

name(), provider() and context_window() are the model's.

ThrottledModel.generate

async def generate(exchange: Exchange, progress: Progress) -> Reply

Run one model call and return the complete Reply.

Text fragments are reported to progress as they arrive; their concatenation equals the reply message's text. Raises ModelFailure for any failure. Must honour cancellation (asyncio.CancelledError) promptly.

ThrottledModel.name

name() -> str | None

What to call this model in the record of what it cost: a non-empty str (an adapter gives the vendor's model id), or None when it has none (the default). Constant for the object's life. The ModelFulfiller journals it with every answer whose Reply does not name its own model (Reply.model()).

ThrottledModel.provider

provider() -> str | None

Which service serves this model: a non-empty lower-case str naming the provider as OpenTelemetry's GenAI conventions name it where they do ("anthropic", "openai", "deepseek", ...), or None when it has none to give (the default). Constant for the object's life. The ModelFulfiller journals it with every answer whose Reply does not name its own provider (Reply.provider()), so a run's record says which service each call went to.

ThrottledModel.context_window

context_window() -> int | None

How many tokens one call to this model can hold (its context window): an int >= 1, or None when unknown (the default). A fact about the model, constant for the object's life. The ModelFulfiller journals it with every reply, which is how an actor's ContextBudget learns it (gvn.harness.context_window).

ThrottledModel.model

model() -> Model

The Model served.

ThrottledModel.throttle

throttle() -> Throttle

The Throttle.