mirror of
https://github.com/coder/coder.git
synced 2026-11-30 18:17:08 +08:00
feea5ab959f59cd2135443ed2a0c19bf7643db8f
8
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
85f02dfc29 |
refactor(coderd/x/chatd/chatsanitize): drop Anthropic guard escalation passes (#30970)
`ApplyAnthropicProviderToolGuard` now validates the result of its targeted repair once, then returns it or fails closed. This removes 163 production lines (2 added): the escalation that ran after a failed repair (an all-messages repair, then two strip passes) and its helpers `isSafeAnthropicProviderToolPrompt`, `providerExecutedToolMessageIndexes`, `stripAnthropicProviderToolHistoryFromMessages` and `addAnthropicProviderToolSanitizationStats`, plus their internal tests. `git grep` finds no other callers. ## Why it is safe The escalation ran but could never repair a prompt. `SanitizeAnthropicProviderToolHistory` loops until nothing is left to remove outside the last assistant message when that message carries signed or redacted reasoning, so after the targeted repair any violation left is in that message. Every later pass skips that message, so the guard failed anyway. - A differential test (not committed) ran the old and new guard on 1,000,000 random prompts and on every prompt the existing `chatsanitize`, `chatloop` and chatd Anthropic tests pass in. Outputs and errors matched in 1,000,000 of 1,000,000. 200,020 of 1,000,000 prompts reached the escalation; 0 came out repaired. - New subtest `invalid pair in latest signed assistant fails closed` pins the failure path (nil prompt, `ErrAnthropicProviderToolPromptUnsafe`, log fields). It passes before and after; no other test covered that path. - New sanitizer row `drops provider result without output text` takes over the one deleted assertion no other test made: it kills the mutant that keeps an empty-output provider result as empty text. The log detail cap test stays. All 12 mutants of the code the deleted tests touched fail a remaining test. ## Review focus Failures log less: the fallback and strip warnings are gone, and the error log drops `immutable_latest_signed_assistant` (always true), no longer says "nuclear strip", and its `message_index` values point into the prompt the guard validated. ## Validation - `go test ./coderd/x/chatd/chatsanitize/... ./coderd/x/chatd/chatloop/... -count=1`, `go test ./coderd/x/chatd/ -run 'Anthropic|Guard|Sanitiz' -count=1 -p 4 -parallel 4`, `go vet`, `golangci-lint` on `chatsanitize`: pass. ## Stack This stack moves the Anthropic guard unit test into `chatsanitize`, then deletes the guard escalation that can never repair a prompt. 1. #30968 Move the Anthropic guard unit test into its own file 2. #30969 Move the Anthropic guard unit test into `chatsanitize` 3. #30970 Drop the Anthropic guard escalation passes > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
0647a096f2 |
test(coderd/x/chatd): move the Anthropic guard unit test into chatsanitize (#30969)
Renames `coderd/x/chatd/anthropic_guard_test.go` to `coderd/x/chatd/chatsanitize/anthropic_guard_test.go` and moves the ten helpers only `TestAnthropicProviderToolPreRequestGuard` uses from `chatd_test.go` into it. The test now lives in `chatsanitize`, the package it tests. ## Why it is safe This is a pure move. The only changed lines are the package clause (`chatd_test` to `chatsanitize_test`) and the `chatsanitize` import that `chatd_test.go` no longer needs. Git records the file as a rename (`R056`). - Every moved helper had no other caller in package `chatd_test` (`git grep -nw` per name), and none collides with a name in `chatsanitize_test`. - Purity check: the sorted `-`/`+` diff prints only the package clause and the removed import. `git diff --color-moved=plain` marks all 128 moved helper lines as moved and leaves those 3 lines unmarked. - The same four subtests pass in `./coderd/x/chatd/chatsanitize/` as before in `./coderd/x/chatd/`. ## Review focus Confirm that the helpers arrived unchanged. `git diff -M --color-moved=plain` shows it. ## Validation - `go test ./coderd/x/chatd/chatsanitize/... -count=1` and `-run '^TestAnthropicProviderToolPreRequestGuard$' -v`: pass, same 4 subtests. - `go vet ./coderd/x/chatd/ ./coderd/x/chatd/chatsanitize/`: clean. - Pre-commit hook: passed. ## Stack This stack moves the Anthropic guard unit test into `chatsanitize`, then deletes the guard escalation that can never repair a prompt. 1. #30968 Move the Anthropic guard unit test into its own file 2. #30969 Move the Anthropic guard unit test into `chatsanitize` 3. #30970 Drop the Anthropic guard escalation passes > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
b2c8798e0e |
fix: replay stateless OpenAI reasoning across chat turns (#30298)
OpenAI Responses chats default to `store=false`, and chatd only replayed reasoning as an `item_reference`, which needs provider-side storage. Reasoning was therefore dropped between tool steps and turns, so reasoning models lost their chain of thought mid-task. This pins coder/fantasy `coder_2_33` at 6ba8681, which includes fantasy #63 (and #64, #65, and #66). #63 captures each completed reasoning item (ID, `encrypted_content`, summary) and replays it in full regardless of `store`. In chatd: - Every Responses call requests `reasoning.encrypted_content`. The `store` default and configured includes are unchanged, and Chat Completions requests are untouched. - Prompt rebuilds keep reasoning parts without visible text when they carry finalized encrypted state, so reasoning survives durable history and coderd restarts. - The provider-switch sanitizer also strips OpenAI reasoning from history produced by a different or unknown provider instance, since reasoning IDs and encrypted content only resolve where they were issued. - A compaction model override on a different provider instance, or with a different model, gets a compaction prompt without the chat's OpenAI reasoning. - Each saved reasoning part records the provider instance, model, and credential (the deployment's or the user's personal API key) that produced it, and the sanitizer keeps it only when all three match the current turn, because another model, or the organization behind another credential, can reject the encrypted content. Switching models, adding or removing a personal key, or editing a config's model or provider drops the earlier reasoning; switching back restores it. The record is never returned by the API. Reasoning saved before this change has no record and follows its model config. - If OpenAI rejects replayed reasoning it cannot decrypt (`invalid_encrypted_content`), for example after the deployment's key is replaced with one from another organization, the request is retried once without reasoning, and the reasoning that step produces is saved with the provider's next rejection epoch. Epochs are kept separately for each provider, model, and credential. Later steps and turns leave out reasoning from earlier epochs, on any replica and after restarts, so only the first request after the change is rejected and newer reasoning keeps replaying. A retried step that returns no reasoning saves its epoch on its first part. The advisor's prompt never includes OpenAI reasoning, as on `main`. ## Testing Rebased onto main at |
||
|
|
4f74a7adee |
fix: enable goleak in chatd tests (#26335)
Enable goleak in chatd tests and fix some leaks. Addresses https://github.com/coder/coder/pull/26109#discussion_r3380039964 |
||
|
|
4debd23cbb |
fix: chatd refactor (#26270)
Implements the chatd stabilization RFC. Combines: - https://github.com/coder/coder/pull/25908 - https://github.com/coder/coder/pull/25923 - https://github.com/coder/coder/pull/26109 - https://github.com/coder/coder/pull/26110 - https://github.com/coder/coder/pull/26111 - https://github.com/coder/coder/pull/26112 |
||
|
|
1e8c8d7dba |
fix(coderd/x/chatd): drop orphan provider tool calls on replay (#25491)
Anthropic replay can fail when stored history contains a
provider-executed tool call like `web_search` without the matching
provider-executed result. That orphaned call is incomplete
provider-internal state, so replaying it can make an otherwise usable
chat unreplayable even though there is no search result to preserve.
This fixes replay by dropping orphan provider-executed tool calls from
the model-visible prompt, preserving signed reasoning and the rest of
the assistant content, then revalidating before the request. We do not
synthesize tool results or drop reasoning. The database can retain the
historical artifact for inspection, while Anthropic only sees replayable
content.
This matches permissively licensed prior art. Vercel AI SDK
(Apache-2.0), used by mux, keeps incomplete tool state in UI/history but
omits it from model requests with `convertToModelMessages(..., {
ignoreIncompleteToolCalls: true })`. LangChain, LiteLLM, and OpenAI
Agents (MIT for the relevant open-source code) also preserve Anthropic
signed reasoning as opaque replay data. Coder applies that model-visible
replay boundary explicitly because our persisted history is already in
provider-message form.
This matches mux, is cleaner than the older idea around not persisting
the search query tool, and the model handles the repaired prompt fine.
Closes CODAGT-448
## Before
<img width="963" height="491" alt="image"
src="https://github.com/user-attachments/assets/a7788ebf-2728-4420-90cf-5e4f6905bdf7"
/>
## After
<img width="842" height="513" alt="image"
src="https://github.com/user-attachments/assets/ae39c262-7586-4e2d-b7db-1b639a7e8e15"
/>
|
||
|
|
e75bd3aca4 |
fix: preserve Anthropic replay fidelity (#25377)
Anthropic is strict about replaying the latest assistant turn once it contains signed or redacted reasoning. We were still mutating that turn in a few Coder-owned places: dropping empty reasoning blocks on replay, rewriting provider-tool history during sanitization, and in the worst case sending a prompt we already knew Anthropic would reject. This patch keeps the latest signed assistant immutable through Coder's replay and sanitization paths, preserves empty signed or redacted reasoning anywhere Coder owns the ledger, and fails before the provider call if the prompt is still unsafe. It also bumps the existing `coder/fantasy` `coder_2_33` fork that `main` already uses to the commit containing coder/fantasy#35. These fixes have also been upstreamed to charmbracelet/fantasy. Closes CODAGT-409. |
||
|
|
99eb46dac1 |
fix(coderd/x/chatd): repair Anthropic provider tool history (#24744)
## Problem Anthropic returns HTTP 400 when an assistant message contains a `web_search_tool_result` block whose `tool_use_id` has no matching earlier `server_tool_use` block in the same assistant message. A previous fix (#24706) sanitized provider-executed tool calls without matching results, but the opposite direction, orphaned or misordered provider-executed results, could still slip through both the prompt sanitizer and the persistence path. ## Fix Tighten Anthropic provider-executed tool history handling while preserving the useful result payload as normal assistant text when the provider-tool metadata is unsafe. 1. Extract Anthropic provider-tool sanitization into `coderd/x/chatd/chatsanitize` so provider-specific repair logic is no longer spread through `chatprompt` and `chatloop`. 2. `chatsanitize.SanitizeAnthropicProviderToolHistory` removes invalid provider-executed tool structure for Anthropic prompts: orphans in either direction, result-before-call, duplicate IDs, invalid JSON inputs, empty IDs and tool names, unsupported tool names, mismatched `ProviderExecuted` flags, provider-executed blocks outside assistant messages, and web-search results without serializable Anthropic result metadata. Provider-executed result payloads are textified instead of being discarded when there is text to preserve. 3. `chatsanitize.SanitizeAnthropicProviderToolContent` mirrors the same rule at the streamed step content level. Persisted history no longer carries invalid provider-tool blocks forward, but it keeps the result text for future turns. 4. `chatsanitize.ApplyAnthropicProviderToolGuard` only repairs structurally invalid Anthropic provider-tool history. It no longer strips otherwise-valid historical `web_search` blocks just because web search is disabled for the current request. The fail-closed fallback also textifies provider results before removing provider-tool metadata. Tests cover prompt sanitization, validation reason strings, result payload textification, content-level persistence sanitization, disabled web-search history preservation, direct pre-request guard behavior, and the fallback strip path. > Mux is acting on Mike's behalf. |