Elffuss BraidHub

kikocis/utopia public

One malformed fact should not discard the whole chunk (#127)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset840297f8134fdafa01bd4fa9c6e8c2887ae0e901c0eac819d7ef07b0425bb9e6
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 04:39 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 04:39 +08:00
Parentsb19da2756d4b

Browse the files at this changeset

5 files changed

modified crates/utopia-extract/src/lib.rs +173 −3
@@ -11,6 +11,15 @@
1111 pub entities: Vec<ExtractedEntity>,
1212 #[serde(default)]
1313 pub facts: Vec<ExtractedFact>,
14+ /// 逐项解析时被跳过的条目数。**必须报给调用方**——不报就是一次静默丢弃,
15+ /// 与 #108「部分抽取报告成完成」同一类错
16+ #[serde(skip)]
17+ pub skipped_entities: usize,
18+ #[serde(skip)]
19+ pub skipped_facts: usize,
20+ /// 模型的输出被截断,这里是修补后解析的
21+ #[serde(skip)]
22+ pub truncated: bool,
1423 }
1524
1625 #[derive(Debug, Deserialize)]
@@ -296,11 +305,116 @@
296305 }
297306 }
298307
308+/// 把 head 后面缺的括号补上。字符串字面量里的括号不算——`"a[b"` 不是一个开括号。
309+///
310+/// 返回 None = 结构本身就不对(比如括号已经多了),不是"没写完"。
311+fn close_brackets(head: &str) -> Option<String> {
312+ let mut stack: Vec<char> = Vec::new();
313+ let (mut in_str, mut esc) = (false, false);
314+ for c in head.chars() {
315+ if in_str {
316+ if esc {
317+ esc = false;
318+ } else if c == '\\' {
319+ esc = true;
320+ } else if c == '"' {
321+ in_str = false;
322+ }
323+ continue;
324+ }
325+ match c {
326+ '"' => in_str = true,
327+ '[' | '{' => stack.push(c),
328+ // 不写成两条带守卫的分支:那样 stack.pop() 的副作用藏在守卫里,
329+ // 碰巧是对的,但读的人不会预期守卫会改状态
330+ ']' | '}' => {
331+ let want = if c == ']' { '[' } else { '{' };
332+ if stack.pop() != Some(want) {
333+ return None;
334+ }
335+ }
336+ _ => {}
337+ }
338+ }
339+ if in_str {
340+ return None; // 断在字符串中间,这一截不可用
341+ }
342+ let mut out = String::from(head);
343+ for c in stack.iter().rev() {
344+ out.push(if *c == '[' { ']' } else { '}' });
345+ }
346+ Some(out)
347+}
348+
349+/// 输出被截断时,退到**最后一个完整对象**的结尾再把括号补齐。
350+///
351+/// 模型写到一半没了(撞上 max_tokens)时,前面那些对象是完整且正确的。
352+/// 整块作废等于把已经抽对的十几条事实一起扔掉——实测 246 次调用里 4 次是这种。
353+fn repair_truncated(json: &str) -> Option<String> {
354+ let mut cut = json.len();
355+ for _ in 0..64 {
356+ let idx = json[..cut].rfind('}')?;
357+ if let Some(closed) = close_brackets(&json[..=idx]) {
358+ if serde_json::from_str::<serde_json::Value>(&closed).is_ok() {
359+ return Some(closed);
360+ }
361+ }
362+ cut = idx;
363+ }
364+ None
365+}
366+
367+/// **一条坏记录不该毁掉一整块。**
368+///
369+/// 从前这里是 `serde_json::from_str::<Extraction>`——全有或全无。一个缺 `predicate`
370+/// 的对象、或者一次输出截断,整块的实体和事实一起作废,而一块里常有二十条好事实。
371+/// 实测 246 次调用里 5 次这样丢掉(2%),并且会让整个 `extract_document` 任务失败、
372+/// 走重试,三次之后文档标记失败。
373+///
374+/// 现在:先解成 `Value`(截断就先补齐括号),再逐项 `from_value`,好的收下、
375+/// 坏的计数。**计数必须往外传**——静默跳过就是另一种"报告成完成"。
299376 pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> {
300377 let json_str = json_block(raw)?;
301- let extraction: Extraction = serde_json::from_str(&json_str)
302- .map_err(|e| anyhow::anyhow!("Failed to parse extraction JSON: {e}"))?;
303- Ok(extraction)
378+ let (value, truncated) = match serde_json::from_str::<serde_json::Value>(&json_str) {
379+ Ok(v) => (v, false),
380+ Err(e) => match repair_truncated(&json_str) {
381+ Some(fixed) => (
382+ serde_json::from_str::<serde_json::Value>(&fixed)
383+ .map_err(|e| anyhow::anyhow!("Failed to parse extraction JSON: {e}"))?,
384+ true,
385+ ),
386+ // 补不回来才是真解析失败:连一个完整对象都没有
387+ None => anyhow::bail!("Failed to parse extraction JSON: {e}"),
388+ },
389+ };
390+
391+ fn take<T: serde::de::DeserializeOwned>(
392+ value: &serde_json::Value,
393+ key: &str,
394+ ) -> (Vec<T>, usize) {
395+ let Some(arr) = value.get(key).and_then(|v| v.as_array()) else {
396+ return (Vec::new(), 0);
397+ };
398+ let mut out = Vec::with_capacity(arr.len());
399+ let mut skipped = 0;
400+ for item in arr {
401+ match serde_json::from_value::<T>(item.clone()) {
402+ Ok(v) => out.push(v),
403+ Err(_) => skipped += 1,
404+ }
405+ }
406+ (out, skipped)
407+ }
408+
409+ let (entities, skipped_entities) = take::<ExtractedEntity>(&value, "entities");
410+ let (facts, skipped_facts) = take::<ExtractedFact>(&value, "facts");
411+ Ok(Extraction {
412+ entities,
413+ facts,
414+ skipped_entities,
415+ skipped_facts,
416+ truncated,
417+ })
304418 }
305419
306420 // ---------------------------------------------------------------------------
@@ -629,6 +743,62 @@
629743 assert_eq!(normalize_attr_value("text", &json!([1])), None);
630744 }
631745
746+ /// **一条坏记录不该毁掉一整块。**
747+ ///
748+ /// 形态取自真实日志:`missing field \`predicate\``。模型偶尔会漏写这个字段
749+ /// (`related_to` 退场后它没有万能选项可挑),从前 serde 会让整块作废,
750+ /// 而这一块里另外两条事实是好的。
751+ #[test]
752+ fn one_malformed_fact_does_not_take_the_whole_chunk() {
753+ let raw = r#"{
754+ "entities": [{"name": "OpenAI", "type": "organization"}],
755+ "facts": [
756+ {"subject": "OpenAI", "predicate": "produces", "object": "GPT-4"},
757+ {"subject": "OpenAI", "object": "ChatGPT"},
758+ {"subject": "Sam Altman", "predicate": "leads", "object": "OpenAI"}
759+ ]
760+ }"#;
761+ let x = parse_response(raw).unwrap();
762+ assert_eq!(x.facts.len(), 2, "好的两条该留下");
763+ assert_eq!(x.skipped_facts, 1, "跳过的那条要报出来,不能静默");
764+ assert_eq!(x.entities.len(), 1);
765+ assert!(!x.truncated);
766+ }
767+
768+ /// **输出被截断时,已经完整的那些要救回来。**
769+ ///
770+ /// 撞上 max_tokens 时模型写到一半就没了(真实日志:`EOF while parsing a list`)。
771+ /// 前面的对象是完整且正确的,整块作废等于把抽对的十几条一起扔掉。
772+ #[test]
773+ fn a_cut_off_reply_keeps_what_was_complete() {
774+ let raw = r#"{
775+ "entities": [{"name": "Anthropic", "type": "organization"}],
776+ "facts": [
777+ {"subject": "Anthropic", "predicate": "produces", "object": "Claude"},
778+ {"subject": "Dario Amodei", "predicate": "leads", "object": "Anthropic"},
779+ {"subject": "Anthropic", "predicate": "loca"#;
780+ let x = parse_response(raw).unwrap();
781+ assert!(x.truncated, "截断要标出来");
782+ assert_eq!(x.facts.len(), 2, "断点之前的两条是完整的");
783+ assert_eq!(x.entities.len(), 1);
784+ }
785+
786+ /// 括号出现在字符串里不算结构——`"a[b"` 不是一个开括号。
787+ #[test]
788+ fn brackets_inside_strings_are_not_structure() {
789+ let raw =
790+ r#"{"entities": [], "facts": [{"subject": "a[b{c", "predicate": "p", "object": "o"}]}"#;
791+ let x = parse_response(raw).unwrap();
792+ assert_eq!(x.facts.len(), 1);
793+ assert!(!x.truncated, "结构完整,不该判成截断");
794+ }
795+
796+ /// 连一个完整对象都没有时,仍然要报失败——**容错不是把空结果说成成功**。
797+ #[test]
798+ fn a_reply_with_nothing_complete_still_fails() {
799+ assert!(parse_response(r#"{"facts": [{"subject": "a"#).is_err());
800+ }
801+
632802 #[test]
633803 fn parse_response_with_fence() {
634804 let raw = "好的,结果如下:\n```json\n{\"entities\":[{\"name\":\"张三\",\"type\":\"person\"}],\"facts\":[]}\n```";
modified crates/utopia-server/src/extraction.rs +35 −0
@@ -337,6 +337,41 @@
337337 continue;
338338 }
339339 };
340+ // **跳过了什么必须说出来。** 逐项解析救回了整块,但被跳过的那几条
341+ // 如果不落信号,就成了另一种「部分抽取报告成完成」(#108 修过一次)
342+ if extraction.truncated {
343+ drop_signal(
344+ state,
345+ doc.kb_id,
346+ document_id,
347+ utopia_store::extraction_drops::reason::TRUNCATED_REPLY,
348+ &format!("分块 #{} 的输出被截断", chunk.seq),
349+ None,
350+ )
351+ .await;
352+ }
353+ let skipped = extraction.skipped_entities + extraction.skipped_facts;
354+ if skipped > 0 {
355+ tracing::warn!(
356+ %document_id,
357+ seq = chunk.seq,
358+ entities = extraction.skipped_entities,
359+ facts = extraction.skipped_facts,
360+ "跳过了结构不合的条目"
361+ );
362+ drop_signal(
363+ state,
364+ doc.kb_id,
365+ document_id,
366+ utopia_store::extraction_drops::reason::MALFORMED_ITEM,
367+ &format!(
368+ "分块 #{} 跳过 {} 个实体 / {} 条事实",
369+ chunk.seq, extraction.skipped_entities, extraction.skipped_facts
370+ ),
371+ None,
372+ )
373+ .await;
374+ }
340375
341376 // 实体消解:名称 → 实体 id(本分块的事实按原文名字连线)
342377 let mut entity_ids: HashMap<String, Uuid> = HashMap::new();
modified crates/utopia-store/src/extraction_drops.rs +4 −2
@@ -26,8 +26,10 @@
2626 pub const LOW_CONFIDENCE: &str = "low_confidence";
2727 /// 关系事实缺宾语
2828 pub const OBJECT_MISSING: &str = "object_missing";
29- /// 词表外谓词本该降级,但本体里连兜底关系都没有 → 整条消失
30- pub const FALLBACK_RELATION_MISSING: &str = "fallback_relation_missing";
29+ /// 模型给的这一条不合结构(缺 predicate 之类)→ 只跳这一条,不牵连整块
30+ pub const MALFORMED_ITEM: &str = "malformed_item";
31+ /// 模型输出被截断(撞上 max_tokens)→ 已完整的那些留下,尾巴丢掉
32+ pub const TRUNCATED_REPLY: &str = "truncated_reply";
3133 }
3234
3335 pub async fn record(
modified web/src/i18n/en.ts +2 −1
@@ -324,7 +324,8 @@
324324 attr_datatype: "Value did not match the datatype",
325325 low_confidence: "Below the confidence threshold",
326326 object_missing: "Relation had no object",
327- fallback_relation_missing: "No fallback relation in the ontology",
327+ malformed_item: "The model's item did not fit the schema",
328+ truncated_reply: "The model's reply was cut off",
328329 } as Record<string, string>,
329330 // 来源级重抽:不危险,只是费时费钱——轻确认,文案直说成本与保留项
330331 reExtractSource: "Re-extract",
modified web/src/i18n/zh.ts +2 −1
@@ -299,7 +299,8 @@
299299 attr_datatype: "取值与数据类型不符",
300300 low_confidence: "低于置信度阈值",
301301 object_missing: "关系缺少宾语",
302- fallback_relation_missing: "本体里没有兜底关系",
302+ malformed_item: "模型给的这一条结构不合",
303+ truncated_reply: "模型的输出被截断",
303304 },
304305 reExtractSource: "重新抽取",
305306 reExtractTitle: "重新抽取这个来源?",