Tail Sampling Decision
Decide whether to keep a completed trace from its duration, error status and a fallback sample rate.
Code
from dataclasses import dataclass, field
import random
@dataclass
class Span:
name: str
duration_ms: float
error: bool = False
@dataclass
class Policy:
slow_ms: float = 500.0
keep_errors: bool = True,
fallback_rate: float = 0.01
def decide(spans: list['Span'], policy: Policy, rng: random.Random | None = None) -> tuple[bool, str]:
rng = rng or random.Random()
if not spans:
return False, 'empty'
if policy.keep_errors and any(s.error for s in spans):
return True, 'error'
slowest = max(s.duration_ms for s in spans)
if slowest >= policy.slow_ms:
return True, 'slow'
if rng.random() < policy.fallback_rate:
return True, 'sampled'
return False, 'dropped'How the snippet works
The working surface is the class class and the function decide — everything else is wiring.
Applying it
Entry signature: def decide(spans: list['Span'], policy: Policy, rng: random.Random | None = None) -> tuple[bool, str]
The surface worth importing is decide; the helpers around it are private to the snippet.
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `dataclasses`, `random`. The file defines `decide` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.