From 4a523965aaa9a235aa54c5a7ea4afdc53eed0e83 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 14:19:14 +0000 Subject: [PATCH 1/2] fix(store): forgetting a user leaves nothing of theirs in the recorded changes, and an import naming another customer's row is refused - Requests.RenameUser and ForgetUserSettings rename the user in every recorded change of the app's requests and campaigns that names them, deleted rows' included, in the same statement as the rewrite. A request recorded after the statement keeps its change. - BranchMessages.DeleteUser and Sessions.Delete turn the recorded inserts and updates of the copies they delete into deletes that carry nothing. The copy's own delete change stays. - Every change keeps its number, so no follower of any app is told to export again. - importRow returns ErrAnotherCustomersRow when it wrote nothing because another customer holds the row's key here, instead of dropping the row. A re-import of the importer's own row is still a no-op. --- acceleration/internal/store/branch_message.go | 10 +- .../internal/store/branch_message_test.go | 48 ++++++ acceleration/internal/store/datamove.go | 41 ++++- acceleration/internal/store/datamove_test.go | 75 +++++++- acceleration/internal/store/forget.go | 32 +++- acceleration/internal/store/forget_test.go | 162 ++++++++++++++++++ acceleration/internal/store/request.go | 9 +- acceleration/internal/store/session.go | 6 +- 8 files changed, 369 insertions(+), 14 deletions(-) create mode 100644 acceleration/internal/store/forget_test.go diff --git a/acceleration/internal/store/branch_message.go b/acceleration/internal/store/branch_message.go index 14f3763c65..1b28594d5e 100644 --- a/acceleration/internal/store/branch_message.go +++ b/acceleration/internal/store/branch_message.go @@ -121,15 +121,19 @@ func (r *BranchMessages) Delete(ctx context.Context, customerID, sessionID strin } // DeleteUser deletes every copy of a hidden message in the sessions of an app's end user, on -// every shard, and answers how many it deleted. +// every shard, and answers how many it deleted. The changes recorded of those copies are +// emptied with them, since they hold the same words (forgottenCopies). func (r *BranchMessages) DeleteUser(ctx context.Context, appID, userID string) (int64, error) { if appID == "" || userID == "" { return 0, stack.Wrap(errors.New("store: an app and a user id are required")) } + sessions := "(SELECT id FROM agent_sessions WHERE customer_id = ? AND user_id = ?)" deleted, err := onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { - return db.NewDelete().Model((*AgentBranchMessage)(nil)). + // A data-modifying WITH runs to the end whether or not the statement reads it. + changes := forgottenCopies(db, appID).Where("payload->>'session_id' IN "+sessions, appID, userID) + return db.NewDelete().With("changes", changes).Model((*AgentBranchMessage)(nil)). Where("customer_id = ?", appID). - Where("session_id IN (SELECT id FROM agent_sessions WHERE customer_id = ? AND user_id = ?)", appID, userID). + Where("session_id IN "+sessions, appID, userID). Exec(ctx) }) if err != nil { diff --git a/acceleration/internal/store/branch_message_test.go b/acceleration/internal/store/branch_message_test.go index be00ac2598..a56d09c956 100644 --- a/acceleration/internal/store/branch_message_test.go +++ b/acceleration/internal/store/branch_message_test.go @@ -4,6 +4,7 @@ package store import ( "fmt" + "slices" "time" ) @@ -136,3 +137,50 @@ func (s *StoreSuite) TestACopyNamingNoCustomerIsNotWritten() { err := s.store.BranchMessages.UpsertMany(s.ctx, []AgentBranchMessage{{SessionID: "one", OriginalMessageID: "invalid"}}) s.refusedUnwritten(err, "agent_branch_messages", "original_message_id", "invalid") } + +func (s *StoreSuite) TestForgettingAUserEmptiesTheChangesRecordedOfTheirCopies() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + s.opened("one", "app", s.base, nil) + s.opened("two", "app", s.base, func(session *AgentSession) { session.UserID = "rlafleur" }) + theirs := hidden("m2", "second", "switch", s.base, "kept words") + theirs.SessionID = "two" + s.Require().NoError(s.store.BranchMessages.UpsertMany(s.ctx, []AgentBranchMessage{hidden("m1", "second", "switch", s.base, "forgotten words"), theirs})) + s.Require().NoError(s.store.Calls.Start(s.ctx, &Call{ID: "call-1", SessionID: "one", CustomerID: "app", ConversationID: "agent:one", StartedAt: s.base})) + before := seqs(s.recordedFor("app")) + s.Require().NotEmpty(s.payloadsNaming("app", "forgotten words"), "the copy's insert was recorded") + + _, err := s.store.BranchMessages.DeleteUser(s.ctx, "app", "jlahey") + s.Require().NoError(err) + + s.Empty(s.payloadsNaming("app", "forgotten words")) + s.NotEmpty(s.payloadsNaming("app", "kept words"), "another user's copies keep their changes") + s.Subset(seqs(s.recordedFor("app")), before, "every change keeps its number") + deletes := slices.DeleteFunc(s.recordedOf("app", "agent_branch_messages"), func(change DataChange) bool { return change.Op != ChangeDelete }) + s.Len(deletes, 2, "the copy's insert, emptied, and its delete, still recorded for the deployment the app is moving to") + calls := s.recordedOf("app", "calls") + s.Require().Len(calls, 1) + s.Contains(string(calls[0].Payload), `"agent:one"`, "a call of the session is no copy") +} + +func (s *StoreSuite) TestForgettingAUserAfterTheirSessionWasDeletedLeavesNoChangeOfItsCopies() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + s.opened("one", "app", s.base, nil) + s.opened("two", "app", s.base, func(session *AgentSession) { session.UserID = "rlafleur" }) + other := hidden("m2", "second", "switch", s.base, "kept words") + other.SessionID = "two" + s.Require().NoError(s.store.BranchMessages.UpsertMany(s.ctx, []AgentBranchMessage{hidden("m1", "second", "switch", s.base, "forgotten words"), other})) + s.Require().NotEmpty(s.payloadsNaming("app", "forgotten words"), "the copy's insert was recorded") + + s.Require().NoError(s.store.Sessions.Delete(s.ctx, "app", "one")) + _, err := s.store.BranchMessages.DeleteUser(s.ctx, "app", "jlahey") + s.Require().NoError(err) + + s.Empty(s.payloadsNaming("app", "forgotten words")) + s.NotEmpty(s.payloadsNaming("app", "kept words"), "a copy in another session keeps its change") +} diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index e9b1a2e881..d8bc38b5df 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -669,7 +669,8 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an // customer inside every row it carries, and believing that would let anybody holding // credentials for one app write into another. For a row that belongs to a customer // through a parent there is no column to overwrite, so the parent is checked instead and -// a row whose parent is somebody else's is silently not written. +// a row whose parent is somebody else's is silently not written. A row whose key a row of +// another customer holds here is refused (ErrAnotherCustomersRow). // // It upserts, so importing the same export twice is the same as importing it once, which // is what lets a move be resumed after it was interrupted. @@ -865,12 +866,48 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str "%sINSERT INTO %s (%s) SELECT %s FROM %sjsonb_populate_record(NULL::%s, %s) AS r%s ON CONFLICT %s %s", locked, spec.name, quoted, selected, through, spec.name, subject, where, spec.conflictTarget(shape), conflict) - if _, err := db.ExecContext(ctx, query, args...); err != nil { + result, err := db.ExecContext(ctx, query, args...) + if err != nil { return fmt.Errorf("store: import %s: %w", table, err) } + written, err := result.RowsAffected() + if err != nil { + return stack.Wrap(fmt.Errorf("store: import %s: %w", table, err)) + } + if written > 0 || spec.copied != "" { + return nil + } + // Nothing written is the importer's own row kept as it is here, or a row whose key another + // customer holds, which is refused rather than dropped. A copied row's key names its customer. + keys := shape.keys + if spec.across != "" { + keys = []string{spec.across} + } + keyed, held, imported := make([]string, 0, len(keys)), make([]string, 0, len(keys)), make([]string, 0, len(keys)) + for _, key := range keys { + expression := "r." + key + if i := slices.Index(columns, key); i >= 0 { + expression = picked[i] + } + keyed = append(keyed, expression+" AS "+key) + held, imported = append(held, "h."+key), append(imported, "i."+key) + } + var taken bool + if err := db.QueryRowContext(ctx, fmt.Sprintf( + "SELECT EXISTS (SELECT 1 FROM (SELECT %s FROM jsonb_populate_record(NULL::%s, %s) AS r) AS i JOIN %s AS h ON (%s) = (%s) WHERE NOT %s)", + strings.Join(keyed, ", "), spec.name, subject, spec.name, strings.Join(held, ", "), strings.Join(imported, ", "), spec.owned("h")), + append(slices.Clone(read), customerID)...).Scan(&taken); err != nil { + return fmt.Errorf("store: import %s: %w", table, err) + } + if taken { + return fmt.Errorf("store: import %s: %w", table, ErrAnotherCustomersRow) + } return nil } +// ErrAnotherCustomersRow refuses an imported row whose key a row of another customer holds here. +var ErrAnotherCustomersRow = errors.New("a row with this key belongs to another customer here") + // validated is a model that refuses a row the API would not store. type validated interface{ Validate() error } diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 26b1e6b99f..840367f189 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -451,8 +451,10 @@ func (s *DataMoveSuite) TestAnImportCannotOverwriteAnotherCustomersRow() { "INSERT INTO agent_configs (id, customer_id, name, instructions) VALUES (?, ?, ?, ?)", id, "resident", "theirs", "be brief") s.Require().NoError(err) + row, err := json.Marshal(s.export("acme").of("agent_configs")[0]) + s.Require().NoError(err) - s.move("acme", "intruder") + s.ErrorIs(s.destination.ImportRow(s.ctx, "intruder", "agent_configs", row), ErrAnotherCustomersRow) var name, owner string s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, @@ -474,7 +476,10 @@ func (s *DataMoveSuite) TestAReplayedChangeCannotDeleteAnotherCustomersRow() { id, "resident", "theirs", "be brief") s.Require().NoError(err) - s.Require().NoError(s.destination.ApplyChanges(s.ctx, "intruder", changes)) + s.ErrorIs(s.destination.ApplyChanges(s.ctx, "intruder", changes), ErrAnotherCustomersRow, "the insert is refused") + deletes := slices.DeleteFunc(changes, func(change DataChange) bool { return change.Op != ChangeDelete }) + s.Require().NotEmpty(deletes) + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "intruder", deletes)) var count int s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, @@ -2516,7 +2521,18 @@ func (s *DataMoveSuite) TestTheCutOverLeavesATaskWhoseConfigIsAnotherCustomersHe _, err := s.destination.GlobalDB().ExecContext(s.ctx, "INSERT INTO agent_configs (id, customer_id, name, instructions) VALUES ('config-1', 'resident', 'theirs', 'be brief')") s.Require().NoError(err) - s.move("acme", "moved") + reservation, err := s.destination.ReserveImportedIDs(s.ctx) + s.Require().NoError(err) + for _, row := range s.export("acme").rows { + encoded, err := json.Marshal(row.row) + s.Require().NoError(err) + if row.table == "agent_configs" { + s.Require().ErrorIs(s.destination.ImportRow(s.ctx, "moved", row.table, encoded), ErrAnotherCustomersRow) + continue + } + s.Require().NoError(reservation.Cover(s.ctx, row.table, encoded)) + s.Require().NoError(s.destination.ImportRow(s.ctx, "moved", row.table, encoded)) + } resumed, skipped, _, _, err := s.destination.ResumeMovedRows(s.ctx, "moved") @@ -3582,6 +3598,59 @@ func (s *DataMoveSuite) TestAMovedRequestNeverOverwritesTheDestinationsRowWithIt } } +func (s *DataMoveSuite) TestARequestWhoseIDsAnotherCustomerHoldsHereLandsBesideTheirs() { + // Far from where either sequence draws, as a row of another deployment's would be. + id := time.Now().UnixNano() % 1_000_000_000_000 + moved := s.takenRequest(s.source, id) + held := s.takenRequest(s.destination, id) + _, err := s.destination.ShardDB().ExecContext(s.ctx, "UPDATE requests SET customer_id = 'resident', usage_id = ? WHERE usage_id = ?", moved.UsageID, held.UsageID) + s.Require().NoError(err) + + s.move("acme", "acme") + s.move("acme", "acme") + + var owner string + s.Require().NoError(s.destination.ShardDB().QueryRowContext(s.ctx, + "SELECT customer_id FROM requests WHERE usage_id = ?", moved.UsageID).Scan(&owner)) + s.Equal("resident", owner, "the other customer's row is left as it was") + rows := s.requestsByUsage() + s.Require().Len(rows, 1, "the moved row, once however often it is imported") + s.NotContains(rows, moved.UsageID.String(), "under a usage id of the destination's") +} + +func (s *DataMoveSuite) TestALogTakenBackWhereItCameFromIsNotRefusedOverAnotherAppsLogWithItsCopysID() { + s.seedLog("acme", "copied") + // The destination has drawn ids of its own, so the copy's is not the one it came from. + _, err := s.destination.GlobalDB().ExecContext(s.ctx, "SELECT setval('agent_logs_id_seq', nextval('agent_logs_id_seq') + 1000)") + s.Require().NoError(err) + s.move("acme", "acme") + copied := s.logsHere("acme") + s.Require().Len(copied, 1) + for id := range copied { + // The copy's id here is another app's log's back where it came from. + _, err = s.source.GlobalDB().ExecContext(s.ctx, ` +INSERT INTO agent_logs (id, customer_id, source, severity, event_type, message) VALUES (?, 'resident', 'agent', 'info', 'turn', 'theirs')`, id) + s.Require().NoError(err) + } + + for _, row := range s.exportFrom(s.destination, "acme").of("agent_logs") { + encoded, err := json.Marshal(row) + s.Require().NoError(err) + s.NoError(s.source.ImportRow(s.ctx, "acme", "agent_logs", encoded), "the log is the one it was copied from") + } +} + +func (s *DataMoveSuite) TestReimportingTheImportersOwnRowsIsTheSameAsImportingThemOnce() { + s.seedAgentConfig(s.source, "acme", "mine") + s.takenRequest(s.source, 3) + + s.move("acme", "acme") + s.move("acme", "acme") + + s.Len(s.exportFrom(s.destination, "acme").of("agent_configs"), 1) + s.Len(s.requestsByUsage(), 1) +} + func (s *DataMoveSuite) TestADeletedRequestIsReplayedByItsUsageID() { s.capture("acme") id := time.Now().UnixNano() % 1_000_000_000_000 diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index 316836cc8d..a60b4231a0 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -88,9 +88,36 @@ func (s *Store) CountUserSettings(ctx context.Context, appID, userID string) (Us return counts, nil } +// dataChange is a row of data_changes, the changes recorded for a customer who is moving. +type dataChange struct { + bun.BaseModel `bun:"table:data_changes,alias:dc"` + + Seq int64 `bun:"seq,pk"` +} + +// renamedChanges replaces an end user's id with replacement in the recorded changes of a +// table's rows that name them in user_id, deleted rows' included. +// Changes are rewritten rather than deleted: a follower is refused a cursor below the oldest +// change kept of any customer (Changes), so dropping one would make every move copy again. +func renamedChanges(db bun.IDB, customerID, table, userID, replacement string) *bun.UpdateQuery { + return db.NewUpdate().Model((*dataChange)(nil)). + Set("payload = jsonb_set(payload, '{user_id}', to_jsonb(?::text))", replacement). + Where("customer_id = ? AND table_name = ? AND payload->>'user_id' = ?", customerID, table, userID) +} + +// forgottenCopies turns the recorded inserts and updates of a customer's copies of hidden +// messages into deletes that carry nothing, for the caller to narrow to the copies it deletes. +// They keep their numbers (renamedChanges), and the copy's own delete change stays after them. +func forgottenCopies(db bun.IDB, customerID string) *bun.UpdateQuery { + return db.NewUpdate().Model((*dataChange)(nil)).Set("op = ?", ChangeDelete).Set("payload = NULL"). + Where("customer_id = ? AND table_name = 'agent_branch_messages' AND op <> ?", customerID, ChangeDelete) +} + // ForgetUserSettings deletes an app's end user's own policy and user-level limits, so they fall // back to the app's, replaces their id with replacement on their resets, grants and campaigns, -// and records entry, with these counts added to its changes, in the same transaction. A +// 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. func (s *Store) ForgetUserSettings(ctx context.Context, appID, userID, replacement string, entry *AuditEntry) (UserSettings, error) { @@ -104,7 +131,8 @@ func (s *Store) ForgetUserSettings(ctx context.Context, appID, userID, replaceme {&counts.Limits, tx.NewDelete().Model((*Limit)(nil)).Where("level = ? AND app_id = ? AND user_id = ?", LevelUser, appID, userID).Exec}, {&counts.Resets, tx.NewUpdate().Model((*UsageReset)(nil)).Set("user_id = ?", replacement).Where("app_id = ? AND user_id = ?", appID, userID).Exec}, {&counts.Grants, tx.NewUpdate().Model((*LimitGrant)(nil)).Set("user_id = ?", replacement).Where("app_id = ? AND user_id = ?", appID, userID).Exec}, - {&counts.Campaigns, tx.NewUpdate().Model((*Campaign)(nil)).Set("user_id = ?", replacement).Where("customer_id = ? AND user_id = ?", appID, userID).Exec}, + {&counts.Campaigns, tx.NewUpdate().With("renamed", renamedChanges(tx, appID, "campaigns", userID, replacement)). + Model((*Campaign)(nil)).Set("user_id = ?", replacement).Where("customer_id = ? AND user_id = ?", appID, userID).Exec}, } { result, err := change.exec(ctx) if err != nil { diff --git a/acceleration/internal/store/forget_test.go b/acceleration/internal/store/forget_test.go new file mode 100644 index 0000000000..7757eec0c6 --- /dev/null +++ b/acceleration/internal/store/forget_test.go @@ -0,0 +1,162 @@ +//go:build integration + +package store + +import ( + "encoding/json" + "slices" + "strings" + "time" +) + +// recordedFor is every change recorded for a customer, as following their move reads them. +func (s *StoreSuite) recordedFor(customerID string) []DataChange { + changes, _, err := s.store.Changes(s.ctx, customerID, 0, 1000) + s.Require().NoError(err) + return changes +} + +// payloadsNaming are the recorded changes of a customer whose row names a user. +func (s *StoreSuite) payloadsNaming(customerID, userID string) []DataChange { + var naming []DataChange + for _, change := range s.recordedFor(customerID) { + if strings.Contains(string(change.Payload), `"`+userID+`"`) { + naming = append(naming, change) + } + } + return naming +} + +// recordedOf are the recorded changes of one table of a customer's. +func (s *StoreSuite) recordedOf(customerID, table string) []DataChange { + return slices.DeleteFunc(s.recordedFor(customerID), func(change DataChange) bool { return change.Table != table }) +} + +// seqs are the numbers of changes. +func seqs(changes []DataChange) []int64 { + numbers := make([]int64, 0, len(changes)) + for _, change := range changes { + numbers = append(numbers, change.Seq) + } + return numbers +} + +// forget runs the shared database's step of forgetting jlahey of app. +func (s *StoreSuite) forget() { + _, err := s.store.ForgetUserSettings(s.ctx, "app", "jlahey", "forgotten", &AuditEntry{ + CustomerID: "app", ResourceType: AuditEndUser, ResourceID: "forgotten", Action: AuditUpdated, Source: AuditSourceCLI, ActorID: "ops", + }) + s.Require().NoError(err) +} + +func (s *StoreSuite) TestForgettingAUserRenamesThemInTheChangesRecordedOfTheirCampaigns() { + for _, app := range []string{"app", "app2"} { + s.Require().NoError(s.store.StartDataCapture(s.ctx, app, time.Hour, time.Second)) + } + reused := Campaign{CustomerID: "app2", Name: "Renewals", ConfigID: "config-1", FromNumber: "+15550100", UserID: "jlahey"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &reused)) + // The other app's campaign is gone and the app's holds its id, so only the customer tells + // their changes apart: an id is unique among the rows that exist, not among those recorded. + s.Require().NoError(s.store.Campaigns.Delete(s.ctx, "app2", reused.ID)) + _, err := s.store.global.ExecContext(s.ctx, + "INSERT INTO campaigns (id, customer_id, name, config_id, from_number, user_id) VALUES (?, 'app', 'Renewals', 'config-1', '+15550100', 'jlahey')", reused.ID) + s.Require().NoError(err) + other := Campaign{CustomerID: "app", Name: "Winback", ConfigID: "config-1", FromNumber: "+15550100", UserID: "rlafleur"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &other)) + before := seqs(s.recordedFor("app")) + s.Require().NotEmpty(s.payloadsNaming("app", "jlahey"), "the campaign's insert was recorded") + + s.forget() + + s.Empty(s.payloadsNaming("app", "jlahey")) + s.Len(s.payloadsNaming("app", "forgotten"), 2, "the insert renamed, and the rewrite recorded under the replacement") + s.NotEmpty(s.payloadsNaming("app", "rlafleur"), "another user's changes stay") + s.NotEmpty(s.payloadsNaming("app2", "jlahey"), "the same user id of another app is another user") + s.Subset(seqs(s.recordedFor("app")), before, "every change keeps its number") +} + +func (s *StoreSuite) TestForgettingAUserOfOneAppLeavesAnotherAppsFollowerWhereItWas() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + theirs := Campaign{CustomerID: "app", Name: "Renewals", ConfigID: "config-1", FromNumber: "+15550100", UserID: "jlahey"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &theirs)) + s.Require().NoError(s.store.StartDataCapture(s.ctx, "other", time.Hour, time.Second)) + cursor, err := s.store.ExportCustomer(s.ctx, "other", func(string, json.RawMessage) error { return nil }) + s.Require().NoError(err) + // The user's changes are then on both sides of the follower's cursor, and the oldest kept. + later := Campaign{CustomerID: "app", Name: "Winback", ConfigID: "config-1", FromNumber: "+15550100", UserID: "jlahey"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &later)) + unread := Campaign{CustomerID: "other", Name: "Winback", ConfigID: "config-1", FromNumber: "+15550101", UserID: "rlafleur"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &unread)) + + s.forget() + + changes, _, err := s.store.Changes(s.ctx, "other", cursor, 100) + s.Require().NoError(err, "forgetting a user of another app takes no change of this one's") + s.Len(changes, 1) +} + +func (s *StoreSuite) TestForgettingAUserRenamesThemInTheChangesOfTheRequestsRewrittenAlone() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + request := func(user string) *Request { + recorded := &Request{Modality: "stt", CustomerID: "app", UserID: user, Provider: "deepgram", Model: "flux-general-en", StartedAt: s.base, Success: true} + s.Require().NoError(s.store.Requests.Insert(s.ctx, recorded)) + return recorded + } + request("jlahey") + request("rlafleur") + s.opened("one", "app", s.base, nil) + + _, err := s.store.Requests.RenameUser(s.ctx, "app", "jlahey", "forgotten") + s.Require().NoError(err) + // A request in flight when its rows were rewritten, which forget-user waits out and rewrites + // on a later run: until then its row names the user, and so does its change. + late := request("jlahey") + s.forget() + + var naming []string + for _, change := range s.recordedOf("app", "requests") { + if strings.Contains(string(change.Payload), `"jlahey"`) { + naming = append(naming, string(change.Key)) + } + } + s.Require().Len(naming, 1, "only the late request's change names the user") + s.Contains(naming[0], late.UsageID.String()) + s.Len(slices.DeleteFunc(s.recordedOf("app", "requests"), func(change DataChange) bool { + return !strings.Contains(string(change.Payload), `"forgotten"`) + }), 2, "the rewritten request's insert renamed, and its rewrite") + s.NotEmpty(s.payloadsNaming("app", "rlafleur"), "another user's changes stay") + s.NotEmpty(s.recordedOf("app", "agent_sessions")[0].Payload, "a table forget leaves alone keeps its changes") + s.Contains(string(s.recordedOf("app", "agent_sessions")[0].Payload), `"jlahey"`) +} + +func (s *StoreSuite) TestForgettingAUserRenamesThemInTheChangesOfACampaignDeletedBefore() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + gone := Campaign{CustomerID: "app", Name: "Renewals", ConfigID: "config-1", FromNumber: "+15550100", UserID: "jlahey"} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &gone)) + s.Require().NoError(s.store.Campaigns.Delete(s.ctx, "app", gone.ID)) + s.Require().NotEmpty(s.payloadsNaming("app", "jlahey"), "the campaign's insert was recorded") + + s.forget() + + s.Empty(s.payloadsNaming("app", "jlahey")) +} + +func (s *StoreSuite) TestRenamingAUserRenamesThemInTheChangesOfARequestDeletedBefore() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "app", time.Hour, time.Second)) + gone := &Request{Modality: "stt", CustomerID: "app", UserID: "jlahey", Provider: "deepgram", Model: "flux-general-en", StartedAt: s.base, Success: true} + s.Require().NoError(s.store.Requests.Insert(s.ctx, gone)) + _, err := s.store.shard.ExecContext(s.ctx, "DELETE FROM requests WHERE usage_id = ?", gone.UsageID) + s.Require().NoError(err) + s.Require().NotEmpty(s.payloadsNaming("app", "jlahey"), "the request's insert was recorded") + + _, err = s.store.Requests.RenameUser(s.ctx, "app", "jlahey", "forgotten") + s.Require().NoError(err) + + s.Empty(s.payloadsNaming("app", "jlahey")) +} diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index 22fc1f9e83..20a7142cdc 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -715,11 +715,14 @@ func (r *Requests) CountByUser(ctx context.Context, appID, userID string) (int64 return total, nil } -// RenameUser replaces an app's end user id with replacement on every shard's requests, and -// answers how many rows it rewrote. +// RenameUser replaces an app's end user id with replacement on every shard's requests, and in +// the changes recorded of their requests in the same statement (renamedChanges), and answers +// how many rows it rewrote. A request recorded after the statement keeps its change as it is. func (r *Requests) RenameUser(ctx context.Context, appID, userID, replacement string) (int64, error) { renamed, err := onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { - return db.NewUpdate().Model((*Request)(nil)).Set("user_id = ?", replacement). + // A data-modifying WITH runs to the end whether or not the statement reads it. + changes := renamedChanges(db, appID, "requests", userID, replacement) + return db.NewUpdate().With("changes", changes).Model((*Request)(nil)).Set("user_id = ?", replacement). Where("customer_id = ?", appID).Where("user_id = ?", userID).Exec(ctx) }) if err != nil { diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index 19f35f8cdc..650654d8fe 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -558,7 +558,11 @@ func (r *Sessions) Delete(ctx context.Context, customerID, id string) error { return stack.Wrap(fmt.Errorf("store: delete session documents: %w", err)) } _, err = onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { - return db.NewDelete().Model((*AgentSession)(nil)). + // The copies of hidden messages go with the session, and the changes recorded of them, + // which hold the same words, are emptied (forgottenCopies). A data-modifying WITH runs + // whether or not it is read. + changes := forgottenCopies(db, customerID).Where("payload->>'session_id' = ?", id) + return db.NewDelete().With("changes", changes).Model((*AgentSession)(nil)). Where("id = ?", id). Where("customer_id = ?", customerID). Exec(ctx) From 7da2982c2ebe1cac5db55aaebe03093002eb69a3 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 16:41:40 +0000 Subject: [PATCH 2/2] docs(store): join a split comment on ForgetUserSettings --- acceleration/internal/store/forget.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index a60b4231a0..1433dd1116 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -117,9 +117,8 @@ func forgottenCopies(db bun.IDB, customerID string) *bun.UpdateQuery { // back to the app's, replaces their id with replacement on their resets, grants and campaigns, // 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. +// (renamedChanges). A campaign's contacts and their attempts stay: they are the app's data +// about third parties, not the user's. 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 {