Documentation
¶
Overview ¶
本文件是 debug payload 的内容寻址存储(CAS)层:跨目录重复的 字节区间(系统提示/工具声明/会话历史前缀——01 叶子质量跨 dir 复用实测 ~92%)以 CDC 切块后按内容哈希共享入库。
存储模型:debug_blobs 装切块明文(EncodePayload 编码,hash 取 明文 sha256 截 16B),debug_chunk_refs 记「哪个文件行引用了哪些 blob」(GC 视图,随行同生死),debug_files 的 01 行本体只存 manifest(casMagic + usize + 有序 (hash,len) 表)。保活不变式 「blob 活 ⟺ ∃ ref 行」由三件事维持:blob/ref/manifest 同批事务 落库(无孤儿窗口);ref 随文件行同一 WHERE 被删除漏斗带走; ReapOrphanBlobs 在写连接上做 mark-sweep 兜底(含回滚期旧二进制 删 dir 不知 refs 表留下的悬垂 ref 先扫一道)。
只有 01-http-request.json 走本形态:02/03* 对 01 的同 dir delta 残差已 1-5%,切块对齐不上;04/06 流式行不进首版。manifest 行 usize 恒 >0(逻辑尺寸),DebugFile 的「usize>0 → 整读解码」分支 因此恒兜住它。
本文件是 logs 预聚合 rollup(log_cells/log_err_cells 两表)的单一 事实源:列注册表、DDL、回填/补漏 INSERT SELECT、写路径行贡献 (Go 镜像)与读侧 SUM 清单全部由 cellMetrics 一份登记表派生。
设计要点:
- 格子键 (slot, day, api, emodel, key_hash):slot=time/600000 是 600 秒桶序号;day 是逐行物化的本地日期(strftime localtime 同 源)——600s 槽会横跨本地午夜(时区偏移非 600s 整数倍,如 +5:45 尼泊尔),把 day 作维度而非派生谓词,让「按自然日聚合」对全部 时区都精确;slot 查询对跨界 cell 直接 SUM 两行,同样精确。
- 全部指标列是可加量(SUM/COUNT 形态),跨粒度任意再聚合; min_time 记最早行时刻(entries 的 window_start),last_key 是 printf('%020d',id)|started_at 打包串——字符串 MAX 等价于 「最大 id 行的 started_at」,替代裸列绑定(同查询里还有 MIN(time),多个 min/max 聚合下裸列归属不确定)。
- 覆盖水位线 runtime_state.log_cells_covered_id:所有 id ≤ 水位 的 logs 行都已完成 rollup 记账(非 rejected 已入格、rejected 被有意剔除)。双写路径在同一事务推进水位;任何绕过双写的 写入(无 cells 码的旧二进制、外部工具、importIndex)由 Open 收尾的 ReconcileCells 补记。
- rejected 行(管线前拒绝)不进 rollup——全部聚合口径本来就 剔除它;log_err_cells 只记 error_stage != ” 的行(错误稀疏, 单列迷你表比给主表加错误维度便宜得多)。
本文件是 debug payload 的透明压缩层:写入侧对超阈值的内容先压缩 再入库,读出侧按 magic bytes 判帧解压——无魔数的存量行原样透传, 不需要回填。usize 列记解压前字节数(0=未压缩),清单与截断读的 total 口径保持逻辑尺寸,容量淘汰仍按库存尺寸计磁盘占用。
四种库存形态:gzip(独立压缩)、zstd delta 帧(以同目录 01 明文为 raw dict 的 patch-from 编码——02/03-devin-request* 与 01 是同一请求 的三重投影,字节级冗余让它们只存残差)、raw(小体/压不出收益的)、 CAS manifest(01 的内容寻址指针行,见 cas.go)。读侧对 zstd 帧必须 取回字典才能解码,见 DebugFile 的基座取用。
本文件是调试 payload(debug_files/debug_chunks 两表)的领域方法。
存储模型镜像文件时代的 logs/<dir>/ 目录:dir 是请求目录名(仍作 X-Request-Id/debug_ref 身份),name 是目录内相对路径(顶层文件或 attachments/xxx)。一次性整文件(meta.json、error.json、01-03、 attachments/*)进 debug_files;流式 JSONL(04/05/06)按 flush 批 追加进 debug_chunks,读时 ORDER BY seq 拼接——追加行代替 BLOB 反复重写,飞行中请求的已提交前缀对面板实时可见,崩溃后已写帧不丢。
本文件是 detached_events 表(脱钩流完成缓存的生命周期台账)的读写 路径。写方是 adapter/devin 的 detachedRegistry.pushEvent:内存事件环 每条生命周期事件同步落一行——环只有 64 条且随进程死蒸发,而脱钩事件 的两侧请求目录都可能缺席(claim 失败的重试零 payload、origin 标记行 在 sqlite 争用风暴中被丢弃),本表是「脱钩后谁来接过、怎么收场」的 兜底取证面。kind/detail 词表由写方定版:admit/attach/miss/cross_miss/ evict/finish/truncate,detail 记移除原因或泵终局档。
本文件是 ImportLegacy 的逆方向:把库内状态写回文件时代布局 (logs/index.jsonl、auth_tokens.json、models.json、 panel-settings.json、quota.jsonl、gate-state*.json)。 upstream_accounts.yaml 是例外:面板账号没有文件时代对应物,导出的是 手工粘回 config.yaml devin.accounts 的片段,ImportLegacy 不回灌。
服务的两类逃生场景:(a) 回滚文件版二进制且要保住 sqlite 窗口期 写入——auth_tokens 的面板令牌变更是唯一真权限损失;(b) DB 损坏 或误删时的取证重建。入口是主二进制的 -export-legacy flag:服务 起不来恰是最需要导出的场景,admin 端点那时不可用。
本文件是 lane_attempt_causes 表(号池被放弃 lane 尝试的持久聚合账) 的读写路径。写方是 logs 行的同事务展开:LogRow.SwitchCauses(由 debuglog.logRowFor 从 meta.json 同源的 upstream_attempts 投影)在 InsertLog/WriteDebugBatch 里按 (day,lane,cause) 主键累加——meta.json 的 upstream_attempts 明细受 payload 与目录保留期约束会淘汰,本表 是「为什么换号」的唯一持久口径。cause 词表的唯一事实源在 logvocab (写方 debuglog.switchCauseKey 经它取词):local_gate[:reason] 是 本地闸门快败的幻影换号(零上游发送)、connect code 是真实 failover 发送、nocode 是无 code 的传输断裂。
本文件是 logs 表的读路径:列表检索(SearchLogs 的状态表达式/q/时间窗 等全量筛选都下推 SQL)、格子聚合(LogCells 替代旧的内存 rollup)、 短窗速率(recent 口径)、last_* 快照与趋势种子。
语义对齐被替换的 index.jsonl 读取面(debuglog.reader 的 match 与 ccpanel.rollup 的格子口径),差异只有两处有意的升级:计数精确化 (不再受 4MB 尾部窗口约束)与时间边界改成毫秒闭区间(修掉旧实现 started_at 纳秒严格比较在边界丢掉最后 1ms 内行的问题)。
本文件是 /admin/usage 与 runtime-metrics 延迟组的聚合读路径—— 旧 debuglog.usageAggregator(内存 replay 索引尾部)的 SQL 版。 聚合源头从「256MB 索引尾部回放」升级为 logs 全表:条数/维度计数由 GROUP BY 一次算出,分位数仍按旧口径取最近 N 条样本在 Go 侧排序 (SQLite 无原生分位数;窗口函数把「每桶/每维最近 N 条」压成一次扫描)。
本文件是 schema_migrations 表的运行器:schema.go 的 CREATE TABLE 始终声明当前形状(新列可直接写进建表语句),这里的版本化迁移为 存量库补同样的演进——补列一律走 addColumnIfAbsent 幂等执行,新库 上「列已在」只登记版本不重复 ALTER。每条迁移一个版本号、一个事务 ——apply 与版本登记同提交,不存在 DDL 成功而登记失败的半迁移窗口; 任一迁移失败 Open 即报错退出。
事务一律 BEGIN IMMEDIATE(writeTx):deferred 事务先读 (pragma_table_info 探列)后写(ALTER 升级写锁)时,读快照与升级 之间被并发写挤入会吃 SQLITE_BUSY_SNAPSHOT 快败——busy_timeout 救 不了过期快照(9-19 prod 实证:交接进程迁移 6ms 死于此,正值在役 实例提交请求行)。IMMEDIATE 在 BEGIN 即取写锁、借 busy_timeout 排队等锁,没有读快照就没有 SNAPSHOT 类。写锁被连续占压越过单次 排队耐心(在役实例的长写事务)时外层按 migrationLockBudget 重试 整轮事务——失败即回滚还原,重跑幂等。
Package store 是全部面板可见状态的 SQLite 持久层:请求日志、调试 payload、下游令牌、模型注册表、面板设置、配额采样与运行时小状态。 它取代原先的 index.jsonl/auth_tokens.json/models.json/ panel-settings.json/quota.jsonl/gate-state*.json 文件持久化。
读写分离双池:写只走 db(单连接串行化——ccLoad 实证 SQLite 多连接 高并发写触发 BUSY/DEADLOCK);读只走 ro(WAL 下多读者与写者并行, query_only pragma 在连接级拒绝写语句)。面板聚合读不再与日志写、 配额采样、retention 清扫互相排队。
Index ¶
- Constants
- Variables
- func DecodePayloadFile(data, dict []byte) ([]byte, error)
- func EncodePayload(data []byte) (stored []byte, usize int64)
- func EncodePayloadDelta(data, base []byte) (stored []byte, usize int64)
- func GateStateKey(lane string) string
- func IsBusy(err error) bool
- type AccountRow
- type AccountUsageRow
- type AccountUsageToday
- type CASChunk
- type CellsAuditReport
- type CellsBackfillReport
- type DebugBatch
- type DebugBlobRow
- type DebugChunkRow
- type DebugFileInfo
- type DebugFileRow
- type DebugRefRow
- type DetachedBlob
- type DetachedEvent
- type DimensionAgg
- type ExportReport
- type GateDaySends
- type GateWindow
- type LaneAttemptCause
- type LatencyStats
- type LogCellKey
- type LogCellTotals
- type LogModelLast
- type LogQuery
- type LogRecentAgg
- type LogRow
- type LogScope
- type LogTrendSeed
- type MatrixCell
- type ModelEntry
- type PayloadDeltaEncoder
- type PayloadEncoder
- type QuotaSample
- type RateLimitEvent
- type ResolvedAccount
- type SendsRowDay
- type Store
- func (s *Store) AccountsUsage(ctx context.Context, accounts []string) (map[string]*AccountUsageRow, error)
- func (s *Store) AppendDebugChunks(ctx context.Context, rows []DebugChunkRow) error
- func (s *Store) BackfillCells(ctx context.Context, slotLo, slotHi int64, apply bool) (*CellsBackfillReport, error)
- func (s *Store) CellsAudit(ctx context.Context, slotLo, slotHi int64) (*CellsAuditReport, error)
- func (s *Store) ClaimDebugFile(ctx context.Context, dir, name string, content []byte) (claimed bool, err error)
- func (s *Store) Close() error
- func (s *Store) DBBytes() int64
- func (s *Store) DebugBlobBytes(ctx context.Context) (int64, error)
- func (s *Store) DebugDirSizes(ctx context.Context) (map[string]int64, error)
- func (s *Store) DebugDirSizesSplit(ctx context.Context, anchor []string) (total, strippable map[string]int64, err error)
- func (s *Store) DebugDirs(ctx context.Context) ([]string, error)
- func (s *Store) DebugDirsByPrefix(ctx context.Context, prefix string) ([]string, error)
- func (s *Store) DebugDirsContaining(ctx context.Context, name string) (map[string]bool, error)
- func (s *Store) DebugErrorSignatures(ctx context.Context) (map[string][2]string, error)
- func (s *Store) DebugFile(ctx context.Context, dir, name string, maxBytes int64) (data []byte, total int64, ok bool, err error)
- func (s *Store) DebugFileList(ctx context.Context, dir string) ([]DebugFileInfo, error)
- func (s *Store) DebugFileNames(ctx context.Context, dir string) ([]string, error)
- func (s *Store) DebugPayloadBytes() int64
- func (s *Store) DeleteAccount(ctx context.Context, name string) error
- func (s *Store) DeleteDebugDir(ctx context.Context, dir string) error
- func (s *Store) DeleteDebugDirsBefore(ctx context.Context, dirPrefix string, exclude []string) error
- func (s *Store) DeleteDebugPayloadsBefore(ctx context.Context, bound string, exact, prefixes []string) error
- func (s *Store) DeleteLogsBefore(ctx context.Context, ms int64) (int64, error)
- func (s *Store) DeleteModel(ctx context.Context, model string) error
- func (s *Store) DeleteSetting(ctx context.Context, key string) error
- func (s *Store) DeleteState(ctx context.Context, key string) error
- func (s *Store) DeleteToken(ctx context.Context, id int64) error
- func (s *Store) EffectiveAccounts(ctx context.Context, declared []config.DevinAccountConfig) ([]ResolvedAccount, error)
- func (s *Store) ExistsLogBefore(ctx context.Context, q LogQuery) (bool, error)
- func (s *Store) ExportLegacy(ctx context.Context, stateDir, logRoot string) (*ExportReport, error)
- func (s *Store) GCTombstonedAccounts(ctx context.Context, declared []string) (int64, error)
- func (s *Store) GateSendsByDay(ctx context.Context, sinceUnix int64) (map[string]GateDaySends, int, error)
- func (s *Store) GetAccount(ctx context.Context, name string) (row *AccountRow, ok bool, err error)
- func (s *Store) GetSetting(ctx context.Context, key string) (value string, updatedAt int64, ok bool, err error)
- func (s *Store) GetState(ctx context.Context, key string) (value string, ok bool, err error)
- func (s *Store) ImportDebugDirs(ctx context.Context, logRoot, progressKey string) error
- func (s *Store) ImportLegacy(ctx context.Context, stateDir, logRoot string) error
- func (s *Store) IncrementalVacuum(ctx context.Context) error
- func (s *Store) InsertDetachedBlob(ctx context.Context, b DetachedBlob) error
- func (s *Store) InsertDetachedEvent(ctx context.Context, e DetachedEvent) error
- func (s *Store) InsertGateWindow(ctx context.Context, w *GateWindow) error
- func (s *Store) InsertLog(ctx context.Context, e *LogRow) (int64, error)
- func (s *Store) InsertQuotaSample(ctx context.Context, q *QuotaSample) error
- func (s *Store) InsertToken(ctx context.Context, t *TokenRow) (int64, error)
- func (s *Store) LaneAttemptCauses(ctx context.Context, sinceDay string) ([]LaneAttemptCause, error)
- func (s *Store) ListAccounts(ctx context.Context) ([]*AccountRow, error)
- func (s *Store) ListGateWindows(ctx context.Context, lane string, since int64, limit int) ([]*GateWindow, error)
- func (s *Store) ListModels(ctx context.Context) ([]ModelEntry, error)
- func (s *Store) ListQuotaSamples(ctx context.Context, account string, since int64, limit int) ([]*QuotaSample, error)
- func (s *Store) ListSettings(ctx context.Context) (values map[string]string, updated map[string]int64, err error)
- func (s *Store) ListTokens(ctx context.Context) ([]*TokenRow, error)
- func (s *Store) LoadDetachedBlobs(ctx context.Context, lane string, since int64) ([]DetachedBlob, error)
- func (s *Store) LogCells(ctx context.Context, slotSec, sinceSec, untilSec int64, sc LogScope, ...) error
- func (s *Store) LogCount(ctx context.Context) (int64, error)
- func (s *Store) LogDirByID(ctx context.Context, id int64) (dir string, timeMS int64, ok bool, err error)
- func (s *Store) LogLastByModel(ctx context.Context, kh string) (map[string]LogModelLast, error)
- func (s *Store) LogLatency(ctx context.Context) (map[string]LatencyStats, error)
- func (s *Store) LogMatrixCells(ctx context.Context, q LogQuery, slotSec int64) ([]MatrixCell, error)
- func (s *Store) LogModels(ctx context.Context, kh string) ([]string, error)
- func (s *Store) LogRecentRPM(ctx context.Context, sc LogScope) (float64, error)
- func (s *Store) LogRecentRPMByKeyHash(ctx context.Context) (map[string]float64, error)
- func (s *Store) LogRecentRPMByModel(ctx context.Context, kh string) (map[string]float64, error)
- func (s *Store) LogRecentWindow(ctx context.Context, seconds int64, sc LogScope) (LogRecentAgg, error)
- func (s *Store) LogStatusCodes(ctx context.Context, keyHash string) ([]int, error)
- func (s *Store) LogTrendSeeds(ctx context.Context, limit int) ([]LogTrendSeed, error)
- func (s *Store) Maintain(ctx context.Context, logRowDays int64) error
- func (s *Store) PruneDetachedBlobs(ctx context.Context, before int64) (int64, error)
- func (s *Store) PruneDetachedEvents(ctx context.Context, before int64) (int64, error)
- func (s *Store) PruneGateWindows(ctx context.Context, before int64) (int64, error)
- func (s *Store) PruneLaneAttemptCauses(ctx context.Context, beforeDay string) (int64, error)
- func (s *Store) PruneQuotaSamples(ctx context.Context) (int64, error)
- func (s *Store) PutDebugFile(ctx context.Context, dir, name string, content []byte) error
- func (s *Store) QueueState(key, value string, del bool)
- func (s *Store) ReapOrphanBlobs(ctx context.Context) error
- func (s *Store) ReconcileCells(ctx context.Context) error
- func (s *Store) ReconcileDebugPayloadBytes(ctx context.Context, actual int64) (drift int64, err error)
- func (s *Store) SearchLogMatrix(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, err error)
- func (s *Store) SearchLogs(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, err error)
- func (s *Store) SearchLogsPage(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, hasMore bool, err error)
- func (s *Store) SetModel(ctx context.Context, e ModelEntry) error
- func (s *Store) SetSetting(ctx context.Context, key, value string, updatedAt int64) error
- func (s *Store) SetState(ctx context.Context, key, value string) error
- func (s *Store) StateQueueDrops() int64
- func (s *Store) StoreOpens(ctx context.Context) (*StoreOpensReport, error)
- func (s *Store) StripDebugDirsBefore(ctx context.Context, bound string, keep, exclude []string) error
- func (s *Store) UpsertAccount(ctx context.Context, row *AccountRow) error
- func (s *Store) UpsertToken(ctx context.Context, t *TokenRow) error
- func (s *Store) UsageStats(ctx context.Context) (UsageSnapshot, error)
- func (s *Store) WALBytes() int64
- func (s *Store) WriteDebugBatch(ctx context.Context, batch DebugBatch) error
- type StoreOpen
- type StoreOpensReport
- type SwitchCause
- type TokenRow
- type UsageDayRow
- type UsageMinPoint
- type UsageSnapshot
- type UsageTotals
Constants ¶
const ( AccountSourceConfig = "config" AccountSourcePanel = "panel" AccountSourceTombstoned = "tombstoned" )
账号来源标记,按 source 语义进 JSON 契约。
Variables ¶
var ( // ErrAccountExists 重名(含 config 声明名与墓碑名——墓碑走 restore)。 ErrAccountExists = errors.New("account already exists") // ErrAccountNotFound 名不在生效集(含死墓碑与 quota/refresh 视角的 tombstoned)。 ErrAccountNotFound = errors.New("account not found") // ErrAccountTombstoned 写路径撞上墓碑名:先 restore 再改。 ErrAccountTombstoned = errors.New("account is tombstoned") // ErrAccountNotTombstoned restore 撞上活号:无墓可还。 ErrAccountNotTombstoned = errors.New("account is not tombstoned") )
账号操作的领域错误(%w 包装携带名字):ops 层(main)只产语义错误, HTTP 状态码映射归面板 handlers——同一条件在不同端点状态码不同 (PUT tombstoned=409 而 quota/refresh tombstoned=404)。
Functions ¶
func DecodePayloadFile ¶ added in v0.15.0
DecodePayloadFile 是导出文件(writefile() 直出/端点下载)的魔数 分派解码:gzip 帧解压、raw 透传、zstd delta 帧用 dict 解(dict 取 同目录 01 的解后明文)。供进程外消费方(cmd/probe 等)复用与读 路径同一套判帧口径;delta 帧缺 dict 时返回显式错误。
func EncodePayload ¶ added in v0.14.0
EncodePayload 返回入库字节与 usize:能压出 ≥10% 收益的内容存 压缩形态(usize=解压前尺寸),否则原样(usize=0)。BestSpeed 对 JSON 文本已有一个量级压缩率,更高档换 CPU 不值。 导出供 debuglog 在请求 goroutine 上预编码——压缩是写路径 CPU 大头, 摊到调用方后写 worker 只剩落库。
func EncodePayloadDelta ¶ added in v0.15.0
EncodePayloadDelta 以 base 为字典把 data 编成 zstd delta 帧(raw content dict,patch-from 语义):同目录 02/03-devin-request* 相对 01 的差异只剩投影改写的结构部分——逐文件重复编码持 PayloadDeltaEncoder 复用字典表,本函数是单次入口。档位取 SpeedBetterCompression—— SpeedFastest 的 dict 编码器是 32K 槽单探针快表(enc_fast.go fastEncoderDict,tableBits=15),dict 超 ~300KB 碰撞饱和、残差随 字典尺寸单调劣化(生产实测 0.6%@150K → 41.6%@750K dict);level 3 全尺寸段覆盖且部分场景编码更快。「SpeedFastest ≈ zstd CLI -3」是 错误等价——CLI -3 对应的是 klauspost SpeedBetterCompression。 base 为空或残差收益不达阈值时回退 EncodePayload 独立存储——读侧 按魔数自判形态,回退不需要任何标记位。
func GateStateKey ¶
GateStateKey 是 lane 冷却闩在 runtime_state 里的键名约定:gate:<lane>, 隐式单 lane 记 gate:default。devin 闸门的读写与导入器对 gate-state*.json 的搬移共用这一约定。
func IsBusy ¶ added in v0.16.0
IsBusy 报告 err 是否为 SQLite 的「数据库文件被锁」失败(原始 SQLITE_BUSY)。busy_timeout 只兜住连接级等待耐心:跨进程写者(reuseport 交接期持锁排空的前任进程、侧开 store 的工具)持锁超 30s 时驱动原样抛 *sqlite.Error;tx.Commit 经 driver.Tx 接口拿不到 ctx(驱动内跑 context.Background()),其唯一上界正是 busy_timeout,故请求级 5s ctx 之下 BUSY 仍可达——生产 9-19 实证 +5~36s 的「database is locked」簇。 驱动建连即开 extended result codes,Code() 低 8 位才是主码—— BUSY_SNAPSHOT/RECOVERY/TIMEOUT 同属「此刻拿不到文件锁」,对整调用 重试(新事务)均可救,故按主码判。
Types ¶
type AccountRow ¶
type AccountRow struct {
Name string
Token string
CredentialsFile string // 写入时已锚定为绝对路径
APIKey string // Devin 平台 durable key(cog_*),mint 自愈来源
Disabled bool
Deleted bool
Priority *int64 // 池级排序元数据,nil=无覆盖
MaxRPM *int64 // 该号自己的分钟窗口配额,nil=继承全局
Notes string // 面板侧自由注解,config 无对应字段
CreatedAt int64
UpdatedAt int64
}
AccountRow 是 upstream_accounts 表一行的领域形状。token/ credentials_file 可空(NULL→"");deleted=1 是墓碑——压住 config 同名声明,等 config 撤名后由 GC 物理收掉。时间一律 unix 毫秒, 对齐 TokenRow 口径。priority/max_rpm 是 *int64——NULL 语义是「无行 覆盖」,merge 时回落 config 值;notes 照 nullAccountField 惯例 ""↔NULL。
type AccountUsageRow ¶
type AccountUsageRow struct {
Recent LogRecentAgg
Today AccountUsageToday
TTFB LatencyStats
TTFBAvgMS float64
}
AccountUsageRow 是单账号 usage 块的原始量集合——内部行类型不进 wire,供 P2 /admin/accounts 的 usage 字段({rpm_now, tps_now, ttfb_avg, ttfb_p50, ttfb_p90, cache_rate, today:{requests, success_rate, tokens}})投影消费。口径全部复用既有读路径:
- Recent:LogRecentWindow 60s 完成窗——rpm_now=Recent.Req(非 499 完成数,同 LogRecentRPM),tps_now=Recent.OutTok*1000/Recent.GenMS (同 stats recentBlock 速度列),cache_rate=Recent.CrTok/ (Recent.InTok+Recent.CrTok+Recent.CwTok)(同 recentBlock cache_pct)。
- TTFB:最近 usageSampleCapacity 条非空 first_upstream_ms 样本 (同 LogLatency["ttfb"] 口径)——TTFB.P50/P90 直取,TTFBAvgMS 是同一样本集的均值,与分位同源。
- Today:本地日界内计数——success_rate=Today.OK/Today.Non499。
type AccountUsageToday ¶
type AccountUsageToday struct {
Requests int64 // 全部完成行(含 499)
OK int64 // 2xx——success_rate 分子
Non499 int64 // 非 499(ccLoad total 口径,success_rate 分母)
Tokens int64 // total_tokens 和
}
AccountUsageToday 是单账号本地日界内的原始计数。
type CASChunk ¶ added in v0.15.0
CASChunk 是一块待入库的共享内容:Hash 是明文 sha256 截 16B(blob 行 与 ref 行的共同键),Stored/Usize 是 EncodePayload 产物(与 debug_files 行同编码口径——读侧对 blob 复用 decodePayload)。
func EncodeCASManifest ¶ added in v0.15.0
func EncodeCASManifest(enc *PayloadEncoder, data []byte) (manifest []byte, usize int64, chunks []CASChunk, ok bool)
EncodeCASManifest 把 data 按内容定义切块(CDC),逐块算 hash 与入库 编码,返回 manifest 入库字节、逻辑尺寸与去重后的块集。ok=false 表示 切不出 ≥2 块(小文件/无内部边界)——整文件存 manifest 只赔不赚, 调用方回退普通 EncodePayload。块集按 hash 去重(同文件内重复区间只 存一份),manifest 的位置表仍按序逐块登记——重组语义不变。
type CellsAuditReport ¶ added in v0.16.0
type CellsAuditReport struct {
SlotLo, SlotHi int64 // 审计窗口
Watermark int64 // 对账时刻的覆盖水位
Rows int64 // 窗口内 id≤水位 的非 rejected 源行数
Dims int64 // 源行聚合出的维度数
MismatchDims int64 // src.req != cell.req 的维度数
DeficitRows int64 // 失配维度上 Σ(src-cell),带符号
SurplusDims int64 // cell.req > src.req 的维度数(REPLACE 会按源真值重写)
OrphanCells int64 // 窗口内有格无源的维度数(源行已被删净的残格)
ErrDims int64 // err 侧 (slot,stage) 源组数
ErrMismatchDims int64
ErrDeficitRows int64
ErrOrphans int64
TailRows int64 // 窗口内 id>水位 的行数(不属本对账域)
}
CellsAuditReport 汇总一个 slot 窗口(闭区间)内「源行 vs 格子」的 对账结果;对账域是 id ≤ Watermark 的非 rejected 行(水位外行归 ReconcileCells,见 TailRows)。
type CellsBackfillReport ¶ added in v0.16.0
type CellsBackfillReport struct {
Pre CellsAuditReport
Post CellsAuditReport
Applied bool // false=干跑(未写库)
}
CellsBackfillReport 是 BackfillCells 的结算:Pre 为动手前审计, Post 为写入后复测(干跑时与 Pre 相同——Remaining 即 Pre 自身)。
type DebugBatch ¶ added in v0.14.0
type DebugBatch struct {
Files []DebugFileRow
Chunks []DebugChunkRow
Blobs []DebugBlobRow
Refs []DebugRefRow
StripDirs []string
LogRows []*LogRow
// Encoder 非空时 chunk 的 gzip 编码用它(调用方持有的复用编码器,
// 如写 worker 的专属实例——调用串行化由调用方保证);空走共享池。
Encoder *PayloadEncoder
}
DebugBatch 是一次跨目录合并事务的全部内容:整文件行、chunk 行、 CAS 共享对象(Blobs/Refs——manifest 文件行引用的切块与其 ref 行, 与文件行同事务落库无孤儿窗口)、StripDirs 列出「剥 payload」的 目录(errors_only 收尾——除 meta.json/error.json 锚点外行全删: meta 留下作目录锚点,X-Request-Id 仍可解析、占位防同秒目录名复用 撞 logs.dir UNIQUE)、LogRows 是完成请求的 logs 摘要行。几类写入 同一事务提交:完成请求不再为 payload 冲刷、剥离与日志行各付一次 commit。
type DebugBlobRow ¶ added in v0.15.0
DebugBlobRow 是批量事务里的一行共享 blob:OR IGNORE 语义,同 hash 已存在时本行不写(字节记账按 RowsAffected 实计)。
type DebugChunkRow ¶ added in v0.14.0
DebugChunkRow 是一次跨目录批量追加里的单行:全局写 worker 把多个 在飞请求的刷写缓冲合并进一个事务,行内自带 dir 归属。data 内可含 多行已序列化记录,入库为一行 chunk。
type DebugFileInfo ¶
type DebugFileInfo struct {
// Name 是相对请求目录的路径(顶层文件名或 attachments/xxx)。
Name string
// Size 是文件字节数;chunked 文件是全部 chunk 的合计。
Size int64
}
DebugFileInfo 是目录内一个文件的清单项。
type DebugFileRow ¶ added in v0.14.0
DebugFileRow 是一次跨目录批量写入里的单行整文件:Stored 是调用方 经 EncodePayload 预编码的入库字节(Usize 与之配套),IfAbsent 对应 INSERT OR IGNORE(error.json 的 first-write-wins),否则 OR REPLACE。
type DebugRefRow ¶ added in v0.15.0
DebugRefRow 是批量事务里的一行引用:PK(dir,name,hash),随文件行 同一 WHERE 被删除漏斗带走——引用即行是 CAS 的 GC 事实源。
type DetachedBlob ¶ added in v0.16.0
type DetachedBlob struct {
Key string
Lane string
OriginDir string
FinishedAt time.Time
Payload []byte
}
DetachedBlob 是 detached_blobs 的一行:一条 completed 脱钩条目的 事件载荷(编码格式见 adapter/devin detached_blob.go,本层不解读)。 FinishedAt 记 unix 毫秒,作播种 TTL 判据与同键冲突仲裁。
type DetachedEvent ¶ added in v0.16.0
type DetachedEvent struct {
At time.Time
Lane string
Key string
OriginDir string
Kind string
Detail string
}
DetachedEvent 是 detached_events 的一行:一次脱钩生命周期事件。 Key 是全量语义请求哈希(内存环为显示截前 12 位,台账留全键—— 04 标记行里的 key 是全量,取证按全键对照);OriginDir 是首请求的 调试目录名(重放事件的原始帧取证在那边),事件与条目脱钩时可为空 (如 pre-detach 截断、跨 lane miss 由本 lane 记账但条目在 owner)。
type DimensionAgg ¶
type DimensionAgg struct {
Name string `json:"name"`
UsageTotals
LastAt string `json:"last_at,omitempty"`
AvgDuration float64 `json:"avg_duration_ms"`
AvgTTFB float64 `json:"avg_ttfb_ms"`
// InTok/OutTok 分位数描述该维度的请求体量分布:计费与上下文窗口
// 占用都跟长度强相关,均值会掩盖长尾。
InTokP50 int64 `json:"input_p50,omitempty"`
InTokP95 int64 `json:"input_p95,omitempty"`
OutTokP50 int64 `json:"output_p50,omitempty"`
OutTokP95 int64 `json:"output_p95,omitempty"`
}
DimensionAgg 是按模型或 key 哈希聚合的行。
type ExportReport ¶
type ExportReport struct {
// Written 是实际落盘的文件路径——目标被现役文件占用时改道
// <name>.exported,此处反映真实路径。
Written []string
// Notices 是需要操作员知晓的旁注(目标被占改道 .exported 等)。
Notices []string
// DebugRows 是 debug_files+debug_chunks 的残留行数。调试目录的
// 文件还原不在本工具范围;>0 时调用方应提示「回滚后请求详情页
// 只剩 DB 副本」这一取证缺口。
DebugRows int
}
ExportReport 汇总一次 ExportLegacy 的落盘结果。
type GateDaySends ¶ added in v0.15.0
GateDaySends 是单日闸门放行数的分解:Sends 是当日放行的真实请求数 (used_fg+used_bg−used_bg_ping——每次放行对应一次真实上游发送,含 内层重试与闩内滴灌探针;保温 ping 走 adapter 内部路径不产生 logs 行,留在分子里会垫高 sends/row 的「每请求一发」基线),RetryAdmits 是其中同 lane 续试重发的放行数,Slots 是当日落库的 (lane,window_start) 行数——(lane,window_start) 有唯一索引,COUNT(*) 即去重 lane-slot 数, 是覆盖率的实有侧。
type GateWindow ¶ added in v0.15.0
type GateWindow struct {
Lane string `json:"lane"`
WindowStart int64 `json:"window_start"` // unix 秒,窗口起点(对齐分钟桶界)
Quota int `json:"quota"` // 关窗时生效的窗口配额(<=0 表示不限速)
UsedFg int `json:"used_fg"` // 本窗 fg 放行数
UsedBg int `json:"used_bg"` // 本窗 bg 放行数(含保温 ping 与闩内探针)
UsedBgPing int `json:"used_bg_ping"` // 本窗经 tryAdmit 的保温 ping 放行数(used_bg 的子集——used_bg-本列=真实 bg 需求)
Drip int `json:"drip"` // 本窗闩内滴灌探针放行数(used_* 的子集,单列供配额归因)
RetryAdmits int `json:"retry_admits"` // 本窗同 lane 续试重发的放行数(used_* 的子集——reopen/续轮/凭据自愈/瞬时重试的再发送,不含号池 failover 后新 lane 首发)
ReservePeak int `json:"reserve_peak"` // 本窗 bg 预留量的峰值
WaitersPeak int `json:"waiters_peak"` // 本窗闸内排队数峰值(fg+bg)
// 按拒绝成因分列的快败数:quota 排队预算耗尽(桶满/死区睡到下
// 一窗口将超 maxHold)、bgReserve bg 让路(预留/爬坡)、latch
// 闩内快败、yield 兄弟有余量提前让给 failover。
RejectQuota int `json:"reject_quota"`
RejectBgReserve int `json:"reject_bg_reserve"`
RejectLatch int `json:"reject_latch"`
RejectYield int `json:"reject_yield"`
FgRate float64 `json:"fg_rate"` // 关窗折叠后的 fg 准入速率 EMA(条/窗,bg 预留的输入)
}
GateWindow 是 gate_windows 一行的领域形状:某 lane 一个被观察关闭的 对齐分钟窗口的聚合账。行只覆盖闸门实际触碰过的窗口——未被触碰的空窗 期没有行(缺口=无观测,与零用量区分)。写方是闸门翻页:窗口关闭时把 本窗口的用量/拒绝/峰值快照成行;字段语义与 rategate 的 win* 账同源。
type LaneAttemptCause ¶ added in v0.15.0
type LaneAttemptCause struct {
Date string `json:"date"`
Lane string `json:"lane"`
Cause string `json:"cause"`
N int64 `json:"n"`
}
LaneAttemptCause 是 lane_attempt_causes 的读侧行:某 lane 某日某成因 的被放弃尝试数。
type LatencyStats ¶
type LatencyStats struct {
Samples int64 `json:"samples"`
P50 int64 `json:"p50"`
P90 int64 `json:"p90"`
P95 int64 `json:"p95"`
P99 int64 `json:"p99"`
Max int64 `json:"max"`
}
LatencyStats 是样本算出的延迟分布。
type LogCellKey ¶
type LogCellKey struct {
Slot int64 // unix 秒,600 对齐
API string // 入口协议原值:anthropic/openai-chat/openai-responses/responses-ws
Model string // 生效模型(model 退化 requested_model)
KeyHash string
}
LogCellKey 是聚合格子的键:10 分钟时间槽 × 入口 api × 生效模型 × key_hash——与旧 rollup cellKey 同形。
type LogCellTotals ¶
type LogCellTotals struct {
Requests int64
OK int64
Gone int64
Limited int64
NDur int64 // duration>0 行数(stats avg_duration 分母,含 499)
NDurOK int64 // 2xx && duration>0(metrics duration_count)
InTok int64
OutTok int64
CacheRead int64
CacheWrite int64
InTokNG int64
OutTokNG int64
CacheReadNG int64
CacheWriteNG int64
SumDurMS int64 // duration>0 行 duration 和(含 499)
SumDurOKMS int64 // 2xx 行 duration 和
// streaming && 2xx && fbt>0:stats/health/metrics 的 TTFB 口径
SumFirstOKMS int64
NFirstOK int64
// streaming 行 fbt 和与样本数(不限状态):token 统计 stream_avg_ttfb
SumFirstStreamMS int64
NFirstStream int64
// 非 streaming 行 duration 和与行数(不限状态):token 统计 non_stream_avg_rt
SumDurNonStreamMS int64
NNonStream int64
// 非 499 行按 stream 拆分:token 统计 stream_count/non_stream_count
NStreamNG int64
NNonStreamNG int64
// SumGenMS 是生成时长和:stream 行扣首字(dur−fbt),非 stream/无
// fbt 行取全时长——TPS(输出 token/生成秒)的分母,同速度列口径。
SumGenMS int64
}
LogCellTotals 是单格子的累计计数;字段口径与旧 cellTotals 一一对应: ok=2xx,gone=499(客户端断连),limited=429;NG 后缀=非 499 行合计 (metrics/token 统计口径),无后缀 token 字段含 499 行(summary/stats)。
func (LogCellTotals) Add ¶ added in v0.17.0
func (t LogCellTotals) Add(o LogCellTotals) LogCellTotals
Add 返回 t+o 的逐字段和——格子指标全是可加量,跨槽/跨维再聚合 (per-model 累计、健康时间线桶、全局 total)在 Go 侧用本方法 合并 LogCells 回调出的行。
type LogModelLast ¶
type LogModelLast struct {
ReqAt int64 // unix 毫秒
ReqID int64
ReqStatus int
ReqResult string
OKAt int64 // unix 毫秒
OKID int64
}
LogModelLast 是单生效模型的最近时刻快照:Req* 是最近非 499 行 (含真实自增 id),OK* 是最近 2xx 行——ccLoad last_request_*/ last_success_at 的投影源。
type LogQuery ¶
type LogQuery struct {
SinceMS int64
UntilMS int64
// KeyHash 收敛数据范围(api_token 身份/auth_token_id 参数解析结果)。
KeyHash string
// Account 是上游账号 lane 名过滤,走读侧折叠口径
//(logAccountExpr:'default' 命中 ”+'default' 两群)。
Account string
// LogSource 为空时默认剔除 rejected(管线前拒绝行有自己的计数
// 与事件环,落表只为留存检索,不与服役流量混排);"all" 不过滤,
// 其余值精确匹配。API/UpstreamProtocol 为空或 "all" 不过滤。
LogSource string
API string
UpstreamProtocol string
Model string
ModelLike string
Query string
StatusExpr string
StatusClass string
Result string
ErrorStage string
// BeforeID 是 keyset 游标:只取 id 小于它的行。翻页传「上一页
// 最旧行的 id」即可走主键范围扫,替代随页深线性退化的 OFFSET。
BeforeID int64
// Limit<=0 表示不限(LIMIT -1);Offset<0 按 0。
Limit int
Offset int
// SkipCount 置位时 SearchLogs 省略 COUNT(*) 返回 total=-1:深页
// 翻页不需要精确命中数(列表页有缺省降级路径),生产全窗计数
// ~0.7-1s/页是纯税。调用方需自行用 limit+1 探测判 has_more。
SkipCount bool
}
LogQuery 是 logs 表的结构化筛选;零值即全量。 对应旧 debuglog.RequestFilter + 行级筛选的合并下推:since/until 按 time 列(毫秒)闭区间比较;status 是状态表达式(499/4xx/>=400/!200, 逗号 OR);model 精确命中三段模型名其一;model_like 子串;q 是对行内 文本列拼接后的小写子串匹配(LOWER() 只折叠 ASCII,比旧 Go ToLower 的 Unicode 折叠窄——非 ASCII 搜索词行为基本不变)。
type LogRecentAgg ¶
type LogRecentAgg struct {
Req int64
InTok int64
OutTok int64
CrTok int64
CwTok int64
DurMS int64
NDur int64
GenMS int64
FirstMS int64
NFirst int64
}
LogRecentAgg 是短窗聚合(旧 recentAgg):req 只数非 499(RPM 口径), token 全量累计;genMS 是生成时长和,firstMS/nFirst 沿用格子 TTFB 口径。
type LogRow ¶
type LogRow struct {
// ID 是自增日志行号——面板 log_id 与 last_*_id 的身份;读侧回填。
ID int64
// LogSource 是写入时定版的来源:写侧置值即生效(rejected 行靠它
// 与服役流量分域),留空时 InsertLog 回落 'proxy'——业务分类归
// 写方(debuglog.logRowFor / 导入器各自定版);读路径回填库内原值。
LogSource string
// UpstreamProtocol 保留过滤维度的统一形状(当前恒 devin);读侧回填。
UpstreamProtocol string
Dir string
StartedAt time.Time
DurationMS int64
// 延迟分解字段用指针区分「未发生」(nil,省略)与「即时发生」(0ms);
// int 零值会掩盖这两种语义。分解口径见 debuglog.Recorder 同名字段注释:
// ready→sent 本地投影、sent→open 建流往返、open→first_upstream 上游
// 思考 TTFT、first_upstream→first_client 代理编码下发。upstream_done_ms
// 是泵收完上游事件流的时刻——非流式 egress 段以它为基线(流式仍用
// first_upstream);库列在 DDL 尾部与 ALTER 补齐的物理列序一致,
// 字段按语义归在分解块。
RequestReadyMS *int64
UpstreamSentMS *int64
UpstreamOpenMS *int64
FirstUpstreamMS *int64
FirstClientMS *int64
UpstreamDoneMS *int64
API string
Method string
Path string
StatusCode int
Result string
RequestedModel string
Model string
ResponseModel string
ModelMismatch bool
Stream bool
InputTokens int64
OutputTokens int64
CacheReadTokens int64
CacheWriteTokens int64
ReasoningTokens int64
TotalTokens int64
// CreditCost 是上游帧上报的权威计费读数(单请求口径,可加总);
// Committed* 系账户快照读数不进索引——逐请求保留见 meta.json。
CreditCost int64
UpstreamRequestID string
ClientIP string
KeyHash string
// ClientRequestID 是客户端自带的关联 ID(X-Request-Id 等),
// 让调用方能用自己的 ID 反查本次请求。
ClientRequestID string
// ErrorStage 是首个失败阶段(http_decode/provider_stream/http_stream 等),
// 让检索直接定位失败发生在哪一层。只在终结性失败(result!=completed)
// 时落盘:中途被重试救回的错误仍留在目录 error.json 与 retry_attempts
// 里,进索引会把「发生过失败」与「请求失败」混成一桶。
ErrorStage string
// ErrorMessage 是首个失败的错误文案(与 error.json 的 message 同源,
// 截断后随索引落盘)。目录被保留策略淘汰后,日志行仍能回答
// 「为什么败」——此前只剩阶段名,归因必须靠目录在场。
ErrorMessage string
DroppedEvents uint64
// RetryAfterSeconds 是上游限流给出的 reset 秒数 hint,
// 供聚合区分「有退避提示的限流」与「裸限流」;非限流请求为 0。
RetryAfterSeconds int64
// RateLimited 标记本请求被限流语义终结(上游 429 / 本地闸门 / 流内
// 限流错误事件)。HTTP 状态码认不全限流——流内下发的限流仍是 200,
// 责任归因与限流采样用本字段而不是 status_code。
RateLimited bool
// Retries 是上游重发次数(attempt2+,token 自愈/空响应/transport
// 重开);明细在同目录 meta.json 的 retry_attempts 与 04 的
// retry_attempt 分界行。0 表示一次发送完成。
Retries int
// Account 是最终服务请求的上游账号名(号池 lane 名);迁移前
// 历史行另有 ”/'default' 残留,读侧按 'default' 折叠归桶。
Account string
// AccountSwitches 是号池 failover 换号次数(成功前的失败尝试数),
// 明细在同目录 meta.json 的 upstream_attempts。0 表示首号即成。
AccountSwitches int
// PrematureEndTurn 标记「工具结果之后模型纯文本 end_turn」的可疑收尾,
// 供检索统计该模型行为的真实频率。
PrematureEndTurn bool
// Repairs 是请求投影为上游 wire 格式时的静默修复动作总数
//(重排/降级/剥离/指纹改写),明细在同名 meta.json 字段。
Repairs int
// ConnReused 标记成功建流那次发送是否复用了 idle 连接;指针是为了
// 区分「未记录」(nil,省略)与「复用失败新建」(false)——connect
// 段偏高时靠它区分「握手成本」与「上游响应头延迟」。
ConnReused *bool
ConnIdleMS *int64
// AffinityHash 是号池选号的会话谱系亲和键(SessionAffinityKey 的
// SHA-256,不可逆),与 meta.json 的 affinity_hash 同源——谱系
// 分析(绑定谱系/warm 救援/failover 同族)的 GROUP BY 维。非号池
// 路径与管线前拒绝留空串;读侧回填库内原值。
AffinityHash string
// SwitchCauses 是被放弃 lane 尝试的归因聚合({lane,cause}→次数),
// 由写方 debuglog.logRowFor 从 meta.json 同源的 upstream_attempts
// 投影而来——它不是列,只作 InsertLog/WriteDebugBatch 展开进
// lane_attempt_causes 表的瞬时载体,读侧回填恒为 nil。
SwitchCauses map[SwitchCause]int
}
LogRow 是 logs 表一行的领域形状。它不是 wire 投影——对外字段名由 各端点自己的投影类型持有(ccpanel 的 logEntry/matrixEntry/ logExportRow,store 导出文件的 logRowToLegacyIndexEntry)。 time/minute_bucket 由 InsertLog 从 StartedAt 派生、不进字段; upstream_protocol 由 DDL 默认值供值——两者都只在读侧回填出现。
type LogScope ¶
LogScope 是聚合查询的范围谓词(旧 cellKey 行级筛选的下推版): model 精确命中生效模型,modelLike 是它的子串匹配,account 按读侧 折叠口径过滤上游账号 lane('default' 命中 ”+'default' 两群)。
type LogTrendSeed ¶
LogTrendSeed 是 obs 趋势桶的预热种子:完成时刻 + 是否错误。
type MatrixCell ¶ added in v0.16.0
type MatrixCell struct {
Slot int64 `json:"slot"` // 桶起点 unix 秒
Account string `json:"account"` // 读侧折叠名(logAccountExpr)
OK int64 `json:"ok"`
Err int64 `json:"err"`
RL int64 `json:"rl"`
SW int64 `json:"sw"`
}
MatrixCell 是按 (slot, account) 聚合的健康矩阵桶:账号页 48×30min 健康条的服务端口径——entries 被 requestsFetchCap 截断时格子仍覆盖 全窗。分类对齐 debuglog.ErrorOwner 的失败责任归因:rl 是限流语义 终结(429 或 rate_limited 标记),err 是上游责任失败(失败且非客户 端断连/中断/读写阶段错),ok 是其余(成功 + 客户端责任——lane 已尽 责送达,断连不归 lane 失分);sw 是 account_switches 合计。
type ModelEntry ¶
type ModelEntry struct {
Model string
RedirectModel string
Disabled bool
UpdatedAt int64 // unix 毫秒
}
ModelEntry 是 model_registry 一行的领域形状,字段镜像 modelreg.Entry(注册表覆盖项:重定向目标与停用位)。
type PayloadDeltaEncoder ¶ added in v0.16.0
type PayloadDeltaEncoder struct {
// contains filtered or unexported fields
}
PayloadDeltaEncoder 是单持有者复用的 zstd delta 编码器:Encode 每次供给 base,相同(指针判等)直接编、不同经 ResetWithOptions 换 dict。换 dict 只付 dict 哈希表的 clear+重填 CPU——编码器长短表 与 8MB window hist 跨 base 永续复用,把「每目录新建 dict 编码器」 ~16MB 的一次性建造成本摊成零。非并发安全:持有者是单编码协程。
func NewPayloadDeltaEncoder ¶ added in v0.16.0
func NewPayloadDeltaEncoder() *PayloadDeltaEncoder
NewPayloadDeltaEncoder 建空编码器;底层 zstd writer 随首个带合法 base 的 Encode 懒建——无 delta 候选的持有者不付建造成本。
func (*PayloadDeltaEncoder) Close ¶ added in v0.16.0
func (e *PayloadDeltaEncoder) Close()
Close 释放编码器占有的内部缓冲;EncodeAll 路径无流式状态可冲刷。
type PayloadEncoder ¶ added in v0.15.0
type PayloadEncoder struct {
// contains filtered or unexported fields
}
PayloadEncoder 是单持有者复用的 payload 编码器:内部 gzip.Writer 跨调用 Reset 续用 flate 窗口与哈希表——sync.Pool 会被 GC 清空, 长驻协程(编码分片/写 worker)各自持有一份后,表重建摊成一次性 成本。非并发安全:持有者必须保证串行调用。
func NewPayloadEncoder ¶ added in v0.15.0
func NewPayloadEncoder() *PayloadEncoder
NewPayloadEncoder 返回一个可长期持有的编码器,压缩档与 EncodePayload 同为 BestSpeed。
type QuotaSample ¶
type QuotaSample struct {
At int64 `json:"at"` // unix 秒
Account string `json:"account,omitempty"`
DailyRemaining *float64 `json:"daily_remaining"`
WeeklyRemaining *float64 `json:"weekly_remaining"`
DailyResetAt int64 `json:"daily_reset_at,omitempty"`
WeeklyResetAt int64 `json:"weekly_reset_at,omitempty"`
PromptCredits float64 `json:"prompt_credits,omitempty"`
FlowCredits float64 `json:"flow_credits,omitempty"`
FlexCredits float64 `json:"flex_credits,omitempty"`
ACUConsumed float64 `json:"acu_consumed,omitempty"`
ACULimit float64 `json:"acu_limit,omitempty"`
UsedPromptCredits float64 `json:"used_prompt_credits,omitempty"`
UsedFlowCredits float64 `json:"used_flow_credits,omitempty"`
UsedFlexCredits float64 `json:"used_flex_credits,omitempty"`
GracePeriodStatus string `json:"grace_period_status,omitempty"`
GracePeriodEnd int64 `json:"grace_period_end,omitempty"`
WasReducedByOrphanedUsage bool `json:"was_reduced_by_orphaned_usage,omitempty"`
TopUpEnabled bool `json:"top_up_enabled,omitempty"`
TopUpTransactionStatus string `json:"top_up_transaction_status,omitempty"`
OverageBalanceMicros int64 `json:"overage_balance_micros,omitempty"`
}
QuotaSample 是 quota_samples 一行的领域形状,也是 /admin/quota 响应 points 的线格式(与被取代的 quota.jsonl 行格式一致); Daily/WeeklyRemaining 指针语义保留——NULL/nil 表示「上游没报」, 0 表示「真到 0」,故该两字段不带 omitempty。
type RateLimitEvent ¶
type RateLimitEvent struct {
At int64 `json:"at"` // unix 秒
Model string `json:"model,omitempty"`
RPM int64 `json:"rpm"` // At 前 60s 内启动的请求数(含本请求)
Stage string `json:"stage,omitempty"`
}
RateLimitEvent 是一次 429 的采样:发生时刻(≈请求完成时刻)、模型、 以及该时刻前 60s 内启动的请求数。stage 区分来源——rate_gate 是本地 闸门快败(RPM 读数为到达速率,含被拒),其余是上游真 429。
type ResolvedAccount ¶
type ResolvedAccount struct {
Name string
Token string // 生效值:行非空用行,否则 config 值
CredentialsFile string // 同上逐字段覆盖
APIKey string // 同上逐字段覆盖(durable mint key)
Disabled bool // 恒取行值(config 无该字段)
Priority int // 行 ?? config ?? 0
MaxRPM int // 行 ?? config ?? 0(0=继承全局 max_rpm)
Notes string // 仅行值(config 无该字段)
Source string // "config" | "panel" | "tombstoned"
// Overridden 列出被覆盖行顶掉的 config 字段名(token/credentials_file/
// api_key/priority/max_rpm)——merge 点唯一知道哪侧赢了,provenance
// 投影据它把「文件声明→行覆盖」渲染出来;config 无对应物的行字段
// (disabled/notes)不算覆盖。
Overridden []string
ConfigDeclared bool
HasRow bool // 是否存在 overlay 行(含墓碑)
CreatedAt int64
UpdatedAt int64
}
ResolvedAccount 是 config 声明集与 overlay 行 merge 后的生效视图, 不进库。Source 推导:deleted=1 && ConfigDeclared → tombstoned; !deleted && ConfigDeclared(可有覆盖行)→ config; !deleted && !ConfigDeclared → panel。死墓碑(deleted && !declared) 不进视图,由 GCTombstonedAccounts 收。
func MergeAccounts ¶
func MergeAccounts(declared []config.DevinAccountConfig, rows []*AccountRow) []ResolvedAccount
MergeAccounts 是 overlay 生效集的纯函数:declared 顺序起步,同名行 逐字段覆盖(行 token/credentials_file 非空覆盖,disabled 恒取行值), deleted=1 的同名项标 tombstoned,未声明的活行追加为 panel。干跑 校验与读路径共用,不写库。
type SendsRowDay ¶ added in v0.15.0
type SendsRowDay struct {
Date string `json:"date"`
Sends int64 `json:"sends"`
Rows int64 `json:"rows"`
RetryAdmits int64 `json:"retry_admits"`
Coverage *float64 `json:"coverage,omitempty"`
SendsMissing int64 `json:"sends_missing,omitempty"`
Ratio *float64 `json:"ratio,omitempty"`
}
SendsRowDay 是单日 sends/row 探针行:sends 是当日闸门放行数 (gate_windows 的 used_fg+used_bg−used_bg_ping——每次放行对应一次 真实上游发送,含日志不可见的同 protoRequest 内层重试与闩内滴灌 探针;保温 ping 不产生 logs 行,留在分子里会垫高「每请求一发」 的期望基线),rows 是当日非 rejected logs 行数。RetryAdmits 是 sends 中同 lane 续试重发的放行数(reopen/续轮/凭据自愈/瞬时重试) ——放行里的重试份额直接可读,不必再整窗回推残差。Coverage 是当日 实有 lane-slot ÷ 预期 lane-slot(预期 = 窗内 lane 数 × 当日已流逝 分钟数,见 gateExpectedSlots):分子对分母日界的覆盖比例——部署 截断日、未装表日、丢窗日的低比值据此读成低覆盖而非低倍率;丢窗 与零触碰空窗不可分辨,差额一律记 SendsMissing 不插值。Ratio 只在 rows>0 时置值——「quota<=0 闸门不记账」(sends=0, rows>0)与 「纯探针日无请求」(rows=0)靠指针把真 0 与未定义分开。
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store 包装读写两个 *sql.DB,对外只暴露领域方法。
func Open ¶
Open 打开(或创建)path 处的库。schema 幂等,重复打开只做 CREATE IF NOT EXISTS;是否跑 ImportLegacy 由导入器按源文件 存在性自判,Open 不报告 created。
func (*Store) AccountsUsage ¶ added in v0.17.0
func (s *Store) AccountsUsage(ctx context.Context, accounts []string) (map[string]*AccountUsageRow, error)
AccountsUsage 批量返回各账号的 usage 原始量;折叠口径同 LogScope ('default' 命中 ”+'default' 两群)。Recent 与 Today 各一条按 logAccountExpr 分组的聚合扫描;TTFB 样本逐号走 recentSamples—— 「每号最近 N 条」靠 id 索引截断,比窗口函数全表分区便宜。每个请求 名保证有行(窗口内零活动的号得零值行),面板逐号快照的 3N 次查询 收成 2+N 次。
func (*Store) AppendDebugChunks ¶
func (s *Store) AppendDebugChunks(ctx context.Context, rows []DebugChunkRow) error
AppendDebugChunks 把一批 chunk(可跨目录)合并进一个事务:每行 INSERT 一次 commit/fsync 改为整批一次;任一失败整体回滚,调用方 保留全部缓冲下次重发,不会出现半截批次。
func (*Store) BackfillCells ¶ added in v0.16.0
func (s *Store) BackfillCells(ctx context.Context, slotLo, slotHi int64, apply bool) (*CellsBackfillReport, error)
BackfillCells 重算 [slotLo, slotHi] 窗口内全部格子的 rollup—— 「水位内无格子」历史洞的修复路径(9-19 prod 实证:cells 化二进制 与旧二进制 reuseport 交接期交叠写库,留下 47 维 / 8,582 行的洞, 行 id 均 ≤ 水位,ReconcileCells 的 id>水位 补漏永远够不着)。
apply=false 时只审计不写库(Pre 即缺口报告)。apply=true 时在 一个 BEGIN IMMEDIATE 事务里顺序做:完整性守卫 → 审计 → 两表 INSERT OR REPLACE → 复测。守卫与写入同事务共享快照;事务对prod 写者串行(busy_timeout 兜底等待),窗口内新落的行要么先于事务 提交(被重算吃进)要么在其后(双写 upsert 叠在重算格上)—— 两种交错都收敛,故不阻塞运行中实例执行。
两道守卫把「源行已被部分删除」的窗口拦在重写前(REPLACE 会把格子 写小、永久毁掉格子里尚存的历史):
- 完整性:占用 slot 的格底 < 全表 MIN(time) ⇒ 前缀删除已越过该 slot 下缘(retention 的 DELETE FROM logs WHERE time < cutoff 只可能是部分删除的来源)。窗口内任一占用 slot 破缺即整体中止, 不跳过单格——「缺口+部分删除」在对账面上不可分。
- 盈余:某 slot 的 SUM(cell.req) > 存活源行数 ⇒ 出现了非前缀 删除或外部改写,REPLACE 修复前提不成立,中止。
func (*Store) CellsAudit ¶ added in v0.16.0
CellsAudit 只读对账一个 slot 窗口的 rollup 覆盖——返回的失配集即 BackfillCells 会修复的对象。lo=0/hi=math.MaxInt64 即全表扫。 水位与计数放在同一读事务里取:谓词以水位分域,两个读快照不拼在 同一事务会出「行已记账但水位读旧」的假缺口。
func (*Store) ClaimDebugFile ¶
func (s *Store) ClaimDebugFile(ctx context.Context, dir, name string, content []byte) (claimed bool, err error)
ClaimDebugFile 是带占位语义的 IfAbsent 变体:无行时插入并返回 true,已有行则原样保留并返回 false——目录分配把它当原子占位用 (等价文件时代 mkdir 的 EEXIST),也是 error.json 的 first-write-wins:首个失败点最有诊断价值,覆盖语义由调用方表达。
func (*Store) Close ¶
Close 关闭连接池;WAL checkpoint 由驱动在关闭时收尾。读池退化 复用写池时 ro==db,避免重复 Close。异步播种协程先取消再等退出—— 它的 ro 快照聚合在 GB 级库上是秒级在飞查询,直接 Close 会被池等待 拖住;取消后经 ctx 中止,等待退出口径把「协程写已关闭池」噪声消掉。
func (*Store) DebugBlobBytes ¶ added in v0.15.0
DebugBlobBytes 返回 CAS 共享 blob 的库存字节合计——全局口径的 另一部分(目录口径见 DebugDirSizes):blob 被 refs 跨目录共享, 不属于任何单一目录,淘汰闸门与计数器对账按 Σdir+blob 读总账。
func (*Store) DebugDirSizes ¶
DebugDirSizes 返回各目录内容字节数合计,供 max_total_mb 容量淘汰。 按库存尺寸计(压缩行的 content/data 是 gzip 帧长)——淘汰的目标是 磁盘占用,usize 的逻辑尺寸在这里不适用。refs 行按 dir 归属计入 (ref 随文件行同生死,尺寸口径与删除 RETURNING 表达式同源); 共享 blob 字节不属于任何目录,全局口径走 DebugBlobBytes。
func (*Store) DebugDirSizesSplit ¶ added in v0.15.0
func (s *Store) DebugDirSizesSplit(ctx context.Context, anchor []string) (total, strippable map[string]int64, err error)
DebugDirSizesSplit 是 DebugDirSizes 的双口径版:一趟聚合同时返回各 目录的总库存字节与「剥到锚点」可释放的字节(名字不在 anchor 名单 中的行合计)——容量淘汰两相各用一份:第一相按 strippable 预估剥载 释放,第二相按剥后残值圈整删界。refs 行按 name 同源判定(ref 的 name 是引用它的 manifest 文件名——manifest 非锚点,ref 随之可剥)。
func (*Store) DebugDirs ¶
DebugDirs 返回库中全部调试目录名,按名排序——目录名内嵌 "20060102-150405" 时间戳,字典序即时间序,清理器直接复用该序。
func (*Store) DebugDirsByPrefix ¶
DebugDirsByPrefix 返回名以 prefix 开头的目录名(字典序)——dir 名 前 15 字符内嵌 "20060102-150405" 时间戳,按 started_at 毫秒反查 目录时先圈同秒候选,再逐目录比对 meta.json 消歧。GLOB 前缀可走 索引;调用方保证 prefix 不含通配符(时间戳格式只含数字与 '-')。
func (*Store) DebugDirsContaining ¶
DebugDirsContaining 返回含指定文件名(如 error.json)的目录集合—— keep_error_dirs 容量淘汰的保护集来源。文件与 chunk 两表都查。
func (*Store) DebugErrorSignatures ¶ added in v0.14.0
DebugErrorSignatures 返回「含 error.json 的 dir → (error_stage, error_message)」——keep_error_dirs 按签名限帽的归并源。join 只取 logs 表里归因已落的行;无对应 logs 行(413/飞行中/行已先删)的 目录缺席,调用方按各自独立签名处理。
func (*Store) DebugFile ¶
func (s *Store) DebugFile(ctx context.Context, dir, name string, maxBytes int64) (data []byte, total int64, ok bool, err error)
DebugFile 读一个文件的内容:先查 debug_files(整文件),miss 则按 seq 顺序拼接 debug_chunks。maxBytes>0 时只取前 maxBytes 字节(面板 4MB 截断读取的落点),total 恒为文件真实大小——调用方以 total>len(data) 判截断。maxBytes<=0 表示不限。文件不存在返回 ok=false。
func (*Store) DebugFileList ¶
DebugFileList 返回目录内全部文件的名字与字节数,按名排序——Detail 端点的 Files 清单等价物。同名文件在两表并存时尺寸合并(正常写入 路径按扩展名分表,不会撞名)。
func (*Store) DebugFileNames ¶
DebugFileNames 返回目录内全部文件名(两表 UNION DISTINCT,按名排序)。
func (*Store) DebugPayloadBytes ¶ added in v0.15.0
DebugPayloadBytes 返回 debug payload 库存字节合计的内存镜像——与 DebugDirSizes 各目录值之和同口径(库存字节,压缩行计 gzip 帧长)。 派生态:权威值是表内聚合,cleaner 以周期对账修漂。
func (*Store) DeleteAccount ¶
DeleteAccount 物理删行(纯面板名与墓碑 GC 用);名不存在是空操作。
func (*Store) DeleteDebugDir ¶
DeleteDebugDir 删除一个目录在两表中的全部行;两表删除同事务提交。
func (*Store) DeleteDebugDirsBefore ¶
func (s *Store) DeleteDebugDirsBefore(ctx context.Context, dirPrefix string, exclude []string) error
DeleteDebugDirsBefore 删除目录名字典序小于 prefix 的全部目录—— retention_days 的落点:目录名内嵌 "20060102-150405" 时间戳, dir<cutoff 即「进入时刻早于界限」(同秒 -NN 后缀排在裸名之后, 字典序与时间序一致)。exclude 里的目录名豁免(keep_error_dirs 保护集对龄删同样生效)。
func (*Store) DeleteDebugPayloadsBefore ¶ added in v0.14.0
func (s *Store) DeleteDebugPayloadsBefore(ctx context.Context, bound string, exact, prefixes []string) error
DeleteDebugPayloadsBefore 删除目录名小于 bound 的全部目录中、名字 命中 exact 精确名或 prefixes 前缀(GLOB 词干)的行——payload_hours 剥离的集合化形态:一条 DELETE 替代逐目录枚举+删除的 N+1。 bound 由调用方先钳位到活跃集最小名之下(请求在写的目录不剥)。
func (*Store) DeleteLogsBefore ¶
DeleteLogsBefore 删除 time 早于 ms 的行(logs 表的时间保留清理), 返回删除行数。按 deleteLogsBatch 分片循环:每片一条 IN 子查询圈定 最旧 id 段的小事务,中断后下一轮按原谓词续删。删除域钳在 rollup 水位内(id ≤ log_cells_covered_id):水位内行已记账,删除后其贡献 留在 cells 账本;水位外行只属于绕过双写的写入者留下的缝隙,留给 覆盖(后续任意插入推进水位、或 Open 的 ReconcileCells)后下轮再删, 避免其聚合贡献无声消失。
func (*Store) DeleteModel ¶
DeleteModel 删除一条模型注册项;不存在时为空操作。
func (*Store) DeleteSetting ¶
DeleteSetting 删除一个设置键;不存在时为空操作。
func (*Store) DeleteState ¶
DeleteState 删 runtime_state 一键;不存在时为空操作。
func (*Store) DeleteToken ¶
DeleteToken 按 id 删除令牌行。
func (*Store) EffectiveAccounts ¶
func (s *Store) EffectiveAccounts(ctx context.Context, declared []config.DevinAccountConfig) ([]ResolvedAccount, error)
EffectiveAccounts 是读路径便捷封装:ListAccounts + MergeAccounts。
func (*Store) ExistsLogBefore ¶
ExistsLogBefore 报告在 q 的筛选口径下是否仍存在 time 早于 q.SinceMS 的行(has_more 的「窗口下界之外仍有更早历史」投影)。 沿用同一 where 编译——不带筛选的无条件探测会让过滤翻页窗外无命中 时也报 has_more。
func (*Store) ExportLegacy ¶
ExportLegacy 把各表逐源写回文件时代格式。逐源独立——单源失败不 阻断其余,全部错误经 errors.Join 汇总返回(调用方据此定退出码)。 stateDir/logRoot 与 ImportLegacy 同义:整文件 JSON 落 stateDir, jsonl 与 gate-state 落 logRoot(缺失时由调用方建好)。
func (*Store) GCTombstonedAccounts ¶
GCTombstonedAccounts 收死墓碑:deleted=1 AND name NOT IN declared (declared 为空时收掉全部墓碑)。只在重推成功后由装配层调,读路径 不做写。返回删除行数。
func (*Store) GateSendsByDay ¶ added in v0.15.0
func (s *Store) GateSendsByDay(ctx context.Context, sinceUnix int64) (map[string]GateDaySends, int, error)
GateSendsByDay 把闸门放行数按本地日聚合,返回 'YYYY-MM-DD'→分解读数 与窗口内出现过的 lane 数。sends/row 的覆盖率期望 = lanes × 当日已流逝 分钟数——lane 数取整个查询窗的全集而非逐日:某 lane 整日零行时逐日 口径会把它从期望值里抹掉,而整日静默恰恰是要被覆盖率暴露的缺口。 sinceUnix(unix 秒)按 window_start 下界过滤。跨 lane 合计——sends/row 指标的分母(logs 行数)同样是跨 lane 口径。quota<=0 的闸门照常记窗行: 不限速放行仍是真实发送,与限流放行走同一本 used_* 账。
func (*Store) GetAccount ¶
GetAccount 按名取行;不存在时 ok=false。
func (*Store) GetSetting ¶
func (s *Store) GetSetting(ctx context.Context, key string) (value string, updatedAt int64, ok bool, err error)
GetSetting 读一个设置键;不存在返回 ok=false。
func (*Store) ImportDebugDirs ¶
ImportDebugDirs 把 logRoot 下遗留的请求目录搬进 debug 两表后删除。 供 D3 换底后的启动后台任务调用,可在服务运行中执行——与在线写入 互不干扰(在线请求拿的是新时间戳目录名,不会撞上历史目录)。
断点续传:目录按名序(=时间序)逐个处理,每个目录的「文件行 + runtime_state[progressKey]=水线值」在同一事务提交;水线只前进不 后退。重跑不盲信水线:先查库,已入库的目录只剩删盘兜底;未入库 目录重新导入——包括水线之下被放回的旧名目录(备份恢复/手工拷贝), 否则它们会被静默删而从未入库。顶层文件(stderr.log、index.jsonl、 *.migrated 等)与名字不匹配请求目录模式的子目录一律不碰。
func (*Store) ImportLegacy ¶
ImportLegacy 把文件时代的持久化搬进库。触发条件是「源文件存在」 而不是一次性标记:分阶段落地期间旧写路径(D2–D6 切换前仍在写 index.jsonl/auth_tokens.json 等)会在导入后重建同名文件,再次 调用必须把新文件也并进来。每个源在「数据行 + imported:<src> 标记」的同一事务内提交,导入全部幂等(dir 唯一索引、token 按 token 列去重、(account,at) 配额去重、KV 覆盖),成功后原文件改名 <name>.migrated。可重复调用,无文件时退化成几次 stat。 imported:<src> 与 import_base_done 只写不读——纯粹的一次性留痕, 供排障确认「那次导入跑过」,不参与任何判定。
func (*Store) IncrementalVacuum ¶
IncrementalVacuum 回收 freelist 页——auto_vacuum=INCREMENTAL 只把 删除页挂进 freelist,不显式跑这步 .db 文件不回缩(db_bytes 会与 实际占用分叉)。按 vacuumChunkPages 小块循环:每次调用间释放写连接, 让批量写事务与清洁工删除插队,直到 freelist 清空或耗尽墙钟预算。
func (*Store) InsertDetachedBlob ¶ added in v0.16.0
func (s *Store) InsertDetachedBlob(ctx context.Context, b DetachedBlob) error
InsertDetachedBlob 落一条 completed 条目载荷。同键冲突按 finished_at 仲裁:只接受不旧于在场的写入——同语义请求在两条 lane 先后脱钩完成、 或被替换的旧泵晚于新泵收尾时,库里的恒是较新那份重放。
func (*Store) InsertDetachedEvent ¶ added in v0.16.0
func (s *Store) InsertDetachedEvent(ctx context.Context, e DetachedEvent) error
InsertDetachedEvent 追加一条台账行;at 记 unix 毫秒(与 logs.time 同单位)。
func (*Store) InsertGateWindow ¶ added in v0.15.0
func (s *Store) InsertGateWindow(ctx context.Context, w *GateWindow) error
InsertGateWindow 追加一条闸门窗口聚合行。(lane,window_start) 有唯一 索引——reuseport 交接期新旧进程会并发观察同一窗口,撞车丢后写者不报错, 与 quota_samples 的 OR IGNORE 口径一致。
func (*Store) InsertLog ¶
InsertLog 写入一条请求日志行,返回自增 id。log_source 原样落字段 (业务分类归写方 debuglog.logRowFor 与导入器)。行插入与 rollup 记账(log_cells 贡献 + 水位推进)同一事务提交。
func (*Store) InsertQuotaSample ¶
func (s *Store) InsertQuotaSample(ctx context.Context, q *QuotaSample) error
InsertQuotaSample 追加一条配额快照。(account,at) 有唯一索引—— 同秒撞车(导入与实时采样并行、间隔配成 <1s)时丢新点不报错, 与导入路径的 OR IGNORE 口径一致。
func (*Store) InsertToken ¶
InsertToken 插入令牌行并返回自增 id;调用方持零 ID 传入。
func (*Store) LaneAttemptCauses ¶ added in v0.15.0
LaneAttemptCauses 返回 sinceDay(本地日 'YYYY-MM-DD')起的全部聚合行, 按日/泳道/成因升序。表体积天然有界(lane×日×成因),不做额外聚合。
func (*Store) ListAccounts ¶
func (s *Store) ListAccounts(ctx context.Context) ([]*AccountRow, error)
ListAccounts 返回全部行含墓碑,ORDER BY created_at, name。
func (*Store) ListGateWindows ¶ added in v0.15.0
func (s *Store) ListGateWindows(ctx context.Context, lane string, since int64, limit int) ([]*GateWindow, error)
ListGateWindows 按窗口起点升序返回某 lane since(unix 秒)之后的行, 至多 limit 条(取最新者——SQL 倒序截断后 Go 侧反转回升序);limit<=0 不限。lane 为空串时返回全部 lane。
func (*Store) ListModels ¶
func (s *Store) ListModels(ctx context.Context) ([]ModelEntry, error)
ListModels 返回全部注册项,按 model 排序。
func (*Store) ListQuotaSamples ¶
func (s *Store) ListQuotaSamples(ctx context.Context, account string, since int64, limit int) ([]*QuotaSample, error)
ListQuotaSamples 按时间升序返回某账号 since 之后的快照,至多 limit 条(取最新者——SQL 倒序截断后 Go 侧反转回升序);limit<=0 不限。 account 为空串时返回全部账号(兼容单号时代无 account 字段的行)。
func (*Store) ListSettings ¶
func (s *Store) ListSettings(ctx context.Context) (values map[string]string, updated map[string]int64, err error)
ListSettings 返回全部设置键值与各自更新时间。
func (*Store) ListTokens ¶
ListTokens 返回全部令牌行(含停用),按 id 升序——与旧文件 的排序语义一致。
func (*Store) LoadDetachedBlobs ¶ added in v0.16.0
func (s *Store) LoadDetachedBlobs(ctx context.Context, lane string, since int64) ([]DetachedBlob, error)
LoadDetachedBlobs 取某 lane 在 since(unix 毫秒)之后完成的全部 载荷行——开机播种窗口即条目的 completed TTL。按 finished_at 升序 返回,播种侧依序灌册让较新的条目在容量让位序里排在后。
func (*Store) LogCells ¶
func (s *Store) LogCells(ctx context.Context, slotSec, sinceSec, untilSec int64, sc LogScope, cb func(LogCellKey, LogCellTotals)) error
LogCells 按 (slotSec 秒槽,api,生效模型,key_hash) 聚合时间窗内的日志行, 逐格回调。格子计入条件是它与 [since,until)(unix 秒)有任意重叠—— 即 slot+slotSec>since 且 slot<until,翻译成行的 time 范围是 [alignUp(since-(slotSec-1)), alignDown(until-1)+slotSec) 毫秒。 槽宽是 600s 整数倍且 scope 无 account 维时走 log_cells UNION 补尾: 窗口两界已按槽宽对齐,整格覆盖无需边带,只有水位外行落原始侧。
func (*Store) LogDirByID ¶
func (s *Store) LogDirByID(ctx context.Context, id int64) (dir string, timeMS int64, ok bool, err error)
LogDirByID 按自增 id 反查调试目录名与请求时刻(毫秒)。
func (*Store) LogLastByModel ¶
LogLastByModel 返回各生效模型的最近快照;kh 非空时只看该令牌的行。 逐模型 emodel=? ORDER BY id DESC LIMIT 1 点查走 idx_logs_emodel_id (模型数远小于行数),替代两遍无时间界 GROUP BY 全表扫。
func (*Store) LogLatency ¶
LogLatency 返回全局延迟分位数摘要(duration/ttfb 两行)—— /admin/runtime-metrics 轮询只消费这两行。
func (*Store) LogMatrixCells ¶ added in v0.16.0
func (s *Store) LogMatrixCells(ctx context.Context, q LogQuery, slotSec int64) ([]MatrixCell, error)
LogMatrixCells 把 q 筛选窗口内的日志行聚合成 (slotSec 秒槽, 折叠 account) 桶,供健康条逐格分色;与 SearchLogs 共享 where 编译, rejected 行同口径剔除。
func (*Store) LogModels ¶
LogModels 返回出现过的生效模型名集合(排序);kh 非空时只数该 key_hash 产生过流量的模型(api_token 身份的数据范围收敛)。
func (*Store) LogRecentRPM ¶
LogRecentRPM 返回最近 60 秒内完成的非 499 请求数;sc 为零值时全量 (model 生效模型、kh、account 逐维下推,per-account 变体即 LogScope{Account: lane})。time 预筛同 LogRecentWindow。
func (*Store) LogRecentRPMByKeyHash ¶ added in v0.16.0
LogRecentRPMByKeyHash 按 key_hash 分组返回最近 60 秒内完成的非 499 请求数——替代逐令牌 LogRecentRPM 循环的一次 GROUP BY 扫描。
func (*Store) LogRecentRPMByModel ¶ added in v0.16.0
LogRecentRPMByModel 按生效模型分组返回最近 60 秒内完成的非 499 请求数;kh 非空时只看该令牌的行。替代逐模型 LogRecentRPM 循环 的一次 GROUP BY 扫描。
func (*Store) LogRecentWindow ¶
func (s *Store) LogRecentWindow(ctx context.Context, seconds int64, sc LogScope) (LogRecentAgg, error)
LogRecentWindow 聚合最近 seconds 秒内完成的条目(recent 环的 SQL 版)。 完成时刻表达式不可索引,用 time > (cut-3600s) 预筛把扫描圈进 idx_logs_time_status 范围——duration 受排空上限约束(≪3600s),不漏行。
func (*Store) LogStatusCodes ¶
LogStatusCodes 返回出现过的状态码集合(升序,不含 0 占位); keyHash 非空时只看该令牌的行——api_token 身份的过滤面板与别处 的 key_hash 收敛同口径。
func (*Store) LogTrendSeeds ¶
LogTrendSeeds 返回最近 60 分钟内完成的条目(新在前,上限 limit), 供启动时预热 RPM/QPS 趋势桶——等价于旧「读索引尾部 50000 行再 按完成时刻过滤」的路径,窗口谓词直接下推。
func (*Store) Maintain ¶ added in v0.14.0
Maintain 执行一轮库级周期养护:logs 行按龄删除(logRowDays<=0 时 跳过)、quota_samples 恢复到行数界、gate_windows 与 lane_attempt_causes、detached_events 按同一保留期按龄删除、回收 freelist 页。各项互相独立,单项失败不阻断后续——错误经 errors.Join 汇总返回,调用方记日志即可。原 debuglog.cleanOnce 的 收尾职责上移到这里:养护对象是库不是目录,由 main.go 的 ticker 驱动。 gate_windows 与 logs 摘要行共用 logRowDays:两者都是「时间序列 明细行」的检索面,保留期同口径不单设旋钮。
func (*Store) PruneDetachedBlobs ¶ added in v0.16.0
PruneDetachedBlobs 删除 finished_at 早于 before(unix 毫秒)的行, 返回删除数。表的唯一消费者是开机播种(窗口=条目 completed TTL); before 取略大于 TTL 的保留界即可——过期行只供死后取证,不留长史。
func (*Store) PruneDetachedEvents ¶ added in v0.16.0
PruneDetachedEvents 删除早于 before(unix 毫秒)的行,返回删除数。 与 logs 摘要行共用同一保留期(Maintain 同一 cutoff 调用)。
func (*Store) PruneGateWindows ¶ added in v0.15.0
PruneGateWindows 删除窗口起点早于 before(unix 秒)的行,返回删除数。 与 logs 摘要行共用同一时间保留口径(Maintain 按 logRowDays 喂入); 分片逐批提交,保留期调小的存量差不独占写连接。
func (*Store) PruneLaneAttemptCauses ¶ added in v0.15.0
PruneLaneAttemptCauses 删除早于 beforeDay 的行,返回删除数。与 logs 摘要行共用同一保留期(Maintain 同一 cutoff 调用);分片与其他 保留删除同形。
func (*Store) PruneQuotaSamples ¶
PruneQuotaSamples 把 quota_samples 截到最新 quotaSampleKeep 行 (同秒并列按 id 取新者,帽是精确界)。返回删除行数。保留集谓词 对分片删除稳定:被删的都是集外旧行,帽内成员资格不随分片漂移。
func (*Store) PutDebugFile ¶
PutDebugFile 写 debug_files 一行(同名覆写):meta.json 等 可重写文件走这里。超阈值内容透明压缩(usize=解压前尺寸)。
func (*Store) QueueState ¶ added in v0.16.0
QueueState 把一步 runtime_state 写排进单写者协程:set/delete 按 入队序应用——调用方在自己的互斥区内入队,原「写/删须在锁内序化」 的约束由 FIFO 承接(clear 先入队、persist 后入队的交错在协程侧 不可能倒序落库),锁内自此不再带 SQLite I/O。非阻塞:队满丢弃 记数——内存态权威,落库只服务重启恢复,丢行最坏是复活一条到期 即清的旧冷却。
func (*Store) ReapOrphanBlobs ¶ added in v0.15.0
ReapOrphanBlobs 做 CAS 的 mark-sweep 收尸,两个 sweep 各自分片 (原先同一事务全量删除随 CAS 体量长到秒级,独占唯一写连接饿死 claim/写路径)。先扫悬垂 ref——引用即行的保活前提是「(dir,name) 文件行还是 manifest」,文件行已死(回滚期旧二进制删 dir 不知 refs 表的泄漏路径)或被覆写/剥离成非 manifest(OR IGNORE 重放 等)时 ref 已死,留着只会让 blob 假活。再删过宽限期仍无引用的 blob。每片内谓词复检与删除同事务原子完成,等价原单事务的 「判定到提交无并发写者撞入」;片间中断下轮重枚举续删。挂在 Maintain 的周期养护里——对象是表不是目录,节奏与淘汰 tick 同量级即可,共享字节滞后释放。
func (*Store) ReconcileCells ¶ added in v0.15.0
ReconcileCells 把水位线之后落库的非 rejected 行补记进 rollup—— 绕过双写的写入者有无 cells 码的旧二进制、外部工具与 importIndex: Open 收尾固定调它闭合这类缝隙(9-19 实证 7,634 行险些永隐), ImportLegacy 收尾再补一次导入期写入;常规调用是 id>水位 的空扫。
func (*Store) ReconcileDebugPayloadBytes ¶ added in v0.15.0
func (s *Store) ReconcileDebugPayloadBytes(ctx context.Context, actual int64) (drift int64, err error)
ReconcileDebugPayloadBytes 用权威总量重置计数器(持久化行与内存镜像 一起校正),返回重置前内存读数与权威值之差(正=计数高估,负=低估)—— 供 cleaner 对账记录漂移。upsert 顺带补回被手删的计数器行,并清掉 异步播种半途残留的 pending 行(crash 僵尸继续吞增量会让内存镜像的 增量被收进死账);持久化失败时内存镜像仍被校正,错误如实返回由调用方 告警。
func (*Store) SearchLogMatrix ¶ added in v0.17.0
func (s *Store) SearchLogMatrix(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, err error)
SearchLogMatrix 是 SearchLogs 的窄列变体:只回填 matrixEntry 与 ErrorOwner 消费的字段,其余 LogRow 字段保持零值。
func (*Store) SearchLogs ¶
func (s *Store) SearchLogs(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, err error)
SearchLogs 返回命中行(新在前,id 倒序=旧 index 追加序倒排的忠实 移植——行只在完成时落库,id 序即完成序)与命中总数 total (分页前的完整计数——与旧「窗口内扫到的命中数」不同,旧口径只是 读取窗口内的命中,新口径是 SQL 精确值)。页查询与计数分两条: COUNT(*) OVER() 会把全命中集物化进 temp B-tree(实测 9k 行无过滤 首页 ~45ms),独立标量计数只走索引扫描,页查询靠主键逆序 LIMIT 只读本页行。
func (*Store) SearchLogsPage ¶ added in v0.17.0
func (s *Store) SearchLogsPage(ctx context.Context, q LogQuery) (rows []*LogRow, total int64, hasMore bool, err error)
SearchLogsPage 是日志页的 keyset 翻页编排(原 ccpanel.dashboardLogs 的页边界规则,编排下沉后与语义一起搬家):q 携带原始页参数—— Limit<=0 按 200、>1000 按 1000;Offset<0 按 0;BeforeID 是上一页 最旧行的 id,与 Offset 并存时谓词取交(id<before_id 且按 offset 跳行)。返回本页行(新在前)、total 与 has_more:
- 首页(Offset==0 且 BeforeID==0)付精确 COUNT(*),total 是 筛选命中总数,has_more=total>len(rows);
- 深页多取一行(limit+1 探测)判 has_more 并跳过全窗计数—— total=-1 标记计数缺席,调用方据此省略 count 字段(深页翻页时 全窗计数 ~0.7-1s/页是纯税,字段缺席走前端既有降级分支);
- 两条路径都判不出更多命中时回落 ExistsLogBefore——时间窗下界 之外仍有更早历史也算 has_more。
func (*Store) SetModel ¶
func (s *Store) SetModel(ctx context.Context, e ModelEntry) error
SetModel 写入或覆盖一条模型注册项。
func (*Store) SetSetting ¶
SetSetting 写入一个设置键;updatedAt 传 0 时取当前毫秒。 面板设置的「覆盖 config.yaml 恒赢」语义在上层,本表只是 KV。
func (*Store) StateQueueDrops ¶ added in v0.16.0
StateQueueDrops 返回异步写丢弃数(队满拒收与写失败合计)——台账 存在的目的就是兜住争用期的丢痕迹,它自己丢了多少必须有数。
func (*Store) StoreOpens ¶ added in v0.16.0
func (s *Store) StoreOpens(ctx context.Context) (*StoreOpensReport, error)
StoreOpens 读开库台账快照。三条 SELECT 都走读池;行数被 keep-last-N 自界(≤storeOpensKeep),无索引全扫也是微秒级。
func (*Store) StripDebugDirsBefore ¶ added in v0.15.0
func (s *Store) StripDebugDirsBefore(ctx context.Context, bound string, keep, exclude []string) error
StripDebugDirsBefore 把目录名小于 bound、且不在 exclude 名单中的目录 剥到归因锚点:删除名字不在 keep 中的全部行——容量淘汰第一相的集合 形态,files/chunks/refs 三表共用同一 WHERE(ref 的 name 是 manifest 文件名,manifest 非锚点故引用随行死,锚点文件本身没有 CAS 引用)。 语义与 WriteDebugBatch 的 StripDirs 一致(errors_only 剥载同款)。
func (*Store) UpsertAccount ¶
func (s *Store) UpsertAccount(ctx context.Context, row *AccountRow) error
UpsertAccount INSERT ... ON CONFLICT(name) DO UPDATE;created_at 只在 首插写(row.CreatedAt 为 0 时取 now),updated_at 恒刷新成 now。整行 覆盖语义——调用方做部分字段补丁时须先读后写;token/credentials_file/ notes 传 "" 落 NULL、priority/max_rpm 传 nil 落 NULL,即清掉行覆盖。
func (*Store) UpsertToken ¶
UpsertToken 按 id 覆盖整行——Token 的窗口折叠等域逻辑都在 调用方内存里完成,本方法只是持久化快照(替代整文件重写)。
func (*Store) UsageStats ¶
func (s *Store) UsageStats(ctx context.Context) (UsageSnapshot, error)
UsageStats 返回 logs 表全量聚合快照:窗口/今日/逐日累计、按模型/按 key、模型×日矩阵、错误阶段、8 天 10 分钟粒度趋势、全局延迟分位数 (最近 4096 条)与最近 256 个限流事件。
func (*Store) WALBytes ¶ added in v0.15.0
WALBytes 返回 WAL 文件的磁盘占用:db_bytes 与 debug payload 口径差的 主要解释项——checkpoint 饥饿时 WAL 可远超主库文件,单列它让「WAL 顶爆 DBBytes」在面板上可见而不是事后挖掘。
func (*Store) WriteDebugBatch ¶ added in v0.14.0
func (s *Store) WriteDebugBatch(ctx context.Context, batch DebugBatch) error
WriteDebugBatch 把一个 DebugBatch 合并进一个事务——写 worker 的周期 冲刷把各在飞请求的暂存与完成收尾合批,一次 commit 覆盖全部本周期 写入。文件行内容须预编码(编码成本由调用方 goroutine 承担);chunk 行仍带原文,在本函数内编码。删除排在插入之后:同事务内为被剥目录 暂存的 payload 行一并清除,meta/error 锚点不在删除谓词内。任一失败 整体回滚。
type StoreOpen ¶ added in v0.16.0
StoreOpen 是 store_opens 台账一行的领域形状;Argv 保留落库原值 (os.Args 的 JSON 数组文本,4KB 截断可能切出非法 JSON),渲染归 调用方。
type StoreOpensReport ¶ added in v0.16.0
StoreOpensReport 是开库台账快照:总行数、最近若干行(新在前)、 回看窗内 distinct pid 数。台账是观测面——表缺席/被污染时读失败 原样上抛,由调用方降级省略该组而非视为致命。
type SwitchCause ¶ added in v0.15.0
SwitchCause 是一次被放弃 lane 尝试的归因键:Lane 是被试的 lane, Cause 是放弃成因(词表见 lane_attempt_causes DDL 注释)。 LogRow.SwitchCauses 的键型——不是列,只是写路径的展开载体。
type TokenRow ¶
type TokenRow struct {
ID int64
Token string
Description string
CreatedAt int64
ExpiresAt *int64
LastUsedAt *int64
IsActive bool
SuccessCount int64
FailureCount int64
StreamAvgTTFB float64
NonStreamAvgRT float64
StreamCount int64
NonStreamCount int64
PromptTokensTotal int64
CompletionTokensTotal int64
CacheReadTokensTotal int64
CacheCreationTokensTotal int64
TotalCostUSD float64
EffectiveCostUSD float64
CostUsedMicroUSD int64
CostLimitMicroUSD int64
DailyUsedMicroUSD int64
DailyLimitMicroUSD int64
DailyPeriodStart int64
MonthlyUsedMicroUSD int64
MonthlyLimitMicroUSD int64
MonthlyPeriodStart int64
Cost5hUsedMicroUSD int64
Cost5hLimitMicroUSD int64
Cost5hAnchor int64
WeeklyUsedMicroUSD int64
WeeklyLimitMicroUSD int64
WeeklyPeriodStart int64
AllowedModels []string
MaxConcurrency int
MaxRPM int
Class string
}
TokenRow 是 auth_tokens 表一行的领域形状,字段镜像 authtoken.Token 的持久化字段;瞬态字段(inflight/rpm*)不在此。 时间一律 unix 毫秒;allowed_models 序列化为 JSON 数组文本。
type UsageDayRow ¶
type UsageDayRow struct {
Date string `json:"date"`
UsageTotals
}
UsageDayRow 是单日聚合。
type UsageMinPoint ¶
type UsageMinPoint struct {
At int64 `json:"at"` // 桶起点 unix 秒
UsageTotals
}
UsageMinPoint 是输出给面板的 10 分钟粒度数据点。
func (UsageMinPoint) MarshalJSON ¶ added in v0.15.0
func (p UsageMinPoint) MarshalJSON() ([]byte, error)
MarshalJSON 稀疏编码单点:只发非零字段。面板 8 天网格的绝大多数桶 只有 requests 与少数字段非零——15 个定长字段全发会让 points 段占到 响应的 82-95%。缺失键在消费侧(stats.js sumUsageTotals 的 Number(p[k])||0)按 0 处理,合计口径不变。at 恒发——零值过滤对它 无意义且是切片的唯一谓词键。
type UsageSnapshot ¶
type UsageSnapshot struct {
WindowStart string `json:"window_start"` // 窗口内最早一条日志的时间
Entries int64 `json:"entries"` // 窗口内参与聚合的行数
Today UsageTotals `json:"today"`
Window UsageTotals `json:"window"`
Days []UsageDayRow `json:"days"` // 新在前
Points []UsageMinPoint `json:"points"` // 旧到新,10 分钟粒度,仅非零桶(稀疏)
Models []DimensionAgg `json:"models"`
Keys []DimensionAgg `json:"keys"`
// ModelDays 是 模型×自然日 的 totals 矩阵,面板的时间范围选择器
// 用它把模型表过滤到所选窗口。
ModelDays map[string]map[string]UsageTotals `json:"model_days,omitempty"`
ErrorStages map[string]int64 `json:"error_stages"`
Duration LatencyStats `json:"duration"`
TTFB LatencyStats `json:"ttfb"`
// RateLimitEvents 是最近的上游 429 采样(旧到新),供面板推算限流阈值。
RateLimitEvents []RateLimitEvent `json:"rate_limit_events,omitempty"`
// SendsPerRow 是逐日(旧到新)sends/row 探针:分子闸门放行数
// (已剔保温 ping)、分母当日 logs 行——内层 connect 重试漂移的
// 唯一活指标;coverage/sends_missing 标注分子对分母日界的覆盖。
// gate_windows 全期无行(闸门整窗未被流量/保温触碰)时整段省略;
// quota<=0 的闸门照样记行——不限速放行也计入分子。
SendsPerRow []SendsRowDay `json:"sends_per_row,omitempty"`
// AttemptCauses 是被放弃 lane 尝试的 日×lane×cause 聚合
//(lane_attempt_causes 表 31 天窗口直读,旧到新):区分真实
// failover 发送(connect code)与本地闸门幻影换号(local_gate:*,
// 零上游成本)。表自 0007 迁移起累计,之前的历史不可回填。
AttemptCauses []LaneAttemptCause `json:"attempt_causes,omitempty"`
}
UsageSnapshot 是聚合结果的完整快照(JSON 形状与旧版一致)。
type UsageTotals ¶
type UsageTotals struct {
Requests int64 `json:"requests"`
Errors int64 `json:"errors"` // status>=400 或 result=failed
Disconnected int64 `json:"disconnected"` // 含 aborted
// RateLimited 是上游返回 429 的次数。本地并发拒绝在 recorder 创建前
// 返回、不进 logs 表,故此处纯为上游限流语义。
RateLimited int64 `json:"rate_limited"`
// ClientFaults/UpstreamFaults 是 errorOwner 归因计数:调用方责任
//(断连/中断/请求体阶段失败)与服务端责任(上游错误与代理自身
// 失败)分列——SLA 口径只把后者算作失分。
ClientFaults int64 `json:"client_faults"`
UpstreamFaults int64 `json:"upstream_faults"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheRead int64 `json:"cache_read_tokens"`
CacheWrite int64 `json:"cache_write_tokens"`
Reasoning int64 `json:"reasoning_tokens"`
TotalTokens int64 `json:"total_tokens"`
// CreditCost 是上游权威计费读数的累计(替代纯 token 估算的 quota 口径)。
CreditCost int64 `json:"credit_cost,omitempty"`
// GenMS/GenOut 是 decode 速率的分母分子:只累计「可信流式」条目
//(见 logDecodeCond),前端用 gen_tokens/gen_ms 求 tok/s。
GenMS int64 `json:"gen_ms,omitempty"`
GenOut int64 `json:"gen_tokens,omitempty"`
}
UsageTotals 是一组请求的基础累计量(JSON 形状与旧 usageTotals 一致)。