Skip to content

refactor(runtime): single owner for provider finish-reason semantics #3802

Closed as not planned

Description

@Astro-Han

finishReason semantics are now decided in two places with two vocabularies.

  • classifyModelFinishBoundary returns 'authoritative' | 'incomplete' | 'retryable-network-failure' and handles network_error, other, unknown, and an output-free stop.
  • settleModelStepOutcome separately maps content-filter and error to terminal failures, in ModelStepOutcome['kind'].

Both answer the same question — what does this finish reason mean. Adding a provider behaviour means remembering to touch both.

Upstream of both, chunkFinishReason (packages/runtime/src/model-adapter.ts:651, from #2297) un-maps the AI SDK's unified: 'other' back to the raw provider spelling, on the premise that other plus a spelling means an ordinary finished turn. That premise does not hold for the class of providers that report abnormal termination through finish_reason. Zhipu's API FAQ documents exactly this for SSE calls, and network_error (#3772) and sensitive are both observed values; OpenRouter separately emits error.

Prior art puts the map at the translation seam rather than in downstream policy: LiteLLM's map_finish_reason() (litellm#24373) and pydantic-ai's per-provider _CHAT_FINISH_REASON_MAP (pydantic-ai#7678).

The decision this needs: which layer owns provider-spelling to Maka finish semantics, so that supporting a new spelling is a one-line change in one table. No implementation is preferred here.

Related: #3777, #3772, #2297.

简体中文

finishReason 的语义目前在两个地方判定,用的是两套词表。

  • classifyModelFinishBoundary 返回 'authoritative' | 'incomplete' | 'retryable-network-failure',处理 network_error、other、unknown 和无输出的 stop。
  • settleModelStepOutcome 另外把 content-filter 和 error 映射成终止失败,用的是 ModelStepOutcome['kind']。

两者回答的是同一个问题——这个 finish reason 是什么意思。新增一种供应商行为,就得记得两边都改。

在它们上游,chunkFinishReason(packages/runtime/src/model-adapter.ts:651,来自 #2297)把 AI SDK 的 unified: 'other' 换回供应商原始拼写,前提是「other 带拼写 = 一次普通结束」。对于那一类通过 finish_reason 上报异常终止的供应商,这个前提不成立。智谱 API FAQ 对流式调用正是这么写的,network_error(#3772)和 sensitive 都是实际观察到的值;OpenRouter 另外还会发 error。

先例都把这张表放在翻译层而不是下游策略里:LiteLLM 的 map_finish_reason()(litellm#24373)和 pydantic-ai 的按供应商 _CHAT_FINISH_REASON_MAP(pydantic-ai#7678)。

需要定的是:供应商拼写到 Maka finish 语义的映射由哪一层拥有,使得支持一个新拼写只需要在一张表里改一行。这里不预设实现方案。

本 issue 由 Claude 协助起草。

Activity

  1. added
    help wanted
    on Aug 25, 2026
  2. chinawch007 commented on Aug 25, 2026

    @chinawch007
    Contributor

    Proposal: own the map at the translation seam

    Thanks for writing this up — the two-vocabulary split is exactly what #3772 ran into. Proposing an answer to "which layer owns provider-spelling → Maka finish semantics": the translation seam (chunkFinishReason), with the judgment layers kept as pure policy over a closed enum.

    Organizing principle: these are two different jobs

    • "What does this spelling mean" is a dictionary question. The answer depends only on the spelling itself (plus provider identity when needed), never on stream state — network_error means network failure whether or not the stream produced text.
    • "How does this request settle" is an evidence question. The answer depends on accumulated stream state: text/tool activity, usable usage, abort, error events.

    The dictionary belongs at the seam; the evidence policy stays where it is. Neither classifyModelFinishBoundary nor settleModelStepOutcome loses its judgment responsibility — what goes away is the second place that reads provider spellings.

    Why the seam specifically

    1. Full information exists only there. The chunk carries both unified and raw; after chunkFinishReason picks one string, the other is gone. Every consumer below the seam can only match on whatever single string was forwarded, which is why each of them ended up hard-coding its own fragment of the dictionary.

    2. fix(runtime): stop reporting a truncated provider stream as a finished turn #2297's premise was minted here, so its correction belongs here. "other plus a spelling means an ordinary finished turn" is a seam-level default. Replacing it with an explicit default row — unknown spelling fails closed as truncated, with the raw spelling carried in the failure message and telemetry so triage is a discoverable one-row fix — is a one-place change. This is a deliberate behavior change for the unknown-spelling class (that's the point — Runtime treats output-free provider finish frames as successful completion #3772); known-benign spellings like eos_token get explicit rows so their current completed behavior is preserved (adapter tests pin this today).

    3. The judgment layers are not the only string consumers. history-compact-summarizer compares the finish reason against 'length' to detect a truncated compaction summary (history-compact-summarizer.ts:131), the backend compares === 'tool-calls' to label step_limit (ai-sdk-backend.ts:2985), mapFinishReason dispatches on strings, and tool-free-model-call normalizes finish reasons on its own paths. A table owned by classifyModelFinishBoundary fixes two consumers and leaves the rest reading raw dialect — a provider spelling length as token_limit would still corrupt compaction silently. Seam normalization fixes every consumer at once.

    4. It continues what's already there. fix(runtime): retry output-free provider finishes #3777's RAW_FINISH_REASON_ALIASES already applies at chunkFinishReason, and the codebase already persists a raw annotation (NormalizedUsage.rawFinishReason, carried into runtime events and usage records). "Semantic primary, raw as annotation" is half-built; this finishes it. One small correctness fold-in while we're there: today the persisted rawFinishReason is the string chunkFinishReason chose, not necessarily the provider's true raw spelling.

    5. Prior art agrees. LiteLLM's map_finish_reason() (litellm#24373) and pydantic-ai's per-provider _CHAT_FINISH_REASON_MAP (pydantic-ai#7678) both sit at the translation seam.

    Shape

    // The sole dictionary: open spellings -> closed Maka vocabulary
    type MakaFinishReason =
      | 'stop' | 'length' | 'tool-calls'
      | 'content-filter' | 'provider-error' | 'retryable-transient' | 'unnamed';
    
    const FINISH_REASON_SEMANTICS: ReadonlyMap<string, MakaFinishReason> = new Map([
      // unified vocabulary
      ['stop', 'stop'], ['length', 'length'], ['tool-calls', 'tool-calls'],
      ['content-filter', 'content-filter'], ['error', 'provider-error'],
      // raw dialects observed in the wild
      ['network_error', 'retryable-transient'],
      ['sensitive', 'content-filter'],
      ['eos_token', 'stop'],
      // ...a new spelling is a new row; nothing else moves
    ]);
    • ModelFinishReason (currently a bare string) becomes this closed union; the raw spelling keeps riding along for telemetry/replay as it does today.
    • chunkFinishReason becomes a table lookup with an explicit default row (unnamed), so the fix(runtime): stop reporting a truncated provider stream as a finished turn #2297 assumption becomes data instead of subtext.
    • classifyModelFinishBoundary and settleModelStepOutcome keep their evidence jobs and become pure policy over the closed enum; settleModelStepOutcome's content-filter/error string branches move into the table. They can share a module and vocabulary, though their call moments stay distinct (streaming vs post-stream).
    • Disposition still needs enriching either way — settlement must distinguish content-filter from provider-error to pick failure kind and message — so that work is common to both candidate owners.
    • One guardrail worth stating explicitly: no evidence policy at the seam. translateChunk stays per-chunk and stateless; "an empty stop is retryable" depends on accumulated stream evidence and stays in the judgment layers.

    Behavior expectations

    Currently-correct cases (content-filter / error terminal failures, the eos_token completion) stay pinned by the existing adapter tests, with fixtures switching from string spellings to the enum. The only intended behavior change is the unknown-spelling default: fail closed instead of assume-normal, with the raw spelling surfaced in the failure.

    Happy to discuss the vocabulary shape and the default-row policy — in particular whether unnamed should fail closed unconditionally or allow per-provider overrides.

    If maintainers agree the seam is the right owner, please assign this issue to me and I'll start on the implementation (on top of #3777).

  3. added a commit that references this issue on Aug 26, 2026
  4. removed
    help wanted
    on Aug 29, 2026
  5. added theissue type on Aug 29, 2026
  6. chinawch007 commented on Aug 31, 2026

    @chinawch007
    Contributor

    I'm waiting for #3777 merged.

  7. added
    enhancement
    on Sep 17, 2026
  8. Astro-Han commented on Nov 5, 2026

    @Astro-Han
    ContributorAuthor

    Closing: this targets the TypeScript implementation on main, which is superseded by rust-preview (#6366). If it still applies to rust-preview, please open a new issue against it.

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

Metadata

Metadata

Assignees

Labels

enhancement

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions