Skip to content

fix: use runtime.HTTPPattern for route extraction in spans#55

Merged
ankurs merged 17 commits intomainfrom
fix/http-span-name
Mar 29, 2026
Merged

fix: use runtime.HTTPPattern for route extraction in spans#55
ankurs merged 17 commits intomainfrom
fix/http-span-name

Conversation

@ankurs
Copy link
Copy Markdown
Member

@ankurs ankurs commented Mar 29, 2026

Summary

  • Fix spanRouteMiddleware to use runtime.HTTPPattern (Pattern struct set by handleHandler) instead of runtime.HTTPPathPattern (string set later inside AnnotateContext). This was causing route patterns to never appear in span names.
  • Add tests with in-memory OTel exporter verifying span name, all semconv attributes, and end-to-end grpc-gateway route pattern extraction

Test plan

  • make test passes with -race
  • TestTracingWrapperSpanAttributes verifies all span attributes
  • TestTracingWrapperGatewaySpanName verifies span renamed to GET /api/v1/rules/{rule_id=*} with http.route attribute

Summary by CodeRabbit

  • New Features

    • Improved HTTP tracing: more accurate scheme detection (including forwarded proto), server address recorded only when present, route-pattern-based span naming, and automatic capture of panics as 500 errors in spans.
  • Tests

    • Added end-to-end tracing tests verifying span names, HTTP semantic attributes, error status for panics, and route pattern attributes.

ankurs added 11 commits March 28, 2026 23:17
The tracingWrapper middleware hardcoded "ServeHTTP" as the OTEL span name
for all HTTP requests, making traces hard to distinguish. Now uses
r.Method + " " + r.URL.Path (e.g. "GET /api/v1/rules") following
OpenTelemetry HTTP semantic conventions.
- Add statusRecorder to capture response status codes
- Record http.status_code attribute on every HTTP span
- Set span status to Error for 5xx responses
- statusRecorder.Unwrap() preserves http.Flusher etc. for gzip middleware
- HTTPMethodKey → HTTPRequestMethodKey (http.request.method)
- HTTPTargetKey → URLPath + URLQuery (url.path, url.query)
- HTTPStatusCodeKey → HTTPResponseStatusCode (http.response.status_code)
- ServiceNameKey/ServiceVersionKey → ServiceName/ServiceVersion functions
- Add url.scheme and server.address attributes to HTTP spans
- Span starts as r.Method, then spanRouteMiddleware renames it to
  "GET /api/v1/{resource}" using runtime.HTTPPathPattern after routing
- Sets http.route attribute per OTel HTTP semantic conventions
- Simplify tracingWrapper: extract endSpan() and httpSpanAttributes(),
  consolidate r.WithContext() calls (3→1), skip empty url.scheme/query
- statusRecorder: track wroteHeader to record only the first status
  code, matching net/http behavior where subsequent calls are no-ops
- httpSpanAttributes: split r.Host with net.SplitHostPort to set
  server.address (host only) and server.port separately per semconv
Read runtime/debug.BuildInfo to attach build metadata as OTEL
resource attributes on all spans:
- process.runtime.name, process.runtime.version (Go version)
- vcs.repository.ref.head.revision (git commit hash)
- vcs.time (commit timestamp)
- vcs.modified (dirty working tree flag)
Read runtime/debug.BuildInfo to attach build metadata as OTEL
resource attributes on all spans:
- process.executable.name (binary name from os.Args[0])
- process.runtime.version (Go version)
- vcs.repository.ref.head.revision (git commit hash)
- vcs.time (commit timestamp)
- vcs.modified (dirty working tree flag)

These are set once on the OTEL resource, so they appear on every
span automatically without per-request overhead.
- WriteHeader: only record first final status (>= 200), skip 1xx
- Write: set status to 200 if WriteHeader was never called, matching
  net/http implicit status behavior
… tests

The spanRouteMiddleware was using runtime.HTTPPathPattern (set inside
the handler via AnnotateContext) instead of runtime.HTTPPattern (set
by handleHandler before the middleware runs). This caused the route
pattern to never be found.

Adds tests with in-memory OTel exporter that verify:
- Span name, http.request.method, url.path, url.query, server.address,
  server.port, http.response.status_code attributes
- End-to-end grpc-gateway routing: span renamed to "GET /api/v1/rules/{rule_id=*}"
  with http.route attribute set
Copilot AI review requested due to automatic review settings March 29, 2026 07:37
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 29, 2026

Warning

Rate limit exceeded

@ankurs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 9 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 2 minutes and 9 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 90182487-7eb9-4c1d-bd63-25257877b777

📥 Commits

Reviewing files that changed from the base of the PR and between 13df802 and f5b473c.

📒 Files selected for processing (2)
  • core.go
  • core_coverage_test.go
📝 Walkthrough

Walkthrough

Updated HTTP tracing: derive URL scheme from headers/TLS, omit empty server address, switch route pattern source, and make span finalization recover panics and record errors. Added OpenTelemetry in-memory tests validating span attributes, naming, status, and panic handling.

Changes

Cohort / File(s) Summary
Core HTTP tracing
core.go
Derived URL scheme from X-Forwarded-Proto or TLS when missing; only add semconv.ServerAddress if host is non-empty; wrap span termination in a defer that recovers panics, records HTTP 500 and span error, sets span status, ends the span, then re-panics; use runtime.HTTPPattern and pattern.String() for span naming and http.route attribute.
Tracing tests
core_coverage_test.go
Added in-memory OpenTelemetry tracer setup (setupTestTracer), helpers (findSpanByName, spanAttrMap), and tests verifying: span emission from tracingWrapper (name, HTTP semantic attributes, status codes, panic->500 behavior) and spanRouteMiddleware route naming and http.route attribute.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TracingMiddleware
  participant Handler
  participant Tracer

  Client->>TracingMiddleware: HTTP request (may include X-Forwarded-Proto)
  TracingMiddleware->>Tracer: Start span (derive scheme, set attributes)
  TracingMiddleware->>Handler: Invoke handler (wrap response writer)
  alt handler completes normally
    Handler-->>TracingMiddleware: Response (status)
    TracingMiddleware->>Tracer: End span (set status from response)
  else handler panics
    Handler-->>TracingMiddleware: panic
    TracingMiddleware->>Tracer: Record error, set status=Error, set 500
    TracingMiddleware->>Tracer: End span
    TracingMiddleware-->>Client: propagate panic (re-panic)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hop where traces thread the night,

Schemes found by headers or TLS light,
A panic caught, then logged with care,
Spans end tidy, endings fair—
Hooray, the tests all gleam and bite! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'fix: use runtime.HTTPPattern for route extraction in spans' directly and clearly summarizes the main change: switching from runtime.HTTPPathPattern to runtime.HTTPPattern for proper route extraction in span names.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/http-span-name

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 and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes HTTP gateway span naming by extracting the matched grpc-gateway route pattern from runtime.HTTPPattern and aligning HTTP span attributes/resource metadata with newer OpenTelemetry semantic conventions.

Changes:

  • Update spanRouteMiddleware to rename spans and set http.route using runtime.HTTPPattern.
  • Improve HTTP tracing spans: record HTTP status codes on spans (and mark 5xx as errors) and emit updated semconv HTTP attributes.
  • Add tests using an in-memory OTel exporter to validate span names, attributes, and end-to-end route pattern extraction.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
initializers.go Adds richer OTEL resource attributes (service/process/VCS) and updates semconv version usage.
core.go Updates HTTP tracing span naming/attributes, adds status recording + span error status for 5xx, and fixes grpc-gateway route pattern extraction for spans.
core_coverage_test.go Adds OTel in-memory exporter tests validating span attributes and grpc-gateway span naming/route extraction.
config/README.md Documents deprecation and default change for OpenTracing bridge config.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread core.go Outdated
Comment thread core.go
Comment thread core_coverage_test.go Outdated
Comment thread core_coverage_test.go Outdated
- httpSpanAttributes: only set server.address when host is non-empty
- Tests: find spans by name instead of index to avoid flakiness
- Add TestTracingWrapperSpanErrorStatus verifying codes.Error for 5xx
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
core_coverage_test.go (1)

176-251: Add regression cases for the 101/1xx branch.

statusRecorder now has special handling for 101 Switching Protocols and informational 1xx responses, but the new tests only cover 200/404/500 and implicit 200. A 101 case plus a 103 -> 200 sequence would lock down the branch that makes the recorder non-trivial.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@core_coverage_test.go` around lines 176 - 251, Add tests exercising the 1xx
branch: in TestTracingWrapper_StatusCodes add a case that the handler calls
WriteHeader(http.StatusSwitchingProtocols) and assert wrapped response code
becomes 101, and add another case that first writes an informational status
(e.g. 103) then later writes a final status (e.g. 200) to verify the recorder
transitions to the final 200; target the tracingWrapper-wrapped handler and/or
directly construct a statusRecorder to assert its status field behavior for the
101 and 103->200 sequence so the special handling in statusRecorder is covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@core.go`:
- Around line 248-259: The span records 200 when a handler panics before headers
because statusRecorder.initializes status to http.StatusOK; change the behavior
so a missing explicit status is distinguishable and treated as 500 in panic
paths: make statusRecorder start with a zero/undefined status, ensure
statusRecorder sets status only in WriteHeader (and on first Write if
WriteHeader was never called), and update endSpan (called in the deferred block
alongside serverSpan) to treat an undefined/zero status as
http.StatusInternalServerError before setting span attributes; keep the same
statusRecorder and endSpan symbols so the deferred endSpan(serverSpan, rec)
correctly records 500 for panics that write a 500 later by net/http.

---

Nitpick comments:
In `@core_coverage_test.go`:
- Around line 176-251: Add tests exercising the 1xx branch: in
TestTracingWrapper_StatusCodes add a case that the handler calls
WriteHeader(http.StatusSwitchingProtocols) and assert wrapped response code
becomes 101, and add another case that first writes an informational status
(e.g. 103) then later writes a final status (e.g. 200) to verify the recorder
transitions to the final 200; target the tracingWrapper-wrapped handler and/or
directly construct a statusRecorder to assert its status field behavior for the
101 and 103->200 sequence so the special handling in statusRecorder is covered.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b0e0e04-7107-4b85-9443-0bf3da41334f

📥 Commits

Reviewing files that changed from the base of the PR and between 31c93af and e4c4757.

📒 Files selected for processing (4)
  • config/README.md
  • core.go
  • core_coverage_test.go
  • initializers.go

Comment thread core.go Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@core.go`:
- Around line 217-244: In httpSpanAttributes, url.scheme is being taken from
r.URL.Scheme which is empty for server requests; change the logic in
httpSpanAttributes to set scheme by checking r.TLS first (if non-nil => "https",
else "http") and only fall back to r.URL.Scheme for edge cases, then append
semconv.URLScheme with that derived scheme; update uses of r.URL.Scheme in
httpSpanAttributes to use the new derived variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2e95c3eb-c0c1-4375-a7fa-e43d73a40efb

📥 Commits

Reviewing files that changed from the base of the PR and between e4c4757 and be90f26.

📒 Files selected for processing (2)
  • core.go
  • core_coverage_test.go
✅ Files skipped from review due to trivial changes (1)
  • core_coverage_test.go

Comment thread core.go
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread core_coverage_test.go
Comment thread core_coverage_test.go
Comment thread core_coverage_test.go
Comment thread core_coverage_test.go
Comment thread core.go Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread core.go
Comment thread core_coverage_test.go
@ankurs ankurs requested a review from Copilot March 29, 2026 09:35
@ankurs ankurs merged commit c0dd090 into main Mar 29, 2026
7 checks passed
@ankurs ankurs deleted the fix/http-span-name branch March 29, 2026 09:42
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread core.go
Comment on lines +246 to +250
} else {
scheme = "http"
}
}
attrs = append(attrs, semconv.URLScheme(scheme))
Copy link

Copilot AI Mar 29, 2026

Choose a reason for hiding this comment

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

httpSpanAttributes is documented as "omitting empty-valued attributes", but the new logic always appends url.scheme (defaulting to "http"). Either update the function comment to match the new behavior, or only set url.scheme when it’s explicitly known (URL scheme provided, TLS present, or a trusted forwarded-proto header).

Suggested change
} else {
scheme = "http"
}
}
attrs = append(attrs, semconv.URLScheme(scheme))
}
}
if scheme != "" {
attrs = append(attrs, semconv.URLScheme(scheme))
}

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch on the comment — url.scheme is now always set (derived from X-Forwarded-Proto / r.TLS / default http). The function comment should be updated. Will fix if we do another pass on this PR.

Comment thread core.go
Comment on lines +269 to +279
defer func() {
if recovered := recover(); recovered != nil {
if !rec.wroteHeader {
rec.status = http.StatusInternalServerError
}
serverSpan.RecordError(fmt.Errorf("panic: %v", recovered))
serverSpan.SetStatus(codes.Error, "panic")
endSpan(serverSpan, rec)
panic(recovered)
}
endSpan(serverSpan, rec)
Copy link

Copilot AI Mar 29, 2026

Choose a reason for hiding this comment

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

The new panic recovery path updates the span (RecordError/SetStatus) and may force a 500 status, but there’s no test covering this behavior. Add a test that triggers a panic in the wrapped handler, asserts the request panics (recovered in the test), and verifies the exported span has http.response.status_code=500 and Status.Code==Error (and ideally an error event/recorded error).

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Valid — a panic recovery test would strengthen coverage. Adding OTel SDK as a test dep already enabled span assertions; a panic test is a good follow-up alongside the existing TestTracingWrapperSpanErrorStatus.

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