diff --git a/acceleration/cmd/router/forget_integration_test.go b/acceleration/cmd/router/forget_integration_test.go index 94312fa8fd..3fae660b7c 100644 --- a/acceleration/cmd/router/forget_integration_test.go +++ b/acceleration/cmd/router/forget_integration_test.go @@ -450,6 +450,27 @@ func (s *ForgetUserSuite) TestForgettingAUserClearsTheirCountersPolicyAndLimits( s.Contains(out, "shared database: 1 policies and 1 limits deleted; 1 resets, 1 grants and 1 campaigns rewritten") } +func (s *ForgetUserSuite) TestForgettingAUserDropsTheirPolicyARouterCached() { + router, err := store.OpenShards(store.Options{ + DSN: s.settings.Postgres.DSN, ShardDSN: s.settings.Postgres.ShardDSN, Shards: s.settings.Postgres.Shards, + Redis: store.Redis{Address: s.settings.Redis.Addr}, + }) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(router.Close()) }) + s.settingsOf(s.app, person) + cached, err := router.Policies.Get(s.ctx, store.ScopeUser, store.UserScopeID(s.app, person)) + s.Require().NoError(err) + s.Require().NotNil(cached.Quota) + + s.forget(s.app, person) + + s.Eventually(func() bool { + read, err := router.Policies.Get(s.ctx, store.ScopeUser, store.UserScopeID(s.app, person)) + s.Require().NoError(err) + return read.Quota == nil + }, 5*time.Second, 10*time.Millisecond, "the router still answers the policy the user had") +} + func (s *ForgetUserSuite) TestTheAuditRowNeverNamesTheUser() { s.recorded(0, s.app, person, 100) s.settingsOf(s.app, person) diff --git a/acceleration/cmd/router/usage.go b/acceleration/cmd/router/usage.go index 9c2fc892ff..3223487574 100644 --- a/acceleration/cmd/router/usage.go +++ b/acceleration/cmd/router/usage.go @@ -400,11 +400,9 @@ func runUsageForgetUser(ctx context.Context, args []string, settings config.Conf if err != nil { return err } - pgStore, err := openPriceStore(settings) - if err != nil { - return err + if settings.Postgres.DSN == "" { + return errors.New("this needs a database: set postgres.dsn") } - defer pgStore.Close() redis, err := forgetRedis(settings) if err != nil { return err @@ -414,6 +412,17 @@ func runUsageForgetUser(ctx context.Context, args []string, settings config.Conf client.Close() } }() + // With the routers' Redis, so the policy deleted is dropped from what every router cached. + pgStore, err := store.OpenShards(store.Options{ + DSN: settings.Postgres.DSN, + ShardDSN: settings.Postgres.ShardDSN, + Shards: settings.Postgres.Shards, + Redis: store.Redis{Address: settings.Redis.Addr, Username: settings.Redis.Username, Password: settings.Redis.Password}, + }) + if err != nil { + return err + } + defer pgStore.Close() run := forgetting{ store: pgStore, usage: client, redis: redis, app: *app, user: *user, actor: *actor, replacement: *replacement, out: out, diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 9acdf2d490..9d5a2550cb 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -333,7 +333,7 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error { config.UpdatedAt = now config.DeletedAt = nil - err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { missing, err := lockBoundConnections(ctx, tx, config) if err != nil { return err @@ -361,13 +361,14 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error { return fmt.Errorf("store: create agent config: %w", err) } return nil + }, func() []string { + // Only the name, because the id was minted by the insert and nothing can have asked for + // it yet. The name may well have been asked for and not found. + return []string{agentConfigNameKey(config.CustomerID, config.Name)} }) if err != nil { return stack.Wrap(err) } - // Only the name, because the id was minted by the insert and nothing can have asked for it - // yet. The name may well have been asked for and not found. - r.store.forget(ctx, agentConfigNameKey(config.CustomerID, config.Name)) return nil } @@ -391,7 +392,7 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { config.UpdatedAt = time.Now().UTC() var wasName string - err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { missing, err := lockBoundConnections(ctx, tx, config) if err != nil { return err @@ -448,14 +449,20 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { return fmt.Errorf("store: update agent config: %w", err) } return nil + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if wasName == "" { + return nil + } + return []string{ + agentConfigKey(config.CustomerID, config.ID), + agentConfigNameKey(config.CustomerID, config.Name), + agentConfigNameKey(config.CustomerID, wasName), + } }) if err != nil { return stack.Wrap(err) } - r.store.forget(ctx, - agentConfigKey(config.CustomerID, config.ID), - agentConfigNameKey(config.CustomerID, config.Name), - agentConfigNameKey(config.CustomerID, wasName)) return nil } @@ -467,20 +474,27 @@ func (r *AgentConfigs) Delete(ctx context.Context, customerID, id string) error } var name string - err := r.store.global.NewUpdate().Model((*AgentConfig)(nil)). - Set("deleted_at = ?", time.Now().UTC()). - Where("id = ?", id). - Where("customer_id = ?", customerID). - Where("deleted_at IS NULL"). - Returning("name"). - Scan(ctx, &name) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model((*AgentConfig)(nil)). + Set("deleted_at = ?", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + Returning("name"). + Scan(ctx, &name) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if name == "" { + return nil + } + return []string{agentConfigKey(customerID, id), agentConfigNameKey(customerID, name)} + }) if errors.Is(err, sql.ErrNoRows) { return unknownAgentConfig(id) } if err != nil { return stack.Wrap(fmt.Errorf("store: delete agent config: %w", err)) } - r.store.forget(ctx, agentConfigKey(customerID, id), agentConfigNameKey(customerID, name)) return nil } diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index 6e6d2452b5..dc15b89a10 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -3,9 +3,12 @@ package store import ( + "context" "errors" "strings" "time" + + "github.com/uptrace/bun" ) // boundConfig stores a config of the customer's carrying bindings. @@ -226,6 +229,27 @@ func (s *StoreSuite) expiryOf(key string) time.Duration { return time.Duration(ttl) * time.Millisecond } +func (s *StoreSuite) TestADeleteARequestGaveUpOnIsNotCachedAgainByAReadBeforeItCommits() { + config := s.boundConfig("acme-app") + _, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err) + + err = s.readWhileWriting(s.lockingRow("agent_configs", config.ID), func(ctx context.Context) error { + return s.store.AgentConfigs.Delete(ctx, "acme-app", config.ID) + }, func() { + _, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err, "the config is not deleted yet") + _, err = s.store.AgentConfigs.GetByName(s.ctx, "acme-app", config.Name) + s.Require().NoError(err, "the config is not deleted yet") + }, bun.Tx.Commit) + + _, getErr := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) + s.ErrorIs(getErr, ErrNoAgentConfig) + _, getErr = s.store.AgentConfigs.GetByName(s.ctx, "acme-app", config.Name) + s.ErrorIs(getErr, ErrNoAgentConfig) + s.NoError(err, "the delete outlives the request that asked for it") +} + func (s *StoreSuite) TestAgentConfigQueryBudgets() { for range 20 { s.boundConfig("acme-app") @@ -276,5 +300,5 @@ func (s *StoreSuite) TestAgentConfigQueryBudgets() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) })) return } - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } diff --git a/acceleration/internal/store/api_key.go b/acceleration/internal/store/api_key.go index 09f875866f..5b7dd394f4 100644 --- a/acceleration/internal/store/api_key.go +++ b/acceleration/internal/store/api_key.go @@ -156,25 +156,36 @@ func (r *APIKeys) Touch(ctx context.Context, id string, interval time.Duration) // dropped; when it was not, they take the key until that copy lapses. func (r *APIKeys) Revoke(ctx context.Context, appID, id, by string) (told bool, err error) { now := time.Now().UTC() - result, err := r.store.global.NewUpdate().Model((*APIKey)(nil)). - Set("revoked_at = ?", now). - Set("revoked_by = ?", by). - Where("id = ?", id). - Where("app_id = ?", appID). - Where("revoked_at IS NULL"). - Exec(ctx) - if err != nil { - return false, stack.Wrap(fmt.Errorf("store: revoke api key: %w", err)) + var affected int64 + told, err = r.store.detachedWriteTold(ctx, func(ctx context.Context, tx bun.Tx) error { + result, err := tx.NewUpdate().Model((*APIKey)(nil)). + Set("revoked_at = ?", now). + Set("revoked_by = ?", by). + Where("id = ?", id). + Where("app_id = ?", appID). + Where("revoked_at IS NULL"). + Exec(ctx) + if err != nil { + return err + } + affected, err = result.RowsAffected() + return err + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if affected == 0 { + return nil + } + return []string{cacheKey("key", id)} + }) + if affected > 0 { + r.touched.Delete(id) } - affected, err := result.RowsAffected() if err != nil { return false, stack.Wrap(fmt.Errorf("store: revoke api key: %w", err)) } if affected == 0 { return false, stack.Wrap(ErrNoAPIKey) } - told = r.store.forget(ctx, cacheKey("key", id)) - r.touched.Delete(id) return told, nil } diff --git a/acceleration/internal/store/api_key_test.go b/acceleration/internal/store/api_key_test.go index 5584c0fbe7..2afd6311bb 100644 --- a/acceleration/internal/store/api_key_test.go +++ b/acceleration/internal/store/api_key_test.go @@ -258,10 +258,10 @@ func (s *StoreSuite) TestAPIKeyQueryBudgets() { read() s.Equal(0, s.countQueries(func() { s.Equal(0, s.countRedis(read)) }), "then the local cache answers") } - s.Equal(1, s.countQueries(func() { + s.Equal(3, s.countQueries(func() { s.Equal(s.redisTrips(1), s.countRedis(func() { _, err := s.store.APIKeys.Revoke(s.ctx, app.ID, key.ID, "thierry") s.Require().NoError(err) })) - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } diff --git a/acceleration/internal/store/app_organization.go b/acceleration/internal/store/app_organization.go index e93cc25889..7c66e233d3 100644 --- a/acceleration/internal/store/app_organization.go +++ b/acceleration/internal/store/app_organization.go @@ -47,10 +47,11 @@ func (r *AppOrganizations) Upsert(ctx context.Context, membership *AppOrganizati Set("organization_id = EXCLUDED.organization_id"). Set("seen_at = EXCLUDED.seen_at"). Exec(ctx) + // A write can commit and still fail to answer (a cancelled request). + r.store.forget(ctx, appOrganizationKey(membership.AppID), appPoliciesKey(membership.AppID)) if err != nil { return stack.Wrap(fmt.Errorf("store: join organization: %w", err)) } - r.store.forget(ctx, appOrganizationKey(membership.AppID), appPoliciesKey(membership.AppID)) return nil } diff --git a/acceleration/internal/store/budget_test.go b/acceleration/internal/store/budget_test.go index 7365bdc9c8..8560748176 100644 --- a/acceleration/internal/store/budget_test.go +++ b/acceleration/internal/store/budget_test.go @@ -5,10 +5,12 @@ package store import ( "context" "os" + "strings" "sync/atomic" "time" "github.com/redis/rueidis" + "github.com/redis/rueidis/rueidisaside" "github.com/uptrace/bun" ) @@ -70,10 +72,20 @@ func (s *StoreSuite) countEveryQuery() { type roundTrips struct{ sent atomic.Int64 } func (r *roundTrips) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResult { - r.sent.Add(1) + if !asideMarker(cmd) { + r.sent.Add(1) + } return client.Do(ctx, cmd) } +// asideMarker says cmd writes the marker rueidisaside keeps for this client, which it refreshes +// on its own every few seconds: not a round trip the store makes, but one that lands in a +// counted window now and then. +func asideMarker(cmd rueidis.Completed) bool { + parts := cmd.Commands() + return len(parts) > 1 && parts[0] == "SET" && strings.HasPrefix(parts[1], rueidisaside.PlaceholderPrefix) +} + func (r *roundTrips) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) []rueidis.RedisResult { r.sent.Add(1) return client.DoMulti(ctx, multi...) diff --git a/acceleration/internal/store/custom_model.go b/acceleration/internal/store/custom_model.go index cdc56076db..421edbc3c3 100644 --- a/acceleration/internal/store/custom_model.go +++ b/acceleration/internal/store/custom_model.go @@ -104,13 +104,16 @@ func (r *CustomModels) Insert(ctx context.Context, model *CustomModel) error { model.CreatedAt = now model.UpdatedAt = now - if _, err := r.store.global.NewInsert().Model(model).Exec(ctx); err != nil { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(model).Exec(ctx) + return err + }, func() []string { return []string{customModelKey(model.CustomerID, model.Name)} }) + if err != nil { if constraint(err) == "custom_models_name_idx" { return stack.Wrap(ErrNameTaken) } return stack.Wrap(fmt.Errorf("store: create model: %w", err)) } - r.store.forget(ctx, customModelKey(model.CustomerID, model.Name)) return nil } @@ -135,14 +138,25 @@ func (r *CustomModels) Update(ctx context.Context, model *CustomModel) error { Where("customer_id = ?", model.CustomerID). For("UPDATE") var wasName string - err := r.store.global.NewUpdate().Model(model). - With("was", was). - TableExpr("was"). - ExcludeColumn("id", "customer_id", "created_at"). - Where("cm.id = ?", model.ID). - Where("cm.customer_id = ?", model.CustomerID). - Returning("was.name"). - Scan(ctx, &wasName) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model(model). + With("was", was). + TableExpr("was"). + ExcludeColumn("id", "customer_id", "created_at"). + Where("cm.id = ?", model.ID). + Where("cm.customer_id = ?", model.CustomerID). + Returning("was.name"). + Scan(ctx, &wasName) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if wasName == "" { + return nil + } + return []string{ + customModelKey(model.CustomerID, model.Name), + customModelKey(model.CustomerID, wasName), + } + }) switch { case constraint(err) == "custom_models_name_idx": return stack.Wrap(ErrNameTaken) @@ -151,7 +165,6 @@ func (r *CustomModels) Update(ctx context.Context, model *CustomModel) error { case err != nil: return stack.Wrap(fmt.Errorf("store: update model: %w", err)) } - r.store.forget(ctx, customModelKey(model.CustomerID, model.Name), customModelKey(model.CustomerID, wasName)) return nil } @@ -162,18 +175,25 @@ func (r *CustomModels) Delete(ctx context.Context, customerID, id string) error } var name string - err := r.store.global.NewDelete().Model((*CustomModel)(nil)). - Where("id = ?", id). - Where("customer_id = ?", customerID). - Returning("name"). - Scan(ctx, &name) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewDelete().Model((*CustomModel)(nil)). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Returning("name"). + Scan(ctx, &name) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if name == "" { + return nil + } + return []string{customModelKey(customerID, name)} + }) if errors.Is(err, sql.ErrNoRows) { return stack.Wrap(fmt.Errorf("%w: %s", ErrNoCustomModel, id)) } if err != nil { return stack.Wrap(fmt.Errorf("store: delete model: %w", err)) } - r.store.forget(ctx, customModelKey(customerID, name)) return nil } diff --git a/acceleration/internal/store/custom_model_test.go b/acceleration/internal/store/custom_model_test.go index 3ca1ac5567..ab32a12bca 100644 --- a/acceleration/internal/store/custom_model_test.go +++ b/acceleration/internal/store/custom_model_test.go @@ -78,8 +78,8 @@ func (s *StoreSuite) TestCustomModelQueryBudgets() { s.Len(listed, 11) })) model.Model = "llama-2" - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.CustomModels.Update(s.ctx, &model)) })) - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.CustomModels.Delete(s.ctx, "app", model.ID)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.CustomModels.Update(s.ctx, &model)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.CustomModels.Delete(s.ctx, "app", model.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") if s.store.cache == nil { return } diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index 1433dd1116..7b48c2eba8 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -144,6 +144,8 @@ func (s *Store) ForgetUserSettings(ctx context.Context, appID, userID, replaceme entry.Changes = append(entry.Changes, counts.Changes()...) return recordAuditEntry(ctx, tx, entry) }) + // Dropped whatever the outcome, since a commit that fails can still have landed. + s.Policies.forget(ctx, ScopeUser, UserScopeID(appID, userID)) if err != nil { return UserSettings{}, stack.Wrap(fmt.Errorf("store: forget user settings: %w", err)) } diff --git a/acceleration/internal/store/policy.go b/acceleration/internal/store/policy.go index 03c212c006..f7fcb99216 100644 --- a/acceleration/internal/store/policy.go +++ b/acceleration/internal/store/policy.go @@ -200,15 +200,17 @@ func (r *Policies) Upsert(ctx context.Context, policy *Policy) error { replace = "document = jsonb_strip_nulls(jsonb_build_object('require_own_stream_app', " + "pol.document->'require_own_stream_app')) || EXCLUDED.document" } - _, err := r.store.global.NewInsert().Model(policy). - On("CONFLICT (scope, scope_id) DO UPDATE"). - Set(replace). - Set("updated_at = EXCLUDED.updated_at"). - Exec(ctx) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(policy). + On("CONFLICT (scope, scope_id) DO UPDATE"). + Set(replace). + Set("updated_at = EXCLUDED.updated_at"). + Exec(ctx) + return err + }, func() []string { return r.keys(ctx, policy.Scope, policy.ScopeID) }) if err != nil { return stack.Wrap(fmt.Errorf("store: save policy: %w", err)) } - r.forget(ctx, policy.Scope, policy.ScopeID) return nil } @@ -218,18 +220,21 @@ func (r *Policies) Delete(ctx context.Context, scope PolicyScope, id string) err if id == "" { return stack.Wrap(errors.New("store: a policy needs a scope id")) } - result, err := r.store.global.NewDelete().Model((*Policy)(nil)). - Where("scope = ?", scope). - Where("scope_id = ?", id). - Exec(ctx) - if err != nil { - return stack.Wrap(fmt.Errorf("store: delete policy: %w", err)) - } - deleted, err := result.RowsAffected() + var deleted int64 + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + result, err := tx.NewDelete().Model((*Policy)(nil)). + Where("scope = ?", scope). + Where("scope_id = ?", id). + Exec(ctx) + if err != nil { + return err + } + deleted, err = result.RowsAffected() + return err + }, func() []string { return r.keys(ctx, scope, id) }) if err != nil { return stack.Wrap(fmt.Errorf("store: delete policy: %w", err)) } - r.forget(ctx, scope, id) if deleted == 0 { return stack.Wrap(ErrNoPolicy) } @@ -276,11 +281,16 @@ func (r *Policies) HasUsers(ctx context.Context, appID string) (bool, error) { }) } -// forget drops what every replica had cached of a scope's document once it was written. An -// organization's is in the AppPolicies of every app seen under it, listed after the write -// committed: an app seen under it since drops its own (AppOrganizations.Upsert). A listing that -// fails is logged, as a deletion that fails is (Store.forget), and the TTL covers it. +// forget drops what every replica had cached of a scope's document once it was written. func (r *Policies) forget(ctx context.Context, scope PolicyScope, id string) { + r.store.forget(ctx, r.keys(ctx, scope, id)...) +} + +// keys are what every replica cached of a scope's document. An organization's is in the +// AppPolicies of every app seen under it, listed after the write committed: an app seen under +// it since drops its own (AppOrganizations.Upsert). A listing that fails is logged, as a +// deletion that fails is (Store.forget), and the TTL covers it. +func (r *Policies) keys(ctx context.Context, scope PolicyScope, id string) []string { keys := policyKeys(scope, id) if scope == ScopeOrganization && r.store.cache != nil { var apps []string @@ -293,7 +303,7 @@ func (r *Policies) forget(ctx context.Context, scope PolicyScope, id string) { keys = append(keys, appPoliciesKey(app)) } } - r.store.forget(ctx, keys...) + return keys } // policyKeys are the cached values a write of one scope's document changes, but for the diff --git a/acceleration/internal/store/policy_test.go b/acceleration/internal/store/policy_test.go index a55ac0cc46..43ace27254 100644 --- a/acceleration/internal/store/policy_test.go +++ b/acceleration/internal/store/policy_test.go @@ -286,10 +286,10 @@ func (s *StoreSuite) TestPolicyQueryBudgets() { limit := int64(3) user := Policy{Scope: ScopeUser, ScopeID: UserScopeID(app, "ann"), Document: PolicyDocument{Quota: &Quota{MessagesPerUserPerDay: &limit}}} - s.Equal(1, s.countQueries(func() { + s.Equal(3, s.countQueries(func() { s.Equal(s.redisTrips(1), s.countRedis(func() { s.Require().NoError(s.store.Policies.Upsert(s.ctx, &user)) }), "the document and the app's user flag are forgotten in one round trip") - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") s.Equal(1, s.countQueries(func() { _, err := s.store.Policies.SelectUsers(s.ctx, app, "", 10) s.Require().NoError(err) @@ -310,9 +310,9 @@ func (s *StoreSuite) TestPolicyQueryBudgets() { s.Equal(0, s.countQueries(func() { s.Equal(0, s.countRedis(read)) }), name+" is then answered locally") } } - s.Equal(1, s.countQueries(func() { + s.Equal(3, s.countQueries(func() { s.Equal(s.redisTrips(1), s.countRedis(func() { s.Require().NoError(s.store.Policies.Delete(s.ctx, ScopeUser, user.ScopeID)) })) - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } func (s *StoreSuite) TestAppPoliciesQueryBudgets() { @@ -338,8 +338,9 @@ func (s *StoreSuite) TestAppPoliciesQueryBudgets() { read() s.Equal(0, s.countQueries(func() { s.Equal(0, s.countRedis(read)) }), "then answered locally") } - // The write, then the apps whose cached policies it changed, all forgotten in one round trip. - s.Equal(s.redisTrips(1)+1, s.countQueries(func() { + // The write (begin, the write and commit), then the apps whose cached + // policies it changed, all forgotten in one round trip. + s.Equal(s.redisTrips(1)+3, s.countQueries(func() { s.Equal(s.redisTrips(1), s.countRedis(func() { s.Require().NoError(s.store.Policies.Upsert(s.ctx, &organization)) })) }), "an organization's save, however many apps it has") } diff --git a/acceleration/internal/store/provider_key.go b/acceleration/internal/store/provider_key.go index 8ba71fbc92..107a81bbbd 100644 --- a/acceleration/internal/store/provider_key.go +++ b/acceleration/internal/store/provider_key.go @@ -93,7 +93,7 @@ func (r *ProviderKeys) Upsert(ctx context.Context, key *ProviderKey) (ProviderKe var was ProviderKey var replaced bool - err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { err := tx.NewSelect().Model(&was). Where("customer_id = ? AND provider = ? AND region = ?", key.CustomerID, key.Provider, key.Region). For("UPDATE"). @@ -117,11 +117,10 @@ func (r *ProviderKeys) Upsert(ctx context.Context, key *ProviderKey) (ProviderKe Set("updated_at = EXCLUDED.updated_at"). Exec(ctx) return err - }) + }, func() []string { return []string{providerKeysKey(key.CustomerID)} }) if err != nil { return ProviderKey{}, false, stack.Wrap(fmt.Errorf("store: put provider key: %w", err)) } - r.store.forget(ctx, providerKeysKey(key.CustomerID)) return was, replaced, nil } @@ -187,17 +186,24 @@ func (r *ProviderKeys) Delete(ctx context.Context, customerID, provider, region return ProviderKey{}, stack.Wrap(errors.New("store: a customer, a provider and a region are required")) } var deleted ProviderKey - err := r.store.global.NewDelete().Model(&deleted). - Where("customer_id = ? AND provider = ? AND region = ?", customerID, provider, region). - Returning("*"). - Scan(ctx) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewDelete().Model(&deleted). + Where("customer_id = ? AND provider = ? AND region = ?", customerID, provider, region). + Returning("*"). + Scan(ctx) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if deleted.CustomerID == "" { + return nil + } + return []string{providerKeysKey(customerID)} + }) if errors.Is(err, sql.ErrNoRows) { return ProviderKey{}, stack.Wrap(fmt.Errorf("%w: %s in %s", ErrNoProviderKey, provider, region)) } if err != nil { return ProviderKey{}, stack.Wrap(fmt.Errorf("store: delete provider key: %w", err)) } - r.store.forget(ctx, providerKeysKey(customerID)) return deleted, nil } diff --git a/acceleration/internal/store/provider_key_test.go b/acceleration/internal/store/provider_key_test.go index c07a9097a9..8d35e58a10 100644 --- a/acceleration/internal/store/provider_key_test.go +++ b/acceleration/internal/store/provider_key_test.go @@ -114,10 +114,10 @@ func (s *StoreSuite) TestProviderKeyQueryBudgets() { all() s.Equal(0, s.countQueries(func() { s.Equal(0, s.countRedis(all)) }), "then the local cache answers") } - s.Equal(1, s.countQueries(func() { + s.Equal(3, s.countQueries(func() { s.Equal(s.redisTrips(1), s.countRedis(func() { _, err := s.store.ProviderKeys.Delete(s.ctx, "app", "openai", "global") s.Require().NoError(err) })) - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } diff --git a/acceleration/internal/store/redis.go b/acceleration/internal/store/redis.go index 51430107df..14e039fa61 100644 --- a/acceleration/internal/store/redis.go +++ b/acceleration/internal/store/redis.go @@ -34,6 +34,16 @@ const keyCacheTTL = time.Minute // otherwise be kept for cacheTTL. const missTTL = time.Minute +// forgetAttempts is how many times a deletion Redis did not take is tried again, the first +// forgetBackoff after it and each one twice as long after the last. forgetSlots bounds how +// many are being retried at once, so a Redis that is down costs a few goroutines and not one +// per write. +const ( + forgetAttempts = 3 + forgetBackoff = 100 * time.Millisecond + forgetSlots = 64 +) + // Redis says where a Redis server is. An empty Address is none. type Redis struct { // Address is a host:port, for example localhost:6379. @@ -165,10 +175,10 @@ type found[T any] struct { // forget drops cached rows from Redis, which drops them from every replica's local cache // too, in one round trip. // -// A deletion that does not land is logged rather than returned: the write it followed has -// already happened, and refusing it afterwards would tell the caller their change was -// rejected when it was not. The TTL is what covers the difference. It reports whether the -// deletion landed, false without Redis, for a caller that tells a person so. +// A deletion that does not land is tried again in the background rather than returned: the +// write it followed has already happened, and refusing it afterwards would tell the caller +// their change was rejected when it was not. It reports whether the deletion landed now, false +// without Redis, for a caller that tells a person so. // // The deletion goes out even when the request has been cancelled since the write: rueidis // returns the context's error before it sends anything, so neither the DEL nor the EXISTS @@ -195,12 +205,67 @@ func (s *Store) forget(ctx context.Context, names ...string) bool { commands = append(commands, client.B().Del().Key(name).Build(), client.B().Exists().Key(name).Build()) } replies := client.DoMulti(ctx, commands...) - landed := true + var missed []string + var failed error for i, name := range names { if err := replies[2*i].Error(); err != nil && !errors.Is(err, rueidis.Nil) { - slog.Default().Error("could not drop a cached row", "key", name, "error", err) - landed = false + missed, failed = append(missed, name), err } } - return landed + if len(missed) > 0 { + s.forgetLater(missed, failed) + } + return len(missed) == 0 +} + +// forgetLater tries again, a few times and in the background, a deletion Redis did not take. +// The usual cause is a connection Redis dropped, which the client dials again at once. A +// deletion still not taken after that, or one with no slot left to retry in, is what the TTL +// covers. +func (s *Store) forgetLater(names []string, err error) { + s.retryMu.Lock() + defer s.retryMu.Unlock() + if s.closed { + slog.Default().Error("could not drop cached rows, and the store is closing", "keys", names, "error", err) + return + } + select { + case s.retries <- struct{}{}: + default: + slog.Default().Error("could not drop cached rows, and no retry is free", "keys", names, "error", err) + return + } + s.retrying.Add(1) + go func() { + defer s.retrying.Done() + defer func() { <-s.retries }() + client := s.cache.Client() + wait := forgetBackoff + for range forgetAttempts { + timer := time.NewTimer(wait) + select { + case <-s.closing.Done(): + timer.Stop() + slog.Default().Error("could not drop cached rows before the store closed", "keys", names, "error", err) + return + case <-timer.C: + } + // One DEL per key, as forget sends them, since a cluster refuses one across slots. + commands := make(rueidis.Commands, 0, len(names)) + for _, name := range names { + commands = append(commands, client.B().Del().Key(name).Build()) + } + var missed []string + for i, reply := range client.DoMulti(s.closing, commands...) { + if failed := reply.Error(); failed != nil && !errors.Is(failed, rueidis.Nil) { + missed, err = append(missed, names[i]), failed + } + } + if names = missed; len(names) == 0 { + return + } + wait *= 2 + } + slog.Default().Error("gave up dropping cached rows", "keys", names, "attempts", forgetAttempts, "error", err) + }() } diff --git a/acceleration/internal/store/redis_test.go b/acceleration/internal/store/redis_test.go index 5ca0e94939..4d094e39ac 100644 --- a/acceleration/internal/store/redis_test.go +++ b/acceleration/internal/store/redis_test.go @@ -3,11 +3,23 @@ package store import ( + "bytes" + "context" "crypto/rand" + "encoding/binary" + "errors" "fmt" + "io" + "net" + "net/url" "os" + "runtime" + "strconv" "sync" "sync/atomic" + "time" + + "github.com/uptrace/bun" ) // clusterAddressVar names a node of a Redis Cluster with more than one shard, which CI does @@ -150,3 +162,669 @@ func (s *StoreSuite) forgotten(store *Store, names []string) { s.Zero(held, name) } } + +// heldBy begins a transaction that hold makes the writes under test wait behind, such as one +// holding a row with FOR UPDATE, and answers it with its backend's pid. +func (s *StoreSuite) heldBy(hold func(bun.Tx)) (bun.Tx, int) { + holder, err := s.store.global.BeginTx(s.ctx, nil) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = holder.Rollback() }) + var pid int + s.Require().NoError(holder.NewRaw("SELECT pg_backend_pid()").Scan(s.ctx, &pid)) + hold(holder) + return holder, pid +} + +// lockingRow holds the row of table with this id. +func (s *StoreSuite) lockingRow(table, id string) func(bun.Tx) { + return func(holder bun.Tx) { + _, err := holder.NewRaw("SELECT 1 FROM ? WHERE id = ? FOR UPDATE", bun.Ident(table), id).Exec(s.ctx) + s.Require().NoError(err) + } +} + +// waitingBehind waits until a statement waits for the holder with this pid, and answers that +// statement's backend's pid. +func (s *StoreSuite) waitingBehind(holder int) int { + var waiting int + s.Require().Eventually(func() bool { + var pids []int + s.Require().NoError(s.store.global.NewSelect().TableExpr("pg_stat_activity").Column("pid"). + Where("? = ANY(pg_blocking_pids(pid))", holder).Scan(s.ctx, &pids)) + if len(pids) == 0 { + return false + } + waiting = pids[0] + return true + }, 5*time.Second, 10*time.Millisecond, "the write's statement waits behind the holder") + return waiting +} + +// readWhileWriting runs write under a request deadline that passes while its statement waits +// behind a transaction hold set up, and then read: a read before Postgres can commit the +// write. The write must outlive its request until then. release ends the holder, and what the +// write answered is returned. +func (s *StoreSuite) readWhileWriting(hold func(bun.Tx), write func(context.Context) error, read func(), release func(bun.Tx) error) error { + holder, pid := s.heldBy(hold) + ctx, cancel := context.WithTimeout(s.ctx, 300*time.Millisecond) + defer cancel() + answered := make(chan error, 1) + go func() { answered <- write(ctx) }() + s.waitingBehind(pid) + <-ctx.Done() + var err error + returned := false + s.Never(func() bool { + select { + case err = <-answered: + returned = true + default: + } + return returned + }, time.Second, 10*time.Millisecond, "the write gave up with its request") + read() + s.Require().NoError(release(holder)) + if !returned { + err = <-answered + } + return err +} + +func (s *StoreSuite) TestAWriteThatRunsOutOfTimeIsRolledBackAndTheCacheAgrees() { + impatient, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN, Redis: s.redis(), writeTimeout: 300 * time.Millisecond}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(impatient.Close()) }) + config := s.routerConfig("acme-app", "fast") + holder, pid := s.heldBy(s.lockingRow("router_configs", config.ID)) + + answered := make(chan error, 1) + go func() { answered <- impatient.RouterConfigs.Delete(s.ctx, "acme-app", config.ID) }() + writer := s.waitingBehind(pid) + select { + case err = <-answered: + s.Require().Error(err, "the delete runs out of time") + case <-time.After(3 * time.Second): + s.FailNow("the delete outlived its own write timeout") + } + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err, "the config is still there while the delete waits") + s.Require().NoError(holder.Commit()) + s.Require().Eventually(func() bool { + alive, err := s.store.global.NewSelect().TableExpr("pg_stat_activity").Where("pid = ?", writer).Exists(s.ctx) + s.Require().NoError(err) + return !alive + }, 5*time.Second, 10*time.Millisecond, "the delete's backend finishes") + + deleted, err := s.store.global.NewSelect().Model((*RouterConfig)(nil)). + Where("id = ? AND deleted_at IS NOT NULL", config.ID).Exists(s.ctx) + s.Require().NoError(err) + s.False(deleted, "a delete that ran out of time is rolled back") + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.NoError(err, "and the cache agrees with the row") +} + +// redisProxy stands between a store and the suite's Redis and can drop every connection +// through it, as a Redis that restarts or a network that fails does. +type redisProxy struct { + listener net.Listener + target string + mu sync.Mutex + down bool + conns []net.Conn +} + +func (s *StoreSuite) redisProxy() *redisProxy { + if s.store.cache == nil { + s.T().Skipf("%s not set", redisAddressVar) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + proxy := &redisProxy{listener: listener, target: s.redis().Address} + s.T().Cleanup(func() { + _ = listener.Close() + proxy.setDown(true) + }) + go proxy.serve() + return proxy +} + +func (p *redisProxy) serve() { + for { + conn, err := p.listener.Accept() + if err != nil { + return + } + p.mu.Lock() + if p.down { + p.mu.Unlock() + _ = conn.Close() + continue + } + upstream, err := net.Dial("tcp", p.target) + if err != nil { + p.mu.Unlock() + _ = conn.Close() + continue + } + p.conns = append(p.conns, conn, upstream) + p.mu.Unlock() + go func() { _, _ = io.Copy(upstream, conn); _ = upstream.Close() }() + go func() { _, _ = io.Copy(conn, upstream); _ = conn.Close() }() + } +} + +// setDown drops every connection and refuses new ones while down, and lets them through again +// once not. +func (p *redisProxy) setDown(down bool) { + p.mu.Lock() + defer p.mu.Unlock() + p.down = down + if down { + for _, conn := range p.conns { + _ = conn.Close() + } + p.conns = nil + } +} + +func (s *StoreSuite) TestACachedRowIsForgottenOnceRedisTakesTheDeletionAgain() { + proxy := s.redisProxy() + behind, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN, Redis: Redis{Address: proxy.listener.Addr().String()}}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(behind.Close()) }) + config := s.boundConfig("acme-app") + _, err = s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err) + + proxy.setDown(true) + s.Require().NoError(behind.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) + proxy.setDown(false) + + s.Eventually(func() bool { + _, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) + return errors.Is(err, ErrNoAgentConfig) + }, 5*time.Second, 10*time.Millisecond, "the other node still holds the deleted config") +} + +// pgProxy stands between a store and the suite's Postgres and does one thing to the first +// COMMIT a client sends through it: drops every answer after it, as a network that fails then +// does, or holds it until let, as a COMMIT slow to reach the server does. +type pgProxy struct { + listener net.Listener + target string + hold bool + release chan struct{} + mu sync.Mutex + seen bool + released bool +} + +// pgProxy starts a proxy in front of the suite's shared database, and answers it with the DSN +// of a store on it, whose reads give up after a second. +func (s *StoreSuite) pgProxy(hold bool) (*pgProxy, string) { + target, err := url.Parse(s.dsn) + s.Require().NoError(err) + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + proxy := &pgProxy{listener: listener, target: target.Host, hold: hold, release: make(chan struct{})} + s.T().Cleanup(func() { + _ = listener.Close() + proxy.let() + }) + go proxy.serve() + target.Host = listener.Addr().String() + query := target.Query() + query.Set("read_timeout", "1s") + target.RawQuery = query.Encode() + return proxy, target.String() +} + +// let sends a held COMMIT on. +func (p *pgProxy) let() { + p.mu.Lock() + defer p.mu.Unlock() + if !p.released { + p.released = true + close(p.release) + } +} + +func (p *pgProxy) serve() { + for { + conn, err := p.listener.Accept() + if err != nil { + return + } + upstream, err := net.Dial("tcp", p.target) + if err != nil { + _ = conn.Close() + continue + } + var dropped atomic.Bool + go func() { + defer func() { _ = upstream.Close() }() + p.toServer(conn, upstream, &dropped) + }() + go func() { + defer func() { _ = conn.Close() }() + buf := make([]byte, 32<<10) + for { + n, err := upstream.Read(buf) + if n > 0 && !dropped.Load() { + if _, err := conn.Write(buf[:n]); err != nil { + return + } + } + if err != nil { + return + } + } + }() + } +} + +// toServer forwards a client's messages, the startup message and then typed ones, and treats +// the first simple-query COMMIT among them as the proxy says. +func (p *pgProxy) toServer(conn, upstream net.Conn, dropped *atomic.Bool) { + header := make([]byte, 4) + if _, err := io.ReadFull(conn, header); err != nil { + return + } + startup := make([]byte, binary.BigEndian.Uint32(header)-4) + if _, err := io.ReadFull(conn, startup); err != nil { + return + } + if _, err := upstream.Write(append(header, startup...)); err != nil { + return + } + for { + header := make([]byte, 5) + if _, err := io.ReadFull(conn, header); err != nil { + return + } + body := make([]byte, binary.BigEndian.Uint32(header[1:])-4) + if _, err := io.ReadFull(conn, body); err != nil { + return + } + if header[0] == 'Q' && bytes.HasPrefix(body, []byte("COMMIT")) && p.first() { + if p.hold { + <-p.release + } else { + dropped.Store(true) + } + } + if _, err := upstream.Write(append(header, body...)); err != nil { + return + } + } +} + +func (p *pgProxy) first() bool { + p.mu.Lock() + defer p.mu.Unlock() + first := !p.seen + p.seen = true + return first +} + +func (s *StoreSuite) TestADeleteWhoseCommitAnswerIsLostIsForgottenAtOnce() { + _, dsn := s.pgProxy(false) + lossy, err := OpenShards(Options{DSN: dsn, ShardDSN: s.shardDSN, Redis: s.redis(), writeTimeout: 300 * time.Millisecond}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(lossy.Close()) }) + config := s.routerConfig("acme-app", "fast") + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err) + + s.Require().Error(lossy.RouterConfigs.Delete(s.ctx, "acme-app", config.ID), "the COMMIT's answer never comes") + + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.ErrorIs(err, ErrNoRouterConfig, "the COMMIT landed, and the copy was dropped with no answer to it") +} + +func (s *StoreSuite) TestADeleteWhoseCommitLandsAfterItGaveUpIsForgottenAgain() { + proxy, dsn := s.pgProxy(true) + slow, err := OpenShards(Options{DSN: dsn, ShardDSN: s.shardDSN, Redis: s.redis(), writeTimeout: 300 * time.Millisecond}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(slow.Close()) }) + config := s.routerConfig("acme-app", "fast") + + s.Require().Error(slow.RouterConfigs.Delete(s.ctx, "acme-app", config.ID), "the COMMIT is held past the read timeout") + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err, "the config is still there while the COMMIT is held") + proxy.let() + s.Require().Eventually(func() bool { + deleted, err := s.store.global.NewSelect().Model((*RouterConfig)(nil)). + Where("id = ? AND deleted_at IS NOT NULL", config.ID).Exists(s.ctx) + s.Require().NoError(err) + return deleted + }, 5*time.Second, 10*time.Millisecond, "the held COMMIT lands") + + s.Eventually(func() bool { + _, err := s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + return errors.Is(err, ErrNoRouterConfig) + }, 5*time.Second, 10*time.Millisecond, "the copy cached before the COMMIT landed is dropped again") +} + +func (s *StoreSuite) TestForgetsBehindADownRedisAreBoundedAndEndWithTheStore() { + proxy := s.redisProxy() + before := runtime.NumGoroutine() + behind, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN, Redis: Redis{Address: proxy.listener.Addr().String()}}) + s.Require().NoError(err) + opened := runtime.NumGoroutine() + proxy.setDown(true) + + for i := range 200 { + behind.forget(s.ctx, cacheKey("probe", strconv.Itoa(i))) + } + s.LessOrEqual(runtime.NumGoroutine()-opened, forgetSlots+8, "the retries are bounded") + + closed := make(chan error, 1) + go func() { closed <- behind.Close() }() + select { + case err := <-closed: + s.NoError(err) + case <-time.After(2 * time.Second): + s.FailNow("Close waits on the retries") + } + // Polled here rather than with Eventually, whose own goroutine would be counted. + for deadline := time.Now().Add(2 * time.Second); runtime.NumGoroutine() > before && time.Now().Before(deadline); { + time.Sleep(10 * time.Millisecond) + } + s.LessOrEqual(runtime.NumGoroutine(), before, "no retry outlives the store") +} + +// lockingWhere holds the rows of table that where picks. +func (s *StoreSuite) lockingWhere(table, where string, args ...any) func(bun.Tx) { + return func(holder bun.Tx) { + _, err := holder.NewRaw("SELECT 1 FROM ? WHERE "+where+" FOR UPDATE", append([]any{bun.Ident(table)}, args...)...).Exec(s.ctx) + s.Require().NoError(err) + } +} + +// inserting holds an insert of row, not yet committed, which a write of the same name waits +// behind. +func (s *StoreSuite) inserting(row any) func(bun.Tx) { + return func(holder bun.Tx) { + _, err := holder.NewInsert().Model(row).Exec(s.ctx) + s.Require().NoError(err) + } +} + +// Every write of a cached row outlives the request that asked for it, and a read made while it +// waits leaves no stale copy behind: each site, written on its request's context and forgotten +// only on success, fails its row. +func (s *StoreSuite) TestEveryCachedWriteARequestGaveUpOnLeavesNoStaleCopy() { + now := time.Now().UTC() + for name, site := range map[string]func(){ + "AgentConfigs.Insert": func() { + name := "agent-" + newID() + other := AgentConfig{ID: newID(), CustomerID: "acme-app", Name: name, CreatedAt: now, UpdatedAt: now} + normalizeConfig(&other) + config := AgentConfig{CustomerID: "acme-app", Name: name, Mode: AgentModeText} + err := s.readWhileWriting(s.inserting(&other), func(ctx context.Context) error { + return s.store.AgentConfigs.Insert(ctx, &config) + }, func() { + _, err := s.store.AgentConfigs.GetByName(s.ctx, "acme-app", name) + s.Require().ErrorIs(err, ErrNoAgentConfig, "the name is not taken yet") + }, bun.Tx.Rollback) + s.Require().NoError(err) + found, err := s.store.AgentConfigs.GetByName(s.ctx, "acme-app", name) + s.Require().NoError(err) + s.Equal(config.ID, found.ID) + }, + "AgentConfigs.Update": func() { + config := s.boundConfig("acme-app") + was := config.Name + config.Name = "agent-" + newID() + err := s.readWhileWriting(s.lockingRow("agent_configs", config.ID), func(ctx context.Context) error { + return s.store.AgentConfigs.Update(ctx, &config) + }, func() { + _, err := s.store.AgentConfigs.GetByName(s.ctx, "acme-app", was) + s.Require().NoError(err, "the config is not renamed yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + _, err = s.store.AgentConfigs.GetByName(s.ctx, "acme-app", was) + s.ErrorIs(err, ErrNoAgentConfig) + }, + "Skills.Insert": func() { + config := s.boundConfig("acme-app") + other := Skill{ID: newID(), CustomerID: "acme-app", ConfigID: config.ID, Name: "refund", Files: map[string]string{}, CreatedAt: now, UpdatedAt: now} + skill := Skill{CustomerID: "acme-app", ConfigID: config.ID, Name: "refund", Description: "does refund", Instructions: "do refund"} + err := s.readWhileWriting(s.inserting(&other), func(ctx context.Context) error { + return s.store.Skills.Insert(ctx, &skill) + }, func() { + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Require().Empty(named, "the skill is not there yet") + }, bun.Tx.Rollback) + s.Require().NoError(err) + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Len(named, 1) + }, + "Skills.Update": func() { + config := s.boundConfig("acme-app") + skill := s.skill(config, "refund") + skill.Instructions = "ask first" + err := s.readWhileWriting(s.lockingRow("skills", skill.ID), func(ctx context.Context) error { + return s.store.Skills.Update(ctx, &skill) + }, func() { + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Require().Len(named, 1) + }, bun.Tx.Commit) + s.Require().NoError(err) + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Require().Len(named, 1) + s.Equal("ask first", named[0].Instructions) + }, + "Skills.Delete": func() { + config := s.boundConfig("acme-app") + skill := s.skill(config, "refund") + err := s.readWhileWriting(s.lockingRow("skills", skill.ID), func(ctx context.Context) error { + return s.store.Skills.Delete(ctx, "acme-app", skill.ID) + }, func() { + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Require().Len(named, 1, "the skill is not deleted yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + named, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, []string{"refund"}) + s.Require().NoError(err) + s.Empty(named) + }, + "Voices.Insert": func() { + name := "voice-" + newID() + other := Voice{ID: newID(), CustomerID: "acme", Name: name, CreatedAt: now, UpdatedAt: now} + voice := Voice{CustomerID: "acme", Name: name} + err := s.readWhileWriting(s.inserting(&other), func(ctx context.Context) error { + return s.store.Voices.Insert(ctx, &voice) + }, func() { + _, err := s.store.Voices.GetByName(s.ctx, "acme", name) + s.Require().ErrorIs(err, ErrNoVoice, "the name is not taken yet") + }, bun.Tx.Rollback) + s.Require().NoError(err) + found, err := s.store.Voices.GetByName(s.ctx, "acme", name) + s.Require().NoError(err) + s.Equal(voice.ID, found.ID) + }, + "Voices.Update": func() { + voice := Voice{CustomerID: "acme", Name: "voice-" + newID()} + s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) + was := voice.Name + voice.Name = "voice-" + newID() + err := s.readWhileWriting(s.lockingRow("voices", voice.ID), func(ctx context.Context) error { + return s.store.Voices.Update(ctx, &voice) + }, func() { + _, err := s.store.Voices.GetByName(s.ctx, "acme", was) + s.Require().NoError(err, "the voice is not renamed yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + _, err = s.store.Voices.GetByName(s.ctx, "acme", was) + s.ErrorIs(err, ErrNoVoice) + }, + "Voices.Delete": func() { + voice := Voice{CustomerID: "acme", Name: "voice-" + newID()} + s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) + err := s.readWhileWriting(s.lockingRow("voices", voice.ID), func(ctx context.Context) error { + return s.store.Voices.Delete(ctx, "acme", voice.ID) + }, func() { + _, err := s.store.Voices.Get(s.ctx, "acme", voice.ID) + s.Require().NoError(err, "the voice is not deleted yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + _, err = s.store.Voices.Get(s.ctx, "acme", voice.ID) + s.ErrorIs(err, ErrNoVoice) + }, + "VoiceBindings.Upsert": func() { + voice := Voice{CustomerID: "acme", Name: "voice-" + newID()} + s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) + binding := VoiceBinding{VoiceID: voice.ID, Provider: "elevenlabs", ExternalID: "old", State: VoiceReady} + s.Require().NoError(s.store.VoiceBindings.Upsert(s.ctx, &binding)) + binding.ExternalID = "new" + err := s.readWhileWriting(s.lockingRow("voice_bindings", binding.ID), func(ctx context.Context) error { + return s.store.VoiceBindings.Upsert(ctx, &binding) + }, func() { + external, err := s.store.VoiceBindings.GetReady(s.ctx, "acme", voice.ID, "elevenlabs") + s.Require().NoError(err) + s.Require().Equal("old", external) + }, bun.Tx.Commit) + s.Require().NoError(err) + external, err := s.store.VoiceBindings.GetReady(s.ctx, "acme", voice.ID, "elevenlabs") + s.Require().NoError(err) + s.Equal("new", external) + }, + "CustomModels.Insert": func() { + name := "model-" + newID() + other := CustomModel{ID: newID(), CustomerID: "app", Name: name, BaseURL: "https://models.example.com/v1", Model: "llama", + InputModalities: []string{}, CreatedAt: now, UpdatedAt: now} + model := CustomModel{CustomerID: "app", Name: name, BaseURL: "https://models.example.com/v1", Model: "llama"} + err := s.readWhileWriting(s.inserting(&other), func(ctx context.Context) error { + return s.store.CustomModels.Insert(ctx, &model) + }, func() { + _, err := s.store.CustomModels.GetByName(s.ctx, "app", name) + s.Require().ErrorIs(err, ErrNoCustomModel, "the name is not taken yet") + }, bun.Tx.Rollback) + s.Require().NoError(err) + found, err := s.store.CustomModels.GetByName(s.ctx, "app", name) + s.Require().NoError(err) + s.Equal(model.ID, found.ID) + }, + "CustomModels.Update": func() { + model := s.customModel("app", "model-"+newID()) + model.Model = "llama-2" + err := s.readWhileWriting(s.lockingRow("custom_models", model.ID), func(ctx context.Context) error { + return s.store.CustomModels.Update(ctx, &model) + }, func() { + found, err := s.store.CustomModels.GetByName(s.ctx, "app", model.Name) + s.Require().NoError(err) + s.Require().Equal("llama", found.Model) + }, bun.Tx.Commit) + s.Require().NoError(err) + found, err := s.store.CustomModels.GetByName(s.ctx, "app", model.Name) + s.Require().NoError(err) + s.Equal("llama-2", found.Model) + }, + "CustomModels.Delete": func() { + model := s.customModel("app", "model-"+newID()) + err := s.readWhileWriting(s.lockingRow("custom_models", model.ID), func(ctx context.Context) error { + return s.store.CustomModels.Delete(ctx, "app", model.ID) + }, func() { + _, err := s.store.CustomModels.GetByName(s.ctx, "app", model.Name) + s.Require().NoError(err, "the model is not deleted yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + _, err = s.store.CustomModels.GetByName(s.ctx, "app", model.Name) + s.ErrorIs(err, ErrNoCustomModel) + }, + "ProviderKeys.Upsert": func() { + customer := "app-" + newID() + key := s.providerKey(customer, "openai", "global", "one") + _, _, err := s.store.ProviderKeys.Upsert(s.ctx, &key) + s.Require().NoError(err) + key = s.providerKey(customer, "openai", "global", "two") + err = s.readWhileWriting(s.lockingWhere("provider_keys", "customer_id = ?", customer), func(ctx context.Context) error { + _, _, err := s.store.ProviderKeys.Upsert(ctx, &key) + return err + }, func() { + all, err := s.store.ProviderKeys.SelectAll(s.ctx, customer) + s.Require().NoError(err) + s.Require().Len(all, 1) + s.Require().Equal([]byte("one"), all[0].APIKeySealed) + }, bun.Tx.Commit) + s.Require().NoError(err) + all, err := s.store.ProviderKeys.SelectAll(s.ctx, customer) + s.Require().NoError(err) + s.Require().Len(all, 1) + s.Equal([]byte("two"), all[0].APIKeySealed) + }, + "ProviderKeys.Delete": func() { + customer := "app-" + newID() + key := s.providerKey(customer, "openai", "global", "one") + _, _, err := s.store.ProviderKeys.Upsert(s.ctx, &key) + s.Require().NoError(err) + err = s.readWhileWriting(s.lockingWhere("provider_keys", "customer_id = ?", customer), func(ctx context.Context) error { + _, err := s.store.ProviderKeys.Delete(ctx, customer, "openai", "global") + return err + }, func() { + all, err := s.store.ProviderKeys.SelectAll(s.ctx, customer) + s.Require().NoError(err) + s.Require().Len(all, 1, "the key is not deleted yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + all, err := s.store.ProviderKeys.SelectAll(s.ctx, customer) + s.Require().NoError(err) + s.Empty(all) + }, + "Policies.Upsert": func() { + app := "app-" + newID() + yes, no := true, false + s.Require().NoError(s.store.Policies.Upsert(s.ctx, &Policy{Scope: ScopeApp, ScopeID: app, Document: PolicyDocument{PromptInjection: &yes}})) + err := s.readWhileWriting(s.lockingWhere("policies", "scope = ? AND scope_id = ?", ScopeApp, app), func(ctx context.Context) error { + return s.store.Policies.Upsert(ctx, &Policy{Scope: ScopeApp, ScopeID: app, Document: PolicyDocument{PromptInjection: &no}}) + }, func() { + document, err := s.store.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Require().Equal(&yes, document.PromptInjection) + }, bun.Tx.Commit) + s.Require().NoError(err) + document, err := s.store.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Equal(&no, document.PromptInjection) + }, + "Policies.Delete": func() { + app := "app-" + newID() + yes := true + s.Require().NoError(s.store.Policies.Upsert(s.ctx, &Policy{Scope: ScopeApp, ScopeID: app, Document: PolicyDocument{PromptInjection: &yes}})) + err := s.readWhileWriting(s.lockingWhere("policies", "scope = ? AND scope_id = ?", ScopeApp, app), func(ctx context.Context) error { + return s.store.Policies.Delete(ctx, ScopeApp, app) + }, func() { + document, err := s.store.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection, "the policy is not deleted yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + document, err := s.store.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Nil(document.PromptInjection) + }, + "APIKeys.Revoke": func() { + app := s.app() + key := s.key(app.ID, "vak_live_dddddddddddddddd00000000", nil) + err := s.readWhileWriting(s.lockingRow("api_keys", key.ID), func(ctx context.Context) error { + _, err := s.store.APIKeys.Revoke(ctx, app.ID, key.ID, "thierry") + return err + }, func() { + _, err := s.store.APIKeys.GetLive(s.ctx, key.ID) + s.Require().NoError(err, "the key is not revoked yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + _, err = s.store.APIKeys.GetLive(s.ctx, key.ID) + s.ErrorIs(err, ErrNoAPIKey) + }, + } { + s.Run(name, site) + } +} diff --git a/acceleration/internal/store/router_config.go b/acceleration/internal/store/router_config.go index 1ea183036a..e72d053683 100644 --- a/acceleration/internal/store/router_config.go +++ b/acceleration/internal/store/router_config.go @@ -70,13 +70,16 @@ func (r *RouterConfigs) Insert(ctx context.Context, config *RouterConfig) error config.UpdatedAt = now config.DeletedAt = nil - if _, err := r.store.global.NewInsert().Model(config).Exec(ctx); err != nil { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(config).Exec(ctx) + return err + }, func() []string { return []string{routerConfigNameKey(config.CustomerID, config.Name)} }) + if err != nil { if constraint(err) == "router_configs_name_idx" { return stack.Wrap(ErrNameTaken) } return stack.Wrap(fmt.Errorf("store: create router config: %w", err)) } - r.store.forget(ctx, routerConfigNameKey(config.CustomerID, config.Name)) return nil } @@ -100,14 +103,26 @@ func (r *RouterConfigs) Update(ctx context.Context, config *RouterConfig) error Where("deleted_at IS NULL"). For("UPDATE") var wasName string - err := r.store.global.NewUpdate().Model(config). - With("was", was). - TableExpr("was"). - Column("name", "stt", "tts", "llm", "sts", "search", "updated_at"). - Where("rc.id = ?", config.ID). - Where("rc.customer_id = ?", config.CustomerID). - Returning("was.name"). - Scan(ctx, &wasName) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model(config). + With("was", was). + TableExpr("was"). + Column("name", "stt", "tts", "llm", "sts", "search", "updated_at"). + Where("rc.id = ?", config.ID). + Where("rc.customer_id = ?", config.CustomerID). + Returning("was.name"). + Scan(ctx, &wasName) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if wasName == "" { + return nil + } + return []string{ + routerConfigKey(config.CustomerID, config.ID), + routerConfigNameKey(config.CustomerID, config.Name), + routerConfigNameKey(config.CustomerID, wasName), + } + }) switch { case constraint(err) == "router_configs_name_idx": return stack.Wrap(ErrNameTaken) @@ -116,10 +131,6 @@ func (r *RouterConfigs) Update(ctx context.Context, config *RouterConfig) error case err != nil: return stack.Wrap(fmt.Errorf("store: update router config: %w", err)) } - r.store.forget(ctx, - routerConfigKey(config.CustomerID, config.ID), - routerConfigNameKey(config.CustomerID, config.Name), - routerConfigNameKey(config.CustomerID, wasName)) return nil } @@ -131,20 +142,27 @@ func (r *RouterConfigs) Delete(ctx context.Context, customerID, id string) error } var name string - err := r.store.global.NewUpdate().Model((*RouterConfig)(nil)). - Set("deleted_at = ?", time.Now().UTC()). - Where("id = ?", id). - Where("customer_id = ?", customerID). - Where("deleted_at IS NULL"). - Returning("name"). - Scan(ctx, &name) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model((*RouterConfig)(nil)). + Set("deleted_at = ?", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + Returning("name"). + Scan(ctx, &name) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if name == "" { + return nil + } + return []string{routerConfigKey(customerID, id), routerConfigNameKey(customerID, name)} + }) if errors.Is(err, sql.ErrNoRows) { return unknownRouterConfig(id) } if err != nil { return stack.Wrap(fmt.Errorf("store: delete router config: %w", err)) } - r.store.forget(ctx, routerConfigKey(customerID, id), routerConfigNameKey(customerID, name)) return nil } diff --git a/acceleration/internal/store/router_config_test.go b/acceleration/internal/store/router_config_test.go index 0884722377..b4d3ab26b0 100644 --- a/acceleration/internal/store/router_config_test.go +++ b/acceleration/internal/store/router_config_test.go @@ -2,7 +2,12 @@ package store -import "time" +import ( + "context" + "time" + + "github.com/uptrace/bun" +) func (s *StoreSuite) routerConfig(customerID, name string) RouterConfig { config := RouterConfig{CustomerID: customerID, Name: name} @@ -72,13 +77,59 @@ func (s *StoreSuite) TestARenamedRouterConfigIsNoLongerFoundUnderItsOldName() { s.ErrorIs(err, ErrNoRouterConfig) } +func (s *StoreSuite) TestARenameARequestGaveUpOnIsNotCachedAgainByAReadBeforeItCommits() { + config := s.routerConfig("acme-app", "fast") + _, err := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().NoError(err) + + renamed := config + renamed.Name = "cheap" + err = s.readWhileWriting(s.lockingRow("router_configs", config.ID), func(ctx context.Context) error { + return s.store.RouterConfigs.Update(ctx, &renamed) + }, func() { + _, err := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().NoError(err, "the config is not renamed yet") + _, err = s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(err) + }, bun.Tx.Commit) + + _, getErr := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.ErrorIs(getErr, ErrNoRouterConfig) + found, getErr := s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) + s.Require().NoError(getErr) + s.Equal("cheap", found.Name) + s.NoError(err, "the rename outlives the request that asked for it") +} + +func (s *StoreSuite) TestAnInsertARequestGaveUpOnIsNotCachedAsAbsentByAReadBeforeItCommits() { + _, err := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().ErrorIs(err, ErrNoRouterConfig) + other := RouterConfig{ID: newID(), CustomerID: "acme-app", Name: "fast"} + + config := RouterConfig{CustomerID: "acme-app", Name: "fast"} + err = s.readWhileWriting(func(holder bun.Tx) { + _, err := holder.NewInsert().Model(&other).Exec(s.ctx) + s.Require().NoError(err) + }, func(ctx context.Context) error { + return s.store.RouterConfigs.Insert(ctx, &config) + }, func() { + _, err := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().ErrorIs(err, ErrNoRouterConfig, "the name is not taken yet") + }, bun.Tx.Rollback) + + found, getErr := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().NoError(getErr, "the insert landed once the other let the name go") + s.Equal(config.ID, found.ID) + s.NoError(err, "the insert outlives the request that asked for it") +} + func (s *StoreSuite) TestRouterConfigQueryBudgets() { for range 20 { s.routerConfig("acme-app", "r"+newID()) } config := RouterConfig{CustomerID: "acme-app", Name: "fast"} - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Insert(s.ctx, &config)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Insert(s.ctx, &config)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") s.Equal(1, s.countQueries(func() { listed, err := s.store.RouterConfigs.Select(s.ctx, "acme-app") s.Require().NoError(err) @@ -89,7 +140,7 @@ func (s *StoreSuite) TestRouterConfigQueryBudgets() { s.Require().NoError(err) })) config.Name = "cheap" - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Update(s.ctx, &config)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Update(s.ctx, &config)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") if s.store.cache != nil { for range 2 { _, err := s.store.RouterConfigs.Get(s.ctx, "acme-app", config.ID) @@ -106,5 +157,5 @@ func (s *StoreSuite) TestRouterConfigQueryBudgets() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.RouterConfigs.Delete(s.ctx, "acme-app", config.ID)) })) return } - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Delete(s.ctx, "acme-app", config.ID)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.RouterConfigs.Delete(s.ctx, "acme-app", config.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } diff --git a/acceleration/internal/store/shards.go b/acceleration/internal/store/shards.go index 10a177cc0b..613284fdd3 100644 --- a/acceleration/internal/store/shards.go +++ b/acceleration/internal/store/shards.go @@ -10,6 +10,7 @@ import ( "maps" "slices" "sync" + "time" "github.com/redis/rueidis/rueidishook" "github.com/uptrace/bun" @@ -43,6 +44,8 @@ type Options struct { ShardRedis Redis // redisHook sees every Redis command, for the tests counting round trips. redisHook rueidishook.Hook + // writeTimeout bounds a write of a cached row. Zero is writeTimeout; a test shortens it. + writeTimeout time.Duration } // OpenShards connects to the shared database, this shard's, and every other shard's. @@ -51,7 +54,9 @@ func OpenShards(options Options) (*Store, error) { return nil, errors.New("store: dsn is required") } db := connect(options.DSN, maxConns) - s := &Store{global: db, shard: db, globalDSN: options.DSN, shardDSN: options.DSN} + s := &Store{global: db, shard: db, globalDSN: options.DSN, shardDSN: options.DSN, + retries: make(chan struct{}, forgetSlots), writeTimeout: cmp.Or(options.writeTimeout, writeTimeout)} + s.closing, s.stop = context.WithCancel(context.Background()) if options.ShardDSN != "" && options.ShardDSN != options.DSN { s.shard = connect(options.ShardDSN, maxConns) s.shardDSN = options.ShardDSN diff --git a/acceleration/internal/store/skill.go b/acceleration/internal/store/skill.go index 8263353f7f..16aa3e57e5 100644 --- a/acceleration/internal/store/skill.go +++ b/acceleration/internal/store/skill.go @@ -83,13 +83,16 @@ func (r *Skills) Insert(ctx context.Context, skill *Skill) error { skill.Files = map[string]string{} } - if _, err := r.store.global.NewInsert().Model(skill).Exec(ctx); err != nil { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(skill).Exec(ctx) + return err + }, func() []string { return []string{skillsKey(skill.CustomerID, skill.ConfigID)} }) + if err != nil { if constraint(err) == "skills_name_idx" { return stack.Wrap(ErrNameTaken) } return stack.Wrap(fmt.Errorf("store: create skill: %w", err)) } - r.store.forget(ctx, skillsKey(skill.CustomerID, skill.ConfigID)) return nil } @@ -115,14 +118,25 @@ func (r *Skills) Update(ctx context.Context, skill *Skill) error { Where("deleted_at IS NULL"). For("UPDATE") var wasConfig string - err := r.store.global.NewUpdate().Model(skill). - With("was", was). - TableExpr("was"). - Column("config_id", "name", "description", "instructions", "files", "capture_video", "deadline_ms", "updated_at"). - Where("sk.id = ?", skill.ID). - Where("sk.customer_id = ?", skill.CustomerID). - Returning("was.config_id"). - Scan(ctx, &wasConfig) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model(skill). + With("was", was). + TableExpr("was"). + Column("config_id", "name", "description", "instructions", "files", "capture_video", "deadline_ms", "updated_at"). + Where("sk.id = ?", skill.ID). + Where("sk.customer_id = ?", skill.CustomerID). + Returning("was.config_id"). + Scan(ctx, &wasConfig) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if wasConfig == "" { + return nil + } + return []string{ + skillsKey(skill.CustomerID, skill.ConfigID), + skillsKey(skill.CustomerID, wasConfig), + } + }) switch { case constraint(err) == "skills_name_idx": return stack.Wrap(ErrNameTaken) @@ -131,7 +145,6 @@ func (r *Skills) Update(ctx context.Context, skill *Skill) error { case err != nil: return stack.Wrap(fmt.Errorf("store: update skill: %w", err)) } - r.store.forget(ctx, skillsKey(skill.CustomerID, skill.ConfigID), skillsKey(skill.CustomerID, wasConfig)) return nil } @@ -142,20 +155,27 @@ func (r *Skills) Delete(ctx context.Context, customerID, id string) error { } var configID string - err := r.store.global.NewUpdate().Model((*Skill)(nil)). - Set("deleted_at = ?", time.Now().UTC()). - Where("id = ?", id). - Where("customer_id = ?", customerID). - Where("deleted_at IS NULL"). - Returning("config_id"). - Scan(ctx, &configID) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model((*Skill)(nil)). + Set("deleted_at = ?", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + Returning("config_id"). + Scan(ctx, &configID) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if configID == "" { + return nil + } + return []string{skillsKey(customerID, configID)} + }) if errors.Is(err, sql.ErrNoRows) { return unknownSkill(id) } if err != nil { return stack.Wrap(fmt.Errorf("store: delete skill: %w", err)) } - r.store.forget(ctx, skillsKey(customerID, configID)) return nil } diff --git a/acceleration/internal/store/skill_test.go b/acceleration/internal/store/skill_test.go index f15cb168ae..af388c1b0b 100644 --- a/acceleration/internal/store/skill_test.go +++ b/acceleration/internal/store/skill_test.go @@ -91,7 +91,7 @@ func (s *StoreSuite) TestSkillQueryBudgets() { } skill := Skill{CustomerID: "acme-app", ConfigID: config.ID, Name: "refund"} - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Skills.Insert(s.ctx, &skill)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Skills.Insert(s.ctx, &skill)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") s.Equal(1, s.countQueries(func() { listed, err := s.store.Skills.Select(s.ctx, "acme-app", SkillFilter{ConfigID: config.ID}) s.Require().NoError(err) @@ -107,7 +107,7 @@ func (s *StoreSuite) TestSkillQueryBudgets() { s.Require().NoError(err) })) skill.Instructions = "ask first" - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Skills.Update(s.ctx, &skill)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Skills.Update(s.ctx, &skill)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") if s.store.cache != nil { for range 2 { _, err := s.store.Skills.GetByNames(s.ctx, "acme-app", config.ID, names) @@ -123,5 +123,5 @@ func (s *StoreSuite) TestSkillQueryBudgets() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.Skills.Delete(s.ctx, "acme-app", skill.ID)) })) return } - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Skills.Delete(s.ctx, "acme-app", skill.ID)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Skills.Delete(s.ctx, "acme-app", skill.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") } diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 8e32dc8efb..b81bc669dd 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -17,6 +17,7 @@ import ( "maps" "slices" "strings" + "sync" "sync/atomic" "time" @@ -62,6 +63,59 @@ type Store struct { shapes tableShapes // pins says how Stream app pins cross between deployments, once the router has said. pins pinsHolder + // retries holds a slot for each deletion forgetLater is trying again. stop ends them + // when the store closes, and retrying is what Close waits on. retryMu guards closed, so no + // retry starts once Close is waiting. + retries chan struct{} + closing context.Context + stop context.CancelFunc + retrying sync.WaitGroup + retryMu sync.Mutex + closed bool + // writeTimeout bounds detachedWrite. + writeTimeout time.Duration +} + +// writeTimeout is how long the statements of a write of a cached row may take when Options +// does not say. Its COMMIT is bounded by the DSN's read_timeout instead (detachedWrite). +const writeTimeout = 10 * time.Second + +// detachedWrite runs write in a transaction of the shared database that outlives ctx's +// cancellation, its statements within the store's write timeout. pgdriver sends the COMMIT on +// context.Background(), so only the DSN's read_timeout bounds that, and a write can take the +// write timeout plus the read timeout. It then drops from the cache the keys that +// keys names, whatever the commit answered. A request that gives up therefore leaves no +// statement for Postgres to commit after a read has cached the old row again: the transaction +// is rolled back when its connection goes, since Postgres commits nothing without the COMMIT. +// keys is read once write has run, and names nothing when write found no row. +// +// A COMMIT whose answer was lost may land after the deletion, so its keys are dropped again +// shortly after it (forgetLater). +func (s *Store) detachedWrite(ctx context.Context, write func(context.Context, bun.Tx) error, keys func() []string) error { + _, err := s.detachedWriteTold(ctx, write, keys) + return err +} + +// detachedWriteTold is detachedWrite, and says whether every replica was told, the keys' +// deletion having landed in Redis. +func (s *Store) detachedWriteTold(ctx context.Context, write func(context.Context, bun.Tx) error, keys func() []string) (told bool, err error) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), s.writeTimeout) + defer cancel() + var committing bool + err = s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + if err := write(ctx, tx); err != nil { + return err + } + committing = true + return nil + }) + names := keys() + told = s.forget(ctx, names...) + var answered pgdriver.Error + if err != nil && committing && !errors.As(err, &answered) && s.cache != nil && len(names) > 0 { + s.forgetLater(names, err) + } + return told, err } // Open connects to Postgres using a pgdriver DSN, for example @@ -102,6 +156,11 @@ func (s *Store) Server(ctx context.Context) (database, address string, err error // Close releases the connection pools. func (s *Store) Close() error { + s.retryMu.Lock() + s.closed = true + s.retryMu.Unlock() + s.stop() + s.retrying.Wait() s.closeRedis() return errors.Join(s.closeShards(), s.global.Close()) } diff --git a/acceleration/internal/store/voice.go b/acceleration/internal/store/voice.go index f8d7a0ef7e..a1259b556e 100644 --- a/acceleration/internal/store/voice.go +++ b/acceleration/internal/store/voice.go @@ -63,13 +63,16 @@ func (r *Voices) Insert(ctx context.Context, voice *Voice) error { voice.UpdatedAt = now voice.DeletedAt = nil - if _, err := r.store.global.NewInsert().Model(voice).Exec(ctx); err != nil { + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(voice).Exec(ctx) + return err + }, func() []string { return []string{voiceNameKey(voice.CustomerID, voice.Name)} }) + if err != nil { if constraint(err) == "voices_name_idx" { return stack.Wrap(ErrNameTaken) } return stack.Wrap(fmt.Errorf("store: create voice: %w", err)) } - r.store.forget(ctx, voiceNameKey(voice.CustomerID, voice.Name)) return nil } @@ -93,14 +96,26 @@ func (r *Voices) Update(ctx context.Context, voice *Voice) error { Where("deleted_at IS NULL"). For("UPDATE") var wasName string - err := r.store.global.NewUpdate().Model(voice). - With("was", was). - TableExpr("was"). - Column("name", "description", "updated_at"). - Where("v.id = ?", voice.ID). - Where("v.customer_id = ?", voice.CustomerID). - Returning("was.name"). - Scan(ctx, &wasName) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model(voice). + With("was", was). + TableExpr("was"). + Column("name", "description", "updated_at"). + Where("v.id = ?", voice.ID). + Where("v.customer_id = ?", voice.CustomerID). + Returning("was.name"). + Scan(ctx, &wasName) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if wasName == "" { + return nil + } + return []string{ + voiceKey(voice.CustomerID, voice.ID), + voiceNameKey(voice.CustomerID, voice.Name), + voiceNameKey(voice.CustomerID, wasName), + } + }) switch { case constraint(err) == "voices_name_idx": return stack.Wrap(ErrNameTaken) @@ -109,10 +124,6 @@ func (r *Voices) Update(ctx context.Context, voice *Voice) error { case err != nil: return stack.Wrap(fmt.Errorf("store: update voice: %w", err)) } - r.store.forget(ctx, - voiceKey(voice.CustomerID, voice.ID), - voiceNameKey(voice.CustomerID, voice.Name), - voiceNameKey(voice.CustomerID, wasName)) return nil } @@ -125,24 +136,31 @@ func (r *Voices) Delete(ctx context.Context, customerID, id string) error { var name string var providers []string - err := r.store.global.NewUpdate().Model((*Voice)(nil)). - Set("deleted_at = ?", time.Now().UTC()). - Where("id = ?", id). - Where("customer_id = ?", customerID). - Where("deleted_at IS NULL"). - Returning("name, ARRAY(SELECT vb.provider FROM voice_bindings AS vb WHERE vb.voice_id = v.id)"). - Scan(ctx, &name, pgdialect.Array(&providers)) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewUpdate().Model((*Voice)(nil)). + Set("deleted_at = ?", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + Returning("name, ARRAY(SELECT vb.provider FROM voice_bindings AS vb WHERE vb.voice_id = v.id)"). + Scan(ctx, &name, pgdialect.Array(&providers)) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if name == "" { + return nil + } + keys := []string{voiceKey(customerID, id), voiceNameKey(customerID, name)} + for _, provider := range providers { + keys = append(keys, voiceBindingKey(customerID, id, provider)) + } + return keys + }) if errors.Is(err, sql.ErrNoRows) { return unknownVoice(id) } if err != nil { return stack.Wrap(fmt.Errorf("store: delete voice: %w", err)) } - keys := []string{voiceKey(customerID, id), voiceNameKey(customerID, name)} - for _, provider := range providers { - keys = append(keys, voiceBindingKey(customerID, id, provider)) - } - r.store.forget(ctx, keys...) return nil } diff --git a/acceleration/internal/store/voice_binding.go b/acceleration/internal/store/voice_binding.go index eaa9f6c73d..3dbcd6305f 100644 --- a/acceleration/internal/store/voice_binding.go +++ b/acceleration/internal/store/voice_binding.go @@ -82,19 +82,26 @@ func (r *VoiceBindings) Upsert(ctx context.Context, binding *VoiceBinding) error // The row has no customer of its own, and the key it is cached under names the voice's. var customerID string - err := r.store.global.NewInsert().Model(binding). - On("CONFLICT (voice_id, provider) DO UPDATE"). - Set("external_id = EXCLUDED.external_id"). - Set("state = EXCLUDED.state"). - Set("error = EXCLUDED.error"). - Set("updated_at = EXCLUDED.updated_at"). - Set("synced_at = COALESCE(EXCLUDED.synced_at, vb.synced_at)"). - Returning("(SELECT v.customer_id FROM voices AS v WHERE v.id = vb.voice_id)"). - Scan(ctx, &customerID) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return tx.NewInsert().Model(binding). + On("CONFLICT (voice_id, provider) DO UPDATE"). + Set("external_id = EXCLUDED.external_id"). + Set("state = EXCLUDED.state"). + Set("error = EXCLUDED.error"). + Set("updated_at = EXCLUDED.updated_at"). + Set("synced_at = COALESCE(EXCLUDED.synced_at, vb.synced_at)"). + Returning("(SELECT v.customer_id FROM voices AS v WHERE v.id = vb.voice_id)"). + Scan(ctx, &customerID) + }, func() []string { + // Named once the write answered: a commit that fails can still have landed. + if customerID == "" { + return nil + } + return []string{voiceBindingKey(customerID, binding.VoiceID, binding.Provider)} + }) if err != nil { return stack.Wrap(fmt.Errorf("store: save voice binding: %w", err)) } - r.store.forget(ctx, voiceBindingKey(customerID, binding.VoiceID, binding.Provider)) return nil } diff --git a/acceleration/internal/store/voice_binding_test.go b/acceleration/internal/store/voice_binding_test.go index 2e3bfe489c..03ab60043c 100644 --- a/acceleration/internal/store/voice_binding_test.go +++ b/acceleration/internal/store/voice_binding_test.go @@ -145,7 +145,7 @@ func (s *StoreSuite) TestVoiceBindingQueryBudgets() { } binding := VoiceBinding{VoiceID: voice.ID, Provider: "elevenlabs", ExternalID: "el-1", State: VoiceReady} - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.VoiceBindings.Upsert(s.ctx, &binding)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.VoiceBindings.Upsert(s.ctx, &binding)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") s.Equal(1, s.countQueries(func() { bindings, err := s.store.VoiceBindings.Select(s.ctx, voice.ID) s.Require().NoError(err) diff --git a/acceleration/internal/store/voice_test.go b/acceleration/internal/store/voice_test.go index 068c27b00e..d13f6d230d 100644 --- a/acceleration/internal/store/voice_test.go +++ b/acceleration/internal/store/voice_test.go @@ -98,7 +98,7 @@ func (s *StoreSuite) TestVoiceQueryBudgets() { } voice := Voice{CustomerID: "acme", Name: "founder"} - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") s.Equal(1, s.countQueries(func() { listed, err := s.store.Voices.Select(s.ctx, "acme") s.Require().NoError(err) @@ -109,7 +109,7 @@ func (s *StoreSuite) TestVoiceQueryBudgets() { s.Require().NoError(err) })) voice.Description = "the one from the ad" - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Voices.Update(s.ctx, &voice)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Voices.Update(s.ctx, &voice)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") for _, provider := range []string{"elevenlabs", "cartesia"} { binding := VoiceBinding{VoiceID: voice.ID, Provider: provider, ExternalID: "x", State: VoiceReady} s.Require().NoError(s.store.VoiceBindings.Upsert(s.ctx, &binding)) @@ -125,11 +125,11 @@ func (s *StoreSuite) TestVoiceQueryBudgets() { s.Require().NoError(err) })) })) - s.Equal(1, s.countQueries(func() { + s.Equal(3, s.countQueries(func() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.Voices.Delete(s.ctx, "acme", voice.ID)) }), "forgetting the voice, its name and every provider's binding is one round trip") - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") return } - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Voices.Delete(s.ctx, "acme", voice.ID)) })) + s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.Voices.Delete(s.ctx, "acme", voice.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") }