Repository navigation
Reject truncated/incomplete AI text function responses - #111830
Conversation
|
Workflow [PR], commit [d352771] Summary: ✅ AI ReviewSummaryThis PR normalizes provider-specific stop reasons into a shared Tests
Final VerdictNeeds one more focused Anthropic refusal regression test before merge. |
rschu1ze
left a comment
There was a problem hiding this comment.
I see that a finish reason is set but I don't see it used somewhere, e.g. in logging, is this intended?
There was a problem hiding this comment.
@rschu1ze it is used here to throw an error for a truncated row. Before this change, it was silently allowed, which is unexpected behavior.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 49/63 (77.78%) · Uncovered code |
|
The failure has a fix, waiting on someone to review the PR. Meanwhile merging master. |
AI text functions (aiGenerate, aiClassify, aiExtract, aiTranslate) silently returned partial output when a provider stopped early. The providers captured the finish reason but the shared base class never read it, so a response cut off by max_tokens came back as a fragment. Normalize each provider's native stop reason (OpenAI finish_reason, Anthropic stop_reason) into a canonical FinishReason enum and reject non-completed generations in FunctionBaseAI. Truncation (token limit) throws AI_PROVIDER_RESPONSE_TRUNCATED; a filtered/tool-call response throws AI_PROVIDER_RESPONSE_INCOMPLETE. Both honor ai_function_throw_on_error and are non-retriable. Unknown reasons are accepted to avoid false positives. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Anthropic structured output is implemented via a forced tool call, so a successful aiClassify/aiExtract reply comes back with stop_reason "tool_use" and is already parsed into the result. The previous mapping sent tool_use to ToolCall, which was rejected as AI_PROVIDER_RESPONSE_INCOMPLETE, breaking every Anthropic structured request. Map tool_use to Complete; pause_turn stays a rejected continuation signal. Add an aiClassify regression test over the Anthropic tool_use path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After tool_use was reclassified as Complete, this value only catches stop reasons where the model hands control back expecting a further action (OpenAI tool_calls, Anthropic pause_turn), so RequiresAction describes it better than ToolCall. Pure rename, no behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A truncated, filtered, or requires-action response still consumed provider tokens. Recording them only on the success path let such rows bypass `ai_function_max_input_tokens_per_query` / `ai_function_max_output_tokens_per_query` and miss `AIInputTokens` / `AIOutputTokens`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
de94bf3 to
2ab0039
Compare
A safety refusal populates `message.refusal` and leaves `finish_reason` as "stop", so a `finish_reason`-only check accepted it and returned an empty answer. Map it to `ContentFilter`, matching how the Anthropic provider already maps its "refusal" stop reason. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units20 translation units recompiled, 57 s compile time in total, 20 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Anthropic reports both an output cap and an exhausted context window as `Truncated`, but raising `max_tokens` reserves more output space and makes a context-window overflow worse. Branch the diagnosis and the remedy on `raw_finish_reason`, and cover `model_context_window_exceeded` in the mock. Co-Authored-By: Claude Opus 5 <[email protected]>
`tool_calls`, `function_call` and `pause_turn` all normalize to `RequiresAction`, which had no test. Add mock endpoints for OpenAI `tool_calls` and Anthropic `pause_turn`. The assertions check the arm's own wording, since `ContentFilter` raises the same error code with the same reason string. Co-Authored-By: Claude Opus 5 <[email protected]>
Master took error code 780 for `SW_SERVER_NO_WORKERS_AVAILABLE`, so the AI response codes move to 781 and 782. They are referenced by name only.
|
The CI failures on
|
…-truncated-responses
Rejecting an incomplete response throws out of `executeImpl`, past the `ProfileEvents` increments, so a failing query reported zero usage for a call the provider had already charged for. Flush from a destructor so the normal and throwing exits both publish the counters. Co-Authored-By: Claude Opus 5 <[email protected]>
raw_finish_reason is provider-controlled text; route it through sanitizeForLog before interpolating it into the AI_PROVIDER_RESPONSE_* exceptions that reach the logs and system.query_log, matching the existing defense in formatProviderError. Promote sanitizeForLog to a shared declaration in IAIProvider.h. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Replace the single-use AICountersFlusher RAII struct with a SCOPE_EXIT block co-located with the counters it flushes. Same semantics (flush on normal and exception exit), without the positional reference-member mapping that a reorder could silently break. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-truncated-responses
The shared FunctionBaseAI rejection path also covers aiRedact. Update its FunctionDocumentation: a reply truncated by a too-low max_tokens is now rejected with AI_PROVIDER_RESPONSE_TRUNCATED (or the column default when ai_function_throw_on_error is disabled) rather than returning partially redacted text. Add throw and graceful truncation regression tests. Co-Authored-By: Claude Opus 4.8 <[email protected]>
aiFilter shares the FunctionBaseAI rejection path. A provider-signalled incomplete reply (truncated / content-filtered / requires-action) is now an error rather than a silent non-match: dropping the row on a non-answer would be a silent false negative. Clarify the docs (unrecognised-but- complete still maps to 0; incomplete replies throw at the default ai_function_throw_on_error=1, map to 0 when disabled) and add throw and graceful regression tests. Co-Authored-By: Claude Opus 4.8 <[email protected]>
tool_use is a completed answer only when the request forced the synthetic structured_output tool via response_format. On a request that sent no tools (aiGenerate/aiTranslate/aiFilter/aiRedact), a tool_use stop is a tool-call turn, not a final answer, so map it to RequiresAction and reject it instead of accepting the tool input JSON (or an empty string) as complete. Add an aiGenerate negative regression test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-truncated-responses
…-truncated-responses
…-truncated-responses
| ai_response.finish_reason = forced_structured_output ? FinishReason::Complete : FinishReason::RequiresAction; | ||
| else if (ai_response.raw_finish_reason == "max_tokens" || ai_response.raw_finish_reason == "model_context_window_exceeded") | ||
| ai_response.finish_reason = FinishReason::Truncated; | ||
| else if (ai_response.raw_finish_reason == "refusal") |
There was a problem hiding this comment.
This new Anthropic-specific branch is part of the PR contract, but the added integration suite never exercises it. The tests cover OpenAI finish_reason="content_filter", OpenAI message.refusal, and Anthropic pause_turn / max_tokens / tool_use, but there is no Anthropic-shaped stop_reason="refusal" case.
That leaves this mapping unproven: a future regression here would silently fall back to Unknown/accepted output without any failing test. Please add a small /v1/anthropic/refusal mock plus one aiGenerate(..., map('credentials', 'ai_anthropic_refusal')) assertion that it surfaces AI_PROVIDER_RESPONSE_INCOMPLETE.
There was a problem hiding this comment.
I'll add it in a different PR.
…rs-on-throw Takes the canonical `FinishReason` mapping and refusal handling from #111830, applied to the `AIResponse` out-parameter. Its trailing `usage` block is dropped: `call` now reads the usage before validating the body. Its scope guard around the text-path counters replaces the unguarded increments, so a throwing text query now reports them too. Co-Authored-By: Claude Opus 5 <[email protected]>
The AI text functions (
aiGenerate,aiClassify,aiExtract,aiTranslate) could silently return a truncated answer. When a provider stops early — most commonly by hitting themax_tokenslimit — it reports this in the response, but the shared base classFunctionBaseAInever inspected the signal and returned whatever partial text came back. For example,aiGenerate('Write three sentences about the ocean.', map(..., 'max_tokens', '5'))returned the fragmentThe ocean covers more thanwith no error.This change normalizes each provider's native stop reason (OpenAI
finish_reason, Anthropicstop_reason) into a canonicalFinishReasonenum, so the base class can make a single completeness decision without knowing the provider dialect:Truncated(token/context limit) → throwsAI_PROVIDER_RESPONSE_TRUNCATED.ContentFilter(OpenAIcontent_filter, Anthropicrefusal) andToolCall→ throwsAI_PROVIDER_RESPONSE_INCOMPLETE.Complete(natural end, or a caller stop sequence such as Anthropicstop_sequence) andUnknown(unrecognized reason) are accepted, so benign non-stopreasons are not misclassified as truncation.The rejection is thrown inside the existing per-row
try, so it is non-retriable (retrying would hit the same limit) and honorsai_function_throw_on_error: with1the exception propagates; with0the row becomes the column default.aiEmbedis unaffected (embeddings have no finish reason).Integration tests in
test_ai_functionscover truncation (throw + graceful), content-filter, an accepted unknown reason, and the Anthropicstop_sequence(must not throw) andmax_tokens(must throw) cases.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
AI text functions (
aiGenerate,aiClassify,aiExtract,aiTranslate) now reject truncated or otherwise incomplete provider responses (e.g. when the model hits themax_tokenslimit) instead of silently returning partial output. Behavior follows theai_function_throw_on_errorsetting.Workflow [PR]
Sync PR [sync-upstream/pr/111830]
Version info
26.8.1.1887(included in26.8and later)