diff --git a/backend/internal/service/ratelimit_rollover_weekly_usage_test.go b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go new file mode 100644 index 0000000000..86bb9fa802 --- /dev/null +++ b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "encoding/json" + "maps" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// applyExtraCalls applies UpdateExtra calls the way the JSONB merge does: +// a nil value is stored as JSON null. +func applyExtraCalls(extra map[string]any, calls []ueCall) map[string]any { + merged := maps.Clone(extra) + for _, call := range calls { + maps.Copy(merged, call.Updates) + } + return merged +} + +// A Fable-exhausted account stops receiving Fable requests, so its non-Fable +// responses carry 5h and 7d headers but no 7d_oi. A 5h rollover must keep the +// still-current 7d F reading instead of erasing it until the weekly reset. +func TestUpdateSessionWindow_RolloverKeepsCurrentWeeklyReadings(t *testing.T) { + now := time.Now() + weeklyReset := now.Add(72 * time.Hour).Unix() + expiredEnd := now.Add(-time.Minute) + extra := map[string]any{ + "session_window_utilization": 1.0, + "passive_usage_7d_utilization": 0.7, + "passive_usage_7d_reset": float64(weeklyReset), // as decoded from JSONB + "passive_usage_7d_oi_utilization": 1.0, + "passive_usage_7d_oi_reset": json.Number(strconv.FormatInt(weeklyReset, 10)), + "passive_usage_sampled_at": now.Add(-time.Hour).UTC().Format(time.RFC3339), + } + account := &Account{ID: 7, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, SessionWindowEnd: &expiredEnd, Extra: extra} + + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(now.Add(5*time.Hour).Unix(), 10)) + headers.Set("anthropic-ratelimit-unified-5h-utilization", "0.05") + headers.Set("anthropic-ratelimit-unified-7d-utilization", "0.71") + headers.Set("anthropic-ratelimit-unified-7d-reset", strconv.FormatInt(weeklyReset, 10)) + + repo := &sessionWindowMockRepo{} + newRateLimitServiceForTest(repo).UpdateSessionWindow(context.Background(), account, headers) + + require.Len(t, repo.updateExtraCalls, 2, "rollover clear, then the new sample") + require.Equal(t, map[string]any{"session_window_utilization": nil}, repo.updateExtraCalls[0].Updates) + + merged := applyExtraCalls(extra, repo.updateExtraCalls) + require.Equal(t, 0.05, merged["session_window_utilization"]) + require.Equal(t, 0.71, merged["passive_usage_7d_utilization"]) + require.Equal(t, 1.0, merged["passive_usage_7d_oi_utilization"], "7d F reading must survive a non-Fable rollover") + require.Equal(t, json.Number(strconv.FormatInt(weeklyReset, 10)), merged["passive_usage_7d_oi_reset"]) + require.NotNil(t, merged["passive_usage_sampled_at"]) + + fable := buildPassiveUsageWindow(merged, "passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset") + require.NotNil(t, fable) + require.Equal(t, 100.0, fable.Utilization) +} + +func TestRolloverPassiveUsageClears(t *testing.T) { + now := time.Now() + future := now.Add(24 * time.Hour).Unix() + past := now.Add(-time.Hour).Unix() + weekly := []string{"passive_usage_7d_utilization", "passive_usage_7d_reset"} + fable := []string{"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"} + + for _, tc := range []struct { + name string + extra map[string]any + cleared []string + kept []string + clearSample bool + }{ + { + name: "both current", + extra: map[string]any{"passive_usage_7d_reset": future, "passive_usage_7d_oi_reset": float64(future)}, + kept: append(weekly, fable...), + }, + { + name: "weekly expired, fable current", + extra: map[string]any{"passive_usage_7d_reset": past, "passive_usage_7d_oi_reset": strconv.FormatInt(future, 10)}, + cleared: weekly, + kept: fable, + }, + { + name: "reading without reset is stale", + extra: map[string]any{"passive_usage_7d_utilization": 0.4, "passive_usage_7d_oi_reset": nil}, + cleared: append(weekly, fable...), + clearSample: true, + }, + { + name: "no extra", + cleared: append(weekly, fable...), + clearSample: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + updates := rolloverPassiveUsageClears(tc.extra, now) + require.Contains(t, updates, "session_window_utilization") + require.Nil(t, updates["session_window_utilization"]) + for _, key := range tc.cleared { + value, present := updates[key] + require.True(t, present, key) + require.Nil(t, value, key) + } + for _, key := range tc.kept { + require.NotContains(t, updates, key) + } + if tc.clearSample { + require.Contains(t, updates, "passive_usage_sampled_at") + } else { + require.NotContains(t, updates, "passive_usage_sampled_at") + } + }) + } +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index e0ec3476fe..c2d6a1d407 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2109,16 +2109,10 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc slog.Info("account_session_window_initialized", "account_id", account.ID, "window_start", start, "window_end", end, "status", status) } - // 窗口重置时清除旧的 utilization 和被动采样数据,避免残留上个窗口的数据 + // 5h 窗口重置时清除上个 5h 窗口的 utilization。周窗口有自己的重置时间, + // 只清除已经过期的周读数(见 rolloverPassiveUsageClears)。 if windowEnd != nil && needInitWindow { - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ - "session_window_utilization": nil, - "passive_usage_7d_utilization": nil, - "passive_usage_7d_reset": nil, - "passive_usage_7d_oi_utilization": nil, - "passive_usage_7d_oi_reset": nil, - "passive_usage_sampled_at": nil, - }) + _ = s.accountRepo.UpdateExtra(ctx, account.ID, rolloverPassiveUsageClears(account.Extra, time.Now())) } if err := s.accountRepo.UpdateSessionWindow(ctx, account.ID, windowStart, windowEnd, status); err != nil { @@ -2136,6 +2130,36 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc } } +// passiveWeeklyUsageWindows lists the sampled weekly windows as utilization/reset Extra keys. +var passiveWeeklyUsageWindows = [...][2]string{ + {"passive_usage_7d_utilization", "passive_usage_7d_reset"}, + {"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"}, +} + +// rolloverPassiveUsageClears returns the Extra updates for a 5h window rollover. +// The 5h utilization always belongs to the previous window. A weekly reading +// is kept while its own reset is still ahead: only Fable responses carry 7d_oi, +// so a Fable-exhausted account that no longer receives Fable traffic would +// otherwise lose its 7d F reading at every rollover until the weekly reset. +// Readings with no reset, or a reset that has passed, are stale and cleared. +func rolloverPassiveUsageClears(extra map[string]any, now time.Time) map[string]any { + updates := map[string]any{"session_window_utilization": nil} + kept := false + for _, keys := range passiveWeeklyUsageWindows { + if reset := parseExtraFloat64(extra[keys[1]]); reset > 0 && time.Unix(int64(reset), 0).After(now) { + kept = true + continue + } + updates[keys[0]] = nil + updates[keys[1]] = nil + } + // The sample time still describes any weekly reading that was kept. + if !kept { + updates["passive_usage_sampled_at"] = nil + } + return updates +} + // samplePassiveUsageFromHeaders 从 Anthropic 响应头收集 5h/7d/7d_oi 的 // utilization 与 reset 被动采样数据,合并为一次 Extra 写入。无数据时不写。 func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, account *Account, headers http.Header) {