feat(parity): C1 核心 RowDiff 逐行对拍引擎 + 归一化规则 + 17 单测

diff 内核(com.eip4.platform.parity.diff):
- Normalizer:char(36) 尾空格 / numeric scale / 整数布尔跨类型 /
  bigint 时间戳 / ISO 串↔epoch / NULL-vs-缺列 归一化规则
- RowDiff:两结果集按主键排序配对,逐行逐列归一比较,行序无关
- DiffReport:结构化差异报告(JSON + Markdown 摘要)
- RowDiffTest:17 例覆盖全部归一化规则与差异检出(全绿)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-10 23:41:01 +08:00
parent a9219c5c77
commit 3aec8f292e
5 changed files with 573 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
package com.eip4.platform.parity.diff;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 一次结果集逐行对拍的结构化差异报告。
*
* <p>同时承载机器可读(JSON 序列化)与人读(Markdown 摘要)两种产物:
* {@link #toSummaryMap()} 给 JSON,{@link #toMarkdown()} 给报告附录。
*/
public class DiffReport {
/** 对拍标签(通常是实体/表名)。 */
public final String label;
/** 左侧(基线,旧系统/录制)行数。 */
public int leftRowCount;
/** 右侧(新引擎)行数。 */
public int rightRowCount;
/** 用于排序与配对的主键列(规范化后)。 */
public final List<String> keyColumns = new ArrayList<>();
/** 仅左侧存在的行(右侧缺失),记录主键。 */
public final List<String> onlyInLeft = new ArrayList<>();
/** 仅右侧存在的行(左侧缺失),记录主键。 */
public final List<String> onlyInRight = new ArrayList<>();
/** 主键匹配但有单元格差异的行。 */
public final List<RowMismatch> mismatches = new ArrayList<>();
public DiffReport(String label) {
this.label = label;
}
/** 主键匹配、单元格全等的行数。 */
public int matchedRows;
public boolean isClean() {
return onlyInLeft.isEmpty() && onlyInRight.isEmpty() && mismatches.isEmpty();
}
/** 总比对行数(以两侧并集计)。 */
public int totalCompared() {
return matchedRows + mismatches.size() + onlyInLeft.size() + onlyInRight.size();
}
/** 一致率(matched / 并集),用于报告里"逐行一致率"。 */
public double consistencyRate() {
int total = totalCompared();
return total == 0 ? 1.0 : (double) matchedRows / total;
}
/** 单元格级差异。 */
public static class CellDiff {
public final String column;
public final Object left;
public final Object right;
/** 差异原因:VALUE(值不同)/ MISSING_LEFT(左缺列)/ MISSING_RIGHT(右缺列)。 */
public final String reason;
public CellDiff(String column, Object left, Object right, String reason) {
this.column = column;
this.left = left;
this.right = right;
this.reason = reason;
}
public Map<String, Object> toMap() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("column", column);
m.put("left", left);
m.put("right", right);
m.put("reason", reason);
return m;
}
}
/** 主键匹配但内容有差异的一行。 */
public static class RowMismatch {
public final String key;
public final List<CellDiff> cells = new ArrayList<>();
public RowMismatch(String key) {
this.key = key;
}
public Map<String, Object> toMap() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("key", key);
List<Map<String, Object>> cs = new ArrayList<>();
for (CellDiff c : cells) {
cs.add(c.toMap());
}
m.put("cells", cs);
return m;
}
}
/** 机器可读摘要(JSON 序列化用)。 */
public Map<String, Object> toSummaryMap() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("label", label);
m.put("keyColumns", keyColumns);
m.put("leftRowCount", leftRowCount);
m.put("rightRowCount", rightRowCount);
m.put("matchedRows", matchedRows);
m.put("mismatchRows", mismatches.size());
m.put("onlyInLeft", onlyInLeft);
m.put("onlyInRight", onlyInRight);
m.put("clean", isClean());
m.put("consistencyRate", consistencyRate());
List<Map<String, Object>> ms = new ArrayList<>();
for (RowMismatch r : mismatches) {
ms.add(r.toMap());
}
m.put("mismatches", ms);
return m;
}
/** 人读 Markdown 摘要(进 C1 报告附录)。 */
public String toMarkdown() {
StringBuilder sb = new StringBuilder();
sb.append("### 对拍:").append(label).append("\n\n");
sb.append("- 主键列:`").append(String.join(",", keyColumns)).append("`\n");
sb.append("- 左/右行数:").append(leftRowCount).append(" / ").append(rightRowCount).append("\n");
sb.append("- 匹配一致行:").append(matchedRows).append("\n");
sb.append("- 内容差异行:").append(mismatches.size()).append("\n");
sb.append("- 仅左侧:").append(onlyInLeft.size())
.append(" 仅右侧:").append(onlyInRight.size()).append("\n");
sb.append("- 逐行一致率:").append(String.format("%.4f", consistencyRate()))
.append(isClean() ? " ✅ 完全一致" : " ⚠️ 存在差异").append("\n");
if (!mismatches.isEmpty()) {
sb.append("\n差异明细(前 20 行):\n\n");
sb.append("| 主键 | 列 | 左值 | 右值 | 原因 |\n|---|---|---|---|---|\n");
int shown = 0;
for (RowMismatch r : mismatches) {
for (CellDiff c : r.cells) {
if (shown++ >= 20) {
break;
}
sb.append("| ").append(r.key).append(" | ").append(c.column)
.append(" | ").append(c.left).append(" | ").append(c.right)
.append(" | ").append(c.reason).append(" |\n");
}
if (shown >= 20) {
break;
}
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,165 @@
package com.eip4.platform.parity.diff;
import java.math.BigDecimal;
import java.util.Objects;
/**
* 单值规范化器 —— 把"语义等值但表示不同"的两个值归一到可直接 equals 的规范形式。
*
* <p>归一化规则全部源自保真层引擎与 PG 物理类型口径(见 {@code Entity.createTableSql}
* 与《C1实测报告.md》归一化规则表),逐条对应一类"旧/新两侧表示差异但语义一致"的场景:
*
* <ol>
* <li><b>char(36) 尾部空格</b>:PG {@code character(n)} 定长列读出会补空格(id/外键/CREATEBY 等),
* 两侧驱动/字段长度差异会带来不同尾空格 → 统一 {@code stripTrailing()}。</li>
* <li><b>数值 scale 归一</b>:{@code numeric(18,6)} 读出 {@code 2.000000} 与 amis/JDBC 读出 {@code 2}
* 语义等值 → 统一用 {@link BigDecimal#compareTo} 而非 {@code equals}(后者比较 scale)。</li>
* <li><b>整数跨类型</b>:同一整数列在两侧可能是 Integer/Long/Short/BigInteger → 统一比较 long 值。</li>
* <li><b>布尔/整型混用</b>:BOOLEAN 物理列是 integer(0/1),一侧 Boolean 一侧 Integer → 归一到 0/1。</li>
* <li><b>bigint 时间戳原样</b>:DATE/TIME 物理列是 epoch 毫秒 bigint,按整数原样比(不做时区/格式解释)。</li>
* <li><b>NULL 区分缺列</b>:本类只负责单值;NULL-vs-缺列的区分在 {@link RowDiff} 行级处理。</li>
* </ol>
*
* 设计为无状态纯函数,便于单测覆盖每条规则。
*/
public final class Normalizer {
private Normalizer() {
}
/** 归一化的规范形式标记:用于报告里描述某值被按哪条规则处理。 */
public enum Kind {
NULL, STRING, INTEGRAL, DECIMAL, BOOL_AS_INT, OTHER
}
/**
* 把单值归一到规范对象:
* <ul>
* <li>{@code null} → {@code null}</li>
* <li>定长字符串/字符 → 去尾部空格的 {@link String}</li>
* <li>整型族(Byte/Short/Integer/Long/BigInteger) → {@link Long}</li>
* <li>{@link Boolean} → {@link Long} 0/1(对齐 BOOLEAN 物理列 integer 口径)</li>
* <li>小数族(Float/Double/BigDecimal) → 去掉尾零的 {@link BigDecimal}</li>
* <li>其他 → 原值的 {@code toString()} 去尾空格</li>
* </ul>
*/
public static Object canonical(Object v) {
if (v == null) {
return null;
}
if (v instanceof Boolean b) {
return b ? 1L : 0L;
}
if (v instanceof Byte || v instanceof Short || v instanceof Integer || v instanceof Long) {
return ((Number) v).longValue();
}
if (v instanceof java.math.BigInteger bi) {
return bi.longValueExact();
}
if (v instanceof BigDecimal bd) {
return stripBd(bd);
}
if (v instanceof Float || v instanceof Double) {
return stripBd(BigDecimal.valueOf(((Number) v).doubleValue()));
}
if (v instanceof CharSequence || v instanceof Character) {
return stripTrailing(v.toString());
}
// 兜底:任意对象按字符串去尾空格(覆盖 java.sql.Timestamp/joda 等)
return stripTrailing(v.toString());
}
/** 两值是否语义等值(经规范化后比较)。NULL == NULL 为 true(缺列区分在行级)。 */
public static boolean equal(Object a, Object b) {
Object ca = canonical(a);
Object cb = canonical(b);
if (ca == null || cb == null) {
return ca == null && cb == null;
}
// 数值跨族比较:Long 与 BigDecimal 之间也应等值(2 vs 2.000000)
if (ca instanceof Long la && cb instanceof BigDecimal db) {
return new BigDecimal(la).compareTo(db) == 0;
}
if (ca instanceof BigDecimal da && cb instanceof Long lb) {
return da.compareTo(new BigDecimal(lb)) == 0;
}
if (ca instanceof BigDecimal da && cb instanceof BigDecimal db) {
return da.compareTo(db) == 0;
}
// 规则5b:DATE/TIME 物理列是 bigint epoch 毫秒,但引擎 REST 侧经 JodaModule 序列化为
// ISO-8601 字符串(如 1970-01-01T00:00:00.000Z)。一侧 epoch(Long) 一侧 ISO 串时,
// 解析 ISO 为 epoch 毫秒后比较,使"同一时刻两种表示"语义等值。
Long ea = epochOf(ca);
Long eb = epochOf(cb);
if (ea != null && eb != null) {
return ea.longValue() == eb.longValue();
}
return Objects.equals(ca, cb);
}
/**
* 把"已规范化的值"尝试解读为 epoch 毫秒:
* Long 原样返回;ISO-8601 instant 字符串(带 Z)解析为毫秒;否则 null(不可比为时间)。
* 仅当对端也是时间表示时才生效,普通字符串/整数不会被误判。
*/
private static Long epochOf(Object canonical) {
if (canonical instanceof Long l) {
return l;
}
if (canonical instanceof String s && looksLikeIsoInstant(s)) {
try {
return java.time.Instant.parse(s).toEpochMilli();
} catch (RuntimeException ignore) {
return null;
}
}
return null;
}
private static boolean looksLikeIsoInstant(String s) {
// 形如 1970-01-01T00:00:00.000Z;要求含 'T' 与结尾 'Z',避免把普通文本当时间
return s.length() >= 16 && s.indexOf('T') == 10 && s.endsWith("Z");
}
/** 分类标记(报告/调试用)。 */
public static Kind kindOf(Object v) {
if (v == null) {
return Kind.NULL;
}
if (v instanceof Boolean) {
return Kind.BOOL_AS_INT;
}
if (v instanceof Byte || v instanceof Short || v instanceof Integer
|| v instanceof Long || v instanceof java.math.BigInteger) {
return Kind.INTEGRAL;
}
if (v instanceof BigDecimal || v instanceof Float || v instanceof Double) {
return Kind.DECIMAL;
}
if (v instanceof CharSequence || v instanceof Character) {
return Kind.STRING;
}
return Kind.OTHER;
}
/** char(n) 定长列尾部空格归一(只去尾部,保留中间与前导)。 */
public static String stripTrailing(String s) {
if (s == null) {
return null;
}
int end = s.length();
while (end > 0 && s.charAt(end - 1) == ' ') {
end--;
}
return s.substring(0, end);
}
private static BigDecimal stripBd(BigDecimal bd) {
BigDecimal stripped = bd.stripTrailingZeros();
// stripTrailingZeros 对 0 会给出 0E-n,规范成 0 比例,避免 scale 噪声
if (stripped.compareTo(BigDecimal.ZERO) == 0) {
return BigDecimal.ZERO;
}
return stripped;
}
}