Files
shaguabijia-app-server/tests/test_analytics_health.py
T
guke 37fd51a498 feat(analytics): 埋点/上报健康度自报计数(selfstat)+ admin 健康度聚合端点 (#127)
背景 / 目标
客户端埋点从「采集」到「上报落库」全链路存在丢失(采集端丢帧、网络丢包、上报失败),现有 analytics_event(行为事件)无法度量这条链路的健康度。本 MR 引入一条与行为埋点完全独立的自报计数(selfstat)链路:客户端周期上报「自 epoch 起算的累计计数」,服务端只 append 存原始快照,admin 查询时在 Python 侧差分聚合出两段成功率(埋点成功率 / 上报成功率),支持总览 / 按天趋势 / 按维度下钻。

改动概览
① App 侧 — 上报接入(不强制登录)

新增 POST /api/v1/analytics/selfstat:一份快照 = 设备头 + N 条 event 累计计数,单事务落库,返回 snapshot_id。
稳态兜底:落库异常不裸奔 500,logger.exception 后回 503(计数链路要稳,不阻塞端上主流程)。
events 允许空列表(某次只报设备级计数也合法),上限 200 条/次;与行为埋点 min_length=1 有意不同。
② Admin 侧 — 健康度聚合(只读,需 admin 鉴权)

新增 GET /admin/api/analytics-health/{overview,trend,breakdown}。
差分聚合:原始累计快照按 (device_id, epoch_id, event) 分区、created_at 升序做相邻差分;分区首行增量=累计值,负值(epoch 重置 / 乱序)夹 0;每条增量按其快照 created_at 归入北京天桶。
基线行:取 date_from 左侧每分区最后一条快照,保证区间第一条增量正确(参与差分后丢弃)。
两段率(分母为 0 → null):
埋点成功率 track_success_rate = (attempted − drop_capture) / attempted
上报成功率 report_success_rate = delivered / (delivered + drop_undelivered)
breakdown 维度限 event | app_ver | oem(路由正则校验);结果按上报成功率升序(最差在前,None 垫底)。
③ 数据模型 / 基建

新表 analytics_selfstat(快照头 + 设备维度 app_ver/oem/os + 设备级诊断量 batches_attempted/ok/fail、retries、queue_depth、端 sent_at + 服务端权威 created_at)与 analytics_selfstat_event(四类累计计数,FK → 快照头)。
Alembic 迁移 11c44afbea58(down_revision admin_user_plain_password):建两表 + 索引。
模型登记进 app/models/__init__.py(供 Alembic 发现);路由挂进 app/admin/main.py。
关键设计取舍
只存原始累计、查询时 Python 差分:admin 低频、量级小,跨 PG/SQLite 无方言坑(与 cps.py/coupon_data.py 同款约定)。
选「最新一条」用 max(id) 而非 max(created_at):id 严格单调,规避 SQLite 秒级时间戳撞车的歧义。
tz 口径统一:SQLite 返回 naive UTC、PG 返回 aware UTC,过滤前统一转 naive UTC 再比较。
基线子查询无下界:扫 date_from 左侧全量(spec §7 已接受的取舍;量级变大再上物化 rollup)。
测试(+14,全绿)
tests/test_analytics_selfstat.py(3):正常落库 / 空 events / 落库异常回 503。
tests/test_analytics_health.py(11):差分逻辑(首行=累计值、相邻差、epoch 重置换分区、乱序夹 0、同时间戳按 id 定序)、两段率公式、零分母→None、北京天边界、端点(overview 鉴权 / overview / breakdown)。
迁移 / 部署注意
部署需执行 alembic upgrade head(建两张新表)。纯新增表,无回填、无破坏性改动,向后兼容。
客户端需按约定 payload(snake_case、累计语义)对接 /api/v1/analytics/selfstat;admin 前端(独立仓 shaguabijia-admin-web)消费三个 analytics-health 端点,不在本 MR 范围。

---------

Co-authored-by: guke <guke@autohome.com.cn>
Reviewed-on: #127
2026-07-09 17:31:24 +08:00

161 lines
6.0 KiB
Python

"""埋点健康度聚合:纯差分函数 + admin 端点。"""
from __future__ import annotations
from datetime import datetime, timezone
from app.admin.repositories.analytics_health import _cn_day, _rates, diff_snapshots
def _row(device, epoch, event, ts, **cum) -> dict:
base = {"attempted": 0, "drop_capture": 0, "delivered": 0, "drop_undelivered": 0}
base.update(cum)
return {
"device_id": device, "epoch_id": epoch, "event": event,
"created_at": datetime(2026, 7, 1, ts, 0, tzinfo=timezone.utc),
"app_ver": "0.2.12(62)", "oem": "ColorOS", "os": "Android 14",
**base,
}
def test_diff_first_row_is_full_cumulative() -> None:
rows = [_row("d", "e", "video_play", 1, attempted=100, delivered=90)]
out = diff_snapshots(rows)
assert len(out) == 1
assert out[0]["d_attempted"] == 100
assert out[0]["d_delivered"] == 90
def test_diff_consecutive_delta() -> None:
rows = [
_row("d", "e", "video_play", 1, attempted=100, delivered=90),
_row("d", "e", "video_play", 2, attempted=150, delivered=140),
]
out = sorted(diff_snapshots(rows), key=lambda r: r["created_at"])
assert out[1]["d_attempted"] == 50
assert out[1]["d_delivered"] == 50
def test_diff_epoch_reset_new_partition() -> None:
rows = [
_row("d", "e1", "video_play", 1, attempted=100),
_row("d", "e2", "video_play", 2, attempted=5),
]
out = {(r["epoch_id"]): r["d_attempted"] for r in diff_snapshots(rows)}
assert out["e1"] == 100
assert out["e2"] == 5
def test_diff_clamps_negative_on_reorder() -> None:
rows = [
_row("d", "e", "video_play", 1, attempted=100),
_row("d", "e", "video_play", 2, attempted=80),
]
out = sorted(diff_snapshots(rows), key=lambda r: r["created_at"])
assert out[1]["d_attempted"] == 0
def test_rates_computes_both_formulas() -> None:
out = _rates({"attempted": 150, "drop_capture": 0, "delivered": 140, "drop_undelivered": 10})
assert out["track_success_rate"] == 1.0
assert out["report_success_rate"] == 140 / 150
def test_rates_zero_denominator_yields_none() -> None:
out = _rates({"attempted": 0, "drop_capture": 0, "delivered": 0, "drop_undelivered": 0})
assert out["track_success_rate"] is None
assert out["report_success_rate"] is None
def test_cn_day_beijing_boundary() -> None:
# UTC 15:59 → 北京 23:59 同日;UTC 16:00 → 北京 次日 00:00
assert _cn_day(datetime(2026, 7, 1, 15, 59, tzinfo=timezone.utc)) == "2026-07-01"
assert _cn_day(datetime(2026, 7, 1, 16, 0, tzinfo=timezone.utc)) == "2026-07-02"
def test_diff_same_timestamp_ordered_by_id() -> None:
ts = datetime(2026, 7, 1, 1, 0, tzinfo=timezone.utc)
# 相同 created_at,乱序传入(id=2 在前);应按 id 排序 → id=1(cum100) 在前
rows = [
{"id": 2, "device_id": "d", "epoch_id": "e", "event": "vp", "created_at": ts,
"app_ver": "v", "oem": "o", "os": "s",
"attempted": 150, "drop_capture": 0, "delivered": 0, "drop_undelivered": 0},
{"id": 1, "device_id": "d", "epoch_id": "e", "event": "vp", "created_at": ts,
"app_ver": "v", "oem": "o", "os": "s",
"attempted": 100, "drop_capture": 0, "delivered": 0, "drop_undelivered": 0},
]
out = diff_snapshots(rows)
assert out[0]["d_attempted"] == 100 # id=1 sorts first → its cumulative
assert out[1]["d_attempted"] == 50 # id=2 second → 150-100
import pytest
from fastapi.testclient import TestClient
from app.admin.main import admin_app
from app.admin.repositories import admin_user as admin_repo
from app.db.session import SessionLocal
@pytest.fixture()
def admin_client() -> TestClient:
return TestClient(admin_app)
@pytest.fixture()
def admin_token() -> str:
db = SessionLocal()
try:
if admin_repo.get_by_username(db, "health_admin") is None:
admin_repo.create_admin(db, username="health_admin", password="pw", role="super_admin")
finally:
db.close()
c = TestClient(admin_app)
r = c.post("/admin/api/auth/login", json={"username": "health_admin", "password": "pw"})
return r.json()["access_token"]
def _auth(t: str) -> dict:
return {"Authorization": f"Bearer {t}"}
def _seed_two_snapshots(client: TestClient) -> None:
for attempted, delivered in ((100, 90), (150, 140)):
client.post("/api/v1/analytics/selfstat", json={
"device_id": "d-health", "epoch_id": "e-health",
"app_ver": "0.2.12(62)", "oem": "ColorOS", "os": "Android 14",
"events": [{"event": "video_play", "attempted": attempted,
"drop_capture": 0, "delivered": delivered, "drop_undelivered": 0}],
})
def test_health_overview_requires_auth(admin_client: TestClient) -> None:
r = admin_client.get("/admin/api/analytics-health/overview",
params={"date_from": "2026-07-01T00:00:00Z", "date_to": "2030-01-01T00:00:00Z"})
assert r.status_code == 401
def test_health_overview(client: TestClient, admin_client: TestClient, admin_token: str) -> None:
_seed_two_snapshots(client) # 播种走公开 app(ingest 端点在 app,不在 admin_app)
r = admin_client.get(
"/admin/api/analytics-health/overview",
params={"date_from": "2026-07-01T00:00:00Z", "date_to": "2030-01-01T00:00:00Z"},
headers=_auth(admin_token),
)
assert r.status_code == 200, r.text
data = r.json()
# 两快照累计 100→150,差分后 attempted 总 150(首快照 100 + 增量 50)
assert data["attempted"] == 150
assert data["track_success_rate"] == 1.0
def test_health_breakdown(client: TestClient, admin_client: TestClient, admin_token: str) -> None:
_seed_two_snapshots(client) # 播种走公开 app
r = admin_client.get(
"/admin/api/analytics-health/breakdown",
params={"date_from": "2026-07-01T00:00:00Z", "date_to": "2030-01-01T00:00:00Z", "dim": "event"},
headers=_auth(admin_token),
)
assert r.status_code == 200, r.text
rows = r.json()
assert any(row["key"] == "video_play" for row in rows)