sampling: undetermined validation results and repair feedback
Los mantenedores suelen responder en 3 días
@planetf1 ya está trabajando en esto.
Desde el 8/10/2026.
Evaluación
Este issue todavía no se ha evaluado.
Descripción
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:
errorhas 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
- In the built-in strategies, an undetermined result never drives repair or resampling.
- 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 insample_validations, and a warning
naming the requirement and the exception. - When some failures are genuine, repair goes ahead on those, and undetermined
requirements add nothing to the repair instruction. - The outcome stays fail-closed: a run that ends on undetermined results doesn't report
success. - The exception stays reachable, on the
ValidationResultinsample_validationsand
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
BaseSamplingStrategyloop's stop check (base.py:476-509); BudgetForcingSamplingStrategy, which overrides_samplewith its own stop check and
repair call (mellea/stdlib/sampling/budget_forcing.py:253-285);RepairTemplateStrategy.repair(base.py:631-646) andMultiTurnStrategy.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
ValidationResultalready 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
ALoraRequirementor a custom
output_to_boolget 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:
Requirement.validate'sexcept(mellea/core/requirement.py:447-453) returns a
result witherror=exc,reason=None(deliberate; the comment there explains
why), so nothing ever raises.- The post-check payload in
mellea/stdlib/functional.pysetsexceptiononly inside
the wrappingexcept BaseExceptionaround the gather; an errored-but-returned result
never passes through it, sopayload.exceptionstaysNone. ValidationTracingPlugin.on_post_check
(mellea/telemetry/tracing_plugins.py:592-610) forwards thatNone, 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."- The
failure_reasonscomprehension (:602) collectsr.reasonfor failing results
(Noneon this path by design), so the span records no reason either. - 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 tofailure_reasonswhen 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:596docstring wording to match); - in the metrics plugin, read
.errorand 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 alwaysNone; 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()setsscorefrom a graded validator.reasonstops 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 onALoraRequirement; 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, returnssuccess=False, keeps the exception
insample_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 givessuccess=Truewith no
regeneration. - Package 2: an undetermined result appends a
failure_reasonsmarker, closes its
span ERROR, and is labelled distinctly in metrics, not as an "LLM judgment" failure. - Package 3:
scoreis populated from a graded validator;reasonis not raw JSON;
the SOFAI signature varies throughscorerather 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:
GroundednessRequirementerrors are not verdicts; feeds package 1 with real
errored results. - #1497 / PR #1727: the SOFAI half of the repair-feedback fix; #1727 deliberately
leaves theRepairTemplateStrategyreason path to package 3 here (the two come from
one branch and should be fixed together). - #1358 (closed): added
errortoValidationResult; the precedent for extending what
a result carries rather than widening the boolean. - #1499: asks for the
SamplingResultinspection 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.
- Lenguaje dominante
- Python
- Estrellas
- 1.8k
- Forks
- 161
- Merge medio
- 4 d 3 h
- PR fusionados (30 d)
- 45
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de generative-computing/mellea
-
bug: `mellea.plugins.builtin_debug.generation.log_generation_post_call` shows model as unknownAbiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
generative-computing/mellea#1864 ·
Los mantenedores suelen responder en 3 días
-
bug: instruct() and react() replay tool-call turns without tool_callsPosiblemente ocupada @simonyang08 la tomó hace 21 días. Abiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
generative-computing/mellea#1784 · 1 comentario ·
Los mantenedores suelen responder en 3 días
-
Silently mangled docstrings: lone backslash line-continuations in non-raw docstrings collapse command examplesPosiblemente ocupada @madhusudhan1260 la tomó hace 18 días. Abiertogood first issue p2
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
generative-computing/mellea#1780 · 2 comentarios · 1 asignado ·
Los mantenedores suelen responder en 3 días
-
area/telemetry enhancement p2
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
generative-computing/mellea#1210 ·
Los mantenedores suelen responder en 3 días
-
Add requirement priorityAbiertoarea/requirement area/stdlib enhancement p2
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
generative-computing/mellea#31 · 2 comentarios ·
Los mantenedores suelen responder en 3 días
Todos los issues de generative-computing/mellea
Issues similares
-
cron: raise a distinct error when next_fire finds no match in its search bound (from #813 item 5)Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día
-
Pin Hugging Face commit revisions for AuK weight downloads and eliminate post-download SHA TOCTOUAbiertoarea:voice better-dependency-freedom dependencies effort:low in-progress model:medium plan planner:gemini-4-neon-high priority:2 security
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
Los mantenedores suelen responder en 1 día
-
needs-area-label
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
OpenFreeEnergy/openfe#2371 ·
Los mantenedores suelen responder en 2 días
-
HMDB's smiles file writes "None" for metabolites with an empty <smiles/> (file not currently used)Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
NCATSTranslator/Babel#1269 ·
Los mantenedores suelen responder en 1 día