sampling: undetermined validation results and repair feedback

Đang mở
#1,720 0 bình luận 0 reaction 1 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 3 ngày

@planetf1 đang làm issue này rồi.

Từ ngày 8/10/2026.

Đánh giá

Issue này chưa được đánh giá.

Mô tả

area/requirement area/sampling area/telemetry bug p1

Status (2026-10-20). Consolidation host for validation-result truthfulness on the
requirement/sampling side. Absorbs:

  • #1673, duplicate of this issue's original scope;
  • #1674, the observability half: an undetermined result is recorded as an ordinary
    failure in traces and metrics (package 2 below);
  • #1675, the mirror image on the same dataclass: error has no consumer, score
    has no producer (package 3 below).

Three packages; package 3 is sequenced after #1738 (same validate() code). The
absorbed issues' full bodies stay readable on the closed issues.

Problem

When you attach requirements to a call with a sampling strategy, the reasonable
expectation is that the response is regenerated only when a requirement says it's wrong.
Two things break that.

A requirement can fail to reach a verdict at all. Its adapter errors, or its judge
output can't be parsed. ValidationResult already records that case. It carries the
exception on error, and as_bool() returns False so nothing passes by accident
(mellea/core/requirement.py:108-112). The sampling loop doesn't tell the two apart. It
checks bool() on each result (mellea/stdlib/sampling/base.py:476), and nothing under
mellea/stdlib/sampling/ reads error. So a check that never ran counts as a failure,
and the loop spends its budget regenerating.

With a stub backend and one requirement whose validation always returns
ValidationResult(False, error=RuntimeError("adapter down")):

  • RepairTemplateStrategy(loop_budget=3) generated three times, and both retries were
    told: The following requirements failed before: * Response must be grounded
  • With a second requirement that genuinely failed (reason="too long"), the repair
    instruction listed both.
  • RejectionSamplingStrategy(loop_budget=3) generated three times.

What the user sees: every retry costs a full generation and a full validation pass, and
the instruction steers the model away from an answer that was never judged.
MultiTurnStrategy and SOFAI return a later, rewritten attempt;
RejectionSamplingStrategy and RepairTemplateStrategy return the first attempt
(base.py:562, :606), after spending the budget anyway.

This already happens in shipped code. Requirement.validate returns an errored result
whenever a custom output_to_bool raises (mellea/core/requirement.py:440-453), which
is how ALoraRequirement handles unparsable adapter output. The docs promise more than
the loop delivers: docs/docs/tutorials/08-adapter-schema-migrations.md:129-132 says a
schema mismatch "is never silently treated as 'requirement not met'", which holds for a
direct validate() call but not under sampling. #1718 makes GroundednessRequirement
produce errored results too, which makes the case routine.

And when a requirement did fail, the repair loop can be told the wrong thing. For a
requirement validated by an adapter, the failure line in the retry prompt is the
adapter's raw JSON (* {"requirement_check": {"score": 0.15}}), a wire format in the
one slot meant to explain what went wrong, while the typed score field built to carry
that number stays empty (package 3).

Telemetry has the same blind spot (package 2): RequirementMetricsPlugin records an
errored result as an ordinary failure labelled "LLM judgment"
(mellea/telemetry/metrics_plugins.py:485-494), and the validation tracing plugin drops
results with no reason (mellea/telemetry/tracing_plugins.py:601-602).

Package 1: an undetermined result never drives repair

Decision: A2 (re-validate the same response once, then stop quietly). The options
considered are kept at the end of this package for the record.

Requirements
  1. In the built-in strategies, an undetermined result never drives repair or resampling.
  2. When the only failures are undetermined, sampling re-validates the same response once
    (no regeneration), then stops: success=False, the response chosen by
    select_from_failure, the errored results in sample_validations, and a warning
    naming the requirement and the exception.
  3. When some failures are genuine, repair goes ahead on those, and undetermined
    requirements add nothing to the repair instruction.
  4. The outcome stays fail-closed: a run that ends on undetermined results doesn't report
    success.
  5. The exception stays reachable, on the ValidationResult in sample_validations and
    in the logs.
Proposed approach

Split each iteration's failures into two groups: results with error set, and the rest.
Only the second group drives repair() or a resample. The built-in repair() methods
are all @staticmethod, and SOFAI doesn't subclass BaseSamplingStrategy
(mellea/stdlib/sampling/sofai.py:45), so make the split a module-level function in
mellea/stdlib/sampling/base.py and use it in:

  • the BaseSamplingStrategy loop's stop check (base.py:476-509);
  • BudgetForcingSamplingStrategy, which overrides _sample with its own stop check and
    repair call (mellea/stdlib/sampling/budget_forcing.py:253-285);
  • RepairTemplateStrategy.repair (base.py:631-646) and MultiTurnStrategy.repair
    (base.py:698-712);
  • ModelFriendlyRepairStrategy (mellea/stdlib/sampling/feedback.py);
  • SOFAI: its repair feedback (sofai.py:145-153), its S2 summary (sofai.py:487-492),
    and its S1 loop (sofai.py:723, :746-751). Leave undetermined results out of the
    "no improvement" comparison, and when the only failures left are undetermined, return
    before Phase 2 (sofai.py:784) so it doesn't escalate to S2.

RejectionSamplingStrategy.repair already ignores validation results
(base.py:565-584), so for it only the stop check changes.

Custom strategies that override repair() still receive errored results in past_val.
Requirement 1 covers the built-ins. Document how a custom strategy can detect an
undetermined result (result.error is not None).

Decision record: what happens when the only failures are undetermined

Today a transient error can recover. If attempt 1's validation errors and the
regenerated attempt 2 validates and passes, the run ends with success=True. Every
option below changes that for some callers, so it's part of the choice.

A. Return the response (quiet stop). The loop ends early and takes the normal
failure path: success=False, the response chosen by select_from_failure, and the
errored results in sample_validations. Log a warning naming the requirement and the
exception; the current failure message is info-level (base.py:380-385).

  • For: it's the convention ValidationResult already uses, where the exception is
    carried and not raised (core/requirement.py:440-453). The loop already treats a
    raising subsample the same way: it logs a warning and carries on, and raises only when
    no attempt produced anything (base.py:359-374). Callers still get a response back,
    as they do after an errored run today.
  • Against: a run that would have recovered on a later attempt now reports
    success=False. It's also easy to miss: a deployment with a permanently broken
    adapter returns unvalidated responses with only a warning in the logs.
  • Long term: an opt-in raise can be added later without breaking anyone.

A2. Re-validate the same response once, then quiet stop. Before stopping, run
validation again on the same response, with no regeneration. If it now reaches a
verdict, carry on as normal.

  • For: recovers transient failures (a dropped connection, a backend timeout) without
    regenerating a response that may be fine.
  • Against: one extra validation pass on every undetermined run. It doesn't help
    deterministic failures: an adapter at temperature 0 that produced unparsable output
    will usually do so again for the same input, where a regenerated response might have
    parsed.
  • Long term: the retry count could become configurable, but one is enough to start.

B. Raise. The loop raises an exception carrying the errored results.

  • For: impossible to miss. A broken deployment fails on the first call instead of
    quietly returning unvalidated output.
  • Against: a breaking change. Callers using ALoraRequirement or a custom
    output_to_bool get a response after an errored run today; under B they get an
    exception they've never had to handle. A single transient error also ends a run the
    caller might have accepted unvalidated.
  • Long term: hard to soften later, since switching back to returning is another
    behaviour change.

C. A strategy option, defaulting to A or A2.

  • For: callers who want B can opt in.
  • Against: more API surface for a case that's still uncommon.
  • Long term: this is where A ends up if anyone asks for B, so it can wait until someone
    does.

Decided: A2. It keeps the convention the codebase already uses in two places,
recovers the transient case that A would lose, and leaves C available later without
breaking anyone. B is the one option that's expensive to undo.

Package 2: telemetry distinguishes undetermined from failed

From #1674 (root cause confirmed against main at 4c53add4e, 2026-10-05). Five links
in the chain:

  1. Requirement.validate's except (mellea/core/requirement.py:447-453) returns a
    result with error=exc, reason=None (deliberate; the comment there explains
    why), so nothing ever raises.
  2. The post-check payload in mellea/stdlib/functional.py sets exception only inside
    the wrapping except BaseException around the gather; an errored-but-returned result
    never passes through it, so payload.exception stays None.
  3. ValidationTracingPlugin.on_post_check
    (mellea/telemetry/tracing_plugins.py:592-610) forwards that None, and
    finish_validation_span (mellea/telemetry/tracing.py:~957) branches on
    exception is None → the span closes OK. The plugin docstring states the intent:
    "Close the validation span, ERROR only when validation raised."
  4. The failure_reasons comprehension (:602) collects r.reason for failing results
    (None on this path by design), so the span records no reason either.
  5. The metrics plugin (mellea/telemetry/metrics_plugins.py:~487) falls through to the
    ordinary judgment-failure label without reading .error.

Net effect: the one case where the check did not run is indistinguishable in
traces and metrics from "the model did not meet the requirement". A dashboard shows the
requirement failing and points at the model; the adapter is the broken part.

Fix (plugins only; validate()'s fail-closed contract is correct and stays):

  • in on_post_check, append a marker to failure_reasons when a failing result carries
    .error (e.g. "validation error: {type(exc).__name__}: {exc}");
  • in finish_validation_span, treat "a result failed closed with an error" as the ERROR
    case alongside "validation raised" (update the :596 docstring wording to match);
  • in the metrics plugin, read .error and label this failure class distinctly from an
    ordinary judgment failure.

Scope: two telemetry plugin files plus the span-finish helper. One behaviour change to
flag: validation spans close ERROR for a new class of event, so dashboards and alerts on
span status see more errors, which is the point.

Package 3: repair feedback carries a usable reason

From #1675. Sequenced after #1738, which edits the same validate() code.

validate() assigns the adapter's own output as the reason
(mellea/core/requirement.py:425-430); the "yes"/"no" special case is the only
thing that replaces it. So a failed adapter-backed requirement contributes its raw JSON
to the retry prompt, and the typed score field is never filled: no production
ValidationResult(...) call site passes score=. Consequences:

  • the retry gains nothing from having failed: the requirement description is already
    rendered by the instruction's requirements block, and the one block describing the
    failed attempt offers a key name and a number the model can't interpret;
  • a caller wanting to route on the score has to re-parse the reason string written for
    a human;
  • SOFAI's no-improvement signature (req.description, val.reason, val.score)
    (sofai.py:724) compares a third element that is always None; it works by
    accident through the reason string;
  • the pass threshold is a hardcoded 0.5
    (mellea/stdlib/requirements/requirement.py:62).

Proposal: parse the adapter's output into the fields built for it.

  • validate() sets score from a graded validator.
  • reason stops carrying machine output: the requirement description, or a short
    rendering a person would read. The "yes"/"no" special case becomes the general
    rule it was reaching for: a reason is for a human and for the repair prompt, so a
    machine-readable payload never belongs in it.
  • Decide where the threshold lives (options kept in #1675's body): keep 0.5 in
    requirement_check_to_bool; make it a constructor argument on ALoraRequirement; or
    return only the score and let strategies threshold.

A stub-backend reproducer exists in #1675's body (no GPU, no adapter needed) and
converts directly to tests. What this deliberately does not claim: populating score
does not make it calibrated: nothing in mellea has measured whether adapter scores are
calibrated, and carrying the number properly is the prerequisite for measuring that,
not the claim.

What to check while doing it (from #1675): whether the three graded adapter functions
mean the same thing. requirement_check is satisfaction, check_certainty is the
model's self-assessed certainty, and guardian_check is an inverted risk score
(intrinsic/guardian.py:219-220). Glossing over that gives a threshold meaning "accept
above" for one requirement and "reject above" for another, with nothing in the type to
warn the user.

Testing and documentation

Unit tests with a stub backend like mocked_context_backend
(test/stdlib/sampling/test_sampling_base_unit.py:121):

  • Package 1: undetermined only. Each built-in strategy, including budget forcing
    and SOFAI, never regenerates or repairs, returns success=False, keeps the exception
    in sample_validations, logs the warning. Undetermined plus a genuine failure: the
    repair instruction names only the genuine one (repair template, multi-turn, SOFAI,
    model-friendly). Mixed then resolved: both pass on attempt 2, success=True. SOFAI:
    no S2 escalation when the only failures are undetermined. Re-validation: an error on
    the first validation and a pass on the re-validation gives success=True with no
    regeneration.
  • Package 2: an undetermined result appends a failure_reasons marker, closes its
    span ERROR, and is labelled distinctly in metrics, not as an "LLM judgment" failure.
  • Package 3: score is populated from a graded validator; reason is not raw JSON;
    the SOFAI signature varies through score rather than by accident; the escalation
    trigger is tested deliberately rather than left to inherit the accident.

Docs:

  • docs/docs/concepts/instruct-validate-repair.md: describe what happens when a
    requirement can't reach a verdict, and how a custom strategy can detect it.
  • docs/docs/tutorials/08-adapter-schema-migrations.md:129-132: once this ships, its
    claim holds under sampling too; add a line saying so.
  • The PR descriptions should call out the behaviour changes, since the changelog is
    generated from PR titles.

#1718 and package 3 both edit ModelFriendlyRepairStrategy's generic branch in
feedback.py; doing #1718 first keeps that simple. #1071 (Guardian requirement
subclass) proposes ValidationResult(result=score < threshold, ...), which drops the
float exactly as requirement_check_to_bool does; if it merges before this package, it
should carry the score.

Line references are against 46ad3b3a5 (#1674's against 4c53add4e; #1675's against
its own filing).

Related

  • #1718: GroundednessRequirement errors are not verdicts; feeds package 1 with real
    errored results.
  • #1497 / PR #1727: the SOFAI half of the repair-feedback fix; #1727 deliberately
    leaves the RepairTemplateStrategy reason path to package 3 here (the two come from
    one branch and should be fixed together).
  • #1358 (closed): added error to ValidationResult; the precedent for extending what
    a result carries rather than widening the boolean.
  • #1499: asks for the SamplingResult inspection surface to be documented; a
    per-validation score is part of what a caller wants from it.
  • #1071: the Guardian instance of the score gap.
Ngôn ngữ chính
Python
Star
1.8k
Fork
161
Merge trung bình
4 ngày 3 giờ
Pull request đã merge (30 ngày)
45

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của generative-computing/mellea

Tất cả issue của generative-computing/mellea

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.