# Logs, traces and streams

This guide wires a run to the places you watch it from: your logs, your tracing system and
the live stream a user reads. At the end you have one run reporting to all three at once,
and an output of your own that counts tokens as they are spent.

- **You will be able to:** log a run as structured records or JSON lines, export it as
  OpenTelemetry spans, stream the answer to a user as it is written, do all three at once, and
  count tokens as they are spent.
- **Read first:** the [quickstart](../quickstart.md). [Streaming and
  observability](../concepts/streaming-and-observability.md) explains the port and the six
  kinds of signal in depth, and the tutorial
  [5. A policy and approval](../tutorials/agent-with-approval.md) wires the agent and the
  Governor used here step by step. With `run_agent`, pass any output of this page as
  `output=` ([The short path](shortcuts.md#watching-the-run)).
- **Time:** about 20 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), the **Governor** drives a run: it
hands events to the actor, gives requests to the fulfillers and writes every event to the
journal. This guide is about a fifth thing the Governor talks to, beside those: the place it
reports what is happening, so that people and systems can watch the run while it goes.

```mermaid
flowchart LR
    governor["<b>Governor</b><br/>drives the run"]
    journal[("<b>Journal</b><br/>durable record")]
    output["<b>Output</b> port<br/>one signal per thing that happens"]
    fanout["<b>Fanout</b>"]
    logs["LoggingOutput<br/>your logs"]
    traces["TracingOutput<br/>your tracing system"]
    stream["StreamOutput<br/>the user's screen"]
    governor -- "records events" --> journal
    governor -- "emits signals" --> output
    output --> fanout
    fanout --> logs
    fanout --> traces
    fanout --> stream
```

A [**port**](../reference/glossary.md#port) is an interface the Governor calls without
knowing what is behind it. The observing port is called `Output`, and it has one method,
`emit(signal)`. A [**signal**](../reference/glossary.md#signal) is one small record of
something that happened: an event the actor handled, a request the Governor started, a
fragment of text a model wrote (a **delta**), the run stopping to wait, or the run finishing.
The [Streaming and observability](../concepts/streaming-and-observability.md) concept page
lists all six kinds.

The journal and the output differ in purpose. The journal is the durable record a run is
rebuilt from; the output is for watching, and nothing reads it back. Text fragments, for
example, reach the output but are never journaled.

A Governor takes exactly one output. To send the same run to several places, you give it a
`Fanout`, which passes every signal on to each output in a list. gvn ships these outputs:

| Output | Module | Needs | For |
|---|---|---|---|
| `LoggingOutput` | `gvn.adapters.logs` | nothing | structured log records through the standard `logging` module |
| `JsonFormatter` | `gvn.adapters.logs` | nothing | one line of JSON per record |
| `TracingOutput` | `gvn.adapters.otel` | the `otel` extra | OpenTelemetry spans |
| `StreamOutput` | `gvn.runtime.outputs` | nothing | the user's live stream, read with `async for` |
| `Fanout` | `gvn.runtime.outputs` | nothing | several outputs at once |

(`JsonFormatter` is not an output itself: it is a formatter for the standard `logging`
module that you put on a handler under `LoggingOutput`. OpenTelemetry, the `otel` row, is the
common open standard for traces, explained in step 3.)

The steps below take one output at a time, then combine them, then count tokens.

## Step 1: a run to observe

Every example below drives the same small run: an agent searches once, then answers in two
fragments. Only the output changes, so the run is wrapped in a function that takes the output
as its argument.

The pieces are the ones the tutorials wired by hand
([3. An agent with a scripted model](../tutorials/first-agent.md) and
[5. A policy and approval](../tutorials/agent-with-approval.md)):

- The model is a `ScriptedModel`, a fake that replies from a script instead of calling a
  vendor. An entry of its script is either a `Reply` (one model answer), or a pair of the
  text fragments to stream and the `Reply` they add up to.
- The tool is a `StubTool`, a test fake that accepts the declared arguments and returns a
  fixed result. It is built once and passed as the object both to the agent, which offers
  it to the model, and to the `Toolbox`, from which the runtime runs it
  ([Tools](../concepts/tools.md)). The scripted model asks for it by its short name,
  `search`, as a real model would.
- The policy is a tiny [Decision](../concepts/decisions.md) that clears every call.
  `VERDICTS` is the set of answers a policy may give (`cleared`, `needs_approval`,
  `forbidden`).
- The Governor gets one [fulfiller](../reference/glossary.md#fulfiller) per kind of request,
  a `MemoryJournal` (a journal kept in memory), a `ManualClock` (a clock that only moves when
  a test moves it), and the output under test.

```python
import asyncio

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Output, Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.governor import Governor, Result
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel, StubTool


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

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


search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})


def searching_governor(output: Output) -> Governor:
    toolbox = Toolbox(tools=[search])
    lookup = ToolCall(call_id="c1", name="search", arguments={"query": "moore"})
    model = ScriptedModel(
        script=[
            Reply(message=Message.assistant(text="", calls=[lookup])),
            (["Three ", "hits."], Reply(message=Message.assistant(text="Three hits."))),
        ]
    )
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=Allow()),
        },
        journal=MemoryJournal(),
        output=output,
        clock=ManualClock(),
    )


def helper() -> Agent:
    return Agent(name="helper", instructions="Be brief.", tools=[search])


QUESTION = Event("started", payload={"prompt": "Look it up."})


def run(output: Output) -> Result:
    governor = searching_governor(output)
    return asyncio.run(governor.deliver(actor=helper(), event=QUESTION))


print(run(RecordingOutput()).status())  # finished
```

`run(output)` builds a fresh Governor over `output` and delivers the `started` event: the
run goes to its end. `RecordingOutput`, a test fake, keeps every signal; here it only shows
that the run finishes.

## Step 2: structured logs

`LoggingOutput(logger=...)` writes one record per signal on the standard-library logger you
give it. Each record has a short readable message, and the signal's structure in extra
fields of the record, so any handler or formatter can use it. `JsonFormatter` renders each
record as one line of JSON:

```python
import io
import logging

from gvn.adapters.logs import JsonFormatter, LoggingOutput

buffer = io.StringIO()
handler = logging.StreamHandler(buffer)
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("docs.gvn.observability")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False

run(LoggingOutput(logger=logger))
lines = buffer.getvalue().splitlines()
print(len(lines))  # 10
print(lines[1])
# {"actor":"helper","at":0.0,"data":{"kind":"invoke_model","request_id":"helper/3"},"kind":"request",
#  "level":"INFO","logger":"docs.gvn.observability","message":"helper request invoke_model helper/3",
#  "sequence":1}
logger.removeHandler(handler)
```

The messages alone read as a log of the run. An event's message names the state it ended
in, and the address when the event was addressed (results of requests are addressed to the
actor that asked):

```text
helper event started -> thinking
helper request invoke_model helper/3
helper event model_replied -> vetting (to helper)
helper request consult_policy helper/5
helper event cleared -> acting (to helper)
helper request invoke_tools helper/6
helper event tools_returned -> thinking (to helper)
helper request invoke_model helper/10
helper event model_replied -> completed (to helper)
helper finished in completed
```

The structured fields each record carries (in the JSON line, the `gvn_` prefix is dropped):

| Field | Value |
|---|---|
| `gvn_kind` | the signal's kind: `event`, `rejected`, `request`, `delta`, `waiting` or `finished` |
| `gvn_actor` | the actor's name |
| `gvn_sequence` | the Governor's signal counter |
| `gvn_at` | the Clock's time |
| `gvn_data` | the signal's data, as plain JSON |

Deltas log at `DEBUG`, rejections at `WARNING`, everything else at `INFO`. A logger that is
not enabled for a level costs one check per signal and nothing more.

Logs carry the signal's data, and that includes payloads: the final answer in a `finished`
record, and the text of every fragment in `delta` records (at `DEBUG`). Decide what your log
pipeline may keep before you turn `DEBUG` on. `LoggingOutput` also accepts a
`logging.LoggerAdapter`, so you can add fields of your own (a deployment, a tenant) and keep
the gvn fields.

## Step 3: traces

A **trace** shows one piece of work as a tree of timed **spans**: one span for the whole
run, with a child span for each model call, policy check and tool round inside it.
OpenTelemetry is the open standard most tracing systems accept. Its **GenAI semantic
conventions** fix the names and attributes of spans for LLM applications, and `TracingOutput`
uses them: the run is an `invoke_agent` span, a model call a `chat` span and a tool call an
`execute_tool` span. A trace viewer built for LLM applications therefore shows a gvn run as
an agent trace, with its model calls, token counts and tool executions, without configuration.
Tool arguments, tool results and message contents are never put on spans. In its terms, a **tracer**
creates spans, a **tracer provider** makes tracers and sends their finished spans to an
**exporter**, and the exporter delivers them to your tracing system.

`TracingOutput(tracer=...)` turns signals into OpenTelemetry spans. It depends on the
OpenTelemetry API only; you supply the tracer, so exporting is configured wherever you
configure OpenTelemetry. This example uses the SDK's in-memory exporter, which simply keeps
the finished spans in a list (the SDK is in gvn's dev environment; in your project, install
`opentelemetry-sdk` or your vendor's distribution):

```python
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from gvn.adapters.otel import TracingOutput

exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracing = TracingOutput(tracer=provider.get_tracer("docs"))

run(tracing)
for span in exporter.get_finished_spans():
    attributes = span.attributes
    print(span.name, span.kind.name, attributes.get("gvn.request.result", attributes.get("gvn.state", "")))
# chat CLIENT model_replied
# gvn.request consult_policy INTERNAL cleared
# execute_tool search INTERNAL
# gvn.request invoke_tools INTERNAL tools_returned
# chat CLIENT model_replied
# invoke_agent helper INTERNAL completed

answer = exporter.get_finished_spans()[4]
print(answer.attributes["gvn.request.deltas"], answer.attributes["gvn.request.delta_chars"])
# 2 11
print(tracing.open_spans())  # 0
```

What to notice: one span per piece of work the agent asked for, in order, then the
`invoke_agent` span that contains them. The model calls are `chat` spans (a `CLIENT` span,
which marks a call out to another service), the policy check is a `gvn.request` span, and the
tool round is a `gvn.request invoke_tools` span holding one `execute_tool` span for the
`search` call. Each span carries **attributes** (key and value pairs): here, how each request
ended, and on the final model call how many text fragments it streamed (2) and how many
characters they held (11). The scripted model names no model and reports no tokens, so these
`chat` spans are named plain `chat` and their token counts are 0; a real model's answer names
it, and the span becomes `chat <model>`.

The tracer comes from a provider you hold, not from the global one, so the example leaves
no global state behind. In production you would typically pass
`opentelemetry.trace.get_tracer("my-service")` after configuring the global provider once.

### The span model

| Span | Name | Opens | Closes | Attributes |
|---|---|---|---|---|
| run | `invoke_agent <actor>` | at the first signal for the actor in a Governor call | at its `waiting` or `finished` signal | `gen_ai.operation.name` (`invoke_agent`), `gen_ai.agent.name`, `gvn.actor`; at the end `gvn.state`, `gvn.status` (`waiting` or `finished`) and, when waiting, `gvn.pending` (the external request kinds); under an [allowance](spending-and-rate-limits.md), `gvn.spent.input_tokens`, `gvn.spent.output_tokens`, `gvn.spent.calls`, `gvn.spent.cost` (when the allowance has rates) and `gvn.overspent` (when the run has reached its allowance: its tally is at or above one of the allowance's thresholds) |
| model call | `chat`, renamed `chat <model>` once the answer names the model; a `CLIENT` span, a child of the run | at the `request` signal of kind `invoke_model` | at the `event` signal that answers it | `gen_ai.operation.name` (`chat`), `gen_ai.agent.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens` (every input token, cached or not), `gen_ai.usage.output_tokens`, `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens`, and the `gvn.request.*` attributes below; `gvn.request.retries` counts the attempts given up on. A `model_failed` answer marks the span an error, with `error.type` = `model_failed` |
| tool round | `gvn.request invoke_tools`, a child of the run | at the `request` signal | at the `event` signal that answers it | the `gvn.request.*` attributes below |
| tool call | `execute_tool <name>`, an internal child of the tool round | with the tool round | with the tool round | `gen_ai.operation.name` (`execute_tool`), `gen_ai.agent.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gvn.tool.identity` |
| other request | `gvn.request <kind>`, a child of the run | at the `request` signal | at the `event` or `rejected` signal addressed to the request's origin; or when the run span closes, then marked cancelled | the `gvn.request.*` attributes below |

Every request span (a `chat` span, a tool round or an other request) carries
`gvn.request.id`, `gvn.request.kind`, `gvn.request.origin`, `gvn.request.deltas` and
`gvn.request.delta_chars`, then `gvn.request.result` (the event's name, status OK) or
`gvn.request.cancelled`.

Each `event` and `rejected` signal is also recorded as a span event (`gvn.event` or
`gvn.rejected`) on the run span, with `gvn.event.name`, `gvn.event.to` (when addressed) and
`gvn.event.state`.

Some things to know about it:

- **A run span covers one driven stretch, not a whole run.** A run that waits for a person
  ends its span with `gvn.status = waiting`. When the answer is delivered, possibly days
  later in another process, a new run span opens. Link them by `gvn.actor`.
- **Workflows nest by origin.** Signals of a [workflow](../concepts/workflows.md) name the
  workflow as their actor, so the whole tree shares one run span. Each child's requests are
  child spans with `gvn.request.origin` naming the child, such as `report/researching.1.0`,
  and their `chat` and `execute_tool` spans carry that child as `gen_ai.agent.name`, so the
  trace shows which agent made each call.
- **Payload contents are never recorded.** Not prompts, not answers, not tool arguments or
  results. Spans carry names, counts and identifiers only. Deltas are counted on the request's span, not recorded one by one.
- **Times come from the Clock.** Span start and end times are the Governor's Clock readings,
  so under `ManualClock` they are all the same; under `SystemClock` (the clock that reads
  real time) they are real.
- **It holds only open spans.** `open_spans()` says how many; after a call returns, it is 0
  for that actor.

## Step 4: the user's stream

`StreamOutput` is an output you iterate with `async for` while the run is in flight: the
stream you forward to a browser or a terminal. `emit` never blocks (the buffer is
unbounded), and iteration ends after `close()` once the buffer is drained. Create it and
consume it on one event loop, and close it when the call returns, even on failure:

```python
from gvn.runtime.outputs import StreamOutput


async def answer_as_it_is_written() -> list[str]:
    stream = StreamOutput()
    governor = searching_governor(stream)

    async def drive() -> Result:
        try:
            return await governor.deliver(actor=helper(), event=QUESTION)
        finally:
            stream.close()

    driving = asyncio.create_task(drive())
    shown = [signal.data()["text"] async for signal in stream if signal.kind() == "delta"]
    await driving
    return shown


print(asyncio.run(answer_as_it_is_written()))  # ['Three ', 'hits.']
```

A user interface usually wants `delta` signals (text as it is written), `waiting` (the run
needs someone) and `finished` (the answer). In a workflow, a delta's `request` field starts
with the child's name, so you can tell which agent is writing.

## Step 5: all three at once

`Fanout` sends every signal to several outputs, in order. If one raises, the others still
receive the signal, and the Governor counts the error (`governor.output_errors()`) without
stopping the run:

```python
from gvn.runtime.outputs import Fanout

exporter.clear()
buffer = io.StringIO()
handler = logging.StreamHandler(buffer)
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)

recorded = RecordingOutput()
tracing = TracingOutput(tracer=provider.get_tracer("docs"))
run(Fanout(outputs=[LoggingOutput(logger=logger), tracing, recorded]))
print(len(buffer.getvalue().splitlines()), len(exporter.get_finished_spans()), recorded.text())
# 10 6 Three hits.
logger.removeHandler(handler)
```

`StreamOutput` fits in the same `Fanout`; it is left out here only because it needs a
consumer running alongside the call.

## Step 6: counting tokens as they are spent

The `event` signal of a `model_replied` carries `"usage"`, the tokens that model call
reported, as four figures: `input_tokens` (every input token, cached or not), `output_tokens`, and
`cache_read_tokens` and `cache_write_tokens`, the parts of `input_tokens` read from and written to the vendor's
prompt cache (see [usage](vendors.md#what-a-call-cost-usage)). An output can total them live,
per actor, for a budget alarm or a dashboard:

```python
from gvn.harness.ports import Signal


class Tokens(Output):
    def __init__(self) -> None:
        self._spent = {}

    def emit(self, signal: Signal) -> None:
        usage = signal.data().get("usage") if signal.kind() == "event" else None
        if usage:
            spent = self._spent.setdefault(signal.actor(), dict.fromkeys(usage, 0))
            for figure, count in usage.items():
                spent[figure] += count

    def spent(self) -> dict[str, dict[str, int]]:
        return {actor: dict(totals) for actor, totals in self._spent.items()}


tokens = Tokens()
priced_reply = Reply(
    message=Message.assistant(text="Three hits."),
    input_tokens=900,
    output_tokens=12,
    cache_read_tokens=800,
)
priced_model = ScriptedModel(script=[priced_reply])
counting_governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=priced_model, toolbox=Toolbox())},
    journal=MemoryJournal(),
    output=tokens,
    clock=ManualClock(),
)
plain_helper = Agent(name="helper", instructions="Be brief.")  # no tools this time
asyncio.run(counting_governor.deliver(actor=plain_helper, event=QUESTION))
print(tokens.spent())
# {'helper': {'input_tokens': 900, 'output_tokens': 12, 'cache_read_tokens': 800, 'cache_write_tokens': 0}}
```

The `event` signal of a `model_failed` carries `"usage"` too when the vendor reported what the
failed call spent. When a `ModelFulfiller` retried before answering, the signal of either
event also carries `"retries"`, one entry per attempt it gave up on, each with its own
`"usage"` when known; the `Tokens` output above does not add those. And a reply whose message
cites sources carries `"citations"`.

Four more fields of signal data serve observers. An `event` that answers a model call carries
`"model"` and `"provider"` when the answer names them. An `event` carries `"by"`, the
`subject` and `issuer` of the principal, when the event says who it came from
([Trust](../concepts/trust.md)). The `request` signal of `invoke_tools` carries `"tools"`: one
entry per call that will run, with its `call_id`, short `name` and `identity`. Under an
[allowance](spending-and-rate-limits.md) (a threshold of tokens, model calls or cost given
to the Governor), `waiting` and `finished` carry `"spent"` (the tokens and calls so far, and
`"cost"` when the allowance has rates) and, when the run has reached its allowance (its
tally is at or above one of the allowance's thresholds), `"overspent"`. `TracingOutput`
turns these into the span names and attributes above.

The journal keeps the same figures, so a recorded run can be totalled afterwards with
`Trace.usage()` (see [Replay and evaluation](replay-and-evaluation.md#what-the-runs-cost)),
which counts failed calls and retried attempts too. Calls cancelled before their answer was
journaled are in neither.

## Writing your own output

`Output` has one method, `emit(signal)`. It is synchronous and must return promptly: it is
called on the Governor's event loop, between steps. Anything slow (a network exporter, a
database) belongs behind a buffer that a task of your own drains, which is what the
OpenTelemetry batch span processor does for traces. An output that raises cannot break a
run, but its error is only counted, so test it: `gvn.testing.contracts.OutputContract` is a
ready-made set of tests (a contract suite) that every output in gvn passes, and that you can
run against yours (see [Testing your harness](../concepts/testing.md)).

## Running it safely

- **Decide what your logs keep.** `finished` records carry the final answer, and `delta`
  records at `DEBUG` carry every fragment. Choose what your log pipeline may keep before you
  turn `DEBUG` on. Traces never record payload contents.
- **Close a stream.** A `StreamOutput` ends only after `close()`. Close it in a `finally`, as
  step 4 does, so a consumer is released when the run fails.
- **Keep `emit` quick.** `emit` runs on the Governor's event loop, so put a network call
  behind a buffer.
- **Watch `governor.output_errors()`.** An output that raises does not stop the run; its
  errors are counted there, so read the count.

## Recap

- One port, `Output`, sees everything a run does; a Governor takes exactly one.
- `LoggingOutput` and `JsonFormatter` give logs, `TracingOutput` gives OpenTelemetry spans,
  `StreamOutput` gives the user's live stream, and `Fanout` sends to several at once.
- `model_replied` events carry token usage, so an output can count spending live.

## Next

Choose by what you need now:

- **A limit on what a run spends.** [Spending and rate limits](spending-and-rate-limits.md)
  gives the Governor an allowance, whose figures the signals above carry.
- **A finished run, read back.** [Inspecting a run](inspecting-a-run.md) reads a recorded
  run moment by moment from its journal, and
  [Replay and evaluation](replay-and-evaluation.md) grades it.
- **The same outputs in a service.** [Running as a service](running-as-a-service.md) shares
  runs between processes.
