Skip to content

bug(requirements): an adapter-backed requirement repairs against raw score JSON #1675

Closed

Description

@planetf1

A requirement that fails should tell the repair loop something it can use. Mellea carries that on
ValidationResult.reason, and RepairTemplateStrategy puts it under "The following requirements failed
before" in the retry prompt, which is the only part of that prompt describing the attempt that just
failed.

For a requirement validated by an adapter, that line is the adapter's JSON. The retry is told the score
in 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.

Current behaviour

Validating a requirement runs three steps:

  1. The adapter scores the output. requirement-check answers with the contract
    {"requirement_check": {"score": <float>}}, a number in [0.0, 1.0] where higher means more likely
    satisfied.
  2. validate() produces a verdict and an explanation. It calls output_to_bool for the pass/fail,
    and separately sets reason for people and for the repair prompt. ALoraRequirement supplies
    requirement_check_to_bool as that converter
    (mellea/stdlib/requirements/requirement.py:110).
  3. The strategy builds the retry. A failed requirement contributes its reason to the prompt, and
    falls back to the requirement's description only when there is no reason
    (mellea/stdlib/sampling/base.py:729-740).

Step 2 is where the explanation and the payload get crossed. validate() assigns the adapter's own
output as the reason (mellea/core/requirement.py:425-430):

judge_output = llm_as_a_judge_result.value
reason = judge_output
if judge_output:
    judge_output_str = str(judge_output).strip().lower()
    if judge_output_str in ("yes", "no"):
        reason = self.description

The substitution fires only for a bare "yes" or "no". The comment above it says why that case
exists: a bare "no" is unhelpful, and the requirement description is more actionable. An adapter's
JSON is neither of those strings, so it survives as the reason verbatim.

flowchart LR
    A["requirement_check adapter<br/>JSON payload, score 0.15"] --> B
    B["validate()<br/>reason = raw output<br/>score = None"] --> C
    C["RepairTemplateStrategy<br/>* {validation.reason}"] --> OUT["retry prompt explains<br/>nothing about the failure"]

    classDef graded fill:#cde7cd,stroke:#4a7a4a,color:#111
    classDef wrong fill:#f5cfcf,stroke:#a35050,color:#111
    classDef plain fill:#d3e2f5,stroke:#48688f,color:#111
    class A graded
    class B,C wrong
    class OUT plain
Loading

Problem

Take a requirement described as "State the opening time." and an adapter that scores an attempt at
0.15. The requirement fails, correctly. RepairTemplateStrategy prefers the validation reason over the
requirement description when building the retry feedback (mellea/stdlib/sampling/base.py:729-740), so
rendering the repaired instruction gives the model this:

State the museum's opening time.
Fulfill the following requirements:
* State the opening time.
The following requirements failed before:
* {"requirement_check": {"score": 0.15}}

The retry gains nothing from having failed. The requirement is still there, carried by the
instruction's own requirements block, so nothing has gone missing. But the one block describing the
attempt that just failed offers a key name from mellea's adapter contract and a number the model has no
way to interpret. A generation is spent and no diagnosis is passed on.

Meanwhile the typed field for that number is never filled. score (float | None): Optional numeric score returned by the validator (mellea/core/requirement.py:40), with a public accessor at :75.
No ValidationResult( or PartialValidationResult( call site in production Python passes score=;
the only occurrences of the name are the two __repr__ methods at :122 and :210. So the grade is
present in the result as text the model reads, and absent as a value code can act on. A caller wanting
to auto-approve above 0.9 and send below 0.6 to a human has to re-parse the reason string that was
written for a human, using knowledge of an adapter contract they never called.

The field is already load-bearing, and silently inert. mellea/stdlib/sampling/sofai.py:724
builds its no-improvement signature as (req.description, val.reason, val.score) and compares it
between attempts to decide whether the fast model is making progress. The third element is always
None. A reader of that line would reasonably believe the check compares scores. It cannot, and
nothing says so. What it compares instead is the reason, which happens to contain the score as JSON,
so the comparison works by accident through the wrong field.

And the threshold is not the user's. 0.5 is hardcoded at mellea/stdlib/requirements/requirement.py:62
and documented as fixed at :36 and :43. A safety check that should reject at 0.2 and an editorial
check that should accept at 0.95 get the same midpoint, and changing it means writing your own
output_to_bool.

Reproducer

No GPU and no adapter needed; a stub backend returns what the adapter's contract guarantees it returns.

ADAPTER_OUTPUT = '{"requirement_check": {"score": 0.85}}'

class StubBackend:
    async def generate_from_context(self, action, ctx, *, format=None, model_options=None):
        return ModelOutputThunk(value=ADAPTER_OUTPUT), ctx

ctx = Mock(spec=Context)
ctx.last_output.return_value = ModelOutputThunk(value="The museum opens at 10:00.")
req = Requirement("Answer is supported.", validation_fn=None,
                  output_to_bool=requirement_check_to_bool)   # what ALoraRequirement wires
r = asyncio.run(req.validate(backend=StubBackend(), ctx=ctx))
result bool     : True
result.score    : None
result.reason   : '{"requirement_check": {"score": 0.85}}'

Feeding a failing result (0.15) through RepairTemplateStrategy.repair then gives:

The following requirements failed before:
* {"requirement_check": {"score": 0.15}}

Both scripts are short enough to become tests as they stand.

Proposal

Parse the adapter's output into the fields built for it, rather than passing it through as prose.

  • validate() sets score from a graded validator, so the number is available as a number.
  • reason stops carrying machine output. When a converter has produced a structured result, the
    reason should be either the requirement description, as the "yes"/"no" branch already does, or a
    short rendering a person would want to read, rather than the adapter payload.
  • 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.
flowchart LR
    A["adapter output<br/>score 0.15"] --> B
    B["validate()<br/>score = 0.15<br/>reason = the requirement"] --> C
    C["strategy<br/>repair on the requirement<br/>route on the score"] --> OUT["retry explains the failure<br/>code reads the number"]

    classDef graded fill:#cde7cd,stroke:#4a7a4a,color:#111
    classDef plain fill:#d3e2f5,stroke:#48688f,color:#111
    class A,B graded
    class C plain
Loading

What changes for a user: the retry prompt names the requirement the output missed instead of a JSON
object, so repair has something to act on. Their code can read result.score and set its own threshold.
A user who only checks bool(result) sees no change, since as_bool() keeps its current meaning and
keeps failing closed.

What this deliberately does not claim. Populating score does not make it trustworthy. Nothing in
mellea has measured whether these adapter scores are calibrated, so a reported 0.7 is not yet evidence
that seven such cases in ten are satisfied. That measurement is worth doing and cannot be done while
the number is only available as text inside a prose field. Carrying it properly is the prerequisite,
not the claim.

Decision needed before implementation: where does the threshold live

Keep 0.5 in requirement_check_to_bool and set score alongside it. Smallest change and it fixes
the reporting and repair-prompt problems immediately. Long-term it leaves the threshold
unconfigurable, so anyone needing a different one still writes their own converter.

Make the threshold a constructor argument on ALoraRequirement. The requirement owns its decision
boundary, which is where a reader looks for it. Long-term this matches how people describe the problem
("reject this one at 0.2"), at the cost of one parameter and a decision about its default.

Return only the score and let strategies threshold. Best fit if strategies grow real routing, but
as_bool() must still answer, so a default has to live somewhere anyway, and the change reaches every
strategy. Today it moves complexity outward for no present consumer.

What to check while doing it

  1. Do the three graded adapter functions mean the same thing? The axis is comparability.
    requirement_check is satisfaction ("higher = more likely satisfied"), check_certainty is the
    model's certainty about its own response, and guardian_check is documented as "Risk score as a
    float between 0.0 (no risk) and 1.0 (risk detected)" (intrinsic/guardian.py:219-220), so its
    direction is inverted. What the user notices if this is glossed over: a threshold meaning "accept
    above" for one requirement and "reject above" for another, with nothing in the type to warn them.
  2. What should reason say instead? The axis is repair quality. The description is the safe answer
    and matches the existing "yes"/"no" branch. What the user notices: whether the retry prompt
    becomes useful or merely stops being JSON.
  3. Does PartialValidationResult get the same treatment? The axis is streaming parity. It has the
    identical unset score field and accessor (:177). What the user notices: per-chunk validation
    stays unthresholdable while whole-output validation becomes thresholdable, for no visible reason.
  4. What does a non-adapter validator report? The axis is coverage. simple_validate and the
    plain-Python validators have no natural score, so score stays None for them. What the user
    notices: any code reading it must handle both, which is the honest outcome but should be documented
    rather than discovered.

Also in scope

  • Fix sofai.py:724 or document it. Either the signature stops including a term that is always None,
    or it genuinely compares scores once they exist. Leaving a constant in a change-detector is
    misleading to the next reader either way.
  • The ValidationResult docstring describes score as "returned by the validator", which no validator
    does. Either the field gets a producer or the docstring stops implying one.
  • Document that score is populated only by validators that produce one, and that its calibration is
    unmeasured.

Related

Activity

  1. added
    bug
    needs-design
    area/adapter-functions
    area/requirement
    area/sampling
    on Sep 24, 2026
  2. planetf1 commented on Oct 5, 2026

    @planetf1
    ContributorAuthor

    Status: root cause confirmed (2026-10-05)

    Verified against main at 4c53add4e. The crossing happens in Requirement.validate (mellea/core/requirement.py:425-430): the judge output is assigned straight to reason, with the description substituting only for a literal "yes"/"no" — the shape LLM-as-a-Judge emits, but not the adapter contract. For an adapter-backed requirement (ALoraRequirement, output_to_bool=requirement_check_to_bool) the judge output is the parsed contract, so a failed check hands the repair prompt's "The following requirements failed before:" slot (mellea/stdlib/sampling/base.py:644) the wire-format JSON {"requirement_check": {"score": 0.2}} — while the typed score field on ValidationResult stays unset, because ALoraRequirement.__init__ passes validation_fn=None (mellea/stdlib/requirements/requirement.py:110, with the live # TODO: ... so that we can set the score at :108 pointing at exactly this).

    Net effect: the retry sees the score in serialised form in the one slot that exists to explain what went wrong, and the field designed to carry the number is empty for every consumer that reads it.

    Proposed direction — two parts, different risk:

    1. Minimal (safe, local): in validate(), when the judge output is a parsed adapter contract carrying a numeric score, set score= on the result and write reason as a human sentence ("<description> — adapter score 0.20"). The repair prompt improves for every adapter-backed requirement; no API change.
    2. Full (needs the design call this issue is tagged for): implement the TODO — have ALoraRequirement supply a validation_fn so the typed field is populated at the source for all consumers. That touches the Requirement.validate API path and the score semantics (is it always the contract's [0.0, 1.0] float, or could a future adapter score on a different scale?), which is why it stays needs-design rather than being rolled into part 1.
  3. added
    p2
    on Oct 5, 2026
  4. self-assigned this
    on Oct 6, 2026
  5. planetf1 commented on Oct 20, 2026

    @planetf1
    ContributorAuthor

    Cross-link from #1497, which closes via #1727 with its Part 1 only. Part 2 there proposed making feedback_strategy="simple" return a None reason, or defaulting to "first_error". Post-#1727 this is inert on the sofai path (the generic strings are filtered and the description always renders), but two bits survive: the generic reason still reaches RepairTemplateStrategy's failed-requirements block verbatim, and a "first_error" default is an unmeasured quality tradeoff. Both belong in this issue's "what should reason say" decision rather than as separate work, so recording them here before #1497 auto-closes.

  6. planetf1 commented on Oct 20, 2026

    @planetf1
    ContributorAuthor

    Folded into #1720 as package 3 (repair feedback carries a usable reason), sequenced after #1738 since both touch Requirement.validate. The proposal, threshold options and reproducer are in the host body. For anyone arriving from #1497 or PR #1727: the RepairTemplateStrategy reason path described here is #1720 package 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/adapter-functionsarea/requirementarea/samplingbugneeds-designp2

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions