Files
Cyrene_v2/internal/config/decode.go
T
AskaEth 72b95df22b
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(config,runtime): 上下文预算按模型窗口推导 + usage/缓存可观测 + sidecar 存全文(T1)
- 窗口声明:models.json 组级 contextWindow + env LLM_CONTEXT_WINDOW(per-group materialize 播种,0 不写盘、负数报错)。

- 预算三态:CONTEXT_MAX_TOKENS 未设置 ⇒ 按窗口推导;>0 显式覆盖;0|负 关闭压缩(不变)。推导 budget = min(窗口×比例, 窗口−输出保留),比例默认 2/3(CONTEXT_BUDGET_RATIO,1M ⇒ 699050 tokens ≈ 683Ki);输出保留 = max(32768, 该组 maxTokens) 且封顶窗口/2(防配置矛盾时退化成 1 token);窗口未声明 ⇒ 回落 131072 + 恰好一条 WARN。接线在组合根 wire_context.go(唯一决策点)。

- usage/缓存可观测(此前**完全不可观测**):Response 增 CacheHit/CacheMiss/Reasoning tokens + CacheHitRate;解析 OpenAI 兼容(prompt_cache_hit_tokens/prompt_cache_miss_tokens/cached_tokens/reasoning_tokens)与 anthropic(cache_read_input_tokens/cache_creation_input_tokens)两种形状;记录点在适配器 record(换入口不丢成本日志),日志无凭据;单次输入 ≥预算 90% 记 WARN(不阻断)。

- 根治清单「续读」假承诺:抽取期不再按注入预算截断(sidecar 存全文,只受 MaxSidecarBytes=8 MiB 安全上限,ExtractorVersion v1→v2 旧 sidecar 失效重抽);注入预算改在装配期生效 ⇒ ref.Chars/Truncated 是注入侧事实、游标真是继续读的起点;document-read 的 limit 上限改为独立具名常量。

- 顺手修越界:config.go 505 行(超 500)拆出 llm.go。

- 主会话独立验收:隔离 worktree(HEAD + 本切片 39 文件,排除在途 gateway)build/vet 绿、全树 59 包 0 FAIL、linux+darwin 交叉编译绿;变异独立复现(比例改 0.25 ⇒ 推导用例红 262144 vs 699050)。
2026-10-04 17:57:08 +08:00

178 lines
4.4 KiB
Go

package config
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
)
// decodeValue populates the struct pointed to by v. Precedence, highest first:
// process environment variable, the parsed .env file, then the default tag.
func decodeValue(v reflect.Value, fromEnv map[string]string) error {
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return fmt.Errorf("config: decode expects a pointer to a struct")
}
return decodeStruct(v.Elem(), fromEnv)
}
func decodeStruct(sv reflect.Value, fromEnv map[string]string) error {
st := sv.Type()
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
if !field.IsExported() {
continue
}
fv := sv.Field(i)
envTag, hasEnv := field.Tag.Lookup("env")
if !hasEnv {
// Untagged struct fields are nested config groups.
if fv.Kind() == reflect.Struct {
if err := decodeStruct(fv, fromEnv); err != nil {
return err
}
}
continue
}
name := envTagName(envTag)
raw := lookupRaw(name, field.Tag.Get("default"), fromEnv)
if err := setField(fv, raw); err != nil {
return fmt.Errorf("config: %s: %w", name, err)
}
}
return nil
}
// envTagName extracts the variable name from an env tag (dropping any
// comma-separated options that may be added later).
func envTagName(tag string) string {
name, _, _ := strings.Cut(tag, ",")
return strings.TrimSpace(name)
}
// lookupRaw returns the effective raw value for key: process env, then .env,
// then default.
func lookupRaw(key, def string, fromEnv map[string]string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
if v, ok := fromEnv[key]; ok {
return v
}
return def
}
// envProvided reports whether key was given by the process environment or the
// .env file — the same precedence chain as lookupRaw, only separating out the
// "fell through to the default tag" case. It carries semantics that need to
// tell "unset" from "explicitly zero" (CONTEXT_MAX_TOKENS: 0 = compaction off,
// unset = derive the budget from the model window), which a plain zero value
// cannot express.
func envProvided(key string, fromEnv map[string]string) bool {
if _, ok := os.LookupEnv(key); ok {
return true
}
_, ok := fromEnv[key]
return ok
}
func setField(fv reflect.Value, raw string) error {
switch fv.Kind() {
case reflect.String:
fv.SetString(raw)
return nil
case reflect.Bool:
return setBool(fv, raw)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// time.Duration is an int64 kind but is configured as a Go duration
// string (e.g. "720h"), so it must be parsed before the integer path.
if fv.Type() == reflect.TypeOf(time.Duration(0)) {
return setDuration(fv, raw)
}
return setInt(fv, raw)
case reflect.Float32, reflect.Float64:
return setFloat(fv, raw)
case reflect.Slice:
return setStringSlice(fv, raw)
default:
return fmt.Errorf("unsupported kind %s", fv.Kind())
}
}
func setBool(fv reflect.Value, raw string) error {
if raw == "" {
fv.SetBool(false)
return nil
}
b, err := strconv.ParseBool(strings.ToLower(raw))
if err != nil {
return fmt.Errorf("invalid boolean %q", raw)
}
fv.SetBool(b)
return nil
}
func setInt(fv reflect.Value, raw string) error {
if raw == "" {
fv.SetInt(0)
return nil
}
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return fmt.Errorf("invalid integer %q", raw)
}
fv.SetInt(n)
return nil
}
func setFloat(fv reflect.Value, raw string) error {
if raw == "" {
fv.SetFloat(0)
return nil
}
n, err := strconv.ParseFloat(raw, 64)
if err != nil {
return fmt.Errorf("invalid float %q", raw)
}
fv.SetFloat(n)
return nil
}
// setDuration parses a Go duration string (e.g. "720h", "30m") into a
// time.Duration field. An empty value sets the zero duration.
func setDuration(fv reflect.Value, raw string) error {
if strings.TrimSpace(raw) == "" {
fv.SetInt(0)
return nil
}
d, err := time.ParseDuration(raw)
if err != nil {
return fmt.Errorf("invalid duration %q", raw)
}
fv.SetInt(int64(d))
return nil
}
func setStringSlice(fv reflect.Value, raw string) error {
if fv.Type().Elem().Kind() != reflect.String {
return fmt.Errorf("unsupported slice element kind %s", fv.Type().Elem().Kind())
}
if strings.TrimSpace(raw) == "" {
fv.Set(reflect.MakeSlice(fv.Type(), 0, 0))
return nil
}
parts := strings.Split(raw, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if t := strings.TrimSpace(p); t != "" {
out = append(out, t)
}
}
fv.Set(reflect.ValueOf(out))
return nil
}