telemetry

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Overview

Package telemetry owns the daemon's OpenTelemetry export and its privacy boundary: every exported span and metric is rebuilt from the registered names, attribute keys, and value policies below.

Index

Constants

View Source
const (
	ErrorCanceled         = "canceled"
	ErrorDeadlineExceeded = "deadline_exceeded"
	ErrorProvider         = "provider_error"
	ErrorPermissionDenied = "permission_denied"
	ErrorNotFound         = "not_found"
	ErrorInvalidInput     = "invalid_input"
	ErrorIO               = "io_error"
	ErrorInternal         = "internal"
)

Error classes reported by Classify, the only error description telemetry exports.

View Source
const (
	ScopeHTTP       = "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	ScopeSession    = "github.com/compozy/compozy/internal/session"
	ScopeACP        = "github.com/compozy/compozy/internal/acp"
	ScopeMCP        = "github.com/compozy/compozy/internal/mcp"
	ScopeTools      = "github.com/compozy/compozy/internal/tools"
	ScopeStore      = "github.com/compozy/compozy/internal/store"
	ScopeObserve    = "github.com/compozy/compozy/internal/observe"
	ScopeHooks      = "github.com/compozy/compozy/internal/hooks"
	ScopeLoop       = "github.com/compozy/compozy/internal/loop"
	ScopeAutomation = "github.com/compozy/compozy/internal/automation"
	ScopeScheduler  = "github.com/compozy/compozy/internal/scheduler"
)

Instrumentation scopes accepted by the sanitizing exporters. ScopeHTTP is the otelgin middleware scope shared by the HTTP and UDS servers.

View Source
const (
	SpanSessionTurn       = "session.turn"
	SpanACPProcessSpawn   = "acp.process.spawn"
	SpanACPPermissionWait = "acp.permission.wait"
	SpanMCPHostedCall     = "mcp.hosted.call"
	SpanToolExecute       = "tool.execute"
	SpanDBWrite           = "db.write"
	SpanHookDispatch      = "hook.dispatch"
	SpanLoopRun           = "loop.run"
	SpanAutomationRun     = "automation.run"
	SpanSchedulerTick     = "scheduler.tick"
)

Registered span names. ACP RPC spans are named "acp <method>" for a registered ACP method; HTTP spans are "<METHOD> <route template>" for a registered template, or "HTTP <METHOD>" when unmatched.

View Source
const (
	EventFirstToken = "first_token"
	EventRecovery   = "recovery"
)

Registered span event names; event attributes are never exported.

View Source
const (
	AttrProfileID      attribute.Key = "compozy.profile_id"
	AttrWorkspaceID    attribute.Key = "compozy.workspace_id"
	AttrSessionID      attribute.Key = "compozy.session_id"
	AttrTurnID         attribute.Key = "compozy.turn_id"
	AttrRunID          attribute.Key = "compozy.run_id"
	AttrLoopID         attribute.Key = "compozy.loop.id"
	AttrAutomationID   attribute.Key = "compozy.automation.id"
	AttrAgent          attribute.Key = "compozy.agent"
	AttrGenAISystem    attribute.Key = "gen_ai.system"
	AttrGenAIModel     attribute.Key = "gen_ai.request.model"
	AttrTool           attribute.Key = "compozy.tool"
	AttrToolRisk       attribute.Key = "compozy.tool.risk"
	AttrOutcome        attribute.Key = "compozy.outcome"
	AttrTokenType      attribute.Key = "compozy.token.type" // #nosec G101 -- attribute key, not a credential.
	AttrCostStatus     attribute.Key = "compozy.cost.status"
	AttrDBOperation    attribute.Key = "compozy.db.operation"
	AttrDBCoalesced    attribute.Key = "compozy.db.coalesced"
	AttrDBFlushes      attribute.Key = "compozy.db.flushes"
	AttrDBWriteMSTotal attribute.Key = "compozy.db.write_ms_total"
	AttrHookEvent      attribute.Key = "compozy.hook.event"
	AttrRPCSystem      attribute.Key = "rpc.system"
	AttrRPCMethod      attribute.Key = "rpc.method"
	AttrHTTPRoute      attribute.Key = "http.route"
	AttrHTTPMethod     attribute.Key = "http.request.method"
	AttrHTTPStatusCode attribute.Key = "http.response.status_code"
	AttrErrorType      attribute.Key = "error.type"
)

Registered attribute keys.

View Source
const (
	ValueOther   = "other"
	ValueCustom  = "custom"
	ValueInvalid = "invalid"
)

Values substituted by the per-key fallback policy.

View Source
const (
	OutcomeOK          = "ok"
	OutcomeError       = "error"
	OutcomeCancelled   = "cancelled" //nolint:misspell // Exported catalog spelling (_dx.md).
	OutcomeApproved    = "approved"
	OutcomeDenied      = "denied"
	OutcomeUnbound     = "unbound"
	OutcomeAfterRun    = "after_run"
	OutcomeSetupFailed = "setup_failed"
)

Registered AttrOutcome values.

View Source
const (
	TokenInput      = "input"
	TokenOutput     = "output"
	TokenCacheRead  = "cache_read"
	TokenCacheWrite = "cache_write"
)

Registered AttrTokenType values.

View Source
const (
	CostActual    = "actual"
	CostEstimated = "estimated"
)

Registered AttrCostStatus values: provider-reported and catalog-estimated USD amounts.

View Source
const (
	MetricSessionTurnDuration  = "compozy.session.turn.duration"
	MetricSessionTTFT          = "compozy.session.ttft"
	MetricACPRPCDuration       = "compozy.acp.rpc.duration"
	MetricToolCallDuration     = "compozy.tool.call.duration"
	MetricHTTPServerDuration   = "http.server.request.duration"
	MetricDBWriteDuration      = "compozy.db.write.duration"
	MetricDBWriteAdmissionWait = "compozy.db.write.admission_wait"
	MetricTokens               = "compozy.tokens" // #nosec G101 -- metric name, not a credential.
	MetricCost                 = "compozy.cost"
	MetricToolCalls            = "compozy.tool.calls"
	MetricPermissionRequests   = "compozy.permission.requests"
	MetricAgentErrors          = "compozy.agent.errors"
	MetricSessionActive        = "compozy.session.active"
	MetricAgentActive          = "compozy.agent.active"
	MetricUptime               = "compozy.uptime"
)

Registered metric instruments.

View Source
const RPCSystemJSONRPC = "jsonrpc"

RPCSystemJSONRPC is the only registered AttrRPCSystem value.

View Source
const UnknownName = "compozy.unknown"

UnknownName replaces unregistered span names and instrumentation scopes.

Variables

This section is empty.

Functions

func Classify

func Classify(err error) string

Classify maps err to one fixed class; it never returns error text. A nil error has no class.

func DurationHistogram

func DurationHistogram(ctx context.Context, scope, name string) (metric.Float64Histogram, bool)

DurationHistogram returns scope's global-meter histogram for the registered duration instrument name, and false when it does not record (export or metrics off), so callers build attributes only for a measurement that is kept.

func EndSpan

func EndSpan(span trace.Span, err error)

EndSpan ends span with compozy.outcome from err: canceled work gets OutcomeCancelled without an error status, any other error gets OutcomeError through MarkError, and no error gets OutcomeOK.

func ExportRequested

func ExportRequested(cfg config.ObservabilityConfig) bool

ExportRequested reports whether cfg asks Init to start export, which may still come up degraded.

func MarkError

func MarkError(span trace.Span, err error)

MarkError records err on span as status Error with an empty description and error.type from Classify. Instrumentation uses it instead of RecordError or a status description. A span that is not recording (export disabled or unsampled) skips classification.

func Meter

func Meter(scope string) metric.Meter

Meter returns the global meter for an instrumentation scope (one of the Scope constants).

func MeterProvider

func MeterProvider() metric.MeterProvider

MeterProvider returns a provider whose float histograms record through the global provider installed at that moment, so the HTTP and UDS middleware, built before Init, follows the provider Init installs. Its other instruments are no-ops: the middleware's only registered instrument is http.server.request.duration.

func ModelLabel

func ModelLabel(provider, model string) string

ModelLabel is the gen_ai.request.model value a metric records: the catalog name, "custom", or "other". Metrics classify when they record, not when they export, so a series keeps one label for its lifetime: a cumulative series relabeled at export would look reset under its old label and double-counted under its new one.

func Outcome

func Outcome(err error) string

Outcome is the compozy.outcome of work that ended with err: canceled work is OutcomeCancelled, any other error OutcomeError, and no error OutcomeOK.

func Propagator

func Propagator() propagation.TextMapPropagator

Propagator extracts and injects only the W3C traceparent. An incoming tracestate is ignored, so it reaches no sampler, span, or outgoing request.

func ProviderError

func ProviderError(err error) error

ProviderError marks err as a provider failure for Classify without changing its text or chain.

func RecordDBWrite

func RecordDBWrite(ctx context.Context, write DBWrite, slowDBWriteMS int)

RecordDBWrite records write in the write histograms and, when writeSpanWanted holds for slowDBWriteMS, as a db.write span with the measured timestamps under ctx's span.

func TraceParent

func TraceParent(ctx context.Context) string

TraceParent formats the W3C traceparent of ctx's span. It is empty unless the span records, so nothing propagates for a trace the daemon does not export (export disabled, or the trace not sampled).

func Tracer

func Tracer(scope string) trace.Tracer

Tracer returns the global tracer for an instrumentation scope (one of the Scope constants).

func TracerProvider

func TracerProvider() trace.TracerProvider

TracerProvider returns a provider whose tracers start each span with the global provider installed at that moment, so instrumentation built before Init, such as the HTTP and UDS middleware, follows the provider Init installs.

Types

type DBWrite

type DBWrite struct {
	Operation     string
	Coalesced     bool
	Started       time.Time
	AdmissionWait time.Duration
	Duration      time.Duration
	Err           error
}

DBWrite is one finished database write: Duration spans admission, every retry, and commit; AdmissionWait is the part spent waiting for write admission. Its fields mirror store.WriteObservation, which converts to it.

type ModelClass

type ModelClass int

ModelClass classifies a gen_ai.request.model value for export. The zero value is ModelUnknown.

const (
	// ModelUnknown is a value no registry knows; it exports as "other".
	ModelUnknown ModelClass = iota
	// ModelCatalog is a trusted model-catalog entry (built-in or models.dev); it exports verbatim.
	ModelCatalog
	// ModelCustom is known only from user configuration; it exports as "custom".
	ModelCustom
)

type Registries

type Registries struct {
	RouteTemplates []string // from the mounted gin engines (HTTP and UDS)
	ACPMethods     []string
	// HookEvents is the hook event taxonomy, injected because internal/hooks is instrumented with this
	// package and so cannot be imported by it.
	HookEvents []string
	ToolIDs    func(id string) bool   // native tool registry membership
	Providers  func(name string) bool // configured providers
	Agents     func(name string) bool // registered agent definitions
	// Models classifies a model value; nil classifies every value as ModelUnknown.
	Models func(provider, model string) ModelClass
	// IDs validates an identity attribute with its owner's canonical format; a key without a
	// validator is never exported.
	IDs map[attribute.Key]func(string) bool
	// Secrets reports whether s contains a registered secret; nil uses the internal/redact registry.
	Secrets func(s string) bool
}

Registries are fixed when the exporters are built; values outside them are replaced or omitted (fail closed). Function registries may serve refreshed snapshots of their owning registry and must be safe for concurrent use: the span and metric exporters call them from their own goroutines.

type Runtime

type Runtime interface {
	Status() Status
	// ProviderEnv returns the OTLP export variables forwarded to provider processes (endpoint, protocol, and
	// resolved headers), or nil unless forward_to_providers is on and export started.
	ProviderEnv() []string
	// Shutdown flushes pending telemetry within ctx; it returns ctx.Err() when the flush outlives ctx.
	Shutdown(ctx context.Context) error
}

Runtime is a started export.

func Init

func Init(
	ctx context.Context,
	cfg config.ObservabilityConfig,
	refs SecretResolver,
	reg Registries,
	info version.Info,
	logger *slog.Logger,
) (Runtime, error)

Init installs the global providers for cfg. Disabled or inactive export installs no-op providers. When export cannot start (a header ref that does not resolve, an exporter that cannot be built) Init logs it, installs no-op providers, and returns a runtime reporting StateDegraded: export never blocks daemon boot.

type SecretResolver

type SecretResolver interface {
	ResolveRef(ctx context.Context, ref string) (string, error)
}

SecretResolver resolves env: and vault: header refs.

type SignalStatus

type SignalStatus struct {
	Enabled        bool
	LastExportAt   time.Time // zero until the first successful export
	LastErrorClass string    // fixed export error class; "" when the last export succeeded
	FailedExports  int64
}

SignalStatus is one signal's export health.

type State

type State string

State is the export state reported by status.

const (
	StateDisabled                      State = "disabled"
	StateInactiveObservabilityDisabled State = "inactive_observability_disabled"
	StateOK                            State = "ok"
	StateDegraded                      State = "degraded"
)

type Status

type Status struct {
	State              State
	Protocol           string // "grpc" | "http/protobuf"
	EndpointHost       string // host[:port] only; never userinfo, path, or query
	SampleRatio        float64
	ForwardToProviders bool
	Traces             SignalStatus
	Metrics            SignalStatus
	DroppedSpans       int64
}

Status is the export state, target, and per-signal health. It never carries header values.

Jump to

Keyboard shortcuts

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