Documentation
¶
Overview ¶
Package semantic 是「可选语义检索」(#266 步骤 2b)的核心:切块、凭据隐去、向量量化、内存索引、后台嵌入流水线与查询。
隐私与资源不变量(设计文档 V1–V9,每一条都有对应测试与变异对照):
- V1 关闭 = 零协程、零出站、零内存缓存:工作协程只在「总开关开 + 未暂停 + 密钥可用 + 至少勾了一个项目」时才存在;
- V2 同意范围:只有「已勾选项目 ∩ 允许的内容类型」内、未归档的内容才会被切块外发;外发前再按真实归属核对一次;
- V3 凭据隐去:外发的、哈希的、给用户看的片段都是隐去之后的文本(TitleAndLines 是唯一入口);
- V4 逐条回源校验:查询命中要重读最新原文、核对范围与归档、重算 text_hash,对不上就丢弃;
- V5 出站只经 embedding.Service.Embed:本包不引入 net/http(有测试盯着);
- V6 资源有界:块数上限、嵌入限速(块 / 分钟)、查询限速(次 / 分钟)、不在持有数据库连接时出站;
- V7 向量只在同一签名(model|dims)内比较;签名变了旧向量作废,重建要用户确认;
- V8 取消勾选的项目,向量立刻删除(同步),不等下一轮对账;
- V9 只给网页登录用户(由 API 层保证)。
Package semantic 是可选语义检索的第二部分(#266 步骤 2b):切块、向量量化、凭据隐去、内存向量索引、 后台嵌入流水线与语义查询。
它站在 internal/embedding(配置、密钥、外呼、预算)与 internal/store(条目与向量的持久化)之上: 所有出站请求只走 embedding.Service.Embed,所有数据库读写只走 store 的导出方法。
不变量(设计稿 .cursor/planning/2026-10-26-266-step2b-vector-pipeline-design.md 第 0 节):
V1 关闭 = 零:没有后台协程、没有出站、没有内存缓存。 V2 同意范围:只有「已勾选项目 ∩ 允许类型」的内容会出站。 V3 凭据隐去:出站文本里的凭据特征先替换成 Redacted。 V4 回源校验:语义命中要重新读源行、重算文本哈希,对不上就丢弃。 V5 预算:出站只走 Service.Embed。 V6 资源有界:块数上限、单条最多 MaxChunks 块、出站期间不占数据库连接。 V7 签名一致:向量只和同一个 model|dims 签名的向量比较。 V8 撤回即删:取消勾选项目,该项目的向量立即删除。
Index ¶
- Constants
- Variables
- func Clean(s string) string
- func CleanLine(s string) string
- func Dequantize(q []int8, scale float32) []float32
- func Dot(a, b []int8) int32
- func EstimateTokens(s string) int
- func EstimateTokensFor(chars int64) int64
- func Normalize(s string) string
- func PackInt8(q []int8) []byte
- func Quantize(v []float32) (q []int8, scale float32, err error)
- func Redact(s string) string
- func Score(dot int32, sa, sb float32) float32
- func SigOf(cfg embedding.Config) string
- func UnpackInt8(b []byte) []int8
- type Built
- type Chunk
- type ClearResult
- type Controller
- func (c *Controller) Clear(ctx context.Context) (*ClearResult, error)
- func (c *Controller) Close()
- func (c *Controller) Incomplete(ctx context.Context) (*IncompleteList, error)
- func (c *Controller) IndexLoaded() (loaded bool, entries, chunks int, bytes int64)
- func (c *Controller) Notify()
- func (c *Controller) Pause(ctx context.Context) error
- func (c *Controller) QueriesPerMinute() int
- func (c *Controller) Query(ctx context.Context, p QueryParams) (*QueryResult, error)
- func (c *Controller) Rebuild(ctx context.Context) (*RebuildResult, error)
- func (c *Controller) Rescan()
- func (c *Controller) Resume(ctx context.Context) error
- func (c *Controller) Running() bool
- func (c *Controller) SetEnabled(ctx context.Context, on bool) (store.SemanticRun, error)
- func (c *Controller) SetQueriesPerMinute(n int)
- func (c *Controller) SetScope(ctx context.Context, kinds *[]string, projects *[]uint) (*ScopeResult, error)
- func (c *Controller) Status(ctx context.Context, detail bool) (*Status, error)
- type Hit
- type IncompleteItem
- type IncompleteList
- type Index
- func (ix *Index) Apply(meta Meta, chunks []Vec) error
- func (ix *Index) Bytes() int64
- func (ix *Index) Clear()
- func (ix *Index) Dims() int
- func (ix *Index) Has(kind, ref string) (Meta, bool)
- func (ix *Index) Keys() []Key
- func (ix *Index) Len() (entries, chunks int)
- func (ix *Index) Remove(keys ...Key) int
- func (ix *Index) Search(query []float32, k int, minScore float32, allow func(Meta) bool) ([]Hit, error)
- func (ix *Index) SetMeta(meta Meta) bool
- func (ix *Index) Sig() string
- type Key
- type KindStat
- type Meta
- type NotReadyError
- type Options
- type Params
- type Prepared
- type ProjectStatus
- type QueryHit
- type QueryParams
- type QueryResult
- type RebuildResult
- type ScopeResult
- type State
- type Status
- type Vec
Constants ¶
const ( DefaultChunksPerMinute = 1000 // 嵌入限速:每分钟最多外发多少块 DefaultQueriesPerMinute = 30 // 查询限速:每分钟最多外发多少次查询向量 DefaultMaxChunks = 200_000 // 向量块数上限(内存索引约 200 MB @1024 维) DefaultMinScore float32 = embedding.DefaultMinScore // 默认相似度下限:低于它的语义命中不展示(设置页「相似度下限」可调,默认值的来由见 embedding.DefaultMinScore) )
默认参数(Options 里没给的取这里)。
const ( // ReasonTruncated:内容超过单条上限,只嵌入了前面一部分。 ReasonTruncated = "truncated" // ReasonTailRejected:补后半部分时被嵌入服务拒绝(比如内容安全拦截),保留了前面已经嵌好的部分。 ReasonTailRejected = "tail_rejected" // ReasonRejected:整条被嵌入服务拒绝(比如内容安全拦截),没有向量。 ReasonRejected = "rejected" // ReasonTooShort:去掉空白与隐去内容之后太短(少于 MinRunes 个字符),不嵌入。 ReasonTooShort = "too_short" )
没有被完整嵌入的原因(界面按它给出人话)。
const EntryMaxChunks = 600
EntryMaxChunks 是一个条目最多嵌入多少块(单条上限):600 块 ≈ 21 万 token ≈ 25 万个汉字, 覆盖绝大多数长文档与长对话段;超出的部分不嵌入(关键词检索不受影响,它走全文索引,单条上限是 1 MiB)。
提高这个上限**不改** chunkerVersion:文本哈希(含 chunkerVersion)只取决于清洗后的文本,与块数上限无关, 查询时的回源校验(V4)比的就是它;改了版本号会让库里的每一个命中都被当成「内容变了」丢掉。 切块是顺序的(第 i 块只取决于它前面的内容),所以上限变高时前面的块与块哈希一字不变,向量照旧复用, 只有新增的后半部分要发出去嵌入。
const IncompleteListMax = 200
IncompleteListMax 是一次最多列出多少条(总数另给,界面写明「只列出前 N 条」)。
const LegacyEntryMaxChunks = 200
LegacyEntryMaxChunks 是单条上限提高之前写入的条目所用的上限;库里 chunk_cap = 0 的条目按它算。
const Redacted = "[已隐去]"
Redacted 是被隐去内容的替换文字。
Variables ¶
var DefaultParams = Params{TargetTokens: 350, OverlapTokens: 50, MaxChunks: EntryMaxChunks, MinRunes: 20, TitleMaxRunes: 200}
DefaultParams 是线上用的参数。运行期间只读:嵌入流水线与查询时的回源校验共用它(V4),测试要改上限时 必须在创建控制器之前改、停掉控制器之后再还原。
var ErrBadVector = errors.New("向量不可用(空、含非数字或全零)")
ErrBadVector 表示服务返回的向量不能用(空、含 NaN / Inf、全零)。
var ErrDimMismatch = errors.New("语义索引:向量维度与索引不一致")
ErrDimMismatch 表示向量维度与索引不一致(换了模型 / 维度,或提供商悄悄变了):不写入、不比较。
Functions ¶
func Dequantize ¶
Dequantize 把量化向量还原成(近似的单位)浮点向量,测试与诊断用。
func EstimateTokens ¶
EstimateTokens 估算一段文字的 token 数:汉字假名约 0.7、ASCII 约 0.3、其他约 0.5,向上取整。 只用来决定块的大小;预算入账用的是服务回报的真实用量。
func EstimateTokensFor ¶
EstimateTokensFor 把字符数估成 token 数(上限)。
func UnpackInt8 ¶
Types ¶
type Built ¶
type Built struct {
Chunks []Chunk
Truncated bool // 超过 MaxChunks,后面的内容没有嵌入
Skipped bool // 内容太短或几乎全是隐去内容:不嵌入、不外发
TextHash string // 归一化并隐去凭据后的「标题 + 正文」的哈希(含切块规则版本)
}
Built 是一个条目切块的结果。
type Chunk ¶
type Chunk struct {
Seq int
Text string // 要嵌入的文本:标题行 + 块正文
Hash string // Text 的哈希(32 个十六进制字符)
Tokens int // 估算 token 数(含标题)
// First / Last 是这一块覆盖的源行下标(含)。群消息段里一行就是一条消息,靠它把块映射回消息。
First, Last int
}
Chunk 是一块要嵌入的文本。
type ClearResult ¶
ClearResult 是清除向量的结果。
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller 管理语义检索的后台嵌入流水线、内存索引与查询。可并发使用。
func (*Controller) Clear ¶
func (c *Controller) Clear(ctx context.Context) (*ClearResult, error)
Clear 删除全部向量并暂停(否则后台会立刻把它们重新嵌回来)。勾选的项目与设置保留。
func (*Controller) Close ¶
func (c *Controller) Close()
Close 停止工作协程并释放全部内存;之后 Notify 不再起任何协程。可重复调用。
func (*Controller) Incomplete ¶
func (c *Controller) Incomplete(ctx context.Context) (*IncompleteList, error)
Incomplete 列出没有被完整嵌入的条目(及原因)。
func (*Controller) IndexLoaded ¶
func (c *Controller) IndexLoaded() (loaded bool, entries, chunks int, bytes int64)
IndexLoaded 报告内存索引是否在内存里,以及它的条目数 / 块数 / 向量字节数。
func (*Controller) Notify ¶
func (c *Controller) Notify()
Notify 通知控制器「设置变了」,按最新设置对齐工作协程,可以放心在任何改动设置的地方调用(总开关、范围、暂停、密钥、嵌入配置):
- 现在不该跑(关闭 / 暂停 / 没有项目 / 没有密钥……)→ 立刻叫停工作协程(取消进行中的外呼、叫醒睡眠)并等它退出,再释放内存缓存; 返回时不会再有这条流水线发出的新请求(已经在路上的那个请求被取消,结果丢弃);
- 该跑、已有工作协程 → 唤醒它立即对账;
- 该跑、没有工作协程 → 启动。
启动时调用一次即可恢复上次的运行。不能在工作协程里调用(它会等工作协程退出)。
func (*Controller) Pause ¶
func (c *Controller) Pause(ctx context.Context) error
Pause 暂停:后台嵌入与语义查询都停止,内存缓存释放;向量保留。
func (*Controller) QueriesPerMinute ¶
func (c *Controller) QueriesPerMinute() int
QueriesPerMinute 是「查询向量外发」当前每分钟的上限。
func (*Controller) Query ¶
func (c *Controller) Query(ctx context.Context, p QueryParams) (*QueryResult, error)
Query 做一次语义查询:任何一步失败都返回 State != ok 的回执(不是错误),让调用方退回词法; 只有范围本身不合法(项目不存在、参数冲突)才返回 error。
func (*Controller) Rebuild ¶
func (c *Controller) Rebuild(ctx context.Context) (*RebuildResult, error)
Rebuild 在模型 / 维度变了之后,由用户确认:删掉签名不符的旧向量(以及上次被服务拒绝的条目,让它们重试), 然后按新签名重新嵌入。没有可重建的内容返回 invalid-input 错误。
func (*Controller) Resume ¶
func (c *Controller) Resume(ctx context.Context) error
Resume 继续(同时清掉自动暂停留下的原因)。
func (*Controller) SetEnabled ¶
func (c *Controller) SetEnabled(ctx context.Context, on bool) (store.SemanticRun, error)
SetEnabled 打开 / 关闭总开关。打开前要求密钥可用且维度已填;打开会清除暂停状态;关闭立刻释放内存缓存(向量保留、不再使用)。
func (*Controller) SetQueriesPerMinute ¶
func (c *Controller) SetQueriesPerMinute(n int)
SetQueriesPerMinute 改「查询向量外发」每分钟最多多少次,立即生效。设置页「智能体检索额度」里的「语义合计」保存时调用, 进程启动时也按存下的值调用一次,所以这个限速(网页搜索框与智能体共用)跟着用户设的合计走;缓存命中的查询不占次数。
func (*Controller) SetScope ¶
func (c *Controller) SetScope(ctx context.Context, kinds *[]string, projects *[]uint) (*ScopeResult, error)
SetScope 修改勾选的项目与允许外发的内容类型(nil = 不改)。范围缩小时,范围外的向量在返回之前就已同步删除(V8), 并让进行中的流水线作废它手里的落库(scopeGen 前进),所以取消勾选的内容不会被复活。
type IncompleteItem ¶
type IncompleteItem struct {
Kind string `json:"kind"`
Ref string `json:"ref"`
Title string `json:"title"`
Projects []string `json:"projects"` // 条目所属的、已勾选的项目名
Reason string `json:"reason"`
Chunks int `json:"chunks"` // 已嵌入的块数
ChunkCap int `json:"chunk_cap,omitempty"` // 嵌入时的单条上限(truncated / tail_rejected)
Redo bool `json:"redo,omitempty"` // truncated:单条上限已经提高,后半部分正在或即将补上
}
IncompleteItem 是一个没有被完整嵌入的条目。
type IncompleteList ¶
type IncompleteList struct {
Total int `json:"total"`
Counts map[string]int `json:"counts"` // 四种原因各有多少条(都在,没有的是 0)
Items []IncompleteItem `json:"items"` // 最多 IncompleteListMax 条:先按原因(截断在前、太短在后),再按内容类型、已嵌入块数(多的在前)
More bool `json:"more"` // 还有没列出来的(Total > len(Items))
EntryMaxChunks int `json:"entry_max_chunks"`
MinRunes int `json:"min_runes"`
}
IncompleteList 是明细的响应。
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index 是向量库在内存里的副本,只用来做「扫一遍」的最近邻查询(几十万块以内,纯 Go 点积,不引入任何依赖)。 所有方法并发安全;查询持读锁,写入(Apply / Remove)持写锁——一次全量扫描是几十到一两百毫秒,写入最多等这么久。
func (*Index) Search ¶
func (ix *Index) Search(query []float32, k int, minScore float32, allow func(Meta) bool) ([]Hit, error)
Search 找与查询向量最相近的前 k 个条目(每个条目取最高分的块)。 allow 为空表示不筛;非空时对每个条目的快照调用一次,返回 false 的条目不参与(范围过滤,V2 / V4 的第一道)。 minScore 以下的不返回。结果按分数降序,同分按 (类型, ref) 升序,完全确定。
type Meta ¶
type Meta struct {
Kind, Ref string
WorkflowID string
ProjectID uint
ConversationID string
TextHash string
}
Meta 是一个条目在内存里保留的归属快照:查询时先按它筛范围(便宜),命中后仍会回源按真实归属再核一遍(V4)。
type NotReadyError ¶
type NotReadyError struct{ Reason string }
NotReadyError 表示现在还不能打开语义检索(密钥不可用 / 维度没填);Reason 面向用户。
func (*NotReadyError) Error ¶
func (e *NotReadyError) Error() string
type Options ¶
type Options struct {
Store *store.Store
Embed *embedding.Service
ChunksPerMinute int
QueriesPerMinute int
MaxChunks int
GroupSize int
ReconcileEvery time.Duration
BatchPause time.Duration
BackoffMin time.Duration
BackoffMax time.Duration
IdleRelease time.Duration
// MinScore 大于 0 时是对相似度下限的强制覆盖(测试 / 运维用);0 = 跟随设置页里的「相似度下限」。
MinScore float32
QueryCacheSize int
QueryCacheTTL time.Duration
Now func() time.Time
Logf func(format string, args ...any)
}
Options 创建控制器的参数。
type Params ¶
type Params struct {
TargetTokens int // 每块正文的目标估算 token 数(约 350 ≈ 500 个汉字)
OverlapTokens int // 相邻块重叠的估算 token 数(约 15%)
MaxChunks int // 一个条目最多切多少块;超出的部分不嵌入(Truncated)
MinRunes int // 去掉空白与隐去标记后,标题 + 正文少于这么多个字符的条目不嵌入(Skipped)
TitleMaxRunes int // 标题行最长字符数
}
Params 是切块参数。
type Prepared ¶
type Prepared struct {
Built Built
Title string
Lines []string
LineSeq []int64 // 群消息段:每一行对应的消息 seq;其它类型为 nil
}
Prepared 是一条原文清洗、切块后的结果:嵌入流水线与查询时的回源校验共用 Prepare, 所以两边切出的块与 text_hash 永远一致(V3 / V4)。凭据隐去也发生在这里:外发的、哈希的、给用户看的片段,都是隐去之后的文本。
func (Prepared) MessageSeq ¶
MessageSeq 返回一个块第一行对应的群消息 seq(用来跳到群里的那条消息);不是群消息段返回 0。
type ProjectStatus ¶
type ProjectStatus struct {
ID uint `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Archived bool `json:"archived,omitempty"`
Enabled bool `json:"enabled"`
// 以下按「当前允许的内容类型」统计。
Eligible int `json:"eligible"` // 范围内(允许类型)的条目数
Covered int `json:"covered"` // 其中已追平的(已嵌入,或判定为不嵌入)
Chars int64 `json:"chars"` // 全部内容的字符数
EstTokens int64 `json:"est_tokens"` // 全部嵌入需要的 token(上限估算)
PendingTokens int64 `json:"pending_tokens"` // 还没追平的部分需要的 token(上限估算)
// 各类内容(SearchKinds 里的每一类)各自的体量(不论当前是否允许)。
Kinds map[string]KindStat `json:"kinds"`
}
ProjectStatus 是一个项目的语义检索情况(设置页的项目列表用)。
type QueryParams ¶
type QueryParams struct {
Q string
ProjectID uint
WorkflowID string
Kinds []string // 空 = 全部允许的类型
Limit int
// MinScore 非 nil 时覆盖这一次查询的相似度下限(-1~1,余弦相似度的取值范围)。只给评测与阈值校准用:降到 -1 就是不设下限,
// 才看得到完整的分数分布;只改「展示哪些命中」,同意范围、回源核对与限速都不受影响。
MinScore *float32
}
QueryParams 是一次语义查询。范围字段与词法检索同义(project_id 与 workflow_id 互斥)。
type QueryResult ¶
type QueryResult struct {
State State `json:"state"`
Reason string `json:"reason,omitempty"`
Hits []QueryHit `json:"hits"`
Covered int `json:"covered"` // 范围内已追平的条目数
Total int `json:"total"` // 范围内的条目总数
}
QueryResult 是一次语义查询的回执。State != ok 时 Hits 为空,Reason 说明原因(调用方退回词法结果并给一句话说明)。
type RebuildResult ¶
type RebuildResult struct {
Dropped int `json:"dropped_entries"`
}
RebuildResult 是重建的结果。
type ScopeResult ¶
type ScopeResult struct {
Added []uint `json:"added"`
Removed []uint `json:"removed"`
Deleted int `json:"deleted_entries"` // 因为不在范围内而被立即删除向量的条目数
}
ScopeResult 是修改勾选范围的结果。
type State ¶
type State string
State 是语义检索的状态(界面徽标与查询回执共用)。
const ( StateOff State = "off" // 总开关关 StateNoProject State = "no_project" // 开了,但一个项目都没勾 StateNoKinds State = "no_kinds" // 开了,但没有允许外发的内容类型 StatePaused State = "paused" // 用户暂停 StateAttention State = "attention" // 自动暂停:需要处理(原因见 Reason) StateNoKey State = "no_key" // API Key 不可用 StateNeedsDims State = "needs_dims" // 向量维度为 0,无法确定签名 StateNeedsRebuild State = "needs_rebuild" // 模型 / 维度变了,旧向量已停用,等用户确认重建 StateIdle State = "idle" // 已追平 StateRunning State = "running" // 正在嵌入 StateRetry State = "retry" // 外呼失败,等待重试 StateBudget State = "budget" // 今日 token 额度用完 StateFull State = "full" // 向量块数到达上限 // 以下只出现在查询回执里。 StateOK State = "ok" StateProjectOff State = "project_off" // 查询限定的项目没有开启语义检索 StateThrottled State = "throttled" // 查询过于频繁 StateDegraded State = "degraded" // 查询失败,已退回词法 StateEmpty State = "empty" // 还没有任何向量 )
type Status ¶
type Status struct {
State State `json:"state"`
Reason string `json:"reason,omitempty"`
Enabled bool `json:"enabled"`
Paused bool `json:"paused"`
Kinds []string `json:"kinds"`
ProjectIDs []uint `json:"project_ids"`
Sig string `json:"sig"`
Entries int64 `json:"entries"` // 向量库里已嵌入的条目(含旧签名的)
Skipped int64 `json:"skipped"` // 内容太短而不嵌入的条目
Failed int64 `json:"failed"` // 服务拒绝嵌入的条目
StaleEntries int64 `json:"stale_entries"` // 签名与当前不同、需要重建的条目
Truncated int64 `json:"truncated"` // 因超长只嵌入了前面部分的条目
Chunks int64 `json:"chunks"`
VecBytes int64 `json:"vec_bytes"`
MaxChunks int `json:"max_chunks"`
// 范围内条目数 / 已追平 / 待嵌入:不带 detail 时是工作协程上一次对账的快照(snapshot_at 是它的时间);
// 关闭、暂停、没有勾选项目等不运行的状态下没有快照(全为 0、没有 snapshot_at),要看现算的数字请加 detail。
Eligible int `json:"eligible"`
Covered int `json:"covered"`
Pending int `json:"pending"`
PendingTokens int64 `json:"pending_tokens"`
SnapshotAt *time.Time `json:"snapshot_at,omitempty"`
ProgressDone int `json:"progress_done"`
ProgressTotal int `json:"progress_total"`
RetryAt *time.Time `json:"retry_at,omitempty"`
LastError string `json:"last_error,omitempty"`
LastErrorAt *time.Time `json:"last_error_at,omitempty"`
IndexLoaded bool `json:"index_loaded"`
IndexEntries int `json:"index_entries"`
IndexChunks int `json:"index_chunks"`
IndexBytes int64 `json:"index_bytes"`
ChunksPerMinute int `json:"chunks_per_minute"`
QueriesPerMinute int `json:"queries_per_minute"`
MinScore float32 `json:"min_score"`
Projects []ProjectStatus `json:"projects,omitempty"`
}
Status 是语义检索的整体状态。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fakeembed 是测试用的「假嵌入服务」:一个本机的 OpenAI 兼容 /embeddings 端点, 用确定性的「概念词典 + 字符 n-gram 哈希」造向量,使近义词在向量上相近、而词法完全不命中—— 这样才能验证「语义检索」真的比词法多找到了东西。
|
Package fakeembed 是测试用的「假嵌入服务」:一个本机的 OpenAI 兼容 /embeddings 端点, 用确定性的「概念词典 + 字符 n-gram 哈希」造向量,使近义词在向量上相近、而词法完全不命中—— 这样才能验证「语义检索」真的比词法多找到了东西。 |