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
10 changes: 7 additions & 3 deletions acceleration/internal/store/branch_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
48 changes: 48 additions & 0 deletions acceleration/internal/store/branch_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package store

import (
"fmt"
"slices"
"time"
)

Expand Down Expand Up @@ -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")
}
41 changes: 39 additions & 2 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Comment thread
thesyncim marked this conversation as resolved.
Resolved
}
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 }

Expand Down
75 changes: 72 additions & 3 deletions acceleration/internal/store/datamove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Comment thread
thesyncim marked this conversation as resolved.
Resolved
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")

Expand Down Expand Up @@ -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
Expand Down
35 changes: 31 additions & 4 deletions acceleration/internal/store/forget.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,37 @@ 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
// campaign's contacts and their attempts stay: they are the app's data about third parties,
// not the user's.
// 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) {
var counts UserSettings
err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
Expand All @@ -104,7 +130,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 {
Expand Down
Loading
Loading