Skip to content
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
0baad07
fix(proxy): prioritize TTFB when stream gate is not enforced
ding113 Sep 3, 2026
705742b
fix(proxy): record routing trace events during legacy hedge racing (#…
ding113 Sep 7, 2026
2b9a20f
fix(proxy): strip stale content encoding after reserialization (#1464)
ROOOO Sep 7, 2026
13649bb
fix(providers): auto-attach x-opencode-session and support regex capt…
ding113 Sep 7, 2026
01b3625
fix(proxy): use undici fetch with ProxyAgent on Node 24 (#1476)
kexichan Sep 9, 2026
8c2507c
fix(logs): prevent session ID suggestion query timeouts (#1479)
sususu98 Sep 9, 2026
9af35d1
feat(langfuse): reconstruct streamed outputs and enrich traces (#1478)
kexichan Sep 9, 2026
f08bd66
fix(proxy): 修复首内容串行排队并按可用内存分配预算 (#1474)
tesgth032 Sep 9, 2026
2d9ae9a
fix(logs): preserve UUID case and validate PostgreSQL indexes (#1479)
ding113 Sep 9, 2026
7e5124f
fix(langfuse): preserve streamed output and redact original headers (…
ding113 Sep 9, 2026
e83df23
fix(proxy): coordinate memory growth and pause local admission deadli…
ding113 Sep 9, 2026
20265ad
feat(providers): header templates and OpenCode Go adapter (#1480)
kexichan Sep 23, 2026
b40c7a2
fix(custom-headers): return null for unrecognized template expressions
Sep 23, 2026
99b87a4
fix(memory): stop MemoryGovernor 429 lockups from leaked leases and a…
kexichan Sep 23, 2026
87e0761
chore(deps): bump next in the npm_and_yarn group across 1 directory (…
dependabot[bot] Sep 23, 2026
01ba8af
fix(responses-ws): fall back to HTTP for oversized upstream requests …
ROOOO Sep 23, 2026
7fa4ff4
fix(migrations): create session prefix indexes outside runMigrations
Sep 23, 2026
dd35081
fix(providers): stop sending the raw session ID to OpenCode
Sep 23, 2026
d9b6fa6
fix(proxy): bound pre-auth capacity rejection attribution
Sep 23, 2026
8429453
fix(proxy): write redirected Gemini model names into the path literally
Sep 23, 2026
2a685e9
fix(langfuse): do not flag reconstructed streams as missing a response
Sep 23, 2026
ce01266
fix(langfuse): finalize parameterless tools and data-only Anthropic s…
Sep 23, 2026
e234254
fix(langfuse): send Responses usage as exclusive Langfuse buckets
Sep 23, 2026
a81bc76
fix(multicore): keep four database connections per auto-mode worker
Sep 23, 2026
256ecfe
test: cover the IPC callback retry path and assert the held gate lease
Sep 23, 2026
f5300b2
fix(migrations): refuse blocking prefix index builds on large tables
Sep 23, 2026
c6bc798
fix(migrations): scope the 0122 guard per table and list concurrent s…
Sep 23, 2026
a906155
fix(logs): preserve upstream errors in routing decision chains (#1490)
ding113 Sep 23, 2026
71278c9
fix(logs): match decision-chain entries to routing attempts exactly
Sep 23, 2026
17215e1
feat(providers): 供应商管理页展示上游余额 (#1492)
ding113 Sep 24, 2026
47a915f
fix(proxy): treat Anthropic refusal as a deliverable result, not an e…
Lynricsy Sep 25, 2026
926db2b
fix(providers): 正确识别 Sub2API 余额,支持用 New API 系统访问令牌查询账户余额 (#1496)
ding113 Sep 26, 2026
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
31 changes: 28 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ ADMIN_TOKEN=change-me
# 自动迁移控制(生产环境默认开启)
# 设置为 false 可禁用自动迁移
AUTO_MIGRATE=true
# 迁移时以 CREATE INDEX CONCURRENTLY 建索引的锁等待上限与单条语句上限(毫秒),超时会终止启动。
# 存在长事务或日志表很大时调高。
# MIGRATION_INDEX_LOCK_TIMEOUT_MS=5000
# MIGRATION_INDEX_STATEMENT_TIMEOUT_MS=900000

# 网关多核心模式(生产启动入口 cluster.js)
# - auto(默认):仅在有效 vCPU >= 4 且内存/共享预算足够时启用。4 vCPU 默认 2 个
# 完整网关进程,8+ vCPU 默认最多 4 个;请求正文始终只由其中一个进程持有,不经 IPC 复制。
# 完整网关进程,按 floor(vCPU/2) 扩展,最多 32 个,且每个进程至少分到 4 个数据库连接
# (默认 DB_POOL_MAX=20 时最多 5 个);正文不经 IPC 复制。
# - on:显式要求至少 2 个进程;off:保持单进程。
# - CCH_MULTICORE_WORKERS 可显式指定 1~32;1 等价于单进程。显式多进程仍会校验内存和预算。
# - 多进程依赖 Redis Pub/Sub 同步安全、路由、系统设置与 Provider group 计费倍率失效;未配置 Redis 或关闭
Expand Down Expand Up @@ -108,6 +113,11 @@ REDIS_TLS_REJECT_UNAUTHORIZED=true # 是否验证 Redis TLS 证书(默认
API_KEY_AUTH_CACHE_TTL_SECONDS="60" # 鉴权缓存 TTL(秒,默认 60,最大 3600)
ENABLE_API_KEY_REDIS_CACHE="true" # 是否启用 API Key Redis 缓存(默认:true)

# 供应商余额查询
PROVIDER_BALANCE_CACHE_TTL=600 # 上游余额快照缓存时间(秒,默认 600 = 10 分钟)
# 供应商管理页按该周期向上游重新查询余额;查询失败的快照最多缓存 120 秒
# 需要 REDIS_URL;没有 Redis 时每次请求都会直接查询上游

# Session 配置
# 降低该值会按签发时间收紧已签发 ADMIN_TOKEN 签名 cookie 的剩余寿命,且不会延长其原始 exp。
AUTH_SESSION_TTL_SECONDS=604800 # Web UI 登录态过期时间(秒,默认 604800 = 7 天,范围 60-31536000)
Expand Down Expand Up @@ -198,8 +208,21 @@ DETACHED_STREAM_METERING_RESERVE_BYTES=16777216
# 流式内容门禁在容器内共享的 precommit 原始字节与解析文本预算(默认 256 MiB,
# 内置多进程间分摊)。
# 预算不足时请求等待现有前缀被消费,不会关闭门禁或误触发供应商切换。
# 至少应为 STREAM_GATE_PREBUFFER_BYTE_CAP 的 4 倍。
STREAM_GATE_GLOBAL_PREBUFFER_BYTE_CAP=268435456
# 未设置时使用统一自动内存预算;显式设置仍作为门控子项上限。
# STREAM_GATE_GLOBAL_PREBUFFER_BYTE_CAP=268435456

# 受管业务内存总预算:默认根据可用 RAM + 0.5 * 可用 swap 自动计算。
# 同时遵守 cgroup v1/v2 可见祖先配额、memory.high,以及热点的物理余量。
# 该预算是应用软上限,不等于容器 RSS 硬限制。
# CCH_MEMORY_BUDGET_BYTES=auto
# 门控/正文溢写目录必须是本部署独享的真实磁盘目录,不能使用 tmpfs/ramfs。
# CCH_MEMORY_SPILL_DIR=/app/spool
# 容器内所有 workers 合计磁盘上限(默认 8 GiB,同时不超过可用磁盘的 10%)。
# CCH_MEMORY_SPILL_MAX_BYTES=8589934592
# 本地准入队列最多等待 20 秒,超时返回 429 + Retry-After: 1。
# 响应结束后,后台消费者(落库、快照、输家计费等)继续持有请求内存的最长无进展宽限(毫秒)。
# 到期后强制归还租约并记录卡住的所有者;实际宽限不短于 HEDGE_LOSER_DRAIN_TIMEOUT_MS + 30 秒。
# REQUEST_MEMORY_BACKGROUND_GRACE_MS=150000

# 入站压缩请求体(content-encoding: zstd/gzip/deflate/br)解压上限(字节)
# 功能说明:/v1、/v1beta 代理路径不受 proxyClientMaxBodySize 钳制,这两项是入站解压的内存/CPU 兜底。
Expand All @@ -220,6 +243,8 @@ LANGFUSE_SECRET_KEY= # Langfuse project secret key (sk-lf
LANGFUSE_BASE_URL=https://cloud.langfuse.com # Langfuse server URL (self-hosted or cloud)
LANGFUSE_SAMPLE_RATE=1.0 # Trace sampling rate (0.0-1.0, default: 1.0 = 100%)
LANGFUSE_DEBUG=false # Enable Langfuse debug logging
LANGFUSE_TRACING_ENVIRONMENT= # Optional environment tag (production/staging). Do not start with langfuse
LANGFUSE_RELEASE= # Optional release identifier (git sha or VERSION)

# 智能探测配置
# 功能说明:当熔断器处于 OPEN 状态时,定期探测供应商以实现更快恢复
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,4 @@ tmp/
.omx/
.opencode/
bunx-*/
.research/
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@

## Unreleased

### 新增

- Langfuse 流式请求还原完整最终输出(Claude / OpenAI Chat Completions / Responses / Gemini),避免把原始 SSE 文本当作 generation output
- Langfuse 将客户端原始请求头写入 generation `client_metadata`(凭据中间打码)
- 支持 `LANGFUSE_TRACING_ENVIRONMENT` / `LANGFUSE_RELEASE` 传入 LangfuseSpanProcessor
- 供应商自定义请求头支持动态模板:可用 `{{header.Name}}` 复制入站请求头,`{{session.id}}` 写入 Session ID,`{{session.client_id}}` 写入客户端 Session ID;来源缺失时跳过该头

### 优化

- Langfuse trace 名称改为 `user:shortModel`,去掉供应商前缀
- 按 Langfuse JS SDK v5 在 `propagateAttributes` 内创建 observation
- 大请求/响应体 1 MiB 截断,并在异步发送前快照,避免观测路径拖住完整 body

### 修复

- 修复上游响应流发生 error 后 Node/Undici body 未完成销毁的问题:Node-to-Web adapter 和 demand-driven pump
Expand Down
23 changes: 22 additions & 1 deletion cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
const cluster = require("node:cluster");
const path = require("node:path");
const { createClusterSupervisor } = require("./server-lib/cluster-supervisor");
const { createMemoryCoordinator } = require("./server-lib/memory-coordinator");
const { readResourceSnapshot } = require("./server-lib/resource-snapshot");
const {
createMulticorePlan,
detectRuntimeResources,
Expand Down Expand Up @@ -55,7 +57,11 @@ async function main() {
}

loadLauncherEnvironment();
const resources = detectRuntimeResources();
const detected = detectRuntimeResources();
const resources = {
...detected,
effectiveMemoryBytes: Math.min(detected.effectiveMemoryBytes, readResourceSnapshot().availableRamBytes),
};
const plan = createMulticorePlan({ env: process.env, resources });
log("info", "multicore_plan_resolved", {
enabled: plan.enabled,
Expand Down Expand Up @@ -86,6 +92,21 @@ async function main() {
exec: path.join(__dirname, "server.js"),
execArgv: process.execArgv,
});
process.env.CCH_MEMORY_COORDINATED = "1";
const memory = createMemoryCoordinator({ log });
const readyWorkers = new Set();
cluster.on("fork", (worker) => {
memory.attach(worker);
worker.on("message", (message) => {
if (message?.type !== "cch:gateway-ready") return;
readyWorkers.add(worker.id);
if (readyWorkers.size === plan.workerCount) memory.resetBaseline();
});
worker.once("exit", () => readyWorkers.delete(worker.id));
});
const monitor = setInterval(() => memory.sample(), 1000);
monitor.unref();
log("info", "memory_plan_resolved", memory.snapshot());

createClusterSupervisor({
clusterModule: cluster,
Expand Down
12 changes: 7 additions & 5 deletions docs/multicore-gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,26 @@
| 有效 vCPU < 4 | 单进程 |
| 4 vCPU、内存/预算足够 | 2 个完整网关 worker |
| 6 vCPU、内存/预算足够 | 3 个完整网关 worker |
| 8+ vCPU、内存/预算足够 | 最多 4 个完整网关 worker |
| 8+ vCPU、内存/预算足够 | `floor(vCPU/2)`,最多 32 个完整网关 worker |
| 未配置 Redis 跨进程缓存失效 | 单进程 |
| 内存或任一共享预算不足以安全容纳 2 个 worker | 单进程 |

自动数量为以下容量的最小值:

```text
min(4, floor(effective_vCPU / 2), memory_capacity, shared_budget_capacity)
min(32, floor(effective_vCPU / 2), memory_capacity, shared_budget_capacity, floor(DB_POOL_MAX / 4))
```

最后一项保证自动模式下每个 worker 至少有 4 个数据库连接(data 2、control 1、writer 1),避免三条连接 lane 退化为共用一个单连接池。默认 `DB_POOL_MAX=20` 时自动模式最多 5 个 worker;需要更多 worker 时按比例调高 `DB_POOL_MAX`。显式 `CCH_MULTICORE_WORKERS` 只要求每个 worker 至少 1 个连接。

每个进程预留两个 vCPU 的原因是主 JavaScript 线程之外仍有 GC、异步 zlib/libuv、TLS 和原生代码工作,避免“4 vCPU 启 4 个主线程”把尾延迟和内存推到不可控区间。需要覆盖默认值时可显式设置 worker 数。

## 资源探测

`server-lib/multicore.js` 使用最保守的可见资源值:

- CPU:`os.availableParallelism()`、cgroup v2 `cpu.max`、cgroup v1 CFS quota 和 cpuset 的最小值;小数 quota 向下取整。
- 内存:`os.totalmem()` 与 cgroup v2/v1 memory limit 的最小值。
- worker 容量:`os.totalmem()`、cgroup v2/v1 memory limit 和当前实际可用物理内存的最小值。swap 不用于增加 worker 数量。
- 默认每个完整网关预留 1024 MiB,并为轻量 primary/运行时开销预留 256 MiB。

自动模式还要求配置 `REDIS_URL`,且 `ENABLE_RATE_LIMIT` 不能关闭。错误规则、请求过滤器、敏感词、Provider cache、系统设置、Provider group 计费倍率、熔断配置和 API Key Vacuum Filter 等进程本地快照使用 Redis Pub/Sub 接收微小的失效通知;没有这条控制通道时自动回退单进程,避免管理写入只刷新命中它的某一个 worker。显式要求多进程但缺少该通道会直接启动失败。Redis 在启动或运行期间暂时不可用时,订阅登记不会丢失:共享订阅器按 1 秒到 60 秒的指数退避持续重试;首次订阅和每次重连成功后都会向所有登记者合成一次 resync 失效,强制从数据库等权威存储重载,从而覆盖 Pub/Sub 无法补发的断线窗口。恢复前仍沿用现有多实例 fail-open 语义。
Expand Down Expand Up @@ -94,7 +96,7 @@ Provider group 倍率缓存额外使用版本号阻止“更新通知到达后
| `DETACHED_STREAM_MAX_CONCURRENCY` | 64 | 1 | 防止 detached stream 数量倍增 |
| `DETACHED_STREAM_BUDGET_BYTES` | 64 MiB | 3 MiB + 64 KiB | 限制 detached/replay 缓冲 |
| `DETACHED_STREAM_METERING_RESERVE_BYTES` | 16 MiB | 64 KiB | 保留最小计量空间 |
| `STREAM_GATE_GLOBAL_PREBUFFER_BYTE_CAP` | 256 MiB | `4 * STREAM_GATE_PREBUFFER_BYTE_CAP` | 限制 stream gate 前缀缓冲 |
| `STREAM_GATE_GLOBAL_PREBUFFER_BYTE_CAP` | 未显式设置时使用统一自动预算 | 128 KiB | 按实际前缀记账,超出热额度落盘 |
| `REPLAY_MAX_CONCURRENT_SPOOLS` | 64 | 1 | 防止每进程各自获得完整 spool 并发 |

例如默认 2 worker 时,`DB_POOL_MAX=20` 变成 10/10;3 worker 时是 7/7/6。Kubernetes 的多个 Pod 仍各自拥有一份聚合预算,所以数据库总连接上限需要按 Pod 数继续核算。
Expand Down Expand Up @@ -133,7 +135,7 @@ CCH_MULTICORE_PRIMARY_MEMORY_RESERVE_MB=256

- 回滚到旧的单进程拓扑:`CCH_MULTICORE_MODE=off` 或 `CCH_MULTICORE_WORKERS=1`。
- 4 vCPU 但内存小于默认安全模型:保持单进程,或在压测证明安全后显式下调 `CCH_MULTICORE_MEMORY_PER_WORKER_MB`;最低允许 256 MiB,不代表生产推荐值。
- 指定更多 worker:同时复核聚合 DB/stream/replay/writer 预算;launcher 最多允许 32,自动模式最多 4。
- 指定更多 worker:同时复核聚合 DB/stream/replay/writer 预算;显式配置与自动模式上限均为 32。
- 外部已经为每个容器限制到 1~2 vCPU:维持单进程并通过 Pod/容器副本横向扩展通常更简单。

`CCH_MULTICORE_ACTIVE`、`CCH_MULTICORE_WORKER_INDEX`、`CCH_MULTICORE_WORKER_COUNT` 和 `CCH_MULTICORE_BACKGROUND_OWNER` 由 launcher 写入,不能作为普通部署配置手工拼装。
Expand Down
Loading
Loading