Repository navigation
fix(store): validate imported rows and force what a request counts against #2181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
94e26d1
8eb4671
03eafd8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
| // 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"}, | ||
|
|
@@ -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"}, | ||
|
|
@@ -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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Nit] R1.4 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 | ||
|
|
@@ -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) | ||
|
|
@@ -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{ | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Should fix] R1.2 Tests cover only the Fix: add a test that walks |
||
| "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 | ||
|
|
@@ -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) | ||
| } | ||
|
|
||
| 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. |
There was a problem hiding this comment.
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_samplesandvoice_bindingslines. Two kinds of move break:importDatastops 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.data_changes.Changes()still serves them, andApplyChangesfails 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
retiredTablesalready does for tables an older export may carry. Nothing gets written, so the voice is still protected, and moves still finish. ChangeTestAnImportOfAVoiceSampleOrBindingIsRefusedto expect no error and no row, and add anApplyChangescase with onevoice_samplesinsert and one delete.