feat(notification): V171 给去重键补唯一约束,插入侧把竞态念成去重命中(B30)
用户问「后台 488 条未读是不是只进不出、消重到底生效没有」。实测结论:消重在生效 (12h 全表 `GROUP BY dedupe_key HAVING c>1` = 0 组、空键 0 行;管理员扇出走 pushOrRefresh 同键只更新文案不动 read_at),观感上的"每十几分钟一条"是扇出(1 事件 ×24 管理员=24 行) 加节拍(secret_shared 走 cost-guard.shared-scan-interval-ms=600000,实测 15:52/16:12/16:22; 任务失败那路 scan-interval-ms=300000)。未读只进不出的唯一出口是 7 天保留期物理删除。 真缺陷在约束缺失:查重是 SELECT-then-INSERT,表上只有非唯一的 idx_dedupe(V116:19), 双节点同轮撞键会各插一行——今天没踩到靠的是 job 锁(扫描 5 分钟/cost-guard 2 分钟), 不是靠约束。 - V171:`NULLIF(dedupe_key,'')` 的 STORED 投影列 + 唯一键。不给 dedupe_key 直接加唯一键 是因为空串按设计就是"不去重"(服务 javadoc + V116 的 DEFAULT ''),第二条空串会 1062 被 catch 成推送失败 ⇒ 一类通知静默消失;唯一索引允许多个 NULL,投影正好绕开。 存量重复按 MIN(id) 收口——判据与服务自身 selectByDedupeKey 的 orderByAsc(id) limit 1 同一行, 删的是永不被看见的副本。两条 DDL 各查 information_schema 再 PREPARE(repair 重跑不炸), 故意不钉 ALGORITHM=INSTANT(STORED 生成列不支持,钉了 1846 顶死迁移)。 取号 171:生产已应用到 170(今天 17:0x 只读实查 160–167、170 全在),台账 docs/migration-inventory.md 的旧快照"六支未落库"随之更正,DROP COLUMN 那一路顺延 172。 - push():DuplicateKeyException 分诊成「去重命中(竞态由唯一键兜住)」的 info,不并入 「推送落库失败」的 warn。**写成分诊、没新增 catch**——CatchSilenceRatchetTest.STRICT_TOTAL 已钉在 1004 满格,多一块就得重钉基线,那是该逐处记名说话的账,不该由一笔并发兜底花掉。 门禁:定向 46 例绿(新增迁移文本 5 例+服务 3 例,含 CatchSilenceRatchetTest 9 例、 MigrationInventoryTest 7 例);后端整量 `mvn -o test` **4794 例/0 红/0 错/18 skip/ BUILD SUCCESS**(第一遍曾被本笔新增的 catch 顶红棘轮 1004→1005,按上面口径改成分诊后转绿, 未动基线)。变异验证:唯一键改指 dedupe_key ⇒ 迁移用例判红 1 例;摘掉 DuplicateKeyException 分诊 ⇒ 服务用例判红 1 例;两处均逐字节还原(md5 对撞)。 ⚠ 残留:这段 DDL 未在真 MySQL 上 dry-run(本机 127.0.0.1:3306 是另一路的 dev server 8.4.9、 无口令且可能是 A 机隧道,不拿来赌;生产实例未获批准不建隔离 schema)。发版前必须补这一次。
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* task-…(2026-10-24):V171 给 biz_user_notification 的去重键补唯一约束,本类钉它的形状。
|
||||
*
|
||||
* <p>立账出处是 ops 仓 {@code docs/audit/BACKLOG.md} 的 B30:通知的查重是
|
||||
* SELECT-then-INSERT({@code NotificationService.push} → {@code insert}),表上只有非唯一的
|
||||
* {@code idx_dedupe}(V116:19),所以双节点同轮撞键会各插一行——今天全表实查 0 组重复,
|
||||
* 靠的是 job 锁没失效,不是靠约束。这一笔把它变成数据库层的不变量。</p>
|
||||
*
|
||||
* <p>这个类守的三件事,每件都是"写错了会在生产上炸"的方向:</p>
|
||||
* <ol>
|
||||
* <li><b>空串键不许被唯一性杀掉</b>:{@code dedupe_key} 允许 '',而 '' 按设计就是"不去重"
|
||||
* (服务里的 javadoc 与 V116 的 DEFAULT '')。直接给 {@code dedupe_key} 加唯一键,
|
||||
* 第二条 '' 通知会报 1062 被 catch 成"推送落库失败"⇒ 一类通知静默消失。
|
||||
* 所以唯一键必须落在 {@code NULLIF(dedupe_key,'')} 的投影列上。</li>
|
||||
* <li><b>存量有重复时迁移必须自己收口</b>:不先按 {@code MIN(id)} 合并就 ADD UNIQUE ⇒ 1062
|
||||
* ⇒ Flyway 失败 ⇒ 两台 java 起不来。收口判据与服务自身的读取口径一致
|
||||
* ({@code orderByAsc(id)...limit 1}),删的是永远不会被看见的副本。</li>
|
||||
* <li><b>可重跑</b>:DDL 不进事务,中途失败后 repair 会从第一条语句重跑整个文件,
|
||||
* 两条 ALTER 必须各自查 information_schema 再 PREPARE(首例 V143/V145/V162)。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>{@code stripComments}/{@code normalize} 逐字沿用 {@link CompanyMigrationV144Test}
|
||||
* 那一份实现:注释里的 {@code --} 与字符串字面量里的 {@code --} 是两件事,
|
||||
* 另写一版简化实现会让断言打在残缺 SQL 上。</p>
|
||||
*/
|
||||
class NotificationDedupeUniqueMigrationV171Test {
|
||||
|
||||
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
|
||||
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
|
||||
private static final Pattern VERSION_PREFIX = Pattern.compile("^V(\\d+)(?:_(\\d+))?__");
|
||||
|
||||
// ---------------------------------------------------------------- 取文件
|
||||
|
||||
private static List<Path> versionFiles() throws IOException {
|
||||
try (Stream<Path> s = Files.list(DB_DIR)) {
|
||||
return s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static Path migration() throws IOException {
|
||||
List<Path> hits = versionFiles().stream()
|
||||
.filter(p -> p.getFileName().toString().startsWith("V171__"))
|
||||
.toList();
|
||||
assertEquals(1, hits.size(),
|
||||
"V171 必须恰好一个迁移文件,实际 " + hits.size() + " 个(0=唯一键还没落盘;2=撞号,Flyway 启动即失败)");
|
||||
return hits.get(0);
|
||||
}
|
||||
|
||||
private static String rawSql() throws IOException {
|
||||
return Files.readString(migration());
|
||||
}
|
||||
|
||||
private static String executable() throws IOException {
|
||||
return normalize(stripComments(rawSql()));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 取号
|
||||
|
||||
@Test
|
||||
void versionIsSeventyOneAndHeaderTitleMatchesTheFileName() throws IOException {
|
||||
Matcher m = VERSION_PREFIX.matcher(migration().getFileName().toString());
|
||||
assertTrue(m.find(), "文件名应能抽出整数版本:" + migration().getFileName());
|
||||
assertEquals(171, Integer.parseInt(m.group(1)),
|
||||
"本迁移必须是 V171:生产 flyway_schema_history 今天(10-24)实查已应用到 170(头注释第 3 段)。"
|
||||
+ "把号往回填会被 Flyway 当 ignored migration 静默跳过,各环境 schema 悄悄漂移");
|
||||
assertTrue(migration().getFileName().toString().matches("^V171__[A-Za-z0-9_.-]+\\.sql$"),
|
||||
"命名不合规:" + migration().getFileName());
|
||||
// 头注释标题必须与文件名同号:V170 就留了一句"标题仍写 V168"的欠账(inventory §1 尾注)
|
||||
assertTrue(rawSql().contains("迁移 V171__notification_dedupe_key_unique"),
|
||||
"头注释标题与本文件名不同号 ⇒ 复制模板时没回头改,下一路会被标题带偏");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 1. 空串键的语义
|
||||
|
||||
@Test
|
||||
void uniqueKeySitsOnTheNullProjectionNotOnDedupeKey() throws IOException {
|
||||
String sql = executable();
|
||||
assertTrue(sql.contains("GENERATED ALWAYS AS (NULLIF(`dedupe_key`, '''')) STORED"),
|
||||
"投影列写法被改动:空串必须映射成 NULL,否则唯一键会杀掉「不去重」那一类通知\n实际:" + sql);
|
||||
assertTrue(Pattern.compile("ADD UNIQUE KEY `ux_dedupe_key` \\(`dedupe_uk`\\)").matcher(sql).find(),
|
||||
"唯一键必须落在那一列上");
|
||||
assertFalse(Pattern.compile("UNIQUE KEY [^(]*\\(`dedupe_key`\\)").matcher(sql).find(),
|
||||
"直接给 dedupe_key 加唯一键 = 第二条空串键报 1062 ⇒ 一类通知静默消失");
|
||||
assertFalse(sql.contains("DROP INDEX `idx_dedupe`") || sql.contains("DROP KEY `idx_dedupe`"),
|
||||
"idx_dedupe 要留着服务 push 的 WHERE dedupe_key=?,新键服务不了那条形状");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 2. 存量收口
|
||||
|
||||
@Test
|
||||
void collapsesDuplicatesBeforeAddingTheKey() throws IOException {
|
||||
String sql = executable();
|
||||
int deleteAt = sql.indexOf("DELETE n FROM `biz_user_notification` n");
|
||||
int addKeyAt = sql.indexOf("ADD UNIQUE KEY `ux_dedupe_key`");
|
||||
assertTrue(deleteAt >= 0, "没有按键收口存量重复的 DELETE ⇒ 有重复时 ADD UNIQUE 报 1062,两台 java 起不来");
|
||||
assertTrue(addKeyAt > deleteAt, "顺序锁死:收口必须排在加唯一键之前");
|
||||
assertTrue(sql.contains("WHERE dedupe_key <> ''"),
|
||||
"收口不许碰空串键(NULLIF 之后它们本来就能共存,删了就是无故丢通知)");
|
||||
assertTrue(sql.contains("MIN(id) AS keep_id") && sql.contains("n.id > dup.keep_id"),
|
||||
"保留行的判据必须与服务查重读取口径一致(orderByAsc(id) ... limit 1)");
|
||||
assertTrue(sql.contains("HAVING COUNT(*) > 1"), "只收口真重复,别写成一刀切");
|
||||
assertEquals(1, occurrences(sql, "DELETE n FROM `biz_user_notification`"), "本笔只该有一条 DELETE");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3. 可重跑与边界
|
||||
|
||||
@Test
|
||||
void bothAlterAreGuardedAndReplayable() throws IOException {
|
||||
String sql = executable();
|
||||
assertEquals(2, occurrences(sql, "information_schema."), "两条 DDL 各查一次元数据表");
|
||||
assertEquals(2, occurrences(sql, "PREPARE stmt FROM"), "两条 DDL 各走一次 PREPARE");
|
||||
assertEquals(2, occurrences(sql, "DEALLOCATE PREPARE"), "PREPARE 不 DEALLOCATE 会串到下一条");
|
||||
assertTrue(sql.contains("already exists, skipped"), "命中已有对象时必须回一句可读的 note,而不是裸报 1061/1060");
|
||||
assertFalse(sql.toUpperCase().contains("ALGORITHM = INSTANT") || sql.toUpperCase().contains("ALGORITHM=INSTANT"),
|
||||
"STORED 生成列不支持 INSTANT,钉了会 1846 把迁移顶死(头注释第 3 段写明为什么不钉)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void touchesOnlyTheNotificationTableAndDropsNothing() throws IOException {
|
||||
String sql = executable();
|
||||
List<String> tables = Pattern.compile("(?:FROM|TABLE|JOIN)\\s+`?([a-z_]+)`?")
|
||||
.matcher(sql).results()
|
||||
.map(r -> r.group(1))
|
||||
.filter(t -> !"information_schema".equals(t) && !"DUAL".equalsIgnoreCase(t))
|
||||
.distinct().toList();
|
||||
assertEquals(List.of("biz_user_notification"), tables, "射程外的表:" + tables);
|
||||
assertFalse(sql.toUpperCase().contains("DROP TABLE"), "不许删表");
|
||||
assertFalse(sql.toUpperCase().contains("DROP INDEX"), "不许删索引(回滚是人工补丁,写在头注释第 8 段)");
|
||||
assertFalse(sql.toUpperCase().contains("TRUNCATE"), "整表清空会把已读未读一起抹掉");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具(沿用 V144 那份)
|
||||
|
||||
private static int occurrences(String haystack, String needle) {
|
||||
int n = 0, from = 0;
|
||||
while ((from = haystack.indexOf(needle, from)) >= 0) {
|
||||
n++;
|
||||
from += needle.length();
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
private static String stripComments(String sql) {
|
||||
StringBuilder out = new StringBuilder(sql.length());
|
||||
int i = 0;
|
||||
while (i < sql.length()) {
|
||||
char c = sql.charAt(i);
|
||||
if (c == '\'') {
|
||||
int end = i + 1;
|
||||
while (end < sql.length()) {
|
||||
if (sql.charAt(end) == '\'') {
|
||||
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
|
||||
end += 2;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
end++;
|
||||
}
|
||||
out.append(sql, i, Math.min(end + 1, sql.length()));
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
|
||||
while (i < sql.length() && sql.charAt(i) != '\n') {
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
i = end < 0 ? sql.length() : end + 2;
|
||||
continue;
|
||||
}
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String normalize(String sql) {
|
||||
return sql.replaceAll("\\s+", " ").trim();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user