telemetry

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package telemetry is Tacklr's OpenTelemetry instrumentation: spans, metrics and log events on the process-wide OpenTelemetry providers, and the Carrier that takes a turn's trace across what a context cannot (a wake, a durable step, a journal, an HTTP request). A turn is one trace from the client's request to the answer (docs/telemetry.md). It depends only on the OpenTelemetry API, so it builds anywhere the harness does. Package telemetry/export installs the SDK providers and exporters (OTLP, Prometheus) a host process sends them to.

Span starters, Instruments.Record*, attribute constants, and EmitEvent are for the harness and the session package. Hosts must not start tacklr spans or record harness metrics; that can break traces and double-count metrics.

Index

Constants

View Source
const (
	OperationInvokeAgent = "invoke_agent"
	OperationChat        = "chat"
	OperationExecuteTool = "execute_tool"
)

GenAI operation names (gen_ai.operation.name), which name their spans.

View Source
const (
	AttrGenAIOperationName    = "gen_ai.operation.name"
	AttrGenAIProviderName     = "gen_ai.provider.name"
	AttrGenAIRequestModel     = "gen_ai.request.model"
	AttrGenAIAgentName        = "gen_ai.agent.name"
	AttrGenAIConversationID   = "gen_ai.conversation.id"
	AttrGenAIToolName         = "gen_ai.tool.name"
	AttrGenAIToolCallID       = "gen_ai.tool.call.id"
	AttrGenAIToolType         = "gen_ai.tool.type"
	AttrGenAITokenType        = "gen_ai.token.type"
	AttrGenAIInputTokens      = "gen_ai.usage.input_tokens"
	AttrGenAIOutputTokens     = "gen_ai.usage.output_tokens"
	AttrGenAICachedTokens     = "gen_ai.usage.cached_tokens"
	AttrGenAICacheWriteTokens = "gen_ai.usage.cache_write_tokens"
	AttrErrorType             = "error.type"
	AttrHTTPStatus            = "http.response.status_code"

	AttrRPCSystem    = "rpc.system"
	AttrRPCMethod    = "rpc.method"
	AttrJSONRPCError = "rpc.jsonrpc.error_code"
)

Attribute keys of the OpenTelemetry semantic conventions. https://opentelemetry.io/docs/specs/semconv/gen-ai/ and .../rpc/

View Source
const (
	AttrTurnKind      = "tacklr.turn.kind" // prompt | resume | continue
	AttrRuntime       = "tacklr.runtime"   // temporal | durableobject
	AttrParentSession = "tacklr.session.parent"
	AttrToolNS        = "tacklr.tool.namespace"
	AttrModelPhase    = "tacklr.model.phase" // turn | handoff | compress
	AttrInterruptKind = "tacklr.interrupt.kind"
	AttrOutcome       = "tacklr.outcome"
	AttrErrorCode     = "tacklr.error.code" // the provider's error code
	AttrStopReason    = "tacklr.stop_reason"
)

Tacklr's own attribute keys (static identifiers and closed enums).

View Source
const (
	RuntimeTemporal      = "temporal"
	RuntimeDurableObject = "durableobject"
)

Runtime values for AttrRuntime (closed enum).

View Source
const (
	ModelPhaseTurn     = "turn"
	ModelPhaseHandoff  = "handoff"
	ModelPhaseCompress = "compress"
)

Model phase values for AttrModelPhase (closed enum).

View Source
const (
	GenAIProviderAnthropic = "anthropic"
	GenAIProviderAzure     = "azure.openai"
	GenAIProviderOpenAI    = "openai"
	GenAIProviderUnknown   = "unknown"
)

GenAI provider values (closed enum).

View Source
const (
	ToolTypeFunction  = "function"
	ToolTypeExtension = "extension"
)

GenAI tool types (gen_ai.tool.type): a host's function, or a tool an MCP server provides.

View Source
const (
	ErrorClassOK          = "ok"
	ErrorClassProvider4xx = "provider_4xx"
	ErrorClassProvider5xx = "provider_5xx"
	ErrorClassMaxTokens   = "max_tokens"
	ErrorClassCancelled   = "cancelled"
	ErrorClassTimeout     = "timeout"
	ErrorClassOther       = "other"
)

Error class buckets for error.type (closed enum).

View Source
const (
	HandoffOutcomeOK       = "ok"
	HandoffOutcomeFallback = "fallback"
	HandoffOutcomeError    = "error"
)

Handoff outcome values.

View Source
const (
	EventModelRequest   = "gen_ai.request"
	EventProviderFailed = "provider.failed"
	EventToolFailed     = "tool.failed"
	EventPlanInstalled  = "plan.installed"
	EventTurnStarted    = "turn.started"
	EventTurnEnded      = "turn.ended"
	EventFuseMount      = "vfs.fuse.mount"
	EventFuseUnmount    = "vfs.fuse.unmount"
)

Log event names (OTel Logs Record.SetEventName): what happened within an operation, with its dynamic values as attributes.

View Source
const (
	EventAttrOutcome      = "outcome"
	EventAttrInputItems   = "input_items"
	EventAttrMessages     = "context.messages"
	EventAttrToolPairs    = "context.tool_pairs"
	EventAttrAfterTools   = "after_tools"
	EventAttrSeq          = "seq"
	EventAttrPromptLength = "prompt.length"
	EventAttrResumes      = "resumes"
	EventAttrTodos        = "todos"
	EventAttrOpenTodos    = "todos.open"
	EventAttrError        = "error"
)

Attribute keys on log events (dynamic values).

View Source
const (
	AreaRuntime    = "runtime"
	AreaHarness    = "harness"
	AreaModelTasks = "model_tasks"
	AreaContext    = "context"
)

Area values for the "area" field of Tacklr's slog records: which part of Tacklr logged it.

View Source
const (
	OutcomeOK        = "ok"
	OutcomeError     = "error"
	OutcomeCancelled = "cancelled"
	OutcomeYield     = "yield"
)

Outcome values for AttrOutcome / EventAttrOutcome.

View Source
const (
	MetricTurnDuration    = "tacklr.turn.duration"
	MetricTurnTotal       = "tacklr.turn.total"
	MetricTurnActive      = "tacklr.turn.active"
	MetricToolCalls       = "tacklr.tool.calls"
	MetricToolDuration    = "tacklr.tool.duration"
	MetricInterruptTotal  = "tacklr.interrupt.total"
	MetricHandoffTotal    = "tacklr.context.handoff.total"
	MetricCompressTotal   = "tacklr.context.compress.total"
	MetricSessionCreated  = "tacklr.session.created.total"
	MetricCheckpointSave  = "tacklr.checkpoint.save.total"
	MetricFuseMount       = "tacklr.fuse.mount.total"
	MetricConnections     = "tacklr.server.connections"
	MetricModelDuration   = "gen_ai.client.operation.duration"
	MetricTokenUsage      = "gen_ai.client.token.usage"
	MetricRPCCallDuration = "rpc.server.call.duration"
)

Metric names. The model's and the protocol server's are the semantic conventions' (gen_ai.client.*, rpc.server.*); the rest are Tacklr's. Prometheus export writes '.' as '_'.

View Source
const (
	LabelAgent      = AttrGenAIAgentName
	LabelTurnKind   = AttrTurnKind
	LabelOutcome    = "outcome"
	LabelTool       = AttrGenAIToolName
	LabelToolNS     = AttrToolNS
	LabelStatus     = "status"
	LabelKind       = "kind" // interrupt kind
	LabelModelPhase = AttrModelPhase
	LabelErrorType  = AttrErrorType
	LabelProtocol   = "protocol"
)

Label keys: closed enums and configuration ids only, never free text or a session id.

View Source
const (
	FuseMountOutcomeOK    = "ok"
	FuseMountOutcomeError = "error"
)

Fuse mount outcomes for RecordFuseMount (closed enum).

View Source
const InstrumentationName = "github.com/ryanaldo34/tacklr"

InstrumentationName is the OpenTelemetry instrumentation scope for Tacklr.

View Source
const RPCSystemJSONRPC = "jsonrpc"

RPC system of a protocol (rpc.system).

View Source
const (
	SpanHandoff = "tacklr.context.handoff"
)

Span names. A turn is one trace, from the client's request to the answer, across every process and runtime it touches:

session/prompt                SERVER   the protocol request (rpc.*)
  invoke_agent {agent}        INTERNAL the turn (gen_ai.* invoke_agent)
    chat {model}              CLIENT   one model request (gen_ai.* chat)
    execute_tool {tool}       INTERNAL one tool call (gen_ai.* execute_tool)
    tacklr.context.handoff    INTERNAL a plan handoff, with its model request
    invoke_agent {specialist} INTERNAL a child session's turn
  session/request_permission  CLIENT   a question the agent asks the client

The span names of the turn, the model request and the tool call are the OpenTelemetry GenAI semantic conventions'; the protocol request's are the RPC conventions' (rpc.system jsonrpc). Each name is the operation and its static target, so names stay few.

Attributes on spans are static and searchable: identifiers, closed enums, and the outcome and error.type set at the end. Values that change within an operation or are free text (lengths, counts, error messages, answers) go on span-correlated logs (EmitEvent, slog with the context), never on spans. Metric labels are closed enums and configuration ids only: never a session id.

Variables

This section is empty.

Functions

func AgentFromContext added in v0.5.0

func AgentFromContext(ctx context.Context) string

AgentFromContext is the agent's name, or "".

func ClassifyErrorClass added in v0.2.0

func ClassifyErrorClass(err error, httpStatus int) string

ClassifyErrorClass buckets err into a closed error.class enum.

func ContextWithAfterTools

func ContextWithAfterTools(ctx context.Context) context.Context

ContextWithAfterTools marks the next model request as the one after a reply's tool calls.

func ContextWithAgent added in v0.5.0

func ContextWithAgent(ctx context.Context, agent string) context.Context

ContextWithAgent attaches the agent's name.

func ContextWithModelIdentity

func ContextWithModelIdentity(ctx context.Context, id ModelIdentity) context.Context

ContextWithModelIdentity attaches the model's identity for its spans.

func ContextWithSessionID added in v0.2.0

func ContextWithSessionID(ctx context.Context, sessionID string) context.Context

ContextWithSessionID attaches the session id (gen_ai.conversation.id).

func EmitEvent

func EmitEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)

EmitEvent emits an OTel log record with EventName set (span-correlated). Severity defaults to Info; use EmitEventSeverity for errors.

func EmitEventSeverity

func EmitEventSeverity(ctx context.Context, name string, severity log.Severity, attrs ...attribute.KeyValue)

EmitEventSeverity is EmitEvent with an explicit severity.

func FromHeaders added in v0.5.0

func FromHeaders(ctx context.Context, h http.Header) context.Context

FromHeaders is ctx with the trace context of an incoming request's headers, for a server that continues the trace of its caller.

func Logger

func Logger() log.Logger

Logger returns the package Logger from the global LoggerProvider (noop-safe).

func Meter

func Meter() metric.Meter

Meter returns a Tacklr-scoped Meter from the global MeterProvider.

func PlanInstalled added in v0.5.0

func PlanInstalled(ctx context.Context, todos, open int, err error)

PlanInstalled logs the install of a plan document into the window, with how many todos it has and how many are open.

func RecordCheckpointAttempt added in v0.2.0

func RecordCheckpointAttempt(ctx context.Context, err error)

RecordCheckpointAttempt records one harness snapshot persist (ok or error).

func SessionIDFromContext added in v0.2.0

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext returns the session id or "".

func SetMeterProvider

func SetMeterProvider(mp metric.MeterProvider)

SetMeterProvider installs mp as the process-wide MeterProvider and rebuilds the cached global Instruments so later Init/SetMeterProvider calls take effect. Hosts usually get this from export.Init (package telemetry/export). Pass nil for noop.

func SetTracerProvider

func SetTracerProvider(tp trace.TracerProvider)

SetTracerProvider installs tp as the process-wide TracerProvider.

func Step added in v0.5.0

func Step(ctx context.Context, turn Carrier, agent, sessionID string) context.Context

Step is the context one step of a turn runs in: the turn's span (from turn, the context its runtime recorded), the session and its agent, so the step's spans are children of the turn's span and carry the session.

func Tracer

func Tracer() trace.Tracer

Tracer is otel.Tracer(InstrumentationName) on the process-wide provider.

func Transport added in v0.5.0

func Transport(base http.RoundTripper) http.RoundTripper

Transport sends each request with its context's trace context in its headers (W3C traceparent), so the system it reaches (a model provider or a gateway before one, an MCP server) continues the trace. It starts no span: the operation's own span (chat, execute_tool) is the client span. A nil base is http.DefaultTransport.

func TurnStarted added in v0.5.0

func TurnStarted(ctx context.Context, promptLen, resumes int)

TurnStarted logs a turn's start with its dynamic values: the prompt's length and how many answers it resumed with.

Types

type Carrier added in v0.5.0

type Carrier map[string]string

Carrier is a trace context (W3C traceparent, tracestate and baggage) as plain data: how a turn's trace crosses what a context cannot, such as a wake to a session, a step of a durable runtime, a journal, or a message between objects. It is nil when there is no trace.

func Inject added in v0.5.0

func Inject(ctx context.Context) Carrier

Inject is ctx's trace context as a Carrier, by the process-wide propagator (export.Init installs W3C trace context and baggage). It is nil when ctx has no span.

func (Carrier) Context added in v0.5.0

func (c Carrier) Context(ctx context.Context) context.Context

Context is ctx with c's trace context: a span started from it is a child of the span c carries. With no trace in c it is ctx.

func (c Carrier) Link() (trace.Link, bool)

Link is a link to the span c carries, for a span that follows from it without being its child; ok is false when c carries none.

type HandoffSpan

type HandoffSpan struct {
	// contains filtered or unexported fields
}

HandoffSpan is an in-flight tacklr.context.handoff span. Call End once.

func StartHandoffSpan

func StartHandoffSpan(ctx context.Context, openTodos int) (context.Context, *HandoffSpan)

StartHandoffSpan starts a context-handoff span: the model request that writes the handoff is its child. openTodos goes on its log.

func (*HandoffSpan) End

func (s *HandoffSpan) End(outcome string, err error)

End ends the handoff span and records the handoff metric. outcome is HandoffOutcomeOK, HandoffOutcomeFallback, or HandoffOutcomeError.

type Instruments

type Instruments struct {
	// contains filtered or unexported fields
}

Instruments holds cached metric instruments for one Meter.

func Metrics added in v0.5.0

func Metrics() *Instruments

Metrics is Tacklr's metric instruments on the process-wide MeterProvider (SetMeterProvider rebuilds them).

func MustInstruments

func MustInstruments(m metric.Meter) *Instruments

MustInstruments builds instruments from m. Names are constants; the SDK only errors on invalid names, which would be a compile-time programmer error.

func (*Instruments) RecordCheckpointSave

func (i *Instruments) RecordCheckpointSave(ctx context.Context, outcome string)

RecordCheckpointSave counts a checkpoint save by outcome.

func (*Instruments) RecordCompress

func (i *Instruments) RecordCompress(ctx context.Context, agent string)

RecordCompress counts a collapse of the context window.

func (*Instruments) RecordConnection added in v0.5.0

func (i *Instruments) RecordConnection(ctx context.Context, protocol string, delta int64)

RecordConnection adds delta (1 or -1) to the open connections of protocol.

func (*Instruments) RecordFuseMount added in v0.2.0

func (i *Instruments) RecordFuseMount(ctx context.Context, outcome string)

RecordFuseMount increments tacklr.fuse.mount.total{outcome=...}.

func (*Instruments) RecordInterrupt

func (i *Instruments) RecordInterrupt(ctx context.Context, agent, kind string)

RecordInterrupt counts a park of a tool call on an interrupt of kind.

func (*Instruments) RecordSessionCreated

func (i *Instruments) RecordSessionCreated(ctx context.Context)

RecordSessionCreated counts a session a protocol server created.

type ModelIdentity

type ModelIdentity struct {
	// Provider is a closed enum: anthropic | azure.openai | openai | unknown.
	Provider string
	// Model is the deployment or model id (configuration, low cardinality).
	Model string
}

ModelIdentity is the static identity of a model's requests.

func NewModelIdentity

func NewModelIdentity(model, baseURL string) ModelIdentity

NewModelIdentity builds GenAI identity from deployment config (model id + API base URL).

type ModelSpan

type ModelSpan struct {
	// contains filtered or unexported fields
}

ModelSpan is an in-flight chat span. Call End once.

func StartModelSpan

func StartModelSpan(ctx context.Context, phase string, seq int, shape WindowShape) (context.Context, *ModelSpan)

StartModelSpan starts the chat span of one model request (the GenAI semantic conventions' client span, chat {model}), and logs the request's dynamic shape: its sequence in the session, the window it sends, and whether it follows a reply's tool calls.

func (*ModelSpan) End

func (m *ModelSpan) End(err error, usage TokenUsage)

End ends the chat span with its outcome and, on failure, error.type (a closed class), the provider's HTTP status and error code; it records the provider-reported usage on the span and in the GenAI metrics.

type ProviderStatus added in v0.5.0

type ProviderStatus interface {
	ProviderHTTPStatus() int
	ProviderErrorCode() string
}

ProviderStatus is HTTP metadata a provider error may carry. A model span reads it with errors.As when the request fails.

type RPCSpan added in v0.5.0

type RPCSpan struct {
	// contains filtered or unexported fields
}

RPCSpan is a protocol request's span (the RPC semantic conventions, rpc.system jsonrpc): a request the server answers (SERVER), or one it sends the client (CLIENT), such as a permission it asks. End it once, when the response is sent or received.

func StartRPC added in v0.5.0

func StartRPC(ctx context.Context, kind trace.SpanKind, method, session string, extra ...attribute.KeyValue) (context.Context, *RPCSpan)

StartRPC starts the span of a protocol request named by its method. A server request's parent is the client's trace context in ctx (its _meta.traceparent, or the connection's); session is the request's session (gen_ai.conversation.id), when it names one.

func (*RPCSpan) Context added in v0.5.0

func (s *RPCSpan) Context() context.Context

Context is the span's context: a span of the work the request does is its child.

func (*RPCSpan) End added in v0.5.0

func (s *RPCSpan) End(code int, stop string)

End ends the request's span. code is the JSON-RPC error code of an error response (zero for a result); stop is a prompt's stop reason, when it has one. A server request records its duration.

type TokenUsage

type TokenUsage struct {
	Input      int
	Output     int
	Reasoning  int
	Cached     int
	CacheWrite int
}

TokenUsage is provider-reported token consumption for one model invoke.

type Tool added in v0.5.0

type Tool struct {
	Name      string
	Namespace string
	// CallID is the model's id of the call (gen_ai.tool.call.id), to find
	// the span of one call.
	CallID string
	// Type is ToolTypeFunction for a host's tool, ToolTypeExtension for an
	// MCP server's.
	Type string
}

Tool is the static identity of one tool call's span.

type ToolSpan

type ToolSpan struct {
	// contains filtered or unexported fields
}

ToolSpan is an in-flight execute_tool span. Call Finish once.

func StartToolSpan

func StartToolSpan(ctx context.Context, t Tool) (context.Context, *ToolSpan)

StartToolSpan starts the execute_tool span of one tool call.

func (*ToolSpan) Finish

func (t *ToolSpan) Finish(status string, err error)

Finish ends the tool span with status (success, error, interrupt) and counts the call. A failure's text goes to the span's tool.failed log.

type Turn added in v0.5.0

type Turn struct {
	Agent   string
	Session string
	// Parent is the parent session of a child session.
	Parent string
	// Kind is prompt, resume or continue (a turn a runtime restarted).
	Kind    string
	Runtime string
}

Turn is the static identity of one turn's span: invoke_agent of the session's agent (a specialist's name for a specialist session).

type TurnSpan

type TurnSpan struct {
	// contains filtered or unexported fields
}

TurnSpan is a turn's running invoke_agent span. End it once.

func StartTurn added in v0.5.0

func StartTurn(ctx context.Context, t Turn, links ...Carrier) (context.Context, *TurnSpan)

StartTurn starts a turn's span as a child of the span in ctx (the client's request, or the parent session's turn), with a link to each span of links (the request that resumed it), and counts it as running. A durable runtime starts it once for each turn it runs, and records the span's context (Inject) so a replay of the turn reuses it without starting another.

func (*TurnSpan) End

func (s *TurnSpan) End(outcome string, err error)

End ends the turn's span with outcome (ok, error, cancelled, yield) and the error that ended it, and counts the turn by its outcome.

type WindowShape

type WindowShape struct {
	Messages  int
	ToolPairs int
}

WindowShape is a snapshot of the context window a model request sends. It changes with each request, so its model.request log carries it.

Directories

Path Synopsis
Package export installs the OpenTelemetry SDK providers a Tacklr host process sends its telemetry to: OTLP traces, metrics and logs (Init), or a Prometheus scrape (PrometheusMeterProvider).
Package export installs the OpenTelemetry SDK providers a Tacklr host process sends its telemetry to: OTLP traces, metrics and logs (Init), or a Prometheus scrape (PrometheusMeterProvider).
Package otlpjson sends spans to an OTLP/HTTP endpoint in OTLP's JSON encoding (POST {endpoint}/v1/traces, application/json), over net/http alone.
Package otlpjson sends spans to an OTLP/HTTP endpoint in OTLP's JSON encoding (POST {endpoint}/v1/traces, application/json), over net/http alone.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL