diff --git a/acceleration/cmd/router/replicate.go b/acceleration/cmd/router/replicate.go index 9e0df36d17..c8ca582d0b 100644 --- a/acceleration/cmd/router/replicate.go +++ b/acceleration/cmd/router/replicate.go @@ -345,8 +345,11 @@ func follow(ctx context.Context, source *deployment, pgStore *store.Store, reser if err := pgStore.ApplyChanges(ctx, customerID, page.Changes); err != nil { return err } + logger.Info("caught up on changes", "changes", len(page.Changes), "cursor", page.Cursor) + } + // A page can move the cursor with no change on it: past changes the source leaves out. + if page.Cursor > cursor { cursor = page.Cursor - logger.Info("caught up on changes", "changes", len(page.Changes), "cursor", cursor) } // Saved after every read rather than only one that brought changes: a read is what keeps // the source recording the app's changes (carryOn). diff --git a/acceleration/cmd/router/replicate_repeat_integration_test.go b/acceleration/cmd/router/replicate_repeat_integration_test.go index c760b34e6d..019a12d968 100644 --- a/acceleration/cmd/router/replicate_repeat_integration_test.go +++ b/acceleration/cmd/router/replicate_repeat_integration_test.go @@ -393,6 +393,24 @@ func (s *ReplicateRepeatSuite) TestARunThatBringsNoChangesStillSavesWhenItReadTh s.WithinDuration(time.Now(), s.saved().ReadAt, time.Minute, "the read kept the source recording, so the next run is not refused") } +// The source leaves an organization's policy under the app's id out of the changes, and the +// cursor it answers past it is where the next run starts. +func (s *ReplicateRepeatSuite) TestARunWhosePageCarriesNoChangeStillMovesItsCursor() { + s.recorded(1) + s.Require().NoError(s.once("acme", false)) + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, updated_at) VALUES ('organization', 'acme', now())") + s.Require().NoError(err) + var last int64 + s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx, + "SELECT max(seq) FROM data_changes WHERE customer_id = 'acme'").Scan(&last)) + + s.Require().NoError(s.once("acme", false)) + + s.Require().NotNil(s.saved().Cursor) + s.Equal(last, *s.saved().Cursor) +} + func (s *ReplicateRepeatSuite) TestAnOrganizationsPolicyUnderTheAppsIDIsNotTheAppsData() { // The export carries only app policies, so an organization's under the same id is not a copy. _, err := s.target.GlobalDB().ExecContext(s.ctx, diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 1a9dc183ee..96d3f8186d 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -721,7 +721,12 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an // is what lets a move be resumed after it was interrupted. func (s *Store) ImportRow(ctx context.Context, customerID, table string, row json.RawMessage) error { spec, _ := dataTableByName(table) - return s.importRow(ctx, s.sideOf(spec), customerID, table, row) + var stale []string + if err := s.importRow(ctx, s.sideOf(spec), customerID, table, row, &stale); err != nil { + return err + } + s.forget(ctx, stale...) + return nil } // sideOf is the database a table's rows are written to here: this shard's or the shared one. @@ -738,7 +743,9 @@ func (s *Store) sideOf(table dataTable) *bun.DB { var lineColumns = []string{"stream_trunk_id", "stream_route_id", "stream_app_pk", "stream_call_id", "stream_call_type", "attached_at", "config_id"} -func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage) error { +// importRow writes one row of an export or of a change (ImportRow). It adds to stale the cached +// values the row was and is read through, for the caller to forget once the write has committed. +func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage, stale *[]string) error { if slices.Contains(retiredTables, table) { return nil } @@ -925,10 +932,22 @@ 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) + // A row renamed, or a skill moved to another config, is cached under what it was too. + var was []byte + if cachedByID(table) { + err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT to_jsonb(h) FROM %s AS h WHERE h.id::text = ?::jsonb ->> 'id' AND h.customer_id = ?", + spec.name), string(row), customerID).Scan(&was) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("store: import %s: %w", table, err) + } + } + result, err := db.ExecContext(ctx, query, args...) if err != nil { return fmt.Errorf("store: import %s: %w", table, err) } + *stale = append(*stale, cachedKeys(customerID, table, was)...) + *stale = append(*stale, cachedKeys(customerID, table, row)...) written, err := result.RowsAffected() if err != nil { return stack.Wrap(fmt.Errorf("store: import %s: %w", table, err)) @@ -967,6 +986,48 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str // 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") +// cachedByID is whether a moved table's rows are cached by their id and something else they +// hold, which a write can change. +func cachedByID(table string) bool { + return slices.Contains([]string{"agent_configs", "router_configs", "skills", "voices"}, table) +} + +// cachedKeys are the cached values a row of a moved table, as row reads under customerID, is read +// through: what the table's own writes forget (AgentConfigs.Update and its siblings). An app's +// policy is cached by its app alone, so any row of it names the same values. +func cachedKeys(customerID, table string, row []byte) []string { + if table == "policies" { + return policyKeys(ScopeApp, customerID) + } + if !cachedByID(table) || len(row) == 0 { + return nil + } + // The columns are text, which jsonb_populate_record also fills from a number, so a value is + // read as the text it is written as. A row that is not a JSON object was refused before it + // was written. + var fields map[string]any + decoder := json.NewDecoder(bytes.NewReader(row)) + decoder.UseNumber() + if decoder.Decode(&fields) != nil { + return nil + } + text := func(column string) string { + if value, found := fields[column]; found && value != nil { + return fmt.Sprint(value) + } + return "" + } + switch table { + case "agent_configs": + return []string{agentConfigKey(customerID, text("id")), agentConfigNameKey(customerID, text("name"))} + case "router_configs": + return []string{routerConfigKey(customerID, text("id")), routerConfigNameKey(customerID, text("name"))} + case "voices": + return []string{voiceKey(customerID, text("id")), voiceNameKey(customerID, text("name"))} + } + return []string{skillsKey(customerID, text("config_id"))} +} + // validated is a model that refuses a row the API would not store. type validated interface{ Validate() error } @@ -1734,10 +1795,13 @@ func (s *Store) Changes(ctx context.Context, customerID string, after int64, lim return nil, 0, ErrChangesExpired } + // A policy is recorded under its scope id whatever its scope, so an organization's sharing the + // customer's id is left out, as an export leaves it out. It is left out before the limit, so a + // page is as full as the customer's own changes make it. rows, err := tx.QueryContext(ctx, ` SELECT seq, table_name, op, key, payload, at FROM data_changes -WHERE customer_id = ? AND seq > ? AND seq <= ? +WHERE customer_id = ? AND seq > ? AND seq <= ? AND (table_name <> 'policies' OR key ->> 'scope' = 'app') ORDER BY seq LIMIT ?`, customerID, after, mark, limit) if err != nil { @@ -1765,6 +1829,15 @@ LIMIT ?`, customerID, after, mark, limit) if err := rows.Err(); err != nil { return nil, 0, fmt.Errorf("store: changes: %w", err) } + // A page that is not full holds every change of theirs up to the mark, so the cursor moves past + // the ones left out too: one left ahead of it would be pruned in time and expire the cursor. + if len(changes) < limit { + if err := tx.QueryRowContext(ctx, + "SELECT COALESCE(MAX(seq), ?) FROM data_changes WHERE customer_id = ? AND seq > ? AND seq <= ?", + cursor, customerID, cursor, mark).Scan(&cursor); err != nil { + return nil, 0, fmt.Errorf("store: changes: %w", err) + } + } return changes, cursor, nil } @@ -1796,26 +1869,49 @@ func (s *Store) applyChanges(ctx context.Context, db *bun.DB, customerID string, if len(changes) == 0 { return nil } - return db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + var stale []string + err := db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { for _, change := range changes { + if !appPolicy(change) { + continue + } switch change.Op { case ChangeDelete: - if err := s.deleteRow(ctx, tx, customerID, change); err != nil { + if err := s.deleteRow(ctx, tx, customerID, change, &stale); err != nil { return err } default: - if err := s.importRow(ctx, tx, customerID, change.Table, change.Payload); err != nil { + if err := s.importRow(ctx, tx, customerID, change.Table, change.Payload, &stale); err != nil { return err } } } return nil }) + if err != nil { + return err + } + s.forget(ctx, stale...) + return nil +} + +// appPolicy is false for a change to a policy of another scope than an app's. The trigger records +// a policy under its scope id whatever its scope, so an organization's that shares an id with the +// app is recorded under the app, and replaying it would write it over the app's (identity). +func appPolicy(change DataChange) bool { + if change.Table != "policies" { + return true + } + var key struct { + Scope string `json:"scope"` + } + return json.Unmarshal(change.Key, &key) == nil && key.Scope == string(ScopeApp) } // deleteRow removes what a delete change names, scoped to the customer replaying it so a -// change carrying somebody else's key cannot reach their row. -func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, change DataChange) error { +// change carrying somebody else's key cannot reach their row. It adds to stale the cached values +// the row was read through. +func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, change DataChange, stale *[]string) error { if slices.Contains(retiredTables, change.Table) { return nil } @@ -1845,6 +1941,11 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch args = append(args, string(change.Key)) } else { for _, column := range shape.keys { + // The customer in the key is the source's, which a move under another id does not + // keep: the customer's own condition below is what scopes the delete. + if column == spec.customer { + continue + } conditions = append(conditions, fmt.Sprintf("t.%s::text = (?::jsonb ->> '%s')", column, column)) args = append(args, string(change.Key)) } @@ -1865,7 +1966,33 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch args = append(args, customerID) query := fmt.Sprintf("DELETE FROM %s AS t WHERE %s", spec.name, strings.Join(conditions, " AND ")) - if _, err := db.ExecContext(ctx, query, args...); err != nil { + if !cachedByID(change.Table) { + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return fmt.Errorf("store: delete %s: %w", change.Table, err) + } + deleted, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("store: delete %s: %w", change.Table, err) + } + if deleted > 0 { + *stale = append(*stale, cachedKeys(customerID, change.Table, nil)...) + } + return nil + } + rows, err := db.QueryContext(ctx, query+" RETURNING to_jsonb(t)", args...) + if err != nil { + return fmt.Errorf("store: delete %s: %w", change.Table, err) + } + defer rows.Close() + for rows.Next() { + var row []byte + if err := rows.Scan(&row); err != nil { + return fmt.Errorf("store: delete %s: %w", change.Table, err) + } + *stale = append(*stale, cachedKeys(customerID, change.Table, row)...) + } + if err := rows.Err(); err != nil { return fmt.Errorf("store: delete %s: %w", change.Table, err) } return nil diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 288b1b32ac..7bdbbe40a6 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -14,6 +14,7 @@ import ( "os" "regexp" "slices" + "strconv" "strings" "sync" "testing" @@ -105,18 +106,45 @@ func (s *DataMoveSuite) SetupTest() { // move copies everything a customer has to the other deployment, the way the replicate // command does, and returns the cursor their changes carry on from. func (s *DataMoveSuite) move(from, to string) int64 { + return s.moveTo(s.destination, from, to) +} + +// moveTo is move into the destination as the store given reads it. +func (s *DataMoveSuite) moveTo(destination *Store, from, to string) int64 { export := s.export(from) - reservation, err := s.destination.ReserveImportedIDs(s.ctx) + reservation, err := destination.ReserveImportedIDs(s.ctx) s.Require().NoError(err) for _, row := range export.rows { encoded, err := json.Marshal(row.row) s.Require().NoError(err) s.Require().NoError(reservation.Cover(s.ctx, row.table, encoded)) - s.Require().NoError(s.destination.ImportRow(s.ctx, to, row.table, encoded)) + s.Require().NoError(destination.ImportRow(s.ctx, to, row.table, encoded)) } return export.cursor } +// cachedDestination is the destination as a router with Redis reads it, where a row once +// served stays served until a write forgets it. Its customers need ids of their own, since +// Redis keeps what an earlier test cached. +func (s *DataMoveSuite) cachedDestination() *Store { + address := os.Getenv(redisAddressVar) + if address == "" { + s.T().Skipf("%s not set: the cache is what this test reads", redisAddressVar) + } + store, err := OpenShards(Options{DSN: elsewhere(os.Getenv(DSNEnvVar), "moved"), Redis: Redis{Address: address}}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(store.Close()) }) + return store +} + +// replay applies to the destination given what changed at the source since a cursor. +func (s *DataMoveSuite) replay(destination *Store, from, to string, cursor int64) { + changes, _, err := s.source.Changes(s.ctx, from, cursor, 100) + s.Require().NoError(err) + s.Require().NotEmpty(changes) + s.Require().NoError(destination.ApplyChanges(s.ctx, to, changes)) +} + // moveEdited is move with the rows of one table edited first, as a file the importer wrote // itself would carry them. func (s *DataMoveSuite) moveEdited(from, to, table string, edit func(map[string]any)) { @@ -1703,6 +1731,418 @@ func (s *DataMoveSuite) TestOnlyTheAppsOwnPolicyMoves() { s.Equal("app", policies[0]["scope"]) } +// A scheduled task is keyed by its customer and its id, and the customer in a delete's key is +// the source's. +func (s *DataMoveSuite) TestADeletedTaskIsReplayedUnderTheIDTheAppMovedTo() { + s.capture("acme") + s.seedScheduledTask("cancelled", "acme", ScheduledTaskActive) + s.seedScheduledTask("kept", "acme", ScheduledTaskActive) + cursor := s.move("acme", "moved") + + _, err := s.source.GlobalDB().ExecContext(s.ctx, "DELETE FROM scheduled_tasks WHERE id = 'cancelled'") + s.Require().NoError(err) + s.replay(s.destination, "acme", "moved", cursor) + + var left []string + s.Require().NoError(s.destination.GlobalDB().NewSelect().Table("scheduled_tasks").Column("id"). + Where("customer_id = 'moved'").Scan(s.ctx, &left)) + s.Equal([]string{"kept"}, left) +} + +// An organization's policy is recorded under its id, which can be an app's too. +func (s *DataMoveSuite) TestAnOrganizationsPolicyIsNotReplayedOverTheAppsOfTheSameID() { + s.capture("acme") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + s.move("acme", "acme") + + // As a source from before Changes left such a change out records it. + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", []DataChange{{ + Seq: 1, Table: "policies", Op: ChangeInsert, At: time.Now(), + Key: json.RawMessage(`{"scope": "organization", "scope_id": "acme"}`), + Payload: json.RawMessage(`{"scope": "organization", "scope_id": "acme", "document": {"prompt_injection": false}, "updated_at": "2026-11-23T00:00:00Z"}`), + }})) + + document, err := s.destination.Policies.Get(s.ctx, ScopeApp, "acme") + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection) + s.True(*document.PromptInjection) +} + +// A change whose key names no scope is no app's either. +func (s *DataMoveSuite) TestAPolicyChangeNamingNoScopeIsNotReplayed() { + _, err := s.destination.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", []DataChange{{ + Seq: 1, Table: "policies", Op: ChangeUpdate, At: time.Now(), Key: json.RawMessage(`{}`), + Payload: json.RawMessage(`{"scope": "organization", "scope_id": "acme", "document": {"prompt_injection": false}, "updated_at": "2026-11-23T00:00:00Z"}`), + }})) + + document, err := s.destination.Policies.Get(s.ctx, ScopeApp, "acme") + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection) + s.True(*document.PromptInjection) +} + +// The organization's policy is left out before the limit, so the page still holds the app's +// own change after it, and a follower is not told it caught up early. +// The organization's policy is still one of the app's rows in the feed, so pruning it would expire +// a cursor left behind it. +func (s *DataMoveSuite) TestACursorPastAnOrganizationsPolicyLeftOutIsNotExpiredByItsPruning() { + s.capture("acme") + s.seedAgentConfig(s.source, "acme", "greeter") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('organization', 'acme', ?, now())", + `{"prompt_injection": false}`) + s.Require().NoError(err) + _, cursor, err := s.source.Changes(s.ctx, "acme", 0, 100) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE data_changes SET at = at - interval '8 days'") + s.Require().NoError(err) + _, err = s.source.PruneDataChanges(s.ctx, 7*day) + s.Require().NoError(err) + + _, _, err = s.source.Changes(s.ctx, "acme", cursor, 100) + s.NoError(err) +} + +// A full page may end before the customer's last change, so its cursor is its own last change. +func (s *DataMoveSuite) TestAFullPageOfChangesResumesAfterItsLastChange() { + s.capture("acme") + s.seedAgentConfig(s.source, "acme", "greeter") + s.seedAgentConfig(s.source, "acme", "welcomer") + + first, cursor, err := s.source.Changes(s.ctx, "acme", 0, 1) + s.Require().NoError(err) + s.Require().Len(first, 1) + rest, _, err := s.source.Changes(s.ctx, "acme", cursor, 100) + + s.Require().NoError(err) + s.Require().Len(rest, 1) + var config struct { + Name string `json:"name"` + } + s.Require().NoError(json.Unmarshal(rest[0].Payload, &config)) + s.Equal("welcomer", config.Name) +} + +func (s *DataMoveSuite) TestChangesCarryNoOrganizationsPolicyOfTheAppsID() { + s.capture("acme") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('organization', 'acme', ?, now())", + `{"prompt_injection": false}`) + s.Require().NoError(err) + s.seedAgentConfig(s.source, "acme", "greeter") + + changes, _, err := s.source.Changes(s.ctx, "acme", 0, 1) + + s.Require().NoError(err) + s.Require().Len(changes, 1) + s.Equal("agent_configs", changes[0].Table) +} + +func (s *DataMoveSuite) TestAnAppsPolicyChangeIsReplayed() { + s.capture("acme") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + cursor := s.move("acme", "moved") + + _, err = s.source.GlobalDB().ExecContext(s.ctx, + "UPDATE policies SET document = ? WHERE scope = 'app' AND scope_id = 'acme'", `{"prompt_injection": false}`) + s.Require().NoError(err) + s.replay(s.destination, "acme", "moved", cursor) + + document, err := s.destination.Policies.Get(s.ctx, ScopeApp, "moved") + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection) + s.False(*document.PromptInjection) +} + +// Before the move the destination had no such config, and said so to whoever asked. +func (s *DataMoveSuite) TestAnImportedConfigIsServedRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.seedAgentConfig(s.source, "acme", "greeter") + _, err := destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.Require().ErrorIs(err, ErrNoAgentConfig) + + s.moveTo(destination, "acme", app) + + config, err := destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.Require().NoError(err) + s.Equal("be brief", config.Instructions) +} + +func (s *DataMoveSuite) TestAReplayedConfigChangeIsServedRightAfterIt() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + id := s.seedAgentConfig(s.source, "acme", "greeter") + cursor := s.moveTo(destination, "acme", app) + _, err := destination.AgentConfigs.Get(s.ctx, app, id) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE agent_configs SET instructions = 'be thorough' WHERE id = ?", id) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + config, err := destination.AgentConfigs.Get(s.ctx, app, id) + s.Require().NoError(err) + s.Equal("be thorough", config.Instructions) +} + +func (s *DataMoveSuite) TestAConfigRenamedByAReplayIsNoLongerServedByItsOldName() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + id := s.seedAgentConfig(s.source, "acme", "greeter") + cursor := s.moveTo(destination, "acme", app) + _, err := destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE agent_configs SET name = 'welcomer' WHERE id = ?", id) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + _, err = destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.ErrorIs(err, ErrNoAgentConfig) +} + +func (s *DataMoveSuite) TestAConfigDeletedByAReplayIsNoLongerServed() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + s.seedAgentConfig(s.source, "acme", "greeter") + cursor := s.moveTo(destination, "acme", app) + _, err := destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "DELETE FROM agent_configs WHERE name = 'greeter'") + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + _, err = destination.AgentConfigs.GetByName(s.ctx, app, "greeter") + s.ErrorIs(err, ErrNoAgentConfig) +} + +func (s *DataMoveSuite) TestARouterConfigImportedIsServedRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO router_configs (id, customer_id, name) VALUES (?, 'acme', 'fast')", newID()) + s.Require().NoError(err) + _, err = destination.RouterConfigs.GetByName(s.ctx, app, "fast") + s.Require().ErrorIs(err, ErrNoRouterConfig) + + s.moveTo(destination, "acme", app) + + _, err = destination.RouterConfigs.GetByName(s.ctx, app, "fast") + s.NoError(err) +} + +func (s *DataMoveSuite) TestAVoiceImportedIsServedRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.seedVoice(s.source, "acme", "narrator") + _, err := destination.Voices.GetByName(s.ctx, app, "narrator") + s.Require().ErrorIs(err, ErrNoVoice) + + s.moveTo(destination, "acme", app) + + _, err = destination.Voices.GetByName(s.ctx, app, "narrator") + s.NoError(err) +} + +func (s *DataMoveSuite) TestAReplayedSkillChangeIsServedRightAfterIt() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + config := s.seedAgentConfig(s.source, "acme", "greeter") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO skills (id, customer_id, config_id, name, description, instructions) VALUES (?, 'acme', ?, 'greet', 'greets', 'wave')", + newID(), config) + s.Require().NoError(err) + cursor := s.moveTo(destination, "acme", app) + _, err = destination.Skills.GetByNames(s.ctx, app, config, []string{"greet"}) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE skills SET instructions = 'bow' WHERE name = 'greet'") + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + skills, err := destination.Skills.GetByNames(s.ctx, app, config, []string{"greet"}) + s.Require().NoError(err) + s.Require().Len(skills, 1) + s.Equal("bow", skills[0].Instructions) +} + +func (s *DataMoveSuite) TestAnImportedPolicyIsServedRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + document, err := destination.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Require().Nil(document.PromptInjection) + + s.moveTo(destination, "acme", app) + + document, err = destination.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Require().NotNil(document.PromptInjection) + s.True(*document.PromptInjection) +} + +// What decides an app's requests is cached apart from its own document (Policies.OfApp). +func (s *DataMoveSuite) TestAnImportedPolicyDecidesTheAppsRequestsRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + policies, err := destination.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + s.Require().Nil(policies.App.PromptInjection) + + s.moveTo(destination, "acme", app) + + policies, err = destination.Policies.OfApp(s.ctx, app) + s.Require().NoError(err) + s.Require().NotNil(policies.App.PromptInjection) + s.True(*policies.App.PromptInjection) +} + +func (s *DataMoveSuite) TestAPolicyDeletedByAReplayIsNoLongerServed() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO policies (scope, scope_id, document, updated_at) VALUES ('app', 'acme', ?, now())", + `{"prompt_injection": true}`) + s.Require().NoError(err) + cursor := s.moveTo(destination, "acme", app) + _, err = destination.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "DELETE FROM policies WHERE scope = 'app' AND scope_id = 'acme'") + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + document, err := destination.Policies.Get(s.ctx, ScopeApp, app) + s.Require().NoError(err) + s.Nil(document.PromptInjection) +} + +// A name is a text column, which an imported row can carry as a number. +func (s *DataMoveSuite) TestAConfigImportedWithANumericNameIsServedRightAfterTheImport() { + destination := s.cachedDestination() + app := "moved-" + newID() + name := rand.Int64N(1 << 50) + _, err := destination.AgentConfigs.GetByName(s.ctx, app, strconv.FormatInt(name, 10)) + s.Require().ErrorIs(err, ErrNoAgentConfig) + + s.seedAgentConfig(s.source, "acme", "greeter") + exported := s.export("acme").of("agent_configs")[0] + exported["name"] = name + row, err := json.Marshal(exported) + s.Require().NoError(err) + s.Require().NoError(destination.ImportRow(s.ctx, app, "agent_configs", row)) + + _, err = destination.AgentConfigs.GetByName(s.ctx, app, strconv.FormatInt(name, 10)) + s.NoError(err) +} + +func (s *DataMoveSuite) TestAReplayedRouterConfigChangeIsServedRightAfterIt() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + id := newID() + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO router_configs (id, customer_id, name) VALUES (?, 'acme', 'fast')", id) + s.Require().NoError(err) + cursor := s.moveTo(destination, "acme", app) + _, err = destination.RouterConfigs.Get(s.ctx, app, id) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE router_configs SET name = 'slow' WHERE id = ?", id) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + config, err := destination.RouterConfigs.Get(s.ctx, app, id) + s.Require().NoError(err) + s.Equal("slow", config.Name) +} + +func (s *DataMoveSuite) TestASkillMovedByAReplayLeavesItsOldConfig() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + from := s.seedAgentConfig(s.source, "acme", "greeter") + to := s.seedAgentConfig(s.source, "acme", "welcomer") + _, err := s.source.GlobalDB().ExecContext(s.ctx, + "INSERT INTO skills (id, customer_id, config_id, name, description, instructions) VALUES (?, 'acme', ?, 'greet', 'greets', 'wave')", + newID(), from) + s.Require().NoError(err) + cursor := s.moveTo(destination, "acme", app) + skills, err := destination.Skills.GetByNames(s.ctx, app, from, []string{"greet"}) + s.Require().NoError(err) + s.Require().Len(skills, 1) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE skills SET config_id = ? WHERE name = 'greet'", to) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + skills, err = destination.Skills.GetByNames(s.ctx, app, from, []string{"greet"}) + s.Require().NoError(err) + s.Empty(skills) +} + +func (s *DataMoveSuite) TestAVoiceRenamedByAReplayIsNoLongerServedByItsOldName() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + id := s.seedVoice(s.source, "acme", "narrator") + cursor := s.moveTo(destination, "acme", app) + _, err := destination.Voices.GetByName(s.ctx, app, "narrator") + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE voices SET name = 'announcer' WHERE id = ?", id) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + _, err = destination.Voices.GetByName(s.ctx, app, "narrator") + s.ErrorIs(err, ErrNoVoice) +} + +func (s *DataMoveSuite) TestAReplayedVoiceChangeIsServedRightAfterIt() { + destination := s.cachedDestination() + app := "moved-" + newID() + s.capture("acme") + id := s.seedVoice(s.source, "acme", "narrator") + cursor := s.moveTo(destination, "acme", app) + _, err := destination.Voices.Get(s.ctx, app, id) + s.Require().NoError(err) + + _, err = s.source.GlobalDB().ExecContext(s.ctx, "UPDATE voices SET name = 'announcer' WHERE id = ?", id) + s.Require().NoError(err) + s.replay(destination, "acme", app, cursor) + + voice, err := destination.Voices.Get(s.ctx, app, id) + s.Require().NoError(err) + s.Equal("announcer", voice.Name) +} + func (s *DataMoveSuite) seedAgentConfig(store *Store, customerID, name string) string { id := newID() _, err := store.GlobalDB().ExecContext(s.ctx,