Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2917,7 +2917,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, 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
Expand Down
2 changes: 1 addition & 1 deletion acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22366,7 +22366,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 with a 504 `timeout` when a line has taken a minute to arrive.
Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth.
Expand Down
21 changes: 21 additions & 0 deletions acceleration/cmd/router/replicate_repeat_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,27 @@ func (s *ReplicateRepeatSuite) TestAFirstCopyBringsEverythingAndSavesTheCursor()
s.WithinDuration(time.Now(), saved.ReadAt, time.Minute)
}

// 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)
}
}

func (s *ReplicateRepeatSuite) TestARepeatOnceBringsOnlyTheChangesSinceItsCursor() {
s.recorded(1)
s.recorded(2)
Expand Down
11 changes: 7 additions & 4 deletions acceleration/internal/api/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,10 +340,13 @@ func writeImportFailure(w http.ResponseWriter, r *http.Request, err error) {
writeError(w, refusal)
return
}
if errors.Is(err, store.ErrAnotherCustomersRow) {
// Who holds the key is the operator's to know, so a caller is told only which row it is.
writeError(w, invalidRequest(strings.Replace(err.Error(), store.ErrAnotherCustomersRow.Error(), "this row cannot be written here", 1)))
return
for _, refused := range []error{store.ErrAnotherCustomersRow, store.ErrNamesNoRow} {
if errors.Is(err, refused) {
// Who holds the key, or what it names, is the operator's to know, so a caller is told
// only which row it is.
writeError(w, invalidRequest(strings.Replace(err.Error(), refused.Error(), "this row cannot be written here", 1)))
return
}
}
var invalid *store.ValidationError
if errors.Is(err, store.ErrInvalidImport) || errors.Is(err, store.ErrNotACustomConnector) || errors.As(err, &invalid) {
Expand Down
28 changes: 28 additions & 0 deletions acceleration/internal/api/datamove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,34 @@ func (s *DataMoveSuite) TestChangesAreAppliedToAnAppThatHoldsData() {
s.Equal("edited at the source", s.instructionsOf(agent.Id))
}

// A row that names a row the app does not hold is the export's to correct, and the answer names it.
func (s *DataMoveSuite) TestAnImportedRowThatNamesARowTheAppDoesNotHoldIsRefusedNamingIt() {
theirs, nobodys, turn := s.utils.uuid(), 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()}))

for _, session := range []string{theirs, nobodys} {
row := json.RawMessage(`{"id": "` + turn + `", "session_id": "` + session + `", "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.Equal(`store: import agent_responses:{"id":"`+turn+`"}: this row cannot be written here`, failure, "whoever holds the session")
}
}
}

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()) + `}`
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/api/handwritten.go
Original file line number Diff line number Diff line change
Expand Up @@ -977,7 +977,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 " +
Expand Down
21 changes: 21 additions & 0 deletions acceleration/internal/campaign/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions acceleration/internal/store/campaign.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
}
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 9 additions & 3 deletions acceleration/internal/store/campaign_attempt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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) {
count, err := r.store.global.NewSelect().Model((*CampaignAttempt)(nil)).
Where("contact_id = ?", contactID).
Where(ofItsContactsCampaign).
Where("attempt = ?", attempt).
Where("result = ?", result).
Count(ctx)
Expand All @@ -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)
Expand Down Expand Up @@ -170,12 +176,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 ?
Expand Down Expand Up @@ -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 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))
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/store/campaign_contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down Expand Up @@ -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)
Expand Down
60 changes: 60 additions & 0 deletions acceleration/internal/store/campaign_contact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,66 @@ 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) 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
Expand Down
42 changes: 42 additions & 0 deletions acceleration/internal/store/campaign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading