diff --git a/acceleration/README.md b/acceleration/README.md index d8f4e1b8ab..12434226d4 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2392,7 +2392,9 @@ window the replacement already has taking the forgotten one's spend), and again database their own policy and user-level limits, deleted, so the app's defaults apply, and the id on their resets, grants and campaigns. Usage and cost stay under the app. It writes one `end_user` audit row naming the replacement and the actor, never the id, and the service one -`forget_user` row per organization. `--dry-run` prints the counts and changes nothing. Every +`forget_user` row per organization. `--dry-run` prints the counts and changes nothing. Once the +last step, the shared database's, has started, it completes even if the command is interrupted, +and the command drops the user's cached policy from every router before it exits. Every step only touches what still names the id, so it is safe to repeat: to finish a run that stopped, pass the replacement it printed as `--replacement`, and the rest is rewritten under that one replacement, with the run's own audit row. Sessions, conversation history and diff --git a/acceleration/cmd/router/forget_close_integration_test.go b/acceleration/cmd/router/forget_close_integration_test.go new file mode 100644 index 0000000000..4a6d06ebb4 --- /dev/null +++ b/acceleration/cmd/router/forget_close_integration_test.go @@ -0,0 +1,165 @@ +//go:build integration + +package main + +import ( + "bytes" + "encoding/binary" + "io" + "net" + "net/url" + "sync" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// commitHolder stands in front of a Postgres and holds, on the first connection that deletes +// a policy, the COMMIT after that delete until let. gaveUp is closed once the client drops that +// connection, as pgdriver does when its read times out. +type commitHolder struct { + listener net.Listener + target string + release chan struct{} + gaveUp chan struct{} + once sync.Once + letOnce sync.Once +} + +// holdingCommit puts a commitHolder in front of the shared database and answers the DSN that +// reaches it, whose reads give up after a second. +func (s *ForgetUserSuite) holdingCommit() (*commitHolder, string) { + target, err := url.Parse(s.settings.Postgres.DSN) + s.Require().NoError(err) + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + holder := &commitHolder{listener: listener, target: target.Host, release: make(chan struct{}), gaveUp: make(chan struct{})} + s.T().Cleanup(func() { + _ = listener.Close() + holder.let() + }) + go holder.serve() + target.Host = listener.Addr().String() + query := target.Query() + query.Set("read_timeout", "1s") + target.RawQuery = query.Encode() + return holder, target.String() +} + +func (h *commitHolder) let() { h.letOnce.Do(func() { close(h.release) }) } + +func (h *commitHolder) serve() { + for { + conn, err := h.listener.Accept() + if err != nil { + return + } + upstream, err := net.Dial("tcp", h.target) + if err != nil { + _ = conn.Close() + continue + } + go func() { + defer func() { _ = upstream.Close() }() + h.toServer(conn, upstream) + }() + go func() { + defer func() { _ = conn.Close() }() + _, _ = io.Copy(conn, upstream) + }() + } +} + +// toServer forwards a client's startup message and then its typed messages, holding the +// COMMIT that follows a delete of policies on the first connection to send one. +func (h *commitHolder) toServer(conn, upstream net.Conn) { + 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 + } + var deleting bool + 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(`DELETE FROM "policies"`)) { + deleting = true + } + if header[0] == 'Q' && deleting && bytes.HasPrefix(body, []byte("COMMIT")) { + held := false + h.once.Do(func() { held = true }) + if held { + // The client gives up on the answer and drops the connection meanwhile. + go func() { + _, _ = io.Copy(io.Discard, conn) + close(h.gaveUp) + }() + <-h.release + } + } + if _, err := upstream.Write(append(header, body...)); err != nil { + return + } + } +} + +// A run whose COMMIT lands after it gave up on its answer still drops, before it exits, the +// policy a router cached meanwhile: closing the store lets the deletions held for that COMMIT +// run. +func (s *ForgetUserSuite) TestARunWhoseCommitLandsAfterItGaveUpStillDropsThePolicyARouterCached() { + 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) + scope := store.UserScopeID(s.app, person) + cached, err := router.Policies.Get(s.ctx, store.ScopeUser, scope) + s.Require().NoError(err) + s.Require().NotNil(cached.Quota) + holder, dsn := s.holdingCommit() + s.settings.Postgres.DSN = dsn + + ran := make(chan error, 1) + go func() { + ran <- s.runForget([]string{"forget-user", "--app", s.app, "--user", person, "--actor", "staff@example.com", "--settle", "0s"}, &bytes.Buffer{}) + }() + select { + case <-holder.gaveUp: + case <-time.After(10 * time.Second): + s.FailNow("the run never gave up on the held COMMIT") + } + // The run drops the policy as it gives up; a router reading it meanwhile caches it again, + // since the delete has not committed. + for deadline := time.Now().Add(30 * time.Millisecond); time.Now().Before(deadline); { + read, err := router.Policies.Get(s.ctx, store.ScopeUser, scope) + s.Require().NoError(err) + s.Require().NotNil(read.Quota, "the delete is not committed yet") + } + holder.let() + select { + case err := <-ran: + s.Error(err, "the run never had the COMMIT's answer") + case <-time.After(10 * time.Second): + s.FailNow("the run never ended") + } + + s.Eventually(func() bool { + read, err := router.Policies.Get(s.ctx, store.ScopeUser, scope) + s.Require().NoError(err) + return read.Quota == nil + }, 3*time.Second, 10*time.Millisecond, "the router still answers the policy the user had") +} diff --git a/acceleration/internal/policy/join_test.go b/acceleration/internal/policy/join_test.go new file mode 100644 index 0000000000..b8d3fbfd5e --- /dev/null +++ b/acceleration/internal/policy/join_test.go @@ -0,0 +1,183 @@ +//go:build integration + +package policy + +import ( + "fmt" + "time" + + "github.com/google/uuid" + "github.com/uptrace/bun" + + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// heldMembership begins a transaction holding an app's membership row, which a write of it +// waits behind, and answers it with its backend's pid. +func (s *PolicySuite) heldMembership(appID string) (bun.Tx, int) { + s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &store.AppOrganization{AppID: appID, OrganizationID: "org-before"})) + holder, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = holder.Rollback() }) + var pid int + s.Require().NoError(holder.QueryRowContext(s.ctx, "SELECT pg_backend_pid()").Scan(&pid)) + _, err = holder.ExecContext(s.ctx, "SELECT 1 FROM app_organizations WHERE app_id = ? FOR UPDATE", appID) + s.Require().NoError(err) + return holder, pid +} + +// waitingBehind is how many statements wait for the holder with this pid. +func (s *PolicySuite) waitingBehind(holder int) int { + var waiting int + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT count(*) FROM pg_stat_activity WHERE ? = ANY(pg_blocking_pids(pid))", holder).Scan(&waiting)) + return waiting +} + +// organizationOf is the organization the app's row names now, read past the cache, or empty +// with no row. +func (s *PolicySuite) organizationOf(appID string) string { + var organization string + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT coalesce((SELECT organization_id FROM app_organizations WHERE app_id = ?), '')", appID).Scan(&organization)) + return organization +} + +func (s *PolicySuite) TestAnAppNamingOrganizationsInTurnHasOneMembershipWrittenAtATimeAndTheLastWins() { + enforcer := s.newEnforcer(s.store, nil) + app := "app-" + uuid.NewString() + holder, pid := s.heldMembership(app) + + for i := range 200 { + enforcer.Join(s.ctx, app, fmt.Sprintf("org-%d", i%2), openTier) + } + enforcer.Join(s.ctx, app, "org-last", openTier) + s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond, + "the first write waits behind the holder") + s.Never(func() bool { return s.waitingBehind(pid) > 1 }, 300*time.Millisecond, 10*time.Millisecond, + "one write of the app's membership runs at a time") + + s.Require().NoError(holder.Commit()) + s.Eventually(func() bool { return s.organizationOf(app) == "org-last" }, 5*time.Second, 10*time.Millisecond, + "the organization named last is the one recorded") + closed := make(chan struct{}) + go func() { + enforcer.Close() + close(closed) + }() + select { + case <-closed: + case <-time.After(joinTimeout / 2): + s.FailNow("the app's writes go on once the last organization named landed") + } +} + +func (s *PolicySuite) TestAnAppJoiningAnotherOrganizationLaterIsRecordedUnderIt() { + enforcer := s.newEnforcer(s.store, nil) + app := "app-" + uuid.NewString() + enforcer.Join(s.ctx, app, "org-first", openTier) + s.Require().Eventually(func() bool { return s.organizationOf(app) == "org-first" }, 5*time.Second, 10*time.Millisecond, + "the first organization is recorded") + + enforcer.Join(s.ctx, app, "org-second", openTier) + + s.Eventually(func() bool { return s.organizationOf(app) == "org-second" }, 5*time.Second, 10*time.Millisecond, + "an organization named after the first write ended is written too") +} + +func (s *PolicySuite) TestAnOrganizationNamedBehindAWriteIsNotWrittenOnceCloseBegan() { + enforcer, err := New(s.store, quick, nil) + s.Require().NoError(err) + app := "app-" + uuid.NewString() + holder, pid := s.heldMembership(app) + enforcer.Join(s.ctx, app, "org-first", openTier) + s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond, + "the first write waits behind the holder") + enforcer.Join(s.ctx, app, "org-second", openTier) + + closed := make(chan struct{}) + go func() { + enforcer.Close() + close(closed) + }() + s.Require().Eventually(func() bool { + enforcer.joinsMu.Lock() + defer enforcer.joinsMu.Unlock() + return enforcer.joinsClosed + }, 5*time.Second, 10*time.Millisecond, "Close began") + s.Require().NoError(holder.Commit()) + select { + case <-closed: + case <-time.After(5 * time.Second): + s.FailNow("Close never returned") + } + s.Equal("org-first", s.organizationOf(app), "the write under way when Close began lands, and the one behind it is not started") +} + +func (s *PolicySuite) TestCloseWaitsForAMembershipBeingWritten() { + enforcer, err := New(s.store, quick, nil) + s.Require().NoError(err) + app := "app-" + uuid.NewString() + holder, pid := s.heldMembership(app) + enforcer.Join(s.ctx, app, "org-after", openTier) + s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond, + "the write waits behind the holder") + + closed := make(chan struct{}) + go func() { + enforcer.Close() + close(closed) + }() + s.Never(func() bool { + select { + case <-closed: + return true + default: + return false + } + }, 300*time.Millisecond, 10*time.Millisecond, "Close returns while the membership is being written") + s.Require().NoError(holder.Commit()) + select { + case <-closed: + case <-time.After(5 * time.Second): + s.FailNow("Close never returned") + } + s.Equal("org-after", s.organizationOf(app), "the membership landed before Close returned") +} + +func (s *PolicySuite) TestCloseStopsWaitingForAMembershipAfterJoinTimeout() { + enforcer, err := New(s.store, quick, nil) + s.Require().NoError(err) + app := "app-" + uuid.NewString() + _, pid := s.heldMembership(app) + enforcer.Join(s.ctx, app, "org-after", openTier) + s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond, + "the write waits behind the holder") + + closed := make(chan struct{}) + go func() { + enforcer.Close() + close(closed) + }() + select { + case <-closed: + case <-time.After(joinTimeout + 2*time.Second): + s.FailNow("Close waited on the membership past joinTimeout") + } +} + +func (s *PolicySuite) TestAJoinAfterCloseWritesNoMembership() { + enforcer, err := New(s.store, quick, nil) + s.Require().NoError(err) + enforcer.Close() + app := "app-" + uuid.NewString() + + enforcer.Join(s.ctx, app, "org-after", openTier) + + s.Never(func() bool { + var written bool + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT EXISTS (SELECT 1 FROM app_organizations WHERE app_id = ?)", app).Scan(&written)) + return written + }, 300*time.Millisecond, 10*time.Millisecond, "a closed enforcer starts no write") +} diff --git a/acceleration/internal/policy/policy.go b/acceleration/internal/policy/policy.go index b8a43524a7..0affbfccde 100644 --- a/acceleration/internal/policy/policy.go +++ b/acceleration/internal/policy/policy.go @@ -50,8 +50,10 @@ import ( var tracer = tracing.Tracer("policy") -// joinTimeout bounds recording which organization an app belongs to, and every read of an -// app's policies: in the background, and the one a request with no decision yet waits on. +// joinTimeout bounds every read of an app's policies: in the background, and the one a request +// with no decision yet waits on, and how long Close waits on the memberships being written. +// Recording which organization an app belongs to is given it too, but that write outlives it, +// within the store's write timeout (AppOrganizations.Upsert). const joinTimeout = 2 * time.Second // tierTTL is how long an organization's tier is believed without a request naming it before @@ -206,6 +208,14 @@ type Enforcer struct { // members is which organization each app has already been recorded under by this // process, so a membership is written once rather than on every request. members sync.Map + // joins is, for each app whose membership is being written, the organization to write + // next, empty for none: one write per app runs at a time, and the last organization named + // while it ran waits behind it. joining is those writes, which Close waits on; joinsClosed + // says Close has begun, after which none starts. + joinsMu sync.Mutex + joins map[string]string + joining sync.WaitGroup + joinsClosed bool // tiers is each organization's tier as this process last knew it, from a request or from // organization_tiers, and what it last wrote there. tiersMu sync.Mutex @@ -272,17 +282,31 @@ func New(config *store.Store, settings Settings, logger *slog.Logger) (*Enforcer } e := &Enforcer{ config: config, logger: logger, settings: settings.withDefaults(), - decisions: map[string]decision{}, tiers: map[string]tierSeen{}, now: time.Now, + decisions: map[string]decision{}, tiers: map[string]tierSeen{}, joins: map[string]string{}, now: time.Now, } e.money.start(e) return e, nil } -// Close stops the money loop and waits for it. Admit keeps answering from what it last read. +// Close stops the money loop and waits for it, and waits up to joinTimeout for the memberships +// being written. Admit keeps answering from what it last read. func (e *Enforcer) Close() { if e == nil { return } + e.joinsMu.Lock() + e.joinsClosed = true + e.joinsMu.Unlock() + joined := make(chan struct{}) + go func() { + e.joining.Wait() + close(joined) + }() + select { + case <-joined: + case <-time.After(joinTimeout): + e.logger.Error("closed with memberships still being written") + } e.money.stop() } @@ -402,19 +426,48 @@ func (e *Enforcer) Join(ctx context.Context, appID, organizationID, tier string) return } e.members.Store(appID, organizationID) + e.joinsMu.Lock() + defer e.joinsMu.Unlock() + if e.joinsClosed { + return + } + if _, running := e.joins[appID]; running { + e.joins[appID] = organizationID + return + } + e.joins[appID] = "" + e.joining.Add(1) go func() { - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), joinTimeout) - defer cancel() - if err := e.config.AppOrganizations.Upsert(ctx, &store.AppOrganization{AppID: appID, OrganizationID: organizationID}); err != nil { - e.members.Delete(appID) - e.logger.Error("could not record which organization an app belongs to", - "app", appID, "organization", organizationID, "error", err) - return + defer e.joining.Done() + // An organization named later is written on a context of its own, not that request's. + for ctx, organization := ctx, organizationID; ; ctx = context.Background() { + e.record(ctx, appID, organization) + e.joinsMu.Lock() + organization = e.joins[appID] + if organization == "" || e.joinsClosed { + delete(e.joins, appID) + e.joinsMu.Unlock() + return + } + e.joins[appID] = "" + e.joinsMu.Unlock() } - e.refresh(ctx, appID) }() } +// record writes that an app is in an organization, and reads its decision again once it is. +func (e *Enforcer) record(ctx context.Context, appID, organizationID string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), joinTimeout) + defer cancel() + if err := e.config.AppOrganizations.Upsert(ctx, &store.AppOrganization{AppID: appID, OrganizationID: organizationID}); err != nil { + e.members.Delete(appID) + e.logger.Error("could not record which organization an app belongs to", + "app", appID, "organization", organizationID, "error", err) + return + } + e.refresh(ctx, appID) +} + // warm starts reading an app's decision in the background when this process has none. func (e *Enforcer) warm(ctx context.Context, appID string) { e.mu.Lock() diff --git a/acceleration/internal/store/app_organization.go b/acceleration/internal/store/app_organization.go index 7c66e233d3..72a1a81d89 100644 --- a/acceleration/internal/store/app_organization.go +++ b/acceleration/internal/store/app_organization.go @@ -35,20 +35,24 @@ type AppOrganizations struct { store *Store } -// Upsert records that an app was seen under an organization now, and drops what every -// replica had cached of the app's. +// Upsert records that an app was seen under an organization now, in a write that outlives ctx +// within the store's write timeout, and drops what every replica had cached of the app's +// (detachedWrite). func (r *AppOrganizations) Upsert(ctx context.Context, membership *AppOrganization) error { if err := membership.Validate(); err != nil { return stack.Wrap(err) } membership.SeenAt = time.Now().UTC() - _, err := r.store.global.NewInsert().Model(membership). - On("CONFLICT (app_id) DO UPDATE"). - 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)) + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(membership). + On("CONFLICT (app_id) DO UPDATE"). + Set("organization_id = EXCLUDED.organization_id"). + Set("seen_at = EXCLUDED.seen_at"). + Exec(ctx) + return err + }, func() []string { + return []string{appOrganizationKey(membership.AppID), appPoliciesKey(membership.AppID)} + }) if err != nil { return stack.Wrap(fmt.Errorf("store: join organization: %w", err)) } diff --git a/acceleration/internal/store/app_organization_test.go b/acceleration/internal/store/app_organization_test.go index 6ebd9fd8ae..93295dec85 100644 --- a/acceleration/internal/store/app_organization_test.go +++ b/acceleration/internal/store/app_organization_test.go @@ -63,7 +63,7 @@ func (s *StoreSuite) TestAnAppBelongsToTheOrganizationItWasLastSeenUnder() { func (s *StoreSuite) TestAnAppMovedToAnotherOrganizationIsAnsweredUnderTheNewOneOnEveryReplica() { replica := s.replica() - app := "app-" + uuid.NewString() + app := "app-" + newID() s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: app, OrganizationID: "org-first"})) under, err := replica.AppOrganizations.Get(s.ctx, app) s.Require().NoError(err) @@ -81,11 +81,11 @@ func (s *StoreSuite) TestAppOrganizationQueryBudgets() { registered := s.app() seen := "app-" + uuid.NewString() - 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.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: seen, OrganizationID: "org-1"})) })) - })) + }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own") get := func() { _, err := s.store.AppOrganizations.Get(s.ctx, seen) s.Require().NoError(err) @@ -119,3 +119,36 @@ func (s *StoreSuite) TestAnOrganizationsAppsAreReadInOneStatement() { s.Require().NoError(err) }), "its apps, then whether the app of its own id is its") } + +func (s *StoreSuite) TestAnAppMovedByACommitThatLandsAfterItGaveUpIsForgottenAgain() { + 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()) }) + app := "app-" + newID() + s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: app, OrganizationID: "org-before"})) + + s.Require().Error(slow.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: app, OrganizationID: "org-after"}), + "the COMMIT is held past the read timeout") + seen, err := s.store.AppOrganizations.Get(s.ctx, app) + s.Require().NoError(err) + s.Require().Equal("org-before", seen.OrganizationID, "the app has not moved while the COMMIT is held") + policies, err := s.store.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + s.Require().Equal("org-before", policies.OrganizationID, "nor have its policies") + proxy.let() + s.Require().Eventually(func() bool { + moved, err := s.store.global.NewSelect().Model((*AppOrganization)(nil)). + Where("app_id = ? AND organization_id = ?", app, "org-after").Exists(s.ctx) + s.Require().NoError(err) + return moved + }, 5*time.Second, 10*time.Millisecond, "the held COMMIT lands") + + s.Eventually(func() bool { + seen, err := s.store.AppOrganizations.Get(s.ctx, app) + s.Require().NoError(err) + policies, err := s.store.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + return seen.OrganizationID == "org-after" && policies.OrganizationID == "org-after" + }, 5*time.Second, 10*time.Millisecond, "the copies cached before the COMMIT landed are dropped again") +} diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index 60d059f91f..d871dff877 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -118,10 +118,12 @@ func forgottenCopies(db bun.IDB, customerID string) *bun.UpdateQuery { // and records entry, with these counts added to its changes, in the same transaction. The // changes recorded of their campaigns, deleted ones' included, name the replacement too // (renamedChanges). A campaign's contacts and their attempts stay: they are the app's data -// about third parties, not the user's. +// about third parties, not the user's. It outlives ctx, its statements sharing the store's write +// timeout, and drops the user's cached policy whatever the commit answered, and again after a +// COMMIT whose answer was lost (detachedWrite). func (s *Store) ForgetUserSettings(ctx context.Context, appID, userID, replacement string, entry *AuditEntry) (UserSettings, error) { var counts UserSettings - err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + err := s.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { for _, change := range []struct { count *int64 exec func(context.Context, ...any) (sql.Result, error) @@ -143,9 +145,7 @@ 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)) + }, func() []string { return s.Policies.keys(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/forget_test.go b/acceleration/internal/store/forget_test.go index 7757eec0c6..5eb2b6ba4e 100644 --- a/acceleration/internal/store/forget_test.go +++ b/acceleration/internal/store/forget_test.go @@ -160,3 +160,46 @@ func (s *StoreSuite) TestRenamingAUserRenamesThemInTheChangesOfARequestDeletedBe s.Empty(s.payloadsNaming("app", "jlahey")) } + +func (s *StoreSuite) TestAUsersPolicyForgottenByACommitThatLandsAfterItGaveUpIsForgottenAgain() { + 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()) }) + app := "app-" + newID() + user := UserScopeID(app, "jlahey") + yes := true + s.Require().NoError(s.store.Policies.Upsert(s.ctx, &Policy{Scope: ScopeUser, ScopeID: user, Document: PolicyDocument{PromptInjection: &yes}})) + + _, err = slow.ForgetUserSettings(s.ctx, app, "jlahey", "forgotten", &AuditEntry{ + CustomerID: app, ResourceType: AuditEndUser, ResourceID: "forgotten", Action: AuditUpdated, Source: AuditSourceCLI, ActorID: "ops", + }) + s.Require().Error(err, "the COMMIT is held past the read timeout") + document, err := s.store.Policies.Get(s.ctx, ScopeUser, user) + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection, "the policy is still there while the COMMIT is held") + has, err := s.store.Policies.HasUsers(s.ctx, app) + s.Require().NoError(err) + s.Require().True(has, "and the app still has a user with a policy") + // Past the first deletion that follows, so the COMMIT lands between two of them. + for deadline := time.Now().Add(2 * forgetBackoff); time.Now().Before(deadline); { + document, err := s.store.Policies.Get(s.ctx, ScopeUser, user) + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection, "the policy is still there while the COMMIT is held") + } + proxy.let() + s.Require().Eventually(func() bool { + held, err := s.store.global.NewSelect().Model((*Policy)(nil)). + Where("scope = ? AND scope_id = ?", ScopeUser, user).Exists(s.ctx) + s.Require().NoError(err) + return !held + }, 5*time.Second, 10*time.Millisecond, "the held COMMIT lands") + + s.Eventually(func() bool { + document, err := s.store.Policies.Get(s.ctx, ScopeUser, user) + s.Require().NoError(err) + has, err := s.store.Policies.HasUsers(s.ctx, app) + s.Require().NoError(err) + return document.PromptInjection == nil && !has + }, 5*time.Second, 10*time.Millisecond, "the copies cached before the COMMIT landed are dropped again") +} diff --git a/acceleration/internal/store/policy.go b/acceleration/internal/store/policy.go index f7fcb99216..53f06e80f1 100644 --- a/acceleration/internal/store/policy.go +++ b/acceleration/internal/store/policy.go @@ -281,11 +281,6 @@ 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. -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 @@ -307,7 +302,7 @@ func (r *Policies) keys(ctx context.Context, scope PolicyScope, id string) []str } // policyKeys are the cached values a write of one scope's document changes, but for the -// AppPolicies of an organization's apps (forget). +// AppPolicies of an organization's apps (keys). func policyKeys(scope PolicyScope, id string) []string { keys := []string{cacheKey("policy", string(scope), id)} if scope == ScopeApp { diff --git a/acceleration/internal/store/redis.go b/acceleration/internal/store/redis.go index a192c6a8a6..7d675787fc 100644 --- a/acceleration/internal/store/redis.go +++ b/acceleration/internal/store/redis.go @@ -47,11 +47,14 @@ 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. +// per write. forgetGrace is how long Close lets them run before it stops them: past the last +// attempt of one that began as Close did, when Redis answers it promptly. One that waits on a +// slow Redis can still be cut short at its third attempt. const ( forgetAttempts = 3 forgetBackoff = 100 * time.Millisecond forgetSlots = 64 + forgetGrace = forgetBackoff << forgetAttempts ) // Redis says where a Redis server is. An empty Address is none. @@ -295,7 +298,7 @@ func (s *Store) forget(ctx context.Context, names ...string) bool { } } if len(missed) > 0 { - s.forgetLater(missed, failed) + s.forgetLater(missed, failed, false) } return len(missed) == 0 } @@ -303,8 +306,9 @@ func (s *Store) forget(ctx context.Context, names ...string) bool { // 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) { +// covers. With every set, each attempt deletes all of names whatever the last one answered: +// the keys of a COMMIT whose answer was lost, which may land at any time during them. +func (s *Store) forgetLater(names []string, err error, every bool) { s.retryMu.Lock() defer s.retryMu.Unlock() if s.closed { @@ -323,6 +327,7 @@ func (s *Store) forgetLater(names []string, err error) { defer func() { <-s.retries }() client := s.cache.Client() wait := forgetBackoff + var missed []string for range forgetAttempts { timer := time.NewTimer(wait) select { @@ -337,7 +342,7 @@ func (s *Store) forgetLater(names []string, err error) { for _, name := range names { commands = append(commands, client.B().Del().Key(name).Build()) } - var missed []string + missed = nil attempt, cancel := context.WithTimeout(s.closing, forgetWait) for i, reply := range client.DoMulti(attempt, commands...) { if failed := reply.Error(); failed != nil && !errors.Is(failed, rueidis.Nil) { @@ -345,11 +350,15 @@ func (s *Store) forgetLater(names []string, err error) { } } cancel() - if names = missed; len(names) == 0 { - return + if !every { + if names = missed; len(names) == 0 { + return + } } wait *= 2 } - slog.Default().Error("gave up dropping cached rows", "keys", names, "attempts", forgetAttempts, "error", err) + if len(missed) > 0 { + slog.Default().Error("gave up dropping cached rows", "keys", missed, "attempts", forgetAttempts, "error", err) + } }() } diff --git a/acceleration/internal/store/redis_test.go b/acceleration/internal/store/redis_test.go index 2b9470505f..2dbcbece0e 100644 --- a/acceleration/internal/store/redis_test.go +++ b/acceleration/internal/store/redis_test.go @@ -589,6 +589,53 @@ func (s *StoreSuite) TestEveryCachedWriteARequestGaveUpOnLeavesNoStaleCopy() { _, err = s.store.AgentConfigs.GetByName(s.ctx, "acme-app", was) s.ErrorIs(err, ErrNoAgentConfig) }, + "AppOrganizations.Upsert": func() { + app := "app-" + newID() + s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: app, OrganizationID: "org-before"})) + err := s.readWhileWriting(s.lockingWhere("app_organizations", "app_id = ?", app), func(ctx context.Context) error { + return s.store.AppOrganizations.Upsert(ctx, &AppOrganization{AppID: app, OrganizationID: "org-after"}) + }, func() { + seen, err := s.store.AppOrganizations.Get(s.ctx, app) + s.Require().NoError(err) + s.Require().Equal("org-before", seen.OrganizationID, "the app has not moved yet") + policies, err := s.store.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + s.Require().Equal("org-before", policies.OrganizationID, "the app's policies are not moved yet") + }, bun.Tx.Commit) + s.Require().NoError(err) + seen, err := s.store.AppOrganizations.Get(s.ctx, app) + s.Require().NoError(err) + s.Equal("org-after", seen.OrganizationID) + policies, err := s.store.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + s.Equal("org-after", policies.OrganizationID, "the app's policies are read under the new organization") + }, + "ForgetUserSettings": func() { + app := "app-" + newID() + user := UserScopeID(app, "jlahey") + yes := true + s.Require().NoError(s.store.Policies.Upsert(s.ctx, &Policy{Scope: ScopeUser, ScopeID: user, Document: PolicyDocument{PromptInjection: &yes}})) + err := s.readWhileWriting(s.lockingWhere("policies", "scope = ? AND scope_id = ?", ScopeUser, user), func(ctx context.Context) error { + _, err := s.store.ForgetUserSettings(ctx, app, "jlahey", "forgotten", &AuditEntry{ + CustomerID: app, ResourceType: AuditEndUser, ResourceID: "forgotten", Action: AuditUpdated, Source: AuditSourceCLI, ActorID: "ops", + }) + return err + }, func() { + document, err := s.store.Policies.Get(s.ctx, ScopeUser, user) + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection, "the user's policy is not deleted yet") + has, err := s.store.Policies.HasUsers(s.ctx, app) + s.Require().NoError(err) + s.Require().True(has, "the app still has a user with a policy") + }, bun.Tx.Commit) + s.Require().NoError(err) + document, err := s.store.Policies.Get(s.ctx, ScopeUser, user) + s.Require().NoError(err) + s.Nil(document.PromptInjection) + has, err := s.store.Policies.HasUsers(s.ctx, app) + s.Require().NoError(err) + s.False(has, "the app has no user with a policy any more") + }, "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} diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index ae7de3e23d..24d2c96d7a 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -92,7 +92,7 @@ const writeTimeout = 10 * time.Second // 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). +// on each of the next few attempts (forgetLater), which Close lets run. 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 @@ -115,7 +115,7 @@ func (s *Store) detachedWriteTold(ctx context.Context, write func(context.Contex 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) + s.forgetLater(names, err, true) } return told, err } @@ -225,11 +225,21 @@ func (s *Store) Server(ctx context.Context) (database, address string, err error return database, server.String, nil } -// Close releases the connection pools. +// Close releases the connection pools, once the deletions forgetLater holds have run, or +// forgetGrace has passed. func (s *Store) Close() error { s.retryMu.Lock() s.closed = true s.retryMu.Unlock() + retried := make(chan struct{}) + go func() { + s.retrying.Wait() + close(retried) + }() + select { + case <-retried: + case <-time.After(forgetGrace): + } s.stop() s.retrying.Wait() s.closeRedis()