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:
2026-10-24 18:22:14 +08:00
parent dff0658b32
commit eb46a5abc7
4 changed files with 402 additions and 0 deletions
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.notification.model.vo.NotificationRefVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
@@ -161,6 +162,17 @@ public class NotificationService {
try {
userNotificationMapper.insert(row);
} catch (Exception ex) {
// ux_dedupe_key(V171)兜的就是上面那次 SELECT-then-INSERT 的竞态窗口:两个实例同轮
// 扫到同一条异常、各自查无同键、各插一行。这一支不许并入下面的 warn——同键已有行
// 就是去重命中,与 existsByDedupeKey 那一支语义一字不差,念成"落库失败"会把一次
// 正常收敛报成数据库故障,值班会去查一台其实好好的库。
// 写成分诊而不是再加一个 catch(DuplicateKeyException):catch 普查棘轮的
// STRICT_TOTAL 已钉在 1004 满格上,多一块就得重钉基线(见 CatchSilenceRatchetTest)。
if (ex instanceof DuplicateKeyException) {
log.info("[notification] 去重命中(竞态由唯一键兜住)userId={} audience={} scene={} dedupeKey={}",
userId, normalizedAudience, normalizedScene, key);
return false;
}
// 通知失败不阻断业务主流程(巡检/扫描 job 的调用方也不应因此中断)
log.warn("[notification] 推送落库失败 userId={} scene={} err={}", userId, scene, ex.getMessage(), ex);
return false;
@@ -0,0 +1,105 @@
-- =============================================================
-- 迁移 V171__notification_dedupe_key_unique
-- 模板:docs/flyway-migration-template.md
-- 立账:ops 仓 docs/audit/BACKLOG.md 的 B30(2026-10-24 通知面消重取证)
--
-- 1. 变更目的:给 biz_user_notification 的去重键补**唯一约束**。
-- 现状:NotificationService.push() 的查重是 SELECT-then-INSERT(先 existsByDedupeKey
-- 再 insert),表上只有非唯一的 idx_dedupe(V116:19)。双节点在同一轮扫描里各自
-- "查无同键"然后各插一行 ⇒ 同一条异常落两条。今天没踩到(2026-10-24 16:5x 全表实查
-- GROUP BY dedupe_key HAVING COUNT(*)>1 = 0 行),但这条洞是靠 job 锁兜着的
-- (NotificationScanScheduler 锁 TTL 5 分钟、CostGuardScheduler 2 分钟),而扫描时长
-- 不封顶——锁失效的窗口就是重复落库的窗口。唯一约束把它变成数据库层的不变量,
-- 插入侧的竞态由 DuplicateKeyException 收口(同批 Java 改动)。
--
-- 2. 为什么是「STORED 生成列 + 普通唯一键」,而不是直接给 dedupe_key 加唯一键、
-- 也不是表达式唯一索引:
-- - 直接加唯一键会坏事:dedupe_key 允许空串,而**空串按设计就是不参与去重**
-- (NotificationService 的 javadoc:dedupeKey 为空则不去重;V116:14 该列
-- NOT NULL DEFAULT '')。第二行空串会报 1062,把"不去重的那类通知"整条丢掉。
-- - NULLIF(dedupe_key,'') 把空串映射成 NULL 正好绕开(唯一索引允许多个 NULL)。
-- - 表达式索引(ADD UNIQUE INDEX ux ((NULLIF(...))))在线 DDL 手册里没有独立条目,
-- 只有"creating or adding a secondary index"那一行;生成列 + 普通唯一键是最标准、
-- 也最容易被下一路读懂的写法。
--
-- 3. 读数(2026-10-24 16:5x 主机A 业务库只读实查,不是估的):
-- biz_user_notification = 1,675 行(最早一行的 created_at = 2026-10-17 04:09:46)
-- dedupe_key = '' 的行 = 0 行(今天没有生产者在传空键,但这一支语义必须留着)
-- 重复键 = 0 组
-- MySQL = 8.4.8
-- 已应用的最大整数版本 = 170(163–167 与 170 今天实查确认已落库 ⇒ 本笔取 171;
-- docs/migration-inventory.md §1 那句"六支未落库"是旧快照,已随本笔更正)
-- 表 1,675 行 ⇒ ADD COLUMN(STORED 生成列必然重建表)代价可忽略。**故意不钉
-- ALGORITHM=INSTANT**:STORED 生成列不支持 INSTANT,钉了会 1846 直接把迁移顶死。
--
-- 4. 第 1 段那条 DELETE 为什么必要、且不算删数据:
-- 存量有重复时 ADD UNIQUE 直接 1062 ⇒ 整个迁移失败 ⇒ 两台 java 起不来。收口判据不是
-- 拍的:应用的查重读取路径就是 `orderByAsc(id) ... limit 1`(NotificationService
-- .selectByDedupeKey),同键里 MIN(id) 那一行**本来已是唯一被看见的行**,比它大的同键行
-- 从那一刻起就是死行——push 看不到它,_prod_watch 的"独立事件数"按去掉末段去重键计数
-- 也只算一条。今天命中 0 行;这条是给"锁失效窗口真撞了一次"的未来准备的。
-- ⚠ 删的是重复副本,每个键至少保留一行。
--
-- 5. 锁表风险:低。一条走 idx_dedupe 的 DELETE(今天命中 0 行)+ 一次 1,675 行的表重建。
-- 不碰 biz_file_task、不碰 biz_task_file_job 这些锁热点表。
--
-- 6. 验证 SQL(迁移后人工跑):
-- SHOW INDEX FROM `biz_user_notification` WHERE Key_name IN ('idx_dedupe','ux_dedupe_key');
-- -> 期望 ux_dedupe_key 的 Non_unique=0、Column_name=dedupe_uk,idx_dedupe 原样保留
-- (push 的 WHERE dedupe_key=? 走的仍是它,新键服务不了那条形状)
-- SELECT dedupe_key, COUNT(*) c FROM `biz_user_notification`
-- WHERE dedupe_key<>'' GROUP BY 1 HAVING c>1; -> 期望 0 行
-- INSERT INTO biz_user_notification (user_id,audience,scene,level,title,content,dedupe_key,created_at)
-- VALUES (1,'admin','x','warning','t','c','' ,NOW()),(2,'admin','x','warning','t','c','' ,NOW());
-- -> 期望两条都成功(空串不参与去重);人工跑完删掉这两行
--
-- 7. 可重跑性:DDL 不进事务。若 ADD COLUMN 落了而 ADD UNIQUE 失败,repair 重跑时第 2 段
-- 必须只补索引 ⇒ 两条 DDL 各自查 information_schema 再 PREPARE(首例 V143 全文件、
-- V145 的索引段、V162 的加列段)。
--
-- 8. 回滚(人工补丁,写成注释以免被 Flyway 当迁移执行):
-- ALTER TABLE `biz_user_notification` DROP INDEX `ux_dedupe_key`;
-- ALTER TABLE `biz_user_notification` DROP COLUMN `dedupe_uk`;
-- 只回滚 jar 不需要 DROP:旧 jar 的实体没有这一列,INSERT 不写它,唯一键继续生效,
-- 行为退化成"竞态时插入报错、被旧的 catch(Exception) 吞成推送失败"。
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 收口重复键:每键保留 MIN(id)(与 push 的查重读取口径同一个"第一行") ----------
DELETE n FROM `biz_user_notification` n
JOIN (
SELECT dedupe_key, MIN(id) AS keep_id FROM (
SELECT id, dedupe_key FROM `biz_user_notification` WHERE dedupe_key <> ''
) cur
GROUP BY dedupe_key
HAVING COUNT(*) > 1
) dup ON n.dedupe_key = dup.dedupe_key AND n.id > dup.keep_id;
-- ---------- 2. 生成列:空串→NULL(不参与唯一性),dedupe_key 本身的语义一个字节不动 ----------
SET @has_col = (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name
AND TABLE_NAME = 'biz_user_notification'
AND COLUMN_NAME = 'dedupe_uk'
);
SET @ddl_col = IF(@has_col = 0,
'ALTER TABLE `biz_user_notification` ADD COLUMN `dedupe_uk` VARCHAR(160) GENERATED ALWAYS AS (NULLIF(`dedupe_key`, '''')) STORED',
'SELECT ''biz_user_notification.dedupe_uk already exists, skipped'' AS note');
PREPARE stmt FROM @ddl_col;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 3. 唯一键(NULL 行不受约束,所以"空串=不去重"这条既有设计不被破坏) ----------
SET @has_idx = (
SELECT COUNT(*) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name
AND TABLE_NAME = 'biz_user_notification'
AND INDEX_NAME = 'ux_dedupe_key'
);
SET @ddl_idx = IF(@has_idx = 0,
'ALTER TABLE `biz_user_notification` ADD UNIQUE KEY `ux_dedupe_key` (`dedupe_uk`)',
'SELECT ''biz_user_notification.ux_dedupe_key already exists, skipped'' AS note');
PREPARE stmt FROM @ddl_idx;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -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();
}
}
@@ -1,5 +1,8 @@
package com.nanri.aiimage.modules.notification.service;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@@ -13,6 +16,9 @@ import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.QueryTimeoutException;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -461,6 +467,83 @@ class NotificationServiceTest {
assertThat(captor.getAllValues().get(0).getSqlSegment()).contains("id =");
}
/**
* V171 唯一键的插入侧:查重没命中但被唯一键拦下=竞态窗口里"同键已有人插过",
* 语义与 {@code pushSkipsWhenDedupeKeyExists} 一字不差,必须念成去重命中、
* 不许落进"推送落库失败"那条 warn(把一次正常收敛报成数据库故障,值班就会去查库)。
*/
@Test
void pushTreatsUniqueKeyRaceAsDedupeHitNotAsFailure() {
when(mapper.selectOne(any())).thenReturn(null);
when(mapper.insert(any(UserNotificationEntity.class)))
.thenThrow(new DuplicateKeyException("Duplicate entry for key 'ux_dedupe_key'"));
ListAppender<ILoggingEvent> captured = captureLogs();
try {
assertThat(service.push(7L, NotificationService.AUDIENCE_ADMIN,
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_ERROR,
"代理欠费", "余额不足", "secret_balance:7:proxy:20261024:1")).isFalse();
} finally {
releaseLogs(captured);
}
List<String> lines = captured.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
assertThat(lines).anyMatch(l -> l.contains("去重命中") && l.contains("竞态"));
assertThat(lines).as("唯一键拦下的重复插入被念成落库失败 ⇒ 值班会去查一台其实正常的库")
.noneMatch(l -> l.contains("推送落库失败"));
}
/**
* 非零对照:别的数据库故障仍然必须走 warn。把上一条的 DuplicateKeyException 换成
* 其它 DataAccessException 若也进"去重命中",上面那条断言就会失去鉴别力。
*/
@Test
void otherInsertFailuresStillWarn() {
when(mapper.selectOne(any())).thenReturn(null);
when(mapper.insert(any(UserNotificationEntity.class)))
.thenThrow(new QueryTimeoutException("lock wait timeout"));
ListAppender<ILoggingEvent> captured = captureLogs();
try {
assertThat(service.push(7L, NotificationService.AUDIENCE_ADMIN,
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_ERROR,
"代理欠费", "余额不足", "secret_balance:7:proxy:20261024:2")).isFalse();
} finally {
releaseLogs(captured);
}
List<String> lines = captured.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
assertThat(lines).anyMatch(l -> l.contains("推送落库失败"));
assertThat(lines).noneMatch(l -> l.contains("去重命中"));
}
/**
* 空串键是"按设计不参与去重"那一支(V171 用 NULLIF 把它映射成 NULL 正是为了保住它):
* 不许查 dedupe、也不许因为唯一键丢掉第二条。
*/
@Test
void emptyDedupeKeyNeverConsultsTheLookupAndStillInserts() {
when(mapper.insert(any(UserNotificationEntity.class))).thenReturn(1);
assertThat(service.push(7L, NotificationService.AUDIENCE_USER,
NotificationService.SCENE_SYSTEM, NotificationService.LEVEL_INFO, "t", "c", "")).isTrue();
assertThat(service.push(8L, NotificationService.AUDIENCE_USER,
NotificationService.SCENE_SYSTEM, NotificationService.LEVEL_INFO, "t", "c", "")).isTrue();
verify(mapper, never()).selectOne(any());
verify(mapper, times(2)).insert(any(UserNotificationEntity.class));
}
private ListAppender<ILoggingEvent> captureLogs() {
Logger logger = (Logger) LoggerFactory.getLogger(NotificationService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
return appender;
}
private void releaseLogs(ListAppender<ILoggingEvent> appender) {
((Logger) LoggerFactory.getLogger(NotificationService.class)).detachAppender(appender);
}
private void assertScopedTo(LambdaQueryWrapper<UserNotificationEntity> wrapper, long userId, String audience) {
assertThat(wrapper.getSqlSegment()).contains("user_id").contains("audience");
assertThat(wrapper.getParamNameValuePairs().values()).contains(userId, audience);