telemetry

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package telemetry configures OpenTelemetry tracing for the second-brain backend and exports spans to a self-hosted Langfuse instance over OTLP/HTTP.

Langfuse does not publish a Go SDK — only Python/JS/TS. The documented integration path for other languages is the standard OpenTelemetry SDK talking OTLP/HTTP directly to Langfuse's OTLP receiver, authenticated with HTTP Basic Auth (base64(publicKey:secretKey)). This package implements exactly that path; it intentionally does not depend on any Langfuse-specific client library.

Endpoint path contract (verified against a live deployment, not just docs): the "endpoint" this package's callers configure (e.g. LANGFUSE_OTLP_ENDPOINT) is Langfuse's OTLP *base* path (".../api/public/otel"), NOT the literal traces-ingestion URL. Langfuse's receiver actually listens at "{base}/v1/traces" — POSTing to the bare base path returns the Langfuse web app's own 404 page (it's a valid route in its Next.js router, just not the OTLP one), which otlptracehttp treats as an ordinary failed export and silently drops the span after retries — no crash, no visible error unless you go looking. This mirrors the standard OTEL_EXPORTER_OTLP_ENDPOINT convention (base URL, "/v1/traces" auto-appended), so InitOTel appends "/v1/traces" itself rather than requiring every caller to remember to include it in the configured value.

Non-blocking guarantee: this package NEVER calls sdktrace.WithBlocking(). Spans are exported via a BatchSpanProcessor with a bounded export timeout, so a dead or unreachable Langfuse collector can only ever cause buffered spans to be dropped once the queue fills — it can never stall or fail application request handling.

Index

Constants

View Source
const (
	// AttrGenAISystem identifies the GenAI provider/protocol family (e.g.
	// "openai"). Set on every LLM/embedding/transcription span.
	AttrGenAISystem = "gen_ai.system"
	// AttrGenAIRequestModel is the model name requested (e.g.
	// "gpt-4o-transcribe-diarize", "text-embedding-3-small").
	AttrGenAIRequestModel = "gen_ai.request.model"
	// AttrGenAIRequestMaxTokens is the max_tokens request parameter, when
	// applicable (chat completions only).
	AttrGenAIRequestMaxTokens = "gen_ai.request.max_tokens"
	// AttrGenAIUsageInputTokens is the prompt/input token count reported by
	// the provider's response, when available.
	AttrGenAIUsageInputTokens = "gen_ai.usage.input_tokens"
	// AttrGenAIUsageOutputTokens is the completion/output token count
	// reported by the provider's response, when available.
	AttrGenAIUsageOutputTokens = "gen_ai.usage.output_tokens"
)

GenAI semantic convention attribute keys used across the LLM/embedding/ transcription instrumentation in internal/llm, internal/search, and internal/collector. Langfuse's OTLP receiver inspects these exact keys to auto-populate provider/model/token/cost fields in its UI.

These are plain string constants rather than sourced from go.opentelemetry.io/otel/semconv/*: the GenAI conventions are experimental and have changed key names across semconv releases (e.g. "gen_ai.system" was renamed to "gen_ai.provider.name" starting in semconv v1.36.0, which is newer than what this module vendors). Pinning to a semconv package version would silently drift the wire attribute names Langfuse expects away from what its docs (and this integration's plan) specify. Using literal keys here keeps the contract explicit and independent of whichever semconv version happens to be vendored.

View Source
const (
	// AttrEmbeddingBatchSize is the number of texts in an EmbedBatch
	// sub-batch request.
	AttrEmbeddingBatchSize = "embedding.batch_size"
	// AttrAudioSizeBytes is the size in bytes of an audio file submitted for
	// transcription.
	AttrAudioSizeBytes = "audio.size_bytes"
	// AttrLLMRetryAttempt is the zero-based attempt index of an individual
	// LLM chat-completion request within CompleteWithMessages' retry loop.
	AttrLLMRetryAttempt = "llm.retry.attempt"
)

Operation-specific attributes that are NOT part of the GenAI semantic conventions but add useful context for the batching/concurrency patterns this codebase uses (sub-batched embeddings, worker-pool transcription).

View Source
const (
	// SpanFeedbackEvidence is emitted once per successfully recorded evidence
	// vote. Failed requests do not emit a span — a failure is an HTTP-layer
	// concern and is already logged there.
	SpanFeedbackEvidence = "feedback.evidence.recorded"
	// SpanTuneDatasetLoaded reports the size of each split at the start of a
	// tuning run: this is the "training set growth" series.
	SpanTuneDatasetLoaded = "tune.dataset.loaded"
	// SpanTuneCoordinate reports the outcome of coordinate search on the
	// training set (train-set objectives only, never holdout).
	SpanTuneCoordinate = "tune.coordinate.completed"
	// SpanTunePromotion reports the holdout verdict and the gate decision.
	SpanTunePromotion = "tune.promotion.decision"
	// SpanWeightsAction reports an actual state change in
	// search_weights_history: propose, promote or rollback.
	SpanWeightsAction = "weights.action.applied"
)

Span names and attribute keys for the search-feedback loop: evidence-level thumbs collection (internal/api), weight tuning (cmd/tune, internal/tune) and weight promotion/rollback (internal/store/weights_history.go).

Why span attributes rather than a metrics pipeline: this package exports traces to Langfuse over OTLP and configures no metric exporter (otel.go). Adding one for a handful of counters would mean a second delivery path to operate. A promotion span carrying tune.ndcg_gain plotted over time in Langfuse *is* the "holdout score trend" chart, and a feedback.evidence span per vote *is* the collection-rate series — the trace timeline answers "did the change make things better" without a second system.

What may appear here, and what may not:

  • Allowed: document UUIDs, closed-domain enums (thumbs, split, gate reason codes), and aggregate scalars.
  • Not allowed: query text, and — unlike the local logs, which may carry dataset.QueryHash — not even the query hash. Langfuse is a hosted service whose retention outlives this project's logs, so the safe amount of user speech to send there is none. Reproducing a decision needs feedback.split and search_weights_history, both of which stay in Postgres.

TestAttrKeys_MatchAllowlist parses this file and fails if the constant set drifts from the allowlist in the test, so a new attribute cannot be added without someone reading the paragraph above.

View Source
const (
	// AttrFeedbackDocumentID is the voted-on document's UUID. An opaque
	// identifier, not content.
	AttrFeedbackDocumentID = "feedback.document_id"
	// AttrFeedbackThumbs is the vote the database settled on: -1, 0 (cleared)
	// or 1.
	AttrFeedbackThumbs = "feedback.thumbs"
	// AttrFeedbackSplit is "train" or "holdout" — which half of the labelled
	// set this vote landed in.
	AttrFeedbackSplit = "feedback.split"

	// AttrTuneTrainQueries and AttrTuneHoldoutQueries are the two split sizes.
	AttrTuneTrainQueries   = "tune.train_queries"
	AttrTuneHoldoutQueries = "tune.holdout_queries"
	// AttrTuneTotalRows is the total number of labelled evaluation pairs behind
	// a run — the feedback-collection trend.
	AttrTuneTotalRows = "tune.total_feedback_rows"
	// AttrTuneSweeps and AttrTuneEvals describe how much work the search did.
	AttrTuneSweeps = "tune.sweeps"
	AttrTuneEvals  = "tune.evals"
	// AttrTuneBaseObjective and AttrTuneBestObjective are TRAINING-set
	// objectives: where the search started and where it ended.
	AttrTuneBaseObjective = "tune.base_objective"
	AttrTuneBestObjective = "tune.best_objective"
	// AttrTuneGatePassed is the promotion decision.
	AttrTuneGatePassed = "tune.gate_passed"
	// AttrTuneGateReason is a fixed enum code from internal/tune (gate.go),
	// never free text and never the human sentence stored in Postgres — free
	// text is how user input eventually leaks into a trace.
	AttrTuneGateReason = "tune.gate_reason"
	// AttrTuneNDCGGain and AttrTuneFPDelta are the holdout deltas the gate
	// judged. Plotted over runs, these are the holdout score trend.
	AttrTuneNDCGGain = "tune.ndcg_gain"
	AttrTuneFPDelta  = "tune.fp_delta"

	// AttrWeightsHistoryID is the search_weights_history primary key.
	AttrWeightsHistoryID = "weights.history_id"
	// AttrWeightsAction is one of the WeightsAction* values below.
	AttrWeightsAction = "weights.action"
	// AttrWeightsPreviousHistoryID is the row a rollback restored, when there
	// was one.
	AttrWeightsPreviousHistoryID = "weights.previous_history_id"
)
View Source
const (
	WeightsActionPropose  = "propose"
	WeightsActionPromote  = "promote"
	WeightsActionRollback = "rollback"
)

Closed set of values for AttrWeightsAction. These are payload rather than keys, which is why the allowlist test ignores them — but they are constants so that the batch command and any future dashboard query agree on spelling.

View Source
const ServiceName = "second-brain"

ServiceName identifies this process in the OTel resource `service.name` attribute and is the value Langfuse groups traces by when multiple services (server, collector, eval runner) export to the same project.

Variables

This section is empty.

Functions

func InitOTel

func InitOTel(ctx context.Context, endpoint, publicKey, secretKey string) (func(context.Context) error, error)

InitOTel configures the process-global OpenTelemetry TracerProvider and returns a shutdown function the caller must defer.

When endpoint is empty, tracing is fully disabled: the global TracerProvider is set to a no-op implementation (noop.NewTracerProvider) so every otel.Tracer(...).Start(...) call anywhere in the codebase becomes a safe, side-effect-free no-op. This is the default (unconfigured) behavior in local dev and CI, where LANGFUSE_OTLP_ENDPOINT is unset.

When endpoint is non-empty, spans are batched (sdktrace.BatchSpanProcessor with WithBatchTimeout(5s)/WithExportTimeout(3s) — see package doc for why WithBlocking() is never used) and exported over OTLP/HTTP, authenticated via HTTP Basic Auth using publicKey/secretKey (Langfuse's documented OTLP ingestion contract). endpoint is the OTLP *base* URL — "/v1/traces" is appended automatically (see the package doc's "Endpoint path contract").

Example endpoint for this deployment: "http://100.77.20.12:3300/api/public/otel" (the langfuse-web Tailscale-interface binding, port 3300 — see the ops repo's Langfuse compose). Do NOT use the public hostname (https://langfuse.<domain>) here: that hostname sits behind Cloudflare Access, so a server-to-server OTLP POST with no browser session gets a silent 302-to-login instead of a real response, and the span is dropped with no error surfaced anywhere — the failure is invisible unless someone checks the Langfuse UI and wonders why it's empty.

The returned shutdown function flushes any buffered spans and releases the exporter. Callers MUST wrap invocation of the returned func with a short timeout (e.g. 5s) — see package doc: a dead collector must never block process shutdown.

Types

This section is empty.

Jump to

Keyboard shortcuts

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