Elffuss BraidHub

kikocis/utopia public

Short type names get an index shaped like them, and responses arrive compressed (#116)

* Short type names get an index shaped like them, and responses arrive compressed

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* rustfmt

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Clippy

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changesetae59bab5e01a40cd106ff51fc8a2e08b48d808b4710702075138e1618faa6a26
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 00:15 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 00:15 +08:00
Parents834f8753ffd7

Browse the files at this changeset

7 files changed

modified Cargo.lock +30 −0
@@ -116,6 +116,18 @@
116116 "password-hash",
117117 ]
118118
119+[[package]]
120+name = "async-compression"
121+version = "0.4.43"
122+source = "registry+https://github.com/rust-lang/crates.io-index"
123+checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"
124+dependencies = [
125+ "compression-codecs",
126+ "compression-core",
127+ "pin-project-lite",
128+ "tokio",
129+]
130+
119131 [[package]]
120132 name = "async-stream"
121133 version = "0.3.6"
@@ -587,6 +599,23 @@
587599 "memchr",
588600 ]
589601
602+[[package]]
603+name = "compression-codecs"
604+version = "0.4.38"
605+source = "registry+https://github.com/rust-lang/crates.io-index"
606+checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
607+dependencies = [
608+ "compression-core",
609+ "flate2",
610+ "memchr",
611+]
612+
613+[[package]]
614+name = "compression-core"
615+version = "0.4.32"
616+source = "registry+https://github.com/rust-lang/crates.io-index"
617+checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
618+
590619 [[package]]
591620 name = "const-oid"
592621 version = "0.9.6"
@@ -4466,6 +4495,7 @@
44664495 source = "registry+https://github.com/rust-lang/crates.io-index"
44674496 checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
44684497 dependencies = [
4498+ "async-compression",
44694499 "bitflags",
44704500 "bytes",
44714501 "futures-core",
modified Cargo.toml +5 −1
@@ -55,7 +55,11 @@
5555 pdf-extract = "0.12"
5656 calamine = "0.36"
5757 pgvector = { version = "0.4", features = ["sqlx"] }
58-reqwest = { version = "0.13", default-features = false, features = ["json", "stream", "http2", "rustls", "webpki-roots", "charset", "system-proxy"] }
58+# `gzip` 不是可选项:一次嵌入回 64×1024 个浮点数,写成 JSON 文本每个数字占
59+# 21 字节而信息量只有 4 字节,一次响应 1.33 MB。实测同一条链路上不压缩 62 秒、
60+# gzip 21 秒(429 KB)——服务端算完只用 1 秒,其余全在传。
61+# `default-features = false` 把它一并关掉了,这里补回来。
62+reqwest = { version = "0.13", default-features = false, features = ["json", "stream", "http2", "rustls", "webpki-roots", "charset", "system-proxy", "gzip"] }
5963
6064 feed-rs = "2"
6165 cron = "0.12"
modified crates/utopia-server/src/ontology_index.rs +75 −16
@@ -9,11 +9,31 @@
99 //! 而对比原文不会。
1010
1111 use crate::{llm_util, AppState};
12+use futures_util::{stream, StreamExt};
1213 use utopia_store::ontology::TypeToEmbed;
1314 use uuid::Uuid;
1415
15-/// 一次送多少条去嵌入。跟文档分块那边同量级,够摊平往返又不至于把请求撑爆。
16+/// 一次送多少条去嵌入。
17+///
18+/// **64 是实测站得住的那个数。** 曾经改成 16,理由是拿合成短文本量出来的
19+/// "每条更快"——而真实的类文本平均 151 字符,那组数据不作数。改小之后请求数
20+/// 翻四倍、每个都付约 2.5 秒固定开销,整体吞吐反而掉了一半。
21+///
22+/// 换批大小之前先拿**真实的 `embedded_text`** 去量,别拿造出来的短句。
1623 const BATCH: usize = 64;
24+/// 同时在飞的嵌入批数上限。
25+///
26+/// **关键不是快,是不能把闸门占死。** 这是个后台补齐任务,而嵌入模型的并发闸门
27+/// (`model_concurrency`,缺省 10)是全局共享的——文档分块入库也要走它。
28+///
29+/// 从前这里串行,一次一张许可证、每批之间释放,文档处理插得进来。改成
30+/// `join_all` 一次挂 31 个批次之后,它变成一个常驻的 10 深队列,每个批次握着
31+/// 许可证 60 秒:**5 篇文档全卡在 `embedding` 状态,抽取 15 分钟零进展**。
32+/// 不是 API 挂了,是这个任务把共享资源占满了。
33+///
34+/// 所以这里的上限必须**明显小于**闸门,给别的活留出位置。4 是实测能跑满
35+/// 吞吐又留有余量的:4 个 16 条并发,墙钟 18.5 秒(串行要 50 秒)。
36+const EMBED_JOBS: usize = 4;
1737
1838 /// 把这个库里陈掉的本体向量补齐。没配嵌入模型就直接返回 `Ok(0)`——
1939 /// 检索是增强,不该拦住没配模型的部署。
@@ -38,31 +58,60 @@
3858 };
3959 let (Some(client), Some(model)) = (
4060 llm_util::embed_client(&settings),
41- settings.embed_model.as_deref(),
61+ // 取拥有的一份:下面那些 future 要把 settings 挪进 Arc,借着它就动不了了
62+ settings.embed_model.clone(),
4263 ) else {
4364 return Ok(0);
4465 };
4566
4667 let stale =
47- utopia_store::ontology::types_needing_embedding(&state.pool, kb_id, model, only).await?;
68+ utopia_store::ontology::types_needing_embedding(&state.pool, kb_id, &model, only).await?;
4869 if stale.is_empty() {
4970 return Ok(0);
5071 }
5172 let mut done = 0usize;
52- for batch in stale.chunks(BATCH) {
53- let texts: Vec<String> = batch.iter().map(|t| t.text.clone()).collect();
54- let _permit = llm_util::acquire_embed(state, &settings).await;
55- let vectors = client.embed(&texts).await?;
56- // 数量对不上就整批放弃:按位置配对,错位会把 person 的向量写到
57- // organization 上,而这种错一旦落库就再也看不出来了
58- if vectors.len() != batch.len() {
59- anyhow::bail!("嵌入返回 {} 条,送去的是 {} 条", vectors.len(), batch.len());
73+ let mut failed = 0usize;
74+ // **全部用拥有的数据**:这些 future 要跨 await 被并发驱动,借用过不了 Send 边界
75+ let client = std::sync::Arc::new(client);
76+ let model = std::sync::Arc::new(model);
77+ let settings = std::sync::Arc::new(settings);
78+ let batches: Vec<Vec<TypeToEmbed>> = stale.chunks(BATCH).map(<[_]>::to_vec).collect();
79+ let mut jobs = stream::iter(batches.into_iter().map(|batch| {
80+ let (client, model, settings) = (client.clone(), model.clone(), settings.clone());
81+ async move {
82+ let texts: Vec<String> = batch.iter().map(|t| t.text.clone()).collect();
83+ let _permit = llm_util::acquire_embed(state, &settings).await;
84+ let vectors = client.embed(&texts).await?;
85+ // 数量对不上就整批放弃:按位置配对,错位会把 person 的向量写到
86+ // organization 上,而这种错一旦落库就再也看不出来了
87+ if vectors.len() != batch.len() {
88+ anyhow::bail!("嵌入返回 {} 条,送去的是 {} 条", vectors.len(), batch.len());
89+ }
90+ let n = batch.len();
91+ let items: Vec<(TypeToEmbed, Vec<f32>)> = batch.into_iter().zip(vectors).collect();
92+ utopia_store::ontology::set_type_embeddings(&state.pool, &model, &items).await?;
93+ Ok::<usize, anyhow::Error>(n)
94+ }
95+ }))
96+ .buffer_unordered(EMBED_JOBS);
97+ // **一批失败不拖垮其余**:这是补齐任务,缺的下一轮自愈(判据是"当时嵌的
98+ // 原文对不对得上",不是时间戳)。整个 bail 掉等于把已经嵌好的也白跑一遍
99+ while let Some(r) = jobs.next().await {
100+ match r {
101+ Ok(n) => done += n,
102+ Err(e) => {
103+ failed += 1;
104+ tracing::warn!(%kb_id, error = %e, "一批本体向量没嵌上,留给下一轮");
105+ }
60106 }
61- let items: Vec<(TypeToEmbed, Vec<f32>)> = batch.iter().cloned().zip(vectors).collect();
62- utopia_store::ontology::set_type_embeddings(&state.pool, model, &items).await?;
63- done += batch.len();
64107 }
65- tracing::info!(%kb_id, count = done, "本体向量已补齐");
108+ // **失败数要出现在这一行。** 从前它只报补齐了多少,于是 24 批全挂的那次
109+ // 日志照样写着"已补齐",看日志的人以为没事
110+ if failed > 0 {
111+ tracing::warn!(%kb_id, count = done, failed, "本体向量补了一部分,其余留给下一轮");
112+ } else {
113+ tracing::info!(%kb_id, count = done, "本体向量已补齐");
114+ }
66115 Ok(done)
67116 }
68117
@@ -101,7 +150,12 @@
101150 for v in &vectors {
102151 out.push(match target {
103152 Target::Class => {
104- utopia_store::ontology::nearest_entity_types(&state.pool, kb_id, v, limit).await?
153+ utopia_store::ontology::nearest_entity_types(&state.pool, kb_id, v, limit, false)
154+ .await?
155+ }
156+ Target::ClassLabel => {
157+ utopia_store::ontology::nearest_entity_types(&state.pool, kb_id, v, limit, true)
158+ .await?
105159 }
106160 Target::Predicate(kind) => {
107161 utopia_store::ontology::nearest_relation_types(&state.pool, kb_id, v, limit, kind)
@@ -119,7 +173,12 @@
119173 /// 拿一个词表外的类名去关系里检索,回来的一定是勉强相关的关系。
120174 #[derive(Debug, Clone, Copy)]
121175 pub enum Target {
176+ /// 整段索引(label + 描述)。长画像走这一路
122177 Class,
178+ /// **只有 label 的索引**(0050)。短说法(`district. place`)走这一路。
179+ /// 短说法比整段索引会被同义反复的类接管——`Map` 那一行的描述就是
180+ /// "A map.",赢在长度不在语义
181+ ClassLabel,
123182 /// `Some("attribute")` 只找属性、`Some("relation")` 只找关系、`None` 都找。
124183 /// 字面值宾语的事实要的是属性,实体宾语的要的是关系
125184 Predicate(Option<&'static str>),
modified crates/utopia-server/src/type_resolution.rs +45 −26
@@ -39,8 +39,14 @@
3939
4040 /// 一轮看多少个实体。够一次人工过目,也够看出检索准不准。
4141 const BATCH: i64 = 60;
42-/// 每个实体检索几个候选。给裁决看的,不是让它在一堆勉强相关里硬挑一个。
43-const CANDIDATES: i64 = 8;
42+/// 每个实体检索几个候选。
43+///
44+/// **检索的活是端候选,说不是裁决的活。** 所以宁可多端两个——裁决看得到描述、
45+/// 看得到现类,能说出"这些都不是";而检索漏掉的,裁决再好也够不着。0001 P3a
46+/// 实测的失败正是全在检索一侧(`administrative_area`、`periodical` 从没被端上来)。
47+///
48+/// 从 8 加到 10:两路交替各占五席。代价是提示词里多两行类定义,而漏检没有退路。
49+const CANDIDATES: i64 = 10;
4450 /// 看几个已定类的近邻。少了凑不出票数,多了尾巴上全是噪音。
4551 const NEIGHBOURS: i64 = 10;
4652
@@ -123,28 +129,42 @@
123129 // 两次结果取并集——多一次嵌入,换掉一整类漏检。
124130 let profiles: Vec<String> = subjects.iter().map(profile_of).collect();
125131 let names: Vec<Option<String>> = subjects.iter().map(name_query_of).collect();
126- let mut queries: Vec<String> = Vec::with_capacity(subjects.len() * 2);
127- // 每个实体在 queries 里占的下标:(画像, 名字)
132+ // **两路各查各的索引**(0050)。从前两路共用整段索引,于是短说法那一路
133+ // 被同义反复的类接管:`district. place` 回来的是 Map / Park / Country /
134+ // Museum,四个赢家的嵌入原文全是 `X\nAn X.` 一行话,而带一百字定义的
135+ // AdministrativeArea 排不进前八。短对短、长对长,这才是可比的
136+ let name_queries: Vec<String> = names.iter().flatten().cloned().collect();
137+ let (profile_hits, name_hits) = tokio::join!(
138+ ontology_index::nearest_for_each(
139+ state,
140+ kb_id,
141+ &profiles,
142+ // 多取一些再按祖先过滤:过滤在检索之后,所以要留出被滤掉的余量
143+ CANDIDATES * 4,
144+ ontology_index::Target::Class,
145+ ),
146+ ontology_index::nearest_for_each(
147+ state,
148+ kb_id,
149+ &name_queries,
150+ CANDIDATES * 4,
151+ ontology_index::Target::ClassLabel,
152+ )
153+ );
154+ let profile_hits = profile_hits.unwrap_or_default();
155+ let name_hits = name_hits.unwrap_or_default();
156+ // 每个实体在两份结果里各占的下标:(画像, 名字)。名字那一路只有给得出
157+ // 说法的实体才发了查询,所以下标要单独数
128158 let mut slots: Vec<(usize, Option<usize>)> = Vec::with_capacity(subjects.len());
129- for (p, n) in profiles.iter().zip(&names) {
130- let pi = queries.len();
131- queries.push(p.clone());
132- let ni = n.as_ref().map(|q| {
133- queries.push(q.clone());
134- queries.len() - 1
159+ let mut ni = 0usize;
160+ for (pi, n) in names.iter().enumerate() {
161+ let slot = n.as_ref().map(|_| {
162+ let k = ni;
163+ ni += 1;
164+ k
135165 });
136- slots.push((pi, ni));
166+ slots.push((pi, slot));
137167 }
138- let hits = ontology_index::nearest_for_each(
139- state,
140- kb_id,
141- &queries,
142- // 多取一些再按祖先过滤:过滤在检索之后,所以要留出被滤掉的余量
143- CANDIDATES * 4,
144- ontology_index::Target::Class,
145- )
146- .await
147- .unwrap_or_default();
148168
149169 let mut out = Vec::with_capacity(subjects.len());
150170 for (i, s) in subjects.iter().enumerate() {
@@ -176,11 +196,10 @@
176196 //
177197 // 交替之后两路各占一半席位,谁的距离数值大小不再影响谁被看见。
178198 let (pi, ni) = slots[i];
179- let lists: Vec<Vec<_>> = [Some(pi), ni]
180- .into_iter()
181- .flatten()
182- .map(|idx| hits.get(idx).cloned().unwrap_or_default())
183- .collect();
199+ let mut lists: Vec<Vec<_>> = vec![profile_hits.get(pi).cloned().unwrap_or_default()];
200+ if let Some(k) = ni {
201+ lists.push(name_hits.get(k).cloned().unwrap_or_default());
202+ }
184203 let mut seen_ids: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
185204 let mut ranked: Vec<utopia_core::models::TypeCandidate> = Vec::new();
186205 let longest = lists.iter().map(Vec::len).max().unwrap_or(0);
modified crates/utopia-store/src/ontology.rs +57 −7
@@ -826,6 +826,17 @@
826826 pub id: Uuid,
827827 pub kind: TypeKind,
828828 pub text: String,
829+ /// 写进哪一组列。类有两份向量:整段(label + 描述)与只有 label 的那份,
830+ /// 分别服务长画像与短说法两种查询(见迁移 0050)
831+ pub field: EmbedField,
832+}
833+
834+/// 同一行的两份向量。**短查询比 Label,长画像比 Full**——查询分了两种形状,
835+/// 文档也得分两种,否则短查询会被同义反复的类接管(`Map\nA map.` 那一类)。
836+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
837+pub enum EmbedField {
838+ Full,
839+ Label,
829840 }
830841
831842 /// 本体行属于哪张表。类进 `entity_types`,关系与属性同住 `relation_types`。
@@ -884,6 +895,26 @@
884895 id,
885896 kind: TypeKind::Entity,
886897 text: embed_text(&label, &desc),
898+ field: EmbedField::Full,
899+ }));
900+ // 只嵌 label 的那一份(0050)。短查询走这个索引——查询分了两种形状,
901+ // 文档也得分两种,否则短查询被同义反复的类接管
902+ let labels: Vec<(Uuid, String)> = sqlx::query_as(
903+ "SELECT id, label FROM entity_types
904+ WHERE kb_id = $1
905+ AND (label_embedding IS NULL
906+ OR label_embedded_model IS DISTINCT FROM $2
907+ OR label_embedded_text IS DISTINCT FROM btrim(label))",
908+ )
909+ .bind(kb_id)
910+ .bind(model)
911+ .fetch_all(pool)
912+ .await?;
913+ out.extend(labels.into_iter().map(|(id, label)| TypeToEmbed {
914+ id,
915+ kind: TypeKind::Entity,
916+ text: label.trim().to_string(),
917+ field: EmbedField::Label,
887918 }));
888919 if only == Some(TypeKind::Entity) {
889920 return Ok(out);
@@ -915,6 +946,8 @@
915946 id,
916947 kind: TypeKind::Relation,
917948 text: embed_text(&label, &desc),
949+ // 关系没有短查询那一路,只有整段这一份
950+ field: EmbedField::Full,
918951 }));
919952 Ok(out)
920953 }
@@ -932,8 +965,17 @@
932965 TypeKind::Entity => "entity_types",
933966 TypeKind::Relation => "relation_types",
934967 };
968+ // 两份向量各写各的列(0050)。列名前缀不同,其余一模一样
969+ let (vec_col, text_col, model_col) = match item.field {
970+ EmbedField::Full => ("embedding", "embedded_text", "embedded_model"),
971+ EmbedField::Label => (
972+ "label_embedding",
973+ "label_embedded_text",
974+ "label_embedded_model",
975+ ),
976+ };
935977 sqlx::query(&format!(
936- "UPDATE {table} SET embedding = $2, embedded_text = $3, embedded_model = $4
978+ "UPDATE {table} SET {vec_col} = $2, {text_col} = $3, {model_col} = $4
937979 WHERE id = $1"
938980 ))
939981 .bind(item.id)
@@ -967,17 +1009,25 @@
9671009 kb_id: Uuid,
9681010 embedding: &[f32],
9691011 limit: i64,
1012+ // true = 比只有 label 的那份向量(0050)。短说法走这一路:**短对短**,
1013+ // 否则 `district. place` 会被 `Map\nA map.` 这类同义反复的一行话赢过去
1014+ by_label: bool,
9701015 ) -> AppResult<Vec<TypeCandidate>> {
971- let rows: Vec<(Uuid, String, String, String, f64)> = sqlx::query_as(
972- "SELECT id, key, label, coalesce(description, ''), (embedding <=> $2)::float8
1016+ let col = if by_label {
1017+ "label_embedding"
1018+ } else {
1019+ "embedding"
1020+ };
1021+ let rows: Vec<(Uuid, String, String, String, f64)> = sqlx::query_as(&format!(
1022+ "SELECT id, key, label, coalesce(description, ''), ({col} <=> $2)::float8
9731023 FROM entity_types t
974- WHERE t.kb_id = $1 AND t.embedding IS NOT NULL
1024+ WHERE t.kb_id = $1 AND t.{col} IS NOT NULL
9751025 AND (coalesce(btrim(t.description), '') <> ''
9761026 OR EXISTS (SELECT 1 FROM entity_type_parents p
9771027 WHERE p.child_id = t.id OR p.parent_id = t.id))
978- ORDER BY embedding <=> $2
979- LIMIT $3",
980- )
1028+ ORDER BY {col} <=> $2
1029+ LIMIT $3"
1030+ ))
9811031 .bind(kb_id)
9821032 .bind(Vector::from(embedding.to_vec()))
9831033 .bind(limit)
added migrations/0050_label_embedding.sql +30 −0
@@ -0,0 +1,30 @@
1+-- 类的**第二个**向量:只嵌 label,不带描述。
2+--
3+-- 类型消解对每个实体发两种查询(见 `type_resolution.rs`):一种是模型自己给的
4+-- 说法(`district. place`,短),一种是整段画像(长)。两种此前比的是同一批
5+-- `label + description` 向量——**查询分了两种形状,文档只有一种**。
6+--
7+-- 后果是短查询被同义反复的类接管。实测「杭州拱墅区」(specific_type = district)
8+-- 的短查询回来的是:
9+--
10+-- Map(0.308) / Park(0.345) / Country(0.347) / Museum(0.356)
11+--
12+-- 四个赢家的嵌入原文分别是 `Map\nA map.`、`Park\nA park.`、`Country\nA country.`、
13+-- `Museum\nA museum.`——全是一行同义反复。而正确答案 AdministrativeArea 的原文是
14+-- `AdministrativeArea\nA geographical region, typically under the jurisdiction of a
15+-- particular government.`,一百字,排不进前八。
16+--
17+-- 不是语义更近,是**长度对上了**。整体测得:被检索出来的类,嵌入原文长度中位数
18+-- 44,而全部 965 个类的中位数是 89——检索系统性地偏好短文本。
19+--
20+-- 「短的那一侧距离系统性地更小」这条规律,本仓库已经栽过四次(跨实体不可比、
21+-- 两路之间不可比、同一路两个查询之间不可比、空描述的悬空类占便宜)。前四次修的
22+-- 都是查询一侧,这一次是文档一侧:**两种查询就该有两份文档**,短对短、长对长。
23+ALTER TABLE entity_types ADD COLUMN label_embedding vector;
24+
25+-- 与 `embedded_text` / `embedded_model` 同一套自愈判据(见 0038):比对「当时嵌的
26+-- 原文与模型名跟现在对不对得上」,而不是看时间戳。改了 label、换了嵌入模型都会
27+-- 当场对不上,于是自动重嵌——不必在每个改 label 的写入点挂钩子,漏挂一个就悄悄烂掉。
28+ALTER TABLE entity_types
29+ ADD COLUMN label_embedded_text text,
30+ ADD COLUMN label_embedded_model text;
modified scripts/bench/run.mjs +5 −1
@@ -178,8 +178,12 @@
178178 // 分钟,分不清是在跑还是卡死了。
179179 await until(
180180 async () => {
181+ // **两份向量都要等**(0050)。只等 `embedding` 的话,label 那份还没补完
182+ // 就开跑,短说法那一路一条都检索不到——测出来的是个半成品,而且看不出来
181183 const left = num(
182- "SELECT count(*) FILTER (WHERE embedding IS NULL) FROM entity_types WHERE kb_id='" +
184+ "SELECT count(*) FILTER (WHERE embedding IS NULL)" +
185+ " + count(*) FILTER (WHERE label_embedding IS NULL)" +
186+ " FROM entity_types WHERE kb_id='" +
183187 kb +
184188 "'",
185189 );