Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Ten upstream channels — **CodeBuddy** (China + international, two separate cha
- **Shared credential pool**: admin-maintained, shared by all users, encrypted with `APP_SECRET`; device-code / OAuth login, multi-account switching, quota probing, check-in, token pre-refresh.
- **Three roles**: `admin` / `operator` / `viewer` (SQLite); one-time activation links, forced password change on first login, role change / disable revokes sessions immediately; logins and writes are audited.
- **Growth center** (CodeBuddy only): claim gifts, dispatch Buddy, claim task rewards, make up missed logins, exchange streaks, open blind boxes. `GROWTH_IRREVERSIBLE_ACTIONS=false` disables irreversible actions; enterprise accounts are skipped.
- **Privacy-preserving stats**: no conversations stored; 90 days of detail, permanent hourly rollups; views by user / channel / model / credential; cost estimated from OpenRouter list prices; live detail via SSE.
- **Privacy-preserving stats**: no conversations stored; 45 days of detail (default `RETENTION_DAYS`, hot-updatable), permanent hourly rollups; views by user / channel / model / credential; cost estimated from OpenRouter list prices; live detail via SSE.
- **Monthly billing** (`operator` and up): per-month, per-user / per-key requests, tokens and cost; CSV / JSONL export with an audit entry.
- **Tool-call robustness**: missing `id` backfilled by index and remembered; leaked DeepSeek DSML is read back into structured calls; malformed non-stream `arguments` fail closed (400, no credential cooldown).
- **Failure routing**: `11134` provider overload is queued (no penalty); request-level errors do not carry conversation stickiness across credentials; exhausted pool returns 503 with `Retry-After` and a **pool breakdown** (`total=25 cooling=20 disabled=3 …`).
Expand Down Expand Up @@ -106,7 +106,7 @@ echo "$PASSWORD" | python3 scripts/create_user.py alice --role admin --password-

## Audit and server logs

- **Audit** (`/audit`, admin only): logins (success and failure) plus write operations, filterable by actor / action and paginated. Each entry: time / actor / action / object / note / source IP. **No plaintext passwords or tokens** (activation tokens are stored as SHA-256). Retained 90 days.
- **Audit** (`/audit`, admin only): logins (success and failure) plus write operations, filterable by actor / action and paginated. Each entry: time / actor / action / object / note / source IP. **No plaintext passwords or tokens** (activation tokens are stored as SHA-256). Retained 45 days (`RETENTION_DAYS`).
- **Server logs** (`/logs`, admin only): live in-process log stream. `GET /api/logs` returns the last N lines, `GET /api/logs/stream` is SSE (replay then live); level filter, keyword filter, follow, pause, clear. **No write endpoint**.
- **Redaction is mandatory**: every line passes an allowlist before leaving the process; lines matching `token` / `secret` / `authorization` / `cookie` / `password` / `api_key`, `sk-…` patterns or `Bearer <value>` are dropped entirely.
- In-memory buffer `LOG_BUFFER_LINES` (default 500, hot-reloadable, `0` disables the page); **persistence** `LOG_PERSIST_LINES` (default 2000, hot-reloadable) writes a second copy into the SQLite `log_events` ring table, so logs survive restarts and support `?request_id=`, `?since=<epoch>`, `?level=ERROR`. Trimmed by line count, not time. Write failures warn once and never propagate.
Expand Down Expand Up @@ -478,29 +478,29 @@ Default is the **last 24 hours** (also 7 / 30 days, all time, custom). Custom us
- **Failure types** (`CONTROLLED_ERROR_TYPES`): the closing row carries the **real attribution of the last error** — `model_unavailable` / `rate_limit` / `upstream_timeout` / `network_error` (local DNS / connect failure, no cooldown) / `context_overflow` (11115) / `model_capability` (CodeArts 001001020) / `model_not_found` (retired model, distinct from "bad request") / `truncated_stream` (stream closed cleanly before any terminal event) / `empty_output` (upstream reached terminal state with no content / reasoning / tool calls / usage — recorded as a failure only after one same-credential retry, zero cooldown). Only when **no credential was ever selected** does it fall back to `no_healthy_credential`. External codes are identical; only stats semantics differ.
- **Request ID**: responses carry `X-Request-ID`; a valid inbound value is reused, otherwise generated (`[A-Za-z0-9._:-]`, 1–128 chars); stored in `usage_events.request_id` and **never forwarded upstream**.
- **Attempt-chain headers** (only with `EXPOSE_UPSTREAM_HEADERS=true`, off by default): `X-Upstream-Attempts` = credentials actually tried, `X-Upstream-Degraded` = whether `MODEL_FALLBACK_GROUPS` fallback was used. When off, the middleware strips same-named headers (including forged values from upstreams or middleboxes). Off by default because these headers hand out pool size, cost and routing fingerprints. For streams they only reflect attempts **before** the response head is sent; later rotations cannot rewrite an already-sent head.
- **Content-refusal freeze**: upstream content-safety refusals (currently only CodeBuddy `11128`) do not rotate or cool a credential; a hit is attributed to the requester (username first, API Key id otherwise). Once `ACCESS_FREEZE_THRESHOLD=N` (default `0` = record only) is reached, requests from that requester × provider get `403 provider_access_frozen` before reaching upstream; `GET /api/access-freezes` shows hits/frozen state and `POST /api/access-freezes/unfreeze` clears it (operator+, audited). Hit rows share the detail retention (90 days); the list filters and pages in SQL.
- **Content-refusal freeze**: upstream content-safety refusals (currently only CodeBuddy `11128`) do not rotate or cool a credential; a hit is attributed to the requester (username first, API Key id otherwise). Once `ACCESS_FREEZE_THRESHOLD=N` (default `0` = record only) is reached, requests from that requester × provider get `403 provider_access_frozen` before reaching upstream; `GET /api/access-freezes` shows hits/frozen state and `POST /api/access-freezes/unfreeze` clears it (operator+, audited). Hit rows share the detail retention (`RETENTION_DAYS`, 45 days); the list filters and pages in SQL.
- **Credit**: CodeBuddy uses upstream truth; TRAE is derived from official unit prices and marked `≈` (`src/provider/trae/pricing.py`, unlisted models are not derived). Backfill with `scripts/backfill_trae_credit.py`.
- **TRAE cache is no longer reported**: since 2026-10 TRAE returns `cache_read_input_tokens` as a constant 0 and `prompt_cache_pool_record` as null, yet the **cache discount still applies**. This service records such "unreported" values as NULL (no lying) and shows an **`≈` derived cache rate** (the stored value stays NULL, never counted as reported); credits / cost are estimated with a **calibratable assumed hit ratio** (`TRAE_ASSUMED_CACHE_RATIO`, default `0.95`, measured from production `credit_events` balance deltas). The periodic *cache-ratio calibration* task runs every `CACHE_RATIO_INTERVAL_MINUTES` (default 6h) and re-derives the real ratio from the last 7 days of balance deltas against tokens **over the whole window** (bucketing by UTC day misaligns deltas and tokens); it writes back only when the drift is ≥0.01. **Historical rows**: run `scripts/normalize_trae_cache.py` once to turn post-cutoff zeros into NULL (preview by default, `--apply` writes), then `backfill_trae_credit.py --apply` / `backfill_cost.py --provider trae --apply` to re-estimate credits and cost with the assumed ratio (scoped to the channel so other channels' historical cost is left alone).
- **Cost (estimated ≈)**: tokens × public list price, not the actual upstream charge. `(input−cached)×input + cached×cache + output×output` in USD → converted to CNY at write time using `USD_CNY_RATE`; history is not recomputed. Unmatched models are not priced (cost is a lower bound); channel-specific ids map to base models only via explicit equivalence rules.
- **Cache hit rate**: cached tokens ÷ input tokens **of requests that reported cache details** (one decimal). Unreported channels / requests stay out of the denominator (otherwise one huge input drags the whole figure to 0); all-unreported or zero denominator → `—`.
- **Output speed** = total tokens ÷ total generation time (not an average of per-request ratios). Two views: **body speed** `output_tokens - reasoning_tokens` and **total throughput** including reasoning. Only successful requests routed through this service with ≥1 output token; generation time = `latency_ms - ttfb_ms`; samples under 200ms or above 1000 tok/s are dropped. No samples → estimated mode (prefixed `≈`); neither → `—`.
- **Charts**: requests / tokens / cost / cost per request / latency / TTFB / success rate / cache hit rate. Derived metrics are `sum ÷ sum`, no samples render as `—` (gap) not 0; latency and TTFB also get a percentile chart (P50 + P95 from details, 90 days only). The time axis is filled hourly. Out-of-domain `metric` is an explicit 400; an invalid custom range pauses fetching.
- **Compression gains panel**: trigger counts (tool output / context trimming), characters and tokens saved (lower-bound estimate), the concurrent prefix-cache hit rate, and both compression switches, on one screen. Savings must be read next to the cache cost, otherwise "keep it on or turn it off" is unanswerable; `GET /api/stats/compression?since=&until=` (operator+, hourly buckets summed over the same window as the overview; omit both ends for the lifetime total). Hourly buckets and lifetime totals are persisted to `DATA_DIR/compress_buckets.json` (60s throttle, flushed on shutdown), surviving restarts for 90 days.
- **Charts**: requests / tokens / cost / cost per request / latency / TTFB / success rate / cache hit rate. Derived metrics are `sum ÷ sum`, no samples render as `—` (gap) not 0; latency and TTFB also get a percentile chart (P50 + P95 from details, 45 days only). The time axis is filled hourly. Out-of-domain `metric` is an explicit 400; an invalid custom range pauses fetching.
- **Compression gains panel**: trigger counts (tool output / context trimming), characters and tokens saved (lower-bound estimate), the concurrent prefix-cache hit rate, and both compression switches, on one screen. Savings must be read next to the cache cost, otherwise "keep it on or turn it off" is unanswerable; `GET /api/stats/compression?since=&until=` (operator+, hourly buckets summed over the same window as the overview; omit both ends for the lifetime total). Hourly buckets and lifetime totals are persisted to `DATA_DIR/compress_buckets.json` (60s throttle, flushed on shutdown), surviving restarts for 45 days.

### Credits and check-in records

- **Change ledger** (arrow after the quota figure) = **net change between two quota probes**, not per-action attribution (check-in, growth and chat all move the balance and upstream logs nothing → the UI says "net change"). The first probe only establishes a baseline; unchanged balances are not recorded; a change to "unknown" is recorded without a delta; retained 90 days.
- **Change ledger** (arrow after the quota figure) = **net change between two quota probes**, not per-action attribution (check-in, growth and chat all move the balance and upstream logs nothing → the UI says "net change"). The first probe only establishes a baseline; unchanged balances are not recorded; a change to "unknown" is recorded without a delta; retained 45 days (`RETENTION_DAYS`).
- **Split by ledger**: entries carry `ledger` (`pool` / `credits`); CodeArts and Raccoon use `credits` (both are credit-based), everything else `pool`. `GET /api/credentials/{id}/credit-events?ledger=`.
- **Check-in records** (*More → Check-in records*) = the check-in audit log, one row per round (time / result / credits claimed / upstream business code / message / trigger), retained 90 days; `GET /api/credentials/{id}/checkin-events?limit=`. This is the **per-action result**, independent of balance diffs, so "shows success but no credits" can be checked directly against the upstream reply.
- **Check-in records** (*More → Check-in records*) = the check-in audit log, one row per round (time / result / credits claimed / upstream business code / message / trigger), retained 45 days (`RETENTION_DAYS`); `GET /api/credentials/{id}/checkin-events?limit=`. This is the **per-action result**, independent of balance diffs, so "shows success but no credits" can be checked directly against the upstream reply.
- **Availability timeline** (*credential detail → View timeline*) = history of state transitions (cooldown start / cooldown end / hard failure / revived / enabled / disabled), each row carrying the model (for model-level cooldowns), a redacted reason, a readable detail and the triggering request ID; `GET /api/credentials/{id}/timeline?since=&until=&limit=` (operator+), retained 30 days. Complements the **current state** in `credential_model_cooldowns`: answering "why was this credential unavailable at 14:00 yesterday" no longer requires digging through server logs.
- **Today's check-in summary**: `GET /api/credentials` attaches `checkin_today` (the latest entry for today from the local audit log, `null` if none). `null` means "no conclusion yet" (task not due / paused / channel has no check-in), not failure.

### Grouping

Four tabs (channel / model / user / credential) sharing one table (channel / requests / credit / cost / tokens / speed / average latency / P95 latency), endpoints `GET /api/stats/by-provider|by-model|by-user|by-credential`. **Latency percentiles P50 / P90 / P95 / P99** (default P95, nearest-rank). User / credential dimensions are admin / operator only.

- **Scope differences**: channel / model / user read hourly rollups (permanent, last 5 minutes not yet included); credentials read the detail table (90 days only).
- **Latency**: successful requests only. Average = `latency_sum ÷ successes`; percentiles come from details (90 days). Rows with `ttfb_ms = NULL` are ranked independently.
- **Scope differences**: channel / model / user read hourly rollups (permanent, last 5 minutes not yet included); credentials read the detail table (45 days only).
- **Latency**: successful requests only. Average = `latency_sum ÷ successes`; percentiles come from details (45 days). Rows with `ttfb_ms = NULL` are ranked independently.
- **Failure attribution** (`GET /api/stats/errors`, operator+): aggregates `ok=0` by `(channel, model, error type)`, returning failures / **unrecovered** / latest failure (desc, `limit` ≤5000). **Row policy**: hard failures (`credential_unavailable` / `account_restricted` / `invalid_request` / `model_capability`) write one row per attempt; other categories write one closing row per request. A successful row for the same user and `request_id` counts as recovered. Special cases: a 401 becomes `credential_unavailable`, **but when quota exhaustion is proven** (officeace `401 APIG.1009`) it is reclassified as `CREDIT` (cooldown to 04:00 next day, no hard disable); `11140` → `account_restricted` (2h account cooldown; a channel-wide backoff only when every credential on that channel is hit within 10 minutes); `11102` / `11158` → `model_not_found` (negative cache, no account cooldown); `11115` → `context_overflow` and `001001020` → `model_capability` (no credential penalty); `001001044` → `invalid_request`. When no credential was selected the row names the **candidate channel**. Full taxonomy and cooldown durations: TECHNICAL.md §3.2.
- **Drill-down**: clicking a group row filters details by it, conditions stack; `GET /api/stats/events` accepts `provider` / `model` / `credential_id` (AND) plus `ok=0`.
- **Merged columns**: tokens, latency, speed, channel / credential are each one column, expandable on hover; the merged header offers a sub-column sort (`sort=cache_rate` / `tps_visible` / `tps` / `provider` / `credential`).
Expand Down Expand Up @@ -539,7 +539,7 @@ Nine rules feed `alert_events` (`/alerts`, admin only):
- **Silence window**: one DB row / push per `(rule, object)` per window.
- **Hysteresis**: alert after N consecutive hits, resolve after M consecutive misses; resolving stamps `resolved_at` on all open rows for that `(rule, object)` and emits a `status="resolved"` webhook.
- **Multiple sinks**: generic webhook (full JSON + signature), Feishu bot and Slack incoming webhook may be configured together; one failing does not block the others but marks delivery as failed overall.
- **Self-healing**: hysteresis counters live in-process, "which alerts are open" is rebuilt from the DB. Manual *Mark resolved* needs admin + CSRF + audit. Retention matches details (90 days).
- **Self-healing**: hysteresis counters live in-process, "which alerts are open" is rebuilt from the DB. Manual *Mark resolved* needs admin + CSRF + audit. Retention matches details (`RETENTION_DAYS`, 45 days).

### Backup and restore

Expand Down
16 changes: 16 additions & 0 deletions tests/test_readme_retention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""README 口径防回归:保留期必须是 45 天(`RETENTION_DAYS` 默认值),不得回退到 90 天。"""

from pathlib import Path

README_EN = Path(__file__).resolve().parents[1] / "README.en.md"


def test_readme_en_has_no_stale_90_day_retention() -> None:
text = README_EN.read_text(encoding="utf-8")
assert "90 days" not in text


def test_readme_en_states_45_day_retention_with_config_key() -> None:
text = README_EN.read_text(encoding="utf-8")
assert "45 days" in text
assert "RETENTION_DAYS" in text