# gvn.adapters

Implementations of the ports for real vendors and backends: model clients, SQLite and PostgreSQL journals, logs, traces and eval files. One module per vendor or backend.

The ideas behind it are explained in [Using a vendor model](../../guides/vendors.md), [Running as a service](../../guides/running-as-a-service.md). This page is generated from the source, so it lists every public name with its signature and docstring. [Python API](../python.md) has the other packages and an index of every name.

## Modules

| Module | What it holds | Names |
|---|---|---|
| [`gvn.adapters.anthropic`](#gvn.adapters.anthropic) | The Model port over Anthropic's Messages API | [`AnthropicModel`](#AnthropicModel), [`answer_format`](#anthropic.answer_format), [`retry_after`](#anthropic.retry_after) |
| [`gvn.adapters.chat_completions`](#gvn.adapters.chat_completions) | The Model port over the Chat Completions API (``POST <base URL>/chat/completions``) | [`answer_format`](#chat_completions.answer_format), [`ChatCompletionsModel`](#ChatCompletionsModel) |
| [`gvn.adapters.clock`](#gvn.adapters.clock) | A Clock that reads the system's wall clock | [`SystemClock`](#SystemClock) |
| [`gvn.adapters.eval_files`](#gvn.adapters.eval_files) | Eval files: cases as CSV or JSONL, and an eval described in TOML | [`FileProblem`](#FileProblem), [`case_fields`](#case_fields), [`read_cases`](#read_cases), [`write_cases`](#write_cases), [`add_case`](#add_case), [`replace_case`](#replace_case), [`remove_case`](#remove_case), [`CriterionEntry`](#CriterionEntry), [`EvalFile`](#EvalFile), [`read_eval`](#read_eval) |
| [`gvn.adapters.eval_store`](#gvn.adapters.eval_store) | Eval results kept in a SQLite database file | [`SqliteResults`](#SqliteResults) |
| [`gvn.adapters.logs`](#gvn.adapters.logs) | An Output that writes structured log records through the standard ``logging`` module | [`LoggingOutput`](#LoggingOutput), [`JsonFormatter`](#JsonFormatter) |
| [`gvn.adapters.openai`](#gvn.adapters.openai) | The Model port over OpenAI's Responses API (``POST /v1/responses``) | [`OpenAIModel`](#OpenAIModel), [`answer_format`](#openai.answer_format), [`retry_after`](#openai.retry_after), [`OpenAIEmbedder`](#OpenAIEmbedder) |
| [`gvn.adapters.otel`](#gvn.adapters.otel) | An Output that turns Signals into OpenTelemetry spans that LLM-trace viewers understand | [`TracingOutput`](#TracingOutput) |
| [`gvn.adapters.postgres`](#gvn.adapters.postgres) | A Journal, Leases and a Memory kept in PostgreSQL, over psycopg 3 (the ``postgres`` extra) | [`SchemaNotPrepared`](#SchemaNotPrepared), [`NewerSchema`](#NewerSchema), [`PostgresJournal`](#PostgresJournal), [`PostgresLeases`](#PostgresLeases), [`PostgresMemory`](#PostgresMemory) |
| [`gvn.adapters.sqlite`](#gvn.adapters.sqlite) | A Journal, Leases and a Memory kept in SQLite database files | [`SqliteJournal`](#SqliteJournal), [`SqliteLeases`](#SqliteLeases), [`SqliteMemory`](#SqliteMemory) |

## gvn.adapters.anthropic

The Model port over Anthropic's Messages API.

The client is injected, so configuration (keys, base URL, retries, timeouts,
transport) stays with the caller and tests can supply a client that never
touches the network. Requires the ``anthropic`` extra.

Translation:

* Exchange.instructions -> the system prompt (omitted when empty).
* A user Message -> a user turn with its text. An assistant Message -> an
  assistant turn: first its sealed blocks (see below), then a text block (when it
  has text), then one tool-use block per ToolCall. A tool Message -> a user turn
  with one tool-result block per ToolResult (the content as JSON text with sorted
  keys, flagged as an error when it failed; its attachments after it, see below).
  An instruction Message -> a ``system`` message inside ``messages`` (``{"role":
  "system", "content": &lt;its text>}``), in its place in the conversation: Anthropic's
  operator-level channel, never a user turn. gvn places an instruction directly after a
  user message (a tool Message is one, being a user turn of tool results), which is
  where the API accepts one. It is not emulated: a model without such messages answers
  400, which fails as a bad request below. It carries no ``cache_control`` and is
  rendered the same on every call, so the prefix it ends stays byte-identical and the
  top-level breakpoint moves past it on the next call like any turn.
* Each ToolSpec -> a tool with its name, description and JSON Schema; tools in name
  order, every object's keys sorted, so the same tools are the same bytes on every
  call and after a journal round trip (prompt caching is a byte-prefix match).
  Tool-call arguments are sent with sorted keys for the same reason.
* The streamed reply -> text fragments to ``progress`` as they arrive, and a
  Reply whose Message carries the full text, the tool calls (ids and names as
  the API gave them, arguments parsed from JSON) and the sealed blocks, with
  token usage.

Thinking (sealed content). Every ``thinking`` and ``redacted_thinking`` block of a
reply is kept, exactly as the API sent it, as a sealed record
``{"vendor": "anthropic", "model": <this adapter's model id>, "block": {...}}`` in
the order received. Every sealed record of an assistant Message whose vendor is
``"anthropic"``, whatever its model, is sent back unmodified (every field and value
as received; keys in sorted order, like every object this adapter sends, so a
journal that reorders keys changes no byte), as Anthropic advises: the API drops,
unbilled, the blocks the current model cannot read, and keeps those it can (Claude
Opus 5.5 reads Claude Haiku 5.5's). Another vendor's records are never sent.

Order. The API requires a turn's thinking blocks back in the order the model wrote
them, among its other blocks. A reply whose blocks are, in order, its thinking, at
most one text block and then its tool calls (what Claude Haiku 5.5 sends) needs
nothing more: the turn is sent back in that order. Any other order (thinking between
tool calls, several text blocks) is recorded on the reply's first sealed record as
``"layout"``: one entry per original block, ``"sealed"`` (the next sealed record),
``["text", n]`` (the next ``n`` characters of the message's text) or ``"tool_use"``
(the next call). Empty text blocks are left out, as the text has none of them. The
turn is then sent back block for block in that order. A layout that does not fit the
message (another number of records, calls or characters) is ignored, and so is a
record without one: the turn is sent in the default order.

The API also checks that nothing before a thinking block changed since it was
produced (preserved thinking); gvn's transcripts are append-only, and every reduction
step of gvn.harness.context_window (ClearToolResults, KeepRecent, Summarise) removes
sealed content from the messages it returns.

Caching (``cache=True``, the default). Three of the four breakpoints the API
allows: one on the last tool (the tools are the most stable part of the prompt and
render first), one on the system prompt (tools and instructions together), and
top-level automatic caching, which places one on the last block of the
conversation and moves it forward as the conversation grows, so each call reads
the previous call's prefix. A prefix shorter than the model's minimum cacheable
length (512 tokens on Claude Haiku 5.5) is silently not cached. With
``cache=False`` no ``cache_control`` is sent and the system prompt is a plain
string.

Effort. ``effort`` None sends nothing (the model's default); otherwise one of
EFFORTS, sent as ``output_config: {"effort": ...}``. Thinking is not configured:
models that think by default (adaptive thinking) do so.

Usage. ``Reply.input_tokens`` is every input token: the API's ``input_tokens``
(uncached) plus ``cache_creation_input_tokens`` (written to the cache, also
``cache_write_tokens``) plus ``cache_read_input_tokens`` (read from it, also
``cache_read_tokens``). These are the response's top-level figures, which leave out
the ``compaction`` entries of ``usage.iterations``: a call that compacted reports the
conversation as the model then saw it (the summary and what follows), not the longer
conversation that was summarised. The summarising pass is billed but not counted in
the Reply.

Context window. ``context_window`` (constructor) is what ``context_window()`` returns:
None (unknown, the default) or the caller's figure in tokens. gvn keeps no table of
model sizes and does not ask the Models API.

Context overflow. A conversation that does not fit fails with
``ModelFailure(exceeded_context=True)``, never retryable: a reply that stops with
``model_context_window_exceeded`` (carrying the tokens it spent), and the 400
``invalid_request_error`` whose message says the prompt is too long. Every other 400 is
a plain bad request.

Vendor-side reduction (``context_edits=``, default none). Anthropic's own context
edits (clearing old tool results or thinking, compacting older turns into a summary)
are enabled only by passing their definitions, plain dicts sent as given, in the order
given, as ``context_management.edits`` (for example ``{"type": "compact_20260112"}``);
their ``type`` must be one of CONTEXT_EDITS. gvn does not interpret them. A request
with edits goes to the beta Messages endpoint with the beta flag each edit type needs;
so does a request whose history holds a compaction block, whatever this adapter's
edits. Anthropic applies the edits on its side: gvn's transcript keeps every message,
and only the usage shows a smaller conversation. A ``compaction`` block in a reply is
kept as a sealed record, in order (with a layout, as thinking), and sent back
unmodified, so later calls continue from the summary. A turn paused after compacting
(stop reason ``compaction``) fails as below.

Structured answers. An Exchange with an ``answer`` (a kernel Record) is sent with
``output_config: {"format": {"type": "json_schema", "schema": ...}}`` (beside
``effort`` when set): Anthropic constrains the reply's text to that JSON Schema
(structured outputs, on every current model). The Record's JSON Schema is sent as gvn
renders it when Anthropic can express it exactly, and refused otherwise, before any
call, with a non-retryable ModelFailure naming what cannot be expressed
(``answer_format`` raises the same ValueError, for checking a schema up front):
``Integer`` bounds (no ``minimum``/``maximum``), ``MapOf`` (every object must set
``additionalProperties: false``), ``Json()`` (any value), a ``Text`` pattern with
backreferences, lookaround or word boundaries, more than 24 optional fields or more
than 16 ``Nullable`` fields in one schema (Anthropic's documented limits; a schema
within them may still be "too complex", which the service reports as a 400). A
schema is never loosened. Anthropic does not guarantee the letter case of an enum
value; gvn's own check is exact. Citations cannot be combined with a structured answer
(the API answers 400): an Exchange with both fails before the call. A reply refused or
cut off at ``max_tokens`` fails as below, so a truncated answer is never parsed.

Attachments. A user Message with attachments is sent as content blocks: its text (when
not empty), then one ``image`` or ``document`` block per Attachment, with a ``base64``
source (``media_type``, ``data``) or a ``url`` source; a document's ``title`` is sent,
and ``citations: {"enabled": true}`` when it is ``cited``. A user Message without
attachments is sent as before (its text as the content string).

Tool results with attachments (``ToolResult.attachments``, from a tool that returned a
``ToolOutput``). The ``tool_result`` block's ``content`` becomes a list: a ``text`` block
with the JSON content, then one ``image`` or ``document`` block per Attachment, built as
for a user message (a tool result's document is never ``cited``). The Messages API accepts
``text``, ``image``, ``document`` and ``search_result`` blocks inside a ``tool_result``
(the "Handle tool calls" guide, checked 2026-11-17; the SDK's ``ToolResultBlockParam``), so
every media type an Attachment accepts is sent as it is, with no fallback. A result
without attachments is sent as before (its content as a JSON string).

Citations. Each text block of a reply may carry citations (``char_location``,
``page_location``, ``content_block_location``, ``web_search_result_location``,
``search_result_location``). Each becomes a citation record on the Message
``{"vendor": "anthropic", "start", "end", "source": <the citation as the API sent it>}``,
``start``/``end`` the span of its text block in the message text. They are not sent
back: the assistant turn's text goes back as plain text.

Server tools (``server_tools=``, default none). Tools Anthropic runs itself (web search,
web fetch, code execution) are enabled only by passing their definitions, plain dicts
sent as given after the Exchange's tools (for example ``{"type":
"web_search_20260209", "name": "web_search", "max_uses": 3}``). gvn does not govern
them: the policy, approvals and the budget never see their calls, which run inside the
model call. Their blocks in a reply (``server_tool_use`` and every ``*_tool_result``)
are kept as sealed records, in order (with a layout, as thinking), and sent back
unmodified, so a conversation that used them continues. A turn the API pauses
(``pause_turn``, a long server-tool turn) fails as below.

Failures become ModelFailure, never a vendor exception: rate limiting,
overload, server errors, timeouts and connection errors are retryable; bad
requests, authentication and permission errors are not. A reply cut off by the
token limit, a refusal, or tool arguments that are not a JSON object are
failures too (not retryable), because a truncated reply must not be acted on.
Not fitting the context window fails as above. A status failure carries the
``retry-after`` the API sent (``retry-after-ms`` first, then ``retry-after`` in
seconds; an HTTP date is not read); a refused or cut-off reply carries the tokens it
spent. Cancellation propagates as asyncio.CancelledError and
closes the stream.

Constants: `ASSISTANT`, `IMAGE`, `INSTRUCTION`, `TOOL`, `USER`, `VENDOR`, `EFFORTS`, `CONTEXT_EDITS`.

### AnthropicModel

```python
from gvn.adapters.anthropic import AnthropicModel
```

```text
AnthropicModel(
    client: object,
    model: str,
    max_tokens: int = 4096,
    effort: str | None = None,
    cache: bool = True,
    server_tools: Iterable[Mapping[str, typing.Any]] = (),
    context_window: int | None = None,
    context_edits: Iterable[Mapping[str, typing.Any]] = (),
) -> None
```

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

#### AnthropicModel.name

```text
name() -> str
```

The model id this adapter asks for (the constructor's ``model``).

#### AnthropicModel.provider

```text
provider() -> str
```

``"anthropic"``: this adapter calls Anthropic's Messages API.

#### AnthropicModel.context_window

```text
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).

#### AnthropicModel.generate

```text
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.

### anthropic.answer_format

```python
from gvn.adapters.anthropic import answer_format
```

```text
answer_format(answer: Record) -> dict[str, typing.Any]
```

The ``output_config.format`` that asks Anthropic for an answer matching ``answer``
(a kernel Record): ``{"type": "json_schema", "schema": <its JSON Schema>}``.

ValueError naming what Anthropic's structured outputs cannot express (see the module
docstring); the schema is never loosened.

### anthropic.retry_after

```python
from gvn.adapters.anthropic import retry_after
```

```text
retry_after(response: object) -> float | None
```

The seconds a response asks to wait (``retry-after-ms``, else ``retry-after`` as a
number of seconds), or None when it asks nothing usable. An HTTP-date value is not
read (it would need the clock).

## gvn.adapters.chat_completions

The Model port over the Chat Completions API (``POST <base URL>/chat/completions``).

Chat Completions is the request and reply format most model services accept, each
at its own base URL. One adapter covers them: the client is injected, so the key,
the base URL, retries, timeouts and transport stay with the caller, and tests can
supply a client that never touches the network. Requires the ``openai`` extra (its
SDK is the client).

    client = openai.AsyncOpenAI(api_key=key, base_url="https://api.deepseek.com")
    model = ChatCompletionsModel(client, "deepseek-flash", vendor="deepseek")

Stateless. Every request carries the whole conversation as ``messages``; nothing
refers to state kept by the service. gvn's journal is the only record of a run, so a
run replays from it and can change vendor.

``vendor`` names the service behind the client (``"deepseek"``, ``"mistral"``, ...).
The adapter cannot tell from a client whose service it reaches, and what one service
returns as its own (its reasoning) must never be sent to another, so the caller says
which it is. It is the ``vendor`` of the sealed records this adapter writes and reads
back, and nothing else: it is never sent.

Translation:

* Exchange.instructions -> a leading ``system`` message (omitted when empty).
* A user Message -> a ``user`` message with its text as ``content``. An instruction
  Message (``Message.instruction``) -> a ``system`` message with its text, in place.
* An assistant Message -> an ``assistant`` message: ``content`` its text (None when
  it has no text), ``tool_calls`` one ``{"id", "type": "function", "function":
  {"name", "arguments"}}`` per ToolCall (arguments as JSON text with sorted keys;
  the key is omitted when there are no calls), and its reasoning when it has some
  from this vendor (see below).
* A tool Message -> one ``tool`` message per ToolResult, in order, with its
  ``tool_call_id`` and ``content`` the result's content as JSON text with sorted keys
  (a failed result is ``{"content": ..., "error": true}``, since the format has no
  error flag).
* Each ToolSpec -> ``{"type": "function", "function": {"name", "description",
  "parameters": &lt;its JSON Schema>}}``, in name order with every object's keys sorted,
  so the same tools are the same bytes on every call and after a journal round trip.
  ``tools`` is omitted when there are none. ``tool_choice`` is never sent (the
  service's default: the model decides).
* The reply is always streamed (``stream: true`` with ``stream_options:
  {"include_usage": true}``): text fragments go to ``progress`` as they arrive, and
  the Reply's Message carries the full text, the tool calls (ids and names as the
  service gave them, arguments joined from their fragments and parsed from JSON;
  empty or whitespace-only arguments mean ``{}``), the reasoning and the token
  usage. Only the first choice is read (``n`` is never sent). Reasoning text is not
  reported to ``progress``.

Reasoning (sealed content). Services that show a model's reasoning send it beside
the text as ``reasoning_content`` (in ``delta`` while streaming). The adapter joins
the fragments and, when the result is not empty, keeps it as one sealed record
``{"vendor": &lt;vendor>, "model": &lt;this adapter's model id>, "block":
{"reasoning_content": &lt;the text>}}``. On the way back, an assistant Message that
holds a sealed record of this adapter's vendor (whatever its model) with a
``reasoning_content`` str is sent with ``reasoning_content`` set to it (the first
such record). Services that reason across tool rounds require this and refuse the
conversation without it; services that do not read it ignore it. Another vendor's
records are never sent, so a conversation begun on another vendor continues here
without its reasoning.

Effort. ``effort`` None sends nothing (the model's default); otherwise one of
EFFORTS, sent as ``reasoning_effort``. Which levels a model accepts is the
service's decision: one it does not support is rejected, and the failure's reason
quotes the service's message.

``max_tokens`` None sends nothing; an int is sent as ``max_tokens``.

``extra`` (default none): a mapping of further top-level request fields, plain JSON,
sent as given with every request, for what a service adds to the format (for
example ``{"thinking": {"type": "disabled"}}``). A key the adapter sets itself
(``model``, ``messages``, ``tools``, ``tool_choice``, ``stream``, ``stream_options``,
``response_format``, ``max_tokens``, ``reasoning_effort``, ``n``) is refused at
construction (ValueError naming it). gvn does not interpret them.

Usage: ``Reply.input_tokens`` is ``usage.prompt_tokens`` (every input token);
``cache_read_tokens`` is ``usage.prompt_tokens_details.cached_tokens`` or, when that
is absent, ``usage.prompt_cache_hit_tokens`` (0 when both are absent, and never more
than the input); ``cache_write_tokens`` is 0; ``output_tokens`` is
``usage.completion_tokens`` (reasoning tokens included). The usage is read from
whichever chunk carries one that is not null (the last such chunk wins); a stream
with none gives zeros.

Structured answers. An Exchange with an ``answer`` (a kernel Record) is sent with
``response_format: {"type": "json_schema", "json_schema": {"name": "answer",
"schema": ..., "strict": true}}``: the service constrains the reply's text to the
schema. The Record's JSON Schema is sent as gvn renders it when strict mode can
express it exactly, and refused otherwise, before any call, with a non-retryable
ModelFailure naming what cannot be expressed (``answer_format`` raises the same
ValueError), under the same rules as ``gvn.adapters.openai``: an optional field,
``MapOf``, ``Json()``, more than 10 levels of nested objects, more than 1,000 enum
values or more than 5,000 properties. A schema is never loosened, and no other way
of asking for JSON is used in its place: a service that does not take
``json_schema`` rejects the request, which is a failure that is not retryable.

Attachments. A user Message with attachments is sent with a content list: its text
as a ``text`` part (when not empty), then per Attachment an ``image_url`` part
(``image_url: {"url": ...}``: a ``data:`` URL of the base64 bytes, or the URL) or a
``file`` part (``file: {"file_data": &lt;a data: URL>, "filename": &lt;the title or
document.pdf>}``; an Attachment given by URL has no ``file`` form in this format and
is refused before any call with a non-retryable ModelFailure). ``cited`` has no
effect. A ToolResult with attachments is sent with ``content`` as a list: a ``text``
part with the JSON text, then the parts built the same way. A service that does not
take a part answers with an error, which is a failure that is not retryable. Messages
and results without attachments are sent as plain text, as above.

Context window. ``context_window=`` (None, the default, or an int >= 1) is what
``context_window()`` returns: given by the caller, never looked up. When the service
refuses a conversation with error code ``context_length_exceeded`` (as an HTTP error
or inside the stream), the failure has ``exceeded_context=True`` and is not
retryable. Nothing else sets it.

How a reply ends. ``finish_reason`` ``stop`` or ``tool_calls`` (or ``function_call``)
is a reply. ``length`` (cut off at the token limit; the failure carries the tokens
spent) and ``content_filter`` are failures that are not retryable, so a truncated
answer is never parsed; so is a reply carrying a ``refusal``, and one whose tool
arguments are not a JSON object. Any other ``finish_reason`` is a retryable failure
naming it, and so is a stream that ends without one.

Failures become ModelFailure, never a vendor exception: rate limiting (429), server
errors (5xx), timeouts and connection errors are retryable; other status errors
(bad request, authentication, permission, not found, unprocessable) are not. A
status failure carries the ``retry-after`` the service sent (``retry-after-ms``
first, then ``retry-after`` in seconds; an HTTP date is not read). An ``error``
object arriving inside the stream is a failure: retryable unless its ``code`` or
``type`` says the request was at fault. The reason of a status or stream error
includes the service's own message: one line, at most 160 characters, with the
client's key (and anything shaped like ``sk-...``) redacted. Cancellation propagates
as asyncio.CancelledError and closes the stream.

Constants: `EFFORTS`.

### chat_completions.answer_format

```python
from gvn.adapters.chat_completions import answer_format
```

```text
answer_format(answer: Record) -> dict[str, typing.Any]
```

The ``response_format`` value for ``answer`` (a kernel Record): ``{"type":
"json_schema", "json_schema": {"name": "answer", "schema": ..., "strict": True}}``.

TypeError unless a Record; ValueError naming what strict mode cannot express
(see the module docstring).

### ChatCompletionsModel

```python
from gvn.adapters.chat_completions import ChatCompletionsModel
```

```text
ChatCompletionsModel(
    client: object,
    model: str,
    vendor: str,
    max_tokens: int | None = None,
    effort: str | None = None,
    context_window: int | None = None,
    extra: Mapping[str, typing.Any] | None = None,
) -> None
```

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

#### ChatCompletionsModel.name

```text
name() -> str
```

The model id.

#### ChatCompletionsModel.vendor

```text
vendor() -> str
```

The vendor name this adapter was given.

#### ChatCompletionsModel.provider

```text
provider() -> str | None
```

The ``vendor`` this adapter was given, lower-cased (the service behind the
client), or None when it is not a non-empty str.

#### ChatCompletionsModel.context_window

```text
context_window() -> int | None
```

The ``context_window`` this adapter was given, or None.

#### ChatCompletionsModel.generate

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

One streamed Chat Completions call for ``exchange`` (see the module docstring).

Returns a Reply; raises ModelFailure. TypeError unless an Exchange and a
Progress.

## gvn.adapters.clock

A Clock that reads the system's wall clock. Standard library only.

This is the only place in gvn that reads the system clock for the Clock port.

### SystemClock

```python
from gvn.adapters.clock import SystemClock
```

```text
SystemClock() -> None
```

Real time: seconds since the epoch, from ``time.time()``.

``now()`` never goes backwards within one instance: if the system clock is
stepped back, it keeps returning the last value it returned until the system
clock catches up. ``sleep`` awaits ``asyncio.sleep`` and so honours
cancellation.

#### SystemClock.now

```text
now() -> float
```

Seconds since the epoch, as a float; never less than the previous reading.

#### SystemClock.sleep

```text
async def sleep(seconds: float) -> None
```

Return once ``seconds`` have passed. ``sleep(0)`` yields once and returns.

TypeError unless ``seconds`` is a number (bool is not), ValueError if it is
negative or NaN.

## gvn.adapters.eval_files

Eval files: cases as CSV or JSONL, and an eval described in TOML.

Standard library only (csv, json, tomllib). These are the files people who do not
write Python edit, so every refusal is a ``FileProblem`` whose message names the
file, the line or row, and what to change, in plain words.

A cases file is ``<name>.cases.csv`` or ``<name>.cases.jsonl`` (the dataset's name
is the file name without those endings).

CSV: a header row, then one case per row. Columns: ``case_id`` (required),
``tags`` (optional; tags separated by spaces), ``brief.<field>`` and
``expect.<field>`` (a dot inside ``<field>`` nests: ``brief.order.id``). A cell that
parses as JSON (``12``, ``true``, ``["a"]``, ``{"k": 1}``, ``"quoted"``) is that
value; any other cell is the text itself; an empty cell means the field is absent.
Any other column is a FileProblem naming it. Rows are counted from 1, the header
being row 1; a row whose cells are all empty is ignored; a file saved by a
spreadsheet program (with a byte order mark, with either kind of line end) is read
as it is. Two columns that name the same place in one row (``brief.order`` and
``brief.order.id``) are a FileProblem.

JSONL: one ``Case.to_plain()`` object per line; blank lines are skipped.

An eval file is ``<name>.eval.toml``::

    name = "support-quality"        # optional; default: the file name
    cases = "support.cases.csv"     # relative to this file
    trials = 3                      # optional; default 1
    environment = "shop"            # a name the project offers
    stand_in = "approve_all"        # optional; a name the project offers
    only = ["smoke"]                # optional; run only the cases with these tags or ids

    [[criteria]]
    use = "resolved"                # a criterion the project offers, by its key
    # name = "the case is closed"   # optional; default: the criterion's own name
    # measured = true               # optional; default: must pass

    [[criteria]]
    spends = { tokens = 12000 }     # tokens, calls or both: what one trial may spend
    name = "stays within budget"    # optional; default: "spends at most 12000 tokens"
    measured = true

    [[criteria]]
    name = "polite"
    judge = "The reply is polite and does not blame the customer."
    passes = "Sorry about that, I have refunded order 1."     # optional example
    fails = "You should have read the policy."                # optional example

    [[criteria]]
    name = "would you send this?"
    review = "Would you be happy for a customer to receive this reply?"
    measured = true

``use`` names a criterion by the key the project offers it under (a short word the
developers chose); reports call it by the ``name`` given beside it, or by the
criterion's own name when there is none. ``spends`` limits the tokens and model calls
of each trial (``gvn.evals.criteria.Spends``). ``passes`` and ``fails`` belong to
``judge`` criteria only. No criterion may be named ``passed``: reports use that name
for whether a trial passed overall.

### FileProblem

```python
from gvn.adapters.eval_files import FileProblem
```

A cases or eval file cannot be used as it is; the message says where and why.

### case_fields

```python
from gvn.adapters.eval_files import case_fields
```

```text
case_fields(dataset: Dataset) -> dict[str, list[str]]
```

``{"brief": [...], "expect": [...]}``: the dotted field names any case uses,
in first-use order (what a form offers one input for). A nested dict gives one
name per leaf; an empty dict is a leaf.

### read_cases

```python
from gvn.adapters.eval_files import read_cases
```

```text
read_cases(path: Path) -> Dataset
```

The Dataset of a cases file. FileProblem for an unknown ending, a missing
file, a malformed row or line (naming it, 1-based), a duplicate id, or no cases.

### write_cases

```python
from gvn.adapters.eval_files import write_cases
```

```text
write_cases(path: Path, dataset: Dataset) -> None
```

Write ``dataset`` to ``path`` in the format its ending names, replacing the
file in one step (write beside it, then rename), so a reader never sees half a
file. The dataset's own name is not written: it is the file name. CSV columns:
``case_id``, ``tags``, then every ``brief.*`` field then every ``expect.*`` field
any case uses, each in first-use order; nested dicts become dotted columns, an
empty dict is the JSON text ``{}`` in the column of its field, lists and other
values JSON text. ``read_cases(path)`` afterwards gives an equal Dataset, because
a str that would read back as something else (empty, with a space at either end,
a control character, or text that parses as JSON such as ``12``, ``true``,
``null``, ``[1]``) is written JSON-quoted. CSV cannot hold, so FileProblem is
raised and nothing is written, for: a field name (in a brief or an expect, at any
depth of nested dicts) that is empty, holds a dot, has a space at either end or
holds a control character, since a dot means nesting; a tag holding a space, since
a space separates tags; a value of more than 131072 characters; a character
that cannot be saved as UTF-8. Dicts inside lists are JSON text and have no such
limit. JSONL holds every dataset.

### add_case

```python
from gvn.adapters.eval_files import add_case
```

```text
add_case(path: Path, case: Case) -> None
```

Add ``case`` to the cases file (FileProblem when its id is already there).
The file is read and written whole; a CSV keeps its column order and new fields
are appended as new columns.

### replace_case

```python
from gvn.adapters.eval_files import replace_case
```

```text
replace_case(path: Path, case_id: str, case: Case) -> None
```

Replace the case ``case_id`` (FileProblem when absent, or when the new id
belongs to another case). It keeps its place in the file.

### remove_case

```python
from gvn.adapters.eval_files import remove_case
```

```text
remove_case(path: Path, case_id: str) -> None
```

Remove the case ``case_id`` (FileProblem when absent or when it is the last).

### CriterionEntry

```python
from gvn.adapters.eval_files import CriterionEntry
```

```text
CriterionEntry(
    kind: str,
    name: str | None = None,
    text: str = '',
    passes: str | None = None,
    fails: str | None = None,
    measured: bool = False,
    use: str | None = None,
    spends: collections.abc.Mapping[str, int] | None = None,
) -> None
```

One ``[[criteria]]`` table of an eval file. Immutable; equal by content.

``kind()``: ``"use"``, ``"spends"``, ``"judge"`` or ``"review"``. ``use()``: the
key of the project's criterion a ``use`` entry names, else None. ``spends()``: the
limits of a ``spends`` entry (``{"tokens": 12000}``, ``{"calls": 3}`` or both; a
fresh dict), else None. ``named()``: whether the file gives the name itself (a
judge and a review always do). ``name()``: the name the file gives; when it gives
none, the key of a ``use`` entry (reports then show the project criterion's own
name) or the name ``Spends`` gives its limits (``"spends at most 12000
tokens"``). ``text()``: the judge's statement or the review's question (``""``
otherwise). ``passes()`` / ``fails()``: the examples or None (only a judge has
them). ``measured()``: bool.

TypeError / ValueError for another kind, an empty name, a judge or review without
a name or text, a ``use`` without its key, a ``spends`` without a limit (or a
limit that is not an int >= 0), a key, limits or text on a kind that does not
take them, or examples on anything but a judge.

#### CriterionEntry.kind

```text
kind() -> str
```

#### CriterionEntry.name

```text
name() -> str
```

#### CriterionEntry.named

```text
named() -> bool
```

#### CriterionEntry.use

```text
use() -> str | None
```

#### CriterionEntry.spends

```text
spends() -> dict[str, int] | None
```

#### CriterionEntry.text

```text
text() -> str
```

#### CriterionEntry.passes

```text
passes() -> str | None
```

#### CriterionEntry.fails

```text
fails() -> str | None
```

#### CriterionEntry.measured

```text
measured() -> bool
```

### EvalFile

```python
from gvn.adapters.eval_files import EvalFile
```

```text
EvalFile(
    path: Path,
    name: str,
    cases: Path,
    environment: str,
    criteria: typing.Sequence[CriterionEntry],
    trials: int = 1,
    stand_in: str | None = None,
    only: typing.Sequence[str] = (),
) -> None
```

An eval file as read: names and text only, nothing resolved. Immutable;
equal by content.

#### EvalFile.path

```text
path() -> Path
```

#### EvalFile.name

```text
name() -> str
```

#### EvalFile.cases

```text
cases() -> Path
```

The cases file, resolved against the eval file's directory.

#### EvalFile.environment

```text
environment() -> str
```

#### EvalFile.criteria

```text
criteria() -> tuple[CriterionEntry, ...]
```

#### EvalFile.trials

```text
trials() -> int
```

#### EvalFile.stand_in

```text
stand_in() -> str | None
```

#### EvalFile.only

```text
only() -> tuple[str, ...]
```

### read_eval

```python
from gvn.adapters.eval_files import read_eval
```

```text
read_eval(path: Path) -> EvalFile
```

The EvalFile at ``path``. FileProblem for a missing file, invalid TOML, an
unknown key (naming it and the keys allowed), a criterion table that is not
exactly one of use / spends / judge / review, a judge or review without ``name``,
a ``spends`` that limits nothing or something other than tokens and calls, a
criterion whose ``name`` is ``"passed"`` (naming the entry: that name is taken by
the overall result), two criteria with one name (by ``CriterionEntry.name()``), no
must-pass criterion, or
``trials`` &lt; 1. Also refused, each naming the key: a missing ``cases``,
``environment`` or ``criteria``, a value of the wrong kind, and ``passes`` or
``fails`` on a criterion that is not a judge.

## gvn.adapters.eval_store

Eval results kept in a SQLite database file. Standard library only.

``SqliteResults(path)`` is a ``gvn.evals.ports.Results``: for each eval run its manifest
and one record per trial, durable once a method returns. Several objects, in one process
or several, may use the same file.

### SqliteResults

```python
from gvn.adapters.eval_store import SqliteResults
```

```text
SqliteResults(path: str | os.PathLike[str]) -> None
```

Durable Results over one SQLite file (tables ``eval_runs``, ``eval_trials`` and
``eval_claims``; the file's ``user_version`` records the format: 2, and a file of
format 1, which had no claims, is brought up to date when opened).

Every write is committed before the method returns. Several SqliteResults objects, in
one process or several, may use the same file; two opening one run name with equal
manifests both succeed, with different manifests the later gets ManifestMismatch.
Runs are ordered by the order in which they were first opened, trials by the order in
which each (case, trial) was first saved. The blocking database calls run in a worker
thread, one at a time per object; writers everywhere are serialised by SQLite. WAL mode,
``synchronous=FULL``. Cancellation: a call already in its worker thread still completes.
Passes gvn.testing.eval_contracts.ResultsContract.

#### SqliteResults.open

```text
async def open(run_name: str, manifest: dict[str, typing.Any]) -> None
```

Begin the eval run ``run_name`` with ``manifest``, or continue it: opening a
name that exists with an equal manifest changes nothing; with a different one
it raises ``ManifestMismatch`` naming the keys that differ, and writes nothing.

#### SqliteResults.amend

```text
async def amend(run_name: str, manifest: dict[str, typing.Any]) -> None
```

Replace the manifest of the eval run ``run_name``, in one step. LookupError
when there is no such run. For scoring a recorded run again under changed
criteria; ``open`` remains the only way to begin a run.

#### SqliteResults.manifest

```text
async def manifest(run_name: str) -> dict[str, typing.Any] | None
```

The manifest of ``run_name``, or None when there is no such eval run.

#### SqliteResults.runs

```text
async def runs() -> tuple[str, ...]
```

The names of every eval run, oldest first.

#### SqliteResults.save_trial

```text
async def save_trial(
    run_name: str,
    case_id: str,
    trial: int,
    record: dict[str, typing.Any],
) -> None
```

Keep ``record`` as trial ``trial`` of ``case_id``, replacing an earlier
record of that trial. LookupError for an eval run that was not opened.

#### SqliteResults.trials

```text
async def trials(run_name: str) -> tuple[dict[str, typing.Any], ...]
```

Every trial record of ``run_name``, ordered by the order in which each
(case, trial) was first saved. Empty for an unknown run.

#### SqliteResults.claim

```text
async def claim(
    run_name: str,
    case_id: str,
    trial: int,
    owner: str,
    now: float,
    until: float,
) -> bool
```

Take, or renew, ``owner``'s claim on trial ``trial`` of ``case_id`` until
``until``: True when the trial was unclaimed, its claim had run out (its
``until`` &lt;= ``now``) or was ``owner``'s already; False when another owner's
claim is still live, and then nothing changes. One step: of two owners claiming
at once, exactly one gets True. ``owner``: a non-empty str; ``now`` and
``until``: finite numbers with ``until`` > ``now`` (ValueError otherwise).
LookupError for an eval run that was not opened.

#### SqliteResults.release

```text
async def release(run_name: str, case_id: str, trial: int, owner: str) -> None
```

Give up ``owner``'s claim on that trial. Changes nothing when ``owner`` holds
none there (it ran out and another took it, or it was never taken).

#### SqliteResults.claims

```text
async def claims(run_name: str, now: float) -> tuple[tuple[str, int, str], ...]
```

The claims of ``run_name`` still live at ``now``, each ``(case_id, trial,
owner)``, ordered by case id then trial. Empty for an unknown run.

#### SqliteResults.close

```text
async def close() -> None
```

Release the database. Idempotent; using the store afterwards raises RuntimeError.

## gvn.adapters.logs

An Output that writes structured log records through the standard ``logging`` module.

One record per Signal on the given logger. The message is short and human
readable (``"helper event started -> thinking"``); the structure is in the
record's extra fields, so any handler or formatter can use it:

    gvn_kind, gvn_actor, gvn_sequence, gvn_at, gvn_data

``delta`` signals are logged at DEBUG, ``rejected`` at WARNING, everything else
at INFO. Text fragments of deltas appear only in ``gvn_data``, never in the
message.

``JsonFormatter`` renders a record as one line of JSON holding the level, logger
name, message and the gvn fields (without the ``gvn_`` prefix), for log
pipelines that want JSON lines.

Constants: `DELTA`, `EVENT`, `REJECTED`, `REQUEST`, `WAITING`.

### LoggingOutput

```python
from gvn.adapters.logs import LoggingOutput
```

```text
LoggingOutput(logger: logging.Logger | logging.LoggerAdapter) -> None
```

Receives every Signal. Structured logs, tracing and user streams implement this.

#### LoggingOutput.emit

```text
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.

### JsonFormatter

```python
from gvn.adapters.logs import JsonFormatter
```

```text
JsonFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)
```

Formatter instances are used to convert a LogRecord to text.

Formatters need to know how a LogRecord is constructed. They are
responsible for converting a LogRecord to (usually) a string which can
be interpreted by either a human or an external system. The base Formatter
allows a formatting string to be specified. If none is supplied, the
style-dependent default value, "%(message)s", "{message}", or
"${message}", is used.

The Formatter can be initialized with a format string which makes use of
knowledge of the LogRecord attributes - e.g. the default value mentioned
above makes use of the fact that the user's message and arguments are pre-
formatted into a LogRecord's message attribute. Currently, the useful
attributes in a LogRecord are described by:

%(name)s            Name of the logger (logging channel)
%(levelno)s         Numeric logging level for the message (DEBUG, INFO,
                    WARNING, ERROR, CRITICAL)
%(levelname)s       Text logging level for the message ("DEBUG", "INFO",
                    "WARNING", "ERROR", "CRITICAL")
%(pathname)s        Full pathname of the source file where the logging
                    call was issued (if available)
%(filename)s        Filename portion of pathname
%(module)s          Module (name portion of filename)
%(lineno)d          Source line number where the logging call was issued
                    (if available)
%(funcName)s        Function name
%(created)f         Time when the LogRecord was created (time.time()
                    return value)
%(asctime)s         Textual time when the LogRecord was created
%(msecs)d           Millisecond portion of the creation time
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
                    relative to the time the logging module was loaded
                    (typically at application startup time)
%(thread)d          Thread ID (if available)
%(threadName)s      Thread name (if available)
%(taskName)s        Task name (if available)
%(process)d         Process ID (if available)
%(message)s         The result of record.getMessage(), computed just as
                    the record is emitted

#### JsonFormatter.format

```text
format(record: logging.LogRecord) -> str
```

Format the specified record as text.

The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is
called to format the event time. If there is exception information,
it is formatted using formatException() and appended to the message.

## gvn.adapters.openai

The Model port over OpenAI's Responses API (``POST /v1/responses``).

The client is injected, so configuration (keys, base URL, retries, timeouts,
transport) stays with the caller and tests can supply a client that never
touches the network. Works with any service that implements the Responses API.
Requires the ``openai`` extra.

Stateless. Every request is sent with ``store: false`` and carries the whole
conversation as input items; nothing refers to state kept by the service
(``previous_response_id`` and ``conversation`` are never sent). gvn's journal is
the only record of a run, so a run replays from it and can change vendor.

Translation:

* Exchange.instructions -> ``instructions`` (omitted when empty).
* A user Message -> a user ``message`` item. An assistant Message -> its items in
  order: its OpenAI sealed records (reasoning items, see below), an assistant
  ``message`` item with its text (when it has text), then one ``function_call`` item
  per ToolCall (arguments as JSON text with sorted keys). A tool Message -> one
  ``function_call_output`` item per ToolResult (the content as JSON text with sorted
  keys; a failed result is ``{"content": ..., "error": true}``, since the protocol
  has no error flag; its attachments after it, see below). An instruction Message
  (``Message.instruction``) -> a ``message`` item with role ``developer`` and its text,
  in place: the service's authority for text from the developer, above the user's.
* Each ToolSpec -> a ``function`` tool with its name, description and JSON Schema,
  ``strict: false`` (the schema is used as written, not normalised by the service).
  Tools in name order and every object's keys sorted, so the same tools are the same
  bytes on every call and after a journal round trip: the service's prompt cache is
  a prefix match.
* The streamed reply -> text fragments to ``progress`` as they arrive, and a Reply
  whose Message carries the full text, the tool calls (ids and names as the API
  gave them, arguments parsed from JSON), the sealed reasoning items and the token
  usage. Empty or whitespace-only arguments mean no arguments (``{}``).

Reasoning (sealed content). Every ``reasoning`` output item of a reply is kept,
exactly as the stream's ``response.output_item.done`` event gave it (encrypted
reasoning in ``encrypted_content``), as a sealed record ``{"vendor": "openai",
"model": &lt;this adapter's model id>, "block": {...}}`` in output order. Every sealed
record of an assistant Message whose vendor is ``"openai"``, whatever its model, is
sent back as an input item, unmodified (keys sorted). The service omits reasoning a
model cannot use (another model family); it rejects reasoning whose encrypted
content it cannot verify (HTTP 400). Another vendor's records are never sent.

Order. A reply whose items are, in order, its reasoning, at most one message
without a ``phase`` and then its function calls needs nothing more. Any other
reply with reasoning (several messages, reasoning between calls, a message
``phase``, which OpenAI asks to be sent back) is recorded on the first sealed record
as ``"layout"``: one entry per original item, ``"reasoning"`` (the next sealed
record), ``["message", n]`` or ``["message", n, phase]`` (the next ``n`` characters
of the text) or ``"function_call"`` (the next call). A layout that does not fit the
message is ignored, and the turn is sent in the default order.

Effort. ``effort`` None sends nothing (the model's default); otherwise one of
EFFORTS, sent as ``reasoning: {"effort": ...}``. Which levels a model accepts is the
service's decision: a level the model does not support is rejected (HTTP 400), and
the failure's reason quotes the service's message, which names the levels it does.

Caching is automatic on this service: nothing is sent to turn it on. Usage:
``Reply.input_tokens`` is the API's ``input_tokens`` (every input token);
``cache_read_tokens`` is ``input_tokens_details.cached_tokens`` and
``cache_write_tokens`` is ``input_tokens_details.cache_write_tokens``, each 0 when
absent (capped so their sum never exceeds the input). ``output_tokens`` includes
reasoning tokens.

Structured answers. An Exchange with an ``answer`` (a kernel Record) is sent with
``text: {"format": {"type": "json_schema", "name": "answer", "schema": ...,
"strict": true}}``: the service constrains the reply's text to the schema (Structured
Outputs). The Record's JSON Schema is sent as gvn renders it when strict mode can
express it exactly, and refused otherwise, before any call, with a non-retryable
ModelFailure naming what cannot be expressed (``answer_format`` raises the same
ValueError): an optional field (strict mode requires every field; make it required, or
required and Nullable), ``MapOf`` (every object must set ``additionalProperties:
false``), ``Json()`` (any value), more than 10 levels of nested objects, more than 1,000
enum values or more than 5,000 properties (the documented limits). A schema is never
loosened. A refusal or a reply cut off at the token limit fails as below, so a
truncated answer is never parsed.

Attachments. A user Message with attachments is sent with a content list: its text as
``input_text`` (when not empty), then per Attachment an ``input_image`` (``image_url``:
a ``data:`` URL of the base64 bytes, or the URL; ``detail: "auto"``) or an
``input_file`` (``file_data``: a ``data:`` URL with ``filename`` the title or
``document.pdf``; or ``file_url``). ``cited`` has no effect: the service does not cite
document inputs. A user Message without attachments is sent as before.

Tool results with attachments (``ToolResult.attachments``, from a tool that returned a
``ToolOutput``). The ``function_call_output`` item's ``output`` becomes a list: an
``input_text`` part with the JSON text (wrapped as above when failed), then one
``input_image`` or ``input_file`` part per Attachment, built as for a user message. The
Responses API documents ``output`` as "a string or an array of content outputs (text,
image, file)" (API reference and the SDK's ``ResponseFunctionCallOutputItemListParam``,
checked 2026-11-17), so every media type an Attachment accepts is sent as it is, with no
fallback. A compatible service that does not take the list form answers HTTP 400: a
failure that is not retryable. A result without attachments is sent as before.

Citations. The annotations of a reply's ``output_text`` parts (``url_citation``,
``file_citation``, ``container_file_citation``, ``file_path``) become citation records
on the Message ``{"vendor": "openai", "start", "end", "source": &lt;the annotation as the
service sent it>}``, offsets in the message text (an annotation with one ``index`` has
``start == end``). They are not sent back.

Server tools (``server_tools=``, default none). Tools the service runs itself (web
search, file search, code interpreter, image generation) are enabled only by passing
their definitions, plain dicts sent as given after the Exchange's tools (for example
``{"type": "web_search"}``). gvn does not govern them: the policy, approvals and the
budget never see their calls, which run inside the model call. Their output items
(``web_search_call``, ``file_search_call``, ``code_interpreter_call``,
``image_generation_call``) are kept as sealed records in output order (layout entry
``"sealed"``) and sent back unmodified as input items, so a conversation that used them
continues.

Context window. ``context_window=`` (None, the default, or an int >= 1) is what
``context_window()`` returns: given by the caller, never looked up (no table, no extra
call). When the service refuses a conversation as too large for the model's context
window (error code ``context_length_exceeded``, whether as an HTTP error, an
``error`` event, an error inside the stream or a ``response.failed``), the failure has
``exceeded_context=True`` and is not retryable. Nothing else sets it: a reply cut off
by ``max_output_tokens`` is the token limit, not an overflow.

Vendor-side compaction (``context_management=``, default none). The service's own
``context_management`` entries (plain dicts, each with a "type", for example
``{"type": "compaction", "compact_threshold": 200000}``) are sent as given; gvn does not
interpret them. When the service compacts, its ``compaction`` output item (opaque,
encrypted) and any ``configuration_update`` item after it are kept as sealed records
in output order (layout entry ``"sealed"``) and sent back unmodified at their place in
the next request, which still carries the whole conversation (``store: false``). The
service says the latest compaction item carries what came before it; gvn sends the
earlier items too, since its transcript is not made smaller. Usage is the response's
own ``usage``, read as for any reply. Compaction items arrive whatever the setting
and are always kept.

Failures become ModelFailure, never a vendor exception: rate limiting, server
errors, timeouts and connection errors are retryable; bad requests,
authentication and permission errors are not. A status failure carries the
``retry-after`` the service sent (``retry-after-ms`` first, then ``retry-after`` in
seconds; an HTTP date is not read); a reply cut off at the token limit carries the
tokens it spent. The reason of a status or stream
error includes the service's own message: one line, at most 160 characters, with
the client's key and anything shaped like an OpenAI key redacted. A reply cut off
by the token limit (``incomplete``), stopped by a content filter, refused, or
carrying tool arguments that are not a JSON object is a failure too (not
retryable). Cancellation propagates as asyncio.CancelledError and closes the
stream.

The module also holds ``OpenAIEmbedder``, the ``Embedder`` over the embeddings endpoint
(``POST <base URL>/embeddings``), for a memory that recalls by meaning. It is a separate
class from the model, over its own injected client, and shares the module's failure
wording and secret hiding.

Constants: `ASSISTANT`, `IMAGE`, `INSTRUCTION`, `TOOL`, `USER`, `VENDOR`, `EFFORTS`.

### OpenAIModel

```python
from gvn.adapters.openai import OpenAIModel
```

```text
OpenAIModel(
    client: object,
    model: str,
    max_tokens: int | None = None,
    effort: str | None = None,
    server_tools: Iterable[Mapping[str, typing.Any]] = (),
    context_window: int | None = None,
    context_management: Iterable[Mapping[str, typing.Any]] = (),
) -> None
```

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

#### OpenAIModel.name

```text
name() -> str
```

The model id this adapter asks for (the constructor's ``model``).

#### OpenAIModel.provider

```text
provider() -> str
```

``"openai"``: this adapter calls OpenAI's Responses API.

#### OpenAIModel.context_window

```text
context_window() -> int | None
```

The ``context_window`` given to the constructor (an int >= 1), or None.

#### OpenAIModel.generate

```text
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.

### openai.answer_format

```python
from gvn.adapters.openai import answer_format
```

```text
answer_format(answer: Record) -> dict[str, typing.Any]
```

The ``text.format`` that asks the service for an answer matching ``answer`` (a
kernel Record): ``{"type": "json_schema", "name": "answer", "schema": ..., "strict":
true}``.

ValueError naming what strict Structured Outputs cannot express (see the module
docstring); the schema is never loosened.

### openai.retry_after

```python
from gvn.adapters.openai import retry_after
```

```text
retry_after(response: object) -> float | None
```

The seconds a response asks to wait (``retry-after-ms``, else ``retry-after`` as a
number of seconds), or None when it asks nothing usable. An HTTP-date value is not
read (it would need the clock).

### OpenAIEmbedder

```python
from gvn.adapters.openai import OpenAIEmbedder
```

```text
OpenAIEmbedder(
    client: object,
    model: str,
    dimensions: int | None = None,
    name: str | None = None,
    batch: int = 256,
) -> None
```

The ``Embedder`` over the embeddings endpoint (``POST <base URL>/embeddings``), the
format many embedding services accept at their own base URL, through an injected
``openai.AsyncOpenAI``.

Where it sits: hand it to a memory that recalls by meaning, for example
``SqliteMemory(path, embedder=OpenAIEmbedder(client, "embedding-model-id"))``. The
memory calls ``embed`` to keep a vector beside each entry and to turn a query into a
vector; nothing else in gvn sees an embedder. As with ``OpenAIModel``, the client is
injected, so keys, base URL, timeouts, transport and retries are the caller's
configuration of that client. This class never retries: a failed request is one
``EmbedderFailure``.

``embed(texts)`` sends the texts as the request's ``input`` (at most ``batch`` per
request; more texts go as several requests, one after the other, in order) with
``encoding_format="float"``, and returns one vector per text, in the texts' order:
the vectors are put in order by each item's ``index``, not by arrival. It raises
``EmbedderFailure``, with a one-line reason that never holds the API key or a request
body, for any SDK error (connection, timeout, status), a response without exactly one
embedding per text, an index out of range or repeated, a vector that is not a list
of finite numbers, vectors of different lengths (across all the requests of one
call), and an empty or all-zero vector. Cancellation propagates as
``asyncio.CancelledError``.

``name()`` is the ``name`` given, or ``"openai:<model>"``, with ``":<dimensions>"``
appended when ``dimensions`` is given. Vectors are only ever compared under one name,
so a deployment that points the client at another service's base URL gives its own
``name``: the same model id on two services need not make the same vectors.

#### OpenAIEmbedder.name

```text
name() -> str
```

The ``name`` given, or ``"openai:<model>"`` (with ``":<dimensions>"`` when
dimensions were given).

#### OpenAIEmbedder.embed

```text
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.

## gvn.adapters.otel

An Output that turns Signals into OpenTelemetry spans that LLM-trace viewers understand.

Depends on the OpenTelemetry API only (the ``otel`` extra); exporting is
configured by whoever supplies the tracer.

What a reader of a trace sees. One trace per driven stretch of an actor (from the
first signal seen for an actor until its ``waiting`` or ``finished`` signal), and
inside it one span per request, from its ``request`` signal until the ``event`` or
``rejected`` signal addressed to the request's origin, or until the run ends (then
marked cancelled). The spans follow the OpenTelemetry GenAI semantic conventions, so
tools that display LLM traces (Langfuse, Logfire, Phoenix and others) show a gvn run
as an agent trace with model calls, token counts and tool executions, with no
configuration:

* The run is the span ``invoke_agent <actor>`` (operation ``invoke_agent``, agent
  name = the actor), with the ``gvn.*`` attributes (actor, state, status, pending);
  when the closing signal reports spending, also ``gvn.spent.input_tokens``,
  ``gvn.spent.output_tokens``, ``gvn.spent.calls``, ``gvn.spent.cost`` and, when the
  budget was exceeded, ``gvn.overspent``.
* A model call is a CLIENT span named ``chat`` (renamed ``chat <model>`` once the
  answer names the model), operation ``chat``. The answer adds the response and
  request model, the provider, and the token usage: ``gen_ai.usage.input_tokens``
  counts every input token, cached or not (as in the conventions); the cache figures
  are the parts of it read from or written to the cache. A failed call is marked
  ERROR with ``error.type`` = ``model_failed``. ``gvn.request.retries`` counts the
  attempts given up on.
* A tool request keeps its ``gvn.request invoke_tools`` span and gets one INTERNAL
  child span per call, ``execute_tool <name>`` (operation ``execute_tool``, tool
  name, tool call id, ``gvn.tool.identity``), starting and ending with the request.
* Every other request is a ``gvn.request <kind>`` span.
* A ``chat`` or ``execute_tool`` span carries the agent name of the request's origin,
  which is a child actor when the run is a workflow, so a trace shows which agent
  made each call.

Deltas are counted on the request's span, not recorded one by one. Span names and
attributes use only data carried by Signals; payload contents (prompts, replies,
tool arguments and results) are never recorded. Timestamps come from the Signals
(the Clock), not from the system clock. The attribute names are module constants
here (this module does not import the semantic conventions package); a test checks
them against the installed conventions.

``emit`` never blocks and holds only the spans currently open.

Constants: `DELTA`, `EVENT`, `FINISHED`, `REJECTED`, `REQUEST`, `WAITING`, `GEN_AI_OPERATION_NAME`, `GEN_AI_AGENT_NAME`, `GEN_AI_PROVIDER_NAME`, `GEN_AI_REQUEST_MODEL`, `GEN_AI_RESPONSE_MODEL`, `GEN_AI_TOOL_NAME`, `GEN_AI_TOOL_CALL_ID`, `GEN_AI_USAGE_INPUT_TOKENS`, `GEN_AI_USAGE_OUTPUT_TOKENS`, `GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS`, `GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS`, `ERROR_TYPE`, `OPERATION_CHAT`, `OPERATION_EXECUTE_TOOL`, `OPERATION_INVOKE_AGENT`.

### TracingOutput

```python
from gvn.adapters.otel import TracingOutput
```

```text
TracingOutput(tracer: trace.Tracer) -> None
```

Receives every Signal. Structured logs, tracing and user streams implement this.

#### TracingOutput.emit

```text
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.

#### TracingOutput.open_spans

```text
open_spans() -> int
```

How many spans are currently open (runs plus requests).

## gvn.adapters.postgres

A Journal, Leases and a Memory kept in PostgreSQL, over psycopg 3 (the ``postgres``
extra).

    journal = PostgresJournal(conninfo="postgresql://gvn@db/gvn")
    leases = PostgresLeases(conninfo="postgresql://gvn@db/gvn")
    await journal.prepare()          # creates or upgrades gvn's tables; safe to repeat
    ...
    await leases.close()
    await journal.close()

Both classes over the same database share its storage: a fenced journal write is
checked against the lease table in the same statement or transaction as the write
(``gvn.harness.ports.Journal``, "Fencing").

Tables (all named ``gvn_*``; put them in a schema of your own with
``options=-csearch_path=...`` in the conninfo):

    gvn_schema           (component, version)       which version of the tables exists
    gvn_runs             one row per run: its record count, fence, lease and due time
    gvn_records          (run, position) -> body    the journal, bodies as ``json``
    gvn_snapshots        run -> (sequence, body)    the highest-sequence snapshot
    gvn_first_snapshots  run -> (sequence, body)    the first snapshot ever saved
    gvn_memory_entries   (scope, key) -> text       PostgresMemory's entries

Bodies are stored as ``json`` (the text exactly as written, validated by the
server), and read back as text and parsed here: their shape belongs to the runtime's
``Forms``, and nothing in the database depends on it.

Schema. Nothing is created implicitly: ``await prepare()`` creates the tables, or
upgrades them from an older version, inside one transaction holding a
transaction-scoped advisory lock, so any number of processes may call it at once.
The journal's and leases' tables are one component of ``gvn_schema`` (at
``SCHEMA_VERSION``), the memory's table another (at ``MEMORY_SCHEMA_VERSION``).
Using a journal or leases before the tables are at this build's version raises
``SchemaNotPrepared``; tables of a newer version raise ``NewerSchema``.

Event loops. All database work runs on a private event loop in a thread of each
object's own (started on first use, stopped by ``close``), with a pool of up to
``max_connections`` autocommit connections. The public methods may be awaited from
any event loop, and from several in turn (as ``asyncio.run`` in a test does).

Cancellation. Cancelling a caller cancels its database work: psycopg then asks the
server to cancel the statement, which "does not guarantee that the operation will
not complete" (psycopg's documentation). So a cancelled ``append`` may or may not
have added its record; if it did, the record is whole and at the next position (each
append is one statement or one transaction: the record and the run's count change
together or not at all). The same holds for every other write. A pooled connection whose work was
cancelled is rolled back or discarded by the pool before it is used again.

Constants: `SCHEMA_VERSION`, `MEMORY_SCHEMA_VERSION`.

### SchemaNotPrepared

```python
from gvn.adapters.postgres import SchemaNotPrepared
```

gvn's tables are missing or older than this build: run ``await prepare()``.

### NewerSchema

```python
from gvn.adapters.postgres import NewerSchema
```

gvn's tables were made by a newer build than this one: nothing is touched.

### PostgresJournal

```python
from gvn.adapters.postgres import PostgresJournal
```

```text
PostgresJournal(conninfo: str, max_connections: int = 4) -> None
```

Durable Journal in PostgreSQL. See the module docstring.

Each append is a single statement that bumps the run's count in ``gvn_runs`` and
inserts the record at the old count, so appends to one run are serialised by the
row lock and positions never skip or repeat; a fenced append adds
``fence = %s AND holder IS NOT NULL`` to that same statement. A ``begin``, and an
append naming its ``position``, is one transaction that locks the run's
``gvn_runs`` row first (checking the fence there), then checks the place and
writes, so of several writers naming one place exactly one succeeds. Every write is
committed before the method returns. Passes gvn.testing.contracts.JournalContract.

#### PostgresJournal.prepare

```text
async def prepare() -> int
```

Create or upgrade gvn's tables to ``SCHEMA_VERSION`` (an int, returned).
Idempotent and safe to run from many processes at once. NewerSchema if the
database is ahead of this build.

#### PostgresJournal.begin

```text
async def begin(
    run_id: str,
    state: dict[str, typing.Any],
    record: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably begin ``run_id``, as one atomic step: keep ``state`` as its snapshot
taken after 0 records (its first snapshot and its latest) and add ``record`` at
position 0 (fenced as the class says).

Made only if the run has no record and no snapshot at that moment; otherwise
``PositionTaken`` is raised and nothing is written. So a run is never left
with a birth snapshot and no opening record, and of several callers beginning
one run exactly one succeeds while the others change nothing.

#### PostgresJournal.append

```text
async def append(
    run_id: str,
    record: dict[str, typing.Any],
    fence: int | None = None,
    position: int | None = None,
) -> None
```

Durably add ``record`` at the end of ``run_id`` (fenced as the class says).

``position``: None (the default) adds at the end wherever that is. An int >= 0
(TypeError / ValueError otherwise) is where the caller believes the end is:
the record is added only if the run has exactly ``position`` records at the
moment of the write (the check and the write are one atomic step); otherwise
``PositionTaken`` is raised and nothing is written.

#### PostgresJournal.read

```text
async def read(run_id: str, start: int = 0) -> tuple[dict[str, typing.Any], ...]
```

Tuple of the records of ``run_id`` from position ``start`` (an int >= 0), in order.

Empty for an unknown run or a ``start`` at or past the end.

#### PostgresJournal.length

```text
async def length(run_id: str) -> int
```

How many records ``run_id`` has; 0 for an unknown run.

#### PostgresJournal.runs

```text
async def runs(after: str | None = None, limit: int | None = None) -> tuple[str, ...]
```

The ids of the runs this journal holds, as a tuple in ascending order.

A run is held once it has a record or a snapshot. The order is that of
Python's ``str`` comparison (by code point) on every storage, so a caller can
read a long list in pages: ``after`` (None, or a str, which need not be a run
the journal holds) leaves out every id that is not greater than it, and
``limit`` (None, or an int >= 1) keeps at most that many of the ids that are
left, the lowest ones. TypeError for an ``after`` that is neither None nor a
str or a ``limit`` that is neither None nor an int (a bool is not an int
here); ValueError for a ``limit`` below 1. Empty when no run fits.

#### PostgresJournal.save_snapshot

```text
async def save_snapshot(
    run_id: str,
    sequence: int,
    state: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably keep ``state`` as the snapshot of ``run_id`` taken after ``sequence`` records
(fenced as the class says).

``sequence`` is an int >= 0: the state reflects exactly the records at
positions below it. Two snapshots are kept per run: the first one ever
saved, and the one with the highest sequence; saving a lower one than is
already held changes nothing (beyond becoming the first, if it is).

#### PostgresJournal.latest_snapshot

```text
async def latest_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the highest-sequence snapshot of ``run_id``, or None.

#### PostgresJournal.first_snapshot

```text
async def first_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the first snapshot ever saved for ``run_id``, or None.

The first snapshot is kept for good (later saves never replace it), so a
run can always be replayed from its beginning.

#### PostgresJournal.close

```text
async def close() -> None
```

Close the connections and stop the private loop. Idempotent; using the
journal afterwards raises RuntimeError.

### PostgresLeases

```python
from gvn.adapters.postgres import PostgresLeases
```

```text
PostgresLeases(conninfo: str, max_connections: int = 2) -> None
```

Leases in PostgreSQL, in the ``gvn_runs`` table the journal of the same database
uses. See the module docstring.

``acquire`` is one ``INSERT ... ON CONFLICT DO UPDATE ... WHERE`` statement, so
concurrent acquirers are serialised by the run's row lock and at most one wins.
``due`` and ``earliest`` read partial indexes: one on ``(pool, due)`` for the runs
that have a due time, one on ``pool`` for the runs held now. Passes
gvn.testing.contracts.LeasesContract.

#### PostgresLeases.prepare

```text
async def prepare() -> int
```

As ``PostgresJournal.prepare``: both create the same tables.

#### PostgresLeases.acquire

```text
async def acquire(
    run_id: str,
    pool: str,
    holder: str,
    now: float,
    until: float,
) -> Lease | None
```

Take ``run_id`` for ``holder`` until ``until`` (> ``now``), or None.

Succeeds only when the run has no lease or an expired one (the same holder
included: a lease is never taken twice). On success the run's fence grows by
one (1 for a run never leased), its pool becomes ``pool``, its ``due`` becomes
``now``, and the new Lease is returned. On failure nothing changes.
TypeError / ValueError for bad arguments.

#### PostgresLeases.renew

```text
async def renew(lease: Lease, until: float) -> Lease | None
```

Extend ``lease`` to ``until``: the renewed Lease (same fence), or None when the
lease is no longer the run's current one (taken over or released). An expired
lease nobody took is renewed.

#### PostgresLeases.release

```text
async def release(lease: Lease, due: float | None = None) -> bool
```

Give ``lease`` back and set the run's ``due`` (None or a finite number).

True if released; False, with nothing changed, when it was no longer the
run's current lease. The fence is kept: the next acquire makes a higher one,
and a released lease writes nothing more.

#### PostgresLeases.holder

```text
async def holder(run_id: str) -> Lease | None
```

The run's current Lease (taken and not released; expired or not), or None.

#### PostgresLeases.due

```text
async def due(pool: str, now: float, limit: int) -> tuple[str, ...]
```

Tuple of up to ``limit`` (an int >= 1) run ids claimable by ``pool`` at ``now``,
earliest ``due`` first (ties by run id). Answered from an index: it does not
read every run.

#### PostgresLeases.earliest

```text
async def earliest(pool: str) -> float | None
```

The earliest time at which some run of ``pool`` with a ``due`` becomes
claimable (``max(due, until)`` for a leased run), or None if no run of the pool
has a ``due``. A time already past means some run is claimable now.

#### PostgresLeases.close

```text
async def close() -> None
```

Close the connections and stop the private loop. Idempotent.

### PostgresMemory

```python
from gvn.adapters.postgres import PostgresMemory
```

```text
PostgresMemory(conninfo: str, max_connections: int = 2) -> None
```

A durable Memory in PostgreSQL, shared by every process that reaches the database.

    memory = PostgresMemory(conninfo="postgresql://gvn@db/gvn")
    await memory.prepare()           # creates or upgrades its table; safe to repeat
    ...
    await memory.close()

It may live in the same database as a ``PostgresJournal`` (it shares ``gvn_schema``,
under its own component) or in another one. Nothing is created implicitly:
``prepare()`` creates or upgrades the table inside one transaction holding the same
advisory lock the journal's ``prepare`` holds, so any number of processes may call
either at once. Using a memory whose table is not at ``MEMORY_SCHEMA_VERSION``
raises ``SchemaNotPrepared``; a newer table raises ``NewerSchema``. Neither is a
MemoryFailure: the deployment is wrong, and a retry cannot help.

Every entry is a row of ``gvn_memory_entries``: its scope, its key, its text and a
number (the entry's id, as a str) from an identity column, with a unique constraint
on ``(scope, key)``, so remembering is idempotent even when several processes
remember the same key at once: whichever commits first wins, and every caller gets
that entry's id. Numbers are never given twice, so an id of a forgotten entry is
never an id again. Every recall reads only the asked scope's entries.

What "match" means. Keyword search, not meaning: no embeddings, no synonyms, and no
extension to install. The query's words are its runs of letters, digits and ``_``;
everything else only separates them, and each word reaches the database as a
parameter, never as search syntax, so a query can never be read as a search
expression. Entries are indexed with PostgreSQL full-text search under the
``english`` configuration (stemming, so "invoices" finds "invoice"): an entry
matches when it holds any of the query's words, entries are ranked by ``ts_rank``,
best first, then oldest first. A query with no words (empty, whitespace, only
punctuation), or whose words the configuration all discards, matches nothing.

Forgetting deletes the rows; the index follows in the same statement, and the
entry's key goes with it.

Event loops, connections and cancellation are as the module docstring says for the
journal: a cancelled ``remember`` may or may not have kept its text (wholly if it
did; its key makes the retry harmless). Every write is committed before the method
returns. A database error while remembering, recalling or forgetting (the server
unreachable, a statement refused, a read-only database) is raised as MemoryFailure
with a one-line reason that never holds the conninfo. Passes
gvn.testing.contracts.MemoryContract.

#### PostgresMemory.prepare

```text
async def prepare() -> int
```

Create or upgrade the memory's table to ``MEMORY_SCHEMA_VERSION`` (an int,
returned). Idempotent and safe to run from many processes at once, and beside a
journal's ``prepare``. NewerSchema if the database is ahead of this build. The
journal's tables and version are not touched.

#### PostgresMemory.remember

```text
async def remember(scope: str, text: str, key: str) -> str
```

Keep ``text`` (a non-empty str) under ``scope`` and return the entry's id (a
non-empty str, unique within the scope).

``key`` is a non-empty str that identifies this act of remembering: work is
delivered at least once, so the same ``scope`` and ``key`` may arrive again after
a crash. Then nothing new is kept and the first entry's id is returned (whatever
the text). Once the method returns, the entry survives the process. Raises
MemoryFailure when it cannot keep the text, which includes a memory that is
read-only. Must honour cancellation promptly.

#### PostgresMemory.recall

```text
async def recall(scope: str, query: str, limit: int) -> list[dict[str, str]]
```

The entries under ``scope`` that best match ``query`` (a str; what "match"
means is the implementation's), best first, at most ``limit`` (an int >= 1): a
list of ``{"id": str, "text": str}``, a fresh copy, empty when nothing matches.
Raises MemoryFailure when it cannot search. Must honour cancellation promptly.

#### PostgresMemory.forget

```text
async def forget(scope: str, entry: str) -> bool
```

Remove the entry whose id is ``entry`` (a non-empty str, as ``remember`` and
``recall`` give it) from ``scope`` (a non-empty str). True when an entry was
removed; False, with nothing changed, when ``scope`` holds no entry with that id
(an id that belongs to another scope included: scopes are kept apart here too).

Once the method returns, the removal survives the process and the entry is never
recalled again. Ids are never reused within a scope: a later ``remember`` gets a
new id. The entry's idempotency key goes with it, so ``remember`` with the same
``scope`` and ``key`` afterwards keeps a NEW entry (a new id, the new text).
Forgetting twice is safe: the second call returns False. Raises MemoryFailure
when it cannot remove, which includes a memory that is read-only. Must honour
cancellation promptly.

#### PostgresMemory.forget_all

```text
async def forget_all(scope: str) -> int
```

Remove every entry of ``scope`` (a non-empty str) and return how many were
removed (0 for a scope that holds nothing). No other scope is touched.

Once the method returns, the removal survives the process and none of those
entries is recalled again. Ids are never reused within a scope, and the entries'
idempotency keys go with them: ``remember`` with a key the scope used before
keeps a NEW entry. Raises MemoryFailure when it cannot remove, which includes a
memory that is read-only. Must honour cancellation promptly.

#### PostgresMemory.close

```text
async def close() -> None
```

Close the connections and stop the private loop. Idempotent; using the memory
afterwards raises RuntimeError.

## gvn.adapters.sqlite

A Journal, Leases and a Memory kept in SQLite database files. Standard library only.

``SqliteJournal(path)`` and ``SqliteLeases(path)`` over the same file share its
storage: a fenced journal write is checked against the file's lease table in the
same transaction (``gvn.harness.ports.Journal``, "Fencing"). ``SqliteMemory(path)``
keeps a ``gvn.harness.ports.Memory`` with keyword search (FTS5 where available), and
with an embedder (``SqliteMemory(path, embedder=...)``) search by meaning as well.

### SqliteJournal

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

```text
SqliteJournal(path: str | os.PathLike[str]) -> None
```

Durable Journal over one SQLite file.

Every write is committed before the method returns. Several SqliteJournal
objects, in one process or several, may use the same file. The blocking
database calls do not block the event loop: each runs in a worker thread, one at
a time per object, and writers everywhere are serialised by SQLite (every write
is a ``BEGIN IMMEDIATE`` transaction, so an append's position, and the check of
a ``begin`` or of a named ``position``, are made in the same transaction as the
insert and cannot race; a busy timeout makes contenders wait). The file uses WAL
mode with ``synchronous=FULL``. Passes gvn.testing.contracts.JournalContract.

Fenced writes are checked against the lease table of the same file (written by
``SqliteLeases``) inside the write's own transaction.

Cancellation: if a caller is cancelled while a call is in the worker thread, that
call still completes, so a cancelled ``append`` may still have added its record
(wholly: a record is never half written, and positions never skip).

#### SqliteJournal.begin

```text
async def begin(
    run_id: str,
    state: dict[str, typing.Any],
    record: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably begin ``run_id``, as one atomic step: keep ``state`` as its snapshot
taken after 0 records (its first snapshot and its latest) and add ``record`` at
position 0 (fenced as the class says).

Made only if the run has no record and no snapshot at that moment; otherwise
``PositionTaken`` is raised and nothing is written. So a run is never left
with a birth snapshot and no opening record, and of several callers beginning
one run exactly one succeeds while the others change nothing.

#### SqliteJournal.append

```text
async def append(
    run_id: str,
    record: dict[str, typing.Any],
    fence: int | None = None,
    position: int | None = None,
) -> None
```

Durably add ``record`` at the end of ``run_id`` (fenced as the class says).

``position``: None (the default) adds at the end wherever that is. An int >= 0
(TypeError / ValueError otherwise) is where the caller believes the end is:
the record is added only if the run has exactly ``position`` records at the
moment of the write (the check and the write are one atomic step); otherwise
``PositionTaken`` is raised and nothing is written.

#### SqliteJournal.read

```text
async def read(run_id: str, start: int = 0) -> tuple[dict[str, typing.Any], ...]
```

Tuple of the records of ``run_id`` from position ``start`` (an int >= 0), in order.

Empty for an unknown run or a ``start`` at or past the end.

#### SqliteJournal.length

```text
async def length(run_id: str) -> int
```

How many records ``run_id`` has; 0 for an unknown run.

#### SqliteJournal.runs

```text
async def runs(after: str | None = None, limit: int | None = None) -> tuple[str, ...]
```

The ids of the runs this journal holds, as a tuple in ascending order.

A run is held once it has a record or a snapshot. The order is that of
Python's ``str`` comparison (by code point) on every storage, so a caller can
read a long list in pages: ``after`` (None, or a str, which need not be a run
the journal holds) leaves out every id that is not greater than it, and
``limit`` (None, or an int >= 1) keeps at most that many of the ids that are
left, the lowest ones. TypeError for an ``after`` that is neither None nor a
str or a ``limit`` that is neither None nor an int (a bool is not an int
here); ValueError for a ``limit`` below 1. Empty when no run fits.

#### SqliteJournal.save_snapshot

```text
async def save_snapshot(
    run_id: str,
    sequence: int,
    state: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably keep ``state`` as the snapshot of ``run_id`` taken after ``sequence`` records
(fenced as the class says).

``sequence`` is an int >= 0: the state reflects exactly the records at
positions below it. Two snapshots are kept per run: the first one ever
saved, and the one with the highest sequence; saving a lower one than is
already held changes nothing (beyond becoming the first, if it is).

#### SqliteJournal.first_snapshot

```text
async def first_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the first snapshot ever saved for ``run_id``, or None.

The first snapshot is kept for good (later saves never replace it), so a
run can always be replayed from its beginning.

#### SqliteJournal.latest_snapshot

```text
async def latest_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the highest-sequence snapshot of ``run_id``, or None.

#### SqliteJournal.close

```text
async def close() -> None
```

Release the database. Idempotent; using the journal afterwards raises RuntimeError.

### SqliteLeases

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

```text
SqliteLeases(path: str | os.PathLike[str]) -> None
```

Leases kept in a SQLite file, beside the journal of the same file.

One row per run in the ``leases`` table, with partial indexes on ``(pool, due)``
for the runs that have a ``due`` and on ``pool`` for the runs held now, so ``due``
and ``earliest`` do not read every run. Every write
is a ``BEGIN IMMEDIATE`` transaction, atomic with respect to every other process
using the file. Threading and cancellation are as for ``SqliteJournal``: a
cancelled call still completes. Passes gvn.testing.contracts.LeasesContract.

#### SqliteLeases.acquire

```text
async def acquire(
    run_id: str,
    pool: str,
    holder: str,
    now: float,
    until: float,
) -> Lease | None
```

Take ``run_id`` for ``holder`` until ``until`` (> ``now``), or None.

Succeeds only when the run has no lease or an expired one (the same holder
included: a lease is never taken twice). On success the run's fence grows by
one (1 for a run never leased), its pool becomes ``pool``, its ``due`` becomes
``now``, and the new Lease is returned. On failure nothing changes.
TypeError / ValueError for bad arguments.

#### SqliteLeases.renew

```text
async def renew(lease: Lease, until: float) -> Lease | None
```

Extend ``lease`` to ``until``: the renewed Lease (same fence), or None when the
lease is no longer the run's current one (taken over or released). An expired
lease nobody took is renewed.

#### SqliteLeases.release

```text
async def release(lease: Lease, due: float | None = None) -> bool
```

Give ``lease`` back and set the run's ``due`` (None or a finite number).

True if released; False, with nothing changed, when it was no longer the
run's current lease. The fence is kept: the next acquire makes a higher one,
and a released lease writes nothing more.

#### SqliteLeases.holder

```text
async def holder(run_id: str) -> Lease | None
```

The run's current Lease (taken and not released; expired or not), or None.

#### SqliteLeases.due

```text
async def due(pool: str, now: float, limit: int) -> tuple[str, ...]
```

Tuple of up to ``limit`` (an int >= 1) run ids claimable by ``pool`` at ``now``,
earliest ``due`` first (ties by run id). Answered from an index: it does not
read every run.

#### SqliteLeases.earliest

```text
async def earliest(pool: str) -> float | None
```

The earliest time at which some run of ``pool`` with a ``due`` becomes
claimable (``max(due, until)`` for a leased run), or None if no run of the pool
has a ``due``. A time already past means some run is claimable now.

#### SqliteLeases.close

```text
async def close() -> None
```

Release the database. Idempotent; using the leases afterwards raises RuntimeError.

### SqliteMemory

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

```text
SqliteMemory(
    path: str | os.PathLike[str],
    full_text: bool = True,
    embedder: Embedder | None = None,
    *,
    least_similarity: float = 0.0,
) -> None
```

A durable Memory in a SQLite file. Standard library only.

Every entry is a row of ``memory_entries``: its scope, its key, its text and a
number (the entry's id, as a str), with a unique constraint on ``(scope, key)``, so
remembering is idempotent even when several objects or processes remember the same
key at once: whichever commits first wins, and every caller gets that entry's id.
Every recall reads only the asked scope's entries. Numbers are never given twice
(AUTOINCREMENT), so an id of a forgotten entry is never an id again.

What "match" means. Without an embedder, words: an entry matches a query that shares
a word with it, and nothing else. With an embedder (``embedder=``, a
``gvn.runtime.memory.Embedder``), words and meaning: each entry also has a vector,
and a recall fuses two rankings, by words and by meaning, into one with
``gvn.runtime.memory.fused_ranking`` (reciprocal rank fusion), so an entry both find
comes before an entry only one finds, and an entry that shares no word with the
query can still be found by meaning.

By words. The query's words are its runs of letters, digits and ``_``; everything
else only separates them, so a query can never be read as search syntax.

* With FTS5 (``full_text=True`` and the SQLite build has it, checked at
  construction; ``full_text()`` says which): a full-text index (``memory_words``,
  porter stemming over unicode61, so "invoices" finds "invoice"). An entry matches
  when it holds any of the query's words; entries are ranked by BM25, best first,
  then oldest first. Each word is quoted before it reaches FTS5.
* Otherwise: an entry matches when it holds any query word as a substring, compared
  case-insensitively; entries are ranked by how many distinct query words they hold,
  then oldest first. This reads every entry of the scope, so it suits small scopes.

A query with no words (empty, whitespace, only punctuation) matches nothing, and the
embedder is not asked.

By meaning. ``remember`` asks the embedder for the text's vector first (on the event
loop), then keeps the entry and, only when this call kept it, its vector, in one
transaction. Vectors are rows of ``memory_vectors``: the entry's number, the
embedder's ``name()``, and the vector, unit-normalised, as little-endian float32. A
recall asks the embedder for the query's vector, then ranks the scope's entries by
the cosine of their vector with it, highest first, then oldest first, leaving out
those below ``least_similarity`` (keyword-only, a finite number in [-1, 1], default
0.0): with a real embedder most texts are somewhat similar to each other, so a
deployment that wants a query about nothing relevant to recall nothing raises it.
Each of the two rankings contributes at most ``max(4 * limit, 20)`` entries to the
fusion. The similarity search reads every vector of the scope (exact cosine, in
Python), which suits scopes of up to some thousands of entries.

* Only vectors recorded under this object's embedder's ``name()`` are compared;
  vectors of another embedder never are.
* An entry with no vector under that name (kept by an object without an embedder,
  or with another embedder) is found by words only until ``embed_missing()`` gives
  it one.
* Every vector the embedder gives is checked (``gvn.runtime.memory.embedded``); a
  vector whose length differs from those already stored under the same name in this
  file is a MemoryFailure naming both lengths, and nothing is kept. An
  ``EmbedderFailure`` is a MemoryFailure with its reason, and nothing is kept.
* The same key again keeps nothing new and no new vector. A cheap read first finds
  a key the scope already holds, so the embedder is not asked for it; two calls
  racing on a new key may both ask, and the vector of the call that did not keep the
  entry is discarded.

Forgetting. ``forget`` and ``forget_all`` each delete the entries, their index rows
and their vectors in one ``BEGIN IMMEDIATE`` transaction. An object without FTS5
removes the index rows too when its SQLite can; when it cannot, a leftover row is
never returned (a recall joins the index to the entries) and the next indexing
object to connect drops it. An object without an embedder never makes the
``memory_vectors`` table, but deletes an entry's vectors when the file has it, so no
vector outlives its entry.

Objects of every kind (with and without FTS5, with and without an embedder, with
different embedders) may share one file. The index is brought up to date when an
FTS5 object connects and inside each of its ``remember`` calls, so an entry kept by
an object without FTS5 is found by FTS5 recalls from then on.

Threading, durability and cancellation are as for ``SqliteJournal``: every call runs
in a worker thread (the event loop is never blocked), every write is a ``BEGIN
IMMEDIATE`` transaction committed before the method returns (WAL, ``synchronous =
FULL``), and a cancelled call returns at once while its work completes (a cancelled
``remember`` may still have kept its text, wholly; its key makes the retry harmless).
A call cancelled while the embedder is asked keeps nothing. Any SQLite error,
opening the file included, is raised as MemoryFailure. Passes
gvn.testing.contracts.MemoryContract.

#### SqliteMemory.full_text

```text
full_text() -> bool
```

True when this object searches with FTS5, False when with substrings.

#### SqliteMemory.embedder

```text
embedder() -> Embedder | None
```

The Embedder this object was built with, or None.

#### SqliteMemory.remember

```text
async def remember(scope: str, text: str, key: str) -> str
```

Keep ``text`` (a non-empty str) under ``scope`` and return the entry's id (a
non-empty str, unique within the scope).

``key`` is a non-empty str that identifies this act of remembering: work is
delivered at least once, so the same ``scope`` and ``key`` may arrive again after
a crash. Then nothing new is kept and the first entry's id is returned (whatever
the text). Once the method returns, the entry survives the process. Raises
MemoryFailure when it cannot keep the text, which includes a memory that is
read-only. Must honour cancellation promptly.

#### SqliteMemory.forget

```text
async def forget(scope: str, entry: str) -> bool
```

Remove the entry whose id is ``entry`` (a non-empty str, as ``remember`` and
``recall`` give it) from ``scope`` (a non-empty str). True when an entry was
removed; False, with nothing changed, when ``scope`` holds no entry with that id
(an id that belongs to another scope included: scopes are kept apart here too).

Once the method returns, the removal survives the process and the entry is never
recalled again. Ids are never reused within a scope: a later ``remember`` gets a
new id. The entry's idempotency key goes with it, so ``remember`` with the same
``scope`` and ``key`` afterwards keeps a NEW entry (a new id, the new text).
Forgetting twice is safe: the second call returns False. Raises MemoryFailure
when it cannot remove, which includes a memory that is read-only. Must honour
cancellation promptly.

#### SqliteMemory.forget_all

```text
async def forget_all(scope: str) -> int
```

Remove every entry of ``scope`` (a non-empty str) and return how many were
removed (0 for a scope that holds nothing). No other scope is touched.

Once the method returns, the removal survives the process and none of those
entries is recalled again. Ids are never reused within a scope, and the entries'
idempotency keys go with them: ``remember`` with a key the scope used before
keeps a NEW entry. Raises MemoryFailure when it cannot remove, which includes a
memory that is read-only. Must honour cancellation promptly.

#### SqliteMemory.recall

```text
async def recall(scope: str, query: str, limit: int) -> list[dict[str, str]]
```

The entries under ``scope`` that best match ``query`` (a str; what "match"
means is the implementation's), best first, at most ``limit`` (an int >= 1): a
list of ``{"id": str, "text": str}``, a fresh copy, empty when nothing matches.
Raises MemoryFailure when it cannot search. Must honour cancellation promptly.

#### SqliteMemory.embed_missing

```text
async def embed_missing(scope: str | None = None, batch: int = 64) -> int
```

Give a vector to every entry (of ``scope``, or of every scope when None) that
has none under this object's embedder's name, and return how many vectors this
call stored (0 when none was missing). Entries are read in id order, ``batch``
texts per embedder call, and each batch's vectors are committed in one
transaction, so the batches committed before a failure stay. Safe to run again
and from several objects or processes at once: an entry embedded by two of them
keeps one vector (the first committed), and only the call that stored it counts
it. An entry forgotten meanwhile gets no vector.

``scope``: None or a non-empty str. ``batch``: an int >= 1. TypeError/ValueError
otherwise; ValueError when this object has no embedder. MemoryFailure when the
embedder or the database fails, or a vector's length differs from those stored
under the name. Cancellation as for every call: a batch being written completes,
wholly; one being embedded is not written.

#### SqliteMemory.close

```text
async def close() -> None
```

Release the database. Idempotent; using the memory afterwards raises RuntimeError.
