diff --git a/CHANGES.md b/CHANGES.md index f37703d8..3b17bd7f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -23,6 +23,7 @@ Release Notes. * Update `docs/en/agent/support-plugins.md` with the framework version ranges verified by the plugin test scenarios, and describe the two grpc plugins. * Update the Go versions of the published base images in `docs/en/setup/docker.md` to Go 1.26 and Go 1.27. * Describe in `docs/en/development-and-contribution/write-plugin-testing.md` how each plugin test case pins its framework version and builds outside the repository workspace, and document the `toolkit` and `excepted-file` options. +* Describe the sampling policy in `docs/en/agent/tracing-metrics-logging.md`: `agent.sampler` applies only to the traces that a service starts, and a request with a valid upstream `sw8` header is always traced. Fix the environment key of `agent.sampler` there, which is `SW_AGENT_SAMPLE`, not `SW_AGENT_SAMPLER`. #### Bug Fixes @@ -46,6 +47,7 @@ Release Notes. * kratos: do not panic in the client middleware when a body-less HTTP call reads the reply header into a nil `http.Header`. Since kratos v2.7.2, that header is sent as the request header. * go-micro: do not fail a call, stream, or publish when its exit span cannot be created, for example a call with an empty service name and `client.WithAddress`. The call runs untraced, and the peer of the caller's span does not change. * Bump vulnerable dependencies in the agent module, the reporter (`plugins/core`), and the go-agent tool. `github.com/klauspost/compress` moves from v1.15.9 to v1.18.7 to fix CVE-2026-63209, `golang.org/x/net` moves from v0.61.0 to v0.62.0 to fix GO-2026-6860 and GO-2026-6866, and `github.com/sirupsen/logrus` in the go-agent tool moves from v1.9.0 to v1.9.4 to fix CVE-2025-65637. +* Keep a trace that the caller has already sampled. An entry span that starts a tracing context checked for the upstream `sw8` reference before attaching it, so the local sampler ran even when the request carried a valid `sw8` header: with `agent.sampler` below 1, a downstream service dropped already-sampled traces, sent no `sw8` header onward, and its own downstream services could start unrelated traces. The sampler also received an empty operation name, and the `sw_go_created_tracing_context_counter{created_by="propagated"}` self-observability counter never increased. A `sw8` header now counts as valid only when every required field is set, as in the Java agent, so a header such as `1---0----` no longer creates a segment with an empty trace ID. #### Unsupported Library Versions diff --git a/docs/en/agent/tracing-metrics-logging.md b/docs/en/agent/tracing-metrics-logging.md index ec6e263e..9e37ebc4 100644 --- a/docs/en/agent/tracing-metrics-logging.md +++ b/docs/en/agent/tracing-metrics-logging.md @@ -24,7 +24,7 @@ The basic configuration is as follows: | Name | Environment Key | Default Value | Description | |-------------------------|----------------------------|--------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------| -| agent.sampler | SW_AGENT_SAMPLER | 1 | Sampling rate of tracing data, which is a floating-point value that must be between 0 and 1. | +| agent.sampler | SW_AGENT_SAMPLE | 1 | Sampling rate of tracing data, which is a floating-point value that must be between 0 and 1. It applies only to the traces that this service starts. A request that carries a valid `sw8` header from an upstream service is always traced, so the upstream sampling decision is kept. The [sw8 protocol](https://skywalking.apache.org/docs/main/next/en/api/x-process-propagation-headers-v3/#sampling) defines a sample flag in the header, but by the convention of the SkyWalking agent implementations, it is always `1` and is not checked: SkyWalking builds complete metrics and topology from the reported traces, so agents commonly sample 100%, and storage is reduced by trace sampling at the OAP server instead. `agent.ignore_suffix`, `agent.trace_ignore_path`, and a disconnected reporter still take precedence. | | agent.ignore_suffix | SW_AGENT_IGNORE_SUFFIX | .jpg,.jpeg,.js,.css,.png,.bmp,.gif,.ico,.mp3,.mp4,.html,.svg | If the suffix obtained by splitting the operation name by the last index of "." in this set, this segment should be ignored.(multiple split by ","). | | agent.trace_ignore_path | SW_AGENT_TRACE_IGNORE_PATH | | If the operation name of the first span is matching, this segment should be ignored.(multiple split by ","). | diff --git a/plugins/core/propagating.go b/plugins/core/propagating.go index 57569952..8a7ad390 100644 --- a/plugins/core/propagating.go +++ b/plugins/core/propagating.go @@ -159,10 +159,21 @@ func (s *SpanContext) DecodeSW8(header string) error { if err != nil { return errors.Wrap(err, "network address parse error") } - s.Valid = true + s.Valid = s.hasRequiredFields() return nil } +// hasRequiredFields reports whether the decoded sw8 header carries every +// required field. A valid header forces sampling, so like the Java agent's +// ContextCarrier#isValid, a header that decodes but misses a field, such as +// "1---0----", is ignored: the request starts a new trace, subject to the +// local sampler. +func (s *SpanContext) hasRequiredFields() bool { + return s.TraceID != "" && s.ParentSegmentID != "" && s.ParentSpanID >= 0 && + s.ParentService != "" && s.ParentServiceInstance != "" && + s.ParentEndpoint != "" && s.AddressUsedAtClient != "" +} + // EncodeSW8 converts SpanContext to string header func (s *SpanContext) EncodeSW8() string { return strings.Join([]string{ diff --git a/plugins/core/tracing.go b/plugins/core/tracing.go index bae6492a..3f354426 100644 --- a/plugins/core/tracing.go +++ b/plugins/core/tracing.go @@ -342,6 +342,12 @@ func (t *Tracer) createNoop(operationName string) (*TracingContext, TracingSpan, func (t *Tracer) createSpan0(ctx *TracingContext, parent TracingSpan, pluginOpts []interface{}, coreOpts ...interface{}) (s TracingSpan, noop bool, err error) { ds := NewDefaultSpan(t, parent) + // process the opts from agent core for prepare building segment span. + // They must run before the sampling decision below: they set the upstream + // refs (which force sampling) and the operation name passed to the sampler. + for _, opt := range coreOpts { + opt.(tracing.SpanOption).Apply(ds) + } var parentSpan SegmentSpan if parent != nil { tmpSpan, ok := parent.(SegmentSpan) @@ -360,10 +366,6 @@ func (t *Tracer) createSpan0(ctx *TracingContext, parent TracingSpan, pluginOpts return newNoopSpan(t), true, nil } } - // process the opts from agent core for prepare building segment span - for _, opt := range coreOpts { - opt.(tracing.SpanOption).Apply(ds) - } s, err = NewSegmentSpan(ctx, ds, parentSpan) if err != nil { return nil, false, err diff --git a/plugins/core/tracing_test.go b/plugins/core/tracing_test.go index 22a6bc59..8d874ccb 100644 --- a/plugins/core/tracing_test.go +++ b/plugins/core/tracing_test.go @@ -297,6 +297,69 @@ func TestSpanContextReading(t *testing.T) { assert.Equal(t, parentEndpoint, refCtx.GetParentEndpoint(), "ref endpoint not correct") } +type recordingSampler struct { + decision bool + operations []string +} + +func (s *recordingSampler) IsSampled(operation string) bool { + s.operations = append(s.operations, operation) + return s.decision +} + +func TestPropagatedContextIsNotResampled(t *testing.T) { + defer ResetTracingContext() + sampler := &recordingSampler{decision: false} + Tracing.Sampler = sampler + s, err := tracing.CreateEntrySpan("/entry", func(key string) (string, error) { + if key == Header { + return header, nil + } + return "", nil + }) + assert.NoError(t, err) + assert.Empty(t, sampler.operations, "the sampler must not run for a propagated context") + assert.Equal(t, traceID, s.TraceID(), "the upstream trace id should be kept") + s.End() + spans := waitReportedSpans(t, 1) + if !assert.Equal(t, 1, len(spans[0].Refs()), "refs not correct") { + return + } + assert.Equal(t, parentSegmentID, spans[0].Refs()[0].GetParentSegmentID(), "ref segment id not correct") +} + +func TestIncompletePropagatedContextIsIgnored(t *testing.T) { + defer ResetTracingContext() + sampler := &recordingSampler{decision: true} + Tracing.Sampler = sampler + incomplete := (&SpanContext{Sample: sample, ParentSpanID: parentSpanID}).EncodeSW8() // "1---0----" + s, err := tracing.CreateEntrySpan("/entry", func(key string) (string, error) { + if key == Header { + return incomplete, nil + } + return "", nil + }) + assert.NoError(t, err) + assert.Equal(t, []string{"/entry"}, sampler.operations, "an incomplete header must not force sampling") + assert.NotEmpty(t, s.TraceID(), "the request should start a new trace") + assert.NotEqual(t, "N/A", s.TraceID(), "the request should start a new trace") + s.End() + spans := waitReportedSpans(t, 1) + assert.Empty(t, spans[0].Refs(), "an incomplete header must not become a ref") +} + +func TestSamplerReceivesOperationName(t *testing.T) { + defer ResetTracingContext() + sampler := &recordingSampler{decision: false} + Tracing.Sampler = sampler + s, err := tracing.CreateEntrySpan("/entry", func(key string) (string, error) { + return "", nil + }) + assert.NoError(t, err) + s.End() + assert.Equal(t, []string{"/entry"}, sampler.operations, "the sampler should receive the operation name") +} + func TestReporterDisconnect(t *testing.T) { defer ResetTracingContext() ReportConnectionStatus = reporter.ConnectionStatusDisconnect diff --git a/test/plugins/scenarios/so11y/config/excepted.yml b/test/plugins/scenarios/so11y/config/excepted.yml index 60232110..5d147924 100644 --- a/test/plugins/scenarios/so11y/config/excepted.yml +++ b/test/plugins/scenarios/so11y/config/excepted.yml @@ -116,7 +116,7 @@ meterItems: name: sw_go_created_tracing_context_counter tags: - {name: created_by, value: propagated} - singleValue: 0.0 + singleValue: 2.0 - meterId: name: sw_go_created_ignored_context_counter tags: @@ -131,5 +131,5 @@ meterItems: name: sw_go_created_tracing_context_counter tags: - {name: created_by, value: sampler} - singleValue: 6.0 + singleValue: 4.0 logItems: [ ]