> ## Documentation Index
> Fetch the complete documentation index at: https://docs.odigos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Span Attribute Sampler

> This action is a [Service Action](../../../pipeline/actions/introduction#scope-categories) that samples traces based on the presence or value of specific attributes within a trace.

<Warning>
  This feature is in beta. It may be subject to changes and improvements based on user feedback.
</Warning>

## Considerations

<Warning>
  Before enabling the **Service Name Sampler**, please consider the following:

  * Only supports **traces**.
  * Sampling is trace-wide: either all spans in a trace are kept, or all are dropped.
  * The sampler introduces a delay of up to 30 seconds before traces are exported.
  * Traces with durations longer than 30 seconds might not be sampled correctly.
  * Using the `json_condition` will cause a higher resource utilization!
</Warning>

## Overview

The **Span Attribute Sampler** is an action designed to sample traces from a specified service based on conditions applied to span attributes. It supports several types of attribute evaluations:

* **String Conditions:** Check for existence, equality, inequality, substring containment, or regex matching.
* **Number Conditions:** Compare numeric attribute values using equality, inequality, or threshold comparisons.
* **Boolean Conditions:** Evaluate the presence of a boolean attribute or check for a specific boolean value.
* **JSON Conditions:** Validate JSON structure or evaluate nested JSON content using JSONPath expressions.

If any span from the specified service meets the condition, the trace is sampled. Otherwise, the trace is sampled based on the configured fallback sampling ratio.

<Note>
  {" "}

  Using JSON Conditions will cause spikes in performance and resources utilization.{" "}
</Note>

## Use Cases

### Targeted Debugging

Sample only traces where a specific error flag is set. For example, sample traces from a checkout service where `error = true`.

[See example →](#match-error-in-checkout-service)

### Feature Rollout Monitoring

Retain traces for users or sessions flagged via JSON content. For instance, sample traces for an API service where the JSON payload indicates `"user.role": "admin"`.

[See example →](#json-nested-attribute-match)

### Route-Specific Analytics

Track performance or usage of specific endpoints by matching against HTTP target attributes.

[See example →](#match-http-target-endpoint)

### Production Environment Sampling

Collect traces only from the production environment.

[See example →](#sample-prod-traces)

### Latest Version Monitoring

Sample only traces from the latest relesed version, while still capturing a representative subset of older versions.

[See example →](#regex-condition-no-match)

## Configuration Options

The SpanAttributeSampler action is configured using the `odigos.io/v1alpha1.Action` CRD with the `samplers` configuration section.

<AccordionGroup>
  <Accordion title="actionName">
    **actionName** `string` : Allows you to attach a meaningful name to the action for convenience.

    * This field is *optional*
    * <Icon icon="triangle-exclamation" iconType="solid" color="yellow" /> Odigos does not use or assume any meaning from this field
  </Accordion>

  <Accordion title="notes">
    **notes** `string` : Allows you to attach notes regarding the action for convenience.

    * This field is *optional*
    * <Icon icon="triangle-exclamation" iconType="solid" color="yellow" /> Odigos does not use or assume any meaning from this field
  </Accordion>

  <Accordion title="disabled">
    **disabled** `boolean` : Allows you to temporarily disable the action, but keep it saved for future use.

    * This field is *optional*, and defaults to `false`
  </Accordion>

  <Accordion title="signals *">
    **signals** `string[]` : An array with the signals that the action will operate on.

    * This field is *required*
    * Supported values: `TRACES`
  </Accordion>

  <Accordion title="samplers *">
    **samplers** `object` : Configuration for sampling actions.

    * This field is *required* for this action type

    <AccordionGroup>
      <Accordion title="spanAttributeSampler *">
        **spanAttributeSampler** `object` : Configuration for the SpanAttributeSampler.

        * This field is *required* for this action type

        <AccordionGroup>
          <Accordion title="attribute_filters *">
            **attribute\_filters** `object[]` : An array of objects representing the filters for the service and attribute filters.

            * This field is *required*

            <AccordionGroup>
              <Accordion title="service_name *">
                **service\_name** `string` : Specifies the service name to search within the trace (Across all available spans).

                * This field is *required*
              </Accordion>

              <Accordion title="attribute_key *">
                **attribute\_key** `string` : Specifies the attribute key inside of the span.

                * This field is *required*
              </Accordion>

              <Accordion title="condition *">
                **condition** `object` : An object representing the filters for span attributes filters.

                * This field is *required*

                <AccordionGroup>
                  <Accordion title="string_condition">
                    <AccordionGroup>
                      <Accordion title="operation">
                        **operation** `string` : Specifies the operation to run against the attribute.

                        accepted values for the boolean operation:

                        * **exists** : Checks that the attribute is present (and not an empty string).
                        * **equals** : String equality comparison with expected\_value.
                        * **not\_equals** : String inequality comparison with expected\_value.
                        * **contains** : Checks if the attribute contains expected\_value as a substring.
                        * **not\_contains** : Checks if the attribute does not contain expected\_value.
                        * **regex** : Interprets expected\_value as a regular expression (RE2 syntax) and checks for a match within the attribute.
                      </Accordion>

                      <Accordion title="expected_value">
                        **expected\_value** `string` : The values to test the attribute against.

                        * Required when operation is set to one of `[equals, not_equals, contains, not_contains, regex]`.
                      </Accordion>
                    </AccordionGroup>
                  </Accordion>

                  <Accordion title="number_condition">
                    <AccordionGroup>
                      <Accordion title="operation">
                        **operation** `string` : Specifies the operation to run against the attribute.

                        accepted values for the number condition:

                        * **exists** : Checks that the numeric attribute is present (non-null).
                        * **equals** : Checks if the attribute equals expected\_value.
                        * **not\_equals** : Checks if the attribute does not equal expected\_value.
                        * **greater\_than** : Checks if attribute > expected\_value.
                        * **less\_than** : Checks if attribute \< expected\_value.
                        * **greater\_than\_or\_equal** : Checks if attribute >= expected\_value.
                        * **less\_than\_or\_equal** : Checks if attribute \<= expected\_value.
                      </Accordion>

                      <Accordion title="expected_value">
                        **expected\_value** `float` : The values to test the attribute against.

                        * Required when operation is set to one of `[equals, not_equals, greater_than, less_than, greater_than_or_equal, less_than_or_equal]`.
                      </Accordion>
                    </AccordionGroup>
                  </Accordion>

                  <Accordion title="boolean_condition">
                    <AccordionGroup>
                      <Accordion title="operation">
                        **operation** `string` : Specifies the operation to run against the attribute.

                        accepted values for the boolean operation:

                        * **exists** : Checks that the boolean attribute is present.
                        * **equals** : Checks if the attribute exactly matches expected\_value.
                      </Accordion>

                      <Accordion title="expected_value">
                        **expected\_value** `boolean` : The values to test the attribute against.

                        * Required when operation is set to `equals`.
                      </Accordion>
                    </AccordionGroup>
                  </Accordion>

                  <Accordion title="json_condition">
                    <AccordionGroup>
                      <Accordion title="operation">
                        **operation** `string` : Specifies the operation to run against the attribute.

                        accepted values for the boolean operation:

                        * **exists** : Checks that the attribute is a non-empty string.
                        * **equals** : Compares the full JSON string to expected\_value.
                        * **not\_equals** : Verifies the full JSON string is not equal to expected\_value.
                        * **is\_valid\_json** : Ensures the string parses as valid JSON.
                        * **is\_invalid\_json** : Ensures the string is not valid JSON.
                        * **jsonpath\_exists** : Asserts that the specified json\_path resolves to a non-empty result.
                        * **key\_equals** : Compares the value at json\_path to expected\_value.
                        * **key\_not\_equals** : Verifies the value at json\_path is not equal to expected\_value.
                      </Accordion>

                      <Accordion title="expected_value">
                        **expected\_value** `string` : The values to test the attribute against.

                        * Required when operation is set to one of `[equals, not_equals, jsonpath_exists, key_equals, key_not_equals]`.
                      </Accordion>

                      <Accordion title="json_path">
                        **json\_path** `string` : It is a JSONPath expression used to navigate the JSON structure.

                        * Required when operation is set to one of `[jsonpath_exists, key_equals, key_not_equals]`.
                      </Accordion>
                    </AccordionGroup>
                  </Accordion>
                </AccordionGroup>
              </Accordion>

              <Accordion title="fallback_sampling_ratio *">
                **fallback\_sampling\_ratio** `float` : Specifies the percentage of traces that don't meet the service name filter and that you still like to retain.

                * This field is *required*
              </Accordion>
            </AccordionGroup>
          </Accordion>
        </AccordionGroup>
      </Accordion>
    </AccordionGroup>
  </Accordion>
</AccordionGroup>

<Info>
  If **any span from the specified service** satisfies the attribute
  condition, the trace is sampled. If no match is found, the trace is sampled
  based on the fallback ratio.
</Info>

## Examples

Below are several YAML examples that demonstrate different use cases.

### Match Error in Checkout Service

Sample traces where the `error` attribute (a boolean) equals `true` for the `checkout-service` using the new Action CRD.

```yaml theme={null}
apiVersion: odigos.io/v1alpha1
kind: Action
metadata:
  name: checkout-errors
  namespace: odigos-system
spec:
  signals:
    - TRACES
  samplers:
    spanAttributeSampler:
      attribute_filters:
        - service_name: checkout-service
          attribute_key: error
          condition:
            boolean_condition:
              operation: equals
              expected_value: "true"
          fallback_sampling_ratio: 10
```

### JSON Nested Attribute Match

For JSON evaluation, the JSON attribute is provided as a string. In this example the rule checks that the JSONPath expression returns a value and that the nested key equals the expected value using the new Action CRD.

```yaml theme={null}
apiVersion: odigos.io/v1alpha1
kind: Action
metadata:
  name: admin-json-check
  namespace: odigos-system
spec:
  signals:
    - TRACES
  samplers:
    spanAttributeSampler:
      attribute_filters:
        - service_name: api-service
          attribute_key: payload
          condition:
            json_condition:
              operation: key_equals
              json_path: "$.user.role"
              expected_value: admin
          fallback_sampling_ratio: 5
```

### Match HTTP Target Endpoint

Sample traces where the HTTP target endpoint (a string) contains /api/products using the new Action CRD.

```yaml theme={null}
apiVersion: odigos.io/v1alpha1
kind: Action
metadata:
  name: match-api-products
  namespace: odigos-system
spec:
  signals:
    - TRACES
  samplers:
    spanAttributeSampler:
      attribute_filters:
        - service_name: frontend
          attribute_key: http.target
          condition:
            string_condition:
              operation: contains
              expected_value: "/api/products"
          fallback_sampling_ratio: 5
```

### Sample Prod Traces

For example, sample all traces from the staging environment by matching on the env attribute using the new Action CRD.

```yaml theme={null}
apiVersion: odigos.io/v1alpha1
kind: Action
metadata:
  name: sample-staging
  namespace: odigos-system
spec:
  signals:
    - TRACES
  samplers:
    spanAttributeSampler:
      attribute_filters:
        - service_name: orders-service
          attribute_key: env
          condition:
            string_condition:
              operation: equals
              expected_value: prod
          fallback_sampling_ratio: 1
```

### Regex Condition (No Match)

The following example shows a regex condition for a version string. If the version does not match the expected pattern, the rule does not match the span. In this case, if the attribute exists but fails the regex test, the trace will not be sampled by this rule (and the fallback ratio applies) using the new Action CRD.

```yaml theme={null}
apiVersion: odigos.io/v1alpha1
kind: Action
metadata:
  name: version-regex-test
  namespace: odigos-system
spec:
  signals:
    - TRACES
  samplers:
    spanAttributeSampler:
      attribute_filters:
        - service_name: test-service
          attribute_key: version
          condition:
            string_condition:
              operation: regex
              expected_value: "^v1\.2\.\d+$"
          fallback_sampling_ratio: 12
```

### Final Notes

* Multiple Filters: You can define multiple attribute filters across different services and attribute types. These filters are OR-combined; if any filter matches, the trace is sampled.
* Fallback Sampling: When no span satisfies the condition, the trace is sampled based on the `fallback_sampling_ratio`. This allows you to collect a percentage of non-matching traces for broad observability without overwhelming storage costs.
* JSON Evaluation: For JSON conditions, the sampler always uses the provided [json\_path](https://goessner.net/articles/JsonPath/) to navigate the JSON structure. Ensure that the attribute value is a JSON-encoded string.

By following these guidelines and examples, you can configure the Span Attribute Sampler for production environments with clarity and precision.
