[Performance] Streaming persistence rewrites the full message on every delta

Đang mở
#4,569 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@akushonkamen đang làm issue này rồi.

Từ ngày 13/10/2026.

  • #4575 của @akushonkamen — đang mở

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
42/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
go, sqlite
Lĩnh vực
backend, databases, performance

Hướng nghiên cứu

Start with pkg/runtime/persistence_observer.go and pkg/session/store.go to trace how each delta reaches the SQLite update; read pkg/runtime/observer.go to understand synchronous event delivery. Use the supplied fake-provider probe to reproduce the write growth, then add regression coverage for bounded checkpoint writes, final persisted content, completion, and cancellation. Done means persistence reduces repeated full-message writes while preserving the stated recovery behavior.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

area/runtime area/sessions

Severity: medium · Type: performance

Location

Reviewed commit: cd65d7c776dda80d554735ee20572d09cfe2d791.

Issue details

Incremental persistence repeatedly serializes the growing message, yielding quadratic cumulative payload volume for fixed-size deltas. The SQLite adapter executes one full-row JSON update per delta, on the event-delivery path. This buys fine-grained recovery, but long responses and reasoning streams pay for all their previous content again on every chunk.

A fake provider plus counting store exercised the actual public runtime and its stock persistence observer, with no model API requests:

16-byte text chunks Final text bytes Assistant writes (including finalization) Cumulative text bytes passed to store JSON bytes serialized with the same json.Marshal(msg.Message) as SQLite
1,024 16,384 1,025 8,413,184 8,500,393
2,048 32,768 2,049 33,603,584 33,777,833
4,096 65,536 4,097 134,316,032 134,664,361

Doubling the final response roughly quadruples cumulative payload volume. These numbers measure the observer/store contract and JSON serialization volume; they are not a disk-I/O or end-to-end latency benchmark. The SQLite source establishes that each update serializes and sends the full message to an SQL update.

Save the following as /tmp/persistence-probe.go and run go run /tmp/persistence-probe.go from the repository root:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"strings"

	"github.com/docker/docker-agent/pkg/agent"
	"github.com/docker/docker-agent/pkg/chat"
	"github.com/docker/docker-agent/pkg/config/latest"
	"github.com/docker/docker-agent/pkg/model/provider/contracts"
	"github.com/docker/docker-agent/pkg/modelsdev"
	"github.com/docker/docker-agent/pkg/runtime"
	"github.com/docker/docker-agent/pkg/session"
	"github.com/docker/docker-agent/pkg/team"
	"github.com/docker/docker-agent/pkg/tools"
)

type countingStore struct {
	session.Store
	writes, contentBytes, jsonBytes int
}

func (s *countingStore) AddMessage(ctx context.Context, id string, msg *session.Message) (int64, error) {
	s.record(msg)
	return s.Store.AddMessage(ctx, id, msg)
}
func (s *countingStore) UpdateMessage(ctx context.Context, sid string, id int64, msg *session.Message) error {
	s.record(msg)
	return s.Store.UpdateMessage(ctx, sid, id, msg)
}
func (s *countingStore) record(msg *session.Message) {
	if msg.Message.Role != chat.MessageRoleAssistant { return }
	s.writes++
	s.contentBytes += len(msg.Message.Content)
	b, err := json.Marshal(msg.Message)
	if err != nil { panic(err) }
	s.jsonBytes += len(b)
}

type fakeProvider struct { n int }
func (p fakeProvider) ID() modelsdev.ID { return modelsdev.NewID("test", "mock") }
func (p fakeProvider) BaseConfig() contracts.Config {
	return contracts.Config{ModelConfig: latest.ModelConfig{Provider: "test", Model: "mock"}}
}
func (p fakeProvider) CreateChatCompletionStream(context.Context, []chat.Message, []tools.Tool) (chat.MessageStream, error) {
	return &fakeStream{n: p.n}, nil
}
type fakeStream struct { n, i int }
func (s *fakeStream) Recv() (chat.MessageStreamResponse, error) {
	if s.i > s.n { return chat.MessageStreamResponse{}, io.EOF }
	choice := chat.MessageStreamChoice{}
	if s.i == s.n { choice.FinishReason = chat.FinishReasonStop } else { choice.Delta.Content = strings.Repeat("x", 16) }
	s.i++
	return chat.MessageStreamResponse{Choices: []chat.MessageStreamChoice{choice}}, nil
}
func (*fakeStream) Close() {}
type fakeCatalog struct{}
func (fakeCatalog) GetModel(context.Context, modelsdev.ID) (*modelsdev.Model, error) { return nil, nil }
func (fakeCatalog) GetDatabase(context.Context) (*modelsdev.Database, error) { return &modelsdev.Database{}, nil }

func main() {
	for _, n := range []int{1024, 2048, 4096} {
		ctx := context.Background()
		store := &countingStore{Store: session.NewInMemorySessionStore()}
		a := agent.New("root", "Respond.", agent.WithModel(fakeProvider{n: n}))
		rt, err := runtime.New(ctx, team.New(team.WithAgents(a)), runtime.WithSessionStore(store), runtime.WithModelStore(fakeCatalog{}), runtime.WithSessionCompaction(false))
		if err != nil { panic(err) }
		sess := session.New(session.WithUserMessage("hi"), session.WithNonInteractive(true))
		for ev := range rt.RunStream(ctx, sess) {
			if e, ok := ev.(*runtime.ErrorEvent); ok { panic(e.Error) }
		}
		if err := rt.Close(); err != nil { panic(err) }
		fmt.Printf("chunks=%d final_bytes=%d assistant_writes=%d cumulative_content_bytes=%d serialized_json_bytes=%d\n", n, n*16, store.writes, store.contentBytes, store.jsonBytes)
	}
}
Impact

Large text/reasoning replies cause avoidable serialization, allocations and database updates. Because persistence is synchronous, slower storage also delays delivery to the terminal/UI and downstream observers. Concurrent sessions amplify pressure on the store.

Recommended fix

Coalesce persistence updates by time and/or added byte count, with bounded buffering and a guaranteed final flush on message completion and lifecycle teardown. Preserve partial recovery semantics explicitly. Alternatively store append-only deltas with periodic snapshots.

Add a fake-provider/counting-store regression that bounds checkpoint writes as chunk count grows, verifies the final persisted content, and covers completion/cancellation. Benchmark the SQLite-backed path before selecting checkpoint intervals.

Ngôn ngữ chính
Go
Star
4.7k
Fork
565
Merge trung bình
18 giờ 52 phút
Pull request đã merge (30 ngày)
221

Chuẩn bị môi trường

Mở trong Codespaces

Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.

  • Có Dockerfile hoặc tệp Docker Compose
  • Không có mẫu pull request
  • Không có hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của docker/docker-agent

Tất cả issue của docker/docker-agent

Issue tương tự

Thêm issue về Go

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.