From bb275a72ce22658759af97ff931918e3ee18b775 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 12:47:24 +0000 Subject: [PATCH 1/6] fix(session): the recorder retries a write that can pass and keeps other sessions' items A write that fails for a dropped or refused connection, a timeout, a server shutting down, or a serialization failure or deadlock is tried again in place, in queue order, for up to 10 seconds. A batch of items refused for a missing parent row is written again per session, and only the sessions whose row is missing are dropped. Session and call ends that still cannot be stored, and dropped items, are counted in router_session_records_lost_total. --- CHANGELOG.md | 4 + .../internal/session/record_flush_test.go | 75 +++++++++ acceleration/internal/session/records.go | 155 +++++++++++++++--- acceleration/internal/store/postgres.go | 31 ++++ 4 files changed, 241 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb26da99e0..0ad2cc9416 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -925,6 +925,10 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env A request row's cost is added to a grant it names only when the grant belongs to the row's organization or to its app's (the organization the app is in, or the app itself for an app in none), both as the row is written and when the grant uses are reconciled. A grant scoped to an app, or to its key or user, counts only that app's rows. A use refused because the grant is not the row's is counted on `/metrics` as `router_usage_grant_uses_refused_total`. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. +### A dropped database connection no longer loses a conversation's record + +The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout, a server shutting down, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a session or turn that was never stored no longer stop the items of other sessions written in the same batch. A session or call end that still cannot be stored is counted in `router_session_records_lost_total{write}`, as are dropped items. + ### A customer can no longer list or speak in another customer's cloned voice Clones made through `/v1/agents/voices` sit in the deployment's shared provider account, which lists them all as its own. A voice id that another customer's voice was prepared as is now refused, whether it is the session's voice or the `voice_id` of TTS overwrites. The voice library lists only the caller's own clones besides the provider's published voices, previews another customer's clone as not found, and no longer suggests one as the closest voice. diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index a8b079d51b..e4158c2ab9 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -366,6 +367,80 @@ func (s *RecordFlushSuite) TestATitleTheStoreCouldNotWriteStillLogsAnError() { s.Contains(logged.String(), "could not record the session's title") } +func (s *RecordFlushSuite) TestASessionWriteCutOffByADroppedConnectionIsStoredWithWhatFollowsIt() { + held, release := s.heldRow() + response := store.AgentResponse{ID: rand.Text(), SessionID: held.ID, CustomerID: s.customer, Said: "Where is my order?"} + s.records.Opened(held, nil) + s.records.Responding(response) + s.records.Item(store.AgentResponseItem{ResponseID: response.ID, Ordinal: 0, SessionID: held.ID, + Kind: store.ItemSaid, Text: "Where is my order?", At: time.Now().UTC()}) + + // The writer's session insert waits on the held row's lock; its connection is cut there, + // mid-statement, as a failover cuts it. + var writer int + s.Require().Eventually(func() bool { + err := s.store.GlobalDB().QueryRowContext(s.ctx, `SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%agent_sessions%'`).Scan(&writer) + return err == nil + }, settleFor, 5*time.Millisecond, "the writer never waited on the held row") + _, err := s.store.GlobalDB().ExecContext(s.ctx, "SELECT pg_terminate_backend(?)", writer) + s.Require().NoError(err) + release() + s.Require().NoError(s.records.Flush(s.bounded())) + + s.True(s.stored(held.ID), "the session is not stored") + got, err := s.store.Responses.Get(s.ctx, s.customer, held.ID, response.ID) + s.Require().NoError(err, "the turn is not stored") + s.Equal(held.ID, got.SessionID) + items, err := s.store.ResponseItems.Select(s.ctx, s.customer, held.ID, store.ItemFilter{ResponseID: response.ID, Limit: 10}) + s.Require().NoError(err) + s.Len(items, 1, "the turn's item is not stored") +} + +func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopAnotherSessionsItems() { + kept, orphaned := s.row(), s.row() + s.records.Opened(kept, nil) + s.records.Opened(orphaned, nil) + response := store.AgentResponse{ID: rand.Text(), SessionID: kept.ID, CustomerID: s.customer, Said: "Where is my order?"} + s.records.Responding(response) + lost := testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)) + + // Back to back, so both go in one batch. + s.records.Item(store.AgentResponseItem{ResponseID: response.ID, Ordinal: 0, SessionID: kept.ID, + Kind: store.ItemSaid, Text: "It ships today.", At: time.Now().UTC()}) + s.records.Item(store.AgentResponseItem{ResponseID: rand.Text(), Ordinal: 0, SessionID: orphaned.ID, + Kind: store.ItemSaid, Text: "Thanks.", At: time.Now().UTC()}) + s.Require().NoError(s.records.Flush(s.bounded())) + + items, err := s.store.ResponseItems.Select(s.ctx, s.customer, kept.ID, store.ItemFilter{ResponseID: response.ID, Limit: 10}) + s.Require().NoError(err) + s.Len(items, 1, "the item of a session whose turn is stored was lost with the other session's") + s.InDelta(lost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)), 0, "the dropped item is not counted") +} + +func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRunOut() { + // Nothing listens on port 1, so every try is refused, the way a database that stays + // down refuses it. + down, err := store.Open("postgres://postgres:postgres@127.0.0.1:1/router?sslmode=disable") + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(down.Close()) }) + records := s.recorderLogging(down, &syncBuffer{}) + sessionsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)) + callsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)) + + start := time.Now() + records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) + (&callRecorder{records: records}).Ended(s.customer, rand.Text(), time.Now().UTC()) + s.Require().NoError(records.Flush(s.bounded())) + + // One budget in all: once a write ran out of retries, the next is tried once. + s.Less(time.Since(start), recordRetryFor*3/2, "the writer retried each write for a budget of its own") + s.InDelta(sessionsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)), 0, + "the session end that was never stored is not counted") + s.InDelta(callsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)), 0, + "the call end that was never stored is not counted") +} + // recorderLogging is a writer over db that logs everything, even debug lines, into logged. func (s *RecordFlushSuite) recorderLogging(db *store.Store, logged *syncBuffer) *sessionRecorder { records := newSessionRecorder(db, slog.New(slog.NewTextHandler(logged, &slog.HandlerOptions{Level: slog.LevelDebug}))) diff --git a/acceleration/internal/session/records.go b/acceleration/internal/session/records.go index 3042f7c90d..1c6ea490c8 100644 --- a/acceleration/internal/session/records.go +++ b/acceleration/internal/session/records.go @@ -9,6 +9,9 @@ import ( "sync/atomic" "time" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -22,6 +25,37 @@ const recordQueueSize = 1024 // recordWriteTimeout bounds a single write so a stuck database cannot wedge the writer. const recordWriteTimeout = 5 * time.Second +// recordRetryFor bounds how long one write is tried again after a failure that may pass, so +// a database that stays down holds the single writer, and the rows queued behind it, no +// longer than a failover takes. recordRetryFirst is the wait before the first retry, doubled +// each time up to recordRetryMost. +const ( + recordRetryFor = 10 * time.Second + recordRetryFirst = 50 * time.Millisecond + recordRetryMost = time.Second +) + +// The writes recordsLost counts, a fixed set. +const ( + lostSessionEnd = "session_ended" + lostCallEnd = "call_ended" + lostItems = "items" +) + +var recordsLost = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "router", + Name: "session_records_lost_total", + Help: "Session records the writer could not store after retrying, by write: session_ended and call_ended " + + "(the row stays open), and items (dropped because their session or response row was never stored)", +}, []string{"write"}) + +// The series exist from the start, so a rate over the first loss reads it. +func init() { + for _, write := range []string{lostSessionEnd, lostCallEnd, lostItems} { + recordsLost.WithLabelValues(write) + } +} + // itemFlushEvery is how long a partial batch of items waits for company. // // Items arrive in bursts -- a question, then nothing while a tool runs, then several at once @@ -144,6 +178,10 @@ type sessionRecorder struct { // another customer's: their items are not written under it. Kept by the writer alone, and // each until its turn ends. refused map[string]struct{} + // failing is set, by the writer alone, once a write ran out of retries, and cleared by the + // next that succeeds. Meanwhile each write is tried once: a database that stays down + // would otherwise hold every queued write, and Close behind them, for a whole budget each. + failing bool } func newSessionRecorder(pgStore *store.Store, logger *slog.Logger) *sessionRecorder { @@ -383,28 +421,33 @@ func (w *flushWaiters) release(taken int) { } func (r *sessionRecorder) write(write recordWrite) { - ctx, cancel := context.WithTimeout(context.Background(), recordWriteTimeout) - defer cancel() - switch { case write.session != nil: - if err := r.store.Sessions.Upsert(ctx, write.session); err != nil { + if err := r.attempt(func(ctx context.Context) error { return r.store.Sessions.Upsert(ctx, write.session) }); err != nil { r.logger.Error("could not record the session starting", "error", err) return } - if err := r.store.SessionTools.Upsert(ctx, write.session.CustomerID, write.session.ID, write.tools); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.SessionTools.Upsert(ctx, write.session.CustomerID, write.session.ID, write.tools) + }); err != nil { r.logger.Error("could not record the session's tools", "error", err) } case write.offered != "": - if err := r.store.SessionTools.Upsert(ctx, write.customerID, write.offered, write.tools); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.SessionTools.Upsert(ctx, write.customerID, write.offered, write.tools) + }); err != nil { r.logger.Error("could not record the session's tools", "error", err) } case write.closed != "": - if err := r.store.Sessions.Close(ctx, write.customerID, write.closed, write.closedAt, write.endReason); err != nil { - r.logger.Error("could not record the session ending", "error", err) + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.Close(ctx, write.customerID, write.closed, write.closedAt, write.endReason) + }); err != nil { + // The row stays open, read as live and counted in every concurrency peak. + recordsLost.WithLabelValues(lostSessionEnd).Inc() + r.logger.Error("could not record the session ending", "session", write.closed, "error", err) } case write.response != nil: - err := r.store.Responses.Insert(ctx, write.response) + err := r.attempt(func(ctx context.Context) error { return r.store.Responses.Insert(ctx, write.response) }) if errors.Is(err, store.ErrIDTaken) { r.refused[write.response.ID] = struct{}{} } @@ -413,12 +456,16 @@ func (r *sessionRecorder) write(write recordWrite) { } case write.finished != "": delete(r.refused, write.finished) - if err := r.store.Responses.Finish(ctx, write.customerID, write.finished, write.status, write.failure, write.finishedAt); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Responses.Finish(ctx, write.customerID, write.finished, write.status, write.failure, write.finishedAt) + }); err != nil { r.logger.Error("could not record the turn ending", "error", err) } case write.described != nil: d := write.described - err := r.store.Sessions.Describe(ctx, d.customerID, d.id, d.title, d.description, d.custom) + err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.Describe(ctx, d.customerID, d.id, d.title, d.description, d.custom) + }) if errors.Is(err, store.ErrNoSession) { // The conversation is named after it ran, so the customer may have deleted it by // then. Nothing is lost: the title had nothing left to name. @@ -428,33 +475,45 @@ func (r *sessionRecorder) write(write recordWrite) { } case write.chose != nil: c := write.chose - if err := r.store.Sessions.ChooseConnection(ctx, c.customerID, c.id, c.name, c.connectionID); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.ChooseConnection(ctx, c.customerID, c.id, c.name, c.connectionID) + }); err != nil { r.logger.Error("could not record the connection a login chose", "session", c.id, "error", err) } case write.timed != nil: t := write.timed - if err := r.store.Sessions.SetToolTimeout(ctx, write.customerID, t.id, t.kind, t.milliseconds); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.SetToolTimeout(ctx, write.customerID, t.id, t.kind, t.milliseconds) + }); err != nil { r.logger.Error("could not record the session's tool timeout", "session", t.id, "error", err) } case write.sawVideo != "": - if err := r.store.Sessions.SawVideo(ctx, write.customerID, write.sawVideo); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.SawVideo(ctx, write.customerID, write.sawVideo) + }); err != nil { r.logger.Error("could not record the session's video", "session", write.sawVideo, "error", err) } case write.voiced != "": - if err := r.store.Sessions.Voiced(ctx, write.customerID, write.voiced); err != nil { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.Voiced(ctx, write.customerID, write.voiced) + }); err != nil { r.logger.Error("could not record the session's voice", "session", write.voiced, "error", err) } case write.callStarted != nil: - if err := r.store.Calls.Start(ctx, write.callStarted); err != nil { + if err := r.attempt(func(ctx context.Context) error { return r.store.Calls.Start(ctx, write.callStarted) }); err != nil { r.logger.Error("could not record the call starting", "error", err) } case write.callChanged != nil: - if err := r.store.Calls.ChangeModels(ctx, write.callChanged); err != nil { + if err := r.attempt(func(ctx context.Context) error { return r.store.Calls.ChangeModels(ctx, write.callChanged) }); err != nil { r.logger.Error("could not record the call changing models", "error", err) } case write.callEnded != "": - if err := r.store.Calls.Finish(ctx, write.customerID, write.callEnded, write.callEndedAt); err != nil { - r.logger.Error("could not record the call ending", "error", err) + if err := r.attempt(func(ctx context.Context) error { + return r.store.Calls.Finish(ctx, write.customerID, write.callEnded, write.callEndedAt) + }); err != nil { + // The call stays open, its minutes growing, as a session left open does. + recordsLost.WithLabelValues(lostCallEnd).Inc() + r.logger.Error("could not record the call ending", "call", write.callEnded, "error", err) } } } @@ -463,14 +522,62 @@ func (r *sessionRecorder) writeItems(items []store.AgentResponseItem) { if len(items) == 0 { return } - ctx, cancel := context.WithTimeout(context.Background(), recordWriteTimeout) - defer cancel() - // The slice is copied because the caller reuses its buffer, and the write outlives the // call that handed it over only by as long as this statement takes. batch := append([]store.AgentResponseItem(nil), items...) - if err := r.store.ResponseItems.InsertMany(ctx, batch); err != nil { - r.logger.Error("could not record what a turn did", "error", err, "items", len(batch)) + err := r.attempt(func(ctx context.Context) error { return r.store.ResponseItems.InsertMany(ctx, batch) }) + if !store.IsForeignKeyViolation(err) { + if err != nil { + r.logger.Error("could not record what a turn did", "error", err, "items", len(batch)) + } + return + } + // The batch holds the items of every session, so one whose session or response row was + // never written would fail all of them: each session's are written on their own instead. + var sessions []string + bySession := map[string][]store.AgentResponseItem{} + for _, item := range batch { + if _, seen := bySession[item.SessionID]; !seen { + sessions = append(sessions, item.SessionID) + } + bySession[item.SessionID] = append(bySession[item.SessionID], item) + } + for _, session := range sessions { + own := bySession[session] + err := r.attempt(func(ctx context.Context) error { return r.store.ResponseItems.InsertMany(ctx, own) }) + switch { + case store.IsForeignKeyViolation(err): + recordsLost.WithLabelValues(lostItems).Add(float64(len(own))) + r.logger.Warn("dropped what a turn did: its session or response was never recorded", + "session", session, "items", len(own)) + case err != nil: + r.logger.Error("could not record what a turn did", "session", session, "error", err, "items", len(own)) + } + } +} + +// attempt runs do until it succeeds, fails for a reason another try would not change, or +// recordRetryFor has passed. It retries in place, holding the writes queued behind it: a +// session or response row lost to a dropped connection or a failover would fail the foreign +// key of every later row of its conversation, and the queue's order is what keeps those +// keys whole. While failing, a write is tried once. +func (r *sessionRecorder) attempt(do func(context.Context) error) error { + deadline := time.Now().Add(recordRetryFor) + wait := recordRetryFirst + for { + ctx, cancel := context.WithTimeout(context.Background(), min(time.Until(deadline), recordWriteTimeout)) + err := do(ctx) + cancel() + if err == nil || !store.Transient(err) { + r.failing = false + return err + } + if r.failing || time.Until(deadline) < wait { + r.failing = true + return err + } + time.Sleep(wait) + wait = min(2*wait, recordRetryMost) } } diff --git a/acceleration/internal/store/postgres.go b/acceleration/internal/store/postgres.go index ead12a93d3..990f36ca58 100644 --- a/acceleration/internal/store/postgres.go +++ b/acceleration/internal/store/postgres.go @@ -1,10 +1,15 @@ package store import ( + "context" "database/sql" + "database/sql/driver" "errors" "fmt" + "io" + "net" "strings" + "syscall" "github.com/uptrace/bun/driver/pgdriver" @@ -23,6 +28,32 @@ func isViolation(err error, code string) bool { return errors.As(err, &refused) && refused.Field('C') == code } +// IsForeignKeyViolation reports whether err is Postgres refusing a row whose parent row is +// missing. +func IsForeignKeyViolation(err error) bool { + return isViolation(err, foreignKeyViolation) +} + +// Transient reports whether err is a failure that may pass if the same statement is sent +// again: the connection dropped or was refused, the statement timed out, the server is +// shutting down or full, or Postgres gave up on a serialization or a deadlock. A closed +// pool, a violated constraint and a bad statement are not. +func Transient(err error) bool { + var refused pgdriver.Error + if errors.As(err, &refused) { + switch code := refused.Field('C'); code { + case "40001", "40P01", "53300", "57P01", "57P02", "57P03": + return true + default: + return strings.HasPrefix(code, "08") + } + } + var network net.Error + return errors.As(err, &network) || errors.Is(err, context.DeadlineExceeded) || + errors.Is(err, driver.ErrBadConn) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || + errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) +} + // oneRow turns an update or delete that matched nothing into missing. func oneRow(result sql.Result, missing error) error { affected, err := result.RowsAffected() From 313c4a7c704463927d60f1218c67884981a07646 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 13:11:23 +0000 Subject: [PATCH 2/6] fix(session): items fall back per turn, and a read-only or cancelled write is retried A batch of items refused for a missing parent is written again per response, the row the items' key names, so a stored turn's items are kept beside a session's missing turn; a batch of one turn is not sent again. A write refused with 25006 (read-only transaction, a demoted primary) or 57014 (statement cancelled) is retried, as a client-side timeout already was. A session or call end dropped by a full queue is counted as lost, and a write refused before it reached the database no longer marks the writer healthy. --- CHANGELOG.md | 2 +- .../internal/session/record_flush_test.go | 34 +++++++++++++-- acceleration/internal/session/records.go | 42 ++++++++++++------- acceleration/internal/store/postgres.go | 18 ++++++-- 4 files changed, 73 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ad2cc9416..a43e8f7707 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -927,7 +927,7 @@ A request row's cost is added to a grant it names only when the grant belongs to ### A dropped database connection no longer loses a conversation's record -The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout, a server shutting down, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a session or turn that was never stored no longer stop the items of other sessions written in the same batch. A session or call end that still cannot be stored is counted in `router_session_records_lost_total{write}`, as are dropped items. +The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout on either side, a server shutting down, a write reaching a primary a failover made read-only, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a turn that was never stored no longer stop the items of other turns written in the same batch, in the same session or another. A session or call end that still cannot be stored, or that the full queue dropped, is counted in `router_session_records_lost_total{write}`, as are dropped items. ### A customer can no longer list or speak in another customer's cloned voice diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index e4158c2ab9..b207a7e77c 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -418,6 +418,25 @@ func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopAnotherSes s.InDelta(lost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)), 0, "the dropped item is not counted") } +func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopItsSessionsStoredTurn() { + session := s.row() + s.records.Opened(session, nil) + stored := store.AgentResponse{ID: rand.Text(), SessionID: session.ID, CustomerID: s.customer, Said: "Can I change the address?"} + s.records.Responding(stored) + + // Back to back, so both go in one batch: one item of the stored turn, one of a turn whose + // row was never written, in the same session. + s.records.Item(store.AgentResponseItem{ResponseID: stored.ID, Ordinal: 0, SessionID: session.ID, + Kind: store.ItemSaid, Text: "Yes, until it ships.", At: time.Now().UTC()}) + s.records.Item(store.AgentResponseItem{ResponseID: rand.Text(), Ordinal: 0, SessionID: session.ID, + Kind: store.ItemSaid, Text: "Great, thanks.", At: time.Now().UTC()}) + s.Require().NoError(s.records.Flush(s.bounded())) + + items, err := s.store.ResponseItems.Select(s.ctx, s.customer, session.ID, store.ItemFilter{ResponseID: stored.ID, Limit: 10}) + s.Require().NoError(err) + s.Len(items, 1, "the stored turn's item was dropped with its session's missing turn") +} + func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRunOut() { // Nothing listens on port 1, so every try is refused, the way a database that stays // down refuses it. @@ -431,10 +450,17 @@ func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRun start := time.Now() records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) (&callRecorder{records: records}).Ended(s.customer, rand.Text(), time.Now().UTC()) - s.Require().NoError(records.Flush(s.bounded())) - - // One budget in all: once a write ran out of retries, the next is tried once. - s.Less(time.Since(start), recordRetryFor*3/2, "the writer retried each write for a budget of its own") + // Bounded well past one retry budget, so a slow runner is not read as a hang. + ctx, cancel := context.WithTimeout(s.ctx, 3*recordRetryFor) + defer cancel() + s.Require().NoError(records.Flush(ctx)) + + // The first end is retried until its budget is all but spent, the last wait being at + // most recordRetryMost; tried once, it would be refused within milliseconds. Once it ran + // out, the next is tried once: one budget in all. + took := time.Since(start) + s.GreaterOrEqual(took, recordRetryFor-recordRetryMost, "the session end was not tried again") + s.Less(took, recordRetryFor*3/2, "the writer retried each write for a budget of its own") s.InDelta(sessionsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)), 0, "the session end that was never stored is not counted") s.InDelta(callsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)), 0, diff --git a/acceleration/internal/session/records.go b/acceleration/internal/session/records.go index 1c6ea490c8..7f2866228f 100644 --- a/acceleration/internal/session/records.go +++ b/acceleration/internal/session/records.go @@ -312,6 +312,13 @@ func (r *sessionRecorder) queueWrite(write recordWrite) { case r.queue <- write: default: r.dropped.Add(1) + // An end dropped here leaves its row open, as one the store refused does. + switch { + case write.closed != "": + recordsLost.WithLabelValues(lostSessionEnd).Inc() + case write.callEnded != "": + recordsLost.WithLabelValues(lostCallEnd).Inc() + } } } @@ -532,26 +539,29 @@ func (r *sessionRecorder) writeItems(items []store.AgentResponseItem) { } return } - // The batch holds the items of every session, so one whose session or response row was - // never written would fail all of them: each session's are written on their own instead. - var sessions []string - bySession := map[string][]store.AgentResponseItem{} + // The batch holds the items of every turn, and an item's key is its response, so one + // whose response row was never written would fail all of them: each turn's are written + // on their own instead. A batch of one turn already had its answer. + var responses []string + byResponse := map[string][]store.AgentResponseItem{} for _, item := range batch { - if _, seen := bySession[item.SessionID]; !seen { - sessions = append(sessions, item.SessionID) + if _, seen := byResponse[item.ResponseID]; !seen { + responses = append(responses, item.ResponseID) } - bySession[item.SessionID] = append(bySession[item.SessionID], item) + byResponse[item.ResponseID] = append(byResponse[item.ResponseID], item) } - for _, session := range sessions { - own := bySession[session] - err := r.attempt(func(ctx context.Context) error { return r.store.ResponseItems.InsertMany(ctx, own) }) + for _, response := range responses { + own := byResponse[response] + if len(responses) > 1 { + err = r.attempt(func(ctx context.Context) error { return r.store.ResponseItems.InsertMany(ctx, own) }) + } switch { case store.IsForeignKeyViolation(err): recordsLost.WithLabelValues(lostItems).Add(float64(len(own))) - r.logger.Warn("dropped what a turn did: its session or response was never recorded", - "session", session, "items", len(own)) + r.logger.Warn("dropped what a turn did: its response was never recorded", + "session", own[0].SessionID, "response", response, "items", len(own)) case err != nil: - r.logger.Error("could not record what a turn did", "session", session, "error", err, "items", len(own)) + r.logger.Error("could not record what a turn did", "response", response, "error", err, "items", len(own)) } } } @@ -569,7 +579,11 @@ func (r *sessionRecorder) attempt(do func(context.Context) error) error { err := do(ctx) cancel() if err == nil || !store.Transient(err) { - r.failing = false + // Only an answer from the database says it is back: a write refused before it + // was sent says nothing either way. + if err == nil || store.Answered(err) { + r.failing = false + } return err } if r.failing || time.Until(deadline) < wait { diff --git a/acceleration/internal/store/postgres.go b/acceleration/internal/store/postgres.go index 990f36ca58..99781881a6 100644 --- a/acceleration/internal/store/postgres.go +++ b/acceleration/internal/store/postgres.go @@ -34,15 +34,25 @@ func IsForeignKeyViolation(err error) bool { return isViolation(err, foreignKeyViolation) } +// Answered reports whether err is Postgres answering a statement, rather than a failure +// before the statement reached it. +func Answered(err error) bool { + var answer pgdriver.Error + return errors.As(err, &answer) +} + // Transient reports whether err is a failure that may pass if the same statement is sent -// again: the connection dropped or was refused, the statement timed out, the server is -// shutting down or full, or Postgres gave up on a serialization or a deadlock. A closed -// pool, a violated constraint and a bad statement are not. +// again: the connection dropped or was refused, the statement timed out on either side, the +// server is shutting down or full, a write reached a primary a failover demoted (read-only +// transaction), or Postgres gave up on a serialization or a deadlock. A closed pool, a +// violated constraint and a bad statement are not. func Transient(err error) bool { var refused pgdriver.Error if errors.As(err, &refused) { switch code := refused.Field('C'); code { - case "40001", "40P01", "53300", "57P01", "57P02", "57P03": + // 57014 is a statement cancelled by statement_timeout, or by the driver once the + // context ran out: the same wait as the context.DeadlineExceeded below. + case "25006", "40001", "40P01", "53300", "57014", "57P01", "57P02", "57P03": return true default: return strings.HasPrefix(code, "08") From 12d31fdb38236f838cdb1d54a69f77bc0e6986b0 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 13:35:35 +0000 Subject: [PATCH 3/6] fixup! fix(session): items fall back per turn, and a read-only or cancelled write is retried --- CHANGELOG.md | 2 +- acceleration/internal/session/records.go | 8 ++-- acceleration/internal/store/postgres.go | 7 --- acceleration/internal/store/postgres_test.go | 47 ++++++++++++++++++++ 4 files changed, 52 insertions(+), 12 deletions(-) create mode 100644 acceleration/internal/store/postgres_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a43e8f7707..2916770511 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -927,7 +927,7 @@ A request row's cost is added to a grant it names only when the grant belongs to ### A dropped database connection no longer loses a conversation's record -The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout on either side, a server shutting down, a write reaching a primary a failover made read-only, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a turn that was never stored no longer stop the items of other turns written in the same batch, in the same session or another. A session or call end that still cannot be stored, or that the full queue dropped, is counted in `router_session_records_lost_total{write}`, as are dropped items. +The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout on either side, a server shutting down, a write reaching a primary a failover made read-only, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a turn that was never stored no longer stop the items of other turns written in the same batch, in the same session or another. A session or call end that still cannot be stored, or that the full queue dropped, is counted in `router_session_records_lost_total{write}`, as are items dropped because their turn was never stored. ### A customer can no longer list or speak in another customer's cloned voice diff --git a/acceleration/internal/session/records.go b/acceleration/internal/session/records.go index 7f2866228f..d33a29e0bf 100644 --- a/acceleration/internal/session/records.go +++ b/acceleration/internal/session/records.go @@ -561,7 +561,8 @@ func (r *sessionRecorder) writeItems(items []store.AgentResponseItem) { r.logger.Warn("dropped what a turn did: its response was never recorded", "session", own[0].SessionID, "response", response, "items", len(own)) case err != nil: - r.logger.Error("could not record what a turn did", "response", response, "error", err, "items", len(own)) + r.logger.Error("could not record what a turn did", "session", own[0].SessionID, "response", response, + "error", err, "items", len(own)) } } } @@ -579,9 +580,8 @@ func (r *sessionRecorder) attempt(do func(context.Context) error) error { err := do(ctx) cancel() if err == nil || !store.Transient(err) { - // Only an answer from the database says it is back: a write refused before it - // was sent says nothing either way. - if err == nil || store.Answered(err) { + // Only a write that succeeded says the database is back. + if err == nil { r.failing = false } return err diff --git a/acceleration/internal/store/postgres.go b/acceleration/internal/store/postgres.go index 99781881a6..b8f11220e8 100644 --- a/acceleration/internal/store/postgres.go +++ b/acceleration/internal/store/postgres.go @@ -34,13 +34,6 @@ func IsForeignKeyViolation(err error) bool { return isViolation(err, foreignKeyViolation) } -// Answered reports whether err is Postgres answering a statement, rather than a failure -// before the statement reached it. -func Answered(err error) bool { - var answer pgdriver.Error - return errors.As(err, &answer) -} - // Transient reports whether err is a failure that may pass if the same statement is sent // again: the connection dropped or was refused, the statement timed out on either side, the // server is shutting down or full, a write reached a primary a failover demoted (read-only diff --git a/acceleration/internal/store/postgres_test.go b/acceleration/internal/store/postgres_test.go new file mode 100644 index 0000000000..43b258e18f --- /dev/null +++ b/acceleration/internal/store/postgres_test.go @@ -0,0 +1,47 @@ +//go:build integration + +package store + +import ( + "crypto/rand" + "strings" +) + +func (s *StoreSuite) TestAWriteToADemotedPrimaryIsTransient() { + conn, err := s.store.GlobalDB().Conn(s.ctx) + s.Require().NoError(err) + // Back in the pool read-only, the connection would refuse every later test's writes. + defer func() { + _, err := conn.ExecContext(s.ctx, "RESET ALL") + s.NoError(err) + s.NoError(conn.Close()) + }() + table := "transient_" + strings.ToLower(rand.Text()) + _, err = conn.ExecContext(s.ctx, "CREATE TABLE "+table+" (x int)") + s.Require().NoError(err) + defer func() { + _, err := s.store.GlobalDB().ExecContext(s.ctx, "DROP TABLE "+table) + s.NoError(err) + }() + + // A primary a failover demoted answers every write as a read-only transaction does. + _, err = conn.ExecContext(s.ctx, "SET default_transaction_read_only = on") + s.Require().NoError(err) + _, err = conn.ExecContext(s.ctx, "INSERT INTO "+table+" VALUES (1)") + s.Require().Error(err) + s.True(Transient(err), "a write refused as read-only is not retried: %v", err) +} + +func (s *StoreSuite) TestAStatementCutOffByStatementTimeoutIsTransient() { + conn, err := s.store.GlobalDB().Conn(s.ctx) + s.Require().NoError(err) + // The driver drops a connection whose statement was cancelled, so no later test gets its + // timeout, and Close finds it already closed. + defer func() { _ = conn.Close() }() + + _, err = conn.ExecContext(s.ctx, "SET statement_timeout = 1") + s.Require().NoError(err) + _, err = conn.ExecContext(s.ctx, "SELECT pg_sleep(1)") + s.Require().Error(err) + s.True(Transient(err), "a statement the server timed out is not retried: %v", err) +} From f62194516acd039ce1638af8015f9aebb178be46 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 13:55:01 +0000 Subject: [PATCH 4/6] chore: drop the CHANGELOG entry; pull requests no longer edit it --- CHANGELOG.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2916770511..cb26da99e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -925,10 +925,6 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env A request row's cost is added to a grant it names only when the grant belongs to the row's organization or to its app's (the organization the app is in, or the app itself for an app in none), both as the row is written and when the grant uses are reconciled. A grant scoped to an app, or to its key or user, counts only that app's rows. A use refused because the grant is not the row's is counted on `/metrics` as `router_usage_grant_uses_refused_total`. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. -### A dropped database connection no longer loses a conversation's record - -The session recorder now tries a write again, for up to 10 seconds and in queue order, when it fails for a reason that can pass: a dropped or refused connection, a timeout on either side, a server shutting down, a write reaching a primary a failover made read-only, or a serialization failure or deadlock. Before, one such failure lost the session or turn row and with it every later row of the conversation. Items of a turn that was never stored no longer stop the items of other turns written in the same batch, in the same session or another. A session or call end that still cannot be stored, or that the full queue dropped, is counted in `router_session_records_lost_total{write}`, as are items dropped because their turn was never stored. - ### A customer can no longer list or speak in another customer's cloned voice Clones made through `/v1/agents/voices` sit in the deployment's shared provider account, which lists them all as its own. A voice id that another customer's voice was prepared as is now refused, whether it is the session's voice or the `voice_id` of TTS overwrites. The voice library lists only the caller's own clones besides the provider's published voices, previews another customer's clone as not found, and no longer suggests one as the closest voice. From 5c5d4037abce1fa17df75e90666c48aeaac2f6b4 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 16:41:41 +0000 Subject: [PATCH 5/6] test(session): pin every write's retry, the try-once mode and the lost counts Each write kind is cut mid-statement by a terminated backend and must still be stored, a reopen's tools included. A proxy outage longer than a budget, then a write that gets through, must end the try-once mode; a write refused before it reached the database must not. Two items of a missing turn count as two, and an end a full queue drops is counted. store.Transient is tested against a fake server's SQLSTATEs, a silent server, a closed pool and local errors; it now retries a failed dial, read or write and a timeout, not every errno, and its 57014 comment says what sends one. --- .../internal/session/record_flush_test.go | 340 +++++++++++++++++- acceleration/internal/store/postgres.go | 23 +- .../internal/store/postgres_unit_test.go | 144 ++++++++ 3 files changed, 491 insertions(+), 16 deletions(-) create mode 100644 acceleration/internal/store/postgres_unit_test.go diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index b207a7e77c..945ef43222 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -5,10 +5,14 @@ package session import ( "context" "crypto/rand" + "io" "log/slog" + "net" + "net/url" "os" "strings" "sync" + "sync/atomic" "testing" "time" @@ -405,17 +409,21 @@ func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopAnotherSes s.records.Responding(response) lost := testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)) - // Back to back, so both go in one batch. + // Back to back, so all go in one batch: the missing turn has two items. + missing := rand.Text() s.records.Item(store.AgentResponseItem{ResponseID: response.ID, Ordinal: 0, SessionID: kept.ID, Kind: store.ItemSaid, Text: "It ships today.", At: time.Now().UTC()}) - s.records.Item(store.AgentResponseItem{ResponseID: rand.Text(), Ordinal: 0, SessionID: orphaned.ID, + s.records.Item(store.AgentResponseItem{ResponseID: missing, Ordinal: 0, SessionID: orphaned.ID, Kind: store.ItemSaid, Text: "Thanks.", At: time.Now().UTC()}) + s.records.Item(store.AgentResponseItem{ResponseID: missing, Ordinal: 1, SessionID: orphaned.ID, + Kind: store.ItemSaid, Text: "You're welcome.", At: time.Now().UTC()}) s.Require().NoError(s.records.Flush(s.bounded())) items, err := s.store.ResponseItems.Select(s.ctx, s.customer, kept.ID, store.ItemFilter{ResponseID: response.ID, Limit: 10}) s.Require().NoError(err) s.Len(items, 1, "the item of a session whose turn is stored was lost with the other session's") - s.InDelta(lost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)), 0, "the dropped item is not counted") + s.InDelta(lost+2, testutil.ToFloat64(recordsLost.WithLabelValues(lostItems)), 0, + "each dropped item is not counted, one by one") } func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopItsSessionsStoredTurn() { @@ -449,6 +457,8 @@ func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRun start := time.Now() records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) + // Refused before it reaches the database, which says nothing about whether it is back. + records.Closed("", rand.Text(), time.Now().UTC(), TimeoutHangup) (&callRecorder{records: records}).Ended(s.customer, rand.Text(), time.Now().UTC()) // Bounded well past one retry budget, so a slow runner is not read as a hang. ctx, cancel := context.WithTimeout(s.ctx, 3*recordRetryFor) @@ -461,12 +471,332 @@ func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRun took := time.Since(start) s.GreaterOrEqual(took, recordRetryFor-recordRetryMost, "the session end was not tried again") s.Less(took, recordRetryFor*3/2, "the writer retried each write for a budget of its own") - s.InDelta(sessionsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)), 0, - "the session end that was never stored is not counted") + s.InDelta(sessionsLost+2, testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)), 0, + "the session ends that were never stored are not counted") s.InDelta(callsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)), 0, "the call end that was never stored is not counted") } +// cutRows are the rows a write of every kind changes, stored before it is queued. +type cutRows struct { + session store.AgentSession + response store.AgentResponse + call store.Call +} + +func (s *RecordFlushSuite) TestEveryWriteCutOffByADroppedConnectionIsStored() { + tool := []store.ToolDefinition{{Name: "track_order", Description: "Where an order is."}} + for _, write := range []struct { + name string + // held are the tables whose rows are locked while the write is queued: all four + // unless it names some. + held []string + // prepare, when set, readies the rows before they are held. + prepare func(cutRows) + queue func(*sessionRecorder, cutRows) + check func(cutRows) + }{{ + name: "a reopened session's tools", + held: []string{"agent_session_tools"}, + queue: func(r *sessionRecorder, rows cutRows) { + rows.session.Title = "Reopened" + r.Opened(rows.session, tool) + }, + check: func(rows cutRows) { s.Equal(tool, s.toolsOf(rows.session.ID)) }, + }, { + name: "the tools a session is offered", + queue: func(r *sessionRecorder, rows cutRows) { r.Offered(s.customer, rows.session.ID, tool) }, + check: func(rows cutRows) { s.Equal(tool, s.toolsOf(rows.session.ID)) }, + }, { + name: "a session ending", + queue: func(r *sessionRecorder, rows cutRows) { + r.Closed(s.customer, rows.session.ID, time.Now().UTC(), TimeoutHangup) + }, + check: func(rows cutRows) { s.NotNil(s.sessionOf(rows.session.ID).ClosedAt) }, + }, { + name: "a turn starting", + queue: func(r *sessionRecorder, rows cutRows) { + r.Responding(store.AgentResponse{ID: "next-" + rows.response.ID, SessionID: rows.session.ID, CustomerID: s.customer}) + }, + check: func(rows cutRows) { + _, err := s.store.Responses.Get(s.ctx, s.customer, rows.session.ID, "next-"+rows.response.ID) + s.NoError(err) + }, + }, { + name: "a turn ending", + queue: func(r *sessionRecorder, rows cutRows) { + r.Responded(s.customer, rows.response.ID, store.ResponseCompleted, "", time.Now().UTC()) + }, + check: func(rows cutRows) { + got, err := s.store.Responses.Get(s.ctx, s.customer, rows.session.ID, rows.response.ID) + s.Require().NoError(err) + s.NotNil(got.FinishedAt) + }, + }, { + name: "what a turn did", + queue: func(r *sessionRecorder, rows cutRows) { + r.Item(store.AgentResponseItem{ResponseID: rows.response.ID, SessionID: rows.session.ID, + Kind: store.ItemSaid, Text: "It ships today.", At: time.Now().UTC()}) + }, + check: func(rows cutRows) { + items, err := s.store.ResponseItems.Select(s.ctx, s.customer, rows.session.ID, + store.ItemFilter{ResponseID: rows.response.ID, Limit: 10}) + s.Require().NoError(err) + s.Len(items, 1) + }, + }, { + name: "a title", + queue: func(r *sessionRecorder, rows cutRows) { + r.Described(s.customer, rows.session.ID, "Where an order went", "", nil) + }, + check: func(rows cutRows) { s.Equal("Where an order went", s.sessionOf(rows.session.ID).Title) }, + }, { + name: "a connection a login chose", + queue: func(r *sessionRecorder, rows cutRows) { r.Chose(s.customer, rows.session.ID, "github", "connection-1") }, + check: func(rows cutRows) { + s.Equal([]store.SessionConnectorSelection{{Name: "github", ConnectionID: "connection-1"}}, + s.sessionOf(rows.session.ID).ConnectorSelections) + }, + }, { + name: "a tool timeout", + queue: func(r *sessionRecorder, rows cutRows) { + r.ToolTimeout(s.customer, rows.session.ID, rows.session.CallerKind, 30_000) + }, + check: func(rows cutRows) { s.Equal(30_000, s.sessionOf(rows.session.ID).ToolTimeoutMs) }, + }, { + name: "video seen", + queue: func(r *sessionRecorder, rows cutRows) { r.SawVideo(s.customer, rows.session.ID) }, + check: func(rows cutRows) { s.Equal(store.ModalityVideo, s.sessionOf(rows.session.ID).Modality) }, + }, { + name: "voice started", + queue: func(r *sessionRecorder, rows cutRows) { r.Voiced(s.customer, rows.session.ID) }, + check: func(rows cutRows) { s.Equal(store.ModalityVoice, s.sessionOf(rows.session.ID).Modality) }, + }, { + name: "a call starting again", + prepare: func(rows cutRows) { + s.Require().NoError(s.store.Calls.Finish(s.ctx, s.customer, rows.call.ID, time.Now().UTC())) + }, + queue: func(r *sessionRecorder, rows cutRows) { (&callRecorder{records: r}).Started(rows.call) }, + check: func(rows cutRows) { s.Nil(s.callOf(rows.call.ID).EndedAt) }, + }, { + name: "a call changing models", + queue: func(r *sessionRecorder, rows cutRows) { + rows.call.STT = "deepgram/nova-3" + (&callRecorder{records: r}).Changed(rows.call) + }, + check: func(rows cutRows) { s.Equal("deepgram/nova-3", s.callOf(rows.call.ID).STT) }, + }, { + name: "a call ending", + queue: func(r *sessionRecorder, rows cutRows) { + (&callRecorder{records: r}).Ended(s.customer, rows.call.ID, time.Now().UTC()) + }, + check: func(rows cutRows) { s.NotNil(s.callOf(rows.call.ID).EndedAt) }, + }} { + s.Run(write.name, func() { + rows := s.cutRows() + if write.prepare != nil { + write.prepare(rows) + } + held := write.held + if held == nil { + held = []string{"agent_sessions", "agent_session_tools", "agent_responses", "calls"} + } + release := s.holdRows(rows, held) + records := newSessionRecorder(s.store, slog.New(slog.DiscardHandler)) + defer records.Close() + write.queue(records, rows) + + s.cutWaitingWriter() + release() + s.Require().NoError(records.Flush(s.bounded())) + write.check(rows) + }) + } +} + +func (s *RecordFlushSuite) TestAnEndQueuedWhileTheDatabaseIsBrieflyDownAfterAnOutageIsStored() { + proxy := s.proxy() + db, err := store.Open(proxy.dsn) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(db.Close()) }) + records := s.recorderLogging(db, &syncBuffer{}) + row := s.row() + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &row)) + long := func() context.Context { + ctx, cancel := context.WithTimeout(s.ctx, 3*recordRetryFor) + s.T().Cleanup(cancel) + return ctx + } + + // An outage longer than a budget: the writer gives up and tries the next write once. + proxy.setDown(true) + records.Voiced(s.customer, row.ID) + s.Require().NoError(records.Flush(long())) + // The database is back, and a write gets through. + proxy.setDown(false) + records.SawVideo(s.customer, row.ID) + s.Require().NoError(records.Flush(s.bounded())) + s.Equal(store.ModalityVideo, s.sessionOf(row.ID).Modality, "a write after the outage is not stored") + + // A blip: down when the end is first tried, up again for its retry. + proxy.setDown(true) + refused := proxy.refused.Load() + records.Closed(s.customer, row.ID, time.Now().UTC(), TimeoutHangup) + s.Require().Eventually(func() bool { return proxy.refused.Load() > refused }, settleFor, time.Millisecond, + "the end was never tried while the database was down") + proxy.setDown(false) + s.Require().NoError(records.Flush(s.bounded())) + s.NotNil(s.sessionOf(row.ID).ClosedAt, "the writer still tried each write once after one got through") +} + +func (s *RecordFlushSuite) TestEndsAFullQueueDropsAreCounted() { + release := s.holdWriter() + defer release() + for range recordQueueSize { + s.records.Voiced(s.customer, rand.Text()) + } + sessionsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)) + callsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)) + + s.records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) + (&callRecorder{records: s.records}).Ended(s.customer, rand.Text(), time.Now().UTC()) + + s.Equal(int64(2), s.records.Dropped(), "the queue was not full") + s.InDelta(sessionsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)), 0, + "a session end the full queue dropped is not counted") + s.InDelta(callsLost+1, testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)), 0, + "a call end the full queue dropped is not counted") +} + +// cutRows stores a running text session offered no tools yet, a turn of it and a call of it. +func (s *RecordFlushSuite) cutRows() cutRows { + rows := cutRows{session: s.row()} + rows.session.CallerKind = "server" + rows.session.Modality = store.ModalityText + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &rows.session)) + s.Require().NoError(s.store.SessionTools.Upsert(s.ctx, s.customer, rows.session.ID, nil)) + rows.response = store.AgentResponse{ID: rand.Text(), SessionID: rows.session.ID, CustomerID: s.customer} + s.Require().NoError(s.store.Responses.Insert(s.ctx, &rows.response)) + rows.call = store.Call{ID: rand.Text(), CustomerID: s.customer, SessionID: rows.session.ID} + s.Require().NoError(s.store.Calls.Start(s.ctx, &rows.call)) + return rows +} + +// holdRows locks the rows of tables in another transaction, until the returned release +// rolls it back. +func (s *RecordFlushSuite) holdRows(rows cutRows, tables []string) (release func()) { + tx, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + release = sync.OnceFunc(func() { s.NoError(tx.Rollback()) }) + s.T().Cleanup(release) + keys := map[string]string{"agent_sessions": "id", "agent_session_tools": "session_id", "agent_responses": "id", "calls": "id"} + ids := map[string]string{"agent_sessions": rows.session.ID, "agent_session_tools": rows.session.ID, + "agent_responses": rows.response.ID, "calls": rows.call.ID} + for _, table := range tables { + var one int + s.Require().NoError(tx.QueryRowContext(s.ctx, "SELECT 1 FROM "+table+" WHERE "+keys[table]+" = ? FOR UPDATE", + ids[table]).Scan(&one), table) + } + return release +} + +// cutWaitingWriter terminates the backend waiting on a lock, as a failover cuts the +// writer's connection mid-statement. +func (s *RecordFlushSuite) cutWaitingWriter() { + var writer int + s.Require().Eventually(func() bool { + err := s.store.GlobalDB().QueryRowContext(s.ctx, `SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' AND pid <> pg_backend_pid()`).Scan(&writer) + return err == nil + }, settleFor, 5*time.Millisecond, "the writer never waited on the held rows") + _, err := s.store.GlobalDB().ExecContext(s.ctx, "SELECT pg_terminate_backend(?)", writer) + s.Require().NoError(err) +} + +func (s *RecordFlushSuite) sessionOf(id string) store.AgentSession { + got, err := s.store.Sessions.Get(s.ctx, s.customer, id) + s.Require().NoError(err) + return got +} + +func (s *RecordFlushSuite) toolsOf(id string) []store.ToolDefinition { + got, err := s.store.SessionTools.Get(s.ctx, id) + s.Require().NoError(err) + return got +} + +func (s *RecordFlushSuite) callOf(id string) store.Call { + got, err := s.store.Calls.Get(s.ctx, s.customer, id) + s.Require().NoError(err) + return got +} + +// flakyProxy passes connections through to the suite's Postgres. While down it cuts the +// connections it holds and closes each new one at once, counting them in refused. +type flakyProxy struct { + dsn string + target string + refused atomic.Int64 + + mu sync.Mutex + down bool + pipes []net.Conn +} + +func (s *RecordFlushSuite) proxy() *flakyProxy { + address, err := url.Parse(s.dsn) + s.Require().NoError(err) + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + proxy := &flakyProxy{target: address.Host} + address.Host = listener.Addr().String() + proxy.dsn = address.String() + var serving sync.WaitGroup + s.T().Cleanup(func() { + s.NoError(listener.Close()) + proxy.setDown(true) + serving.Wait() + }) + serving.Go(func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + proxy.mu.Lock() + if proxy.down { + proxy.mu.Unlock() + proxy.refused.Add(1) + _ = conn.Close() + continue + } + upstream, err := net.Dial("tcp", proxy.target) + if err != nil { + proxy.mu.Unlock() + _ = conn.Close() + continue + } + proxy.pipes = append(proxy.pipes, conn, upstream) + proxy.mu.Unlock() + serving.Go(func() { _, _ = io.Copy(upstream, conn); _ = upstream.Close() }) + serving.Go(func() { _, _ = io.Copy(conn, upstream); _ = conn.Close() }) + } + }) + return proxy +} + +func (p *flakyProxy) setDown(down bool) { + p.mu.Lock() + defer p.mu.Unlock() + p.down = down + if down { + for _, conn := range p.pipes { + _ = conn.Close() + } + p.pipes = nil + } +} + // recorderLogging is a writer over db that logs everything, even debug lines, into logged. func (s *RecordFlushSuite) recorderLogging(db *store.Store, logged *syncBuffer) *sessionRecorder { records := newSessionRecorder(db, slog.New(slog.NewTextHandler(logged, &slog.HandlerOptions{Level: slog.LevelDebug}))) diff --git a/acceleration/internal/store/postgres.go b/acceleration/internal/store/postgres.go index b8f11220e8..fc6d9bcf49 100644 --- a/acceleration/internal/store/postgres.go +++ b/acceleration/internal/store/postgres.go @@ -1,7 +1,6 @@ package store import ( - "context" "database/sql" "database/sql/driver" "errors" @@ -9,7 +8,6 @@ import ( "io" "net" "strings" - "syscall" "github.com/uptrace/bun/driver/pgdriver" @@ -35,26 +33,29 @@ func IsForeignKeyViolation(err error) bool { } // Transient reports whether err is a failure that may pass if the same statement is sent -// again: the connection dropped or was refused, the statement timed out on either side, the -// server is shutting down or full, a write reached a primary a failover demoted (read-only -// transaction), or Postgres gave up on a serialization or a deadlock. A closed pool, a -// violated constraint and a bad statement are not. +// again: the connection dropped or was refused, the statement or the context ran out of +// time, the server is shutting down or full, a write reached a primary a failover demoted +// (read-only transaction), or Postgres gave up on a serialization or a deadlock. A closed +// pool, a violated constraint, a bad statement and a local failure such as a missing file +// are not. func Transient(err error) bool { var refused pgdriver.Error if errors.As(err, &refused) { switch code := refused.Field('C'); code { - // 57014 is a statement cancelled by statement_timeout, or by the driver once the - // context ran out: the same wait as the context.DeadlineExceeded below. + // 57014 is a statement statement_timeout or an operator's pg_cancel_backend stopped. + // The driver sends no cancel of its own: a context that ran out is a net timeout. case "25006", "40001", "40P01", "53300", "57014", "57P01", "57P02", "57P03": return true default: return strings.HasPrefix(code, "08") } } + // A dial, read or write that failed is an *net.OpError; a deadline, the context's + // included, is a net.Error that timed out. + var op *net.OpError var network net.Error - return errors.As(err, &network) || errors.Is(err, context.DeadlineExceeded) || - errors.Is(err, driver.ErrBadConn) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || - errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) + return errors.As(err, &op) || errors.As(err, &network) && network.Timeout() || + errors.Is(err, driver.ErrBadConn) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) } // oneRow turns an update or delete that matched nothing into missing. diff --git a/acceleration/internal/store/postgres_unit_test.go b/acceleration/internal/store/postgres_unit_test.go new file mode 100644 index 0000000000..de71581faa --- /dev/null +++ b/acceleration/internal/store/postgres_unit_test.go @@ -0,0 +1,144 @@ +package store + +import ( + "context" + "database/sql" + "encoding/binary" + "errors" + "io" + "net" + "os" + "path/filepath" + "sync" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/uptrace/bun/driver/pgdriver" +) + +func TestTransientTellsAFailureAnotherTryCanPassFromOneItCannot(t *testing.T) { + for code, transient := range map[string]bool{ + "25006": true, // read-only transaction: a primary a failover demoted + "40001": true, // serialization failure + "40P01": true, // deadlock + "53300": true, // too many connections + "57014": true, // statement_timeout or pg_cancel_backend + "57P01": true, // admin shutdown + "57P02": true, // crash shutdown + "57P03": true, // cannot connect now + "08006": true, // connection failure + "08P01": true, // protocol violation + "23503": false, // foreign key violation + "42P01": false, // undefined table + "28P01": false, // invalid password + "55P03": false, // lock not available + } { + t.Run(code, func(t *testing.T) { + err := pingPostgres(t, refusingServer(t, code), time.Second) + var answer pgdriver.Error + require.ErrorAs(t, err, &answer) + require.Equal(t, code, answer.Field('C')) + require.Equal(t, transient, Transient(err), "%v", err) + }) + } + + t.Run("a server that never answers", func(t *testing.T) { + err := pingPostgres(t, silentServer(t), 200*time.Millisecond) + require.Error(t, err) + require.True(t, Transient(err), "%v", err) + }) + t.Run("a closed pool", func(t *testing.T) { + db := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN("postgres://postgres@127.0.0.1:1/router?sslmode=disable"))) + require.NoError(t, db.Close()) + err := db.PingContext(context.Background()) + require.Error(t, err) + require.False(t, Transient(err), "%v", err) + }) + t.Run("a failure of the caller's own", func(t *testing.T) { + require.False(t, Transient(errors.New("store: a customer is required"))) + require.False(t, Transient(context.Canceled)) + _, missing := os.Open(filepath.Join(t.TempDir(), "missing")) + require.ErrorIs(t, missing, syscall.ENOENT) + require.False(t, Transient(missing), "%v", missing) + require.False(t, Transient(syscall.EACCES)) + }) +} + +// pingPostgres is a pool's first statement against the server at addr, given wait. +func pingPostgres(t *testing.T, addr string, wait time.Duration) error { + db := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN("postgres://postgres@" + addr + "/router?sslmode=disable"))) + t.Cleanup(func() { require.NoError(t, db.Close()) }) + ctx, cancel := context.WithTimeout(context.Background(), wait) + defer cancel() + return db.PingContext(ctx) +} + +// refusingServer answers every startup message with a FATAL ErrorResponse carrying code. +func refusingServer(t *testing.T, code string) string { + return serve(t, func(conn net.Conn) { + if readStartup(conn) != nil { + return + } + var fields []byte + for _, field := range []struct { + kind byte + value string + }{{'S', "FATAL"}, {'V', "FATAL"}, {'C', code}, {'M', "refused"}} { + fields = append(append(append(fields, field.kind), field.value...), 0) + } + fields = append(fields, 0) + message := binary.BigEndian.AppendUint32([]byte{'E'}, uint32(4+len(fields))) + _, _ = conn.Write(append(message, fields...)) + }) +} + +// silentServer takes connections and never says a word. +func silentServer(t *testing.T) string { + return serve(t, func(conn net.Conn) { _, _ = io.Copy(io.Discard, conn) }) +} + +// serve runs answer on every connection to a local listener until the test ends. +func serve(t *testing.T, answer func(net.Conn)) string { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + var answering sync.WaitGroup + var mu sync.Mutex + var conns []net.Conn + t.Cleanup(func() { + _ = listener.Close() + mu.Lock() + for _, conn := range conns { + _ = conn.Close() + } + mu.Unlock() + answering.Wait() + }) + answering.Go(func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + mu.Lock() + conns = append(conns, conn) + mu.Unlock() + answering.Go(func() { + defer conn.Close() + answer(conn) + }) + } + }) + return listener.Addr().String() +} + +// readStartup reads the client's startup message: a length that counts itself, then the rest. +func readStartup(conn net.Conn) error { + var length [4]byte + if _, err := io.ReadFull(conn, length[:]); err != nil { + return err + } + _, err := io.CopyN(io.Discard, conn, int64(binary.BigEndian.Uint32(length[:]))-4) + return err +} From a1e9cead4145a7b08ded604e107c1dc93c63a649 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 17:48:21 +0000 Subject: [PATCH 6/6] test(store): pin Transient's dropped-connection, dial and deadline branches A wrapped driver.ErrBadConn, io.EOF, io.ErrUnexpectedEOF and context.DeadlineExceeded, and a dial to a closed port, are each retried; the 57014 comment reads as a sentence. --- acceleration/internal/store/postgres.go | 2 +- acceleration/internal/store/postgres_unit_test.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/store/postgres.go b/acceleration/internal/store/postgres.go index fc6d9bcf49..015d35a85c 100644 --- a/acceleration/internal/store/postgres.go +++ b/acceleration/internal/store/postgres.go @@ -42,7 +42,7 @@ func Transient(err error) bool { var refused pgdriver.Error if errors.As(err, &refused) { switch code := refused.Field('C'); code { - // 57014 is a statement statement_timeout or an operator's pg_cancel_backend stopped. + // 57014 is a statement that statement_timeout or an operator's pg_cancel_backend stopped. // The driver sends no cancel of its own: a context that ran out is a net timeout. case "25006", "40001", "40P01", "53300", "57014", "57P01", "57P02", "57P03": return true diff --git a/acceleration/internal/store/postgres_unit_test.go b/acceleration/internal/store/postgres_unit_test.go index de71581faa..a4e2643a8b 100644 --- a/acceleration/internal/store/postgres_unit_test.go +++ b/acceleration/internal/store/postgres_unit_test.go @@ -3,8 +3,10 @@ package store import ( "context" "database/sql" + "database/sql/driver" "encoding/binary" "errors" + "fmt" "io" "net" "os" @@ -49,6 +51,19 @@ func TestTransientTellsAFailureAnotherTryCanPassFromOneItCannot(t *testing.T) { require.Error(t, err) require.True(t, Transient(err), "%v", err) }) + // A context that ran out is what the pool answers a caller left waiting for a connection. + for _, cut := range []error{driver.ErrBadConn, io.EOF, io.ErrUnexpectedEOF, context.DeadlineExceeded} { + t.Run(cut.Error(), func(t *testing.T) { + err := fmt.Errorf("write: %w", cut) + require.True(t, Transient(err), "%v", err) + }) + } + t.Run("a port nobody listens on", func(t *testing.T) { + err := pingPostgres(t, "127.0.0.1:1", 2*time.Second) + var dial *net.OpError + require.ErrorAs(t, err, &dial) + require.True(t, Transient(err), "%v", err) + }) t.Run("a closed pool", func(t *testing.T) { db := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN("postgres://postgres@127.0.0.1:1/router?sslmode=disable"))) require.NoError(t, db.Close())