Repository navigation
Conversation
|
🔍 OpenCodeReview found 12 issue(s) in this PR.
|
f8a030c to
ba91479
Compare
|
Thank you for the detailed analysis in #805 and for taking the time to follow it through with a complete implementation here. The problem statement is accurate, the reproduction is convincing, and the If we may offer some background on why the current behavior looks the way it does: when this design was first put together, the model APIs we targeted did not require the intermediate thinking process to be replayed on subsequent turns, so treating thinking as a fallback for With that said, we would like to be careful here, and we hope you will bear with us. Replaying native reasoning state changes the effective prompt on every affected turn, and we expect the impact to vary by model — helping some, and possibly regressing others. Beyond that, existing users have built expectations around the current behavior, and the downstream effect on their experience is genuinely difficult to predict from code review alone. Two things in particular we would rather measure than reason about: models where reasoning replay meaningfully shifts output quality, and how token accounting behaves once hidden reasoning enters the request budget. For those reasons we would like to run a thorough internal evaluation and work through the architectural trade-offs before we commit to a direction. Please read this as caution about changing behavior that affects every user on every turn, rather than as any reservation about the quality of your work. We will keep this PR updated as that evaluation progresses. Should it lead us toward a different design, we would be delighted to have you involved in shaping it — you clearly have a deep understanding of this part of the system, and your input would be valuable to us regardless of which implementation we ultimately land on. Thank you again for raising this and for your patience while we work through it. |
|
Thank you for the thoughtful reply — your caution is well placed, and as it turns out, more justified than you knew. While you were evaluating, I ran a stricter self-review of this PR (including field-level probe tests against the SDK conversion paths) and found several problems I introduced in the PR as submitted. The three most important:
I also need to correct the PR description: "no user-facing behavior changes" was not accurate. Replay itself changes the effective prompt on every affected turn — exactly the concern you raised — and there are two more changes I failed to declare: compression now hard-fails on an oversized latest round instead of degrading, and streaming unconditionally enables So I've converted this PR to a draft and split out the parts that don't depend on the replay design discussion:
Those three can be reviewed independently. I'll rework the replay core here after fixing the problems above, and put it behind a config flag that is off by default — so merging can be decoupled from behavioral evaluation, your internal evaluation can proceed at whatever pace works for you, and the flag's eventual default can follow your data rather than my assumptions. #811 and #812 stay open as tracking issues (both updated with deterministic, no-endpoint-needed reproductions), to be revisited once the direction here settles. |
ba91479 to
f4c7b8f
Compare
|
Update: the rework described above is now pushed. Summary of what changed since the original diff:
The PR body has been rewritten to match. No rush on this one — happy to adjust the flag name/shape to whatever fits the project's config conventions. |
…eams
openai-go v3.41.0 dispatches comment-only SSE blocks (e.g. ": keep-alive"
lines sent by proxies and OpenAI-compatible gateways) as events with empty
data. Stream.Next() then feeds the empty payload to json.Unmarshal, fails
with "unexpected end of JSON input", and aborts the response mid-stream.
Upstream fixed this in v3.43.0 ("ssestream: skip SSE blocks without
data", openai/openai-go#621, commit 114224d) by skipping blocks that
carried no data lines. Upgrade to the current v3.50.0 to pick it up.
No code changes required: the v3 API is backward compatible across this
range, and make test / make check pass unchanged.
Streaming requests currently receive token usage only when the provider volunteers it: OpenAI-compatible servers omit usage from streams unless stream_options.include_usage is set, so streamed reviews silently lose token and cost accounting. Set stream_options.include_usage=true by default when streaming. The existing extra_body passthrough stays in control: an explicit stream_options object replaces the default, an explicit null suppresses the field entirely for gateways that reject stream_options, and non-streaming requests never carry the field (mirroring the alibaba#647 treatment of the "stream" key).
…ted options An explicit stream_options object in extra_body used to replace the include_usage default wholesale, so configuring an unrelated stream option silently disabled usage accounting. include_usage now stays requested unless the config spells it out (or suppresses stream_options with an explicit null).
Three-zone compression currently discards context it should preserve: - partitionMessages marked the whole tail as the compress zone whenever every round still fit the token budget, so each soft-threshold (60%) background compression summarized the entire live conversation instead of leaving it alone. In practice the active zone never survived a background compression. - The frozen zone's own tokens were not reserved against the prompt budget when sizing the active zone, overfilling it once the folded-in summary grew. - runCompression truncated the conversation to the frozen zone when no compression template is configured. - The no-tool retry path appended to the conversation without any token bound: a model that keeps answering without tool calls grew the prompt unchecked until the provider rejected it. An empty compress zone is now represented as compressEnd == frozenEnd and left untouched, the frozen zone reserves its tokens, a missing template keeps the conversation, and the retry path goes through the same append+compression helper as tool rounds (addNextMessage generalized to appendMessagesWithCompression taking the whole update at once).
Sync compression triggers strictly over the warning limit, but the success return used a strict less-than: a conversation sitting exactly at the limit was reported as a compression failure and stopped the loop. Return the exact complement of the trigger condition.
Carry the complete assistant message a provider returned back on the next tool turn as an opaque adapter-owned envelope, instead of rebuilding it from the normalized projection. Off by default: the assistant_replay config field (or OCR_LLM_ASSISTANT_REPLAY) must be set to "native"; the default path keeps the existing normalized rebuild. - Envelope capture validates tool calls and survives gateways that omit the tool call type discriminator or stream continuation fragments without index/id. - Unknown top-level provider fields are never echoed back; only fields with a known request-side contract (reasoning_details) are replayed, plus per-tool-call vendor extensions and request-safe audio ids. - reasoning_content is replayed by default but stripped for providers that document rejecting it in input (DeepSeek). - Message.Clone deep-copies content blocks so stored records cannot be mutated through aliased slices.
…ompression Replay the adapter-owned assistant turn through the agentic loop and compression instead of a lossy content/tool-call rebuild. Compression only hard-stops on an oversized latest round when a real replay envelope would be corrupted; plain tool-call rounds keep the existing degradation path. Token accounting moves to llm.ApproxMessagesTokenCount so opaque replay state is priced in.
…persistence Task records clone messages via llm.CloneMessages so in-memory replay state survives for retries while the persisted JSONL keeps only the redacted normalized projection.
The per-provider strip list was built on the old deepseek-reasoner contract (400 when reasoning_content appears in input). DeepSeek's current thinking-mode documentation inverts that: for requests carrying tools, reasoning_content must be passed back on subsequent turns (400 when missing), and it is ignored on turns without tool calls. A provider-level strip would therefore break exactly the provider it was protecting. Drop the policy seam and carry reasoning_content verbatim; native replay is opt-in per endpoint, so gateways that reject the field simply stay on the default rebuild.
llm.assistant_replay and the per-provider assistant_replay field can now be set through ocr config set with the same normalization and validation as the resolver, instead of requiring hand-edited JSON or the OCR_LLM_ASSISTANT_REPLAY environment variable.
Replay-state accessors, token estimates, custom-tool overlays, audio reduction, flag gating, and streaming delta assembly were exercised only through llmloop wire tests, which per-package coverage does not count. Pin their contracts in-package; total coverage clears the CI threshold again after the replay feature's additions diluted it.
f4c7b8f to
b4c67e8
Compare
|
Two updates, one of which corrects something I said earlier in this thread: 1. Correction: 2. Rebased on current |
|
This change is too messy; it seems to involve several things. |
Description
Fixes #805.
Reworked after splitting the independent fixes out of the original diff (see #821, #822, #823 and the summary comment). This PR is now only the replay feature itself, and the feature is off by default.
What it does
With
assistant_replay: "native"set on a provider entry or thellmsection (viaocr config set llm.assistant_replay native, a provider'sassistant_replayfield, orOCR_LLM_ASSISTANT_REPLAY=native), the OpenAI-compatible adapter carries the complete assistant message a provider returned back on the next tool turn — instead of rebuilding it from the normalized content/tool-call projection. That preservesreasoning_content,reasoning_details, per-tool-call vendor extensions (e.g. Geminiextra_content.google.thought_signature), and exact content presence (empty vs. null vs. absent), which the rebuild loses (#805). DeepSeek's current thinking-mode contract makes this concrete: for requests carrying tools,reasoning_contentmust be passed back on subsequent turns or the API returns 400 — exactly what the normalized rebuild cannot do.Without the flag, behavior is the pre-existing normalized rebuild, byte-for-byte — pinned by
TestRunPerFile_OpenAIDefaultRebuildsNormalizedAssistantHistory.Why default-off
Echoing response fields back as input is provider-dependent territory. Rather than guess, the replay path is conservative and explicit:
reasoning_content,reasoning_details); everything else is treated as response metadata. Vendor tool-call extensions are still overlaid per-call, and audio is reduced to its request-safe{"id"}form.reasoning_contentreplays verbatim, never stripped. An earlier revision stripped it per-provider based on the old deepseek-reasoner contract (400 when present in input); DeepSeek's current documentation inverts that (400 when missing on tool turns, ignored elsewhere), so a strip would break exactly the provider it was protecting. Endpoints whose gateways reject the field simply stay on the default rebuild.id/typeis discarded in favor of the normalized rebuild rather than failing the whole next request; gateways that omit the tool-calltypediscriminator get it defaulted from the response JSON.index/id, legacyfunction_call, negative indexes, and exact empty-vs-absent reasoning.CloneMessagesdeep-copies tool calls and nested content blocks so stored records can't be mutated through aliased slices.Anthropic signed thinking (#811) and OpenAI Responses typed reasoning items (#812) are intentionally left to their own adapters — those protocols need native envelopes and must not be flattened into this Chat Completions representation.
Type of Change
How Has This Been Tested?
Deterministic HTTP-boundary tests cover both flag states: the default state pins the exact rebuilt request (no
reasoning_contentecho, no vendor fields, tool calls reduced toid/type/function), and the opt-in state pins non-streaming and streaming replay — exact visible content presence, omitted/null/empty fields, extension allowlisting, the DeepSeek pass-back contract, corrupt-envelope rejection, missing tool-calltype, continuation fragments withoutindex/id, nested Gemini signatures, parallel and legacy tool calls, no-tool retry, token accounting, persistence redaction, and compression atomicity. Resolver andocr config settests cover the config field, env override, canonicalization, and rejection of unknown values. Total coverage stays above the repository's 90% CI threshold.make testpasses locallyThe built
dist/opencodereviewCLI completed real reviews of disposable Git repositories against a strict local OpenAI-compatible service, in all four {default,assistant_replay: "native"} × {non-streaming, streaming} combinations, with the flag resolved through the real config-file path. The service returned a round-1 assistant message carryingreasoning_content,vendor_state, a Gemini-styleextra_contenttool extension, and (streaming) a tool-call continuation fragment withoutindex/id, then rejected the round-2 request with HTTP 400 unless the assistant history matched the exact expected wire shape for the active mode — replay mode additionally verified exact empty-contentpresence and signature preservation, default mode verified the byte-identical legacy rebuild. All four runs completed throughfile_read/task_done, and persisted session JSONL was checked to contain no envelope internals in either mode.Every commit in the series builds and vets independently.
Checklist
go fmt,go vet)assistant_replaydeferred until the flag name/shape is settled in review — happy to add them to this PR if you'd rather ship them together)Related Issues
Fixes #805
Split-out prerequisites: #821, #822, #823
Follow-up provider adapters: