server: preserve retained images during compaction body recovery

This commit is contained in:
Eva Ho committed 2026-10-26 15:26:15 -04:00
1 parent 66ab8482e0
commit d4995090e5
3 files changed
+194 -12

No files matched your search

+74 -7
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"net/http"
"slices"
"strings"
@@ -22,7 +23,7 @@ const (
OllamaCompactionPayloadVersion = 1
CreateSummaryToolName = "create_summary"
compactionSummaryToolName = "ollama_compaction_summary"
compactionOmissionNotice = "Compaction warning: %d older transcript items were omitted before summarization because the model's context limit was exceeded."
compactionOmissionNotice = "Compaction warning: %d older transcript items were omitted before summarization because request limits were exceeded."
)
// ResponsesCompactionTrigger is the terminal input item sent by current Codex
@@ -79,6 +80,7 @@ type compactionTranscriptItemWire struct {
Message api.Message `json:"message"`
StandaloneName *compactionFunctionName `json:"standalone_name,omitempty"`
ImageCount int `json:"image_count,omitempty"`
ImagesOmitted bool `json:"images_omitted,omitempty"`
}
type compactionToolGroup struct {
@@ -92,11 +94,12 @@ type ResponsesCompactionPlan struct {
Model string
Stream bool
items []CompactionTranscriptItem
tools []compactionToolMetadata
groups []compactionToolGroup
forcedRefs map[string]struct{}
omittedItems int
items []CompactionTranscriptItem
tools []compactionToolMetadata
groups []compactionToolGroup
forcedRefs map[string]struct{}
omittedItems int
omittedSummaryImages map[string]int
}
// ResponsesCompactionResult is the validated result of a compaction-model call.
@@ -821,6 +824,59 @@ func (p *ResponsesCompactionPlan) TrimForContextLimit() int {
return len(removed)
}
// ReduceSummaryBody chooses the smaller of an item-trimmed transcript and one
// without older, unprotected image inputs. Original images remain available for
// retained items. It applies a reduction only when the encoded request shrinks.
func (p *ResponsesCompactionPlan) ReduceSummaryBody() bool {
if len(p.items) < 2 {
return false
}
original, err := p.SummaryRequest("")
if err != nil {
return false
}
best, size := *p, len(original)
consider := func(candidate ResponsesCompactionPlan) {
body, err := candidate.SummaryRequest("")
if err == nil && len(body) < size {
best, size = candidate, len(body)
}
}
trimmed := *p
trimmed.items = slices.Clone(p.items)
trimmed.groups = slices.Clone(p.groups)
if trimmed.TrimForContextLimit() > 0 {
consider(trimmed)
}
images := *p
images.omittedSummaryImages = maps.Clone(p.omittedSummaryImages)
if images.omittedSummaryImages == nil {
images.omittedSummaryImages = make(map[string]int)
}
for _, item := range p.items[:len(p.items)-1] {
if _, protected := p.forcedRefs[item.Ref]; !protected && len(item.Message.Images) > 0 {
images.omittedSummaryImages[item.Ref] = len(item.Message.Images)
}
}
consider(images)
if size == len(original) {
return false
}
*p = best
return true
}
func (p *ResponsesCompactionPlan) imageOmissionNotice() string {
var count int
for _, images := range p.omittedSummaryImages {
count += images
}
if count == 0 {
return ""
}
return fmt.Sprintf("Compaction warning: %d older images were excluded from the summary input because the request was too large.", count)
}
// SummaryRequest returns an ordinary non-streaming Responses request. A repair
// request includes the validation error from the first model response.
func (p *ResponsesCompactionPlan) SummaryRequest(repairError string) ([]byte, error) {
@@ -834,6 +890,9 @@ func (p *ResponsesCompactionPlan) SummaryRequest(repairError string) ([]byte, er
if p.omittedItems > 0 {
prompt += " " + fmt.Sprintf(compactionOmissionNotice, p.omittedItems)
}
if notice := p.imageOmissionNotice(); notice != "" {
prompt += " " + notice
}
if repairError != "" {
prompt += " Your previous create_summary call was invalid: " + repairError + ". Return one corrected create_summary call."
}
@@ -880,9 +939,14 @@ func (p *ResponsesCompactionPlan) summaryTranscriptMessages() ([]any, error) {
for _, item := range p.items {
message := item.Message
images := message.Images
imagesOmitted := p.omittedSummaryImages[item.Ref] > 0
if imagesOmitted {
images = nil
}
message.Images = nil
metadata, err := json.Marshal(compactionTranscriptItemWire{
Ref: item.Ref, Type: item.Type, Message: message, StandaloneName: item.StandaloneName, ImageCount: len(images),
Ref: item.Ref, Type: item.Type, Message: message, StandaloneName: item.StandaloneName,
ImageCount: len(item.Message.Images), ImagesOmitted: imagesOmitted,
})
if err != nil {
return nil, err
@@ -978,6 +1042,9 @@ func (p *ResponsesCompactionPlan) Complete(body []byte) (ResponsesCompactionResu
if p.omittedItems > 0 {
payload.Summary = fmt.Sprintf(compactionOmissionNotice, p.omittedItems) + "\n\n" + payload.Summary
}
if notice := p.imageOmissionNotice(); notice != "" {
payload.Summary = notice + "\n\n" + payload.Summary
}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return ResponsesCompactionResult{}, err
+11 -5
View File
@@ -100,7 +100,7 @@ func resetResponsesRequestBody(r *http.Request, body []byte) {
func (s *Server) handleResponsesCompaction(c *gin.Context, plan *openai.ResponsesCompactionPlan, stream bool) {
var validationErr error
overflowRetried := false
sizeRetried := false
for {
repair := ""
if validationErr != nil {
@@ -114,10 +114,16 @@ func (s *Server) handleResponsesCompaction(c *gin.Context, plan *openai.Response
response := s.runResponsesCompactionInference(c, request)
if response.status < http.StatusOK || response.status >= http.StatusMultipleChoices {
if !overflowRetried && c.Request.Context().Err() == nil && isCompactionContextLimit(response) {
if removed := plan.TrimForContextLimit(); removed > 0 {
overflowRetried = true
slog.WarnContext(c.Request.Context(), "retrying compaction after context overflow", "model", plan.Model, "omitted_items", removed)
if !sizeRetried && c.Request.Context().Err() == nil {
retry := false
if isCompactionContextLimit(response) {
retry = plan.TrimForContextLimit() > 0
} else if response.status == http.StatusRequestEntityTooLarge {
retry = plan.ReduceSummaryBody()
}
if retry {
sizeRetried = true
slog.WarnContext(c.Request.Context(), "retrying compaction after request limit", "model", plan.Model, "status", response.status)
continue
}
}
+109
View File
@@ -146,6 +146,115 @@ func TestResponsesCompactionOverflowWithoutRemovableHistory(t *testing.T) {
}
}
func TestResponsesCompactionBodyRecovery(t *testing.T) {
const imageURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
const tooLarge = "Request Entity Too Large"
image := `{"type":"input_image","image_url":"` + imageURL + `"}`
active := `{"type":"function_call","call_id":"a","name":"screenshot","arguments":"{}"},
{"type":"function_call","call_id":"b","name":"screenshot","arguments":"{}"},
{"type":"function_call_output","call_id":"a","output":[` + image + `]},
{"type":"function_call_output","call_id":"b","output":[` + image + `]}`
for _, test := range []struct {
name string
arguments int
protectedOnly bool
reject bool
wantStatus int
wantAttempts int
wantImages int
}{
{name: "images", wantStatus: 200, wantAttempts: 2, wantImages: 2},
{name: "arguments", arguments: 10_000, wantStatus: 200, wantAttempts: 2, wantImages: 34},
{name: "protected state", protectedOnly: true, wantStatus: 413, wantAttempts: 1, wantImages: 2},
{name: "retry exhausted", reject: true, wantStatus: 413, wantAttempts: 2, wantImages: 2},
} {
t.Run(test.name, func(t *testing.T) {
input := active
if !test.protectedOnly {
arguments, err := json.Marshal(map[string]string{"script": strings.Repeat("x", test.arguments)})
if err != nil {
t.Fatal(err)
}
quoted, _ := json.Marshal(string(arguments))
input = `{"role":"user","content":[` + strings.TrimSuffix(strings.Repeat(image+",", 32), ",") + `]},
{"type":"function_call","call_id":"old","name":"shell","arguments":` + string(quoted) + `},
{"type":"function_call_output","call_id":"old","output":"completed"},
{"role":"assistant","content":"finished"},` + input
}
local, capture := newCompactionTestServer(t, func(attempt int, w http.ResponseWriter, _ *http.Request, _ []byte) {
if attempt == 1 || test.reject {
w.WriteHeader(http.StatusRequestEntityTooLarge)
_, _ = io.WriteString(w, tooLarge)
} else if attempt == 2 {
retained := []string{"item_000001"}
if test.arguments == 0 {
retained = append(retained, "item_000003")
}
_, _ = w.Write(summaryResponse(t, "Continue.", retained))
} else {
_, _ = io.WriteString(w, `{"id":"next","object":"response","status":"completed","output":[]}`)
}
})
status, _, body := postCompactionRequest(t, local, "/v1/responses/compact", `{"model":"fixture:cloud","input":[`+input+`]}`)
_, requests := capture.snapshot()
if status != test.wantStatus || len(requests) != test.wantAttempts {
t.Fatalf("status=%d attempts=%d, want %d/%d", status, len(requests), test.wantStatus, test.wantAttempts)
}
last := requests[len(requests)-1]
if got := bytes.Count(last, []byte(imageURL)); got != test.wantImages {
t.Fatalf("summary images=%d, want %d", got, test.wantImages)
}
if status == http.StatusRequestEntityTooLarge {
if string(body) != tooLarge {
t.Fatalf("upstream error changed: %s", body)
}
return
}
if len(last) >= len(requests[0]) {
t.Fatal("retry did not reduce the serialized request")
}
var compacted openai.ResponsesCompactedResponse
if err := json.Unmarshal(body, &compacted); err != nil {
t.Fatal(err)
}
var payload openai.OllamaCompactionPayload
if err := json.Unmarshal([]byte(compacted.Output[0].EncryptedContent), &payload); err != nil {
t.Fatal(err)
}
wantRetained, activeOffset := 5, 3
warning := "2 older transcript items"
if test.arguments == 0 {
wantRetained, activeOffset = 7, 5
warning = "summary input"
}
if len(payload.Retained) != wantRetained || len(payload.Retained[0].Images) != 32 {
t.Fatal("selected original images or active tool state were lost")
}
for i, id := range []string{"a", "b"} {
message := payload.Retained[i+activeOffset]
if message.ToolCallID != id || len(message.Images) != 1 {
t.Fatalf("active tool result %s changed", id)
}
}
if !strings.Contains(payload.Summary, warning) {
t.Fatal("continuation does not disclose excluded context")
}
next, err := json.Marshal(map[string]any{"model": "fixture:cloud", "input": []any{
compacted.Output[0], map[string]any{"role": "user", "content": "Resume marker."},
}})
if err != nil {
t.Fatal(err)
}
status, _, _ = postCompactionRequest(t, local, "/v1/responses", string(next))
_, requests = capture.snapshot()
continued := requests[len(requests)-1]
if status != http.StatusOK || bytes.Count(continued, []byte(imageURL)) != 34 || !bytes.Contains(continued, []byte("Resume marker.")) || !bytes.Contains(continued, []byte(warning)) {
t.Fatal("next turn did not replay the original images and new user message")
}
})
}
}
func summaryResponse(t *testing.T, summary string, retained []string) []byte {
t.Helper()
arguments, err := json.Marshal(map[string]any{"summary": summary, "retain_item_ids": retained})