trace

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package trace provides distributed tracing support. This is a lightweight stub for future OpenTelemetry integration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EndSpanWithError

func EndSpanWithError(span *Span, err error)

EndSpanWithError finishes a span and marks it as errored if err is non-nil.

Types

type OTelProviders

type OTelProviders struct{}

OTelProviders is a no-op stub when built without the otel tag.

func InitOTelSDK

func InitOTelSDK(cfg TelemetryConfig) (*OTelProviders, error)

InitOTelSDK returns a no-op provider set.

func (*OTelProviders) FlushOTel

func (p *OTelProviders) FlushOTel(ctx context.Context) error

func (*OTelProviders) OTelTracer

func (p *OTelProviders) OTelTracer() interface{}

func (*OTelProviders) RecordMetric

func (p *OTelProviders) RecordMetric(name string, value int64, attrs ...interface{})

func (*OTelProviders) ShutdownOTel

func (p *OTelProviders) ShutdownOTel(ctx context.Context) error

func (*OTelProviders) StartOTelSpan

func (p *OTelProviders) StartOTelSpan(ctx context.Context, name string, attrs ...interface{}) (context.Context, interface{})

type Providers

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

Providers holds the initialized telemetry providers.

func InitTelemetry

func InitTelemetry(cfg TelemetryConfig) (*Providers, error)

InitTelemetry initializes telemetry based on configuration. When OTel SDK is available (future), this will create real OTLP exporters. Currently uses the built-in Tracer as a lightweight fallback.

func (*Providers) Flush

func (p *Providers) Flush(ctx context.Context) error

Flush forces export of pending telemetry data.

func (*Providers) IsEnabled

func (p *Providers) IsEnabled() bool

IsEnabled returns whether telemetry is active.

func (*Providers) Shutdown

func (p *Providers) Shutdown(ctx context.Context) error

Shutdown flushes and shuts down all telemetry providers.

func (*Providers) Tracer

func (p *Providers) Tracer() *Tracer

Tracer returns the active tracer.

type SessionSpan

type SessionSpan struct {
	ID         string            `json:"id"`
	ParentID   string            `json:"parent_id,omitempty"`
	Name       string            `json:"name"`
	StartTime  time.Time         `json:"start_time"`
	EndTime    time.Time         `json:"end_time,omitempty"`
	Duration   time.Duration     `json:"duration,omitempty"`
	Status     SpanStatus        `json:"status"`
	Attributes map[string]string `json:"attributes,omitempty"`
	Children   []*SessionSpan    `json:"children,omitempty"`
}

SessionSpan represents a single operation within a session trace tree. It forms a tree structure via the Children slice, with ParentID linking back to the parent span.

type SessionTrace

type SessionTrace struct {
	SessionID string       `json:"session_id"`
	StartTime time.Time    `json:"start_time"`
	Root      *SessionSpan `json:"root"`
	// contains filtered or unexported fields
}

SessionTrace groups all operations in a session into a parent-child hierarchy, inspired by Helicone's session-level trace trees.

func NewSessionTrace

func NewSessionTrace(sessionID string) *SessionTrace

NewSessionTrace creates a new trace for a session. It initializes a root span that represents the entire session.

func (*SessionTrace) CurrentSpanID

func (st *SessionTrace) CurrentSpanID() string

CurrentSpanID returns the ID of the currently active span.

func (*SessionTrace) EndSpan

func (st *SessionTrace) EndSpan(spanID string, status SpanStatus)

EndSpan completes the span identified by spanID and returns the current active span to its parent. If spanID does not match the current active span, the span is still ended but the active span pointer is only adjusted if it matches.

func (*SessionTrace) FormatTree

func (st *SessionTrace) FormatTree() string

FormatTree renders the trace as an indented tree string using box-drawing characters, similar to the `tree` command output.

func (*SessionTrace) GetSpan

func (st *SessionTrace) GetSpan(spanID string) *SessionSpan

GetSpan retrieves a span by ID. Returns nil if not found.

func (*SessionTrace) StartSpan

func (st *SessionTrace) StartSpan(name string, attrs map[string]string) string

StartSpan begins a new span as a child of the current active span. It returns the new span's ID. The new span becomes the current active span, forming a stack-like push behavior.

func (*SessionTrace) Summary

func (st *SessionTrace) Summary() TraceSummary

Summary returns aggregate statistics for the session trace by walking all spans and parsing their attributes for token counts and cost.

func (*SessionTrace) ToJSON

func (st *SessionTrace) ToJSON() ([]byte, error)

ToJSON exports the full session trace as JSON for external tools such as Jaeger, Grafana, or custom dashboards.

type Span

type Span struct {
	Name      string            `json:"name"`
	TraceID   string            `json:"trace_id"`
	SpanID    string            `json:"span_id"`
	ParentID  string            `json:"parent_id,omitempty"`
	StartTime time.Time         `json:"start_time"`
	EndTime   time.Time         `json:"end_time,omitempty"`
	Tags      map[string]string `json:"tags,omitempty"`
	Events    []SpanEvent       `json:"events,omitempty"`
}

Span represents a trace span.

func SpanFromContext

func SpanFromContext(ctx context.Context) (*Span, bool)

SpanFromContext retrieves a span from context.

func StartAPICallSpan

func StartAPICallSpan(ctx context.Context, t *Tracer, provider, model string) (context.Context, *Span)

StartAPICallSpan creates a span for an LLM API call.

func StartAgentLoopSpan

func StartAgentLoopSpan(ctx context.Context, t *Tracer, provider, model string, messageCount int) (context.Context, *Span)

StartAgentLoopSpan creates a span for the agent loop iteration.

func StartCompactSpan

func StartCompactSpan(ctx context.Context, t *Tracer, strategy string, tokensBefore int) (context.Context, *Span)

StartCompactSpan creates a span for a compaction operation.

func StartSessionSpan

func StartSessionSpan(ctx context.Context, t *Tracer, sessionID string) (context.Context, *Span)

StartSessionSpan creates a span for a full session.

func StartToolSpan

func StartToolSpan(ctx context.Context, t *Tracer, toolName, toolID string) (context.Context, *Span)

StartToolSpan creates a span for a tool execution.

func (*Span) AddEvent

func (s *Span) AddEvent(name string, tags map[string]string)

AddEvent adds an event to the span.

func (*Span) Duration

func (s *Span) Duration() time.Duration

Duration returns the span duration.

func (*Span) Finish

func (s *Span) Finish()

Finish finishes a span.

func (*Span) SetTag

func (s *Span) SetTag(key, value string)

SetTag sets a tag on the span.

type SpanEvent

type SpanEvent struct {
	Name      string            `json:"name"`
	Timestamp time.Time         `json:"timestamp"`
	Tags      map[string]string `json:"tags,omitempty"`
}

SpanEvent represents an event within a span.

type SpanStatus

type SpanStatus int

SpanStatus represents the outcome of a span.

const (
	// SpanOK indicates the span completed successfully.
	SpanOK SpanStatus = iota
	// SpanError indicates the span completed with an error.
	SpanError
)

func (SpanStatus) MarshalJSON

func (s SpanStatus) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for SpanStatus.

func (SpanStatus) String

func (s SpanStatus) String() string

String returns a human-readable representation of the SpanStatus.

func (*SpanStatus) UnmarshalJSON

func (s *SpanStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for SpanStatus.

type TelemetryConfig

type TelemetryConfig struct {
	Enabled         bool
	ServiceName     string
	ServiceVersion  string
	ExporterProto   string
	Endpoint        string
	Headers         map[string]string
	MetricsInterval time.Duration
	TracesInterval  time.Duration
	LogsInterval    time.Duration
	ShutdownTimeout time.Duration
}

TelemetryConfig controls OpenTelemetry initialization.

func DefaultTelemetryConfig

func DefaultTelemetryConfig() TelemetryConfig

DefaultTelemetryConfig returns a config populated from environment variables.

type TraceSummary

type TraceSummary struct {
	TotalDuration  time.Duration `json:"total_duration"`
	LLMCalls       int           `json:"llm_calls"`
	ToolCalls      int           `json:"tool_calls"`
	TotalTokensIn  int           `json:"total_tokens_in"`
	TotalTokensOut int           `json:"total_tokens_out"`
	TotalCostUSD   float64       `json:"total_cost_usd"`
	Errors         int           `json:"errors"`
}

TraceSummary holds aggregate statistics for a session trace.

type Tracer

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

Tracer is a simple tracer.

func NewTracer

func NewTracer() *Tracer

NewTracer creates a new tracer.

func (*Tracer) Clear

func (t *Tracer) Clear()

Clear clears all spans.

func (*Tracer) Disable

func (t *Tracer) Disable()

Disable disables tracing.

func (*Tracer) Enable

func (t *Tracer) Enable()

Enable enables tracing.

func (*Tracer) IsEnabled

func (t *Tracer) IsEnabled() bool

IsEnabled returns whether tracing is enabled.

func (*Tracer) Spans

func (t *Tracer) Spans() []*Span

Spans returns all recorded spans.

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(ctx context.Context, name string) (context.Context, *Span)

StartSpan starts a new span.

Jump to

Keyboard shortcuts

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