Skip to content

Commit db9ef31

Browse files
authored
[COD-51] 失败归因面板仍只读明细表,保留期缩到 45 天后归因历史同步变短(usage_hourly_dim 已带 error_type 维度) (#93)
* feat(stats): 新增失败趋势聚合接口与管理台趋势卡片(小时汇总口径,无逐行救援判定) * fix(stats): 失败趋势 since 锚定 + 修正提示语方位
1 parent c9420b9 commit db9ef31

11 files changed

Lines changed: 637 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,9 +506,10 @@ curl -X POST http://127.0.0.1:8000/v1/fetch \
506506

507507
四维 tabs(渠道 / 模型 / 用户 / 凭证)共用一表(渠道 / 请求 / Credit / 成本 / Token / 速度 / 平均延迟 / P95 延迟),端点 `GET /api/stats/by-provider|by-model|by-user|by-credential`。**延迟分位 P50 / P90 / P95 / P99**(默认 P95,nearest-rank)。用户 / 凭证维度仅 admin / operator。
508508

509-
- **口径差异**:渠道 / 模型 / 用户读 `usage_hourly`,凭证 / Key 读 `usage_hourly_dim`(两张汇总表均永久保留,近 5 分钟未计入);只有逐请求明细、延迟分位、失败归因的「救回数」读明细表(保留期,默认 45 天)。
509+
- **口径差异**:渠道 / 模型 / 用户读 `usage_hourly`,凭证 / Key 读 `usage_hourly_dim`(两张汇总表均永久保留,近 5 分钟未计入);只有逐请求明细、延迟分位、失败归因的「救回数」读明细表(保留期,默认 45 天);失败趋势读小时汇总,故可回看超过保留期。
510510
- **延迟**:只统计成功请求。平均 = `latency_sum ÷ 成功数`;分位从明细算(仅保留期)。`ttfb_ms` 为 `NULL` 的两列各自独立排名。
511511
- **失败归因**(`GET /api/stats/errors`,operator+):按 `(渠道, 模型, 错误类型)` 聚合 `ok=0`,返回失败次数 / **未救回数** / 最近失败时刻(`limit` ≤5000)。**落行口径**:硬失败(`credential_unavailable` / `account_restricted` / `invalid_request` / `model_capability`)每次尝试各一行;其余分类每次请求只落收尾一行。同用户同 `request_id` 另有成功行 = 已救回。特殊判据:凭证 401 落 `credential_unavailable`,**额度耗尽证据成立时**(officeace `401 APIG.1009`)改判 `CREDIT`(冷却到次日 04:00、不硬禁用);`11140` → `account_restricted`(2h 账号级冷却;同渠道 10 分钟内**全部**凭证都中招才整渠道退避);`11102` / `11158` → `model_not_found`(负缓存,不冷却账号);`11115` → `context_overflow`、`001001020` → `model_capability`(不惩罚凭证);`001001044` → `invalid_request`。一次凭证都没选中时明细落**候选渠道**。完整分类与冷却时长见 TECHNICAL.md §3.2。
512+
- **失败趋势**(`GET /api/stats/error-trend`,viewer+):读 `usage_hourly_dim`(小时汇总,**永久保留**)按小时桶 × `error_type` 聚合失败行数(`requests - ok_count`),可选 `provider` / `model` 下钻。**不含逐行救援判定**(小时桶没有 `request_id`,无法关联成功行),故没有「未救回」——长窗口的失败走向看这里,救援口径看上面的失败归因。窗口缺省最近 7 天,桶数上限 5000(约 208 天),超出从下界截断并在 `truncated` + 实际 `since` / `until` 里标注。
512513
- **钻取**:点分组表任一行 → 明细按该行过滤,条件可叠加;`GET /api/stats/events` 接受 `provider` / `model` / `credential_id`(AND)+ `ok=0`。
513514
- **列合并**:Token、延迟、速度、渠道 / 凭证各并一列,悬停展开;合并列头可下拉选子列排序(`sort=cache_rate` / `tps_visible` / `tps` / `provider` / `credential`)。
514515
- **导出 CSV**:`GET /api/stats/events?format=csv`,UTF-8 BOM、`\r\n`、ISO 8601 UTC;`= + - @` 开头加前导单引号防公式注入。单次 ≤10000 行,超出截断 + `X-Export-Truncated: 1`。

‎src/api/admin_stats.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,25 @@ async def stats_errors(principal=Depends(principal_from_request),
227227
username=_scope(principal, username), since=since, until=until,
228228
limit=max(1, min(limit, ERROR_MAX_GROUPS)))}
229229

230+
@router.get("/api/stats/error-trend")
231+
async def stats_error_trend(principal=Depends(principal_from_request),
232+
username: str | None = None,
233+
provider: str | None = None,
234+
model: str | None = None,
235+
since: int | None = None,
236+
until: int | None = None):
237+
"""失败趋势(只读聚合,viewer 及以上):小时汇总按错误类型分桶计数。
238+
239+
与 `/api/stats/errors` 的分工:那条读明细表(含逐行救援判定,只覆盖
240+
明细保留期),这条读 `usage_hourly_dim`(小时汇总永久保留),因此能回看
241+
超出明细保留期的失败趋势。**不含逐行救援判定**,响应里没有 `rescued`。
242+
243+
窗口缺省最近 7 天;桶数超上限时从下界截断,`truncated` 标注实际区间。
244+
"""
245+
return stats_query.error_trend(
246+
username=_scope(principal, username), provider=provider, model=model,
247+
since=since, until=until)
248+
230249
@router.get("/api/stats/events")
231250
async def stats_events(request: Request,
232251
principal=Depends(principal_from_request),

‎src/stats/query.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,13 @@ def row_speed(*, ok: bool | int, output_tokens: int | None, reasoning_tokens: in
261261
ERROR_WINDOW_SECONDS = 86400
262262
ERROR_MAX_GROUPS = 5000
263263

264+
# 失败趋势(`/api/stats/error-trend`):只读聚合,读 `usage_hourly_dim`。
265+
# 默认窗口 7 天;上限 `ERROR_TREND_MAX_HOURS` 个整点桶(约 208 天),超出部分
266+
# 从下界截断并在响应里回传实际覆盖区间——小时汇总本身永不清理,但一次拉几万
267+
# 个空桶的曲线没有意义。
268+
ERROR_TREND_WINDOW_SECONDS = 7 * 86400
269+
ERROR_TREND_MAX_HOURS = 5000
270+
264271
# 分位值的 nearest-rank 名次:第 p 百分位 = 第 ⌈p·n/100⌉ 小的值。用整数运算写
265272
# `(p * n + 99) / 100`(SQLite 整数除法即向下取整,加分母−1 后等价于对分子
266273
# 向上取整),避免浮点误差把名次算偏。与原 P95 的 `(95*n+99)/100` 逐字节一致。
@@ -1277,6 +1284,79 @@ def errors(self, *, username: str | None = None, since: int | None = None,
12771284
"rescued": int(row["rescued"]),
12781285
"last_ts": int(row["last_ts"])} for row in rows]
12791286

1287+
def error_trend(self, *, username: str | None = None,
1288+
provider: str | None = None, model: str | None = None,
1289+
since: int | None = None, until: int | None = None,
1290+
now: int | None = None) -> dict[str, Any]:
1291+
"""失败趋势:小时汇总按 `error_type` 分桶计数(只读聚合,无逐行判定)。
1292+
1293+
与 `errors()` 的分工:那个端点读明细表,能按 `request_id` 还原换号救援
1294+
(`rescued`)、窗口是秒级半开区间,但只覆盖明细保留期(默认 45 天)。
1295+
这条读 `usage_hourly_dim`(小时汇总,**永久保留**),故能回看远超明细
1296+
保留期的失败趋势;代价是**不含逐行救援判定**(小时桶没有 request_id,
1297+
无法关联成功行),响应里也没有 `rescued` 字段——不要拿失败数减任何东西
1298+
当作受损请求数。
1299+
1300+
`hour_utc` 是整点桶起点,故窗口两端对齐到小时:下界向下取整、上界向上
1301+
取整(含不满一小时的尾桶)。默认「最近 7 天」,桶数超过
1302+
`ERROR_TREND_MAX_HOURS` 时从下界截断,`truncated=True` 标注实际区间。
1303+
`error_type` 的 `''` 哨兵(成功行 / 未上报)与 NULL 一并归为 `None`,
1304+
前端显示成「失败」,与 `errors()` 同口径。
1305+
1306+
`points` 只给**有失败**的小时(稀疏):前端按时间戳定位,空档不插点。
1307+
"""
1308+
current = int(now if now is not None else time.time())
1309+
coverage_until = until if until is not None else current
1310+
until_hour = -(-coverage_until // 3600) * 3600
1311+
# 缺省窗口按整点桶算(7 天 = 168 个桶),否则 `until` 的向上取整会让
1312+
# 实际跨度多出不到一小时,前端按「7 天」标窗口时对不上
1313+
since_hour = ((since // 3600) * 3600 if since is not None
1314+
else until_hour - ERROR_TREND_WINDOW_SECONDS)
1315+
truncated = False
1316+
if (until_hour - since_hour) // 3600 > ERROR_TREND_MAX_HOURS:
1317+
truncated = True
1318+
since_hour = until_hour - ERROR_TREND_MAX_HOURS * 3600
1319+
clauses = ["hour_utc >= ?", "hour_utc < ?", "requests > ok_count"]
1320+
params: list[Any] = [since_hour, until_hour]
1321+
for column, value in (("username", username), ("provider", provider),
1322+
("model", model)):
1323+
if value is not None:
1324+
clauses.append(f"{column} = ?")
1325+
params.append(value)
1326+
rows = self._db.connect().execute(
1327+
f"""
1328+
SELECT hour_utc, error_type, SUM(requests - ok_count) AS failures
1329+
FROM usage_hourly_dim
1330+
WHERE {' AND '.join(clauses)}
1331+
GROUP BY hour_utc, error_type
1332+
ORDER BY hour_utc, error_type
1333+
""", params).fetchall()
1334+
by_hour: dict[int, list[dict[str, Any]]] = {}
1335+
totals: dict[str | None, int] = {}
1336+
failures_total = 0
1337+
for row in rows:
1338+
# `''` 与 NULL 都是「没有错误类型」,合并成一组(与 errors() 同口径)
1339+
error_type = row["error_type"] or None
1340+
failures = int(row["failures"])
1341+
by_hour.setdefault(int(row["hour_utc"]), []).append(
1342+
{"error_type": error_type, "failures": failures})
1343+
totals[error_type] = totals.get(error_type, 0) + failures
1344+
failures_total += failures
1345+
return {
1346+
"points": [{"hour": hour,
1347+
"failures": sum(item["failures"] for item in items),
1348+
"error_types": items}
1349+
for hour, items in sorted(by_hour.items())],
1350+
# 图例:全窗口按错误类型汇总,按失败数降序(与 points 同一批行)
1351+
"error_types": [{"error_type": key, "failures": value}
1352+
for key, value in sorted(totals.items(),
1353+
key=lambda kv: (-kv[1], kv[0] or ""))],
1354+
"failures": failures_total,
1355+
"since": since_hour,
1356+
"until": until_hour,
1357+
"truncated": truncated,
1358+
}
1359+
12801360
def model_timeline(self, *, username: str | None = None,
12811361
since: int | None = None, until: int | None = None,
12821362
top: int = 6,

‎tests/api/test_stats_errors.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,39 @@ def test_events_ok_filter_offset_mode_total(admin_client):
129129
"sort": "ts", "order": "asc",
130130
"limit": 2}).json()
131131
assert page["total"] == 4 and len(page["events"]) == 2
132+
133+
134+
TREND_PATH = "/api/stats/error-trend"
135+
136+
137+
def test_error_trend_readable_by_viewer_and_rejects_anonymous(admin_client):
138+
"""沿用统计只读权限:viewer 可读;未登录 401。"""
139+
app, client = admin_client
140+
now = _seed_failures(app)
141+
client.cookies.set("coding2api_session", create_session_token("guest", SECRET))
142+
# viewer 只能看自己:root 的失败不可见,故窗口内为空
143+
viewer = client.get(TREND_PATH, params={"since": now - 3600})
144+
assert viewer.status_code == 200 and viewer.json()["failures"] == 0
145+
app.state.user_repo.update_role("guest", ROLE_OPERATOR)
146+
client.cookies.set("coding2api_session",
147+
create_session_token("guest", SECRET, epoch=1))
148+
assert client.get(TREND_PATH, params={"since": now - 3600}).json()["failures"] == 4
149+
client.cookies.clear()
150+
assert client.get(TREND_PATH).status_code == 401
151+
152+
153+
def test_error_trend_groups_by_error_type_without_rescued(admin_client):
154+
"""按 error_type 分组,且响应里没有逐行救援判定字段。"""
155+
app, client = admin_client
156+
now = _seed_failures(app)
157+
body = client.get(TREND_PATH, params={"since": now - 3600}).json()
158+
assert body["failures"] == 4
159+
assert body["error_types"] == [{"error_type": "rate_limit", "failures": 3},
160+
{"error_type": "upstream_error", "failures": 1}]
161+
assert set(body) == {"points", "error_types", "failures", "since", "until",
162+
"truncated"}
163+
assert all("rescued" not in item for point in body["points"]
164+
for item in point["error_types"])
165+
# 可选下钻:按渠道 / 模型
166+
assert client.get(TREND_PATH, params={"since": now - 3600, "model": "nope"}
167+
).json()["failures"] == 0

‎tests/stats/test_query_percentiles.py‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import time
1010

11-
from src.stats.query import PERCENTILES
11+
from src.stats.query import ERROR_TREND_MAX_HOURS, ERROR_TREND_WINDOW_SECONDS, PERCENTILES
1212

1313

1414
def _record_latencies(collector, values, *, provider="trae", model="m", username="u",
@@ -396,3 +396,108 @@ def test_errors_rescued_sees_success_before_window_start(stats):
396396
set_request_id(None)
397397
rows = query.errors(since=base, until=base + 10, now=base)
398398
assert rows[0]["failures"] == 1 and rows[0]["rescued"] == 1
399+
400+
401+
# ===== 失败趋势(小时汇总聚合,无逐行救援判定)=====
402+
403+
def _seed_hourly_failures(collector, *, now: int):
404+
"""两小时三组失败 + 一小时成功(成功不计入趋势)。"""
405+
for offset in range(3):
406+
collector.record(username="u", provider="trae", model="glm", ok=False,
407+
error_type="rate_limit", now=now + offset)
408+
collector.record(username="u", provider="trae", model="glm", ok=False,
409+
error_type="upstream_error", now=now + 10)
410+
collector.record(username="v", provider="codebuddy", model="kimi", ok=False,
411+
error_type="rate_limit", now=now + 3600)
412+
collector.record(username="u", provider="trae", model="glm", ok=True, now=now + 20)
413+
414+
415+
def test_error_trend_groups_by_hour_and_error_type(stats):
416+
"""按小时桶 + error_type 分组;成功行不进趋势,也没有 rescued 字段。"""
417+
collector, query = stats
418+
now = 1_700_000_000
419+
_seed_hourly_failures(collector, now=now)
420+
trend = query.error_trend(since=now - 60, now=now + 7200)
421+
hour = (now // 3600) * 3600
422+
assert trend["points"] == [
423+
{"hour": hour, "failures": 4, "error_types": [
424+
{"error_type": "rate_limit", "failures": 3},
425+
{"error_type": "upstream_error", "failures": 1}]},
426+
{"hour": hour + 3600, "failures": 1, "error_types": [
427+
{"error_type": "rate_limit", "failures": 1}]},
428+
]
429+
assert trend["failures"] == 5
430+
assert trend["error_types"] == [{"error_type": "rate_limit", "failures": 4},
431+
{"error_type": "upstream_error", "failures": 1}]
432+
assert all("rescued" not in item for point in trend["points"]
433+
for item in point["error_types"])
434+
assert trend["truncated"] is False
435+
436+
437+
def test_error_trend_reaches_beyond_detail_retention(stats):
438+
"""小时汇总永久保留:60 天前的失败仍能被趋势查到(明细早已清理)。"""
439+
collector, query = stats
440+
now = 1_700_000_000
441+
old = now - 60 * 86400
442+
collector.record(username="u", provider="trae", model="glm", ok=False,
443+
error_type="rate_limit", now=old)
444+
# 按明细保留期清理后:明细归因查不到它,趋势(小时汇总)照样查得到
445+
collector.purge_expired(45, now=now)
446+
assert query.errors(since=old - 60, until=old + 60, now=now) == []
447+
trend = query.error_trend(since=old - 60, until=old + 60, now=now)
448+
assert trend["failures"] == 1
449+
assert trend["points"][0]["error_types"] == [
450+
{"error_type": "rate_limit", "failures": 1}]
451+
452+
453+
def test_error_trend_sums_match_hourly_dim(stats):
454+
"""同一窗口内各 error_type 计数之和 == 汇总表对应行的失败计数。"""
455+
collector, query = stats
456+
now = 1_700_000_000
457+
_seed_hourly_failures(collector, now=now)
458+
trend = query.error_trend(since=now - 60, until=now + 7200, now=now)
459+
expected = query._db.connect().execute(
460+
"SELECT SUM(requests - ok_count) AS c FROM usage_hourly_dim "
461+
"WHERE hour_utc >= ? AND hour_utc < ?",
462+
[(now // 3600) * 3600, ((now + 7200) // 3600) * 3600]).fetchone()["c"]
463+
assert sum(item["failures"] for item in trend["error_types"]) == expected == 5
464+
465+
466+
def test_error_trend_scope_and_drilldown(stats):
467+
"""按用户收窄,可选按渠道 / 模型下钻。"""
468+
collector, query = stats
469+
now = 1_700_000_000
470+
_seed_hourly_failures(collector, now=now)
471+
window = {"since": now - 60, "until": now + 7200, "now": now}
472+
assert query.error_trend(username="v", **window)["failures"] == 1
473+
assert query.error_trend(provider="codebuddy", **window)["failures"] == 1
474+
assert query.error_trend(model="glm", **window)["failures"] == 4
475+
assert query.error_trend(model="nope", **window)["failures"] == 0
476+
477+
478+
def test_error_trend_unknown_error_type_grouped_as_none(stats):
479+
"""`''` 哨兵(未上报)与 NULL 合并成一组 `None`,前端显示「失败」。"""
480+
collector, query = stats
481+
now = 1_700_000_000
482+
collector.record(username="u", provider="trae", model="glm", ok=False, now=now)
483+
trend = query.error_trend(since=now - 60, now=now)
484+
assert trend["error_types"] == [{"error_type": None, "failures": 1}]
485+
486+
487+
def test_error_trend_default_window_is_7_days(stats):
488+
"""缺省窗口最近 7 天;桶数超上限时从下界截断并标注。"""
489+
collector, query = stats
490+
now = 1_700_000_000
491+
collector.record(username="u", provider="trae", model="glm", ok=False,
492+
error_type="rate_limit", now=now - 60)
493+
trend = query.error_trend(now=now)
494+
assert trend["failures"] == 1
495+
assert trend["until"] - trend["since"] == ERROR_TREND_WINDOW_SECONDS
496+
# 窗口只给 until:下界按 until 往前推 7 天
497+
only_until = query.error_trend(until=now, now=now)
498+
assert only_until["until"] == ((now // 3600) + 1) * 3600
499+
assert only_until["since"] == only_until["until"] - ERROR_TREND_WINDOW_SECONDS
500+
# 超上限:截断到 MAX_HOURS 个桶,truncated=True
501+
wide = query.error_trend(since=0, until=now, now=now)
502+
assert wide["truncated"] is True
503+
assert (wide["until"] - wide["since"]) // 3600 == ERROR_TREND_MAX_HOURS

0 commit comments

Comments
 (0)