From 07ec2b336fcc652eaeb0496aef70a2ae688cd3a0 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 19:54:26 +0100 Subject: [PATCH 01/11] AI-3537: stop recording when an API key was last used api_keys.last_used_at was written up to once a minute per key and read only to throttle that write. The write, its throttle and the model field go; the column stays until a later migration drops it. --- acceleration/internal/store/api_key.go | 38 --------------------- acceleration/internal/store/api_key_test.go | 30 ---------------- 2 files changed, 68 deletions(-) diff --git a/acceleration/internal/store/api_key.go b/acceleration/internal/store/api_key.go index 5b7dd394f4..8f4be3fbc3 100644 --- a/acceleration/internal/store/api_key.go +++ b/acceleration/internal/store/api_key.go @@ -5,8 +5,6 @@ import ( "database/sql" "errors" "fmt" - "log/slog" - "sync" "time" "github.com/uptrace/bun" @@ -32,7 +30,6 @@ type APIKey struct { CreatedAt time.Time `bun:"created_at,notnull"` CreatedBy string `bun:"created_by,notnull"` ExpiresAt *time.Time `bun:"expires_at"` - LastUsedAt *time.Time `bun:"last_used_at"` RevokedAt *time.Time `bun:"revoked_at"` RevokedBy string `bun:"revoked_by,notnull"` } @@ -67,18 +64,10 @@ type APIKeyOwner struct { ExpiresAt *time.Time `bun:"expires_at"` } -// KeyUseInterval throttles how often a key's use is recorded. Writing on every request -// would double the writes of a busy key, and recording nothing means nobody can answer -// whether a key is still in use, so nobody ever revokes one. -const KeyUseInterval = time.Minute - // APIKeys are the apps' credentials, in the shared database. The owner of a live key is read // on every authenticated request, so it is cached by key id. type APIKeys struct { store *Store - // touched is when this process last recorded each key's use, keyed by key id. It is per - // process rather than shared because it guards a write nobody reads in anger. - touched sync.Map } // Insert stores a credential and fills in its timestamp. A fresh id is one nothing can have @@ -129,27 +118,6 @@ func (r *APIKeys) GetLive(ctx context.Context, id string) (APIKeyOwner, error) { return owner, nil } -// Touch records that a key was used, but only when the last record is older than interval. -// This process remembers what it last wrote, so the common case is no query at all; the -// query refuses an older record too, for the other replicas' writes. -func (r *APIKeys) Touch(ctx context.Context, id string, interval time.Duration) error { - now := time.Now().UTC() - if last, ok := r.touched.Load(id); ok && now.Sub(last.(time.Time)) < interval { - return nil - } - r.touched.Store(id, now) - _, err := r.store.global.NewUpdate().Model((*APIKey)(nil)). - Set("last_used_at = ?", now). - Where("id = ?", id). - Where("last_used_at IS NULL OR last_used_at < ?", now.Add(-interval)). - Exec(ctx) - if err != nil { - r.touched.Delete(id) - return stack.Wrap(fmt.Errorf("store: touch api key: %w", err)) - } - return nil -} - // Revoke stops one of an app's keys working, here and on every other replica. A key of // another app is ErrNoAPIKey. The row survives, because the audit trail of which key made // which call has to outlive the key. told says whether the replicas' cached copy was @@ -177,9 +145,6 @@ func (r *APIKeys) Revoke(ctx context.Context, appID, id, by string) (told bool, } return []string{cacheKey("key", id)} }) - if affected > 0 { - r.touched.Delete(id) - } if err != nil { return false, stack.Wrap(fmt.Errorf("store: revoke api key: %w", err)) } @@ -224,9 +189,6 @@ func (r *APIKeys) Lookup(sealer *auth.Sealer) auth.Lookup { if err != nil { return auth.App{}, stack.Wrap(fmt.Errorf("store: unseal key %s: %w", key, err)) } - if err := r.Touch(ctx, key, KeyUseInterval); err != nil { - slog.Default().Debug("could not record key use", "key", key, "error", err) - } // The app's settings came back on the same row, so which levels of end user it // admits costs nothing beyond the lookup that was already happening. They are // inverted on the way across because auth measures a caller against a zero value diff --git a/acceleration/internal/store/api_key_test.go b/acceleration/internal/store/api_key_test.go index 2afd6311bb..07a6e7ad44 100644 --- a/acceleration/internal/store/api_key_test.go +++ b/acceleration/internal/store/api_key_test.go @@ -96,30 +96,6 @@ func (s *StoreSuite) TestAnAppKeepsSeveralLiveKeysSoRotationIsNotAnOutage() { } } -func (s *StoreSuite) TestKeyUseIsRecordedOncePerIntervalRatherThanPerRequest() { - app := s.app() - s.key(app.ID, "vak_live_3333333333333333e00d6c93", nil) - - s.Require().NoError(s.store.APIKeys.Touch(s.ctx, "vak_live_3333333333333333e00d6c93", time.Minute)) - keys, err := s.store.APIKeys.Select(s.ctx, app.ID) - s.Require().NoError(err) - s.Require().NotNil(keys[0].LastUsedAt) - first := *keys[0].LastUsedAt - - // A second use inside the interval is not written, because a synchronous update on - // every request would double the writes of a busy key. - s.Require().NoError(s.store.APIKeys.Touch(s.ctx, "vak_live_3333333333333333e00d6c93", time.Minute)) - keys, err = s.store.APIKeys.Select(s.ctx, app.ID) - s.Require().NoError(err) - s.Equal(first, *keys[0].LastUsedAt) - - // Once the interval has passed it is written again. - s.Require().NoError(s.store.APIKeys.Touch(s.ctx, "vak_live_3333333333333333e00d6c93", 0)) - keys, err = s.store.APIKeys.Select(s.ctx, app.ID) - s.Require().NoError(err) - s.True(keys[0].LastUsedAt.After(first)) -} - func (s *StoreSuite) TestAKeyRevokedOnOneReplicaStopsWorkingOnTheOther() { replica := s.replica() app := s.app() @@ -221,9 +197,6 @@ func (s *StoreSuite) TestALookupResolvesAKeyToItsAppAndTheEndUsersItAdmits() { OrganizationID: app.OrganizationID, AppID: app.ID, Secret: secret, Levels: auth.Levels{NoGuest: true}, }, resolved) - keys, err := s.store.APIKeys.Select(s.ctx, app.ID) - s.Require().NoError(err) - s.NotNil(keys[0].LastUsedAt, "its use is recorded") unissued, _, err := auth.NewCredential(auth.Live) s.Require().NoError(err) @@ -242,9 +215,6 @@ func (s *StoreSuite) TestAPIKeyQueryBudgets() { _, err := s.store.APIKeys.Select(s.ctx, app.ID) s.Require().NoError(err) })) - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.APIKeys.Touch(s.ctx, key.ID, time.Hour)) })) - s.Equal(0, s.countQueries(func() { s.Require().NoError(s.store.APIKeys.Touch(s.ctx, key.ID, time.Hour)) }), - "a use inside the interval is not written") s.Equal(0, s.countQueries(func() { _, err := s.store.APIKeys.Lookup(nil)(s.ctx, "not-a-key") s.ErrorIs(err, auth.ErrUnauthenticated) From d4655b12dfa2ebd2717ddff1ffd2e6783b7cbc9b Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 19:55:22 +0100 Subject: [PATCH 02/11] AI-3537: drop the TLS scheme no connection is created with connector_connections.tls_scheme was validated on insert and set by no caller. The model field and its two checks go; the column stays until a later migration drops it. --- .../internal/store/connector_connection.go | 13 ++------ .../store/connector_connection_test.go | 30 ------------------- .../store/connector_connection_unit_test.go | 10 ------- 3 files changed, 2 insertions(+), 51 deletions(-) diff --git a/acceleration/internal/store/connector_connection.go b/acceleration/internal/store/connector_connection.go index c2d0df812a..79f811df48 100644 --- a/acceleration/internal/store/connector_connection.go +++ b/acceleration/internal/store/connector_connection.go @@ -86,10 +86,8 @@ type ConnectorConnection struct { DefinitionRevision int `bun:"definition_revision,notnull"` OwnerType string `bun:"owner_type,notnull"` OwnerID string `bun:"owner_id,notnull"` - // AuthScheme and TLSScheme are names in the scheme registry. TLSScheme is empty when the - // transport needs no client certificate. + // AuthScheme is a name in the scheme registry. AuthScheme string `bun:"auth_scheme,notnull"` - TLSScheme string `bun:"tls_scheme,nullzero"` // Inputs are what the connection was created with; Metadata what consent captured. Inputs map[string]string `bun:"inputs,type:jsonb,notnull"` Metadata map[string]string `bun:"metadata,type:jsonb,notnull"` @@ -190,7 +188,7 @@ type ConnectorConnections struct { } // Insert records a new connection, pending until credentials are saved -// onto it. Its schemes must be in registry and listed by the definition revision it pins, which +// onto it. Its scheme must be in registry and listed by the definition revision it pins, which // must be one the customer can see. The registry is passed in rather than held by the store, so which // schemes exist is decided by whoever built it, and a test can register its own. func (r *ConnectorConnections) Insert(ctx context.Context, registry core.Registry, connection *ConnectorConnection) error { @@ -202,9 +200,6 @@ func (r *ConnectorConnections) Insert(ctx context.Context, registry core.Registr if _, found := registry.Schemes[connection.AuthScheme]; !found { return stack.Wrap(fmt.Errorf("%w: auth scheme %q", ErrUnregisteredScheme, connection.AuthScheme)) } - if _, found := registry.Schemes[connection.TLSScheme]; connection.TLSScheme != "" && !found { - return stack.Wrap(fmt.Errorf("%w: tls scheme %q", ErrUnregisteredScheme, connection.TLSScheme)) - } // The stored credentials' AAD binds the connection id, which does not exist until this returns. if len(connection.CredentialsSealed) > 0 { return stack.Wrap(errors.New("store: credentials are saved onto a connection after it exists, not with it")) @@ -229,10 +224,6 @@ func (r *ConnectorConnections) Insert(ctx context.Context, registry core.Registr return fmt.Errorf("%w: %s revision %d does not list auth scheme %q", ErrSchemeNotAllowed, connection.ConnectorID, connection.DefinitionRevision, connection.AuthScheme) } - if connection.TLSScheme != "" && !slices.Contains(definition.Manifest.Schemes, connection.TLSScheme) { - return fmt.Errorf("%w: %s revision %d does not list tls scheme %q", ErrSchemeNotAllowed, - connection.ConnectorID, connection.DefinitionRevision, connection.TLSScheme) - } // Truncated to what Postgres keeps, so the row handed back is the row a read returns. now := time.Now().UTC().Truncate(time.Microsecond) connection.ID = newID() diff --git a/acceleration/internal/store/connector_connection_test.go b/acceleration/internal/store/connector_connection_test.go index ce012b0a8a..27e37011bf 100644 --- a/acceleration/internal/store/connector_connection_test.go +++ b/acceleration/internal/store/connector_connection_test.go @@ -73,7 +73,6 @@ func (s *StoreSuite) TestACreatedConnectionIsPendingAtRevisionOneWithNoCredentia s.Equal(OwnerApp, found.OwnerType) s.Empty(found.OwnerID) s.Equal("test_key", found.AuthScheme) - s.Empty(found.TLSScheme) s.Equal(map[string]string{"region": "eu"}, found.Inputs) s.Equal(map[string]string{}, found.Metadata) s.Equal("Support workspace", found.Label) @@ -86,24 +85,6 @@ func (s *StoreSuite) TestACreatedConnectionIsPendingAtRevisionOneWithNoCredentia s.Nil(found.DeletedAt) } -func (s *StoreSuite) TestATLSSchemeIsStoredBesideTheAuthScheme() { - created := s.connection("acme-app", func(connection *ConnectorConnection) { connection.TLSScheme = "test_mtls" }) - - found, err := s.store.ConnectorConnections.Get(s.ctx, "acme-app", created.ID) - s.Require().NoError(err) - s.Equal("test_mtls", found.TLSScheme) - - var stored *string - s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, - "SELECT tls_scheme FROM connector_connections WHERE id = ?", created.ID).Scan(&stored)) - s.Require().NotNil(stored) - - plain := s.connection("acme-app", nil) - s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, - "SELECT tls_scheme FROM connector_connections WHERE id = ?", plain.ID).Scan(&stored)) - s.Nil(stored, "no TLS scheme is NULL, not an empty name") -} - func (s *StoreSuite) TestARegisteredAuthSchemeItsConnectorDoesNotListIsRefused() { s.seed(acmeManifest) connection := appConnection() @@ -115,17 +96,6 @@ func (s *StoreSuite) TestARegisteredAuthSchemeItsConnectorDoesNotListIsRefused() s.ErrorContains(err, `acme revision 1 does not list auth scheme "test_unlisted"`) } -func (s *StoreSuite) TestARegisteredTLSSchemeItsConnectorDoesNotListIsRefused() { - s.seed(acmeManifest) - connection := appConnection() - connection.TLSScheme = "test_unlisted" - - err := s.store.ConnectorConnections.Insert(s.ctx, testSchemes, connection) - - s.ErrorIs(err, ErrSchemeNotAllowed) - s.ErrorContains(err, `acme revision 1 does not list tls scheme "test_unlisted"`) -} - func (s *StoreSuite) TestTheDatabaseRefusesAnAppOwnedConnectionNamingAUser() { s.ErrorContains(s.insertRaw(OwnerApp, "alice"), "connector_connections_owner") } diff --git a/acceleration/internal/store/connector_connection_unit_test.go b/acceleration/internal/store/connector_connection_unit_test.go index 65b45f2615..96871a40d6 100644 --- a/acceleration/internal/store/connector_connection_unit_test.go +++ b/acceleration/internal/store/connector_connection_unit_test.go @@ -108,16 +108,6 @@ func TestAConnectionIsNotCreatedWithAProviderUnit(t *testing.T) { require.ErrorContains(t, err, "a provider unit is set on a connection after consent") } -func TestAConnectionWithAnUnregisteredTLSSchemeIsRefused(t *testing.T) { - connection := appConnection() - connection.TLSScheme = "mtls" - - err := (&Store{}).ConnectorConnections.Insert(context.Background(), testSchemes, connection) - - require.ErrorIs(t, err, ErrUnregisteredScheme) - require.ErrorContains(t, err, `tls scheme "mtls"`) -} - func TestAnEmptyRegistryRegistersNoScheme(t *testing.T) { err := (&Store{}).ConnectorConnections.Insert(context.Background(), core.Registry{}, appConnection()) From fdac9e3c546af3477c0828966cb63a58ece96bc4 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 19:56:33 +0100 Subject: [PATCH 03/11] AI-3537: stop copying the vendor call id onto the contact campaign_contacts.vendor_call_id was written on every settle and read by nothing: the dial's own row (campaign_attempts) is the copy that is read. The column stays until a later migration drops it. --- acceleration/internal/campaign/transition.go | 2 +- acceleration/internal/campaign/transition_test.go | 3 +-- acceleration/internal/store/campaign_contact.go | 12 +++++------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/campaign/transition.go b/acceleration/internal/campaign/transition.go index e123fc85d2..f8aa3bf885 100644 --- a/acceleration/internal/campaign/transition.go +++ b/acceleration/internal/campaign/transition.go @@ -60,7 +60,7 @@ func (d Dialed) answered() bool { // out or ended unknown writes nothing: the caller dials again at once. func afterDial(sequence Sequence, hours CallingHours, zone *time.Location, contact store.Contact, dial int, dialed Dialed, started, now time.Time) (settle store.Settle, dialAgain bool) { step := sequence.First() - settle = store.Settle{StepID: step.ID, Attempt: contact.Attempt, CallID: dialed.CallID, VendorCallID: dialed.VendorCallID} + settle = store.Settle{StepID: step.ID, Attempt: contact.Attempt, CallID: dialed.CallID} if dial == 2 && (dialed.Result == Deferred || dialed.Result == Paused || dialed.Result == Refused || dialed.Result == NotPlaced || dialed.Result == DialFailed) { // Dial 1 already rang the person, so the attempt is used whatever stopped dial 2. return unanswered(step, hours, zone, contact, started, settle), false diff --git a/acceleration/internal/campaign/transition_test.go b/acceleration/internal/campaign/transition_test.go index 26a0072c37..8447f1813e 100644 --- a/acceleration/internal/campaign/transition_test.go +++ b/acceleration/internal/campaign/transition_test.go @@ -61,7 +61,7 @@ func (s *TransitionSuite) TestAFirstDialWhoseSessionNeverOpenedUsesTheAttemptWit } func (s *TransitionSuite) TestNobodyAnsweringTheDoubleDialSchedulesTheNextAttemptAfterItsDelay() { - settle, again := afterDial(s.sequence(true), s.hours, s.chicago, s.contact(1), 2, Dialed{Outcome: outcome.NoAnswer, CallID: "c2", VendorCallID: "v2"}, s.at(2, 10, 0), s.at(2, 10, 3)) + settle, again := afterDial(s.sequence(true), s.hours, s.chicago, s.contact(1), 2, Dialed{Outcome: outcome.NoAnswer, CallID: "c2"}, s.at(2, 10, 0), s.at(2, 10, 3)) s.False(again) s.Equal(store.Enrolled, settle.Stage) s.Equal(2, settle.Attempt) @@ -69,7 +69,6 @@ func (s *TransitionSuite) TestNobodyAnsweringTheDoubleDialSchedulesTheNextAttemp s.Require().NotNil(settle.NextAttemptAt) s.True(s.at(5, 10, 0).Equal(*settle.NextAttemptAt), settle.NextAttemptAt.String()) s.Equal("c2", settle.CallID) - s.Equal("v2", settle.VendorCallID) } func (s *TransitionSuite) TestWithoutDoubleDialTheFirstUnansweredDialSchedulesTheNextAttempt() { diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index ee1d42df29..dd0767b0df 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -57,10 +57,9 @@ type Contact struct { Outcome string `bun:"outcome,notnull"` Converted bool `bun:"converted,notnull"` // CallID is the calls row of the last dial. - CallID string `bun:"call_id,nullzero"` - VendorCallID string `bun:"vendor_call_id,nullzero"` - Reason string `bun:"reason,nullzero"` - CreatedAt time.Time `bun:"created_at,notnull"` + CallID string `bun:"call_id,nullzero"` + Reason string `bun:"reason,nullzero"` + CreatedAt time.Time `bun:"created_at,notnull"` } // Validate refuses a contact nobody could be rung at. @@ -549,8 +548,8 @@ type Settle struct { Outcome string Converted bool Reason string - // CallID and VendorCallID are the last dial's; empty keeps the ones already stored. - CallID, VendorCallID string + // CallID is the last dial's; empty keeps the one already stored. + CallID string // LeaseUntil is the lease the owner's claim returned, which every claim and take-over sets // anew. Set, the contact settles only under that same lease: an owner is one process, and a // call that outlives its lease may find the contact taken over, settled and claimed again @@ -604,7 +603,6 @@ func (r *CampaignContacts) settleContact(ctx context.Context, owner, contactID s Set("outcome = ?", settle.Outcome). Set("converted = ?", settle.Converted). Set("call_id = COALESCE(?, cc.call_id)", nullable(settle.CallID)). - Set("vendor_call_id = COALESCE(?, cc.vendor_call_id)", nullable(settle.VendorCallID)). Set("leased_by = ''"). Set("lease_until = NULL"). Where("cp.id = cc.campaign_id"). From c0c7db3eb35f94fb76488bbd0b325d14be4c6be7 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 19:58:07 +0100 Subject: [PATCH 04/11] AI-3537: stop marking a dial converted campaign_attempts.converted was written when a dial was classified and read by nothing: the contact's own converted is what the analytics and the API read. The column stays until a later migration drops it. --- acceleration/internal/campaign/campaign.go | 2 +- acceleration/internal/store/campaign_attempt.go | 4 +--- acceleration/internal/store/campaign_contact.go | 2 -- acceleration/internal/store/campaign_contact_test.go | 6 ++---- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index 0b57853c86..277a287bbc 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -688,7 +688,7 @@ func (r *Runner) classify(ctx context.Context, claimed store.Classifying) error } settle.LeaseUntil = contact.LeaseUntil return r.store.CampaignContacts.ClassifyAndSettle(ctx, r.owner, - store.Classification{AttemptID: attempt.ID, Outcome: settle.Outcome, Converted: settle.Converted}, contact.ID, settle) + store.Classification{AttemptID: attempt.ID, Outcome: settle.Outcome}, contact.ID, settle) } // unanswered settles an answered call nobody spoke on like a dial nobody picked up: the next diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index 9a0df47735..0668123bbb 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -32,7 +32,6 @@ type CampaignAttempt struct { // happening, and for a dial that placed none. CallOutcome string `bun:"call_outcome,nullzero"` Outcome string `bun:"outcome,notnull"` - Converted bool `bun:"converted,notnull"` // ClassifyState is empty, pending, done or abandoned: whether an answered call's outcome // is still to be read from its transcript. Abandoned is one whose contact settled before // it was read. @@ -265,12 +264,11 @@ func (r *CampaignAttempts) PutOff(ctx context.Context, owner, attemptID string, // Classified records an answered dial's outcome. A dial deleted with its campaign, or no longer // pending because another runner read it or its contact settled, is nothing to record. -func (r *CampaignAttempts) Classified(ctx context.Context, attemptID, outcome string, converted bool) error { +func (r *CampaignAttempts) Classified(ctx context.Context, attemptID, outcome string, _ bool) error { _, err := r.store.global.NewUpdate().Model((*CampaignAttempt)(nil)). Set("classify_state = ?", classifyDone). Set("classify_after = NULL"). Set("outcome = ?", outcome). - Set("converted = ?", converted). Where("id = ?", attemptID). Where("classify_state = ?", classifyPending). Exec(ctx) diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index dd0767b0df..a5559524c9 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -653,7 +653,6 @@ func (r *CampaignContacts) settleContact(ctx context.Context, owner, contactID s type Classification struct { AttemptID string Outcome string - Converted bool } // ClassifyAndSettle records what an answered dial's transcript said and settles its contact, both @@ -668,7 +667,6 @@ func (r *CampaignContacts) ClassifyAndSettle(ctx context.Context, owner string, Set("classify_after = NULL"). Set("classify_state = ?", classifyDone). Set("outcome = ?", classification.Outcome). - Set("converted = ?", classification.Converted). Where("id = ?", classification.AttemptID). Where("classify_state = ?", classifyPending). Exec(ctx) diff --git a/acceleration/internal/store/campaign_contact_test.go b/acceleration/internal/store/campaign_contact_test.go index 53d963cdf4..3bf6d581f9 100644 --- a/acceleration/internal/store/campaign_contact_test.go +++ b/acceleration/internal/store/campaign_contact_test.go @@ -314,7 +314,6 @@ func (s *StoreSuite) TestAnAnsweredDialWaitsToBeClassifiedAndIsClaimedOnce() { s.Require().NoError(err) s.Equal("done", latest.ClassifyState) s.Equal("success", latest.Outcome) - s.True(latest.Converted) s.Equal(ContactCompleted, s.contactByNumber(campaign, "+15550001").Stage) later, err := s.store.CampaignAttempts.ClaimClassifications(s.ctx, "a", classifyAfter.Add(time.Hour), time.Minute, 10) s.Require().NoError(err) @@ -524,7 +523,6 @@ func (s *StoreSuite) TestALateClassificationChangesNothing() { byID[attempt.ID] = attempt } s.Equal("success", byID[latest.ID].Outcome) - s.True(byID[latest.ID].Converted) s.Equal("abandoned", byID[older.ID].ClassifyState) s.Empty(byID[older.ID].Outcome) } @@ -574,7 +572,7 @@ func (s *StoreSuite) TestAClassificationWhoseContactCannotSettleStaysPending() { _, err := s.store.CampaignAttempts.ClaimClassifications(s.ctx, "b", s.base, time.Minute, 10) s.Require().NoError(err) - err = s.store.CampaignContacts.ClassifyAndSettle(s.ctx, "a", Classification{AttemptID: attempt.ID, Outcome: "success", Converted: true}, + err = s.store.CampaignContacts.ClassifyAndSettle(s.ctx, "a", Classification{AttemptID: attempt.ID, Outcome: "success"}, claimed.Contact.ID, Settle{Stage: ContactCompleted, Attempt: 1, Outcome: "success", Converted: true}) s.ErrorIs(err, ErrNotLeaseHolder) @@ -593,7 +591,7 @@ func (s *StoreSuite) TestAClassificationAndItsContactSettleTogether() { _, err := s.store.CampaignAttempts.ClaimClassifications(s.ctx, "a", s.base, time.Minute, 10) s.Require().NoError(err) - s.Require().NoError(s.store.CampaignContacts.ClassifyAndSettle(s.ctx, "a", Classification{AttemptID: attempt.ID, Outcome: "success", Converted: true}, + s.Require().NoError(s.store.CampaignContacts.ClassifyAndSettle(s.ctx, "a", Classification{AttemptID: attempt.ID, Outcome: "success"}, claimed.Contact.ID, Settle{Stage: ContactCompleted, Attempt: 1, Outcome: "success", Converted: true})) latest, _, err := s.store.CampaignAttempts.Latest(s.ctx, claimed.Contact.ID) From 6225399e030c0f2f53fb1bac1c966d8af40e75c3 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 19:59:19 +0100 Subject: [PATCH 05/11] AI-3537: stop storing a recording's source and TTS options recordings.source and recordings.tts were written when a job was accepted and read by nothing: the job runs from the request it came in on. The columns stay until a later migration drops them. --- acceleration/internal/api/recordings.go | 2 -- acceleration/internal/store/recording.go | 6 +----- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/acceleration/internal/api/recordings.go b/acceleration/internal/api/recordings.go index 7072c99c0c..56d721d39c 100644 --- a/acceleration/internal/api/recordings.go +++ b/acceleration/internal/api/recordings.go @@ -100,7 +100,6 @@ func (s *Server) transcribeRecording(ctx context.Context, request *transcribeRec job := store.Recording{ CustomerID: customerID, Modality: string(Stt), - Source: source.URL, STT: held, Callback: value(request.Body.Callback), Tags: tags, @@ -237,7 +236,6 @@ func (s *Server) recordSpeech(ctx context.Context, request *recordSpeechRequest) CustomerID: customerID, Modality: string(Tts), Text: request.Body.Text, - TTS: held, Callback: value(request.Body.Callback), Tags: tags, } diff --git a/acceleration/internal/store/recording.go b/acceleration/internal/store/recording.go index 6869d71f00..bc89e6dc34 100644 --- a/acceleration/internal/store/recording.go +++ b/acceleration/internal/store/recording.go @@ -32,14 +32,10 @@ type Recording struct { // Provider and Model are what served it, once routing has picked. Provider string `bun:"provider,nullzero"` Model string `bun:"model,nullzero"` - // Source is the recording to transcribe: a URL, or empty when the audio was sent - // inline, which is not kept. - Source string `bun:"source,nullzero"` // Text is what to say, for a voice job. Text string `bun:"text,nullzero"` - // Options are what was asked for. Only the block for this modality is set. + // STT is what a transcription was asked for. STT options.STT `bun:"stt,type:jsonb"` - TTS options.TTS `bun:"tts,type:jsonb"` // Callback is a URL the finished job is POSTed to. Empty means the caller polls. Callback string `bun:"callback,nullzero"` Tags map[string]string `bun:"tags,type:jsonb"` From 8be7c5e0f40249bd1353c6c11bb449eba163f3c9 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 20:00:34 +0100 Subject: [PATCH 06/11] AI-3537: stop recording when a guest was claimed users.claimed_at was written with claimed_by and read by nothing: claimed_by alone says a guest is claimed and by whom. The column stays until a later migration drops it. --- acceleration/internal/store/datamove_test.go | 4 ---- acceleration/internal/store/models.go | 3 +-- acceleration/internal/store/session_test.go | 1 - acceleration/internal/store/sessions.go | 7 +++---- 4 files changed, 4 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 2d6dd17147..bbf6b96150 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -295,8 +295,6 @@ func (s *DataMoveSuite) TestAMoveKeepsWhoItsUsersAre() { s.Require().NoError(s.source.RecordGuest(s.ctx, &User{ID: "guest-1", CustomerID: "acme", Name: "Guest"})) _, err := s.source.ClaimGuest(s.ctx, "acme", "guest-1", "alice") s.Require().NoError(err) - claimed, err := s.source.Guest(s.ctx, "acme", "guest-1") - s.Require().NoError(err) s.move("acme", "moved") @@ -305,8 +303,6 @@ func (s *DataMoveSuite) TestAMoveKeepsWhoItsUsersAre() { guest, err := s.destination.Guest(s.ctx, "moved", "guest-1") s.Require().NoError(err) s.Equal("alice", guest.ClaimedBy) - s.Require().NotNil(guest.ClaimedAt) - s.True(claimed.ClaimedAt.Equal(*guest.ClaimedAt)) _, err = s.destination.ClaimGuest(s.ctx, "moved", "guest-1", "mallory") s.ErrorIs(err, ErrGuestClaimed) } diff --git a/acceleration/internal/store/models.go b/acceleration/internal/store/models.go index eb24a2bca6..57912f066a 100644 --- a/acceleration/internal/store/models.go +++ b/acceleration/internal/store/models.go @@ -483,8 +483,7 @@ type User struct { // ClaimedBy is the real user this guest turned out to be, empty while they are still a // guest. A guest is claimed once: a second claim naming somebody else would move one // person's conversations onto another's account. - ClaimedBy string `bun:"claimed_by,nullzero"` - ClaimedAt *time.Time `bun:"claimed_at"` + ClaimedBy string `bun:"claimed_by,nullzero"` // ClaimFinishedAt is when every step of ClaimedBy's claim ran (FinishGuestClaim), nil // while a claim that set ClaimedBy has not got that far. ClaimFinishedAt *time.Time `bun:"claim_finished_at"` diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index a84e5a3b2c..b48ae975d9 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -851,7 +851,6 @@ func (s *StoreSuite) TestClaimingAGuestMovesTheirConversations() { guest, err := s.store.Guest(s.ctx, "app", "guest-1") s.Require().NoError(err) s.Equal("jlahey", guest.ClaimedBy) - s.Require().NotNil(guest.ClaimedAt) } func (s *StoreSuite) TestAGuestIsClaimedOnce() { diff --git a/acceleration/internal/store/sessions.go b/acceleration/internal/store/sessions.go index 7f41bf0e18..a45ffb8a4a 100644 --- a/acceleration/internal/store/sessions.go +++ b/acceleration/internal/store/sessions.go @@ -187,7 +187,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri if !s.Sharded() && len(s.peers) == 0 { var moved int64 err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil { + if err := claimGuest(ctx, tx, customerID, guestID, userID); err != nil { return err } if err := moveTasks(ctx, tx); err != nil { @@ -210,7 +210,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri } err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil { + if err := claimGuest(ctx, tx, customerID, guestID, userID); err != nil { return err } return moveTasks(ctx, tx) @@ -227,10 +227,9 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri // claimGuest marks a guest claimed by userID. A claim userID already made stands rather than // fails, for a caller that has more to finish after it. -func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string, now time.Time) error { +func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string) error { claimed, err := db.NewUpdate().Model((*User)(nil)). Set("claimed_by = ?", userID). - Set("claimed_at = ?", now). Where("id = ?", guestID). Where("customer_id = ?", customerID). Where("kind = ?", UserKindGuest). From 4b468fc428358b34659da500cb807803d7297f7f Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 20:01:26 +0100 Subject: [PATCH 07/11] AI-3537: stop reading when a chat message was received chat_inbound.received_at is filled by its default and was read into the model for nothing to use. The field and its place in the claim's column list go, so a later migration can drop the column. --- acceleration/internal/store/chat_inbound.go | 3 +-- acceleration/internal/store/chat_inbound_test.go | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/acceleration/internal/store/chat_inbound.go b/acceleration/internal/store/chat_inbound.go index 4336d6906f..85d6bc7a77 100644 --- a/acceleration/internal/store/chat_inbound.go +++ b/acceleration/internal/store/chat_inbound.go @@ -56,7 +56,6 @@ type ChatInbound struct { Attempts int `bun:"attempts,notnull"` // NextAttemptAt is when the message is due; on a claimed row, the end of the claim's lease. NextAttemptAt time.Time `bun:"next_attempt_at,notnull"` - ReceivedAt time.Time `bun:"received_at,notnull"` FinishedAt *time.Time `bun:"finished_at"` // Heard is what the voice recording sent with the message said, once it was heard // (ChatInbounds.KeepHeard); nil before. @@ -83,7 +82,7 @@ type ChatInbounds struct { // chatInboundColumns are the columns a ChatInbound is read from, named rather than taken // with *, so a router older than a migration that adds one still reads the rows. const chatInboundColumns = "cd.seq, cd.stream_app_pk, cd.message_id, cd.customer_id, cd.deployment, cd.api_key, cd.body, " + - "cd.state, cd.attempts, cd.next_attempt_at, cd.received_at, cd.finished_at, cd.heard" + "cd.state, cd.attempts, cd.next_attempt_at, cd.finished_at, cd.heard" // Queue queues delivery to be answered, due at delivery.NextAttemptAt. A message already // queued under the same app and id, answered or given up within its keep, is not queued again: diff --git a/acceleration/internal/store/chat_inbound_test.go b/acceleration/internal/store/chat_inbound_test.go index 95e74b3308..89a28724e2 100644 --- a/acceleration/internal/store/chat_inbound_test.go +++ b/acceleration/internal/store/chat_inbound_test.go @@ -83,7 +83,6 @@ func (s *StoreSuite) TestAClaimedChatInboundHasEverythingItWasQueuedWith() { s.Equal(ChatInboundQueued, claimed.State) s.Equal(1, claimed.Attempts, "a claim counts its attempt") s.WithinDuration(time.Now().Add(chatLease), claimed.NextAttemptAt, 5*time.Second, "a claimed message is due at the end of the lease its claim gave") - s.WithinDuration(time.Now(), claimed.ReceivedAt, time.Minute) s.Nil(claimed.FinishedAt) } From 0427cd0683b6568c1318da77025fef63e9ec2ac5 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 20:02:28 +0100 Subject: [PATCH 08/11] AI-3537: say why columns no code reads are kept campaigns.consent_at and usage_resets.actor are records for people, and so are the created_at and updated_at of every table. --- .claude/skills/go/store.md | 2 ++ acceleration/internal/store/campaign.go | 4 +++- acceleration/internal/store/usage_reset.go | 5 +++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.claude/skills/go/store.md b/.claude/skills/go/store.md index 4c45c13ccb..6bca0cbf47 100644 --- a/.claude/skills/go/store.md +++ b/.claude/skills/go/store.md @@ -113,6 +113,8 @@ A state change that is more than a column write gets a domain verb on the same r - A lease is `lease_until` and `leased_by`. A queue row retries with `attempts` and `next_attempt_at`. A sealed secret column ends in `_sealed` with its key version in `_kek_version` (`kek_version` when the table has one secret). +- `created_at` and `updated_at` are records for people: a table keeps them even when no code + reads them. ## Adding a model diff --git a/acceleration/internal/store/campaign.go b/acceleration/internal/store/campaign.go index f001fd0fa1..0839ab7e33 100644 --- a/acceleration/internal/store/campaign.go +++ b/acceleration/internal/store/campaign.go @@ -69,7 +69,9 @@ type Campaign struct { LaunchedAt *time.Time `bun:"launched_at"` StartedAt *time.Time `bun:"started_at"` StoppedAt *time.Time `bun:"stopped_at"` - ConsentAt *time.Time `bun:"consent_at"` + // ConsentAt is when the customer said its contacts agreed to be called. No code reads + // it: it is the record for whoever is asked to show that consent. + ConsentAt *time.Time `bun:"consent_at"` // FinishedAt is when the campaign completed. FinishedAt *time.Time `bun:"finished_at"` // PausedReason is the code of what refused a call when the router paused the campaign diff --git a/acceleration/internal/store/usage_reset.go b/acceleration/internal/store/usage_reset.go index f55342e6d0..4b390d26b7 100644 --- a/acceleration/internal/store/usage_reset.go +++ b/acceleration/internal/store/usage_reset.go @@ -28,8 +28,9 @@ type UsageReset struct { WindowStart time.Time `bun:"window_start,notnull"` BaselineMicros int64 `bun:"baseline_micros,notnull"` Reason string `bun:"reason,notnull"` - Actor string `bun:"actor,notnull"` - CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp"` + // Actor is who reset it. No code reads it: it is the record for whoever asks who did. + Actor string `bun:"actor,notnull"` + CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp"` } // Ref is the subject the reset is of. From 5c89b32946ad3751059623dd55a8273ebe4fd780 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 21:55:37 +0100 Subject: [PATCH 09/11] AI-3537: docs: stop describing the key-use and TLS-scheme writes --- .factory/features/app_store.md | 4 ---- .factory/features/auth.md | 3 +-- acceleration/internal/connectors/core/AGENTS.md | 2 +- acceleration/internal/store/api_key.go | 4 ++-- 4 files changed, 4 insertions(+), 9 deletions(-) diff --git a/.factory/features/app_store.md b/.factory/features/app_store.md index 76a4d0a92b..fa8488396b 100644 --- a/.factory/features/app_store.md +++ b/.factory/features/app_store.md @@ -31,10 +31,6 @@ The authenticator, `policy.Enforcer`, `api.Server`, `session.Manager` and the vo resolver and service all read through it. A deployment with no Redis address, or one whose Redis is unreachable, reads Postgres and nothing fails. -`TouchAPIKey` is throttled per process as well. The store already refused to write -`last_used_at` more than once a minute, but it took a query to find that out, which on a -busy key was a second round trip per request for a column nothing reads in anger. - ## Tracing, which is how it was measured [internal/tracing](../../acceleration/internal/tracing) is `go.opentelemetry.io/otel` with diff --git a/.factory/features/auth.md b/.factory/features/auth.md index fbeff53b53..30928c4a51 100644 --- a/.factory/features/auth.md +++ b/.factory/features/auth.md @@ -202,8 +202,7 @@ The rest of the credential's shape is borrowed rather than invented. `vak_live_ config is visible as one, and the key id ends in a CRC32 so a truncated paste is rejected before the database is asked. `last4` is all the dashboard would ever show of a secret again. A revoked key keeps its row, because a year of request rows pointing at a deleted key -is unattributable noise, and `last_used_at` is written at most once a minute per key, since -a synchronous update would double the writes of a busy one. +is unattributable noise. ## Not done diff --git a/acceleration/internal/connectors/core/AGENTS.md b/acceleration/internal/connectors/core/AGENTS.md index e144aa4538..57fb07b80d 100644 --- a/acceleration/internal/connectors/core/AGENTS.md +++ b/acceleration/internal/connectors/core/AGENTS.md @@ -163,7 +163,7 @@ client.Do(request) the egress client of one connection - **A 401 renews first, and is sent again at most once.** Only a 401 is classified, as the design says (`docs/connectors/channels.md` on `connectors/planning`, «The proxy»: «On a 401 the Router calls Invalidate, refreshes and retries once»). A refused credential may belong to a grant that still works: the provider's clock runs ahead, or it ended the access token early. So the transport first asks for a credential renewed past the refused one (`CredentialRequest.Refused`, which reaches the scheme as `RetrieveOptions.Refused`); only a refused renewal, as with any failed renewal, moves the connection. The request goes again when the body can be read again (`GetBody`). `Invalidate` is called only when nothing renews the credential (a static key, a token with no refresh token) or the renewed one is refused too, with the credential that was sent. Example: an `oauth2_code` token the provider ended an hour early is refreshed, the call succeeds, the connection stays connected; with a refused refresh it moves to `needs_reauthorization`. A 403 `insufficient_scope` is returned as it is: a scope one tool lacks says nothing about the others. Check: `go test -run 'TestTransportsSuite/(TestARefused|TestARefusal|TestABodyThat|TestA401)' ./internal/connectors/core`, `go test -run 'TestOAuth2CodeSuite/(TestARefusedAccessToken|TestAFailedRefreshOfARefused)' ./internal/connectors/schemes/oauth2code` and, with Postgres, `go test -tags integration -run TestTransportSuite ./internal/connectors/resolver`. - **One client per connection, a copy per caller.** `Transports.Client` builds the client once per `ConnectionRef` and returns a copy that shares its connection pool, so a caller that replaces its copy's `Transport` changes nothing for the others. `Transports.Close(ref)` drops it and closes its idle connections, for the delete and disconnect paths to call. `cmd/router` builds one `Transports` and hands it to the API (`api.Options.ConnectorTransports`), whose validate endpoint is one caller; the session's dispatcher (`session.ManagerOptions.Connectors`) shares it, and `deleteConnection` calls `Close`. A copy held past `Close` still asks the resolver first, which refuses a connection that is gone. A client nothing asked for or sent with for `idleAfter` (90 s, `DefaultTransport`'s `IdleConnTimeout`, by when it holds no idle socket) is dropped the next time a client is built, at most once per `idleAfter`, so every replica forgets connections it no longer uses. Check: `go test -run 'TestTransportsSuite/(TestOneConnection|TestClosing|TestReplacing|TestAClientUnused)' ./internal/connectors/core` and `go test -tags integration -run TestTransportSuite/TestAClientHeldPastADelete ./internal/connectors/resolver`. - **`Retrieve` can run before egress refuses.** The dial check comes after `Wrap`, so a refresh for a host that resolves to a private address still runs; the token never leaves the router. When `Retrieve` itself must not run, call `egress.ValidatePublicHTTPSURL` on the endpoint first. -- A scheme's TLS client certificate (`mtls`, `tls_scheme`) is not built yet; it belongs to this one client per connection. +- A scheme's TLS client certificate (`mtls`) is not built yet; it belongs to this one client per connection. - **A request records what it saw for whoever asked (`Exchange`, `records.go`).** A context made by `WithExchange` gets told whether a request left with a credential, the provider's last status, the `Resolver`'s refusal and a client timeout; nothing else is kept, never a header, a body or a credential. `Exchange.Redact` takes out of a text, such as the tool source's error, what the error body has taken out: the last request's path and query and its credential's strings, held only inside a function so nothing prints them (AI-1244). The session's dispatcher reads it to say how a tool call failed in the invocation log, because a tool source's error does not say whether anything was sent and the MCP client reports a 401 only as its status text. A context without one records nothing. Example: a provider answering 401 to a call is `customer_auth`; arguments the source refuses before sending are `denied`. Check: `go test -tags integration -run TestInvocationLogSuite ./internal/session`. - **Who caused a grant change rides on the context (`Correlation`, `records.go`).** The API puts the request's `X-Request-Id` on every request's context, and the session's dispatcher adds the session's id, both when a binding is opened and when a tool is called; the resolver copies both onto the audit rows it writes. A session's turns run on the context of the request that created it, so for an incognito session the dispatcher drops the request id too, on open and on call, and its rows carry neither. Check: `go test -tags integration -run TestResolverSuite/TestAuditOfARefreshIsOne ./internal/connectors/resolver` and `go test -tags integration -run 'TestInvocationLogSuite/Test(AnIncognito|ARecorded)' ./internal/session`. diff --git a/acceleration/internal/store/api_key.go b/acceleration/internal/store/api_key.go index 8f4be3fbc3..2ca21576c5 100644 --- a/acceleration/internal/store/api_key.go +++ b/acceleration/internal/store/api_key.go @@ -14,8 +14,8 @@ import ( ) // APIKey is one credential belonging to an app. Several may be live at once, because -// rotation without downtime is: create the new key, deploy it, watch the old one go quiet, -// revoke it. One key per app makes every rotation an outage, so rotation stops happening. +// rotation without downtime is: create the new key, deploy it, watch the old one go quiet +// (requests.api_key), revoke it. One key per app makes every rotation an outage, so rotation stops happening. type APIKey struct { bun.BaseModel `bun:"table:api_keys,alias:k"` From 3f8aee7cebc938cdffafce33938326bd9829e16f Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Mon, 23 Nov 2026 21:55:37 +0100 Subject: [PATCH 10/11] AI-3537: docs(skills): say how a column is removed --- .claude/skills/go/store.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.claude/skills/go/store.md b/.claude/skills/go/store.md index 6bca0cbf47..d82b01c37f 100644 --- a/.claude/skills/go/store.md +++ b/.claude/skills/go/store.md @@ -93,6 +93,8 @@ A state change that is more than a column write gets a domain verb on the same r - Opening the database with `bun.WithDiscardUnknownColumns()` means a release that does not know a new column still reads the row. So add a column to the table that owns it, nullable or with a default; do not create a 1:1 side table to dodge a rollback. +- Remove a column over two releases. First stop writing it and take it out of the model: + routers of the release before still name it in their SQL. Drop it in the next release. - A table of work routers claim (inbound messages, deliveries, jobs) is a `queue` (`queue.go`): `claim` leases due rows with `FOR UPDATE SKIP LOCKED` in one query, `nextDue` says when to look again, and every write after the claim goes through `heldBy`, From f58ecff2a3de18e84ae1f600d962002757d5bb33 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Tue, 24 Nov 2026 15:33:28 +0100 Subject: [PATCH 11/11] docs(store): comments and docs name what exists today (#2376) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stacked on #2375 (AI-3537), second of four: the diff here is this PR's 20 commits only. Merge in order; once #2375 is squash-merged this branch is rebased onto `main`. **Problem** Comments and docs point at things that no longer exist. 66 comments and README lines cite migration files the squash removed. About 150 comments name functions from before the store became one repository per model (#2173), such as `SetConnectorConnectionProviderUnit`. `.claude/skills/go/store.md` names a file and two methods that are not there. **Fix** Comment and documentation text only: no code token changes. - A migration citation now says what the schema does, naming the constraint or index where the citation was the evidence (`agent_configs_role_idx`, `episodes_check`, `limits_level_check`). Words rather than the baseline file, since the migrations are being squashed again. - A stale function name becomes the current `Repository.Method`. Each mapping was checked against the #2173 diff or the method's signature. - `store.md`: `image_jobs.go` → `image_job.go`, `CampaignContacts.Lease` → `CampaignContacts.Claim`, `Episodes.Close` → `Episodes.CloseIdle`. - The same old names in 11 package `AGENTS.md` files, the `pagination` and `telnyx` skills, `docs/stream-tenancy.md` and the `pgsealed` notes. - README: two paragraphs on what three removed price migrations did, with their down steps, are now six lines on what existing rows hold. Revert `docs(readme): say what the schema holds` if the upgrade notes are still wanted. - Left on purpose: history pinned to a commit (the prototype at `cf62af0d`, the previous release at `ba2c5e912`), names from other repositories and vendors, and `logmask_test.go`'s file name, which is test data. **Tests** - A `go/scanner` comparison of every changed Go file, comments left out, finds no difference: nothing but comments and Markdown changed. - All 114 distinct `Type.Method` names on added lines resolve to a method or field on this tree. An independent reviewer checked about 45 reworded statements against the code or `schema/*.sql`. - `grep -rnE "20[0-9]{12}_[a-z0-9_]+\.sql"` over `internal`, `cmd`, the README, `docs` and the skills finds only the test data line. Closes AI-3472 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .claude/skills/go/store.md | 4 +- .claude/skills/pagination/SKILL.md | 2 +- .claude/skills/telnyx/SKILL.md | 2 +- acceleration/README.md | 46 ++++++------------ .../cmd/router/usage_integration_test.go | 2 +- acceleration/docs/stream-tenancy.md | 2 +- acceleration/internal/activity/activity.go | 2 +- acceleration/internal/agent/approval.go | 2 +- acceleration/internal/agent/ids.go | 2 +- acceleration/internal/api/audit.go | 2 +- acceleration/internal/api/authorizations.go | 2 +- acceleration/internal/api/chat_channels.go | 2 +- acceleration/internal/api/chat_episodes.go | 4 +- acceleration/internal/api/chatinbound.go | 2 +- acceleration/internal/api/configs_test.go | 2 +- acceleration/internal/api/connection_proxy.go | 5 +- .../internal/api/connection_proxy_test.go | 2 +- .../internal/api/connection_records.go | 2 +- .../internal/api/connection_records_test.go | 2 +- .../internal/api/connection_tool_approvals.go | 2 +- acceleration/internal/api/connections.go | 8 ++-- acceleration/internal/api/connections_test.go | 2 +- acceleration/internal/api/connector_events.go | 5 +- .../internal/api/connector_provider_apps.go | 2 +- acceleration/internal/api/connectors.go | 2 +- acceleration/internal/api/connectors_test.go | 4 +- acceleration/internal/api/dispatchws.go | 2 +- .../internal/api/linq_channel_test.go | 2 +- acceleration/internal/api/oauth_clients.go | 4 +- .../internal/api/scheduled_delivery.go | 2 +- acceleration/internal/api/server.go | 5 +- acceleration/internal/api/sync.go | 2 +- acceleration/internal/api/threadhooks.go | 2 +- acceleration/internal/api/user_phones_test.go | 4 +- acceleration/internal/audiofloor/hearer.go | 2 +- acceleration/internal/campaign/campaign.go | 2 +- acceleration/internal/channelbridge/AGENTS.md | 26 +++++----- acceleration/internal/channelbridge/bridge.go | 10 ++-- acceleration/internal/channelbridge/gate.go | 6 +-- .../internal/channelbridge/inbound.go | 6 +-- .../internal/channelbridge/keywords.go | 9 ++-- acceleration/internal/chatinbound/AGENTS.md | 12 ++--- acceleration/internal/chatinbound/worker.go | 2 +- .../credentialstores/pgsealed/AGENTS.md | 10 ++-- .../credentialstores/pgsealed/pgsealed.go | 2 +- .../internal/connectors/providers/AGENTS.md | 2 +- .../connectors/providers/providers.go | 2 +- .../internal/connectors/resolver/AGENTS.md | 2 +- .../internal/connectors/resolver/resolver.go | 2 +- .../internal/connectors/slackapps/AGENTS.md | 2 +- acceleration/internal/eventforward/AGENTS.md | 8 ++-- acceleration/internal/mcpevents/AGENTS.md | 2 +- acceleration/internal/omnichannel/AGENTS.md | 47 ++++++++++--------- acceleration/internal/omnichannel/close.go | 2 +- .../internal/omnichannel/close_test.go | 2 +- acceleration/internal/omnichannel/read.go | 6 +-- acceleration/internal/phone/lines.go | 2 +- acceleration/internal/phone/outcome/AGENTS.md | 4 +- acceleration/internal/phone/service.go | 2 +- acceleration/internal/policy/holds.go | 2 +- acceleration/internal/policy/spend.go | 4 +- acceleration/internal/pricing/pricing.go | 4 +- acceleration/internal/routing/attribution.go | 2 +- acceleration/internal/scheduling/AGENTS.md | 2 +- acceleration/internal/scheduling/describe.go | 2 +- acceleration/internal/scheduling/scheduler.go | 2 +- .../scheduling/scheduler_activity_test.go | 2 +- .../internal/session/connector_tools.go | 2 +- acceleration/internal/session/episode_card.go | 4 +- .../session/episode_reading_link_test.go | 6 +-- acceleration/internal/session/manager.go | 2 +- .../internal/session/resume_history.go | 2 +- acceleration/internal/session/step_up.go | 2 +- acceleration/internal/store/agent_config.go | 31 +++++------- .../internal/store/agent_config_test.go | 2 +- acceleration/internal/store/agent_log.go | 4 +- acceleration/internal/store/app.go | 2 +- acceleration/internal/store/audit_entry.go | 15 +++--- acceleration/internal/store/campaign_test.go | 2 +- .../internal/store/channel_inbound.go | 7 ++- .../internal/store/channel_inbound_test.go | 4 +- acceleration/internal/store/channel_owner.go | 2 +- acceleration/internal/store/channel_thread.go | 7 ++- .../internal/store/channel_thread_member.go | 2 +- .../internal/store/channel_thread_message.go | 3 +- acceleration/internal/store/chat_inbound.go | 4 +- .../internal/store/connector_audit_event.go | 5 +- .../internal/store/connector_connection.go | 31 ++++++------ .../store/connector_connection_test.go | 6 +-- .../internal/store/connector_definition.go | 13 +++-- .../store/connector_definition_test.go | 6 +-- .../internal/store/connector_invocation.go | 4 +- .../store/connector_invocation_test.go | 5 +- .../internal/store/connector_oauth_client.go | 9 ++-- .../store/connector_oauth_client_test.go | 2 +- .../internal/store/connector_tool_pin.go | 8 ++-- .../internal/store/contact_map_entry.go | 9 ++-- .../internal/store/credential_lock.go | 8 ++-- acceleration/internal/store/datamove.go | 23 +++++---- acceleration/internal/store/episode.go | 17 ++++--- acceleration/internal/store/episode_test.go | 2 +- acceleration/internal/store/event_delivery.go | 6 +-- acceleration/internal/store/image_job.go | 6 +-- acceleration/internal/store/limit.go | 2 +- .../internal/store/limit_grant_test.go | 2 +- .../internal/store/limit_grant_use_test.go | 2 +- acceleration/internal/store/models.go | 2 +- acceleration/internal/store/provider_key.go | 3 +- acceleration/internal/store/request.go | 8 ++-- acceleration/internal/store/scheduled_task.go | 2 +- .../internal/store/session_unit_test.go | 2 +- acceleration/internal/store/use_case.go | 2 +- acceleration/internal/store/user_phone.go | 21 ++++----- .../internal/store/user_phone_history_test.go | 2 +- .../internal/store/user_phone_test.go | 4 +- .../internal/store/waiting_message.go | 2 +- acceleration/internal/ttsrouter/recordings.go | 2 +- 117 files changed, 305 insertions(+), 343 deletions(-) diff --git a/.claude/skills/go/store.md b/.claude/skills/go/store.md index d82b01c37f..ea026f175d 100644 --- a/.claude/skills/go/store.md +++ b/.claude/skills/go/store.md @@ -29,7 +29,7 @@ Use these names, with the customer first after `ctx` for every tenant-scoped mod | `Delete(ctx, customerID, id)` | Removes one row; `ErrNoX` when absent. | A state change that is more than a column write gets a domain verb on the same repository: -`Calls.Finish`, `CampaignContacts.Lease`, `Episodes.Close`. Batch versions take a slice +`Calls.Finish`, `CampaignContacts.Claim`, `Episodes.CloseIdle`. Batch versions take a slice (`InsertMany`, `GetMany`) and run one statement, never a loop of single ones. ## Validation @@ -98,7 +98,7 @@ A state change that is more than a column write gets a domain verb on the same r - A table of work routers claim (inbound messages, deliveries, jobs) is a `queue` (`queue.go`): `claim` leases due rows with `FOR UPDATE SKIP LOCKED` in one query, `nextDue` says when to look again, and every write after the claim goes through `heldBy`, - so a claim whose lease ran out cannot overwrite the next one. `image_jobs.go` is the + so a claim whose lease ran out cannot overwrite the next one. `image_job.go` is the example. Do not write the claim by hand. - Every serving connection runs with `statement_timeout` 8s, `lock_timeout` 3s, `idle_in_transaction_session_timeout` 30s and `timezone` UTC (`sessionDefaults` in diff --git a/.claude/skills/pagination/SKILL.md b/.claude/skills/pagination/SKILL.md index 29eec42cef..4593eb01cf 100644 --- a/.claude/skills/pagination/SKILL.md +++ b/.claude/skills/pagination/SKILL.md @@ -35,7 +35,7 @@ type SessionPosition struct { } ``` -Store, in `QuerySessions`: +Store, in `Sessions.Select`: ```go if after := filter.Cursor; after != nil { diff --git a/.claude/skills/telnyx/SKILL.md b/.claude/skills/telnyx/SKILL.md index b87ff8786e..c9f066b260 100644 --- a/.claude/skills/telnyx/SKILL.md +++ b/.claude/skills/telnyx/SKILL.md @@ -200,7 +200,7 @@ ticket comments (AI-1842, AI-1843). - **The sandbox gate** (`dlc.Gate`) can hold back a text or a reply on a line that is not registered for 10DLC. A text it refuses reaches no agent. - **A webhook older than 5 minutes is refused** (`Telnyx-Timestamp`, `max_age: 5m` in the - manifest). Telnyx may send a webhook twice. The bridge claims each message once (`store.ClaimChannelThreadMessage`), so a retried delivery is dropped. + manifest). Telnyx may send a webhook twice. The bridge claims each message once (`store.ChannelThreadMessages.Claim`), so a retried delivery is dropped. - **The line's current binding answers.** A text on an existing thread is answered by the config bound to the line now, the same one the bridge picks (oldest binding first). The history stays in the thread channel, so a newly bound config sees the earlier messages. diff --git a/acceleration/README.md b/acceleration/README.md index c25a5ed9ce..e96a93cd9a 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -567,11 +567,9 @@ must have a limit to be granted (404 `no_limit`), and an organization has at mos grants, a used-up one not counted (409 `too_many_grants`). `getLimitUsage` lists the subject's live grants and says, per window, when its work runs on one. -The organization and app budgets that policies held moved into this table with the migration -`20261112120000_limits`: each became the organization's or the app's own limit on its interval, -an app's under the organization it was last seen in, or under itself when it was seen in none. -The migration stops while an hourly budget exists, since limits have no hourly interval. Coming -down puts one budget back into each policy from its scope's own limits. +The organization and app budgets that policies held moved into this table: each became the +organization's or the app's own limit on its interval, an app's under the organization it was +last seen in, or under itself when it was seen in none. ### The account, its credit and its teams @@ -993,8 +991,8 @@ An agent's work is done in one region, `us` or `eu` for now, and never in anothe its sessions route to, its knowledge base and its sandbox. The region is the agent's own. `agent.yaml` names it as `region` (the sync's `region`), as a config written with the API does (`AgentConfigRequest.region`, `AgentConfigPatch.region`), and it is stored in -`agent_configs.region` (migration `20261202135000_agent_region`, which puts every agent before it -in `us`). An agent that names none is in `us` (`pricing.DefaultRegion`), and a sync, an update or a +`agent_configs.region` (an agent stored before the column existed is in `us`). An agent that +names none is in `us` (`pricing.DefaultRegion`), and a sync, an update or a patch that leaves it out keeps the stored one. A region is a letter and up to 31 of a-z, 0-9 and hyphens (`pricing.ValidRegion`). @@ -1080,8 +1078,8 @@ Knowledge and sandboxes are not routed, so they are done in the work's region - **Knowledge.** One turbopuffer backend per region `knowledge.regions` maps (`ROUTER_KNOWLEDGE_REGIONS`), `us` always among them as before. A knowledge base stays in the - region of its first write through the router, recorded in `knowledge_namespaces` (migration - `20261202125000_knowledge_region`, which records every existing base as `us`). Work naming a + region of its first write through the router, recorded in `knowledge_namespaces` (a base from + before regions is recorded as `us`). Work naming a region, an agent's, reads and writes a base kept there, makes one nothing was written to there, and is refused one kept in another rather than having it moved. Work naming none, as the knowledge API's (`/v1/agents/knowledge`) and a page's read, goes where the base is kept, @@ -1111,7 +1109,7 @@ vendor the deployment routes whose factory builds with an instance's own key and for `daytona`; any other is a 400 `provider_takes_no_key` naming the ones that are. Only a key is taken, never an endpoint: the deployment's own is used. -Keys are kept in `provider_keys` (migration `20261202130000_provider_keys`), sealed with the +Keys are kept in `provider_keys`, sealed with the deployment's keyring (`auth.Sealer`, as the other customer secrets are) and bound to the customer, the vendor and the region, so a sealed key copied to another row does not open. A key is never returned, logged or put in an error: the API lists its last four characters (`key_hint`, empty for a @@ -2227,7 +2225,7 @@ from the hour `since` falls in, one item per leg with `turns` and the `p50_ms`, The endpoint sums the rows of the organization's current apps, including rows the sweeper has not processed yet, while the cost-anomaly check sums `requests.organization_id` over swept billable rows, so the two can disagree for two reasons. One is an app that moved organization -within the window. The other is rows the sweeper has not yet given an organization: `MeterUses` +within the window. The other is rows the sweeper has not yet given an organization: `Spend.Meters` reads an org's apps with no organization filter, while the cost-anomaly check skips rows with an empty `organization_id`. @@ -2526,26 +2524,12 @@ a vendor quotes outright, such as a number's monthly rental, is charged at that same factor, which no entry stores; its `base_cost_micros` is the vendor's amount, or 0 with the fee charged for a BYOK item. -Migration `20261118120000_price_entry_prices` stored every existing entry's price as what it -was charged: its rates times its own markup, else the list's in force when it is (or was), and -gave every item its SKU. Migration `20261130120000_drop_price_markup` then drops the -`markup_bps` those markups were kept in, on `price_changes` and `price_entries`, which nothing -had read since. - -Migration `20261202120000_price_entry_region` renames `price_entries` to `price_list_entries` -and adds `region` and `byok`: every existing entry is `us` and not BYOK, and `region` keeps no -default, so every later insert names one. It ends every existing SKU in `-us` -(`llm-openai-a` becomes `llm-openai-a-us`, `llm-openai-gpt-4-1-2` becomes -`llm-openai-gpt-4-1-2-us`), and indexes items by region and BYOK state as well. `requests.sku` -and the usage ledger are not rewritten: a row keeps the SKU it was billed under, so a row priced -before the migration names its item's SKU without the region. The rename is what keeps a router -built before it from reading a BYOK entry as its item's newest price: that router's reads and -writes of the price list fail, and it keeps pricing with the list it holds in memory, reading -again every 30 seconds, until it is replaced. The first start after the migration writes one -`release` change holding only the BYOK twins the files now have, at the fee; every US item keeps -its price and its SKU. Down takes the region off the SKUs, drops the columns and renames the -table back, and refuses a list that holds a BYOK or non-US entry, which a router built before -it would read as a US price. +An entry from before prices were stored holds what it was charged: its rates times its own +markup, else the list's in force then. An entry from before regions is `us` and not BYOK, and +its SKU ends in `-us` (`llm-openai-a` became `llm-openai-a-us`). `region` has no default, so +every insert names one. `requests.sku` and the usage ledger were not rewritten: a row keeps the +SKU it was billed under, so a row priced before regions names its item's SKU without the +region. | Command | What it does | | --- | --- | diff --git a/acceleration/cmd/router/usage_integration_test.go b/acceleration/cmd/router/usage_integration_test.go index b6384ff1fb..7e19277e25 100644 --- a/acceleration/cmd/router/usage_integration_test.go +++ b/acceleration/cmd/router/usage_integration_test.go @@ -331,7 +331,7 @@ func (s *UsageCommandsSuite) states() map[uuid.UUID]shipState { // rowsOfEveryKind writes, started ten minutes ago, a row the usage service has, one it refused, // one written before the router shipped, and one a data move carried in, which arrives as the -// import writes it (see TestAnImportedRequestKeepsItsUsageIDAndIsNeverShipped). +// import writes it. func (s *UsageCommandsSuite) rowsOfEveryKind() (shipped, rejected, beforeShipping, imported uuid.UUID) { shippedAt := time.Now().UTC().Add(-5 * time.Minute) shipped = s.recorded(10*time.Minute, func(request *store.Request) { request.ShippedAt = &shippedAt }) diff --git a/acceleration/docs/stream-tenancy.md b/acceleration/docs/stream-tenancy.md index 533676d466..ac0bd81887 100644 --- a/acceleration/docs/stream-tenancy.md +++ b/acceleration/docs/stream-tenancy.md @@ -41,7 +41,7 @@ App mode needs Postgres, a keyring (`ROUTER_AUTH_KEK_V_WRAPPED` with `ROUTER_ - **Floor.** An organisation can require its apps' own Stream app (`router stream-apps require`). - **Operator CLI:** `router stream-apps require|legacy|fallbacks|backfill-pins`. -Apps that registered their keys before forwarded tokens were given a placeholder token row by migration `20261022120000`, so their background work asks the gateway for a token rather than waiting for their next request. Migration `20261023120000` then dropped the old `stream_apps` and `stream_app_keys` tables. +Apps that registered their keys before forwarded tokens were given a placeholder token row, so their background work asks the gateway for a token rather than waiting for their next request. The old `stream_apps` and `stream_app_keys` tables were then dropped. ## Testing diff --git a/acceleration/internal/activity/activity.go b/acceleration/internal/activity/activity.go index 1266777789..cde1d2364e 100644 --- a/acceleration/internal/activity/activity.go +++ b/acceleration/internal/activity/activity.go @@ -1,5 +1,5 @@ // Package activity counts the requests each app makes, by area of the API and by client, and -// writes the sums to customer_activity (store.RecordActivity). +// writes the sums to customer_activity (store.Activities.Add). // // Every authenticated request is one, and so is a hook checked as an app's (NoteCustomer), and // the work the router does for an app on its own: a forward to its endpoint, a scheduled task's diff --git a/acceleration/internal/agent/approval.go b/acceleration/internal/agent/approval.go index c04e9694a3..82c8b2cafa 100644 --- a/acceleration/internal/agent/approval.go +++ b/acceleration/internal/agent/approval.go @@ -318,7 +318,7 @@ func (a *Agent) approvedName(call llm.ToolCall) string { return call.Name } -// runningAs is the call a running call's id is held under: an approved call runs under the +// runningAsLocked is the call a running call's id is held under: an approved call runs under the // confirmation that ran it, which is the call the model has open. The caller holds the lock. func (a *Agent) runningAsLocked(id string) string { if run, ok := a.approvedRuns[id]; ok { diff --git a/acceleration/internal/agent/ids.go b/acceleration/internal/agent/ids.go index 259f1847e3..6a4fa2d4a7 100644 --- a/acceleration/internal/agent/ids.go +++ b/acceleration/internal/agent/ids.go @@ -268,7 +268,7 @@ func fromNote(text string) bool { // A name field can identify a place or business, not just a person. The lexical // heuristics must not reject a name the caller or a successful tool already gave. A tool that -// reads back what the agent wrote with the name in it does not give it (ownLines.readBack). +// reads back what the agent wrote with the name in it does not give it (heldLines.readBack). func nameWasGiven(history []llm.Message, name string) bool { words := func(text string) string { return " " + strings.ToLower(strings.Join(strings.FieldsFunc(text, func(r rune) bool { diff --git a/acceleration/internal/api/audit.go b/acceleration/internal/api/audit.go index 1cffb60803..4548c4a942 100644 --- a/acceleration/internal/api/audit.go +++ b/acceleration/internal/api/audit.go @@ -416,7 +416,7 @@ var auditBookkeeping = []string{"id", "created_at", "updated_at", "sync_hash"} // auditDiff is the fields that moved between two renderings of a resource. // // It compares the API's own shape of the thing rather than the stored row, so what a change -// names is what a client reads the resource by: `tools`, not `progressive_tools`. A field +// names is what a client reads the resource by: `tools`, not `tool_groups`. A field // absent from one side and present on the other has moved, which is what makes a create // every field at once and a delete every field back to nothing. func auditDiff(before, after any) []store.AuditChange { diff --git a/acceleration/internal/api/authorizations.go b/acceleration/internal/api/authorizations.go index ddecdcaed4..b9d796ef09 100644 --- a/acceleration/internal/api/authorizations.go +++ b/acceleration/internal/api/authorizations.go @@ -724,7 +724,7 @@ func (s *Server) handOffConnectorLaunch(w http.ResponseWriter, r *http.Request) // 2. the browser holds that attempt's cookie (RFC 6749 section 10.12, RFC 9700 section // 2.1: the state is bound to the user agent), so a callback in another browser is // refused and the right browser can still finish; -// 3. the attempt is used up, once (store.ConsumeConnectorAuthorizationAttempt), so a +// 3. the attempt is used up, once (store.ConnectorAuthorizationAttempts.Consume), so a // replayed callback never reaches the provider again; // 4. the manifest's before_complete hook sees the whole callback; // 5. Scheme.Complete checks state, iss (RFC 9207 section 2.4) and the provider's error diff --git a/acceleration/internal/api/chat_channels.go b/acceleration/internal/api/chat_channels.go index 8b93063f95..34115ad4b3 100644 --- a/acceleration/internal/api/chat_channels.go +++ b/acceleration/internal/api/chat_channels.go @@ -19,7 +19,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) -// A channel of a type an agent config names (store.AgentConfig.ChatChannels), such as a team's +// A channel of a type an agent config names (store.AgentConfig.Channels.Chat), such as a team's // group channel, is answered by the Router itself, as a thread channel is: // // message.new, no source, in callouts:team-1 receiveMessageEvent, receiveChatInbound diff --git a/acceleration/internal/api/chat_episodes.go b/acceleration/internal/api/chat_episodes.go index db023f943a..f143e031e8 100644 --- a/acceleration/internal/api/chat_episodes.go +++ b/acceleration/internal/api/chat_episodes.go @@ -24,7 +24,7 @@ const chatCardTimeout = 30 * time.Second // on or record (Spec.WritesCards), has any: off, nothing here reads or writes. A thread channel's episode is the channel bridge's, an // omni-channel is where cards are written and never where an episode starts, and a session on // a call has its call's card, whose lines a chat episode in the same channel would cut short -// (store.EpisodeCards, until). +// (store.Episodes.Cards, until). // // The episode is the person's only in a channel whose members are that person alone, or that // person and the agent, the Stream user the agent writes its replies as: its agent id, which is @@ -40,7 +40,7 @@ const chatCardTimeout = 30 * time.Second // // Every message calls Open, which keeps the episode open (episodes.last_message_at). // A message delivered again, by Stream or by the queue's next try, finds the episode its first -// delivery opened (store.OpenEpisode, episodes_open_thread), so it opens no second one and +// delivery opened (store.Episodes.Open, episodes_open_thread), so it opens no second one and // writes no second card. An episode or a card that fails costs the card, not the answer: it // is logged and the message is answered all the same. func (s *Server) chatEpisode(ctx context.Context, origin hookOrigin, event messageEvent, answering session.Spec) { diff --git a/acceleration/internal/api/chatinbound.go b/acceleration/internal/api/chatinbound.go index 3b9a1a4ce7..8874633418 100644 --- a/acceleration/internal/api/chatinbound.go +++ b/acceleration/internal/api/chatinbound.go @@ -294,7 +294,7 @@ func (s *Server) answerChatInboundForPeer(w http.ResponseWriter, r *http.Request } // answerOnce settles a queued delivery's row as its answer starts, so a try of it after that, on -// this router or another, answers nothing (store.StartChatInboundAnswer). answer is false when +// this router or another, answers nothing (store.ChatInbounds.StartAnswer). answer is false when // the message is not to be answered now, and settled then says whether that holds: its answer // already started, or the row could not be written and a later try may. A hook is never tried // again, so it settles nothing. A router that stops mid-answer leaves the message answered at diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go index d6042c988e..4b69cd2b81 100644 --- a/acceleration/internal/api/configs_test.go +++ b/acceleration/internal/api/configs_test.go @@ -2179,7 +2179,7 @@ func (s *ConfigsSuite) TestNessyBesideSeveralOutboundToolsNamesThemAll() { // TestNessyBesideAConnectorWithOneOutboundSourceAmongSeveralIsRefused: a connector sends data // out if any of its sources may, not only the first. Manifest.Validate accepts several sources -// and CreateConnectorDefinition takes any manifest, so a custom connector can put a source that +// and store.ConnectorDefinitions.Revise takes any manifest, so a custom connector can put a source that // says outbound: false before one that does not. func (s *ConfigsSuite) TestNessyBesideAConnectorWithOneOutboundSourceAmongSeveralIsRefused() { s.useInternalApp() diff --git a/acceleration/internal/api/connection_proxy.go b/acceleration/internal/api/connection_proxy.go index b0c08e700a..faf76a2664 100644 --- a/acceleration/internal/api/connection_proxy.go +++ b/acceleration/internal/api/connection_proxy.go @@ -406,9 +406,8 @@ func waitSeconds(wait time.Duration) string { } // auditProxyCall records one direct call the connection's client sent (T44): the provider's -// status, nil when no answer came, the time to its answer and the host it reached -// (20261007170000_connector_invocations_and_audit.sql). The call happened whatever the row -// does, so a row that cannot be written is logged. +// status, nil when no answer came, the time to its answer and the host it reached. The call +// happened whatever the row does, so a row that cannot be written is logged. func (s *Server) auditProxyCall(ctx context.Context, connection store.ConnectorConnection, host string, status *int, latency int64) { ctx, cancel := detachedWrite(ctx) defer cancel() diff --git a/acceleration/internal/api/connection_proxy_test.go b/acceleration/internal/api/connection_proxy_test.go index 89948c1cd3..ae3bd66cd2 100644 --- a/acceleration/internal/api/connection_proxy_test.go +++ b/acceleration/internal/api/connection_proxy_test.go @@ -1029,7 +1029,7 @@ func (s *ConnectionProxySuite) connectedInAnotherApp(id string) (*testClient, st } // awayFromAMinuteBoundary waits out a minute that ends in under five seconds, so the calls a -// test counts next fall in one of the cap's windows (core.Limiter.Take). +// test counts next fall in one of the cap's windows (core.Limiter.Admit). func awayFromAMinuteBoundary() { if left := time.Until(time.Now().Truncate(time.Minute).Add(time.Minute)); left < 5*time.Second { time.Sleep(left) diff --git a/acceleration/internal/api/connection_records.go b/acceleration/internal/api/connection_records.go index bd5006ff15..8851a5eca8 100644 --- a/acceleration/internal/api/connection_records.go +++ b/acceleration/internal/api/connection_records.go @@ -24,7 +24,7 @@ type ConnectionInvocation struct { StartedAt time.Time `json:"started_at"` LatencyMs int64 `json:"latency_ms" doc:"From the call reaching the router to its answer, the router's own checks included."` ErrorType *InvocationErrorType `json:"error_type,omitempty" doc:"How the call failed. Absent for a call that answered."` - // The row's provider_status and error_message (20261031130000_connector_invocation_failures.sql). + // The row's provider_status and error_message. ProviderStatus *int `json:"provider_status,omitempty" doc:"The HTTP status the provider answered the call's last request with. Absent for a call that answered, and for one no request of which was answered: the router refused or held it, or the provider could not be reached."` ErrorMessage string `json:"error_message,omitempty" doc:"Why the call failed: the start of the provider's error body when it answered with a 4xx or a 5xx, else what the call's error said, at most 1 KiB. Every URL in it keeps only its scheme and host, and the connection's credential and the request's path are taken out. A call the router held for the provider's rate limit says rate limited by the router: retry after s. Absent for a call that answered, and for a call recorded before the router kept it."` Arguments []InvocationArgument `json:"arguments,omitempty" doc:"The shape of what the call was asked, sorted by name. Absent for a call asked with no arguments, for an incognito session's call, for arguments that were not a JSON object, and for a call recorded before the router kept it."` diff --git a/acceleration/internal/api/connection_records_test.go b/acceleration/internal/api/connection_records_test.go index 8e546e914e..d719b29a66 100644 --- a/acceleration/internal/api/connection_records_test.go +++ b/acceleration/internal/api/connection_records_test.go @@ -155,7 +155,7 @@ func (s *ConnectionRecordsSuite) TestACursorTheLogDidNotHandOutIsRefused() { "/v1/agents/connections/"+id+"/invocations?cursor=not-a-cursor", nil, nil)) } -// TestStoringACredentialLeavesOneGrantCreatedRowNamingTheRequest: the credentials write, then +// TestStoringACredentialAndDeletingTheConnectionEachLeaveOneRow: the credentials write, then // the delete, each once, and the deleted connection's rows still listed. func (s *ConnectionRecordsSuite) TestStoringACredentialAndDeletingTheConnectionEachLeaveOneRow() { connector := s.connector() diff --git a/acceleration/internal/api/connection_tool_approvals.go b/acceleration/internal/api/connection_tool_approvals.go index 5d907f79af..03a862f8d0 100644 --- a/acceleration/internal/api/connection_tool_approvals.go +++ b/acceleration/internal/api/connection_tool_approvals.go @@ -94,7 +94,7 @@ func (s *Server) registerToolApprovals(api huma.API) { } // approveConnectionTools pins the tools named at the digests the connection's last validate -// listed, when those are the digests sent, all or none (store.ReapproveConnectorTools). +// listed, when those are the digests sent, all or none (store.ConnectorToolPins.Reapprove). func (s *Server) approveConnectionTools(ctx context.Context, request *approveConnectionToolsRequest) (*approvedConnectionToolsResponse, error) { connection, err := s.reachableConnection(ctx, request.ID) if err != nil { diff --git a/acceleration/internal/api/connections.go b/acceleration/internal/api/connections.go index 528801bb99..afb5659c4e 100644 --- a/acceleration/internal/api/connections.go +++ b/acceleration/internal/api/connections.go @@ -124,7 +124,7 @@ func (ConnectionOwnerType) Schema(registry huma.Registry) *huma.Schema { // AgentLogSource has user too. When two enums share a constant name oapi-codegen prefixes // both with their type (enumsConflict, pkg/codegen/codegen.go:1553 in v2.8.0), which would // rename the Go SDK's User, Agent, System and Tool. Naming these constants keeps the - // others as they were, as PhoneOperation does in api/legacy.yaml. + // others as they were, as PhoneOperation does. registry.Map()["ConnectionOwnerType"].Extensions = map[string]any{ "x-enum-varnames": []string{"ConnectionOwnerTypeApp", "ConnectionOwnerTypeUser"}, } @@ -351,7 +351,7 @@ func (s *Server) createConnection(ctx context.Context, request *createConnection Label: strings.TrimSpace(sent.Label), } err = s.store.ConnectorConnections.Insert(ctx, s.connectors, &connection) - // Deleted since it was read above (DeleteConnectorDefinition), so answered as one never made. + // Deleted since it was read above (store.ConnectorDefinitions.Delete), so answered as one never made. if errors.Is(err, store.ErrNoConnectorDefinition) { return nil, invalidRequest(fmt.Sprintf("no such connector: %q", sent.ConnectorID)) } @@ -771,8 +771,8 @@ func actingUser(ctx context.Context) string { // copied by name, so a column added to the row stays hidden until it is added here. Sealed // credentials, cached tools and last_error are left out: the first is never shown, and the // other two are for the operations that write them (T18, T12). uses are the bindings that -// name it (store.ConnectorConnectionUses), definition how its revision compares with its -// connector's (store.ConnectorDefinitionStatuses), and client the OAuth client its grant was +// name it (store.ConnectorConnections.Uses), definition how its revision compares with its +// connector's (store.ConnectorDefinitions.Statuses), and client the OAuth client its grant was // issued to, nil when none is recorded (store.ConnectorConnection.Client), and validation what // its last validate found, nil before the first (store.ConnectorConnection.Validation). func connectionOf(connection store.ConnectorConnection, uses []store.ConnectionUse, definition store.DefinitionStatus, diff --git a/acceleration/internal/api/connections_test.go b/acceleration/internal/api/connections_test.go index 40811ef51b..5af951ba7e 100644 --- a/acceleration/internal/api/connections_test.go +++ b/acceleration/internal/api/connections_test.go @@ -593,7 +593,7 @@ sources: } // bindFixed makes an agent config of the suite's app bind the connection as its fixed one, -// in the shape store.ConnectorConnectionReferenced matches, and returns the config. The +// in the shape store.ConnectorConnections.DeleteUnbound matches, and returns the config. The // column is written directly, so these tests do not depend on what the config endpoints // accept. func (s *ConnectionsSuite) bindFixed(connectionID string) AgentConfig { diff --git a/acceleration/internal/api/connector_events.go b/acceleration/internal/api/connector_events.go index 67c04bb945..a7648913fd 100644 --- a/acceleration/internal/api/connector_events.go +++ b/acceleration/internal/api/connector_events.go @@ -26,8 +26,7 @@ const connectorEventsPath = "/v1/agents/connectors/events/" // (T38, AI-878; channels.md on connectors/planning, «Integration modes: one Slack app for each // customer»). The URL names the app, and with it the customer and the signing secret, so no // lookup by account picks the customer. It names the connector too, because an app id is -// unique only among one connector's records (connector_oauth_clients_provider_app, -// 20261006195500). +// unique only among one connector's records (connector_oauth_clients_provider_app). const providerAppEventsPath = "/v1/connectors/events/" // maxConnectorEventBytes caps the body read before it is verified. Slack's pages name no @@ -312,7 +311,7 @@ func readConnectorEvent(w http.ResponseWriter, r *http.Request) ([]byte, bool) { // each signal -> the connections of its account -> Resolver.Revoke, with when it ended // the messages -> ChannelBridge.Deliver, with app // none, none skipped and no signal -> an info line -// a provider app's delivery -> eventforward.Forward, queued for the customer's event +// a provider app's delivery -> eventforward.Forwarder.Forward, queued for the customer's event // destinations, handled when a signal or an answered message was in it // 200, or 500 so the provider retries // diff --git a/acceleration/internal/api/connector_provider_apps.go b/acceleration/internal/api/connector_provider_apps.go index 5452e45add..5e7488991e 100644 --- a/acceleration/internal/api/connector_provider_apps.go +++ b/acceleration/internal/api/connector_provider_apps.go @@ -441,7 +441,7 @@ func whyNotManaged(manifest core.Manifest) error { if !slackapps.Serves(manifest) { return invalidRequest(fmt.Sprintf("%s does not authorize at Slack, so the router creates no app for it", manifest.ID)) } - // The store refuses such a record too (store.PutConnectorOAuthClient); checked here so no + // The store refuses such a record too (store.ConnectorOAuthClients.Upsert); checked here so no // app is created at Slack that could never be recorded. if !slices.Contains(manifest.Client.Registration, core.ClientManaged) { return invalidRequest(fmt.Sprintf("%s takes no app the router creates: its client.registration is %v, which does not list managed", diff --git a/acceleration/internal/api/connectors.go b/acceleration/internal/api/connectors.go index 9375c644eb..054c9ad143 100644 --- a/acceleration/internal/api/connectors.go +++ b/acceleration/internal/api/connectors.go @@ -356,7 +356,7 @@ func (s *Server) createConnector(ctx context.Context, request *createConnectorRe } // deleteConnector deletes one of the caller's own definitions, refused while something uses -// it unless forced (store.DeleteConnectorDefinition). +// it unless forced (store.ConnectorDefinitions.Delete). func (s *Server) deleteConnector(ctx context.Context, request *deleteConnectorRequest) (*struct{}, error) { customerID, ok := CustomerFrom(ctx) if !ok { diff --git a/acceleration/internal/api/connectors_test.go b/acceleration/internal/api/connectors_test.go index 113784d546..7bfd057855 100644 --- a/acceleration/internal/api/connectors_test.go +++ b/acceleration/internal/api/connectors_test.go @@ -715,7 +715,7 @@ func (s *ConnectorsSuite) TestABindingToAConnectorDeletedMeanwhileIsRefused() { // duringADeleteOf makes call while a delete of the app's connector id holds its lock on the // definition: a SHARE lock on connector_oauth_clients holds the delete at its DELETE there, -// which comes after that lock (store.DeleteConnectorDefinition). The call is let go once it +// which comes after that lock (store.ConnectorDefinitions.Delete). The call is let go once it // waits for the definition, and it answers after the delete committed. Suites beside this one // may wait on the table meanwhile; the waits counted are the delete's and the call's alone. func (s *ConnectorsSuite) duringADeleteOf(id string, call func() (int, string)) (int, string) { @@ -726,7 +726,7 @@ func (s *ConnectorsSuite) duringADeleteOf(id string, call func() (int, string)) s.Require().NoError(err) deleted := make(chan int, 1) go func() { deleted <- s.serverClient.do(http.MethodDelete, "/v1/agents/connectors/"+id, nil, nil) }() - // The two seconds and the ten milliseconds are assertTheWaitEnded's (internal/store/credentials_test.go). + // The two seconds and the ten milliseconds are assertTheWaitEnded's (internal/store/credential_lock_test.go). s.Require().Eventually(func() bool { return s.waitingFor(`DELETE FROM "connector_oauth_clients"`, id) == 1 }, 2*time.Second, 10*time.Millisecond, "the delete waits at its DELETE") type answer struct { diff --git a/acceleration/internal/api/dispatchws.go b/acceleration/internal/api/dispatchws.go index 06437b1934..e36e6d3bb9 100644 --- a/acceleration/internal/api/dispatchws.go +++ b/acceleration/internal/api/dispatchws.go @@ -36,7 +36,7 @@ const maxCapacity = 1024 // // Server-side only, and this is the clearest case of why: a worker is offered other // people's callers, so anything that can open this socket can answer for the whole app. -// socketRoutes already refuses a client-side caller in the middleware; the same question +// withServerSide already refuses a client-side caller in the middleware; the same question // is asked again here because this is the socket where being wrong is worst, and a second // check costs one comparison. func (s *Server) dispatchCalls(w http.ResponseWriter, r *http.Request) { diff --git a/acceleration/internal/api/linq_channel_test.go b/acceleration/internal/api/linq_channel_test.go index c50e5811c2..1caf28b37c 100644 --- a/acceleration/internal/api/linq_channel_test.go +++ b/acceleration/internal/api/linq_channel_test.go @@ -194,7 +194,7 @@ func (s *LinqChannelSuite) TestAPhotoWithoutACaptionIsAnswered() { } // A photo whose URL answers 404, such as one Linq deleted, is answered with a short reply -// that it could not be opened (api.threadPhotos), not left in silence. +// that it could not be opened (api.messagePhotos), not left in silence. func (s *LinqChannelSuite) TestAPhotoLinqNoLongerServesIsAnsweredThatItCouldNotBeOpened() { s.answersWith("vision/vision-model") chat, asked := s.utils.uuid(), len(s.vision.replies()) diff --git a/acceleration/internal/api/oauth_clients.go b/acceleration/internal/api/oauth_clients.go index 4c39e356f0..8ee642402a 100644 --- a/acceleration/internal/api/oauth_clients.go +++ b/acceleration/internal/api/oauth_clients.go @@ -243,7 +243,7 @@ func (s *Server) setConnectorOAuthClient(ctx context.Context, request *oauthClie ProviderAppID: sent.ProviderAppID, } // The app the customer acts in now is the record's pin when this put creates it; a put - // that replaces the record keeps the pin it has (store.PutConnectorOAuthClient). + // that replaces the record keeps the pin it has (store.ConnectorOAuthClients.Upsert). if s.stream != nil { record.StreamAppPK, err = s.stream.Pin(ctx, customerID) if err != nil { @@ -267,7 +267,7 @@ func (s *Server) setConnectorOAuthClient(ctx context.Context, request *oauthClie record.SigningKEKVersion = s.connectorSecrets.CurrentVersion() } created, err := s.store.ConnectorOAuthClients.Upsert(ctx, record) - // Deleted since it was read above (DeleteConnectorDefinition), so answered as one never made. + // Deleted since it was read above (store.ConnectorDefinitions.Delete), so answered as one never made. if errors.Is(err, store.ErrNoConnectorDefinition) { return nil, notFound("no such connector") } diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 3eaa8a0a84..b75d07f22e 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -803,7 +803,7 @@ func scheduledPrompt(claimed store.ClaimedScheduledTask, now time.Time) string { } // withOccurrence gives a re-dued one-shot back the instant its start names. -// An edit re-dues the occurrence at the edit time (store.SaveScheduledTask), +// An edit re-dues the occurrence at the edit time (store.ScheduledTasks.Update), // so its next run no longer reads as the start and FromStored cannot tell // which pass of a fall-back hour the start is; the run the edit settled can. func (s *Server) withOccurrence(ctx context.Context, claimed store.ClaimedScheduledTask) store.ClaimedScheduledTask { diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 5934901bce..09ff055a39 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -1293,9 +1293,8 @@ func (n operationName) ServeHTTP(_ http.ResponseWriter, r *http.Request) { // withServerSide refuses the generated operations only a backend may reach. // // It sits after withCustomer, because refusing a caller for what it is means having worked -// out what it is first. The four sockets are left out of the embedded spec by being left -// out of generation, so socketRoutes puts them back rather than leaving them to be open by -// omission. +// out what it is first. The routes served by hand are in the spec too (documentHandWritten), +// so none is open by omission. // // A caller that authenticated and asked for one of these gets a 403 rather than a 401: it // has already proved who it is, so there is nothing to be learned from a specific answer diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go index 879769f003..6b15a4d59d 100644 --- a/acceleration/internal/api/sync.go +++ b/acceleration/internal/api/sync.go @@ -80,7 +80,7 @@ func (*SyncAgentRequest) TransformSchema(_ huma.Registry, schema *huma.Schema) * // The caps are the ones the same values have elsewhere: 63 is the longest alias // AgentConnectorBinding's name pattern allows, 64 the longest custom connector id // (custom_ and 57 more, internal/api/connectors.go) and 120 the longest connection label -// (CreateConnectionRequest). A built-in connector id is shorter than a custom one. +// (ConnectionRequest). A built-in connector id is shorter than a custom one. type LeftOutConnector struct { Name string `json:"name" minLength:"1" maxLength:"63" doc:"The alias agent.yaml gave the connector."` ConnectorId string `json:"connector_id" minLength:"1" maxLength:"64" doc:"The connector agent.yaml named, or the alias when it named none."` diff --git a/acceleration/internal/api/threadhooks.go b/acceleration/internal/api/threadhooks.go index 2156a1a7d0..a2f37b3036 100644 --- a/acceleration/internal/api/threadhooks.go +++ b/acceleration/internal/api/threadhooks.go @@ -57,7 +57,7 @@ const threadTurnLease = askTimeout + 30*time.Second // Session.FollowUp(text, photos), its author the person's message is already // (WithAuthor); a photo the agent cannot see in the channel: none is written // or that cannot be fetched is dropped, with a -// note to the turn (threadPhotos) +// note to the turn (messagePhotos) // wait until the turn is over; close the session it opened; let go of the lease // linkedThread is the external thread a channel holds, when it is a thread channel of the diff --git a/acceleration/internal/api/user_phones_test.go b/acceleration/internal/api/user_phones_test.go index 0dd43e2290..7ce790e9ce 100644 --- a/acceleration/internal/api/user_phones_test.go +++ b/acceleration/internal/api/user_phones_test.go @@ -475,7 +475,7 @@ func (s *LinqSandboxSuite) SetupTest() { // Catches a one-to-one chat under a config with episode_cards off, which opens no episode, whose // replies would reach nobody the sandbox lists: the person a chat's replies reach is its // episode's row, and with none it is the person who started the chat -// (store.ChannelThreadStarter), as the sender admit checked. Its reply and a scheduled delivery +// (store.ChannelThreads.Starter), as the sender admit checked. Its reply and a scheduled delivery // go out (AI-2856). func (s *LinqSandboxSuite) TestAOneToOneChatUnderAConfigWithTheCardsOffIsAnswered() { s.config.EpisodeCards.On = false @@ -490,7 +490,7 @@ func (s *LinqSandboxSuite) TestAOneToOneChatUnderAConfigWithTheCardsOffIsAnswere } // A group chat under a config with episode_cards off has no episode and no one person, and its -// replies and scheduled deliveries reach the person who started it (store.ChannelThreadStarter), +// replies and scheduled deliveries reach the person who started it (store.ChannelThreads.Starter), // whom the sandbox lists, as base 518ac7e9f's did through the episode it opened whatever the // config said (AI-2856 R1.1). Catches a group chat with no episode whose replies reach nobody, // so the sandbox holds them back. diff --git a/acceleration/internal/audiofloor/hearer.go b/acceleration/internal/audiofloor/hearer.go index ded63ac91f..580b7ede74 100644 --- a/acceleration/internal/audiofloor/hearer.go +++ b/acceleration/internal/audiofloor/hearer.go @@ -261,7 +261,7 @@ func (h *Hearer) rule(policy Policy, turn harness.FlowTurn, answer Answer) (Chec } // ruleStill reads the model's answer about a turn whose words have held still as the policy's -// cap reads one (heldStill): the turn has ended with the floor free, on the model's own ruling, +// cap reads one: the turn has ended with the floor free, on the model's own ruling, // whatever p_eot says. It counts no check in a row: the run is a pause's, and this is no pause the // speech gate heard. func (h *Hearer) ruleStill(policy Policy, answer Answer) (Check, error) { diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index 277a287bbc..4991566c5f 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -420,7 +420,7 @@ func (r *Runner) mayRing(ctx context.Context, campaign store.Campaign, contact s if err != nil { return store.Campaign{}, false, err } - // StopContact marks a contact in a call with the reason it would end with. + // store.CampaignContacts.Stop marks a contact in a call with the reason it would end with. marked, _, err := r.store.CampaignContacts.Get(ctx, campaign.ID, contact.ID) if err != nil { return store.Campaign{}, false, err diff --git a/acceleration/internal/channelbridge/AGENTS.md b/acceleration/internal/channelbridge/AGENTS.md index b9fe30f350..06863c69f3 100644 --- a/acceleration/internal/channelbridge/AGENTS.md +++ b/acceleration/internal/channelbridge/AGENTS.md @@ -17,9 +17,9 @@ Slack -> POST /v1/connectors/events/{connector}/{app} api.receiveProviderAppEv connection store.AppConnectionByAccount(customer, connector, provider unit) agent store.AgentConfigsBindingConnection: exactly one, else dropped addressed a reply not to the bot on a thread nobody linked waits - (store.WaitChannelThreadMessage) for the message that links it - thread store.LinkChannelThread: one thread channel per external thread - accept store.AcceptChannelInbound, one transaction: claim (a retried + (store.WaitingMessages.Wait) for the message that links it + thread store.ChannelThreads.Link: one thread channel per external thread + accept store.ChannelInbounds.Accept, one transaction: claim (a retried delivery is dropped) and queue the message, the config and the delivery's forward; the message that starts its thread takes the replies that waited and queues them after it, with no forward @@ -29,7 +29,7 @@ inbound worker (every router) off the request wakes: at start, on wake (a message queued), on a finished write, at the first queued row due (at least 1 s), and at least once a lease (1 min) claims until the router's stop signal (Start's ctx) or Close; the writes taken finish - store.ClaimChannelInbound: the oldest queued row of each thread channel, due, + store.ChannelInbounds.Claim: the oldest queued row of each thread channel, due, lease 1 min, SKIP LOCKED, at most 16 in flight per router admit from the row and its thread channel: chat person and members (linq), keywords (answer marked on the row, then sent), gate (texting connectors); @@ -40,7 +40,7 @@ inbound worker (every router) off the request support_customer_id, support_agent_id) -> Stream Chat upload: each downloaded photo to the channel; fails: the attempt fails, but on the last attempt or a 4xx but 429 it is left out; none and nothing else: done, nothing written - store.SaveChannelInboundMedia: the new uploads on the row (media "uploaded"), under its + store.ChannelInbounds.SaveMedia: the new uploads on the row (media "uploaded"), under its lease; fails: the attempt fails, nothing written; lease gone: returns, the lease holder writes store.AgentConfig of the row's config id (queuedEpisode): episode_cards off, or the @@ -64,7 +64,7 @@ inbound worker (every router) off the request row's forward -> Options.Unanswered (Forwarder.ForwardUnanswered), once per delivery a Stream Chat 4xx other than 429 (refusedForGood): failed at once, as above - store.PruneChannelInbound once an hour: done rows after a day, failed after 30 + store.ChannelInbounds.Prune once an hour: done rows after a day, failed after 30 Stream Chat -> message.new -> api.receiveMessageEvent (the hook route, served one more release as a way back: the router points no message hook; Chat delivery reaches the same routing through chat_inbound) bridged true: nothing, the worker hands it over any other message without source (somebody writing in the app) -> api.answerThread @@ -91,15 +91,15 @@ conversation flush: final text stored (UpdateMessagePartial, no webhook) | Term | What it is | In code | | --- | --- | --- | | thread channel | The agent channel that holds one external thread, `agent:thread-` | `store.ChannelThread.ChannelID` | -| thread link | One external thread (customer, connector, provider unit, thread key) to its thread channel, with the connection replies use | table `channel_threads`, `store.LinkChannelThread` | +| thread link | One external thread (customer, connector, provider unit, thread key) to its thread channel, with the connection replies use | table `channel_threads`, `store.ChannelThreads.Link` | | author user | The Stream Chat user an external author writes as: one per customer, connector, provider unit and author | `authorUserID` | | episode card | One message in the omni-channel of whoever started a thread, with `source`, for the thread's episode (T41) | `internal/omnichannel`, table `episodes` | ## Rules -- **Acknowledge fast, write later, on any router.** `Deliver` touches Postgres only, so the provider gets its answer within its limit (Slack: three seconds, https://docs.slack.dev/apis/events-api/). It queues each message it takes (`channel_thread_inbound`), and a worker on any router writes it into Stream Chat with its episode card, so a router that stops after the answer loses nothing. A message the worker gives up was answered by no agent, so the delivery stored with it (`unanswered`, from the events route) goes to the customer's event destinations of unhandled events (AI-924). The claim, the take of the replies that waited and the queue insert are one transaction (`store.AcceptChannelInbound`): a store that fails leaves the message unclaimed and its replies waiting, and answers 500, so the provider's retry queues the message and its replies. The transaction runs off the request (`detached`: `context.WithoutCancel`, bounded by `Options.QueueTimeout`, 10 s), so a provider that hangs up meanwhile leaves the message queued or unclaimed, never claimed with no row. Everything after the queue (`admit`, the write, the card) is the worker's, so a store that fails there is retried by the queue, never answered 500; one that fails the card costs the card alone (below). Check: `go test -tags integration -run 'TestEventForwardingSuite/(TestAMessageARouterQueued|TestAMessageWhose|TestAReplyThatWaited|TestTwoDeliveries)' ./internal/api`. +- **Acknowledge fast, write later, on any router.** `Deliver` touches Postgres only, so the provider gets its answer within its limit (Slack: three seconds, https://docs.slack.dev/apis/events-api/). It queues each message it takes (`channel_thread_inbound`), and a worker on any router writes it into Stream Chat with its episode card, so a router that stops after the answer loses nothing. A message the worker gives up was answered by no agent, so the delivery stored with it (`unanswered`, from the events route) goes to the customer's event destinations of unhandled events (AI-924). The claim, the take of the replies that waited and the queue insert are one transaction (`store.ChannelInbounds.Accept`): a store that fails leaves the message unclaimed and its replies waiting, and answers 500, so the provider's retry queues the message and its replies. The transaction runs off the request (`detached`: `context.WithoutCancel`, bounded by `Options.QueueTimeout`, 10 s), so a provider that hangs up meanwhile leaves the message queued or unclaimed, never claimed with no row. Everything after the queue (`admit`, the write, the card) is the worker's, so a store that fails there is retried by the queue, never answered 500; one that fails the card costs the card alone (below). Check: `go test -tags integration -run 'TestEventForwardingSuite/(TestAMessageARouterQueued|TestAMessageWhose|TestAReplyThatWaited|TestTwoDeliveries)' ./internal/api`. - **A queued inbound message is written once, under its own id** (`inbound.go`). The worker writes a row of `channel_thread_inbound` under the Stream message id `inboundMessageID`: the thread channel's id, `-`, and the provider's id for the message. Stream Chat keeps a message id unique in the whole app, so the thread channel is part of it. A provider id longer than the 255 characters Stream Chat takes leaves room for, or with a character other than letters, digits, `.`, `_` and `-`, is its SHA-256 in hex after `=`. A write whose answer was lost, or whose lease ran out while Stream Chat stored it, is refused the second time with HTTP 400, code 4 and «a message with ID … already exists»; `alreadyWritten` takes that as written, for the message and for the episode card (whose id is the episode's). Example: Slack `1793125611.816139` in `thread-0b7c…` is message `thread-0b7c…-1793125611.816139`. Check: `go test -tags integration -run TestInboundSuite ./internal/channelbridge`. -- **A queued message that fails is written again, then given up.** Any failure (the thread, `admit`, the write, the hand-off) but a refusal retries the row after each of `Options.InboundRetries` (2 s, 10 s, 30 s, 2 min, 10 min); the thread's later messages wait behind it, so a thread stays in order. A STOP on a connector with an opt-out channel is never given up (`optsOut`): past the scheduled waits it runs again every 10 min (the last wait) until its opt-out is recorded. After the last, any other row is `failed` (kept 30 days), the worker logs a WARN, and the row's `forward` goes to `Options.Unanswered`, which cmd/router binds to `Forwarder.ForwardUnanswered`. Only the first given-up message of a delivery whose forward is queued forwards it (`store.FailChannelInbound`, under a lock on the delivery, in the transaction that gives it up; the row is marked `forward.forwarded`): the destinations key a forward by the delivery only while it is queued, and a thread's messages are given up minutes apart. A forward that fails, or a router that stops before the transaction commits, leaves the delivery to the next of its messages given up. Check: `go test -tags integration -run 'TestInboundSuite/TestADeliveryWhoseForwardFailed' ./internal/channelbridge`. Stream Chat answering a 4xx other than 429 refuses the next attempt too (`refusedForGood`, as a reply's `retryable`): the row is given up at once, so the thread's later messages do not wait 13 minutes. A message whose episode started after it was queued writes the episode card again, since an earlier attempt may have opened the episode and stopped before its card (failed, router stopped, lease ran out); a later message of the episode writes none. Example: Stream Chat answers 429 for 13 minutes; the customer's `unhandled` destination gets the Slack delivery once. +- **A queued message that fails is written again, then given up.** Any failure (the thread, `admit`, the write, the hand-off) but a refusal retries the row after each of `Options.InboundRetries` (2 s, 10 s, 30 s, 2 min, 10 min); the thread's later messages wait behind it, so a thread stays in order. A STOP on a connector with an opt-out channel is never given up (`optsOut`): past the scheduled waits it runs again every 10 min (the last wait) until its opt-out is recorded. After the last, any other row is `failed` (kept 30 days), the worker logs a WARN, and the row's `forward` goes to `Options.Unanswered`, which cmd/router binds to `Forwarder.ForwardUnanswered`. Only the first given-up message of a delivery whose forward is queued forwards it (`store.ChannelInbounds.Fail`, under a lock on the delivery, in the transaction that gives it up; the row is marked `forward.forwarded`): the destinations key a forward by the delivery only while it is queued, and a thread's messages are given up minutes apart. A forward that fails, or a router that stops before the transaction commits, leaves the delivery to the next of its messages given up. Check: `go test -tags integration -run 'TestInboundSuite/TestADeliveryWhoseForwardFailed' ./internal/channelbridge`. Stream Chat answering a 4xx other than 429 refuses the next attempt too (`refusedForGood`, as a reply's `retryable`): the row is given up at once, so the thread's later messages do not wait 13 minutes. A message whose episode started after it was queued writes the episode card again, since an earlier attempt may have opened the episode and stopped before its card (failed, router stopped, lease ran out); a later message of the episode writes none. Example: Stream Chat answers 429 for 13 minutes; the customer's `unhandled` destination gets the Slack delivery once. - **A card that fails costs the card, not the answer.** An episode `Cards.Open` cannot open (the store) or a card `Cards.Write` cannot write (Stream Chat, 4xx or 5xx) is logged at ERROR (`could not open the episode of an inbound message`, `could not write the episode card of a thread`), and the message is still written and handed to the agent on the same attempt, as before the queue: retrying it would hold the thread's later messages back for up to 13 minutes, and a 4xx would give it up unanswered. After a failed `Cards.Write` that episode has no card: a later message of the thread finds the episode open and writes none. After a failed `Cards.Open` no episode is open (`Open` returns no episode), so the thread's next message opens one and writes its card. A card Stream Chat already holds (`alreadyWritten`) is no failure. Example: the omni-channel refuses the card with 400; Alice's Slack message is answered once, with no card. Check: `go test -tags integration -run 'TestInboundSuite/(TestAMessageWhoseCard|TestAMessageWhoseEpisode|TestACardStreamChatAlreadyHolds)' ./internal/channelbridge`. - **The worker hands the message to the agent; the message hook does not.** A customer's app that sends this router no `message.new` (its own hook list saved, or the hook pointed at another router) still gets its replies. After the write and the card, `writeQueued` hands the message to `Answer`, which `Start` is given (cmd/router: `api.Server.AnswerQueued`, after `api.NewServer`, which takes the bridge): the message as Stream Chat answered the write, or rebuilt from the row (`writeInto`) when Stream Chat refused it as already written, as that answer carries no message. `Answer` claims the message's turn (`store.ClaimTurn`) inside the attempt, so the row is done only after the claim: a router that stops between the write and the claim leaves the row queued, and the next attempt is refused as written, rebuilds the message and claims it. A claim that fails is the attempt failing; a message whose turn was claimed already is done with no turn. `Answer` skips what the hook skips (`api.addressed`): a message with no text, photo or voice recording, such as a Linq video alone, is not answered. Of a message's files `writeInto` writes only its photos (`photos`, an `image/*` file), so a thread message is answered from its text and photos. A message Stream Chat bounces (the write's answer has type `error`, as a moderation block does) is not handed over: Stream Chat sends no `message.new` for it, and the row is done. A router with no sessions (no LLM router) hands nothing over, as its hook answers no thread channel. It is handed the thread with the chat person `admit` just recorded, so a Linq 1:1 chat's first message is offered the person's tools (`api.threadPerson`). The turn (`answerThread` past its claim) waits for the thread's turn and the reply, up to `askTimeout`, so it runs on a goroutine and context of its own, off the worker's slot. A draining router waits for it (below); `Close` does not, and a turn the drain's end cuts is lost as one the hook started was. `writeInto` sets `stream_agents_bridged: true` (`BridgedField`) on the message, a name of this router's own since the customer's clients write custom fields in the same app, and the hook skips a message in a thread channel that has it; a message somebody writes into the channel through Stream Chat itself has none and is answered by the hook. Stream Chat keeps a message's custom fields and its `message.new` carries them at the top level of the message, as it carries the `source` the agent writes on its own (`api.messageEvent.Source`). Only JSON `true` is the mark. Example: Slack `1793125611.816139` is written as `thread-0b7c…-1793125611.816139`, its turn is claimed and the reply leaves; the `message.new` about it starts nothing. Check: `go test -tags integration -run 'TestInboundSuite/(TestAWritten|TestAMessageStreamChatAlreadyHoldsIsHanded|TestAMessageWhoseTurn|TestATurnRuns)' ./internal/channelbridge` and `go test -tags integration -run 'TestSlackChannelSuite/(TestAMessageIsAnsweredWithNo|TestAMessageNewFor|TestAMessageAnAppUser|TestARetriedDeliveryIsAnswered|TestAMessageWrittenBefore|TestAMessageWhoseTurnWasClaimedBefore)' ./internal/api` and `go test -tags integration -run 'TestLinqChannelSuite/(TestAVideoIsNotPassedOn|TestALinqOneToOneChatSchedules)' ./internal/api`. - **One Info line per step, ids only:** `accepted an inbound message`, `queued an inbound message` (Deliver), `an inbound message is written into its thread channel`, `an inbound message is handed to the agent`, `an inbound message is done`, `... is tried again` (retried), `an inbound message Stream Chat bounced is not handed to the agent`, `gave up an inbound message` (WARN). @@ -107,7 +107,7 @@ conversation flush: final text stored (UpdateMessagePartial, no webhook) - **A retried delivery is dropped by the provider's message id**, in the thread channel (`channel_thread_messages`). Example: Slack sends the same `message` event with `X-Slack-Retry-Num: 1`; the claim fails and nothing is written. - **The agent gets the person's words without the mention of the account** (AI-990 F29). `take` writes `MessageRule.WithoutMention` of the connection's pinned revision: in Slack «<@U0000BOT> is the build green?» is written as «is the build green?». A mention of anybody else stays; a message that is only the mention is written as it is. A connector without `addressed.mention` is written as the provider sent it. Check: `go test -tags integration -run 'TestSlackChannelSuite/(TestAMessageIsWritten|TestAMentionInAThread)' ./internal/api`. - **A message the connection's revision does not read is dropped** (AI-2133). The events route reads a delivery with the latest revision, and `take` reads each message again with the connection's pinned one (`read`). A message only a newer revision reads, such as a WhatsApp photo, video or document by its caption (revision 2) on a connection still on revision 1, is logged at warn («dropped an inbound message the revision of its connection does not read») and dropped, as a message nobody answers is: a retry finds the same revision, so a 500 would only repeat. A reply that waited (below) and that the connection's revision does not read when the message that starts its thread takes it, such as one the connection was pinned away from meanwhile, is dropped the same way («dropped a waiting reply the revision of its connection does not read», AI-2743), and that message is answered. The dropped reply is deleted and never read again. Messages that come after the connection's next credential save are read with the latest revision. Check: `go test -tags integration -run 'TestWhatsAppChannelSuite/TestAConnectionStillOnRevision1' ./internal/api` and `go test -tags integration -run 'TestSlackChannelSuite/TestAWaitingReply' ./internal/api`. -- **A photo goes with the person's message** (AI-2094). `take` carries the files of the message as the connection's pinned revision reads them (`MessageRule.Media`), and `writeInto` writes each one whose MIME type is `image/*` as a Stream Chat `image` attachment (`image_url`) on the thread message, which the message hook hands the model (`api.threadPhotos`, AI-2093). Another file, such as a video, is not written: the agent gets the text alone, and a message with neither text nor a photo is not answered. A connection on a revision without `media` (Linq revision 2, until its API key is saved again) writes no photo. Example: a Linq [photo, «What is in this photo?»] is one message with that text and one image attachment. Check: `go test -tags integration -run 'TestLinqChannelSuite/(TestAPhoto|TestAVideo|TestAConnectionStillOnRevision2)' ./internal/api`. +- **A photo goes with the person's message** (AI-2094). `take` carries the files of the message as the connection's pinned revision reads them (`MessageRule.Media`), and `writeInto` writes each one whose MIME type is `image/*` as a Stream Chat `image` attachment (`image_url`) on the thread message, which the message hook hands the model (`api.messagePhotos`, AI-2093). Another file, such as a video, is not written: the agent gets the text alone, and a message with neither text nor a photo is not answered. A connection on a revision without `media` (Linq revision 2, until its API key is saved again) writes no photo. Example: a Linq [photo, «What is in this photo?»] is one message with that text and one image attachment. Check: `go test -tags integration -run 'TestLinqChannelSuite/(TestAPhoto|TestAVideo|TestAConnectionStillOnRevision2)' ./internal/api`. - **A photo the provider names by id is downloaded with the connection's credential and uploaded to the thread channel** (AI-2740, WhatsApp revision 3). Its URL needs the token, so neither Stream Chat nor the model can read it. Before the episode opens, `writeQueued` has `download` look the photo up (`MessageRule.MediaLookup`) and GET the file it names, both through the connection's own client (`core.Transports.Client`), within `downloadTimeout` (10 s). The lookup answer may be up to 64 KiB and the file up to 5 MiB (api's `maxRunImageBytes`). The file's bytes must sniff as an image. `upload` stores it on the thread channel as the person (`conversation.Upload`), and `writeInto` writes that upload as the image attachment. The connection's revision decides where the lookup goes, and `core.ResolvedManifest.MediaFile` refuses a file on any host but the manifest's, so the token reaches Graph and `lookaside.fbsbx.com` only. A file named by id whose type is not `image/*` is neither looked up nor written. A photo that cannot be downloaded is left out and logged at warn with the connection and no URL («a photo the provider names by id could not be downloaded»): its caption is answered as on revision 2. A message that is only such files, with no text, is not written or answered and opens no episode; the row is done, so nothing loops. An upload Stream Chat fails is the attempt failing, as its other writes are: the row is tried again and downloads again. Once a photo is uploaded, the row keeps where Stream Chat stored it (`core.Media.Uploaded`, the `uploaded` key of the row's `media`, AI-2757) before the message is written, and the photo's type as its bytes sniffed: a later attempt of the row, after a write Stream Chat failed or an answer that was lost, writes that upload and neither looks the photo up nor uploads it again, so a photo alone is still answered once Meta's URL has expired. A row that cannot keep its uploads is the attempt failing. A build from before it ignores the key and downloads again. On the row's last attempt, or when Stream Chat refuses the upload with a 4xx other than 429 (`refusedForGood`), the photo is left out and logged at warn («a photo Stream Chat did not store is left out»): a captioned photo is answered by its caption, and a photo alone is not written or answered, and opens no episode. An attempt that Stream Chat refuses as already written rebuilds the message with the row's uploads, never a provider URL. Every attempt that has no upload of the photo looks the file up again, since Meta's URL lasts 5 minutes. A connection on revision 2 reads the photo by its caption and downloads nothing. Example: a WhatsApp photo with «Is this tooth chipped?» is one message with that text and one image at its Stream Chat CDN URL. Check: `go test -tags integration -run 'TestWhatsAppChannelSuite/(TestAPhoto|TestARetriedPhoto|TestAConnectionStillOnRevision2)' ./internal/api`. - **The person's message has no `source`.** That is how the message hook (`api.addressed`) knows a person wrote it, and how the conversation on the channel reads it back as a user turn (`conversation.messageFromThread`). The session is told it with `FollowUp`, which writes no second copy. - **A thread channel is a conversation.** The session that answers holds its persistent conversation on the thread channel, so the reply is kept there: the Router's own session (`api.threadSession`) and one a caller opens through `POST /v1/agents/sessions` with `agent_id` naming the channel (`api.threadConversation`). The hook does not hand a thread channel's message to a dispatch worker. @@ -115,7 +115,7 @@ conversation flush: final text stored (UpdateMessagePartial, no webhook) - **One hand-off point for replies.** The conversation calls `Reply` once a reply's final text is stored; the webhook never carries it (`UpdateMessagePartial` sends none). `Reply` claims the reply by its Stream message id, so a reply written again is sent once. Example: a reply a login later marks is told twice and leaves once. - **One turn per thread, across routers.** The hook leases the thread's turn in `channel_turns` (`store.ChannelTurns.Take`) before it tells the session, and lets go after the reply; a router that stops holds it at most `askTimeout` + 30 s. A session the hook opens is closed after the turn, so the next turn on any router reopens the conversation from the channel. Example: router A answers Alice; Bob's message reaches router B, which waits for A's lease, then answers with Alice's turn in its history. - **A failed send is sent again.** No answer, a 5xx, a 429, or a refusal the scheme reads as transient or rate limited: the reply is sent again after each of `Options.RetryBackoff` (2 s, 10 s, 30 s). The claim stays while it is retried; a reply never sent is unclaimed, so its next hand-off sends it. A refusal is unclaimed too, so a refused reply leaves no `reply` row in `channel_thread_messages` (AI-990 F28), and the log line names the answer's `error` member. A 2xx answer the bridge cannot read keeps the claim, since the provider may have posted the reply. Example: Slack answers HTTP 200 `{"ok": false, "error": "not_in_channel"}`; the row is gone and the log says `error "not_in_channel"`. -- **A reply that arrives before its thread's link waits for it** (AI-990 F31a). Slack retries a mention whose delivery failed after the replies in its thread arrived (https://docs.slack.dev/apis/events-api/, «Retries»). A reply that is not to the bot, on a thread nobody linked, is kept in `channel_thread_waiting` for 10 minutes. When a message that starts its thread links it, it takes those replies, and they are answered after it, in the same delivery. Its retry takes them too when its first delivery linked the thread and failed: the take is in the transaction that claims and queues (`store.AcceptChannelInbound`), so a failure leaves them waiting; each waiting row is taken once. A reply the connection's revision does not read is dropped there (above); any other failure to read one fails the message, which waits for the retry with its replies. A link made by a reply, such as a mention in a thread of people, takes none: some came before the bot was spoken to (AI-989). The reply looks for the link again after it is kept, so a link made meanwhile finds it or it finds the link. Check: `go test -tags integration -run 'TestSlackChannelSuite/(TestAReply(ThatArrivesBefore|ThatWaited)|TestAWaitingReply|TestAMentionWhoseWaitingReply)' ./internal/api`. +- **A reply that arrives before its thread's link waits for it** (AI-990 F31a). Slack retries a mention whose delivery failed after the replies in its thread arrived (https://docs.slack.dev/apis/events-api/, «Retries»). A reply that is not to the bot, on a thread nobody linked, is kept in `channel_thread_waiting` for 10 minutes. When a message that starts its thread links it, it takes those replies, and they are answered after it, in the same delivery. Its retry takes them too when its first delivery linked the thread and failed: the take is in the transaction that claims and queues (`store.ChannelInbounds.Accept`), so a failure leaves them waiting; each waiting row is taken once. A reply the connection's revision does not read is dropped there (above); any other failure to read one fails the message, which waits for the retry with its replies. A link made by a reply, such as a mention in a thread of people, takes none: some came before the bot was spoken to (AI-989). The reply looks for the link again after it is kept, so a link made meanwhile finds it or it finds the link. Check: `go test -tags integration -run 'TestSlackChannelSuite/(TestAReply(ThatArrivesBefore|ThatWaited)|TestAWaitingReply|TestAMentionWhoseWaitingReply)' ./internal/api`. - **A reply that waited was already forwarded as unhandled** (AI-1001). When it arrives, no agent answers it, so `Deliver` returns `answered` false and the events route sends its delivery to the customer's destinations of unhandled events. When the mention then links the thread, the agent answers the reply too. Nothing takes the forward back, and no event says that the agent answered it. The reply is queued with no forward, so if its write fails after the take, nothing is forwarded: the forward `Deliver` was handed is the mention's delivery, which the destinations must not get as unhandled, and they already have the reply's own. Example: Bob's reply arrives at 10:00:01 and goes to the customer's URL; Slack retries Alice's mention at 10:01:00; the agent answers both. Check: `go test -tags integration -run 'TestEventForwardingSuite/TestAReplyThatWaited' ./internal/api`. - **A refusal the transport cannot see still ends the grant.** Slack answers a revoked token with HTTP 200 `invalid_auth`; the scheme's `Classify` reads it and `Reply` calls `Resolver.Invalidate`. - **One agent per connection.** The agent that answers is the one agent config of the customer that binds the connection as `fixed`. None or two: the message is dropped and logged. @@ -123,9 +123,9 @@ conversation flush: final text stored (UpdateMessagePartial, no webhook) - **One card for each thread, in its starter's omni-channel.** The first message of a thread opens its episode; the later ones, anybody's, find it open. Example: Alice starts a thread, Bob replies; the card is in Alice's omni-channel only. Slack has no phone number, so a Slack user's omni-channel is keyed by workspace and user until account linking joins it to a phone's. - **A thread gets cards only under a config that writes them.** The worker reads the agent config the queued row names as it is stored when it writes the message (`queuedEpisode`), and opens the thread's episode only when its `episode_cards` is `record` or `on` (`store.AgentConfig.WritesCards`): `off`, the default, opens none, so the thread has no card and no summary, and its message is written and answered as any other. A config deleted since the message was queued opens none and logs nothing. Example: support-sms has the cards off; a patient's SMS is answered, and no episode row is written. Check: `go test -tags integration -run 'TestInboundSuite/(TestAThreadUnder|TestAMessageQueuedBefore|TestAMessageWhoseConfigWasDeleted)' ./internal/channelbridge`. - **A connector gets cards once it has an episode source** (`episodeSources`): `slack_bot` (`slack`, keyed by workspace and user), `linq` (`imessage`, keyed by the sender's E.164 number with `omnichannel.Phone`; an author it refuses, such as an email handle, gets no card) `telnyx` (`sms`, keyed by the number the same way) and `whatsapp` (`whatsapp`, T51: Meta writes the author as digits with no `+`, so the person and their opt-outs are keyed by `+` and the digits, `recipient`; the thread key and the reply's `to` stay as Meta wrote them). The manifest's `channel` block does not say what its authors are to the contact map. Check: `go test -tags integration -run TestLinqChannelSuite/TestAChatIsOneThreadChannelAndOneIMessageCard ./internal/api`. -- **SMS answers the carriers' keywords before the agent** (`keywords.go`, T53, wave 3c Q9). A connector whose episode source names an opt-out channel (`optOuts`: `telnyx` `sms`, `whatsapp` `whatsapp`, `linq` `imessage`) has them; Meta answers none of them itself, so the bridge answers all three on WhatsApp. In the worker, before the card, a message that is STOP (or STOPALL, END, UNSUBSCRIBE, CANCEL, QUIT, REVOKE, OPT OUT), START (UNSTOP) or HELP, read without case or punctuation, reaches no agent and is answered by the bridge with internal/channels' texts unless the provider answered it itself (`answered`: Telnyx always answers STOP, START and HELP and says so in `data.payload.autoresponse_type`, so the bridge answers only the rest, such as REVOKE and OPT OUT); STOP and START write the customer's `opt_outs` (`source: keyword`), the record `dlc.Gate` and the opt-out API read. A person with a live opt-out reaches no agent, and `Reply` sends them nothing, not even a reply the agent finished after their STOP or one it sends again after a failed send. A store that fails fails the worker's attempt, which runs the row again, so the opt-out is recorded: a STOP's row is never given up (`optsOut`). Example: `opt_outs` refuses writes for an hour; the STOP is recorded and confirmed on the first attempt after it. The answer is sent inline and at most once: the row's `keyword_answered` is set under its lease before the send (`store.MarkChannelInboundKeywordAnswered`), so an attempt after one whose router stopped sends nothing. Sources: CTIA Messaging Principles and Best Practices (May 2023) 5.1.3, FCC 24-24 (47 CFR 64.1200(a)(10)), Telnyx's default opt-in/out words. `internal/channels` keeps its own list (`internal/channels/keywords.go`) until T62. Check: `go test -tags integration -run 'TestTelnyxChannelSuite/(TestStop|TestHelp|TestAReply|TestAStop|TestEach|TestAMessage|TestKeywords|TestARevoke)' ./internal/api`. +- **SMS answers the carriers' keywords before the agent** (`keywords.go`, T53, wave 3c Q9). A connector whose episode source names an opt-out channel (`optOuts`: `telnyx` `sms`, `whatsapp` `whatsapp`, `linq` `imessage`) has them; Meta answers none of them itself, so the bridge answers all three on WhatsApp. In the worker, before the card, a message that is STOP (or STOPALL, END, UNSUBSCRIBE, CANCEL, QUIT, REVOKE, OPT OUT), START (UNSTOP) or HELP, read without case or punctuation, reaches no agent and is answered by the bridge with internal/channels' texts unless the provider answered it itself (`answered`: Telnyx always answers STOP, START and HELP and says so in `data.payload.autoresponse_type`, so the bridge answers only the rest, such as REVOKE and OPT OUT); STOP and START write the customer's `opt_outs` (`source: keyword`), the record `dlc.Gate` and the opt-out API read. A person with a live opt-out reaches no agent, and `Reply` sends them nothing, not even a reply the agent finished after their STOP or one it sends again after a failed send. A store that fails fails the worker's attempt, which runs the row again, so the opt-out is recorded: a STOP's row is never given up (`optsOut`). Example: `opt_outs` refuses writes for an hour; the STOP is recorded and confirmed on the first attempt after it. The answer is sent inline and at most once: the row's `keyword_answered` is set under its lease before the send (`store.ChannelInbounds.MarkKeywordAnswered`), so an attempt after one whose router stopped sends nothing. Sources: CTIA Messaging Principles and Best Practices (May 2023) 5.1.3, FCC 24-24 (47 CFR 64.1200(a)(10)), Telnyx's default opt-in/out words. `internal/channels` keeps its own list (`internal/channels/keywords.go`) until T62. Check: `go test -tags integration -run 'TestTelnyxChannelSuite/(TestStop|TestHelp|TestAReply|TestAStop|TestEach|TestAMessage|TestKeywords|TestARevoke)' ./internal/api`. - **iMessage has the keywords too** (T62a, AI-921): `linq` names `imessage` as its opt-out channel. Linq answers none of them itself; it refuses later sends to a person who texted STOP with 403 (error 2024, https://docs.linqapp.com/channel/imessage/error/codes/2xxx/2024/index.md), so the bridge's STOP confirmation there is refused unless a send sets `override_optout` (not set yet). A Linq thread is a chat, so the person its replies reach is the one who started it (`replyTo`: the contact map row of its episode); a chat with no episode, as under a config with `episode_cards` off, is the person recorded as its starter in `channel_threads.starter`, group or not: the first author the worker admitted in it whom the contact map keys, written at the step where that message's episode would open (`recordStarter`). An author it cannot key, such as an email handle, starts no chat; a chat with neither row is nobody, whom the sandbox does not list. Check: `go test -tags integration -run 'TestInboundSuite/TestAChatWithNoEpisode' ./internal/channelbridge` and `-run 'TestLinqSandboxSuite/TestA(OneToOne|Group)ChatUnderAConfigWithTheCardsOff' ./internal/api`. A Linq message whose `data.chat.is_group` is `false` records its sender as the thread's person in `channel_threads.chat_person` (`episodeSource.oneToOne`), the person a 1:1 chat schedules tasks for (`api.threadPerson`); any other message, the latest one deciding, clears it. Only a claimed message does, in the worker: a retried copy of an older 1:1 message leaves a group chat a group's. A reply to a chat reaches everyone in it, so every fresh message's author is recorded in `channel_thread_members` whatever `is_group` says, and while one of them has a live iMessage opt-out, from STOP there or anywhere else, the chat gets no reply, resend or scheduled delivery (`silenced`, `refusesReply`) and the others' messages reach no agent; STOP and START are still confirmed there (AI-2015). A keyword answer the provider refuses, such as Linq's 403, is logged at INFO (AI-2016). Check: `go test -tags integration -run 'TestLinqChannelSuite/(TestAStop|TestAReply|TestAGroup|TestAPerson|TestAnAuthor)' ./internal/api`. -- **Keyword texts come from the line's use case** (T62a): `store.UseCaseForNumber` with the provider unit, so the use case the number is assigned to, else the customer's default; an empty text is the one before. WhatsApp's provider unit is a `phone_number_id`, which no number is stored under, so a WhatsApp line has the default use case's texts. Check: `go test -tags integration -run 'TestTelnyxChannelSuite/(TestKeywords|TestAKeyword)' ./internal/api`. +- **Keyword texts come from the line's use case** (T62a): `store.UseCases.GetForNumber` with the provider unit, so the use case the number is assigned to, else the customer's default; an empty text is the one before. WhatsApp's provider unit is a `phone_number_id`, which no number is stored under, so a WhatsApp line has the default use case's texts. Check: `go test -tags integration -run 'TestTelnyxChannelSuite/(TestKeywords|TestAKeyword)' ./internal/api`. - **The sandbox gate on texting lines** (T62a): `Options.Gate` is the router's `dlc.Gate`, the one `internal/channels` uses. On a connector with an opt-out channel, a message passes `Gate.Allow` in the worker, after the keywords and before it is written (refused: the row is done, it reaches no agent and opens no card; a gate that fails to read is retried), each reply passes it before it is claimed and before each resend, and a reply sent counts with `Gate.Sent`. Keyword answers go out past it, as on `internal/channels`. Slack has no opt-out channel and no gate. A nil gate lets everything through. Check: `go test -tags integration -run TestTelnyxSandboxSuite ./internal/api`. - **A reply's files go as links** (T62a): `conversation.FinishedReply.Files` are appended to the text, one URL a line after a blank line (`withFiles`), on every provider; a reply that is only files is handed over too. Native media per provider is a later ticket. - **No text and no author in logs.** They are a person's. diff --git a/acceleration/internal/channelbridge/bridge.go b/acceleration/internal/channelbridge/bridge.go index 5c433cd497..1eb872ee4e 100644 --- a/acceleration/internal/channelbridge/bridge.go +++ b/acceleration/internal/channelbridge/bridge.go @@ -168,10 +168,10 @@ type episodeSource struct { // chats is a thread key that is a chat, not the person a reply reaches: a Linq chat id // (linq.yaml). Its replies reach the person who started the thread (replyTo) and everyone // else in the chat, its members as far as their messages show them - // (store.AddChannelThreadMember), so one of them who opted out silences it (refusesReply). + // (store.ChannelThreadMembers.Insert), so one of them who opted out silences it (refusesReply). chats bool // oneToOne is whether a chat's raw event says the chat is one person's, not a group, so the - // thread records its author as the chat's person (store.SetChannelThreadChatPerson). Nil is + // thread records its author as the chat's person (store.ChannelThreads.SetChatPerson). Nil is // never. oneToOne func(raw []byte) bool // window is how long after the person's last message the provider takes free text, when @@ -368,7 +368,7 @@ func (b *Bridge) Close() { // Deliver takes the messages one verified event of a provider app carried. For each it finds // the app's connection of the provider unit and the agent that answers there, links the // external thread to its thread channel, and claims and queues the message by the provider's -// id for it in one transaction (store.AcceptChannelInbound), so a retried delivery is dropped +// id for it in one transaction (store.ChannelInbounds.Accept), so a retried delivery is dropped // and a claimed message is never left without its row. A worker on any router admits and // writes it into Stream Chat with its episode card (Start), off the request: a provider waits // a few seconds at most (Slack: «respond ... within three seconds», @@ -735,7 +735,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa // mention in a thread of people, leaves them waiting until they are dropped: some came // before the bot was spoken to, which it does not read (AI-989). The message takes them // whether or not it made the link now and whether or not it was taken before, and each - // waiting reply is handed out once (store.AcceptChannelInbound). + // waiting reply is handed out once (store.ChannelInbounds.Accept). if startsThread(read) { waiting = func(reply core.InboundMessage) (core.InboundMessage, bool, error) { read, rule, err := b.read(connection, definition, reply) @@ -819,7 +819,7 @@ func (b *Bridge) episode(ctx context.Context, thread store.ChannelThread, config } // recordStarter records the author of a chat's message as the person who started the chat -// (store.SetChannelThreadStarter), at the step whose message would open the chat's episode, so +// (store.ChannelThreads.SetStarter), at the step whose message would open the chat's episode, so // the first one the bridge admits names them whatever the config's episode_cards: the person // its replies reach while it has no episode (replyTo). An author the contact map cannot key, // such as an email handle, starts no chat, as they open no episode. diff --git a/acceleration/internal/channelbridge/gate.go b/acceleration/internal/channelbridge/gate.go index 5a49abd26d..c3ac488ee7 100644 --- a/acceleration/internal/channelbridge/gate.go +++ b/acceleration/internal/channelbridge/gate.go @@ -136,7 +136,7 @@ func (b *Bridge) refusesReply(ctx context.Context, thread store.ChannelThread) e } // silenced is whether a chat thread reaches a person, one of the authors seen in it -// (store.AddChannelThreadMember), with a live opt-out of the connector's channel (AI-2015). A +// (store.ChannelThreadMembers.Insert), with a live opt-out of the connector's channel (AI-2015). A // reply to an iMessage group reaches everyone in it, and after STOP a person gets one // confirmation, then nothing (CTIA 5.1.3; Linq: «The block applies to that recipient across // every chat and every line», https://docs.linqapp.com/error/codes/2xxx/2024/). @@ -153,9 +153,9 @@ func (b *Bridge) silenced(ctx context.Context, thread store.ChannelThread) (bool // one thread key part), a WhatsApp thread its digits (whatsapp.yaml's), which Read writes as // they are, since a number has no % or : to encode. A Linq thread is a chat, whose id names // nobody, so it is the person who started it: the contact map row of the thread's episode -// (store.ThreadContact), with the agent that answers on the thread's connection (take). A chat +// (store.ContactMapEntries.GetByThread), with the agent that answers on the thread's connection (take). A chat // with no episode, as under a config with episode_cards off, is the person recorded as its -// starter (store.ChannelThreadStarter), the one its first message's episode would have named, +// starter (store.ChannelThreads.Starter), the one its first message's episode would have named, // group or not. A chat with neither, such as one an email handle started, is "", which no // opt-out names and no sandbox lists. func (b *Bridge) replyTo(ctx context.Context, thread store.ChannelThread) (string, error) { diff --git a/acceleration/internal/channelbridge/inbound.go b/acceleration/internal/channelbridge/inbound.go index 4e32109e7e..7445592164 100644 --- a/acceleration/internal/channelbridge/inbound.go +++ b/acceleration/internal/channelbridge/inbound.go @@ -30,12 +30,12 @@ const inboundLease = time.Minute const defaultInboundPoll = time.Second // inboundInFlight is how many queued messages one router writes at once. A thread's messages -// are written one at a time whatever it is (store.ClaimChannelInbound). eventforward's inFlight, +// are written one at a time whatever it is (store.ChannelInbounds.Claim). eventforward's inFlight, // a choice, not a measurement. const inboundInFlight = 16 // pruneEvery is how often a worker deletes the rows past their keep: a day for a written -// message, 30 days for a given-up one (store.PruneChannelInbound), so an hour late is nothing. +// message, 30 days for a given-up one (store.ChannelInbounds.Prune), so an hour late is nothing. // A choice. const pruneEvery = time.Hour @@ -332,7 +332,7 @@ func (b *Bridge) writeQueued(ctx context.Context, message store.ChannelInbound) } // forwardUnanswered hands a given-up message's delivery to the customer's event destinations of -// unhandled events (Options.Unanswered), for store.FailChannelInbound to call: only the first +// unhandled events (Options.Unanswered), for store.ChannelInbounds.Fail to call: only the first // given-up message of a delivery whose forward is queued does, so two of them are one forward. // Nil without Options.Unanswered. func (b *Bridge) forwardUnanswered(message store.ChannelInbound) func(context.Context) error { diff --git a/acceleration/internal/channelbridge/keywords.go b/acceleration/internal/channelbridge/keywords.go index f87ed41c2b..9b1bc3a7dc 100644 --- a/acceleration/internal/channelbridge/keywords.go +++ b/acceleration/internal/channelbridge/keywords.go @@ -47,7 +47,7 @@ var ( ) // What a keyword is answered with when the line's 10DLC use case says nothing -// (store.UseCaseForNumber: the use case its number is assigned to, else the customer's +// (store.UseCases.GetForNumber: the use case its number is assigned to, else the customer's // default): internal/channels/keywords.go's texts, so a person reads the same answer on either // line. The CTIA's 5.1.3 asks for «one final opt-out confirmation message»; no other message // follows it (Bridge.reply). @@ -57,8 +57,7 @@ const ( helpReply = "Reply STOP to unsubscribe." ) -// optOutSource is opt_outs.source for a texted keyword (20261006120200_opt_outs.sql: «keyword -// (they texted STOP)»), as internal/channels records it. +// optOutSource is opt_outs.source for a texted keyword, as internal/channels records it. const optOutSource = "keyword" // keyword answers a carrier keyword before any agent sees the message, on a connector whose @@ -71,7 +70,7 @@ const optOutSource = "keyword" // again. A store that fails fails the worker's attempt, which runs the row again: an opt-out is // never lost, since the worker never gives its row up (optsOut). The answer is sent at most // once, whatever the attempts: the row records it before it is sent -// (store.MarkChannelInboundKeywordAnswered), as a reply is claimed before it is sent. +// (store.ChannelInbounds.MarkKeywordAnswered), as a reply is claimed before it is sent. func (b *Bridge) keyword(ctx context.Context, thread store.ChannelThread, queued store.ChannelInbound) (bool, error) { message := queued.Message() source := episodeSources[message.ConnectorID] @@ -199,7 +198,7 @@ func telnyxAnswered(raw []byte) bool { } // detached is ctx without its cancellation, bounded by queueTimeout, for the transaction that -// claims and queues a message (store.AcceptChannelInbound): a provider that hangs up cancels +// claims and queues a message (store.ChannelInbounds.Accept): a provider that hangs up cancels // the request's context (net/http), and the message is queued all the same. func (b *Bridge) detached(ctx context.Context) (context.Context, context.CancelFunc) { return context.WithTimeout(context.WithoutCancel(ctx), b.queueTimeout) diff --git a/acceleration/internal/chatinbound/AGENTS.md b/acceleration/internal/chatinbound/AGENTS.md index b70ad751b3..3f402bc2a9 100644 --- a/acceleration/internal/chatinbound/AGENTS.md +++ b/acceleration/internal/chatinbound/AGENTS.md @@ -7,7 +7,7 @@ Stream Chat's own delivery of messages to the router. `chatinbound.go` checks a ``` endpoint api.receiveChatInbound signature, app served here, message.new, addressed, fresh (app mode) - one tx: QueueFirstChatInbound + one tx: ChatInbounds.QueueFirst deliveries_seen hook :message: the webhook's key (deliveryKey) chat_inbound row committed: 200, Kick wakes this router's worker @@ -15,14 +15,14 @@ endpoint api.receiveChatInbound store error or no store: 503 Stream Chat delivers it again worker (every router) Worker.answerDue - ClaimChatInbound: due rows, lease 5 min, SKIP LOCKED + ChatInbounds.Claim: due rows, lease 5 min, SKIP LOCKED Answer = api.AnswerChatInbound -> routeArrivingMessage thread channel answerThread claims the turn; row stays queued session here answerOnce: queued -> done, then answer worker here answerOnce: queued -> done, then AssignMessage session or worker hand over; the peer runs the same steps on a peer - nil: FinishChatInbound error: again after 2s, 10s, 30s, 2min, 10min + nil: ChatInbounds.Finish error: again after 2s, 10s, 30s, 2min, 10min out of waits: failed done rows deleted after 24h; failed rows kept 30 days ``` @@ -33,9 +33,9 @@ done rows deleted after 24h; failed rows kept 30 days - **One key per message, whoever brings it.** The endpoint and the message webhook record the same key, `:message:`, so the second of the two acts on nothing. In deployment mode the webhook records it only while Stream Chat deliveries are on (`TestAMessageTheWebhookBroughtIsNotQueuedWhenDelivered`, `TestTheWebhookOfAMessageDeliveredFirstIsNotActedOn`). - **The worker never reads the key.** The key keeps a second delivery out of the queue; the row is what the worker answers. Example: the router stops after the 200; the next worker answers the row (`TestADeliveryTakenBeforeTheRouterStoppedIsAnsweredOnceAWorkerStarts`). - **One row is one answer.** No try of a row answers it a second time, on any router. Example: a peer answers and its reply is lost; the next try finds the row `done` and answers nothing (`TestAQueuedDeliveryAPeerAnsweredIsNotAnsweredAgainWhenItsReplyWasLost`). -- **The session and dispatch paths settle the row as the answer starts.** `answerOnce` moves the row from `queued` to `done` (`store.StartChatInboundAnswer`) before the answer. A router that stops mid-answer leaves the message answered at most once. This is the trade-off: at most once, not at least once. -- **The thread path is claimed by its turn.** `answerThread` claims the message's turn (`store.ClaimChannelThreadMessage`, `store.ClaimTurn`). The row stays `queued` for the worker to finish. A second try finds the turn taken and answers nothing. -- **A row goes back to the queue only on a failure that proves nothing took it.** `unanswered` moves it from `done` to `queued` (`store.ReleaseChatInboundAnswer`). Example: no dispatch worker is connected. A failure that leaves it open keeps the row settled. Example: the node with the worker did not reply in time (`node.ErrNoReply`); it may have placed the message (`TestAQueuedDeliveryAnotherNodePlacedIsNotPlacedAgainWhenItsReplyWasLate`). +- **The session and dispatch paths settle the row as the answer starts.** `answerOnce` moves the row from `queued` to `done` (`store.ChatInbounds.StartAnswer`) before the answer. A router that stops mid-answer leaves the message answered at most once. This is the trade-off: at most once, not at least once. +- **The thread path is claimed by its turn.** `answerThread` claims the message's turn (`store.ChannelThreadMessages.Claim`, `store.ClaimTurn`). The row stays `queued` for the worker to finish. A second try finds the turn taken and answers nothing. +- **A row goes back to the queue only on a failure that proves nothing took it.** `unanswered` moves it from `done` to `queued` (`store.ChatInbounds.ReleaseAnswer`). Example: no dispatch worker is connected. A failure that leaves it open keeps the row settled. Example: the node with the worker did not reply in time (`node.ErrNoReply`); it may have placed the message (`TestAQueuedDeliveryAnotherNodePlacedIsNotPlacedAgainWhenItsReplyWasLate`). - **A hook settles nothing.** A webhook delivery is never tried again, so it has no row. - **The stop signal stops the claims.** `Start` takes the router's stop signal (cmd/router: the signal context, as `scheduling.Scheduler.Start`), so a draining router claims no more rows; the rows still queued wait for another router. The answers already running go on (`TestAfterTheStopSignalAWorkerFinishesItsAnswerAndClaimsNoOther`), and cmd/router's drain waits for them (`Running`, counted in `running` as the scheduled deliveries are) until the drain runs out (`TestRunningCountsTheAnswersInFlight`, `TestDrainSuite`). - **Close waits for the answers in flight.** It records what came of each, so no row waits for its lease to run out. diff --git a/acceleration/internal/chatinbound/worker.go b/acceleration/internal/chatinbound/worker.go index 6b18ec148c..276e05f910 100644 --- a/acceleration/internal/chatinbound/worker.go +++ b/acceleration/internal/chatinbound/worker.go @@ -37,7 +37,7 @@ const inFlight = 64 var defaultRetries = []time.Duration{2 * time.Second, 10 * time.Second, 30 * time.Second, 2 * time.Minute, 10 * time.Minute} // pruneEvery is how often a worker deletes the rows past their keep: a day for an answered -// message, 30 days for a given-up one (store.PruneChatInbound), so an hour late is nothing. +// message, 30 days for a given-up one (store.ChatInbounds.Prune), so an hour late is nothing. // A choice, the channel bridge's. const pruneEvery = time.Hour diff --git a/acceleration/internal/connectors/credentialstores/pgsealed/AGENTS.md b/acceleration/internal/connectors/credentialstores/pgsealed/AGENTS.md index 412adb3064..398727980a 100644 --- a/acceleration/internal/connectors/credentialstores/pgsealed/AGENTS.md +++ b/acceleration/internal/connectors/credentialstores/pgsealed/AGENTS.md @@ -1,6 +1,6 @@ # internal/connectors/credentialstores/pgsealed -The `core.CredentialStore` that keeps a connection's credential state in Postgres: the `connector_connections` row, with `core.StoredCredentials` sealed by `auth.Sealer` (AES-GCM, KEK keyring) into `credentials_sealed`. The SQL is the store's (`internal/store/credentials.go`: `WithLockedConnectorConnection`, `SaveConnectorConnectionAtRevision`); this package turns the row into a `core.CredentialState` and back, and owns sealing, the revision and the rewrap. The resolver (`internal/connectors/resolver`) takes it directly, built in `cmd/router/resolver.go`: a connection names no credential store, so `core.Registry.CredentialStores` stays empty until a second one exists. +The `core.CredentialStore` that keeps a connection's credential state in Postgres: the `connector_connections` row, with `core.StoredCredentials` sealed by `auth.Sealer` (AES-GCM, KEK keyring) into `credentials_sealed`. The SQL is the store's (`internal/store/connector_connection.go`: `ConnectorConnections.WithLocked`, `ConnectorConnections.SaveAtRevision`); this package turns the row into a `core.CredentialState` and back, and owns sealing, the revision and the rewrap. The resolver (`internal/connectors/resolver`) takes it directly, built in `cmd/router/resolver.go`: a connection names no credential store, so `core.Registry.CredentialStores` stays empty until a second one exists. ## Flow @@ -25,10 +25,10 @@ Update(ref, fn) Nothing waits inside Postgres at 1, so a caller that gives up just stops trying: no wait stays queued on the server and no connection is held while it pauses. A blocking `pg_advisory_lock` cannot promise that, because pgdriver bounds every read by its `ReadTimeout` (10s by default, `newDefaultConfig` in `uptrace/bun/driver/pgdriver` v1.2.18) or the ctx deadline, drops the socket when it passes, and the server "will detect the loss of the connection only at the next interaction with the socket" ([client_connection_check_interval](https://www.postgresql.org/docs/current/runtime-config-connection.html#GUC-CLIENT-CONNECTION-CHECK-INTERVAL)). The cost of trying is that waiters are not served in order. Writes at 5 and 6 run detached from ctx for the same driver reason: a passed deadline is a passed socket deadline, which would drop tokens a provider already rotated. -## Why session-level here and xact-level in connectors.go +## Why session-level here and xact-level in connector_definition.go ``` -connectors.go (T6, definition revisions) credentials.go (T8, this store) +connector_definition.go (T6, revisions) credential_lock.go (T8, this store) BEGIN pg_try_advisory_lock <- held pg_advisory_xact_lock <- held UPDATE status = needs_reauthorization (checkpoint, autocommit) SELECT latest, INSERT next POST refresh_token to the provider <- side effect @@ -46,7 +46,7 @@ The second key is 32 bits because the two-integer form is what buys that separat - **The credential store owns the revision.** New `StoredCredentials` (any byte of `Scheme`, `Version`, `Payload` differs) are sealed for revision + 1; anything else keeps the revision. fn changing `CredentialState.Revision` gets `errRevisionIsTheStores`. Check: `go test -tags integration -run 'TestPGSealedSuite/(TestNewCredentials|TestTheRevisionIsNot|TestAStatusChange)' ./internal/connectors/credentialstores/pgsealed`. - **Every write is a compare-and-swap on the revision last committed.** A stale write, or one onto a deleted row, is `store.ErrConnectorConnectionChanged`. Check: `go test -tags integration -run 'TestStoreSuite/(TestASaveAtAStale|TestASaveOntoADeleted|TestAWriteThatSkipped|TestALockedCallbackCannotMove)' ./internal/store`. -- **`SaveConnectorConnectionAtRevision` is new credentials at the next revision, nothing else.** A checkpoint can commit a status without moving the revision, so a same-revision save from an older snapshot would put back the credentials the checkpoint retired. Check: `go test -tags integration -run 'TestStoreSuite/(TestASaveIsNewCredentials|TestASaveCannotPutBack)' ./internal/store`. +- **`ConnectorConnections.SaveAtRevision` is new credentials at the next revision, nothing else.** A checkpoint can commit a status without moving the revision, so a same-revision save from an older snapshot would put back the credentials the checkpoint retired. Check: `go test -tags integration -run 'TestStoreSuite/(TestASaveIsNewCredentials|TestASaveCannotPutBack)' ./internal/store`. - **A commit lands even after the caller's deadline**, within 2s of its own. Check: `go test -tags integration -run TestStoreSuite/TestACommitAfter ./internal/store`. - **One locked callback per connection at a time, across routers.** Check: `go test -tags integration -run TestStoreSuite/TestLockedCallbacks ./internal/store` and `go test -tags integration -run TestPGSealedSuite/TestConcurrent ./internal/connectors/credentialstores/pgsealed`. - **Checkpoint before a side effect that cannot be taken back.** A refresh whose outcome is never learned leaves `needs_reauthorization` and the refresh token is never sent again. Check: `go test -tags integration -run TestPGSealedSuite/TestRefreshOutcomeSurvives ./internal/connectors/credentialstores/pgsealed`. @@ -55,7 +55,7 @@ The second key is 32 bits because the two-integer form is what buys that separat - **A key version the keyring lacks is the keyring's fault, not the connection's.** `Update` returns `auth.ErrKeyVersionUnavailable`, runs no fn and writes nothing, so putting the key back restores the connection. Check: `go test -tags integration -run TestPGSealedSuite/TestAKeyVersionMissing ./internal/connectors/credentialstores/pgsealed`. - **Stored credentials under an older key are rewrapped on the next use that returns no error**, at the same revision, and a use that returned changed false has its rewrap written from what was stored, never from fn's edits. Check: `go test -tags integration -run 'TestPGSealedSuite/(TestCredentialsSealedUnder|TestAFailedUse|TestARewrapKeeps)' ./internal/connectors/credentialstores/pgsealed`. - **`connected_at` is the caller's.** A commit writes the `ConnectedAt` fn leaves; the store stamps nothing. Whatever begins a grant names when it began: a consent (`api/authorizations.go`), and a credentials write that connects a connection that was not connected (`api/connection_tools.go`). A refresh keeps it, even past its own checkpoint, and so does the resolver's `saveAgain`, which saves a renewal again in an Update that loads the checkpoint's `needs_reauthorization` (AI-3504). `Resolver.Revoke` reads it to leave a grant newer than a provider's signal, and the tool pins of a grant are keyed by it. Check: `go test -tags integration -run 'TestPGSealedSuite/(TestAConnectionCommittedConnected|TestARefreshPastItsCheckpoint|TestWhenAConsentConnected)' ./internal/connectors/credentialstores/pgsealed`. -- **fn does not lock the same connection again** (`Update`, `SaveConnectorConnectionAtRevision`): that is a second pool connection waiting on the first. +- **fn does not lock the same connection again** (`Update`, `ConnectorConnections.SaveAtRevision`): that is a second pool connection waiting on the first. - **Secrets never print.** Stored credentials go into an error or a log only as `core.StoredCredentials`, whose `String`, `GoString` and `LogValue` redact the payload; tests compare blobs with `bytes.Equal`, not `Equal`, so a failure prints no ciphertext. - **Every hardcoded value says where it comes from**, beside it. diff --git a/acceleration/internal/connectors/credentialstores/pgsealed/pgsealed.go b/acceleration/internal/connectors/credentialstores/pgsealed/pgsealed.go index 5941bf90d5..7df2c99308 100644 --- a/acceleration/internal/connectors/credentialstores/pgsealed/pgsealed.go +++ b/acceleration/internal/connectors/credentialstores/pgsealed/pgsealed.go @@ -1,7 +1,7 @@ // Package pgsealed is the core.CredentialStore that keeps a connection's credential state in // Postgres: the connection row in connector_connections, its StoredCredentials sealed with // auth.Sealer, under a session-level advisory lock held across replicas -// (store.WithLockedConnectorConnection). +// (store.ConnectorConnections.WithLocked). package pgsealed import ( diff --git a/acceleration/internal/connectors/providers/AGENTS.md b/acceleration/internal/connectors/providers/AGENTS.md index dc95979bdb..1cbfb6eb44 100644 --- a/acceleration/internal/connectors/providers/AGENTS.md +++ b/acceleration/internal/connectors/providers/AGENTS.md @@ -1,6 +1,6 @@ # internal/connectors/providers -The built-in connector manifests: one `.yaml` per connector, in the schema `core.ParseManifest` reads (`internal/connectors/core/manifest.go`). `providers.go` embeds them; at every start the router's `openStore` calls `store.SeedConnectorDefinitions` (`internal/store/connectors.go`), which writes each one to `connector_definitions` under the built-in customer. +The built-in connector manifests: one `.yaml` per connector, in the schema `core.ParseManifest` reads (`internal/connectors/core/manifest.go`). `providers.go` embeds them; at every start the router's `openStore` calls `store.ConnectorDefinitions.Seed` (`internal/store/connector_definition.go`), which writes each one to `connector_definitions` under the built-in customer. ## Rules diff --git a/acceleration/internal/connectors/providers/providers.go b/acceleration/internal/connectors/providers/providers.go index d9d4aa787d..98f63160d0 100644 --- a/acceleration/internal/connectors/providers/providers.go +++ b/acceleration/internal/connectors/providers/providers.go @@ -1,5 +1,5 @@ // Package providers holds the built-in connector manifests, one .yaml per connector. -// They are embedded so the router binary carries them, and store.SeedConnectorDefinitions +// They are embedded so the router binary carries them, and store.ConnectorDefinitions.Seed // writes them to connector_definitions at every start. package providers diff --git a/acceleration/internal/connectors/resolver/AGENTS.md b/acceleration/internal/connectors/resolver/AGENTS.md index fbcde9e76f..3d14440792 100644 --- a/acceleration/internal/connectors/resolver/AGENTS.md +++ b/acceleration/internal/connectors/resolver/AGENTS.md @@ -55,7 +55,7 @@ Revoke(ref, why, endedAt) why is revoked, uninstalled or rotated, else r ## Cache - **Key**: the connection, holding the revision of the stored credentials the credential came from. A new revision (a refresh on any router, a reconnect) is a miss. -- **The row is read on every call.** A delete, a disconnect or an `Invalidate` on any router reaches every other router's next `Resolve`, with no window. A soft delete (`store.DeleteConnectorConnection`, #746) sets `deleted_at` and `disconnected` and moves no revision, so a revision check alone would miss it. A maximum age alone would leave a window of that age on every router. An `Invalidate` from the delete handler would reach only the router that served the delete. Example: Alice deletes her connection through router A while her session runs on router B, which cached her token a second earlier. B's next `Resolve` reads no live row and fails, so the deleted connection's token never leaves B again. +- **The row is read on every call.** A delete, a disconnect or an `Invalidate` on any router reaches every other router's next `Resolve`, with no window. A soft delete (`store.ConnectorConnections.Delete`, #746) sets `deleted_at` and `disconnected` and moves no revision, so a revision check alone would miss it. A maximum age alone would leave a window of that age on every router. An `Invalidate` from the delete handler would reach only the router that served the delete. Example: Alice deletes her connection through router A while her session runs on router B, which cached her token a second earlier. B's next `Resolve` reads no live row and fails, so the deleted connection's token never leaves B again. - **A status other than connected is never served from the cache.** It goes to the lock, which is where a refresh in flight on another router (status `needs_reauthorization` by its checkpoint) ends: the waiter then sees the final state. - **maxAge (30 s) bounds what the row does not show**: a credential the scheme would now renew, and stored credentials under an old key that `pgsealed` rewraps on its next use. - **A credential that expires before `req.Deadline` is not served**: the call goes to the lock, and the scheme renews it for the deadline (`RetrieveOptions.ValidUntil`). The renewed one is cached, so the next call inside the window takes no lock. One exception: a credential this router renewed within `maxAge` is served while it has not expired, even when it expires before the deadline. It is as long as the provider issues them, so renewing again gives one no longer, and asking for that on every call would be a refresh per call. Then a call does start with a credential that dies during it; nothing can give it a longer one. Check: `go test -tags integration -run 'TestResolverSuite/(TestACachedCredentialThatExpiresBefore|TestACredentialThatExpiresBefore|TestACredentialRenewedForADeadline)' ./internal/connectors/resolver`. diff --git a/acceleration/internal/connectors/resolver/resolver.go b/acceleration/internal/connectors/resolver/resolver.go index 1b8a2ea21f..9d1f4d87e2 100644 --- a/acceleration/internal/connectors/resolver/resolver.go +++ b/acceleration/internal/connectors/resolver/resolver.go @@ -101,7 +101,7 @@ var revokedErrors = map[core.SignalKind]string{ // ErrNotConnected says the connection's status is not connected: it is pending a consent, it // needs a reconnect, or it was disconnected. Or it is connected on a definition revision a -// later one marked broken (store.BrokenConnectorRevision). Only the person who owns it can fix +// later one marked broken (store.ConnectorBrokenRevisions.Get). Only the person who owns it can fix // that. var ErrNotConnected = errors.New("resolver: the connection is not connected") diff --git a/acceleration/internal/connectors/slackapps/AGENTS.md b/acceleration/internal/connectors/slackapps/AGENTS.md index 7dfba0b008..6545fc5d80 100644 --- a/acceleration/internal/connectors/slackapps/AGENTS.md +++ b/acceleration/internal/connectors/slackapps/AGENTS.md @@ -19,7 +19,7 @@ A Slack app is Slack's alone, so this is provider code, which lives under `inter - **Outbound calls go through egress.** `Config.HTTP` is `egress.NewClient(connectorHTTPTimeout, nil)` in `cmd/router`; a test passes `fakeprovider.Server.Client()` with `BaseURL` at the fake's `PathSlackAPI`. - **Secrets never print.** `Credentials` and `ConfigToken` redact their secrets in `String`, `GoString` and `LogValue`. Check: `go test -run TestSlackAppsSuite/TestCredentialsAndConfigTokensNeverPrintTheirSecrets ./internal/connectors/slackapps`. -- **A spent refresh token is never sent again.** Slack's pages do not say whether the old one keeps working, so the caller saves what `Rotate` returns before anything else, under the provider app lock (`store.WithConnectorProviderAppLock`). +- **A spent refresh token is never sent again.** Slack's pages do not say whether the old one keeps working, so the caller saves what `Rotate` returns before anything else, under the provider app lock (`store.ConnectorConfigTokens.WithProviderAppLock`). - **The manifest is built from the connector, not written by hand.** Scopes are the connector's `scopes.list`: user scopes for a connector that authorizes at `https://slack.com/oauth/v2_user/authorize` (the Slack MCP server's flow), bot scopes and a bot user otherwise. Events are the connector's `channel.subscriptions`, sent as `bot_events` (or `user_events` for a user-token connector): `providers/slack_bot.yaml` lists `message.channels`, `message.im` and `tokens_revoked`. They are listed rather than derived, because a message rule's `event.type` (`message`) is not a subscription name, and Go names no event. - **The app is the `slack_bot` connector's.** Its request URL is `api.providerAppEventsPath` + `slack_bot/{app id}`, the route `receiveProviderAppEvent` serves, which verifies only a channel whose secret is `provider_app`. The user-token `slack` connector stays on the operator's app: the Slack MCP server wants clients «backed by a registered Slack app with a fixed app ID» ([Slack MCP server](https://docs.slack.dev/ai/slack-mcp-server/)), and its channel verifies with the operator's secret. - **Every limit has its page beside it**: name ≤ 35 characters, description ≤ 140, `allowed_ip_address_ranges` ≤ 10, `request_url` https. diff --git a/acceleration/internal/eventforward/AGENTS.md b/acceleration/internal/eventforward/AGENTS.md index 9d55e70482..4fa7ae366c 100644 --- a/acceleration/internal/eventforward/AGENTS.md +++ b/acceleration/internal/eventforward/AGENTS.md @@ -14,16 +14,16 @@ Slack -> POST /v1/connectors/events/{connector}/{app} api.receiveProviderAppEv trigger_id), else the body; provider headers verify until their timestamp + channel.verifier.max_age (Slack: 5 min) Forwarder.Forward on the request, Postgres only - QueueEventDeliveries: one row per destination that takes it + EventDeliveries.Queue: one row per destination that takes it forward all: every delivery; forward unhandled: only when !handled 200 the bridge's inbound worker gives a message up off the request, any router the row's forward -> Forwarder.ForwardUnanswered: unhandled destinations - only, once per delivery (store.FailChannelInbound) + only, once per delivery (store.ChannelInbounds.Fail) worker (every router) off the request wakes: at start, on Forward, on a finished send, at the first queued row due (at least 1 s), and at least once a lease (1 min) - ClaimEventDeliveries: due rows, lease 1 min, SKIP LOCKED, due checked + EventDeliveries.Claim: due rows, lease 1 min, SKIP LOCKED, due checked again on the locked row, at most 2 in flight per destination per router POST url: raw body, Content-Type, the verifier's headers (only until they stop verifying), webhook-id, webhook-timestamp, @@ -50,7 +50,7 @@ worker (every router) off the request - **`webhook-id` is the provider's event id.** The manifest's `channel.event_id` names it (`core.ChannelRule.DeliveryEventID`): Slack's `event_id` on an event, `trigger_id` on an interaction. A body with no such id is keyed by a digest of the body. The same id on every attempt, and for the provider's own retry. Example: Slack delivers `Ev0000ONE` again with another body; it is one forward while the first is pending, and two Slack events with the same bytes but two `event_id`s are two forwards. Either way the id is hashed, since `trigger_id` holds dots. - **One destination cannot take every send slot.** A router runs 16 sends at once, at most 2 to one destination (`perDestination`). Example: one customer's URL never answers; it holds 2 slots for 15 s each, and another customer's forward goes out at once, not after 15 s (`TestADestinationThatNeverAnswersDoesNotHoldUpAnother`). - **The provider's signature headers go only while they verify.** Each forward keeps its provider timestamp plus `channel.verifier.max_age` (`provider_headers_until`). An attempt after that carries `Content-Type` alone of the provider's headers. Example: Slack Bolt refuses a request whose `X-Slack-Request-Timestamp` is more than 5 minutes old (`requestTimestampMaxDeltaMin = 5`, bolt-js `src/receivers/verify-request.ts`), so the retries after 5 min, 30 min and 2 h carry no Slack signature, and the receiver verifies `webhook-signature`. A stale Slack signature is never presented, for a receiver that skips the timestamp check to take as Slack's. -- **A message the bridge could not write is unhandled after all.** `Bridge.Deliver` counts a message as answered before it writes it into its thread channel, after the ack. The route hands `Deliver` the delivery (`unanswered`: its event id, provider headers and when they stop verifying) when it forwards and nothing else handled the delivery, and the bridge stores it with each queued message (`channel_thread_inbound.forward`). When the bridge's worker gives a message up, on whichever router, it queues that delivery for the `unhandled` destinations alone (`ForwardUnanswered`); the `all` destinations already have it. Only the first given-up message of a delivery whose forward was queued forwards it (`store.FailChannelInbound`): a sent forward's row is deleted, so the destinations' key alone would not stop a second one; a forward that failed leaves it to the next message given up. A Slack reply that waited for its thread's link is the exception (AI-1001): it is queued with no forward, since its own delivery went to the `unhandled` destinations when it arrived; a failed write of it later forwards nothing, and never the delivery of the mention that took it. +- **A message the bridge could not write is unhandled after all.** `Bridge.Deliver` counts a message as answered before it writes it into its thread channel, after the ack. The route hands `Deliver` the delivery (`unanswered`: its event id, provider headers and when they stop verifying) when it forwards and nothing else handled the delivery, and the bridge stores it with each queued message (`channel_thread_inbound.forward`). When the bridge's worker gives a message up, on whichever router, it queues that delivery for the `unhandled` destinations alone (`ForwardUnanswered`); the `all` destinations already have it. Only the first given-up message of a delivery whose forward was queued forwards it (`store.ChannelInbounds.Fail`): a sent forward's row is deleted, so the destinations' key alone would not stop a second one; a forward that failed leaves it to the next message given up. A Slack reply that waited for its thread's link is the exception (AI-1001): it is queued with no forward, since its own delivery went to the `unhandled` destinations when it arrived; a failed write of it later forwards nothing, and never the delivery of the mention that took it. - **An idle router looks once a lease, not once a second.** The worker looks at start, on `Forward`, on a finished send, at the first queued row due, and at least once a lease (1 min) whatever is queued. Example: a router with connectors on and no destination sends Postgres two queries at start and two a minute after (`TestAForwarderWithNothingQueuedSendsNoQuery`); router A queues a forward and is scaled down before it sends it, and idle router B sends it within about two minutes, its next look plus A's lease (`TestAnIdleRouterSendsAForwardAnotherRouterLeftQueued`, `TestARouterWaitingOnALaterRetryStillSendsAForwardAnotherRouterLeft`). - **A claimed row is one router's.** The claim ranks due rows from the statement's start, then locks them and checks `next_attempt_at` again on the locked row: a row another router leased in between is skipped (`TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce`). - **The claim counts the attempt.** A forwarder that dies between its claim and its send records nothing, so a row claimed more often than it may be tried is dropped unsent (`TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAttempts`). A router without the key version a destination's secret was sealed with sends nothing: it gives the attempt back and leaves the row due a lease later, for a router that holds the key (`TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneThatCan`), and logs it once a lease per destination. A forward no router has signed for longer than its retries and a lease is given up as `forward_failed` (`TestAForwardNoRouterCanSignIsGivenUpAndNotClaimedEveryPoll`). A secret that opens under no key is still given up. diff --git a/acceleration/internal/mcpevents/AGENTS.md b/acceleration/internal/mcpevents/AGENTS.md index 4827991936..9fa7cedf19 100644 --- a/acceleration/internal/mcpevents/AGENTS.md +++ b/acceleration/internal/mcpevents/AGENTS.md @@ -19,7 +19,7 @@ POST /v1/agents/connections/{id}/validate api.validateConnection worker (every router) off the request wakes: at start, on Reconcile, on a delivery for an undeclared event, at the first row due, and at least once a lease (1 min) - ClaimConnectionEventSubscriptions: one due row at a time, lease 1 min, + ConnectionEventSubscriptions.Claim: one due row at a time, lease 1 min, SKIP LOCKED; one attempt is two requests of 10 s at most per row: connection deleted or disconnected -> row dropped diff --git a/acceleration/internal/omnichannel/AGENTS.md b/acceleration/internal/omnichannel/AGENTS.md index f8229ae0bc..19fc41f642 100644 --- a/acceleration/internal/omnichannel/AGENTS.md +++ b/acceleration/internal/omnichannel/AGENTS.md @@ -23,11 +23,13 @@ channel bridge, a thread's message session manager, a call's session join | started_at: message.created_at | / Cards.Open Postgres only - store.MapContact (customer, agent config, kind, address) + store.ContactMapEntries.Map + (customer, agent config, kind, address) -> omni-channel agent:omni- a new stream_user or phone row of a linked pair takes its partner's omni-channel (joinPartner) - store.OpenEpisode open episode of the thread or the call session + store.Episodes.Open + open episode of the thread or the call session Cards.Write only an episode Open opened omni-channel agent user = channel id, agent_config_id card message id episode-, source, status, @@ -40,8 +42,8 @@ Linking (AI-2701), the customer's backend: PUT /v1/agents/users/{user_id} {"phone": "+15551234567" | null, api.putUser, server-side only "include_phone_history": bool, "phone_history_since": RFC 3339} (GET answers what is stored, api.getUser) app: the request's pin (streamapp.Clients.Pin), 0 for the deployment's own - phone: omnichannel.Phone, else 400; null unlinks (store.UnlinkUserPhone) - store.LinkUserPhone under the link's lock (pg_advisory_xact_lock, per customer, app, user): + phone: omnichannel.Phone, else 400; null unlinks (store.UserPhones.Unlink) + store.UserPhones.Link under the link's lock (pg_advisory_xact_lock, per customer, app, user): user_phones (customer, app, user_id, phone), one pair per app; a number another user of the app holds: 409 phone_taken writeHistory user_phone_history (the link's key, linked_at, since): true is NULL (all of @@ -67,7 +69,8 @@ Reading (T56 and T42, AI-885), only for an agent config with `episode_cards` on ``` session.Manager.Create, before the history is restored callCards.read text session on a thread channel voice session on a call - store.ThreadContact(own thread) calledParty -> Phone -> store.Contact + store.ContactMapEntries.GetByThread calledParty -> Phone -> store.ContactMapEntries.GetByAddress + (own thread) alone: every person's message in (read only: never makes a row) the thread is by its creator \ / @@ -75,7 +78,7 @@ session.Manager.Create, before the history is restored callCards.read | chatContact: the author of the message handed out (Spec.HandedOutBy), | when the channel's members are that user alone, or that user and the agent, | and every person's or source-less message there is theirs - | -> StreamUser(session's app, author) -> store.Contact + | -> StreamUser(session's app, author) -> store.ContactMapEntries.GetByAddress | / | any other session the person's own device opened (deviceCaller: | CallerKind authenticated, Caller.UserID, not ServerSide), a call @@ -84,11 +87,11 @@ session.Manager.Create, before the history is restored callCards.read | deviceContact: the conversation it carries on, if any, not shared | (conversation.Shared) and its members that user alone, or that user | and the agent (Between) - | -> StreamUser(session's app, Caller.UserID) -> store.Contact + | -> StreamUser(session's app, Caller.UserID) -> store.ContactMapEntries.GetByAddress | app chat and device only: Stream says the app checks tokens | (streamapp.Clients.ChecksTokens, Readiness.AuthChecksOff false), else none Cards.Context - store.EpisodeCards same customer, same agent, same omni-channel; + store.Episodes.Cards same customer, same agent, same omni-channel; own thread, own chat channel, own conversation and own call left out; so is a linked number's episode that started before its link's boundary; @@ -114,7 +117,7 @@ idle sweeper, every minute call.session_ended hook (api.endC left to close or summarize (startEpisodeSweeper) | | - store.CloseIdleEpisodes store.EndCallEpisodes + store.Episodes.CloseIdle store.Episodes.EndCall thread and chat episodes, last message call episodes of the call in the older than episodes.idle_after event's app, still in progress \ / @@ -127,7 +130,7 @@ idle sweeper, every minute call.session_ended hook (api.endC ok: card text = summary, status summarized; row summarized fail: card status summary_failed; row summary_failed; text and thread kept router stopped: row stays ended; the next sweep takes it once the lease runs out - (store.ClaimEpisodeSummaries) + (store.Episodes.ClaimSummaries) ``` ### Close API (for T48 and later callers) @@ -147,10 +150,10 @@ A card closed after the idle period is updated in the app its episode is pinned | Term | What it is | In code | | --- | --- | --- | | omni-channel | One agent channel for each person and agent of a customer, holding one card for each episode | `store.ContactMapEntry.ConversationID` | -| contact map | How a person is known (an E.164 number, a Slack user, or a Stream user of the app chat) to their omni-channel | table `contact_map`, `store.MapContact` | -| episode | One call, or one run of messages on one external thread or in one agent channel of the app chat | table `episodes`, `store.OpenEpisode` | +| contact map | How a person is known (an E.164 number, a Slack user, or a Stream user of the app chat) to their omni-channel | table `contact_map`, `store.ContactMapEntries.Map` | +| episode | One call, or one run of messages on one external thread or in one agent channel of the app chat | table `episodes`, `store.Episodes.Open` | | episode card | The episode's one message in the omni-channel | `Cards.Write` | -| link | A customer's word that a Stream user of its app and a number are one person | table `user_phones`, `store.LinkUserPhone` | +| link | A customer's word that a Stream user of its app and a number are one person | table `user_phones`, `store.UserPhones.Link` | ## Rules @@ -168,13 +171,13 @@ A card closed after the idle period is updated in the app its episode is pinned - **A chat episode starts when Stream made its message.** Its `started_at` is the opening message's `created_at`, so the summary and a card in progress, which read the lines from the start on (`linesOf`), hold the message: the router opens the episode after Stream made it. A message whose `created_at` says no time starts it when it is opened, as before. Each message keeps the episode open from its own time, and a message tried again after a later one never moves `last_message_at` back (`touchThreadEpisodeQuery`, `GREATEST`). Example: Anya writes at 08:05:28.655Z; the episode starts then, not at 08:05:29Z, and its summary says what she asked. - **One chat episode per run of messages.** Every message calls `Open`, which keeps the episode open; only the message that opened it writes a card. A delivery Stream makes again, or the queue tries again, finds the open episode (`episodes_open_thread`) and writes nothing. A card that fails costs the card, not the answer: logged at ERROR, and the message is answered. A hook's card is written off its request, as its answer is, and counted until it ends (`Server.ChatCardsRunning`, summed in cmd/router's `running`), so a draining router waits for it: a card lost then is lost for good, as the next message finds its episode open. - **An app chat's channel is the customer's by the config it names.** The customer's app makes it with `agent_config_id` and none of the router's stamps, so `linesOf` reads it for a chat card of that config (`theirs`); a stamped channel is read only for the customer it names. -- **A link makes one omni-channel of two.** The customer's backend says a Stream user of its app and a number are one person (`PUT /v1/agents/users/{user_id}`); under each agent the user's `stream_user` row and the number's `phone` row then point at the older of their omni-channels, and a row made later takes its partner's (`store.MapContact`). One number per user and one user per number within a Stream app: the same user id in another app is another person, and a number another user holds is a 409. No message moves: the cards written before stay where they were, and are read by their message id from any omni-channel, as long as its own agent wrote them (`writtenAsCard`). A link and a first sighting at once each read after their own write, so one sees the other; two PUTs for one user at once take turns under the link's lock, and the join reads the link as stored (`store.lockLink`). Example: Anya's app chat made `omni-B` on Tuesday, and the customer links her to her number; her first SMS after the link makes the number's row, which takes `omni-B`, and reads her chat's card. +- **A link makes one omni-channel of two.** The customer's backend says a Stream user of its app and a number are one person (`PUT /v1/agents/users/{user_id}`); under each agent the user's `stream_user` row and the number's `phone` row then point at the older of their omni-channels, and a row made later takes its partner's (`store.ContactMapEntries.Map`). One number per user and one user per number within a Stream app: the same user id in another app is another person, and a number another user holds is a 409. No message moves: the cards written before stay where they were, and are read by their message id from any omni-channel, as long as its own agent wrote them (`writtenAsCard`). A link and a first sighting at once each read after their own write, so one sees the other; two PUTs for one user at once take turns under the link's lock, and the join reads the link as stored (`store.lockLink`). Example: Anya's app chat made `omni-B` on Tuesday, and the customer links her to her number; her first SMS after the link makes the number's row, which takes `omni-B`, and reads her chat's card. - **A number the user no longer has keeps none of their history.** Unlinking (`"phone": null`) or a new number points each of the old number's rows that shares the user's omni-channel at a new `agent:omni-` (`store.detachLinked`); the user keeps theirs. The number's episodes go with its row (`episodes.contact_id`), so it keeps its own cards and none of the user's. Example: Anya unlinks `+15550100`, and Bob is linked to it; Bob's chat and the number's SMS read none of Anya's chat cards, and Anya reads none of Bob's. Her SMS from the number stay with it until Bob's link sets them aside (next rule). -- **A new link starts the number clean.** A number says who holds the line, not who the person is, so what it said before the link is not the user's: the number's rows that hold episodes, under each agent config with `episode_cards` record or on and in the link's app, are set aside (`store.retireHistory`): record writes the same episodes on does, which a session reads once the config turns on. Each keeps its omni-channel and its episodes, so its cards stay where they were written, but its address becomes `retired::`, which no sighting, read or join finds by the number. What still talks to the person on the row's thread, call or cards reads the number back (`store.reachedAt`): `ThreadContact`, so a Linq chat's replies and scheduled deliveries check opt-outs, the sandbox and the limits against it (`channelbridge.replyTo`), and the closed episodes' and the cards' `contact_address`, so a call going on at the link still finds its caller's lines (`callerOf`) and is summarized. The number's next episode makes a row of its own, which joins the user (`joinPartner`). The user's own texts from before the link do not join either: nothing proves they were the user's, unless the customer says so: under a link whose boundary is before it (`include_phone_history: true`, or `phone_history_since` earlier than the link), the user's cards read the number's set-aside rows of the link's app too (`store.EpisodeCards`, `setAsideRead`, index `contact_map_retired`), from the boundary on. The rows stay where they are, so an unlink or a new number leaves them off the user, and a router that knows no boundary (v0.6.284) reads none of them. A row with no episode joins as it is, the same link again changes nothing, and a config with `episode_cards` off keeps its rows as before. Example: `+15550100` texted the agent on Monday, from Carl or from Bob before the customer knew him; Bob is linked to it on Tuesday; Bob's chat reads none of Monday's SMS, and his SMS on Wednesday reaches his chat. The card of the number's next episode, in progress, reads only that episode's lines (`linesOf`, from its start), though the number's thread channel holds Monday's texts too. -- **What a number said before its link's boundary is never read, however the cards got turned on.** A config with `episode_cards` off at the link sets nothing aside, so its rows join the user as they are, with the episodes the number had: written while the config recorded or read the cards, or by a release whose channel bridge wrote them whatever the config said. Every session leaves out, whole, an episode of a linked number that started before the boundary (`store.EpisodeCards`, `historyBoundary`): the link as `linkOf` finds it, in the row's app, a set-aside row by its number; the boundary is `user_phone_history.since` (NULL: none) of the row written for the link's time (`linked_at` = `user_phones.updated_at`), else the link's time, `user_phones.updated_at`, by Postgres's clock as the start of a number's episode is, which a new number moves and the same number again leaves. An SMS episode starts at the inbound queue's `created_at`; a call's at `statement_timestamp()` less its session's age by the router's monotonic clock (`store.Episode.Began`), so a call that began before the link stays before it however far the router's clock runs ahead and however late its card is written. That covers the summarized cards, the cards in progress and the call cards, for the app chat, the user's own device, the number's calls and its SMS threads. Example: Bob is linked to `+15550100` on Tuesday under a config with the cards off; the config turns them on on Wednesday; Bob's chat reads none of Monday's SMS, still in progress or not, and reads Wednesday's. A session on the number's thread is handed none of the thread's messages from before the boundary either (`store.ThreadHistorySince`, the thread's newest episode with a linked number; `conversation.Restore.Since`, in `session.Manager.restoring`); a thread whose number is linked to nobody is handed all of it, as before. Example: Bob is linked to `+15550100` on Tuesday with neither field; his SMS session on Wednesday is handed none of Monday's texts; with `phone_history_since` Monday it is handed them, and with `include_phone_history: true` Sunday's too. +- **A new link starts the number clean.** A number says who holds the line, not who the person is, so what it said before the link is not the user's: the number's rows that hold episodes, under each agent config with `episode_cards` record or on and in the link's app, are set aside (`store.retireHistory`): record writes the same episodes on does, which a session reads once the config turns on. Each keeps its omni-channel and its episodes, so its cards stay where they were written, but its address becomes `retired::`, which no sighting, read or join finds by the number. What still talks to the person on the row's thread, call or cards reads the number back (`store.reachedAt`): `ContactMapEntries.GetByThread`, so a Linq chat's replies and scheduled deliveries check opt-outs, the sandbox and the limits against it (`channelbridge.replyTo`), and the closed episodes' and the cards' `contact_address`, so a call going on at the link still finds its caller's lines (`callerOf`) and is summarized. The number's next episode makes a row of its own, which joins the user (`joinPartner`). The user's own texts from before the link do not join either: nothing proves they were the user's, unless the customer says so: under a link whose boundary is before it (`include_phone_history: true`, or `phone_history_since` earlier than the link), the user's cards read the number's set-aside rows of the link's app too (`store.Episodes.Cards`, `setAsideRead`, index `contact_map_retired`), from the boundary on. The rows stay where they are, so an unlink or a new number leaves them off the user, and a router that knows no boundary (v0.6.284) reads none of them. A row with no episode joins as it is, the same link again changes nothing, and a config with `episode_cards` off keeps its rows as before. Example: `+15550100` texted the agent on Monday, from Carl or from Bob before the customer knew him; Bob is linked to it on Tuesday; Bob's chat reads none of Monday's SMS, and his SMS on Wednesday reaches his chat. The card of the number's next episode, in progress, reads only that episode's lines (`linesOf`, from its start), though the number's thread channel holds Monday's texts too. +- **What a number said before its link's boundary is never read, however the cards got turned on.** A config with `episode_cards` off at the link sets nothing aside, so its rows join the user as they are, with the episodes the number had: written while the config recorded or read the cards, or by a release whose channel bridge wrote them whatever the config said. Every session leaves out, whole, an episode of a linked number that started before the boundary (`store.Episodes.Cards`, `historyBoundary`): the link as `linkOf` finds it, in the row's app, a set-aside row by its number; the boundary is `user_phone_history.since` (NULL: none) of the row written for the link's time (`linked_at` = `user_phones.updated_at`), else the link's time, `user_phones.updated_at`, by Postgres's clock as the start of a number's episode is, which a new number moves and the same number again leaves. An SMS episode starts at the inbound queue's `created_at`; a call's at `statement_timestamp()` less its session's age by the router's monotonic clock (`store.Episode.Began`), so a call that began before the link stays before it however far the router's clock runs ahead and however late its card is written. That covers the summarized cards, the cards in progress and the call cards, for the app chat, the user's own device, the number's calls and its SMS threads. Example: Bob is linked to `+15550100` on Tuesday under a config with the cards off; the config turns them on on Wednesday; Bob's chat reads none of Monday's SMS, still in progress or not, and reads Wednesday's. A session on the number's thread is handed none of the thread's messages from before the boundary either (`store.UserPhones.ThreadHistorySince`, the thread's newest episode with a linked number; `conversation.Restore.Since`, in `session.Manager.restoring`); a thread whose number is linked to nobody is handed all of it, as before. Example: Bob is linked to `+15550100` on Tuesday with neither field; his SMS session on Wednesday is handed none of Monday's texts; with `phone_history_since` Monday it is handed them, and with `include_phone_history: true` Sunday's too. - **The deployment's own app is one app, whatever its pin.** A chat row from it carries its id (the message hook), in its pin and its address, an SMS row none, and a request acting in it 0 (`store.linkApp`, `streamUserAddresses`). - **Reading cards is opt-in too.** Off or record, `callCards.read` returns before any read, and the session is handed what it was before. Example: an SMS thread session under a config without `episode_cards` reads its thread as before and nothing else. -- **A person's cards are their omni-channel's.** `store.EpisodeCards` takes the contact rows of the same customer and agent that point at the omni-channel, so a linked Slack row and a phone row are one person, and the same number under another agent or customer is another. Example: `+15550100199`'s cards are never read for `+15550100100`. +- **A person's cards are their omni-channel's.** `store.Episodes.Cards` takes the contact rows of the same customer and agent that point at the omni-channel, so a linked Slack row and a phone row are one person, and the same number under another agent or customer is another. Example: `+15550100199`'s cards are never read for `+15550100100`. - **An app chat's session reads the cards of the one person who wrote there.** Only the text session a worker opens to answer a message the router handed out (`Spec.Dispatched`) reads them: the spec names no person (`UserID` is who the agent joins a call as, `Caller` is empty for the worker's server key), so the person is the Stream user who wrote the message handed out (`session.Manager.HandOut`, `Spec.HandedOutBy`), as `api.chatEpisode` keyed the card, and only in a channel whose members are that user alone, or that user and the agent, and while every message in the channel's last 100 that is a person's line or has no source is theirs: a voice recording alone is handed out though it is no line. The agent is the Stream user the session writes its replies as, its agent id (`conversation.sendWith` writes as `ledger.Agent`), which a worker's session takes from the channel's id (`Manager.handedOut`). The members are read from the channel's state, the same read as the messages, so the check costs no request of its own; a channel with a third member, two members of whom one is not the agent, or members the state does not list reads none, as with `episode_cards` off. A hand-out that names nobody, as a node from before made, reads none. Its own channel's episodes are left out, as a thread's own thread is: the session reads it word for word. Example: Anya's second chat starts with the summary of her first; her team's channel with the agent, which Carl is a member of, reads none of her cards though only she wrote there; Bob writes in her chat, sends a photo or a voice recording there, or replies in a Stream thread of it, and the session opened for that reads none of her cards. - **The person's own device reads their cards.** A text or voice session opened with an end user's token signed for that user (`CallerKind` `authenticated`: by the app's secret in `api_key` mode, `auth.keyed`; by Stream behind the gateway, `auth.proxied`) reads the cards of that Stream user in the session's app, as the app chat keys them (`deviceContact`, `StreamUser`, `samePin`), the conversation it carries on left out, since it reads that word for word, while nobody else reads the answers: the conversation it carries on is not open to its members (`support_access` `members`, `conversation.Shared`) and its members are that user alone, or that user and the agent (`Reading.OwnAgent`), and a call with no number on it has as members and participants that user alone, or that user and the user the agent joins as (`Spec.UserID`), by `Between` as the app chat's members are checked. A call with a number on it reads the number's cards, whoever opened it. A guest (a temporary account the app does not know), an anonymous caller (any name), a backend naming a user, a scheduled task's session and the worker's (`Caller.ServerSide`) read none. Example: Anya chats «my appointment is Friday at 3»; later she taps «Talk to assistant» and the session her token opens starts with that card; a session opened with Bob's token reads none of hers, and neither does her session on a conversation Carl is a member of, nor her call Bob is on. - **A Stream user's word needs an app that checks tokens.** The app chat's and the device's sessions read cards only when Stream says the session's app checks the tokens it is sent, and an app chat's message opens an episode and writes its card only when Stream says so of the app the message came from (`streamapp.Clients.ChecksTokens`, one rule for both, `streamapp.Readiness`, kept a minute): with auth checks off a client may sign in, or write in the app chat, as anybody. An app Stream could not be asked about, or not within `ReadTimeout`, reads and writes none; the message is answered all the same. Example: a dev app with auth checks off; Bob's client writes as `anya_123`, reads none of her cards, and writes none into her omni-channel. @@ -186,14 +189,14 @@ A card closed after the idle period is updated in the app its episode is pinned - **The last lines whatever Stream's order.** The query is bounded by the window's end only, as Stream's documented backward pagination is; the start is applied in Go, and the lines are sorted by `created_at` before the tail is taken. - **No cards for a native speech-to-speech session.** Its history goes into its instructions as a transcript (`agent.openSpeech`), which drops the system note, so the cards would lose the note that they are not authority. A cascaded session that started with cards is refused a move onto one (`session.ErrCardedToNative`; the API answers `carded_session_to_native`, 400, from `setSessionSettings` and `updateSession`); a session without cards moves as before. - **A call card names where its transcript is.** Its `thread_channel` is the channel the transcript is written into (`Session.transcribedInto`), read as the transcript factory reads it (`Spec.TranscriptChannel`, `Spec.ConversationChannel`). A device's call under a thread channel's agent id writes none there (`persistent.BarThread`), so it has no episode. -- **A call the router placed is filed under who it rang.** A session opened on a call placed through `POST /v1/phone/calls` names no `PhoneSpec.To`, and the phone that joins such a call is the vendor's leg, which can come in under the line's own number (`store.ConnectCallLeg` matches it by `local_number`). So a phone session (`PhoneSpec` set) a backend opened (`auth.KindServer`) reads who the call rang from the router's record of it (`phone_calls.remote_number`, `outcome.Keeper.Read`, `callCards.rung`): the call id and type its own, in its own Stream app (`stream_app_pk`), and the vendor's call id its own (`PhoneSpec.VendorCallID`) when it names one. An end user's device and a session with no phone never do: either may name the id of a call it was never meant to be on. Example: a backend rings `+15550100160` from `+15550100150`; the card goes to `+15550100160`'s omni-channel. +- **A call the router placed is filed under who it rang.** A session opened on a call placed through `POST /v1/phone/calls` names no `PhoneSpec.To`, and the phone that joins such a call is the vendor's leg, which can come in under the line's own number (`store.CallLegs.Connect` matches it by `local_number`). So a phone session (`PhoneSpec` set) a backend opened (`auth.KindServer`) reads who the call rang from the router's record of it (`call_legs.remote_number`, `outcome.Keeper.Read`, `callCards.rung`): the call id and type its own, in its own Stream app (`stream_app_pk`), and the vendor's call id its own (`PhoneSpec.VendorCallID`) when it names one. An end user's device and a session with no phone never do: either may name the id of a call it was never meant to be on. Example: a backend rings `+15550100160` from `+15550100150`; the card goes to `+15550100160`'s omni-channel. - **The line is never the person.** A phone on the call whose number is the session's own (`PhoneSpec.Number`, `ownLine`) is the line, so it is neither read off the call nor waited for. Example: a placed call the router kept no record of, its vendor's leg `sip-+15550100150` on it, gets no card rather than one every person the line rang shares. - **A caller who joins after the agent still gets a card.** The call is read once; a phone session (`PhoneSpec` set) with no number on it then waits for the session to hear its first phone caller join (`Session.awaitCaller`, from the edge's `ParticipantJoined`; a second caller does not replace the first), as long as the session waits for anybody (`startTimeout`) and no longer than the session runs (`Session.close`). A call no phone session is on waits for nobody, as before. Example: Stream's `call.session_started` names no caller yet; the caller's leg joins two seconds after the agent and the card goes to their omni-channel. - **The budget covers the call read.** `callCards.read` puts `calledParty` under `ReadTimeout` too, so a slow Stream delays a call's join by at most 5 s. - **A card with nothing to say is skipped, not a stop.** `render` passes over a card with neither a summary nor a line, so the older cards are still read. Example: a call in a named channel at -60 s does not hide an SMS at -120 s. - **An episode closes once, whatever the number of routers.** Each close is one transaction whose row lock one router wins (`FOR UPDATE SKIP LOCKED`, then the status and the last message checked again), and the winner holds the summary for `summaryLease`. Example: two routers sweep at the same second; each idle thread gets one summary. -- **A message keeps its thread open.** `store.OpenEpisode` sets `episode_activity.last_message_at` with each message, in the statement that finds the episode open and holds it against a close; a message that arrives after the close opens the next episode and card. -- **An episode closes whatever its config says now.** Turning `episode_cards` off opens no new episode on any channel (a connector thread's is opened by the channel bridge under the config as stored when the message is written, `channelbridge.Bridge.queuedEpisode`), but an episode already open closes and is summarized as any other: the sweeper starts for a thread or chat episode still in progress, or a summary lease still held, though no config has the cards on (`store.AnyEpisodeToSweep`, AI-2771), and a call's hook closes a call's whatever the config. Example: Anya's chat episode is open when the config turns the cards off and the router restarts; it closes an hour after her last message and its card holds the summary. +- **A message keeps its thread open.** `store.Episodes.Open` sets `episodes.last_message_at` with each message, in the statement that finds the episode open and holds it against a close; a message that arrives after the close opens the next episode and card. +- **An episode closes whatever its config says now.** Turning `episode_cards` off opens no new episode on any channel (a connector thread's is opened by the channel bridge under the config as stored when the message is written, `channelbridge.Bridge.queuedEpisode`), but an episode already open closes and is summarized as any other: the sweeper starts for a thread or chat episode still in progress, or a summary lease still held, though no config has the cards on (`store.Episodes.AnyToSweep`, AI-2771), and a call's hook closes a call's whatever the config. Example: Anya's chat episode is open when the config turns the cards off and the router restarts; it closes an hour after her last message and its card holds the summary. - **A call ends with its call, never as idle.** The sweeper closes thread and chat episodes only (`session_id IS NULL`): a chat episode has no session, so it closes after `episodes.idle_after` as a thread's does. - **A card is updated as its author.** The closer reads each card once (`Closer.authorOf`, by its message id) and makes every update as the message's user: the agent of the omni-channel it was written in. Not the omni-channel the person's row points at now: an unlink points a number's row at a new omni-channel whose agent user is made only with its first card, and Stream refuses an update by a user it does not have («the user omni-… does not exist», staging, AI-2771). Example: Anya's number is linked, she texts, the number is unlinked; the card in her omni-channel still ends summarized. - **A failed summary keeps the raw text.** `summary_failed` changes the card's status only; the thread channel is never written. A call in a channel its session named gives no lines (`linesOf`), so its summary fails rather than mix in another caller's words. @@ -227,8 +230,8 @@ A card closed after the idle period is updated in the app its episode is pinned - A member added to a device session's conversation, or anybody who joins its call, after it read her cards hears the answers too: members and participants are read once, when the session opens. - A member added to a person's channel after its session read her cards reads the answers that session writes until somebody else's message retires it (`api.retire`): members are read once, when the session opens. Bob's second message while it retires can open a second session the conversation refuses (R3.1, its own ticket). - A worker's session for another person's message opened on another router does not wait for the retiring one: a conversation is held per process (`conversation.Service`), so both write in the channel until it closes. -- An SMS episode still open when its number is linked goes on as the number's: its next messages keep it open (`episodes_open_thread`) and read the set-aside row's cards from the boundary on, not the user's, until it closes as idle; the next episode joins the user. A call from the number reads no cards until an episode of the number makes its new row (`store.Contact` makes none). -- A thread session's history is cut at the boundary by clocks Postgres does not own (`conversation.Restore.Since` against each message): a message the router wrote is dated by the router's clock (`started_at` in its metadata, `conversation.go` `time.Now()`), a person's line or message by Stream's `created_at` (`messageFromVoice`, `messageFromThread`), and the pinned first message by the router's (`agent_responses.created_at`, `store.StartResponse`). A message within the clock skew of the boundary can fall on either side. A call episode's end is the router's clock too (`EndCallEpisodes`), or the shard's for a card closed with its session (`closed_at`). A call card's window therefore mixes three clocks: its start by Postgres's, its end (`Until`) by the router's or the shard's, its lines by Stream's `created_at`. If the router's clock runs behind Postgres's by more than the call lasts, `Until` falls before `started_at` and the card has no lines; the skew is milliseconds and a call lasts seconds or more. +- An SMS episode still open when its number is linked goes on as the number's: its next messages keep it open (`episodes_open_thread`) and read the set-aside row's cards from the boundary on, not the user's, until it closes as idle; the next episode joins the user. A call from the number reads no cards until an episode of the number makes its new row (`store.ContactMapEntries.GetByAddress` makes none). +- A thread session's history is cut at the boundary by clocks Postgres does not own (`conversation.Restore.Since` against each message): a message the router wrote is dated by the router's clock (`started_at` in its metadata, `conversation.go` `time.Now()`), a person's line or message by Stream's `created_at` (`messageFromVoice`, `messageFromThread`), and the pinned first message by the router's (`agent_responses.created_at`, `store.Responses.Insert`). A message within the clock skew of the boundary can fall on either side. A call episode's end is the router's clock too (`Episodes.EndCall`), or the shard's for a card closed with its session (`closed_at`). A call card's window therefore mixes three clocks: its start by Postgres's, its end (`Until`) by the router's or the shard's, its lines by Stream's `created_at`. If the router's clock runs behind Postgres's by more than the call lasts, `Until` falls before `started_at` and the card has no lines; the skew is milliseconds and a call lasts seconds or more. - A data move carries no link (`store.dataTables`): the contact rows it joins stay behind too, so the customer links again where it moved to. - A message nothing runs for, in a channel whose last call ran under another config than the one the channel names, or a channel naming none, opens no chat episode unless it holds a voice recording: `heldConfigOf` reads no config there. - A session a caller opens on a thread channel through the API and keeps open is checked for a shared thread once, when it opens; the Router's own sessions open for each turn (`api.answerThread`). diff --git a/acceleration/internal/omnichannel/close.go b/acceleration/internal/omnichannel/close.go index 2151e85930..587b8d6df3 100644 --- a/acceleration/internal/omnichannel/close.go +++ b/acceleration/internal/omnichannel/close.go @@ -331,7 +331,7 @@ func (c *Closer) ask(ctx context.Context, config store.AgentConfig, episode stor // authorOf is who an episode's card is updated as: its author, the agent user of the // omni-channel it was written in (Write). A message that is not a card as Write writes it has // no such author, as one that cannot be read has none: it is never updated as whoever wrote it. Not the omni-channel the person's row points at now: -// an unlink gives the number's row a new one (store.UnlinkUserPhone), whose agent user is made +// an unlink gives the number's row a new one (store.UserPhones.Unlink), whose agent user is made // only with its first card, and Stream refuses an update by a user it does not have («the user // omni-… does not exist», staging, AI-2771). func (c *Closer) authorOf(ctx context.Context, episode store.ClosedEpisode) (string, error) { diff --git a/acceleration/internal/omnichannel/close_test.go b/acceleration/internal/omnichannel/close_test.go index 7dbe716c1c..7db19c13ab 100644 --- a/acceleration/internal/omnichannel/close_test.go +++ b/acceleration/internal/omnichannel/close_test.go @@ -311,7 +311,7 @@ func (s *CloserSuite) TestAFailedSummaryLeavesSummaryFailedAndTheThreadIntact() func (s *CloserSuite) TestACardIsSummarizedAsItsAuthorAfterTheNumberWasUnlinked() { s.chat.KnownAuthors() user := "anya-" + uuid.NewString() - // A Stream user of the deployment's own app, as a link names one (store.LinkUserPhone). + // A Stream user of the deployment's own app, as a link names one (store.UserPhones.Link). chatting, err := s.cards.Open(s.ctx, Episode{ CustomerID: s.customerID, AgentConfigID: s.config.ID, AgentName: s.config.Name, Person: Person{Kind: store.ContactStreamUser, Address: store.StreamUserAddress(0, user)}, diff --git a/acceleration/internal/omnichannel/read.go b/acceleration/internal/omnichannel/read.go index 1798ae42e9..e1d0080220 100644 --- a/acceleration/internal/omnichannel/read.go +++ b/acceleration/internal/omnichannel/read.go @@ -172,7 +172,7 @@ func (c *Cards) whose(ctx context.Context, reading Reading) (store.ContactMapEnt // alone reports whether every person's message the session reads in its thread channel is // by the one who started the thread. The channel bridge makes the channel as the author of -// the thread's first message, the one the thread's episode is with (store.OpenEpisode). A +// the thread's first message, the one the thread's episode is with (store.Episodes.Open). A // Slack thread somebody else replied in is not alone: Alice's cards are never read for Bob. func (c *Cards) alone(ctx context.Context, reading Reading) (bool, error) { window, err := c.window(ctx, reading, reading.Thread) @@ -373,7 +373,7 @@ func summaryOf(ctx context.Context, bound streamapp.Bound, card store.EpisodeCar // writtenAsCard reports whether a message is in an omni-channel, by the channel's own agent // user, as Write writes a card. Not only in the reader's omni-channel: once a link joins a -// Stream user's and a number's rows (store.LinkUserPhone), the cards written before stay in the +// Stream user's and a number's rows (store.UserPhones.Link), the cards written before stay in the // omni-channel their row pointed at then, and are still the person's. func writtenAsCard(message getstream.MessageWithChannelResponse) bool { channelID, ok := strings.CutPrefix(message.Cid, chatlog.ChannelType+":") @@ -384,7 +384,7 @@ func writtenAsCard(message getstream.MessageWithChannelResponse) bool { // episode: before Until and not before it started, for a session reading the card as for its // summary (Closer). A call channel can hold other callers' calls, and a thread channel holds // every episode of its thread, one after another: a number's SMS thread holds what it texted -// before a link set those episodes aside (store.LinkUserPhone), so the card of its next +// before a link set those episodes aside (store.UserPhones.Link), so the card of its next // episode, in progress, never hands them to the linked user. // A channel that is not the customer's has none, and so has a call card whose window holds a // person's line by anybody but the card's caller: two callers on one call id at once, or a diff --git a/acceleration/internal/phone/lines.go b/acceleration/internal/phone/lines.go index fdc68845aa..aa074b6250 100644 --- a/acceleration/internal/phone/lines.go +++ b/acceleration/internal/phone/lines.go @@ -345,7 +345,7 @@ func (s *Service) routeAgain(ctx context.Context, stream *Stream, tx *store.Trun return routeID, nil } -// inTrunkGroup is store.InTrunkGroup behind a lock of this process's own. A caller waiting +// inTrunkGroup is store.StreamTrunks.InGroup behind a lock of this process's own. A caller waiting // on the database's lock holds a pooled connection, so a burst of calls for one group, a // campaign starting, would otherwise take every connection and leave none for the rest of // the router. diff --git a/acceleration/internal/phone/outcome/AGENTS.md b/acceleration/internal/phone/outcome/AGENTS.md index 2d824c5077..3eaca0e684 100644 --- a/acceleration/internal/phone/outcome/AGENTS.md +++ b/acceleration/internal/phone/outcome/AGENTS.md @@ -1,7 +1,7 @@ # internal/phone/outcome How each phone call ended. The `Keeper` keeps one row per call the router placed -(`phone_calls`), and `decide` (`outcome.go`) is the one place that turns the vendor's reports +(`call_legs`), and `decide` (`outcome.go`) is the one place that turns the vendor's reports and the phone's join and leave into its stored outcome: `completed`, `busy`, `no_answer`, `failed`, `canceled` or `unknown`. The API and billing read those values: add to them, never change one. @@ -43,7 +43,7 @@ Count once, whatever the order of events: phone may be ringing. - **Not counted**: a transfer's leg (an outbound leg with no row). - **Known gap**: a join that Stream delivers again after the call ended revives the leg - (`ConnectCallLeg`), and the stored outcome becomes `completed`. The call was already counted + (`CallLegs.Connect`), and the stored outcome becomes `completed`. The call was already counted under the outcome known at its first end (`no_answer`, or `unknown`), and it is not counted again. ## What a dropped call is diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 6b66fd08b2..0f53e32178 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -1443,7 +1443,7 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl Shared: shared, } // A shared line outlives the call, so its row costs nothing to undo when the dial fails, - // and the call's app (CallPin) is known before its leg arrives. + // and the call's app (store.CallResources.Pin) is known before its leg arrives. if shared { if err := s.store.CallResources.Insert(ctx, resource); err != nil { s.forgetOutcome(ctx, token, callID) diff --git a/acceleration/internal/policy/holds.go b/acceleration/internal/policy/holds.go index a270389822..7584729459 100644 --- a/acceleration/internal/policy/holds.go +++ b/acceleration/internal/policy/holds.go @@ -657,7 +657,7 @@ func (m *money) release(key string, acct *account, now time.Time) { acct.letGoGrants(held) case held.countedAt.IsZero() && !held.writtenAt.IsZero() && now.Sub(held.writtenAt) > uncountable: // The reconcile misses a row written past its overlap after it started, and - // AddGrantUses refuses one naming a grant long ended: neither ever counts. + // store.LimitGrantUses.InsertMany refuses one naming a grant long ended: neither ever counts. stranded += held.micros strandedGrants = append(strandedGrants, held.grants...) acct.letGoGrants(held) diff --git a/acceleration/internal/policy/spend.go b/acceleration/internal/policy/spend.go index c9b659df14..b2e1dbecc0 100644 --- a/acceleration/internal/policy/spend.go +++ b/acceleration/internal/policy/spend.go @@ -214,8 +214,8 @@ func (m *money) unread(acct *account, key string, owner routing.Owner, now time. // queueFirst adds an account to the batch of first reads gathering now, under m.mu, and starts // one when none is. A batch gathers for firstWindow and at most firstBatches are read at once, -// so a cold start that sees thousands of accounts makes a few calls of each kind (LimitsFor, -// Resets, the service's windows) rather than a call of each per account. +// so a cold start that sees thousands of accounts makes a few calls of each kind (store.Limits.SelectOf, +// store.UsageResets.Select, the service's windows) rather than a call of each per account. func (m *money) queueFirst(db *store.Store, key string) { if m.firstQueue == nil { m.firstQueue = map[string]bool{} diff --git a/acceleration/internal/pricing/pricing.go b/acceleration/internal/pricing/pricing.go index d2cc247de4..2a0660b59e 100644 --- a/acceleration/internal/pricing/pricing.go +++ b/acceleration/internal/pricing/pricing.go @@ -222,7 +222,7 @@ type Entry struct { } // QuotedVersion is the version of a quote for an amount the vendor quoted outright, such as -// a number's monthly rental: no entry of the list priced it, only QuotedFactorBps. +// a number's monthly rental: no entry of the list priced it, only PriceFactorBps. const QuotedVersion = "quoted" // Quote is what one unit of work costs, in millionths of a dollar, and the price list @@ -251,7 +251,7 @@ type Quote struct { type Pricer interface { Quote(item Item, used Quantities) Quote // Quoted resells an amount the vendor quoted outright for the item: the amount times - // QuotedFactorBps, versioned QuotedVersion. + // PriceFactorBps, versioned QuotedVersion. Quoted(item Item, micros int64) Quote Billable(item Item) bool // Entry is the item's entry: its vendor cost and its price. diff --git a/acceleration/internal/routing/attribution.go b/acceleration/internal/routing/attribution.go index 474e6f7ee5..4dd61cec34 100644 --- a/acceleration/internal/routing/attribution.go +++ b/acceleration/internal/routing/attribution.go @@ -69,7 +69,7 @@ const ( // JobOrigin is the origin of work one of the router's own jobs did, such as // job:episode_summary. A campaign or a scheduled task created before their scheduler was kept -// reads back job:campaign or job:scheduled_task (20261111120000_usage_identity.sql). +// reads back job:campaign or job:scheduled_task. func JobOrigin(name string) string { return "job:" + name } // CLIOrigin is the origin of work one of the router's own commands did on an operator's diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index 7ebe5e592c..dfb9a0773b 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -368,7 +368,7 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestDataMoveSuite/TestTheCutOver*`, `TestATaskTheUser*`, `TestReplicateResumeSuite` (`cmd/router`), `TestScheduledTasksSuite/TestATaskAMovePaused*` (`internal/api`), `TestScheduleResumeSuite/TestATaskAMovePaused*` (`internal/session`). -- **History is kept 90 days.** `PruneScheduledTasks` (daily, `pruneScheduledTasks` in `cmd/router`) deletes +- **History is kept 90 days.** `ScheduledTasks.Prune` (daily, `pruneScheduledTasks` in `cmd/router`) deletes runs finished, and completed or failed tasks last changed, over `ScheduledTasksKept` ago. An active or paused task stays; its old runs do not. A run by hand still running a day after it started (`scheduledTaskManualRunLost`) is written `missed` first: only the router that took the request diff --git a/acceleration/internal/scheduling/describe.go b/acceleration/internal/scheduling/describe.go index f61dba963a..cd88a2e840 100644 --- a/acceleration/internal/scheduling/describe.go +++ b/acceleration/internal/scheduling/describe.go @@ -65,7 +65,7 @@ func (r *repeatRule) sayable() error { } for i, day := range r.byMonthDay { switch { - // monthDayName names only -1 and -2 among the negative days. + // monthDays names only -1 and -2 among the negative days. case day < -2: return fail(CodeInvalidRepeat, "BYMONTHDAY=%d is not supported; the days counted from the end are -1 and -2; %s", day, supportedRepeats) case slices.Contains(r.byMonthDay[:i], day): diff --git a/acceleration/internal/scheduling/scheduler.go b/acceleration/internal/scheduling/scheduler.go index e21e962a45..30c1609820 100644 --- a/acceleration/internal/scheduling/scheduler.go +++ b/acceleration/internal/scheduling/scheduler.go @@ -50,7 +50,7 @@ var errOutOfTime = errors.New("the occurrence ran out of time") // or claimed elsewhere, so another router's claims are not chased in a loop. const poll = time.Second -// deliveryWindow is how late each kind of occurrence may be: a task that runs +// How late each kind of occurrence may be: a task that runs // once is still worth delivering a day late, told that it is late; a repeating // one is only run at its latest due occurrence, the older ones written missed. const ( diff --git a/acceleration/internal/scheduling/scheduler_activity_test.go b/acceleration/internal/scheduling/scheduler_activity_test.go index ddd00a18cf..b54e17378d 100644 --- a/acceleration/internal/scheduling/scheduler_activity_test.go +++ b/acceleration/internal/scheduling/scheduler_activity_test.go @@ -182,7 +182,7 @@ func (s *SchedulerSuite) TestAnOccurrenceWhoseRunWasNotWrittenIsNotCounted() { delivered := make(chan struct{}, 1) lose := func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { if claimed.Task.ID == task.ID { - // The run row gone, so FinishScheduledTaskRun's read of it fails. + // The run row gone, so store.ScheduledTasks.Finish's read of it fails. _, err := s.db.GlobalDB().ExecContext(ctx, `DELETE FROM scheduled_task_runs WHERE id = ?`, claimed.Run.ID) s.Require().NoError(err) delivered <- struct{}{} diff --git a/acceleration/internal/session/connector_tools.go b/acceleration/internal/session/connector_tools.go index 1df7a9296b..bce3db79a8 100644 --- a/acceleration/internal/session/connector_tools.go +++ b/acceleration/internal/session/connector_tools.go @@ -67,7 +67,7 @@ const ( // unavailableConnection: no live connection by that id that the binding may use. One code // for a missing connection and for another person's, so it says nothing of whose an id is. // A custom connector deleted while the session opens gets it too: a forced delete deletes - // its connections with it (store.DeleteConnectorDefinition). + // its connections with it (store.ConnectorDefinitions.Delete). unavailableConnection = "connection_unavailable" // unavailableProvider: the connection is to another connector than the binding names. unavailableProvider = "provider_mismatch" diff --git a/acceleration/internal/session/episode_card.go b/acceleration/internal/session/episode_card.go index 986f5c717f..2b5ba2018e 100644 --- a/acceleration/internal/session/episode_card.go +++ b/acceleration/internal/session/episode_card.go @@ -206,7 +206,7 @@ func (c *callCards) Close() { // party is the number of the person on a call session, for its card. A phone session whose // caller is not on the call yet waits for the session to hear them join: the caller can join // after the agent, as the call hook is not told who is calling until they have (an inbound -// leg can open without its caller, store.ConnectCallLeg). It waits as long as the session +// leg can open without its caller, store.CallLegs.Connect). It waits as long as the session // waits for anybody, its start timeout, past which a phone session nobody joined ends, or until // the session closes, whichever is first. func (c *callCards) party(created *Session, spec Spec, stream streamapp.Bound) (string, error) { @@ -284,7 +284,7 @@ func (c *callCards) calledParty(ctx context.Context, spec Spec, stream streamapp // rung is who the router rang on the session's call, for a session the customer's backend // opened on a call placed through POST /v1/phone/calls, which names no PhoneSpec.To: the // phone that joins such a call is the vendor's leg, under the line's own number -// (store.ConnectCallLeg matches it by local_number). Only for a phone session (PhoneSpec set) +// (store.CallLegs.Connect matches it by local_number). Only for a phone session (PhoneSpec set) // on the call placed: its call type and Stream app, and its vendor's call id when the session // names one (the SDKs send it). Not for an end user's device, nor a session with no phone, // either of which may name the session id of a call it was never meant to be on. Empty for a diff --git a/acceleration/internal/session/episode_reading_link_test.go b/acceleration/internal/session/episode_reading_link_test.go index 05a1bff26d..cf300dfb01 100644 --- a/acceleration/internal/session/episode_reading_link_test.go +++ b/acceleration/internal/session/episode_reading_link_test.go @@ -15,14 +15,14 @@ import ( // A card in progress read for its lines (AI-2716): a thread channel holds every episode of its // thread, one after another, so a number's SMS thread holds what it texted before a link set -// those episodes aside (store.LinkUserPhone), and an app chat's channel holds each run of the +// those episodes aside (store.UserPhones.Link), and an app chat's channel holds each run of the // person's messages. // inProgress is the status of a card whose episode is still open. const inProgress = "in_progress" // cardsConfig stores the suite's agent config with episode_cards on, as a link sets the -// number's history aside only for such a config (store.LinkUserPhone, retireHistory). +// number's history aside only for such a config (store.UserPhones.Link, retireHistory). func (s *EpisodeReadingSuite) cardsConfig() { config := store.AgentConfig{CustomerID: s.customerID, Name: "cards-" + uuid.NewString(), Mode: store.AgentModeText, EpisodeCards: store.AgentEpisodeCards{On: true}} @@ -140,7 +140,7 @@ func (s *EpisodeReadingSuite) TestAChatCardInProgressHasOnlyItsOwnEpisodesLines( s.Equal([]string{"my dog is Pepper"}, cardLines(handed[1]), "the run in progress, from its start") } -// linkAt links user to number as the customer's backend does (store.LinkUserPhone), dated +// linkAt links user to number as the customer's backend does (store.UserPhones.Link), dated // seconds after the test's start, where the test's story puts it: the suite dates what is said // before now. func (s *EpisodeReadingSuite) linkAt(user, number string, seconds int) { diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 83354e8c0a..305c4385c1 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -1224,7 +1224,7 @@ func (m *Manager) supersede(spec Spec) { } } -// RetireWithin bounds how long a retiring session (Session.Retire) may take to write the +// RetireWithin bounds how long a retiring session (Manager.Retire) may take to write the // replies it owes before it is closed all the same: as long as a written message's answer may // take (api.askTimeout). const RetireWithin = 2 * time.Minute diff --git a/acceleration/internal/session/resume_history.go b/acceleration/internal/session/resume_history.go index de52b1f8dd..a775db94ed 100644 --- a/acceleration/internal/session/resume_history.go +++ b/acceleration/internal/session/resume_history.go @@ -20,7 +20,7 @@ type ResumeHistories interface { // restoring is ctx with the session's resume_history applied to every conversation it // reads back, and a thread channel's history cut at the boundary of its number's link -// (store.ThreadHistorySince). A session asking for nothing, on no linked number's thread, gets +// (store.UserPhones.ThreadHistorySince). A session asking for nothing, on no linked number's thread, gets // ctx as it was, and the default with it. The boundary that cannot be read refuses the session: // it is the linked user's word on what they may be told. func (m *Manager) restoring(ctx context.Context, spec Spec) (context.Context, error) { diff --git a/acceleration/internal/session/step_up.go b/acceleration/internal/session/step_up.go index 975af3f475..e8c136e326 100644 --- a/acceleration/internal/session/step_up.go +++ b/acceleration/internal/session/step_up.go @@ -110,7 +110,7 @@ func (d *dispatcher) stepUp(ctx context.Context, r route, turnID string, asked c } // attemptOpen reports whether the attempt is still open: not used, not expired, and on a -// connection that was not deleted (store.ConnectorAuthorizationAttemptByID). +// connection that was not deleted (store.ConnectorAuthorizationAttempts.Get). func (d *dispatcher) attemptOpen(ctx context.Context, id string) bool { _, err := d.store.ConnectorAuthorizationAttempts.Get(ctx, id) return err == nil diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 75e7893f9d..93acc5821e 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -35,14 +35,14 @@ type AgentConfig struct { Name string `bun:"name,notnull"` // Role is what the config is for in the app around it, beyond answering people: // RoleAgentModerator, or empty for an ordinary agent. One live config per customer holds a - // role, test copies aside (20261103120000_agent_config_role.sql). + // role, test copies aside (agent_configs_role_idx). Role string `bun:"role,notnull"` // Mode is whether the agent is spoken to or written to: AgentModeVoice or // AgentModeText. A text agent uses neither speech target and joins no call. Mode string `bun:"mode,notnull"` // Region is where the agent's work is done, such as pricing.RegionEU: every model its // sessions run, its knowledge base and its sandbox are there, and nothing of it is done - // elsewhere (20261202135000_agent_region.sql). Empty is stored as pricing.DefaultRegion. + // elsewhere. Empty is stored as pricing.DefaultRegion. Region string `bun:"region,notnull"` // Models are what the agent's sessions run on, one column each. Models AgentModels `bun:"embed:"` @@ -103,16 +103,14 @@ type AgentConfig struct { // episode_cards_ columns. EpisodeCards AgentEpisodeCards `bun:"embed:episode_cards_"` // ToolGroups are the functions an SDK provides that the config's sessions may offer, and - // how each group is loaded (20270103090000_agent_config_tool_groups.sql). A function no - // group names is not offered. + // how each group is loaded. A function no group names is not offered. ToolGroups []ToolGroup `bun:"tool_groups,type:jsonb"` // ResumeHistory is how the config's sessions are handed back a conversation they // carry on. The zero value is the router's default. ResumeHistory ResumeHistory `bun:"resume_history,type:jsonb,notnull"` // FloorControl is the model that controls the floor in the config's sessions, and how - // long a caller may wait once they stop, as the config chose - // (20261221090000_floor_control_max_wait.sql). The zero value, NULL, is no choice: the - // router's default rules (session.FloorControlOf). + // long a caller may wait once they stop, as the config chose. The zero value, NULL, is no + // choice: the router's default rules (session.FloorControlOf). FloorControl FloorControl `bun:"floor_control,type:jsonb,nullzero"` // SyncHash is a fingerprint of the last directory written onto this config. Empty // if it was never synced from a directory. @@ -165,14 +163,12 @@ type AgentDispatch struct { // AgentEpisodeCards is how an agent's conversations use the person's episode cards. type AgentEpisodeCards struct { - // On has each session under the config start with the person's other episode cards - // (20261007042200_agent_config_episode_cards.sql), and the config write them as Record - // does. Off unless a config turns it on. + // On has each session under the config start with the person's other episode cards, and + // the config write them as Record does. Off unless a config turns it on. On bool `bun:"on,notnull"` // Record has each call, app chat and channel thread under the config write its episode - // card and summary into the person's omni-channel while no session reads them - // (20261217090000_agent_config_episode_cards_record.sql). Read only beside On off; - // WritesCards is the two together. + // card and summary into the person's omni-channel while no session reads them. Read only + // beside On off; WritesCards is the two together. Record bool `bun:"record,notnull"` } @@ -182,8 +178,7 @@ type AgentAnswersIn struct { // number to text, an iMessage line. Lines AgentChannels `bun:"lines,type:jsonb,notnull"` // Chat are the Stream Chat channel types of the customer's own app it answers in, such as - // a team's group channels (20261222120000_agent_config_chat_channels.sql). Empty, as every - // config starts, answers in agent channels alone. + // a team's group channels. Empty, as every config starts, answers in agent channels alone. Chat []ChatChannel `bun:"chat,type:jsonb"` } @@ -634,7 +629,7 @@ func (r *AgentConfigs) GetByRole(ctx context.Context, customerID, role string) ( } // GetByChatChannel returns the customer's live agent config that answers in Stream Chat -// channels of the type channelType (AgentConfig.ChatChannels): the oldest, when more than one +// channels of the type channelType (AgentConfig.Channels.Chat): the oldest, when more than one // names it, as the oldest config binding a line answers on it. A test copy (DraftOfTag) // answers in none. It is ErrNoAgentConfig when no config names the type. func (r *AgentConfigs) GetByChatChannel(ctx context.Context, customerID, channelType string) (AgentConfig, error) { @@ -722,7 +717,7 @@ func (r *AgentConfigs) where(ctx context.Context, customerID, column, value stri // lockBoundConnections locks each live connection of the config's customer that the config // binds as fixed until the transaction ends, and returns the ids it binds that are not live. -// It makes a bind and an unforced delete (DeleteUnboundConnectorConnection, which locks the +// It makes a bind and an unforced delete (ConnectorConnections.DeleteUnbound, which locks the // connection FOR UPDATE first) wait for each other, so one of them always sees the other: // // - A delete that locked the connection first is waited for. Under READ COMMITTED the @@ -785,7 +780,7 @@ func boundConnectors(bindings []ConnectorBinding) []string { // refuseUndefined refuses a binding to a custom connector the customer has no definition of, // unless kept, the bindings stored before this write, names it already: a forced connector -// delete leaves its bindings behind on purpose (DeleteConnectorDefinition), and a save that +// delete leaves its bindings behind on purpose (ConnectorDefinitions.Delete), and a save that // keeps one is not a new bind, as refuseUnbindable keeps a forced connection delete's. func refuseUndefined(undefined []string, kept []ConnectorBinding) error { for _, id := range undefined { diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index f4b0532289..945a1dea58 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -157,7 +157,7 @@ func (s *StoreSuite) TestUpdatingAConfigReplacesItsBindings() { s.Equal(replacement.ID, read.Connectors[0].Connection.ConnectionID) } -// The containment query in ConnectorConnectionReferenced reads the JSON this model writes, +// The containment query in ConnectorConnections.Referenced reads the JSON this model writes, // so a change to its tags shows here rather than as a connection deleted out from under an // agent. func (s *StoreSuite) TestAFixedBindingAConfigStoresReferencesItsConnection() { diff --git a/acceleration/internal/store/agent_log.go b/acceleration/internal/store/agent_log.go index d48836cb6f..99eedf505c 100644 --- a/acceleration/internal/store/agent_log.go +++ b/acceleration/internal/store/agent_log.go @@ -220,8 +220,8 @@ func (r *AgentLogs) Get(ctx context.Context, customerID string, id int64) (Agent if err != nil { return AgentLog{}, stack.Wrap(fmt.Errorf("store: agent log: %w", err)) } - // The log row's own details carry the error since 20260914175000_agent_log_failures.sql, - // and are the answer. A request's id is only unique in the database that numbered it, with + // The log row's own details carry the error, and are the answer; a row written before they + // did carries none. A request's id is only unique in the database that numbered it, with // shards or after a data move, which gives a moved request an id of its new deployment's, so // an older row's request is found by that number only when it also started when the row // says it happened, for the same agent: both writers log a request at its started_at. diff --git a/acceleration/internal/store/app.go b/acceleration/internal/store/app.go index 4178929ed5..6d505447e5 100644 --- a/acceleration/internal/store/app.go +++ b/acceleration/internal/store/app.go @@ -37,7 +37,7 @@ type AppSettings struct { AllowAnonymous *bool `json:"allow_anonymous,omitempty"` AllowGuest *bool `json:"allow_guest,omitempty"` // InternalConnectors is whether the app sees the connectors whose manifest says internal - // (visibleTo in connectors.go). Stream sets it on its own apps; no operation writes + // (visibleTo in connector_definition.go). Stream sets it on its own apps; no operation writes // settings, so an app cannot set it on itself. Nil is no. InternalConnectors *bool `json:"internal_connectors,omitempty"` // AgentTeams is whether an end user opens only the agent configs of a team they are in, diff --git a/acceleration/internal/store/audit_entry.go b/acceleration/internal/store/audit_entry.go index b6186dea23..a57525a0c2 100644 --- a/acceleration/internal/store/audit_entry.go +++ b/acceleration/internal/store/audit_entry.go @@ -15,8 +15,7 @@ import ( ) // What a change was made to (AuditEntry.ResourceType). Configuration, all of it: what an -// agent does while it runs is traffic and is kept elsewhere -// (20261008120000_audit_log.sql). +// agent does while it runs is traffic and is kept elsewhere. const ( AuditAgentConfig = "agent_config" AuditSkill = "skill" @@ -26,17 +25,16 @@ const ( AuditPlugin = "plugin" AuditPolicy = "policy" // AuditResourcePriceList is the deployment's price list, which is no customer's: its rows - // have no customer_id, so no app's audit query lists them - // (20261110120000_audit_log_manage.sql). + // have no customer_id, so no app's audit query lists them. AuditResourcePriceList = "price_list" // AuditEndUser is an app's end user whose id was forgotten in the usage records, named by - // the id that replaced it, never by the one forgotten (20261111120000_usage_identity.sql). + // the id that replaced it, never by the one forgotten. AuditEndUser = "end_user" // AuditSpendLimit is one of the organization's spend limits, named by its id, or a grant or - // a reset, named grant: and reset: (20261112120000_limits.sql). + // a reset, named grant: and reset:. AuditSpendLimit = "limit" // AuditProviderKey is a key the customer keeps for their own account at a vendor, named - // / (20261202130000_provider_keys.sql). + // /. AuditProviderKey = "provider_key" ) @@ -60,8 +58,7 @@ const ( AuditUpdated = "updated" AuditDeleted = "deleted" AuditSynced = "synced" - // AuditCancelled is a scheduled price change called off before it took effect - // (20261110140000_audit_log_cancelled.sql). + // AuditCancelled is a scheduled price change called off before it took effect. AuditCancelled = "cancelled" ) diff --git a/acceleration/internal/store/campaign_test.go b/acceleration/internal/store/campaign_test.go index d44c71b174..e9293bf35e 100644 --- a/acceleration/internal/store/campaign_test.go +++ b/acceleration/internal/store/campaign_test.go @@ -299,7 +299,7 @@ func (s *StoreSuite) TestACampaignHoldsAtMostAHundredThousandContacts() { campaign := s.draftCampaign(newID()) // Replica mode skips the row triggers (the data change capture and the campaign foreign // key) for these setup rows only, which is most of what 99,999 rows cost: on a busy runner - // the insert outlasted the driver's 10s read timeout. AddContacts below runs with them. + // the insert outlasted the driver's 10s read timeout. InsertMany below runs with them. err := s.store.GlobalDB().RunInTx(s.ctx, nil, func(ctx context.Context, tx bun.Tx) error { if _, err := tx.ExecContext(ctx, "SET LOCAL session_replication_role = replica"); err != nil { return err diff --git a/acceleration/internal/store/channel_inbound.go b/acceleration/internal/store/channel_inbound.go index 1e305316f1..80831fc006 100644 --- a/acceleration/internal/store/channel_inbound.go +++ b/acceleration/internal/store/channel_inbound.go @@ -28,9 +28,8 @@ const channelInboundDoneKeep = channelMessageKeep // for someone to find why it was never answered. 30 days is a choice, not a measurement. const channelInboundFailedKeep = 30 * 24 * time.Hour -// ChannelInbound is one inbound message queued to be written into its thread channel -// (20261205120000_channel_thread_inbound.sql), with what writing it and opening its episode -// card take. +// ChannelInbound is one inbound message queued to be written into its thread channel, with +// what writing it and opening its episode card take. type ChannelInbound struct { bun.BaseModel `bun:"table:channel_thread_inbound,alias:cti"` @@ -325,7 +324,7 @@ func (r *ChannelInbounds) Finish(ctx context.Context, claimed ChannelInbound, at // Fail records that a claimed message's last attempt failed and it is given up, // at at, and calls forward, when not nil, to forward the message's delivery: when it has one, // and no other message of the delivery forwarded it. The event destinations key a forward by -// the delivery only while it is queued (QueueEventDeliveries; FinishEventDelivery deletes it +// the delivery only while it is queued (EventDeliveries.Queue; EventDeliveries.Finish deletes it // once sent), and one thread's messages are given up minutes apart, so a delivery whose two // messages were never written would otherwise reach a destination twice. A message counts as // forwarded once forward returned nil, so a forward that fails, or a router that stops before diff --git a/acceleration/internal/store/channel_inbound_test.go b/acceleration/internal/store/channel_inbound_test.go index daf6984ac6..32b7d7f831 100644 --- a/acceleration/internal/store/channel_inbound_test.go +++ b/acceleration/internal/store/channel_inbound_test.go @@ -25,7 +25,7 @@ func (s *StoreSuite) inbound(channelID, providerMessageID string, change ...func return message } -// queue queues message in a transaction of its own, as AcceptChannelInbound does after its claim. +// queue queues message in a transaction of its own, as ChannelInbounds.Accept does after its claim. func (s *StoreSuite) queue(message ChannelInbound) (bool, error) { var queued bool err := s.store.global.RunInTx(s.ctx, nil, func(ctx context.Context, tx bun.Tx) error { @@ -669,7 +669,7 @@ func (s *StoreSuite) inboundClaims(channelID string) []string { return ids } -// waitedRow is the row AcceptChannelInbound's waited callback makes of a reply in thread-one. It +// waitedRow is the row ChannelInbounds.Accept's waited callback makes of a reply in thread-one. It // touches no table: the transaction holds the thread channel's row. func (s *StoreSuite) waitedRow(reply core.InboundMessage) (ChannelInbound, bool, error) { return ChannelInbound{ diff --git a/acceleration/internal/store/channel_owner.go b/acceleration/internal/store/channel_owner.go index 0f387be2a8..83a7d39e94 100644 --- a/acceleration/internal/store/channel_owner.go +++ b/acceleration/internal/store/channel_owner.go @@ -33,7 +33,7 @@ func (c AgentConfig) TestCopy() bool { const notTestCopy = "coalesce(tags->>'" + DraftOfTag + "', '') = ''" // channelOwnerLockSeed is the second argument to hashtextextended for the lock a channel -// connection's owner is decided under. Any value other than the 731 RecordAgentLog uses and +// connection's owner is decided under. Any value other than the 731 AgentLogs.Insert uses and // definitionLockSeed (833) would do; 1049 is this rule's issue, AI-1049. const channelOwnerLockSeed = 1049 diff --git a/acceleration/internal/store/channel_thread.go b/acceleration/internal/store/channel_thread.go index ea5bfd9c13..13391396c3 100644 --- a/acceleration/internal/store/channel_thread.go +++ b/acceleration/internal/store/channel_thread.go @@ -13,7 +13,7 @@ import ( ) // ChannelThread links one external thread, such as a Slack thread, to the thread channel the -// channel bridge writes it into (20261007003100_channel_threads.sql). +// channel bridge writes it into. type ChannelThread struct { bun.BaseModel `bun:"table:channel_threads,alias:ct"` @@ -134,9 +134,8 @@ func (r *ChannelThreads) SetChatPerson(ctx context.Context, channelID, person st } // SetStarter records starter as the person who started a thread channel's chat, by the contact -// map address the episode their message opens has -// (20261217090000_agent_config_episode_cards_record.sql). One already recorded is left as it -// is, so the first admitted message's author stays the chat's starter. +// map address the episode their message opens has. One already recorded is left as it is, so +// the first admitted message's author stays the chat's starter. func (r *ChannelThreads) SetStarter(ctx context.Context, channelID, starter string) error { if channelID == "" || starter == "" { return stack.Wrap(errors.New("store: a channel id and a starter are required")) diff --git a/acceleration/internal/store/channel_thread_member.go b/acceleration/internal/store/channel_thread_member.go index 98709eb74a..d72c0d77e6 100644 --- a/acceleration/internal/store/channel_thread_member.go +++ b/acceleration/internal/store/channel_thread_member.go @@ -10,7 +10,7 @@ import ( ) // channelThreadMember is a person a thread channel's chat reaches, by the recipient their -// opt-outs name (20261117110000_channel_thread_members.sql). +// opt-outs name. type channelThreadMember struct { bun.BaseModel `bun:"table:channel_thread_members,alias:ctm"` diff --git a/acceleration/internal/store/channel_thread_message.go b/acceleration/internal/store/channel_thread_message.go index e826d07bad..081f460e60 100644 --- a/acceleration/internal/store/channel_thread_message.go +++ b/acceleration/internal/store/channel_thread_message.go @@ -16,8 +16,7 @@ import ( // choice rather than a measurement. Other providers' retry spans are unverified. const channelMessageKeep = 24 * time.Hour -// What a claimed message of a thread channel is, each with its own ids -// (20261007003100_channel_threads.sql). +// What a claimed message of a thread channel is, each with its own ids. const ( // ClaimInbound is a provider's message the channel bridge took, by the provider's id. ClaimInbound = "inbound" diff --git a/acceleration/internal/store/chat_inbound.go b/acceleration/internal/store/chat_inbound.go index 85d6bc7a77..9389fc3df6 100644 --- a/acceleration/internal/store/chat_inbound.go +++ b/acceleration/internal/store/chat_inbound.go @@ -32,8 +32,8 @@ const chatInboundDoneKeep = channelMessageKeep // as channelInboundFailedKeep. const chatInboundFailedKeep = 30 * 24 * time.Hour -// ChatInbound is one Stream Chat message queued to be answered -// (20261205140000_chat_inbound.sql), with where its delivery came from. +// ChatInbound is one Stream Chat message queued to be answered, with where its delivery came +// from. type ChatInbound struct { bun.BaseModel `bun:"table:chat_inbound,alias:cd"` diff --git a/acceleration/internal/store/connector_audit_event.go b/acceleration/internal/store/connector_audit_event.go index ab8c6ac663..3c53a36d14 100644 --- a/acceleration/internal/store/connector_audit_event.go +++ b/acceleration/internal/store/connector_audit_event.go @@ -22,7 +22,7 @@ const ( AuditProxyCall = "proxy_call" AuditTokenExport = "token_export" // AuditToolReapproved: the app's backend approved tools at the schema the provider lists - // now (ReapproveConnectorTools, 20261101130000_connector_audit_tool_reapproved.sql). + // now (ConnectorToolPins.Reapprove). AuditToolReapproved = "tool_reapproved" ) @@ -48,8 +48,7 @@ const ( ) // ConnectorAuditEvent is one grant a connection got, renewed or lost, with the ids that tie it -// to what caused it. It names no owner id and no account id, so it outlives a user delete -// (20261007170000_connector_invocations_and_audit.sql). +// to what caused it. It names no owner id and no account id, so it outlives a user delete. type ConnectorAuditEvent struct { bun.BaseModel `bun:"table:connector_audit,alias:ca"` diff --git a/acceleration/internal/store/connector_connection.go b/acceleration/internal/store/connector_connection.go index 79f811df48..c06d751e3d 100644 --- a/acceleration/internal/store/connector_connection.go +++ b/acceleration/internal/store/connector_connection.go @@ -70,8 +70,7 @@ var ErrNoSharedWebhook = errors.New("store: the connector's events are not route // disconnected, so it holds no provider unit: only a connected one does. var ErrConnectorConnectionNotConnected = errors.New("store: the connector connection is not connected") -// providerUnitIndex is the unique index ErrProviderUnitTaken stands for -// (20261006194000_connector_connections_provider_unit.sql). +// providerUnitIndex is the unique index ErrProviderUnitTaken stands for. const providerUnitIndex = "connector_connections_provider_unit_idx" // Get is one account at one connector. Stored credentials are sealed by the @@ -96,7 +95,7 @@ type ConnectorConnection struct { Status string `bun:"status,notnull"` GrantedScopes []string `bun:"granted_scopes,type:jsonb,notnull"` // ProviderUnitID is the routing key of a shared webhook, such as a WhatsApp - // phone_number_id: empty unless SetConnectorConnectionProviderUnit wrote it, and emptied + // phone_number_id: empty unless ConnectorConnections.SetProviderUnit wrote it, and emptied // when the connection stops being connected (saveAtRevision). ProviderUnitID string `bun:"provider_unit_id,nullzero"` // Revision advances with every new stored credentials, which are sealed against it. @@ -211,7 +210,7 @@ func (r *ConnectorConnections) Insert(ctx context.Context, registry core.Registr } return stack.Wrap(r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { // A custom definition is held until the connection is stored, so a delete of it waits - // and then finds the connection (DeleteConnectorDefinition). A built-in is never + // and then finds the connection (ConnectorDefinitions.Delete). A built-in is never // deleted, so a revision found here stays. if _, err := lockCustomDefinitions(ctx, tx, connection.CustomerID, []string{connection.ConnectorID}); err != nil { return err @@ -448,7 +447,7 @@ func (r *ConnectorConnections) Select(ctx context.Context, customerID string, fi // Delete soft deletes a live connection and drops its credentials at once, // so nothing can use it from here on, whether or not a config still binds it. It is the -// forced delete; DeleteUnboundConnectorConnection is the one that refuses a bound connection. +// forced delete; DeleteUnbound is the one that refuses a bound connection. func (r *ConnectorConnections) Delete(ctx context.Context, customerID, id string) error { affected, err := softDeleteConnections(ctx, r.store.global, customerID, false, id) if err != nil { @@ -460,8 +459,8 @@ func (r *ConnectorConnections) Delete(ctx context.Context, customerID, id string return nil } -// DeleteUnbound soft deletes a live connection as DeleteConnectorConnection -// does, unless a live agent config of the customer's binds it as its fixed connection. +// DeleteUnbound soft deletes a live connection as Delete does, unless a live agent config of +// the customer's binds it as its fixed connection. // // It locks the connection FOR UPDATE first, and checks for a binding in the UPDATE after. // A config write locks each connection it binds before it writes the binding @@ -502,8 +501,8 @@ func (r *ConnectorConnections) DeleteUnbound(ctx context.Context, customerID, id } // boundByConfig is true for a connection cc that a live agent config of the same customer -// binds as its fixed connection. ConnectorConnectionReferenced and -// DeleteUnbound both use it, so what one reports bound the other refuses. +// binds as its fixed connection. ConnectorConnections.Referenced and DeleteUnbound both use +// it, so what one reports bound the other refuses. // // A binding is matched by containment on the shape the prototype stored // ({"connection": {"type": "fixed", "connection_id": ...}}, ConnectorBinding in @@ -552,8 +551,8 @@ func softDeleteConnections(ctx context.Context, db bun.IDB, customerID string, u return affected, nil } -// DeletedConnection is one connection DeleteUserConnectorConnections or -// DeleteConnectorDefinition removed. +// DeletedConnection is one connection ConnectorConnections.DeleteUser or +// ConnectorDefinitions.Delete removed. type DeletedConnection struct { ID string ConnectorID string @@ -563,7 +562,7 @@ type DeletedConnection struct { } // SelectGrantedOfUser is every live connection of one user of the customer's -// that holds credentials, oldest first: the grants DeleteUserConnectorConnections drops. +// that holds credentials, oldest first: the grants DeleteUser drops. func (r *ConnectorConnections) SelectGrantedOfUser(ctx context.Context, customerID, userID string) ([]ConnectorConnection, error) { var connections []ConnectorConnection err := r.store.global.NewSelect().Model(&connections). @@ -620,8 +619,8 @@ func (r *ConnectorConnections) DeleteUser(ctx context.Context, customerID, userI ids = append(ids, row.ID) deleted = append(deleted, DeletedConnection{ID: row.ID, ConnectorID: row.ConnectorID, OwnerType: row.OwnerType, HadGrant: row.HadGrant}) } - // Attempts reference their connection with no cascade (20261002193100), so they go - // first. Invocations cascade. + // Attempts reference their connection with no cascade, so they go first. Invocations + // cascade. if _, err := tx.NewDelete().Model((*ConnectorAuthorizationAttempt)(nil)). Where("caa.connection_id IN (?)", bun.In(ids)).Exec(ctx); err != nil { return fmt.Errorf("store: delete a user's authorization attempts: %w", err) @@ -836,7 +835,7 @@ var credentialColumns = []string{ // SaveAtRevision saves new stored credentials, already sealed for // expectedRevision + 1, onto a connection that is live and still at expectedRevision, under -// the same lock WithLockedConnectorConnection holds, so it never lands in the middle of a +// the same lock WithLocked holds, so it never lands in the middle of a // refresh. It always advances the revision by one. A locked callback can commit a status // without advancing it (needs_reauthorization before a refresh), so a save at the same // revision from a snapshot read before that would pass the compare-and-swap and put back the @@ -926,7 +925,7 @@ func (r *ConnectorConnections) saveAtRevision(ctx context.Context, conn bun.ICon connection.GrantedScopes = []string{} } // A save that leaves the connection anything but connected frees its provider unit - // (SetConnectorConnectionProviderUnit says why); one that keeps it connected, such as a + // (SetProviderUnit says why); one that keeps it connected, such as a // refresh, keeps the unit the row holds. The row's, not the caller's copy, which may // predate the unit. if connection.Status != ConnectionConnected { diff --git a/acceleration/internal/store/connector_connection_test.go b/acceleration/internal/store/connector_connection_test.go index 27e37011bf..f48fa43d11 100644 --- a/acceleration/internal/store/connector_connection_test.go +++ b/acceleration/internal/store/connector_connection_test.go @@ -316,7 +316,7 @@ func (s *StoreSuite) TestABindThatCommitsBeforeTheDeleteTakesItsSnapshotStopsIt( deleter := s.router() deleted := make(chan error, 1) go func() { deleted <- deleter.ConnectorConnections.DeleteUnbound(s.ctx, "acme-app", connection.ID) }() - // The two seconds and the ten milliseconds are assertTheWaitEnded's (credentials_test.go). + // The two seconds and the ten milliseconds are assertTheWaitEnded's (credential_lock_test.go). s.Require().Eventually(func() bool { return s.waitingForTable("connector_connections") == 1 }, 2*time.Second, 10*time.Millisecond, "the delete waits for the table lock") s.bind("acme-app", fixedBinding(connection.ID)) @@ -369,7 +369,7 @@ func (s *StoreSuite) TestABindThatCommitsWhileTheDeleteWaitsForTheRowStopsIt() { deleter := s.router() deleted := make(chan error, 1) go func() { deleted <- deleter.ConnectorConnections.DeleteUnbound(s.ctx, "acme-app", connection.ID) }() - // The two seconds and the ten milliseconds are assertTheWaitEnded's (credentials_test.go). + // The two seconds and the ten milliseconds are assertTheWaitEnded's (credential_lock_test.go). s.Require().Eventually(func() bool { return s.waitingForALock() == 1 }, 2*time.Second, 10*time.Millisecond, "the delete waits for the row") s.bind("acme-app", fixedBinding(connection.ID)) @@ -759,7 +759,7 @@ func (s *StoreSuite) TestARevocationThatCommitsWhileTheUnitIsSetWins() { setter := s.router() set := make(chan error, 1) go func() { set <- setter.ConnectorConnections.SetProviderUnit(s.ctx, "acme-app", connection.ID, "unit-1") }() - // The two seconds and the ten milliseconds are assertTheWaitEnded's (credentials_test.go). + // The two seconds and the ten milliseconds are assertTheWaitEnded's (credential_lock_test.go). s.Require().Eventually(func() bool { return s.waitingForALock() == 1 }, 2*time.Second, 10*time.Millisecond, "the set waits for the row") s.Require().NoError(held.Commit()) diff --git a/acceleration/internal/store/connector_definition.go b/acceleration/internal/store/connector_definition.go index 772c7f11f9..af45c170f8 100644 --- a/acceleration/internal/store/connector_definition.go +++ b/acceleration/internal/store/connector_definition.go @@ -42,7 +42,7 @@ func ConnectorLabel(id string) string { } // definitionLockSeed is the second argument to hashtextextended for the lock a revision is -// written under. Any value other than the 731 RecordAgentLog uses would do, so a customer's +// written under. Any value other than the 731 AgentLogs.Insert uses would do, so a customer's // log writes never wait on its definitions; 833 is this table's issue, AI-833. const definitionLockSeed = 833 @@ -168,7 +168,7 @@ type Definitions interface { Latest(ctx context.Context, customerID, id string) (ConnectorDefinition, error) } -// latestVisibleDefinition is LatestConnectorDefinition read on db. +// latestVisibleDefinition is ConnectorDefinitions.Latest read on db. func latestVisibleDefinition(ctx context.Context, db bun.IDB, customerID, id string) (ConnectorDefinition, error) { if customerID == "" || id == "" { return ConnectorDefinition{}, stack.Wrap(errors.New("store: a customer and a connector id are required")) @@ -527,7 +527,7 @@ type ConnectorBindingUse struct { Binding string `bun:"binding"` } -// DeletedConnector is what DeleteConnectorDefinition found and removed. +// DeletedConnector is what ConnectorDefinitions.Delete found and removed. type DeletedConnector struct { // Uses is what named the definition when the delete looked, set on ErrConnectorDefinitionInUse too. Uses ConnectorUses @@ -596,7 +596,7 @@ func (r *ConnectorDefinitions) Delete(ctx context.Context, customerID, id string for _, connection := range connections { deleted.Uses.Connections = append(deleted.Uses.Connections, connection.ID) } - // A row whose connectors is not an array binds nothing, as in ConnectorConnectionUses. + // A row whose connectors is not an array binds nothing, as in ConnectorConnections.Uses. err = tx.NewSelect(). TableExpr("agent_configs AS ac"). Join("CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(ac.connectors) = 'array' THEN ac.connectors ELSE '[]'::jsonb END) AS binding"). @@ -623,8 +623,7 @@ func (r *ConnectorDefinitions) Delete(ctx context.Context, customerID, id string ID: connection.ID, ConnectorID: id, OwnerType: connection.OwnerType, HadGrant: connection.HadGrant, }) } - // The deliveries go with their destination (ON DELETE CASCADE, - // 20261007040000_connector_event_destinations.sql). + // The deliveries go with their destination (ON DELETE CASCADE). for _, model := range []any{(*ConnectorOAuthClient)(nil), (*ConnectorConfigToken)(nil), (*EventDestination)(nil)} { q := tx.NewDelete().Model(model).Where("customer_id = ? AND connector_id = ?", customerID, id) if _, err := q.Exec(ctx); err != nil { @@ -648,7 +647,7 @@ func (r *ConnectorDefinitions) Delete(ctx context.Context, customerID, id string // lockCustomDefinitions locks every revision of the customer's own definitions among ids FOR // KEY SHARE until tx ends, and returns the custom ids among them that have none. A writer of -// a row naming a custom definition calls it before its write, so DeleteConnectorDefinition +// a row naming a custom definition calls it before its write, so ConnectorDefinitions.Delete // and the write take turns. A built-in is never deleted, so it is neither locked nor reported. // FOR KEY SHARE, not FOR SHARE, as in lockBoundConnections: definitions are never updated, // and nothing but the delete needs to wait. diff --git a/acceleration/internal/store/connector_definition_test.go b/acceleration/internal/store/connector_definition_test.go index 58ab6375d9..b3d161b602 100644 --- a/acceleration/internal/store/connector_definition_test.go +++ b/acceleration/internal/store/connector_definition_test.go @@ -1065,7 +1065,7 @@ func (s *StoreSuite) TestADeleteWaitsForAConnectionInProgressAndIsRefused() { created := make(chan error, 1) connection := &ConnectorConnection{CustomerID: "acme-app", ConnectorID: id, DefinitionRevision: 1, OwnerType: OwnerApp, AuthScheme: "test_key"} go func() { created <- creator.ConnectorConnections.Insert(s.ctx, testSchemes, connection) }() - // The two seconds and the ten milliseconds are assertTheWaitEnded's (credentials_test.go). + // The two seconds and the ten milliseconds are assertTheWaitEnded's (credential_lock_test.go). s.Require().Eventually(func() bool { return s.waitingForTable("connector_connections") == 1 }, 2*time.Second, 10*time.Millisecond, "the create waits at its INSERT") deleter := s.router() @@ -1458,8 +1458,8 @@ func (s *StoreSuite) TestACustomDefinitionIsInternalRevisionByRevision() { } // An app without the flag, or a customer with no app row, sees the catalog it saw before the flag -// existed: every embedded built-in that is not internal, each found by LatestConnectorDefinition -// and ConnectorDefinition at its latest revision. An app with the flag sees the internal ones too. +// existed: every embedded built-in that is not internal, each found by ConnectorDefinitions.Latest +// and ConnectorDefinitions.Get at its latest revision. An app with the flag sees the internal ones too. func (s *StoreSuite) TestWithoutTheFlagEveryAppSeesTheCatalogItSawBefore() { s.Require().NoError(s.store.ConnectorDefinitions.Seed(s.ctx, providers.FS)) files, err := fs.ReadDir(providers.FS, ".") diff --git a/acceleration/internal/store/connector_invocation.go b/acceleration/internal/store/connector_invocation.go index 146fc8228e..1b78f47ad8 100644 --- a/acceleration/internal/store/connector_invocation.go +++ b/acceleration/internal/store/connector_invocation.go @@ -38,7 +38,7 @@ const ( ) // ConnectorInvocation is one connector tool call a session's dispatcher ran. It holds no -// argument and no result (20261007170000_connector_invocations_and_audit.sql). +// argument and no result. type ConnectorInvocation struct { bun.BaseModel `bun:"table:connector_invocations,alias:ci"` @@ -58,7 +58,7 @@ type ConnectorInvocation struct { // ErrorType is one of the Invocation* values, empty for a call that answered. ErrorType string `bun:"error_type,notnull"` // ProviderStatus is the provider's HTTP status for the call's last answered request, nil - // when none was answered (20261031130000_connector_invocation_failures.sql). + // when none was answered. ProviderStatus *int `bun:"provider_status"` // ErrorMessage is why the call failed, as its log line says it, redacted and at most 1 KiB // (session.dispatcher.record); empty for a call that answered. diff --git a/acceleration/internal/store/connector_invocation_test.go b/acceleration/internal/store/connector_invocation_test.go index a843fec734..ea71745219 100644 --- a/acceleration/internal/store/connector_invocation_test.go +++ b/acceleration/internal/store/connector_invocation_test.go @@ -76,9 +76,8 @@ func (s *StoreSuite) TestAnInvocationKeepsItsProviderStatusAndErrorMessage() { s.Equal("the server refused the request with 403 Forbidden", rows[1].ErrorMessage) } -// baseInvocation is ConnectorInvocation as the router before -// 20261031130000_connector_invocation_failures.sql has it (11fae4b1), without the provider's -// status and the error message. +// baseInvocation is ConnectorInvocation as the router that predates its provider_status and +// error_message columns has it (11fae4b1), without them. type baseInvocation struct { bun.BaseModel `bun:"table:connector_invocations,alias:ci"` diff --git a/acceleration/internal/store/connector_oauth_client.go b/acceleration/internal/store/connector_oauth_client.go index ff85f11a9f..c5064d6d7a 100644 --- a/acceleration/internal/store/connector_oauth_client.go +++ b/acceleration/internal/store/connector_oauth_client.go @@ -108,7 +108,7 @@ func (r *ConnectorOAuthClients) Upsert(ctx context.Context, client *ConnectorOAu err = r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { // A custom definition is held until the client is stored, so a delete of the connector // waits and then deletes it too, or went first and leaves no definition to find - // (DeleteConnectorDefinition): no client secret outlives its connector. + // (ConnectorDefinitions.Delete): no client secret outlives its connector. if _, err := lockCustomDefinitions(ctx, tx, client.CustomerID, []string{client.ConnectorID}); err != nil { return err } @@ -143,7 +143,7 @@ func (r *ConnectorOAuthClients) Upsert(ctx context.Context, client *ConnectorOAu return fmt.Errorf("%w: %s", ErrOAuthClientRegistration, client.ConnectorID) } // ON CONFLICT arbitrates the primary key alone, so another customer's row with the app - // fails the unique index (20261006195500_connector_oauth_clients_provider_app.sql). + // fails the unique index. if constraint(err) == "connector_oauth_clients_provider_app" { return fmt.Errorf("%w: %s %s", ErrProviderAppTaken, client.ConnectorID, client.ProviderAppID) } @@ -182,7 +182,7 @@ func (r *ConnectorOAuthClients) Get(ctx context.Context, customerID, connectorID // GetByProviderApp returns the record of the connector's provider app, the // one customer whose app it is. An inbound request names the app and carries no app // credential, so the app id, not a customer, is what finds the row, as the OAuth state finds an -// attempt (ConnectorAuthorizationAttemptByState). +// attempt (ConnectorAuthorizationAttempts.GetByState). func (r *ConnectorOAuthClients) GetByProviderApp(ctx context.Context, connectorID, providerAppID string) (ConnectorOAuthClient, error) { if connectorID == "" || providerAppID == "" { return ConnectorOAuthClient{}, stack.Wrap(errors.New("store: a connector id and a provider app id are required")) @@ -208,8 +208,7 @@ func (r *ConnectorOAuthClients) RewrapSecret(ctx context.Context, customerID, co return r.rewrap(ctx, "secret_sealed", "kek_version", customerID, connectorID, was, sealed, version) } -// RewrapSigningSecret is RewrapConnectorOAuthClientSecret for the provider -// app's signing secret. +// RewrapSigningSecret is RewrapSecret for the provider app's signing secret. func (r *ConnectorOAuthClients) RewrapSigningSecret(ctx context.Context, customerID, connectorID string, was, sealed []byte, version int) (bool, error) { return r.rewrap(ctx, "signing_secret_sealed", "signing_kek_version", customerID, connectorID, was, sealed, version) } diff --git a/acceleration/internal/store/connector_oauth_client_test.go b/acceleration/internal/store/connector_oauth_client_test.go index 0875171303..2efe7c1b9d 100644 --- a/acceleration/internal/store/connector_oauth_client_test.go +++ b/acceleration/internal/store/connector_oauth_client_test.go @@ -409,7 +409,7 @@ func (s *StoreSuite) TestARecordWithNeitherAClientIDNorASigningSecretIsRefused() } // The CHECK holds what the store checks for a writer that skips it, such as a later -// migration's backfill (20261009130000_connector_oauth_clients_provider_app_only.sql). +// migration's backfill. func (s *StoreSuite) TestTheTableRefusesARowWithNeitherAClientIDNorASigningSecret() { _, err := s.store.GlobalDB().ExecContext(s.ctx, `INSERT INTO connector_oauth_clients (customer_id, connector_id, registration, client_id, provider_app_id) VALUES (?, 'acme_line', 'customer', '', ?)`, diff --git a/acceleration/internal/store/connector_tool_pin.go b/acceleration/internal/store/connector_tool_pin.go index bacedc88d4..52106a8f10 100644 --- a/acceleration/internal/store/connector_tool_pin.go +++ b/acceleration/internal/store/connector_tool_pin.go @@ -17,9 +17,9 @@ import ( ) // ConnectorToolPin is the schema digest one tool of one connection had when a session first -// offered it, for a tool a session binding grants by name alone -// (20261011150000_connector_tool_pins.sql). It holds for the grant the connection had then, -// its ConnectedAt: a reconnect is a new trust event, and the next session pins again. +// offered it, for a tool a session binding grants by name alone. It holds for the grant the +// connection had then, its ConnectedAt: a reconnect is a new trust event, and the next session +// pins again. type ConnectorToolPin struct { bun.BaseModel `bun:"table:connector_tool_pins,alias:ctp"` @@ -156,7 +156,7 @@ func (r *ConnectorToolPins) Reapprove(ctx context.Context, connection ConnectorC } now := time.Now().UTC().Truncate(time.Microsecond) // By name, so two approves of the same tools take the pins' locks in one order, as - // PinConnectorTools does. + // Pin does. ordered := slices.SortedFunc(slices.Values(tools), func(a, b ApprovedTool) int { return strings.Compare(a.Name, b.Name) }) names, digests, previous := make([]string, len(ordered)), make([]string, len(ordered)), make([]string, len(ordered)) for i, tool := range ordered { diff --git a/acceleration/internal/store/contact_map_entry.go b/acceleration/internal/store/contact_map_entry.go index c0e8635675..ff1d4244fb 100644 --- a/acceleration/internal/store/contact_map_entry.go +++ b/acceleration/internal/store/contact_map_entry.go @@ -12,21 +12,20 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) -// How a person is known to the contact map (20261007042000_contact_map.sql). +// How a person is known to the contact map. const ( // ContactPhone is an E.164 number: a call, an SMS, a WhatsApp message or an iMessage. ContactPhone = "phone" // ContactSlack is a Slack user in one workspace, «:». ContactSlack = "slack" // ContactStreamUser is a Stream user of the app chat in one Stream app, by the user id - // Stream signed, «:» (StreamUserAddress, 20261212090000_chat_episodes.sql). + // Stream signed, «:» (StreamUserAddress). ContactStreamUser = "stream_user" ) // ContactMapEntry is one address a person is reached at, for one agent of a customer: the -// omni-channel their episode cards go to (20261007042000_contact_map.sql), or, for a channel -// line's sender, the end user they are and the conversation the next message carries on -// (20270115000100_contact_map_channel_identities.sql). +// omni-channel their episode cards go to, or, for a channel line's sender, the end user they +// are and the conversation the next message carries on. type ContactMapEntry struct { bun.BaseModel `bun:"table:contact_map,alias:cm"` diff --git a/acceleration/internal/store/credential_lock.go b/acceleration/internal/store/credential_lock.go index 7fb2c18951..6d10d33c74 100644 --- a/acceleration/internal/store/credential_lock.go +++ b/acceleration/internal/store/credential_lock.go @@ -16,11 +16,11 @@ import ( // two-integer key spaces apart ("note that these two key spaces do not overlap", // https://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS), // and the other advisory locks in this repository take one bigint -// (hashtextextended(..., 731) in logs.go and the agent_logs migrations, -// hashtextextended(..., definitionLockSeed) in connectors.go), so no key here can be one of +// (hashtextextended(..., 731) in agent_log.go and the agent_logs migrations, +// hashtextextended(..., definitionLockSeed) in connector_definition.go), so no key here can be one of // theirs. 839 is this lock's issue, AI-839, as 833 is definitionLockSeed's; the value only // has to differ from the other two-integer locks: providerAppLockNamespace's 872 -// (config_tokens.go), and the change feed's, whose first key is a change number's high half +// (connector_config_token.go), and the change feed's, whose first key is a change number's high half // (record_data_change), 0 and up, and reaches 839 only past 839 << 32 changes. const credentialLockNamespace int32 = 839 @@ -45,7 +45,7 @@ const ( // withCredentialLock runs fn on one pool connection that holds the session-level advisory lock on // the connection's credential state, and gives the lock and the connection back when fn returns. // -// Session-level, not pg_advisory_xact_lock as connectors.go uses: checkpoint commits while +// Session-level, not pg_advisory_xact_lock as connector_definition.go uses: checkpoint commits while // the lock must stay held, and a transaction-level lock goes with the commit. "Once acquired // at session level, an advisory lock is held until explicitly released or the session ends", // and session-level requests "do not honor transaction semantics" diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 85aa1e3877..39fde43b92 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -196,11 +196,10 @@ var dataTables = []dataTable{ // they hid and the switches that hid it go with their session. {name: "agent_branch_switches", customer: "customer_id", shard: true}, {name: "agent_branch_messages", customer: "customer_id", shard: true}, - // Nothing points at a log's id, so a copied log is given one of this deployment's - // (20261206120000_agent_logs_source_id.sql). + // Nothing points at a log's id, so a copied log is given one of this deployment's. {name: "agent_logs", customer: "customer_id", copied: "source_id"}, // No foreign key points at a request's id. An agent log row names it as text, and - // Store.AgentLog only takes a request's error by that number from a row that carries none of + // AgentLogs.Get only takes a request's error by that number from a row that carries none of // its own and whose time and agent are the request's, so a moved row cannot show the error // of whichever request holds its number here. Its usage id is the unit of work wherever it is. {name: "requests", customer: "customer_id", shard: true, across: "usage_id"}, @@ -231,7 +230,7 @@ var dataTables = []dataTable{ // // isSecret is the one list: the export, the import and the record_data_change trigger // (watchDataChanges) all read it. A trigger attached before the list was passed applies the -// same rule in SQL (20270117000400_record_data_change_secrets.sql): change both together. +// same rule in SQL (record_data_change's own copy): change both together. func isSecret(column string) bool { return strings.HasSuffix(column, "_sealed") || strings.HasSuffix(column, "_secret_hash") || slices.Contains(oauthSecrets, column) @@ -240,8 +239,8 @@ func isSecret(column string) bool { // oauthSecrets are an OAuth grant's tokens and the state of one under way. var oauthSecrets = []string{"access_token", "refresh_token", "oauth_state", "code_verifier"} -// retiredTables are tables an export from an older release may carry that this schema dropped -// (20270112000100_drop_plugin_tables.sql). An import skips their rows, inserts and deletes alike. +// retiredTables are tables an export from an older release may carry that this schema dropped. +// An import skips their rows, inserts and deletes alike. var retiredTables = []string{"agent_plugin_connections", "agent_plugin_clients", "agent_plugin_event_subscriptions", "agent_plugin_event_deliveries"} // DataChange is one thing that happened to one row. @@ -804,7 +803,7 @@ func (s *Store) sideOf(table dataTable) *bun.DB { return s.global } -// lineColumns are what attaching a number, or giving it a line, writes on its row (AttachNumber, +// lineColumns are what attaching a number, or giving it a line, writes on its row (PhoneNumbers.Attach, // TrunkGroupTx.SetLine): where its calls go and which agent answers them. The sealed bridge // password is one too, and an import never writes it (isSecret). var lineColumns = []string{"stream_trunk_id", "stream_route_id", "stream_app_pk", "stream_call_id", "stream_call_type", @@ -894,7 +893,7 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str switch { case spec.isKey(shape, column): case spec.name == "phone_numbers" && slices.Contains(lineColumns, column): - // A number on a trunk here was attached or given a line here (AttachNumber, SetLine), + // A number on a trunk here was attached or given a line here (PhoneNumbers.Attach, TrunkGroupTx.SetLine), // since an imported row arrives off any trunk (identity). Where its calls go is then // this deployment's, so the source's copy of the row, in a copy taken again or a // change applied later, does not detach it. The agent is too only once attached: @@ -1568,7 +1567,7 @@ func settleSkippedRuns(ctx context.Context, tx bun.Tx, customerID string, tasks // It returns how many tasks it resumed, how many it left paused for want of a config, how many // for want of room, and the campaigns still running or scheduled there at the last catch-up. // Those it leaves paused and marked: a contact the source rang after that is still enrolled -// here, and resuming the campaign here (ResumeCampaign) rings it again, so that is left to a +// here, and resuming the campaign here (Campaigns.Resume) rings it again, so that is left to a // person. Any change of a campaign's state here clears the mark (transitionIn). Running it // again resumes nothing twice. func (s *Store) ResumeMovedRows(ctx context.Context, customerID string) (resumed, skipped, overLimit int64, campaigns []string, err error) { @@ -1828,19 +1827,19 @@ func (t dataTable) identity() string { } // A connector connection arrives without its credentials, so it arrives saying it needs // one, rather than connected with nothing to connect with. Key version 0 and no - // expiry are what a connection without credentials holds (20261002193000_connector_connections.sql), + // expiry are what a connection without credentials holds, // so the source credentials' key version and expiry do not come along either, on an import or // on every change applied after it. Nor does its provider unit: a row in an import is // whatever the importer wrote, and a unit stored from it would route another customer's // events to this one. The reconnect it needs proves the unit again - // (SetConnectorConnectionProviderUnit). + // (ConnectorConnections.SetProviderUnit). if t.name == "connector_connections" { return "jsonb_build_object('customer_id', ?::text, 'status', '" + ConnectionNeedsReauthorization + "'," + " 'credentials_kek_version', 0, 'expires_at', NULL, 'provider_unit_id', NULL)" } // A trunk arrives without its password, since the key that sealed it is the other // deployment's, so it arrives at key version 0, which is what a trunk without one - // holds (20261007050000_sip_trunks.sql). + // holds. if t.name == "sip_trunks" { return "jsonb_build_object('customer_id', ?::text, 'password_kek_version', 0)" } diff --git a/acceleration/internal/store/episode.go b/acceleration/internal/store/episode.go index aa4b70d26d..1e91ddf830 100644 --- a/acceleration/internal/store/episode.go +++ b/acceleration/internal/store/episode.go @@ -12,22 +12,21 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) -// What an episode came in on, the source field of its card (20261007042100_episodes.sql). +// What an episode came in on, the source field of its card. const ( EpisodeCall = "call" EpisodeSlack = "slack" EpisodeIMessage = "imessage" EpisodeSMS = "sms" EpisodeWhatsApp = "whatsapp" - // EpisodeChat is a run of messages in one agent channel of the app chat - // (20261212090000_chat_episodes.sql). + // EpisodeChat is a run of messages in one agent channel of the app chat. EpisodeChat = "chat" ) // episodeInProgress is an episode not closed yet, the status its card is written with. const episodeInProgress = "in_progress" -// The statuses that close an episode (20261007042100_episodes.sql; T55, omnichannel.Closer): +// The statuses that close an episode (T55, omnichannel.Closer): // ended once it is closed, then summarized or summary_failed once its summary is written or // could not be. const ( @@ -35,12 +34,12 @@ const ( EpisodeSummaryFailed = "summary_failed" ) -// EpisodeSummarized is an episode whose card holds its summary (20261007042100_episodes.sql; -// T55 sets it). A card in any other status is read by the last lines of its thread channel. +// EpisodeSummarized is an episode whose card holds its summary (T55 sets it). A card in any +// other status is read by the last lines of its thread channel. const EpisodeSummarized = "summarized" // Episode is one call, or one run of messages on one external thread, and its card in the -// person's omni-channel (20261007042100_episodes.sql). +// person's omni-channel. type Episode struct { bun.BaseModel `bun:"table:episodes,alias:ep"` @@ -246,7 +245,7 @@ func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limi // leases each to the router that ended it. The // status is checked on the row the update locks, so the event delivered twice, to two // routers, ends each episode once. session_id IS NOT NULL is every call episode -// (20261007042100_episodes.sql), named so episodes_open_call finds them. +// (episodes_check), named so episodes_open_call finds them. const endCallEpisodesQuery = ` WITH closed AS ( UPDATE episodes @@ -258,7 +257,7 @@ WITH closed AS ( // EndCall ends, at now, the episodes in progress of the call callID in the app scope names, // each leased to holder for its summary until leaseUntil. A call id is unique // only within its app, so the scope is the app the call event came from, as -// ReleaseCallResourcesInApp takes it. None is no error: a call under an agent config without +// CallResources.Release takes it. None is no error: a call under an agent config without // episode cards has none. func (r *Episodes) EndCall(ctx context.Context, scope AppScope, callID string, now, leaseUntil time.Time, holder string) ([]ClosedEpisode, error) { closed := []ClosedEpisode{} diff --git a/acceleration/internal/store/episode_test.go b/acceleration/internal/store/episode_test.go index fb3d44c720..ce87a90f10 100644 --- a/acceleration/internal/store/episode_test.go +++ b/acceleration/internal/store/episode_test.go @@ -375,7 +375,7 @@ func (s *StoreSuite) TestASummaryFinishesOnlyAnEndedEpisode() { s.Equal(episodeInProgress, s.episodeStatus(episode.ID)) } -// anyToSweep is AnyEpisodeToSweep's answer. +// anyToSweep is Episodes.AnyToSweep's answer. func (s *StoreSuite) anyToSweep() bool { due, err := s.store.Episodes.AnyToSweep(s.ctx) s.Require().NoError(err) diff --git a/acceleration/internal/store/event_delivery.go b/acceleration/internal/store/event_delivery.go index 6aaf3ad415..0077af2e74 100644 --- a/acceleration/internal/store/event_delivery.go +++ b/acceleration/internal/store/event_delivery.go @@ -109,7 +109,7 @@ func (r *EventDeliveries) Claim(ctx context.Context, now time.Time, limit, perDe return r.claim(ctx, claimEventDeliveriesQuery, now, limit, perDestination, sending, leaseUntil) } -// claimEventDeliveriesQuery is ClaimEventDeliveries' statement. Postgres refuses FOR UPDATE +// claimEventDeliveriesQuery is Claim's statement. Postgres refuses FOR UPDATE // beside a window function in one SELECT, so ranked numbers each destination's due rows first // and due locks the ones within the cap. // @@ -150,8 +150,8 @@ RETURNING cedl.destination_id, cedl.id, cedl.headers, cedl.body, cedl.attempts, cedl.provider_headers_until, ced.customer_id, ced.connector_id, ced.url, ced.secret_sealed, ced.kek_version, ced.previous_secret_sealed, ced.previous_kek_version, ced.previous_until` -// claim runs query, ClaimEventDeliveries' statement or a test's variant of it -// with a pause in it, with ClaimEventDeliveries' arguments. +// claim runs query, Claim's statement or a test's variant of it with a pause in it, with +// Claim's arguments. func (r *EventDeliveries) claim(ctx context.Context, query string, now time.Time, limit, perDestination int, sending map[string]int, leaseUntil time.Time) ([]ClaimedEventDelivery, error) { claimed := []ClaimedEventDelivery{} if limit < 1 || perDestination < 1 { diff --git a/acceleration/internal/store/image_job.go b/acceleration/internal/store/image_job.go index 8d55755dd2..90452354d3 100644 --- a/acceleration/internal/store/image_job.go +++ b/acceleration/internal/store/image_job.go @@ -25,8 +25,8 @@ const ( imageJobFailedKeep = chatInboundFailedKeep ) -// ImageJob is one picture an agent was asked to draw (20261230090000_image_jobs.sql): what to -// draw, who pays, where it is posted and how far it got. +// ImageJob is one picture an agent was asked to draw: what to draw, who pays, where it is +// posted and how far it got. type ImageJob struct { bun.BaseModel `bun:"table:image_jobs,alias:ij"` @@ -133,7 +133,7 @@ ij.message, ij.failed, ij.outcome, ij.created_at, ij.finished_at` // Claim takes up to limit queued jobs due now, moves each one's next attempt to the end of // lease and counts the claim. The drawn picture is left out of what it returns. decided takes the jobs whose message is decided, which only // post; otherwise the ones still to be drawn. A job whose earlier claim's lease ran out, such as -// one a router stopped in the middle of, is due again, as claimChatInboundQuery's rows are. +// one a router stopped in the middle of, is due again, as ChatInbounds.Claim's rows are. func (r *ImageJobs) Claim(ctx context.Context, limit int, lease time.Duration, decided bool) ([]ImageJob, error) { return claim[ImageJob](ctx, r.store.global, imageJobs, lease, limit, queuedImageJobs(decided), imageJobClaimed) } diff --git a/acceleration/internal/store/limit.go b/acceleration/internal/store/limit.go index 034eaa91aa..d75ef5d5f4 100644 --- a/acceleration/internal/store/limit.go +++ b/acceleration/internal/store/limit.go @@ -28,7 +28,7 @@ const ( ) // limitLevels is each subject's levels, most specific first, which is the order a subject's -// limit is resolved in (20261112120000_limits.sql, limits_level_check). +// limit is resolved in (limits_level_check). var limitLevels = map[usage.Subject][]LimitLevel{ usage.SubjectOrganization: {LevelOrganization}, usage.SubjectApp: {LevelApp}, diff --git a/acceleration/internal/store/limit_grant_test.go b/acceleration/internal/store/limit_grant_test.go index c5f691bac8..687e838b3c 100644 --- a/acceleration/internal/store/limit_grant_test.go +++ b/acceleration/internal/store/limit_grant_test.go @@ -44,7 +44,7 @@ func (s *StoreSuite) TestAGrantNamesOneSubject() { func (s *StoreSuite) TestLiveGrantsLeaveOutRevokedAndExpired() { // An hour ahead, so a slow insert is still before it (limit_grants_expiry_check), and - // LiveGrants is asked at instants pinned to it: how long the setup takes does not matter. + // LimitGrants.SelectLive is asked at instants pinned to it: how long the setup takes does not matter. // Microseconds, as Postgres keeps them. expires := time.Now().Add(time.Hour).Truncate(time.Microsecond) live := s.grant(LimitGrant{}) diff --git a/acceleration/internal/store/limit_grant_use_test.go b/acceleration/internal/store/limit_grant_use_test.go index b418e7e9af..7fe765faaa 100644 --- a/acceleration/internal/store/limit_grant_use_test.go +++ b/acceleration/internal/store/limit_grant_use_test.go @@ -28,7 +28,7 @@ func (s *StoreSuite) grantRow(store *Store, grants []int64, cost int64, billable } // writeAsTheWriter writes the rows and counts the ones written toward their grants, as the -// writer does: RecordRequests counts them with one database, the writer's grant counter apart +// writer does: Requests.InsertMany counts them with one database, the writer's grant counter apart // with shards. func (s *StoreSuite) writeAsTheWriter(store *Store, rows ...Request) { written, err := store.Requests.InsertMany(s.ctx, rows) diff --git a/acceleration/internal/store/models.go b/acceleration/internal/store/models.go index 57912f066a..26943f4d75 100644 --- a/acceleration/internal/store/models.go +++ b/acceleration/internal/store/models.go @@ -81,7 +81,7 @@ type ChildAgent struct { // agent_configs.connectors. // // The JSON is the prototype's (ConnectorBinding in internal/store/models.go on -// codex/connector-support at cf62af0d), and ConnectorConnectionReferenced finds a fixed +// codex/connector-support at cf62af0d), and ConnectorConnections.Referenced finds a fixed // binding by containment on {"connection": {"type": "fixed", "connection_id": ...}}, so a // change to these tags is a change to that query. core.Binding is the same thing for the // adapters, flattened and with a time.Duration; it has no JSON of its own, so it is not diff --git a/acceleration/internal/store/provider_key.go b/acceleration/internal/store/provider_key.go index 107a81bbbd..4244b83fe2 100644 --- a/acceleration/internal/store/provider_key.go +++ b/acceleration/internal/store/provider_key.go @@ -14,8 +14,7 @@ import ( ) // ProviderKey is a key a customer keeps with the router for their own account at a vendor, in -// one region (20261202130000_provider_keys.sql). Work routed on it is billed to them by the -// vendor, and by the router as BYOK. +// one region. Work routed on it is billed to them by the vendor, and by the router as BYOK. type ProviderKey struct { bun.BaseModel `bun:"table:provider_keys,alias:pk"` diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index 5fed5f06ad..4eb32253b4 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -46,7 +46,7 @@ type Request struct { UserID string `bun:"user_id,notnull"` UsageCategories []string `bun:"usage_categories,array,nullzero"` // LimitGrants are the grants the work was admitted on past a spent limit, which its - // billable cost is drawn from (20261112121000_requests_limit_grants.sql). + // billable cost is drawn from. LimitGrants []int64 `bun:"limit_grants,array,nullzero"` // AgentID is the agent the work was done for. Empty outside a conversation. AgentID string `bun:"agent_id,nullzero"` @@ -182,8 +182,8 @@ func measured(prefix string) string { return "COALESCE(" + prefix + "error_code, '') NOT IN ('" + ErrorCancelled + "', '" + ErrorRefused + "')" } -// requestsPrimaryKey is named for the table's first name: 20260815090000_multi_modality.sql -// renamed the table and not its key. +// requestsPrimaryKey is named for the table's first name: the table was renamed and its key +// was not. const requestsPrimaryKey = "stt_requests_pkey" // SpendBucket is what one group cost in one bucket, across every modality. Value is a @@ -302,7 +302,7 @@ func (r *Requests) Insert(ctx context.Context, request *Request) error { // skipped, so writing a batch again after a failure whose commit did land writes nothing twice. // A row InsertMany wrote has its ID set, and one with an agent a provider_request agent log // row. With one database each row it wrote counts toward the grants it names, and is logged, -// in the same transaction (AddGrantUses); with shards the grants are the caller's to count, +// in the same transaction (addGrantUses); with shards the grants are the caller's to count, // apart, and the log rows are written to the shared database after the commit. func (r *Requests) InsertMany(ctx context.Context, requests []Request) ([]uuid.UUID, error) { for i := range requests { diff --git a/acceleration/internal/store/scheduled_task.go b/acceleration/internal/store/scheduled_task.go index 69e6d546a2..e762a0acc4 100644 --- a/acceleration/internal/store/scheduled_task.go +++ b/acceleration/internal/store/scheduled_task.go @@ -284,7 +284,7 @@ func lockTaskLimits(ctx context.Context, tx bun.Tx, customerID string, holders [ // plain UPDATE of deleted_at, whose FOR NO KEY UPDATE conflicts only with // FOR SHARE and stronger (table 13.3, // https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS). -// A config is only ever soft-deleted (DeleteAgentConfig), so an id with no row +// A config is only ever soft-deleted (AgentConfigs.Delete), so an id with no row // is not a delete and is left to the caller, which resolved it. func refuseDeletedConfig(ctx context.Context, tx bun.Tx, customerID, configID string) (AgentScheduling, error) { var configs []AgentConfig diff --git a/acceleration/internal/store/session_unit_test.go b/acceleration/internal/store/session_unit_test.go index 1ea6835dbd..667f014170 100644 --- a/acceleration/internal/store/session_unit_test.go +++ b/acceleration/internal/store/session_unit_test.go @@ -19,7 +19,7 @@ func TestModelOverwritesEmpty(t *testing.T) { require.False(t, ModelOverwrites{Temperature: &zero}.Empty()) } -// TestSearchFallsBackToQuery holds the promise the search box relies on: no words is not +// TestSearchWithoutWordsNeedsACustomer holds the promise the search box relies on: no words is not // the same as no matches. It is checked here rather than against Postgres because what it // is really asserting is which method runs, and that is a decision made before any SQL. func TestSearchWithoutWordsNeedsACustomer(t *testing.T) { diff --git a/acceleration/internal/store/use_case.go b/acceleration/internal/store/use_case.go index ddd4810a09..a4aa110b6a 100644 --- a/acceleration/internal/store/use_case.go +++ b/acceleration/internal/store/use_case.go @@ -323,7 +323,7 @@ func (r *UseCases) Insert(ctx context.Context, useCase *UseCase, numbers ...stri } // Update replaces what an app wrote on a use case. Its status, vendor fields and -// review timestamps are left alone: those move through MoveUseCase. +// review timestamps are left alone: those move through Move. func (r *UseCases) Update(ctx context.Context, useCase *UseCase) error { if err := useCase.Validate(); err != nil { return stack.Wrap(err) diff --git a/acceleration/internal/store/user_phone.go b/acceleration/internal/store/user_phone.go index afa80ed8b2..430b1f611e 100644 --- a/acceleration/internal/store/user_phone.go +++ b/acceleration/internal/store/user_phone.go @@ -17,8 +17,7 @@ import ( // one person, so it is never two users of one app. var ErrPhoneTaken = errors.New("store: the number is linked to another user of the app") -// UserPhone says a Stream user of a customer's app and a phone number are one person -// (20261212100000_user_phones.sql). +// UserPhone says a Stream user of a customer's app and a phone number are one person. type UserPhone struct { bun.BaseModel `bun:"table:user_phones,alias:up"` @@ -30,7 +29,7 @@ type UserPhone struct { Phone string `bun:"phone,notnull"` CreatedAt time.Time `bun:"created_at,notnull"` // UpdatedAt is when the user was linked to Phone: the same number again leaves it, so what - // the number said since the link stays the user's (EpisodeCards). + // the number said since the link stays the user's (Episodes.Cards). UpdatedAt time.Time `bun:"updated_at,notnull"` // History is how much of the number's past a link request gives the user. Nil keeps what the // same number had, and gives a new number's link its own time (user_phone_history). @@ -102,7 +101,7 @@ const userLinkLockSeed = 2701 // number the user had before keeps none of the user's history: its rows that share the user's // omni-channel get one of their own (detachLinked). The new number brings none of its own: its // rows that hold episodes are set aside (retireHistory), so the user reads only what it says -// after the link, unless the link's History gives the user more of it (writeHistory, EpisodeCards). +// after the link, unless the link's History gives the user more of it (writeHistory, Episodes.Cards). // A number another user of the app holds is ErrPhoneTaken. Linking a pair again with no History // changes nothing. func (r *UserPhones) Link(ctx context.Context, link *UserPhone) error { @@ -119,7 +118,7 @@ func (r *UserPhones) Link(ctx context.Context, link *UserPhone) error { } // The link's time is Postgres's, as an SMS episode's start is (the inbound queue's // created_at), so an SMS queued after the link is never dated before it by the skew of - // two clocks (EpisodeCards). + // two clocks (Episodes.Cards). _, err := tx.NewInsert().Model(link). Value("created_at", "statement_timestamp()"). Value("updated_at", "statement_timestamp()"). @@ -152,9 +151,9 @@ func (r *UserPhones) Link(ctx context.Context, link *UserPhone) error { if err != nil { return err } - // After the link is committed, not in its transaction: a contact row MapContact makes at the - // same time either is committed before this reads it, or reads the link itself once it is - // made (ContactMapEntries.Map), so no row is left out of the pair. + // After the link is committed, not in its transaction: a contact row ContactMapEntries.Map + // makes at the same time either is committed before this reads it, or reads the link itself + // once it is made, so no row is left out of the pair. return r.joinLinked(ctx, *link) } @@ -338,7 +337,7 @@ func (r *UserPhones) streamUserAddresses(link UserPhone) []string { // made first, and its pin with it. The number is the link as stored, read under the link's // lock, not link.Phone: a join that comes after another PUT of the user joins the number that // PUT left. No card moves: a card is read by its message id (omnichannel.summaryOf), and the -// cards of a person are those of every row pointing at their omni-channel (EpisodeCards). Two +// cards of a person are those of every row pointing at their omni-channel (Episodes.Cards). Two // joins of one link take turns under its lock, so the second finds the first's rows on one // omni-channel already. Each half of the pair is found for each of the customer's agent // configs by the whole of contact_map_address, and born by contact_map_conversation, so a join @@ -412,7 +411,7 @@ const retiredPrefix = "retired:" // reachedAt is a row's address as the person is reached at: the number of a row a link set // aside (retireHistory), any other row's address as it is. What still talks to the person on -// a thread, call or card the row holds reads it (ThreadContact, the closed episodes' and the +// a thread, call or card the row holds reads it (ContactMapEntries.GetByThread, the closed episodes' and the // cards' contact_address), so a reply's opt-out, sandbox and limit checks and a call's caller // check name the number. Example: retired:3f2a…:+15550100 is reached at +15550100. const reachedAt = `regexp_replace(cm.address, '^` + retiredPrefix + `[^:]*:', '')` @@ -427,7 +426,7 @@ const reachedAt = `regexp_replace(cm.address, '^` + retiredPrefix + `[^:]*:', '' // person on its thread, call or cards still reads the number (reachedAt). The number's next // episode makes a row of its own, which joins the user (joinPartner). A row with no episode has nothing // to set aside and joins as it is (joinLinked); a config with episode_cards off keeps its rows -// as they were, and EpisodeCards' link filter keeps their episodes from the user. Record +// as they were, and Episodes.Cards' link filter keeps their episodes from the user. Record // counts as on: it writes the same episodes, which a session reads once the config turns on. // In tx, under the link's lock. func (r *UserPhones) retireHistory(ctx context.Context, tx bun.Tx, link UserPhone) error { diff --git a/acceleration/internal/store/user_phone_history_test.go b/acceleration/internal/store/user_phone_history_test.go index 60ef0deec5..6775b62c0e 100644 --- a/acceleration/internal/store/user_phone_history_test.go +++ b/acceleration/internal/store/user_phone_history_test.go @@ -228,7 +228,7 @@ func (s *StoreSuite) TestAThreadOfALinkThePreviousReleaseMadeAgainIsCutAtItsTime // previousCards is the previous release's EpisodeCards (ba2c5e912 episodes.go:384-412) for anya's // agent: the rows at the omni-channel, less what a linked number said before its link's time. -// Its agent_config_id is config_id since 20270115000100_contact_map_channel_identities.sql. +// Its agent_config_id has since been renamed config_id. func (s *StoreSuite) previousCards(omni string) []string { var found []string s.Require().NoError(s.store.global.NewRaw(`SELECT ep.id FROM episodes AS ep JOIN contact_map AS cm ON cm.id = ep.contact_id diff --git a/acceleration/internal/store/user_phone_test.go b/acceleration/internal/store/user_phone_test.go index 3424e8e6c9..0d91681e0c 100644 --- a/acceleration/internal/store/user_phone_test.go +++ b/acceleration/internal/store/user_phone_test.go @@ -166,7 +166,7 @@ func (s *StoreSuite) TestALinkSetsAsideTheRowsOfAConfigThatRecordsTheCards() { // Catches a set-aside row whose thread and call no longer name the number: a Linq chat's // replies would check opt-outs, the sandbox and the limits against retired: -// (ThreadContact, channelbridge.replyTo), and a call going on at the link would close with no +// (ContactMapEntries.GetByThread, channelbridge.replyTo), and a call going on at the link would close with no // caller its lines are said by (the closed episodes' contact_address, omnichannel.callerOf). // Its cards started before the link, so no session reads them; the cards of a set-aside row a // link gives the user name the number (TestALinkWithAllOfTheHistoryReadsWhatTheNumberSaidBeforeIt). @@ -578,7 +578,7 @@ func (s *StoreSuite) smsAt(row *ContactMapEntry, at time.Time) string { return episode.ID } -// linkDated links a user to a number as LinkUserPhone does, dated at linkedAt: the link's time its +// linkDated links a user to a number as UserPhones.Link does, dated at linkedAt: the link's time its // history row was written for too, and its boundary when the link is bounded at its own time. func (s *StoreSuite) linkDated(link *UserPhone) { s.Require().NoError(s.store.UserPhones.Link(s.ctx, link)) diff --git a/acceleration/internal/store/waiting_message.go b/acceleration/internal/store/waiting_message.go index 04aca433bc..3f5a1bd477 100644 --- a/acceleration/internal/store/waiting_message.go +++ b/acceleration/internal/store/waiting_message.go @@ -20,7 +20,7 @@ import ( const channelWaitingKeep = 10 * time.Minute // waitingMessage is a customer's message on an external thread no thread channel is linked to -// yet (20261011220000_channel_thread_waiting.sql). +// yet. type waitingMessage struct { bun.BaseModel `bun:"table:channel_thread_waiting,alias:ctw"` diff --git a/acceleration/internal/ttsrouter/recordings.go b/acceleration/internal/ttsrouter/recordings.go index 4aa4210e16..c1fb9658b9 100644 --- a/acceleration/internal/ttsrouter/recordings.go +++ b/acceleration/internal/ttsrouter/recordings.go @@ -275,7 +275,7 @@ func (r *Recordings) speak( } // A text the vendor takes no more of, such as one over Inworld's limit, is the caller's // to shorten, and says nothing about the model's health, which is every customer's (as - // routing.Select does for ErrRequest). + // routing.Router.Select does for ErrRequest). if checked, ok := provider.(tts.Checked); ok { if err := checked.Check(asked); err != nil { return tts.Recorded{}, routing.Refused(err)