Elffuss BraidHub

kikocis/utopia public

dev · 10.1 KiBRawPermalink
1//! 关系的签名(domain / range)在**三条写路径**上都得算数(#190 / #196)。
2//!
3//! 抽取写入时按 #138 掰正方向或留空谓词,但写谓词的路不止一条:**采纳**把谓词挂回
4//! 旧事实,**合并**换掉主语的类型。守卫只装在抽取上,另外两条各自绕过去——实测采纳
5//! 把违反率从 0 抬到 12.3%。这里守三件事:
6//!
7//! 1. 采纳走同一道判断:主语不合宾语合 → 对调着挂;两边都不合 → 不挂,事实留在空谓词上。
8//! 2. 合并之后,被换了主语的事实若违反签名 → `axiom_violations` 里多一条 `signature`。
9//! 3. 一致性检查(R0)也能量出签名违规,事实撤了它就被清掉。
10//!
11//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
12
13use sqlx::PgPool;
14use utopia_store::graph::Adopted;
15use uuid::Uuid;
16
17struct Fixture {
18 org: Uuid,
19 kb: Uuid,
20 company: Uuid,
21 person: Uuid,
22 /// schema.org 的 `employee (organization → person)`
23 employee: Uuid,
24 acme: Uuid,
25 alice: Uuid,
26 bob: Uuid,
27 doc: Uuid,
28 chunk: Uuid,
29}
30
31async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
32 let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
33 let (company, person, employee) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
34 let (acme, alice, bob) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
35 let (src, doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
36
37 sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'signature-test')")
38 .bind(org)
39 .execute(pool)
40 .await?;
41 sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'signature-test')")
42 .bind(ws)
43 .bind(org)
44 .execute(pool)
45 .await?;
46 sqlx::query(
47 "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'signature-test')",
48 )
49 .bind(kb)
50 .bind(ws)
51 .execute(pool)
52 .await?;
53 for (id, key, label) in [
54 (company, "company", "Company"),
55 (person, "person", "Person"),
56 ] {
57 sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
58 .bind(id)
59 .bind(kb)
60 .bind(key)
61 .bind(label)
62 .execute(pool)
63 .await?;
64 }
65 sqlx::query(
66 "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'employee', 'employee')",
67 )
68 .bind(employee)
69 .bind(kb)
70 .execute(pool)
71 .await?;
72 sqlx::query(
73 "INSERT INTO relation_type_domains (relation_type_id, entity_type_id) VALUES ($1, $2)",
74 )
75 .bind(employee)
76 .bind(company)
77 .execute(pool)
78 .await?;
79 sqlx::query(
80 "INSERT INTO relation_type_ranges (relation_type_id, entity_type_id) VALUES ($1, $2)",
81 )
82 .bind(employee)
83 .bind(person)
84 .execute(pool)
85 .await?;
86 for (id, ty, name) in [
87 (acme, company, "Acme"),
88 (alice, person, "Alice"),
89 (bob, person, "Bob"),
90 ] {
91 sqlx::query(
92 "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
93 )
94 .bind(id)
95 .bind(kb)
96 .bind(ty)
97 .bind(name)
98 .execute(pool)
99 .await?;
100 }
101 sqlx::query("INSERT INTO sources (id, kb_id, name) VALUES ($1, $2, 'signature-test')")
102 .bind(src)
103 .bind(kb)
104 .execute(pool)
105 .await?;
106 sqlx::query(
107 "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status)
108 VALUES ($1, $2, $3, 'note.md', 'signature', 'ready')",
109 )
110 .bind(doc)
111 .bind(kb)
112 .bind(src)
113 .execute(pool)
114 .await?;
115 sqlx::query(
116 "INSERT INTO chunks (id, kb_id, document_id, seq, text)
117 VALUES ($1, $2, $3, 0, 'Alice is an employee of Acme. Bob is an employee of Alice.')",
118 )
119 .bind(chunk)
120 .bind(kb)
121 .bind(doc)
122 .execute(pool)
123 .await?;
124 Ok(Fixture {
125 org,
126 kb,
127 company,
128 person,
129 employee,
130 acme,
131 alice,
132 bob,
133 doc,
134 chunk,
135 })
136}
137
138/// 一条没有谓词、证据里留着原文说法 `employee` 的事实——采纳要改写的正是这种
139async fn surfaced_fact(
140 pool: &PgPool,
141 f: &Fixture,
142 subject: Uuid,
143 object: Uuid,
144) -> anyhow::Result<Uuid> {
145 let id = Uuid::now_v7();
146 sqlx::query(
147 "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
148 VALUES ($1, $2, $3, NULL, $4, 0.9)",
149 )
150 .bind(id)
151 .bind(f.kb)
152 .bind(subject)
153 .bind(object)
154 .execute(pool)
155 .await?;
156 sqlx::query(
157 "INSERT INTO fact_evidence (fact_id, chunk_id, quote, proposed_predicate, document_id, doc_version)
158 VALUES ($1, $2, 'employee of', 'employee', $3, 1)",
159 )
160 .bind(id)
161 .bind(f.chunk)
162 .bind(f.doc)
163 .execute(pool)
164 .await?;
165 Ok(id)
166}
167
168async fn live_employee_edges(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
169 Ok(sqlx::query_as(
170 "SELECT subject_id, object_id FROM facts
171 WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL
172 ORDER BY recorded_at",
173 )
174 .bind(f.kb)
175 .bind(f.employee)
176 .fetch_all(pool)
177 .await?)
178}
179
180async fn open_signature_breaks(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<Uuid>> {
181 Ok(sqlx::query_as::<_, (Uuid,)>(
182 "SELECT left_fact FROM axiom_violations
183 WHERE kb_id = $1 AND kind = 'signature' AND status = 'open'",
184 )
185 .bind(kb)
186 .fetch_all(pool)
187 .await?
188 .into_iter()
189 .map(|(id,)| id)
190 .collect())
191}
192
193#[tokio::test]
194async fn adoption_and_merge_respect_the_signature() -> anyhow::Result<()> {
195 let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
196 eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
197 return Ok(());
198 };
199 let pool = PgPool::connect(&url).await?;
200 let f = seed(&pool).await?;
201
202 let run = async {
203 // 模型写的是 "Alice is an employee of Acme" —— 主语 person 违反 domain、宾语 company 符合
204 let reversed = surfaced_fact(&pool, &f, f.alice, f.acme).await?;
205 // "Bob is an employee of Alice" —— 两边都是 person,这个关系压根不适用
206 let hopeless = surfaced_fact(&pool, &f, f.bob, f.alice).await?;
207
208 // 1. 采纳:一条对调着挂上,一条不挂
209 let Adopted {
210 moved, left_off, ..
211 } = utopia_store::graph::adopt_proposed_predicates(
212 &pool,
213 f.kb,
214 f.employee,
215 &["employee".to_string()],
216 false,
217 )
218 .await?;
219 assert_eq!(moved, 1, "the reversed one is adoptable once swapped");
220 assert_eq!(left_off, 1, "the hopeless one must be left without a predicate");
221 assert_eq!(
222 live_employee_edges(&pool, &f).await?,
223 vec![(f.acme, f.alice)],
224 "adoption must write the edge in the ontology's direction: Acme employee Alice"
225 );
226 let (still_bare,): (bool,) =
227 sqlx::query_as("SELECT predicate_id IS NULL AND invalidated_at IS NULL FROM facts WHERE id = $1")
228 .bind(hopeless)
229 .fetch_one(&pool)
230 .await?;
231 assert!(still_bare, "a fact that fits neither way stays live and predicate-less");
232 let (old_gone,): (bool,) =
233 sqlx::query_as("SELECT invalidated_at IS NOT NULL FROM facts WHERE id = $1")
234 .bind(reversed)
235 .fetch_one(&pool)
236 .await?;
237 assert!(old_gone, "the reversed row was superseded, not left beside the corrected one");
238 assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
239
240 // 2. 合并:把 Acme 并进 Bob(person),Acme employee Alice 的主语变成 person
241 utopia_store::resolution::merge_entities(&pool, f.kb, f.acme, f.bob, None, "test")
242 .await?;
243 let edges = live_employee_edges(&pool, &f).await?;
244 assert_eq!(edges, vec![(f.bob, f.alice)], "the merge moved the subject onto Bob");
245 let (moved_fact,): (Uuid,) = sqlx::query_as(
246 "SELECT id FROM facts WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL",
247 )
248 .bind(f.kb)
249 .bind(f.employee)
250 .fetch_one(&pool)
251 .await?;
252 assert_eq!(
253 open_signature_breaks(&pool, f.kb).await?,
254 vec![moved_fact],
255 "a merge that breaks the signature must show up as an open violation"
256 );
257
258 // 3. 一致性检查量得出它,撤了事实就清掉
259 let report = utopia_store::reasoning::run(&pool, f.kb).await?;
260 assert_eq!(report.found, 1);
261 assert_eq!(report.inserted, 0, "already recorded by the merge; the check must not duplicate it");
262 sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
263 .bind(moved_fact)
264 .execute(&pool)
265 .await?;
266 let report = utopia_store::reasoning::run(&pool, f.kb).await?;
267 assert_eq!(report.found, 0);
268 assert_eq!(report.cleared, 1, "a retracted fact takes its violation with it");
269 assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
270
271 // 未分类的实体不算违反:类型是 NULL 的主语没有东西可比
272 let untyped = Uuid::now_v7();
273 sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Nobody')")
274 .bind(untyped)
275 .bind(f.kb)
276 .execute(&pool)
277 .await?;
278 sqlx::query(
279 "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
280 VALUES ($1, $2, $3, $4, $5, 0.9)",
281 )
282 .bind(Uuid::now_v7())
283 .bind(f.kb)
284 .bind(untyped)
285 .bind(f.employee)
286 .bind(f.alice)
287 .execute(&pool)
288 .await?;
289 assert!(
290 utopia_store::reasoning::signature_breaks(&pool, f.kb, None).await?.is_empty(),
291 "an untyped subject is unknown, not wrong"
292 );
293 let _ = (f.company, f.person);
294 anyhow::Ok(())
295 }
296 .await;
297
298 let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
299 .bind(f.org)
300 .execute(&pool)
301 .await;
302 run
303}