Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`):

Expand Down
11 changes: 7 additions & 4 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <app> --user <id>
--actor <who>` 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
Expand All @@ -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:<name>`) and logs them.
A rejected event, a batch refused whole for what it holds (`batch_refused`: a 400, 413 or 422,
Expand Down
24 changes: 22 additions & 2 deletions acceleration/cmd/router/forget_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Expand Down Expand Up @@ -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")
}
32 changes: 24 additions & 8 deletions acceleration/cmd/router/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ const usageCommands = `usage: router usage <command>
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
Expand All @@ -56,9 +58,9 @@ const usageCommands = `usage: router usage <command>
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -498,23 +504,32 @@ 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.
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
Expand Down Expand Up @@ -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
Expand Down
98 changes: 98 additions & 0 deletions acceleration/internal/store/forget.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,101 @@ 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
Comment thread
thesyncim marked this conversation as resolved.
Resolved
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 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 {
Comment thread
thesyncim marked this conversation as resolved.
Resolved
return err
}
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
}
// 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))
}
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{
Comment thread
thesyncim marked this conversation as resolved.
Resolved
"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",
"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, " +
"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",
}
Loading
Loading