Metadata-Version: 2.4
Name: pping-lang
Version: 0.1.0a2
Summary: vLLM 性能诊断插件——把 vLLM 指标 + GPU 物理层数据喂给规则引擎，自动告诉你为什么慢
Project-URL: Homepage, https://github.com/leon/pping-lang
Project-URL: Documentation, https://github.com/leon/pping-lang/tree/main/docs
Author: Leon
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Support. While redistributing the Work or
              Derivative Works thereof, You may choose to offer, and charge a
              fee for, acceptance of support, warranty, indemnity, or other
              liability obligations and/or rights consistent with this License.
              However, in accepting such obligations, You may act only on Your
              own behalf and on Your sole responsibility, not on behalf of any
              other Contributor, and only if You agree to indemnify, defend,
              and hold each Contributor harmless for any liability incurred by,
              or claims asserted against, such Contributor by reason of your
              accepting any such warranty or support.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Leon
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
License-File: LICENSE
Keywords: gpu,llm,observability,performance,profiling,vllm
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Requires-Dist: duckdb>=1.0.0
Requires-Dist: fastapi>=0.110.0
Requires-Dist: nvidia-ml-py>=12.0.0
Requires-Dist: opentelemetry-api>=1.27.0
Requires-Dist: opentelemetry-exporter-otlp>=1.27.0
Requires-Dist: opentelemetry-sdk>=1.27.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: uvicorn[standard]>=0.27.0
Provides-Extra: analyzer
Requires-Dist: prometheus-api-client>=0.5.0; extra == 'analyzer'
Provides-Extra: bench
Requires-Dist: httpx>=0.27.0; extra == 'bench'
Provides-Extra: cupti
Requires-Dist: cupti-python>=13.0.0; extra == 'cupti'
Provides-Extra: dev
Requires-Dist: httpx>=0.27.0; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: server
Requires-Dist: grpcio>=1.60.0; extra == 'server'
Requires-Dist: protobuf>=4.0.0; extra == 'server'
Provides-Extra: vllm
Requires-Dist: vllm<0.22.0,>=0.20.0; extra == 'vllm'
Description-Content-Type: text/markdown

> **简体中文** | [English](README.en.md)

<div align="center">

# pping-lang

**vLLM 性能诊断插件 —— 实时指标采集、规则化分析、结构化建议**

[![PyPI](https://img.shields.io/pypi/v/pping-lang?color=4c8bf5&label=PyPI)](https://pypi.org/project/pping-lang/)
[![Python](https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-4c8bf5)](https://pypi.org/project/pping-lang/)
[![License](https://img.shields.io/badge/license-Apache%202.0-43a047)](LICENSE)
[![Status](https://img.shields.io/badge/status-pre--alpha-fb8c00)](#项目状态)
[![Tests](https://img.shields.io/badge/tests-444%20passing-43a047)](tests/)
[![Live Demo](https://img.shields.io/badge/%F0%9F%8C%90%20Live%20Demo-online-5b5bd6)](https://leon-hf.github.io/pping-lang/)

**[🌐 在线演示 Live Demo →](https://leon-hf.github.io/pping-lang/)** —— 浏览器直接看真机采到的仪表盘（实时 / Kernel / 规则 / 压测，中英双语）

[在线演示](https://leon-hf.github.io/pping-lang/) · [快速上手](#快速上手) · [仪表盘](#仪表盘) · [兼容性](#兼容性) · [架构](#架构) · [路线图](#路线图)

</div>

---

## Latest News

- **2026-06** —— 事实规则诊断引擎：诊断从扁平 if-else 升级为「事实 + 署名推断」两层 —— 规则名即客观事实（测出来的），根因与处方作为署名推断单列；阈值集中到一份 SLA 配置，可在仪表盘里热加载进运行中的引擎，并支持增删自定义规则
- **2026-06** —— 指标持久化去 DuckDB：进程内 DuckDB 改为顺序追加 JSONL（AppendLog），消除每迭代 INSERT 与 colocated serving 抢 GIL/IO；保留窗口改为时间制（`PPING_LANG_RETENTION_SECONDS`，默认 2h），按卷滚动、磁盘有界
- **2026-06** —— Dual-path 实时读取架构：实时面板从 DuckDB SQL 路径迁移至内存 ring buffer，bench 启动后 KPI 可见性延迟由 20s 降至 2s
- **2026-06** —— Roofline analytical fallback：在缺失 `perf_stats` 的 vLLM 版本上，依据 `FLOPS ≈ 2·params·tokens` 从 iter 级 token 计数和模型参数量推算 arithmetic intensity 与 throughput，并附区域着色 + 自动结论卡（memory-bound / compute-bound 判定及对应优化路径）
- **2026-06** —— 延迟指标改为多统计量并报：TTFT / TPOT 同时披露 p50 / p95 / p99 / avg 及请求数，避免单一百分位对偏态分布的失真
- **2026-05** —— 内置 bench 模块：dashboard 直接发起静态压测，含三个标准 prompt 数据集（短问答 / 长文档 / 代码）
- **2026-05** —— `v0.1.0a1` 发布至 PyPI

---

## 概述

vLLM 通过 `stat_logger_plugins` 入口暴露完整的运行时指标（SchedulerStats、IterationStats、cudagraph / perf 派生量），其消费方式通常为 Prometheus 抓取 + Grafana 可视化。该方案能展示指标但不输出决策结论，存在两个具体问题：

1. **指标语义模糊**。`GPU utilization` 反映的是 SM duty cycle 而非吞吐量。在 LLM decode 阶段，该值常稳定于 70–90% 而 MFU 不足 5%，原因为 memory-bound。仅看 utilization 数字无法识别此类瓶颈
2. **缺乏可操作性**。规则触发、阈值告警、根因关联需要使用方自行实现

pping-lang 直接消费 `stat_logger_plugins` 回调，结合 NVML 物理层采样，通过规则引擎输出结构化诊断与优化路径。示例输出：

```text
[pping-lang] WARNING  GPU 利用率偏低
  GPU 平均利用率 3% 持续低于 50% 已 30s
  建议：检查 batch 是否退化为 1，或开启连续 batching

[pping-lang] WARNING  batch 退化
  并发请求数 1.0 ≤ 1.0 已 30s
  建议：增加客户端并发，或检查上游路由是否串行化
```

Roofline 视图附带自动结论：

```text
当前结论  Memory-bound（decode 阶段的典型状态）
  算力利用    1%   （0.40 / 33 TFLOPS）
  带宽利用   52%   （132 / 256 GB/s）

优化路径
  · 增大 batch 直至 KV cache 占用接近 80%
  · 启用 speculative decoding
  · 权重量化 (AWQ / GPTQ)
  · 升级带宽更高的 GPU
```

---

## 快速上手

### 离线 demo（无需 GPU / vLLM）

```bash
pip install pping-lang
python -m examples.embedded.demo
```

脚本注入合成指标，约 7 秒后终端打印诊断，dashboard 可访问 `http://localhost:8765`。

### 接入 vLLM

**基础接入** —— KPI / Roofline / NVML / 诊断,自动加载,不改任何参数：

```bash
pip install pping-lang
vllm serve <model>
```

vLLM 启动日志将输出 dashboard 地址 `[pping-lang] dashboard → http://localhost:8765`。

**完整接入** —— 再加 Kernel 级 PC Sampling（Deep Evidence「为什么慢」）：

```bash
pip install pping-lang
pping-vllm serve <model>      # 等价于 vllm serve,额外开启 Kernel 级采集
```

`pping-vllm` 是一层薄包装：首次自动把内置的 CUPTI 注入库（`libppingcupti.so`）在本机**现编**
（自动探测 cu12/cu13，缓存到 `~/.pping-lang/`），设好注入与采样环境变量，再 `exec vllm serve`
（透传所有参数）。编不出 `.so`（无 g++ / 无 CUPTI）则**自动降级**为基础接入。

> Kernel 级采集通过 `vllm.general_plugins` 入口在 **EngineCore 进程**驱动 PC sampling、结果跨
> 进程回流前端 dashboard —— 在**默认多进程 `vllm serve`** 上即可工作,无需单进程。

---

## 仪表盘

单页应用，单文件 HTML，无需前端构建工具。三个标签页：

| 标签页 | 内容 |
|:--|:--|
| 实时 | 12 项 KPI（TTFT / TPOT / 吞吐 / KV cache / 队列状态 / MFU / GPU 利用 / 显存 / Prefix cache / Padding / 抢占率）；Roofline 散点 + 自动结论；TTFT / TPOT / E2E 时序图。每项 KPI 支持 hover 查看公式与解读 |
| Kernel | 每个 GPU kernel 的 GPU 时间占比 + 算子分类（GEMM / Attention / …）+ 主导 stall；**源码级热点**（Triton kernel 直接定位到 Python 源码行 + 该行代码原文；闭源库给 SASS 指令热点 + kernel 名解码）；**启动来源**（即便闭源 GEMM 也能归因到调用它的 host 代码，如 nn.Linear）；Roofline 宏观定位；Deep Evidence「为什么慢」（warp 周期三态 / 全局 stall 分解 / PerfWorks reason 下钻）。需 `pping-vllm` 完整接入，eager 与 cudagraph（生产默认）模式均支持 |
| 规则 | 只读展示生效中的事实规则（事实名 / 严重度 / 判定条件 + 配置解析后的阈值 / 前置与 regime 门）；中心化 SLA + 阈值编辑器，保存即热加载进运行中的引擎，不重启 vLLM；可增删自定义规则，与策展规则同一引擎评估 |
| 压测 | 内置 OpenAI 协议静态压测器，配置 endpoint / 调用名 / 并发 / 时长 / prompt 来源，输出 client-side TTFT / TPOT / E2E 分布及 SLO 校验 |

实时数据从 Sink 的内存 ring buffer 直读，延迟约等于轮询间隔。

---

## 兼容性

### vLLM 版本

| vLLM | 状态 | SchedulerStats | IterationStats | cudagraph_stats | perf_stats |
|:--|:--|:--:|:--:|:--:|:--:|
| 0.20+ | 推荐 | ✓ | ✓ | ✓ | ✓ |
| 0.13.x | 支持 | ✓ | ✓ | ✓（字段不同） | ✗ |
| < 0.13 | 不支持 | — | — | — | — |

`perf_stats` 是 MFU、显存带宽利用率与实测 Roofline 的数据源，仅 0.20+ 提供。在 0.13.x 上：

- MFU、padding ratio KPI 显示为空（不进行不可靠的构造）
- Roofline 自动切换至 analytical 模式，绝对值存在约 ±20% 误差；卡片标识数据来源
- 其余功能不受影响：TTFT / TPOT / E2E 完整分布、KV cache、prefix cache 命中、preemption、NVML 全套采样、规则诊断

### 运行环境

- Linux：原生支持
- Windows：需通过 WSL2 + Ubuntu。跨子系统访问 dashboard 时需设置 `PPING_LANG_API_HOST=0.0.0.0`

### 已识别 GPU 列表

NVML 设备名 → BF16 peak (TFLOPs/s) 与显存带宽 (GB/s)。未识别的 GPU 不影响指标采集，仅跳过依赖峰值的派生量。

```
Blackwell        B200 (2250 / 8000) · B100 (1800 / 8000)
Hopper           H200 (989 / 4800) · H100 SXM/PCIe/NVL · A100 SXM/PCIe
Ada 数据中心      L40S · L40 · L4
Ada 桌面 / 移动   RTX 4090 / 4080 / 4070 Ti / 4070 / 4060 Ti / 4060 (含 Laptop GPU)
旧代             A30 · A10G · A10 · V100 · T4 · RTX 3090
```

补充设备：在 [`src/pping_lang/hardware.py`](src/pping_lang/hardware.py) 的 `_GPU_PEAK_TABLE` 添加条目。

---

## 性能

### 热路径开销

| 项目 | 实测 |
|:--|:--|
| `push_metric()` 单次 | <5 μs |
| `record()` 单次（含 collector 解析） | ≈100 μs |
| Sink bg flush 线程 CPU | <1% |
| 常驻内存 | ≈6 MB |

### 基准：Qwen2.5-0.5B-Instruct / RTX 4070 Laptop / WSL2 / vLLM 0.13.0

bench concurrency=3，时长 20s：

| 指标 | 值 | 数据来源 |
|:--|:--|:--|
| TTFT p99 | 305 ms | client-side |
| TPOT p99 | 22 ms | client-side |
| Output throughput | 28 tok/s | `vllm.iter.gen_tokens` |
| 单请求 decode 速度 | 138 tok/s | 1000 / TPOT p50 |
| 算力利用 | 1.2% | analytical Roofline |
| 带宽利用 | 51.5% (132 / 256 GB/s) | analytical Roofline |
| Bound 判定 | memory-bound | 中位 AI = 3.0 < knee 130 |

### 实时延迟

实时面板数据自 Sink 内存层直读，不经持久化层（JSONL）。指标自 `record()` 产生至 dashboard 渲染的端到端延迟约等于 HTTP 轮询周期（默认 2s）。

---

## 架构

```
                ┌─── live 内存层（O(1) 写 / O(1) 读）
                │       ↑                ↑
record() ──push─┤   /api/kpis        /api/metrics/recent  ≤60s
NVML 100ms ─────┤   /api/snapshot    /api/roofline        ≤60s
                │   /api/latency_trends                   ≤900s
                │
                │   Sink._latest:  name → (value, ts_ns)
                │   Sink._recent:  name → 2000-deep ring
                │
                └─── bg flush ─── JSONL append-log ─── archival 扫描
                                   metrics / diagnoses    (长时间窗，JsonlStore)
```

热路径仅执行 O(1) 入队，不进行 I/O、序列化或锁等待。持久化是顺序追加 JSONL（无查询引擎 / 事务 / 索引，写入近乎零争用）；长时间窗历史按需扫文件，属冷路径。诊断引擎与 Sink flush 在独立 daemon 线程运行。设计前提：插件任何异常不得影响 vLLM 推理路径。

### 关键源文件

- [`src/pping_lang/sink/base.py`](src/pping_lang/sink/base.py) —— 双路径 Sink 抽象与 ring buffer 定义
- [`src/pping_lang/sink/local.py`](src/pping_lang/sink/local.py) —— JSONL 顺序追加持久化（AppendLog 写端 / JsonlStore 读端，定义见 [`sink/metric_log.py`](src/pping_lang/sink/metric_log.py)）
- [`src/pping_lang/collector/vllm_stats.py`](src/pping_lang/collector/vllm_stats.py) —— vLLM IterationStats → MetricPoint 适配
- [`src/pping_lang/rules/diagnosis_runtime.py`](src/pping_lang/rules/diagnosis_runtime.py) —— 事实规则诊断引擎（评估循环，默认 1s）；纯求值核见 [`diagnosis_engine.py`](src/pping_lang/rules/diagnosis_engine.py)，规则定义见 [`diagnosis_rules.py`](src/pping_lang/rules/diagnosis_rules.py)，中心配置见 [`diagnosis_config.py`](src/pping_lang/rules/diagnosis_config.py)
- [`src/pping_lang/api/routes.py`](src/pping_lang/api/routes.py) —— FastAPI endpoints
- [`src/pping_lang/ui/index.html`](src/pping_lang/ui/index.html) —— Alpine.js + Chart.js dashboard

---

## 配置

| 环境变量 | 默认值 | 说明 |
|:--|:--|:--|
| `PPING_LANG_API_PORT` | `8765` | dashboard 监听端口 |
| `PPING_LANG_API_HOST` | `127.0.0.1` | 监听地址（容器 / WSL 场景设为 `0.0.0.0`） |
| `PPING_LANG_DB_PATH` | `~/.pping-lang/local.duckdb` | 取其父目录作 JSONL 持久化目录（`metrics.jsonl` / `diagnoses.jsonl`）；bench 结果仍存此 DuckDB 文件 |
| `PPING_LANG_RETENTION_SECONDS` | `7200` | 指标持久化保留时间窗口（时间为主，切卷滚动；洪流下按卷大小兜底、磁盘有界） |
| `PPING_LANG_INSTANCE_ID` | 主机名 | 多实例聚合时的标识 |
| `PPING_LANG_FLUSH_INTERVAL_S` | `5.0` | Sink → JSONL 追加周期 |
| `PPING_LANG_SINK_QUEUE_SIZE` | `65536` | Sink 内存队列容量 |
| `PPING_LANG_RULE_EVAL_INTERVAL_S` | `1.0` | 诊断引擎评估周期 |
| `PPING_LANG_RULES_PATH` | — | 规则覆盖 JSON 路径（RuleStore） |
| `PPING_LANG_CUSTOM_RULES_PATH` | `<DB_PATH 父目录>/custom_rules.json` | 自定义规则 JSON 持久化路径（与策展规则同一引擎评估） |
| `PPING_LANG_DISABLE_NVML` | — | 设为 `1` 关闭 NVML 采样 |
| `PPING_LANG_DISABLE_RULES` | — | 设为 `1` 关闭规则引擎 |
| `PPING_LANG_DISABLE_API` | — | 设为 `1` 关闭 HTTP API 与 dashboard |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | — | 配置后将指标同时导出至 OTel 后端 |

---

## 路线图

| 版本 | 部署模式 | 重点 |
|:--|:--|:--|
| v0.1（当前）| Embedded | 单机本地，pip 安装即用，dashboard + 规则引擎 + bench |
| v0.2 | Sidecar / Centralized | 独立 server 进程、Docker 镜像、Helm chart、K8s 多副本指标聚合 |
| v0.3 | Stateless | OTel-native，基于已有 Prometheus / Tempo 后端的诊断 |

---

## 项目状态

Pre-alpha (`v0.1.0a1`)。当前为 Embedded 模式，目标场景为单机本地开发与单卡 / 单 Pod 部署。生产侧的 Sidecar 模式、K8s 多副本聚合在 v0.2 规划。

API 在 0.x 阶段允许不兼容变更；规则 JSON schema 与 dashboard URL 路径承诺向后兼容。

---

## 开发

```bash
git clone https://github.com/leon-hf/pping-lang.git
cd pping-lang
pip install -e ".[dev,bench]"
bash scripts/setup-hooks.sh
pytest
ruff check src/ tests/
```

贡献流程见 [CONTRIBUTING.md](CONTRIBUTING.md)，版本变更记录见 [CHANGELOG.md](CHANGELOG.md)。

---

## Acknowledgments

- [vLLM](https://github.com/vllm-project/vllm) —— `stat_logger_plugins` 入口
- [DuckDB](https://duckdb.org/) —— bench 结果的嵌入式存储
- [NVIDIA NVML](https://docs.nvidia.com/deploy/nvml-api/) —— GPU 物理层采样
- 性能模型参考：Williams et al., *Roofline: An Insightful Visual Performance Model* (CACM 2009)；Kaplan et al., *Scaling Laws for Neural Language Models* (2020)

---

## Citation

```bibtex
@software{pping_lang,
  title  = {pping-lang: A diagnostic plugin for vLLM},
  author = {Leon},
  year   = {2026},
  url    = {https://github.com/leon-hf/pping-lang},
}
```

## License

This project is licensed under the **Apache License, Version 2.0**. See the [LICENSE](LICENSE) file for the full text.

Copyright © 2026 Leon
