From cab377e1d8db85f4558c296ba523a3cf893029fa Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 20:21:06 +0000 Subject: [PATCH 1/8] fix(store): an imported row names only the importing app's rows --- acceleration/README.md | 5 +- .../replicate_repeat_integration_test.go | 22 + acceleration/internal/api/datamove_test.go | 19 + acceleration/internal/store/campaign.go | 6 +- .../internal/store/campaign_attempt.go | 4 +- .../internal/store/campaign_contact.go | 2 +- .../internal/store/campaign_contact_test.go | 18 + acceleration/internal/store/campaign_test.go | 42 ++ .../internal/store/conversation_document.go | 4 +- .../store/conversation_document_test.go | 16 + acceleration/internal/store/datamove.go | 109 +++- .../store/datamove_references_test.go | 556 ++++++++++++++++++ acceleration/internal/store/shards_test.go | 18 + acceleration/internal/store/store.go | 2 +- .../internal/store/store_explain_test.go | 4 + 15 files changed, 803 insertions(+), 24 deletions(-) create mode 100644 acceleration/internal/store/datamove_references_test.go diff --git a/acceleration/README.md b/acceleration/README.md index ca9da8447a..8597a8c216 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2903,7 +2903,10 @@ The customer is always the authenticated caller, never anything in the body or t so an export is the caller's own data and an import lands under the caller's own app however the file was edited on the way. An import upserts and refuses a row whose primary key belongs to another tenant, so replaying the same change twice lands where applying it -once would and a guessed id overwrites nothing. A request row is the exception: each +once would and a guessed id overwrites nothing. A session's call, turn or branch, a simulation's run and a +campaign's attempt name only a session, simulation or contact the app holds here: a row that names another +is refused by its table and primary key (`agent_responses:{"id":"turn-1"}`), and a line of an +import answers it 400. A request row is the exception: each deployment numbers its own, so it is imported with an id the destination gives it, under a `usage_id` made from the importing app and the `usage_id` the row had where it was first recorded (its source id, for a row from before usage ids), and written once. It keeps that diff --git a/acceleration/cmd/router/replicate_repeat_integration_test.go b/acceleration/cmd/router/replicate_repeat_integration_test.go index 019a12d968..a6ec9f82c3 100644 --- a/acceleration/cmd/router/replicate_repeat_integration_test.go +++ b/acceleration/cmd/router/replicate_repeat_integration_test.go @@ -211,6 +211,28 @@ func (s *ReplicateRepeatSuite) TestAFirstCopyBringsEverythingAndSavesTheCursor() s.WithinDuration(time.Now(), saved.ReadAt, time.Minute) } +// A copy, a page of changes and a full copy each stop at a row that names another app's row here. +func (s *ReplicateRepeatSuite) TestARunStopsAtARowThatNamesAnotherAppsRowNamingIt() { + for _, in := range []*store.Store{s.source, s.target} { + _, err := in.GlobalDB().ExecContext(s.ctx, "INSERT INTO agent_sessions (id, customer_id, state) VALUES ('theirs', 'resident', '')") + s.Require().NoError(err) + } + s.recorded(1) + s.Require().NoError(s.once("acme", false)) + _, err := s.source.GlobalDB().ExecContext(s.ctx, "INSERT INTO agent_responses (id, session_id, customer_id) VALUES ('turn', 'theirs', 'acme')") + s.Require().NoError(err) + for _, full := range []bool{false, true} { + err = s.once("acme", full) + + s.Require().ErrorIs(err, store.ErrInvalidImport) + s.ErrorContains(err, `agent_responses:{"id":"turn"}`) + turns, err := s.target.Responses.Select(s.ctx, "acme", "theirs", store.ResponseFilter{}) + s.Require().NoError(err) + s.Empty(turns) + } + s.Equal(int64(0), *s.saved().Cursor, "the page is not passed") +} + func (s *ReplicateRepeatSuite) TestARepeatOnceBringsOnlyTheChangesSinceItsCursor() { s.recorded(1) s.recorded(2) diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 2f453a02ed..3ea5b92694 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -369,6 +369,25 @@ func (s *DataMoveSuite) TestChangesAreAppliedToAnAppThatHoldsData() { s.Equal("edited at the source", s.instructionsOf(agent.Id)) } +// A row that names a row of another app's is the export's to correct, and the answer names it. +func (s *DataMoveSuite) TestAnImportedRowThatNamesAnotherAppsRowIsRefusedNamingIt() { + theirs, turn := s.utils.uuid(), s.utils.uuid() + s.Require().NoError(s.store.Sessions.Upsert(context.Background(), &store.AgentSession{ID: theirs, CustomerID: s.utils.uuid(), + AgentName: "docs", UserID: "sam", CallerKind: "user", CreatedAt: time.Now()})) + row := json.RawMessage(`{"id": "` + turn + `", "session_id": "` + theirs + `", "said": "hello", "status": "completed", + "error": "", "created_at": "2026-01-01T00:00:00Z"}`) + + for _, line := range []dataLine{{Table: "agent_responses", Row: row}, + {Change: &store.DataChange{Seq: 1, Table: "agent_responses", Op: store.ChangeInsert, At: time.Now(), Payload: row}}} { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{line})) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, `agent_responses:{"id":"`+turn+`"}`) + s.Contains(failure, "neither the export nor this app holds") + s.NotContains(failure, theirs) + } +} + // A change to a policy of another scope is skipped, so the answer counts no row for it. func (s *DataMoveSuite) TestAChangeToAnotherScopesPolicyIsNotCountedAsWritten() { key := `{"scope": "organization", "scope_id": ` + strconv.Quote(s.customerID()) + `}` diff --git a/acceleration/internal/store/campaign.go b/acceleration/internal/store/campaign.go index f2d4780d0a..977681d31b 100644 --- a/acceleration/internal/store/campaign.go +++ b/acceleration/internal/store/campaign.go @@ -359,7 +359,7 @@ FROM campaign_contacts cc WHERE campaign_id = ? AND reason IS DISTINCT FROM 'duplicate'` if contacts == DuplicateNotContacted { // An attempt that was deferred or refused rang nobody. - query += ` AND NOT EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id AND ` + placedDial + `)` + query += ` AND NOT EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id AND ca.campaign_id = cc.campaign_id AND ` + placedDial + `)` } if _, err := tx.ExecContext(ctx, query+" ORDER BY seq", copied.ID, source.ID); err != nil { return fmt.Errorf("store: duplicate contacts: %w", err) @@ -630,7 +630,7 @@ func (r *Campaigns) Analytics(ctx context.Context, campaignID string) (CampaignA err = r.store.global.NewRaw(`SELECT count(*) FROM campaign_contacts cc WHERE cc.campaign_id = ? AND EXISTS (SELECT 1 FROM campaign_attempts ca - WHERE ca.contact_id = cc.id AND `+answeredDial+`)`, campaignID).Scan(ctx, &analytics.Connected) + WHERE ca.contact_id = cc.id AND ca.campaign_id = cc.campaign_id AND `+answeredDial+`)`, campaignID).Scan(ctx, &analytics.Connected) if err != nil { return CampaignAnalytics{}, stack.Wrap(fmt.Errorf("store: count connected contacts: %w", err)) } @@ -694,7 +694,7 @@ func (r *Campaigns) Totals(ctx context.Context, campaignIDs []string) (map[strin Converted int } err := r.store.global.NewRaw(`SELECT cc.campaign_id, - count(*) FILTER (WHERE EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id AND `+placedDial+`)) AS dialed, + count(*) FILTER (WHERE EXISTS (SELECT 1 FROM campaign_attempts ca WHERE ca.contact_id = cc.id AND ca.campaign_id = cc.campaign_id AND `+placedDial+`)) AS dialed, count(*) FILTER (WHERE cc.converted) AS converted FROM campaign_contacts cc WHERE cc.campaign_id IN (?) GROUP BY cc.campaign_id`, bun.In(campaignIDs)).Scan(ctx, &rows) if err != nil { diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index 79429d9476..762c72d34a 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -170,12 +170,12 @@ func (r *CampaignAttempts) ClaimClassifications(ctx context.Context, owner strin var attempts []CampaignAttempt err := tx.NewRaw(`WITH due AS ( SELECT ca.id FROM campaign_attempts ca - JOIN campaign_contacts cc ON cc.id = ca.contact_id + JOIN campaign_contacts cc ON cc.id = ca.contact_id AND cc.campaign_id = ca.campaign_id WHERE ca.classify_state = ? AND ca.classify_after <= ? AND cc.stage = ? AND (cc.leased_by = '' OR cc.lease_until IS NULL OR cc.lease_until < now()) AND NOT EXISTS (SELECT 1 FROM campaigns cp WHERE cp.id = cc.campaign_id AND cp.move_paused) AND NOT EXISTS (SELECT 1 FROM campaign_attempts newer - WHERE newer.contact_id = ca.contact_id AND newer.classify_state = ca.classify_state + WHERE newer.contact_id = ca.contact_id AND newer.campaign_id = ca.campaign_id AND newer.classify_state = ca.classify_state AND (newer.started_at, newer.dial) > (ca.started_at, ca.dial)) ORDER BY ca.classify_after LIMIT ? diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index 7e7e88ff7c..4fe0908f2c 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -367,7 +367,7 @@ func (r *CampaignContacts) Get(ctx context.Context, campaignID, contactID string return Contact{}, nil, stack.Wrap(fmt.Errorf("store: campaign contact: %w", err)) } var attempts []CampaignAttempt - err = r.store.global.NewSelect().Model(&attempts).Where("contact_id = ?", contactID).Order("started_at ASC", "id ASC").Scan(ctx) + err = r.store.global.NewSelect().Model(&attempts).Where("contact_id = ?", contactID).Where("campaign_id = ?", campaignID).Order("started_at ASC", "id ASC").Scan(ctx) if err != nil { return Contact{}, nil, stack.Wrap(fmt.Errorf("store: contact attempts: %w", err)) } diff --git a/acceleration/internal/store/campaign_contact_test.go b/acceleration/internal/store/campaign_contact_test.go index 634bdea7e6..0404c40ef2 100644 --- a/acceleration/internal/store/campaign_contact_test.go +++ b/acceleration/internal/store/campaign_contact_test.go @@ -470,6 +470,24 @@ func (s *StoreSuite) TestOnlyTheLatestAnsweredDialOfAContactIsClassified() { s.Empty(later) } +func (s *StoreSuite) TestOnlyADialOfTheContactsCampaignIsClassified() { + campaign := s.runningCampaign(5, "+15550001", "+15550002") + due := s.claimDue("a", s.base, 10) + s.Require().Len(due, 2) + answered, stray := due[0].Contact, due[1].Contact + dial := s.answered("a", campaign, answered, s.base, s.base) + for _, contact := range []Contact{answered, stray} { + s.strayDial(contact, s.base.Add(time.Minute)) + s.Require().NoError(s.store.CampaignContacts.Settle(s.ctx, "a", contact.ID, Settle{Stage: AwaitingOutcome, Attempt: 1})) + } + + claimed, err := s.store.CampaignAttempts.ClaimClassifications(s.ctx, "a", s.base.Add(time.Hour), time.Minute, 10) + + s.Require().NoError(err) + s.Require().Len(claimed, 1) + s.Equal(dial.ID, claimed[0].Attempt.ID) +} + func (s *StoreSuite) TestADialWhoseContactAnotherRunnerHoldsIsNotClassified() { campaign := s.runningCampaign(5, "+15550001") contact := s.claimDue("a", s.base, 10)[0].Contact diff --git a/acceleration/internal/store/campaign_test.go b/acceleration/internal/store/campaign_test.go index e9293bf35e..247ee6ed78 100644 --- a/acceleration/internal/store/campaign_test.go +++ b/acceleration/internal/store/campaign_test.go @@ -494,6 +494,48 @@ func (s *StoreSuite) TestAContactListsItsAttemptsOldestFirst() { s.Equal("b-second", attempts[1].ID) } +// strayDial is a dial of another campaign than its contact's, which no dial is, at. +func (s *StoreSuite) strayDial(contact Contact, at time.Time) { + stray := s.draftCampaign(newID(), "+15550009") + _, err := s.store.GlobalDB().NewInsert().Model(&CampaignAttempt{ID: newID(), CampaignID: stray.ID, ContactID: contact.ID, StepID: "step_1", + Attempt: 1, Dial: 1, StartedAt: at, CallOutcome: "completed", ClassifyState: classifyPending, ClassifyAfter: &at}).Exec(s.ctx) + s.Require().NoError(err) +} + +func (s *StoreSuite) TestAContactListsOnlyItsCampaignsAttempts() { + campaign := s.draftCampaign(newID(), "+15550001") + contact := s.contactsOf(campaign)[0] + s.strayDial(contact, s.base) + + _, attempts, err := s.store.CampaignContacts.Get(s.ctx, campaign.ID, contact.ID) + + s.Require().NoError(err) + s.Empty(attempts) +} + +func (s *StoreSuite) TestAnalyticsCountOnlyTheCampaignsDials() { + campaign := s.draftCampaign(newID(), "+15550001") + s.strayDial(s.contactsOf(campaign)[0], s.base) + + got, err := s.store.Campaigns.Analytics(s.ctx, campaign.ID) + + s.Require().NoError(err) + s.Zero(got.Dialed) + s.Zero(got.Connected) +} + +func (s *StoreSuite) TestADuplicateOfNotContactedReadsOnlyTheCampaignsDials() { + campaign := s.draftCampaign(newID(), "+15550001") + s.launch(campaign, s.base) + s.strayDial(s.contactsOf(campaign)[0], s.base) + s.Require().NoError(s.store.Campaigns.Stop(s.ctx, campaign.CustomerID, campaign.ID, s.base)) + + copied, err := s.store.Campaigns.Duplicate(s.ctx, campaign.CustomerID, campaign.ID, "not_contacted") + + s.Require().NoError(err) + s.Len(s.contactsOf(copied), 1) +} + func (s *StoreSuite) TestCampaignsListNewestFirstByStateAndPage() { customerID := newID() var made []Campaign diff --git a/acceleration/internal/store/conversation_document.go b/acceleration/internal/store/conversation_document.go index 19b6901aec..b907488994 100644 --- a/acceleration/internal/store/conversation_document.go +++ b/acceleration/internal/store/conversation_document.go @@ -159,7 +159,7 @@ func (r *ConversationDocuments) Select(ctx context.Context, customerID string, s query := db.NewSelect().Model((*ConversationDocument)(nil)). Where("cd.customer_id = ?", customerID). Where("cd.owner_user_id = ?", scope.Owner). - Where("NOT EXISTS (SELECT 1 FROM agent_responses AS r WHERE r.id = cd.response_id AND r.rewound_at IS NOT NULL)"). + Where("NOT EXISTS (SELECT 1 FROM agent_responses AS r WHERE r.id = cd.response_id AND r.customer_id = cd.customer_id AND r.rewound_at IS NOT NULL)"). Order("cd.created_at ASC", "cd.id ASC") if scope.ConversationID != "" { query = query.Where("cd.conversation_id = ?", scope.ConversationID) @@ -169,7 +169,7 @@ func (r *ConversationDocuments) Select(ctx context.Context, customerID string, s // A document is written by the router that took its turn, beside the turn's row. if !until.IsZero() { query = query.Where("cd.response_id = '' OR EXISTS (SELECT 1 FROM agent_responses AS sent "+ - "WHERE sent.id = cd.response_id AND sent.created_at <= ?)", until) + "WHERE sent.id = cd.response_id AND sent.customer_id = cd.customer_id AND sent.created_at <= ?)", until) } var documents []ConversationDocument err := query.Scan(ctx, &documents) diff --git a/acceleration/internal/store/conversation_document_test.go b/acceleration/internal/store/conversation_document_test.go index 95dc547a39..ea48f622d3 100644 --- a/acceleration/internal/store/conversation_document_test.go +++ b/acceleration/internal/store/conversation_document_test.go @@ -95,6 +95,22 @@ func (s *StoreSuite) TestAForkStoppingAtATurnReadsOnlyTheDocumentsSentUpToIt() { s.Equal([]string{"carried", "with-first"}, s.documentIDs(DocumentScope{SessionID: "one", Owner: "jlahey", UntilResponse: "first"})) } +func (s *StoreSuite) TestADocumentIsReadBesideOnlyItsCustomersTurns() { + s.opened("one", "app", s.base, nil) + s.responded("one", "first", "read this", s.base) + s.opened("theirs", "somebody-else", s.base, nil) + for _, id := range []string{"rewound", "kept"} { + s.Require().NoError(s.store.Responses.Insert(s.ctx, &AgentResponse{ID: "their-" + id, SessionID: "theirs", CustomerID: "somebody-else", + Said: "hello", CreatedAt: s.base.Add(-time.Hour)})) + s.attached(id, "one", "", "jlahey", "their-"+id, s.base) + } + _, err := s.store.shard.ExecContext(s.ctx, "UPDATE agent_responses SET rewound_at = now() WHERE id = 'their-rewound'") + s.Require().NoError(err) + + s.Equal([]string{"kept", "rewound"}, s.documentIDs(DocumentScope{SessionID: "one", Owner: "jlahey"})) + s.Empty(s.documentIDs(DocumentScope{SessionID: "one", Owner: "jlahey", UntilResponse: "first"})) +} + func (s *StoreSuite) TestAForkStoppingAtATurnThatIsNotThereIsRefused() { _, err := s.store.ConversationDocuments.Select(s.ctx, "app", DocumentScope{SessionID: "one", Owner: "jlahey", UntilResponse: "missing"}) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 44d2b2cfa6..cc73b8c711 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -31,8 +31,8 @@ var ErrChangesExpired = errors.New("store: the changes since that cursor are no var ErrNotACustomConnector = errors.New("not a definition the API would store for a custom connector") // ErrInvalidImport is an export that cannot be written as it is: a table no export carries, a -// row that does not read, or a row the database refuses for what it holds. Its message names -// the table and nothing of the database. A database that failed is never one. +// row that does not read, or a row refused for what it holds or names. Its message names +// the table, and the row's own key at most, and nothing of the database. A database that failed is never one. var ErrInvalidImport = errors.New("store: the export cannot be imported") // invalidImport marks err as ErrInvalidImport without changing its message. @@ -57,7 +57,7 @@ func refusedRow(table string, err error) error { case code == uniqueViolation: reason = "a row holds a value, such as a name, that another row here already holds" case code == foreignKeyViolation: - reason = "a row names a row that neither the export nor this app holds" + reason = namesNoRow case strings.HasPrefix(code, "23"): reason = "a row breaks a rule of its table" case strings.HasPrefix(code, "22"): @@ -86,6 +86,9 @@ type dataTable struct { // parent and parentColumn name the row this one belongs to. parent string parentColumn string + // references are the other rows this one names through a foreign key on an id alone, which + // any customer's row satisfies. A foreign key that holds the customer too needs none. + references []dataReference // filter is an extra predicate on an export, for a table that holds more than one // kind of row. filter string @@ -111,6 +114,12 @@ type dataTable struct { vouched []string } +// dataReference is a column of a moved table that names a row of another one by its id. +type dataReference struct{ column, table string } + +// ofSession is the reference of a row that names its session. +var ofSession = []dataReference{{"session_id", "agent_sessions"}} + // rollup is a table of counts per key that every shard keeps its own rows of, so an export of // several shards folds the rows of one key into one. func (t dataTable) rollup() bool { @@ -173,9 +182,10 @@ var dataTables = []dataTable{ {name: "knowledge_documents", customer: "customer_id", vouched: []string{"state", "error", "object_key"}}, {name: "campaigns", customer: "customer_id"}, {name: "campaign_contacts", parent: "campaigns", parentColumn: "campaign_id"}, - {name: "campaign_attempts", parent: "campaigns", parentColumn: "campaign_id"}, + {name: "campaign_attempts", parent: "campaigns", parentColumn: "campaign_id", + references: []dataReference{{"contact_id", "campaign_contacts"}}}, {name: "simulations", customer: "customer_id"}, - {name: "simulation_runs", customer: "customer_id"}, + {name: "simulation_runs", customer: "customer_id", references: []dataReference{{"simulation_id", "simulations"}}}, {name: "simulation_cases", parent: "simulation_runs", parentColumn: "run_id"}, {name: "users", customer: "customer_id", vouched: []string{"minted"}}, {name: "scheduled_tasks", customer: "customer_id"}, @@ -188,14 +198,14 @@ var dataTables = []dataTable{ {name: "agent_sessions", customer: "customer_id", shard: true}, {name: "agent_session_tools", customer: "customer_id", parent: "agent_sessions", parentColumn: "session_id", shard: true}, // After the sessions their session_id points at. - {name: "calls", customer: "customer_id", shard: true}, - {name: "agent_responses", customer: "customer_id", shard: true}, + {name: "calls", customer: "customer_id", shard: true, references: ofSession}, + {name: "agent_responses", customer: "customer_id", shard: true, references: ofSession}, {name: "agent_response_items", parent: "agent_responses", parentColumn: "response_id", shard: true}, {name: "conversation_documents", customer: "customer_id", shard: true}, // The channel's hidden ranges are in the Stream app and stay there, so the copies of what // they hid and the switches that hid it go with their session. - {name: "agent_branch_switches", customer: "customer_id", shard: true}, - {name: "agent_branch_messages", customer: "customer_id", shard: true}, + {name: "agent_branch_switches", customer: "customer_id", shard: true, references: ofSession}, + {name: "agent_branch_messages", customer: "customer_id", shard: true, references: ofSession}, // Nothing points at a log's id, so a copied log is given one of this deployment's. {name: "agent_logs", customer: "customer_id", copied: "source_id"}, // No foreign key points at a request's id. An agent log row names it as text, and @@ -770,7 +780,8 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an // 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 key a row of -// another customer holds here is refused (ErrAnotherCustomersRow). +// another customer holds here is refused (ErrAnotherCustomersRow), and so is one whose +// references name a row this customer does not hold here. // // 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. @@ -911,7 +922,7 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str subject = fmt.Sprintf("?::jsonb || %s", spec.identity()) } if spec.parent != "" { - where = " WHERE " + spec.owned("r") + where = " WHERE " + spec.belonging().held("r") } if spec.copied != "" { where = " WHERE NOT " + spec.copiedBefore(shape, columns) @@ -934,6 +945,14 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str // The customer forced onto the row, then checked against its parent. args = append(args, customerID) } + for _, reference := range spec.references { + joined := " AND " + if where == "" { + joined = " WHERE " + } + where += fmt.Sprintf("%s(r.%s IS NULL OR %s)", joined, reference.column, reference.held("r")) + args = append(args, customerID) + } if table == "requests" { // The organization a request counts against is the app's here, whatever the row says. // It is in the shared database and requests in this shard's, so it is read first. An app @@ -1051,7 +1070,48 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str if taken { return fmt.Errorf("store: import %s: %w", table, ErrAnotherCustomersRow) } - return nil + if len(spec.references) == 0 { + return nil + } + // A row of a parent that is not this customer's is left out, whatever else it names. Every + // other row of these tables is written, so this one names a row the customer does not hold. + if spec.parent != "" { + var held bool + if err := db.QueryRowContext(ctx, fmt.Sprintf( + "SELECT EXISTS (SELECT 1 FROM jsonb_populate_record(NULL::%s, ?::jsonb) AS r WHERE %s)", + spec.name, spec.owned("r")), string(row), customerID).Scan(&held); err != nil { + return fmt.Errorf("store: import %s: %w", table, err) + } + if !held { + return nil + } + } + key, err := rowKey(table, shape.keys, row) + if err != nil { + return err + } + return stack.Wrap(invalidImport(fmt.Errorf("store: import %s: %s", key, namesNoRow))) +} + +// namesNoRow says a row names one its customer does not hold here, whether or not another does. +const namesNoRow = "a row names a row that neither the export nor this app holds" + +// rowKey names a row as it was sent, by its table and the values of its primary key: +// agent_responses:{"id":"response-1"}. +func rowKey(table string, keys []string, row json.RawMessage) (string, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(row, &fields); err != nil { + return "", invalidImport(fmt.Errorf("store: import %s: %w", table, err)) + } + key := make(map[string]json.RawMessage, len(keys)) + for _, column := range keys { + key[column] = fields[column] + } + encoded, err := json.Marshal(key) + if err != nil { + return "", stack.Wrap(err) + } + return table + ":" + string(encoded), nil } // importCached runs an import's query of a cachedByID table, which returns what each row it wrote @@ -1857,12 +1917,33 @@ func (t dataTable) identity() string { // belongs to the customer the query's next placeholder carries. func (t dataTable) owned(relation string) string { if t.parent != "" { - return fmt.Sprintf("EXISTS (SELECT 1 FROM %s AS p WHERE p.id = %s.%s AND p.customer_id = ?)", - t.parent, relation, t.parentColumn) + return t.belonging().owned(relation, "") } return fmt.Sprintf("%s.%s = ?", relation, t.customer) } +// belonging is the reference of a row of a table with a parent to the row it belongs to. +func (t dataTable) belonging() dataReference { return dataReference{t.parentColumn, t.parent} } + +// owned is the condition that the row this reference names, in the given relation, belongs to +// the customer the query's next placeholder carries. locking is a locking clause for that row. +func (r dataReference) owned(relation, locking string) string { + named, _ := dataTableByName(r.table) + owner := fmt.Sprintf("%s.%s = ?", r.table, named.customer) + if named.customer == "" { + owner = named.belonging().owned(r.table, "") + } + return fmt.Sprintf("EXISTS (SELECT 1 FROM %[1]s WHERE %[1]s.id = %[2]s.%[3]s AND %[4]s%[5]s)", + r.table, relation, r.column, owner, locking) +} + +// held is owned with the named row locked until the statement's transaction ends, for a row +// about to be written: the foreign key then looks for the id again, whoever's row it is by +// then. KEY SHARE is the lock the foreign key takes itself. +func (r dataReference) held(relation string) string { + return r.owned(relation, " FOR KEY SHARE OF "+r.table) +} + // conflictTarget is the index a row of this table is known by across deployments: what an // import resolves a conflict on. The one a copied row is known by holds only copied rows. func (t dataTable) conflictTarget(s shape) string { diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go new file mode 100644 index 0000000000..302434e948 --- /dev/null +++ b/acceleration/internal/store/datamove_references_test.go @@ -0,0 +1,556 @@ +//go:build integration + +package store + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "slices" + "strings" + "time" + + "github.com/uptrace/bun" +) + +// namingRow is a row of a moved table and the row of another table it names. +type namingRow struct { + table, id string + row map[string]any + column string + named, own string +} + +// namedTables are the tables naming rows name a row of, by the column that names it. +var namedTables = map[string]string{"session_id": "agent_sessions", "contact_id": "campaign_contacts", "simulation_id": "simulations"} + +// layouts are the destination as one database and as a shared database with a shard, each +// holding what naming rows may name: acme's own, and resident's under ids of their own. +func (s *DataMoveSuite) layouts(check func(destination *Store, rows []namingRow)) { + s.Run("one database", func() { check(s.destination, s.namingRows(s.destination)) }) + s.Run("a shard of its own", func() { + destination := s.shardedDestination() + check(destination, s.namingRows(destination)) + }) +} + +func (s *DataMoveSuite) shardedDestination() *Store { + dsn := os.Getenv(DSNEnvVar) + shard := s.open(elsewhere(dsn, "moved_shard")) + var sharded []string + for _, table := range dataTables { + if table.shard { + sharded = append(sharded, table.name) + } + } + _, err := shard.GlobalDB().ExecContext(s.ctx, "TRUNCATE "+strings.Join(sharded, ", ")+" CASCADE") + s.Require().NoError(err) + s.Require().NoError(shard.Close()) + destination, err := OpenShards(Options{DSN: elsewhere(dsn, "moved"), ShardDSN: elsewhere(dsn, "moved_shard")}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(destination.Close()) }) + s.Require().NoError(destination.Migrate(s.ctx)) + return destination +} + +// holding is a session, a contact and a simulation customerID holds at a deployment, by id. +func (s *DataMoveSuite) holding(store *Store, customerID string) (session, campaign, contact, simulation string) { + session, campaign, contact, simulation = newID(), newID(), newID(), newID() + s.execute(store.shard, "INSERT INTO agent_sessions (id, customer_id, state) VALUES (?, ?, '')", session, customerID) + s.execute(store.global, "INSERT INTO campaigns (id, customer_id, name) VALUES (?, ?, 'renewals')", campaign, customerID) + s.execute(store.global, "INSERT INTO campaign_contacts (id, campaign_id, to_number) VALUES (?, ?, '+15550002222')", contact, campaign) + s.execute(store.global, "INSERT INTO simulations (id, customer_id, name) VALUES (?, ?, 'lost card')", simulation, customerID) + return session, campaign, contact, simulation +} + +func (s *DataMoveSuite) execute(db bun.IDB, query string, args ...any) { + _, err := db.ExecContext(s.ctx, query, args...) + s.Require().NoError(err, query) +} + +// namingRows is one row of acme's for each reference of each table that names its row by an id +// alone, naming resident's row. +func (s *DataMoveSuite) namingRows(store *Store) []namingRow { + session, campaign, contact, simulation := s.holding(store, "acme") + theirSession, _, theirContact, theirSimulation := s.holding(store, "resident") + at := "2026-01-01T00:00:00Z" + rows := []namingRow{ + {table: "agent_responses", column: "session_id", named: theirSession, own: session, + row: map[string]any{"said": "hello", "status": "completed", "error": "", "created_at": at}}, + {table: "agent_branch_switches", column: "session_id", named: theirSession, own: session, + row: map[string]any{"kind": "edit", "state": "done", "fork_message_id": "m", "target_response_id": "r", "resent": 0, + "inclusive": true, "hidden_from": at, "created_at": at, "updated_at": at}}, + {table: "agent_branch_messages", column: "session_id", named: theirSession, own: session, + row: map[string]any{"switch_id": "s", "response_id": "", "author_id": "sam", "message": map[string]any{}, "chat_created_at": at}}, + {table: "calls", column: "session_id", named: theirSession, own: session, + row: map[string]any{"agent_id": "agent", "call_id": "c", "call_type": "default", "direction": "inbound", "instructions": "", + "llm": "", "stt": "", "tts": "", "sts": "", "voice": "", "subagent": "", "tags": map[string]any{}, "started_at": at}}, + {table: "simulation_runs", column: "simulation_id", named: theirSimulation, own: simulation, + row: map[string]any{"state": "passed", "mode": "text", "config_id": "", "scenario": "lost card", "assertion": "answered", + "judge_target": "", "cases": 0, "passed": 0, "failed": 0, "stop_requested": false, "started_at": at}}, + {table: "campaign_attempts", column: "contact_id", named: theirContact, own: contact, + row: map[string]any{"campaign_id": campaign, "step_id": "step_1", "attempt": 1, "dial": 1, "call_id": "", "vendor_call_id": "", + "result": "", "outcome": "", "converted": false, "classify_state": "", "classify_tries": 0, "started_at": at, + "ended_at": at, "call_outcome": "completed"}}, + } + for i := range rows { + rows[i].id = newID() + rows[i].row[rows[i].key()] = rows[i].id + rows[i].row[rows[i].column] = rows[i].named + if rows[i].table != "campaign_attempts" { + rows[i].row["customer_id"] = "acme" + } + } + return rows +} + +func (n namingRow) key() string { + if n.table == "agent_branch_messages" { + return "original_message_id" + } + return "id" +} + +// naming is the row as sent, naming id. +func (n namingRow) naming(id any) json.RawMessage { + n.row[n.column] = id + encoded, err := json.Marshal(n.row) + if err != nil { + panic(err) + } + return encoded +} + +// nameOf is what the row stored names, empty when none is stored. +func (s *DataMoveSuite) nameOf(destination *Store, n namingRow) string { + spec, _ := dataTableByName(n.table) + var names []string + s.Require().NoError(destination.sideOf(spec).NewSelect().Table(n.table).ColumnExpr("COALESCE(?, '')", bun.Ident(n.column)). + Where("? = ?", bun.Ident(n.key()), n.id).Scan(s.ctx, &names)) + if len(names) == 0 { + return "" + } + return names[0] +} + +// assertNamesNoRow checks a row is refused as naming one its customer does not hold, by its table +// and its key. +func (s *DataMoveSuite) assertNamesNoRow(err error, n namingRow) { + s.Require().ErrorIs(err, ErrInvalidImport, n.table) + s.ErrorContains(err, n.table+`:{`, n.table) + s.ErrorContains(err, `"`+n.key()+`":"`+n.id+`"`, n.table) + s.ErrorContains(err, "a row names a row that neither the export nor this app holds", n.table) + s.NotContains(err.Error(), n.named, "the row it names is not named back") +} + +func (s *DataMoveSuite) TestAnImportedRowNamesOnlyTheImportersRows() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + s.assertNamesNoRow(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.named)), n) + s.Empty(s.nameOf(destination, n), n.table) + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)), n.table) + s.Equal(n.own, s.nameOf(destination, n), n.table) + } + }) +} + +func (s *DataMoveSuite) TestAnImportDoesNotMoveARowOntoAnotherCustomersRow() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)), n.table) + s.assertNamesNoRow(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.named)), n) + s.Equal(n.own, s.nameOf(destination, n), n.table) + } + }) +} + +func (s *DataMoveSuite) TestAReplayedRowNamesOnlyTheReplayersRows() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + written := DataChange{Table: "router_configs", Op: ChangeInsert, Payload: json.RawMessage(fmt.Sprintf( + `{"id": %q, "name": %q, "llm": {}, "stt": {}, "tts": {}, "sts": {}, "search": {}, "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:00:00Z"}`, newID(), newID()))} + s.assertNamesNoRow(destination.ApplyChanges(s.ctx, "acme", []DataChange{written, + {Table: n.table, Op: ChangeInsert, Payload: n.naming(n.named)}}), n) + s.Empty(s.nameOf(destination, n), n.table) + + s.Require().NoError(destination.ApplyChanges(s.ctx, "acme", []DataChange{ + {Table: n.table, Op: ChangeInsert, Payload: n.naming(n.own)}, + {Table: n.table, Op: ChangeUpdate, Payload: n.naming(n.own)}}), n.table) + s.assertNamesNoRow(destination.ApplyChanges(s.ctx, "acme", []DataChange{ + {Table: n.table, Op: ChangeUpdate, Payload: n.naming(n.named)}}), n) + s.Equal(n.own, s.nameOf(destination, n), n.table) + } + }) +} + +// A copy that brings a row before the one it names is refused until that one is here, as before, +// and the same row lands then. +func (s *DataMoveSuite) TestARowLandsOnceTheRowItNamesIsHere() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + s.assertNamesNoRow(destination.ImportRow(s.ctx, "acme", n.table, n.naming("not-here-yet")), namingRow{ + table: n.table, id: n.id, column: n.column, named: "not-here-yet"}) + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)), n.table) + } + }) +} + +// The answer is the same whether the row named is another customer's or nobody's, and comes as +// soon while a transaction holds that other customer's row. +func (s *DataMoveSuite) TestARowIsRefusedTheSameWhoeverHoldsTheRowItNames() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + spec, _ := dataTableByName(n.table) + missing := destination.ImportRow(s.ctx, "acme", n.table, n.naming("nobody-s")) + s.Require().Error(missing, n.table) + tx, err := destination.sideOf(spec).BeginTx(s.ctx, nil) + s.Require().NoError(err) + s.execute(tx, "SELECT 1 FROM "+namedTables[n.column]+" WHERE id = ? FOR UPDATE", n.named) + + within, cancel := context.WithTimeout(s.ctx, 2*time.Second) + theirs := destination.ImportRow(within, "acme", n.table, n.naming(n.named)) + cancel() + + s.Require().NoError(tx.Rollback()) + s.EqualError(theirs, missing.Error(), n.table) + s.Require().ErrorIs(theirs, ErrInvalidImport, n.table) + s.Require().ErrorIs(missing, ErrInvalidImport, n.table) + } + }) +} + +func (s *DataMoveSuite) TestACallOfNoSessionIsImported() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + if n.table == "calls" { + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(nil))) + found, err := destination.Calls.Get(s.ctx, "acme", n.id) + s.Require().NoError(err) + s.Empty(found.SessionID) + } + } + }) +} + +// A row of a campaign another customer holds here is left out, as before, whichever contact it +// names. +func (s *DataMoveSuite) TestAnAttemptOfAnotherCustomersCampaignIsLeftOut() { + s.layouts(func(destination *Store, rows []namingRow) { + _, theirCampaign, _, _ := s.holding(destination, "resident") + for _, n := range rows { + if n.table == "campaign_attempts" { + n.row["campaign_id"] = theirCampaign + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.named))) + s.Empty(s.nameOf(destination, n)) + } + } + }) +} + +func (s *DataMoveSuite) TestARowAnotherCustomerHoldsTheKeyOfIsRefusedAsThat() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)), n.table) + if n.table == "campaign_attempts" { + continue // its owner is its campaign's + } + s.Require().ErrorIs(destination.ImportRow(s.ctx, "other", n.table, n.naming(n.own)), ErrAnotherCustomersRow, n.table) + } + }) +} + +// A move to another deployment and back, and on from the copy, and each again, lands every row +// that names another. +func (s *DataMoveSuite) TestRowsThatNameOthersMoveThereAndBackAndOn() { + session, campaign, contact, simulation := s.holding(s.source, "acme") + s.execute(s.source.global, "UPDATE simulations SET config_id = 'config-1', scenario = 'lost card', variations = 1") + s.execute(s.source.global, "UPDATE campaigns SET config_id = 'config-1', from_number = '+15550001111', concurrency = 1") + for _, n := range s.namingRows(s.source) { + own := map[string]string{"session_id": session, "simulation_id": simulation, "contact_id": contact}[n.column] + if n.table == "campaign_attempts" { + n.row["campaign_id"] = campaign + } + s.Require().NoError(s.source.ImportRow(s.ctx, "acme", n.table, n.naming(own)), n.table) + } + tables := []string{"agent_sessions", "agent_responses", "agent_branch_switches", "agent_branch_messages", "calls", + "simulations", "simulation_runs", "campaigns", "campaign_contacts", "campaign_attempts"} + carry := func(from *Store, as string, to *Store, under string) { + for _, row := range s.exportFrom(from, as).rows { + if !slices.Contains(tables, row.table) { + continue + } + encoded, err := json.Marshal(row.row) + s.Require().NoError(err) + s.Require().NoError(to.ImportRow(s.ctx, under, row.table, encoded), row.table) + } + } + counts := func(store *Store, customer string) map[string]int { + counted := map[string]int{} + for _, table := range tables { + counted[table] = len(s.exportFrom(store, customer).of(table)) + } + return counted + } + want := counts(s.source, "acme") + s.Equal(1, want["campaign_attempts"]) + s.Equal(1, want["agent_responses"]) + + for range 2 { + carry(s.source, "acme", s.destination, "moved") + s.Equal(want, counts(s.destination, "moved")) + carry(s.destination, "moved", s.source, "acme") + s.Equal(want, counts(s.source, "acme")) + } + sharded := s.shardedDestination() + s.execute(s.destination.global, "TRUNCATE campaigns, simulations, agent_sessions CASCADE") + s.execute(s.destination.global, "TRUNCATE calls") + carry(s.source, "acme", sharded, "again") + carry(s.source, "acme", sharded, "again") + var held int + s.Require().NoError(sharded.shard.NewRaw("SELECT count(*) FROM agent_responses WHERE customer_id = 'again'").Scan(s.ctx, &held)) + s.Equal(1, held) +} + +// racing imports n naming its own row while takeover, which deletes that row and gives its id to +// resident, is committing, and answers what the import did. +func (s *DataMoveSuite) racing(destination *Store, n namingRow, takeover ...string) error { + spec, _ := dataTableByName(n.table) + db := destination.sideOf(spec) + tx, err := db.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer func() { _ = tx.Rollback() }() + for _, statement := range takeover { + s.execute(tx, statement) + } + imported := make(chan error, 1) + go func() { imported <- destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)) }() + s.waitingOnALock(db, "INSERT INTO "+n.table) + s.Require().NoError(tx.Commit()) + select { + case err := <-imported: + return err + case <-time.After(10 * time.Second): + return errors.New("the import is still waiting") + } +} + +func (s *DataMoveSuite) TestARowWhoseNamedRowIsTakenOverWhileItIsImportedIsRefused() { + s.layouts(func(destination *Store, rows []namingRow) { + for _, n := range rows { + spec, _ := dataTableByName(n.table) + target := namedTables[n.column] + columns, values := "id, customer_id, name", "'resident', 'theirs'" + switch target { + case "agent_sessions": + columns, values = "id, customer_id, state", "'resident', ''" + case "campaign_contacts": + var campaign string + s.Require().NoError(destination.global.NewRaw("SELECT id FROM campaigns WHERE customer_id = 'resident' LIMIT 1").Scan(s.ctx, &campaign)) + columns, values = "id, campaign_id, to_number", "'"+campaign+"', '+15550003333'" + } + err := s.racing(destination, n, "DELETE FROM "+target+" WHERE id = '"+n.own+"'", + fmt.Sprintf("INSERT INTO %s (%s) VALUES ('%s', %s)", target, columns, n.own, values)) + s.assertNamesNoRow(err, namingRow{table: n.table, id: n.id, column: n.column, named: n.own}) + s.Empty(s.nameOf(destination, n), n.table) + s.execute(destination.sideOf(spec), "DELETE FROM "+target+" WHERE id = '"+n.own+"'") + if target == "agent_sessions" { + s.execute(destination.shard, "INSERT INTO agent_sessions (id, customer_id, state) VALUES (?, 'acme', '')", n.own) + } + } + }) +} + +func (s *DataMoveSuite) TestAChildWhoseParentIsTakenOverWhileItIsImportedIsLeftOut() { + _, campaign, _, _ := s.holding(s.destination, "acme") + contact := namingRow{table: "campaign_contacts", id: newID(), column: "campaign_id", own: campaign, + row: map[string]any{"to_number": "+15550004444", "stage": Enrolled, "attempt": 0, "converted": false, "outcome": "", + "instructions": "", "step_id": "", "time_zone": "", "leased_by": "", "variables": map[string]any{}, "seq": 7, + "created_at": "2026-01-01T00:00:00Z"}} + contact.row["id"] = contact.id + + s.Require().NoError(s.racing(s.destination, contact, "DELETE FROM campaigns WHERE id = '"+campaign+"'", + "INSERT INTO campaigns (id, customer_id, name) VALUES ('"+campaign+"', 'resident', 'theirs')")) + + s.Empty(s.nameOf(s.destination, contact)) +} + +// A row naming an id nobody holds is refused at once, and stays refused when another customer's +// row takes that id in the meantime. +func (s *DataMoveSuite) TestARowNamingAnIdBeingTakenByAnotherCustomerIsRefused() { + s.layouts(func(destination *Store, rows []namingRow) { + n := rows[0] + tx, err := destination.shard.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer func() { _ = tx.Rollback() }() + taken := newID() + s.execute(tx, "INSERT INTO agent_sessions (id, customer_id, state) VALUES (?, 'resident', '')", taken) + + err = destination.ImportRow(s.ctx, "acme", n.table, n.naming(taken)) + + s.assertNamesNoRow(err, namingRow{table: n.table, id: n.id, column: n.column, named: taken}) + s.Require().NoError(tx.Commit()) + s.ErrorIs(destination.ImportRow(s.ctx, "acme", n.table, n.naming(taken)), ErrInvalidImport) + }) +} + +// A delete of a session waits for an import of its turns and takes them with it, so neither +// deadlocks on the other. +func (s *DataMoveSuite) TestASessionsDeleteAndAnImportOfItsTurnsDoNotDeadlock() { + s.layouts(func(destination *Store, rows []namingRow) { + n := rows[0] + s.Require().NoError(destination.ImportRow(s.ctx, "acme", n.table, n.naming(n.own))) + tx, err := destination.shard.BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer func() { _ = tx.Rollback() }() + var stale []string + s.Require().NoError(destination.importRow(s.ctx, tx, "acme", n.table, n.naming(n.own), &stale)) + deleted := make(chan error, 1) + go func() { deleted <- destination.Sessions.Delete(s.ctx, "acme", n.own) }() + s.waitingOnALock(destination.shard, "DELETE FROM") + + s.Require().NoError(destination.importRow(s.ctx, tx, "acme", n.table, n.naming(n.own), &stale)) + s.Require().NoError(tx.Commit()) + + s.Require().NoError(<-deleted) + s.Empty(s.nameOf(destination, n)) + }) +} + +// bareColumns are the columns of moved tables that may name a row of another and are held by no +// foreign key, so a row arrives whatever they name. Each is read with the customer: a lookup of it +// finds only a row of the importing customer's. A column that is added to a moved table and could +// name a row is added here with its reader's customer check, or given a foreign key that holds +// the customer, or a reference in dataTables. +var bareColumns = map[string][]string{ + "agent_configs": {"agents", "calls", "channels_chat", "channels_lines", "connectors", "floor_control", "keyterms", + "left_out_connectors", "llm_fallbacks", "resume_history", "sandbox_options", "scheduling", "skills", "tags", "tool_groups", + "turn_taking", "video", "visible_tools", "workflow"}, + "skills": {"config_id", "files"}, + "connector_definitions": {"manifest"}, + "connector_connections": {"account_id", "cached_tools", "connector_id", "granted_scopes", "inputs", "metadata", "owner_id"}, + "router_configs": {"llm", "search", "sts", "stt", "tts"}, + "sip_trunks": {"codecs"}, + "phone_numbers": {"capabilities", "config_id", "stream_app_pk", "tags", "vendor_id"}, + "campaigns": {"calling_hours", "config_id", "sequence", "tags", "usage_categories", "user_id"}, + "campaign_contacts": {"call_id", "step_id", "variables", "vendor_call_id"}, + "campaign_attempts": {"call_id", "step_id", "vendor_call_id"}, + "simulations": {"config_id", "tags"}, + "simulation_runs": {"config_id"}, + "simulation_cases": {"call_id", "transcript"}, + "users": {"custom"}, + "scheduled_tasks": {"channels", "config_id", "conversation_id", "custom", "origin_session_id", "quiet_hours", "session_id", "usage_categories", "user_id"}, + "scheduled_task_runs": {"session_id", "texted"}, + "recordings": {"result", "stt", "tags", "tts"}, + "agent_sessions": {"agent_id", "caller_tools", "config_id", "connector_selections", "conversation_id", "custom", "floor_control", "model_overwrites", "resume_history", "stream_app_pk", "usage_categories", "user_id"}, + "agent_session_tools": {"tools"}, + "calls": {"agent_id", "agent_user_id", "call_id", "campaign_id", "contact_id", "conversation_id", "skills", "stream_app_pk", "tags"}, + "agent_responses": {"parent_response_id", "question_response_id"}, + "agent_response_items": {"payload", "session_id"}, + "conversation_documents": {"conversation_id", "owner_user_id", "response_id", "session_id"}, + "agent_branch_switches": {"fork_message_id", "target_response_id"}, + "agent_branch_messages": {"author_id", "message", "original_message_id", "response_id", "switch_id"}, + "agent_logs": {"agent_id", "config_id", "details", "session_id", "source_id", "user_id"}, + "requests": {"agent_id", "attributes", "call_id", "meters", "operation_id", "session_id", + "source_usage_id", "tags", "turn_id", "usage_categories", "usage_id", "user_id"}, + "turn_latency_hourly": {"agent_id"}, + "customer_activity": {"organization_id"}, + "policies": {"document"}, +} + +// forcedColumns are written by the import itself or left to this deployment, whatever was sent +// (identity, vouched). +var forcedColumns = map[string][]string{ + "connector_connections": {"client_id", "provider_unit_id"}, + "phone_numbers": {"dlc_use_case_id", "stream_call_id", "stream_route_id", "stream_trunk_id"}, + "requests": {"limit_grants", "organization_id"}, +} + +func (s *DataMoveSuite) TestEveryReferenceOfAMovedTableIsCheckedOrReadWithTheCustomer() { + for _, table := range dataTables { + var checked []string + if table.parent != "" { + checked = append(checked, table.parentColumn) + } + for _, reference := range table.references { + checked = append(checked, reference.column) + } + var keys []struct { + Name string + Columns []string `bun:",array"` + Target string + } + s.Require().NoError(s.destination.sideOf(table).NewRaw(` +SELECT c.conname AS name, c.confrelid::regclass::text AS target, + ARRAY(SELECT a.attname::text FROM unnest(c.conkey) AS k JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k) AS columns +FROM pg_constraint c WHERE c.conrelid = ?::regclass AND c.contype = 'f'`, table.name).Scan(s.ctx, &keys)) + var held []string + for _, key := range keys { + held = append(held, key.Columns...) + if table.customer != "" && slices.Contains(key.Columns, table.customer) { + continue + } + s.Require().Len(key.Columns, 1, key.Name) + s.Contains(checked, key.Columns[0], "%s of %s holds no customer: it is a reference", key.Name, table.name) + named := dataReference{key.Columns[0], key.Target} + s.True(slices.Contains(table.references, named) || table.parent != "" && named == table.belonging(), key.Name) + } + var columns []string + s.Require().NoError(s.destination.sideOf(table).NewRaw(` +SELECT attname::text FROM pg_attribute WHERE attrelid = ?::regclass AND attnum > 0 AND NOT attisdropped AND attgenerated = '' + AND (attname ~ '(_ids?|_pk)$' OR atttypid::regtype::text ~ '^(jsonb?|.*\[\])$')`, table.name).Scan(s.ctx, &columns)) + for _, column := range columns { + known := column == table.customer || column == "customer_id" || slices.Contains(held, column) || + slices.Contains(bareColumns[table.name], column) || slices.Contains(forcedColumns[table.name], column) || + slices.Contains(table.vouched, column) + s.True(known, "%s.%s may name a row of another table: see bareColumns", table.name, column) + } + } +} + +// What a bare id names is looked up with the customer, so one of another customer's is not found. +func (s *DataMoveSuite) TestABareIdOfAnotherCustomersRowIsNotFound() { + session, campaign, _, simulation := s.holding(s.destination, "resident") + config := s.seedAgentConfig(s.destination, "resident", "theirs") + voice := s.seedVoice(s.destination, "resident", "theirs") + connection := s.seedConnectorConnection(s.destination, "resident") + s.Require().NoError(s.destination.Responses.Insert(s.ctx, &AgentResponse{ID: newID(), SessionID: session, CustomerID: "resident"})) + + _, err := s.destination.AgentConfigs.Get(s.ctx, "acme", config) + s.ErrorIs(err, ErrNoAgentConfig) + _, err = s.destination.Voices.Get(s.ctx, "acme", voice) + s.ErrorIs(err, ErrNoVoice) + _, err = s.destination.ConnectorConnections.Get(s.ctx, "acme", connection) + s.ErrorIs(err, ErrNoConnectorConnection) + _, err = s.destination.Campaigns.Get(s.ctx, "acme", campaign) + s.Error(err) + _, err = s.destination.Simulations.Get(s.ctx, "acme", simulation) + s.Error(err) + _, err = s.destination.Sessions.Get(s.ctx, "acme", session) + s.Error(err) + turns, err := s.destination.Responses.Select(s.ctx, "acme", session, ResponseFilter{}) + s.Require().NoError(err) + s.Empty(turns) + s.Require().NoError(s.destination.Sessions.Delete(s.ctx, "acme", session)) + _, err = s.destination.Sessions.Get(s.ctx, "resident", session) + s.NoError(err, "nor deleted") +} + +func (s *DataMoveSuite) TestAnImportOfARowThatNamesAnotherIsTwoQueries() { + rows := s.namingRows(s.destination) + sent := &queryCount{} + counted, err := Open(elsewhere(os.Getenv(DSNEnvVar), "moved")) + s.Require().NoError(err) + defer counted.Close() + for _, n := range rows { + s.Require().NoError(counted.ImportRow(s.ctx, "acme", n.table, n.naming(n.own)), n.table) + } + counted.global.AddQueryHook(sent) + for _, n := range rows { + before := sent.sent.Load() + s.Require().NoError(counted.ImportRow(context.WithoutCancel(s.ctx), "acme", n.table, n.naming(n.own)), n.table) + s.EqualValues(2, sent.sent.Load()-before, "%s is validated and written", n.table) + } +} diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index abaeb613ef..8c5bdf3da5 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -345,6 +345,24 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsOneSessionOfIts s.EqualValues(1, buckets[0].ActiveUsers) } +// The turn a carried-on session answers after is its own customer's, so another customer's of that +// id in the shard it went on in is not taken for it. +func (s *ShardedStoreSuite) TestASessionCarriedOnBesideAnotherCustomersTurnIsOneSession() { + session := s.opened("chat", "app", s.base, nil) + s.turned(session, "chat-1", s.base, nil) + theirs := &AgentSession{ID: "theirs", CustomerID: "globex", AgentName: "docs", UserID: "sam", CallerKind: "user", CreatedAt: s.base} + s.Require().NoError(s.other.Sessions.Upsert(s.ctx, theirs)) + s.Require().NoError(s.other.Responses.Insert(s.ctx, &AgentResponse{ID: "chat-1", SessionID: "theirs", CustomerID: "globex", CreatedAt: s.base})) + s.carriedOnAt("chat", s.base.Add(time.Minute)) + s.turnedThere("chat", "chat-2", "chat-1", s.base.Add(time.Minute), nil) + + buckets, err := s.store.CustomerActivity(s.ctx, "app", ActivityDaily, s.base, s.base.Add(24*time.Hour)) + + s.Require().NoError(err) + s.Require().Len(buckets, 1) + s.EqualValues(1, buckets[0].Sessions) +} + func (s *ShardedStoreSuite) TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindow() { dayOne, dayTwo := s.base, s.base.Add(24*time.Hour) session := s.opened("chat", "app", dayOne, nil) diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 1c9f51d5f1..700a5955ea 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -433,7 +433,7 @@ LEFT JOIN call_counts AS c ON c.bucket = b.bucket`, unit, originOnly) func answersAfterAnotherShard(id string) string { return fmt.Sprintf(`EXISTS (SELECT 1 FROM agent_responses AS carried WHERE carried.session_id = %[1]s AND carried.parent_response_id IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM agent_responses AS parent WHERE parent.id = carried.parent_response_id))`, id) + AND NOT EXISTS (SELECT 1 FROM agent_responses AS parent WHERE parent.id = carried.parent_response_id AND parent.customer_id = carried.customer_id))`, id) } // carriedIn is the SQL condition, on a session id column, that this shard's row only carries diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index f497651f31..9dfc708226 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -690,6 +690,10 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { "config_id": "config-7", "agent_id": "agent-7", "session_id": "seeded-session-7", "user_id": "user-7", "source": "agent", "severity": "info", "event_type": "provider_request", "message": "imported", "details": {}, "occurred_at": "2026-03-01T10:00:00Z", "ingested_at": "2026-03-01T10:00:00Z"}`)) }}, + {name: "Store.ImportRow of a turn", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { + return store.ImportRow(ctx, "customer-7", "agent_responses", json.RawMessage(`{"id": "imported-turn", "session_id": "seeded-session-7", + "said": "hello", "status": "completed", "error": "", "created_at": "2026-03-01T10:00:00Z"}`)) + }}, {name: "Store.HoldingTable", index: "agent_logs_customer_order", run: func(ctx context.Context, store *Store) error { _, err := store.HoldingTable(ctx, "customer-123") return err From 517362fd1f7cf511f505e6fc9777b3b1d08ea9db Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 20:52:17 +0000 Subject: [PATCH 2/8] test(store): rows that name others move there, back and on --- .../cmd/router/replicate_repeat_integration_test.go | 1 - .../internal/store/datamove_references_test.go | 12 ++++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/acceleration/cmd/router/replicate_repeat_integration_test.go b/acceleration/cmd/router/replicate_repeat_integration_test.go index a6ec9f82c3..56fe2d6ea2 100644 --- a/acceleration/cmd/router/replicate_repeat_integration_test.go +++ b/acceleration/cmd/router/replicate_repeat_integration_test.go @@ -230,7 +230,6 @@ func (s *ReplicateRepeatSuite) TestARunStopsAtARowThatNamesAnotherAppsRowNamingI s.Require().NoError(err) s.Empty(turns) } - s.Equal(int64(0), *s.saved().Cursor, "the page is not passed") } func (s *ReplicateRepeatSuite) TestARepeatOnceBringsOnlyTheChangesSinceItsCursor() { diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 302434e948..1e22680ff6 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -142,7 +142,9 @@ func (s *DataMoveSuite) assertNamesNoRow(err error, n namingRow) { s.ErrorContains(err, n.table+`:{`, n.table) s.ErrorContains(err, `"`+n.key()+`":"`+n.id+`"`, n.table) s.ErrorContains(err, "a row names a row that neither the export nor this app holds", n.table) - s.NotContains(err.Error(), n.named, "the row it names is not named back") + if n.table != "agent_branch_messages" { // whose key names its session + s.NotContains(err.Error(), n.named, "the row it names is not named back") + } } func (s *DataMoveSuite) TestAnImportedRowNamesOnlyTheImportersRows() { @@ -215,7 +217,7 @@ func (s *DataMoveSuite) TestARowIsRefusedTheSameWhoeverHoldsTheRowItNames() { cancel() s.Require().NoError(tx.Rollback()) - s.EqualError(theirs, missing.Error(), n.table) + s.EqualError(theirs, strings.ReplaceAll(missing.Error(), "nobody-s", n.named), n.table) s.Require().ErrorIs(theirs, ErrInvalidImport, n.table) s.Require().ErrorIs(missing, ErrInvalidImport, n.table) } @@ -266,9 +268,10 @@ func (s *DataMoveSuite) TestARowAnotherCustomerHoldsTheKeyOfIsRefusedAsThat() { // that names another. func (s *DataMoveSuite) TestRowsThatNameOthersMoveThereAndBackAndOn() { session, campaign, contact, simulation := s.holding(s.source, "acme") - s.execute(s.source.global, "UPDATE simulations SET config_id = 'config-1', scenario = 'lost card', variations = 1") + naming := s.namingRows(s.source) + s.execute(s.source.global, "UPDATE simulations SET config_id = 'config-1', scenario = 'lost card', assertion = 'answered', variations = 1") s.execute(s.source.global, "UPDATE campaigns SET config_id = 'config-1', from_number = '+15550001111', concurrency = 1") - for _, n := range s.namingRows(s.source) { + for _, n := range naming { own := map[string]string{"session_id": session, "simulation_id": simulation, "contact_id": contact}[n.column] if n.table == "campaign_attempts" { n.row["campaign_id"] = campaign @@ -455,6 +458,7 @@ var bareColumns = map[string][]string{ "agent_logs": {"agent_id", "config_id", "details", "session_id", "source_id", "user_id"}, "requests": {"agent_id", "attributes", "call_id", "meters", "operation_id", "session_id", "source_usage_id", "tags", "turn_id", "usage_categories", "usage_id", "user_id"}, + "turn_stats_hourly": {"agent_id"}, "turn_latency_hourly": {"agent_id"}, "customer_activity": {"organization_id"}, "policies": {"document"}, From 6c60be737c037741cfb9892bdc676b213f6a84ae Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 21:24:36 +0000 Subject: [PATCH 3/8] test(store): an import does not wait for an edit of the row it names --- acceleration/README.md | 8 ++++---- .../store/datamove_references_test.go | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/acceleration/README.md b/acceleration/README.md index d69daf2b39..0cccd43184 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2903,10 +2903,10 @@ The customer is always the authenticated caller, never anything in the body or t so an export is the caller's own data and an import lands under the caller's own app however the file was edited on the way. An import upserts and refuses a row whose primary key belongs to another tenant, so replaying the same change twice lands where applying it -once would and a guessed id overwrites nothing. A session's call, turn or branch, a simulation's run and a -campaign's attempt name only a session, simulation or contact the app holds here: a row that names another -is refused by its table and primary key (`agent_responses:{"id":"turn-1"}`), and a line of an -import answers it 400. A request row is the exception: each +once would and a guessed id overwrites nothing. A session's call, turn or branch, a simulation's +run and a campaign's attempt name only a session, simulation or contact the app holds here. A row that +names another is refused, whoever holds that one: `replicate` stops at it and names it, and +`POST /v1/data/import` answers 400 and says only that the row cannot be written here. A request row is the exception: each deployment numbers its own, so it is imported with an id the destination gives it, under a `usage_id` made from the importing app and the `usage_id` the row had where it was first recorded (its source id, for a row from before usage ids), and written once. It keeps that diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 6453dfe5a2..9383e6a130 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -400,6 +400,25 @@ func (s *DataMoveSuite) TestARowNamingAnIdBeingTakenByAnotherCustomerIsRefused() }) } +// A row being written elsewhere that names the same row, or an edit of that row, holds no import up. +func (s *DataMoveSuite) TestAnImportDoesNotWaitForAnEditOfTheRowItNames() { + s.layouts(func(destination *Store, rows []namingRow) { + n := rows[0] + for _, lock := range []string{"KEY SHARE", "NO KEY UPDATE"} { + tx, err := destination.shard.BeginTx(s.ctx, nil) + s.Require().NoError(err) + s.execute(tx, "SELECT 1 FROM agent_sessions WHERE id = ? FOR "+lock, n.own) + + within, cancel := context.WithTimeout(s.ctx, 2*time.Second) + err = destination.ImportRow(within, "acme", n.table, n.naming(n.own)) + cancel() + + s.Require().NoError(tx.Rollback()) + s.Require().NoError(err, lock) + } + }) +} + // A delete of a session waits for an import of its turns and takes them with it, so neither // deadlocks on the other. func (s *DataMoveSuite) TestASessionsDeleteAndAnImportOfItsTurnsDoNotDeadlock() { From 9194e4ee0c2de8a3d15acf38ee7d8f22eb0e83d7 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 22:18:20 +0000 Subject: [PATCH 4/8] fix(store): campaign dials and turns are read beside their own campaign's and customer's rows --- acceleration/api/openapi.yaml | 2 +- acceleration/internal/api/datamove_test.go | 9 ++ acceleration/internal/api/handwritten.go | 3 +- acceleration/internal/campaign/runner_test.go | 21 ++++ .../internal/store/campaign_attempt.go | 8 +- .../internal/store/campaign_contact.go | 1 + .../internal/store/campaign_contact_test.go | 42 +++++++ .../store/conversation_document_test.go | 14 +++ acceleration/internal/store/datamove.go | 8 ++ .../store/datamove_references_test.go | 116 +++++++++++++++--- acceleration/internal/store/response.go | 2 +- acceleration/internal/store/shards_test.go | 32 +++++ acceleration/internal/store/store.go | 20 +-- .../_generated/api/default/import_data.py | 12 +- sdks/go/acceleration/generated.go | 8 +- sdks/js/src/generated/api.ts | 2 +- 16 files changed, 259 insertions(+), 41 deletions(-) diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 910a884944..0fd01acbe5 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -22338,7 +22338,7 @@ paths: /v1/data/import: post: description: |- - Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 25e86d7ed2..02b5a5b270 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -411,6 +411,15 @@ func (s *DataMoveSuite) TestAnImportedRowThatNamesARowTheAppDoesNotHoldIsRefused } } +func (s *DataMoveSuite) TestAnImportedRunOfATaskTheAppDoesNotHoldIsRefusedTheSame() { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{{Table: "scheduled_task_runs", + Row: json.RawMessage(`{"id": "run", "task_id": "not-here", "state": "delivered", "trigger": "schedule", "attempts": 0, "prompt": "", + "delivered_to": "", "session_id": "", "texted": [], "scheduled_for": "2026-01-01T00:00:00Z", "created_at": "2026-01-01T00:00:00Z"}`)}})) + + s.Equal(http.StatusBadRequest, status) + s.Equal(`store: import scheduled_task_runs:{"id":"run"}: this row cannot be written here`, failure) +} + // A change to a policy of another scope is skipped, so the answer counts no row for it. func (s *DataMoveSuite) TestAChangeToAnotherScopesPolicyIsNotCountedAsWritten() { key := `{"scope": "organization", "scope_id": ` + strconv.Quote(s.customerID()) + `}` diff --git a/acceleration/internal/api/handwritten.go b/acceleration/internal/api/handwritten.go index f4d9096535..88712f5a40 100644 --- a/acceleration/internal/api/handwritten.go +++ b/acceleration/internal/api/handwritten.go @@ -974,7 +974,8 @@ func documentHandWritten(api huma.API) { "same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app " + "whatever the file says, so an export from one app cannot be imported into another's " + "rows, and rows belonging to a customer through a parent are only written where that " + - "parent is the caller's.\n" + + "parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does " + + "not hold here is refused with 400.\n" + "An export's rows are written as the source had them, so an export is refused with 409 " + "`conflict`, before any of its rows is written, for an app that already has a row here in a " + "table of the shared database: it would undo what was done here since. `full=true` writes it " + diff --git a/acceleration/internal/campaign/runner_test.go b/acceleration/internal/campaign/runner_test.go index 77f5b41af4..72754d4df8 100644 --- a/acceleration/internal/campaign/runner_test.go +++ b/acceleration/internal/campaign/runner_test.go @@ -407,6 +407,27 @@ func (s *RunnerSuite) TestAContactClaimedBeforeItWasEverDialedGoesBackUnused() { s.Empty(attempts) } +func (s *RunnerSuite) TestATakeOverReadsOnlyTheDialsOfTheContactsCampaign() { + campaign := s.launched(s.single(), 1, "UTC", "+15550000001") + claimed, err := s.store.CampaignContacts.Claim(s.ctx, "router-dead", s.clock.now(), lease, 10) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + other := store.Campaign{CustomerID: uuid.NewString(), Name: "other", ConfigID: "config-1", FromNumber: "+15550100000", Concurrency: 1} + s.Require().NoError(s.store.Campaigns.Insert(s.ctx, &other)) + stray := store.CampaignAttempt{CampaignID: other.ID, ContactID: claimed[0].Contact.ID, StepID: "step_1", Attempt: 1, Dial: 1, + CallID: "another-call", StartedAt: s.clock.now(), CallOutcome: "no_answer"} + s.Require().NoError(s.store.CampaignAttempts.Insert(s.ctx, &stray)) + s.leasesPass(lease + time.Minute) + + s.runner.takeOver(s.ctx) + + contact, attempts := s.contact(campaign, "+15550000001") + s.Equal(store.Enrolled, contact.Stage) + s.Equal(0, contact.Attempt) + s.Empty(contact.CallID) + s.Empty(attempts) +} + func (s *RunnerSuite) TestATakeOverOfAnAttemptNeverDialedLeavesItUnused() { campaign := s.launched(s.single(), 1, "UTC", "+15550000001") s.tick(s.runner) diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index 762c72d34a..8938433ca5 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -112,10 +112,15 @@ func (r *CampaignAttempts) End(ctx context.Context, customerID, id string, resul return nil } +// ofItsContactsCampaign is the condition that a dial is of the campaign its contact is of, as every +// dial a runner places is. +const ofItsContactsCampaign = "campaign_id = (SELECT cc.campaign_id FROM campaign_contacts AS cc WHERE cc.id = contact_id)" + // CountResult counts a contact's dials of one attempt that ended with result. func (r *CampaignAttempts) CountResult(ctx context.Context, contactID string, attempt int, result string) (int, error) { count, err := r.store.global.NewSelect().Model((*CampaignAttempt)(nil)). Where("contact_id = ?", contactID). + Where(ofItsContactsCampaign). Where("attempt = ?", attempt). Where("result = ?", result). Count(ctx) @@ -130,6 +135,7 @@ func (r *CampaignAttempts) Latest(ctx context.Context, contactID string) (Campai var attempt CampaignAttempt err := r.store.global.NewSelect().Model(&attempt). Where("contact_id = ?", contactID). + Where(ofItsContactsCampaign). Order("started_at DESC", "dial DESC"). Limit(1). Scan(ctx) @@ -276,7 +282,7 @@ func (r *CampaignAttempts) Made(ctx context.Context, contactIDs []string) (map[s Made int } err := r.store.global.NewRaw(`SELECT contact_id, count(DISTINCT (step_id, attempt)) AS made -FROM campaign_attempts WHERE contact_id IN (?) AND `+placedDial+` +FROM campaign_attempts WHERE contact_id IN (?) AND `+ofItsContactsCampaign+` AND `+placedDial+` GROUP BY contact_id`, bun.In(contactIDs)).Scan(ctx, &rows) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: count attempts made: %w", err)) diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index 4fe0908f2c..cd3c4924d3 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -630,6 +630,7 @@ func (r *CampaignContacts) settleContact(ctx context.Context, owner, contactID s Set("classify_state = ?", classifyAbandoned). Set("classify_after = NULL"). Where("contact_id = ?", contactID). + Where(ofItsContactsCampaign). Where("classify_state = ?", classifyPending). Exec(ctx); err != nil { return fmt.Errorf("store: abandon pending classifications: %w", err) diff --git a/acceleration/internal/store/campaign_contact_test.go b/acceleration/internal/store/campaign_contact_test.go index 0404c40ef2..69af9a74f1 100644 --- a/acceleration/internal/store/campaign_contact_test.go +++ b/acceleration/internal/store/campaign_contact_test.go @@ -488,6 +488,48 @@ func (s *StoreSuite) TestOnlyADialOfTheContactsCampaignIsClassified() { s.Equal(dial.ID, claimed[0].Attempt.ID) } +func (s *StoreSuite) TestTheLatestDialIsOfTheContactsCampaign() { + contact := s.contactsOf(s.draftCampaign(newID(), "+15550001"))[0] + s.strayDial(contact, s.base) + + _, found, err := s.store.CampaignAttempts.Latest(s.ctx, contact.ID) + + s.Require().NoError(err) + s.False(found) +} + +func (s *StoreSuite) TestDialsMadeAreOfTheContactsCampaign() { + contact := s.contactsOf(s.draftCampaign(newID(), "+15550001"))[0] + s.strayDial(contact, s.base) + + made, err := s.store.CampaignAttempts.Made(s.ctx, []string{contact.ID}) + + s.Require().NoError(err) + s.Empty(made) +} + +func (s *StoreSuite) TestDialsCountedByResultAreOfTheContactsCampaign() { + contact := s.contactsOf(s.draftCampaign(newID(), "+15550001"))[0] + s.strayDial(contact, s.base) + + count, err := s.store.CampaignAttempts.CountResult(s.ctx, contact.ID, 1, "") + + s.Require().NoError(err) + s.Zero(count) +} + +func (s *StoreSuite) TestSettlingAContactLeavesAnotherCampaignsDial() { + s.runningCampaign(5, "+15550001") + contact := s.claimDue("a", s.base, 10)[0].Contact + s.strayDial(contact, s.base) + + s.Require().NoError(s.store.CampaignContacts.Settle(s.ctx, "a", contact.ID, Settle{Stage: ContactCompleted, Attempt: 1})) + + var states []string + s.Require().NoError(s.store.GlobalDB().NewSelect().Table("campaign_attempts").Column("classify_state").Scan(s.ctx, &states)) + s.Equal([]string{"pending"}, states) +} + func (s *StoreSuite) TestADialWhoseContactAnotherRunnerHoldsIsNotClassified() { campaign := s.runningCampaign(5, "+15550001") contact := s.claimDue("a", s.base, 10)[0].Contact diff --git a/acceleration/internal/store/conversation_document_test.go b/acceleration/internal/store/conversation_document_test.go index ea48f622d3..e093fd5858 100644 --- a/acceleration/internal/store/conversation_document_test.go +++ b/acceleration/internal/store/conversation_document_test.go @@ -83,6 +83,20 @@ func (s *StoreSuite) TestADocumentSentWithARewoundTurnIsNotRead() { s.Equal([]string{"kept"}, s.documentIDs(DocumentScope{SessionID: "one", Owner: "jlahey"})) } +func (s *StoreSuite) TestARewindToAnotherCustomersTurnRewindsNothing() { + s.opened("one", "app", s.base, nil) + s.responded("one", "first", "read this", s.base) + s.opened("theirs", "somebody-else", s.base, nil) + s.Require().NoError(s.store.Responses.Insert(s.ctx, &AgentResponse{ID: "their-turn", SessionID: "theirs", CustomerID: "somebody-else", + CreatedAt: s.base.Add(-time.Hour)})) + + s.Require().NoError(s.store.Responses.Rewind(s.ctx, "app", "one", "their-turn", s.base.Add(time.Hour))) + + first, err := s.store.Responses.Get(s.ctx, "app", "one", "first") + s.Require().NoError(err) + s.Nil(first.RewoundAt) +} + func (s *StoreSuite) TestAForkStoppingAtATurnReadsOnlyTheDocumentsSentUpToIt() { s.opened("one", "app", s.base, nil) s.responded("one", "first", "read this", s.base) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 98ef1a24f7..eb62aea3c2 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -1033,6 +1033,14 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str if returning == "" { result, err := db.ExecContext(ctx, query, args...) if err != nil { + if isViolation(err, foreignKeyViolation) { + // A foreign key that holds the customer: the row it names is missing, or another's. + named, keyErr := rowKey(table, shape.keys, row) + if keyErr != nil { + return keyErr + } + return stack.Wrap(invalidImport(marked{fmt.Errorf("store: import %s: %w", named, ErrNamesNoRow), err})) + } if refused := refusedRow(table, err); refused != nil { return refused } diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 9383e6a130..4e0e361d5b 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -484,6 +484,24 @@ var bareColumns = map[string][]string{ "policies": {"document"}, } +// bareTexts are the text columns of moved tables that hold an id under another name, by how they are read: +// forked_from is only answered back, claimed_by is looked up among the customer's users, a +// channel_thread of another customer's is refused by the delivery, and spend by api_key is read with the app. +var bareTexts = []string{"api_key", "channel_thread", "claimed_by", "forked_from"} + +// words are the text columns of moved tables that hold no row's id. +var words = strings.Fields(` + agent_name area assertion auth_scheme call_outcome call_type callback caller_kind caller_stt caller_target caller_tts + caller_voice category channel classify_state client client_registration content_type country created_by declared_title + default_country delivered_to description direction e164 email end_reason ended error error_code error_message event_type + from_number greeting greeting_mode guardrail harness host image instructions judge_target kind label last_error + last_refusal_code leased_by leg llm markdown message modality mode model name namespace knowledge_namespace object_key + organization_tier outcome owner_type paused_reason price_version project prompt provider purpose reason recipient region + result return_url review_instructions review_notes role rrule said sandbox_provider scenario scope search severity sha256 + ship_error sku source stage state status stream_call_type sts stt subagent summary sync_hash tag_key tag_value team text + time_zone timezone title tls_scheme to_number tool_name tools_digest transport trigger tts type ui_instructions url username + validation_code validation_error validation_status vendor verdict video_source voice`) + // forcedColumns are written by the import itself or left to this deployment, whatever was sent // (identity, vouched). var forcedColumns = map[string][]string{ @@ -524,9 +542,9 @@ FROM pg_constraint c WHERE c.conrelid = ?::regclass AND c.contype = 'f'`, table. var columns []string s.Require().NoError(s.destination.sideOf(table).NewRaw(` SELECT attname::text FROM pg_attribute WHERE attrelid = ?::regclass AND attnum > 0 AND NOT attisdropped AND attgenerated = '' - AND (attname ~ '(_ids?|_pk)$' OR atttypid::regtype::text ~ '^(jsonb?|.*\[\])$')`, table.name).Scan(s.ctx, &columns)) + AND (attname ~ '(_ids?|_pk)$' OR atttypid::regtype::text ~ '^(text|uuid|jsonb?|.*\[\])$')`, table.name).Scan(s.ctx, &columns)) for _, column := range columns { - known := column == table.customer || column == "customer_id" || slices.Contains(held, column) || + known := column == "id" || slices.Contains(bareTexts, column) || slices.Contains(words, column) || column == table.customer || column == "customer_id" || slices.Contains(held, column) || slices.Contains(bareColumns[table.name], column) || slices.Contains(forcedColumns[table.name], column) || slices.Contains(table.vouched, column) s.True(known, "%s.%s may name a row of another table: see bareColumns", table.name, column) @@ -534,32 +552,94 @@ SELECT attname::text FROM pg_attribute WHERE attrelid = ?::regclass AND attnum > } } -// What a bare id names is looked up with the customer, so one of another customer's is not found. +// A moved row arrives whatever its bare ids name, and what each names is looked up with the +// customer, so one of another customer's is not found by them, and theirs does not find the row. func (s *DataMoveSuite) TestABareIdOfAnotherCustomersRowIsNotFound() { - session, campaign, _, simulation := s.holding(s.destination, "resident") + session, campaign, contact, simulation := s.holding(s.destination, "resident") config := s.seedAgentConfig(s.destination, "resident", "theirs") voice := s.seedVoice(s.destination, "resident", "theirs") connection := s.seedConnectorConnection(s.destination, "resident") - s.Require().NoError(s.destination.Responses.Insert(s.ctx, &AgentResponse{ID: newID(), SessionID: session, CustomerID: "resident"})) - - _, err := s.destination.AgentConfigs.Get(s.ctx, "acme", config) - s.ErrorIs(err, ErrNoAgentConfig) - _, err = s.destination.Voices.Get(s.ctx, "acme", voice) + turn := newID() + s.execute(s.destination.shard, "INSERT INTO agent_responses (id, session_id, customer_id, created_at) VALUES (?, ?, 'resident', '2026-01-01')", turn, session) + db := s.source.GlobalDB() + s.execute(db, "INSERT INTO agent_configs (id, customer_id, name, voice, connectors) VALUES ('own', 'acme', 'own', ?, jsonb_build_array("+ + "jsonb_build_object('name', 'a', 'connector_id', 'custom_acme', 'connection', jsonb_build_object('type', 'fixed', 'connection_id', ?::text))))", voice, connection) + s.execute(db, "INSERT INTO skills (id, customer_id, config_id, name, description, instructions) VALUES ('sk', 'acme', ?, 'look', '', '')", config) + s.execute(db, "INSERT INTO agent_sessions (id, customer_id, state, config_id, forked_from) VALUES ('se', 'acme', '', ?, ?)", config, session) + s.execute(db, "INSERT INTO agent_responses (id, session_id, customer_id, parent_response_id, question_response_id) VALUES ('r', 'se', 'acme', ?, ?)", turn, turn) + s.execute(db, "INSERT INTO conversation_documents (id, customer_id, owner_user_id, session_id, response_id, name, markdown, sha256)"+ + " VALUES ('d', 'acme', 'sam', ?, ?, 'a', 'b', 'c')", session, turn) + s.execute(db, "INSERT INTO calls (id, customer_id, agent_id, call_id, campaign_id, contact_id) VALUES ('c', 'acme', 'a', 'c', ?, ?)", campaign, contact) + s.execute(db, "INSERT INTO agent_logs (customer_id, source, severity, event_type, message, config_id, session_id, occurred_at)"+ + " VALUES ('acme', 'agent', 'info', 'turn', 'm', ?, ?, now())", config, session) + s.execute(db, "INSERT INTO scheduled_tasks (id, customer_id, config_id, user_id, title, instructions, start_local, timezone, state, session_id, origin_session_id)"+ + " VALUES ('t', 'acme', ?, 'sam', 'a', 'b', '2026-12-01', 'UTC', 'paused', ?, ?)", config, session, session) + + s.move("acme", "acme") + + here := s.destination + moved, err := here.AgentConfigs.Get(s.ctx, "acme", "own") + s.Require().NoError(err) + s.Equal(connection, moved.Connectors[0].Connection.ConnectionID) + _, err = here.Voices.Get(s.ctx, "acme", moved.Voice) s.ErrorIs(err, ErrNoVoice) - _, err = s.destination.ConnectorConnections.Get(s.ctx, "acme", connection) + _, err = here.ConnectorConnections.Get(s.ctx, "acme", connection) s.ErrorIs(err, ErrNoConnectorConnection) - _, err = s.destination.Campaigns.Get(s.ctx, "acme", campaign) + uses, err := here.ConnectorConnections.Uses(s.ctx, "resident", []string{connection}) + s.Require().NoError(err) + s.Empty(uses) + row, err := here.Sessions.Get(s.ctx, "acme", "se") + s.Require().NoError(err) + s.Equal(session, row.ForkedFrom) + _, err = here.Sessions.Get(s.ctx, "acme", row.ForkedFrom) s.Error(err) - _, err = s.destination.Simulations.Get(s.ctx, "acme", simulation) + _, err = here.AgentConfigs.Get(s.ctx, "acme", row.ConfigID) + s.ErrorIs(err, ErrNoAgentConfig) + answer, err := here.Responses.Get(s.ctx, "acme", "se", "r") + s.Require().NoError(err) + s.Equal(turn, answer.ParentResponseID) + _, err = here.Responses.Get(s.ctx, "acme", "se", answer.ParentResponseID) + s.ErrorIs(err, ErrUnknownResponse) + siblings, err := here.Responses.Siblings(s.ctx, "acme", "se", "r", SiblingsOfReply) + s.Require().NoError(err) + s.Len(siblings, 1) + _, err = here.Campaigns.Get(s.ctx, "acme", campaign) s.Error(err) - _, err = s.destination.Sessions.Get(s.ctx, "acme", session) + _, err = here.Simulations.Get(s.ctx, "acme", simulation) s.Error(err) - turns, err := s.destination.Responses.Select(s.ctx, "acme", session, ResponseFilter{}) + + skills, err := here.Skills.Select(s.ctx, "resident", SkillFilter{ConfigID: config}) + s.Require().NoError(err) + s.Empty(skills) + calls, err := here.Calls.Select(s.ctx, "resident", CallFilter{CampaignID: campaign}) + s.Require().NoError(err) + s.Empty(calls) + logs, err := here.AgentLogs.Select(s.ctx, "resident", AgentLogFilter{SessionID: session, ConfigID: config}) + s.Require().NoError(err) + s.Empty(logs) + documents, err := here.ConversationDocuments.Select(s.ctx, "resident", DocumentScope{SessionID: session, Owner: "sam"}) s.Require().NoError(err) - s.Empty(turns) - s.Require().NoError(s.destination.Sessions.Delete(s.ctx, "acme", session)) - _, err = s.destination.Sessions.Get(s.ctx, "resident", session) - s.NoError(err, "nor deleted") + s.Empty(documents) + tasks, err := here.ScheduledTasks.Select(s.ctx, "resident", ScheduledTaskFilter{SessionID: session}) + s.Require().NoError(err) + s.Empty(tasks) + + s.Require().NoError(here.ScheduledTasks.DeleteForSession(s.ctx, "resident", session)) + s.Require().NoError(here.Sessions.Delete(s.ctx, "resident", session)) + left := s.exportFrom(here, "acme") + s.Len(left.of("scheduled_tasks"), 1) + s.Len(left.of("conversation_documents"), 1) + s.Len(left.of("agent_logs"), 1) +} + +// A foreign key that holds the customer refuses a row the same way, named by its key. +func (s *DataMoveSuite) TestARunOfATaskNotHereIsRefusedByItsKey() { + err := s.destination.ImportRow(s.ctx, "acme", "scheduled_task_runs", json.RawMessage(`{"id": "run", "task_id": "not-here", "state": "delivered", + "trigger": "schedule", "attempts": 0, "prompt": "", "delivered_to": "", "session_id": "", "texted": [], + "scheduled_for": "2026-01-01T00:00:00Z", "created_at": "2026-01-01T00:00:00Z"}`)) + + s.ErrorIs(err, ErrInvalidImport) + s.EqualError(err, `store: import scheduled_task_runs:{"id":"run"}: a row names a row that neither the export nor this app holds`) } func (s *DataMoveSuite) TestAnImportOfARowThatNamesAnotherIsTwoQueries() { diff --git a/acceleration/internal/store/response.go b/acceleration/internal/store/response.go index 17558044df..891ff071b9 100644 --- a/acceleration/internal/store/response.go +++ b/acceleration/internal/store/response.go @@ -437,7 +437,7 @@ func (r *Responses) Rewind(ctx context.Context, customerID, sessionID, kept stri // read first rather than in each shard's update. keptAt, err := whicheverShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (AgentResponse, error) { var response AgentResponse - err := db.NewSelect().Model(&response).Column("created_at", "id").Where("id = ?", kept).Scan(ctx) + err := db.NewSelect().Model(&response).Column("created_at", "id").Where("id = ?", kept).Where("customer_id = ?", customerID).Scan(ctx) return response, err }) if errors.Is(err, sql.ErrNoRows) { diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 8c5bdf3da5..490b891cdf 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -363,6 +363,38 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnBesideAnotherCustomersTurnIsOne s.EqualValues(1, buckets[0].Sessions) } +// strayTurnThere records another customer's turn naming a session of "app", in the other shard. +func (s *ShardedStoreSuite) strayTurnThere(id, parent string) { + _, err := s.other.shard.ExecContext(s.ctx, "INSERT INTO agent_responses (id, session_id, customer_id, parent_response_id, created_at)"+ + " VALUES (?, 'chat', 'globex', NULLIF(?, ''), ?)", id, parent, s.base) + s.Require().NoError(err) +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnIsOneSessionBesideAnotherCustomersFirstTurn() { + session := s.opened("chat", "app", s.base, nil) + s.turned(session, "chat-1", s.base, nil) + s.carriedOnAt("chat", s.base.Add(time.Minute)) + s.turnedThere("chat", "chat-2", "chat-1", s.base.Add(time.Minute), nil) + s.strayTurnThere("stray", "") + + buckets, err := s.store.CustomerActivity(s.ctx, "app", ActivityDaily, s.base, s.base.Add(24*time.Hour)) + + s.Require().NoError(err) + s.Require().Len(buckets, 1) + s.EqualValues(1, buckets[0].Sessions, "it began in the other shard") +} + +func (s *ShardedStoreSuite) TestASessionBegunInOneShardIsCountedBesideAnotherCustomersTurn() { + s.carriedOnAt("chat", s.base) + s.strayTurnThere("stray", "not-here") + + buckets, err := s.store.CustomerActivity(s.ctx, "app", ActivityDaily, s.base, s.base.Add(24*time.Hour)) + + s.Require().NoError(err) + s.Require().Len(buckets, 1) + s.EqualValues(1, buckets[0].Sessions, "no turn of its own says it was carried on") +} + func (s *ShardedStoreSuite) TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindow() { dayOne, dayTwo := s.base, s.base.Add(24*time.Hour) session := s.opened("chat", "app", dayOne, nil) diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 4684cf17d9..9497f4ba2b 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -294,7 +294,7 @@ func (s *Store) CustomerActivity( // rows that carry it on count nothing, and what was said in them is counted as messages. originOnly := "" if len(s.peers) > 0 { - originOnly = " AND NOT " + carriedIn("sess.id") + originOnly = " AND NOT " + carriedIn("sess.id", "sess.customer_id") } // Who was seen is read apart from the counts: a person is one person however many shards // they talked to in a bucket, and a guest who signed up is the account they became, which @@ -441,21 +441,21 @@ LEFT JOIN call_counts AS c ON c.bucket = b.bucket`, unit, originOnly) return buckets, nil } -// answersAfterAnotherShard is the SQL condition, on a session id column, that the session has a +// answersAfterAnotherShard is the SQL condition, on a session id and its customer's, that the session has a // response here answered after one this shard does not hold: it was carried on here from // another shard, whose newest response a reopened session answers after (Responses.ActiveLeaf). -func answersAfterAnotherShard(id string) string { +func answersAfterAnotherShard(id, customer string) string { return fmt.Sprintf(`EXISTS (SELECT 1 FROM agent_responses AS carried - WHERE carried.session_id = %[1]s AND carried.parent_response_id IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM agent_responses AS parent WHERE parent.id = carried.parent_response_id AND parent.customer_id = carried.customer_id))`, id) + WHERE carried.session_id = %[1]s AND carried.customer_id = %[2]s AND carried.parent_response_id IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM agent_responses AS parent WHERE parent.id = carried.parent_response_id AND parent.customer_id = carried.customer_id))`, id, customer) } -// carriedIn is the SQL condition, on a session id column, that this shard's row only carries +// carriedIn is the SQL condition, on a session id and its customer's, that this shard's row only carries // the session on: its first turn, a response with no parent, is elsewhere. A carried row with // no response yet cannot be told from the one it began in. -func carriedIn(id string) string { - return fmt.Sprintf(`(%[2]s AND NOT EXISTS (SELECT 1 FROM agent_responses AS began - WHERE began.session_id = %[1]s AND began.parent_response_id IS NULL))`, id, answersAfterAnotherShard(id)) +func carriedIn(id, customer string) string { + return fmt.Sprintf(`(%[3]s AND NOT EXISTS (SELECT 1 FROM agent_responses AS began + WHERE began.session_id = %[1]s AND began.customer_id = %[2]s AND began.parent_response_id IS NULL))`, id, customer, answersAfterAnotherShard(id, customer)) } // CustomerConcurrencyPeak returns the most sessions one customer had open at the same time @@ -614,7 +614,7 @@ func (s *Store) CustomerToolUsage(ctx context.Context, customerID, configID stri array_agg(CASE WHEN c.session_id IS NULL THEN '' ELSE u.session_id END ORDER BY u.session_id) AS first_carriers` carriers = ` carriers AS ( - SELECT DISTINCT session_id FROM first_use WHERE ` + answersAfterAnotherShard("first_use.session_id") + ` + SELECT DISTINCT session_id FROM first_use WHERE ` + answersAfterAnotherShard("first_use.session_id", "?3") + ` ),` carriedJoin = "\n LEFT JOIN carriers AS c ON c.session_id = u.session_id" } diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py index dd6fb44b93..9d10f3cce6 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py @@ -113,7 +113,8 @@ def sync_detailed( with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the - caller's. + caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not + hold here is refused with 400. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -160,7 +161,8 @@ def sync( with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the - caller's. + caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not + hold here is refused with 400. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -202,7 +204,8 @@ async def asyncio_detailed( with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the - caller's. + caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not + hold here is refused with 400. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -247,7 +250,8 @@ async def asyncio( with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the - caller's. + caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not + hold here is refused with 400. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index f3737cd702..663cfb3d31 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -15638,7 +15638,7 @@ type ClientInterface interface { // ImportDataWithBody Write an export, or a batch of changes, into this deployment // - // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. @@ -21417,7 +21417,7 @@ func (c *Client) ExportData(ctx context.Context, reqEditors ...RequestEditorFn) // ImportDataWithBody Write an export, or a batch of changes, into this deployment // -// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. +// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. @@ -39089,7 +39089,7 @@ type ClientWithResponsesInterface interface { // ImportDataWithBodyWithResponse Write an export, or a batch of changes, into this deployment // - // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. @@ -71855,7 +71855,7 @@ func (c *ClientWithResponses) ExportDataWithResponse(ctx context.Context, reqEdi // ImportDataWithBodyWithResponse Write an export, or a batch of changes, into this deployment // -// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. +// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index b2f86d4169..a659ab9fb6 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -3231,7 +3231,7 @@ export type paths = { readonly put?: never; /** * Write an export, or a batch of changes, into this deployment - * @description Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + * @description Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. A row that refers to a session, simulation, contact, task or trunk the caller does not hold here is refused with 400. * An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. * An app runs one import at a time on a router, and a router runs at most four imports at once. An import ends when a line has taken a minute to arrive. * Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. From 32adf7da2347d1f1e20a088655bb722b03f83d2d Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 22:39:14 +0000 Subject: [PATCH 5/8] test(store): a run of a task not here is refused by its key --- acceleration/internal/store/datamove_references_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 4e0e361d5b..1d7dda7ee5 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -581,7 +581,7 @@ func (s *DataMoveSuite) TestABareIdOfAnotherCustomersRowIsNotFound() { moved, err := here.AgentConfigs.Get(s.ctx, "acme", "own") s.Require().NoError(err) s.Equal(connection, moved.Connectors[0].Connection.ConnectionID) - _, err = here.Voices.Get(s.ctx, "acme", moved.Voice) + _, err = here.Voices.Get(s.ctx, "acme", moved.Models.Voice) s.ErrorIs(err, ErrNoVoice) _, err = here.ConnectorConnections.Get(s.ctx, "acme", connection) s.ErrorIs(err, ErrNoConnectorConnection) @@ -639,6 +639,7 @@ func (s *DataMoveSuite) TestARunOfATaskNotHereIsRefusedByItsKey() { "scheduled_for": "2026-01-01T00:00:00Z", "created_at": "2026-01-01T00:00:00Z"}`)) s.ErrorIs(err, ErrInvalidImport) + s.ErrorIs(err, ErrNamesNoRow) s.EqualError(err, `store: import scheduled_task_runs:{"id":"run"}: a row names a row that neither the export nor this app holds`) } From 78cd801d4eb4d47f806d32e0be238eb59f7b136b Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 00:01:10 +0000 Subject: [PATCH 6/8] test(store): the import's refusals and the tool counts each have a row of their own --- .../replicate_repeat_integration_test.go | 2 +- .../store/datamove_references_test.go | 85 +++++++++++++++---- acceleration/internal/store/shards_test.go | 16 ++++ 3 files changed, 87 insertions(+), 16 deletions(-) diff --git a/acceleration/cmd/router/replicate_repeat_integration_test.go b/acceleration/cmd/router/replicate_repeat_integration_test.go index 56fe2d6ea2..5b79de0d7b 100644 --- a/acceleration/cmd/router/replicate_repeat_integration_test.go +++ b/acceleration/cmd/router/replicate_repeat_integration_test.go @@ -211,7 +211,7 @@ func (s *ReplicateRepeatSuite) TestAFirstCopyBringsEverythingAndSavesTheCursor() s.WithinDuration(time.Now(), saved.ReadAt, time.Minute) } -// A copy, a page of changes and a full copy each stop at a row that names another app's row here. +// A page of changes and a full copy each stop at a row that names another app's row here. func (s *ReplicateRepeatSuite) TestARunStopsAtARowThatNamesAnotherAppsRowNamingIt() { for _, in := range []*store.Store{s.source, s.target} { _, err := in.GlobalDB().ExecContext(s.ctx, "INSERT INTO agent_sessions (id, customer_id, state) VALUES ('theirs', 'resident', '')") diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 1d7dda7ee5..1c8c6b6d98 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -487,20 +487,53 @@ var bareColumns = map[string][]string{ // bareTexts are the text columns of moved tables that hold an id under another name, by how they are read: // forked_from is only answered back, claimed_by is looked up among the customer's users, a // channel_thread of another customer's is refused by the delivery, and spend by api_key is read with the app. -var bareTexts = []string{"api_key", "channel_thread", "claimed_by", "forked_from"} - -// words are the text columns of moved tables that hold no row's id. -var words = strings.Fields(` - agent_name area assertion auth_scheme call_outcome call_type callback caller_kind caller_stt caller_target caller_tts - caller_voice category channel classify_state client client_registration content_type country created_by declared_title - default_country delivered_to description direction e164 email end_reason ended error error_code error_message event_type - from_number greeting greeting_mode guardrail harness host image instructions judge_target kind label last_error - last_refusal_code leased_by leg llm markdown message modality mode model name namespace knowledge_namespace object_key - organization_tier outcome owner_type paused_reason price_version project prompt provider purpose reason recipient region - result return_url review_instructions review_notes role rrule said sandbox_provider scenario scope search severity sha256 - ship_error sku source stage state status stream_call_type sts stt subagent summary sync_hash tag_key tag_value team text - time_zone timezone title tls_scheme to_number tool_name tools_digest transport trigger tts type ui_instructions url username - validation_code validation_error validation_status vendor verdict video_source voice`) +var bareTexts = map[string][]string{ + "agent_sessions": {"api_key", "forked_from"}, + "campaigns": {"api_key"}, + "requests": {"api_key"}, + "scheduled_tasks": {"api_key", "channel_thread"}, + "users": {"claimed_by"}, +} + +// words are the text columns of each moved table that hold no row's id. +var words = map[string]string{ + "agent_configs": "greeting greeting_mode guardrail harness image instructions knowledge_namespace llm mode name region review_instructions role sandbox_provider search sts stt subagent sync_hash tts ui_instructions video_source voice", + "skills": "description instructions name", + "connector_definitions": "category description name", + "connector_connections": "auth_scheme client_registration label last_error owner_type status tls_scheme tools_digest validation_code validation_error validation_status", + "router_configs": "name", + "voices": "description name", + "sip_trunks": "host name transport username", + "phone_numbers": "country e164 stream_call_type vendor", + "knowledge_urls": "declared_title description error namespace state title url", + "knowledge_documents": "content_type error namespace object_key source state text", + "campaigns": "default_country from_number name paused_reason state type", + "campaign_contacts": "instructions leased_by outcome reason stage time_zone to_number", + "campaign_attempts": "call_outcome classify_state outcome result", + "simulations": "assertion caller_stt caller_target caller_tts caller_voice judge_target mode name scenario", + "simulation_runs": "assertion error judge_target mode scenario state", + "simulation_cases": "ended error scenario state verdict", + "users": "email kind name timezone", + "scheduled_tasks": "caller_kind created_by instructions leased_by rrule state timezone title", + "scheduled_task_runs": "delivered_to error prompt state trigger", + "opt_outs": "channel recipient source", + "recordings": "callback error modality model provider source status text", + "agent_sessions": "agent_name caller_kind description end_reason modality project return_url state team title", + "calls": "call_type direction from_number instructions llm review_notes sts stt subagent summary to_number tts voice", + "agent_responses": "error said status", + "agent_response_items": "kind text tool_name", + "conversation_documents": "markdown name sha256", + "agent_branch_switches": "kind state", + "agent_logs": "event_type message severity source", + "requests": "error_code error_message modality model organization_tier price_version provider purpose region ship_error sku", + "stats_hourly": "modality model provider", + "stats_daily": "modality model provider", + "stats_tags_hourly": "modality tag_key tag_value", + "stats_tags_daily": "modality tag_key tag_value", + "turn_latency_hourly": "leg", + "customer_activity": "area client last_refusal_code", + "policies": "scope", +} // forcedColumns are written by the import itself or left to this deployment, whatever was sent // (identity, vouched). @@ -544,7 +577,7 @@ FROM pg_constraint c WHERE c.conrelid = ?::regclass AND c.contype = 'f'`, table. SELECT attname::text FROM pg_attribute WHERE attrelid = ?::regclass AND attnum > 0 AND NOT attisdropped AND attgenerated = '' AND (attname ~ '(_ids?|_pk)$' OR atttypid::regtype::text ~ '^(text|uuid|jsonb?|.*\[\])$')`, table.name).Scan(s.ctx, &columns)) for _, column := range columns { - known := column == "id" || slices.Contains(bareTexts, column) || slices.Contains(words, column) || column == table.customer || column == "customer_id" || slices.Contains(held, column) || + known := column == "id" || slices.Contains(bareTexts[table.name], column) || slices.Contains(strings.Fields(words[table.name]), column) || column == table.customer || column == "customer_id" || slices.Contains(held, column) || slices.Contains(bareColumns[table.name], column) || slices.Contains(forcedColumns[table.name], column) || slices.Contains(table.vouched, column) s.True(known, "%s.%s may name a row of another table: see bareColumns", table.name, column) @@ -643,6 +676,28 @@ func (s *DataMoveSuite) TestARunOfATaskNotHereIsRefusedByItsKey() { s.EqualError(err, `store: import scheduled_task_runs:{"id":"run"}: a row names a row that neither the export nor this app holds`) } +func (s *DataMoveSuite) TestAUniqueValueIsNotRefusedAsNamingNoRow() { + s.execute(s.destination.global, "INSERT INTO campaigns (id, customer_id, name) VALUES ('cp', 'acme', 'c'); INSERT INTO campaign_contacts (id, campaign_id, to_number) VALUES ('held', 'cp', '+15550002222')") + var row []byte + s.Require().NoError(s.destination.global.NewRaw("SELECT to_jsonb(d) || '{\"id\": \"other\"}' FROM campaign_contacts d").Scan(s.ctx, &row)) + + err := s.destination.ImportRow(s.ctx, "acme", "campaign_contacts", row) + + s.Require().ErrorIs(err, ErrInvalidImport) + s.NotErrorIs(err, ErrNamesNoRow) + s.EqualError(err, "store: import campaign_contacts: a row holds a value, such as a name, that another row here already holds") +} + +func (s *DataMoveSuite) TestADeleteOfATrunkWithANumberIsRefused() { + trunk := s.trunkOf(s.destination, "acme").ID + s.Require().NoError(s.destination.ImportRow(s.ctx, "acme", "phone_numbers", s.importedNumber("+15550000124", sipTrunkVendor, "sip_trunk_id", trunk))) + + err := s.destination.ApplyChanges(s.ctx, "acme", []DataChange{{Table: "sip_trunks", Op: ChangeDelete, Key: []byte(`{"id": "` + trunk + `"}`)}}) + + s.Require().ErrorIs(err, ErrInvalidImport) + s.ErrorContains(err, "a row names a row that neither the export nor this app holds") +} + func (s *DataMoveSuite) TestAnImportOfARowThatNamesAnotherIsTwoQueries() { rows := s.namingRows(s.destination) sent := &queryCount{} diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 490b891cdf..f15fc8de50 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -395,6 +395,22 @@ func (s *ShardedStoreSuite) TestASessionBegunInOneShardIsCountedBesideAnotherCus s.EqualValues(1, buckets[0].Sessions, "no turn of its own says it was carried on") } +func (s *ShardedStoreSuite) TestToolUseIsNotOfACarriedSessionBesideAnotherCustomersTurn() { + session := s.opened("chat", "app", s.base, nil) + s.turned(session, "chat-1", s.base, nil) + s.carriedOnAt("chat", s.base) + s.turnedThere("chat", "chat-2", "", s.base.Add(time.Minute), nil) + s.calledToolThere("chat", "chat-2", "refund", s.base.Add(time.Minute)) + s.strayTurnThere("stray", "not-here") + + _, tools, err := s.store.CustomerToolUsage(s.ctx, "app", "", s.base, s.base.Add(time.Hour)) + + s.Require().NoError(err) + s.Require().Len(tools, 1) + s.Require().NotNil(tools[0].AvgTurnsBeforeUse) + s.InDelta(0.0, *tools[0].AvgTurnsBeforeUse, 0.001) +} + func (s *ShardedStoreSuite) TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindow() { dayOne, dayTwo := s.base, s.base.Add(24*time.Hour) session := s.opened("chat", "app", dayOne, nil) From 96416d5d0cfe54206eafb1755f4ab1143ebfc203 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 03:28:41 +0000 Subject: [PATCH 7/8] fix(store): name sync hashes as words, and give a refused delete its own reason The condition on a contact's campaign names its columns by relation. --- acceleration/internal/store/campaign_attempt.go | 6 +++--- acceleration/internal/store/datamove.go | 3 +++ acceleration/internal/store/datamove_references_test.go | 7 ++++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index 8938433ca5..291491f758 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -113,8 +113,8 @@ func (r *CampaignAttempts) End(ctx context.Context, customerID, id string, resul } // ofItsContactsCampaign is the condition that a dial is of the campaign its contact is of, as every -// dial a runner places is. -const ofItsContactsCampaign = "campaign_id = (SELECT cc.campaign_id FROM campaign_contacts AS cc WHERE cc.id = contact_id)" +// dial a runner places is. It names the dial by CampaignAttempt's alias. +const ofItsContactsCampaign = "ca.campaign_id = (SELECT cc.campaign_id FROM campaign_contacts AS cc WHERE cc.id = ca.contact_id)" // CountResult counts a contact's dials of one attempt that ended with result. func (r *CampaignAttempts) CountResult(ctx context.Context, contactID string, attempt int, result string) (int, error) { @@ -282,7 +282,7 @@ func (r *CampaignAttempts) Made(ctx context.Context, contactIDs []string) (map[s Made int } err := r.store.global.NewRaw(`SELECT contact_id, count(DISTINCT (step_id, attempt)) AS made -FROM campaign_attempts WHERE contact_id IN (?) AND `+ofItsContactsCampaign+` AND `+placedDial+` +FROM campaign_attempts AS ca WHERE contact_id IN (?) AND `+ofItsContactsCampaign+` AND `+placedDial+` GROUP BY contact_id`, bun.In(contactIDs)).Scan(ctx, &rows) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: count attempts made: %w", err)) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index ae9355ad1c..f43a8c0376 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -2274,6 +2274,9 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch if !cachedByID(change.Table) { result, err := db.ExecContext(ctx, query, args...) if err != nil { + if isViolation(err, foreignKeyViolation) { + return stack.Wrap(invalidImport(marked{fmt.Errorf("store: delete %s: another row here still names this row", change.Table), err})) + } if refused := refusedRow(change.Table, err); refused != nil { return refused } diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index 1c8c6b6d98..d0659c3e12 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -499,9 +499,9 @@ var bareTexts = map[string][]string{ var words = map[string]string{ "agent_configs": "greeting greeting_mode guardrail harness image instructions knowledge_namespace llm mode name region review_instructions role sandbox_provider search sts stt subagent sync_hash tts ui_instructions video_source voice", "skills": "description instructions name", - "connector_definitions": "category description name", + "connector_definitions": "category description name sync_hash", "connector_connections": "auth_scheme client_registration label last_error owner_type status tls_scheme tools_digest validation_code validation_error validation_status", - "router_configs": "name", + "router_configs": "name sync_hash", "voices": "description name", "sip_trunks": "host name transport username", "phone_numbers": "country e164 stream_call_type vendor", @@ -695,7 +695,8 @@ func (s *DataMoveSuite) TestADeleteOfATrunkWithANumberIsRefused() { err := s.destination.ApplyChanges(s.ctx, "acme", []DataChange{{Table: "sip_trunks", Op: ChangeDelete, Key: []byte(`{"id": "` + trunk + `"}`)}}) s.Require().ErrorIs(err, ErrInvalidImport) - s.ErrorContains(err, "a row names a row that neither the export nor this app holds") + s.NotErrorIs(err, ErrNamesNoRow) + s.ErrorContains(err, "store: delete sip_trunks: another row here still names this row") } func (s *DataMoveSuite) TestAnImportOfARowThatNamesAnotherIsTwoQueries() { From 6437b718d0abc2608695080f83e82b2e4fb3e17c Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 04:47:19 +0000 Subject: [PATCH 8/8] test(store): assert a refused delete's whole error, and list a config's voice as a bare id --- .../internal/store/datamove_references_test.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/store/datamove_references_test.go b/acceleration/internal/store/datamove_references_test.go index d0659c3e12..1bab726f07 100644 --- a/acceleration/internal/store/datamove_references_test.go +++ b/acceleration/internal/store/datamove_references_test.go @@ -450,7 +450,7 @@ func (s *DataMoveSuite) TestASessionsDeleteAndAnImportOfItsTurnsDoNotDeadlock() var bareColumns = map[string][]string{ "agent_configs": {"agents", "calls", "channels_chat", "channels_lines", "connectors", "floor_control", "keyterms", "left_out_connectors", "llm_fallbacks", "resume_history", "sandbox_options", "scheduling", "skills", "tags", "tool_groups", - "turn_taking", "video", "visible_tools", "workflow"}, + "turn_taking", "video", "visible_tools", "voice", "workflow"}, "skills": {"config_id", "files"}, "connector_definitions": {"manifest"}, "connector_connections": {"account_id", "cached_tools", "connector_id", "granted_scopes", "inputs", "metadata", "owner_id"}, @@ -497,7 +497,7 @@ var bareTexts = map[string][]string{ // words are the text columns of each moved table that hold no row's id. var words = map[string]string{ - "agent_configs": "greeting greeting_mode guardrail harness image instructions knowledge_namespace llm mode name region review_instructions role sandbox_provider search sts stt subagent sync_hash tts ui_instructions video_source voice", + "agent_configs": "greeting greeting_mode guardrail harness image instructions knowledge_namespace llm mode name region review_instructions role sandbox_provider search sts stt subagent sync_hash tts ui_instructions video_source", "skills": "description instructions name", "connector_definitions": "category description name sync_hash", "connector_connections": "auth_scheme client_registration label last_error owner_type status tls_scheme tools_digest validation_code validation_error validation_status", @@ -696,7 +696,15 @@ func (s *DataMoveSuite) TestADeleteOfATrunkWithANumberIsRefused() { s.Require().ErrorIs(err, ErrInvalidImport) s.NotErrorIs(err, ErrNamesNoRow) - s.ErrorContains(err, "store: delete sip_trunks: another row here still names this row") + s.EqualError(err, "store: delete sip_trunks: another row here still names this row") + s.True(isViolation(err, foreignKeyViolation)) +} + +func (s *DataMoveSuite) TestADeleteWhoseKeyDoesNotReadIsNotRefusedAsNamed() { + err := s.destination.ApplyChanges(s.ctx, "acme", []DataChange{{Table: "phone_numbers", Op: ChangeDelete, Key: []byte(`{"id": "not a number"}`)}}) + + s.Require().ErrorIs(err, ErrInvalidImport) + s.EqualError(err, "store: import phone_numbers: a row holds a value its column cannot take") } func (s *DataMoveSuite) TestAnImportOfARowThatNamesAnotherIsTwoQueries() {