From b70f37434ab31975d9531a6fa5ab955170756cb5 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 15:45:43 +0000 Subject: [PATCH 1/2] fix(store): forgetting a user deletes their scheduled tasks and redacts what was recorded of them ForgetUserTasks deletes the user's scheduled tasks, and their runs by cascade, and turns the changes data_changes recorded of those rows into deletes with no payload under their own numbers. A run is the user's by the latest earlier change of its task, or the live task, so a reused task id keeps another user's runs; the user's tasks are locked first so a write the forget waits on is redacted too. forget-user runs it before anything else. forgottenUserTables and keptUserTables list every table with a user_id column, and a test reads the schema to keep them complete. --- acceleration/README.md | 11 +- .../cmd/router/forget_integration_test.go | 24 +- acceleration/cmd/router/usage.go | 32 +- acceleration/internal/store/forget.go | 93 +++++ .../internal/store/forget_user_test.go | 325 ++++++++++++++++++ 5 files changed, 471 insertions(+), 14 deletions(-) create mode 100644 acceleration/internal/store/forget_user_test.go diff --git a/acceleration/README.md b/acceleration/README.md index 6cc88e1156..ab55b5ab3d 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2377,7 +2377,9 @@ router's `getAccount`, `listCredits`, `listTeams` and `listUsageEvents` read the **Forgetting an end user.** A user id is often an email, so an erasure request for one of a customer's users reaches the usage records. `router usage forget-user --app --user --actor ` replaces the id with `forgotten:` and 32 random hex characters (random, since a -hash of an email can be recomputed from it), in order: the requests of every shard; the usage +hash of an email can be recomputed from it), in order, once their scheduled tasks are deleted +with their runs, so none runs again, and the changes recorded of them made deletes: the +requests of every shard; the usage service's events and the user's windows (`POST /v1/manage/users/forget`, one transaction, a window the replacement already has taking the forgotten one's spend), and again after `--settle` (2 minutes) for a batch a shipper read before the shards were rewritten; the user's @@ -2388,9 +2390,10 @@ id on their resets, grants and campaigns. Usage and cost stay under the app. It `forget_user` row per organization. `--dry-run` prints the counts and changes nothing. 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. It covers -the usage records only: sessions, conversation history and `agent_logs` have their own -retention, and work recorded for the id afterwards carries it again. +that one replacement, with the run's own audit row. Sessions, conversation history and +`agent_logs` stay as they are, and work recorded for the id afterwards carries it again; +`keptUserTables` in `internal/store/forget.go` says why for each table with a `user_id` column +that forgetting leaves alone. The service checks its own alerts, sends them to Sentry (`usage_alert:`) and logs them. A rejected event, a batch refused whole for what it holds (`batch_refused`: a 400, 413 or 422, diff --git a/acceleration/cmd/router/forget_integration_test.go b/acceleration/cmd/router/forget_integration_test.go index 3fae660b7c..0c5648b644 100644 --- a/acceleration/cmd/router/forget_integration_test.go +++ b/acceleration/cmd/router/forget_integration_test.go @@ -297,6 +297,10 @@ func (s *ForgetUserSuite) settingsOf(app, user string) { AmountMicros: 500, Reason: "support", Actor: "staff", }, audit)) s.Require().NoError(shared.Campaigns.Insert(s.ctx, &store.Campaign{CustomerID: app, Name: "renewals", APIKey: "key", UserID: user})) + s.Require().NoError(shared.ScheduledTasks.Insert(s.ctx, &store.ScheduledTask{ + ID: "reminder", CustomerID: app, UserID: user, Title: "Stretch", Instructions: "Remind them to stretch.", + StartLocal: time.Now(), Timezone: "UTC", State: store.ScheduledTaskActive, + }, 0)) } // userRows is what the shared database holds of app's user: their own policy, the limits naming @@ -495,7 +499,7 @@ func (s *ForgetUserSuite) TestTheAuditRowNeverNamesTheUser() { } s.Equal(map[string]float64{ "requests": 1, "branch_messages": 1, "events": 1, "windows": 4, "redis_keys": 1, - "policies_deleted": 1, "limits_deleted": 1, "resets": 1, "grants": 1, "campaigns": 1, + "policies_deleted": 1, "limits_deleted": 1, "resets": 1, "grants": 1, "campaigns": 1, "tasks_deleted": 1, "task_changes_redacted": 0, }, counts) var audits []ledger.ManageAudit s.Require().NoError(s.service.Ledger.DB().NewSelect().Model(&audits).Where("action = ?", ledger.ActionForgetUser).Scan(s.ctx)) @@ -512,7 +516,7 @@ func (s *ForgetUserSuite) TestADryRunChangesNothing() { out := s.forget(s.app, person, "--dry-run") - s.Equal("dry run, nothing is changed\nrequests: 2 rows\nbranch snapshots: 0 messages to delete\nusage service: 2 events, 4 windows\nredis: 8 keys\n"+ + s.Equal("dry run, nothing is changed\nscheduled tasks: 1 to delete, 0 recorded changes to redact\nrequests: 2 rows\nbranch snapshots: 0 messages to delete\nusage service: 2 events, 4 windows\nredis: 8 keys\n"+ "shared database: 1 policies and 1 limits to delete; 1 resets, 1 grants and 1 campaigns to rewrite\n", out) s.Equal(person, s.requests()[id].UserID) s.Equal(person, s.events()[id].UserID) @@ -664,3 +668,19 @@ func (s *ForgetUserSuite) TestForgettingAUserNeedsTheManageKey() { s.ErrorContains(err, "ROUTER_USAGE_MANAGE_KEY") } + +func (s *ForgetUserSuite) TestForgettingAUserDeletesTheirScheduledTasks() { + s.recorded(0, s.app, person, 100) + s.Require().NoError(s.shards[0].StartDataCapture(s.ctx, s.app, time.Hour, time.Second)) + s.settingsOf(s.app, person) + s.settingsOf("other-"+s.app, person) + s.Contains(s.forget(s.app, person, "--dry-run"), "\nscheduled tasks: 1 to delete, 1 recorded changes to redact\n") + + out := s.forget(s.app, person) + + s.Contains(out, "\nscheduled tasks: 1 deleted, 1 recorded changes redacted\nrequests: ", "the tasks go first, so none runs during the forget") + _, err := s.shards[0].ScheduledTasks.Get(s.ctx, s.app, "reminder") + s.ErrorIs(err, store.ErrNoScheduledTask) + _, err = s.shards[0].ScheduledTasks.Get(s.ctx, "other-"+s.app, "reminder") + s.Require().NoError(err, "the same user id in another app keeps theirs") +} diff --git a/acceleration/cmd/router/usage.go b/acceleration/cmd/router/usage.go index 3223487574..14b84ab679 100644 --- a/acceleration/cmd/router/usage.go +++ b/acceleration/cmd/router/usage.go @@ -44,7 +44,9 @@ const usageCommands = `usage: router usage or carried in by a data move. Writes the database forget-user --app id --user id --actor who [--dry-run] [--settle 2m] [--replacement id] replace an app's end user id in the usage records with forgotten: - and 32 random hex characters, in order: the requests of every shard; + and 32 random hex characters, in order, after deleting their + scheduled tasks with their runs, so none runs again, and turning + the changes recorded of them into deletes: the requests of every shard; the usage service's events and windows, and again after --settle for a batch shipped in between; the user's spend counters, holds and quota buckets in Redis, by name; and in the shared database @@ -56,9 +58,9 @@ const usageCommands = `usage: router usage the counts and changes nothing. Every step is safe to repeat: to finish a run that stopped, pass the replacement it printed as --replacement, and only what still names the id is rewritten, - under that one replacement. It covers usage records only: - sessions, conversation history and agent_logs have their own - retention. Needs ROUTER_USAGE_URL and ROUTER_USAGE_MANAGE_KEY. + under that one replacement. Sessions, conversation history and + agent_logs stay as they are. Needs ROUTER_USAGE_URL and + ROUTER_USAGE_MANAGE_KEY. Writes the database storage [--hour time] record an hour of every knowledge base's size: the last hour to have ended, or the RFC 3339 hour given. One storage row per knowledge base @@ -468,6 +470,10 @@ func forgetRedis(settings config.Config) ([]rueidis.Client, error) { // count prints what forget would change, and changes nothing. func (f forgetting) count(ctx context.Context) error { + tasks, err := f.store.CountUserTasks(ctx, f.app, f.user) + if err != nil { + return err + } organizations, err := f.store.UserOrganizations(ctx, f.app, f.user, f.replacement) if err != nil { return err @@ -498,16 +504,18 @@ func (f forgetting) count(ctx context.Context) error { if err != nil { return err } - _, err = fmt.Fprintf(f.out, "dry run, nothing is changed\nrequests: %d rows\nbranch snapshots: %d messages to delete\n"+ + _, err = fmt.Fprintf(f.out, "dry run, nothing is changed\nscheduled tasks: %d to delete, %d recorded changes to redact\n"+ + "requests: %d rows\nbranch snapshots: %d messages to delete\n"+ "usage service: %d events, %d windows\nredis: %d keys\n"+ "shared database: %d policies and %d limits to delete; %d resets, %d grants and %d campaigns to rewrite\n", - requests, branches, service.Events, service.Windows, keys, + tasks.Tasks, tasks.Changes, requests, branches, service.Events, service.Windows, keys, settings.Policies, settings.Limits, settings.Resets, settings.Grants, settings.Campaigns) return err } -// forget replaces the id, in the order each step needs: the shards first, so nothing ships the -// id again, and with them the snapshots of messages a rewind hid, which hold the user's words; +// forget replaces the id, in the order each step needs, once the user's scheduled tasks are +// deleted, so none runs and records the id again meanwhile: the shards first, so nothing ships +// the id again, and with them the snapshots of messages a rewind hid, which hold the user's words; // the usage service twice, the second after settle, for a batch read before the // shards were rewritten; Redis once the service writes no counter of the id any more; and the // shared database last, with the audit row in the same transaction. @@ -515,6 +523,13 @@ func (f forgetting) forget(ctx context.Context, settle time.Duration) error { if _, err := fmt.Fprintf(f.out, "replacing the user's id with %s\n", f.replacement); err != nil { return err } + tasks, err := f.store.ForgetUserTasks(ctx, f.app, f.user) + if err != nil { + return err + } + if _, err := fmt.Fprintf(f.out, "scheduled tasks: %d deleted, %d recorded changes redacted\n", tasks.Tasks, tasks.Changes); err != nil { + return err + } organizations, err := f.store.UserOrganizations(ctx, f.app, f.user, f.replacement) if err != nil { return err @@ -574,6 +589,7 @@ func (f forgetting) forget(ctx context.Context, settle time.Duration) error { {Field: "windows", After: first.Windows + second.Windows}, {Field: "redis_keys", After: keys}, }, } + entry.Changes = append(entry.Changes, tasks.AuditChanges()...) settings, err := f.store.ForgetUserSettings(ctx, f.app, f.user, f.replacement, entry) if err != nil { return err diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index 7b48c2eba8..6b6d9151da 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -151,3 +151,96 @@ func (s *Store) ForgetUserSettings(ctx context.Context, appID, userID, replaceme } return counts, nil } + +// UserTasks are what forgetting an app's end user does to their scheduled tasks: the tasks it +// deletes, with their runs, and the changes recorded of those rows that it redacts. +type UserTasks struct { + Tasks int64 `bun:"tasks"` + Changes int64 `bun:"changes"` +} + +// AuditChanges are the counts as an audit entry records them. +func (u UserTasks) AuditChanges() []AuditChange { + return []AuditChange{{Field: "tasks_deleted", After: u.Tasks}, {Field: "task_changes_redacted", After: u.Changes}} +} + +// userTaskChanges picks, as dc, the recorded inserts and updates of an app's end user's tasks +// and runs, by what their payload holds, taking the app and then the user twice. A run is the user's when the latest change +// of a task by its id before the run's names them, or, with none kept, when the task by that id +// here is theirs: an id freed by a delete can be another user's task later. +const userTaskChanges = `dc.customer_id = ? AND ( + (dc.table_name = 'scheduled_tasks' AND dc.payload->>'user_id' = ?) + OR (dc.table_name = 'scheduled_task_runs' AND COALESCE( + (SELECT t.payload->>'user_id' FROM data_changes AS t + WHERE t.customer_id = dc.customer_id AND t.table_name = 'scheduled_tasks' AND t.payload->>'id' = dc.payload->>'task_id' AND t.seq < dc.seq + ORDER BY t.seq DESC LIMIT 1), + (SELECT st.user_id FROM scheduled_tasks AS st WHERE st.customer_id = dc.customer_id AND st.id = dc.payload->>'task_id')) = ?))` + +// CountUserTasks counts what ForgetUserTasks would change. +func (s *Store) CountUserTasks(ctx context.Context, appID, userID string) (UserTasks, error) { + var counts UserTasks + err := s.global.NewRaw(`SELECT + (SELECT count(*) FROM scheduled_tasks WHERE customer_id = ? AND user_id = ?) AS tasks, + (SELECT count(*) FROM data_changes AS dc WHERE `+userTaskChanges+`) AS changes`, + appID, userID, appID, userID, userID). + Scan(ctx, &counts) + if err != nil { + return UserTasks{}, stack.Wrap(fmt.Errorf("store: count user tasks: %w", err)) + } + return counts, nil +} + +// ForgetUserTasks deletes an app's end user's scheduled tasks, and their runs by cascade, so +// none runs for them again. The changes recorded of those rows hold the user's id and words, so +// each becomes a delete of its row, with no payload, under its own number: deleting it would +// raise the oldest number kept, and expire the cursors of other apps' moves. +func (s *Store) ForgetUserTasks(ctx context.Context, appID, userID string) (UserTasks, error) { + var counts UserTasks + err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + // A write to a task that commits while this waits on its row recorded a change the + // redaction would not see: waiting here first lets the next statement see it. + var locked []string + if err := tx.NewSelect().Model((*ScheduledTask)(nil)).Column("id"). + Where("customer_id = ? AND user_id = ?", appID, userID).For("UPDATE").Scan(ctx, &locked); err != nil { + return err + } + redacted, err := tx.NewUpdate().TableExpr("data_changes AS dc").Set("op = ?", ChangeDelete).Set("payload = NULL"). + Where(userTaskChanges, appID, userID, userID).Exec(ctx) + if err != nil { + return err + } + if counts.Changes, err = redacted.RowsAffected(); err != nil { + return err + } + deleted, err := tx.NewDelete().Model((*ScheduledTask)(nil)).Where("customer_id = ? AND user_id = ?", appID, userID).Exec(ctx) + if err != nil { + return err + } + counts.Tasks, err = deleted.RowsAffected() + return err + }) + if err != nil { + return UserTasks{}, stack.Wrap(fmt.Errorf("store: forget user tasks: %w", err)) + } + return counts, nil +} + +// forgottenUserTables are the tables with a user_id column that forgetting a user reaches: the +// requests of every shard (Requests.RenameUser), the tasks ForgetUserTasks deletes and the rows +// ForgetUserSettings deletes or rewrites. +var forgottenUserTables = []string{"requests", "limits", "usage_resets", "limit_grants", "campaigns", "scheduled_tasks"} + +// keptUserTables are the tables with a user_id column that forgetting a user leaves as they are, +// each with why. +var keptUserTables = map[string]string{ + "agent_sessions": "the user's conversations, which the app deletes one by one (DELETE /v1/agents/sessions/{id}), " + + "their tasks with them", + "agent_logs": "the app's log of what its agents did; nothing deletes or rewrites it, forget included", + "call_legs": "the legs of phone calls as billed, with the numbers on them; forget does not rewrite them", + "channel_links": "one-time codes that tie a number texting in to the user, spent once (used_at) " + + "or expired (expires_at), and kept after", + "contact_map": "the addresses the app's agents reach people at and the conversation each carries on, " + + "one linked to the user among them; forget does not clear the link", + "user_phones": "the number the app linked to the user, which it unlinks (PUT /v1/agents/users/{user_id})", + "user_phone_history": "when a link of user_phones began, deleted with it", +} diff --git a/acceleration/internal/store/forget_user_test.go b/acceleration/internal/store/forget_user_test.go new file mode 100644 index 0000000000..575a3b91f5 --- /dev/null +++ b/acceleration/internal/store/forget_user_test.go @@ -0,0 +1,325 @@ +//go:build integration + +package store + +import ( + "encoding/json" + "maps" + "slices" + "time" + + "github.com/uptrace/bun" +) + +// forgetSam forgets the tasks of acme's user sam. +func (s *StoreSuite) forgetSam() UserTasks { + counts, err := s.store.ForgetUserTasks(s.ctx, "acme", "sam") + s.Require().NoError(err) + return counts +} + +// taskChanges are the changes recorded for a customer of scheduled tasks and their runs, each as +// its table, op and the task it is of: the task's id, or the run's task_id. A delete holds no +// payload, so its task is read from the key, and a run's delete names no task. +func (s *StoreSuite) taskChanges(customerID string) []string { + changes, _, err := s.store.Changes(s.ctx, customerID, 0, 1000) + s.Require().NoError(err) + var found []string + for _, change := range changes { + var row struct { + ID string `json:"id"` + TaskID string `json:"task_id"` + } + if change.Op == ChangeDelete { + s.Empty(change.Payload, "a delete holds no row") + } + switch change.Table { + case "scheduled_tasks": + body := change.Payload + if change.Op == ChangeDelete { + body = change.Key + } + s.Require().NoError(json.Unmarshal(body, &row)) + found = append(found, change.Table+" "+change.Op+" "+row.ID) + case "scheduled_task_runs": + if change.Op != ChangeDelete { + s.Require().NoError(json.Unmarshal(change.Payload, &row)) + } + found = append(found, change.Table+" "+change.Op+" "+row.TaskID) + } + } + return found +} + +func (s *StoreSuite) TestForgettingAUserDeletesTheirTasksAndRuns() { + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.task("later", func(task *ScheduledTask) { task.NextRunAt = &due }) + s.task("graces", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = nil }) + s.task("reminder", func(task *ScheduledTask) { task.CustomerID = "globex"; task.NextRunAt = nil }) + + counts := s.forgetSam() + + s.Equal(int64(2), counts.Tasks) + for _, id := range []string{"reminder", "later"} { + _, err := s.store.ScheduledTasks.Get(s.ctx, "acme", id) + s.ErrorIs(err, ErrNoScheduledTask, id) + } + runs, err := s.store.ScheduledTaskRuns.Select(s.ctx, "acme", ScheduledTaskRunFilter{TaskID: "reminder", Limit: 25}) + s.Require().NoError(err) + s.Empty(runs) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Empty(claimed, "no task of theirs is due any more") + _, err = s.store.ScheduledTasks.Get(s.ctx, "acme", "graces") + s.Require().NoError(err, "another user's task stays") + _, err = s.store.ScheduledTasks.Get(s.ctx, "globex", "reminder") + s.Require().NoError(err, "a user of another app by the same id keeps theirs") + left, err := s.store.CountUserTasks(s.ctx, "acme", "sam") + s.Require().NoError(err) + s.Equal(UserTasks{}, left) +} + +func (s *StoreSuite) TestADryRunCountsTheUsersTasks() { + s.task("reminder", nil) + s.task("later", nil) + s.task("graces", func(task *ScheduledTask) { task.UserID = "grace" }) + s.task("reminder", func(task *ScheduledTask) { task.CustomerID = "globex" }) + + counts, err := s.store.CountUserTasks(s.ctx, "acme", "sam") + + s.Require().NoError(err) + s.Equal(int64(2), counts.Tasks) +} + +func (s *StoreSuite) TestForgettingAUserRedactsTheChangesRecordedOfTheirTasks() { + for _, customer := range []string{"acme", "globex"} { + s.Require().NoError(s.store.StartDataCapture(s.ctx, customer, time.Hour, time.Second)) + } + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + s.task("graces", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = &due }) + // Another app's task of a user by the same id, under the id of another user's task here. + s.task("graces", func(task *ScheduledTask) { task.CustomerID = "globex"; task.NextRunAt = nil }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Contains(s.taskChanges("acme"), "scheduled_task_runs insert reminder", "the run's insert was recorded") + counted, err := s.store.CountUserTasks(s.ctx, "acme", "sam") + s.Require().NoError(err) + + counts := s.forgetSam() + + s.Equal(UserTasks{Tasks: 1, Changes: 3}, counts, "their insert, the claim's update and the run's insert") + s.Equal(counts, counted) + s.ElementsMatch([]string{ + "scheduled_tasks insert graces", "scheduled_tasks update graces", "scheduled_task_runs insert graces", + "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + }, s.taskChanges("acme"), "each change of theirs is a delete under its own number, and the deletes are recorded after them") + s.Equal([]string{"scheduled_tasks insert graces"}, s.taskChanges("globex")) +} + +func (s *StoreSuite) TestForgettingAUserRedactsTheChangesOfTheRunsOfATaskTheyDeletedBefore() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().NoError(s.store.ScheduledTasks.Delete(s.ctx, "acme", "reminder")) + + counts := s.forgetSam() + + s.ElementsMatch([]string{ + "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + }, s.taskChanges("acme")) + s.Equal(UserTasks{Changes: 3}, counts, "the deletes already recorded are not counted") +} + +func (s *StoreSuite) TestForgettingAUserRedactsTheChangesOfTheirRunsWhenThoseOfTheTaskWerePruned() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + _, err = s.store.global.NewDelete().TableExpr("data_changes").Where("table_name = 'scheduled_tasks'").Exec(s.ctx) + s.Require().NoError(err) + s.Require().Equal([]string{"scheduled_task_runs insert reminder"}, s.taskChanges("acme")) + + s.forgetSam() + + s.ElementsMatch([]string{"scheduled_task_runs delete ", "scheduled_task_runs delete ", "scheduled_tasks delete reminder"}, s.taskChanges("acme")) +} + +func (s *StoreSuite) TestForgettingAUserKeepsTheRunsOfAnotherUsersTaskUnderAnIDTheyUsedBefore() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().NoError(s.store.ScheduledTasks.Delete(s.ctx, "acme", "reminder")) + s.task("reminder", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = &due }) + _, err = s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + + s.forgetSam() + + s.ElementsMatch([]string{ + "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + "scheduled_tasks delete reminder", "scheduled_task_runs delete ", + "scheduled_tasks insert reminder", "scheduled_tasks update reminder", "scheduled_task_runs insert reminder", + }, s.taskChanges("acme"), "sam's run goes by the task it was a run of, and grace's task and run keep their changes") + _, err = s.store.ScheduledTasks.Get(s.ctx, "acme", "reminder") + s.Require().NoError(err) +} + +func (s *StoreSuite) TestForgettingAUserKeepsTheRunsOfAnotherUsersTaskWhoseChangesWerePruned() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + due := s.base.Add(-time.Minute) + s.task("x", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = &due }) + s.task("x", func(task *ScheduledTask) { task.CustomerID = "globex"; task.NextRunAt = nil }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + _, err = s.store.global.NewDelete().TableExpr("data_changes").Where("table_name = 'scheduled_tasks'").Exec(s.ctx) + s.Require().NoError(err) + + s.forgetSam() + + s.Equal([]string{"scheduled_task_runs insert x"}, s.taskChanges("acme"), "a task by the same id in another app is not this one") +} + +func (s *StoreSuite) TestForgettingAUserKeepsTheRunsOfAnotherUsersTaskNamedLikeTheirSession() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + s.opened("x", "acme", s.base, func(session *AgentSession) { session.UserID = "sam" }) + due := s.base.Add(-time.Minute) + s.task("x", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + + s.forgetSam() + + s.ElementsMatch([]string{"scheduled_tasks insert x", "scheduled_tasks update x", "scheduled_task_runs insert x"}, s.taskChanges("acme")) +} + +func (s *StoreSuite) TestATaskWriteTheForgetWaitsOnIsRedactedToo() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = nil }) + writing, err := s.store.global.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer writing.Rollback() //nolint:errcheck // committed below; this only ends a failed test's transaction + _, err = writing.ExecContext(s.ctx, "UPDATE scheduled_tasks SET title = 'Stretch twice' WHERE customer_id = 'acme' AND id = 'reminder'") + s.Require().NoError(err) + + forgotten := make(chan error, 1) + go func() { + _, err := s.store.ForgetUserTasks(s.ctx, "acme", "sam") + forgotten <- err + }() + s.Require().Eventually(func() bool { + var waiting bool + s.Require().NoError(s.store.global.NewRaw(`SELECT EXISTS (SELECT 1 FROM pg_stat_activity +WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%scheduled_tasks%')`).Scan(s.ctx, &waiting)) + return waiting + }, 10*time.Second, 10*time.Millisecond, "the forget waits on the task's row") + s.Require().NoError(writing.Commit()) + s.Require().NoError(<-forgotten) + + s.Equal([]string{"scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_tasks delete reminder"}, + s.taskChanges("acme"), "the write's change names them no more") +} + +func (s *StoreSuite) TestAFollowerOfAnotherAppReadsOnFromItsCursorAfterAUserIsForgotten() { + for _, customer := range []string{"acme", "globex"} { + s.Require().NoError(s.store.StartDataCapture(s.ctx, customer, time.Hour, time.Second)) + } + s.task("first", func(task *ScheduledTask) { task.CustomerID = "globex"; task.UserID = "kim"; task.NextRunAt = nil }) + _, cursor, err := s.store.Changes(s.ctx, "globex", 0, 1000) + s.Require().NoError(err) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = nil }) + s.task("second", func(task *ScheduledTask) { task.CustomerID = "globex"; task.UserID = "kim"; task.NextRunAt = nil }) + // The follower's own change has aged out, as the prune drops the oldest changes kept. + _, err = s.store.global.NewDelete().TableExpr("data_changes").Where("seq <= ?", cursor).Exec(s.ctx) + s.Require().NoError(err) + + s.forgetSam() + + changes, _, err := s.store.Changes(s.ctx, "globex", cursor, 1000) + s.Require().NoError(err, "the follower's cursor has not expired") + s.Require().Len(changes, 1) + s.Equal(ChangeInsert, changes[0].Op) + s.JSONEq(`{"customer_id": "globex", "id": "second"}`, string(changes[0].Key)) +} + +func (s *StoreSuite) TestForgettingAUserKeepsTheChangesOfOtherTablesThatNameThem() { + if s.store.Sharded() { + s.T().Skip("a shard's own tables record no changes (watchDataChanges)") + } + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + s.opened("one", "acme", s.base, func(session *AgentSession) { session.UserID = "sam" }) + + s.forgetSam() + + changes, _, err := s.store.Changes(s.ctx, "acme", 0, 1000) + s.Require().NoError(err) + s.True(slices.ContainsFunc(changes, func(change DataChange) bool { + return change.Table == "agent_sessions" && change.Op == ChangeInsert + }), "the session stays, and so does its change") +} + +func (s *StoreSuite) TestEveryTableWithAUserIDIsForgottenOrKeptForAReason() { + var found []string + for _, db := range []*bun.DB{s.store.global, s.store.shard} { + var tables []string + s.Require().NoError(db.NewRaw(`SELECT c.relname FROM pg_attribute AS a +JOIN pg_class AS c ON c.oid = a.attrelid +WHERE a.attname = 'user_id' AND NOT a.attisdropped AND c.relkind IN ('r', 'p') AND NOT c.relispartition + AND c.relnamespace = current_schema()::regnamespace`).Scan(s.ctx, &tables)) + found = append(found, tables...) + } + slices.Sort(found) + found = slices.Compact(found) + + for table, reason := range keptUserTables { + s.NotEmpty(reason, table) + s.NotContains(forgottenUserTables, table, "a table is forgotten or kept, not both") + } + listed := slices.Sorted(slices.Values(append(slices.Clone(forgottenUserTables), slices.Collect(maps.Keys(keptUserTables))...))) + s.Equal(found, listed, "a table with a user_id column goes in forgottenUserTables or keptUserTables") +} + +// tasksOn counts a customer's scheduled tasks and runs on a deployment. +func (s *DataMoveSuite) tasksOn(store *Store, customerID string) (tasks, runs int) { + s.Require().NoError(store.GlobalDB().QueryRowContext(s.ctx, + "SELECT (SELECT count(*) FROM scheduled_tasks WHERE customer_id = ?), (SELECT count(*) FROM scheduled_task_runs WHERE customer_id = ?)", + customerID, customerID).Scan(&tasks, &runs)) + return tasks, runs +} + +func (s *DataMoveSuite) TestAMoveFollowingAForgottenUserEndsWithNoneOfTheirTasks() { + s.capture("acme") + s.seedScheduledTask("st-before", "acme", ScheduledTaskActive) + // Into the same app id, as a move between deployments is: a task's key names its customer. + cursor := s.move("acme", "acme") + s.seedScheduledTask("st-after", "acme", ScheduledTaskActive) + _, err := s.source.ForgetUserTasks(s.ctx, "acme", "sam") + s.Require().NoError(err) + + changes, _, err := s.source.Changes(s.ctx, "acme", cursor, 100) + s.Require().NoError(err) + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", changes)) + tasks, runs := s.tasksOn(s.destination, "acme") + s.Zero(tasks) + s.Zero(runs) + + every, _, err := s.source.Changes(s.ctx, "acme", 0, 100) + s.Require().NoError(err) + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", every), "a follower starting over replays the redacted changes") + tasks, runs = s.tasksOn(s.destination, "acme") + s.Zero(tasks) + s.Zero(runs) +} From 0ca56d05b9c17a67c67e9efd308ad7b632c3e62c Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 19:25:24 +0000 Subject: [PATCH 2/2] fix(store): forgetting a user's tasks waits on their runs and deletes in the redaction's snapshot --- .claude/skills/scheduled-tasks/SKILL.md | 1 + acceleration/internal/store/forget.go | 35 +++++---- .../internal/store/forget_user_test.go | 78 ++++++++++++++++++- 3 files changed, 98 insertions(+), 16 deletions(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 1cf299b9fa..be55fa405f 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -182,6 +182,7 @@ Read the task, then its runs, then the logs, in that order. | The tools | the model never calls `schedule_task` | `scheduling.enabled` off, incognito, a guest or anonymous caller, or a `noauth` router | | Old history gone | a completed or failed task 404, or old runs missing | A daily job deletes runs finished over 90 days ago, and completed or failed tasks over 90 days old (`ScheduledTasksKept`); active and paused tasks stay | | Session deleted | task 404 | Deleting a session deletes the tasks made in it or following up in it (`internal/api/session_delete.go:47`) | +| User forgotten | task 404, its runs gone | `router usage forget-user` deleted every task of that user in the app, with its runs, and redacted the changes recorded of them (`ForgetUserTasks`) | Run `error` codes (`internal/scheduling/scheduler.go:105`): diff --git a/acceleration/internal/store/forget.go b/acceleration/internal/store/forget.go index 6b6d9151da..078bce1161 100644 --- a/acceleration/internal/store/forget.go +++ b/acceleration/internal/store/forget.go @@ -197,27 +197,30 @@ func (s *Store) CountUserTasks(ctx context.Context, appID, userID string) (UserT func (s *Store) ForgetUserTasks(ctx context.Context, appID, userID string) (UserTasks, error) { var counts UserTasks err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - // A write to a task that commits while this waits on its row recorded a change the - // redaction would not see: waiting here first lets the next statement see it. + // A write to a task or a run that commits while this waits on its row recorded a change + // the redaction would not see: waiting here first lets the next statement see it. Some + // run writes lock only the run (TakeCall), so the runs are locked too, after their + // tasks, as Claim and Finish lock them. var locked []string if err := tx.NewSelect().Model((*ScheduledTask)(nil)).Column("id"). Where("customer_id = ? AND user_id = ?", appID, userID).For("UPDATE").Scan(ctx, &locked); err != nil { return err } - redacted, err := tx.NewUpdate().TableExpr("data_changes AS dc").Set("op = ?", ChangeDelete).Set("payload = NULL"). - Where(userTaskChanges, appID, userID, userID).Exec(ctx) - if err != nil { + var runs []string + if err := tx.NewSelect().Model((*ScheduledTaskRun)(nil)).Column("id"). + Where("customer_id = ? AND task_id IN (?)", appID, bun.In(locked)).For("UPDATE").Scan(ctx, &runs); err != nil { return err } - if counts.Changes, err = redacted.RowsAffected(); err != nil { - return err - } - deleted, err := tx.NewDelete().Model((*ScheduledTask)(nil)).Where("customer_id = ? AND user_id = ?", appID, userID).Exec(ctx) - if err != nil { - return err - } - counts.Tasks, err = deleted.RowsAffected() - return err + // One statement, so the delete and the redaction read one snapshot: a task of the + // user's that commits between two statements would be deleted with its changes kept. + // The redaction's fallback to the live task reads that snapshot, from before the delete. + redacted := tx.NewUpdate().Model((*dataChange)(nil)).Set("op = ?", ChangeDelete).Set("payload = NULL"). + Where(userTaskChanges, appID, userID, userID).Returning("1") + deleted := tx.NewDelete().Model((*ScheduledTask)(nil)).Where("customer_id = ? AND user_id = ?", appID, userID).Returning("1") + return tx.NewSelect().With("deleted", deleted).With("redacted", redacted). + ColumnExpr("(SELECT count(*) FROM deleted) AS tasks"). + ColumnExpr("(SELECT count(*) FROM redacted) AS changes"). + Scan(ctx, &counts) }) if err != nil { return UserTasks{}, stack.Wrap(fmt.Errorf("store: forget user tasks: %w", err)) @@ -236,7 +239,9 @@ var keptUserTables = map[string]string{ "agent_sessions": "the user's conversations, which the app deletes one by one (DELETE /v1/agents/sessions/{id}), " + "their tasks with them", "agent_logs": "the app's log of what its agents did; nothing deletes or rewrites it, forget included", - "call_legs": "the legs of phone calls as billed, with the numbers on them; forget does not rewrite them", + "calls": "the call's user from before a call belonged to its session, written only by the release before; " + + "kept for that release, and dropped in a later one", + "call_legs": "the legs of phone calls as billed, with the numbers on them; forget does not rewrite them", "channel_links": "one-time codes that tie a number texting in to the user, spent once (used_at) " + "or expired (expires_at), and kept after", "contact_map": "the addresses the app's agents reach people at and the conversation each carries on, " + diff --git a/acceleration/internal/store/forget_user_test.go b/acceleration/internal/store/forget_user_test.go index 575a3b91f5..ce357d5757 100644 --- a/acceleration/internal/store/forget_user_test.go +++ b/acceleration/internal/store/forget_user_test.go @@ -195,9 +195,10 @@ func (s *StoreSuite) TestForgettingAUserKeepsTheRunsOfAnotherUsersTaskNamedLikeT s.T().Skip("a shard's own tables record no changes (watchDataChanges)") } s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) - s.opened("x", "acme", s.base, func(session *AgentSession) { session.UserID = "sam" }) due := s.base.Add(-time.Minute) s.task("x", func(task *ScheduledTask) { task.UserID = "grace"; task.NextRunAt = &due }) + // Opened after the task, so the session's change is the latest one by that id before the run's. + s.opened("x", "acme", s.base, func(session *AgentSession) { session.UserID = "sam" }) _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) s.Require().NoError(err) @@ -233,6 +234,81 @@ WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE ' s.taskChanges("acme"), "the write's change names them no more") } +// forgetWaiting reports whether a ForgetUserTasks is waiting on a lock: a row, or an advisory one +// a test holds. +func (s *StoreSuite) forgetWaiting() bool { + var waiting bool + s.Require().NoError(s.store.global.NewRaw(`SELECT EXISTS (SELECT 1 FROM pg_stat_activity +WHERE datname = current_database() AND pid <> pg_backend_pid() AND wait_event_type = 'Lock' + AND (query LIKE '%scheduled_task%' OR query LIKE '%data_changes%'))`).Scan(s.ctx, &waiting)) + return waiting +} + +func (s *StoreSuite) TestARunWriteTheForgetWaitsOnIsRedactedToo() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + due := s.base.Add(-time.Minute) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = &due }) + _, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + // As TakeCall writes it: the run's row alone, not its task's. + writing, err := s.store.global.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer writing.Rollback() //nolint:errcheck // committed below; this only ends a failed test's transaction + _, err = writing.ExecContext(s.ctx, "UPDATE scheduled_task_runs SET session_id = 'call' WHERE customer_id = 'acme' AND task_id = 'reminder'") + s.Require().NoError(err) + + forgotten := make(chan error, 1) + go func() { + _, err := s.store.ForgetUserTasks(s.ctx, "acme", "sam") + forgotten <- err + }() + s.Require().Eventually(s.forgetWaiting, 10*time.Second, 10*time.Millisecond, "the forget waits on the run's row") + s.Require().NoError(writing.Commit()) + s.Require().NoError(<-forgotten) + + s.ElementsMatch([]string{ + "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", + "scheduled_task_runs delete ", "scheduled_task_runs delete ", "scheduled_task_runs delete ", + }, s.taskChanges("acme"), "the run write's change, which holds the task's instructions, names them no more") +} + +func (s *StoreSuite) TestATaskOfTheUsersMadeWhileTheForgetRedactsIsKeptWithItsChanges() { + s.Require().NoError(s.store.StartDataCapture(s.ctx, "acme", time.Hour, time.Second)) + s.task("reminder", func(task *ScheduledTask) { task.NextRunAt = nil }) + // The forget stops once it has redacted, until this connection lets it go on. + _, err := s.store.global.ExecContext(s.ctx, `CREATE FUNCTION forget_paused() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN PERFORM pg_advisory_xact_lock(hashtextextended('forget_paused', 0)); RETURN NULL; END $$`) + s.Require().NoError(err) + defer func() { + _, err := s.store.global.ExecContext(s.ctx, "DROP FUNCTION forget_paused() CASCADE") + s.Require().NoError(err) + }() + _, err = s.store.global.ExecContext(s.ctx, + "CREATE TRIGGER forget_paused AFTER UPDATE ON data_changes FOR EACH STATEMENT EXECUTE FUNCTION forget_paused()") + s.Require().NoError(err) + holding, err := s.store.global.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer holding.Rollback() //nolint:errcheck // rolled back below; this only ends a failed test's transaction + _, err = holding.ExecContext(s.ctx, "SELECT pg_advisory_xact_lock(hashtextextended('forget_paused', 0))") + s.Require().NoError(err) + + forgotten := make(chan error, 1) + go func() { + _, err := s.store.ForgetUserTasks(s.ctx, "acme", "sam") + forgotten <- err + }() + s.Require().Eventually(s.forgetWaiting, 10*time.Second, 10*time.Millisecond, "the forget waits once it has redacted") + s.task("late", func(task *ScheduledTask) { task.NextRunAt = nil }) + s.Require().NoError(holding.Rollback()) + s.Require().NoError(<-forgotten) + + _, err = s.store.ScheduledTasks.Get(s.ctx, "acme", "late") + s.Require().NoError(err, "a task the forget's snapshot did not see is not deleted") + s.ElementsMatch([]string{ + "scheduled_tasks delete reminder", "scheduled_tasks delete reminder", "scheduled_tasks insert late", + }, s.taskChanges("acme"), "no task is deleted with a change naming them kept") +} + func (s *StoreSuite) TestAFollowerOfAnotherAppReadsOnFromItsCursorAfterAUserIsForgotten() { for _, customer := range []string{"acme", "globex"} { s.Require().NoError(s.store.StartDataCapture(s.ctx, customer, time.Hour, time.Second))