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
3 changes: 3 additions & 0 deletions .github/workflows/backend-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ jobs:
run: |
go test -race -p 1 -parallel 1 -tags=unit ./internal/service -run '^TestDeepSeekNativeReasoningReplay' -count=1
go test -race -p 1 -parallel 1 -tags=unit ./internal/repository -run 'Test.*(Reasoning|Redis)' -count=1
- name: Fork v2.3.175 protocol and cache regression
working-directory: backend
run: go test -race -p 1 -parallel 1 -tags=unit ./internal/service ./internal/repository -run '^Test(FilterThinkingBlocks|SanitizeAnthropicBodyForBetaTokens_ContextManagementCompactBeta|NormalizeOpenAIResponsesLitePayload_NullBodyDoesNotPanic|SanitizeOpenAIResponsesInputItemIDsMatchesLegacy|SanitizeOpenAIResponsesInputItemIDsTruncatedBodiesMatchLegacy|SanitizeOpenAIResponsesInputItemIDsLeadingWhitespaceKeepsOffsets|StripGrokAPIKeyOpenAICompatFieldsMatchesLegacy|ReasoningContent|DeepSeekNativeReasoningReplayTreatsUndecodableCacheValueAsMiss|ChannelMonitorV2RefreshesEarlierDurableCursor|ClientErrorPrivacy.*PublicLink|SilentRefusalDetector)' -count=1
- name: Session revocation, atomic codes and gateway admission regression
working-directory: backend
run: go test -race -p 1 -parallel 1 -tags=unit ./internal/pkg/httputil ./internal/repository ./internal/service ./internal/handler ./internal/server/middleware ./internal/server/routes -run 'Test(AuthUserTokenCutoff|EmailCode|JWTRevocation|AuthHandlerRevokeAllSessions|OAuthBindCookieRejects|GroupModelAllowlist|GatewayRoutesGroupModelAllowlist|NormalizeLenientJSONRequestBody|DeepSeek|NativeAnthropicPassthrough|PatchGrokResponsesBody|NormalizeGrokChatReasoningEffort|ReleaseAccountSession|CleanupStaleProcessSlots)' -count=1
Expand Down
4 changes: 4 additions & 0 deletions LOCAL_FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,7 @@ Mixed 聚合平台及其协议探测回退、厂商倍率、API Key 四类互斥
二改正式检查点推进至 v2.3.164(`078bc0375`),适配网关斜杠兼容、后台模式 Passkey 完成、统计分拆、首屏加载和余额刷新。保留现有生图分组、Images API、本地计费、主题及既有延期项,原版检查点不变。用户随后授权提交 GitHub 并更新部署,个人 VERSION 升至 2.1.74,按 PR/CI、自有 Release/GHCR、备份实际恢复验证及受控切换流程发布;最终身份和线上验收另存发布证据。完整选择及验证见[同步记录](maintenance/notes/upstream-sync-20261125-v23164-no-canvas.md),发布说明见[个人 v2.1.74](docs/release-notes/v2.1.74.md)。

按用户最新决定移除无限画布的业务源码、入口、代理、专属 CSP 及构建发布接入,取代上一条恢复决定。历史 v2.1.73 记录中的 `canvas/README.md` 等路径已撤下,历史提交与归档保留。画布依赖目录 `canvas/web/node_modules` 的物理删除被自动审批拒绝,暂留本机且不参与构建或分发;具体拦截记录见本轮诊断资料。

## 2026-11-26:二改 v2.3.175 选择性同步

二改正式检查点推进至 v2.3.175(`595b9a2fe`);原版最新正式版仍为已审的 v0.2.25,未发布 main 只观察。适配 Claude 历史签名与压缩 beta、Responses Lite 空值、错误参数和官方链接的脱敏边界(补齐编码凭据回归)、请求 ID/Grok 改写分配、独立且隔离的 DeepSeek 推理缓存压缩、静默拒答观察器、分组策略缓存时效及监控持久游标。保留内部诊断证据、生图 API/分组/计费、原生路由与主题,继续移除无限画布。新计费 schema、完整多因子恢复、共享统计缓存及 SQL 聚合重写分别保留明确延期,取舍与验证见[同步记录](maintenance/notes/upstream-sync-20261126-v23175.md)和[逐项清单](maintenance/notes/fork-selection-ledger-20261126-v23175.json)。同步阶段个人 VERSION 保持 2.1.74,未提交或部署;用户随后授权提交 GitHub 并更新部署,准备以 v2.1.75 沿用现有 PR/CI、自有 Release/GHCR、备份实际恢复和受控切换流程,最终发布与生产验收另存证据。
2 changes: 1 addition & 1 deletion backend/cmd/server/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.1.74
2.1.75
10 changes: 7 additions & 3 deletions backend/internal/repository/gateway_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,11 @@ func (c *gatewayCache) SetReasoningContent(ctx context.Context, itemID string, c
if ttl <= 0 {
ttl = reasoningContentDefaultTTL
}
return c.reasoningRdb.Set(ctx, reasoningContentPrefix+itemID, content, ttl).Err()
return c.reasoningRdb.Set(ctx, reasoningContentPrefix+itemID, encodeReasoningContent(itemID, content), ttl).Err()
}

// GetReasoningContent 返回缓存的 reasoning 全文;未命中返回
// service.ErrReasoningContentNotFound。
// service.ErrReasoningContentNotFound。损坏或超限的压缩值也按未命中处理。
func (c *gatewayCache) GetReasoningContent(ctx context.Context, itemID string) (string, error) {
if c == nil || c.reasoningRdb == nil {
return "", errors.New("gateway cache unavailable")
Expand All @@ -319,7 +319,11 @@ func (c *gatewayCache) GetReasoningContent(ctx context.Context, itemID string) (
}
return "", err
}
return val, nil
content, ok := decodeReasoningContent(val)
if !ok {
return "", service.ErrReasoningContentNotFound
}
return content, nil
}

const (
Expand Down
113 changes: 113 additions & 0 deletions backend/internal/repository/gateway_cache_reasoning_codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package repository

import (
"bytes"
"compress/gzip"
"io"
"strings"
"sync"

"github.com/Wei-Shaw/sub2api/internal/service"
)

// reasoning 缓存值的透明压缩(只改 gatewayCache 的存取,key 名与 TTL 都不变)。
//
// 为什么:DeepSeek 原生 reasoning 条目(key 形如
// reasoning_content:deepseek-native-v1:<scopeHash>:<itemHash>,值是
// {"content":[reasoning_text...],"encrypted_digest":"..."})保存可压缩的文本。
// scopeHash 继续由本地用户、会话、模型共同生成,不改变隔离键或 Redis 客户端。
//
// 格式:压缩值就是一个标准 gzip 流(以 1f 8b 08 开头),其余值保持明文。
// - 读:以 1f 8b 08 识别。合法 UTF-8(JSON、summary 文本)不可能以 0x1f 0x8b 开头
// (0x8b 是续字节),所以不会与旧版本写入的明文冲突;
// - 写:明文若恰好以该前缀开头(只可能是任意二进制输入)也强制压缩,使任意字符串
// 都能无损往返,读侧不需要猜。
//
// 兼容(蓝绿 / 回滚):压缩引入前的本地 v2.1.74 读到压缩值时,DeepSeek 原生读侧
// (prepareDeepSeekNativeReasoningReplay)对它 json.Unmarshal 失败,按未命中处理,随后
// 原有 replay helper 补占位符——与 Redis 被清空时一样,只是
// 那一轮丢掉这条历史 reasoning,不报错、不 400、不 panic。
// 所以只压缩这一族:老族 reasoning_content:<itemID> 由 reasoningContentByID 把读到的
// 字符串原样当 reasoning 文本塞进上游请求,旧进程读到二进制会把乱码当历史 reasoning
// 发给上游;该家族因此保持明文。

const (
// reasoningCompressMinBytes:小于该长度的值收益可忽略(gzip 头尾约 20 字节),直接存原文。
reasoningCompressMinBytes = 512
// reasoningMaxDecodedBytes:解压输出上限(防压缩炸弹)。DeepSeek 原生条目写入上限是
// 2MiB(deepSeekNativeReasoningMaxBytes),留一倍余量;超过按未命中处理。
reasoningMaxDecodedBytes = 4 << 20
)

// 沿用来源修复的 gzip.DefaultCompression(6),复用编解码器以减少逐条分配。
var (
reasoningGzipWriters = sync.Pool{New: func() any { return gzip.NewWriter(io.Discard) }}
reasoningGzipReaders sync.Pool // *gzip.Reader;池空时由 gzip.NewReader 现建
)

func hasGzipMagic(s string) bool {
return len(s) >= 3 && s[0] == 0x1f && s[1] == 0x8b && s[2] == 0x08
}

// reasoningCompressibleKey 只放行 DeepSeek 原生族,原因见文件头注释。
func reasoningCompressibleKey(itemID string) bool {
return strings.HasPrefix(itemID, service.DeepSeekNativeReasoningCacheKeyPrefix)
}

// encodeReasoningContent 返回应当写进 Redis 的字符串:够大、可压缩且压缩后确实更小
// 才存 gzip,否则存原文。一次写入只压缩一次。
func encodeReasoningContent(itemID, content string) string {
// 明文长得像 gzip 头时必须包一层,否则读侧会把它当压缩流。
mustWrap := hasGzipMagic(content)
if !mustWrap && (len(content) < reasoningCompressMinBytes || !reasoningCompressibleKey(itemID)) {
return content
}
z, ok := gzipReasoning(content)
if !ok || (!mustWrap && len(z) >= len(content)) {
return content
}
return z
}

func gzipReasoning(content string) (string, bool) {
zw, ok := reasoningGzipWriters.Get().(*gzip.Writer)
if !ok {
return "", false
}
var buf bytes.Buffer
buf.Grow(len(content)/2 + 64)
zw.Reset(&buf)
_, werr := zw.Write([]byte(content))
cerr := zw.Close()
reasoningGzipWriters.Put(zw)
if werr != nil || cerr != nil {
return "", false
}
return buf.String(), true
}

// decodeReasoningContent 还原 encodeReasoningContent 的结果。ok=false 表示「当作未命中」:
// 压缩流损坏/被截断、或解压后超过 reasoningMaxDecodedBytes。
func decodeReasoningContent(stored string) (string, bool) {
if !hasGzipMagic(stored) {
return stored, true // 旧版本写入的明文,或未压缩的小值
}
src := strings.NewReader(stored)
zr, _ := reasoningGzipReaders.Get().(*gzip.Reader)
if zr == nil {
var err error
if zr, err = gzip.NewReader(src); err != nil {
return "", false
}
} else if err := zr.Reset(src); err != nil {
reasoningGzipReaders.Put(zr)
return "", false
}
defer reasoningGzipReaders.Put(zr)
// 多读 1 字节用来区分「恰好等于上限」和「超过上限」。读到 EOF 时 gzip 会校验 CRC 与长度。
out, err := io.ReadAll(io.LimitReader(zr, reasoningMaxDecodedBytes+1))
if err != nil || len(out) > reasoningMaxDecodedBytes {
return "", false
}
return string(out), true
}
Loading
Loading