Skip to content

Commit 53d8ede

Browse files
authored
[COD-64] CompressStats 的 retention_days 只在启动时注入,热更后压缩收益小时桶仍按旧值裁剪 (#105)
* fix COD-64:CompressStats 保留期现读热更值 * fix COD-64:去重 i18n 词表重复键,恢复前端 tsc
1 parent 49e61f5 commit 53d8ede

5 files changed

Lines changed: 41 additions & 9 deletions

File tree

‎src/api/context.py‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from dataclasses import dataclass, field
2525
from typing import Any
2626

27+
from ..config import live
2728
from ..engine.compress import compress_messages, estimate_messages
2829
from ..engine.prefix_debug import PrefixDebugTracker
2930
from ..engine.sticky_trim import StickyTrimmer, conversation_key
@@ -78,8 +79,9 @@ class CompressStats:
7879
buckets: dict[int, dict[str, int]] = field(default_factory=dict)
7980
#: 时钟可注入:测试按整点定位桶,不必 sleep。
8081
clock: Callable[[], float] = time.time
81-
#: 小时桶保留天数:生产装配传运行时生效值(与明细保留期同一配置)。
82-
retention_days: int = RETENTION_DAYS
82+
#: 小时桶保留天数:零参取值器,裁剪时现读(生产装配传运行时热更值,
83+
#: 与 `StatsQuery`/`RetentionTask` 同一口径;测试仍可传标量整数)。
84+
retention_days: Callable[[], int] = field(default=lambda: RETENTION_DAYS)
8385
#: 上次裁剪到的小时(同一小时内不重复扫描;不参与比较/展示)。
8486
_pruned_hour: int | None = field(default=None, repr=False, compare=False)
8587
#: 落盘快照路径;None = 纯内存(测试与单次装配默认)。
@@ -91,15 +93,21 @@ class CompressStats:
9193
#: 是否有未落盘的变化:关机补写与失败重试都靠它。
9294
_dirty: bool = field(default=False, repr=False, compare=False)
9395

96+
def __post_init__(self) -> None:
97+
"""把保留期统一成零参取值器:标量入参也包装成「恒返回它」。"""
98+
self.retention_days = live(self.retention_days)
99+
94100
@classmethod
95101
def load(cls, path: str, *,
96102
clock: Callable[[], float] = time.time,
97-
retention_days: int = RETENTION_DAYS) -> CompressStats:
103+
retention_days: int | Callable[[], int] = RETENTION_DAYS
104+
) -> CompressStats:
98105
"""从落盘快照恢复小时桶与终身累计;缺失/损坏时回到全新计数器。"""
106+
days = live(retention_days)
99107
buckets, lifetime = load_buckets(path, now=clock(),
100-
retention_days=retention_days)
108+
retention_days=int(days()))
101109
stats = cls(clock=clock, persist_path=path,
102-
retention_days=retention_days, **lifetime)
110+
retention_days=days, **lifetime)
103111
stats.buckets = buckets
104112
return stats
105113

@@ -138,7 +146,9 @@ def _bump(self, **deltas: int) -> None:
138146
# 只在跨小时时扫一次:一条长会话里压缩是逐轮调用的常态,
139147
# 每次请求都遍历全部桶是纯浪费。
140148
self._pruned_hour = hour
141-
cutoff = hour - self.retention_days * 24 * HOUR_SECONDS
149+
# 现读而非在 load 期缓存:管理台热更保留期后,下一次跨小时
150+
# 裁剪即按新值丢桶,不必重启。
151+
cutoff = hour - int(self.retention_days()) * 24 * HOUR_SECONDS
142152
for key in [key for key in self.buckets if key < cutoff]:
143153
del self.buckets[key]
144154
self._dirty = True

‎src/main.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,9 +782,11 @@ def build_app(settings: Settings | None = None, *, providers: dict | None = None
782782
# (统计页要「省下的 token」与「同期命中率」并排读)。启动从
783783
# `DATA_DIR/compress_buckets.json` 读回小时桶,重启不再清空窗口差异;
784784
# 挂到 app.state 是为了测试可以注入独立实例,不影响进程级单例。
785+
# 保留期传零参 lambda 现读运行态覆盖层:管理台改 retention_days 后,
786+
# 下一次跨小时裁剪即按新值丢桶(与 StatsQuery/RetentionTask 同口径)。
785787
compress_stats = CompressStats.load(
786788
compress_buckets_path(config.data_dir),
787-
retention_days=runtime.retention_days)
789+
retention_days=lambda: runtime.retention_days)
788790
executor = Executor(ExecutorDeps(providers=registry, credentials=credentials,
789791
scheduler=Scheduler(
790792
expiry_window=lambda: runtime.quota_expiry_window_seconds,

‎src/persistence/compress_buckets.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@
2727
#: 小时桶的秒数;键与 `usage_hourly.hour_utc` 同一口径(整点起点)。
2828
HOUR_SECONDS = 3600
2929
#: 小时桶保留天数的默认值:与 `Settings.retention_days` 一致。
30-
#: 生产装配把运行时生效值传进来(`CompressStats.load(..., retention_days=...)`),
30+
#: 生产装配把运行时生效值传进来(`CompressStats.load(..., retention_days=...)`;
31+
#: 也接受零参取值器,此处只取一次用于读盘裁剪),
3132
#: 这里只是纯内存实例(测试 / 单次装配)的默认。
3233
RETENTION_DAYS = 45
3334
#: 桶/终身累计里被落盘的字段(`tokens_saved` 是派生值,不存)。

‎tests/api/test_context.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,3 +864,23 @@ def test_compress_stats_retention_days_is_configurable():
864864
tight.buckets = {first_hour: dict.fromkeys(("triggers",), 1)}
865865
tight._bump(triggers=1)
866866
assert first_hour not in tight.buckets
867+
868+
869+
def test_compress_stats_retention_days_follows_hot_reload():
870+
"""保留期现读热更值:管理台改完不必重启,下一次跨小时裁剪即按新值丢桶。"""
871+
from src.api.context import CompressStats
872+
873+
now = {"t": 1_700_000_000.0}
874+
days = {"v": 90}
875+
stats = CompressStats(clock=lambda: now["t"], retention_days=lambda: days["v"])
876+
stats._bump(triggers=1)
877+
first_hour = int(now["t"] // 3600) * 3600
878+
879+
now["t"] += 60 * 86400
880+
stats._bump(triggers=1) # 跨小时触发裁剪;60 天 < 90 天
881+
assert first_hour in stats.buckets
882+
883+
days["v"] = 45 # 热更(45 天 ≤ 60 天):无需重启
884+
now["t"] += 3600
885+
stats._bump(triggers=1)
886+
assert first_hour not in stats.buckets

‎web/src/i18n/text.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1055,7 +1055,6 @@ export const TEXT_EN: Record<string, string> = {
10551055
"天失败": "days failed",
10561056
"天)·": "days) ·",
10571057
"失败归因加载失败(HTTP {0})": "Failed to load failure attribution (HTTP {0})",
1058-
"失败趋势加载失败(HTTP {0})": "Failed to load failure trend (HTTP {0})",
10591058
"完成": "Done",
10601059
"官方状态页": "Official status pages",
10611060
"官方状态页粒度比本服务的模型级冷却粗、更新也滞后,这里只做解释,不参与选号 / 熔断;本服务实时冷却见「凭证管理」页。数据仅存内存,服务重启后归零。": "Official status pages are coarser than this service's per-model cooldown and lag behind, so they only explain, they never pick credentials or trip the breaker; see the credentials page for live cooldowns. The data lives in memory only and resets when the service restarts.",

0 commit comments

Comments
 (0)