From fa827b1ecdd96b998c27719090033b8595f09a9f Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:27:11 +0800 Subject: [PATCH] fix: preserve omitted account extra intent under row lock --- .../account_extra_intent_integration_test.go | 161 ++++++++++++++++++ backend/internal/repository/account_repo.go | 34 ++-- backend/internal/service/account_service.go | 5 + .../service/account_update_context.go | 20 +++ backend/internal/service/admin_account.go | 1 + 5 files changed, 209 insertions(+), 12 deletions(-) create mode 100644 backend/internal/repository/account_extra_intent_integration_test.go diff --git a/backend/internal/repository/account_extra_intent_integration_test.go b/backend/internal/repository/account_extra_intent_integration_test.go new file mode 100644 index 000000000000..858c3ff44f55 --- /dev/null +++ b/backend/internal/repository/account_extra_intent_integration_test.go @@ -0,0 +1,161 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// Return A's real, stale service snapshot only after B has committed its edit. +// No outer test transaction or sleep can hide the read-before-write ordering. +type accountExtraIntentReadRepo struct { + service.AdminAccountRepository + afterRead func(context.Context, *service.Account) error +} + +func (r *accountExtraIntentReadRepo) GetByID(ctx context.Context, id int64) (*service.Account, error) { + account, err := r.AdminAccountRepository.GetByID(ctx, id) + if err == nil && r.afterRead != nil { + hook := r.afterRead + r.afterRead = nil + err = hook(ctx, account) + } + return account, err +} + +func accountExtraIntentAdmin(repo service.AdminAccountRepository) service.AdminService { + return service.NewAdminService(&config.Config{}, nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, integrationEntClient, nil, nil, nil, nil, nil, nil, nil, nil, nil) +} + +func accountExtraIntentFixture(t *testing.T) (service.AdminAccountRepository, *service.Account) { + t.Helper() + repo := NewAdminAccountRepository(integrationEntClient, integrationDB, nil) + account := &service.Account{ + Name: "extra-intent-synthetic", Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 5, + Credentials: map[string]any{"api_key": "synthetic-only"}, + Extra: map[string]any{ + service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}, + service.AccountCostMultiplierExtraKey: .1, + service.AccountCostAutoSyncExtraKey: true, + }, + } + require.NoError(t, repo.Create(context.Background(), account)) + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1`, account.ID) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, account.ID) + }) + return repo, account +} + +func assertAccountExtraIntent(t *testing.T, account *service.Account, want map[string]any) { + t.Helper() + for _, key := range []string{service.AccountProbePenaltyExtraKey, service.AccountCostMultiplierExtraKey, service.AccountCostAutoSyncExtraKey} { + if value, exists := want[key]; exists { + require.Equal(t, value, account.Extra[key], key) + } else { + require.NotContains(t, account.Extra, key) + } + } +} + +func TestAccountExtraIntentServiceReadBeforeConcurrentCommit(t *testing.T) { + for _, route := range []string{"admin", "account-service"} { + for _, extraMode := range []string{"nil-extra", "missing-keys"} { + for _, change := range []string{"disable", "change-amount", "delete"} { + t.Run(route+"/"+extraMode+"/"+change, func(t *testing.T) { + repo, account := accountExtraIntentFixture(t) + latest := map[string]any{ + service.AccountProbePenaltyExtraKey: map[string]any{"enabled": change != "disable", "minimum_charge": .002}, + service.AccountCostMultiplierExtraKey: .2, + service.AccountCostAutoSyncExtraKey: false, + } + if change == "delete" { + latest = map[string]any{} + } + read := false + gate := &accountExtraIntentReadRepo{AdminAccountRepository: repo} + gate.afterRead = func(ctx context.Context, stale *service.Account) error { + read = true + require.Equal(t, .001, stale.ProbePenaltyMinimum(), "A must read the old enabled setting") + if change == "delete" { + _, err := integrationDB.ExecContext(ctx, `UPDATE accounts SET extra=extra-'probe_penalty'-'cost_multiplier'-'cost_multiplier_auto_sync' WHERE id=$1`, account.ID) + return err + } + return repo.UpdateExtra(ctx, account.ID, latest) + } + var extra map[string]any + if extraMode == "missing-keys" { + extra = map[string]any{"form_setting": "saved"} + } + ctx := context.Background() + name := "extra-intent-renamed" + var saved *service.Account + var err error + if route == "admin" { + // The failing HTTP DTO is only {name: ...}: no extra or platform. + saved, err = accountExtraIntentAdmin(gate).UpdateAccount(ctx, account.ID, &service.UpdateAccountInput{Name: name, Extra: extra}) + } else { + input := service.UpdateAccountRequest{Name: &name} + if extra != nil { + input.Extra = &extra + } + saved, err = service.NewAccountService(gate, nil).Update(ctx, account.ID, input) + } + require.NoError(t, err) + require.True(t, read) + got, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, name, got.Name) + assertAccountExtraIntent(t, got, latest) + assertAccountExtraIntent(t, saved, latest) + if extra != nil { + require.Equal(t, "saved", got.Extra["form_setting"]) + } + }) + } + } + } +} + +func TestAccountExtraIntentExplicitServiceUpdates(t *testing.T) { + for _, route := range []string{"admin", "account-service"} { + t.Run(route, func(t *testing.T) { + repo, account := accountExtraIntentFixture(t) + ctx := context.Background() + for _, extra := range []map[string]any{ + { + service.AccountProbePenaltyExtraKey: map[string]any{"enabled": false, "minimum_charge": .002}, + service.AccountCostMultiplierExtraKey: .2, + service.AccountCostAutoSyncExtraKey: false, + }, + { + service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .003}, + service.AccountCostMultiplierExtraKey: 0.0, + service.AccountCostAutoSyncExtraKey: true, + }, + { + service.AccountProbePenaltyExtraKey: nil, + service.AccountCostMultiplierExtraKey: nil, + service.AccountCostAutoSyncExtraKey: nil, + }, + } { + var err error + if route == "admin" { + _, err = accountExtraIntentAdmin(repo).UpdateAccount(ctx, account.ID, &service.UpdateAccountInput{Extra: extra}) + } else { + _, err = service.NewAccountService(repo, nil).Update(ctx, account.ID, service.UpdateAccountRequest{Extra: &extra}) + } + require.NoError(t, err) + got, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + assertAccountExtraIntent(t, got, extra) + } + }) + } +} diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 6d7ed4644589..56efdf73b74c 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -942,18 +942,6 @@ func lockAndMergeAccountProbeExtra( } } - // Omitted cost means an unrelated edit. Keep the value under the row lock, - // including a probe update committed after the edit form was loaded. - for _, key := range []string{service.AccountCostMultiplierExtraKey, service.AccountCostAutoSyncExtraKey, service.AccountProbePenaltyExtraKey} { - if _, provided := extra[key]; !provided { - if value, exists := currentExtra[key]; exists { - if extra == nil { - extra = make(map[string]any) - } - extra[key] = value - } - } - } delete(extra, service.OpenAITwoFAAdmissionExtraKey) if state, ok := currentExtra[service.OpenAITwoFAAdmissionExtraKey]; ok { if extra == nil { @@ -1109,6 +1097,28 @@ func lockAndMergeAccountProbeExtra( } extra = portable } + // A service may have filled omitted request fields with a stale snapshot. + // Resolve omission against the locked row, including a concurrent deletion. + // Do this after platform portability so omitted account-wide costs stay fresh; + // probe penalties still follow the platform transition's discard contract. + for _, key := range []string{service.AccountCostMultiplierExtraKey, service.AccountCostAutoSyncExtraKey, service.AccountProbePenaltyExtraKey} { + if service.AccountPlatformChanging(ctx) && key == service.AccountProbePenaltyExtraKey { + continue + } + provided, scoped := service.AccountExtraUpdateFieldProvided(ctx, key) + if !scoped { + _, provided = extra[key] + } + if !provided { + delete(extra, key) + if value, exists := currentExtra[key]; exists { + if extra == nil { + extra = make(map[string]any) + } + extra[key] = value + } + } + } return extra, nil } diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index cfea0fb7a4f6..db9ce856fe8f 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -342,6 +342,11 @@ func (s *AccountService) ListByGroup(ctx context.Context, groupID int64) ([]Acco // Update 更新账号 func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccountRequest) (*Account, error) { ctx = withAccountStatusPreservation(ctx, req.Status == nil) + var requestedExtra map[string]any + if req.Extra != nil { + requestedExtra = *req.Extra + } + ctx = withAccountExtraUpdateFields(ctx, requestedExtra) account, err := s.accountRepo.GetByID(ctx, id) if err != nil { return nil, fmt.Errorf("get account: %w", err) diff --git a/backend/internal/service/account_update_context.go b/backend/internal/service/account_update_context.go index f935b3dfab79..9bac995fa329 100644 --- a/backend/internal/service/account_update_context.go +++ b/backend/internal/service/account_update_context.go @@ -20,3 +20,23 @@ func PreserveAccountStatus(ctx context.Context) bool { preserve, _ := ctx.Value(preserveAccountStatusKey{}).(bool) return preserve } + +type accountExtraUpdateFieldsKey struct{} + +// Capture request intent before a service fills omitted extra from its snapshot. +// Each request replaces inherited intent, including requests with nil extra. +func withAccountExtraUpdateFields(ctx context.Context, extra map[string]any) context.Context { + provided := make(map[string]bool, 3) + for _, key := range []string{AccountCostMultiplierExtraKey, AccountCostAutoSyncExtraKey, AccountProbePenaltyExtraKey} { + _, provided[key] = extra[key] + } + return context.WithValue(ctx, accountExtraUpdateFieldsKey{}, provided) +} + +// AccountExtraUpdateFieldProvided distinguishes explicit request fields from a +// materialized Account snapshot. Without request scope, internal full-Account +// writers retain their existing key-presence contract. +func AccountExtraUpdateFieldProvided(ctx context.Context, key string) (provided, scoped bool) { + fields, scoped := ctx.Value(accountExtraUpdateFieldsKey{}).(map[string]bool) + return fields[key], scoped +} diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index bff7d6214021..33735d87592f 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -667,6 +667,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U // An omitted status does not own authentication state. Explicit status edits // override any inherited preservation marker just as scheduling intent does. ctx = withAccountStatusPreservation(ctx, input.Status == "") + ctx = withAccountExtraUpdateFields(ctx, input.Extra) if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil { return nil, err }