Skip to content

feat(telemetry): add sampling and validator tracing spans via hooks - #1488

Merged
ajbozarth merged 1 commit into
generative-computing:mainfrom
ajbozarth:feat/1050-sampling-validator-formatter
Aug 3, 2026
Merged

ajbozarth merged 1 commit into
generative-computing:mainfrom
ajbozarth:feat/1050-sampling-validator-formatter

Conversation

@ajbozarth

Copy link
Copy Markdown
Member

Pull Request

Issue

Fixes #1050

Description

Adds sampling and validation tracing spans, emitted by two new plugins (SamplingTracingPlugin, ValidationTracingPlugin) that subscribe to the sampling and validation lifecycle hooks already dispatched by BaseSamplingStrategy.sample() and avalidate().

#1050 also named the formatter, which is intentionally left out: it's a synchronous render step with no duration or place in the trace tree of its own, so it isn't a meaningful span. The data worth capturing from that path — the prompt template and its variables — is component-level information the formatter merely renders, and it belongs as attributes on the backend chat span, which is #1067's scope (llm.prompt_template.*).

Two new plugins in mellea/telemetry/tracing_plugins.py:

  • SamplingTracingPlugin — emits a sampling application span per sampling loop, opened on sampling_loop_start and closed on sampling_loop_end. Each attempt and repair is recorded as a span event (iteration / repair) rather than a child span, so the markers stay on the one span alongside the backend chat spans the same calls emit.
  • ValidationTracingPlugin — emits a validation application span per requirement-validation batch, opened on validation_pre_check and closed on validation_post_check.

Supporting changes:

  • Correlation ids: added observe-only sampling_id / validation_id fields to the sampling and validation hook payloads, minted once at each dispatch site (sample() and avalidate()) so the paired open/close hooks correlate.
  • Span helpers in tracing.py: start/finish_sampling_span, start/finish_validation_span, and a generic add_span_event (renamed from the streaming-specific add_streaming_event, now shared).
  • Error-path span closure: sample() and avalidate() fire their end hook from a try/finally with an optional exception field, so a raised loop/check still closes its span. ERROR status is driven only by an exception — a routine budget-exhausted loop or failing check closes with default status. The metrics and builtin_debug plugins skip the outcome on the exception path.
  • Docs: documented the sampling and validation spans and corrected the span-hierarchy diagrams in tracing.md / telemetry.md (they referenced a requirement_validation span that never existed — the real span is validation).

Notes for reviewers

  • Nesting is session → action → sampling → {chat, validation} on Python 3.12+; on ≤3.11 hook-attached spans collapse to session (same documented degradation as all existing tracing plugins).
  • The add_streaming_event → add_span_event rename updates StreamingTracingPlugin's call sites; no compat shim.
  • The sampling span covers strategies that use the BaseSamplingStrategy loop. Strategies that override sample() with a custom loop (SOFAI, budget-forcing, majority-voting) don't emit it — that coupling is tracked as a follow-up in fix(sampling): sampling span missing for strategies that override sample() #1487, out of scope here.
  • Telemetry plugin priorities moved from the 40s/50s into the 1040s/1050s so they run after user hooks and observe the final post-hook payload state (fixes sampling/validation spans reporting pre-mutation loop_budget/requirement_count). Relative order is unchanged: tracing (1040–1045) still precedes metrics (1050–1057).

Testing

  • Tests added to the respective file if code was changed
  • New code has 100% coverage if code was added
  • Ensure existing tests and github automation passes (a maintainer will kick off the github automation when the rest of the PR is populated)

Attribution

  • AI coding assistants used

Adding a new component, requirement, sampling strategy, or tool?

If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

Add SamplingTracingPlugin and ValidationTracingPlugin, emitting `sampling`
and `validation` application spans through the existing sampling and validation
lifecycle hooks.

- Add observe-only correlation-id fields (`sampling_id`, `validation_id`) to
  the sampling/validation hook payloads, minted at the dispatch sites so the
  paired open/close hooks correlate.
- Add `start/finish_sampling_span`, `start/finish_validation_span`, and a
  generic `add_span_event` (renamed from `add_streaming_event`) to tracing.py;
  iterations and repairs are recorded as span events on the sampling span.
- Fire the sampling/validation end hooks on the error path (via try/finally
  with an optional `exception` field) so a raised loop/check still closes its
  span with ERROR status; a routine budget-exhaustion or failing check closes
  with default status. Metrics and builtin_debug plugins skip the outcome on
  the exception path.
- Document the new spans and corrected span hierarchy in the observability docs.

Assisted-by: Claude Code
Signed-off-by: Alex Bozarth <[email protected]>
@ajbozarth
ajbozarth requested a review from a team as a code owner July 31, 2026 18:26
@ajbozarth ajbozarth added area/telemetry OTel spans, metrics, tracing, semconv area/sampling SamplingStrategy, SamplingResult, ModelOption, generation options labels Jul 31, 2026
@github-actions github-actions Bot added the enhancement New feature or request label Jul 31, 2026
@ajbozarth ajbozarth self-assigned this Jul 31, 2026

@jakelorocco jakelorocco left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm; two non-blocking questions / concerns

Comment on lines +1119 to +1122
results=rvs,
all_validations_passed=exception is None and all(bool(r) for r in rvs),
passed_count=sum(1 for r in rvs if bool(r)),
failed_count=sum(1 for r in rvs if not bool(r)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Just confirming the docstring is correct about results / counts being None/0 when exceptions are raised. These will be 0 / None since we are using asyncio.gather, so any exception will shortcircuit the for loop, right?

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.

Confirmed — the docstring is correct. On the exception path results is [] and both counts are 0, and it's independent of which coroutine failed or when. await asyncio.gather(*coroutines) resolves to a single list before the for loop runs even once, so with the default return_exceptions=False the first raise propagates out of the await and the loop body never executes — nothing gets appended to rvs. The counts aren't left at their field defaults; they're actively recomputed in the finally as sum(...) over an empty rvs, which just lands back on 0. all_validations_passed is additionally guarded by the explicit exception is None check.

Comment on lines +445 to +451
if exception is not None:
end_payload = SamplingLoopEndPayload(
sampling_id=sampling_id,
strategy_name=type(self).__name__,
success=False,
exception=exception,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Would it be worthwhile to define slices earlier so that even with an exception we can determine the number of iterations used? I think that might be helpful information but I can't think of a real use case right now...

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.

Even if we hoisted slices to report len(slices) here, it wouldn't be worth much on the exception path. Under concurrency it's a race-dependent snapshot, not a count: when one producer raises we cancel the others, so the value is however many slices happened to be drained before cancellation settled — same crash, different number each run. And on this path the exception object is the diagnostic, not the iteration count; "3 ran before it crashed" doesn't tell you why. The count is a meaningful signal on the success/budget-exhausted paths, which is exactly where it's already populated.

@ajbozarth
ajbozarth added this pull request to the merge queue Aug 3, 2026
Merged via the queue into generative-computing:main with commit bd2005f Aug 3, 2026
13 of 15 checks passed
@ajbozarth
ajbozarth deleted the feat/1050-sampling-validator-formatter branch August 3, 2026 17:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/sampling SamplingStrategy, SamplingResult, ModelOption, generation options area/telemetry OTel spans, metrics, tracing, semconv enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: sampling, validator, and formatter spans via plugin hooks

2 participants