fix(外观专利): 同步停摆 13 天根治——爬取自由文本列改 TEXT+逐批/逐行容错+真因文案(V219)
客户口径「是不是记录不会保存 / 怎么是11.14号 / 这个公司的数据怎么都没了」, 现网实测量到的是:biz_appearance_patent_clean_item 最后一条 synced_at=2026-11-14 12:07:53, 11-15 起 60 个 SUCCESS 结果文件 0 行入库,且没有任何删除痕迹(bak_v191 与主表逐行对撞无缺失)。 根因链(三层,逐层修): 1) 存储层猜宽度:sku VARCHAR(128) 装的其实是客户端从详情页抓的「About this item」 要点整段(app_client/amazon/detail_spider.py 的 ul.a-unordered-list.a-vertical.a-spacing-mini), 长度由页面决定。V219 把 sku/title/image_url/item_url 改 TEXT、brand 512、price 128、 source_filename 512;真有语义上限的列(asin 64 / country 32 / conclusion 255)保留定长, 由同步侧 fitRequired/fitOptional 钳制并留 ClampLedger 痕迹。 2) 爆炸半径:500 行一批全部包在一个事务里,一行超宽整单回滚。改为逐批事务 + 单批失败降级逐行重试,行级失败只记 failedRows,不再吞掉整单。 3) 可诊断性:Spring 的 DataIntegrityViolationException.getMessage() 是空串,旧 WARN 只留 err= 什么都没说。现在 rootCauseText() 沿 cause 链取真因;整单零写入 / 部分行未写入 一律 log.error 显形(报告 cleanRows/blankAsinSkipped/upserted/failedRows/clamped)。 判据:AppearancePatentCleanSyncTest 新增 3 支(超长与空值不中断整单、单批失败降级逐行、 V219 列类型与服务侧钳制表一致性);外观专利面 397 支绿;catch 棘轮按规矩逐条点名 (GIVEN_NOT_RETHROW/STRICT_TOTAL/STRICT_NOT_RETHROW 各 +2,均 log.error + continue)。 后端全量 mvn -o test:5882 例 / 0 失败 / 19 skip。
This commit is contained in:
+189
-32
@@ -51,11 +51,24 @@ import java.util.Map;
|
||||
* <p><b>累计语义(2026-11-11 客户拍板「ASIN 累计、同 ASIN 只保留一条」,V192 同窗)</b>:
|
||||
* 按 {@code uk_company_user_country_asin} upsert、<b>永不删除</b>——同 ASIN 重复检测
|
||||
* 更新那条(值与 synced_at 刷新),不同 ASIN(含同品牌)全保留,跨任务累计。
|
||||
* 旧的按 result_id delete-then-insert 覆盖式重写已退役:已交付任务被事件重投时
|
||||
* 旧的按 result_id delete-then-insert 覆盖式重写已退役:已交付任务被事件重投时
|
||||
* 载荷重读可能与出表口径不一致(现网实录:交付 XLSX 里有上千行无侵权、同步读载荷
|
||||
* 却 cleanRows=0),覆盖语义在 cleanRows=0 时把该 result 上次的贡献整段抹掉
|
||||
* (2026-11-11 04:00 实抹 1902 行)——upsert-only 下读出 0 行=什么都不写,存量
|
||||
* 天然保留。批量 upsert 分批 ≤500/批,事务收口(中途失败不留半批)。</p>
|
||||
* (2026-11-11 04:00 实抹 1902 行)——upsert-only 下读出 0 行=什么都不写,
|
||||
* 存量天然保留。批量 upsert 分批 ≤500/批。</p>
|
||||
*
|
||||
* <p><b>写入健壮性(2026-11-27 根治,V219 同窗)</b>:2026-11-15~27 这张表 13 天零新增,
|
||||
* 现网日志每次都是 {@code clean-item sync failed ... err=}(真因藏在 cause 里:
|
||||
* {@code MysqlDataTruncation: Data too long for column 'sku'},旧实现 {@code ex.getMessage()}
|
||||
* 拿到空串,所以谁都看不出病在哪)。三个层次一起收口:</p>
|
||||
* <ul>
|
||||
* <li><b>列宽</b>:爬取自由文本({@code sku}/title/image_url/item_url)在 V219 改 TEXT,
|
||||
* 不再拿"猜一个够用的 VARCHAR"当存储设计;仍有语义上限的列由本类钳制;</li>
|
||||
* <li><b>爆炸半径</b>:每批一个事务,单批失败降级逐行重写——一条脏行换一条 ERROR,
|
||||
* 不换整单(旧写法全部批次同事务,一行超宽整单归零);</li>
|
||||
* <li><b>可诊断</b>:异常文案取最内层 cause;有行却整单零写入 / 有行未写入一律 ERROR,
|
||||
* 别再把停摆放进 INFO/WARN 里等客户发现。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -64,6 +77,18 @@ public class AppearancePatentCleanSyncService {
|
||||
/** 分片翻页与插入分批大小,与出表读链的 chunk 页大小同口径。 */
|
||||
private static final int PAGE_OR_BATCH_SIZE = 500;
|
||||
|
||||
/**
|
||||
* V219 之后仍然**定长**的列宽。TEXT 列不在这里:爬取自由文本的长度由页面决定,
|
||||
* 给上限就是给下一次停摆留了口子(V219 头注释第 2 条)。
|
||||
* 超宽的取值按列宽截断并记账({@link ClampLedger}),只截这一行、不带走整批。
|
||||
*/
|
||||
private static final int ASIN_MAX_LENGTH = 64;
|
||||
private static final int COUNTRY_MAX_LENGTH = 32;
|
||||
private static final int CONCLUSION_MAX_LENGTH = 255;
|
||||
private static final int BRAND_MAX_LENGTH = 512;
|
||||
private static final int PRICE_MAX_LENGTH = 128;
|
||||
private static final int SOURCE_FILENAME_MAX_LENGTH = 512;
|
||||
|
||||
private final AppearancePatentCleanItemMapper cleanItemMapper;
|
||||
private final TaskChunkMapper taskChunkMapper;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
@@ -101,9 +126,11 @@ public class AppearancePatentCleanSyncService {
|
||||
try {
|
||||
syncGuarded(task, result);
|
||||
} catch (Exception ex) {
|
||||
// 真因常在最内层 cause(Spring 的 DataIntegrityViolationException message 是空串,
|
||||
// 2026-11-15~27 的 13 天停摆全靠这一条才看得出来)
|
||||
log.warn("[appearance-patent] clean-item sync failed (delivery state untouched) taskId={} resultId={} err={}",
|
||||
task == null ? null : task.getId(), result == null ? null : result.getId(),
|
||||
ex.getMessage(), ex);
|
||||
rootCauseText(ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,11 +163,33 @@ public class AppearancePatentCleanSyncService {
|
||||
}
|
||||
CleanExtraction extraction = extractCleanRows(task, result, companyId, payloadRows);
|
||||
List<CleanItemEntity> rows = extraction.rows();
|
||||
int upserted = upsertRows(rows);
|
||||
SyncWriteResult write = upsertRows(task.getId(), rows);
|
||||
log.info("[appearance-patent] clean-item synced taskId={} resultId={} payloadRows={} cleanRows={} "
|
||||
+ "blankAsinSkipped={} upserted={} companyId={}",
|
||||
+ "blankAsinSkipped={} upserted={} failedRows={} clamped={} companyId={}",
|
||||
task.getId(), result.getId(), payloadRows.size(), rows.size(),
|
||||
extraction.blankAsinSkipped(), upserted, companyId);
|
||||
extraction.blankAsinSkipped(), write.upserted(), write.failedRows(),
|
||||
extraction.clampLedger().describe(), companyId);
|
||||
reportWriteGap(task, result, rows.size(), write, companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 「有行却没落库」必须是 ERROR:客户不会去翻十几万行 INFO 日志,
|
||||
* 2026-11-15~27 这 13 天就是靠 WARN 藏住的。两档分开报,便于监控按锚点抓:
|
||||
* 整单零写入(一行都没进去)与部分未写入(降级逐行后仍有坏行)。
|
||||
*/
|
||||
private void reportWriteGap(FileTaskEntity task, FileResultEntity result, int cleanRows,
|
||||
SyncWriteResult write, Long companyId) {
|
||||
if (cleanRows == 0) {
|
||||
return;
|
||||
}
|
||||
if (write.upserted() == 0) {
|
||||
log.error("[appearance-patent] clean-item 整单零写入 taskId={} resultId={} cleanRows={} failedRows={} companyId={}",
|
||||
task.getId(), result.getId(), cleanRows, write.failedRows(), companyId);
|
||||
} else if (write.failedRows() > 0) {
|
||||
log.error("[appearance-patent] clean-item 有行未写入 taskId={} resultId={} cleanRows={} "
|
||||
+ "upserted={} failedRows={} companyId={}",
|
||||
task.getId(), result.getId(), cleanRows, write.upserted(), write.failedRows(), companyId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,6 +255,7 @@ public class AppearancePatentCleanSyncService {
|
||||
private CleanExtraction extractCleanRows(FileTaskEntity task, FileResultEntity result,
|
||||
Long companyId, Map<String, AppearancePatentResultRowDto> payloadRows) {
|
||||
List<CleanItemEntity> rows = new ArrayList<>();
|
||||
ClampLedger clampLedger = new ClampLedger();
|
||||
int blankAsin = 0;
|
||||
int rowNo = 0;
|
||||
for (AppearancePatentResultRowDto row : payloadRows.values()) {
|
||||
@@ -213,59 +263,166 @@ public class AppearancePatentCleanSyncService {
|
||||
if (row.getAsin() == null || row.getAsin().isBlank()) {
|
||||
blankAsin++;
|
||||
} else {
|
||||
rows.add(toEntity(task, result, companyId, rowNo, row));
|
||||
rows.add(toEntity(task, result, companyId, rowNo, row, clampLedger));
|
||||
}
|
||||
}
|
||||
rowNo++;
|
||||
}
|
||||
return new CleanExtraction(rows, blankAsin);
|
||||
return new CleanExtraction(rows, blankAsin, clampLedger);
|
||||
}
|
||||
|
||||
/** 过滤结果:入选行+空 ASIN 跳过数(日志口径,读不出原因的行不静默消失)。 */
|
||||
private record CleanExtraction(List<CleanItemEntity> rows, int blankAsinSkipped) {
|
||||
/** 过滤结果:入选行+空 ASIN 跳过数+钳制账本(读不出原因的行不静默消失)。 */
|
||||
private record CleanExtraction(List<CleanItemEntity> rows, int blankAsinSkipped, ClampLedger clampLedger) {
|
||||
}
|
||||
|
||||
private CleanItemEntity toEntity(FileTaskEntity task, FileResultEntity result, Long companyId,
|
||||
int rowNo, AppearancePatentResultRowDto row) {
|
||||
int rowNo, AppearancePatentResultRowDto row, ClampLedger clampLedger) {
|
||||
CleanItemEntity entity = new CleanItemEntity();
|
||||
entity.setResultId(result.getId());
|
||||
entity.setTaskId(task.getId());
|
||||
entity.setUserId(task.getUserId());
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setRowNo(rowNo);
|
||||
// AC-1「与 payload 一致」:值原样落列,不 trim、不变换
|
||||
entity.setAsin(row.getAsin());
|
||||
entity.setCountry(row.getCountry());
|
||||
entity.setSku(row.getSku());
|
||||
entity.setBrand(row.getBrand());
|
||||
entity.setPrice(row.getPrice());
|
||||
// AC-1「与 payload 一致」:值原样落列,不 trim、不变换(只有超过列宽才截,且记账留痕)。
|
||||
// NOT NULL 列先 null→""(V189 全列 DEFAULT ''):payload 缺键给 null 时直接落 NULL 会
|
||||
// 整批报 "Column 'x' cannot be null" —— 与超宽同属「一行毁整单」的病。
|
||||
entity.setAsin(fitRequired(row.getAsin(), ASIN_MAX_LENGTH, "asin", clampLedger));
|
||||
entity.setCountry(fitRequired(row.getCountry(), COUNTRY_MAX_LENGTH, "country", clampLedger));
|
||||
// sku/title/image_url/item_url 是爬取自由文本,V219 起 TEXT,不给上限;
|
||||
// sku 仍是 NOT NULL:null 落成空串(与 V189 DEFAULT '' 同义),不落 NULL
|
||||
entity.setSku(emptyIfNull(row.getSku()));
|
||||
entity.setBrand(fitOptional(row.getBrand(), BRAND_MAX_LENGTH, "brand", clampLedger));
|
||||
entity.setPrice(fitOptional(row.getPrice(), PRICE_MAX_LENGTH, "price", clampLedger));
|
||||
entity.setTitle(row.getTitle());
|
||||
entity.setImageUrl(row.getUrl());
|
||||
// item_url:chunk 载荷 23 键契约无该键(Phase 0 黄金测试钉定、V189 头注释同口径)——
|
||||
// 按「payload 有才落」执行,保持 null 不伪造。
|
||||
entity.setConclusion(row.getConclusion());
|
||||
entity.setItemUrl(null);
|
||||
entity.setConclusion(fitRequired(row.getConclusion(), CONCLUSION_MAX_LENGTH, "conclusion", clampLedger));
|
||||
entity.setTitleReason(row.getTitleReason());
|
||||
entity.setAppearanceReason(row.getAppearanceReason());
|
||||
entity.setPatentReason(row.getPatentReason());
|
||||
entity.setSourceFilename(row.getSourceFilename());
|
||||
entity.setSourceFilename(fitOptional(row.getSourceFilename(), SOURCE_FILENAME_MAX_LENGTH,
|
||||
"sourceFilename", clampLedger));
|
||||
// synced_at 不写:列有 DB 默认值 CURRENT_TIMESTAMP(mapper XML 同一口径)
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按唯一键 upsert、永不删除(V192 累计语义):分批 ≤500/批收在同一事务,
|
||||
* 中途失败不留半批。读出 0 行时一个字节都不写——重投递载荷读不准(cleanRows=0)
|
||||
* 绝不反噬存量(2026-11-11 事故的根治点)。
|
||||
*/
|
||||
private int upsertRows(List<CleanItemEntity> rows) {
|
||||
Integer upserted = transactionTemplate.execute(status -> {
|
||||
int touched = 0;
|
||||
for (int from = 0; from < rows.size(); from += PAGE_OR_BATCH_SIZE) {
|
||||
touched += cleanItemMapper.upsertBatch(rows.subList(from, Math.min(from + PAGE_OR_BATCH_SIZE, rows.size())));
|
||||
/** NOT NULL 定长列:null 与空串同义(V189 建表 DEFAULT ''),超宽截断并记账。 */
|
||||
private static String fitRequired(String value, int maxLength, String field, ClampLedger clampLedger) {
|
||||
String text = emptyIfNull(value);
|
||||
if (text.length() <= maxLength) {
|
||||
return text;
|
||||
}
|
||||
return touched;
|
||||
clampLedger.record(field, text.length(), maxLength);
|
||||
return text.substring(0, maxLength);
|
||||
}
|
||||
|
||||
/** NOT NULL 的 TEXT 列(sku):只补空串,不设上限。 */
|
||||
private static String emptyIfNull(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
/** 可空定长列:null 仍是 null(不伪造),超宽截断并记账。 */
|
||||
private static String fitOptional(String value, int maxLength, String field, ClampLedger clampLedger) {
|
||||
if (value == null || value.length() <= maxLength) {
|
||||
return value;
|
||||
}
|
||||
clampLedger.record(field, value.length(), maxLength);
|
||||
return value.substring(0, maxLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分批写库,<b>每批一个事务</b>:单批异常只降级该批,不回滚已写进去的批。
|
||||
*
|
||||
* <p>旧写法把全部批次包在同一个事务里,一行超宽(V219 之前的 {@code sku VARCHAR(128)} 撞上
|
||||
* 详情页要点整段文本)就把整单回滚、一行不落——2026-11-15~27 现网实录 13 天零新增。
|
||||
* 现在单批失败后降级逐行重写:坏行 ERROR 留痕并跳过,同一批里其它行照常落库。
|
||||
* 单批成功仍是批量 INSERT(性能口径不变,500/批)。</p>
|
||||
*/
|
||||
private SyncWriteResult upsertRows(Long taskId, List<CleanItemEntity> rows) {
|
||||
int upserted = 0;
|
||||
int failedRows = 0;
|
||||
for (int from = 0; from < rows.size(); from += PAGE_OR_BATCH_SIZE) {
|
||||
List<CleanItemEntity> batch = rows.subList(from, Math.min(from + PAGE_OR_BATCH_SIZE, rows.size()));
|
||||
try {
|
||||
upserted += writeBatch(batch);
|
||||
} catch (RuntimeException batchFailure) {
|
||||
log.error("[appearance-patent] clean-item 单批写入失败,降级逐行重试 taskId={} batchSize={} err={}",
|
||||
taskId, batch.size(), rootCauseText(batchFailure));
|
||||
BatchRetry retry = writeRowsOneByOne(taskId, batch);
|
||||
upserted += retry.written();
|
||||
failedRows += retry.failed();
|
||||
}
|
||||
}
|
||||
return new SyncWriteResult(upserted, failedRows);
|
||||
}
|
||||
|
||||
private int writeBatch(List<CleanItemEntity> batch) {
|
||||
Integer touched = transactionTemplate.execute(status -> cleanItemMapper.upsertBatch(batch));
|
||||
return touched == null ? 0 : touched;
|
||||
}
|
||||
|
||||
/** 单批失败后的逐行降级:一行一个事务,坏行只报自己。 */
|
||||
private BatchRetry writeRowsOneByOne(Long taskId, List<CleanItemEntity> batch) {
|
||||
int written = 0;
|
||||
int failed = 0;
|
||||
for (CleanItemEntity row : batch) {
|
||||
try {
|
||||
written += writeBatch(List.of(row));
|
||||
} catch (RuntimeException rowFailure) {
|
||||
failed++;
|
||||
log.error("[appearance-patent] clean-item 单行写入失败已跳过 taskId={} asin={} country={} rowNo={} err={}",
|
||||
taskId, row.getAsin(), row.getCountry(), row.getRowNo(), rootCauseText(rowFailure));
|
||||
}
|
||||
}
|
||||
return new BatchRetry(written, failed);
|
||||
}
|
||||
|
||||
/** 真因文案:Spring 的 DataIntegrityViolationException message 常为空串,真因在最内层 cause。 */
|
||||
private static String rootCauseText(Throwable error) {
|
||||
String text = "";
|
||||
Throwable cursor = error;
|
||||
for (int depth = 0; cursor != null && depth < 8; depth++) {
|
||||
if (cursor.getMessage() != null && !cursor.getMessage().isBlank()) {
|
||||
text = cursor.getMessage();
|
||||
}
|
||||
cursor = cursor.getCause();
|
||||
}
|
||||
return text.isBlank() ? error.getClass().getSimpleName() : text;
|
||||
}
|
||||
|
||||
private record SyncWriteResult(int upserted, int failedRows) {
|
||||
}
|
||||
|
||||
private record BatchRetry(int written, int failed) {
|
||||
}
|
||||
|
||||
/** 钳制账本:字段 → 「最长原始长度>列宽」,只进日志,不参与任何业务判定。 */
|
||||
private static final class ClampLedger {
|
||||
private final Map<String, int[]> longestByField = new LinkedHashMap<>();
|
||||
|
||||
void record(String field, int rawLength, int maxLength) {
|
||||
longestByField.merge(field, new int[]{rawLength, maxLength}, ClampLedger::longer);
|
||||
}
|
||||
|
||||
private static int[] longer(int[] left, int[] right) {
|
||||
return left[0] >= right[0] ? left : right;
|
||||
}
|
||||
|
||||
String describe() {
|
||||
if (longestByField.isEmpty()) {
|
||||
return "-";
|
||||
}
|
||||
StringBuilder text = new StringBuilder();
|
||||
longestByField.forEach((field, pair) -> {
|
||||
if (text.length() > 0) {
|
||||
text.append(", ");
|
||||
}
|
||||
text.append(field).append('=').append(pair[0]).append('>').append(pair[1]);
|
||||
});
|
||||
return upserted == null ? 0 : upserted;
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private static String loadNoInfringementConclusion() {
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
-- 迁移 V219:外观专利无侵权明细把「爬取自由文本列」从定长改成 TEXT(2026-11-27 同步停摆 13 天根治)
|
||||
-- ============================================================================
|
||||
-- 1. 现网事故(本迁移的触发点,写死防复发):
|
||||
-- 2026-11-15 起,外观专利出表成功后同步链每次都抛
|
||||
-- `MysqlDataTruncation: Data too long for column 'sku' at row 1`,且因为 500 行一批、
|
||||
-- 全部批次包在**同一个事务**里,一行超宽把整单回滚 ⇒ 后台这张表 11-14 12:07 之后
|
||||
-- 13 天零新增(11-15 起 60 个 SUCCESS 任务、0 行入库),界面表现就是客户说的
|
||||
-- 「是不是记录不会保存 / 怎么是11.14号 / 这个公司的数据怎么都没了」。
|
||||
--
|
||||
-- 2. 为什么不是「把 128 调大一点」:
|
||||
-- `sku` 这一列写入的并不是卖家 SKU,而是客户端从详情页抓的「About this item」要点整段
|
||||
-- (`app_client/amazon/detail_spider.py` 的 `ul.a-unordered-list.a-vertical.a-spacing-mini`
|
||||
-- 文本,历史样本里就是 "Black tee shirt \n 100% Heavyweight Cotton \n ...")。
|
||||
-- 这类爬取自由文本的长度由**页面决定、不由我们决定**,任何定长都是下一次停摆的定时炸弹。
|
||||
-- 口径:**长度不可控的爬取文本一律 TEXT,不给上限**;只有真有语义上限的列(ASIN 10 位、
|
||||
-- 国家名、结论词表)才保留定长并由同步侧钳制(AppearancePatentCleanSyncService)。
|
||||
--
|
||||
-- 3. 变更面(一次改全,避免下一列再炸一次同样的病):
|
||||
-- sku / title / image_url / item_url -> TEXT(爬取自由文本,无上限)
|
||||
-- brand -> VARCHAR(512)(品牌名偶有长尾,256 不够稳)
|
||||
-- price -> VARCHAR(128)(原值字符串,含多币种/区间写法)
|
||||
-- source_filename -> VARCHAR(512)(来源 Excel 文件名可长)
|
||||
-- asin(64) / country(32) / conclusion(255) -> 不动,由同步侧按列宽钳制并留痕
|
||||
--
|
||||
-- 4. 行尺寸与索引:TEXT 在行内只占 20 字节指针,行尺寸反而变小;唯一键
|
||||
-- uk_company_user_country_asin(company_id,user_id,country,asin) 与 idx_company/idx_task/idx_asin
|
||||
-- 都不含本迁移改动的列,索引不受影响。
|
||||
--
|
||||
-- 5. 可重跑性:MySQL 无 MODIFY ... IF EXISTS;重复执行是幂等的类型再声明(同类型 MODIFY 无副作用),
|
||||
-- 但 Flyway 正常只跑一次,人工重跑前先 SHOW CREATE TABLE 核对。
|
||||
--
|
||||
-- 6. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW CREATE TABLE biz_appearance_patent_clean_item;
|
||||
-- -> sku/title/image_url/item_url 四列应为 text,brand 512、price 128、source_filename 512;
|
||||
-- 唯一键仍是 uk_company_user_country_asin,三个索引仍在。
|
||||
-- 应用侧:AppearancePatentCleanSyncTest 钉「超长文本/空值不中断整单」+本文件与同步侧钳制表一致。
|
||||
--
|
||||
-- 7. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- ALTER TABLE biz_appearance_patent_clean_item
|
||||
-- MODIFY COLUMN sku VARCHAR(128) NOT NULL DEFAULT '',
|
||||
-- ...(其余列按 V189 原定义回退);
|
||||
-- 回滚前必须先确认没有超长行,否则下一次同步立刻复发。
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE biz_appearance_patent_clean_item
|
||||
MODIFY COLUMN sku TEXT NOT NULL COMMENT '商品要点文本(爬取自由文本,历史上被当作 SKU 列展示;V219 起不再设长度上限)',
|
||||
MODIFY COLUMN title TEXT NULL COMMENT '商品标题(爬取自由文本)',
|
||||
MODIFY COLUMN image_url TEXT NULL COMMENT '商品主图/检测图 URL(爬取原值)',
|
||||
MODIFY COLUMN item_url TEXT NULL COMMENT '商品详情页 URL(V189 立列可空,payload 有才落)',
|
||||
MODIFY COLUMN brand VARCHAR(512) NULL COMMENT '商品品牌',
|
||||
MODIFY COLUMN price VARCHAR(128) NULL COMMENT '商品价格(原样字符串)',
|
||||
MODIFY COLUMN source_filename VARCHAR(512) NULL COMMENT '来源文件名';
|
||||
@@ -88,7 +88,10 @@ class CatchSilenceRatchetTest {
|
||||
// log.warn 不抛一枚(行已指向新 key,残留只是存储垃圾),出处见 STRICT_TOTAL 上方 11-16 段。
|
||||
// 11-21 v1.7 发版窗抬 625 -> 626:四枚不重抛含 log(JdSizeChartAiService 三枚+
|
||||
// TaskClientPullService.buildQueuePushPayload 一枚),出处与误差方向见 STRICT_TOTAL 上方 11-21 段。
|
||||
static final int GIVEN_NOT_RETHROW = 626;
|
||||
// 11-27 外观专利同步停摆根治抬 626 -> 628:AppearancePatentCleanSyncService 两枚
|
||||
// 「批量入库逐批/逐行容错」——单批失败只降级该批、单行失败只跳该行,都是 log.error
|
||||
// (带 taskId/asin/rowNo 与最内层 cause)后继续,不重抛;出处见 STRICT_TOTAL 上方 11-27 段。
|
||||
static final int GIVEN_NOT_RETHROW = 628;
|
||||
static final int GIVEN_LOG_ONLY = 251;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -431,7 +434,17 @@ class CatchSilenceRatchetTest {
|
||||
// (FillAi/SizeChart 各删一份 parse catch、支撑类落一份,净 −1);
|
||||
// ② asDecimal/asNumber 两处「正则已钉形状后 BigDecimal/Double 再 catch」是死代码,
|
||||
// 整段摘除(净 −2)。降级外壳的口径没动:外层 catch Exception → WARN + 空映射照旧。
|
||||
static final int STRICT_TOTAL = 1110;
|
||||
// 11-27 外观专利同步停摆根治(V219 同窗)抬 1110 -> 1112,两枚逐一记名,都在
|
||||
// AppearancePatentCleanSyncService:
|
||||
// ① upsertRows 的 catch (RuntimeException batchFailure):单批 upsert 失败 → log.error(含
|
||||
// batchSize 与最内层 cause)+ 降级 writeRowsOneByOne,不重抛。理由:旧实现把全部批次
|
||||
// 包在一个事务里,一行 sku 超宽(VARCHAR(128) × 详情页要点整段文本)把整单回滚,
|
||||
// 2026-11-15~27 后台 13 天零入库、60 个 SUCCESS 任务一行没落;
|
||||
// ② writeRowsOneByOne 的 catch (RuntimeException rowFailure):单行失败 → failed++ 后
|
||||
// log.error(taskId/asin/country/rowNo 点名)并继续下一行。理由:一条脏行只该换一条
|
||||
// 日志,不该换整单——这是爆炸半径从"整单"收到"单行"的另一半。
|
||||
// 两处都是 NOT_RETHROW(log + 继续),不进 LOG_ONLY(块体不止一句 log)、不进 EMPTY。
|
||||
static final int STRICT_TOTAL = 1112;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -587,7 +600,8 @@ class CatchSilenceRatchetTest {
|
||||
// 占本格额度——本格含 LOG_ONLY 口径,出处见 STRICT_TOTAL 上方 11-16 段)。
|
||||
// 11-21 v1.7 发版窗 625 -> 626:四枚不重抛含 log(JdSizeChartAiService 三枚+
|
||||
// TaskClientPullService.buildQueuePushPayload 一枚),出处见 STRICT_TOTAL 上方 11-21 段。
|
||||
static final int STRICT_NOT_RETHROW = 626;
|
||||
// 11-27 外观专利同步停摆根治 626 -> 628:逐批/逐行容错两枚,出处见 STRICT_TOTAL 上方 11-27 段。
|
||||
static final int STRICT_NOT_RETHROW = 628;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
|
||||
+93
@@ -329,6 +329,99 @@ class AppearancePatentCleanSyncTest {
|
||||
verify(facade, times(1)).syncFromResult(anyLong(), anyLong());
|
||||
}
|
||||
|
||||
// ===================== 写入健壮性(2026-11-27 停摆根治,V219 同窗) =====================
|
||||
|
||||
/**
|
||||
* 现网形状:{@code sku} 列里放的是详情页「About this item」整段要点(历史样本就是多行服装卖点),
|
||||
* 长度由页面决定。V219 之前该列 {@code VARCHAR(128)},2026-11-15 起每个任务都被
|
||||
* {@code MysqlDataTruncation: Data too long for column 'sku'} 打回,13 天零入库。
|
||||
* 判据:自由文本不截断、NOT NULL 列 null→空串、可空列保持 null,且**一行都不能少**。
|
||||
*/
|
||||
@Test
|
||||
void 爬取自由文本超长与空值不中断整单() throws Exception {
|
||||
AppearancePatentCleanItemMapper cleanItemMapper = mock(AppearancePatentCleanItemMapper.class);
|
||||
TaskChunkMapper taskChunkMapper = mock(TaskChunkMapper.class);
|
||||
AdminUserMapper adminUserMapper = mock(AdminUserMapper.class);
|
||||
when(taskChunkMapper.selectList(any())).thenReturn(List.of(chunk(33001L)));
|
||||
when(adminUserMapper.selectById(77L)).thenReturn(user(7L));
|
||||
String longSku = "要点一\n".repeat(600);
|
||||
String longTitle = "超长标题".repeat(300);
|
||||
AppearancePatentResultRowDto longRow = row("t1", "B0CLEAN001", "无侵权");
|
||||
longRow.setSku(longSku);
|
||||
longRow.setTitle(longTitle);
|
||||
AppearancePatentResultRowDto nullRow = row("t2", "B0CLEAN002", "无侵权");
|
||||
nullRow.setSku(null);
|
||||
nullRow.setBrand(null);
|
||||
AppearancePatentCleanSyncService service = service(cleanItemMapper, taskChunkMapper, adminUserMapper,
|
||||
new ObjectMapper().writeValueAsString(List.of(longRow, nullRow)));
|
||||
|
||||
service.syncFromResult(task(33001L, 77L), result(34819L, 33001L, "oss://result/x.xlsx"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<CleanItemEntity>> rows = ArgumentCaptor.forClass((Class) List.class);
|
||||
verify(cleanItemMapper).upsertBatch(rows.capture());
|
||||
assertEquals(2, rows.getValue().size(), "超长字段与空值都不得让整单少写一行");
|
||||
assertEquals(longSku, rows.getValue().get(0).getSku(), "自由文本列(V219 TEXT)不截断");
|
||||
assertEquals(longTitle, rows.getValue().get(0).getTitle());
|
||||
assertEquals("", rows.getValue().get(1).getSku(), "NOT NULL 列 null→空串,不落 NULL 触发 Column cannot be null");
|
||||
assertNull(rows.getValue().get(1).getBrand(), "可空列保持 null,不伪造");
|
||||
}
|
||||
|
||||
/**
|
||||
* 单批写入失败(约束/类型类异常)只降级这一批:逐行重写,坏行留痕跳过,其它行照常落库。
|
||||
* 旧写法全部批次同事务,一行坏行整单归零——就是 13 天停摆的机制本身。
|
||||
*/
|
||||
@Test
|
||||
void 单批写入失败降级逐行重试不丢整单() throws Exception {
|
||||
AppearancePatentCleanItemMapper cleanItemMapper = mock(AppearancePatentCleanItemMapper.class);
|
||||
TaskChunkMapper taskChunkMapper = mock(TaskChunkMapper.class);
|
||||
AdminUserMapper adminUserMapper = mock(AdminUserMapper.class);
|
||||
when(taskChunkMapper.selectList(any())).thenReturn(List.of(chunk(33001L)));
|
||||
when(adminUserMapper.selectById(77L)).thenReturn(user(7L));
|
||||
when(cleanItemMapper.upsertBatch(any())).thenAnswer(invocation -> {
|
||||
List<?> batch = invocation.getArgument(0);
|
||||
if (batch.size() > 1) {
|
||||
throw new RuntimeException("Data too long for column 'sku' at row 1");
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
AppearancePatentCleanSyncService service = service(cleanItemMapper, taskChunkMapper, adminUserMapper,
|
||||
new ObjectMapper().writeValueAsString(List.of(
|
||||
row("t1", "B0CLEAN001", "无侵权"),
|
||||
row("t2", "B0CLEAN002", "无侵权"),
|
||||
row("t3", "B0CLEAN003", "无侵权"))));
|
||||
|
||||
assertDoesNotThrow(() -> service.syncFromResult(task(33001L, 77L),
|
||||
result(34819L, 33001L, "oss://result/x.xlsx")),
|
||||
"单批失败必须被隔离:同步链自吞异常,不改变出表链终态(AC-3)");
|
||||
// 1 次整批(失败)+ 3 次逐行(成功):三行各写一次,没有一行被整批连坐
|
||||
verify(cleanItemMapper, times(4)).upsertBatch(any());
|
||||
verifyNoMoreInteractions(cleanItemMapper);
|
||||
}
|
||||
|
||||
/** 迁移口径:爬取自由文本列必须是 TEXT,定长列宽与服务侧钳制表逐字一致(两处不许漂移)。 */
|
||||
@Test
|
||||
void 自由文本列在迁移里是TEXT且定长列宽与钳制表一致() throws IOException {
|
||||
String sql = Files.readString(MODULE.resolve(
|
||||
"src/main/resources/db/V219__appearance_patent_clean_item_free_text_columns.sql"));
|
||||
for (String column : new String[]{"sku", "title", "image_url", "item_url"}) {
|
||||
assertTrue(sql.matches("(?s).*MODIFY COLUMN " + column + " TEXT.*"),
|
||||
"V219 必须把 " + column + " 改成 TEXT——这类文本长度由页面决定,定长就是下一次停摆");
|
||||
}
|
||||
String source = stripComments(read(MAIN.resolve(SYNC_SERVICE_REL)));
|
||||
String[][] bounded = {
|
||||
{"brand", "BRAND_MAX_LENGTH", "512"},
|
||||
{"price", "PRICE_MAX_LENGTH", "128"},
|
||||
{"source_filename", "SOURCE_FILENAME_MAX_LENGTH", "512"},
|
||||
};
|
||||
for (String[] pair : bounded) {
|
||||
assertTrue(sql.contains(pair[0] + " VARCHAR(" + pair[2] + ")"),
|
||||
"V219 的 " + pair[0] + " 列宽必须是 " + pair[2]);
|
||||
assertTrue(source.contains(pair[1] + " = " + pair[2]),
|
||||
"同步侧钳制表必须与 V219 同宽:" + pair[1] + " = " + pair[2]);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 夹具 =====================
|
||||
|
||||
private static AppearancePatentCleanSyncService service(AppearancePatentCleanItemMapper cleanItemMapper,
|
||||
|
||||
Reference in New Issue
Block a user