diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 827a750577..2aa73c61ea 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -5,13 +5,18 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" + "errors" "fmt" "log/slog" + "slices" "strconv" + "sync" + "sync/atomic" "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/redis/go-redis/v9" + "github.com/tidwall/gjson" ) const ( @@ -27,6 +32,12 @@ const ( schedulerRetiredPrefix = "sched:retired:" schedulerSnapshotPrefix = "sched:" schedulerLockPrefix = "sched:lock:" + // 账号精简记录(sched:meta:)的修订号:全局修订号与按平台划分的修订号(前缀后接平台名)。 + // 改写精简记录后写入所涉平台的修订号;删除记录、改写平台为空或平台发生变化的记录、写入出错时写入全局修订号。 + // 取值都是新的随机串,读侧只比较是否相等,键丢失后重建也不会与旧取值相同; + // Redis 回滚恢复出缓存记录过的旧取值时,由最长复用时长兜底。 + schedulerAccountMetaRevisionKey = "sched:meta:rev" + schedulerAccountMetaPlatformRevisionPrefix = "sched:meta:rev:" defaultSchedulerSnapshotMGetChunkSize = 128 defaultSchedulerSnapshotWriteChunkSize = 256 @@ -35,6 +46,16 @@ const ( // snapshotGraceTTLSeconds 旧快照过期的宽限期(秒)。 // 替代立即 DEL,让正在读取旧版本的 reader 有足够时间完成 ZRANGE。 snapshotGraceTTLSeconds = 60 + + // schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的最长复用时长, + // 限定了未推进修订号的精简记录改写在本进程的最长可见延迟,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。 + schedulerSnapshotCacheMaxAge = 10 * time.Second + // schedulerSnapshotCacheEvictAge:写入条目时,加载时间早于该时长的其它条目一并清除, + // 已退休分组的条目不会长期驻留。 + schedulerSnapshotCacheEvictAge = 10 * schedulerSnapshotCacheMaxAge + + schedulerAccountMetaRevisionBytes = 16 + schedulerAccountMetaRevisionWriteTimeout = 3 * time.Second ) const ( @@ -223,6 +244,28 @@ type schedulerCache struct { rdb *redis.Client mgetChunkSize int writeChunkSize int + + // now 是进程内快照缓存判定条目年龄的时钟。 + now func() time.Time + + snapshotMu sync.RWMutex + snapshotEntries map[string]*schedulerSnapshotEntry + + // globalRevisionPending 与 globalRevisionWriting 合并写入出错后的后台全局修订号写入,见 scheduleGlobalAccountMetaRevision。 + globalRevisionPending atomic.Bool + globalRevisionWriting atomic.Bool +} + +// schedulerSnapshotEntry 是一个 bucket 的已解码快照。 +// revisions 依次是全局修订号与该 bucket 成员可能涉及的各平台修订号(见 schedulerSnapshotTagKeys)。 +// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄; +// 每次读取都按值复制出本次请求独占的副本再套用 last_used。 +type schedulerSnapshotEntry struct { + active string + revisions []string + loadedAt time.Time + accounts []*service.Account + lastUsedKeys []string } func NewSchedulerCache(rdb *redis.Client) service.SchedulerCache { @@ -237,42 +280,67 @@ func newSchedulerCacheWithChunkSizes(rdb *redis.Client, mgetChunkSize, writeChun writeChunkSize = defaultSchedulerSnapshotWriteChunkSize } return &schedulerCache{ - rdb: rdb, - mgetChunkSize: mgetChunkSize, - writeChunkSize: writeChunkSize, + rdb: rdb, + mgetChunkSize: mgetChunkSize, + writeChunkSize: writeChunkSize, + now: time.Now, + snapshotEntries: make(map[string]*schedulerSnapshotEntry), } } +// GetSnapshot 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存, +// 只有 ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过最长复用时长时才复用; +// 否则重新从 Redis 加载。last_used 每次都从 Redis 读取。 +// 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。 func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { - readyKey := schedulerBucketKey(schedulerReadyPrefix, bucket) - readyVal, err := c.rdb.Get(ctx, readyKey).Result() - if err == redis.Nil { - return nil, false, nil - } + bucketKey := bucket.String() + tagKeys := schedulerSnapshotTagKeys(bucket) + tags, err := c.rdb.MGet(ctx, tagKeys...).Result() if err != nil { return nil, false, err } - if readyVal != "1" { - return nil, false, nil - } - - activeKey := schedulerBucketKey(schedulerActivePrefix, bucket) - activeVal, err := c.rdb.Get(ctx, activeKey).Result() - if err == redis.Nil { - return nil, false, nil + if len(tags) != len(tagKeys) { + return nil, false, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys)) } + readyVal, err := schedulerCacheOptionalString(tags[0]) if err != nil { return nil, false, err } + activeVal, err := schedulerCacheOptionalString(tags[1]) + if err != nil { + return nil, false, err + } + // 修订号缺失(nil)按空字符串比较:它是一个独立取值,不会与任何写入过的随机修订号相等。 + revisions := make([]string, 0, len(tags)-2) + for _, tag := range tags[2:] { + revision, err := schedulerCacheOptionalString(tag) + if err != nil { + return nil, false, err + } + revisions = append(revisions, revision) + } + if readyVal != "1" || activeVal == "" { + c.dropSnapshotEntry(bucketKey) + return nil, false, nil + } - snapshotKey := schedulerSnapshotKey(bucket, activeVal) - ids, err := c.rdb.ZRange(ctx, snapshotKey, 0, -1).Result() + now := c.now() + if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.matches(activeVal, revisions, now) { + accounts, err := c.snapshotAccountsFromEntry(ctx, entry) + if err != nil { + return nil, false, err + } + return accounts, true, nil + } + + ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVal), 0, -1).Result() if err != nil { return nil, false, err } if len(ids) == 0 { // 空快照视为缓存未命中,触发数据库回退查询 // 这解决了新分组创建后立即绑定账号时的竞态条件问题 + c.dropSnapshotEntry(bucketKey) return nil, false, nil } @@ -286,29 +354,143 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul if err != nil { return nil, false, err } - lastUsedValues, err := c.mgetChunked(ctx, lastUsedKeys) - if err != nil { - return nil, false, err - } - accounts := make([]*service.Account, 0, len(values)) - for i, val := range values { + masters := make([]*service.Account, 0, len(values)) + for _, val := range values { if val == nil { + c.dropSnapshotEntry(bucketKey) return nil, false, nil } account, err := decodeCachedAccount(val) if err != nil { return nil, false, err } - if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil { - return nil, false, err - } - accounts = append(accounts, account) + masters = append(masters, account) + } + // 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。 + for _, master := range masters { + master.PrepareSharedSnapshot() } + // 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟:精简记录读取晚于这组取值, + // 之后若再有改写,修订号或 active 必然不同,或在最长复用时长后过期。 + entry := &schedulerSnapshotEntry{ + active: activeVal, + revisions: revisions, + loadedAt: now, + accounts: masters, + lastUsedKeys: lastUsedKeys, + } + c.storeSnapshotEntry(bucketKey, entry) + + accounts, err := c.snapshotAccountsFromEntry(ctx, entry) + if err != nil { + return nil, false, err + } return accounts, true, nil } +func (e *schedulerSnapshotEntry) matches(active string, revisions []string, now time.Time) bool { + if e.active != active || !slices.Equal(e.revisions, revisions) { + return false + } + age := now.Sub(e.loadedAt) + return age >= 0 && age < schedulerSnapshotCacheMaxAge +} + +// snapshotAccountsFromEntry 读取最新 last_used,并为本次调用一次性分配一组母本副本。 +func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]*service.Account, error) { + lastUsedValues, err := c.mgetChunked(ctx, entry.lastUsedKeys) + if err != nil { + return nil, err + } + if len(lastUsedValues) != len(entry.accounts) { + return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(lastUsedValues), len(entry.accounts)) + } + slab := make([]service.Account, len(entry.accounts)) + accounts := make([]*service.Account, len(entry.accounts)) + for i, master := range entry.accounts { + slab[i] = *master + account := &slab[i] + if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil { + return nil, err + } + accounts[i] = account + } + return accounts, nil +} + +func (c *schedulerCache) lookupSnapshotEntry(bucketKey string) *schedulerSnapshotEntry { + c.snapshotMu.RLock() + defer c.snapshotMu.RUnlock() + return c.snapshotEntries[bucketKey] +} + +// storeSnapshotEntry 写入条目,并清除加载时间早于 schedulerSnapshotCacheEvictAge 的其它条目。 +// 已有条目的加载时间晚于新条目时保留已有条目:它基于更晚读到的 (active, 修订号)。 +func (c *schedulerCache) storeSnapshotEntry(bucketKey string, entry *schedulerSnapshotEntry) { + c.snapshotMu.Lock() + defer c.snapshotMu.Unlock() + if current := c.snapshotEntries[bucketKey]; current == nil || !current.loadedAt.After(entry.loadedAt) { + c.snapshotEntries[bucketKey] = entry + } + for key, other := range c.snapshotEntries { + if key != bucketKey && entry.loadedAt.Sub(other.loadedAt) > schedulerSnapshotCacheEvictAge { + delete(c.snapshotEntries, key) + } + } +} + +func (c *schedulerCache) dropSnapshotEntry(bucketKey string) { + c.snapshotMu.RLock() + _, ok := c.snapshotEntries[bucketKey] + c.snapshotMu.RUnlock() + if !ok { + return + } + c.snapshotMu.Lock() + delete(c.snapshotEntries, bucketKey) + c.snapshotMu.Unlock() +} + +// schedulerSnapshotTagKeys 返回 GetSnapshot 一次读取的键:ready、active、全局修订号、bucket 平台的修订号, +// mixed 模式再加 antigravity 平台的修订号。按平台判定失效依赖 bucket 成员只取自 bucket 平台 +// (mixed 模式另含开启混合调度的 antigravity 账号);账号平台发生变化时,写入方另行写入全局修订号。 +func schedulerSnapshotTagKeys(bucket service.SchedulerBucket) []string { + keys := make([]string, 0, 5) + keys = append(keys, + schedulerBucketKey(schedulerReadyPrefix, bucket), + schedulerBucketKey(schedulerActivePrefix, bucket), + schedulerAccountMetaRevisionKey, + schedulerAccountMetaRevisionKeyForPlatform(bucket.Platform), + ) + if bucket.Mode == service.SchedulerModeMixed && bucket.Platform != service.PlatformAntigravity { + keys = append(keys, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAntigravity)) + } + return keys +} + +// schedulerAccountMetaRevisionKeyForPlatform 返回平台修订号的键;平台为空时返回全局修订号的键。 +func schedulerAccountMetaRevisionKeyForPlatform(platform string) string { + if platform == "" { + return schedulerAccountMetaRevisionKey + } + return schedulerAccountMetaPlatformRevisionPrefix + platform +} + +func schedulerCacheOptionalString(value any) (string, error) { + switch typed := value.(type) { + case nil: + return "", nil + case string: + return typed, nil + case []byte: + return string(typed), nil + default: + return "", fmt.Errorf("unexpected scheduler cache value type: %T", value) + } +} + func (c *schedulerCache) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { result, err := captureBucketWriteTokenScript.Run(ctx, c.rdb, []string{ schedulerBucketKey(schedulerEpochPrefix, bucket), @@ -604,7 +786,13 @@ func (c *schedulerCache) DeleteAccount(ctx context.Context, accountID int64) err return nil } id := strconv.FormatInt(accountID, 10) - return c.rdb.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id)).Err() + // 删除精简记录与推进全局修订号在同一个 MULTI 中原子执行:读到删除结果的读者也读到新修订号, + // 进程内快照缓存不会给出已删除的账号。 + pipe := c.rdb.TxPipeline() + pipe.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id)) + pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0) + _, err := pipe.Exec(ctx) + return err } func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]time.Time) error { @@ -614,6 +802,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t pipe := c.rdb.Pipeline() queued := 0 + metaDeleted := false keys := make([]string, 0, schedulerLastUsedUpdateChunkSize*2) args := make([]any, 0, schedulerLastUsedUpdateChunkSize) queueBatch := func() { @@ -638,6 +827,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t idText := strconv.FormatInt(id, 10) pipe.Del(ctx, schedulerAccountKey(idText), schedulerAccountMetaKey(idText), schedulerLastUsedKey(idText)) queued++ + metaDeleted = true continue } idText := strconv.FormatInt(id, 10) @@ -651,6 +841,10 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t if queued == 0 { return nil } + if metaDeleted { + // 被删账号的平台未知,全局修订号排在同一 pipeline 的 DEL 之后。 + pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0) + } _, err := pipe.Exec(ctx) return err } @@ -776,21 +970,53 @@ func decodeCachedAccount(val any) (*service.Account, error) { return &account, nil } +// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。 +// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾, +// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。 +// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号, +// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值), +// 漏检由进程内快照缓存的最长复用时长兜底。 +// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。 func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) { if len(accounts) == 0 { return nil, nil } + type metaWrite struct { + platform string + previous *redis.StatusCmd + } pipe := c.rdb.Pipeline() accountIDs := make([]int64, 0, len(accounts)) + platforms := make([]string, 0, 1) + writes := make([]metaWrite, 0, min(len(accounts), c.writeChunkSize)) pending := 0 - flush := func() error { - if pending == 0 { - return nil + execFailed := false + platformChanged := false + defer func() { + if execFailed { + c.scheduleGlobalAccountMetaRevision(ctx) } - if _, err := pipe.Exec(ctx); err != nil { + }() + exec := func() error { + cmds, err := pipe.Exec(ctx) + if err != nil && !errors.Is(err, redis.Nil) { + execFailed = true return err } + // SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。 + for _, cmd := range cmds { + if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) { + execFailed = true + return cmdErr + } + } + for _, write := range writes { + if schedulerMetaPlatformChanged(write.previous, write.platform) { + platformChanged = true + } + } + writes = writes[:0] pipe = c.rdb.Pipeline() pending = 0 return nil @@ -805,27 +1031,93 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service ) continue } - - id := strconv.FormatInt(account.ID, 10) - pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0) - pipe.Set(ctx, schedulerAccountMetaKey(id), metaPayload, 0) - // Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild - // must not overwrite a newer scheduler update. - accountIDs = append(accountIDs, account.ID) - pending++ if pending >= c.writeChunkSize { - if err := flush(); err != nil { + if err := exec(); err != nil { return nil, err } } + + id := strconv.FormatInt(account.ID, 10) + pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0) + writes = append(writes, metaWrite{ + platform: account.Platform, + previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(id), metaPayload, redis.SetArgs{Get: true}), + }) + // Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild + // must not overwrite a newer scheduler update. + accountIDs = append(accountIDs, account.ID) + if !slices.Contains(platforms, account.Platform) { + platforms = append(platforms, account.Platform) + } + pending++ } - if err := flush(); err != nil { + if pending == 0 { + return accountIDs, nil + } + for _, platform := range platforms { + pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0) + } + if err := exec(); err != nil { return nil, err } + if platformChanged { + c.advanceGlobalAccountMetaRevision(ctx) + } return accountIDs, nil } +// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台; +// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。 +func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool { + raw, err := previous.Result() + if err != nil { + return false + } + if !gjson.Valid(raw) { + return true + } + old := gjson.Get(raw, "Platform") + return old.Type != gjson.String || old.Str != platform +} + +// scheduleGlobalAccountMetaRevision 在后台写入全局修订号,不阻塞调用方。 +// 同一时刻至多一个后台写入:写入前先清除待写标记,写完后标记再次被置位就再写一轮, +// 因此每次调用之后都至少还有一次完整的写入发生在它之后。 +func (c *schedulerCache) scheduleGlobalAccountMetaRevision(ctx context.Context) { + c.globalRevisionPending.Store(true) + if !c.globalRevisionWriting.CompareAndSwap(false, true) { + return + } + go func() { + for { + c.globalRevisionPending.Store(false) + c.advanceGlobalAccountMetaRevision(ctx) + c.globalRevisionWriting.Store(false) + if !c.globalRevisionPending.Load() || !c.globalRevisionWriting.CompareAndSwap(false, true) { + return + } + } + }() +} + +// advanceGlobalAccountMetaRevision 单独写入新的全局修订号,使所有 bucket 的进程内快照失效。 +// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的最长复用时长兜底。 +func (c *schedulerCache) advanceGlobalAccountMetaRevision(ctx context.Context) { + writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), schedulerAccountMetaRevisionWriteTimeout) + defer cancel() + if err := c.rdb.Set(writeCtx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0).Err(); err != nil { + slog.Warn("scheduler cache failed to advance account metadata revision", "error", err) + } +} + +func newSchedulerAccountMetaRevision() string { + raw := make([]byte, schedulerAccountMetaRevisionBytes) + // crypto/rand.Read 读取失败时直接终止进程,不会返回错误。 + _, _ = rand.Read(raw) + return hex.EncodeToString(raw) +} + func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) { fullPayload, err := json.Marshal(account) if err != nil { diff --git a/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go new file mode 100644 index 0000000000..9b3d92ea26 --- /dev/null +++ b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go @@ -0,0 +1,980 @@ +//go:build unit + +package repository + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +// schedulerCacheCommandRecorder 记录发往 Redis 的命令(名称 + 首个参数)与每次 pipeline 执行的命令批次, +// 并可让第 N 次 pipeline 执行失败。新连接的握手命令不计入。 +type schedulerCacheCommandRecorder struct { + mu sync.Mutex + commands []string + batches [][]string + pipelines int + failPipelineAt int +} + +func (r *schedulerCacheCommandRecorder) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (r *schedulerCacheCommandRecorder) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if !isSchedulerCacheHandshakeCommand(cmd) { + r.record(cmd) + } + return next(ctx, cmd) + } +} + +func (r *schedulerCacheCommandRecorder) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return func(ctx context.Context, cmds []redis.Cmder) error { + handshake := len(cmds) > 0 + for _, cmd := range cmds { + handshake = handshake && isSchedulerCacheHandshakeCommand(cmd) + } + if handshake { + return next(ctx, cmds) + } + r.mu.Lock() + r.pipelines++ + fail := r.failPipelineAt > 0 && r.pipelines == r.failPipelineAt + r.mu.Unlock() + batch := make([]string, 0, len(cmds)) + for _, cmd := range cmds { + batch = append(batch, r.record(cmd)) + } + r.mu.Lock() + r.batches = append(r.batches, batch) + r.mu.Unlock() + if fail { + err := errors.New("injected pipeline failure") + for _, cmd := range cmds { + cmd.SetErr(err) + } + return err + } + return next(ctx, cmds) + } +} + +func isSchedulerCacheHandshakeCommand(cmd redis.Cmder) bool { + switch strings.ToLower(cmd.Name()) { + case "hello", "auth", "client", "select": + return true + default: + return false + } +} + +func (r *schedulerCacheCommandRecorder) record(cmd redis.Cmder) string { + entry := strings.ToLower(cmd.Name()) + if args := cmd.Args(); len(args) > 1 { + entry += " " + fmt.Sprint(args[1]) + } + r.mu.Lock() + r.commands = append(r.commands, entry) + r.mu.Unlock() + return entry +} + +func (r *schedulerCacheCommandRecorder) reset() { + r.mu.Lock() + r.commands = nil + r.batches = nil + r.pipelines = 0 + r.mu.Unlock() +} + +func (r *schedulerCacheCommandRecorder) pipelineBatches() [][]string { + r.mu.Lock() + defer r.mu.Unlock() + return append([][]string(nil), r.batches...) +} + +func (r *schedulerCacheCommandRecorder) setFailPipelineAt(n int) { + r.mu.Lock() + r.failPipelineAt = n + r.mu.Unlock() +} + +func (r *schedulerCacheCommandRecorder) recorded() []string { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.commands...) +} + +func (r *schedulerCacheCommandRecorder) countPrefix(prefix string) int { + count := 0 + for _, command := range r.recorded() { + if strings.HasPrefix(command, prefix) { + count++ + } + } + return count +} + +func newSchedulerCacheMemoUnit(t *testing.T, writeChunkSize int) (*schedulerCache, *miniredis.Miniredis, *schedulerCacheCommandRecorder) { + t.Helper() + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + recorder := &schedulerCacheCommandRecorder{} + rdb.AddHook(recorder) + cache, ok := newSchedulerCacheWithChunkSizes(rdb, defaultSchedulerSnapshotMGetChunkSize, writeChunkSize).(*schedulerCache) + require.True(t, ok) + return cache, mr, recorder +} + +func memoTestBucket(groupID int64) service.SchedulerBucket { + return service.SchedulerBucket{GroupID: groupID, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle} +} + +func memoTestAccount(id int64, name string) service.Account { + return memoTestAccountOn(service.PlatformAnthropic, id, name) +} + +func memoTestAccountOn(platform string, id int64, name string) service.Account { + return service.Account{ + ID: id, + Name: name, + Platform: platform, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-sonnet": "sonnet-" + name}, + "access_token": "dropped-by-projection", + }, + Extra: map[string]any{"session_window_utilization": 0.25}, + } +} + +func memoPublish(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket, accounts ...service.Account) { + t.Helper() + ctx := context.Background() + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, accounts)) +} + +func memoRead(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) []*service.Account { + t.Helper() + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.NoError(t, err) + require.True(t, hit) + return accounts +} + +func memoRequireMiss(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) { + t.Helper() + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.NoError(t, err) + require.False(t, hit) + require.Nil(t, accounts) +} + +func memoIDs(accounts []*service.Account) []int64 { + ids := make([]int64, 0, len(accounts)) + for _, account := range accounts { + ids = append(ids, account.ID) + } + return ids +} + +func memoRevision(t *testing.T, cache *schedulerCache, key string) string { + t.Helper() + revision, err := cache.rdb.Get(context.Background(), key).Result() + if errors.Is(err, redis.Nil) { + return "" + } + require.NoError(t, err) + return revision +} + +// memoRevisionValue 读取修订号,不做断言,供 require.Eventually 的条件函数使用。 +func memoRevisionValue(cache *schedulerCache, key string) string { + revision, _ := cache.rdb.Get(context.Background(), key).Result() + return revision +} + +var memoAnthropicRevisionKey = schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAnthropic) + +func memoEntryCount(cache *schedulerCache) int { + cache.snapshotMu.RLock() + defer cache.snapshotMu.RUnlock() + return len(cache.snapshotEntries) +} + +func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(101) + memoPublish(t, cache, bucket, memoTestAccount(1, "a"), memoTestAccount(2, "b"), memoTestAccount(3, "c")) + + recorder.reset() + first := memoRead(t, cache, bucket) + require.Equal(t, 1, recorder.countPrefix("zrange ")) + require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix)) + + recorder.reset() + second := memoRead(t, cache, bucket) + require.Equal(t, []string{ + "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket), + "mget " + schedulerLastUsedKey("1"), + }, recorder.recorded()) + + require.Equal(t, []int64{1, 2, 3}, memoIDs(second)) + require.Equal(t, first, second) + for i := range first { + require.NotSame(t, first[i], second[i]) + } + require.Equal(t, "sonnet-b", second[1].GetMappedModel("claude-sonnet")) + require.NotContains(t, second[1].Credentials, "access_token") +} + +func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(102) + embedded := time.Now().UTC().Truncate(time.Millisecond).Add(-time.Hour) + account := memoTestAccount(11, "a") + account.LastUsedAt = &embedded + memoPublish(t, cache, bucket, account) + + first := memoRead(t, cache, bucket) + require.Equal(t, embedded, *first[0].LastUsedAt) + + latest := embedded.Add(42 * time.Second) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: latest})) + recorder.reset() + second := memoRead(t, cache, bucket) + require.Zero(t, recorder.countPrefix("zrange "), "last_used updates must not invalidate the decoded snapshot") + require.Equal(t, latest, *second[0].LastUsedAt) + require.Equal(t, embedded, *first[0].LastUsedAt, "an earlier result must not observe later reads") + + // 修改返回对象的顶层字段只影响本次结果。 + second[0].Schedulable = false + second[0].Name = "mutated" + second[0].LastUsedAt = nil + second[0].Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "replaced"}} + require.Equal(t, "replaced", second[0].GetMappedModel("claude-sonnet")) + + // 删除 last_used 侧键(不改精简记录):若母本曾被套用 last_used,这里会读到 latest。 + require.NoError(t, cache.rdb.Del(ctx, schedulerLastUsedKey("11")).Err()) + recorder.reset() + third := memoRead(t, cache, bucket) + require.Zero(t, recorder.countPrefix("zrange ")) + require.Equal(t, embedded, *third[0].LastUsedAt) + require.True(t, third[0].Schedulable) + require.Equal(t, "a", third[0].Name) + require.Equal(t, "sonnet-a", third[0].GetMappedModel("claude-sonnet")) +} + +func TestSchedulerCacheSnapshotMemoSetAccountIsVisibleImmediately(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(103) + account := memoTestAccount(21, "a") + memoPublish(t, cache, bucket, account, memoTestAccount(22, "b")) + require.True(t, memoRead(t, cache, bucket)[0].Schedulable) + + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + account.Schedulable = false + account.Extra = map[string]any{"session_window_utilization": 0.9} + require.NoError(t, cache.SetAccount(ctx, &account)) + require.NotEqual(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + + got := memoRead(t, cache, bucket) + require.Equal(t, []int64{21, 22}, memoIDs(got)) + require.False(t, got[0].Schedulable) + require.Equal(t, 0.9, got[0].Extra["session_window_utilization"]) + require.True(t, got[1].Schedulable) +} + +func TestSchedulerCacheSnapshotMemoDeleteAccountMisses(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(104) + memoPublish(t, cache, bucket, memoTestAccount(31, "a"), memoTestAccount(32, "b")) + memoRead(t, cache, bucket) + + revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + require.NoError(t, cache.DeleteAccount(ctx, 32)) + require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + memoRequireMiss(t, cache, bucket) + require.Zero(t, memoEntryCount(cache)) +} + +func TestSchedulerCacheSnapshotMemoCrossBucketMetadataRewrite(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucketA := memoTestBucket(105) + bucketB := memoTestBucket(106) + shared := memoTestAccount(41, "shared") + memoPublish(t, cache, bucketA, shared) + memoPublish(t, cache, bucketB, shared, memoTestAccount(42, "b-only")) + require.Equal(t, "shared", memoRead(t, cache, bucketB)[0].Name) + activeB := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val() + + shared.Name = "shared-renamed" + shared.Priority = 9 + memoPublish(t, cache, bucketA, shared) + + require.Equal(t, activeB, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val()) + got := memoRead(t, cache, bucketB) + require.Equal(t, []int64{41, 42}, memoIDs(got)) + require.Equal(t, "shared-renamed", got[0].Name) + require.Equal(t, 9, got[0].Priority) +} + +func TestSchedulerCacheSnapshotMemoUnencodableLastUsedDeletionMisses(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(107) + memoPublish(t, cache, bucket, memoTestAccount(51, "a"), memoTestAccount(52, "b")) + memoRead(t, cache, bucket) + + revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{52: invalid})) + require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + memoRequireMiss(t, cache, bucket) + + // 正常的 last_used 写入不推进任何修订号。 + globalAfterDelete := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformAfterDelete := memoRevision(t, cache, memoAnthropicRevisionKey) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{51: time.Now()})) + require.Equal(t, globalAfterDelete, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Equal(t, platformAfterDelete, memoRevision(t, cache, memoAnthropicRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoMembershipChangeByAccountIDs(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(108) + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + ids, err := cache.SetSnapshotAndReturnAccountIDs(ctx, bucket, token, []service.Account{memoTestAccount(61, "a"), memoTestAccount(62, "b")}) + require.NoError(t, err) + require.Equal(t, []int64{61, 62}, ids) + require.Equal(t, []int64{61, 62}, memoIDs(memoRead(t, cache, bucket))) + + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + token, err = cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshotByAccountIDs(ctx, bucket, token, []int64{62})) + + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "membership-only publishing does not touch metadata") + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey), "membership-only publishing does not touch metadata") + require.NotEqual(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()) + require.Equal(t, []int64{62}, memoIDs(memoRead(t, cache, bucket))) +} + +func TestSchedulerCacheSnapshotMemoRetireReopenAndRepublish(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(109) + memoPublish(t, cache, bucket, memoTestAccount(71, "before")) + memoRead(t, cache, bucket) + + require.NoError(t, cache.RetireBucket(ctx, bucket)) + memoRequireMiss(t, cache, bucket) + require.Zero(t, memoEntryCount(cache)) + + token, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + memoRequireMiss(t, cache, bucket) + + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{memoTestAccount(72, "after")})) + got := memoRead(t, cache, bucket) + require.Equal(t, []int64{72}, memoIDs(got)) + require.Equal(t, "after", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoEmptyAndNilMetadataAreNotCached(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + + t.Run("empty zset", func(t *testing.T) { + bucket := memoTestBucket(110) + _, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(81, "a")}) + require.NoError(t, err) + memoPublish(t, cache, bucket) + memoRequireMiss(t, cache, bucket) + + active := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + require.NotEmpty(t, active) + require.NoError(t, cache.rdb.ZAdd(ctx, schedulerSnapshotKey(bucket, active), redis.Z{Score: 0, Member: "81"}).Err()) + require.Equal(t, []int64{81}, memoIDs(memoRead(t, cache, bucket))) + }) + + t.Run("nil metadata", func(t *testing.T) { + bucket := memoTestBucket(111) + memoPublish(t, cache, bucket, memoTestAccount(91, "a"), memoTestAccount(92, "b")) + metaKey := schedulerAccountMetaKey("92") + payload, err := cache.rdb.Get(ctx, metaKey).Bytes() + require.NoError(t, err) + require.NoError(t, cache.rdb.Del(ctx, metaKey).Err()) + memoRequireMiss(t, cache, bucket) + + require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err()) + require.Equal(t, []int64{91, 92}, memoIDs(memoRead(t, cache, bucket))) + }) +} + +func TestSchedulerCacheSnapshotMemoDecodeFailureIsNotCached(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(112) + memoPublish(t, cache, bucket, memoTestAccount(101, "a")) + metaKey := schedulerAccountMetaKey("101") + payload, err := cache.rdb.Get(ctx, metaKey).Bytes() + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, metaKey, "{not-json", 0).Err()) + + accounts, hit, err := cache.GetSnapshot(ctx, bucket) + require.Error(t, err) + require.False(t, hit) + require.Nil(t, accounts) + require.Zero(t, memoEntryCount(cache)) + + require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err()) + require.Equal(t, "a", memoRead(t, cache, bucket)[0].Name) +} + +func TestSchedulerCacheSnapshotMemoRedisErrorIsReturned(t *testing.T) { + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(113) + memoPublish(t, cache, bucket, memoTestAccount(111, "a")) + memoRead(t, cache, bucket) + + mr.SetError("injected failure") + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.Error(t, err) + require.False(t, hit) + require.Nil(t, accounts) + + mr.SetError("") + require.Equal(t, []int64{111}, memoIDs(memoRead(t, cache, bucket))) +} + +func TestSchedulerCacheSnapshotMemoConcurrentReadersAndWriters(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(114) + accounts := []service.Account{memoTestAccount(121, "a"), memoTestAccount(122, "b"), memoTestAccount(123, "c")} + memoPublish(t, cache, bucket, accounts...) + + var wg sync.WaitGroup + for reader := 0; reader < 8; reader++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 40; i++ { + got, hit, err := cache.GetSnapshot(ctx, bucket) + if err != nil || !hit { + t.Errorf("GetSnapshot: hit=%v err=%v", hit, err) + return + } + for _, account := range got { + if account.GetModelMapping()["claude-sonnet"] == "" { + t.Errorf("account %d lost its model mapping", account.ID) + return + } + _ = account.IsSchedulableForModel("claude-sonnet") + _ = account.GetHeaderOverrides() + account.Schedulable = !account.Schedulable + account.LastUsedAt = nil + } + } + }() + } + for writer := 0; writer < 2; writer++ { + wg.Add(1) + go func(writer int) { + defer wg.Done() + for i := 0; i < 20; i++ { + account := memoTestAccount(int64(121+writer), fmt.Sprintf("w%d-%d", writer, i)) + account.Extra = map[string]any{"session_window_utilization": float64(i) / 100} + if err := cache.SetAccount(ctx, &account); err != nil { + t.Errorf("SetAccount: %v", err) + return + } + if err := cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: time.Now()}); err != nil { + t.Errorf("UpdateLastUsed: %v", err) + return + } + } + }(writer) + } + wg.Wait() + + got := memoRead(t, cache, bucket) + require.Equal(t, "w0-19", got[0].Name) + require.Equal(t, "w1-19", got[1].Name) + require.Equal(t, "c", got[2].Name) +} + +func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T) { + ctx := context.Background() + geminiRevisionKey := schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini) + + t.Run("revisions share the last chunk", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + accounts := []service.Account{ + memoTestAccount(131, "a"), + memoTestAccountOn(service.PlatformGemini, 132, "b"), + memoTestAccount(133, "c"), + } + recorder.reset() + ids, err := cache.writeAccountIDs(ctx, accounts) + require.NoError(t, err) + require.Equal(t, []int64{131, 132, 133}, ids) + + batches := recorder.pipelineBatches() + require.Len(t, batches, 2, "one execution per chunk") + require.Equal(t, []string{ + "set " + schedulerAccountKey("133"), + "set " + schedulerAccountMetaKey("133"), + "set " + memoAnthropicRevisionKey, + "set " + geminiRevisionKey, + }, batches[1]) + require.NotContains(t, strings.Join(batches[0], "\n"), schedulerAccountMetaRevisionKey) + require.Equal(t, 2, recorder.countPrefix("set "+schedulerAccountMetaRevisionKey), "no revision write outside the last chunk") + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + first := memoRevision(t, cache, memoAnthropicRevisionKey) + require.Len(t, first, schedulerAccountMetaRevisionBytes*2) + require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2) + + _, err = cache.writeAccountIDs(ctx, accounts[:1]) + require.NoError(t, err) + require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("account count is a multiple of the chunk size", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + accounts := []service.Account{ + memoTestAccount(141, "a"), memoTestAccount(142, "b"), + memoTestAccount(143, "c"), memoTestAccount(144, "d"), + } + recorder.reset() + _, err := cache.writeAccountIDs(ctx, accounts) + require.NoError(t, err) + + batches := recorder.pipelineBatches() + require.Len(t, batches, 2, "no extra execution for the revision") + require.Equal(t, []string{ + "set " + schedulerAccountKey("143"), + "set " + schedulerAccountMetaKey("143"), + "set " + schedulerAccountKey("144"), + "set " + schedulerAccountMetaKey("144"), + "set " + memoAnthropicRevisionKey, + }, batches[1]) + require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines") + }) + + t.Run("failure in a later chunk advances the global revision", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 1) + accounts := []service.Account{memoTestAccount(151, "a"), memoTestAccount(152, "b"), memoTestAccount(153, "c")} + bucket := memoTestBucket(115) + memoPublish(t, cache, bucket, accounts...) + memoRead(t, cache, bucket) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + + renamed := []service.Account{memoTestAccount(151, "a2"), memoTestAccount(152, "b2"), memoTestAccount(153, "c2")} + recorder.reset() + recorder.setFailPipelineAt(2) + _, err := cache.writeAccountIDs(ctx, renamed) + require.Error(t, err) + recorder.setFailPipelineAt(0) + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != globalBefore + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + + recorder.reset() + got := memoRead(t, cache, bucket) + require.Equal(t, 1, recorder.countPrefix("zrange "), "the cached snapshot must be reloaded") + require.Equal(t, []string{"a2", "b", "c"}, []string{got[0].Name, got[1].Name, got[2].Name}) + }) + + t.Run("failure in the last chunk advances the global revision", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + recorder.reset() + recorder.setFailPipelineAt(1) + _, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(161, "a")}) + require.Error(t, err) + recorder.setFailPipelineAt(0) + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") + require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("nothing encodable", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 1) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + recorder.reset() + ids, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 171, Platform: service.PlatformAnthropic, ExpiresAt: &invalid}}) + require.NoError(t, err) + require.Empty(t, ids) + require.Empty(t, recorder.recorded()) + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("empty platform uses the global revision", func(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, 2) + _, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 181, Name: "no-platform"}}) + require.NoError(t, err) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + }) +} + +// memoReadExpectHit 读取一次并报告是否重新加载(发出过 ZRANGE)。 +func memoReadExpectHit(t *testing.T, cache *schedulerCache, recorder *schedulerCacheCommandRecorder, bucket service.SchedulerBucket) ([]*service.Account, bool) { + t.Helper() + recorder.reset() + accounts := memoRead(t, cache, bucket) + return accounts, recorder.countPrefix("zrange ") > 0 +} + +func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + geminiSingle := service.SchedulerBucket{GroupID: 201, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + gemini := memoTestAccountOn(service.PlatformGemini, 211, "gemini") + memoPublish(t, cache, geminiSingle, gemini) + _, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded) + + anthropic := memoTestAccount(212, "anthropic") + require.NoError(t, cache.SetAccount(ctx, &anthropic)) + recorder.reset() + memoRead(t, cache, geminiSingle) + require.Equal(t, []string{ + "mget " + schedulerBucketKey(schedulerReadyPrefix, geminiSingle), + "mget " + schedulerLastUsedKey("211"), + }, recorder.recorded(), "an Anthropic account write must not invalidate a Gemini bucket") + + gemini.Name = "gemini-renamed" + require.NoError(t, cache.SetAccount(ctx, &gemini)) + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded) + require.Equal(t, "gemini-renamed", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoPlatformChangeInvalidatesOldPlatformBuckets(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + moved := memoTestAccountOn(service.PlatformGemini, 221, "moved") + memoPublish(t, cache, geminiSingle, moved) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + + moved.Name = "same-platform" + require.NoError(t, cache.SetAccount(ctx, &moved)) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a same-platform rewrite only advances its platform revision") + memoRead(t, cache, geminiSingle) + + moved.Platform = service.PlatformAnthropic + moved.Name = "now-anthropic" + require.NoError(t, cache.SetAccount(ctx, &moved)) + require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a platform change advances the global revision") + + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded, "the old platform bucket must drop the cached account") + require.Equal(t, service.PlatformAnthropic, got[0].Platform) + require.Equal(t, "now-anthropic", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoNewAccountOnlyAdvancesPlatformRevision(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + fresh := memoTestAccountOn(service.PlatformGemini, 231, "fresh") + require.NoError(t, cache.SetAccount(context.Background(), &fresh)) + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini))) +} + +func TestSchedulerCacheSnapshotMemoAntigravityRevisionInvalidatesMixedBuckets(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + antigravity := memoTestAccountOn(service.PlatformAntigravity, 221, "ag") + antigravity.Extra = map[string]any{"mixed_scheduling": true} + gemini := memoTestAccountOn(service.PlatformGemini, 222, "gemini") + anthropic := memoTestAccount(223, "anthropic") + + geminiMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeMixed} + anthropicMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeMixed} + geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + geminiForced := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeForced} + memoPublish(t, cache, geminiMixed, gemini, antigravity) + memoPublish(t, cache, anthropicMixed, anthropic, antigravity) + memoPublish(t, cache, geminiSingle, gemini) + memoPublish(t, cache, geminiForced, gemini) + for _, bucket := range []service.SchedulerBucket{geminiMixed, anthropicMixed, geminiSingle, geminiForced} { + memoRead(t, cache, bucket) + } + + antigravity.Name = "ag-renamed" + require.NoError(t, cache.SetAccount(ctx, &antigravity)) + + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiMixed) + require.True(t, reloaded) + require.Equal(t, "ag-renamed", got[1].Name) + got, reloaded = memoReadExpectHit(t, cache, recorder, anthropicMixed) + require.True(t, reloaded) + require.Equal(t, "ag-renamed", got[1].Name) + _, reloaded = memoReadExpectHit(t, cache, recorder, geminiSingle) + require.False(t, reloaded, "single buckets never contain Antigravity accounts") + _, reloaded = memoReadExpectHit(t, cache, recorder, geminiForced) + require.False(t, reloaded, "forced buckets never contain Antigravity accounts") +} + +func TestSchedulerCacheSnapshotMemoGlobalRevisionInvalidatesEveryPlatform(t *testing.T) { + ctx := context.Background() + buckets := []service.SchedulerBucket{ + {GroupID: 203, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}, + {GroupID: 203, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle}, + {GroupID: 203, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle}, + } + setup := func(t *testing.T) (*schedulerCache, *schedulerCacheCommandRecorder) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + for i, bucket := range buckets { + memoPublish(t, cache, bucket, memoTestAccountOn(bucket.Platform, int64(231+i), bucket.Platform)) + memoRead(t, cache, bucket) + } + // 不属于任何上述 bucket 的账号。 + unrelated := memoTestAccountOn(service.PlatformGrok, 239, "grok") + require.NoError(t, cache.SetAccount(ctx, &unrelated)) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.False(t, reloaded) + } + return cache, recorder + } + + t.Run("DeleteAccount", func(t *testing.T) { + cache, recorder := setup(t) + require.NoError(t, cache.DeleteAccount(ctx, 239)) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.True(t, reloaded, bucket.String()) + } + }) + + t.Run("UpdateLastUsed unencodable deletion", func(t *testing.T) { + cache, recorder := setup(t) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{239: invalid})) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.True(t, reloaded, bucket.String()) + } + }) +} + +func TestSchedulerCacheSnapshotMemoFlushAllAndRepublishSameVersion(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(116) + memoPublish(t, cache, bucket, memoTestAccount(141, "before")) + require.Equal(t, "before", memoRead(t, cache, bucket)[0].Name) + activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + + mr.FlushAll() + memoPublish(t, cache, bucket, memoTestAccount(141, "after")) + require.Equal(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()) + require.Equal(t, "after", memoRead(t, cache, bucket)[0].Name) +} + +type memoTestClock struct { + mu sync.Mutex + now time.Time +} + +func (c *memoTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *memoTestClock) Advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() +} + +func TestSchedulerCacheSnapshotMemoMaxAgeBoundsUnversionedWrites(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(117) + memoPublish(t, cache, bucket, memoTestAccount(151, "old")) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + // 模拟不推进修订号的旧实例:直接改写精简记录。 + _, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(151, "new")) + require.NoError(t, err) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("151"), metaPayload, 0).Err()) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + + clock.Advance(schedulerSnapshotCacheMaxAge - time.Millisecond) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + clock.Advance(time.Millisecond) + require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name) +} + +func TestSchedulerCacheSnapshotMemoEvictsLongIdleEntries(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + idle := memoTestBucket(118) + recent := memoTestBucket(119) + active := memoTestBucket(120) + memoPublish(t, cache, idle, memoTestAccount(161, "idle")) + memoPublish(t, cache, recent, memoTestAccount(162, "recent")) + memoPublish(t, cache, active, memoTestAccount(163, "active")) + + memoRead(t, cache, idle) + clock.Advance(schedulerSnapshotCacheEvictAge / 2) + memoRead(t, cache, recent) + clock.Advance(schedulerSnapshotCacheEvictAge/2 + time.Second) + memoRead(t, cache, active) + + cache.snapshotMu.RLock() + defer cache.snapshotMu.RUnlock() + require.NotContains(t, cache.snapshotEntries, idle.String()) + require.Contains(t, cache.snapshotEntries, recent.String()) + require.Contains(t, cache.snapshotEntries, active.String()) +} + +func TestSchedulerCacheSnapshotMemoKeepsNewerEntryOnLateStore(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + base := time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC) + newer := &schedulerSnapshotEntry{active: "2", revisions: []string{"r2"}, loadedAt: base.Add(time.Second)} + older := &schedulerSnapshotEntry{active: "1", revisions: []string{"r1"}, loadedAt: base} + cache.storeSnapshotEntry("b", newer) + cache.storeSnapshotEntry("b", older) + require.Same(t, newer, cache.lookupSnapshotEntry("b")) +} + +// 母本在发布前预解析了模型映射:副本命中时不计算签名。此处故意原地改写共享的原始映射, +// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。 +func TestSchedulerCacheSnapshotMemoPreparesSharedModelMapping(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(121) + memoPublish(t, cache, bucket, memoTestAccount(171, "a")) + memoRead(t, cache, bucket) + + hit := memoRead(t, cache, bucket)[0] + require.Equal(t, "sonnet-a", hit.GetMappedModel("claude-sonnet")) + + replaced := memoRead(t, cache, bucket)[0] + replaced.Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-replaced"}} + require.Equal(t, "sonnet-replaced", replaced.GetMappedModel("claude-sonnet")) + + probe := memoRead(t, cache, bucket)[0] + rawMapping, ok := probe.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + rawMapping["claude-sonnet"] = "sonnet-mutated-in-place" + require.Equal(t, "sonnet-a", probe.GetMappedModel("claude-sonnet")) +} + +func TestSchedulerCacheSnapshotMemoRevisionValuesAreUnique(t *testing.T) { + seen := make(map[string]struct{}, 64) + for i := 0; i < 64; i++ { + revision := newSchedulerAccountMetaRevision() + require.Len(t, revision, schedulerAccountMetaRevisionBytes*2) + _, err := strconv.ParseUint(revision[:8], 16, 32) + require.NoError(t, err) + _, dup := seen[revision] + require.False(t, dup) + seen[revision] = struct{}{} + } +} + +func TestSchedulerCacheSnapshotMemoPlatformChangeInEarlierChunk(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, 1) + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccountOn(service.PlatformGemini, 241, "moved")))) + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(242, "stays")))) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + + _, err := cache.writeAccountIDs(ctx, []service.Account{ + memoTestAccount(241, "moved"), + memoTestAccount(242, "stays"), + }) + require.NoError(t, err) + require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoUnparsableOldMetadataAdvancesGlobalRevision(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + require.NoError(t, mr.Set(schedulerAccountMetaKey("251"), "not-json")) + + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(251, "replaced")))) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + mr.HSet(schedulerAccountMetaKey("262"), "field", "value") + + _, err := cache.writeAccountIDs(ctx, []service.Account{ + memoTestAccount(261, "fresh"), + memoTestAccount(262, "wrong-type"), + }) + require.Error(t, err, "a WRONGTYPE reply after a nil SET ... GET reply must fail the write") + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") +} + +func TestSchedulerCacheSnapshotMemoCoalescesBackgroundGlobalRevisionWrites(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + recorder.reset() + for range 50 { + cache.scheduleGlobalAccountMetaRevision(context.Background()) + } + require.Eventually(t, func() bool { + return !cache.globalRevisionWriting.Load() && memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond) + writes := 0 + for _, command := range recorder.recorded() { + if command == "set "+schedulerAccountMetaRevisionKey { + writes++ + } + } + require.GreaterOrEqual(t, writes, 1) + require.LessOrEqual(t, writes, 3, "concurrent schedules collapse into at most a couple of background writes") +} + +func ptrAccount(account service.Account) *service.Account { + return &account +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index d09d4c2b8d..8899c2d70d 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -75,6 +75,9 @@ type Account struct { modelMappingCacheRawLen int modelMappingCacheRawSig uint64 modelMappingCacheRuntimeVersion uint64 + // modelMappingCacheShared 为 true 时缓存来自只读共享母本(见 PrepareSharedSnapshot), + // 指针、长度与运行时版本匹配即直接复用预解析结果,不计算签名。 + modelMappingCacheShared bool // header_overrides 热路径缓存(非持久化字段,同 model_mapping 缓存先例) headerOverrideCache map[string]string @@ -634,6 +637,9 @@ func (a *Account) GetModelMapping() map[string]string { a.modelMappingCacheRawPtr == rawPtr && a.modelMappingCacheRawLen == rawLen && a.modelMappingCacheRuntimeVersion == runtimeVersion { + if a.modelMappingCacheShared { + return a.modelMappingCache + } rawSig = modelMappingSignature(rawMapping) rawSigReady = true if a.modelMappingCacheRawSig == rawSig { @@ -653,9 +659,24 @@ func (a *Account) GetModelMapping() map[string]string { a.modelMappingCacheRawLen = rawLen a.modelMappingCacheRawSig = rawSig a.modelMappingCacheRuntimeVersion = runtimeVersion + a.modelMappingCacheShared = false return mapping } +// PrepareSharedSnapshot 预解析模型映射,并把账号标记为只读共享母本。 +// 母本按值复制出的副本与母本共用 Credentials 及其中 model_mapping 的同一 map: +// 这些内层 map 在运行期不被原地修改,母本留在缓存期间持有这些 map,其地址不会被复用, +// 因此副本在指针、长度与运行时版本都匹配时直接复用预解析结果,不计算签名; +// 副本替换 Credentials 等导致任一项不匹配时回到普通的重建路径。 +// 只能由构造该账号的 goroutine 在其发布给其它 goroutine 之前调用,发布后母本不得再被修改。 +func (a *Account) PrepareSharedSnapshot() { + if a == nil { + return + } + a.GetModelMapping() + a.modelMappingCacheShared = true +} + func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]string { if a.Credentials == nil { // Antigravity 平台使用默认映射 diff --git a/backend/internal/service/account_shared_snapshot_test.go b/backend/internal/service/account_shared_snapshot_test.go new file mode 100644 index 0000000000..2d3421193d --- /dev/null +++ b/backend/internal/service/account_shared_snapshot_test.go @@ -0,0 +1,82 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// 共享母本的副本命中预解析缓存时不计算签名:此处故意原地改写共享的原始映射, +// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。 +func TestAccountPrepareSharedSnapshot_CopiesReusePreparedMappingWithoutSignature(t *testing.T) { + rawMapping := map[string]any{"claude-sonnet": "sonnet-a"} + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": rawMapping}, + } + master.PrepareSharedSnapshot() + + replica := *master + require.Equal(t, map[string]string{"claude-sonnet": "sonnet-a"}, replica.GetModelMapping()) + + rawMapping["claude-sonnet"] = "sonnet-b" + require.Equal(t, "sonnet-a", replica.GetModelMapping()["claude-sonnet"], + "the shared fast path must not recompute the signature") + require.Equal(t, "sonnet-a", replica.GetMappedModel("claude-sonnet")) + + // 未标记为共享的账号仍按签名检出原地改写。 + plainRaw := map[string]any{"claude-sonnet": "sonnet-a"} + plain := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": plainRaw}, + } + require.Equal(t, "sonnet-a", plain.GetModelMapping()["claude-sonnet"]) + plainRaw["claude-sonnet"] = "sonnet-b" + require.Equal(t, "sonnet-b", plain.GetModelMapping()["claude-sonnet"]) +} + +func TestAccountPrepareSharedSnapshot_ReplacedCredentialsFallBackToSignaturePath(t *testing.T) { + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-a"}}, + } + master.PrepareSharedSnapshot() + + replica := *master + replacedRaw := map[string]any{"claude-sonnet": "sonnet-b"} + replica.Credentials = map[string]any{"model_mapping": replacedRaw} + require.Equal(t, "sonnet-b", replica.GetModelMapping()["claude-sonnet"]) + + // 重建后副本回到普通路径:同一 map 的原地改写由签名检出。 + replacedRaw["claude-sonnet"] = "sonnet-c" + require.Equal(t, "sonnet-c", replica.GetModelMapping()["claude-sonnet"]) + + // 母本不受副本重建影响。 + require.Equal(t, "sonnet-a", master.GetModelMapping()["claude-sonnet"]) +} + +func TestAccountPrepareSharedSnapshot_MappingLengthChangeRebuilds(t *testing.T) { + rawMapping := map[string]any{"claude-sonnet": "sonnet-a"} + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": rawMapping}, + } + master.PrepareSharedSnapshot() + + replica := *master + rawMapping["claude-opus"] = "opus-a" + require.Equal(t, "opus-a", replica.GetModelMapping()["claude-opus"]) +} + +func TestAccountPrepareSharedSnapshot_NilAccountAndNoMapping(t *testing.T) { + var nilAccount *Account + require.NotPanics(t, nilAccount.PrepareSharedSnapshot) + + master := &Account{Platform: PlatformAnthropic} + master.PrepareSharedSnapshot() + replica := *master + require.Nil(t, replica.GetModelMapping()) + require.Equal(t, "claude-sonnet", replica.GetMappedModel("claude-sonnet")) +} diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index a75fa62094..46e3419e03 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -2,6 +2,7 @@ package service import ( "context" + "maps" "strings" "time" @@ -209,18 +210,13 @@ func (a *Account) modelRateLimitReason(scope string) string { return reason } +// setAccountModelRateLimitSnapshot 把模型级限流写进本账号对象的 Extra 快照。 +// 写时复制:Extra 与其中的 model_rate_limits 可能与调度快照母本及其它副本共享, +// 这里只读取旧 map,写入新复制的 map 后替换 account.Extra,不修改任何已有 map。 func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) { if account == nil || strings.TrimSpace(scope) == "" { return } - if account.Extra == nil { - account.Extra = make(map[string]any) - } - limits, ok := account.Extra[modelRateLimitsKey].(map[string]any) - if !ok { - limits = make(map[string]any) - account.Extra[modelRateLimitsKey] = limits - } payload := map[string]any{ "rate_limited_at": now.UTC().Format(time.RFC3339), "rate_limit_reset_at": resetAt.UTC().Format(time.RFC3339), @@ -228,5 +224,14 @@ func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt ti if reason = strings.TrimSpace(reason); reason != "" { payload["reason"] = reason } + + oldLimits, _ := account.Extra[modelRateLimitsKey].(map[string]any) + limits := make(map[string]any, len(oldLimits)+1) + maps.Copy(limits, oldLimits) limits[scope] = payload + + extra := make(map[string]any, len(account.Extra)+1) + maps.Copy(extra, account.Extra) + extra[modelRateLimitsKey] = limits + account.Extra = extra } diff --git a/backend/internal/service/model_rate_limit_snapshot_cow_test.go b/backend/internal/service/model_rate_limit_snapshot_cow_test.go new file mode 100644 index 0000000000..a73fcff5fe --- /dev/null +++ b/backend/internal/service/model_rate_limit_snapshot_cow_test.go @@ -0,0 +1,209 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSetAccountModelRateLimitSnapshot_CopyOnWrite(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + existingLimit := map[string]any{ + "rate_limited_at": now.Format(time.RFC3339), + "rate_limit_reset_at": now.Add(time.Hour).Format(time.RFC3339), + } + limits := map[string]any{"claude-opus-5": existingLimit} + extra := map[string]any{ + modelRateLimitsKey: limits, + "session_window_utilization": 0.5, + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Extra: extra} + before := *account + + setAccountModelRateLimitSnapshot(account, anthropicFableRateLimitKey, now.Add(2*time.Hour), " threshold ", now) + + // 调用前的 Extra 与嵌套 limits 原样保留。 + require.Len(t, extra, 2) + require.Equal(t, 0.5, extra["session_window_utilization"]) + require.Len(t, limits, 1) + require.Equal(t, existingLimit, limits["claude-opus-5"]) + require.NotContains(t, limits, anthropicFableRateLimitKey) + require.False(t, before.isModelRateLimitedWithContext(ctx, "claude-fable-5")) + + // 新 Extra 同时带有旧条目与新限流,本请求后续读取结果与原地写入一致。 + require.Equal(t, 0.5, account.Extra["session_window_utilization"]) + newLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any) + require.True(t, ok) + require.Len(t, newLimits, 2) + require.Equal(t, existingLimit, newLimits["claude-opus-5"]) + require.Equal(t, map[string]any{ + "rate_limited_at": now.Format(time.RFC3339), + "rate_limit_reset_at": now.Add(2 * time.Hour).Format(time.RFC3339), + "reason": "threshold", + }, newLimits[anthropicFableRateLimitKey]) + require.Equal(t, "threshold", account.modelRateLimitReason(anthropicFableRateLimitKey)) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5")) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.False(t, account.isModelRateLimitedWithContext(ctx, "claude-sonnet-5")) +} + +func TestSetAccountModelRateLimitSnapshot_InitializesMissingOrInvalidLimits(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + empty := &Account{Platform: PlatformAnthropic} + setAccountModelRateLimitSnapshot(empty, "claude-opus-5", now.Add(time.Hour), "", now) + require.True(t, empty.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.Empty(t, empty.modelRateLimitReason("claude-opus-5")) + + invalidExtra := map[string]any{modelRateLimitsKey: "corrupted", "keep": true} + invalid := &Account{Platform: PlatformAnthropic, Extra: invalidExtra} + setAccountModelRateLimitSnapshot(invalid, "claude-opus-5", now.Add(time.Hour), "r", now) + require.True(t, invalid.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.Equal(t, true, invalid.Extra["keep"]) + require.Equal(t, "corrupted", invalidExtra[modelRateLimitsKey]) + + unchanged := &Account{Platform: PlatformAnthropic, Extra: map[string]any{"k": 1}} + setAccountModelRateLimitSnapshot(unchanged, " ", now.Add(time.Hour), "r", now) + require.Equal(t, map[string]any{"k": 1}, unchanged.Extra) +} + +// 同一母本的浅拷贝并发写各自的限流快照:-race 下不得出现竞争,母本与其它副本都看不到这些写入。 +func TestSetAccountModelRateLimitSnapshot_ConcurrentCopiesOfSharedMaster(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + master := &Account{ + ID: 7, + Platform: PlatformAnthropic, + Extra: map[string]any{ + modelRateLimitsKey: map[string]any{ + "claude-opus-5": map[string]any{"rate_limit_reset_at": now.Add(time.Hour).Format(time.RFC3339)}, + }, + "session_window_utilization": 0.2, + }, + } + master.PrepareSharedSnapshot() + + const workers = 16 + var wg sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wg.Add(1) + go func(worker int) { + defer wg.Done() + own := fmt.Sprintf("model-%d", worker) + other := fmt.Sprintf("model-%d", (worker+1)%workers) + for i := 0; i < 50; i++ { + replica := *master + setAccountModelRateLimitSnapshot(&replica, own, now.Add(time.Hour), "r", now) + if !replica.isModelRateLimitedWithContext(ctx, own) { + t.Errorf("worker %d: own limit missing", worker) + return + } + if !replica.isModelRateLimitedWithContext(ctx, "claude-opus-5") { + t.Errorf("worker %d: inherited limit missing", worker) + return + } + if replica.isModelRateLimitedWithContext(ctx, other) { + t.Errorf("worker %d: saw another replica's limit", worker) + return + } + probe := *master + if probe.isModelRateLimitedWithContext(ctx, own) { + t.Errorf("worker %d: master was mutated", worker) + return + } + } + }(worker) + } + wg.Wait() + + limits, ok := master.Extra[modelRateLimitsKey].(map[string]any) + require.True(t, ok) + require.Len(t, limits, 1) + require.Len(t, master.Extra, 2) +} + +type sharedSnapshotFableRepoStub struct { + AccountRepository + modelCalls atomic.Int64 +} + +func (r *sharedSnapshotFableRepoStub) SetModelRateLimit(_ context.Context, _ int64, _ string, _ time.Time, _ ...string) error { + r.modelCalls.Add(1) + return nil +} + +// Fable 阈值在选号阶段写入候选对象:同一母本的其它副本(包括并发读取的副本)与母本本身都不得出现该限流。 +func TestApplyAccountSchedulingThreshold_FableLimitStaysOnOwnSnapshotCopy(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + t.Cleanup(func() { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + }) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"anthropic":100}` + repo := &sharedSnapshotFableRepoStub{} + limiter := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + limiter.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + now := time.Now().UTC() + master := &Account{ + ID: 1006, + Platform: PlatformAnthropic, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"account_scheduling_threshold": 60}, + Extra: map[string]any{ + "passive_usage_7d_utilization": 0.40, + "passive_usage_7d_reset": float64(now.Add(3 * 24 * time.Hour).Unix()), + "passive_usage_7d_oi_utilization": 0.61, + "passive_usage_7d_oi_reset": float64(now.Add(4 * 24 * time.Hour).Unix()), + }, + } + master.PrepareSharedSnapshot() + + const pairs = 8 + var wg sync.WaitGroup + for i := 0; i < pairs; i++ { + wg.Add(2) + go func() { + defer wg.Done() + candidate := *master + if limiter.ApplyAccountSchedulingThreshold(context.Background(), &candidate) { + t.Error("the Fable-only window must not pause the whole account") + } + if candidate.IsSchedulableForModel("claude-fable-5") { + t.Error("the candidate that crossed the threshold must stop scheduling Fable") + } + if !candidate.IsSchedulableForModel("claude-opus-5") { + t.Error("non-Fable models must stay schedulable") + } + }() + go func() { + defer wg.Done() + for j := 0; j < 20; j++ { + reader := *master + if !reader.IsSchedulableForModel("claude-fable-5") { + t.Error("a sibling copy must not see the Fable limit") + return + } + } + }() + } + wg.Wait() + + require.Equal(t, int64(pairs), repo.modelCalls.Load()) + require.NotContains(t, master.Extra, modelRateLimitsKey) + require.True(t, master.IsSchedulableForModel("claude-fable-5")) +} diff --git a/backend/internal/service/scheduler_cache.go b/backend/internal/service/scheduler_cache.go index d507d6ce2a..5e5dbed164 100644 --- a/backend/internal/service/scheduler_cache.go +++ b/backend/internal/service/scheduler_cache.go @@ -76,6 +76,8 @@ func ParseSchedulerBucket(raw string) (SchedulerBucket, bool) { // SchedulerCache 负责调度快照与账号快照的缓存读写。 type SchedulerCache interface { // GetSnapshot 读取快照并返回命中与否(ready + active + 数据完整)。 + // 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值 + // 与其它调用共享,不得原地修改。 GetSnapshot(ctx context.Context, bucket SchedulerBucket) ([]*Account, bool, error) // CaptureBucketWriteToken captures the current open epoch without changing // retirement state. A tombstoned bucket returns ErrSchedulerBucketRetired.