diff --git a/CHANGELOG.md b/CHANGELOG.md index c64ab679e0..438fdfbc49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -867,6 +867,10 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi `Folder.load`, and so `Agent.new(folder: "…")`, raise a `ConfigurationError` for a folder whose agent.yaml names `plugins:`, with an error that names the file and points to `connectors:`. An empty or null `plugins` still loads and sends nothing, as before. Folder sync no longer sends `plugins`, and the warning that plugins are deprecated is gone, as is the check that no name is under both `connectors` and `plugins`. Move each plugin to a `connectors:` entry (AI-2528). +### `POST /v1/phone/opt-outs` refuses a recipient it could never match + +A `recipient` that is neither an E.164 number nor, for channel `imessage` or `all`, an iMessage handle's email address is now refused with a 400 `validation_failed` instead of being stored. Such opt-outs never took effect: an opt-out is matched against the number or handle as written, and numbers are always E.164. `15551110000` and `(555) 111-0000` are refused; send `+15551110000`. + ## Bug Fixes ### A scheduled task whose turn is refused for money in an open conversation fails its run diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 2ed0fb593c..47033d10e6 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -4286,8 +4286,8 @@ components: channel: $ref: '#/components/schemas/OptOutChannel' recipient: - description: The number, in E.164. - maxLength: 20 + description: The number in E.164, or an iMessage handle's email address, for channel imessage or all. + maxLength: 254 minLength: 2 type: string source: @@ -7071,7 +7071,7 @@ components: id: type: string recipient: - description: The number, in E.164. + description: The number in E.164, or an iMessage handle's email address. type: string source: description: keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard. diff --git a/acceleration/internal/api/dlc.go b/acceleration/internal/api/dlc.go index 291b6c0d0f..c3a0165f22 100644 --- a/acceleration/internal/api/dlc.go +++ b/acceleration/internal/api/dlc.go @@ -6,6 +6,7 @@ import ( "errors" "io" "net/http" + "net/mail" "slices" "strings" "time" @@ -248,6 +249,9 @@ func (s *Server) createOptOut(ctx context.Context, request *createOptOutRequest) Channel: string(request.Body.Channel), Source: "api", } + if err := optOutRecipient(optOut.Recipient, optOut.Channel); err != nil { + return nil, err + } if request.Body.Source != nil { optOut.Source = *request.Body.Source } @@ -257,6 +261,27 @@ func (s *Server) createOptOut(ctx context.Context, request *createOptOutRequest) return &optOutResponse{Body: renderedOptOut(optOut)}, nil } +// errOptOutRecipient is a recipient an opt-out would never match: one is matched against the +// recipient of a text or call as it is written, a number in E.164 or, on iMessage, the email +// address of a handle (the Linq bridge writes such a STOP). +var errOptOutRecipient = APIError{Type: ErrorTypeInvalidRequest, Code: codeValidationFailed, + Message: "recipient must be a number in E.164, such as +15550001111, or for channel imessage or all an email address"} + +// optOutRecipient refuses a recipient channel could never be reached at. +func optOutRecipient(recipient, channel string) error { + if store.IsE164(recipient) { + return nil + } + if channel != dlc.IMessage && channel != store.OptOutAll { + return errOptOutRecipient + } + address, err := mail.ParseAddress(recipient) + if err != nil || address.Address != recipient { + return errOptOutRecipient + } + return nil +} + func (s *Server) revokeOptOut(ctx context.Context, request *revokeOptOutRequest) (*struct{}, error) { customerID, err := s.dlcCustomer(ctx) if err != nil { @@ -792,7 +817,7 @@ func (OptOutChannel) Schema(registry huma.Registry) *huma.Schema { // OptOut is somebody who asked not to be reached. type OptOut struct { Id string `json:"id"` - Recipient string `json:"recipient" doc:"The number, in E.164."` + Recipient string `json:"recipient" doc:"The number in E.164, or an iMessage handle's email address."` Channel OptOutChannel `json:"channel"` Source string `json:"source" doc:"keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard."` CreatedAt time.Time `json:"created_at"` @@ -813,7 +838,7 @@ type OptOutPage struct { // CreateOptOutRequest records an opt-out the app heard about another way. type CreateOptOutRequest struct { - Recipient string `json:"recipient" minLength:"2" maxLength:"20" doc:"The number, in E.164."` + Recipient string `json:"recipient" minLength:"2" maxLength:"254" doc:"The number in E.164, or an iMessage handle's email address, for channel imessage or all."` Channel OptOutChannel `json:"channel"` Source *string `json:"source,omitempty" enum:"api,dashboard" doc:"Omitted is api."` } diff --git a/acceleration/internal/api/dlc_test.go b/acceleration/internal/api/dlc_test.go index bfda0cf1f4..ac0004c5c0 100644 --- a/acceleration/internal/api/dlc_test.go +++ b/acceleration/internal/api/dlc_test.go @@ -921,6 +921,31 @@ func (s *DLCSuite) TestAUseCaseIsHiddenFromOtherApps() { }) } +func (s *DLCSuite) TestAnOptOutNotInE164IsRefused() { + for _, recipient := range []string{"15551110000", "+1 555 111 0000", "(555) 111-0000", "+0155511100", + "+15551110000x", "+1555111000012345", "ada@example.com"} { + status, body := s.serverClient.call(http.MethodPost, "/v1/phone/opt-outs", + CreateOptOutRequest{Recipient: recipient, Channel: OptOutChannel(dlc.SMS)}) + s.Equal(http.StatusBadRequest, status, "%q would never match a text sent", recipient) + s.Contains(string(body), `"code":"validation_failed"`, recipient) + } + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/phone/opt-outs", + CreateOptOutRequest{Recipient: "+15551110000", Channel: OptOutChannel(dlc.Voice)}, nil)) +} + +func (s *DLCSuite) TestAnIMessageHandlesAddressIsAnOptOutOnIMessageOnly() { + for _, channel := range []string{dlc.IMessage, store.OptOutAll} { + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/phone/opt-outs", + CreateOptOutRequest{Recipient: "ada@example.com", Channel: OptOutChannel(channel)}, nil), channel) + } + for _, recipient := range []string{"Ada ", "ada", "15551110000"} { + status, body := s.serverClient.call(http.MethodPost, "/v1/phone/opt-outs", + CreateOptOutRequest{Recipient: recipient, Channel: OptOutChannel(dlc.IMessage)}) + s.Equal(http.StatusBadRequest, status, recipient) + s.Contains(string(body), `"code":"validation_failed"`, recipient) + } +} + func (s *DLCSuite) TestADialToSomebodyWhoOptedOutIsRefused() { s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/phone/sandbox/recipients", SetSandboxRecipientsRequest{Recipients: []string{"+15551110000"}}, nil)) diff --git a/acceleration/internal/api/requestid_test.go b/acceleration/internal/api/requestid_test.go index 692a1f35da..7a866d976d 100644 --- a/acceleration/internal/api/requestid_test.go +++ b/acceleration/internal/api/requestid_test.go @@ -177,6 +177,86 @@ func TestACredentialTheKeyStoreCouldNotCheckIsAnsweredAsInternalNotAsAWrongKey(t require.Equal(t, http.StatusUnauthorized, ask().Code, "a key the store refused is still the caller's to fix") } +func TestACallerThatHangsUpWhileItsKeyIsCheckedIsNoFailure(t *testing.T) { + broken, err := store.Open("postgres://router_app:hunter2@127.0.0.1:1/agents_prod?sslmode=disable") + require.NoError(t, err) + t.Cleanup(func() { _ = broken.Close() }) + lookup := broken.APIKeys.Lookup(nil) + key, _, err := auth.NewCredential(auth.Live) + require.NoError(t, err) + logged := &bytes.Buffer{} + server, err := NewServer(Options{ + Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}}, + AuthMode: auth.Custom, + Auth: auth.Func(func(ctx context.Context, _ *http.Request) (auth.Principal, error) { + _, err := lookup(ctx, key) + return auth.Principal{}, err + }), + Logger: slog.New(slog.NewTextHandler(logged, nil)), + }) + require.NoError(t, err) + ctx, hangUp := context.WithCancel(context.Background()) + hangUp() + response := httptest.NewRecorder() + gone := map[string]string{"route": "/v1/agents/configs", "status": "4xx"} + answered := map[string]string{"route": "/v1/agents/configs", "status": "2xx"} + goneBefore, answeredBefore := sumOf(t, "router_http_requests_total", gone), sumOf(t, "router_http_requests_total", answered) + + server.Handler().ServeHTTP(response, httptest.NewRequestWithContext(ctx, http.MethodGet, "/v1/agents/configs", nil)) + + require.Equal(t, statusClientClosed, response.Code, response.Body.String()) + require.NotContains(t, logged.String(), "level=ERROR", "a caller hanging up is not an outage") + require.Equal(t, goneBefore+1, sumOf(t, "router_http_requests_total", gone), "a caller that gave up is counted") + require.Equal(t, answeredBefore, sumOf(t, "router_http_requests_total", answered), "nor as an answer") +} + +func TestAKeyStoreDownIsAFailureEvenIfTheCallerHasGone(t *testing.T) { + broken, err := store.Open("postgres://router_app:hunter2@127.0.0.1:1/agents_prod?sslmode=disable") + require.NoError(t, err) + t.Cleanup(func() { _ = broken.Close() }) + lookup := broken.APIKeys.Lookup(nil) + key, _, err := auth.NewCredential(auth.Live) + require.NoError(t, err) + logged := &bytes.Buffer{} + server, err := NewServer(Options{ + Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}}, + AuthMode: auth.Custom, + // The lookup fails on its own, as an unreachable store does, not for the caller leaving. + Auth: auth.Func(func(context.Context, *http.Request) (auth.Principal, error) { + _, err := lookup(context.Background(), key) + return auth.Principal{}, err + }), + Logger: slog.New(slog.NewTextHandler(logged, nil)), + }) + require.NoError(t, err) + ctx, hangUp := context.WithCancel(context.Background()) + hangUp() + + server.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(ctx, http.MethodGet, "/v1/agents/configs", nil)) + + require.Contains(t, logged.String(), "level=ERROR", "an outage is logged whoever is left to hear of it") + require.Contains(t, logged.String(), "127.0.0.1:1") +} + +func TestALookupCancelledWhileTheCallerWaitsIsStillAFailure(t *testing.T) { + logged := &bytes.Buffer{} + server, err := NewServer(Options{ + Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}}, + AuthMode: auth.Custom, + Auth: auth.Func(func(context.Context, *http.Request) (auth.Principal, error) { + return auth.Principal{}, stack.Wrap(fmt.Errorf("store: get api key: %w", context.Canceled)) + }), + Logger: slog.New(slog.NewTextHandler(logged, nil)), + }) + require.NoError(t, err) + response := httptest.NewRecorder() + + server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/v1/agents/configs", nil)) + + require.Equal(t, http.StatusInternalServerError, response.Code, "the caller is still there to be told") + require.Contains(t, logged.String(), "level=ERROR") +} + func TestAServerErrorNeverWrappedIsLoggedWithTheStackItReachedHumaOn(t *testing.T) { handler, logged := served(t, func() error { return errors.New("never wrapped") }) diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 14f7209a6b..1bf84797cf 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -1345,6 +1345,10 @@ var errServerSideOnly = APIError{ // is how a backend says which of its users it is opening a session for, so that the user's // own device can reach that session afterwards; what keeps the limit off it is that // withQuota looks at whether the caller is server-side rather than at whether there is one. +// statusClientClosed is what a request whose caller hung up before it was answered is counted +// as, nginx's 499: no caller reads it. +const statusClientClosed = 499 + func (s *Server) withCustomer(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Stream is not a customer, and a delivery is authenticated by its signature. Who a @@ -1374,6 +1378,15 @@ func (s *Server) withCustomer(next http.Handler) http.Handler { Message: strings.TrimPrefix(err.Error(), "auth: ")}) return } + // A caller that hung up while its credential was checked is no failure of the router's, + // and nobody is left to answer. The status is for withMetrics, which counts and times it + // as a 4xx: callers giving up on a stalled key store still show there. + if errors.Is(err, context.Canceled) && r.Context().Err() != nil { + s.logger.Debug("the caller left before its credential was checked", "method", r.Method, + "path", loggedPath(s.mux, r), "request_id", RequestIDFrom(r.Context())) + w.WriteHeader(statusClientClosed) + return + } // A credential that could not be checked (the key store down, a key that would not // unseal) is the router's failure, not a wrong key. It is logged here: withRequestLog // runs after this. diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index ce3abf9d8e..d8556b4526 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -1051,9 +1051,11 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er m.records.Closed(spec.CustomerID, created.id, row.OpenedAt, time.Now().UTC(), created.kept()) }) if spec.Reopened.IsZero() { - m.records.Opened(row, toolRows(created)) + m.records.Opened(row, toolRows(created), func() { m.idTaken(created) }) } else { - m.records.CarriedOn(row, toolRows(created)) + // A carry-on skips the check that the id is free, so another customer's row written + // on another shard meanwhile refuses it too. + m.records.CarriedOn(row, toolRows(created), func() { m.idTaken(created) }) } created.startRecording() } @@ -1075,7 +1077,8 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er m.calls.Ended(spec.CustomerID, id, time.Now().UTC()) // The review runs on a model rather than in this closer, so it is started // here and lands on the row whenever it comes back. - if !spec.NoReview { + // A session whose row the store refused (idTaken) has no call row to land on. + if !spec.NoReview && !created.idTaken.Load() { m.reviews.Review(row(created), spec.Attribution, spec.Region, spec.reviewTarget(), spec.ReviewInstructions, created.conversation()) } }) @@ -1099,6 +1102,13 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er fail() return nil, stack.Wrap(ErrSessionExists) } + // Its row was refused before the session was held, so idTaken found nothing to end. + if created.idTaken.Load() { + m.mu.Unlock() + turnedAway = true + fail() + return nil, stack.Wrap(ErrSessionExists) + } m.sessions[created.Key()] = created sessionsActive.Inc() created.active.Store(true) @@ -1726,6 +1736,26 @@ func (m *Manager) end(found *Session, reason EndReason) { found.abandon() } +// idTaken ends created, whose row the store refused because another customer's session has its +// id: the check that an id is free (Create) runs before the row is written, so two routers +// opening one id for two customers both pass it. One not held yet is turned away by Create. +// It runs on the record writer, so the close, which may wait on the writer, runs beside it. +func (m *Manager) idTaken(created *Session) { + created.idTaken.Store(true) + m.logger.Warn("ending a session whose id another customer's session has", + "session", created.id, "customer", created.Spec().CustomerID) + done, held := m.take(created) + if !held { + return + } + created.noteEnd(EndClosed) + go func() { + defer done() + m.release(created) + created.abandon() + }() +} + // hangUp ends found for its agent hanging up, or reason. It closes as Close does, so the // goodbye is not cut short, and in the background: the agent hangs up from inside its own // tool call, and closing the session waits for the agent. diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index 32b3298824..294c32e6fb 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -74,7 +74,7 @@ func (s *RecordFlushSuite) TestFlushesWaitingOnASlowWriterLeaveRoomForRows() { "the waiting flushes took room in the queue") later := s.row() - s.records.Opened(later, nil) + s.records.Opened(later, nil, nil) s.Zero(s.records.Dropped(), "a row queued behind the waiting flushes was dropped") release() @@ -90,7 +90,7 @@ func (s *RecordFlushSuite) TestFlushesWaitingOnASlowWriterLeaveRoomForRows() { func (s *RecordFlushSuite) TestFlushesWaitingTogetherDoNotWaitForRowsQueuedAfterThem() { releaseFirst := s.holdWriter() second, releaseSecond := s.heldRow() - s.records.Opened(second, nil) + s.records.Opened(second, nil, nil) const callers = 64 errs := make(chan error, callers) var started sync.WaitGroup @@ -107,7 +107,7 @@ func (s *RecordFlushSuite) TestFlushesWaitingTogetherDoNotWaitForRowsQueuedAfter s.Require().Eventually(func() bool { return len(s.records.queue) == 0 }, settleFor, 5*time.Millisecond, "the writer never took the second held row") third, _ := s.heldRow() - s.records.Opened(third, nil) + s.records.Opened(third, nil, nil) releaseSecond() deadline := time.After(recordWriteTimeout / 2) @@ -124,7 +124,7 @@ func (s *RecordFlushSuite) TestFlushesWaitingTogetherDoNotWaitForRowsQueuedAfter func (s *RecordFlushSuite) TestAFlushIsNotHeldByALaterFlushWaitingOnARowQueuedAfterIt() { releaseFirst := s.holdWriter() second, releaseSecond := s.heldRow() - s.records.Opened(second, nil) + s.records.Opened(second, nil, nil) first := make(chan error, 1) var started sync.WaitGroup started.Add(1) @@ -138,7 +138,7 @@ func (s *RecordFlushSuite) TestAFlushIsNotHeldByALaterFlushWaitingOnARowQueuedAf s.Require().Eventually(func() bool { return len(s.records.queue) == 0 }, settleFor, 5*time.Millisecond, "the writer never took the second held row") third, _ := s.heldRow() - s.records.Opened(third, nil) + s.records.Opened(third, nil, nil) go func() { _ = s.records.Flush(s.bounded()) }() // Nothing shows that the later Flush has reached the writer; give it time to. time.Sleep(50 * time.Millisecond) @@ -180,7 +180,7 @@ func (s *RecordFlushSuite) TestEachFlushWaitsForTheRowItsCallerQueuedBeforeIt() row := s.row() started.Add(1) finished.Go(func() { - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) started.Done() if err := s.records.Flush(s.bounded()); err != nil { missing <- err.Error() @@ -206,7 +206,7 @@ func (s *RecordFlushSuite) TestEachFlushWaitsForTheRowItsCallerQueuedBeforeIt() func (s *RecordFlushSuite) TestAFlushReturnsOnceTheItemsQueuedBeforeItAreWritten() { row := s.row() - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) response := store.AgentResponse{ID: rand.Text(), SessionID: row.ID, CustomerID: s.customer, Said: "Where is my order?"} s.records.Responding(response) for ordinal, text := range []string{"Where is my order?", "It ships today.", "Thanks."} { @@ -225,7 +225,7 @@ func (s *RecordFlushSuite) TestAFlushReturnsOnceTheItemsQueuedBeforeItAreWritten func (s *RecordFlushSuite) TestAFlushWaitingAsTheWriterClosesReturnsOnceItsRowIsWritten() { release := s.holdWriter() row := s.row() - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) flushed := make(chan error, 1) go func() { flushed <- s.records.Flush(s.bounded()) }() closed := make(chan struct{}) @@ -263,7 +263,7 @@ func (s *RecordFlushSuite) TestAFlushGivesUpWhenItsCallerDoes() { func (s *RecordFlushSuite) TestAFlushTheWriterTookInGivesUpWhenItsCallerDoes() { releaseFirst := s.holdWriter() second, _ := s.heldRow() - s.records.Opened(second, nil) + s.records.Opened(second, nil, nil) ctx, cancel := context.WithCancel(s.ctx) defer cancel() flushed := make(chan error, 1) @@ -291,13 +291,13 @@ func (s *RecordFlushSuite) TestATitleWrittenAfterTheSessionWasDeletedLogsNoError logged := &syncBuffer{} records := s.recorderLogging(s.store, logged) row := s.row() - records.Opened(row, nil) + records.Opened(row, nil, nil) s.Require().NoError(records.Flush(s.bounded())) // The title is queued behind a write the writer is stuck on, as the one a model is // still composing is when the customer deletes the conversation. held, release := s.heldRow() - records.Opened(held, nil) + records.Opened(held, nil, nil) records.Described(s.customer, row.ID, "Where an order went", "A question about an order.", nil) s.Require().NoError(s.store.Sessions.Delete(s.ctx, s.customer, row.ID)) release() @@ -315,7 +315,7 @@ func (s *RecordFlushSuite) TestATitleForASessionThatIsThereIsStored() { logged := &syncBuffer{} records := s.recorderLogging(s.store, logged) row := s.row() - records.Opened(row, nil) + records.Opened(row, nil, nil) records.Described(s.customer, row.ID, "Where an order went", "A question about an order.", nil) s.Require().NoError(records.Flush(s.bounded())) @@ -327,7 +327,7 @@ func (s *RecordFlushSuite) TestATitleForASessionThatIsThereIsStored() { func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOpen() { row := s.row() - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) s.records.Closed("other-"+s.customer, row.ID, row.OpenedAt, time.Now().UTC(), TimeoutHangup) s.Require().NoError(s.records.Flush(s.bounded())) @@ -341,14 +341,14 @@ func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOp func (s *RecordFlushSuite) TestACloseQueuedByTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen() { row := s.row() - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) s.Require().NoError(s.records.Flush(s.bounded())) // Another router carries the session on while the close of this one is still queued. reopening := newSessionRecorder(s.store, slog.New(slog.DiscardHandler)) s.T().Cleanup(reopening.Close) reopened := row reopened.OpenedAt = row.OpenedAt.Add(time.Minute) - reopening.CarriedOn(reopened, nil) + reopening.CarriedOn(reopened, nil, nil) s.Require().NoError(reopening.Flush(s.bounded())) s.records.Closed(s.customer, row.ID, row.OpenedAt, time.Now().UTC(), TimeoutHangup) @@ -371,7 +371,7 @@ func (s *RecordFlushSuite) TestTheItemsOfATurnWhoseIdIsAnotherCustomersAreNotWri turn := rand.Text() s.Require().NoError(s.store.Responses.Insert(s.ctx, &store.AgentResponse{ID: turn, SessionID: theirs.ID, CustomerID: other})) row := s.row() - s.records.Opened(row, nil) + s.records.Opened(row, nil, nil) s.records.Responding(store.AgentResponse{ID: turn, SessionID: row.ID, CustomerID: s.customer}) s.records.Item(store.AgentResponseItem{ResponseID: turn, SessionID: row.ID, Kind: "message", Text: "app's answer"}) @@ -383,6 +383,58 @@ func (s *RecordFlushSuite) TestTheItemsOfATurnWhoseIdIsAnotherCustomersAreNotWri s.Empty(written, "no item was written under the other customer's turn") } +func (s *RecordFlushSuite) TestASessionOpenedAgainOnceItsIDIsFreeKeepsItsTurns() { + other := "other-" + s.customer + row := s.row() + theirs := store.AgentSession{ID: row.ID, CustomerID: other, State: store.SessionRunning, CreatedAt: time.Now().UTC()} + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &theirs)) + refused := make(chan struct{}) + s.records.Opened(row, nil, func() { close(refused) }) + s.records.Responding(store.AgentResponse{ID: rand.Text(), SessionID: row.ID, CustomerID: s.customer}) + s.records.Closed(s.customer, row.ID, row.OpenedAt, time.Now().UTC(), EndClosed) + s.Require().NoError(s.records.Flush(s.bounded())) + s.Require().Eventually(func() bool { + select { + case <-refused: + return true + default: + return false + } + }, settleFor, 5*time.Millisecond, "the row taken by another customer was not refused") + s.Require().NoError(s.store.Sessions.Delete(s.ctx, other, row.ID)) + + s.records.Opened(row, nil, nil) + turn := rand.Text() + s.records.Responding(store.AgentResponse{ID: turn, SessionID: row.ID, CustomerID: s.customer}) + s.Require().NoError(s.records.Flush(s.bounded())) + + turns, err := s.store.Responses.Select(s.ctx, s.customer, row.ID, store.ResponseFilter{Limit: 10}) + s.Require().NoError(err) + s.Require().Len(turns, 1, "only the turn of the session opened once the id was free is kept") + s.Equal(turn, turns[0].ID) +} + +// The close of the refused session never reached the writer, as when a full queue drops it. +func (s *RecordFlushSuite) TestASessionOpenedAgainOnceItsIDIsFreeKeepsItsTurnsWithNoCloseBetween() { + other := "other-" + s.customer + row := s.row() + theirs := store.AgentSession{ID: row.ID, CustomerID: other, State: store.SessionRunning, CreatedAt: time.Now().UTC()} + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &theirs)) + s.records.Opened(row, nil, nil) + s.Require().NoError(s.records.Flush(s.bounded())) + s.Require().NoError(s.store.Sessions.Delete(s.ctx, other, row.ID)) + + s.records.Opened(row, nil, nil) + turn := rand.Text() + s.records.Responding(store.AgentResponse{ID: turn, SessionID: row.ID, CustomerID: s.customer}) + s.Require().NoError(s.records.Flush(s.bounded())) + + turns, err := s.store.Responses.Select(s.ctx, s.customer, row.ID, store.ResponseFilter{Limit: 10}) + s.Require().NoError(err) + s.Require().Len(turns, 1, "the session opened once the id was free keeps its turn") + s.Equal(turn, turns[0].ID) +} + func (s *RecordFlushSuite) TestATitleTheStoreCouldNotWriteStillLogsAnError() { logged := &syncBuffer{} broken, err := store.Open(s.dsn) @@ -399,7 +451,7 @@ func (s *RecordFlushSuite) TestATitleTheStoreCouldNotWriteStillLogsAnError() { 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.Opened(held, nil, 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()}) @@ -428,8 +480,8 @@ func (s *RecordFlushSuite) TestASessionWriteCutOffByADroppedConnectionIsStoredWi func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopAnotherSessionsItems() { kept, orphaned := s.row(), s.row() - s.records.Opened(kept, nil) - s.records.Opened(orphaned, nil) + s.records.Opened(kept, nil, nil) + s.records.Opened(orphaned, nil, 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)) @@ -453,7 +505,7 @@ func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopAnotherSes func (s *RecordFlushSuite) TestAnItemWhoseResponseIsMissingDoesNotStopItsSessionsStoredTurn() { session := s.row() - s.records.Opened(session, nil) + s.records.Opened(session, nil, nil) stored := store.AgentResponse{ID: rand.Text(), SessionID: session.ID, CustomerID: s.customer, Said: "Can I change the address?"} s.records.Responding(stored) @@ -525,7 +577,7 @@ func (s *RecordFlushSuite) TestEveryWriteCutOffByADroppedConnectionIsStored() { held: []string{"agent_session_tools"}, queue: func(r *sessionRecorder, rows cutRows) { rows.session.Title = "Reopened" - r.Opened(rows.session, tool) + r.Opened(rows.session, tool, nil) }, check: func(rows cutRows) { s.Equal(tool, s.toolsOf(rows.session.ID)) }, }, { @@ -852,7 +904,7 @@ func (b *syncBuffer) String() string { // recordWriteTimeout, so a test releases well before that. func (s *RecordFlushSuite) holdWriter() (release func()) { held, release := s.heldRow() - s.records.Opened(held, nil) + s.records.Opened(held, nil, nil) s.Require().Eventually(func() bool { return len(s.records.queue) == 0 }, settleFor, 5*time.Millisecond, "the writer never took the held row") return release diff --git a/acceleration/internal/session/recorded_create_test.go b/acceleration/internal/session/recorded_create_test.go index 03f6ab4b47..50899932a5 100644 --- a/acceleration/internal/session/recorded_create_test.go +++ b/acceleration/internal/session/recorded_create_test.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "os" + "strings" "sync" "testing" "time" @@ -19,6 +20,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" persistent "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation/chattest" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" @@ -43,6 +45,8 @@ type RecordedCreateSuite struct { customer string // dsn is the suite's database, which store keeps every table in. dsn string + // logged is what the test's managers logged. + logged *syncBuffer } func TestRecordedCreateSuite(t *testing.T) { @@ -65,6 +69,7 @@ func (s *RecordedCreateSuite) SetupSuite() { func (s *RecordedCreateSuite) SetupTest() { s.customer = "recorded-" + uuid.NewString() + s.logged = &syncBuffer{} } func (s *RecordedCreateSuite) TestAGreetingSlowerThanTheRowIsStored() { @@ -211,6 +216,140 @@ func (s *RecordedCreateSuite) TestTheSpecReadsRaceNoChose() { } } +// Another router opened the id for another customer while this one joined its call: the +// check that the id is free ran on both before either row was written. This one's row is +// refused once its session is held, which ends it and keeps its turns and call off the id. +func (s *RecordedCreateSuite) TestASessionWhoseIDAnotherCustomerTookOnceItWasHeldIsEnded() { + late := s.manager(newQuietEdge(), &stubTTS{emitter: tts.NewEmitter(64)}, nil) + release := s.holdWriter(late) + other := "other-" + s.customer + spec := s.spec(Spec{ID: "shared-" + uuid.NewString(), Greeting: "Hi, I'm listening."}) + spec.CustomerID = other + + created, err := late.Create(s.ctx, spec) + s.Require().NoError(err) + s.opened(spec.ID) + release() + + s.Require().Eventually(func() bool { return created.State() == Ended }, settleFor, 10*time.Millisecond, + "the session on another customer's id is still running") + _, held := late.Get(spec.ID, Owner{CustomerID: other, Kind: auth.KindServer}) + s.False(held) + s.Require().NoError(late.records.Flush(s.ctx)) + s.theOwnersOnly(spec.ID, other) + s.Require().NotEmpty(created.conversation(), "the greeting is what a review would read") + late.reviews.running.Wait() + s.NotContains(s.logged.String(), "review the call", "a session with no row of its own is reviewed") +} + +// A carry-on skips the check that the id is free, so its row can be refused as a new +// session's is, by another customer's written on another shard meanwhile. +func (s *RecordedCreateSuite) TestACarriedOnSessionWhoseIDAnotherCustomerTookIsEnded() { + other := "other-" + s.customer + late := s.chatting(s.store, chattest.Client(s.T())) + caller := routing.Caller{UserID: "employee-1"} + first, err := late.Create(s.ctx, Spec{CustomerID: other, Text: true, PersistConversation: true, + LLMTarget: "en-low-latency", Caller: caller}) + s.Require().NoError(err) + s.Require().NoError(first.Close()) + s.Require().NoError(late.records.Flush(s.ctx)) + // Meanwhile the id became the suite customer's, as another shard's row would make it. + s.Require().NoError(s.store.Sessions.Delete(s.ctx, other, first.ID())) + s.opened(first.ID()) + + created, err := late.Create(s.ctx, Spec{ID: first.ID(), CustomerID: other, Text: true, PersistConversation: true, + ConversationID: first.Spec().ConversationID, Reopened: first.CreatedAt(), LLMTarget: "en-low-latency", Caller: caller}) + if !errors.Is(err, ErrSessionExists) { + s.Require().NoError(err) + s.Require().Eventually(func() bool { return created.State() == Ended }, settleFor, 10*time.Millisecond, + "the carried-on session on another customer's id is still running") + } + _, held := late.Get(first.ID(), Owner{CustomerID: other, Kind: auth.KindServer}) + s.False(held) + s.Require().NoError(late.records.Flush(s.ctx)) + s.theOwnersOnly(first.ID(), other) +} + +// The same, with the row refused before Create held the session. +func (s *RecordedCreateSuite) TestASessionWhoseIDAnotherCustomerTookBeforeItWasHeldIsTurnedAway() { + joining, joined := make(chan struct{}), make(chan struct{}) + late := s.manager(gatedEdge{newQuietEdge(), joining, joined}, &stubTTS{emitter: tts.NewEmitter(64)}, nil) + other := "other-" + s.customer + spec := s.spec(Spec{ID: "shared-" + uuid.NewString(), Greeting: "Hi, I'm listening."}) + spec.CustomerID = other + refused := make(chan error, 1) + go func() { + _, err := late.Create(s.ctx, spec) + refused <- err + }() + select { + case <-joining: + case <-time.After(settleFor): + s.FailNow("the session never joined its call") + } + s.opened(spec.ID) + + // Create waits to hold the session until the writer has refused its row. + late.mu.Lock() + unlock := sync.OnceFunc(late.mu.Unlock) + defer unlock() + close(joined) + s.Require().Eventually(func() bool { + return strings.Contains(s.logged.String(), "ending a session whose id another customer's session has") + }, settleFor, 10*time.Millisecond, "the row was not refused") + unlock() + + select { + case err := <-refused: + s.Require().ErrorIs(err, ErrSessionExists) + case <-time.After(settleFor): + s.FailNow("Create did not return") + } + _, held := late.Get(spec.ID, Owner{CustomerID: other, Kind: auth.KindServer}) + s.False(held, "the session on another customer's id is held") + s.Require().NoError(late.records.Flush(s.ctx)) + s.theOwnersOnly(spec.ID, other) +} + +// opened writes the suite customer's running session id, as the router that opened it first +// would. +func (s *RecordedCreateSuite) opened(id string) { + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ID: id, CustomerID: s.customer, + Title: "the first one", State: store.SessionRunning, CreatedAt: time.Now().UTC()})) +} + +// theOwnersOnly checks that session id is still the suite customer's, running as it was, and +// that nothing of other's was written under it. +func (s *RecordedCreateSuite) theOwnersOnly(id, other string) { + row, err := s.store.Sessions.Get(s.ctx, s.customer, id) + s.Require().NoError(err) + s.Equal(store.SessionRunning, row.State) + s.Equal("the first one", row.Title) + turns, err := s.store.Responses.Select(s.ctx, other, id, store.ResponseFilter{Limit: 10}) + s.Require().NoError(err) + s.Empty(turns, "the refused session's turns are under the id") + calls, err := s.store.Calls.Select(s.ctx, other, store.CallFilter{SessionID: id}) + s.Require().NoError(err) + s.Empty(calls, "the refused session's call is under the id") +} + +// holdWriter stalls m's writer on a session row another transaction is inserting, until the +// returned release rolls that transaction back. +func (s *RecordedCreateSuite) holdWriter(m *Manager) (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) + held := store.AgentSession{ID: uuid.NewString(), CustomerID: s.customer, State: store.SessionRunning, CreatedAt: time.Now().UTC()} + _, err = tx.ExecContext(s.ctx, "INSERT INTO agent_sessions (id, customer_id, state) VALUES (?, ?, ?)", + held.ID, held.CustomerID, store.SessionRunning) + s.Require().NoError(err) + m.records.Opened(held, nil, nil) + s.Require().Eventually(func() bool { return len(m.records.(*sessionRecorder).queue) == 0 }, settleFor, 5*time.Millisecond, + "the writer never took the held row") + return release +} + // joining is a session as Create holds it while the greeting is spoken: handed the recorder, // its row not queued yet. func (s *RecordedCreateSuite) joining(m *Manager) *Session { @@ -222,7 +361,7 @@ func (s *RecordedCreateSuite) joining(m *Manager) *Session { // queued queues row as Create does once the greeting is over, and reads it back. func (s *RecordedCreateSuite) queued(m *Manager, joining *Session, row store.AgentSession) store.AgentSession { - m.records.Opened(row, nil) + m.records.Opened(row, nil, nil) joining.startRecording() s.Require().NoError(m.records.Flush(s.ctx)) rows, err := s.store.Sessions.Select(s.ctx, s.customer, store.SessionFilter{Limit: 10}) @@ -264,7 +403,7 @@ func (s *RecordedCreateSuite) manager(edge agent.Edge, voice tts.TTS, finder sea // managerOn is manager over on, keeping conversations in conversations unless it is nil. func (s *RecordedCreateSuite) managerOn(on *store.Store, conversations *persistent.Service, edge agent.Edge, voice tts.TTS, finder search.Provider) *Manager { - logger := slog.New(slog.DiscardHandler) + logger := slog.New(slog.NewTextHandler(s.logged, nil)) transcription := sttrouter.NewRegistry() transcription.Register("stub", func(routing.Spec) (stt.STT, error) { return &stubSTT{emitter: stt.NewEmitter(64)}, nil }) transcriber, err := sttrouter.New(sttrouter.Options{Config: stubConfig(), Registry: transcription, Logger: logger}) @@ -346,6 +485,18 @@ func (s *RecordedCreateSuite) chatting(on *store.Store, chat *getstream.Stream) return s.managerOn(on, conversations, newQuietEdge(), &stubTTS{emitter: tts.NewEmitter(64)}, nil) } +// gatedEdge is a call whose join says it began on joining and waits for joined. +type gatedEdge struct { + *quietEdge + joining, joined chan struct{} +} + +func (e gatedEdge) Join(ctx context.Context) error { + close(e.joining) + <-e.joined + return e.quietEdge.Join(ctx) +} + // refusingEdge is a call that will not have the agent. type refusingEdge struct{ *quietEdge } diff --git a/acceleration/internal/session/records.go b/acceleration/internal/session/records.go index 680d3bb94b..3496e3435d 100644 --- a/acceleration/internal/session/records.go +++ b/acceleration/internal/session/records.go @@ -76,10 +76,12 @@ type recordWrite struct { // customerID is whose session the write is to: an id alone may be another customer's. customerID string // session is a session that opened or was renamed, nil otherwise, and tools what its - // model is offered. carriedOn says it was carried on from a row it had. + // model is offered. carriedOn says it was carried on from a row it had. refused is called + // if the store refuses its row because another customer's session has its id. session *store.AgentSession tools []store.ToolDefinition carriedOn bool + refused func() // offered is the session whose model is now offered tools. offered string // closed is the session that ended, opened when the router closing it opened it, closedAt @@ -148,8 +150,11 @@ type recorder interface { // session open and close. type sessionRecords interface { recorder - Opened(row store.AgentSession, tools []store.ToolDefinition) - CarriedOn(row store.AgentSession, tools []store.ToolDefinition) + // Opened says a session started. refused is called, on the writer, if its id turns out to + // be another customer's session's. + Opened(row store.AgentSession, tools []store.ToolDefinition, refused func()) + // CarriedOn says a session was carried on from a row it had; refused is as for Opened. + CarriedOn(row store.AgentSession, tools []store.ToolDefinition, refused func()) Closed(customerID, id string, opened, at time.Time, reason EndReason) Close() } @@ -186,6 +191,10 @@ type sessionRecorder struct { // 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 + // taken are the sessions, by customer and id, whose row the store refused because the id + // is another customer's: their turns and calls are not written under it. Kept by the + // writer alone, and each until the session closes. + taken map[[2]string]struct{} } func newSessionRecorder(pgStore *store.Store, logger *slog.Logger) *sessionRecorder { @@ -196,20 +205,21 @@ func newSessionRecorder(pgStore *store.Store, logger *slog.Logger) *sessionRecor flushes: make(chan chan (<-chan struct{})), done: make(chan struct{}), refused: map[string]struct{}{}, + taken: map[[2]string]struct{}{}, } go r.run() return r } // Opened queues the row for a session that has just started. -func (r *sessionRecorder) Opened(row store.AgentSession, tools []store.ToolDefinition) { - r.queueWrite(recordWrite{session: &row, tools: tools}) +func (r *sessionRecorder) Opened(row store.AgentSession, tools []store.ToolDefinition, refused func()) { + r.queueWrite(recordWrite{session: &row, tools: tools, refused: refused}) } // CarriedOn queues the row of a session carried on from a row it had, maybe in another shard, // which it supersedes once written. -func (r *sessionRecorder) CarriedOn(row store.AgentSession, tools []store.ToolDefinition) { - r.queueWrite(recordWrite{session: &row, tools: tools, carriedOn: true}) +func (r *sessionRecorder) CarriedOn(row store.AgentSession, tools []store.ToolDefinition, refused func()) { + r.queueWrite(recordWrite{session: &row, tools: tools, carriedOn: true, refused: refused}) } // Offered queues what a session's model is now offered. @@ -440,10 +450,24 @@ func (w *flushWaiters) release(taken int) { func (r *sessionRecorder) write(write recordWrite) { switch { case write.session != nil: - if err := r.attempt(func(ctx context.Context) error { return r.store.Sessions.Upsert(ctx, write.session) }); err != nil { + key := [2]string{write.session.CustomerID, write.session.ID} + err := r.attempt(func(ctx context.Context) error { return r.store.Sessions.Upsert(ctx, write.session) }) + if errors.Is(err, store.ErrIDTaken) { + r.taken[key] = struct{}{} + if write.refused != nil { + write.refused() + } + // Expected when two routers open one id at once, and handled where refused ends + // the session, which says so: no ERROR with a stack here. + return + } + if err != nil { r.logger.Error("could not record the session starting", "error", err) return } + // The id is the customer's now, whether or not the close of a refused session before + // it reached the writer: a full queue drops a close. + delete(r.taken, key) if write.carriedOn { if err := r.attempt(func(ctx context.Context) error { return r.store.Sessions.Supersede(ctx, write.session.CustomerID, write.session.ID, write.session.OpenedAt) @@ -463,6 +487,7 @@ func (r *sessionRecorder) write(write recordWrite) { r.logger.Error("could not record the session's tools", "error", err) } case write.closed != "": + delete(r.taken, [2]string{write.customerID, write.closed}) if err := r.attempt(func(ctx context.Context) error { return r.store.Sessions.Close(ctx, write.customerID, write.closed, write.opened, write.closedAt, write.endReason) }); err != nil { @@ -471,6 +496,10 @@ func (r *sessionRecorder) write(write recordWrite) { r.logger.Error("could not record the session ending", "session", write.closed, "error", err) } case write.response != nil: + if _, taken := r.taken[[2]string{write.response.CustomerID, write.response.SessionID}]; taken { + r.refused[write.response.ID] = struct{}{} + return + } 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{}{} @@ -524,6 +553,9 @@ func (r *sessionRecorder) write(write recordWrite) { r.logger.Error("could not record the session's voice", "session", write.voiced, "error", err) } case write.callStarted != nil: + if _, taken := r.taken[[2]string{write.callStarted.CustomerID, write.callStarted.SessionID}]; taken { + return + } 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) } diff --git a/acceleration/internal/session/records_test.go b/acceleration/internal/session/records_test.go index 2d66b89387..9d0f0ad690 100644 --- a/acceleration/internal/session/records_test.go +++ b/acceleration/internal/session/records_test.go @@ -74,9 +74,9 @@ func (r *heldRecorder) Voiced(string, string) {} func (r *heldRecorder) Flush(context.Context) error { return nil } -func (r *heldRecorder) Opened(store.AgentSession, []store.ToolDefinition) {} +func (r *heldRecorder) Opened(store.AgentSession, []store.ToolDefinition, func()) {} -func (r *heldRecorder) CarriedOn(store.AgentSession, []store.ToolDefinition) {} +func (r *heldRecorder) CarriedOn(store.AgentSession, []store.ToolDefinition, func()) {} func (r *heldRecorder) Closed(string, string, time.Time, time.Time, EndReason) {} diff --git a/acceleration/internal/session/session.go b/acceleration/internal/session/session.go index dd53e5bb3b..510c529c3b 100644 --- a/acceleration/internal/session/session.go +++ b/acceleration/internal/session/session.go @@ -383,6 +383,9 @@ type Session struct { // handedOver is set on a session that must not hang up its call: another session serves // it, or the router turned the session away as it shut down. handedOver atomic.Bool + // idTaken is set once the store refused the session's row because another customer's + // session has its id (Manager.idTaken). + idTaken atomic.Bool // active is set while router_sessions_active counts the session: from the manager // holding it until it has closed. agentLeft is set once its agent left the call by itself // (consume). modelErred and replied are whether its model failed a turn and whether diff --git a/acceleration/internal/store/call.go b/acceleration/internal/store/call.go index 0e256983af..9cf9ae3abd 100644 --- a/acceleration/internal/store/call.go +++ b/acceleration/internal/store/call.go @@ -135,7 +135,8 @@ type Calls struct { // It is written when the agent joins rather than when the call ends, so a call that is // still running is findable and one the process died during is not simply lost. Starting // the same call twice updates the row instead of failing: a retried write must not turn -// into a second call. +// into a second call. An id another customer's call has is ErrIDTaken, and their row is left +// as it is. func (r *Calls) Start(ctx context.Context, call *Call) error { if err := call.Validate(); err != nil { return stack.Wrap(err) @@ -162,15 +163,25 @@ func (r *Calls) Start(ctx context.Context, call *Call) error { call.Tags = map[string]string{} } - _, err := r.store.shard.NewInsert().Model(call). + result, err := r.store.shard.NewInsert().Model(call). On("CONFLICT (id) DO UPDATE"). Set("ended_at = NULL"). Set("agent_user_id = COALESCE(c.agent_user_id, EXCLUDED.agent_user_id)"). Set("conversation_id = COALESCE(c.conversation_id, EXCLUDED.conversation_id)"). + // The router mints a call's id (NewID), so only a row imported under it can be another + // customer's. + Where("c.customer_id = EXCLUDED.customer_id"). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: start call: %w", err)) } + written, err := result.RowsAffected() + if err != nil { + return stack.Wrap(fmt.Errorf("store: start call: %w", err)) + } + if written == 0 { + return stack.Wrap(fmt.Errorf("%w: call %s", ErrIDTaken, call.ID)) + } return nil } diff --git a/acceleration/internal/store/call_test.go b/acceleration/internal/store/call_test.go index 7c619c4b96..c03486deaa 100644 --- a/acceleration/internal/store/call_test.go +++ b/acceleration/internal/store/call_test.go @@ -350,3 +350,21 @@ func (s *StoreSuite) TestAnotherCustomersWriteToACallIdChangesNothing() { }) } } + +func (s *StoreSuite) TestAnotherCustomersCallByTheSameIdIsNotOpenedAgain() { + call := Call{ID: "one", CustomerID: "app", CallID: "call-1", AgentID: "agent-theirs", StartedAt: s.base} + s.Require().NoError(s.store.Calls.Start(s.ctx, &call)) + s.Require().NoError(s.store.Calls.Finish(s.ctx, "app", call.ID, s.base.Add(time.Minute))) + before, err := s.store.Calls.Get(s.ctx, "app", "one") + s.Require().NoError(err) + + err = s.store.Calls.Start(s.ctx, &Call{ + ID: "one", CustomerID: "somebody-else", CallID: "call-2", AgentID: "agent-other", StartedAt: s.base.Add(time.Hour), + }) + s.Require().ErrorIs(err, ErrIDTaken) + + after, err := s.store.Calls.Get(s.ctx, "app", "one") + s.Require().NoError(err) + s.Equal(before, after, "app's call is as it was, still ended") + s.Require().NoError(s.store.Calls.Start(s.ctx, &call), "app starting its own call again is not refused") +} diff --git a/acceleration/internal/store/campaign.go b/acceleration/internal/store/campaign.go index 6531d06e88..f001fd0fa1 100644 --- a/acceleration/internal/store/campaign.go +++ b/acceleration/internal/store/campaign.go @@ -358,7 +358,8 @@ SELECT replace(gen_random_uuid()::text, '-', ''), ?, to_number, instructions, va FROM campaign_contacts cc WHERE campaign_id = ? AND reason IS DISTINCT FROM 'duplicate'` if contacts == DuplicateNotContacted { - query += ` AND NOT EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id)` + // An attempt that was deferred or refused rang nobody. + query += ` AND NOT EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id AND ` + placedDial + `)` } if _, err := tx.ExecContext(ctx, query+" ORDER BY seq", copied.ID, source.ID); err != nil { return fmt.Errorf("store: duplicate contacts: %w", err) diff --git a/acceleration/internal/store/campaign_test.go b/acceleration/internal/store/campaign_test.go index 9d38c8c924..d44c71b174 100644 --- a/acceleration/internal/store/campaign_test.go +++ b/acceleration/internal/store/campaign_test.go @@ -245,6 +245,25 @@ func (s *StoreSuite) TestADuplicateOfNotContactedTakesOnlyContactsNeverDialed() s.Empty(s.contactsOf(nobody)) } +func (s *StoreSuite) TestADuplicateOfNotContactedKeepsAContactWhoseAttemptsPlacedNoCall() { + original := s.draftCampaign(newID(), "+15550001", "+15550002", "+15550003") + s.launch(original, s.base) + contacts := s.contactsOf(original) + for i, result := range []string{"deferred", "", "voicemail"} { + _, err := s.store.GlobalDB().NewInsert().Model(&CampaignAttempt{ID: newID(), CampaignID: original.ID, ContactID: contacts[i].ID, + StepID: "step_1", Attempt: 1, Dial: 1, StartedAt: s.base, Result: result}).Exec(s.ctx) + s.Require().NoError(err) + } + s.Require().NoError(s.store.Campaigns.Stop(s.ctx, original.CustomerID, original.ID, s.base)) + + copied, err := s.store.Campaigns.Duplicate(s.ctx, original.CustomerID, original.ID, "not_contacted") + s.Require().NoError(err) + + kept := s.contactsOf(copied) + s.Require().Len(kept, 1, "a deferred attempt rang nobody; a call and a voicemail did") + s.Equal(contacts[0].ToNumber, kept[0].ToNumber) +} + func (s *StoreSuite) TestTheSameNumberTwiceIsADuplicate() { campaign := s.draftCampaign(newID(), "+15550001") diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 6601dfbebe..3fa6b2483b 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2330,6 +2330,69 @@ func (s *DataMoveSuite) TestBackfillPinsTheDeploymentAppsRows() { s.Error(err, "an unknown deployment app pins nothing") } +func (s *DataMoveSuite) TestBackfillPinsARowAnotherWriterChangesMidway() { + locked, other := s.pinnedSession("acme", 0), s.pinnedSession("acme", 0) + + s.backfillPast(locked, "title = 'renamed'") + + s.Zero(s.unpinned(), "rows %s and %s", locked, other) +} + +func (s *DataMoveSuite) TestBackfillPinsTheOnlyRowWhenAnotherWriterChangesIt() { + locked := s.pinnedSession("acme", 0) + + s.backfillPast(locked, "title = 'renamed'") + + s.Zero(s.unpinned(), "row %s", locked) +} + +func (s *DataMoveSuite) TestBackfillLeavesARowAnotherWriterPinnedMidway() { + locked := s.pinnedSession("acme", 0) + + s.backfillPast(locked, "stream_app_pk = 4242") + + var pin int64 + s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx, + "SELECT stream_app_pk FROM agent_sessions WHERE id = ?", locked).Scan(&pin)) + s.Equal(int64(4242), pin, "the other writer's pin is kept") +} + +// backfillPast backfills the source's pins while an update setting set on session id holds its +// row, which commits once the backfill waits on it, as a session written to mid-backfill would. +func (s *DataMoveSuite) backfillPast(id, set string) { + tx, err := s.source.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer tx.Rollback() //nolint:errcheck // a no-op once committed + _, err = tx.ExecContext(s.ctx, "UPDATE agent_sessions SET "+set+" WHERE id = ?", id) + s.Require().NoError(err) + done := make(chan error, 1) + go func() { + _, err := s.source.BackfillStreamPins(s.ctx, 1) + done <- err + }() + s.Require().Eventually(func() bool { + var waiting bool + err := s.source.GlobalDB().QueryRowContext(s.ctx, `SELECT EXISTS (SELECT 1 FROM pg_stat_activity +WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE 'UPDATE agent_sessions SET stream_app_pk%')`).Scan(&waiting) + return err == nil && waiting + }, 10*time.Second, 10*time.Millisecond, "the backfill never waited on the row") + s.Require().NoError(tx.Commit()) + select { + case err := <-done: + s.Require().NoError(err) + case <-time.After(10 * time.Second): + s.FailNow("the backfill did not finish") + } +} + +// unpinned is how many of the source's sessions have no pin. +func (s *DataMoveSuite) unpinned() int { + var count int + s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx, + "SELECT count(*) FROM agent_sessions WHERE stream_app_pk IS NULL").Scan(&count)) + return count +} + func (s *DataMoveSuite) TestADeploymentThatCanNeverKnowItsAppParksAPinnedRow() { // With no Stream key to ask with, waiting would be waiting for ever. s.source.SetStreamPins(StreamPins{Deployment: func() int64 { return 1 }}) diff --git a/acceleration/internal/store/logs.go b/acceleration/internal/store/logs.go index 5b62a51507..9801f14a7f 100644 --- a/acceleration/internal/store/logs.go +++ b/acceleration/internal/store/logs.go @@ -7,6 +7,7 @@ import ( "log/slog" "regexp" "strings" + "unicode/utf8" "github.com/getsentry/sentry-go" ) @@ -144,14 +145,37 @@ var encodedBearer = regexp.MustCompile(`(?i)bearer(?:%(?:25)*20|\+)+[^\s"\x27&#\ func SafeLogText(text string) string { text = RedactLogText(text) if len(text) > 8192 { - text = string([]rune(text)[:min(len([]rune(text)), 2048)]) + "… [truncated]" + text = string([]rune(text)[:min(len([]rune(text)), 2048)]) + truncatedMarker } return text } +// truncatedMarker ends a text that was cut. +const truncatedMarker = "… [truncated]" + +// maxTurnText is the most of one turn's text that is kept: what was asked, thought or answered. +// The session socket takes a message of 5 MiB and the text is stored twice, on the response and +// on its item, while a real turn is a few KiB: a ceiling far above that never cuts one. +const maxTurnText = 256 << 10 + +// turnText is what a conversation said as it is stored: RedactLogText, cut past maxTurnText at a +// rune boundary with the marker SafeLogText adds. +func turnText(text string) string { + text = RedactLogText(text) + if len(text) <= maxTurnText { + return text + } + cut := maxTurnText + for cut > 0 && !utf8.RuneStart(text[cut]) { + cut-- + } + return text[:cut] + truncatedMarker +} + // RedactLogText is text with every credential shape taken out, at whatever length. A caller // that must send the whole text, such as a refusal naming what the caller sent, or a log line, -// which has no cap (RedactLogAttr), uses this; everything stored uses SafeLogText. +// which has no cap (RedactLogAttr), uses this. What a conversation said, read back to the model, +// is stored with turnText; everything else stored uses SafeLogText. func RedactLogText(text string) string { if !mayHoldCredential(text) { return text diff --git a/acceleration/internal/store/migrate.go b/acceleration/internal/store/migrate.go index 8458fa0a7c..f5c6c27498 100644 --- a/acceleration/internal/store/migrate.go +++ b/acceleration/internal/store/migrate.go @@ -231,6 +231,10 @@ var usageIndexes = []struct{ set, name, create string }{ {"shard", "call_legs_token_hash_key", "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS call_legs_token_hash_key ON call_legs (token_hash)"}, {"shard", "call_legs_token_hash_placed_idx", "CREATE INDEX CONCURRENTLY IF NOT EXISTS call_legs_token_hash_placed_idx ON call_legs (placed_at) " + "WHERE token_hash IS NOT NULL"}, + // A session's log lines, newest first. + {"global", "agent_logs_session_order", "CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_logs_session_order ON agent_logs (customer_id, session_id, id DESC)"}, + // A campaign's attempts. + {"global", "campaign_attempts_campaign_idx", "CREATE INDEX CONCURRENTLY IF NOT EXISTS campaign_attempts_campaign_idx ON campaign_attempts (campaign_id)"}, // The queued image jobs of each kind, in the order a claim takes them. {"global", "image_jobs_undecided", "CREATE INDEX CONCURRENTLY IF NOT EXISTS image_jobs_undecided ON image_jobs (next_attempt_at, id) " + "WHERE state = 'queued' AND message = ''"}, diff --git a/acceleration/internal/store/migrate_test.go b/acceleration/internal/store/migrate_test.go index 4744afa97f..f6fba362ca 100644 --- a/acceleration/internal/store/migrate_test.go +++ b/acceleration/internal/store/migrate_test.go @@ -71,6 +71,32 @@ func (s *StoreSuite) ranHistory(name string, global, shard int64) *Store { return db } +func (s *StoreSuite) TestTheSessionLogAndCampaignAttemptIndexesStepBackAndForward() { + stepped := s.shardTo("stepped_indexes", math.MaxInt64) + defer stepped.Close() + versions, err := database.NewStore(database.DialectPostgres, globalSet.table) + s.Require().NoError(err) + provider, err := goose.NewProvider("", stepped.global.DB, globalSet.files, goose.WithStore(versions)) + s.Require().NoError(err) + built := func() (logs, attempts bool) { + s.Require().NoError(stepped.global.QueryRowContext(s.ctx, `SELECT to_regclass('agent_logs_session_order') IS NOT NULL, + to_regclass('campaign_attempts_campaign_idx') IS NOT NULL`).Scan(&logs, &attempts)) + return logs, attempts + } + + _, err = provider.ApplyVersion(s.ctx, 20270202000000, false) + s.Require().NoError(err) + logs, attempts := built() + s.False(logs, "the session log index is gone") + s.False(attempts, "the campaign attempt index is gone") + + _, err = provider.ApplyVersion(s.ctx, 20270202000000, true) + s.Require().NoError(err) + logs, attempts = built() + s.True(logs) + s.True(attempts) +} + // Every database deployed before the squash ran the whole history, so it holds the initial // migration's schema and starts as it is. func (s *StoreSuite) TestADatabaseThatRanTheSquashedHistoryStartsAsItIs() { diff --git a/acceleration/internal/store/pins.go b/acceleration/internal/store/pins.go index a1ef3b3b92..2441b43e87 100644 --- a/acceleration/internal/store/pins.go +++ b/acceleration/internal/store/pins.go @@ -169,15 +169,20 @@ func (s *Store) BackfillStreamPins(ctx context.Context, deployment int64) (map[s db = s.global } for { + // By id, which a row keeps when another writer changes it mid-statement, where its + // ctid would be new and the row skipped. The second IS NULL leaves a row that writer + // pinned as it is. result, err := db.ExecContext(ctx, fmt.Sprintf( - "UPDATE %[1]s SET %[2]s = ? WHERE ctid IN (SELECT ctid FROM %[1]s WHERE %[2]s IS NULL LIMIT ?)", + "UPDATE %[1]s SET %[2]s = ? WHERE id IN (SELECT id FROM %[1]s WHERE %[2]s IS NULL LIMIT ?) AND %[2]s IS NULL", table, pinColumn), deployment, backfillBatch) if err != nil { return pinned, fmt.Errorf("store: backfill %s: %w", table, err) } written, _ := result.RowsAffected() pinned[table] += written - if written < backfillBatch { + // A batch is short when another writer pinned some of its rows meanwhile, so only + // an empty one is the last. + if written == 0 { break } } diff --git a/acceleration/internal/store/response.go b/acceleration/internal/store/response.go index 8c81a0ada1..4555dd06d1 100644 --- a/acceleration/internal/store/response.go +++ b/acceleration/internal/store/response.go @@ -141,7 +141,9 @@ func (r *Responses) Insert(ctx context.Context, response *AgentResponse) error { if response.QuestionResponseID == "" { response.QuestionResponseID = response.ID } - response.Said = SafeLogText(response.Said) + // What was asked is the conversation, read back to the model when it is carried on, so it + // is kept whole, up to maxTurnText. + response.Said = turnText(response.Said) // The update sets nothing new: it tells a retry, which matches its own row, from an id // another customer's row has, which matches none. diff --git a/acceleration/internal/store/response_item.go b/acceleration/internal/store/response_item.go index 59cd8de564..aef42f0843 100644 --- a/acceleration/internal/store/response_item.go +++ b/acceleration/internal/store/response_item.go @@ -141,7 +141,14 @@ func (r *ResponseItems) InsertMany(ctx context.Context, items []AgentResponseIte if err := items[i].Validate(); err != nil { return stack.Wrap(err) } - items[i].Text = SafeLogText(items[i].Text) + // What was said is the conversation, read back to the model when it is carried on, so + // it is kept whole, up to maxTurnText. A tool's output and an error are cut as a log line is. + switch items[i].Kind { + case ItemSaid, ItemThought, ItemAnswer: + items[i].Text = turnText(items[i].Text) + default: + items[i].Text = SafeLogText(items[i].Text) + } if items[i].At.IsZero() { items[i].At = time.Now().UTC() } diff --git a/acceleration/internal/store/scheduled_task.go b/acceleration/internal/store/scheduled_task.go index cbcfefe5ba..b28abf6aa7 100644 --- a/acceleration/internal/store/scheduled_task.go +++ b/acceleration/internal/store/scheduled_task.go @@ -864,11 +864,12 @@ func (r *ScheduledTasks) Postpone(ctx context.Context, customerID, taskID, runID return held, nil } -// Renew extends a claim the worker still holds. False is a -// claim it no longer holds: an update, pause or delete took it. +// Renew extends a claim the worker still holds, never to earlier than it is: a renewal still +// on its way when Postpone held the task for quiet hours would cut the hold to one lease. +// False is a claim it no longer holds: an update, pause or delete took it. func (r *ScheduledTasks) Renew(ctx context.Context, customerID, taskID, leasedBy string, lease time.Duration) (bool, error) { result, err := r.store.global.NewUpdate().Model((*ScheduledTask)(nil)). - Set("lease_until = now() + make_interval(secs => ?)", lease.Seconds()). + Set("lease_until = GREATEST(lease_until, now() + make_interval(secs => ?))", lease.Seconds()). Where("customer_id = ?", customerID). Where("id = ?", taskID). Where("leased_by = ?", leasedBy). diff --git a/acceleration/internal/store/scheduled_task_test.go b/acceleration/internal/store/scheduled_task_test.go index fa32feca74..6c77b06852 100644 --- a/acceleration/internal/store/scheduled_task_test.go +++ b/acceleration/internal/store/scheduled_task_test.go @@ -293,6 +293,27 @@ func (s *StoreSuite) TestQuietHoursRoundTrip() { s.Equal("07:00", found.QuietHours.End) } +func (s *StoreSuite) TestARenewalAfterAHoldDoesNotCutItShort() { + due := s.base.Add(-time.Minute) + s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + until := time.Now().Add(2 * time.Hour) + held, err := s.store.ScheduledTasks.Postpone(s.ctx, "acme", "one", claimed[0].Run.ID, claimed[0].LeasedBy, until) + s.Require().NoError(err) + s.Require().True(held) + + held, err = s.store.ScheduledTasks.Renew(s.ctx, "acme", "one", claimed[0].LeasedBy, time.Minute) + s.Require().NoError(err) + s.True(held, "the claim is still the worker's") + + task, err := s.store.ScheduledTasks.Get(s.ctx, "acme", "one") + s.Require().NoError(err) + s.Require().NotNil(task.LeaseUntil) + s.WithinDuration(until, *task.LeaseUntil, time.Second, "the hold outlasts the renewal's minute") +} + func (s *StoreSuite) TestAPostponedTaskIsHeldUnderItsClaimUntilTheHoldEnds() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index 3872f1bbe1..b9aece6e8d 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -9,6 +9,7 @@ import ( "strings" "sync" "time" + "unicode/utf8" "github.com/uptrace/bun" ) @@ -540,6 +541,18 @@ func (s *StoreSuite) TestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpen() { s.Empty(found.Title) } +func (s *StoreSuite) TestAWriteThatChangesNothingIsRefusedOnlyForAnotherCustomersID() { + late, again := s.base.Add(time.Hour), s.base.Add(2*time.Hour) + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = again }) + write := func(customerID string) error { + return s.store.Sessions.Upsert(s.ctx, &AgentSession{ID: "one", CustomerID: customerID, AgentName: "docs", + ConfigID: "cfg-docs", UserID: "jlahey", CallerKind: "user", State: SessionRunning, CreatedAt: s.base, OpenedAt: late}) + } + + s.NoError(write("app"), "a late write of the app's own session is no refusal") + s.ErrorIs(write("somebody-else"), ErrIDTaken, "the same write under another customer is") +} + func (s *StoreSuite) TestDescribingASessionLongAfterItEnded() { s.opened("one", "app", s.base, nil) s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, s.base.Add(time.Hour), "")) @@ -1587,3 +1600,76 @@ func (s *StoreSuite) TestAnotherCustomersToolsForASessionIdAreNotKept() { }) } } + +func (s *StoreSuite) TestAnIdAnotherCustomersSessionHasIsNotWrittenOver() { + s.opened("one", "app", s.base, func(session *AgentSession) { + session.Title, session.State, session.ClosedAt = "theirs to keep", SessionClosed, &s.base + }) + before, err := s.store.Sessions.Get(s.ctx, "app", "one") + s.Require().NoError(err) + + err = s.store.Sessions.Upsert(s.ctx, &AgentSession{ + ID: "one", CustomerID: "somebody-else", AgentName: "docs", ConfigID: "cfg-docs", UserID: "randy", + CallerKind: "user", State: SessionRunning, Title: "taken over", CreatedAt: s.base, + }) + s.Require().ErrorIs(err, ErrIDTaken) + + after, err := s.store.Sessions.Get(s.ctx, "app", "one") + s.Require().NoError(err) + s.Equal(before, after, "app's session is as it was, still ended") +} + +func (s *StoreSuite) TestWhatWasSaidIsKeptWholeAndAToolResultIsCut() { + s.opened("one", "app", s.base, nil) + secret := strings.Repeat("q7", 12) + long := strings.Repeat("Stream ships chat, video and feeds. ", 400) + "my password: " + secret + s.Require().NoError(s.store.Responses.Insert(s.ctx, &AgentResponse{ + ID: "first", SessionID: "one", CustomerID: "app", Said: long, CreatedAt: s.base, + })) + items := []AgentResponseItem{} + for i, kind := range []string{ItemSaid, ItemThought, ItemAnswer, ItemToolResult, ItemError} { + items = append(items, AgentResponseItem{ResponseID: "first", Ordinal: i, SessionID: "one", Kind: kind, Text: long, At: s.base}) + } + s.Require().NoError(s.store.ResponseItems.InsertMany(s.ctx, items)) + + response, err := s.store.Responses.Get(s.ctx, "app", "one", "first") + s.Require().NoError(err) + kept, err := s.store.ResponseItems.Select(s.ctx, "app", "one", ItemFilter{}) + s.Require().NoError(err) + s.Require().Len(kept, 5) + for name, text := range map[string]string{"the question asked again": response.Said, "the question": kept[0].Text, + "the thought": kept[1].Text, "the answer": kept[2].Text} { + s.Equal(400, strings.Count(text, "Stream ships chat, video and feeds. "), "%s is kept whole", name) + s.Contains(text, "my [redacted]", "%s is redacted where the credential was", name) + s.NotContains(text, secret, "%s keeps no credential", name) + } + for name, text := range map[string]string{"a tool's output": kept[3].Text, "an error": kept[4].Text} { + s.True(strings.HasSuffix(text, truncatedMarker), "%s is cut as a log line is", name) + s.LessOrEqual(utf8.RuneCountInString(text), 2048+utf8.RuneCountInString(truncatedMarker), name) + } +} + +func (s *StoreSuite) TestATurnPastTheCeilingIsCutWithTheMarker() { + s.opened("one", "app", s.base, nil) + // One byte ahead, so the ceiling falls inside a two-byte rune. + huge := "a" + strings.Repeat("é", maxTurnText) + s.Require().NoError(s.store.Responses.Insert(s.ctx, &AgentResponse{ + ID: "first", SessionID: "one", CustomerID: "app", Said: huge, CreatedAt: s.base, + })) + s.Require().NoError(s.store.ResponseItems.InsertMany(s.ctx, []AgentResponseItem{ + {ResponseID: "first", SessionID: "one", Kind: ItemAnswer, Text: huge, At: s.base}, + })) + + response, err := s.store.Responses.Get(s.ctx, "app", "one", "first") + s.Require().NoError(err) + kept, err := s.store.ResponseItems.Select(s.ctx, "app", "one", ItemFilter{}) + s.Require().NoError(err) + s.Require().Len(kept, 1) + for name, text := range map[string]string{"the question": response.Said, "the answer": kept[0].Text} { + s.LessOrEqual(len(text), maxTurnText+len(truncatedMarker), name) + // 256 KiB, the last rune boundary before it, then the marker. + s.Equal(256<<10-1+len(truncatedMarker), len(text), "%s is cut at 256 KiB", name) + s.True(strings.HasSuffix(text, truncatedMarker), name) + s.True(utf8.ValidString(text), "%s is cut between runes", name) + } +} diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index caeac4b1b3..5985ab855a 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -625,7 +625,7 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { _, err := store.AgentLogs.Select(ctx, "customer-7", AgentLogFilter{Severity: "error", After: 1000, Forward: true}) return err }}, - {name: "AgentLogs.Select of a session", index: "agent_logs_customer_order", run: func(ctx context.Context, store *Store) error { + {name: "AgentLogs.Select of a session", index: "agent_logs_session_order", run: func(ctx context.Context, store *Store) error { _, err := store.AgentLogs.Select(ctx, "customer-7", AgentLogFilter{SessionID: "seeded-session-7", UserID: "user-7", Sources: []string{"agent"}, Search: "request"}) return err diff --git a/acceleration/internal/store/store_test.go b/acceleration/internal/store/store_test.go index 122ffa6c79..dd6fe7a390 100644 --- a/acceleration/internal/store/store_test.go +++ b/acceleration/internal/store/store_test.go @@ -522,6 +522,42 @@ func (s *StoreSuite) TestMigrateRebuildsTheContactIndexLeftInvalid() { s.True(valid, "dropped and built again") } +func (s *StoreSuite) TestMigrateRebuildsTheSessionLogIndexLeftInvalid() { + // As a CONCURRENTLY build that failed leaves it: the migration's IF NOT EXISTS skips it. + _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE pg_index SET indisvalid = false WHERE indexrelid = to_regclass('agent_logs_session_order')") + s.Require().NoError(err) + var valid bool + read := func() { + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT indisvalid FROM pg_index WHERE indexrelid = to_regclass('agent_logs_session_order')").Scan(&valid)) + } + read() + s.Require().False(valid) + + s.Require().NoError(s.store.Migrate(s.ctx)) + + read() + s.True(valid, "dropped and built again") +} + +func (s *StoreSuite) TestMigrateRebuildsTheCampaignAttemptIndexLeftInvalid() { + // As a CONCURRENTLY build that failed leaves it: the migration's IF NOT EXISTS skips it. + _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE pg_index SET indisvalid = false WHERE indexrelid = to_regclass('campaign_attempts_campaign_idx')") + s.Require().NoError(err) + var valid bool + read := func() { + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT indisvalid FROM pg_index WHERE indexrelid = to_regclass('campaign_attempts_campaign_idx')").Scan(&valid)) + } + read() + s.Require().False(valid) + + s.Require().NoError(s.store.Migrate(s.ctx)) + + read() + s.True(valid, "dropped and built again") +} + func (s *StoreSuite) TestMigrateRebuildsTheResponseParentIndexLeftInvalid() { // As a CONCURRENTLY build that failed leaves it: the migration's IF NOT EXISTS skips it. s.onShard("UPDATE pg_index SET indisvalid = false WHERE indexrelid = to_regclass('agent_responses_parent_idx')") diff --git a/acceleration/migrations/global/20270202000000_log_session_and_attempt_campaign_idx.sql b/acceleration/migrations/global/20270202000000_log_session_and_attempt_campaign_idx.sql new file mode 100644 index 0000000000..63a51d3e00 --- /dev/null +++ b/acceleration/migrations/global/20270202000000_log_session_and_attempt_campaign_idx.sql @@ -0,0 +1,17 @@ +-- +goose NO TRANSACTION +-- +goose Up + +-- A session's log lines, newest first (AgentLogs.Select with a session): on +-- agent_logs_customer_order a session with fewer lines than the page walked every line the +-- customer ever logged before it could stop. +-- A campaign's attempts, which the cascade of a campaign's delete read by scanning every +-- campaign's. +-- Built without stopping writes; a build that fails is built again in Go (store.usageIndexes). +CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_logs_session_order + ON agent_logs (customer_id, session_id, id DESC); +CREATE INDEX CONCURRENTLY IF NOT EXISTS campaign_attempts_campaign_idx + ON campaign_attempts (campaign_id); + +-- +goose Down +DROP INDEX CONCURRENTLY IF EXISTS campaign_attempts_campaign_idx; +DROP INDEX CONCURRENTLY IF EXISTS agent_logs_session_order; diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index 3839d31efe..c98983e78c 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -81,6 +81,7 @@ TABLE agent_logs CREATE INDEX agent_logs_config_order ON public.agent_logs USING btree (customer_id, config_id, id DESC) CREATE INDEX agent_logs_customer_order ON public.agent_logs USING btree (customer_id, id DESC) CREATE INDEX agent_logs_error_order ON public.agent_logs USING btree (customer_id, severity, id DESC) + CREATE INDEX agent_logs_session_order ON public.agent_logs USING btree (customer_id, session_id, id DESC) CREATE UNIQUE INDEX agent_logs_source_idx ON public.agent_logs USING btree (customer_id, source_id) WHERE (source_id IS NOT NULL) TABLE api_keys @@ -190,6 +191,7 @@ TABLE campaign_attempts CONSTRAINT campaign_attempts_campaign_id_fkey FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON DELETE CASCADE CONSTRAINT campaign_attempts_contact_id_fkey FOREIGN KEY (contact_id) REFERENCES campaign_contacts(id) ON DELETE CASCADE CONSTRAINT campaign_attempts_pkey PRIMARY KEY (id) + CREATE INDEX campaign_attempts_campaign_idx ON public.campaign_attempts USING btree (campaign_id) CREATE INDEX campaign_attempts_classify_idx ON public.campaign_attempts USING btree (classify_after) WHERE (classify_state = 'pending'::text) CREATE INDEX campaign_attempts_contact_idx ON public.campaign_attempts USING btree (contact_id, started_at) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/create_opt_out_request.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/create_opt_out_request.py index d8f2fe8b9c..3f90334969 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/create_opt_out_request.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/create_opt_out_request.py @@ -19,7 +19,7 @@ class CreateOptOutRequest: """ Attributes: channel (OptOutChannel): The channel a recipient opted out of, or all of them. - recipient (str): The number, in E.164. + recipient (str): The number in E.164, or an iMessage handle's email address, for channel imessage or all. source (CreateOptOutRequestSource | Unset): Omitted is api. """ diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/opt_out.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/opt_out.py index b0a142b2a9..a06b834a9c 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/opt_out.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/opt_out.py @@ -22,7 +22,7 @@ class OptOut: channel (OptOutChannel): The channel a recipient opted out of, or all of them. created_at (datetime.datetime): id (str): - recipient (str): The number, in E.164. + recipient (str): The number in E.164, or an iMessage handle's email address. source (str): keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard. """ diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index 26384fc7bc..07674bab16 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -6401,7 +6401,7 @@ public partial class CreateOptOutRequest public string Channel { get; set; } = default!; /// - /// The number, in E.164. + /// The number in E.164, or an iMessage handle's email address, for channel imessage or all. /// [System.Text.Json.Serialization.JsonPropertyName("recipient")] public string Recipient { get; set; } = default!; @@ -10421,7 +10421,7 @@ public partial class OptOut public string Id { get; set; } = default!; /// - /// The number, in E.164. + /// The number in E.164, or an iMessage handle's email address. /// [System.Text.Json.Serialization.JsonPropertyName("recipient")] public string Recipient { get; set; } = default!; diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 814f56897f..741146ef59 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -6216,7 +6216,7 @@ type CreateOptOutRequest struct { // Channel The channel a recipient opted out of, or all of them. Channel OptOutChannel `json:"channel"` - // Recipient The number, in E.164. + // Recipient The number in E.164, or an iMessage handle's email address, for channel imessage or all. Recipient string `json:"recipient"` // Source Omitted is api. @@ -8045,7 +8045,7 @@ type OptOut struct { CreatedAt time.Time `json:"created_at"` Id string `json:"id"` - // Recipient The number, in E.164. + // Recipient The number in E.164, or an iMessage handle's email address. Recipient string `json:"recipient"` // Source keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard. diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index c9d6a1e41b..b25612dc08 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -6970,7 +6970,7 @@ export type components = { }; readonly CreateOptOutRequest: { readonly channel: components["schemas"]["OptOutChannel"]; - /** @description The number, in E.164. */ + /** @description The number in E.164, or an iMessage handle's email address, for channel imessage or all. */ readonly recipient: string; /** * @description Omitted is api. @@ -8641,7 +8641,7 @@ export type components = { /** Format: date-time */ readonly created_at: string; readonly id: string; - /** @description The number, in E.164. */ + /** @description The number in E.164, or an iMessage handle's email address. */ readonly recipient: string; /** @description keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard. */ readonly source: string; diff --git a/sdks/php/src/Generated/CreateOptOutRequest.php b/sdks/php/src/Generated/CreateOptOutRequest.php index 578cb36055..893dc6af07 100644 --- a/sdks/php/src/Generated/CreateOptOutRequest.php +++ b/sdks/php/src/Generated/CreateOptOutRequest.php @@ -12,7 +12,7 @@ { public function __construct( public OptOutChannel|string $channel, - // The number, in E.164. + // The number in E.164, or an iMessage handle's email address, for channel imessage or all. public string $recipient, // Omitted is api. public ?string $source = null, diff --git a/sdks/php/src/Generated/OptOut.php b/sdks/php/src/Generated/OptOut.php index 8789b53c0b..111f01fb8e 100644 --- a/sdks/php/src/Generated/OptOut.php +++ b/sdks/php/src/Generated/OptOut.php @@ -18,7 +18,7 @@ public function __construct( public OptOutChannel|string $channel, public \DateTimeImmutable $createdAt, public string $id, - // The number, in E.164. + // The number in E.164, or an iMessage handle's email address. public string $recipient, // keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or... public string $source, diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index d219f19fd3..2643812211 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -4891,7 +4891,7 @@ pub struct CostSource { #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] pub struct CreateOptOutRequest { pub channel: OptOutChannel, - ///The number, in E.164. + ///The number in E.164, or an iMessage handle's email address, for channel imessage or all. pub recipient: ::std::string::String, ///Omitted is api. #[serde(skip_serializing_if = "::std::option::Option::is_none")] @@ -8786,7 +8786,7 @@ pub struct OptOut { pub channel: OptOutChannel, pub created_at: ::std::string::String, pub id: ::std::string::String, - ///The number, in E.164. + ///The number in E.164, or an iMessage handle's email address. pub recipient: ::std::string::String, ///keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard. pub source: ::std::string::String,