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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,10 @@ An `AgentTool` declared with a `Decodable` arguments type decodes it from the ar

Only a built-in connector takes the OAuth client the deployment keeps in its environment (`<client.env>_MCP_CLIENT_ID` and `_SECRET`) or a record of the operator's app: a custom connector's manifest is its customer's, whatever its `client.registration` and `client.env` say. A data import now holds each connector definition to the rules the API applies to a custom connector, and refuses one the API would refuse with a 400, as it refuses a phone number it cannot take (AI-3474).

### An imported row is held to what the API holds it to

`POST /v1/data/import` and change replays run each row's own validation before writing it, so an import is refused with a 400 naming the field where the API would refuse the same row: a campaign's concurrency above 50 or a config's sandbox over its CPU, memory or disk bounds, among the rest. A moved voice arrives with its id, name and description and without its samples or bindings, whose audio and clone stay with the deployment that made them: add a recording and prepare it again. An import that names `voice_samples` or `voice_bindings` is refused. An imported request is never billable here and counts against the importing app's organization: the one it was last seen under here, else the one it is registered under, else none.

### A customer can no longer list or speak in another customer's cloned voice

Clones made through `/v1/agents/voices` sit in the deployment's shared provider account, which lists them all as its own. A voice id that another customer's voice was prepared as is now refused, whether it is the session's voice or the `voice_id` of TTS overwrites. The voice library lists only the caller's own clones besides the provider's published voices, previews another customer's clone as not found, and no longer suggests one as the closest voice.
Expand Down
27 changes: 19 additions & 8 deletions acceleration/internal/store/app_organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,32 @@ func (r *AppOrganizations) Holds(ctx context.Context, organizationID, appID stri
if appID == "" || organizationID == "" {
return false, nil
}
seen, err := r.Get(ctx, appID)
owner, err := r.OrganizationOf(ctx, appID)
if err != nil {
return false, err
}
return owner == organizationID, nil
}

// OrganizationOf is the organization an app was last seen under by a request, or, for an app
// never seen under any, the one it is registered under. It is empty for an app neither names.
func (r *AppOrganizations) OrganizationOf(ctx context.Context, appID string) (string, error) {
seen, err := r.Get(ctx, appID)
if err != nil {
return "", err
}
if seen.OrganizationID != "" {
return seen.OrganizationID == organizationID, nil
return seen.OrganizationID, nil
}
registered, err := r.store.global.NewSelect().Model((*App)(nil)).
Where("id = ?", appID).
Where("organization_id = ?", organizationID).
Exists(ctx)
var registered []string
err = r.store.global.NewSelect().Model((*App)(nil)).Column("organization_id").Where("id = ?", appID).Scan(ctx, &registered)
if err != nil {
return false, stack.Wrap(fmt.Errorf("store: app in organization: %w", err))
return "", stack.Wrap(fmt.Errorf("store: organization of app: %w", err))
}
if len(registered) == 0 {
return "", nil
}
return registered, nil
return registered[0], nil
}

// Apps is every app of an organization: those requests last named it for, those
Expand Down
94 changes: 89 additions & 5 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ func (t dataTable) rollup() bool {
// moves to pins its tools again on first use. And chat_inbound, Stream
// Chat messages in flight for minutes, and image_jobs, pictures in flight for minutes. And
// call_bridges, an answer parked for seconds at this deployment's URL: its key is the token
// that authenticates the fetch, and it holds the trunk's password in the clear.
// that authenticates the fetch, and it holds the trunk's password in the clear. And
// voice_samples and voice_bindings: a sample's audio is in this deployment's bucket and a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 An import now refuses voice_samples and voice_bindings lines. Two kinds of move break:

  1. An older source. An export from a deployment on the previous release carries those lines for any voice with a sample. importData stops at the first one with a 400, after writing the lines before it. A retry stops at the same line, so the move cannot finish until the source upgrades.
  2. A capture that spans this deploy. The migration drops the triggers, but changes recorded before it stay in data_changes. Changes() still serves them, and ApplyChanges fails the whole batch with "voice_samples" is not a table an export carries.

I checked case 2 with a probe: the previous release starts a capture and stores a sample, then this head migrates the database and replays its changes into another app, and the replay is refused. A rolling deploy can also leave the triggers in place, because an old pod that restarts after the migration puts them back (watchDataChanges).

Fix: skip both tables on import and on delete, as retiredTables already does for tables an older export may carry. Nothing gets written, so the voice is still protected, and moves still finish. Change TestAnImportOfAVoiceSampleOrBindingIsRefused to expect no error and no row, and add an ApplyChanges case with one voice_samples insert and one delete.

// binding's clone in this deployment's account at the provider, so like a knowledge file's,
// neither means anything where the customer moves. A voice arrives with its name and
// description, to be given a recording and prepared again.
var dataTables = []dataTable{
{name: "agent_configs", customer: "customer_id"},
{name: "skills", customer: "customer_id"},
Expand All @@ -113,8 +117,6 @@ var dataTables = []dataTable{
}},
{name: "router_configs", customer: "customer_id"},
{name: "voices", customer: "customer_id"},
{name: "voice_samples", parent: "voices", parentColumn: "voice_id"},
{name: "voice_bindings", parent: "voices", parentColumn: "voice_id"},
{name: "sip_trunks", customer: "customer_id"},
{name: "phone_numbers", customer: "customer_id"},
{name: "knowledge_urls", customer: "customer_id"},
Expand Down Expand Up @@ -794,6 +796,24 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
if spec.copied != "" {
where = " WHERE NOT " + spec.copiedBefore(shape, columns)
}
args := []any{string(row), 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
// this deployment neither saw nor registered has none here, and its requests keep none.
organization, err := s.AppOrganizations.OrganizationOf(ctx, customerID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.4 OrganizationOf runs once for every imported requests row, even though the importing app is the same for the whole import. When the app has no cached membership, that is an uncached apps query per row. On top of that, validateImported adds one more statement for every validated row. An import of N request rows now runs up to 3N statements where it ran N.

Fix: read the organization once per import (or per batch). For a ticket.

if err != nil {
return err
}
args = append(args, organization)
}
read := args
if spec.customer == "" {
read = args[:1]
}
if err := validateImported(ctx, db, spec, shape, columns, picked, subject, read); err != nil {
return fmt.Errorf("store: import %s: %w", table, err)
}

// A row nobody may update is one whose primary key is all it has, and writing it
// again would be the same row. Doing nothing is both the right answer and a legal
Expand All @@ -803,7 +823,6 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
// it. Primary keys are carried across as they are, so without this an import could
// name a row it happened to know the id of and overwrite another customer's.
conflict := "DO NOTHING"
args := []any{string(row), customerID}
if len(assignments) > 0 {
conflict = "DO UPDATE SET " + strings.Join(assignments, ", ") + " WHERE " + spec.owned(spec.name)
args = append(args, customerID)
Expand Down Expand Up @@ -839,6 +858,68 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
return nil
}

// validated is a model that refuses a row the API would not store.
type validated interface{ Validate() error }

// importedModels are the models of the tables an import writes, for those that have a Validate,
// so an imported row is held to what the API holds the same row to. A phone number is checked
// by importableNumber instead, which takes one given back in the form it was held in then.
var importedModels = map[string]func() validated{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 Tests cover only the campaigns and agent_configs entries. I deleted the other 27 entries of importedModels at once and the full TestDataMoveSuite still passed. So a table could later drop out of validation and no test would fail.

Fix: add a test that walks dataTables and requires an entry for every table except a named list: users, phone_numbers, the four stats_* tables, turn_stats_hourly, turn_latency_hourly and customer_activity. I checked that such a test passes on this head and fails when any one entry is removed (for example sip_trunks).

"agent_configs": func() validated { return &AgentConfig{} },
"skills": func() validated { return &Skill{} },
"connector_definitions": func() validated { return &ConnectorDefinition{} },
"connector_connections": func() validated { return &ConnectorConnection{} },
"router_configs": func() validated { return &RouterConfig{} },
"voices": func() validated { return &Voice{} },
"sip_trunks": func() validated { return &SIPTrunk{} },
"knowledge_urls": func() validated { return &KnowledgeURL{} },
"knowledge_documents": func() validated { return &KnowledgeDocument{} },
"campaigns": func() validated { return &Campaign{} },
"campaign_contacts": func() validated { return &Contact{} },
"campaign_attempts": func() validated { return &CampaignAttempt{} },
"simulations": func() validated { return &Simulation{} },
"simulation_runs": func() validated { return &SimulationRun{} },
"simulation_cases": func() validated { return &SimulationCase{} },
"scheduled_tasks": func() validated { return &ScheduledTask{} },
"scheduled_task_runs": func() validated { return &ScheduledTaskRun{} },
"recordings": func() validated { return &Recording{} },
"agent_sessions": func() validated { return &AgentSession{} },
"agent_session_tools": func() validated { return &agentSessionTools{} },
"calls": func() validated { return &Call{} },
"agent_responses": func() validated { return &AgentResponse{} },
"agent_response_items": func() validated { return &AgentResponseItem{} },
"conversation_documents": func() validated { return &ConversationDocument{} },
"agent_branch_switches": func() validated { return &AgentBranchSwitch{} },
"agent_branch_messages": func() validated { return &AgentBranchMessage{} },
"agent_logs": func() validated { return &AgentLog{} },
"requests": func() validated { return &Request{} },
"policies": func() validated { return &Policy{} },
}

// validateImported reads the row as the import would write it, with what it forces and fills
// in, and refuses it when its model's Validate does. A column the import leaves out is read as
// the row sent it.
func validateImported(ctx context.Context, db bun.IDB, spec dataTable, shape shape, columns, picked []string, subject string, args []any) error {
model, found := importedModels[spec.name]
if !found {
return nil
}
read := make([]string, 0, len(shape.columns))
for _, column := range shape.columns {
expression := "r." + column
if i := slices.Index(columns, column); i >= 0 {
expression = picked[i]
}
read = append(read, expression+" AS "+column)
}
row := model()
if err := db.NewRaw(fmt.Sprintf("SELECT %s FROM jsonb_populate_record(NULL::%s, %s) AS r",
strings.Join(read, ", "), spec.name, subject), args...).Scan(ctx, row); err != nil {
return stack.Wrap(fmt.Errorf("read the row: %w", err))
}
return row.Validate()
}

// The gap an import reserves ahead of the ids it writes, at most. Once a row's id comes
// within half a gap of what was reserved, the reservation moves a gap past it, so a live
// insert here draws a number a moved row would hold only when the source handed out half a
Expand Down Expand Up @@ -1424,8 +1505,11 @@ func (t dataTable) identity() string {
// A request was billed by the deployment that recorded it, so this one never ships it, and
// what that one's usage service answered for it is not this one's: a reship of the rows
// this one shipped or had refused leaves it alone.
// Nor is it billed here, and it counts against the importing app's organization alone.
if t.name == "requests" {
return "jsonb_build_object('customer_id', ?::text, 'to_ship', false, 'shipped_at', NULL, 'ship_error', '')"
return "jsonb_build_object('customer_id', ?::text, 'to_ship', false, 'shipped_at', NULL, 'ship_error', '')" +
" || jsonb_build_object('billable', false)" +
" || jsonb_build_object('organization_id', ?::text)"
}
return fmt.Sprintf("jsonb_build_object('%s', ?::text)", t.customer)
}
Expand Down
128 changes: 118 additions & 10 deletions acceleration/internal/store/datamove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1391,32 +1391,140 @@ func (s *DataMoveSuite) ageChange(id string) {
}

func (s *DataMoveSuite) TestChildRowsFollowTheirParent() {
voice := s.seedVoice(s.source, "acme", "narrator")
_, err := s.source.GlobalDB().ExecContext(s.ctx,
"INSERT INTO voice_samples (id, voice_id, object_key) VALUES (?, ?, ?)",
newID(), voice, "voices/acme/1.wav")
campaign := s.seedCampaign("acme", Draft)
_, _, err := s.source.CampaignContacts.InsertMany(s.ctx, campaign, []Contact{{ToNumber: "+15550101"}})
s.Require().NoError(err)

s.move("acme", "acme")

s.Len(s.exportFrom(s.destination, "acme").of("voice_samples"), 1)
s.Len(s.exportFrom(s.destination, "acme").of("campaign_contacts"), 1)
}

func (s *DataMoveSuite) TestAChildRowCannotBeImportedOntoSomebodyElsesParent() {
voice := s.seedVoice(s.destination, "resident", "narrator")
sample, err := json.Marshal(map[string]any{
"id": newID(), "voice_id": voice, "object_key": "voices/theirs/1.wav",
campaign := &Campaign{CustomerID: "resident", Name: "Renewals", ConfigID: "config-1", FromNumber: "+15550100"}
s.Require().NoError(s.destination.Campaigns.Insert(s.ctx, campaign))
contact, err := json.Marshal(map[string]any{
"id": newID(), "campaign_id": campaign.ID, "to_number": "+15550101", "stage": Enrolled,
})
s.Require().NoError(err)

s.Require().NoError(s.destination.ImportRow(s.ctx, "intruder", "voice_samples", sample))
s.Require().NoError(s.destination.ImportRow(s.ctx, "intruder", "campaign_contacts", contact))

var count int
s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx,
"SELECT count(*) FROM voice_samples WHERE voice_id = ?", voice).Scan(&count))
"SELECT count(*) FROM campaign_contacts WHERE campaign_id = ?", campaign.ID).Scan(&count))
s.Zero(count, "a row is only written where its parent belongs to the importing customer")
}

// countOf counts the rows of a table a voice holds on a deployment.
func (s *DataMoveSuite) countOf(store *Store, table, voice string) int {
var count int
s.Require().NoError(store.GlobalDB().QueryRowContext(s.ctx,
"SELECT count(*) FROM "+table+" WHERE voice_id = ?", voice).Scan(&count))
return count
}

func (s *DataMoveSuite) TestAMovedVoiceArrivesWithoutItsSamplesOrBindings() {
voice := s.seedVoice(s.source, "acme", "narrator")
s.Require().NoError(s.source.VoiceSamples.Insert(s.ctx, &VoiceSample{VoiceID: voice, ObjectKey: "voices/acme/1.wav"}))
s.Require().NoError(s.source.VoiceBindings.Upsert(s.ctx, &VoiceBinding{
VoiceID: voice, Provider: "elevenlabs", ExternalID: "provider-voice-1", State: VoiceReady,
}))

s.move("acme", "moved")

voices := s.exportFrom(s.destination, "moved").of("voices")
s.Require().Len(voices, 1)
s.Equal(voice, voices[0]["id"])
s.Equal("narrator", voices[0]["name"])
s.Zero(s.countOf(s.destination, "voice_samples", voice), "the audio is in the source's bucket")
s.Zero(s.countOf(s.destination, "voice_bindings", voice), "the clone is in the source's account at the provider")
}

func (s *DataMoveSuite) TestAnImportOfAVoiceSampleOrBindingIsRefused() {
voice := s.seedVoice(s.destination, "moved", "narrator")
now := time.Now().UTC()
// Whole rows, as an export from before carried them.
rows := map[string]map[string]any{
"voice_samples": {"id": newID(), "voice_id": voice, "object_key": "voices/moved/1.wav",
"content_type": "audio/wav", "bytes": 1024, "transcript": "", "created_at": now},
"voice_bindings": {"id": newID(), "voice_id": voice, "provider": "elevenlabs", "external_id": "provider-voice-1",
"state": VoiceReady, "error": "", "created_at": now, "updated_at": now},
}
for table, row := range rows {
encoded, err := json.Marshal(row)
s.Require().NoError(err)

s.ErrorContains(s.destination.ImportRow(s.ctx, "moved", table, encoded), "not a table an export carries", table)

s.Zero(s.countOf(s.destination, table, voice), table)
}
}

// importEdited imports the source's one row of a table, edited first, as the given customer.
func (s *DataMoveSuite) importEdited(table, customerID string, edit func(map[string]any)) error {
rows := s.export("acme").of(table)
s.Require().Len(rows, 1)
edit(rows[0])
encoded, err := json.Marshal(rows[0])
s.Require().NoError(err)
return s.destination.ImportRow(s.ctx, customerID, table, encoded)
}

func (s *DataMoveSuite) TestAnImportedCampaignAboveTheConcurrencyCapIsRefused() {
s.seedCampaign("acme", Draft)

err := s.importEdited("campaigns", "moved", func(row map[string]any) { row["concurrency"] = 100000 })

s.ErrorContains(err, "concurrency")
s.Empty(s.exportFrom(s.destination, "moved").of("campaigns"))
}

func (s *DataMoveSuite) TestAnImportedConfigOverTheSandboxLimitsIsRefused() {
s.seedAgentConfig(s.source, "acme", "coder")

err := s.importEdited("agent_configs", "moved", func(row map[string]any) {
row["sandbox_provider"] = SandboxDaytona
row["sandbox_options"] = map[string]any{"cpu": 64}
})

s.ErrorContains(err, "sandbox_options.cpu")
s.Empty(s.exportFrom(s.destination, "moved").of("agent_configs"))
}

func (s *DataMoveSuite) TestAnImportedRequestIsNotBilledAndCountsAgainstTheAppsOwnOrganization() {
s.Require().NoError(s.destination.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: "acme", OrganizationID: "acme-org"}))
s.Require().NoError(s.source.Requests.Insert(s.ctx, &Request{UsageID: uuid.Must(uuid.NewV7()), Modality: "stt",
CustomerID: "acme", OrganizationID: "another-org", Billable: true, CostMicros: -5_000_000,
Provider: "deepgram", Model: "flux", StartedAt: time.Now().UTC(), Success: true}))

moved := s.movedRequest(false)

s.Equal(false, moved["billable"])
s.Equal("acme-org", moved["organization_id"])
}

func (s *DataMoveSuite) TestAnImportedRequestOfAnAppRegisteredButUnseenHereCountsAgainstItsOrganization() {
// A move's destination has seen no request of the app yet, but registered it.
org := Organization{Name: "moving"}
s.Require().NoError(s.destination.Organizations.Insert(s.ctx, &org))
app := App{OrganizationID: org.ID, Name: "moving"}
s.Require().NoError(s.destination.Apps.Insert(s.ctx, &app))
s.Require().NoError(s.source.Requests.Insert(s.ctx, &Request{UsageID: uuid.Must(uuid.NewV7()), Modality: "stt",
CustomerID: app.ID, OrganizationID: "another-org", Provider: "deepgram", Model: "flux",
StartedAt: time.Now().UTC(), Success: true}))
exported := s.export(app.ID).of("requests")
s.Require().Len(exported, 1)
encoded, err := json.Marshal(exported[0])
s.Require().NoError(err)

s.Require().NoError(s.destination.ImportRow(s.ctx, app.ID, "requests", encoded))

moved := s.exportFrom(s.destination, app.ID).of("requests")
s.Require().Len(moved, 1)
s.Equal(org.ID, moved[0]["organization_id"])
}

func (s *DataMoveSuite) TestOnlyTheAppsOwnPolicyMoves() {
_, err := s.source.GlobalDB().ExecContext(s.ctx,
"INSERT INTO policies (scope, scope_id, document, updated_at)"+
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- +goose Up

-- A voice's samples and bindings are no longer carried by a move (store.dataTables): the audio
-- is in this deployment's bucket and the clone in this deployment's account at the provider.
DROP TRIGGER IF EXISTS data_changes_recorded ON voice_samples;
DROP TRIGGER IF EXISTS data_changes_recorded ON voice_bindings;

-- +goose Down

-- Nothing: the router puts the trigger back on every table a move carries when it starts.
Loading