Skip to content

feat(observability): OpenTelemetry logs+traces with secret redaction and slog standardization - #290

Merged
Quick104 merged 5 commits into
mainfrom
feat/opentelemetry-plan
Jul 9, 2026
Merged

Quick104 merged 5 commits into
mainfrom
feat/opentelemetry-plan

Conversation

@CoffeeKnyte

Copy link
Copy Markdown
Contributor

Part of #265.

Supersedes #264. Opened in response to @darthShadow's feedback (#265 (comment)) to adopt OpenTelemetry rather than a custom file sink.

Two commits: the OpenTelemetry logs+traces foundation with secret redaction, and the repo-wide slog call-site standardization plus a lint gate that keeps it from regressing.

Problem

Logs disappear when the container is recreated. Silo only ever wrote logs to stderr, so under Docker the only record lives in the daemon's json-file log, which is wiped on every redeploy or image bump. An operator investigating something that happened "before the last restart" has nothing to look at.

There was no standard, tool-agnostic way to ship logs and traces off the box. The earlier attempt (#264) solved durability with a bespoke rotating file sink. On review the maintainer asked us to build observability on OpenTelemetry instead of custom sinks, so a collector/backend of the operator's choice can own retention and correlation. This PR follows that direction.

Secrets could reach the logs unmasked. Redaction only ran on the operational-log database path. Anything written to stderr — and, once telemetry exists, to a collector — emitted API keys, tokens, and cookies verbatim.

Log lines were inconsistent and uncorrelated. Most call sites used the non-context slog form, so a log line could not be tied to the request/trace it belongs to, and nothing stopped new code from staying that way.

Solution

Design and rationale are captured in docs/architecture/observability.md and the plan under docs/superpowers/plans/.

feat(observability): OpenTelemetry logs+traces with secret redaction

Opt-in, gated entirely on SILO_OTEL_ENABLED / OTEL_EXPORTER_OTLP_ENDPOINT. With no config the behaviour is byte-for-byte the same as today (stderr + opslog).

  • New internal/telemetry package. Setup builds one shared resource, a TracerProvider (parent-based trace-id-ratio sampler), a LoggerProvider, and the W3C TraceContext+Baggage propagator from OTEL_* env. It deliberately installs no MeterProvider — metrics stay on Prometheus, and leaving the global meter as the built-in no-op stops the trace instrumentation libraries from double-emitting (internal/telemetry/telemetry.go).
  • Logs are bridged, not rerouted. An otelslog handler is added to the existing chain via fan-out (slog.MultiHandler), so records still reach stderr and the opslog DB/admin pipeline unchanged. The OTel branch is level-gated by the shared LevelVar (otherwise MultiHandler.Enabled would OR the branches and export Debug at log_level=info) and best-effort (a failing collector can't break the console/DB branches) — cmd/silo/main.go buildBaseHandler, internal/telemetry/loghandler.go.
  • Secret redaction on all sinks (internal/logredact). A slog.Handler masks secret-keyed attributes (password, token, api_key, authorization, cookie, …) — including .With-bound attrs, nested groups, secret-keyed group subtrees, and values behind a LogValuer (resolved before inspection) — with a zero-alloc fast path when a record has no secret keys. opslog.shouldRedact now delegates to logredact.SecretKey, so the DB path and the console/OTLP sinks share one marker list and can't drift.
  • Rotation is infra-managed (no custom in-process file sink, per the maintainer's steer). Retention is owned per sink: the container runtime for stderr (documented Docker json-file max-size/max-file + mounted volume), the collector/backend for OTLP, and opslog's existing daily-partition pruning for the DB path.

refactor(observability): slog context+component sweep, sloglint gate (phase 3)

  • Call-site sweep. Converted the remaining slog.<Level>(...) calls to slog.<Level>Context(ctx, …) wherever a context.Context is in scope (background/init calls with no ctx are left as-is), across 183 files, via a type-aware AST codemod. Log levels and message strings are preserved verbatim; a component attr (canonical per-package name) is added to direct package-level calls. main.go and the telemetry package's own conversions ride with their file in the first commit so no file is split across commits.
  • Enforcement (.golangci.yml). Enabled sloglint with context=scope, static-msg, key-naming-case=snake, no-mixed-args. After the sweep all four report zero violations repo-wide, so make lint / CI now blocks any regression to the non-context form. The gate ships with the sweep because it can't be green until the legacy sites are converted.

Risk / follow-ups

  • Redaction is key-based: a secret embedded in a free-text message or under an unrecognized key is not caught.
  • log_quiet also suppresses OTel logs — the fan-out mirrors the console stream, so quieting a subsystem empties its OTLP stream too.
  • Early-boot logs (DB connect, migrations, tuning) reach stderr only, matching existing opslog behaviour.
  • Distributed tracing spans at the seams (HTTP middleware, pgx, redis, plugin gRPC, scanner/playback) are planned as follow-up phases; this PR wires the providers and propagation but does not yet start spans.
  • Per-subsystem trace propagation into plugin subprocesses is owned by silo-plugin-sdk and is a coordination follow-up.
  • Metrics intentionally remain on Prometheus; /metrics and Grafana are untouched.

Verification

  • go build ./..., go vet ./..., gofmt -l — all clean.
  • sloglint (all four rules) — 0 violations repo-wide, tests included.
  • go test ./internal/telemetry/ ./internal/logredact/ -race — pass (bootstrap enable/disable + no-op MeterProvider guard; redaction of record attrs, .With-bound, nested groups, secret group keys, LogValuer, WithGroup, clean pass-through, and slogtest conformance).
  • Default-off path confirmed identical to today; log levels verified unchanged across the sweep (Info/Warn/Error/Debug counts identical pre/post).
  • Each commit builds independently; every file is contained in a single commit.

AI-use disclosure

Implemented with AI assistance (Claude Code): drafting, the AST codemod for the sweep, two rounds of adversarial review (which hardened the SDK bootstrap and found/fixed two secret-leak paths in the redaction handler), and this description. All changes were reviewed by the author.

Part of #265. Adds opt-in OpenTelemetry (logs + traces) alongside the existing
stderr + opslog pipeline, plus secret redaction on all sinks. Default-off: with
no OTEL_* / SILO_OTEL_ENABLED config, behavior is unchanged.

Bootstrap (internal/telemetry):
- Setup() builds one shared resource, a TracerProvider (parent-based trace-id
  ratio sampler), a LoggerProvider, and the W3C TraceContext+Baggage propagator
  from env. It installs NO MeterProvider — metrics stay on Prometheus, and the
  built-in no-op global MeterProvider keeps the trace instrumentation libs from
  double-emitting. Shutdown is deferred with a flush timeout.
- Logs are bridged via otelslog fan-out (slog.MultiHandler), level-gated by the
  shared LevelVar and best-effort so a failing collector can't break the console
  or DB branches. stderr + opslog stay untouched.

Secret redaction (internal/logredact):
- A slog.Handler masks secret-keyed attributes (password, token, api_key,
  authorization, cookie, ...) — including .With-bound attrs, nested groups,
  secret-keyed group subtrees, and values behind a LogValuer — on the console
  and OTLP sinks, with a no-op fast path when a record has no secret keys.
  opslog.shouldRedact delegates to logredact.SecretKey so all sinks share one
  marker list.

Rotation is infra-managed (no custom file sink): container runtime for stderr,
collector/backend for OTLP, opslog partition-pruning for the DB. Documented in
docs/architecture/observability.md.

Verification: go build ./..., go vet, gofmt -l — clean; go test
./internal/telemetry/ ./internal/logredact/ -race pass.

AI-use disclosure: implemented with AI assistance (Claude Code), including
adversarial reviews that hardened the bootstrap and fixed two redaction leak
paths; reviewed by the author.
…(phase 3)

Part of #265. Builds on the OTel bootstrap + redaction commit.

Standardizes every log call site onto the context-carrying slog variants so
records correlate with the active OpenTelemetry trace, and locks the standard
in with a machine gate so future code (human- or AI-authored) can't drift back.

- Call-site sweep: converted the remaining slog.<Level>(...) calls to the
  slog.<Level>Context(ctx, ...) form wherever a context.Context is in scope
  (background/init calls with no ctx are left as-is), across 183 files. Applied
  via a type-aware AST codemod. Log levels and message strings are preserved
  verbatim; a component attr (canonical per-package name) is added to direct
  package-level slog calls. Bound-logger calls keep their existing .With
  bindings. The main.go and telemetry package conversions rode with their file
  in the previous commit to keep each file within a single commit.
- Enforcement (.golangci.yml): enable sloglint with context=scope, static-msg,
  key-naming-case=snake, no-mixed-args. After the sweep all four report zero
  violations repo-wide (tests included), so make lint / CI now blocks any
  regression to the non-context form. The gate ships with the sweep because it
  cannot be green until the legacy sites are converted.

Metrics remain on Prometheus; no behavior change to /metrics or Grafana.

Verification: go build ./..., go vet ./..., gofmt -l — clean; sloglint (all 4
rules) 0 violations repo-wide; log levels verified unchanged.

AI-use disclosure: implemented with AI assistance (Claude Code), including the
codemod; reviewed by the author.
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Too many files!

This PR contains 209 files, which is 59 over the limit of 150.

To get a review, narrow the scope:
• coderabbit review --type committed # exclude uncommitted changes
• coderabbit review --dir # limit to a subdirectory
• coderabbit review --base # compare against a closer base

Upgrade to a paid plan to raise the limit.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e086e087-b6e5-4088-9c33-458bc80a28d5

📥 Commits

Reviewing files that changed from the base of the PR and between 2f95f6b and f14a949.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (209)
  • .golangci.yml
  • cmd/silo/main.go
  • docs/architecture/observability.md
  • docs/superpowers/plans/2026-07-02-opentelemetry-observability.md
  • go.mod
  • internal/activitylog/cleanup.go
  • internal/activitylog/consumer.go
  • internal/adminjob/image_cache_cleanup.go
  • internal/adminjob/runner.go
  • internal/ai/llm/client.go
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_images.go
  • internal/api/handlers/admin_intro.go
  • internal/api/handlers/admin_logs.go
  • internal/api/handlers/admin_marker_providers.go
  • internal/api/handlers/admin_match.go
  • internal/api/handlers/admin_split.go
  • internal/api/handlers/admin_stats.go
  • internal/api/handlers/autoscan.go
  • internal/api/handlers/calendar.go
  • internal/api/handlers/catalog.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/events_publish.go
  • internal/api/handlers/events_ws.go
  • internal/api/handlers/history_import.go
  • internal/api/handlers/history_import_admin.go
  • internal/api/handlers/items.go
  • internal/api/handlers/libraries.go
  • internal/api/handlers/library_collections.go
  • internal/api/handlers/markers.go
  • internal/api/handlers/metadata_ai.go
  • internal/api/handlers/nodes.go
  • internal/api/handlers/people.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_lazy_markers.go
  • internal/api/handlers/playback_missing.go
  • internal/api/handlers/plugins.go
  • internal/api/handlers/policy.go
  • internal/api/handlers/policy_test.go
  • internal/api/handlers/profile_refresh.go
  • internal/api/handlers/profiles.go
  • internal/api/handlers/progress.go
  • internal/api/handlers/recommendations.go
  • internal/api/handlers/sections.go
  • internal/api/handlers/server_control.go
  • internal/api/handlers/session_ws.go
  • internal/api/handlers/settings.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/subtitle_ai.go
  • internal/api/handlers/subtitle_search.go
  • internal/api/handlers/system.go
  • internal/api/handlers/taste_seed.go
  • internal/api/handlers/user_collection_imports.go
  • internal/api/handlers/watch_tonight.go
  • internal/api/handlers/watch_tonight_cards.go
  • internal/api/handlers/webhook_sync.go
  • internal/api/middleware/request_logger.go
  • internal/audiobooks/abs/access_log.go
  • internal/audiobooks/abs/author_series_handler.go
  • internal/audiobooks/abs/bookmarks_handler.go
  • internal/audiobooks/abs/collections_handler.go
  • internal/audiobooks/abs/continue_listening_handler.go
  • internal/audiobooks/abs/extras_handlers.go
  • internal/audiobooks/abs/handler.go
  • internal/audiobooks/abs/libraries_handler.go
  • internal/audiobooks/abs/listening_stats_handler.go
  • internal/audiobooks/abs/login.go
  • internal/audiobooks/abs/native_sessions.go
  • internal/audiobooks/abs/play_response.go
  • internal/audiobooks/abs/playlists_handler.go
  • internal/audiobooks/abs/progress.go
  • internal/audiobooks/abs/rss_feeds_handler.go
  • internal/audiobooks/abs/session_local.go
  • internal/audiobooks/abs/smart_collections_handler.go
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/podcastfeed/refresher.go
  • internal/auth/oauth_handler.go
  • internal/autoscan/service.go
  • internal/catalog/collection_sync_scheduler.go
  • internal/catalog/detail.go
  • internal/catalog/library_collection_service.go
  • internal/catalog/person_repo.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_service.go
  • internal/catalog/semantic_coverage.go
  • internal/catalog/smart_count_refresher.go
  • internal/chapterthumbs/service.go
  • internal/downloads/artifacts.go
  • internal/downloads/offline.go
  • internal/downloads/service.go
  • internal/downloads/subscription_service.go
  • internal/ebooks/enrichment.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/plex_provider.go
  • internal/historyimport/service.go
  • internal/historyimport/service_admin.go
  • internal/historyimport/service_maintenance.go
  • internal/intromarkers/analyzer.go
  • internal/jellycompat/access_filter.go
  • internal/jellycompat/auth.go
  • internal/jellycompat/auth_api_key.go
  • internal/jellycompat/cleanup.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_autoscan.go
  • internal/jellycompat/handlers_collections.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/handlers_websocket.go
  • internal/jellycompat/logging.go
  • internal/jellycompat/playback_sessions_postgres.go
  • internal/jellycompat/profile_refresh.go
  • internal/jellycompat/query.go
  • internal/jellycompat/streams.go
  • internal/jellycompat/userdata_direct.go
  • internal/libraryingest/executor.go
  • internal/logredact/redact.go
  • internal/logredact/redact_test.go
  • internal/manga/enrichment.go
  • internal/markers/contribute.go
  • internal/metadata/chain.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/image_resolver.go
  • internal/metadata/person_refresh.go
  • internal/metadata/provider_id_integrity.go
  • internal/metadata/service.go
  • internal/metadata/translation/service.go
  • internal/metadata/worker.go
  • internal/nodeconfig/watcher.go
  • internal/nodepool/health.go
  • internal/noderecipe/store.go
  • internal/nodesessions/tracker.go
  • internal/notifications/account_channel_engine.go
  • internal/notifications/availability_detector.go
  • internal/notifications/channel_dispatcher.go
  • internal/notifications/discord_dm.go
  • internal/notifications/fanout_worker.go
  • internal/notifications/interest_hooks.go
  • internal/notifications/interest_updater.go
  • internal/notifications/operational_dispatch.go
  • internal/notifications/operational_dispatch_test.go
  • internal/notifications/push_sender.go
  • internal/notifications/request_notifier.go
  • internal/notifications/server_channel_request_notifier.go
  • internal/notifications/server_channel_worker.go
  • internal/notifications/system.go
  • internal/notifications/webhook_sender.go
  • internal/notifications/webpush_sender.go
  • internal/opslog/cleanup.go
  • internal/opslog/consumer.go
  • internal/opslog/handler.go
  • internal/playback/chapter_thumbnail_notifier.go
  • internal/playback/ffmpeg_log_sink.go
  • internal/playback/marker_update_notifier.go
  • internal/playback/session.go
  • internal/playback/subtitle_ready_notifier.go
  • internal/playback/subtitle_stream.go
  • internal/playback/transcode_manager.go
  • internal/plugins/archive_cache.go
  • internal/plugins/auto_update.go
  • internal/plugins/catalog_service.go
  • internal/plugins/event_dispatcher.go
  • internal/plugins/http_proxy.go
  • internal/plugins/service.go
  • internal/plugins/service_connection.go
  • internal/policy/decisionlog_cleanup.go
  • internal/policy/system_test.go
  • internal/proxy/server.go
  • internal/ratelimit/middleware.go
  • internal/ratelimit/redis.go
  • internal/recommendations/embeddings/client.go
  • internal/recommendations/reader.go
  • internal/recommendations/similar.go
  • internal/recommendations/taste.go
  • internal/recommendations/worker.go
  • internal/requests/notify.go
  • internal/requests/presence.go
  • internal/requests/service.go
  • internal/s3client/client.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_scan.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/extras.go
  • internal/scanner/manga_scan.go
  • internal/scanner/podcast_scan.go
  • internal/scanner/scanner.go
  • internal/scanqueue/service.go
  • internal/sections/fetcher.go
  • internal/sections/trending_refresher.go
  • internal/subtitles/ai/service.go
  • internal/taskmanager/manager.go
  • internal/taskmanager/manager_test.go
  • internal/taskmanager/tasks/refresh_metadata.go
  • internal/taskmanager/tasks/scan_libraries.go
  • internal/telemetry/config.go
  • internal/telemetry/config_test.go
  • internal/telemetry/loghandler.go
  • internal/telemetry/loghandler_test.go
  • internal/telemetry/telemetry.go
  • internal/telemetry/telemetry_test.go
  • internal/transcodenode/server.go
  • internal/usercollections/scheduler.go
  • internal/usercollections/sync.go
  • internal/watchlist/maintainer.go
  • internal/watchsync/lists.go
  • internal/watchsync/providers/simkl/provider.go
  • internal/watchsync/service.go
  • internal/webhooksync/service.go
  • internal/worker/cleanup.go
  • scripts/backfill-library-matching/main.go

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/opentelemetry-plan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5da1aa42d2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/logredact/redact.go Outdated
// WithGroup delegates to the inner handler; grouped attributes are still
// redacted by leaf key at Handle/WithAttrs time.
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{inner: h.inner.WithGroup(name)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor secret group names in WithGroup

When code builds a logger with WithGroup("authorization") (or another secret marker) and then logs a non-secret leaf such as "value", this branch passes the secret group name straight to the inner handler; the later redaction pass only sees the leaf key, so stderr/OTLP can emit the token under the secret group. slog.Group("authorization", ...) is already masked as a subtree, so WithGroup needs the same treatment before delegating.

Useful? React with 👍 / 👎.

Comment thread internal/telemetry/config.go Outdated
Comment on lines +71 to +77
protocol := ProtocolGRPC
switch strings.ToLower(strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_PROTOCOL"))) {
case "http/protobuf", "http":
protocol = ProtocolHTTP
case "grpc", "":
protocol = ProtocolGRPC
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor per-signal OTLP protocol overrides

If an operator uses the standard signal-specific env vars, for example OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/protobuf with an HTTP logs endpoint while leaving the generic OTEL_EXPORTER_OTLP_PROTOCOL unset, this defaults cfg.Protocol to gRPC and Setup constructs gRPC exporters; the per-signal protocol env cannot switch the exporter package after that. That breaks common mixed or signal-specific OTLP collector configs even though the exporters are otherwise expected to read OTEL_EXPORTER_OTLP_* settings from the environment.

Useful? React with 👍 / 👎.

…up names

Two Codex review findings on PR #290:

- telemetry: OTEL_EXPORTER_OTLP_{TRACES,LOGS}_PROTOCOL now override the
  generic OTEL_EXPORTER_OTLP_PROTOCOL per signal, so mixed collector
  setups (e.g. HTTP logs + gRPC traces) build the right exporter.
- logredact: entering a group whose name is secret-bearing (e.g.
  WithGroup("authorization")) now masks every leaf in that subtree,
  matching how slog.Group("authorization", ...) is masked as a whole.
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Addressed the two Codex findings in be5ad6e:

  • Per-signal OTLP protocol — OTEL_EXPORTER_OTLP_{TRACES,LOGS}_PROTOCOL now override the generic OTEL_EXPORTER_OTLP_PROTOCOL per signal, so mixed collector setups (e.g. HTTP logs + gRPC traces) build the right exporter (telemetry/config.go, telemetry.go).
  • Secret WithGroup names — entering a group whose name is secret-bearing (e.g. WithGroup("authorization")) now masks every leaf in the subtree, matching slog.Group("authorization", ...) (logredact/redact.go).

build / vet / tests pass.

Quick104 and others added 2 commits July 7, 2026 09:35
- Telemetry setup failure no longer kills boot: Setup returns usable
  no-op providers alongside the error and main logs and continues with
  telemetry disabled, honoring the best-effort contract.
- Honor OTEL_TRACES_SAMPLER (always_on/off, traceidratio, parentbased_*
  variants); unsupported values fall back to parentbased_traceidratio.
- Attach node identity as semconv service.instance.id instead of the
  non-semconv node.name.
- Rename opslog retention-scope log attrs to target_component/target_level
  so they no longer collide with the canonical component routing key, and
  tag those lines with component=opslog.
- Fix stale levelGated comment casing; use WarnContext in the telemetry
  shutdown defer; document the LogValuer double-resolve on the redaction
  slow path.

Co-Authored-By: Claude Fable 5 <[email protected]>
Resolves conflicts against main (audiobooks enrichment provider-error
handling, autoscan transient-resolve stats, go.mod/go.sum dep union) and
converts the slog call sites that landed on main after the sweep to the
context+component convention so the sloglint gate stays green repo-wide
(admin_split, libraries, policy handlers, policy decision-log cleanup,
abs handlers, jellycompat, metadata, playback, plugins, scanner extras,
watchsync, clientip reload; test loggers moved to slog.DiscardHandler).
Adds "policy" to the canonical component list.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Pushed two commits addressing the review and resolving the conflict with main:

ec2c73a — review feedback

  • Telemetry setup failure is now non-fatal: Setup returns usable no-op providers alongside the error, and main logs and continues with telemetry disabled (best-effort contract; a typo'd OTEL_* env can no longer crash-loop the server).
  • OTEL_TRACES_SAMPLER is honored (always_on/always_off/traceidratio/parentbased_*); unsupported values fall back to parentbased_traceidratio.
  • Node identity moved from the non-semconv node.name to service.instance.id.
  • opslog retention-scope attrs renamed to target_component/target_level (they collided with the canonical component routing key); those lines now carry component=opslog.
  • Nits: stale levelGated comment, WarnContext in the shutdown defer, LogValuer double-resolve documented.

f14a949 — merge main

  • Conflict resolution keeps main's logic (audiobooks provider-error handling, autoscan transient-resolve stats) with the sweep's context+component form applied on top; go.mod/go.sum rebuilt from main plus the OTel requires via go mod tidy.
  • Converted the 23 slog call sites that landed on main after the sweep, so the sloglint gate is green repo-wide again. Added policy to the canonical component list.

Verification: go build ./... clean, sloglint (uncapped) 0 issues, go test green across telemetry/logredact and all conflict-touched packages (the two TestBeginWebOperation* jellycompat failures are the known pre-existing flaky baseline).

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit 5fc180e into main Jul 9, 2026
1 check passed
@Quick104
Quick104 deleted the feat/opentelemetry-plan branch July 9, 2026 12:53
Quick104 added a commit that referenced this pull request Jul 10, 2026
…and slog standardization (#290)

* feat(observability): OpenTelemetry logs+traces with secret redaction

Part of #265. Adds opt-in OpenTelemetry (logs + traces) alongside the existing
stderr + opslog pipeline, plus secret redaction on all sinks. Default-off: with
no OTEL_* / SILO_OTEL_ENABLED config, behavior is unchanged.

Bootstrap (internal/telemetry):
- Setup() builds one shared resource, a TracerProvider (parent-based trace-id
  ratio sampler), a LoggerProvider, and the W3C TraceContext+Baggage propagator
  from env. It installs NO MeterProvider — metrics stay on Prometheus, and the
  built-in no-op global MeterProvider keeps the trace instrumentation libs from
  double-emitting. Shutdown is deferred with a flush timeout.
- Logs are bridged via otelslog fan-out (slog.MultiHandler), level-gated by the
  shared LevelVar and best-effort so a failing collector can't break the console
  or DB branches. stderr + opslog stay untouched.

Secret redaction (internal/logredact):
- A slog.Handler masks secret-keyed attributes (password, token, api_key,
  authorization, cookie, ...) — including .With-bound attrs, nested groups,
  secret-keyed group subtrees, and values behind a LogValuer — on the console
  and OTLP sinks, with a no-op fast path when a record has no secret keys.
  opslog.shouldRedact delegates to logredact.SecretKey so all sinks share one
  marker list.

Rotation is infra-managed (no custom file sink): container runtime for stderr,
collector/backend for OTLP, opslog partition-pruning for the DB. Documented in
docs/architecture/observability.md.

Verification: go build ./..., go vet, gofmt -l — clean; go test
./internal/telemetry/ ./internal/logredact/ -race pass.

AI-use disclosure: implemented with AI assistance (Claude Code), including
adversarial reviews that hardened the bootstrap and fixed two redaction leak
paths; reviewed by the author.

* refactor(observability): slog context+component sweep, sloglint gate (phase 3)

Part of #265. Builds on the OTel bootstrap + redaction commit.

Standardizes every log call site onto the context-carrying slog variants so
records correlate with the active OpenTelemetry trace, and locks the standard
in with a machine gate so future code (human- or AI-authored) can't drift back.

- Call-site sweep: converted the remaining slog.<Level>(...) calls to the
  slog.<Level>Context(ctx, ...) form wherever a context.Context is in scope
  (background/init calls with no ctx are left as-is), across 183 files. Applied
  via a type-aware AST codemod. Log levels and message strings are preserved
  verbatim; a component attr (canonical per-package name) is added to direct
  package-level slog calls. Bound-logger calls keep their existing .With
  bindings. The main.go and telemetry package conversions rode with their file
  in the previous commit to keep each file within a single commit.
- Enforcement (.golangci.yml): enable sloglint with context=scope, static-msg,
  key-naming-case=snake, no-mixed-args. After the sweep all four report zero
  violations repo-wide (tests included), so make lint / CI now blocks any
  regression to the non-context form. The gate ships with the sweep because it
  cannot be green until the legacy sites are converted.

Metrics remain on Prometheus; no behavior change to /metrics or Grafana.

Verification: go build ./..., go vet ./..., gofmt -l — clean; sloglint (all 4
rules) 0 violations repo-wide; log levels verified unchanged.

AI-use disclosure: implemented with AI assistance (Claude Code), including the
codemod; reviewed by the author.

* fix(observability): honor per-signal OTLP protocol and secret WithGroup names

Two Codex review findings on PR #290:

- telemetry: OTEL_EXPORTER_OTLP_{TRACES,LOGS}_PROTOCOL now override the
  generic OTEL_EXPORTER_OTLP_PROTOCOL per signal, so mixed collector
  setups (e.g. HTTP logs + gRPC traces) build the right exporter.
- logredact: entering a group whose name is secret-bearing (e.g.
  WithGroup("authorization")) now masks every leaf in that subtree,
  matching how slog.Group("authorization", ...) is masked as a whole.

* fix(observability): address review feedback on telemetry bootstrap

- Telemetry setup failure no longer kills boot: Setup returns usable
  no-op providers alongside the error and main logs and continues with
  telemetry disabled, honoring the best-effort contract.
- Honor OTEL_TRACES_SAMPLER (always_on/off, traceidratio, parentbased_*
  variants); unsupported values fall back to parentbased_traceidratio.
- Attach node identity as semconv service.instance.id instead of the
  non-semconv node.name.
- Rename opslog retention-scope log attrs to target_component/target_level
  so they no longer collide with the canonical component routing key, and
  tag those lines with component=opslog.
- Fix stale levelGated comment casing; use WarnContext in the telemetry
  shutdown defer; document the LogValuer double-resolve on the redaction
  slow path.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Quick <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants