From 90b14ff08b53cc7c7cc158e08e0dffc3deff21e8 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:04:24 +0100 Subject: [PATCH 1/6] fix(api): save an agent config onto its locked row, not a copy PATCH, PUT and sync read the config through the one-hour cache and wrote every column back from that copy, so of two saves at once the later put back what the earlier changed, and a sync put back a model the dashboard had just saved. AgentConfigs.Save reads the row FOR UPDATE in the transaction that writes it, and writes only the columns the caller changed from its copy; every other column keeps the row's value. A patch may send the updated_at of the copy it was made from. When the config was saved after it, the patch is refused with a 409. It is optional, so clients that do not send it are unchanged. Update goes through the same locked write, so every write of a stored config locks its row before its connections and channel owner. Co-Authored-By: Claude Opus 5.5 --- .../skills/sdk/notes/2026-11-23-ai-3516.md | 1 + acceleration/api/openapi.yaml | 4 + acceleration/internal/api/config_patch.go | 10 +- acceleration/internal/api/configs.go | 16 ++- acceleration/internal/api/configs_test.go | 70 ++++++++++ acceleration/internal/api/sync.go | 12 +- acceleration/internal/api/sync_test.go | 40 ++++++ acceleration/internal/store/agent_config.go | 128 +++++++++++------- .../internal/store/agent_config_test.go | 48 ++++++- acceleration/internal/store/channel_owner.go | 5 +- .../_generated/models/agent_config_patch.py | 20 +++ sdks/go/acceleration/generated.go | 7 +- sdks/js/src/generated/api.ts | 5 + 13 files changed, 303 insertions(+), 63 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-11-23-ai-3516.md diff --git a/.claude/skills/sdk/notes/2026-11-23-ai-3516.md b/.claude/skills/sdk/notes/2026-11-23-ai-3516.md new file mode 100644 index 0000000000..0dd62b7ad4 --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-23-ai-3516.md @@ -0,0 +1 @@ +`AgentConfigPatch` has a new optional field, `updated_at` (a date-time): the `updated_at` of the config a patch was made from (AI-3516). Sent, `PATCH /v1/agents/configs/{id}` refuses the patch with a 409 `conflict` when the config was saved after it; left out, nothing changes for the caller, and the router now makes the patch on the row as it stands, so two patches at once to different fields both land. Go has it through the regenerated `acceleration.AgentConfigPatch.UpdatedAt` (`sdks/go/acceleration/generated.go`), Python through the regenerated `AgentConfigPatch.updated_at` and JavaScript through the regenerated `Schemas["AgentConfigPatch"]`. Other SDKs need to update: .NET, Ruby, Rust and PHP add the field to their `AgentConfigPatch` model when they regenerate, serialised as RFC 3339 and left out when unset. Swift, Kotlin and Dart have no patch operation, which is server-side only. No SDK sends it on its own: a helper that patches a config (`UpdateConfig` in Go, `updateConfig` in JavaScript) passes it through only when its caller set it. diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 9f916f17fa..e304ac189a 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -877,6 +877,10 @@ components: ui_instructions: description: What teaches the agent's model to answer with UI. An empty string removes them. type: string + updated_at: + description: 'The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored.' + format: date-time + type: string video: $ref: '#/components/schemas/SessionVideo' visible_tools: diff --git a/acceleration/internal/api/config_patch.go b/acceleration/internal/api/config_patch.go index 8f1468d0a1..fec9d702a1 100644 --- a/acceleration/internal/api/config_patch.go +++ b/acceleration/internal/api/config_patch.go @@ -3,6 +3,7 @@ package api import ( "context" "net/http" + "time" "github.com/danielgtaylor/huma/v2" @@ -54,6 +55,7 @@ type AgentConfigPatch struct { EndOfTurn any `json:"end_of_turn,omitempty" hidden:"true"` // refused: floor_control's max_wait_ms replaced it Tags *map[string]string `json:"tags,omitempty"` Video *SessionVideo `json:"video,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty" doc:"The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored."` } func (*AgentConfigPatch) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { @@ -149,7 +151,6 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig if err != nil { return nil, unknownOr(err, store.ErrNoAgentConfig, errUnknownConfig) } - existing := agentConfigOf(config) original := config heard := config.Models.STT was := sandboxOfConfig(config) @@ -309,13 +310,16 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig return nil, invalidRequest(message) } - if err := s.store.AgentConfigs.Update(ctx, &config); err != nil { + // Written onto the row as it now is rather than over it, so a save since the read above, + // which may have come from the cache, keeps every field this patch does not send. + before, err := s.store.AgentConfigs.Save(ctx, original, &config, value(patch.UpdatedAt)) + if err != nil { return nil, storeFailure(err, errAgentNameTaken) } stored := agentConfigOf(config) s.audit(ctx, auditRecord{ ResourceType: store.AuditAgentConfig, ResourceID: config.ID, ResourceName: config.Name, - Action: store.AuditUpdated, Changes: auditDiff(existing, stored), + Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(before), stored), }) return &agentConfigResponse{Body: stored}, nil } diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go index 43f9c233a8..2e5702d201 100644 --- a/acceleration/internal/api/configs.go +++ b/acceleration/internal/api/configs.go @@ -377,13 +377,16 @@ func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConf } else if !ok { return nil, invalidRequest(message) } - if err := s.store.AgentConfigs.Update(ctx, &config); err != nil { + // Written onto the row as it now is, so a field kept above from a copy read before another + // save, which may have come from the cache, does not write that save's change back. + before, err := s.store.AgentConfigs.Save(ctx, existing, &config, time.Time{}) + if err != nil { return nil, storeFailure(err, errAgentNameTaken) } stored := agentConfigOf(config) s.audit(ctx, auditRecord{ ResourceType: store.AuditAgentConfig, ResourceID: config.ID, ResourceName: config.Name, - Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(existing), stored), + Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(before), stored), }) return &updateAgentConfigResponse{Body: stored}, nil } @@ -604,6 +607,10 @@ var ( } ) +// errAgentConfigChanged is a patch made from a copy of the config older than the config: it +// sent updated_at, and the config was saved after it. +var errAgentConfigChanged = conflict("the agent config was saved after updated_at: read it again and make the change on that") + // errAgentRoleTaken is a save that would give a second live agent config of the customer a // role another one holds. The one there is, agent_moderator, is what the chat worker finds the // app's moderator by, so two would leave it guessing. @@ -649,7 +656,8 @@ func channelConnectionTaken(taken *store.ChannelConnectionTakenError) APIError { // choosing another name. A record, a connection or a custom connector that is not there, such // as one deleted after the request was checked, is the invalid request it has always been // answered with. A channel connection another live agent config binds is a 409 naming that -// config. Anything else is the database failing rather than the +// config, and an agent config saved after the copy a patch was made from is a 409 too. +// Anything else is the database failing rather than the // caller, so err goes back as it is, to be answered as a 500 and recorded with its stack. func storeFailure(err error, taken APIError) error { if owned, ok := errors.AsType[*store.ChannelConnectionTakenError](err); ok { @@ -660,6 +668,8 @@ func storeFailure(err error, taken APIError) error { return taken case errors.Is(err, store.ErrRoleTaken): return errAgentRoleTaken + case errors.Is(err, store.ErrAgentConfigChanged): + return errAgentConfigChanged case errors.Is(err, store.ErrNoAgentConfig), errors.Is(err, store.ErrNoSkill), errors.Is(err, store.ErrNoRouterConfig), errors.Is(err, store.ErrNoVoice), errors.Is(err, store.ErrNoConnectorConnection), errors.Is(err, store.ErrNoConnectorDefinition): diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go index ab565f4b90..ea1c376e71 100644 --- a/acceleration/internal/api/configs_test.go +++ b/acceleration/internal/api/configs_test.go @@ -9,6 +9,7 @@ import ( "net/http" "slices" "strings" + "sync" "testing" "time" @@ -130,6 +131,75 @@ func (s *ConfigsSuite) TestPatchingAnEmptyGreetingRemovesIt() { s.Nil(patched.Greeting) } +// A patch wrote every column from the copy it read, so of patches at once to different fields +// the last to write put back what the others had changed. +func (s *ConfigsSuite) TestPatchesAtOnceToDifferentFieldsAllSurvive() { + created := s.createConfig(map[string]any{"name": "support"}) + for round := range 10 { + patches := []map[string]any{ + {"instructions": fmt.Sprintf("Be brief, %d.", round)}, + {"ui_instructions": fmt.Sprintf("Answer with a card, %d.", round)}, + {"greeting": map[string]any{"text": fmt.Sprintf("Hello, %d.", round)}}, + {"keyterms": []string{fmt.Sprintf("Vision Agents %d", round)}}, + } + statuses := make(chan int, len(patches)) + var wg sync.WaitGroup + for _, patch := range patches { + wg.Go(func() { + statuses <- s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, patch, nil) + }) + } + wg.Wait() + close(statuses) + for status := range statuses { + s.Require().Equal(http.StatusOK, status) + } + + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + s.Equal(fmt.Sprintf("Be brief, %d.", round), value(read.Instructions), "round %d", round) + s.Equal(fmt.Sprintf("Answer with a card, %d.", round), value(read.UiInstructions), "round %d", round) + s.Require().NotNil(read.Greeting, "round %d", round) + s.Equal(fmt.Sprintf("Hello, %d.", round), read.Greeting.Text, "round %d", round) + s.Equal([]string{fmt.Sprintf("Vision Agents %d", round)}, value(read.Keyterms), "round %d", round) + } +} + +// A patch sending the updated_at of the copy it was made from must not write over a save made +// after that copy was read. +func (s *ConfigsSuite) TestAPatchMadeFromACopyOlderThanTheConfigIsRefused() { + created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."}) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"instructions": "Be briefer."}, nil)) + + status, body := s.serverClient.call(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"instructions": "Be loud.", "updated_at": created.UpdatedAt}) + + s.Equal(http.StatusConflict, status) + s.Contains(string(body), `"code":"conflict"`) + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + s.Equal("Be briefer.", value(read.Instructions)) +} + +// The control: a client sending back the updated_at it was last given, by a read or by its own +// save, made its change on the config as it is, and is not refused. The two are not as precise +// as each other, a read's being the database's. +func (s *ConfigsSuite) TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten() { + created := s.createConfig(map[string]any{"name": "support"}) + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + + var patched AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"instructions": "Be brief.", "updated_at": read.UpdatedAt}, &patched)) + var again AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"instructions": "Be briefer.", "updated_at": patched.UpdatedAt}, &again)) + + s.Equal("Be briefer.", value(again.Instructions)) +} + func (s *ConfigsSuite) TestAnImageTargetIsStoredOnCreateAndOnEveryUpdate() { // An update writes a named list of columns; a field missing from it is kept on create and // silently dropped by every save after. diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go index 312de69428..ef6300638a 100644 --- a/acceleration/internal/api/sync.go +++ b/acceleration/internal/api/sync.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/danielgtaylor/huma/v2" @@ -415,19 +416,20 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn config.KnowledgeNamespace = namespace config.SyncHash = hash + var was any if found { - if err := s.store.AgentConfigs.Update(ctx, &config); err != nil { + // Onto the row as it now is, so a setting the directory does not declare keeps what + // the dashboard saved since existing was read, which may have come from the cache. + before, err := s.store.AgentConfigs.Save(ctx, existing, &config, time.Time{}) + if err != nil { return nil, storeFailure(err, errAgentNameTaken) } + was = agentConfigOf(before) } else { if err := s.store.AgentConfigs.Insert(ctx, &config); err != nil { return nil, storeFailure(err, errAgentNameTaken) } } - var was any - if found { - was = agentConfigOf(existing) - } synced := auditDiff(was, agentConfigOf(config)) // The skills and simulations belong to the config, so they are written after it: a new diff --git a/acceleration/internal/api/sync_test.go b/acceleration/internal/api/sync_test.go index 33e724e8ed..70ce573e6e 100644 --- a/acceleration/internal/api/sync_test.go +++ b/acceleration/internal/api/sync_test.go @@ -341,6 +341,46 @@ func (s *SyncSuite) TestASyncWhosePageCannotBeStoredIsAnInternalError() { s.NotContains(string(body), "deadline") } +// A sync wrote every setting from the copy of the config it read, which can come from the +// cache, so a model saved since that the directory does not declare went back to what the copy +// held. The update below goes past the store, as a save the cache has not heard of yet. +func (s *SyncSuite) TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare() { + declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief.", "llm": "llm-flow"} + synced := s.sync(declaration) + s.Require().True(s.sync(declaration).Unchanged, "read, and so cached, by name") + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("llm = ?", "llm-thinking").Set("updated_at = now()"). + Where("id = ?", synced.Config.Id).Exec(context.Background()) + s.Require().NoError(err) + + result := s.sync(map[string]any{"name": "support", "hash": "v2", "instructions": "Be briefer."}) + + s.Equal("Be briefer.", value(result.Config.Instructions)) + s.Equal("llm-thinking", value(result.Config.Llm), "the directory says nothing of the model") +} + +// A patch clears the hash, so the next sync of the directory writes it again. Made on the row +// as it stands, a patch whose copy was read before the last sync could leave that sync's hash, +// and the next sync would find nothing changed. The hash goes past the store, as a sync the +// cache has not heard of yet. +func (s *SyncSuite) TestAPatchFromACopyReadBeforeASyncStillHasTheNextSyncWriteAgain() { + declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief."} + synced := s.sync(declaration) + s.patch(synced.Config.Id, map[string]any{"instructions": "Be briefer."}) + s.Require().Empty(s.configsNamed("support")[0].SyncHash) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+synced.Config.Id, nil, nil), + "read, and so cached, by id") + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("sync_hash = ?", "v1").Where("id = ?", synced.Config.Id).Exec(context.Background()) + s.Require().NoError(err) + + s.patch(synced.Config.Id, map[string]any{"instructions": "Be loud."}) + again := s.sync(declaration) + + s.False(again.Unchanged) + s.Equal("Be brief.", value(again.Config.Instructions)) +} + func (s *SyncSuite) TestASyncDeclaringAPageThatIsNotAFetchablePageIsRefusedInItsWords() { status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sync", map[string]any{ "name": "librarian", "hash": "v1", diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 9d5a2550cb..11743790d7 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -8,6 +8,7 @@ import ( "fmt" "net" "net/netip" + "reflect" "regexp" "slices" "strings" @@ -372,6 +373,10 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error { return nil } +// ErrAgentConfigChanged says a save made from a copy of a config was refused because the +// config was saved again after that copy was read. +var ErrAgentConfigChanged = errors.New("store: the agent config was saved since it was read") + // Update replaces a config a customer holds. Every field is written, so an update is what the // config now is rather than what changed about it. A connection it binds as fixed is locked as // Insert locks it, and has to be live unless the stored config binds it already: a forced @@ -381,18 +386,57 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error { // The config is forgotten under its id and under both the name it had and the one it has, since // a rename leaves whoever asked for the old name holding a config that no longer answers to it. func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { + _, err := r.save(ctx, nil, config, time.Time{}) + return err +} + +// Save writes what a caller changed in read, a copy of a config it read earlier, onto the config +// as it now is: each column config holds differently from read is config's, and every other is +// the row's. Update writes every column, so a copy read before another save, through the cache +// or not, writes that save's columns back; of two Saves at once that change different columns, +// both land. It is checked, locked and forgotten as Update is, leaves config as stored, and +// returns the row as it was before. +// +// With unmodifiedSince set, a row saved after it is refused with ErrAgentConfigChanged: the +// caller made its change from a copy older than the config it would write over. +func (r *AgentConfigs) Save(ctx context.Context, read AgentConfig, config *AgentConfig, unmodifiedSince time.Time) (AgentConfig, error) { + return r.save(ctx, &read, config, unmodifiedSince) +} + +// save is Update when read is nil and Save otherwise. The row is locked first and what it binds +// after, the order every write of a stored config takes them in, so no two writes wait on each +// other in a cycle: neither a connection delete nor Insert locks a stored config's row. +func (r *AgentConfigs) save(ctx context.Context, read, config *AgentConfig, unmodifiedSince time.Time) (AgentConfig, error) { if config.ID == "" { - return stack.Wrap(&ValidationError{Model: "agent config", Field: "id", Reason: "is required"}) - } - normalizeConfig(config) - if err := config.Validate(); err != nil { - return stack.Wrap(err) + return AgentConfig{}, stack.Wrap(&ValidationError{Model: "agent config", Field: "id", Reason: "is required"}) } - config.UpdatedAt = time.Now().UTC() - - var wasName string + var stored AgentConfig err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + err := tx.NewSelect().Model(&stored). + Where("id = ?", config.ID). + Where("customer_id = ?", config.CustomerID). + Where("deleted_at IS NULL"). + For("UPDATE"). + Scan(ctx) + if errors.Is(err, sql.ErrNoRows) { + return unknownAgentConfig(config.ID) + } + if err != nil { + return fmt.Errorf("store: update agent config: %w", err) + } + if !unmodifiedSince.IsZero() && stored.UpdatedAt.After(unmodifiedSince) { + return ErrAgentConfigChanged + } + normalizeConfig(config) + if read != nil { + r.keepUnchanged(*read, config, stored) + } + if err := config.Validate(); err != nil { + return err + } + config.UpdatedAt = time.Now().UTC() + missing, err := lockBoundConnections(ctx, tx, config) if err != nil { return err @@ -401,17 +445,6 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { if err != nil { return err } - var stored AgentConfig - if len(missing) > 0 || len(undefined) > 0 || bindsAnyFixed(config.Connectors) { - err := tx.NewSelect().Model(&stored).Column("connectors", "tags"). - Where("id = ?", config.ID). - Where("customer_id = ?", config.CustomerID). - Where("deleted_at IS NULL"). - Scan(ctx) - if err != nil && !errors.Is(err, sql.ErrNoRows) { - return fmt.Errorf("store: update agent config: %w", err) - } - } if err := refuseUnbindable(missing, stored.Connectors); err != nil { return err } @@ -421,49 +454,56 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { if err := refuseSecondChannelAgent(ctx, tx, config, stored.Connectors, stored.TestCopy()); err != nil { return err } - // The name the row had is read in the same statement, locked, so the one forgotten is - // the one a concurrent rename did not already replace. - was := tx.NewSelect().Model((*AgentConfig)(nil)).Column("name"). - Where("id = ?", config.ID). - Where("customer_id = ?", config.CustomerID). - Where("deleted_at IS NULL"). - For("UPDATE") - err = tx.NewUpdate().Model(config). - With("was", was). - TableExpr("was"). + _, err = tx.NewUpdate().Model(config). Column(configColumns...). Where("ac.id = ?", config.ID). Where("ac.customer_id = ?", config.CustomerID). - Returning("was.name"). - Scan(ctx, &wasName) + Exec(ctx) switch constraint(err) { case "agent_configs_name_idx": return ErrNameTaken case "agent_configs_role_idx": return ErrRoleTaken } - if errors.Is(err, sql.ErrNoRows) { - return unknownAgentConfig(config.ID) - } if err != nil { return fmt.Errorf("store: update agent config: %w", err) } return nil }, func() []string { - // Named once the write answered: a commit that fails can still have landed. - if wasName == "" { + // Named once the locked read found the row: a commit that fails can still have landed. + if stored.Name == "" { return nil } return []string{ agentConfigKey(config.CustomerID, config.ID), agentConfigNameKey(config.CustomerID, config.Name), - agentConfigNameKey(config.CustomerID, wasName), + agentConfigNameKey(config.CustomerID, stored.Name), } }) if err != nil { - return stack.Wrap(err) + return AgentConfig{}, stack.Wrap(err) + } + return stored, nil +} + +// keepUnchanged puts into config the stored value of every column config holds as read held it, +// so the save writes only what its caller changed. Both are normalized first, so a list the +// caller left nil is not taken for one it emptied. sync_hash is always the caller's: whether +// the config still holds the directory last synced is for each save to say, and a patch that +// clears it must clear one a sync wrote since the patch's copy was read. +func (r *AgentConfigs) keepUnchanged(read AgentConfig, config *AgentConfig, stored AgentConfig) { + normalizeConfig(&read) + table := r.store.global.Table(reflect.TypeFor[AgentConfig]()) + was, now, held := reflect.ValueOf(&read).Elem(), reflect.ValueOf(config).Elem(), reflect.ValueOf(&stored).Elem() + for _, column := range configColumns { + if column == "updated_at" || column == "sync_hash" { + continue + } + field := table.FieldMap[column] + if reflect.DeepEqual(field.Value(now).Interface(), field.Value(was).Interface()) { + field.Value(now).Set(field.Value(held)) + } } - return nil } // Delete marks a config as gone. The row stays, because the calls that ran under it still name @@ -686,8 +726,9 @@ func (r *AgentConfigs) where(ctx context.Context, customerID, column, value stri // FOR KEY SHARE, not FOR SHARE: it conflicts with the delete's FOR UPDATE and not with the // FOR NO KEY UPDATE a plain UPDATE of a non-key column takes (table 13.3, // https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS), so a config -// save does not hold up a credential save. The connection is locked before the config row, -// as in the delete, so the two never wait on each other in a cycle. +// save does not hold up a credential save. A config write locks its own row before the +// connection, and the delete locks no config row, so the two never wait on each other in a +// cycle. func lockBoundConnections(ctx context.Context, tx bun.Tx, config *AgentConfig) ([]string, error) { var bound []string for _, binding := range config.Connectors { @@ -724,11 +765,6 @@ func refuseUnbindable(missing []string, kept []ConnectorBinding) error { return nil } -// bindsAnyFixed reports whether a binding has a fixed connection. -func bindsAnyFixed(bindings []ConnectorBinding) bool { - return slices.ContainsFunc(bindings, func(binding ConnectorBinding) bool { return binding.Connection.Type == "fixed" }) -} - // boundConnectors are the connector ids bindings name. func boundConnectors(bindings []ConnectorBinding) []string { ids := make([]string, 0, len(bindings)) diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index dc15b89a10..11c4ed881d 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -80,6 +80,44 @@ func (s *StoreSuite) TestAnUpdateKeepsABindingAForcedDeleteLeftBehind() { s.Equal([]ConnectorBinding{fixed(connection.ID)}, read.Connectors) } +// A save wrote every column from the copy it was made from, so a column another save changed +// since that copy was read went back to what the copy held. +func (s *StoreSuite) TestASaveKeepsWhatAnotherSaveWroteSinceItsCopyWasRead() { + read := s.boundConfig("acme-app") + other := read + other.Greeting = "Hello." + s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &other)) + + mine := read + mine.Instructions = "be brief" + before, err := s.store.AgentConfigs.Save(s.ctx, read, &mine, time.Time{}) + s.Require().NoError(err) + + stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID) + s.Require().NoError(err) + s.Equal("be brief", stored.Instructions) + s.Equal("Hello.", stored.Greeting, "the other save's greeting is kept") + s.Equal("Hello.", mine.Greeting, "the config is left as stored") + s.Equal("Hello.", before.Greeting, "what it saved over is the row, not the copy") +} + +// A save asked to refuse a config saved after its copy must not write over that save. +func (s *StoreSuite) TestASaveFromACopyOlderThanTheConfigIsRefusedWhenAskedTo() { + read := s.boundConfig("acme-app") + other := read + other.Instructions = "be brief" + s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &other)) + + mine := read + mine.Instructions = "be loud" + _, err := s.store.AgentConfigs.Save(s.ctx, read, &mine, read.UpdatedAt) + s.Require().ErrorIs(err, ErrAgentConfigChanged) + + stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID) + s.Require().NoError(err) + s.Equal("be brief", stored.Instructions) +} + func (s *StoreSuite) TestAConfigWithoutBindingsStoresAnEmptyList() { created := s.boundConfig("acme-app") @@ -282,8 +320,14 @@ func (s *StoreSuite) TestAgentConfigQueryBudgets() { s.Require().NoError(err) })) config.Instructions = "be brief" - s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &config)) }), - "begin, the update and commit: a config that binds nothing locks no connection") + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &config)) }), + "begin, the locked read, the update and commit: a config that binds nothing locks no connection") + read := config + config.Greeting = "Hello." + s.Equal(4, s.countQueries(func() { + _, err := s.store.AgentConfigs.Save(s.ctx, read, &config, read.UpdatedAt) + s.Require().NoError(err) + }), "the same as an update: the change is made on the row the locked read returns") if s.store.cache != nil { for range 2 { _, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) diff --git a/acceleration/internal/store/channel_owner.go b/acceleration/internal/store/channel_owner.go index 114d110c96..3c63284dd6 100644 --- a/acceleration/internal/store/channel_owner.go +++ b/acceleration/internal/store/channel_owner.go @@ -123,8 +123,9 @@ func refuseSecondChannelAgent(ctx context.Context, tx bun.Tx, config *AgentConfi // lockChannelOwner takes the lock a channel connection's owner is decided under // (refuseSecondChannelAgent) when the live connection id is a channel connection, and returns -// its connector and whether it is one. A write that also locks the config's row takes this -// lock first, as UpdateAgentConfig does, or the two would wait on each other in a cycle. +// its connector and whether it is one. A write of a stored config locks the config's row +// before this lock (AgentConfigs.save), and Insert locks no stored row, so two writes never +// wait on each other in a cycle. func lockChannelOwner(ctx context.Context, tx bun.Tx, customerID, id string) (string, bool, error) { var connection ConnectorConnection err := tx.NewSelect().Model(&connection).Column("id", "connector_id", "definition_revision"). diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py index 6d6e9f05c9..77223ba5f9 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py @@ -1,5 +1,6 @@ from __future__ import annotations +import datetime from collections.abc import Mapping from typing import TYPE_CHECKING, Any, TypeVar, cast @@ -137,6 +138,10 @@ class AgentConfigPatch: agents (list[ChildAgent] | Unset): Replaces the list whole. An empty list removes it. image (str | Unset): An empty string removes it, and the agent stops being offered generate_image. ui_instructions (str | Unset): What teaches the agent's model to answer with UI. An empty string removes them. + updated_at (datetime.datetime | Unset): The updated_at of the config this change was made from. Sent, the change + is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not + write over a newer one: read the config again and make the change on that. Left out, the change is made on the + config as it now is, and every field it does not send keeps what is stored. """ calls: AgentCalls | Unset = UNSET @@ -180,6 +185,7 @@ class AgentConfigPatch: agents: list[ChildAgent] | Unset = UNSET image: str | Unset = UNSET ui_instructions: str | Unset = UNSET + updated_at: datetime.datetime | Unset = UNSET def to_dict(self) -> dict[str, Any]: from ..models.agent_config_patch_plugins_item_type_1 import ( @@ -347,6 +353,10 @@ def to_dict(self) -> dict[str, Any]: ui_instructions = self.ui_instructions + updated_at: str | Unset = UNSET + if not isinstance(self.updated_at, Unset): + updated_at = self.updated_at.isoformat() + field_dict: dict[str, Any] = {} field_dict.update({}) @@ -432,6 +442,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["image"] = image if ui_instructions is not UNSET: field_dict["ui_instructions"] = ui_instructions + if updated_at is not UNSET: + field_dict["updated_at"] = updated_at return field_dict @@ -694,6 +706,13 @@ def _parse_plugins_item( ui_instructions = d.pop("ui_instructions", UNSET) + _updated_at = d.pop("updated_at", UNSET) + updated_at: datetime.datetime | Unset + if isinstance(_updated_at, Unset): + updated_at = UNSET + else: + updated_at = datetime.datetime.fromisoformat(_updated_at) + agent_config_patch = cls( calls=calls, channels=channels, @@ -736,6 +755,7 @@ def _parse_plugins_item( agents=agents, image=image, ui_instructions=ui_instructions, + updated_at=updated_at, ) return agent_config_patch diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 38b779e035..9ab8f2a816 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -4028,8 +4028,11 @@ type AgentConfigPatch struct { Tts *string `json:"tts,omitempty"` // UiInstructions What teaches the agent's model to answer with UI. An empty string removes them. - UiInstructions *string `json:"ui_instructions,omitempty"` - Video *SessionVideo `json:"video,omitempty"` + UiInstructions *string `json:"ui_instructions,omitempty"` + + // UpdatedAt The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored. + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Video *SessionVideo `json:"video,omitempty"` // VisibleTools Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search. VisibleTools *[]string `json:"visible_tools,omitempty"` diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index be8e37731d..f63c12d103 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -5061,6 +5061,11 @@ export type components = { readonly tts?: string; /** @description What teaches the agent's model to answer with UI. An empty string removes them. */ readonly ui_instructions?: string; + /** + * Format: date-time + * @description The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored. + */ + readonly updated_at?: string; readonly video?: components["schemas"]["SessionVideo"]; /** @description Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search. */ readonly visible_tools?: readonly string[]; From 309e1ffb22ecbaff35b282b41519d20d62cd1652 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:05:38 +0100 Subject: [PATCH 2/6] fix(sync): store a directory's hash after its skills and simulations A sync stored the config with its new hash before it wrote the skills. When a skill write failed, the retry found the same hash and answered unchanged, so the skills were never written. The config is now stored with no hash, and the hash is written once the skills and simulations are, through a save refused if the config was saved in between. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/sync.go | 13 ++++++++++++- acceleration/internal/api/sync_test.go | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go index ef6300638a..1f8325090a 100644 --- a/acceleration/internal/api/sync.go +++ b/acceleration/internal/api/sync.go @@ -414,7 +414,9 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn config.UIInstructions = value(body.UiInstructions) config.Skills = named config.KnowledgeNamespace = namespace - config.SyncHash = hash + // The hash is written last, after the skills and simulations: written here, a sync whose + // skills then failed was found unchanged when sent again, and never wrote them. + config.SyncHash = "" var was any if found { @@ -444,6 +446,15 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn return nil, err } } + // Only onto the config as this sync left it: one saved since no longer holds what the + // directory says, and is written again by the next sync of it. + marked := config + marked.SyncHash = hash + if _, err := s.store.AgentConfigs.Save(ctx, config, &marked, config.UpdatedAt); err == nil { + config = marked + } else if !errors.Is(err, store.ErrAgentConfigChanged) { + return nil, err + } // Recorded last, after the skills the directory brought with it, because what it marks // is the moment the whole directory and the whole stored agent agreed. An entry written // before the skills would leave each of them looking like an edit made since the sync, diff --git a/acceleration/internal/api/sync_test.go b/acceleration/internal/api/sync_test.go index 70ce573e6e..14ff507b46 100644 --- a/acceleration/internal/api/sync_test.go +++ b/acceleration/internal/api/sync_test.go @@ -341,6 +341,24 @@ func (s *SyncSuite) TestASyncWhosePageCannotBeStoredIsAnInternalError() { s.NotContains(string(body), "deadline") } +// The hash was stored with the config, before the skills: a sync whose skills then failed was +// found unchanged when sent again, and its skills were never written. +func (s *SyncSuite) TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain() { + declaration := map[string]any{"name": "support", "hash": "v1", "skills": []map[string]string{ + {"config_id": "", "name": "refund", "description": "work out a refund", "instructions": "Read the policy."}, + }} + s.failQueries(`INSERT INTO "skills"`) + status, _ := s.serverClient.call(http.MethodPost, "/v1/agents/sync", declaration) + s.Require().Equal(http.StatusInternalServerError, status) + s.failing.value.Store(nil) + + again := s.sync(declaration) + + s.False(again.Unchanged, "the first sync did not finish, so this one has work to do") + s.Equal("Read the policy.", s.skillNamed(again.Config.Id, "refund").Instructions) + s.Equal("v1", value(again.Config.SyncHash)) +} + // A sync wrote every setting from the copy of the config it read, which can come from the // cache, so a model saved since that the directory does not declare went back to what the copy // held. The update below goes past the store, as a save the cache has not heard of yet. From 36d9f1f98fbdf9e5d213dfa1453f6435b8ba6473 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:07:05 +0100 Subject: [PATCH 3/6] fix(guests): finish a claim sent again rather than answer it done A claim by the account that already held the guest answered sessions_moved 0 at once. A claim that stopped half-way was therefore answered as done on the retry: with shards, sessions left on a failed shard never moved, and the account never joined the channels of the conversations it now owns. A same-account claim now runs every step again. ClaimGuest lets the same account's claim stand with or without shards, and re-adding a channel member changes nothing. Co-Authored-By: Claude Opus 5.5 --- acceleration/api/openapi.yaml | 2 +- acceleration/internal/api/guests.go | 14 +++++++------- acceleration/internal/api/guests_test.go | 15 +++++++++++++++ acceleration/internal/store/sessions.go | 17 +++++++++-------- .../_generated/api/default/claim_guest_user.py | 12 ++++++++---- sdks/go/acceleration/generated.go | 16 ++++++++-------- sdks/js/src/generated/api.ts | 2 +- 7 files changed, 49 insertions(+), 29 deletions(-) diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index e304ac189a..6688429a24 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -17201,7 +17201,7 @@ paths: description: |- For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - A guest already claimed is refused rather than moved again. + A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. operationId: claimGuestUser requestBody: content: diff --git a/acceleration/internal/api/guests.go b/acceleration/internal/api/guests.go index ee09d8372f..42bd9833bf 100644 --- a/acceleration/internal/api/guests.go +++ b/acceleration/internal/api/guests.go @@ -304,12 +304,11 @@ func (s *Server) claimGuestUser(ctx context.Context, request *claimGuestUserRequ if err != nil { return nil, unknownOr(err, store.ErrNotAGuest, notFound("no such guest")) } - if guest.ClaimedBy != "" { - // A second claim naming the same account is the same claim arriving twice, which is - // not a conflict: a retried request must not read as somebody else's. - if guest.ClaimedBy == userID { - return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: 0}}, nil - } + // A second claim naming the same account is the same claim arriving twice, which is not a + // conflict: a retried request must not read as somebody else's. It runs every step again + // rather than answering as done, since the first may have stopped after marking the guest, + // before the sessions in a shard moved or the account joined their channels. + if guest.ClaimedBy != "" && guest.ClaimedBy != userID { return nil, conflict("that guest was already claimed") } @@ -456,7 +455,8 @@ func (s *Server) registerGuests(api huma.API) { "own backend knows that a given guest is a given account -- it is the thing that just " + "authenticated them. A page allowed to ask this could claim anybody's conversations by " + "guessing a guest id, which is the whole attack.\n" + - "A guest already claimed is refused rather than moved again.", + "A guest another account already claimed is refused. The same claim sent again finishes " + + "whatever the first left undone, and moves nothing twice.", Responses: map[string]*huma.Response{ "200": {Description: "The conversations were moved"}, "409": errorResponse("That guest was already claimed"), diff --git a/acceleration/internal/api/guests_test.go b/acceleration/internal/api/guests_test.go index 198e703743..a34e31e20c 100644 --- a/acceleration/internal/api/guests_test.go +++ b/acceleration/internal/api/guests_test.go @@ -398,6 +398,21 @@ func (s *GuestsSuite) TestTheSameClaimArrivingTwiceIsNotAConflict() { s.Equal(0, again.SessionsMoved, "the conversations moved the first time") } +// A claim that stopped once the guest was marked, before the account joined the channels of +// the conversations it moved, was answered as done when sent again, and the account never +// could read them. The store's half is all the first claim got through. +func (s *GuestsSuite) TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain() { + guest, account := s.recordGuest(), s.data.createUser() + talked := s.talked(guest) + _, err := s.store.ClaimGuest(context.Background(), s.customerID(), guest, account.userID) + s.Require().NoError(err) + s.Require().NotContains(s.chat.Members(s.transcriptOf(talked)), account.userID) + + s.claim(guest, account.userID) + + s.Contains(s.chat.Members(s.transcriptOf(talked)), account.userID, "the account reads what the guest said") +} + func (s *GuestsSuite) TestAGuestSomebodyElseClaimedIsAConflict() { guest := s.recordGuest() s.claim(guest, s.utils.uuid()) diff --git a/acceleration/internal/store/sessions.go b/acceleration/internal/store/sessions.go index cd8d9259bf..c2308813f7 100644 --- a/acceleration/internal/store/sessions.go +++ b/acceleration/internal/store/sessions.go @@ -143,8 +143,9 @@ func (s *Store) Guest(ctx context.Context, customerID, id string) (User, error) // somebody else. A task left on the guest follows up for nobody who can still see it. // // With shards, the guest and the tasks are in the shared database and the sessions in every -// shard, and no transaction spans them. The guest is claimed with its tasks first, and a claim -// by the same user again moves whatever sessions a failed one left behind. +// shard, and no transaction spans them. The guest is claimed with its tasks first. A claim by +// the same user again moves whatever sessions a failed one left behind, with shards or without, +// so a caller with steps after this one can finish them on a retry. func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID string) (int64, error) { if customerID == "" || guestID == "" || userID == "" { return 0, stack.Wrap(errors.New("store: a customer, a guest and a user id are required")) @@ -186,7 +187,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri if !s.Sharded() && len(s.peers) == 0 { var moved int64 err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := claimGuest(ctx, tx, customerID, guestID, userID, now, false); err != nil { + if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil { return err } if err := moveTasks(ctx, tx); err != nil { @@ -209,7 +210,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri } err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := claimGuest(ctx, tx, customerID, guestID, userID, now, true); err != nil { + if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil { return err } return moveTasks(ctx, tx) @@ -224,9 +225,9 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri return moved, nil } -// claimGuest marks a guest claimed by userID. sameUserAgain lets a claim userID already made -// stand rather than fail, for a caller that has more to finish after it. -func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string, now time.Time, sameUserAgain bool) error { +// claimGuest marks a guest claimed by userID. A claim userID already made stands rather than +// fails, for a caller that has more to finish after it. +func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string, now time.Time) error { claimed, err := db.NewUpdate().Model((*User)(nil)). Set("claimed_by = ?", userID). Set("claimed_at = ?", now). @@ -261,7 +262,7 @@ func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID str if err != nil { return fmt.Errorf("claim guest: %w", err) } - if sameUserAgain && existing.ClaimedBy == userID { + if existing.ClaimedBy == userID { return nil } return stack.Wrap(fmt.Errorf("%w: %s was already claimed by %s", ErrGuestClaimed, guestID, existing.ClaimedBy)) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py index 84e35f3166..b1c2770af8 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py @@ -110,7 +110,8 @@ def sync_detailed( knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - A guest already claimed is refused rather than moved again. + A guest another account already claimed is refused. The same claim sent again finishes whatever the + first left undone, and moves nothing twice. Args: body (ClaimGuestRequest): @@ -149,7 +150,8 @@ def sync( knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - A guest already claimed is refused rather than moved again. + A guest another account already claimed is refused. The same claim sent again finishes whatever the + first left undone, and moves nothing twice. Args: body (ClaimGuestRequest): @@ -183,7 +185,8 @@ async def asyncio_detailed( knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - A guest already claimed is refused rather than moved again. + A guest another account already claimed is refused. The same claim sent again finishes whatever the + first left undone, and moves nothing twice. Args: body (ClaimGuestRequest): @@ -220,7 +223,8 @@ async def asyncio( knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - A guest already claimed is refused rather than moved again. + A guest another account already claimed is refused. The same claim sent again finishes whatever the + first left undone, and moves nothing twice. Args: body (ClaimGuestRequest): diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 9ab8f2a816..2f1f498a87 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -14319,7 +14319,7 @@ type ClientInterface interface { // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - // A guest already claimed is refused rather than moved again. + // A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes any type of body and a specified content type. // @@ -14330,7 +14330,7 @@ type ClientInterface interface { // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - // A guest already claimed is refused rather than moved again. + // A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes a body of the `application/json` content type. // @@ -18745,7 +18745,7 @@ func (c *Client) CreateGuestUser(ctx context.Context, body CreateGuestUserJSONRe // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. -// A guest already claimed is refused rather than moved again. +// A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes any type of body and a specified content type. // @@ -18766,7 +18766,7 @@ func (c *Client) ClaimGuestUserWithBody(ctx context.Context, contentType string, // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. -// A guest already claimed is refused rather than moved again. +// A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes a body of the `application/json` content type. // @@ -37632,7 +37632,7 @@ type ClientWithResponsesInterface interface { // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - // A guest already claimed is refused rather than moved again. + // A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). // @@ -37643,7 +37643,7 @@ type ClientWithResponsesInterface interface { // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - // A guest already claimed is refused rather than moved again. + // A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). // @@ -69578,7 +69578,7 @@ func (c *ClientWithResponses) CreateGuestUserWithResponse(ctx context.Context, b // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. -// A guest already claimed is refused rather than moved again. +// A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). // @@ -69595,7 +69595,7 @@ func (c *ClientWithResponses) ClaimGuestUserWithBodyWithResponse(ctx context.Con // // For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. // Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. -// A guest already claimed is refused rather than moved again. +// A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. // // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). // diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index f63c12d103..bc7eecf0a9 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -1464,7 +1464,7 @@ export type paths = { * Move a guest's conversations onto the account they turned out to be * @description For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else. * Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack. - * A guest already claimed is refused rather than moved again. + * A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice. */ readonly post: operations["claimGuestUser"]; readonly delete?: never; From 595c782e7386c280dffb9949b0a69ada92d407e2 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:25:46 +0100 Subject: [PATCH 4/6] fix(api): save an agent config only over the copy it was made from The first version merged a save onto the locked row column by column, deciding what changed by comparing with a copy that may have come from the cache. That kept a stale value the request sent, stored rows no request had checked as a whole (a text agent with a subagent), and let a sync write its hash over a dashboard edit it had kept. AgentConfigs.Save now writes the whole config, under the row lock, only when the row's updated_at equals the copy's (ErrStaleAgentConfig otherwise, nothing written, the cached copies forgotten). PATCH, PUT and sync run again on a stale refusal, at most 5 tries, so what is stored is the request applied to the row it replaces and checked in full. A patch's updated_at is compared for equality, not later-than, so a replica whose clock is behind cannot let a stale patch through. The sync's hash is written only over its own write. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/config_patch.go | 15 ++-- acceleration/internal/api/configs.go | 39 +++++++-- acceleration/internal/api/configs_test.go | 65 ++++++++++++++ acceleration/internal/api/sync.go | 24 +++-- acceleration/internal/api/sync_test.go | 73 +++++++++++++--- acceleration/internal/store/agent_config.go | 87 ++++++++----------- .../internal/store/agent_config_test.go | 47 ++++++---- 7 files changed, 253 insertions(+), 97 deletions(-) diff --git a/acceleration/internal/api/config_patch.go b/acceleration/internal/api/config_patch.go index fec9d702a1..1b4c611d63 100644 --- a/acceleration/internal/api/config_patch.go +++ b/acceleration/internal/api/config_patch.go @@ -136,6 +136,11 @@ func (s *Server) registerConfigPatch(api huma.API) { // patchAgentConfig writes what a caller changed onto a stored config. func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfigRequest) (*agentConfigResponse, error) { + return onTheConfigAsItIs(func() (*agentConfigResponse, error) { return s.tryPatchAgentConfig(ctx, request) }) +} + +// tryPatchAgentConfig is one try of patchAgentConfig, on the config as it reads it. +func (s *Server) tryPatchAgentConfig(ctx context.Context, request *patchAgentConfigRequest) (*agentConfigResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { return nil, errMissingCustomer @@ -151,6 +156,7 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig if err != nil { return nil, unknownOr(err, store.ErrNoAgentConfig, errUnknownConfig) } + existing := agentConfigOf(config) original := config heard := config.Models.STT was := sandboxOfConfig(config) @@ -310,16 +316,15 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig return nil, invalidRequest(message) } - // Written onto the row as it now is rather than over it, so a save since the read above, - // which may have come from the cache, keeps every field this patch does not send. - before, err := s.store.AgentConfigs.Save(ctx, original, &config, value(patch.UpdatedAt)) - if err != nil { + // Only over original, which may have come from the cache: every field this patch does not + // send is what another save since then wrote. + if err := s.store.AgentConfigs.Save(ctx, &config, original.UpdatedAt, value(patch.UpdatedAt)); err != nil { return nil, storeFailure(err, errAgentNameTaken) } stored := agentConfigOf(config) s.audit(ctx, auditRecord{ ResourceType: store.AuditAgentConfig, ResourceID: config.ID, ResourceName: config.Name, - Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(before), stored), + Action: store.AuditUpdated, Changes: auditDiff(existing, stored), }) return &agentConfigResponse{Body: stored}, nil } diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go index 2e5702d201..dac0637136 100644 --- a/acceleration/internal/api/configs.go +++ b/acceleration/internal/api/configs.go @@ -236,6 +236,11 @@ func (s *Server) getAgentConfig(ctx context.Context, request *getAgentConfigRequ // updateAgentConfig replaces a config with what it now is. func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConfigRequest) (*updateAgentConfigResponse, error) { + return onTheConfigAsItIs(func() (*updateAgentConfigResponse, error) { return s.tryUpdateAgentConfig(ctx, request) }) +} + +// tryUpdateAgentConfig is one try of updateAgentConfig, on the config as it reads it. +func (s *Server) tryUpdateAgentConfig(ctx context.Context, request *updateAgentConfigRequest) (*updateAgentConfigResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { return nil, errMissingCustomer @@ -377,16 +382,15 @@ func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConf } else if !ok { return nil, invalidRequest(message) } - // Written onto the row as it now is, so a field kept above from a copy read before another - // save, which may have come from the cache, does not write that save's change back. - before, err := s.store.AgentConfigs.Save(ctx, existing, &config, time.Time{}) - if err != nil { + // Only over existing, which may have come from the cache: the fields kept from it above are + // what another save since then wrote. + if err := s.store.AgentConfigs.Save(ctx, &config, existing.UpdatedAt, time.Time{}); err != nil { return nil, storeFailure(err, errAgentNameTaken) } stored := agentConfigOf(config) s.audit(ctx, auditRecord{ ResourceType: store.AuditAgentConfig, ResourceID: config.ID, ResourceName: config.Name, - Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(before), stored), + Action: store.AuditUpdated, Changes: auditDiff(agentConfigOf(existing), stored), }) return &updateAgentConfigResponse{Body: stored}, nil } @@ -611,6 +615,31 @@ var ( // sent updated_at, and the config was saved after it. var errAgentConfigChanged = conflict("the agent config was saved after updated_at: read it again and make the change on that") +// errAgentConfigBusy is a save of an agent config that other saves replaced the config under on +// every try: sent again, it is made on the config as it then is. +var errAgentConfigBusy = conflict("the agent config was saved by others while this save was made: send it again") + +// configSaveTries is how many times a save of an agent config is made in all while other saves +// keep replacing the config it was made from. A try is lost only to a save that landed while it +// ran, so this many saves of one config at once all land. +const configSaveTries = 5 + +// onTheConfigAsItIs runs save, which reads an agent config, makes a change to it, checks the +// result and stores it, again when another save replaced the config in between +// (store.ErrStaleAgentConfig). The change is then made and checked again on the config as it +// now is, rather than written over a config nobody checked it against. +func onTheConfigAsItIs[T any](save func() (T, error)) (T, error) { + for try := 1; ; try++ { + saved, err := save() + if !errors.Is(err, store.ErrStaleAgentConfig) { + return saved, err + } + if try == configSaveTries { + return saved, errAgentConfigBusy + } + } +} + // errAgentRoleTaken is a save that would give a second live agent config of the customer a // role another one holds. The one there is, agent_moderator, is what the chat worker finds the // app's moderator by, so two would leave it guessing. diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go index ea1c376e71..d6042c988e 100644 --- a/acceleration/internal/api/configs_test.go +++ b/acceleration/internal/api/configs_test.go @@ -200,6 +200,71 @@ func (s *ConfigsSuite) TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten() { s.Equal("Be briefer.", value(again.Instructions)) } +// A patch was checked against its copy of the config, read through the cache, and written onto +// a row another save had made a text agent of since: a text agent was stored with a subagent, +// which none may have. The save goes past the store, as one the cache has not heard of yet. +func (s *ConfigsSuite) TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftIt() { + created := s.createConfig(map[string]any{"name": "support"}) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil), + "read, and so cached, by id") + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("mode = ?", store.AgentModeText).Set("updated_at = now()"). + Where("id = ?", created.Id).Exec(context.Background()) + s.Require().NoError(err) + + status, failure := s.serverClient.failure(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"subagent": "llm-thinking"}) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, "subagent") + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + s.Equal(AgentModeText, read.Mode) + s.Nil(read.Subagent) +} + +// A patch that sent the value its cached copy held kept what another save had written there +// since, and answered 200 with that: the field it sent was never written. The save goes past +// the store, as one the cache has not heard of yet. +func (s *ConfigsSuite) TestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld() { + created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."}) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil), + "read, and so cached, by id") + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("instructions = ?", "Be loud.").Set("updated_at = now()"). + Where("id = ?", created.Id).Exec(context.Background()) + s.Require().NoError(err) + + var patched AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, + map[string]any{"instructions": "Be brief."}, &patched)) + + s.Equal("Be brief.", value(patched.Instructions)) + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + s.Equal("Be brief.", value(read.Instructions)) +} + +// The same through a replacement, which writes the whole config it is sent. +func (s *ConfigsSuite) TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeld() { + created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."}) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil), + "read, and so cached, by id") + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("instructions = ?", "Be loud.").Set("updated_at = now()"). + Where("id = ?", created.Id).Exec(context.Background()) + s.Require().NoError(err) + + var updated AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/configs/"+created.Id, + map[string]any{"name": "support", "instructions": "Be brief."}, &updated)) + + s.Equal("Be brief.", value(updated.Instructions)) + var read AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read)) + s.Equal("Be brief.", value(read.Instructions)) +} + func (s *ConfigsSuite) TestAnImageTargetIsStoredOnCreateAndOnEveryUpdate() { // An update writes a named list of columns; a field missing from it is kept on create and // silently dropped by every save after. diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go index 1f8325090a..879769f003 100644 --- a/acceleration/internal/api/sync.go +++ b/acceleration/internal/api/sync.go @@ -197,6 +197,11 @@ func (s *Server) registerSync(api huma.API) { // The hash is a fingerprint of that directory. A second call with the same hash does // nothing, so a process that syncs on startup is cheap when nothing has changed. func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syncAgentResponse, error) { + return onTheConfigAsItIs(func() (*syncAgentResponse, error) { return s.trySyncAgent(ctx, request) }) +} + +// trySyncAgent is one try of syncAgent, on the config as it reads it. +func (s *Server) trySyncAgent(ctx context.Context, request *syncAgentRequest) (*syncAgentResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { return nil, errMissingCustomer @@ -418,20 +423,21 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn // skills then failed was found unchanged when sent again, and never wrote them. config.SyncHash = "" - var was any if found { - // Onto the row as it now is, so a setting the directory does not declare keeps what - // the dashboard saved since existing was read, which may have come from the cache. - before, err := s.store.AgentConfigs.Save(ctx, existing, &config, time.Time{}) - if err != nil { + // Only over existing, which may have come from the cache: every setting the directory + // does not declare is what another save since then wrote. + if err := s.store.AgentConfigs.Save(ctx, &config, existing.UpdatedAt, time.Time{}); err != nil { return nil, storeFailure(err, errAgentNameTaken) } - was = agentConfigOf(before) } else { if err := s.store.AgentConfigs.Insert(ctx, &config); err != nil { return nil, storeFailure(err, errAgentNameTaken) } } + var was any + if found { + was = agentConfigOf(existing) + } synced := auditDiff(was, agentConfigOf(config)) // The skills and simulations belong to the config, so they are written after it: a new @@ -446,13 +452,13 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn return nil, err } } - // Only onto the config as this sync left it: one saved since no longer holds what the + // Only over the config as this sync left it: one saved since no longer holds what the // directory says, and is written again by the next sync of it. marked := config marked.SyncHash = hash - if _, err := s.store.AgentConfigs.Save(ctx, config, &marked, config.UpdatedAt); err == nil { + if err := s.store.AgentConfigs.Save(ctx, &marked, config.UpdatedAt, time.Time{}); err == nil { config = marked - } else if !errors.Is(err, store.ErrAgentConfigChanged) { + } else if !errors.Is(err, store.ErrStaleAgentConfig) { return nil, err } // Recorded last, after the skills the directory brought with it, because what it marks diff --git a/acceleration/internal/api/sync_test.go b/acceleration/internal/api/sync_test.go index 14ff507b46..ff11061813 100644 --- a/acceleration/internal/api/sync_test.go +++ b/acceleration/internal/api/sync_test.go @@ -8,16 +8,39 @@ import ( "fmt" "net/http" "strings" + "sync/atomic" "testing" + "github.com/uptrace/bun" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) type SyncSuite struct { RouterSuite + // between runs a test's step in the middle of a sync, before a query of its choosing. + between *beforeQuery +} + +// beforeQuery runs a test's step once, just before the first query that holds its marker, as +// another writer's save landing in the middle of a request. +type beforeQuery struct{ step atomic.Pointer[queryStep] } + +type queryStep struct { + marker string + run func() +} + +func (b *beforeQuery) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { + if step := b.step.Load(); step != nil && strings.Contains(event.Query, step.marker) && b.step.CompareAndSwap(step, nil) { + step.run() + } + return ctx } +func (*beforeQuery) AfterQuery(context.Context, *bun.QueryEvent) {} + func TestSyncSuite(t *testing.T) { runSuite(t, new(SyncSuite)) } @@ -28,6 +51,8 @@ func (s *SyncSuite) SetupSuite() { s.speechToSpeech = true s.RouterSuite.SetupSuite() s.Require().NoError(s.store.ConnectorDefinitions.Seed(context.Background(), providers.FS)) + s.between = &beforeQuery{} + s.store.GlobalDB().AddQueryHook(s.between) } // SetupTest gives every test an app of its own, because a sync is named by what the agent @@ -377,22 +402,48 @@ func (s *SyncSuite) TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirector s.Equal("llm-thinking", value(result.Config.Llm), "the directory says nothing of the model") } -// A patch clears the hash, so the next sync of the directory writes it again. Made on the row -// as it stands, a patch whose copy was read before the last sync could leave that sync's hash, -// and the next sync would find nothing changed. The hash goes past the store, as a sync the -// cache has not heard of yet. -func (s *SyncSuite) TestAPatchFromACopyReadBeforeASyncStillHasTheNextSyncWriteAgain() { +// A sync whose copy of the config, read through the cache, missed a dashboard save kept the +// dashboard's wording of a setting its directory declares, and still wrote its hash: every later +// sync of the directory found nothing changed. The save goes past the store, as one the cache has +// not heard of yet. +func (s *SyncSuite) TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissed() { declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief."} synced := s.sync(declaration) - s.patch(synced.Config.Id, map[string]any{"instructions": "Be briefer."}) - s.Require().Empty(s.configsNamed("support")[0].SyncHash) - s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+synced.Config.Id, nil, nil), - "read, and so cached, by id") + s.Require().True(s.sync(declaration).Unchanged, "read, and so cached, by name") _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). - Set("sync_hash = ?", "v1").Where("id = ?", synced.Config.Id).Exec(context.Background()) + Set("instructions = ?", "Dashboard wording.").Set("sync_hash = ''").Set("updated_at = now()"). + Where("id = ?", synced.Config.Id).Exec(context.Background()) s.Require().NoError(err) - s.patch(synced.Config.Id, map[string]any{"instructions": "Be loud."}) + result := s.sync(map[string]any{"name": "support", "hash": "v2", "instructions": "Be brief."}) + + s.Equal("Be brief.", value(result.Config.Instructions)) + s.Equal("v2", value(result.Config.SyncHash)) + s.Equal("Be brief.", value(s.configsNamed("support")[0].Instructions)) +} + +// The hash said the config held the directory although a save landed between the sync's write +// of the config and of its hash, so every later sync of the directory found nothing changed and +// never wrote it again. The save goes past the store, as one the cache has not heard of yet. +func (s *SyncSuite) TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkills() { + declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief.", + "skills": []map[string]string{ + {"config_id": "", "name": "refund", "description": "work out a refund", "instructions": "Read the policy."}, + }} + saved := make(chan error, 1) + s.between.step.Store(&queryStep{marker: `INSERT INTO "skills"`, run: func() { + _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)). + Set("instructions = ?", "Dashboard wording.").Set("sync_hash = ''").Set("updated_at = now()"). + Where("customer_id = ?", s.customerID()).Where("name = ?", "support").Exec(context.Background()) + saved <- err + }}) + s.T().Cleanup(func() { s.between.step.Store(nil) }) + + s.sync(declaration) + s.Require().Len(saved, 1, "the save landed in the middle of the sync") + s.Require().NoError(<-saved) + s.Empty(value(s.configsNamed("support")[0].SyncHash), "the config no longer holds the directory") + again := s.sync(declaration) s.False(again.Unchanged) diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 11743790d7..305afd6568 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -8,7 +8,6 @@ import ( "fmt" "net" "net/netip" - "reflect" "regexp" "slices" "strings" @@ -373,9 +372,14 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error { return nil } -// ErrAgentConfigChanged says a save made from a copy of a config was refused because the -// config was saved again after that copy was read. -var ErrAgentConfigChanged = errors.New("store: the agent config was saved since it was read") +// ErrAgentConfigChanged says a save was refused because the config is not the one saved at +// the updated_at its caller made the change from (Save's unmodifiedSince). +var ErrAgentConfigChanged = errors.New("store: save agent config: saved since the caller's updated_at") + +// ErrStaleAgentConfig says a save was refused because it was made from a copy of the config, +// read through the cache or not, that another save has replaced since. Nothing was written, +// and the cached copies of the config are forgotten, so a read now returns it as it is. +var ErrStaleAgentConfig = errors.New("store: save agent config: saved since the copy was read") // Update replaces a config a customer holds. Every field is written, so an update is what the // config now is rather than what changed about it. A connection it binds as fixed is locked as @@ -386,34 +390,39 @@ var ErrAgentConfigChanged = errors.New("store: the agent config was saved since // The config is forgotten under its id and under both the name it had and the one it has, since // a rename leaves whoever asked for the old name holding a config that no longer answers to it. func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { - _, err := r.save(ctx, nil, config, time.Time{}) - return err + return r.save(ctx, config, time.Time{}, time.Time{}) } -// Save writes what a caller changed in read, a copy of a config it read earlier, onto the config -// as it now is: each column config holds differently from read is config's, and every other is -// the row's. Update writes every column, so a copy read before another save, through the cache -// or not, writes that save's columns back; of two Saves at once that change different columns, -// both land. It is checked, locked and forgotten as Update is, leaves config as stored, and -// returns the row as it was before. +// Save is Update for a change made to a copy of the config, the one stored at read: it is +// written only over that config. When another save has replaced it since, nothing is written +// and ErrStaleAgentConfig says so, so a change checked against one config is never written +// over another one nobody checked it against. The caller reads the config again and makes its +// change on that. With unmodifiedSince set, the config must also be the one saved then, or the +// save is refused with ErrAgentConfigChanged. // -// With unmodifiedSince set, a row saved after it is refused with ErrAgentConfigChanged: the -// caller made its change from a copy older than the config it would write over. -func (r *AgentConfigs) Save(ctx context.Context, read AgentConfig, config *AgentConfig, unmodifiedSince time.Time) (AgentConfig, error) { - return r.save(ctx, &read, config, unmodifiedSince) +// Both are compared with the row's updated_at for equality, at the column's microseconds. A +// later-than comparison would let through a save whose replica's clock is behind. +func (r *AgentConfigs) Save(ctx context.Context, config *AgentConfig, read, unmodifiedSince time.Time) error { + return r.save(ctx, config, read, unmodifiedSince) } -// save is Update when read is nil and Save otherwise. The row is locked first and what it binds +// save is Update when read is zero and Save otherwise. The row is locked first and what it binds // after, the order every write of a stored config takes them in, so no two writes wait on each // other in a cycle: neither a connection delete nor Insert locks a stored config's row. -func (r *AgentConfigs) save(ctx context.Context, read, config *AgentConfig, unmodifiedSince time.Time) (AgentConfig, error) { +func (r *AgentConfigs) save(ctx context.Context, config *AgentConfig, read, unmodifiedSince time.Time) error { if config.ID == "" { - return AgentConfig{}, stack.Wrap(&ValidationError{Model: "agent config", Field: "id", Reason: "is required"}) + return stack.Wrap(&ValidationError{Model: "agent config", Field: "id", Reason: "is required"}) + } + normalizeConfig(config) + if err := config.Validate(); err != nil { + return stack.Wrap(err) } + config.UpdatedAt = time.Now().UTC() + var stored AgentConfig err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { - err := tx.NewSelect().Model(&stored). + err := tx.NewSelect().Model(&stored).Column("name", "connectors", "tags", "updated_at"). Where("id = ?", config.ID). Where("customer_id = ?", config.CustomerID). Where("deleted_at IS NULL"). @@ -425,17 +434,12 @@ func (r *AgentConfigs) save(ctx context.Context, read, config *AgentConfig, unmo if err != nil { return fmt.Errorf("store: update agent config: %w", err) } - if !unmodifiedSince.IsZero() && stored.UpdatedAt.After(unmodifiedSince) { + if !unmodifiedSince.IsZero() && !stored.UpdatedAt.Equal(unmodifiedSince.Truncate(time.Microsecond)) { return ErrAgentConfigChanged } - normalizeConfig(config) - if read != nil { - r.keepUnchanged(*read, config, stored) + if !read.IsZero() && !stored.UpdatedAt.Equal(read.Truncate(time.Microsecond)) { + return ErrStaleAgentConfig } - if err := config.Validate(); err != nil { - return err - } - config.UpdatedAt = time.Now().UTC() missing, err := lockBoundConnections(ctx, tx, config) if err != nil { @@ -470,7 +474,8 @@ func (r *AgentConfigs) save(ctx context.Context, read, config *AgentConfig, unmo } return nil }, func() []string { - // Named once the locked read found the row: a commit that fails can still have landed. + // Named once the locked read found the row: a commit that fails can still have landed, + // and a save refused as stale leaves the copy it was made from to be read again. if stored.Name == "" { return nil } @@ -481,29 +486,9 @@ func (r *AgentConfigs) save(ctx context.Context, read, config *AgentConfig, unmo } }) if err != nil { - return AgentConfig{}, stack.Wrap(err) - } - return stored, nil -} - -// keepUnchanged puts into config the stored value of every column config holds as read held it, -// so the save writes only what its caller changed. Both are normalized first, so a list the -// caller left nil is not taken for one it emptied. sync_hash is always the caller's: whether -// the config still holds the directory last synced is for each save to say, and a patch that -// clears it must clear one a sync wrote since the patch's copy was read. -func (r *AgentConfigs) keepUnchanged(read AgentConfig, config *AgentConfig, stored AgentConfig) { - normalizeConfig(&read) - table := r.store.global.Table(reflect.TypeFor[AgentConfig]()) - was, now, held := reflect.ValueOf(&read).Elem(), reflect.ValueOf(config).Elem(), reflect.ValueOf(&stored).Elem() - for _, column := range configColumns { - if column == "updated_at" || column == "sync_hash" { - continue - } - field := table.FieldMap[column] - if reflect.DeepEqual(field.Value(now).Interface(), field.Value(was).Interface()) { - field.Value(now).Set(field.Value(held)) - } + return stack.Wrap(err) } + return nil } // Delete marks a config as gone. The row stays, because the calls that ran under it still name diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index 11c4ed881d..72fce25360 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -81,8 +81,9 @@ func (s *StoreSuite) TestAnUpdateKeepsABindingAForcedDeleteLeftBehind() { } // A save wrote every column from the copy it was made from, so a column another save changed -// since that copy was read went back to what the copy held. -func (s *StoreSuite) TestASaveKeepsWhatAnotherSaveWroteSinceItsCopyWasRead() { +// since that copy was read went back to what the copy held, and the change was written over a +// config nobody had checked it against. +func (s *StoreSuite) TestASaveMadeFromACopyAnotherSaveReplacedWritesNothing() { read := s.boundConfig("acme-app") other := read other.Greeting = "Hello." @@ -90,34 +91,50 @@ func (s *StoreSuite) TestASaveKeepsWhatAnotherSaveWroteSinceItsCopyWasRead() { mine := read mine.Instructions = "be brief" - before, err := s.store.AgentConfigs.Save(s.ctx, read, &mine, time.Time{}) - s.Require().NoError(err) + s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, read.UpdatedAt, time.Time{}), ErrStaleAgentConfig) stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID) s.Require().NoError(err) - s.Equal("be brief", stored.Instructions) s.Equal("Hello.", stored.Greeting, "the other save's greeting is kept") - s.Equal("Hello.", mine.Greeting, "the config is left as stored") - s.Equal("Hello.", before.Greeting, "what it saved over is the row, not the copy") + s.Empty(stored.Instructions, "nothing of the stale copy is written") } -// A save asked to refuse a config saved after its copy must not write over that save. +// A save asked to refuse a config saved after the version its caller made the change from must +// not write over that save, even when its own copy is the config as stored. func (s *StoreSuite) TestASaveFromACopyOlderThanTheConfigIsRefusedWhenAskedTo() { read := s.boundConfig("acme-app") other := read other.Instructions = "be brief" s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &other)) - mine := read + mine := other mine.Instructions = "be loud" - _, err := s.store.AgentConfigs.Save(s.ctx, read, &mine, read.UpdatedAt) - s.Require().ErrorIs(err, ErrAgentConfigChanged) + s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, other.UpdatedAt, read.UpdatedAt), ErrAgentConfigChanged) stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID) s.Require().NoError(err) s.Equal("be brief", stored.Instructions) } +// A replica whose clock is behind writes an updated_at earlier than the one before it, and a +// later-than comparison let a save made from that one through, over the save it did not see. +func (s *StoreSuite) TestASaveIsRefusedOverASaveWhoseClockWasBehind() { + read := s.boundConfig("acme-app") + earlier := read.UpdatedAt.Add(-time.Hour).Truncate(time.Microsecond) + _, err := s.store.GlobalDB().NewUpdate().Model((*AgentConfig)(nil)). + Set("instructions = ?", "be brief").Set("updated_at = ?", earlier). + Where("id = ?", read.ID).Exec(s.ctx) + s.Require().NoError(err) + + mine := read + mine.Instructions = "be loud" + s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, earlier, read.UpdatedAt), ErrAgentConfigChanged) + + var stored AgentConfig + s.Require().NoError(s.store.GlobalDB().NewSelect().Model(&stored).Where("id = ?", read.ID).Scan(s.ctx)) + s.Equal("be brief", stored.Instructions) +} + func (s *StoreSuite) TestAConfigWithoutBindingsStoresAnEmptyList() { created := s.boundConfig("acme-app") @@ -322,12 +339,10 @@ func (s *StoreSuite) TestAgentConfigQueryBudgets() { config.Instructions = "be brief" s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &config)) }), "begin, the locked read, the update and commit: a config that binds nothing locks no connection") - read := config + read := config.UpdatedAt config.Greeting = "Hello." - s.Equal(4, s.countQueries(func() { - _, err := s.store.AgentConfigs.Save(s.ctx, read, &config, read.UpdatedAt) - s.Require().NoError(err) - }), "the same as an update: the change is made on the row the locked read returns") + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Save(s.ctx, &config, read, read)) }), + "the same as an update: the copy is held against the row the locked read returns") if s.store.cache != nil { for range 2 { _, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID) From 39fe595fe5baee0589fff74f005dff9430dbc8c4 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:25:51 +0100 Subject: [PATCH 5/6] fix(guests): mark a claim finished once its last step ran A claim sent again by the same account ran every step, so a backend that claims at every sign-in paid two Stream calls per conversation of the account each time, and put the account back into channels it had left. users.claim_finished_at (migration 20270201000700) is set by Store.FinishGuestClaim after the channel step. The same claim sent again answers 0 at once once it is set, and runs every step again until then, so a claim that stopped part-way is still finished by its retry. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/guests.go | 14 ++++++++++--- acceleration/internal/api/guests_test.go | 18 +++++++++++++++++ acceleration/internal/store/models.go | 3 +++ acceleration/internal/store/session_test.go | 19 ++++++++++++++++++ acceleration/internal/store/sessions.go | 20 +++++++++++++++++++ .../20270201000700_guest_claim_finished.sql | 10 ++++++++++ acceleration/schema/global.sql | 1 + 7 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 acceleration/migrations/global/20270201000700_guest_claim_finished.sql diff --git a/acceleration/internal/api/guests.go b/acceleration/internal/api/guests.go index 42bd9833bf..e8eee626a6 100644 --- a/acceleration/internal/api/guests.go +++ b/acceleration/internal/api/guests.go @@ -305,12 +305,16 @@ func (s *Server) claimGuestUser(ctx context.Context, request *claimGuestUserRequ return nil, unknownOr(err, store.ErrNotAGuest, notFound("no such guest")) } // A second claim naming the same account is the same claim arriving twice, which is not a - // conflict: a retried request must not read as somebody else's. It runs every step again - // rather than answering as done, since the first may have stopped after marking the guest, - // before the sessions in a shard moved or the account joined their channels. + // conflict: a retried request must not read as somebody else's. if guest.ClaimedBy != "" && guest.ClaimedBy != userID { return nil, conflict("that guest was already claimed") } + // Once every step below ran, the same claim has nothing left to do. Until then it runs them + // all again, since the first may have stopped after marking the guest, before the sessions + // in a shard moved or the account joined their channels. + if guest.ClaimFinishedAt != nil { + return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: 0}}, nil + } moved, err := s.store.ClaimGuest(ctx, customerID, guestID, userID) // Another claim won since the guest was read. @@ -334,6 +338,10 @@ func (s *Server) claimGuestUser(ctx context.Context, request *claimGuestUserRequ s.logger.Error("claimed a guest but could not add the account to their channels", "guest", guestID, "user", userID, "error", err) } + // Last, so a claim that stopped before here is finished by the same claim sent again. + if err := s.store.FinishGuestClaim(ctx, customerID, guestID, userID); err != nil { + return nil, err + } return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: int(moved)}}, nil } diff --git a/acceleration/internal/api/guests_test.go b/acceleration/internal/api/guests_test.go index a34e31e20c..3d955c3784 100644 --- a/acceleration/internal/api/guests_test.go +++ b/acceleration/internal/api/guests_test.go @@ -413,6 +413,24 @@ func (s *GuestsSuite) TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhe s.Contains(s.chat.Members(s.transcriptOf(talked)), account.userID, "the account reads what the guest said") } +// A claim sent again once every step of it ran did them all again: a backend that claims at +// every sign-in put the account back into the channel of a conversation it had left, with two +// Stream calls for each of the account's conversations every time. +func (s *GuestsSuite) TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAre() { + guest, account := s.recordGuest(), s.data.createUser() + talked := s.talked(guest) + s.claim(guest, account.userID) + channel := s.transcriptOf(talked) + s.Require().Contains(s.chat.Members(channel), account.userID) + _, err := s.chat.Client.Chat().UpdateChannel(context.Background(), chatlog.ChannelType, channel, + &getstream.UpdateChannelRequest{RemoveMembers: []string{account.userID}}) + s.Require().NoError(err) + + s.claim(guest, account.userID) + + s.NotContains(s.chat.Members(channel), account.userID, "the claim had nothing left to do") +} + func (s *GuestsSuite) TestAGuestSomebodyElseClaimedIsAConflict() { guest := s.recordGuest() s.claim(guest, s.utils.uuid()) diff --git a/acceleration/internal/store/models.go b/acceleration/internal/store/models.go index 7ab6c02db3..eb24a2bca6 100644 --- a/acceleration/internal/store/models.go +++ b/acceleration/internal/store/models.go @@ -485,6 +485,9 @@ type User struct { // person's conversations onto another's account. ClaimedBy string `bun:"claimed_by,nullzero"` ClaimedAt *time.Time `bun:"claimed_at"` + // ClaimFinishedAt is when every step of ClaimedBy's claim ran (FinishGuestClaim), nil + // while a claim that set ClaimedBy has not got that far. + ClaimFinishedAt *time.Time `bun:"claim_finished_at"` // RefreshSecretHash is the SHA-256 of the refresh secret this guest was last handed // (GuestSecretHash), nil for one handed none. Never sent anywhere: it is the credential // that lets a guest whose token expired come back as themselves. diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index 06c7b7623b..363821a794 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -1103,6 +1103,25 @@ func (s *StoreSuite) TestClaimingAGuestMovesTheirScheduledTasks() { } } +// A claim marked finished for anybody but the account that claimed the guest would have the +// guest's own claim skip the steps it still owes, sent again. +func (s *StoreSuite) TestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedIt() { + s.Require().NoError(s.store.RecordGuest(s.ctx, &User{ID: "guest-1", CustomerID: "acme", Name: "Guest"})) + s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "account-1")) + _, err := s.store.ClaimGuest(s.ctx, "acme", "guest-1", "account-1") + s.Require().NoError(err) + s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "mallory")) + guest, err := s.store.Guest(s.ctx, "acme", "guest-1") + s.Require().NoError(err) + s.Require().Nil(guest.ClaimFinishedAt, "finished before the claim, or by another account") + + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "account-1")) })) + + guest, err = s.store.Guest(s.ctx, "acme", "guest-1") + s.Require().NoError(err) + s.NotNil(guest.ClaimFinishedAt) +} + // sessionIDs is the ids of the sessions, in the order they were found. func sessionIDs(sessions []AgentSession) []string { found := make([]string, 0, len(sessions)) diff --git a/acceleration/internal/store/sessions.go b/acceleration/internal/store/sessions.go index c2308813f7..e14480fceb 100644 --- a/acceleration/internal/store/sessions.go +++ b/acceleration/internal/store/sessions.go @@ -268,6 +268,26 @@ func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID str return stack.Wrap(fmt.Errorf("%w: %s was already claimed by %s", ErrGuestClaimed, guestID, existing.ClaimedBy)) } +// FinishGuestClaim records that every step of userID's claim of a guest ran, so the same claim +// sent again has nothing left to do. A guest userID has not claimed is left as it is. +func (s *Store) FinishGuestClaim(ctx context.Context, customerID, guestID, userID string) error { + if customerID == "" || guestID == "" || userID == "" { + return stack.Wrap(errors.New("store: a customer, a guest and a user id are required")) + } + _, err := s.global.NewUpdate().Model((*User)(nil)). + Set("claim_finished_at = ?", time.Now().UTC()). + Where("id = ?", guestID). + Where("customer_id = ?", customerID). + Where("kind = ?", UserKindGuest). + Where("claimed_by = ?", userID). + Where("claim_finished_at IS NULL"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: finish guest claim: %w", err)) + } + return nil +} + // ErrGuestClaimed is a guest another user has already claimed. var ErrGuestClaimed = errors.New("store: guest claimed") diff --git a/acceleration/migrations/global/20270201000700_guest_claim_finished.sql b/acceleration/migrations/global/20270201000700_guest_claim_finished.sql new file mode 100644 index 0000000000..8797381959 --- /dev/null +++ b/acceleration/migrations/global/20270201000700_guest_claim_finished.sql @@ -0,0 +1,10 @@ +-- +goose Up +SET LOCAL lock_timeout = '5s'; + +-- When every step of a guest's claim ran: its sessions moved and the account joined their +-- channels. NULL while a claim that set claimed_by has not got that far, so the same claim sent +-- again runs its steps again; once set, the same claim sent again has nothing left to do. +ALTER TABLE users ADD COLUMN IF NOT EXISTS claim_finished_at timestamptz; + +-- +goose Down +ALTER TABLE users DROP COLUMN IF EXISTS claim_finished_at; diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index 53b9684181..7c14bdfb80 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -1347,6 +1347,7 @@ TABLE user_phones CREATE UNIQUE INDEX user_phones_phone ON public.user_phones USING btree (customer_id, stream_app_pk, phone) TABLE users + claim_finished_at timestamp with time zone claimed_at timestamp with time zone claimed_by text created_at timestamp with time zone NOT NULL DEFAULT now() From 97593ea81e5ba5ec2a3a06de3f9841751c849c2c Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 23:05:37 +0100 Subject: [PATCH 6/6] chore(sdks): regenerate .NET, PHP, Rust and Ruby models for updated_at The config PATCH took an optional updated_at; the Go, JS and Python clients were regenerated with it, the other server SDKs' models were not, so their generate --check failed in CI. Co-Authored-By: Claude Opus 5.5 --- sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs | 6 ++++++ sdks/php/src/Generated/AgentConfigPatch.php | 6 ++++++ sdks/ruby/lib/getstream/vision_agents/generated/spec.rb | 2 +- sdks/rust/src/types.rs | 3 +++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index 7cd3aa78ef..1b84fb7883 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -1243,6 +1243,12 @@ public partial class AgentConfigPatch [System.Text.Json.Serialization.JsonPropertyName("ui_instructions")] public string? UiInstructions { get; set; } = default!; + /// + /// The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored. + /// + [System.Text.Json.Serialization.JsonPropertyName("updated_at")] + public System.DateTimeOffset? UpdatedAt { get; set; } = default!; + [System.Text.Json.Serialization.JsonPropertyName("video")] public SessionVideo? Video { get; set; } = default!; diff --git a/sdks/php/src/Generated/AgentConfigPatch.php b/sdks/php/src/Generated/AgentConfigPatch.php index 5a44077ce2..a6f5731f7b 100644 --- a/sdks/php/src/Generated/AgentConfigPatch.php +++ b/sdks/php/src/Generated/AgentConfigPatch.php @@ -86,6 +86,8 @@ public function __construct( public ?string $image = null, // What teaches the agent's model to answer with UI. An empty string removes them. public ?string $uiInstructions = null, + // The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict whe... + public ?\DateTimeImmutable $updatedAt = null, ) { } @@ -136,6 +138,7 @@ public static function fromArray(array $data): self agents: array_key_exists('agents', $data) && $data['agents'] !== null ? array_map(ChildAgent::fromArray(...), Json::objects($data, 'agents')) : null, image: array_key_exists('image', $data) && $data['image'] !== null ? Json::string($data, 'image') : null, uiInstructions: array_key_exists('ui_instructions', $data) && $data['ui_instructions'] !== null ? Json::string($data, 'ui_instructions') : null, + updatedAt: array_key_exists('updated_at', $data) && $data['updated_at'] !== null ? Json::date($data, 'updated_at') : null, ); } @@ -270,6 +273,9 @@ public function toArray(): array if ($this->uiInstructions !== null) { $out['ui_instructions'] = $this->uiInstructions; } + if ($this->updatedAt !== null) { + $out['updated_at'] = Json::dateValue($this->updatedAt); + } return $out; } } diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index dfd46670ad..2496d3a998 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -1920,7 +1920,7 @@ module Generated required: %w[created_at id mode name region updated_at].freeze, open: false }.freeze, "AgentConfigPatch" => { - properties: %w[agents calls channels chat_channels connectors dispatch episode_cards floor_control greeting guardrail harness image instructions keyterms knowledge_namespace llm llm_fallbacks mcp_servers mode name plugin_events plugins region resume_history review role sandbox sandbox_options scheduling search skills sts stt subagent tags tools tts ui_instructions video visible_tools voice].freeze, + properties: %w[agents calls channels chat_channels connectors dispatch episode_cards floor_control greeting guardrail harness image instructions keyterms knowledge_namespace llm llm_fallbacks mcp_servers mode name plugin_events plugins region resume_history review role sandbox sandbox_options scheduling search skills sts stt subagent tags tools tts ui_instructions updated_at video visible_tools voice].freeze, required: [].freeze, open: false }.freeze, "AgentConfigRequest" => { diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index 14e11a415d..b90d80196e 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -819,6 +819,9 @@ pub struct AgentConfigPatch { ///What teaches the agent's model to answer with UI. An empty string removes them. #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub ui_instructions: ::std::option::Option<::std::string::String>, + ///The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub updated_at: ::std::option::Option<::std::string::String>, #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub video: ::std::option::Option, ///Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search.