perf(scheduler): skip rewriting unchanged accounts in scheduler cache

Root cause: writeAccountIDs unconditionally SET every account payload and
metadata record on each scheduler refresh. After 0.2.26 stopped embedding
expanded group objects the payload is smaller, but refreshes driven by
snapshots or account updates still rewrote all keys even when their content
was identical, amplifying AOF and replication traffic when several instances
share one Redis.

Change: read the previous full and metadata payloads with one chunked MGET
per write chunk and compare bytes before writing. Only payloads that changed
are SET; unchanged accounts are still returned in the account ID list so
bucket membership is unchanged. Platform revisions advance only when a
payload was actually written and stay in the last writing chunk, after all
metadata writes. The fallback path used when the read fails keeps the
original unconditional write and SET ... GET platform-change detection
(fail-open). Redis remains the source of truth; no in-process caching is
added.

Tests: new unit tests cover repeated identical writes issuing no SET and no
revision, changed payloads being rewritten, per-chunk skipping, platform
changes still advancing the global revision, and the MGET-failure fallback.
Existing scheduler cache revision tests were updated for the read-first write
layout. Validated with go build ./..., go test -tags=unit
./internal/repository/, and gofmt.
This commit is contained in:
debug-zhang committed 2026-12-01 23:02:02 +08:00
1 parent f53641e53c
commit c15bfc71cf
3 files changed
+420 -66

No files matched your search

+200 -63
View File
@@ -1196,11 +1196,39 @@ func decodeCachedAccountPayload(payload string) (*service.Account, error) {
return &account, nil
}
// schedulerAccountCacheWrite 是一个已编码、待写入的账号载荷。
type schedulerAccountCacheWrite struct {
keyID string
platform string
fullPayload []byte
metaPayload []byte
}
// schedulerCachedAccountPayload 是写前从 Redis 读回的旧载荷;present 为 false 表示键不存在。
type schedulerCachedAccountPayload struct {
full string
fullPresent bool
meta string
metaPresent bool
}
// schedulerAccountCacheChange 描述一个账号相对 Redis 中旧载荷的变化。
// platformChanged 仅在读到旧精简记录且平台不一致时为 true,用于保留旧平台 bucket 的失效语义。
type schedulerAccountCacheChange struct {
fullChanged bool
metaChanged bool
platformChanged bool
}
// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。
// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾,
// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。
// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,
// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
// 写入前按块读回旧载荷(完整记录与精简记录同批 MGET),只写入发生变化的账号:
// 调度刷新反复写入相同内容时不再产生整键 SET,避免 AOF/复制放大。
// 未变化的账号仍返回其 ID,调用方需要的成员列表不因此改变。
// 所涉平台的修订号追加在最后一个有写入的块末尾,与最后一批精简记录同一次往返发出,
// 且排在全部精简记录写入之后;全部未变化时不写修订号,读侧进程内缓存继续复用。
// 读取失败时降级为原全量写(fail-open),此时用 SET ... GET 取回旧值:
// 旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,全部写入完成后另行写入全局修订号。
// 该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
// 漏检由进程内快照缓存的直接复用时长与宽限期兜底。
// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。
func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) {
@@ -1208,46 +1236,13 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
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
execFailed := false
platformChanged := false
defer func() {
if execFailed {
c.scheduleGlobalAccountMetaRevision(ctx)
}
}()
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
chunkSize := c.writeChunkSize
if chunkSize <= 0 {
chunkSize = defaultSchedulerSnapshotWriteChunkSize
}
writes := make([]schedulerAccountCacheWrite, 0, len(accounts))
accountIDs := make([]int64, 0, len(accounts))
for _, account := range accounts {
fullPayload, metaPayload, err := marshalSchedulerCacheAccount(account)
if err != nil {
@@ -1257,35 +1252,94 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
)
continue
}
if pending >= c.writeChunkSize {
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}),
writes = append(writes, schedulerAccountCacheWrite{
keyID: strconv.FormatInt(account.ID, 10),
platform: account.Platform,
fullPayload: fullPayload,
metaPayload: metaPayload,
})
// 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 pending == 0 {
if len(writes) == 0 {
return accountIDs, nil
}
for _, platform := range platforms {
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
changes, unconditional, lastWriteChunk := c.planSchedulerAccountWrites(ctx, writes, chunkSize)
if lastWriteChunk < 0 {
return accountIDs, nil
}
if err := exec(); err != nil {
return nil, err
type metaWrite struct {
platform string
previous *redis.StatusCmd
}
execFailed := false
platformChanged := false
defer func() {
if execFailed {
c.scheduleGlobalAccountMetaRevision(ctx)
}
}()
platforms := make([]string, 0, 2)
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
end := min(start+chunkSize, len(writes))
chunk := writes[start:end]
pipe := c.rdb.Pipeline()
metaWrites := make([]metaWrite, 0, len(chunk))
queued := 0
for offset := range chunk {
change := changes[start+offset]
if !change.fullChanged && !change.metaChanged {
continue
}
write := chunk[offset]
if change.fullChanged {
pipe.Set(ctx, schedulerAccountKey(write.keyID), write.fullPayload, 0)
queued++
}
if change.metaChanged {
if unconditional {
metaWrites = append(metaWrites, metaWrite{
platform: write.platform,
previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, redis.SetArgs{Get: true}),
})
} else {
pipe.Set(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, 0)
platformChanged = platformChanged || change.platformChanged
}
queued++
}
if !slices.Contains(platforms, write.platform) {
platforms = append(platforms, write.platform)
}
}
if queued == 0 {
continue
}
if chunkIndex == lastWriteChunk {
for _, platform := range platforms {
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
}
}
cmds, err := pipe.Exec(ctx)
if err != nil && !errors.Is(err, redis.Nil) {
execFailed = true
return nil, err
}
// SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。
for _, cmd := range cmds {
if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) {
execFailed = true
return nil, cmdErr
}
}
for _, write := range metaWrites {
if schedulerMetaPlatformChanged(write.previous, write.platform) {
platformChanged = true
}
}
}
if platformChanged {
c.advanceGlobalAccountMetaRevision(ctx)
@@ -1293,6 +1347,84 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
return accountIDs, nil
}
// planSchedulerAccountWrites 按块读回旧载荷并标记需要写入的账号,返回最后一个有写入的块序号。
// 读取失败时把剩余块标记为全量写(unconditional),由调用方沿用原写入与平台变化检测路径。
func (c *schedulerCache) planSchedulerAccountWrites(ctx context.Context, writes []schedulerAccountCacheWrite, chunkSize int) ([]schedulerAccountCacheChange, bool, int) {
changes := make([]schedulerAccountCacheChange, len(writes))
unconditional := false
lastWriteChunk := -1
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
end := min(start+chunkSize, len(writes))
chunk := writes[start:end]
var previous []schedulerCachedAccountPayload
if !unconditional {
cached, err := c.readSchedulerAccountPayloads(ctx, chunk)
if err != nil {
// 读失败时不能跳过任何账号,否则缓存可能停留在旧值;降级为原全量写。
slog.Warn("scheduler cache falls back to unconditional account writes", "error", err)
unconditional = true
} else {
previous = cached
}
}
chunkChanged := false
for offset := range chunk {
change := schedulerAccountCacheChange{fullChanged: true, metaChanged: true}
if !unconditional {
cached := previous[offset]
change.fullChanged = !cached.fullPresent || cached.full != string(chunk[offset].fullPayload)
change.metaChanged = !cached.metaPresent || cached.meta != string(chunk[offset].metaPayload)
if change.metaChanged && cached.metaPresent {
change.platformChanged = schedulerMetaPlatformChangedValue(cached.meta, chunk[offset].platform)
}
}
changes[start+offset] = change
if change.fullChanged || change.metaChanged {
chunkChanged = true
}
}
if chunkChanged {
lastWriteChunk = chunkIndex
}
}
return changes, unconditional, lastWriteChunk
}
// readSchedulerAccountPayloads 读回一批账号的完整与精简记录旧值,键顺序与 writes 一致。
func (c *schedulerCache) readSchedulerAccountPayloads(ctx context.Context, writes []schedulerAccountCacheWrite) ([]schedulerCachedAccountPayload, error) {
keys := make([]string, 0, len(writes)*2)
for _, write := range writes {
keys = append(keys, schedulerAccountKey(write.keyID), schedulerAccountMetaKey(write.keyID))
}
values, err := c.mgetChunked(ctx, keys)
if err != nil {
return nil, err
}
if len(values) != len(keys) {
return nil, fmt.Errorf("scheduler cache read %d cached payloads for %d keys", len(values), len(keys))
}
cached := make([]schedulerCachedAccountPayload, len(writes))
for index := range writes {
if raw := values[index*2]; raw != nil {
payload, err := schedulerCachePayload(raw)
if err != nil {
return nil, err
}
cached[index].full = payload
cached[index].fullPresent = true
}
if raw := values[index*2+1]; raw != nil {
payload, err := schedulerCachePayload(raw)
if err != nil {
return nil, err
}
cached[index].meta = payload
cached[index].metaPresent = true
}
}
return cached, nil
}
// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台;
// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。
func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool {
@@ -1300,6 +1432,11 @@ func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bo
if err != nil {
return false
}
return schedulerMetaPlatformChangedValue(raw, platform)
}
// schedulerMetaPlatformChangedValue 是 schedulerMetaPlatformChanged 的载荷版本,供写前读取的旧精简记录复用。
func schedulerMetaPlatformChangedValue(raw string, platform string) bool {
if !gjson.Valid(raw) {
return true
}
@@ -577,9 +577,13 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
require.Len(t, first, schedulerAccountMetaRevisionBytes*2)
require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2)
recorder.reset()
_, err = cache.writeAccountIDs(ctx, accounts[:1])
require.NoError(t, err)
require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey))
require.Equal(t, []string{"mget " + schedulerAccountKey("131")}, recorder.recorded(),
"an unchanged payload is only read back")
require.Equal(t, first, memoRevision(t, cache, memoAnthropicRevisionKey),
"an unchanged payload must not rewrite the account or advance its revision")
})
t.Run("account count is a multiple of the chunk size", func(t *testing.T) {
@@ -601,7 +605,8 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
"set " + schedulerAccountMetaKey("144"),
"set " + memoAnthropicRevisionKey,
}, batches[1])
require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines")
require.Len(t, recorder.recorded(), 11, "one payload read per chunk plus every write inside the two pipelines")
require.Equal(t, 2, recorder.countPrefix("mget "), "each chunk reads its old payloads once")
})
t.Run("failure in a later chunk advances the global revision", func(t *testing.T) {
@@ -1200,12 +1205,14 @@ func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) {
ctx := context.Background()
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
mr.HSet(schedulerAccountMetaKey("262"), "field", "value")
// 让写前读取失败,覆盖降级后的 SET ... GET 错误处理路径。
cache.rdb.AddHook(&schedulerCacheMGetFailHook{})
_, 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.Error(t, err, "a WRONGTYPE reply on the fallback SET ... GET path 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")
@@ -0,0 +1,210 @@
//go:build unit
package repository
import (
"context"
"errors"
"strings"
"sync"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
var errSchedulerCacheInjectedMGet = errors.New("injected scheduler cache mget failure")
// schedulerCacheMGetFailHook 让写前读取失败,用于覆盖 MGET 失败后的降级写入路径。
type schedulerCacheMGetFailHook struct {
mu sync.Mutex
failures int
}
func (h *schedulerCacheMGetFailHook) DialHook(next redis.DialHook) redis.DialHook { return next }
func (h *schedulerCacheMGetFailHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if strings.EqualFold(cmd.Name(), "mget") {
h.recordFailure()
return errSchedulerCacheInjectedMGet
}
return next(ctx, cmd)
}
}
func (h *schedulerCacheMGetFailHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return func(ctx context.Context, cmds []redis.Cmder) error {
for _, cmd := range cmds {
if strings.EqualFold(cmd.Name(), "mget") {
h.recordFailure()
return errSchedulerCacheInjectedMGet
}
}
return next(ctx, cmds)
}
}
func (h *schedulerCacheMGetFailHook) recordFailure() {
h.mu.Lock()
h.failures++
h.mu.Unlock()
}
func (h *schedulerCacheMGetFailHook) failureCount() int {
h.mu.Lock()
defer h.mu.Unlock()
return h.failures
}
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedPayloads(t *testing.T) {
ctx := context.Background()
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
accounts := []service.Account{
memoTestAccount(901, "steady"),
memoTestAccountOn(service.PlatformGemini, 902, "steady-gemini"),
}
ids, err := cache.writeAccountIDs(ctx, accounts)
require.NoError(t, err)
require.Equal(t, []int64{901, 902}, ids)
firstAnthropic := memoRevision(t, cache, memoAnthropicRevisionKey)
firstGemini := memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini))
require.NotEmpty(t, firstAnthropic)
recorder.reset()
ids, err = cache.writeAccountIDs(ctx, accounts)
require.NoError(t, err)
require.Equal(t, []int64{901, 902}, ids, "unchanged accounts are still reported to the caller")
// 记录器只保留命令名与首个参数:一次 MGET 覆盖整块旧载荷。
require.Equal(t, []string{"mget " + schedulerAccountKey("901")}, recorder.recorded(),
"unchanged payloads must not be rewritten")
require.Equal(t, firstAnthropic, memoRevision(t, cache, memoAnthropicRevisionKey),
"a stable payload must not advance its platform revision")
require.Equal(t, firstGemini, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a stable payload must not advance the global revision")
}
func TestSchedulerCacheWriteAccountIDsRewritesChangedPayloads(t *testing.T) {
ctx := context.Background()
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
accounts := []service.Account{
memoTestAccount(911, "steady"),
memoTestAccount(912, "before"),
}
_, err := cache.writeAccountIDs(ctx, accounts)
require.NoError(t, err)
before := memoRevision(t, cache, memoAnthropicRevisionKey)
changed := []service.Account{accounts[0], accounts[1]}
changed[1].Name = "after"
changed[1].Status = service.StatusDisabled
changed[1].GroupIDs = []int64{77}
recorder.reset()
ids, err := cache.writeAccountIDs(ctx, changed)
require.NoError(t, err)
require.Equal(t, []int64{911, 912}, ids)
require.Equal(t, []string{
"mget " + schedulerAccountKey("911"),
"set " + schedulerAccountKey("912"),
"set " + schedulerAccountMetaKey("912"),
"set " + memoAnthropicRevisionKey,
}, recorder.recorded(), "only the changed account is rewritten; the revision shares the write batch")
require.NotEqual(t, before, memoRevision(t, cache, memoAnthropicRevisionKey))
cached, err := cache.GetAccount(ctx, 912)
require.NoError(t, err)
require.NotNil(t, cached)
require.Equal(t, "after", cached.Name)
require.Equal(t, service.StatusDisabled, cached.Status)
require.Equal(t, []int64{77}, cached.GroupIDs)
unchanged, err := cache.GetAccount(ctx, 911)
require.NoError(t, err)
require.NotNil(t, unchanged)
require.Equal(t, "steady", unchanged.Name)
}
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedChunks(t *testing.T) {
ctx := context.Background()
cache, _, recorder := newSchedulerCacheMemoUnit(t, 1)
accounts := []service.Account{
memoTestAccount(921, "a"),
memoTestAccount(922, "b"),
}
_, err := cache.writeAccountIDs(ctx, accounts)
require.NoError(t, err)
changed := []service.Account{accounts[0], accounts[1]}
changed[1].Name = "b2"
recorder.reset()
_, err = cache.writeAccountIDs(ctx, changed)
require.NoError(t, err)
require.Equal(t, []string{
"mget " + schedulerAccountKey("921"),
"mget " + schedulerAccountKey("922"),
"set " + schedulerAccountKey("922"),
"set " + schedulerAccountMetaKey("922"),
"set " + memoAnthropicRevisionKey,
}, recorder.recorded(), "unchanged chunks are read but not rewritten")
}
func TestSchedulerCacheWriteAccountIDsPlatformChangeAdvancesGlobalRevision(t *testing.T) {
ctx := context.Background()
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
moved := memoTestAccountOn(service.PlatformGemini, 931, "moved")
_, err := cache.writeAccountIDs(ctx, []service.Account{moved})
require.NoError(t, err)
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
moved.Platform = service.PlatformAnthropic
moved.Name = "moved-again"
_, err = cache.writeAccountIDs(ctx, []service.Account{moved})
require.NoError(t, err)
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
"a platform change must still advance the global revision")
cached, err := cache.GetAccount(ctx, 931)
require.NoError(t, err)
require.NotNil(t, cached)
require.Equal(t, service.PlatformAnthropic, cached.Platform)
require.Equal(t, "moved-again", cached.Name)
}
func TestSchedulerCacheWriteAccountIDsFallsBackWhenPayloadReadFails(t *testing.T) {
ctx := context.Background()
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
account := memoTestAccount(941, "initial")
_, err := cache.writeAccountIDs(ctx, []service.Account{account})
require.NoError(t, err)
hook := &schedulerCacheMGetFailHook{}
cache.rdb.AddHook(hook)
recorder.reset()
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
require.NoError(t, err, "a payload read failure must not fail the write")
require.Positive(t, hook.failureCount())
require.Equal(t, []string{
"mget " + schedulerAccountKey("941"),
"set " + schedulerAccountKey("941"),
"set " + schedulerAccountMetaKey("941"),
"set " + memoAnthropicRevisionKey,
}, recorder.recorded(), "the fallback reads first, then rewrites the account unconditionally")
account.Platform = service.PlatformGemini
account.Name = "moved"
recorder.reset()
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
require.NoError(t, err)
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
"the fallback SET ... GET path still detects platform changes")
cachedPayload, err := cache.rdb.Get(ctx, schedulerAccountKey("941")).Result()
require.NoError(t, err)
cached, err := decodeCachedAccount(cachedPayload)
require.NoError(t, err)
require.Equal(t, service.PlatformGemini, cached.Platform)
}