Skip to content

fix: retry legacy LLM judge on missing score - [SRE-696579] - #2039

Open
Chibionos wants to merge 2 commits into
mainfrom
fix/legacy-judge-missing-score
Open

Chibionos wants to merge 2 commits into
mainfrom
fix/legacy-judge-missing-score

Conversation

@Chibionos

@Chibionos Chibionos commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

What broke

A legacy LLM judge or trajectory evaluator can get a tool response with no valid score. With one attempt, the evaluation records an error and can pull the run average down. The Coastal capture shows an intermittent missing score; elapsed time alone does not establish whether truncation was involved.

Fix

  • Retry malformed responses at most three total calls in both legacy evaluators. Missing or invalid scores and recognized response-schema validation errors can retry; failed transport requests are not retried by this helper.
  • Accept a genuine numeric zero. Retry exhaustion stays an explicit sanitized error rather than inventing a score.
  • Keep evaluator log/error diagnostics to allowlisted metadata. No raw model arguments, justification, or response text in this path. Shared gateway tracing is separate and unchanged.
  • Proposed SDK version: 2.15.16.

Proof on 6e0ba5966fb6e2fbe8a462a30bf17afeae1eb06c

623 SDK evaluator tests passed locally, plus Ruff, focused mypy and independent review. Tests cover each legacy entry point, bounded retries, a valid zero, non-finite/out-of-range scores, booleans, schema errors, sanitized diagnostics and transport failures.

Before S207

Wait for human review and all required hosted checks. Publish and verify the exact SDK artifact, then confirm the affected runtime lane and update its lock, build and image as needed. Verify a comparable hosted evaluation on the resulting runtime. Newer judge implementations and the separate failure to start runs are not fixed here.

Judge models (e.g. anthropic.claude-sonnet-5) intermittently return a
complete submit_evaluation tool call without the required score
argument. The legacy LLM-as-judge and trajectory evaluators made a
single attempt, so one malformed response became an error result
scored 0 and dragged the run aggregate down.

Retry the judge call up to 3 attempts in total when the tool call is
malformed, and log each malformed attempt at WARNING with a preview of
the arguments so future occurrences are diagnosable.

SRE-696579
Copilot AI balanced review requested due to automatic review settings December 3, 2026 05:06
@github-actions github-actions Bot added test:uipath-langchain Triggers tests in the uipath-langchain-python repository test:uipath-runtime test:uipath-integrations labels Dec 3, 2026

Copilot AI 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.

🟢 Approval recommended

No active review issues were identified for the changes adding retries for malformed legacy LLM judge responses.

No open issues 🎉

What changed in this PR

Improves reliability of legacy LLM-based evaluations by retrying malformed judge responses instead of immediately returning zero-scored errors.

Changes:

  • Adds up to three semantic attempts with warning diagnostics, leaving transport retries unchanged.
  • Integrates retries into both legacy evaluators and adds regression tests.
  • Bumps uipath to 2.15.16.
File Description
packages/​uipath/​uv.lock Updates the locked package version.
packages/​uipath/​tests/​evaluators/​test_legacy_llm_judge_retry.py Tests recovery, exhaustion, first-attempt success, and warning logging.
packages/​uipath/​src/​uipath/​eval/​evaluators/​legacy_trajectory_evaluator.py Uses the shared retry helper.
packages/​uipath/​src/​uipath/​eval/​evaluators/​legacy_llm_helpers.py Adds bounded retries and argument-preview warnings.
packages/​uipath/​src/​uipath/​eval/​evaluators/​legacy_llm_as_judge_evaluator.py Uses the shared retry helper.
packages/​uipath/​pyproject.toml Sets version 2.15.16.

Review effort: Balanced

Copy link
Copy Markdown
Contributor Author

Local proof on 6e0ba5966fb6e2fbe8a462a30bf17afeae1eb06c: the two legacy judge callers retry malformed scores up to three total calls. A real zero is accepted. Exhaustion stays an explicit sanitized error. Transport failures are not retried by this helper.

The updated evaluator diagnostics record only allowlisted metadata; raw arguments and model text are not included in this path. Shared gateway tracing is separate and unchanged. HAR duration alone does not establish why a score was missing.

Proof: 623 SDK evaluator tests, Ruff, focused mypy and independent review passed locally.

Next: Please review the exact commit and wait for fresh CI. Verify the hosted runtime and actual SDK pickup before the S207 lock/build update. The separate no-start issue and newer judge scope aren’t closed by this PR.

@sonarqubecloud

sonarqubecloud Bot commented Dec 3, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
89.6% Coverage on New Code (required ≥ 90%)

See analysis details on SonarQube Cloud

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

🚨 Heads up: uipath-langchain cross-tests are FAILING 🚨

Your changes may break the uipath-langchain-python integration.

⚠️ These checks are NOT enforced by branch protection rules. Please review the failures before merging.

🔍 Inspect the failed run →

@ajay-kesavan ajay-kesavan 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.

Three-pass review (adversarial, deep, ponytail). The six failing Test (uipath, …) jobs come from this PR's new caplog tests depending on test order (see the 🔴 comment), not from flaky infra. The cross-repo uipath-langchain failure was not investigated.

assert "Non-numeric score" in str(result.details)
assert _PAYLOAD not in str(result.details)
assert _PAYLOAD not in caplog.text
records = [r for r in caplog.records if hasattr(r, "judge_attempt")]

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.

🔴 These caplog tests are what break the six Test (uipath, …) jobs. CLI tests call setup_logging(), which sets the uipath logger to propagate = False (src/uipath/_utils/_logs.py:21). After that, caplog sees no records, so lines 198, 266 and 280 fail. Reproduced locally: pytest tests/cli/test_pack.py tests/evaluators/test_legacy_llm_judge_retry.py gives 5 failures, while the file alone passes. The _PAYLOAD not in caplog.text checks also pass for the wrong reason when nothing is captured.

Fix: attach caplog's handler straight to the helper logger, the same way tests/resource_overrides/test_overwrites_logging.py does:

@pytest.fixture(autouse=True)
def _capture_helper_logs(caplog: pytest.LogCaptureFixture):
    log = logging.getLogger("uipath.eval.evaluators.legacy_llm_helpers")
    level, propagate = log.level, log.propagate
    log.setLevel(logging.DEBUG)
    log.addHandler(caplog.handler)
    yield
    log.removeHandler(caplog.handler)
    log.setLevel(level)
    log.propagate = propagate

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.

Correction to the fixture above (second pass): as written it leaves propagation on, so whenever the uipath logger still propagates, each record reaches caplog.handler twice, once from the helper logger and once from root. I ran it: pytest tests/evaluators gives 3 failed, 620 passed (assert [1, 1, 2, 2, 3, 3] == [1, 2, 3] in test_malformed_response_does_not_log_or_return_payload, and the ['length', 'stop'] check). It only passes after a CLI test has run, so the order dependence is flipped, not removed.

One more line gives a single path in any order:

    log.setLevel(logging.DEBUG)
    log.propagate = False
    log.addHandler(caplog.handler)

With it: file alone 37 passed, after tests/cli/test_pack.py 80 passed, full tests/ 2965 passed.

Comment on lines +166 to +169
except Exception:
# The legacy error result displays exception text. Gateway failures
# can embed response bodies, so don't re-export their exceptions.
raise RuntimeError("Legacy judge request failed") from None

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.

🟠 Every transport failure now shows the same message. On main, a 401, 403, 404 (unknown model) or 429 reached the eval result as Exception thrown by evaluator: <status + URL>. Now all of them become Legacy judge request failed, and from None drops the cause, so nobody can tell an auth problem from throttling without a repro. EnrichedException.status_code is an int and holds no response text, so it is safe to keep.

Suggested change
except Exception:
# The legacy error result displays exception text. Gateway failures
# can embed response bodies, so don't re-export their exceptions.
raise RuntimeError("Legacy judge request failed") from None
except Exception as error:
# Keep only type and HTTP status; exception text can embed response bodies.
status = getattr(error, "status_code", None)
raise RuntimeError(
f"Legacy judge request failed ({type(error).__name__}, status={status})"
) from None

Comment on lines +150 to +156
max_attempts: int = MAX_EVALUATION_ATTEMPTS,
) -> LLMResponse:
"""Retry malformed tool-call responses, not failed gateway requests."""
if not 1 <= max_attempts <= MAX_EVALUATION_ATTEMPTS:
raise ValueError(
f"max_attempts must be between 1 and {MAX_EVALUATION_ATTEMPTS}"
)

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.

🟡 Dead code that also costs the Sonar gate. No caller passes max_attempts, so this range check and the raise AssertionError on line 198 can never run. They are probably the uncovered lines behind Sonar's 89.6% (it needs 90%). Drop the parameter, use the constant in the loop (range(1, MAX_EVALUATION_ATTEMPTS + 1)), and replace the in-loop if attempt == max_attempts and the final AssertionError with one raise ValueError(f"{reason} after {MAX_EVALUATION_ATTEMPTS} attempt(s)") after the loop.

Suggested change
max_attempts: int = MAX_EVALUATION_ATTEMPTS,
) -> LLMResponse:
"""Retry malformed tool-call responses, not failed gateway requests."""
if not 1 <= max_attempts <= MAX_EVALUATION_ATTEMPTS:
raise ValueError(
f"max_attempts must be between 1 and {MAX_EVALUATION_ATTEMPTS}"
)
) -> LLMResponse:
"""Retry malformed tool-call responses, not failed gateway requests."""

try:
return extract_tool_call_response(response, model)
except _MalformedEvaluationResponse as error:
reason, argument_shape = str(error), error.argument_shape

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.

🟡 Retries can't change the outcome in some cases, and they multiply cost. Each retry sends the identical request again at once (default temperature=0, no hint to the model). A content_filter finish usually comes back with no tool call, so it is retried twice more and filtered the same way each time. Under line_by_line_evaluation, the worst case is 3 calls per line. Fail fast when a retry can't help:

if finish_reason == "content_filter":
    raise ValueError(f"{reason} (content_filter)")

Also consider adding a one-line corrective user message on retry (for example "Call submit_evaluation with both score (0-100) and justification") so the retry has a better chance than resampling at temperature 0.

@ajay-kesavan ajay-kesavan 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.

Second pass: two new points inline, plus a correction to the caplog fixture suggested in the first pass.
The uipath-langchain cross-test failure is not from this PR: attempt 1 failed in chat-models / alpha on a single HTTP 424 from UiPathChat.invoke, nothing there imports the changed files, and the re-run on the same commit passed.

Comment on lines +108 to +109
if not isinstance(justification, str):
raise _MalformedEvaluationResponse("Invalid justification format", "object")

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.

🟡 A valid score is now thrown away when justification isn't a string. main did str(arguments["justification"]). With this check, {"score": 78, "justification": null} (or a list / object) makes 3 calls and ends as a 0-scored error, Invalid justification format after 3 attempt(s). The same response scored 78 on main; I ran both versions.

The check doesn't guarantee an explanation either: "justification": "" still passes. Providers that don't enforce required don't enforce type: string, so a judge that answers this way fails on every item once consumers pick up 2.15.16. Keep the old coercion, as the numeric-string case below does, and drop the invalid-justification case from _INVALID in the new test file (the only test that changes).

Suggested change
if not isinstance(justification, str):
raise _MalformedEvaluationResponse("Invalid justification format", "object")
if not isinstance(justification, str):
# Older SDK versions stringified this; keep the valid score.
justification = str(justification)

Comment on lines +196 to +197
if attempt == max_attempts:
raise ValueError(f"{reason} after {attempt} attempt(s)")

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.

🟡 A truncated answer is retried with the same request and the same output cap. finish_reason is logged but never used. The legacy evaluators don't set max_tokens, so every attempt goes out with the gateway default of 4096 (_llm_gateway_service.py:417). The tool schema lists justification before score, so an answer cut at the cap loses score first, which is the incident shape (the new test_finish_reason_does_not_conflate_truncation_with_normal_stop scripts exactly that).

I ran a finish_reason="length" response through the real UiPathLlmChatService: 3 identical POSTs, each with max_tokens=4096 and temperature=0, and the same Missing 'score' error at the end. The description says truncation isn't ruled out. If that is the cause, this PR triples the cost of those items without fixing them, and the eval result can't show it, because the reason only reaches the warning log.

Same family as the earlier content_filter thread, different fix: put the allowlisted finish_reason in the final error so the result says length, and on length / max_tokens retry with a larger max_tokens where the model allows it instead of the same body (the newer judge already sends 8000 for Claude 4.5, llm_as_judge_evaluator.py:257).

Suggested change
if attempt == max_attempts:
raise ValueError(f"{reason} after {attempt} attempt(s)")
if attempt == max_attempts:
raise ValueError(
f"{reason} after {attempt} attempt(s) (finish_reason={finish_reason})"
)

This branch has not been deployed

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

Labels

test:uipath-integrations test:uipath-langchain Triggers tests in the uipath-langchain-python repository test:uipath-runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants