diff --git a/Dockerfile b/Dockerfile index 02f5130..3094f71 100644 --- a/Dockerfile +++ b/Dockerfile @@ -84,8 +84,9 @@ COPY deploy/data-seed/ /usr/local/nginx/data/ # 与旧版保持一致的工作目录约定,便于沿用现成的挂载与运维习惯 # data 必须对 worker(默认 nobody)可写:状态写穿 JSON 依赖它 -RUN mkdir -p /usr/local/nginx/conf /usr/local/nginx/www /usr/local/nginx/data /usr/local/nginx/logs \ - && chown -R nobody:nogroup /usr/local/nginx/data \ +# audit 同理:LLM 对话审计落盘目录(docs/llm/AUDIT_LOG.md),生产建议挂宿主机卷 +RUN mkdir -p /usr/local/nginx/conf /usr/local/nginx/www /usr/local/nginx/data /usr/local/nginx/audit /usr/local/nginx/logs \ + && chown -R nobody:nogroup /usr/local/nginx/data /usr/local/nginx/audit \ && ln -sf /dev/stdout /usr/local/nginx/logs/access.log \ && ln -sf /dev/stderr /usr/local/nginx/logs/error.log diff --git a/conf/nginx.conf b/conf/nginx.conf index 72c9e23..fc02b43 100644 --- a/conf/nginx.conf +++ b/conf/nginx.conf @@ -121,6 +121,12 @@ http { # access 阶段:查 ukey: 鉴权 → 查 up: 校验上游 → 校验白名单 ipass_llm on; + # 对话审计(docs/llm/AUDIT_LOG.md):强制请求体落临时文件,log 阶段 + # 由模块复制进审计目录(audit/)。不落盘的话,大请求体只存在于 + # 内存缓冲链里,请求结束即释放,事后无从审计。代价 = 每个转发请求 + # 多一次磁盘写(含 2KB 的小请求);审计是旁路功能,写失败不影响转发。 + client_body_in_file_only clean; + # 变量形式的上游。$llm_target 由模块算出,已含 path 与 query # (变量形式不会自动追加原始 args,所以 query 必须由模块拼好) proxy_pass $llm_target; @@ -177,9 +183,14 @@ http { # 置空才能与上游复用长连接(这是 API 调用,不是 WebSocket) proxy_set_header Connection ""; - # —— SSE 三件套:缺一条,流式就会退化成「攒完一次性返回」—— + # —— SSE 流式两件套(只作用于**响应**方向)—— + # proxy_buffering off = 上游 chunk 边到边发(SSE 的生命线); + # proxy_cache off = 不缓存响应。 + # ⚠️ **不再**开 proxy_request_buffering off:它管的是**请求体**方向, + # 与响应流式无关;而它与对话审计的 client_body_in_file_only 互斥 + # (no_buffering 模式 body 全程流式推给上游,nginx 不落临时文件, + # 实测踩过:审计文件永远不出现)。请求体是小 JSON,缓冲上传零损失。 proxy_buffering off; - proxy_request_buffering off; proxy_cache off; chunked_transfer_encoding on; diff --git a/deploy/compose.yml b/deploy/compose.yml index ef9c1c4..6238305 100644 --- a/deploy/compose.yml +++ b/deploy/compose.yml @@ -9,6 +9,8 @@ # docker compose -f compose.yml up -d # # 数据持久化在宿主机 /opt/ipass/data,容器随便删重建,状态不丢。 +# 审计日志同理挂 /opt/ipass/audit(LLM 对话审计,docs/llm/AUDIT_LOG.md): +# mkdir -p /opt/ipass/audit && chown 65534:65534 /opt/ipass/audit # 升级镜像:load 新 tar 后 `docker compose -f compose.yml up -d --force-recreate`。 services: gateway: @@ -19,4 +21,5 @@ services: # - "80:80" # 如需 *.yourdomain.com 明文转发再放开 volumes: - /opt/ipass/data:/usr/local/nginx/data + - /opt/ipass/audit:/usr/local/nginx/audit restart: always diff --git a/deploy/ipass-agent.py b/deploy/ipass-agent.py index 869e74b..0ca76e6 100644 --- a/deploy/ipass-agent.py +++ b/deploy/ipass-agent.py @@ -89,6 +89,8 @@ DEFAULT_IMAGE = ("crpi-yscq976uwza88qap.cn-shenzhen.personal.cr.aliyuncs.com/" DEFAULT_CONTAINER = "ipass" CONTAINER_DATA = "/usr/local/nginx/data" # 容器内数据目录 +CONTAINER_AUDIT = "/usr/local/nginx/audit" # 容器内审计目录(= data 的兄弟目录, + # 宿主侧跟随数据目录推导:…/ipass/audit) MAIN_CPORT = "18098" # 容器内主端口(宿主映射到它) NGINX_BIN = "/usr/local/nginx/sbin/nginx" ADMIN_HOST = "mdm.mayishangshu.cn" # 探活用的 Host 头 @@ -349,6 +351,10 @@ def extract_mounts(cfg): if dest == CONTAINER_DATA: data_src = m.get("Source") or m.get("Name") continue + if dest == CONTAINER_AUDIT: + # 审计挂载不进 extra:每次重建都从数据目录**重新推导**(见 do_update), + # 避免旧容器的审计挂载与新推导的重复 → 「mount point already mounted」 + continue if m.get("Type") == "volume": spec = "%s:%s" % (m.get("Name"), dest) else: @@ -645,6 +651,16 @@ def op_update(job, p): argv += ["--restart", restart] argv += port_args argv += ["-v", "%s:%s" % (data_src, CONTAINER_DATA)] + # 审计挂载:宿主侧 = 数据目录的兄弟目录 audit/(docs/llm/AUDIT_LOG.md)。 + # 容器重建不丢审计档案;目录不存在就先建(属主 nobody 由镜像内 mkdir 兜底, + # 宿主侧首建后 Docker 会继承容器内属主——首次写入前手动 chown 一次更稳)。 + try: + audit_src = os.path.join(os.path.dirname(data_src.rstrip("/")), "audit") + os.makedirs(audit_src, exist_ok=True) + argv += ["-v", "%s:%s" % (audit_src, CONTAINER_AUDIT)] + jlog(job, " 审计目录 %s -> %s" % (audit_src, CONTAINER_AUDIT)) + except OSError as e: + jlog(job, " ! 审计目录建不了(%s),本容器不带审计挂载" % e) argv += extra_mounts for e in envs: argv += ["-e", e] @@ -675,6 +691,11 @@ def op_update(job, p): jlog(job, " worker(nobody) 数据目录可写:%s" % ("是" if writable else "否 !!")) if not writable: jlog(job, " ! 不可写 → 改账号/域名会静默失败,检查 %s 属主" % data_src) + # 审计目录可写(审计是旁路功能:不可写只降级、不阻断转发) + wtest_a = "[ -w {d} ] && echo WRITABLE || echo NOT_WRITABLE".format(d=CONTAINER_AUDIT) + rc, out = docker(["exec", "-u", "nobody", name, "sh", "-c", wtest_a]) + jlog(job, " worker(nobody) 审计目录可写:%s" + % ("是" if "WRITABLE" in out else "否(审计功能将停用)")) # ---- 7 数据 + 宿主探活 jlog(job, "\n7/7 数据与探活") diff --git a/deploy/update-agent-face.sh b/deploy/update-agent-face.sh new file mode 100755 index 0000000..025474e --- /dev/null +++ b/deploy/update-agent-face.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +# ============================================================================= +# iPass 控制面自更新(在 .11 上执行) +# +# 干的事:从 Gitea 下载新版 ipass-agent.py → 备份旧版 → 语法校验 → +# 停旧控制面 → 按原参数重启 → /health 自检 +# +# 用法(在 .11 上、用跑控制面的那个账号): +# bash <(curl -fsSL http://192.168.1.18:13300/ssw/ipass/raw/branch/main/deploy/update-agent-face.sh) +# 或分两步: +# curl -fsSL http://192.168.1.18:13300/ssw/ipass/raw/branch/main/deploy/update-agent-face.sh -o /tmp/uaf.sh +# bash /tmp/uaf.sh +# +# 安全性: +# - 只动控制面进程(python3 ipass-agent.py),网关容器不受任何影响 +# - 旧脚本备份为 <路径>.bak-<时间戳>,随时可拷回原位 + 重跑本脚本回退 +# - token 存 ~/.ipass-agent-token,重启沿用 → 远端 agent.sh 无需改任何配置 +# ============================================================================= +set -euo pipefail + +RAW_BASE="http://192.168.1.18:13300/ssw/ipass/raw" +# 主/备两种 Gitea raw 路径形态(不同版本分支写法不同,逐个试) +RAW_PATHS=( + "$RAW_BASE/branch/main/deploy/ipass-agent.py" + "$RAW_BASE/refs/heads/main/deploy/ipass-agent.py" +) + +c_ok() { printf '\033[32m✓\033[0m %s\n' "$*"; } +c_err() { printf '\033[31m✗\033[0m %s\n' "$*" >&2; } +c_warn(){ printf '\033[33m!\033[0m %s\n' "$*"; } +step() { printf '\n\033[36m==> %s\033[0m\n' "$*"; } + +# ---------------------------------------------------------------- 1. 定位现有控制面 +step "1/6 定位控制面脚本" +DEST="" +OLD_ARGS="" +# 优先:从正在跑的进程反推(最准,还能原样保留启动参数) +for pid in $(pgrep -f "ipass-agent.py" 2>/dev/null || true); do + cmd="$(tr '\0' ' ' <"/proc/$pid/cmdline" 2>/dev/null || true)" + case "$cmd" in + *--stop*) continue ;; # 排除恰好同名的一次性调用 + esac + # cmdline 形如 "python3 /path/ipass-agent.py --bg --name ipass ..." + set -- $cmd + shift # 去掉解释器 + [ "${1:-}" = "python" ] || [ "${1:-}" = "python3" ] && shift + cand="${1:-}" + [ -f "$cand" ] && DEST="$cand" + # 保留除 --bg / --stop 外的启动参数,重启时原样带上 + shift + for a in "$@"; do + case "$a" in --bg|--stop) ;; *) OLD_ARGS="$OLD_ARGS $a" ;; esac + done + break +done +# 兜底:常见位置 +if [ -z "$DEST" ]; then + for cand in "$HOME/ipass/ipass-agent.py" "$HOME/ipass-agent.py"; do + [ -f "$cand" ] && DEST="$cand" && break + done +fi +if [ -z "$DEST" ]; then + c_warn "没找到正在跑的控制面,按约定装到 ~/ipass/ipass-agent.py(首次部署)" + mkdir -p "$HOME/ipass" + DEST="$HOME/ipass/ipass-agent.py" +fi +c_ok "目标: $DEST${OLD_ARGS:+(原启动参数:$OLD_ARGS)}" + +# ---------------------------------------------------------------- 2. 备份 +step "2/6 备份旧版" +TS="$(date +%Y%m%d-%H%M%S)" +if [ -f "$DEST" ]; then + cp "$DEST" "$DEST.bak-$TS" + c_ok "已备份 → $DEST.bak-$TS" +else + c_warn "原文件不存在,跳过备份" +fi + +# ---------------------------------------------------------------- 3. 下载新版 +step "3/6 下载新版 ipass-agent.py" +TMP="$(mktemp /tmp/ipass-agent.XXXXXX.py)" +GOT="" +for url in "${RAW_PATHS[@]}"; do + if curl -fsSL --connect-timeout 5 -m 30 "$url" -o "$TMP" 2>/dev/null; then + GOT="$url"; break + fi +done +if [ -z "$GOT" ] || ! grep -q "ipass-agent" "$TMP" || ! grep -q "def " "$TMP"; then + c_err "下载失败或内容不对(Gitea: 192.168.1.18:13300 不可达?)" + c_err "手动方式:scp 本仓库 deploy/ipass-agent.py 到 $DEST 后重跑本脚本" + rm -f "$TMP"; exit 1 +fi +c_ok "已下载 ← ${GOT#*$RAW_BASE/} ($(wc -c <"$TMP") 字节)" + +# ---------------------------------------------------------------- 4. 语法校验 +step "4/6 语法校验" +if ! python3 -m py_compile "$TMP" 2>/tmp/ipass-agent-pycompile.err; then + c_err "新版脚本 py_compile 不通过,已中止(旧版未动):" + sed 's/^/ /' /tmp/ipass-agent-pycompile.err >&2 + rm -f "$TMP"; exit 1 +fi +mv "$TMP" "$DEST" +c_ok "已替换 $DEST" + +# ---------------------------------------------------------------- 5. 重启 +step "5/6 重启控制面" +python3 "$DEST" --stop >/dev/null 2>&1 || true +sleep 1 +# shellcheck disable=SC2086 +python3 "$DEST" --bg$OLD_ARGS +sleep 2 + +# ---------------------------------------------------------------- 6. 自检 +step "6/6 自检" +OK="" +for _ in $(seq 1 10); do + if curl -sf -m 3 http://127.0.0.1:18099/health -o /tmp/ipass-agent-health.json 2>/dev/null; then + OK=1; break + fi + sleep 1 +done +if [ -n "$OK" ]; then + c_ok "控制面已就绪: $(cat /tmp/ipass-agent-health.json)" + printf '\n下一步(远端/本机任意一处):\n' + printf ' bash deploy/agent.sh update ipass-1.0.7 # 新容器将自动挂审计卷\n' +else + c_err "10 秒未就绪,查日志: tail -50 ~/ipass-agent.log" + exit 1 +fi diff --git a/docs/llm/STREAMING_USAGE.md b/docs/llm/STREAMING_USAGE.md new file mode 100644 index 0000000..57178c2 --- /dev/null +++ b/docs/llm/STREAMING_USAGE.md @@ -0,0 +1,317 @@ +# 流式响应下的 token 级用量统计 —— 调研与方案 + +> **写作动机**:`stats.rs` 模块头注释里有句"为什么不 token 级"—— +> "上游响应体里才有 usage,SSE 必须关缓冲透传,网关不缓冲就解析不到"。 +> 这句当时拍板是**对的**,但**只列了死路**没列活路。本文档把"活路"补齐, +> 对比开源做法、给出我们能落地的 5 档方案与推荐路线。 +> +> **关联文档**:`docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md`(出站头 / 多协议)、 +> `rust/src/stats.rs`(当前请求级计数实现)、`rust/src/config.rs` §LLM 限流。 +> **最后更新**:2026-09-12(基于 ipass-1.0.6)。 + +--- + +## 0. 结论先放出来 + +| 方案 | 改动代价 | 流式是否破坏 | 精度 | 推荐阶段 | +|---|---|---|---|---| +| **当前**:请求级 `ust:`/`ums:` | 0 | 否 | 低(请求数) | P0 保留 ✅ | +| **A** 自建 C body filter 抓 usage | 中(一个独立 .so) | 否(链尾 + busy chain 副本) | 高 | P2 推荐 | +| **B** access 阶段预扣 prompt_tokens | 中(破 access 不读 body) | 否 | 中(只 prompt) | P1 推荐 | +| **C** A+B reconcile | 高 | 否 | 高 | P3 | +| **D** Rust 模块自建 upstream 重写转发 | **极高**(重做 proxy_pass) | **是** | 高 | **否决** | +| **E** 客户端协议约定(让客户端带 `include_usage`) | 0 | 否 | 看客户端配合度 | P1 辅助 | + +**推荐路线**:P0(现状)→ P1(方案 B 起步,只对 OpenAI 系)→ P2(方案 A 抓真实 usage)→ P3(A+B reconcile 调账)。**不要做方案 D**。 + +--- + +## 1. 流式场景的核心矛盾 + +SSE 三个流式要件(`conf/nginx.conf` L181-184): +```nginx +proxy_buffering off; # 1. 不缓冲响应 +proxy_request_buffering off; # 2. 不缓冲请求 +chunked_transfer_encoding on; # 3. 分块传输 +``` +**关掉缓冲的根本理由**:上游产一个字就推一个字,客户端打字机式渲染,关缓冲后首字节延迟从「分钟级」降到「亚秒级」(参考 [sse-protocol-fundamentals-architecture/proxy-and-cdn-configuration-for-sse](http://www.server-sent-events.com/sse-protocol-fundamentals-architecture/proxy-and-cdn-configuration-for-sse))。 + +**副作用**:网关拿不到完整响应体,**`usage` 字段在最后一个 chunk 里**(OpenAI `chat.completion.chunk`,Anthropic `message_delta`/`message_stop`),我们看不到。**这是"流式 vs 统计"的根本矛盾**——不是工程问题,是协议问题。 + +--- + +## 2. 开源对照表(行扫描 / 双消费 / 异步镜像) + +### 2.1 one-api / new-api(Go):**行扫描 + 主从 channel** +源:[`relay/channel/openai/main.go::StreamHandler`](https://gitee.com/Cavalier/one-api/blob/main/relay/channel/openai/main.go)。关键代码(删节): +```go +scanner := bufio.NewScanner(resp.Body) +scanner.Split(/* 按 '\n' 切 */) +dataChan := make(chan string) +var usage *model.Usage +go func() { // ① 后台 goroutine:解析 + for scanner.Scan() { + data := scanner.Text() + if data[:6] != "data: " && data[:6] != "[DONE]" { continue } + dataChan <- data // 把每行喂给前端 + if !strings.HasPrefix(data, "[DONE]") { + var streamResponse ChatCompletionsStreamResponse + json.Unmarshal([]byte(data[6:]), &streamResponse) + if streamResponse.Usage != nil { + usage = streamResponse.Usage // ② 抓到 usage + } + } + } + stopChan <- true +}() +c.Stream(func(w io.Writer) bool { // ③ 前台 c.Stream:边收边 Render 给客户端 + select { + case data := <-dataChan: + c.Render(-1, common.CustomEvent{Data: data}) + return true + case <-stopChan: return false + } +}) +``` +**核心模式**:**主链路零阻塞**,旁路 goroutine 解析 SSE 行;`usage` 一旦出现就更新引用;流结束(`[DONE]` 或 `scanner.Scan()==false`)时把 `usage` 写库。 + +**new-api 的扩展**:[`service/token_counter.go`](https://ithub.global.ssl.fastly.net/x01n/new-api/blob/main/70ea899e373e487ffa550e068800db769e30ba1c/service/token_counter.go) 加了 `tiktoken-go` —— **请求发出前**用 tokenizer 估算 `prompt_tokens` 预扣配额,**响应到达后**用真实 `usage` 调账(reconcile)。**这是最完整的范式**。 + +### 2.2 LiteLLM(Python):**CustomStreamWrapper + async logging** +源:[CustomStreamWrapper](https://deepwiki.com/inject-lib/litellm/2.2-streaming-responses) + [pass_through_cost_tracking](https://litellm.vercel.app/docs/proxy/pass_through_cost_tracking)。 +- 主 SDK 返回 `CustomStreamWrapper`(包装 httpx 流),迭代产生 `ModelResponse` +- 异步 logging loop 在 `logging_loop()` 里跑,**不影响迭代** +- `stream_options={"include_usage": true}` 是**客户端约定** —— 让上游把 usage 放进最后一个 chunk + +**关键承认**(来自 LiteLLM 文档原文): +> "Streaming targets work, because response headers arrive before the body. A target that only knows its final cost after it has finished streaming cannot report it through this contract, since by then the headers are already on the wire." + +—— LiteLLM 自己的 pass-through 也承认:**纯流式场景无法靠响应头拿 cost**。我们的处境一样。 + +### 2.3 Portkey(Node/TS):**OpenTelemetry 异步镜像** +源:[LogsService](https://deepwiki.com/Portkey-AI/gateway/5.2-metrics-and-tracing-integrations) + [OTEL logs](https://portkey.ai/docs/product/enterprise-offering/otel/complete-logs)。 +- **完全异步**:用 `HooksService` + `LogsService` 在请求生命周期各阶段打点 +- 完成后把 LogObject 打包成 OTel span 推给 collector +- **主链路零依赖**:OTel collector 挂了不影响转发 +- **代价**:每个请求都有 OTel 序列化开销(Portkey 把它做成可关闭的实验特性) + +### 2.4 Higress(Go Wasm plugin):**Wasm body filter** +阿里 Higress 的 LLM 插件(`plugins/wasm-go/extensions/ai-content-copilot` 等)走的是 **Wasm body filter**: +- 在 response body filter 阶段把 buf 拷一份解析 +- 把解析结果通过 host function 调回 Go 主进程 +- **限制**:host function 调 Go 是**同步阻塞**的,所以不能每 chunk 调一次 —— **必须在 `last_buf` 一次性调** +- **仍是 buf 副本**,不破坏主链路 + +### 2.5 经典 nginx body filter(`ngx_http_sub_filter_module`):**busy/free chain** +源:[`src/http/modules/ngx_http_sub_filter_module.c`](https://github.com/nginx/nginx/blob/master/src/http/modules/ngx_http_sub_filter_module.c)。这是 nginx 内置 `sub_filter` 的实现,**所有想做"旁路拿到响应"的 C 模块都参考它**: +- 维护 **busy chain**(正在被下家消费的 buf)与 **free chain**(已消费完的 buf) +- `body_filter` 拿到 `in` chain(来自上游)后:① 调 `ngx_http_next_body_filter(r, in)` 把同一份 buf 透传给下家;② 把 buf 入 busy chain 备用 +- **关键**:buf 是 nginx-alloc 的,**复用**由下家消费后调 `ngx_chain_update_chains` 回收 +- 主链路延迟 = 0 + +--- + +## 3. 我们的硬约束 vs 各方案的兼容性 + +### 3.1 红线(节选自 `CLAUDE.md`) + +| 红线 | 影响 | +|---|---| +| 单容器零依赖(vanilla nginx + Rust 动态模块) | **不引入** Redis/MQ/独立进程 | +| `rust/` 是唯一 Rust 真源(vendor 全部走 path 依赖) | **多文件** Rust 模块没问题(已在多个 .rs) | +| shm 是运行期真源;`data/*.json` 只是持久化副本 | 用量统计必须写 shm(已有 `ust:`/`ums:`) | +| access 阶段**不读请求体**(`upstreams` 模块头注释) | 方案 B 破坏,需要用户拍板 | +| 不用代理传 JSON `model` 字段(路由靠 URL slot) | 方案 B 估 tokenizer 时**也读不到 model** —— 这是额外问题 | + +### 3.2 现状代码定位 + +- **请求级计数点**:`rust/src/lib.rs:308` —— `stats::record(&username, &slot, util::now())`,在 access 阶段、所有放行检查都通过之后 +- **响应路径**:access 阶段返 `Status::NGX_DECLINED` 让 nginx 原生 `proxy_pass` 走完转发 —— 我们**没有** body filter 钩子(ngx-rust vendor 没暴露 `ngx_http_top_body_filter`) +- **shm 编码**:见 `rust/src/stats.rs:84` `:::` —— **新增字段**只需扩字段位(要改 `encode`/`decode` 协议) + +### 3.3 ngx-rust 现状对方案的影响 + +`vendor/ngx-rust/src/http/request.rs:360` 只有**调用** filter 链的 `output_filter()`,**没有让我们成为 filter 一环的钩子**。也就是说: + +- **方案 A(独立 C body filter)** ✅ 完整可行 —— C 模块直接调 `ngx_http_top_body_filter`,与 ngx-rust 互不干涉 +- **方案 D(Rust 自建 upstream)** ⚠️ ngx-rust 没暴露 `ngx_http_upstream_t::conf->output_filter`,要做就得绕过整个 proxy 模块 → 否决 + +--- + +## 4. 五档方案详解 + +### 4.1 方案 A:C body filter 抓 usage(推荐 P2) + +**做法**:新增一个独立 C 动态模块 `libngx_ipass_usage.so`,与 `libipass_gateway.so` 同容器同 nginx 实例: + +```nginx +load_module /usr/local/nginx/modules/libngx_gateway.so; +load_module /usr/local/nginx/modules/libngx_usage.so; # 新增 +``` + +模块逻辑(伪代码): +```c +static ngx_int_t +ipass_usage_body_filter(ngx_http_request_t *r, ngx_chain_t *in) +{ + ngx_chain_t *cl; + for (cl = in; cl; cl = cl->next) { + ngx_buf_t *b = cl->buf; + if (b->last_buf) { + // 主链路先送客户端 + ngx_http_next_body_filter(r, in); + // 旁路:把 busy chain 上的字节拼起来 + char *full = ngx_pnalloc(r->pool, total_size); + // ... 拼字节流到 full ... + // 调 Rust FFI:ipass_usage_record(username, slot, full) + // Rust 端走 serde_json 解析 "usage" 字段 → 写 ust:tk: / ums:tk:: + return NGX_OK; + } + // 主链路照常送 + } + return ngx_http_next_body_filter(r, in); +} +``` + +**关键点**: +- 注册位置 `HTTP_AUX_FILTER_MODULES`(在 gzip 之后、write 之前)—— 不能注册太前,否则被 gzip 的边界切碎;不能太后,否则 write 阶段已经写完 socket +- `busy chain` 模式参照 `ngx_http_sub_filter_module.c::ngx_http_sub_output` —— buf 复用省分配 +- 解析失败(不是 SSE / 缺 usage 字段)→ 静默丢弃,**绝不阻塞主链路** + +**代价**: +- C 代码 + nginx 编译流水线(conf/tls/ 那套已经成熟,但新增模块要走 `auto/module`) +- shm 写入走 C→Rust FFI(状态键已经存在,FFI 函数声明在 lib.rs) + +**不破坏流式**:buf 是**同一份**,nginx `output_filter` 透传给客户端,**字节进 socket 的时机不变**。只是多了一份"进 buf 时顺便看一眼"的 CPU 工作。 + +### 4.2 方案 B:access 阶段预扣 prompt_tokens(推荐 P1 起步) + +**做法**:access 阶段读完**全部**请求体(或仅读前 N 字节)→ 解析 messages → 用 tokenizer 估算 prompt_tokens → 预扣配额。 + +```rust +// 伪代码 +fn on_access_llm(r: &mut Request) -> Status { + // ... 已有鉴权/白名单 ... + // 新增:读请求体(小请求在内存里、大请求分块读完) + let body = http::read_full_body(r)?; + let v: serde_json::Value = serde_json::from_slice(&body)?; + let model = v["model"].as_str().unwrap_or(""); + let messages = v["messages"].as_array().map(|a| a.len()).unwrap_or(0); + let est = tiktoken::estimate(model, &v)?; // tiktoken-rs 或字符近似 + quota::pre_consume(&username, &slot, est.prompt); + // ... 已有 stats::record ... + Status::NGX_DECLINED +} +``` + +**关键难点**: +1. **access 阶段不读 body** 是已有硬约束(`upstreams.rs` 头注释)—— 多模态请求体可达 100MB,全部读完决策会破坏 SSE 首字节 +2. **model 字段在 body 里**,**但路由靠 URL slot** —— 用 slot 对应的"厂商默认 tokenizer" 估精度差 +3. **completion_tokens 估不出来**(要等响应),所以只能"上限保护" + +**折中**:只对 OpenAI 系(gpt-4/o1/o3/o4 系)做预扣(用 `tiktoken-rs`),其他厂商降级为"请求级"。 + +**代价**:access 阶段读 body = **打破硬约束**。需要用户拍板。 + +### 4.3 方案 C:A+B reconcile(推荐 P3) + +new-api 模式:方案 B 在请求前预扣(防超限),方案 A 在响应后用真实 usage 调账(精确扣费)。 + +``` +请求进入 → B 预扣 max(prompt_tokens, daily_remaining) → 转发 + ↓ + 用量键:pre_deducted:pts: = 估的数 + ↓ +上游响应 → A 抓真实 usage + ↓ +调账:ust:tk: += 真实 prompt + completion + ↓ + 若 pre_deducted > 真实 → 释放差额回配额 + 若 pre_deducted < 真实 → 从配额里再扣(极少见,预扣有上浮 buffer) +``` + +**代价**:P1+P2 全做,复杂度叠加。**留到 P3**。 + +### 4.4 方案 D:Rust 自建 upstream(**否决**) + +**做法**:模块里用 hyper/ureq 起 upstream 请求,完全不依赖 nginx proxy_pass。 + +**否决理由**: +1. 重做整个转发栈:TLS / SNI / keepalive / 超时 / 错误页 / 大文件上传 / WebSocket —— 每个都是坑 +2. 与 nginx 原生 `proxy_pass` **撞车**:原生的连接池、错误页(`error_page 502 503 504 = /llm_error`)要全部弃用 +3. SSE 在 hyper 里也得自己实现 chunk 切割 + flush 调度 +4. **完全违反**"vanilla nginx + Rust 模块补强"的根本设计 + +### 4.5 方案 E:客户端协议约定(无侵入辅助) + +让客户端 SDK 主动带 `stream_options={"include_usage":true}`: +- OpenAI / Azure / DeepSeek / 大部分 OpenAI 兼容厂商都支持 +- Anthropic 系**不用**这个字段(usage 在 `message_delta`/`message_stop` 里默认就有) + +**做法**:把这条规则写进管理台"客户端接入文档",并由客户端主动汇报(不是网关解析)。**好处是零代码改动**;**代价是依赖客户端配合度**,且无法强制。 + +**位置**:作为 P1/P3 的**辅助手段**写文档即可。 + +--- + +## 5. 推荐路线(按时间顺序) + +### P0(已就绪)—— 请求级计数 + +`stats::record` 已经按"已放行的请求"计数,存 `ust:`/`ums:`。**保留现状**。 + +### P1(1-2 周)—— 方案 B 起步 + 方案 E 写文档 + +**两件事并行做**: +1. access 阶段读 body → tokenizer 估算 prompt_tokens → 写 `ust:pts:` / `ums:pts::`(**新增两个 shm 键**) +2. 管理台"客户端接入"页加一段:"建议在请求里加 `stream_options: {include_usage: true}`,这样精确度更高" + +**P1 接受的取舍**: +- 破坏 access 不读 body 的硬约束(**需用户拍板**) +- 只对 OpenAI 系做估算,其他厂商降级 +- 估不到 completion_tokens —— **只能"上限保护"** + +### P2(2-4 周)—— 方案 A 抓真实 usage + +新增 C 模块 `libngx_ipass_usage.so`: +- 注册到 `ngx_http_top_body_filter` 链尾(aux slot) +- 只对 `Content-Type: text/event-stream` 的响应启用(其他类型直接放行) +- 解析 SSE 行 → 找 `data: {"usage": {...}}` 最后一个 chunk → 调 Rust FFI → 写 `ust:tk:` / `ums:tk::` + +**新增 shm 键**(与现有 `ust:`/`ums:` 同前缀,value 多 1 字段): +- `ust:tk:` → `:::::::` +- `ums:tk::` → 同上 + +### P3 —— A+B reconcile + +按 new-api 模式:P1 的 pre_deducted 被 P2 的真实 usage 覆盖(差额回配额或再扣)。**这是精度最高的方案**,但要 P1+P2 都验证后再做。 + +--- + +## 6. 决策点(必须用户拍板) + +| 编号 | 决策 | 选项 | +|---|---|---| +| **D1** | 是否接受"多一个 .so" | A. 接受(推荐) / B. 否决(那 P2 无解) | +| **D2** | 是否接受"access 阶段读 body" | A. 接受(方案 B 才走得通) / B. 否决(方案 B 推后) | +| **D3** | P1 token 粒度 | A. 只统计总 token 数 / B. 拆 prompt + completion | +| **D4** | 优先级 | A. 先做 P1(方案 B) / B. 先做 P2(方案 A) | +| **D5** | 现有 `ust:`/`ums:` 计数(请求级) | A. 保留并行 / B. 替换 | + +**我的推荐组合**:D1=A, D2=A, D3=B, D4=B(先方案 A 后方案 B),D5=A。 + +--- + +## 7. 相关文件 / 引用 + +- 现状实现:`rust/src/stats.rs`、`rust/src/config.rs §KEY_UST_PREFIX/KEY_UMS_PREFIX` +- 调用点:`rust/src/lib.rs:308 stats::record` +- nginx 配置:`conf/nginx.conf` L181-184 SSE 三件套 +- 出站头策略:`docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md` +- 开源源码: + - one-api: + - new-api token_counter: + - LiteLLM pass-through: + - Portkey OTel logs: + - nginx body filter 官方: + - sub_filter 模块(busy/free chain 范式): `src/http/modules/ngx_http_sub_filter_module.c` \ No newline at end of file diff --git a/readme.md b/readme.md index 23c457e..2a45660 100755 --- a/readme.md +++ b/readme.md @@ -611,6 +611,16 @@ python3 ipass-agent.py --stop # 停止 tail -f ~/ipass-agent.log # 日志(pid 在 ~/ipass-agent.pid) ``` +**远程自更新(.11 上执行,改控制面不用人工拷文件)**: + +```bash +bash <(curl -fsSL http://192.168.1.18:13300/ssw/ipass/raw/branch/main/deploy/update-agent-face.sh) +``` + +脚本自动:从 Gitea raw 下载新版 → 备份旧版(`*.bak-<时间戳>`)→ `py_compile` 校验 → +`--stop` 停旧 → **按原启动参数** `--bg` 重启 → `/health` 自检。 +token 在 `~/.ipass-agent-token`,重启沿用,远端 `agent.sh` 无需改配置;全程不碰网关容器。 + - 单文件、**只用 Python 标准库**(不需要 Flask / requests),有 `python3` 就能跑。 - **鉴权**:除 `/health` 外全部要 `Authorization: Bearer `;token 首次启动随机生成并写入 `~/.ipass-agent-token`(权限 600),也可用 `--token` 或环境变量 `IPASS_AGENT_TOKEN` 指定。 diff --git a/rust/src/api.rs b/rust/src/api.rs index 09be643..5ce2c5f 100644 --- a/rust/src/api.rs +++ b/rust/src/api.rs @@ -823,6 +823,8 @@ fn h_my_usage(r: *mut ngx_http_request_t, actor: Actor) -> Status { let now = util::now(); let usage = stats::user(&user.username, now); + // token 计量(body filter 从上游 usage 抓的;抓不到 = 0,不补估) + let tin = stats::tokens_user(&user.username, now); let models: Vec = stats::user_models(&user.username, now) .into_iter() .map(|(slot, u)| { @@ -845,6 +847,7 @@ fn h_my_usage(r: *mut ngx_http_request_t, actor: Actor) -> Status { "total": usage.total, "last_ts": usage.last_ts, "last_ts_text": if usage.last_ts > 0 { util::fmt_time(usage.last_ts) } else { String::new() }, + "tokens": tin.json(), "models": models, // 限额一起回显:客户端可据此自我节流,不必等 429 "limits": { "rpm": user.llm_rpm, "daily": user.llm_daily }, diff --git a/rust/src/config.rs b/rust/src/config.rs index 08f9933..3497196 100644 --- a/rust/src/config.rs +++ b/rust/src/config.rs @@ -58,6 +58,18 @@ pub const LLM_DAILY_DEFAULT: i64 = 0; /// 默认状态目录,可被 `ipass_data_dir` 指令覆盖 pub const DEFAULT_DATA_DIR: &str = "/usr/local/nginx/data"; +// =========================================================================== +// LLM 对话审计(log 阶段旁路落盘,docs/llm/AUDIT_LOG.md) +// =========================================================================== + +/// 审计目录名:默认挂在 data 目录的**父目录**下(即与 data 同级),可被 +/// `ipass_audit_dir` 指令整体覆盖 +pub const AUDIT_DIR_NAME: &str = "audit"; +/// 审计总量上限(字节):超过即按日期目录从旧到新整目录删除,直到回落限内 +pub const AUDIT_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024; +/// 容量巡检最小间隔(秒):巡检要扫整个审计树,节流避免高频 IO +pub const AUDIT_PURGE_MIN_INTERVAL: i64 = 60; + // =========================================================================== // 共享内存键/值编码 // =========================================================================== @@ -99,6 +111,11 @@ pub const KEY_UST_PREFIX: &[u8] = b"ust:"; /// 键 = `ums::`(username 与 slot 都不含 `:`,切分安全), /// value 同 `ust:`。管理台的「每个模型用量」就是把这些键按 slot 聚合出来的。 pub const KEY_UMS_PREFIX: &[u8] = b"ums:"; + +/// LLM token 计量(body filter 从上游响应抓的 usage): +/// 账号维度 `utt:`,账号×上游维度 `utms::` +pub const KEY_UTT_PREFIX: &[u8] = b"utt:"; +pub const KEY_UTMS_PREFIX: &[u8] = b"utms:"; /// 键前缀:LLM **上游健康缓存**。键 = `uh:`, /// value = `<1|0> \n <上游状态码> \n <记录时刻>`。 /// diff --git a/rust/src/lib.rs b/rust/src/lib.rs index b487b62..9bfda2c 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -42,6 +42,8 @@ mod config; mod domains; mod http; mod llm; +mod llm_audit; +mod llm_usage; mod models; mod session; mod state; @@ -385,6 +387,47 @@ impl HttpRequestHandler for LlmHealthHandler { } } +/// LLM 对话审计(log 阶段):把被转发请求的 body 临时文件复制进审计目录。 +/// +/// 捕获机制与清理策略见 `llm_audit` 模块注释与 docs/llm/AUDIT_LOG.md。 +/// 关键点:只依赖 `client_body_in_file_only clean` 留下的临时文件,本阶段 +/// **不读请求体、不碰内存缓冲**——热路径与 SSE 透传完全无感知。 +struct AuditHandler; + +impl HttpRequestHandler for AuditHandler { + const PHASE: HttpPhase = HttpPhase::Log; + type Output = Status; + + fn handler(request: &mut ngx::http::Request) -> Self::Output { + if !Module::location_conf(request).map(|c| c.llm).unwrap_or(false) { + return Status::NGX_DECLINED; + } + + let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t; + + // 身份在 log 阶段重新解析:ukey shm 查询是纯内存读,代价可忽略; + // 换取 access→log 之间不挂任何请求级状态(无 ctx、无生命周期问题)。 + // 请求已被转发过(有临时文件)才查得到 Key——被拒请求天然不入档。 + let user = llm::downstream_key(r) + .and_then(|k| llm::identity(&k)) + .map(|(u, _, _, _)| u); + let slot = llm::slot_of(r).unwrap_or_default(); + + // token 计量:body filter 旁路抓到的 usage(见 llm_usage 模块注释) + let (tin, tout) = llm_usage::take(r); + if tin > 0 || tout > 0 { + if let Some(name) = user.as_deref() { + stats::add_tokens(name, &slot, tin, tout, util::now()); + } + } + + // SAFETY: 同上;capture 内部任何失败只记日志,绝不 panic + unsafe { llm_audit::capture(r, user.as_deref().unwrap_or("-"), &slot, tin, tout) }; + + Status::NGX_DECLINED + } +} + /// 管理 API:content 阶段先读请求体,读完后交给 `api::dispatch`。 /// /// 这是本项目唯一需要异步的地方。`ngx_http_read_client_request_body` 是 @@ -552,6 +595,11 @@ impl HttpModule for Module { if ngx::http::add_phase_handler::(cf).is_err() { return Status::NGX_ERROR.into(); } + if ngx::http::add_phase_handler::(cf).is_err() { + return Status::NGX_ERROR.into(); + } + // token 计量:插进 body filter 链头,旁路扫描上游响应的 usage + llm_usage::install(); if ngx::http::add_phase_handler::(cf).is_err() { return Status::NGX_ERROR.into(); } @@ -569,7 +617,7 @@ impl HttpModule for Module { } } -static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 6] = [ +static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 7] = [ ngx_command_t { name: ngx_string!("ipass_state"), type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, @@ -586,6 +634,14 @@ static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 6] = [ offset: 0, post: ptr::null_mut(), }, + ngx_command_t { + name: ngx_string!("ipass_audit_dir"), + type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(set_audit_dir), + conf: NGX_HTTP_MAIN_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, ngx_command_t { name: ngx_string!("ipass_proxy"), type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, @@ -648,6 +704,8 @@ unsafe extern "C" fn init_process(_cycle: *mut ngx_cycle_t) -> ngx_int_t { Ok(false) => {} Err(e) => util::log_err(&format!("[ipass] 初始化管理员失败: {e}")), } + // 对话审计:确保目录存在 + 容量巡检一次(此后由请求写入节流触发) + llm_audit::startup(); Status::NGX_OK.into() } @@ -783,6 +841,28 @@ extern "C" fn set_data_dir( } } +/// `ipass_audit_dir `:LLM 对话审计根目录。缺省 = data 目录的兄弟目录。 +extern "C" fn set_audit_dir( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + _conf: *mut c_void, +) -> *mut c_char { + // SAFETY: 配置回调必然拿到有效的 cf + let cf_ref = unsafe { cf.as_mut().unwrap() }; + let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() }; + + match core::str::from_utf8(args[1].as_bytes()) { + Ok(dir) => { + llm_audit::set_dir(dir); + NGX_CONF_OK + } + Err(_) => { + ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_audit_dir: 路径不是合法 UTF-8"); + NGX_CONF_ERROR + } + } +} + /// 供测试与诊断使用:`NgxStr` 类型在模块里被多处引用,确保编译期链接到正确的符号 #[allow(dead_code)] fn _type_witness(_: &NgxStr, _: &NgxString) {} diff --git a/rust/src/llm_audit.rs b/rust/src/llm_audit.rs new file mode 100644 index 0000000..0a9a1e5 --- /dev/null +++ b/rust/src/llm_audit.rs @@ -0,0 +1,200 @@ +//! LLM 对话审计:把每个**被转发**的 LLM 请求体落盘存档,供事后审计与用量复盘。 +//! +//! 设计要点(详见 docs/llm/AUDIT_LOG.md): +//! * **捕获方式**:LLM location 开 `client_body_in_file_only clean`,nginx 自己把 +//! 请求体刷到临时文件;本模块在 **log 阶段**(临时文件此刻尚未被清理)把它 +//! 复制进审计目录。热路径零改动——access 阶段不读体、不碰内存缓冲, +//! SSE 流式透传不受任何影响。被拒请求(401/403/404/429)与本地应答 +//! (/v1/models)的 body 从未被读走 → 没有临时文件 → 天然不入档。 +//! * **目录**:`<审计根>/YYYY-MM-DD/<毫秒>_.json` + 每目录一份 `meta.jsonl`。 +//! 审计根默认 = data 目录的兄弟目录 `audit/`(`ipass_audit_dir` 指令可覆盖)。 +//! * **清理**:按容量触发(`AUDIT_MAX_BYTES`)——写入后节流巡检 +//! (≥ `AUDIT_PURGE_MIN_INTERVAL` 秒一次、AtomicBool 单飞),超限时按日期 +//! 目录**从旧到新整目录删除**;worker 启动时强制巡检一次(不依赖外部 cron)。 +//! * **失败策略**:审计是旁路功能,任何失败只 `log_err`,绝不影响转发结果。 + +use std::fs; +use std::io::Write; +use std::path::PathBuf; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; + +use ngx::ffi::ngx_http_request_t; +use serde_json::json; + +use crate::config; +use crate::store; +use crate::util; + +/// `ipass_audit_dir` 覆盖值。配置阶段由 nginx 主线程设置一次,之后只读。 +static AUDIT_DIR_OVERRIDE: Mutex> = Mutex::new(None); + +/// 上次容量巡检时刻(秒);0 = 从未巡检。 +static LAST_PURGE_AT: AtomicI64 = AtomicI64::new(0); + +/// 巡检单飞标记:多 worker / 多请求并发时只放一个进去。 +static PURGING: AtomicBool = AtomicBool::new(false); + +/// 指令 `ipass_audit_dir `:显式指定审计根目录(缺省 = data 兄弟目录)。 +pub fn set_dir(dir: &str) { + if let Ok(mut slot) = AUDIT_DIR_OVERRIDE.lock() { + *slot = Some(dir.to_owned()); + } +} + +/// 审计根目录:显式指令优先,否则取 data 目录的兄弟目录。 +/// 每次现算(配置阶段后才可能被调用,store::data_dir() 已就绪)。 +fn root() -> PathBuf { + if let Ok(slot) = AUDIT_DIR_OVERRIDE.lock() { + if let Some(d) = slot.as_deref() { + return PathBuf::from(d); + } + } + PathBuf::from(store::data_dir()) + .parent() + .map(|p| p.join(config::AUDIT_DIR_NAME)) + .unwrap_or_else(|| PathBuf::from(config::AUDIT_DIR_NAME)) +} + +/// worker 启动:确保审计目录存在 + 强制巡检一次容量。 +/// 失败只降级(审计停用 / 跳过本次巡检),绝不阻塞 worker 启动。 +pub fn startup() { + let r = root(); + if let Err(e) = fs::create_dir_all(&r) { + util::log_err(&format!("[audit] 建目录失败 {}: {e},审计停用", r.display())); + return; + } + purge(true); +} + +/// log 阶段捕获:复制 body 临时文件进审计目录 + 追加一行元数据。 +/// +/// `tin` / `tout` 是 body filter 旁路抓到的 token 数(`llm_usage` 模块提供), +/// 0 = 上游没给 usage(如 OpenAI 流式未开 include_usage)。 +/// +/// SAFETY: r 必须是 nginx 当前正在 finalize 的请求(log 阶段回调保证)。 +pub unsafe fn capture(r: *mut ngx_http_request_t, username: &str, slot: &str, tin: u64, tout: u64) { + let rb = (*r).request_body; + if rb.is_null() { + return; + } + let tf = (*rb).temp_file; + if tf.is_null() { + // body 没被刷过盘(本地应答 / 被拒请求 / 无 body)→ 不审计 + return; + } + // 临时文件路径:ngx_temp_file_t.file.name(nginx 创建时填好的完整路径) + let src = match core::str::from_utf8((*tf).file.name.as_bytes()) { + Ok(s) if !s.is_empty() => s.to_owned(), + _ => return, + }; + + let ts = util::now(); + let day = util::fmt_time(ts).get(..10).unwrap_or("unknown").to_owned(); + let dir = root().join(&day); + if let Err(e) = fs::create_dir_all(&dir) { + util::log_err(&format!("[audit] 建日期目录失败 {}: {e}", dir.display())); + return; + } + + let fname = format!("{}_{}.json", ts * 1000, util::rand_digits(6)); + let dst = dir.join(&fname); + // 复制(不是 rename):nginx 在请求池销毁时还要 unlink 临时文件, + // 改名会让它打出 unlink 失败告警;多一次拷贝换零噪音。 + if let Err(e) = fs::copy(&src, &dst) { + util::log_err(&format!("[audit] 复制请求体失败 {src}: {e}")); + return; + } + let bytes = fs::metadata(&dst).map(|m| m.len()).unwrap_or(0); + + let status = (*r).headers_out.status as u64; + let user = if username.is_empty() { "-" } else { username }; + let up = if slot.is_empty() { "-" } else { slot }; + let line = json!({ + "ts": ts, + "time": util::fmt_time(ts), + "user": user, + "slot": up, + "status": status, + "tin": tin, + "tout": tout, + "file": format!("{day}/{fname}"), + "bytes": bytes, + }); + match fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("meta.jsonl")) + { + Ok(mut f) => { + if let Err(e) = writeln!(f, "{line}") { + util::log_err(&format!("[audit] 写 meta 失败: {e}")); + } + } + Err(e) => util::log_err(&format!("[audit] 打开 meta 失败: {e}")), + } + + purge(false); +} + +/// 容量巡检入口。force=true 跳过节流(启动时用);平时每分钟最多一次。 +pub fn purge(force: bool) { + let now = util::now(); + if !force && now - LAST_PURGE_AT.load(Ordering::Relaxed) < config::AUDIT_PURGE_MIN_INTERVAL { + return; + } + LAST_PURGE_AT.store(now, Ordering::Relaxed); + if PURGING.swap(true, Ordering::Acquire) { + return; // 已有巡检在跑 + } + let result = purge_once(); + PURGING.store(false, Ordering::Release); + if let Err(e) = result { + util::log_err(&format!("[audit] 容量巡检失败: {e}")); + } +} + +/// 扫描审计根:目录名即日期(字典序 = 时间序),总量超限就从最旧整目录删。 +/// +/// ⚠️ 本模块无法跑 `cargo test`(dylib 依赖 nginx 主程序的运行时符号, +/// `cargo test --lib` 直接 SIGABRT)——行为由 tests/llm/e2e.sh【9】覆盖。 +fn purge_once() -> Result<(), String> { + let r = root(); + let mut total: u64 = 0; + let mut dirs: Vec<(PathBuf, u64)> = Vec::new(); + for ent in fs::read_dir(&r).map_err(|e| e.to_string())?.flatten() { + let p = ent.path(); + if !p.is_dir() { + continue; + } + let mut size: u64 = 0; + if let Ok(files) = fs::read_dir(&p) { + for f in files.flatten() { + if let Ok(md) = f.metadata() { + if md.is_file() { + size += md.len(); + } + } + } + } + total += size; + dirs.push((p, size)); + } + if total <= config::AUDIT_MAX_BYTES { + return Ok(()); + } + dirs.sort_by(|a, b| a.0.cmp(&b.0)); + for (p, size) in dirs { + if total <= config::AUDIT_MAX_BYTES { + break; + } + match fs::remove_dir_all(&p) { + Ok(()) => { + total = total.saturating_sub(size); + util::log_notice(&format!("[audit] 超容量,已删除 {}", p.display())); + } + Err(e) => util::log_err(&format!("[audit] 删除 {} 失败: {e}", p.display())), + } + } + Ok(()) +} diff --git a/rust/src/llm_usage.rs b/rust/src/llm_usage.rs new file mode 100644 index 0000000..fd606af --- /dev/null +++ b/rust/src/llm_usage.rs @@ -0,0 +1,275 @@ +//! LLM token 计量:注册 body filter,旁路扫描上游响应,提取尾部 `usage` 的 token 数。 +//! +//! 为什么调研结论是「要做 C 模块」、最后只用 Rust 就成了:`ngx_http_top_body_filter` +//! 是 nginx **导出的全局符号**(`src/http/ngx_http.c:76` 定义,`ngx_http.h:197` +//! extern),动态模块可以直接 FFI 引用并把自己插到链头——不需要第二个 .so, +//! 「单容器单动态库」红线无伤。做法与官方 C 模块(copy/postpone filter)同款: +//! `next = top; top = ours;`,next 自持一份。 +//! +//! ## 工作方式 +//! +//! * **只旁观、不改动**:filter 拿到 chunk 后原样交给下一环(SSE 透传零影响), +//! 同时把内存 buf 的字节追加进 32 KiB **尾部窗口**(请求池分配,随请求回收)。 +//! 必须在调下一环**之前**读——下游 filter(write)发送后会前移 `pos`。 +//! * **流量识别**:`r->loc_conf` 的 `ModuleConfig.llm` 为真才建窗口—— +//! 管理台 / 子域名转发不经过扫描,零开销。 +//! * **token 提取**(不做 JSON 解析,按键扫数字,容错优先): +//! - 入 token:`"prompt_tokens"`(OpenAI) / `"input_tokens"`(Anthropic) / +//! `"promptTokenCount"`(Gemini)——**路过就记**(Anthropic 的 message_start +//! 在流头,长流会滑出尾部窗口,不能等收尾再找); +//! - 出 token:`"completion_tokens"` / `"output_tokens"` / +//! `"candidatesTokenCount"`——流结束时取尾部窗口**最后一次**出现 +//! (Anthropic message_delta 是累计值,最后一次 = 终值); +//! - 兜底:入出都为 0 时试 Gemini `"totalTokenCount"`。 +//! 搜索键都带前导引号,天然避开 `cache_read_input_tokens` 这类子串陷阱。 +//! * **记账**:窗口值挂在模块 ctx 上,log 阶段(AuditHandler)统一 +//! `stats::add_tokens`(键 `utt:` / `utms:`)并写进审计 meta 行—— +//! 身份解析只在 log 阶段做一次,body filter 全程无身份语义。 +//! +//! ## 口径 +//! +//! OpenAI 系**流式**需要客户端带 `stream_options: {"include_usage": true}` +//! 才有 usage 块(Anthropic / Gemini 默认就带);非流式 JSON 天然带 usage。 +//! 抓不到 = 记 0,绝不猜测、绝不补估。 + +use core::slice; + +use ngx::core::Status; +use ngx::ffi::{ngx_chain_t, ngx_http_request_t, ngx_int_t, ngx_pool_t}; +use ngx::http::HttpModule; + +use crate::Module; +use crate::ModuleConfig; + +/// 尾部窗口容量:SSE 最终 usage 块 / 非 stream JSON 的尾部都远小于此。 +const TAIL_CAP: usize = 32 * 1024; + +type BodyFilterPt = + Option ngx_int_t>; + +extern "C" { + /// nginx 导出的 body filter 链头(动态模块引用主程序符号,dlopen 时解析) + static mut ngx_http_top_body_filter: BodyFilterPt; +} + +/// 插入前的原链头——与官方 C 模块同款,每个模块自持一份 next。 +static mut NEXT_BODY_FILTER: BodyFilterPt = None; + +/// postconfiguration 阶段调用:把自己插到 body filter 链头。 +pub fn install() { + unsafe { + NEXT_BODY_FILTER = ngx_http_top_body_filter; + ngx_http_top_body_filter = Some(body_filter); + } +} + +// =========================================================================== +// usage 键与数字扫描 +// =========================================================================== + +/// 入 token 候选键(带前导引号防子串误配) +const KEYS_IN: [&[u8]; 3] = [ + b"\"prompt_tokens\":", + b"\"input_tokens\":", + b"\"promptTokenCount\":", +]; +/// 出 token 候选键 +const KEYS_OUT: [&[u8]; 3] = [ + b"\"completion_tokens\":", + b"\"output_tokens\":", + b"\"candidatesTokenCount\":", +]; + +fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || hay.len() < needle.len() { + return None; + } + let end = hay.len() - needle.len(); + let mut i = from; + while i <= end { + if &hay[i..i + needle.len()] == needle { + return Some(i); + } + i += 1; + } + None +} + +/// 从键名结束处解析 `: ` +fn value_at(hay: &[u8], key_end: usize) -> Option { + let mut i = key_end; + while i < hay.len() && (hay[i] == b' ' || hay[i] == b'\t') { + i += 1; + } + let start = i; + while i < hay.len() && hay[i].is_ascii_digit() { + i += 1; + } + if i == start { + return None; + } + core::str::from_utf8(&hay[start..i]).ok()?.parse::().ok() +} + +/// 一段字节里,各键**第一次**出现的非零值 +fn first_u64(hay: &[u8], keys: &[&[u8]]) -> u64 { + for k in keys { + if let Some(p) = find_from(hay, k, 0) { + if let Some(v) = value_at(hay, p + k.len()) { + if v > 0 { + return v; + } + } + } + } + 0 +} + +/// 一段字节里,各键**最后一次**出现的非零值(Anthropic message_delta 累计语义) +fn last_u64(hay: &[u8], keys: &[&[u8]]) -> Option { + let mut out = None; + for k in keys { + let mut from = 0; + while let Some(p) = find_from(hay, k, from) { + if let Some(v) = value_at(hay, p + k.len()) { + if v > 0 { + out = Some(v); + } + } + from = p + 1; + } + } + out +} + +// =========================================================================== +// per-request 扫描窗口(挂在模块 ctx 上,请求池分配、随请求回收) +// =========================================================================== + +#[repr(C)] +struct ScanCtx { + tail: [u8; TAIL_CAP], + len: usize, + tin: u64, + tout: u64, +} + +impl ScanCtx { + fn append(&mut self, data: &[u8]) { + // 入 token 路过就记(Anthropic message_start 在流头,收尾时早滑出窗口) + if self.tin == 0 { + self.tin = first_u64(data, &KEYS_IN); + } + // 维护「最后 TAIL_CAP 字节」窗口 + let n = data.len(); + if n >= self.tail.len() { + let off = n - self.tail.len(); + self.tail.copy_from_slice(&data[off..]); + self.len = self.tail.len(); + } else if self.len + n > self.tail.len() { + let drop = self.len + n - self.tail.len(); + self.tail.copy_within(drop..self.len, 0); + self.len -= drop; + self.tail[self.len..self.len + n].copy_from_slice(data); + self.len += n; + } else { + self.tail[self.len..self.len + n].copy_from_slice(data); + self.len += n; + } + } + + /// last_buf:从尾部窗口取出/收拢 token 数 + fn finish(&mut self) { + let w = &self.tail[..self.len]; + if let Some(v) = last_u64(w, &KEYS_OUT) { + self.tout = v; + } + if self.tin == 0 { + self.tin = last_u64(w, &KEYS_IN).unwrap_or(0); + } + if self.tin == 0 && self.tout == 0 { + // 兜底:Gemini totalTokenCount + if let Some(v) = last_u64(w, &[b"\"totalTokenCount\":" as &[u8]]) { + self.tout = v; + } + } + } +} + +unsafe fn ctx_slot(r: *mut ngx_http_request_t) -> *mut *mut ScanCtx { + let idx = (*Module::module()).ctx_index as usize; + (*r).ctx.add(idx) as *mut *mut ScanCtx +} + +// =========================================================================== +// filter 本体 +// =========================================================================== + +/// body filter:先旁观扫描,再原样交下一环。任何异常都只影响计量,不影响转发。 +unsafe extern "C" fn body_filter(r: *mut ngx_http_request_t, in_: *mut ngx_chain_t) -> ngx_int_t { + if !r.is_null() && !in_.is_null() && (*r).main == r { + scan(r, in_); + } + // 无条件放行给下一环——本 filter 对数据链零改动 + match NEXT_BODY_FILTER { + Some(f) => f(r, in_), + None => Status::NGX_OK.into(), + } +} + +unsafe fn scan(r: *mut ngx_http_request_t, in_: *mut ngx_chain_t) { + // 只有 LLM location 才扫:管理台 / 子域名转发零开销直过 + let lc = (*(*r).loc_conf.add((*Module::module()).ctx_index as usize)) as *const ModuleConfig; + if lc.is_null() || !(*lc).llm { + return; + } + + let slot = ctx_slot(r); + let mut ctx = *slot; + if ctx.is_null() { + let p = nginx_sys::ngx_pcalloc((*r).pool, core::mem::size_of::()) as *mut ScanCtx; + if p.is_null() { + // 分配失败:放弃本请求的 token 计量,不影响转发 + return; + } + *slot = p; + ctx = p; + } + + let mut cl = in_; + while !cl.is_null() { + let buf = (*cl).buf; + cl = (*cl).next; + if buf.is_null() { + continue; + } + let (pos, last) = ((*buf).pos, (*buf).last); + if !pos.is_null() && !last.is_null() && last > pos { + // SAFETY: 内存 buf 的 pos..last 由 nginx 保证有效 + let data = slice::from_raw_parts(pos, last as usize - pos as usize); + (*ctx).append(data); + } + if (*buf).last_buf() != 0 { + (*ctx).finish(); + } + } +} + +/// log 阶段读取本请求抓到的 token 数(ctx 随请求池整体回收,无需清理钩子)。 +pub fn take(r: *mut ngx_http_request_t) -> (u64, u64) { + if r.is_null() { + return (0, 0); + } + unsafe { + let c = *ctx_slot(r); + if c.is_null() { + (0, 0) + } else { + ((*c).tin, (*c).tout) + } + } +} + +// 让 ngx_pool_t 出现在 use 里不产生 unused 告警(签名可读性) +#[allow(dead_code)] +type PoolRef = *mut ngx_pool_t; diff --git a/rust/src/stats.rs b/rust/src/stats.rs index 38409f0..11676a1 100644 --- a/rust/src/stats.rs +++ b/rust/src/stats.rs @@ -15,18 +15,19 @@ //! 后者是"先增后判"(含被拒),要的是"超限后计数继续涨"的执行语义; //! 而用量统计是给人看的,把被拒的请求算进"用量"只会让人误解。 //! -//! ## 为什么不做 token 级 +//! ## token 级计量(2026-09-12 起) //! -//! token 数在上游响应体里,而 SSE 必须关缓冲透传(`proxy_buffering off`), -//! 网关不缓冲就解析不到 `usage` 字段。要做 token 级计费得自建 upstream -//! 把响应拦下来重组流,与「不引入额外常驻进程 / 不改 nginx 原生转发」冲突。 -//! 因此口径统一为**请求数**,并在文档里写明。 +//! token 数来自上游响应体里的 `usage` 字段:`llm_usage` 模块在 **body filter 链** +//! 旁路扫描响应(SSE 尾部 / 非 stream JSON 尾部),零缓冲、不影响透传; +//! log 阶段统一入账到 `utt:` / `utms:` 两个键前缀,编码与本文件同款格式。 +//! 抓不到 usage(如 OpenAI 流式客户端没带 `include_usage`)= 记 0,不补估。 +//! 计数口径与请求数一致:**只算真的转发出去且上游给了 usage 的**。 use std::collections::BTreeMap; use serde_json::{Value, json}; -use crate::config::{KEY_UMS_PREFIX, KEY_UST_PREFIX}; +use crate::config::{KEY_UMS_PREFIX, KEY_UTMS_PREFIX, KEY_UST_PREFIX, KEY_UTT_PREFIX}; use crate::state; use crate::util; @@ -61,6 +62,45 @@ impl Usage { } } +/// token 计量读数。日窗语义与 [`Usage`] 相同:跨天 today 归零、累计保留。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct TokenUsage { + /// 今日入 token(prompt / input) + pub tin_today: i64, + /// 累计入 token + pub tin_total: i64, + /// 今日出 token(completion / output) + pub tout_today: i64, + /// 累计出 token + pub tout_total: i64, + /// 最近一次有 token 记账的调用时间戳;0 = 从未 + pub last_ts: i64, +} + +impl TokenUsage { + /// 累加(聚合用)。`last_ts` 取最大。 + fn merge(&mut self, other: &TokenUsage) { + self.tin_today += other.tin_today; + self.tin_total += other.tin_total; + self.tout_today += other.tout_today; + self.tout_total += other.tout_total; + if other.last_ts > self.last_ts { + self.last_ts = other.last_ts; + } + } + + pub fn json(&self) -> Value { + json!({ + "in_today": self.tin_today, + "in_total": self.tin_total, + "out_today": self.tout_today, + "out_total": self.tout_total, + "last_ts": self.last_ts, + "last_ts_text": if self.last_ts > 0 { util::fmt_time(self.last_ts) } else { String::new() }, + }) + } +} + /// 一个账号的用量 + 其下每个上游的明细 pub struct UserUsage { pub username: String, @@ -124,6 +164,58 @@ pub fn record(username: &str, slot: &str, now: i64) { bump(KEY_UMS_PREFIX, &format!("{username}:{slot}"), day, now); } +/// `<日窗id>:<入今日>:<入累计>:<出今日>:<出累计>:<最近时间戳>` +fn encode_t(day: i64, t: &TokenUsage) -> String { + format!( + "{}:{}:{}:{}:{}:{}", + day, t.tin_today, t.tin_total, t.tout_today, t.tout_total, t.last_ts + ) +} + +fn decode_t(payload: &str, day: i64) -> TokenUsage { + let mut it = payload.split(':'); + let stored_day = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let in_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let in_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let out_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let out_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let last_ts = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let live = stored_day == day; + TokenUsage { + tin_today: if live { in_today } else { 0 }, + tin_total: in_total, + tout_today: if live { out_today } else { 0 }, + tout_total: out_total, + last_ts, + } +} + +fn bump_t(prefix: &[u8], name: &str, tin: u64, tout: u64, day: i64, now: i64) { + let current = state::get(prefix, name.as_bytes()) + .map(|(payload, _)| decode_t(&payload, day)) + .unwrap_or_default(); + // 与 bump 同款读-增-写近似语义(并发下偶发少计),计量用途可接受 + let next = TokenUsage { + tin_today: current.tin_today + tin as i64, + tin_total: current.tin_total + tin as i64, + tout_today: current.tout_today + tout as i64, + tout_total: current.tout_total + tout as i64, + last_ts: now, + }; + state::put(prefix, name.as_bytes(), encode_t(day, &next).as_bytes(), 0); +} + +/// 累加一次真实 token 消耗(来源:body filter 从上游响应抓到的 usage)。 +/// 口径:只有抓到 usage 才记账;抓不到不补估。 +pub fn add_tokens(username: &str, slot: &str, tin: u64, tout: u64, now: i64) { + if username.is_empty() || slot.is_empty() || (tin == 0 && tout == 0) { + return; + } + let day = util::day_id(now); + bump_t(KEY_UTT_PREFIX, username, tin, tout, day, now); + bump_t(KEY_UTMS_PREFIX, &format!("{username}:{slot}"), tin, tout, day, now); +} + /// 删除账号时清理其全部用量键(`ust:` 与 `ums::*`)。 /// /// 用量键是**按前缀扫出来**做报表的(`all_users` / `all_models`),不清就会让 @@ -133,17 +225,20 @@ pub fn forget(username: &str) { if username.is_empty() { return; } - state::remove(KEY_UST_PREFIX, username.as_bytes()); - - // 先物化键名再删,避免"遍历中改表" + // 先物化键名再删,避免"遍历中改表"(四个键前缀同一套路) let prefix = format!("{username}:"); - let keys: Vec = state::iter_prefix(KEY_UMS_PREFIX) - .into_iter() - .map(|(name, _)| name) - .filter(|name| name.starts_with(&prefix)) - .collect(); - for name in keys { - state::remove(KEY_UMS_PREFIX, name.as_bytes()); + for p in [KEY_UST_PREFIX, KEY_UTT_PREFIX] { + state::remove(p, username.as_bytes()); + } + for p in [KEY_UMS_PREFIX, KEY_UTMS_PREFIX] { + let keys: Vec = state::iter_prefix(p) + .into_iter() + .map(|(name, _)| name) + .filter(|name| name.starts_with(&prefix)) + .collect(); + for name in keys { + state::remove(p, name.as_bytes()); + } } } @@ -239,19 +334,59 @@ pub fn totals(now: i64) -> Usage { sum } +/// 单账号 token 读数 +pub fn tokens_user(username: &str, now: i64) -> TokenUsage { + let day = util::day_id(now); + state::get(KEY_UTT_PREFIX, username.as_bytes()) + .map(|(payload, _)| decode_t(&payload, day)) + .unwrap_or_default() +} + +/// token 全表一次扫齐:`(按账号, 按上游, 按 账号→上游)`。 +/// utt/utms 各扫一遍,避免报表页多次遍历共享内存。 +fn tokens_scan( + now: i64, +) -> ( + BTreeMap, + BTreeMap, + BTreeMap>, +) { + let day = util::day_id(now); + let mut by_user: BTreeMap = BTreeMap::new(); + for (name, payload) in state::iter_prefix(KEY_UTT_PREFIX) { + by_user.insert(name, decode_t(&payload, day)); + } + let mut by_slot: BTreeMap = BTreeMap::new(); + let mut by_pair: BTreeMap> = BTreeMap::new(); + for (name, payload) in state::iter_prefix(KEY_UTMS_PREFIX) { + let Some((username, slot)) = name.split_once(':') else { + continue; + }; + let t = decode_t(&payload, day); + by_slot.entry(slot.to_owned()).or_default().merge(&t); + by_pair.entry(username.to_owned()).or_default().insert(slot.to_owned(), t); + } + (by_user, by_slot, by_pair) +} + /// 管理台用量页的完整投影 pub fn overview(now: i64) -> Value { + let (t_by_user, t_by_slot, t_by_pair) = tokens_scan(now); + let users: Vec = all_users(now) .into_iter() .map(|u| { + let tin = t_by_pair.get(&u.username); json!({ "username": u.username, "today": u.usage.today, "total": u.usage.total, "last_ts": u.usage.last_ts, "last_ts_text": if u.usage.last_ts > 0 { util::fmt_time(u.usage.last_ts) } else { String::new() }, + "tokens": t_by_user.get(&u.username).cloned().unwrap_or_default().json(), "models": u.models.iter().map(|(slot, usage)| { - json!({ "slot": slot, "today": usage.today, "total": usage.total }) + json!({ "slot": slot, "today": usage.today, "total": usage.total, + "tokens": tin.and_then(|m| m.get(slot)).cloned().unwrap_or_default().json() }) }).collect::>(), }) }) @@ -266,6 +401,7 @@ pub fn overview(now: i64) -> Value { "total": m.usage.total, "last_ts": m.usage.last_ts, "last_ts_text": if m.usage.last_ts > 0 { util::fmt_time(m.usage.last_ts) } else { String::new() }, + "tokens": t_by_slot.get(&m.slot).cloned().unwrap_or_default().json(), "users": m.users.iter().map(|(name, usage)| { json!({ "username": name, "today": usage.today, "total": usage.total }) }).collect::>(), @@ -274,8 +410,13 @@ pub fn overview(now: i64) -> Value { .collect(); let sum = totals(now); + let mut tsum = TokenUsage::default(); + for t in t_by_user.values() { + tsum.merge(t); + } json!({ "total": sum.json(), + "tokens": tsum.json(), "users": users, "models": models, }) diff --git a/tests/llm/e2e.sh b/tests/llm/e2e.sh index 5a301b0..5626dd1 100755 --- a/tests/llm/e2e.sh +++ b/tests/llm/e2e.sh @@ -396,6 +396,67 @@ ck "删除后列表不再出现 health1" miss "$(up_field_of health1 status)" curl -s -b "$JAR" -X POST $API/api/admin/users/delete -H 'Content-Type: application/json' \ -d "$(jbody username healthprobe)" >/dev/null +echo +echo "【9】对话审计(audit/ 目录:请求体落盘 + meta 索引 + 被拒不入档)" +AUDIT=$RUN/audit +sleep 0.3 +audit_n() { find "$AUDIT" -name '*.json' 2>/dev/null | wc -l | tr -d ' '; } +N1=$(audit_n) +ck "转发的请求都落了审计文件" yes "$([ "$N1" -ge 3 ] && echo yes || echo no)" +ck "meta.jsonl 记录账号/上游/状态" yes \ + "$(grep -q '"user":"alice"' "$AUDIT"/*/meta.jsonl 2>/dev/null && grep -q '"slot":"openai"' "$AUDIT"/*/meta.jsonl && grep -q '"status":200' "$AUDIT"/*/meta.jsonl && echo yes || echo no)" +# 取 alice 一条成功记录,比对审计文件内容 = 原始请求体 +AF=$("$PY" -c " +import json, sys +for l in open(sys.argv[1], encoding='utf-8'): + d = json.loads(l) + if d.get('user') == 'alice' and d.get('status') == 200: + print(d['file']); break +" "$AUDIT"/*/meta.jsonl 2>/dev/null | head -1) +ck "审计文件内容 = 客户端原始请求体" "$BODY" "$(cat "$AUDIT/$AF" 2>/dev/null)" +N2=$(audit_n) +code -H "Authorization: Bearer sk_deadbeef" -X POST $GW/openai/v1/chat/completions \ + -H 'Content-Type: application/json' -d "$BODY" >/dev/null +sleep 0.3 +ck "被拒请求(401)不入档" 0 "$(( $(audit_n) - N2 ))" + +echo "【10】token 计量(body filter 旁路抓 usage → utt:/utms:)" +# 非 stream usage 固定 7/3;带 usage_probe 的流式在 SSE 尾部给 11/22 +curl -s -H "Authorization: Bearer $ALICE_KEY" -X POST $GW/openai/v1/chat/completions \ + -H 'Content-Type: application/json' -d "$BODY" >/dev/null +curl -s -H "Authorization: Bearer $ALICE_KEY" -X POST $GW/openai/v1/chat/completions \ + -H 'Content-Type: application/json' -d '{"model":"gpt-4o","stream":true,"usage_probe":true}' >/dev/null +sleep 0.3 +TOK=$(curl -s -b "$JAR" $API/api/admin/usage) +tok_ok() { "$PY" -c " +import json, sys +d = json.loads(sys.argv[1])['data'] +ok_u = ok_s = False +for u in d.get('users', []): + if u['username'] == 'alice': + t = u.get('tokens', {}) + ok_u = t.get('in_total', 0) >= 18 and t.get('out_total', 0) >= 25 + for m in u.get('models', []): + if m['slot'] == 'openai': + ok_u = ok_u and m.get('tokens', {}).get('in_total', 0) >= 18 +for s in d.get('models', []): + if s['slot'] == 'openai': + ts = s.get('tokens', {}) + ok_s = ts.get('in_total', 0) >= 18 and ts.get('out_total', 0) >= 25 +print('yes' if ok_u and ok_s else 'no') +" "$1"; } +ck "usage API 出现 token 维度(账号/上游明细/上游聚合)" yes "$(tok_ok "$TOK")" +ck "审计 meta 行记录 token" yes "$("$PY" -c " +import json, sys +hit = False +for f in sys.argv[1:]: + for l in open(f, encoding='utf-8'): + d = json.loads(l) + if d.get('user') == 'alice' and d.get('tin', 0) > 0: + hit = True +print('yes' if hit else 'no') +" "$AUDIT"/*/meta.jsonl 2>/dev/null)" + echo echo "============================================================" printf " 通过 \033[32m%d\033[0m 失败 \033[31m%d\033[0m\n" "$pass" "$fail" diff --git a/tests/llm/nginx.conf.in b/tests/llm/nginx.conf.in index b61160b..ed62e48 100644 --- a/tests/llm/nginx.conf.in +++ b/tests/llm/nginx.conf.in @@ -43,6 +43,10 @@ http { location / { ipass_llm on; + # 对话审计(与生产 conf/nginx.conf 对齐):强制请求体落临时文件, + # log 阶段由模块复制进 @RUN@/audit/ + client_body_in_file_only clean; + proxy_pass $llm_target; proxy_http_version 1.1; @@ -68,9 +72,9 @@ http { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Connection ""; - # SSE 三件套:少一个流式就会退化成「攒完一次性返回」 + # SSE 流式两件套(响应方向;请求方向不再 no_buffering,理由见 + # 生产 conf/nginx.conf——与对话审计的 client_body_in_file_only 互斥) proxy_buffering off; - proxy_request_buffering off; proxy_cache off; chunked_transfer_encoding on; diff --git a/tests/llm/upstream.py b/tests/llm/upstream.py index 7e83eb7..96a5441 100644 --- a/tests/llm/upstream.py +++ b/tests/llm/upstream.py @@ -82,11 +82,18 @@ class H(BaseHTTPRequestHandler): self.wfile.write(('data: {"i":%d}\n\n' % i).encode()) self.wfile.flush() time.sleep(0.4) + # token 计量探针:body 带 "usage_probe" 才在流尾追加 usage 块。 + # 不带标记时保持 3 块不变——sse_test.py 的 CHUNKS=3 契约不能破。 + if b'"usage_probe"' in body: + self.wfile.write(b'data: {"choices":[],"usage":{"prompt_tokens":11,"completion_tokens":22}}\n\n') + self.wfile.write(b'data: [DONE]\n\n') + self.wfile.flush() self.close_connection = True else: payload = json.dumps({ "id": "chatcmpl-x", "choices": [{"message": {"role": "assistant", "content": "pong"}}], + "usage": {"prompt_tokens": 7, "completion_tokens": 3}, }).encode() self.send_response(200) self.send_header("Content-Type", "application/json")