Skip to content

Reject truncated/incomplete AI text function responses - #111830

Merged
george-larionov merged 21 commits into
masterfrom
ai-functions-reject-truncated-responses
Aug 21, 2026
Merged

george-larionov merged 21 commits into
masterfrom
ai-functions-reject-truncated-responses

Conversation

@george-larionov

@george-larionov george-larionov commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

The AI text functions (aiGenerate, aiClassify, aiExtract, aiTranslate) could silently return a truncated answer. When a provider stops early — most commonly by hitting the max_tokens limit — it reports this in the response, but the shared base class FunctionBaseAI never 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 fragment The ocean covers more than with no error.

This change normalizes each provider's native stop reason (OpenAI finish_reason, Anthropic stop_reason) into a canonical FinishReason enum, so the base class can make a single completeness decision without knowing the provider dialect:

  • Truncated (token/context limit) → throws AI_PROVIDER_RESPONSE_TRUNCATED.
  • ContentFilter (OpenAI content_filter, Anthropic refusal) and ToolCall → throws AI_PROVIDER_RESPONSE_INCOMPLETE.
  • Complete (natural end, or a caller stop sequence such as Anthropic stop_sequence) and Unknown (unrecognized reason) are accepted, so benign non-stop reasons 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 honors ai_function_throw_on_error: with 1 the exception propagates; with 0 the row becomes the column default. aiEmbed is unaffected (embeddings have no finish reason).

Integration tests in test_ai_functions cover truncation (throw + graceful), content-filter, an accepted unknown reason, and the Anthropic stop_sequence (must not throw) and max_tokens (must throw) cases.

Changelog category (leave one):

  • Improvement

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 the max_tokens limit) instead of silently returning partial output. Behavior follows the ai_function_throw_on_error setting.


Workflow [PR]
Sync PR [sync-upstream/pr/111830]

Version info

  • Merged into: 26.8.1.1887 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d352771]

Summary: ✅


AI Review

Summary

This PR normalizes provider-specific stop reasons into a shared FinishReason and rejects truncated or otherwise incomplete AI text responses instead of silently returning partial output. The current patch fixes the earlier correctness gaps around token accounting, throwing-path ProfileEvents, OpenAI structured refusals, Anthropic tool_use, and the aiFilter / aiRedact contract changes, but one new Anthropic branch is still missing focused regression coverage.

Tests
  • ⚠️ [src/Functions/AI/AnthropicProvider.cpp:133] The new stop_reason == "refusal" mapping is still unproven. The integration suite now covers OpenAI message.refusal, Anthropic pause_turn, Anthropic truncation, Anthropic context-window exhaustion, and Anthropic tool_use, but there is still no /v1/anthropic/refusal mock plus one aiGenerate(..., map('credentials', 'ai_anthropic_refusal')) assertion that this branch surfaces AI_PROVIDER_RESPONSE_INCOMPLETE.
Final Verdict

Needs one more focused Anthropic refusal regression test before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 24, 2026
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see that a finish reason is set but I don't see it used somewhere, e.g. in logging, is this intended?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rschu1ze it is used here to throw an error for a truncated row. Before this change, it was silently allowed, which is unexpected behavior.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right. Tnx

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 49/63 (77.78%) · Uncovered code

Full report · Diff report

@george-larionov

Copy link
Copy Markdown
Member Author

The failure has a fix, waiting on someone to review the PR. Meanwhile merging master.

george-larionov and others added 5 commits August 5, 2026 23:25
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]>
@george-larionov
george-larionov force-pushed the ai-functions-reject-truncated-responses branch from de94bf3 to 2ab0039 Compare August 5, 2026 23:28
Comment thread src/Functions/AI/OpenAIProvider.cpp Resolved
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]>
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d35277176 with master daae2ec89 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0b043a6c6; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.45 MiB 701.40 MiB -3.05 MiB (-0.43%)

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 units

20 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.
The matched translation units cost +3.6 s (+7%) in total before that adjustment.

Job report

@rschu1ze rschu1ze self-assigned this Aug 7, 2026
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]>
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
`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]>
@george-larionov
george-larionov added this pull request to the merge queue Aug 12, 2026
@george-larionov
george-larionov removed this pull request from the merge queue due to a manual request Aug 12, 2026
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.
@george-larionov

Copy link
Copy Markdown
Member Author

The CI failures on 52cf7d6 are not caused by these changes.

Mergeable Check and PR are rollups of the two above.

Comment thread src/Functions/FunctionBaseAI.cpp Resolved
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]>
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
george-larionov and others added 3 commits August 14, 2026 20:33
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]>
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
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]>
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
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]>
Comment thread src/Functions/AI/AnthropicProvider.cpp Resolved
george-larionov and others added 3 commits August 17, 2026 21:50
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]>
@george-larionov

Copy link
Copy Markdown
Member Author

Created 2 issues for the test failures, working on them separately. #115661 and #115662.

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")

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add it in a different PR.

@george-larionov
george-larionov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into master with commit 31e78bb Aug 21, 2026
347 of 348 checks passed
@george-larionov
george-larionov deleted the ai-functions-reject-truncated-responses branch August 21, 2026 21:46
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
george-larionov added a commit that referenced this pull request Aug 22, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants