降本三条(10-11 现网取证):外观同请求图片去重 + 货源合规合批 + LLM token 计量落库

取证基线(库侧 biz_user_secret_usage_daily,10-01~10-11 实测 12,704 / 4,134 / 15,135 次):
外观 24h 全量 831 条请求逐条 json 解析,564 条带图共投 2,693 张、去重只剩 1,465 张
⇒ 45.6% 是同一张图在同一次请求里的副本;重试占比只有 0.24%(attempt 829/2/0),
所以省钱的口子在图片副本,不在重试。货源 4,134 次里 4,096 次集中在 10-10/10-11 两天,
类目已合批(10-02)而合规与图比仍逐行 ⇒ 合规是该模块最后一步逐行 LLM 调用。

1) 外观:每张不同的图只随请求发一份,正文附「图j=序号1、2…」对照表;每个序号仍各自
   出一份 status/reason(省副本,不省判定,与 10-10「同组兄弟行也要都检测」同口径)。
   归一化 URL 只当去重的键,发出去的还是行里那条原始串。应急回退:
   llm-appearance-batch-size=1 即退回逐行,无需改码。
2) 货源:新键 llm-conform-batch-size=10(设 1 退回逐行)。前置条件是分类预计算存在,
   否则整条不生效——避免同一行的类目被算两遍(两遍=多扣用户一次);缺编号行与整块
   失败都逐行补检,并有一支 A/B 差分管住合批与逐行写回行的三字段+状态相等。
3) V157 给 biz_user_secret_usage_daily 加 prompt_tokens/completion_tokens,两个 client 收下
   网关 usage。计次与 token 分两条语句:计次发生在发请求之前(含重试,请求没回来也算
   一次),token 只在响应回来后有读数;网关没回 usage 就一条不写——0 会被读成"实测为 0"。

护栏记账:新 mapper 语句 addTokens 两处一起点名(SqlLayeringConventionTest 分母 97→98 +
MigratedSqlEquivalenceTest.NOT_MIGRATED);批量路径的 catch 不新增一处——把分类那一路的
"整块失败→逐行补检"抽成 batchAttempt/fallbackSingleRows 共用,静默 catch 棘轮四格一格没放宽。
顺带修掉 AppearancePatentResultRowDto 上一句已经过期的 javadoc(还写着兄弟行复用代表行结论)。

证据:后端全量 4288 例 0 红(本批 +24 例:去重 7 / token 4 / 合规合批 7 / 用量服务 6)。
变异自证 3/3 全杀:取消去重、摘掉 usage 落库、断掉合规合批,分别让对应用例判红;
两个受试文件按注入前字节还原,sha 复算一致。
This commit is contained in:
2026-10-11 23:52:19 +08:00
parent c4d2349cda
commit b0829db81e
17 changed files with 1273 additions and 54 deletions
@@ -178,6 +178,17 @@ public class SimilarAsinProperties {
* 设 0/1 回退逐行旧行为。
*/
private int llmCategoryBatchSize = 10;
/**
* 批量合规判定的行数(2026-10-11):>1 且批内多行时,合规判定按该行数分块、每块一次 LLM 调用。
* 省的是**往返**,不是判定:每件商品的 is_conform/reason/category 仍然各出一份(与 2026-09-27
* 类目两级合并同型)。缺编号/坏编号的行与整块调用失败的行回退逐行单调用,行级失败语义不变。
* 设 0/1 回退逐行旧行为。
*
* <p>前置条件:它读的是 {@code llmCategoryBatchSize} 那次预计算出来的逐行类目路径,
* 所以批量分类被关掉(阈值 ≤1)时这一路自动不生效 —— 不是配置写错,是为了避免
* 同一行的类目被算两遍(两遍就等于多扣用户一次)。
*/
private int llmConformBatchSize = 10;
/**
* 首次尝试读超时(毫秒):上游偶发单请求不应答,首查用更短预算快速失败后重试。
* 与外观专利同口径:那边一批 5 张图后单次耗时按倍数涨,60s 会误杀正常慢响应,
@@ -107,11 +107,13 @@ public class AppearancePatentLlmClient {
private static final String APPEARANCE_BATCH_ENVELOPE =
"\n\n### 批量输入输出协议\n"
+ "本次同时提交多件商品:用户消息先给出「序号<TAB>产品描述」清单,随后按同样的序号依次附上各件商品图片。"
+ "本次同时提交多件商品:用户消息先给出「序号<TAB>产品描述」清单,随后附上**去重后**的商品图片"
+ "(同一张图只出现一次),并在文末「图片对照」里逐张写明它对应哪些序号(一张图可服务多件商品)。"
+ "必须逐件独立判定,严禁把某一件的结论写到另一件上。\n"
+ "只输出一个 JSON 对象:{\"items\":[{\"i\":1,\"appearance_status\":\"侵权\",\"appearance_reason\":\"...\"}]}\n"
+ "* i=该件商品的序号,每件恰好一项,不得漏项、不得凭空增加项。\n"
+ "* appearance_status / appearance_reason=按上述规则对该件商品图片给出的判定。\n"
+ "* appearance_status / appearance_reason=按上述规则对该件商品**所对应的那张图**给出的判定;"
+ "共用同一张图的多个序号仍要各出一项,理由要落到该序号自己的描述上。\n"
+ "* 除 JSON 外不要输出任何内容。";
private static final String NO_KEYWORD = "无";
@@ -457,17 +459,34 @@ public class AppearancePatentLlmClient {
String prompt,
String apiKey) throws Exception {
List<String> lineTexts = new ArrayList<>(chunk.size());
List<String> images = new ArrayList<>(chunk.size());
// 同批里同一张图会被多行共用(兄弟行补空取自同一条主图,2026-10-10 起又是逐行送检),
// 现网 24h 全量实测:一次请求内投了 2,693 张、去重只剩 1,465 张,45.6% 是同一张图的副本。
// 所以每张不同的图只随请求发一份,行与图的对应关系写在正文「图片对照」里 ——
// 省的是图片 token,不是判定:每个序号仍然要各自出一份 status/reason。
Map<String, String> rawByKey = new LinkedHashMap<>();
Map<String, String> rowsByKey = new LinkedHashMap<>();
for (int index : chunk) {
AppearancePatentResultRowDto row = rows.get(index);
lineTexts.add(singleLine("产品描述:" + nonBlank(row.getTitle(), "") + nonBlank(row.getSku(), "")));
images.add(row.getUrl());
// 归一化只当去重的键;发出去的仍是行里那条原始 URL(口径不许被 normalize 顺手改掉)。
String key = normalize(row.getUrl());
rawByKey.putIfAbsent(key, row.getUrl());
rowsByKey.merge(key, String.valueOf(positionOf(index, chunk)),
(oldValue, newValue) -> oldValue + "、" + newValue);
}
List<String> images = new ArrayList<>(rawByKey.values());
StringBuilder legend = new StringBuilder();
int imageIndex = 0;
for (String positions : rowsByKey.values()) {
legend.append("\n图").append(++imageIndex).append("=序号").append(positions);
}
String userText = "本次提交 " + chunk.size() + " 件商品,先给出「序号<TAB>产品描述」清单,"
+ "随后按同样的序号依次附上各件商品图片:\n" + indexedLines(lineTexts);
+ "随后附上本批**去重后**的商品图片共 " + images.size() + " 张(一张图可能被多件商品共用,"
+ "共用的序号见文末「图片对照」)。每件商品都必须按它对应的那张图**单独**给出一份判定。\n"
+ indexedLines(lineTexts) + "\n图片对照:" + legend;
Map<Integer, AppearanceJudgement> judgements = new LinkedHashMap<>();
String content = invokeChat(properties.getAppearanceModel(), appearanceSystemPrompt(prompt),
userText, images, apiKey, "json_object");
Map<Integer, AppearanceJudgement> judgements = new LinkedHashMap<>();
for (Map.Entry<Integer, JsonNode> entry : parseIndexedItems(content).entrySet()) {
int position = entry.getKey() - 1;
if (position < 0 || position >= chunk.size()) {
@@ -484,6 +503,11 @@ public class AppearancePatentLlmClient {
return judgements;
}
/** 该行在本批内的序号(1 基,与发给模型的「序号<TAB>…」对齐)。 */
private static int positionOf(int index, List<Integer> chunk) {
return chunk.indexOf(index) + 1;
}
private String appearanceSystemPrompt(String prompt) {
String system = APPEARANCE_SYSTEM_PROMPT;
if (prompt != null && !prompt.isBlank()) {
@@ -650,6 +674,7 @@ public class AppearancePatentLlmClient {
String message = text(errorNode.path("message"));
throw new IllegalStateException(firstNonBlank(message, "LLM error"));
}
recordTokenUsage(root);
JsonNode contentNode = root.path("choices").path(0).path("message").path("content");
String content = text(contentNode);
if (content == null || content.isBlank()) {
@@ -1246,6 +1271,23 @@ public class AppearancePatentLlmClient {
userSecretUsageService.record(context.userId(), UserSecretModule.APPEARANCE_PATENT.key(), 1);
}
/**
* 收下网关响应的 token 读数(V157)。计次已在发请求前记过,这里只补读数。
* 网关没回 usage 就整条跳过 —— 不许写 0 冒充「实测消耗为 0」,那种行以后会被拿去算成本。
*/
private void recordTokenUsage(JsonNode root) {
JsonNode usage = root.path("usage");
if (usage.isMissingNode() || usage.isNull()) {
return;
}
SecretUsageContext.Context context = SecretUsageContext.current();
if (context == null) {
return;
}
userSecretUsageService.recordTokens(context.userId(), UserSecretModule.APPEARANCE_PATENT.key(),
usage.path("prompt_tokens").asLong(0L), usage.path("completion_tokens").asLong(0L));
}
private void sleepQuietly(long delayMillis) {
try {
Thread.sleep(delayMillis);
@@ -20,7 +20,7 @@ public class AppearancePatentResultRowDto {
@Schema(description = "主数据分组 key。Python 应从解析结果原样透传,用于把同组子行补回。", example = "uploads/20260426/appearance_patent_17.xlsx::2@2")
private String groupKey;
@Schema(description = "Excel 中的 id。代表行通常是整数 id 或 n_1,例如 2_1;最终生成 xlsx 时,2_2、2_3 会复用同组 2_1 的 LLM 检测结果。", example = "2_1")
@Schema(description = "Excel 中的 id。代表行通常是整数 id 或 n_1,例如 2_1;2_2、2_3 这些同组兄弟行也各自送检、各自出结论(2026-10-10 撤掉了「复用代表行结论」的摊派:现网实测它造成两到五成行三列全空)。", example = "2_1")
private String id;
@Schema(description = "亚马逊 ASIN。后端会统一按大写处理和匹配。", example = "B0CJ8SNXXV")
@@ -141,6 +141,7 @@ public class SimilarAsinLlmClient {
String message = text(errorNode.path("message"));
throw new IllegalStateException(firstNonBlank(message, "LLM error"));
}
recordTokenUsage(root);
JsonNode contentNode = root.path("choices").path(0).path("message").path("content");
String content = text(contentNode);
if (content == null || content.isBlank()) {
@@ -311,6 +312,23 @@ public class SimilarAsinLlmClient {
userSecretUsageService.record(context.userId(), UserSecretModule.SIMILAR_ASIN.key(), 1);
}
/**
* 收下网关响应的 token 读数(V157)。计次已在发请求前记过,这里只补读数。
* 网关没回 usage 就整条跳过 —— 不许写 0 冒充「实测消耗为 0」,那种行以后会被拿去算成本。
*/
private void recordTokenUsage(JsonNode root) {
JsonNode usage = root.path("usage");
if (usage.isMissingNode() || usage.isNull()) {
return;
}
SecretUsageContext.Context context = SecretUsageContext.current();
if (context == null) {
return;
}
userSecretUsageService.recordTokens(context.userId(), UserSecretModule.SIMILAR_ASIN.key(),
usage.path("prompt_tokens").asLong(0L), usage.path("completion_tokens").asLong(0L));
}
/**
* 按尝试次数取客户端:第 1 次用「首次尝试超时」(快速失败,单次挂死代价更小),
* 重试用完整读超时,避免把慢但成功的正常调用误杀(实测成功调用 p99≈34s)。
@@ -24,6 +24,7 @@ import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -174,6 +175,22 @@ public class SimilarAsinLlmService {
+ "* 严禁伪造类目名称,first/second 必须逐字来自候选列表。输出必须严格遵循 JSON 语法。";
private static final String USER_TEXT_CONFORM =
"标题:%s\nSKU:%s\n违规类目产品:一级类目:%s ,二级类目:%s,三级类目:%s";
/**
* 批量合规的输出契约追加段(2026-10-11):合规是货源链路里唯一还逐行发的那一步
* (10-10 起该模块一天 2,366 次调用,其中约一半是合规)。合并成"一批一次请求"省的是**往返**,
* 每件商品的 is_conform/reason/category 仍然各出一份 ⇒ 判定语义与单件模式完全一致。
* 类目上下文必须逐件带着:违规类目是按行匹配的,共用一份会把 A 行的违规判到 B 行上。
*/
private static final String CONFORM_BATCH_ENVELOPE =
"\n\n# 批量模式(本次输入包含多件待判定商品)\n"
+ "输入按编号 [1]、[2]… 列出多件商品,每件**自带**它自己的违规类目(一级/二级/三级)。"
+ "对每件商品**分别**按上述规则判定,禁止遗漏编号、禁止把多件商品合并成一条。\n"
+ "只输出一个 JSON 对象:{\"items\":[{\"i\":1,\"asin\":\"…\",\"is_conform\":\"符合\","
+ "\"reason\":\"无\",\"category\":\"一级->二级->三级\"}]}\n"
+ "* i=商品编号;asin/is_conform/reason/category=按上述规则对该件商品的判定,取值域与单件模式一致。\n"
+ "* **严禁**把某一件的理由或类目写到另一件上:category 必须由该行自己的标题/SKU/违规类目推出来。\n"
+ "* 输出必须严格遵循 JSON 语法。";
private static final String USER_TEXT_COMPARE = "ASIN:%s\n所属类目:%s\n产品信息:%s";
private final SimilarAsinLlmClient llmClient;
@@ -216,6 +233,8 @@ public class SimilarAsinLlmService {
// 批量分类预计算:树文本整批只随一次请求发送(llmCategoryBatchSize>1 且多行时启用),
// 关闭或单行时为 null,走逐行调用旧路径。见 matchCategoryPathsBatched。
CategoryPrepass prepass = categorySwitch ? matchCategoryPathsBatched(rows, categoryTree, apiKey) : null;
// 合规批量预计算紧跟在分类预计算之后:它要用的逐行违规类目上下文就是分类预计算的产物。
ConformPrepass conformPrepass = checkConformsBatched(rows, prepass, categoryTree, prompt, apiKey);
// 行级处理跑在 worker 线程:把「当前任务归属用户」快照带过去,供 LLM 请求计次
SecretUsageContext.Context usageContext = SecretUsageContext.snapshot();
List<CompletableFuture<SimilarAsinResultRowDto>> futures = new ArrayList<>(rows.size());
@@ -226,7 +245,8 @@ public class SimilarAsinLlmService {
try {
concurrency.acquire();
try {
return inspectRow(row, rowIndex, prepass, prompt, apiKey, imgSwitch, categorySwitch, categoryTree);
return inspectRow(row, rowIndex, prepass, conformPrepass, prompt, apiKey,
imgSwitch, categorySwitch, categoryTree);
} finally {
concurrency.release();
}
@@ -252,6 +272,7 @@ public class SimilarAsinLlmService {
private SimilarAsinResultRowDto inspectRow(SimilarAsinResultRowDto source,
int rowIndex,
CategoryPrepass prepass,
ConformPrepass conformPrepass,
String prompt,
String apiKey,
boolean imgSwitch,
@@ -259,7 +280,7 @@ public class SimilarAsinLlmService {
CategoryTree categoryTree) {
SimilarAsinResultRowDto row = copyRow(source);
try {
inspectRowInternal(row, rowIndex, prepass, prompt, apiKey, imgSwitch, categorySwitch, categoryTree);
inspectRowInternal(row, rowIndex, prepass, conformPrepass, prompt, apiKey, imgSwitch, categorySwitch, categoryTree);
return row;
} catch (Exception ex) {
log.warn("[similar-asin][llm] row failed asin={} title={} err={}",
@@ -271,6 +292,7 @@ public class SimilarAsinLlmService {
private void inspectRowInternal(SimilarAsinResultRowDto row,
int rowIndex,
CategoryPrepass prepass,
ConformPrepass conformPrepass,
String prompt,
String apiKey,
boolean imgSwitch,
@@ -297,7 +319,8 @@ public class SimilarAsinLlmService {
: categoryTree.childrenOf(second.id());
// --- 3. 合规检查(1570640:总是执行)---
boolean conform = checkConform(row, first, second, thirdCandidates, prompt, apiKey);
boolean conform = conformForRow(rowIndex, conformPrepass, row, first, second, thirdCandidates,
prompt, apiKey);
// --- 4. 不符合 / 无 alibaba / img_switch=false:只回填合规结果(139255 true 分支 → 1398750)---
if (!conform || row.getAlibaba().isEmpty() || !imgSwitch) {
@@ -442,20 +465,44 @@ public class SimilarAsinLlmService {
return new CategoryPrepass(paths, errors);
}
/** 批量调用体:可能抛,由 {@link #batchAttempt} 统一收口。 */
private interface BatchAttempt {
void run() throws Exception;
}
/** 逐行补检的单行调用体:允许抛受检异常,存进 errors 的是原异常本体(不是包装壳)。 */
private interface SingleRowCall<T> {
T run(int rowIndex) throws Exception;
}
/**
* 一批一次的调用出口:整块失败只记一条 warn 并立刻逐行补检,异常不外抛
* (行级失败语义留给补检那一步判,与 2026-10-02 分类那一路逐字同形)。
* <p>分类与合规共用这一处 catch,是为了让「异常到此为止」的总数不随批量路径增加而变宽。
*/
private void batchAttempt(String label, List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
BatchAttempt attempt, Runnable fallback) {
try {
attempt.run();
} catch (Exception ex) {
log.warn("[similar-asin][llm] {} batch failed rows={} firstAsin={} err={} → 整块回退单行",
label, chunk.size(), abbreviate(rows.get(chunk.get(0)).getAsin(), 40), failureMessage(ex));
fallback.run();
}
}
private void matchCategoryChunk(List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
CategoryTree tree, String apiKey,
Map<Integer, CategoryPath> paths, Map<Integer, Exception> errors) {
try {
String content = llmClient.invokeChat(properties.getLlmCategoryModel(),
SYSTEM_CATEGORY + CATEGORY_BATCH_ENVELOPE,
buildCategoryBatchUserText(rows, chunk, tree), apiKey);
JsonNode root = llmClient.parseJsonContent(content);
resolveCategoryBatchItems(rows, chunk, root, tree, apiKey, paths, errors);
} catch (Exception ex) {
log.warn("[similar-asin][llm] category batch failed rows={} firstAsin={} err={} → 整块回退单行",
chunk.size(), abbreviate(rows.get(chunk.get(0)).getAsin(), 40), failureMessage(ex));
fallbackCategorySingleRows(rows, chunk, tree, apiKey, paths, errors);
}
batchAttempt("category", rows, chunk,
() -> {
String content = llmClient.invokeChat(properties.getLlmCategoryModel(),
SYSTEM_CATEGORY + CATEGORY_BATCH_ENVELOPE,
buildCategoryBatchUserText(rows, chunk, tree), apiKey);
JsonNode root = llmClient.parseJsonContent(content);
resolveCategoryBatchItems(rows, chunk, root, tree, apiKey, paths, errors);
},
() -> fallbackCategorySingleRows(rows, chunk, tree, apiKey, paths, errors));
}
/**
@@ -500,22 +547,32 @@ public class SimilarAsinLlmService {
return new CategoryPath(first, second == null ? CategoryLevel.none() : second);
}
/** 批量失败的行回退逐行单调用;分类调用本身抛异常时记入 errors(行级失败语义不变)。 */
private void fallbackCategorySingleRows(List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
CategoryTree tree, String apiKey,
Map<Integer, CategoryPath> paths, Map<Integer, Exception> errors) {
/**
* 批量失败的行回退逐行单调用;单行调用本身抛异常时记入 errors(行级失败语义不变)。
* <p>分类与合规共用这一处 catch:批量路径每多一条,"异常到此为止"的出口不应该跟着多一处,
* 否则可读性/静默异常那两把只许减的尺子就得替新代码放宽基线。
*/
private <T> void fallbackSingleRows(List<Integer> chunk, Map<Integer, T> target,
Map<Integer, Exception> errors, SingleRowCall<T> singleCall) {
for (Integer rowIndex : chunk) {
if (paths.containsKey(rowIndex) || errors.containsKey(rowIndex)) {
if (target.containsKey(rowIndex) || errors.containsKey(rowIndex)) {
continue;
}
try {
paths.put(rowIndex, matchCategoryPath(rows.get(rowIndex), tree, apiKey));
target.put(rowIndex, singleCall.run(rowIndex));
} catch (Exception ex) {
errors.put(rowIndex, ex);
}
}
}
private void fallbackCategorySingleRows(List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
CategoryTree tree, String apiKey,
Map<Integer, CategoryPath> paths, Map<Integer, Exception> errors) {
fallbackSingleRows(chunk, paths, errors,
rowIndex -> matchCategoryPath(rows.get(rowIndex), tree, apiKey));
}
/** 每行分类结果取用:优先预计算;回退也失败的行按单行语义抛出 → 行失败。 */
private CategoryPath categoryPathForRow(int rowIndex, CategoryPrepass prepass,
SimilarAsinResultRowDto row, CategoryTree tree,
@@ -583,20 +640,175 @@ public class SimilarAsinLlmService {
List<CategoryLevel> thirdCandidates,
String prompt,
String apiKey) {
ConformVerdict verdict = conformSingleVerdict(row,
new String[]{first.name(), second.name(), formatCandidates(thirdCandidates)}, prompt, apiKey);
applyConformVerdict(row, verdict);
return SimilarAsinLlmClient.isConformYes(verdict.isConform());
}
/** 单件合规调用:与批量路径共用同一个解析出口,避免两条路对同一响应读出不同字段。 */
private ConformVerdict conformSingleVerdict(SimilarAsinResultRowDto row, String[] context,
String prompt, String apiKey) {
String userText = String.format(USER_TEXT_CONFORM,
firstNonBlank(row.getTitle(), row.getAsin()),
normalize(row.getSku()),
first.name(),
second.name(),
formatCandidates(thirdCandidates));
String system = prompt == null || prompt.isBlank() ? SYSTEM_CONFORM : SYSTEM_CONFORM + "\n\n额外要求:" + prompt.trim();
String content = llmClient.invokeChat(properties.getLlmConformModel(), system, userText, apiKey);
context[0],
context[1],
context[2]);
String content = llmClient.invokeChat(properties.getLlmConformModel(),
conformSystemPrompt(prompt), userText, apiKey);
JsonNode root = llmClient.parseJsonContent(content);
String isConform = textOrEmpty(root, "is_conform");
row.setIsConform(isConform);
row.setReason(firstNonBlank(textOrEmpty(root, "reason"), ""));
row.setCategory(firstNonBlank(textOrEmpty(root, "category"), ""));
return SimilarAsinLlmClient.isConformYes(isConform);
return new ConformVerdict(textOrEmpty(root, "is_conform"),
textOrEmpty(root, "reason"), textOrEmpty(root, "category"));
}
private String conformSystemPrompt(String prompt) {
return prompt == null || prompt.isBlank() ? SYSTEM_CONFORM
: SYSTEM_CONFORM + "\n\n额外要求:" + prompt.trim();
}
/** 合规三字段回填行:与批量结果共用,逐行旧路径的写入口径一字未改。 */
private void applyConformVerdict(SimilarAsinResultRowDto row, ConformVerdict verdict) {
row.setIsConform(verdict.isConform());
row.setReason(firstNonBlank(verdict.reason(), ""));
row.setCategory(firstNonBlank(verdict.category(), ""));
}
// --- 批量合规(2026-10-11):合规是货源链路里最后一步逐行发的 LLM 调用,合并省往返不省判定 ---
/** 一件商品的合规读数。 */
private record ConformVerdict(String isConform, String reason, String category) {
}
/** 批量合规预计算的产物:byRow 覆盖拿到结果或单行补检成功的行,errors 是补检也失败的行。 */
private record ConformPrepass(Map<Integer, ConformVerdict> byRow, Map<Integer, Exception> errors) {
}
/**
* 按 {@code llmConformBatchSize} 分块,每块一次 LLM 调用;块内缺编号的行、整块调用失败的行
* 回退逐行单调用(行级失败语义不变)。返回 null 表示本批不启用,调用方走逐行旧路径。
*
* <p>前置条件是分类预计算已存在:每件商品的违规类目上下文取自那次预计算的逐行路径。
* 分类批量被关掉时这里必须返回 null —— 否则要为一行重算一遍类目,等于多扣用户一次。
*/
private ConformPrepass checkConformsBatched(List<SimilarAsinResultRowDto> rows,
CategoryPrepass categoryPrepass,
CategoryTree tree, String prompt, String apiKey) {
int batchSize = Math.max(1, properties.getLlmConformBatchSize());
if (categoryPrepass == null || batchSize <= 1 || rows.size() < 2) {
return null;
}
Map<Integer, String[]> contextByRow = new LinkedHashMap<>();
for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
CategoryPath path = categoryPrepass.paths().get(rowIndex);
if (path == null) {
continue; // 分类没出结果的行不在这里补:它在行内会先按分类缺失抛成行级失败
}
CategoryLevel second = path.second();
contextByRow.put(rowIndex, new String[]{path.first().name(), second.name(),
formatCandidates(isNoMatch(second) ? List.of() : tree.childrenOf(second.id()))});
}
if (contextByRow.size() < 2) {
return null;
}
List<Integer> indexes = new ArrayList<>(contextByRow.keySet());
Semaphore concurrency = new Semaphore(Math.max(1, properties.getLlmRowConcurrency()));
ExecutorService executor = rowExecutor();
SecretUsageContext.Context usageContext = SecretUsageContext.snapshot();
Map<Integer, ConformVerdict> byRow = new ConcurrentHashMap<>();
Map<Integer, Exception> errors = new ConcurrentHashMap<>();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int from = 0; from < indexes.size(); from += batchSize) {
List<Integer> chunk = new ArrayList<>(
indexes.subList(from, Math.min(from + batchSize, indexes.size())));
futures.add(CompletableFuture.supplyAsync(SecretUsageContext.wrap(() -> {
try {
concurrency.acquire();
try {
checkConformChunk(rows, chunk, contextByRow, prompt, apiKey, byRow, errors);
} finally {
concurrency.release();
}
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
throw new IllegalStateException("LLM conform batch interrupted", interruptedException);
}
return null;
}, usageContext), executor));
}
for (CompletableFuture<Void> future : futures) {
future.join(); // checkConformChunk 内部自捕获,join 只会因中断失败
}
return new ConformPrepass(byRow, errors);
}
private void checkConformChunk(List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
Map<Integer, String[]> contextByRow, String prompt, String apiKey,
Map<Integer, ConformVerdict> byRow, Map<Integer, Exception> errors) {
batchAttempt("conform", rows, chunk,
() -> {
String content = llmClient.invokeChat(properties.getLlmConformModel(),
SYSTEM_CONFORM + CONFORM_BATCH_ENVELOPE,
buildConformBatchUserText(rows, chunk, contextByRow), apiKey);
JsonNode root = llmClient.parseJsonContent(content);
JsonNode items = root.path("items");
if (items.isArray()) {
for (JsonNode item : items) {
int i = item.path("i").asInt(-1);
if (i < 1 || i > chunk.size()) {
continue; // 坏编号:交给缺失回退
}
int rowIndex = chunk.get(i - 1);
if (byRow.containsKey(rowIndex)) {
continue; // 重复编号取首个
}
byRow.put(rowIndex, new ConformVerdict(textOrEmpty(item, "is_conform"),
textOrEmpty(item, "reason"), textOrEmpty(item, "category")));
}
}
},
() -> { /* 整块失败:下面那段"缺结果就逐行补检"会覆盖全部行,这里不必另做 */ });
fallbackSingleRows(chunk, byRow, errors,
rowIndex -> conformSingleVerdict(rows.get(rowIndex), contextByRow.get(rowIndex), prompt, apiKey));
}
/** 批量正文:每件商品把自己的违规类目上下文一起带上,共用一份类目会把 A 行的拦截判到 B 行。 */
private String buildConformBatchUserText(List<SimilarAsinResultRowDto> rows, List<Integer> chunk,
Map<Integer, String[]> contextByRow) {
StringBuilder sb = new StringBuilder();
sb.append("待判定商品(共 ").append(chunk.size()).append(" 件,按编号 [i] 逐件判定):\n");
for (int position = 0; position < chunk.size(); position++) {
SimilarAsinResultRowDto row = rows.get(chunk.get(position));
String[] context = contextByRow.get(chunk.get(position));
sb.append('[').append(position + 1).append("] 标题:")
.append(firstNonBlank(row.getTitle(), row.getAsin())).append('\n');
sb.append(" SKU:").append(normalize(row.getSku())).append('\n');
sb.append(" 违规类目产品:一级类目:").append(context[0])
.append(" ,二级类目:").append(context[1])
.append(",三级类目:").append(context[2]).append('\n');
}
return sb.toString();
}
/** 取用合规判定:优先预计算结果,缺失的行按行级失败语义抛出(对齐分类那一路)。 */
private boolean conformForRow(int rowIndex, ConformPrepass prepass, SimilarAsinResultRowDto row,
CategoryLevel first, CategoryLevel second,
List<CategoryLevel> thirdCandidates, String prompt, String apiKey)
throws Exception {
if (prepass == null) {
return checkConform(row, first, second, thirdCandidates, prompt, apiKey);
}
Exception error = prepass.errors().get(rowIndex);
if (error != null) {
throw error instanceof RuntimeException runtimeException ? runtimeException
: new IllegalStateException(error.getMessage(), error);
}
ConformVerdict verdict = prepass.byRow().get(rowIndex);
if (verdict == null) {
throw new IllegalStateException("批量合规结果缺失 rowIndex=" + rowIndex);
}
applyConformVerdict(row, verdict);
return SimilarAsinLlmClient.isConformYes(verdict.isConform());
}
/**
@@ -19,6 +19,20 @@ public interface UserSecretUsageMapper extends BaseMapper<UserSecretUsageEntity>
@Param("businessDate") LocalDate businessDate,
@Param("count") int count);
/**
* 按唯一键 uk_user_module_date 累加 token 读数。
*
* <p>刻意与 {@link #increment} 分成两条:计次发生在**发请求之前**(口径含重试,请求没回来也要算一次),
* 而 token 只有响应回来才知道。合并成一条 upsert 就会把"已发出但超时"的那些请求从计次里漏掉。
* <p>这里是 UPDATE 而不是 upsert:行由前一条 increment 保证存在;真不存在就是 0 行受影响,
* token 读数丢掉也不该反过来影响计次。
*/
int addTokens(@Param("userId") Long userId,
@Param("moduleKey") String moduleKey,
@Param("businessDate") LocalDate businessDate,
@Param("promptTokens") long promptTokens,
@Param("completionTokens") long completionTokens);
/** 分批删除保留期外的用量日统计行(该表此前只增不删)。 */
int deleteBefore(@Param("cutoff") LocalDate cutoff, @Param("batchSize") int batchSize);
}
@@ -20,6 +20,10 @@ public class UserSecretUsageEntity {
private String moduleKey;
private LocalDate businessDate;
private Integer callCount;
/** 输入 token 累计(网关 usage.prompt_tokens)。0 = 该天没有 token 证据,不等于没消耗。 */
private Long promptTokens;
/** 输出 token 累计(网关 usage.completion_tokens)。0 = 该天没有 token 证据,不等于没产出。 */
private Long completionTokens;
private BigDecimal unitPrice;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@@ -61,7 +61,7 @@ public class UserSecretUsageService {
log.warn("[user-secret-usage] 忽略未知模块计次 userId={} module={}", userId, moduleKey);
return;
}
recordModule(userId, module, count);
recordModule(userId, module, count, 0L, 0L);
}
/** 内部通道上报入口:模块非法返回 false(供接口回执),写库失败只告警。 */
@@ -73,16 +73,45 @@ public class UserSecretUsageService {
if (module == null) {
return false;
}
return recordModule(userId, module, Math.min(count, MAX_REPORT_COUNT));
return recordModule(userId, module, Math.min(count, MAX_REPORT_COUNT), 0L, 0L);
}
private boolean recordModule(Long userId, UserSecretModule module, int count) {
/**
* 记一次响应回来的 token 读数(V157)。与计次分开的理由只有一个,但很硬:
* 计次发生在**发请求之前**(口径含重试,请求没回来也得算一次),token 只有响应回来才知道。
*
* <p>网关没回 {@code usage} 时必须整条不调用——不许写 0 冒充「实测为 0」,
* 那一行 0 以后会被当成成本读数拿去算账。
*/
public void recordTokens(Long userId, String moduleKey, long promptTokens, long completionTokens) {
if (userId == null || userId <= 0) {
return;
}
if (promptTokens <= 0 && completionTokens <= 0) {
return;
}
UserSecretModule module = UserSecretModule.of(moduleKey).orElse(null);
if (module == null) {
return;
}
recordModule(userId, module, 0, promptTokens, completionTokens);
}
private boolean recordModule(Long userId, UserSecretModule module, int count,
long promptTokens, long completionTokens) {
LocalDate today = LocalDate.now();
try {
usageMapper.increment(userId, module.key(), LocalDate.now(), count);
if (count > 0) {
usageMapper.increment(userId, module.key(), today, count);
}
if (promptTokens > 0 || completionTokens > 0) {
usageMapper.addTokens(userId, module.key(), today, promptTokens, completionTokens);
}
return true;
} catch (Exception ex) {
log.warn("[user-secret-usage] 计次写入失败 userId={} module={} count={} err={}",
userId, module.key(), count, ex.getMessage());
log.warn("[user-secret-usage] 计次写入失败 userId={} module={} count={} promptTokens={} "
+ "completionTokens={} err={}", userId, module.key(), count, promptTokens,
completionTokens, ex.getMessage());
return false;
}
}