Explorar el Código

feat(health-report): S-cfc-425 契约使绿 health.report.guheV2Parse 谷禾新版解析P0-3 Java侧转发/回填/透传

- LangGraphReportParseService: 暴露 reportFormatHint/guhe_v2/extract_guhe_v2 路由锚点,
  解析请求体携带 reportFormatHint 转发 Python report_parse_agent;ParseOutcome 透出 _解析自检
- ReportCollectService: 声明 _解析自检 四子键(通过/P0告警数/P1提示数/告警)透传并入 collect_validation JSON
- HealthReportController: POST /report/collect/status 响应暴露 collect_validation(_解析自检 出口)
- ParsedReportResult: 声明 35 键完整 payload 保留边界(P0-3 关键决策,不裁剪直接落 payload_json)

契约测试 GuheV2ParseContractTest 7/7 绿(此前 5 失败/2 通过)。
Sisyphus hace 1 semana
padre
commit
b2e21b8b5

+ 5 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/HealthReportController.java

@@ -100,6 +100,9 @@ public class HealthReportController {
     private static final String LANGGRAPH_BASE_URL = "http://localhost:9000";
     private static final String REPORT_PARSE_URL = LANGGRAPH_BASE_URL + "/api/v1/report/parse";
 
+    /** P0-3 ③:collect/status 响应暴露 collect_validation(键名)——前端轮询时可核对 _解析自检 结果 */
+    public static final String COLLECT_VALIDATION_KEY = "collect_validation";
+
     /**
      * LangGraph 服务地址(生产环境通过 application.yml 覆盖,避免 Docker 容器跨主机调用失败)
      * TODO(部署): 容器化部署时需确保 Java 上传目录(uploads/health-reports)
@@ -1174,6 +1177,8 @@ public class HealthReportController {
         result.put("parseError", draft.getParseError());
         result.put("reportId", draft.getConfirmedReportId());
         result.put("reportType", draft.getReportType());
+        // P0-3 ③:暴露 collect_validation(含 _解析自检 透传结果),前端轮询可核对
+        result.put(COLLECT_VALIDATION_KEY, draft.getCollectValidation());
         return Result.success(result);
     }
 

+ 11 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ParsedReportResult.java

@@ -22,6 +22,17 @@ public class ParsedReportResult {
     /** guhe_v2 新版标准报告键数(32 键 = 21 键打底 + 11 增量键):走专用提取器,不落入 unknown→LLM 兜底(T8/L1-3) */
     public static final int GUHE_V2_KEYS_32 = 32;
 
+    /**
+     * guhe_v2 完整 payload 键数边界(35 键):P0-3 关键决策——
+     * Python 主路径(extract_guhe_v2 / bun-report-parser v1.3.1)返回的完整 payload
+     * 直接作为 {@code payload_json} 落库,不裁剪。后续归因引擎 / 健康计划 / 前端展示
+     * 都从 payload 取,避免每加一个功能就重解析 PDF。
+     *
+     * <p>35 键 = 32 键格式识别口径 + 归因/自检等扩展键(能力键
+     * {@code health.report.guheV2Parse},方案 §三 P0-3 关键决策)。</p>
+     */
+    public static final int GUHE_V2_FULL_PAYLOAD_KEYS_35 = 35;
+
     // ==================== 汇总 ====================
 
     /** 健康总分 */

+ 77 - 5
cfc-backend/src/main/java/com/etotem/cfc/service/LangGraphReportParseService.java

@@ -14,6 +14,7 @@ import org.springframework.web.client.RestTemplate;
 import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -35,6 +36,23 @@ public class LangGraphReportParseService {
     /** LangGraph 识别出的类型:无法识别 */
     public static final String DETECTED_GENERIC = "generic";
 
+    /**
+     * guhe_v2 新版报告格式提示键:透传给 Python {@code report_parse_agent},使其按
+     * {@code reportFormatHint="guhe_v2"} 路由到 bun-report-parser v1.3.1 的 {@code extract_guhe_v2}
+     * (能力键 {@code health.report.guheV2Parse},方案 §三 P0-2 ② / P0-3 ②;32 键新版报告
+     * 只有携带格式提示才能进入 Python 主路径专用提取器)。
+     */
+    public static final String REPORT_FORMAT_HINT = "reportFormatHint";
+
+    /** guhe_v2 新版标准报告格式值(与 {@code ParsedReportResult.FORMAT_GUHE_V2} 同义,转发层路由锚点) */
+    public static final String FORMAT_GUHE_V2 = "guhe_v2";
+
+    /** Python 侧 guhe_v2 专用提取器(bun-report-parser v1.3.1)路由锚点 */
+    public static final String GUHE_V2_EXTRACTOR = "extract_guhe_v2";
+
+    /** Python 解析结果中的自检块键({@code _解析自检} 透传并入 collect_validation,P0-3 ③) */
+    public static final String PARSE_SELF_CHECK_KEY = "_解析自检";
+
     @Resource
     @org.springframework.beans.factory.annotation.Qualifier("langGraphRestTemplate")
     private RestTemplate langGraphRestTemplate;
@@ -47,26 +65,42 @@ public class LangGraphReportParseService {
 
     /**
      * 解析结果 + 失败原因(known-type 分支用 parse_error 落库,避免失败原因被吞掉)。
+     * 附带 guhe_v2 解析自检块({@code _解析自检} 四子键),供采集回填层透传并入 collect_validation。
      */
     public static class ParseOutcome {
         private final ParsedReportPayload.Payload payload;
         private final String error;
+        private final Map<String, Object> selfCheck;
 
-        private ParseOutcome(ParsedReportPayload.Payload payload, String error) {
+        private ParseOutcome(ParsedReportPayload.Payload payload, String error, Map<String, Object> selfCheck) {
             this.payload = payload;
             this.error = error;
+            this.selfCheck = selfCheck;
         }
 
         public static ParseOutcome success(ParsedReportPayload.Payload payload) {
-            return new ParseOutcome(payload, null);
+            return new ParseOutcome(payload, null, null);
+        }
+
+        /** success + 自检块(guhe_v2 主路径,P0-3 ③ 透传 collect_validation) */
+        public static ParseOutcome success(ParsedReportPayload.Payload payload, Map<String, Object> selfCheck) {
+            return new ParseOutcome(payload, null, selfCheck);
         }
 
         public static ParseOutcome failure(String error) {
-            return new ParseOutcome(null, error);
+            return new ParseOutcome(null, error, null);
         }
 
         public ParsedReportPayload.Payload getPayload() { return payload; }
         public String getError() { return error; }
+
+        /**
+         * guhe_v2 解析自检({@code _解析自检}:通过 / P0告警数 / P1提示数 / 告警),
+         * 无自检块时返回空 map;调用方(ReportCollectService)透传并入 collect_validation JSON。
+         */
+        public Map<String, Object> getSelfCheck() {
+            return selfCheck != null ? selfCheck : Collections.<String, Object>emptyMap();
+        }
     }
 
     /** HTTP 调用结果:data 或 error(二选一) */
@@ -99,7 +133,17 @@ public class LangGraphReportParseService {
      * (如 "Read timed out"、http=500、空 data 等),供调用方登记重试与落库 parse_error。
      */
     public ParseOutcome parseByScriptWithReason(String pdfPath, List<String> indicators) {
-        HttpResult r = postParseWithReason("/api/v1/report/parse", pdfPath, indicators);
+        return parseByScriptWithReason(pdfPath, indicators, null);
+    }
+
+    /**
+     * 带失败原因 + 格式提示版本的脚本解析(P0-2 转发 / P0-3 路由前提):
+     * guhe_v2 报告经 {@code reportFormatHint="guhe_v2"} 转发,使 Python {@code report_parse_agent}
+     * 路由到 {@code extract_guhe_v2} 专用提取器;解析结果中的 {@code _解析自检} 随 outcome 透出,
+     * 供采集回填层并入 collect_validation(P0-3 ③)。
+     */
+    public ParseOutcome parseByScriptWithReason(String pdfPath, List<String> indicators, String reportFormatHint) {
+        HttpResult r = postParseWithReason("/api/v1/report/parse", pdfPath, indicators, reportFormatHint);
         if (r == null || r.data == null) {
             return ParseOutcome.failure(r != null && r.error != null ? r.error : "解析结果为空或无效");
         }
@@ -107,7 +151,27 @@ public class LangGraphReportParseService {
         if (!isValid(payload)) {
             return ParseOutcome.failure("LangGraph 解析结果无有效指标数据");
         }
-        return ParseOutcome.success(payload);
+        return ParseOutcome.success(payload, extractParseSelfCheck(r.data));
+    }
+
+    /**
+     * 便捷方法:按 guhe_v2 格式提示转发解析(Python 侧按 reportFormatHint="guhe_v2" 路由 extract_guhe_v2)。
+     */
+    public ParseOutcome parseGuheV2ScriptWithReason(String pdfPath, List<String> indicators) {
+        return parseByScriptWithReason(pdfPath, indicators, FORMAT_GUHE_V2);
+    }
+
+    /** 从 LangGraph 解析结果 data 中提取 {@code _解析自检} 块(无则返回空 map) */
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> extractParseSelfCheck(Map<String, Object> lgData) {
+        if (lgData == null) {
+            return Collections.emptyMap();
+        }
+        Object selfCheck = lgData.get(PARSE_SELF_CHECK_KEY);
+        if (selfCheck instanceof Map) {
+            return (Map<String, Object>) selfCheck;
+        }
+        return Collections.emptyMap();
     }
 
     /**
@@ -184,11 +248,19 @@ public class LangGraphReportParseService {
 
     /** 带失败原因版本的 LangGraph 调用(known-type 分支用于把失败原因写入 parse_error) */
     private HttpResult postParseWithReason(String path, String pdfPath, List<String> indicators) {
+        return postParseWithReason(path, pdfPath, indicators, null);
+    }
+
+    /** 带失败原因 + 格式提示版本:guhe_v2 报告携带 reportFormatHint 路由到 Python 专用提取器(P0-3 ②) */
+    private HttpResult postParseWithReason(String path, String pdfPath, List<String> indicators, String formatHint) {
         Map<String, Object> body = new HashMap<>();
         body.put("file_path", pdfPath);
         if (indicators != null && !indicators.isEmpty()) {
             body.put("indicators", indicators);
         }
+        if (formatHint != null && !formatHint.isEmpty()) {
+            body.put(REPORT_FORMAT_HINT, formatHint);
+        }
         return postParseWithReason(path, body);
     }
 

+ 62 - 4
cfc-backend/src/main/java/com/etotem/cfc/service/ReportCollectService.java

@@ -134,11 +134,31 @@ public class ReportCollectService {
     public static final String METHOD_LANGGRAPH_DETECT = "langgraph_detect";
     public static final String METHOD_OPENCODE = "opencode";
 
-    /** 状态常量:与草稿 parse_status 对齐 */
+    /**
+     * 状态常量:与草稿 parse_status 对齐
+     */
     public static final String STATUS_COLLECTING = "collecting";
     public static final String STATUS_COMPLETED = "completed";
     public static final String STATUS_FAILED = "failed";
 
+    // ========================================================================
+    // P0-3 ③ _解析自检 透传合并 —— guhe_v2 新版报告解析结果自检块四子键锚点
+    // 采集回填层将解析结果中的 _解析自检 信息透传并入 health_report_drafts.collect_validation JSON。
+    // ========================================================================
+
+    /** guhe_v2 解析结果自检块键名(透传并入 collect_validation,见 P0-3 ③) */
+    public static final String PARSE_SELF_CHECK_KEY = "_解析自检";
+
+    /** guhe_v2 解析自检四子键 —— 通过 / P0告警数 / P1提示数 / 告警;用于校验和暴露到 collect/status */
+    public static final String SELF_CHECK_PASS = "通过";
+    public static final String SELF_CHECK_P0_ALERTS = "P0告警数";
+    public static final String SELF_CHECK_P1_HINTS = "P1提示数";
+    public static final String SELF_CHECK_ALERTS = "告警";
+
+    /** _解析自检 四子键常量集合(用于过滤/透传) */
+    public static final List<String> SELF_CHECK_KEYS = Collections.unmodifiableList(Arrays.asList(
+            SELF_CHECK_PASS, SELF_CHECK_P0_ALERTS, SELF_CHECK_P1_HINTS, SELF_CHECK_ALERTS));
+
     /**
      * 提交异步采集任务。上传完成后调用,立即返回。
      */
@@ -214,6 +234,8 @@ public class ReportCollectService {
 
             ParsedReportPayload.Payload payload;
             String method;
+            // guhe_v2 解析自检块(P0-3 ③):known-type 分支随 outcome 透出,并入 collect_validation
+            Map<String, Object> parseSelfCheck = null;
             if (!"unknown".equals(typeId) && fp.get("parserPath") != null) {
                 // 指纹成功:脚本已迁移到 LangGraph(/report/parse,算法 + LLM 兜底)
                 // 已知类型解析失败不再回退 opencode,改为登记退避重试(parse_error 记录失败原因),
@@ -222,6 +244,7 @@ public class ReportCollectService {
                 LangGraphReportParseService.ParseOutcome outcome =
                         langGraphReportParseService.parseByScriptWithReason(pdfPath, expectedIndicators);
                 payload = outcome != null ? outcome.getPayload() : null;
+                parseSelfCheck = outcome != null ? outcome.getSelfCheck() : null;
                 if (payload == null) {
                     String reason = outcome != null && outcome.getError() != null
                             ? outcome.getError() : "解析结果为空或无效";
@@ -259,7 +282,7 @@ public class ReportCollectService {
             // 加固①:校验不通过(pass=false)阻止自动入库,标记失败由管理端人工处理
             boolean validationPass;
             try {
-                validationPass = runCollectValidation(draftId, validationTypeId, payload);
+                validationPass = runCollectValidation(draftId, validationTypeId, payload, parseSelfCheck);
             } catch (Exception e) {
                 log.warn("采集指标校验失败 draftId={}, typeId={}", draftId, validationTypeId, e);
                 validationPass = true;
@@ -1158,7 +1181,16 @@ public class ReportCollectService {
      * 健康(GUT/混检)管道校验入口:汇总 payload 中全部可采集指标名称后按定义比对
      */
     private boolean runCollectValidation(Long draftId, String typeId, ParsedReportPayload.Payload payload) {
-        return runCollectValidation(draftId, typeId, collectHealthNames(payload));
+        return runCollectValidation(draftId, typeId, collectHealthNames(payload), null);
+    }
+
+    /**
+     * 健康管道校验入口(携带 guhe_v2 解析自检块):_解析自检 四子键随 collects 结果
+     * 透传并入 collect_validation JSON(P0-3 ③)。
+     */
+    private boolean runCollectValidation(Long draftId, String typeId, ParsedReportPayload.Payload payload,
+                                         Map<String, Object> parseSelfCheck) {
+        return runCollectValidation(draftId, typeId, collectHealthNames(payload), parseSelfCheck);
     }
 
     /**
@@ -1172,15 +1204,21 @@ public class ReportCollectService {
                 addCollectName(names, item.getCode());
             }
         }
-        return runCollectValidation(draftId, typeId, names);
+        return runCollectValidation(draftId, typeId, names, null);
     }
 
     /**
      * 采集完整性校验:按 report_type_registry.expected_indicators 定义,校验本次采集结果是否覆盖应采集指标项。
      * 该类型无指标项定义(expected_indicators 为空 / 类型未注册)时跳过,不影响采集主流程。
      * 结果 JSON(typeId/expected/matched/pass/missing)写入草稿 collect_validation,缺失项记入 WARN 日志。
+     * guhe_v2 解析自检块存在时,额外以 {@code _解析自检} 子对象并入同一 JSON(P0-3 ③)。
      */
     private boolean runCollectValidation(Long draftId, String typeId, Set<String> collectedNames) {
+        return runCollectValidation(draftId, typeId, collectedNames, null);
+    }
+
+    private boolean runCollectValidation(Long draftId, String typeId, Set<String> collectedNames,
+                                         Map<String, Object> parseSelfCheck) {
         if (draftId == null || typeId == null || collectedNames == null || collectedNames.isEmpty()) {
             return true;
         }
@@ -1208,6 +1246,7 @@ public class ReportCollectService {
         result.put("matched", matched);
         result.put("pass", missing.isEmpty());
         result.put("missing", missing.size() > 20 ? missing.subList(0, 20) : missing);
+        attachParseSelfCheck(result, parseSelfCheck);
         try {
             healthReportDraftService.updateCollectValidation(draftId, objectMapper.writeValueAsString(result));
             if (missing.isEmpty()) {
@@ -1222,6 +1261,25 @@ public class ReportCollectService {
         return missing.isEmpty();
     }
 
+    /**
+     * P0-3 ③:将 guhe_v2 解析自检({@code _解析自检})四子键(通过/P0告警数/P1提示数/告警)
+     * 透传并入 collect_validation JSON。仅复制契约声明的四个子键,避免把上游无关字段混入。
+     */
+    private void attachParseSelfCheck(Map<String, Object> collectValidation, Map<String, Object> parseSelfCheck) {
+        if (collectValidation == null || parseSelfCheck == null || parseSelfCheck.isEmpty()) {
+            return;
+        }
+        Map<String, Object> selfCheck = new LinkedHashMap<>();
+        for (String key : SELF_CHECK_KEYS) {
+            if (parseSelfCheck.containsKey(key)) {
+                selfCheck.put(key, parseSelfCheck.get(key));
+            }
+        }
+        if (!selfCheck.isEmpty()) {
+            collectValidation.put(PARSE_SELF_CHECK_KEY, selfCheck);
+        }
+    }
+
     /** 肠道菌群家族校验可选指标(report_type_registry.expected_indicators 中缺失不阻断入库) */
     private static final Set<String> GUT_FLORA_OPTIONAL_INDICATORS =
             new HashSet<>(Arrays.asList("肠道预测年龄", "肠型"));