Compare commits
13 Commits
f43ed6f116
...
09a34a2856
| Author | SHA1 | Date | |
|---|---|---|---|
| 09a34a2856 | |||
| 00f45cc20f | |||
| e71fa7fa83 | |||
| c8cd75cf6c | |||
| fee4df5bf6 | |||
| b9d23d5936 | |||
| 51401de2d5 | |||
| 34f730d403 | |||
| 66621d8a16 | |||
| 43240b9a10 | |||
| 6444c17edc | |||
| a04c1f3cf6 | |||
| 13fd426133 |
@@ -14,6 +14,8 @@ backend-java/target/
|
|||||||
backend-java/data/
|
backend-java/data/
|
||||||
backend-java/*.log
|
backend-java/*.log
|
||||||
backend-java/logs/
|
backend-java/logs/
|
||||||
|
# 会话级诊断脚本残渣(2026-11-03 瘦身审计 BD-8:_diag_keyword_sync.py 有误提交风险)
|
||||||
|
backend-java/tmp/
|
||||||
backend-java/src/main/resources/application-local.yml
|
backend-java/src/main/resources/application-local.yml
|
||||||
backend-java/.idea/
|
backend-java/.idea/
|
||||||
backend-java/*.iml
|
backend-java/*.iml
|
||||||
|
|||||||
@@ -9,7 +9,16 @@ import { useAdminSessionStore } from '@/stores/admin-session'
|
|||||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||||
import type { DuplicateItem, DuplicateOccurrence, DuplicateMetrics, DuplicateShop } from './duplicate-model.ts'
|
import type { DuplicateItem, DuplicateOccurrence, DuplicateMetrics, DuplicateShop } from './duplicate-model.ts'
|
||||||
import { fetchDuplicateConsole, fetchDuplicateLedger, requestDuplicateExportBlob, type LedgerSortKey } from './duplicate-console-api.ts'
|
import { fetchDuplicateConsole, fetchDuplicateLedger, requestDuplicateExportBlob, type LedgerSortKey } from './duplicate-console-api.ts'
|
||||||
import { aggregateDrawerRows, drawerSummaryOf, dupWithinGroup, indexShopGroups, type DrawerAggRow, type DrawerSummary, type ShopGroups } from './duplicate-console-logic.ts'
|
import {
|
||||||
|
aggregateDrawerRows,
|
||||||
|
drawerSummaryOf,
|
||||||
|
indexShopGroups,
|
||||||
|
itemBrandOf,
|
||||||
|
type DrawerAggRow,
|
||||||
|
type DrawerSummary,
|
||||||
|
type ShopGroups,
|
||||||
|
} from './duplicate-console-logic.ts'
|
||||||
|
import { useDuplicateMatrix } from './duplicate-matrix-window.ts'
|
||||||
import type { DuplicateConsole, LedgerRow } from './duplicate-console-model.ts'
|
import type { DuplicateConsole, LedgerRow } from './duplicate-console-model.ts'
|
||||||
import { ASIN_COUNTRY_CODES, asinCountryLabel } from '../asin/asin-country.ts'
|
import { ASIN_COUNTRY_CODES, asinCountryLabel } from '../asin/asin-country.ts'
|
||||||
import { orderedPair } from '@/utils/datetime'
|
import { orderedPair } from '@/utils/datetime'
|
||||||
@@ -73,7 +82,8 @@ function toast(msg: string) {
|
|||||||
const overview = computed(() => consoleData.value?.overview ?? null)
|
const overview = computed(() => consoleData.value?.overview ?? null)
|
||||||
const summary = computed<DuplicateMetrics | null>(() => overview.value?.summary ?? null)
|
const summary = computed<DuplicateMetrics | null>(() => overview.value?.summary ?? null)
|
||||||
const shops = computed(() => overview.value?.shops ?? [])
|
const shops = computed(() => overview.value?.shops ?? [])
|
||||||
const dupItems = computed(() => consoleData.value?.dup ?? [])
|
/** 当前撞款行窗口:服务端按 page/page_size(+dup_group) 切好的一窗(B60),页面不再自切全集。 */
|
||||||
|
const dupItems = computed<DuplicateItem[]>(() => consoleData.value?.dup ?? [])
|
||||||
const groupStats = computed(() => consoleData.value?.groups ?? [])
|
const groupStats = computed(() => consoleData.value?.groups ?? [])
|
||||||
|
|
||||||
const countryOptions = computed<string[]>(() => {
|
const countryOptions = computed<string[]>(() => {
|
||||||
@@ -118,26 +128,32 @@ function selectedGroupMembers(): string[] {
|
|||||||
|
|
||||||
const groupChips = computed(() => groupStats.value.filter((group) => group.shopCount >= 2))
|
const groupChips = computed(() => groupStats.value.filter((group) => group.shopCount >= 2))
|
||||||
|
|
||||||
/** 当前撞款行集:全局=撞款全集;分组=组内成员撞款子集;均按 ASIN 升序(reference 台账顺序)。 */
|
|
||||||
const dupRows = computed<DuplicateItem[]>(() => {
|
|
||||||
const rows = scope.value === 'global' ? dupItems.value : dupWithinGroup(dupItems.value, selectedGroupMembers())
|
|
||||||
return [...rows].sort((a, b) => a.asin.localeCompare(b.asin))
|
|
||||||
})
|
|
||||||
|
|
||||||
/** 矩阵列:分组范围=该组成员店;全店=全部可见店铺(按上架量降序)。 */
|
|
||||||
const matrixShops = computed<string[]>(() => {
|
|
||||||
if (scope.value === 'group') return selectedGroupMembers()
|
|
||||||
return orderedShops.value.map((shop) => shop.shopName)
|
|
||||||
})
|
|
||||||
|
|
||||||
const activeGroupStat = computed(() => groupStats.value.find((group) => group.name === selectedGroup.value) || null)
|
const activeGroupStat = computed(() => groupStats.value.find((group) => group.name === selectedGroup.value) || null)
|
||||||
/** 撞款 Tab 计数:全店范围取后端权威 total_dup(防后端截断计数偏小);分组范围取组内子集长度。 */
|
/** 撞款行总数:服务端在本页 + 本范围(全局或所选分组)内未分页的计数,翻页控件与 KPI 共用。 */
|
||||||
const totalDupCount = computed(() => (scope.value === 'global' ? (consoleData.value?.totalDup ?? dupRows.value.length) : dupRows.value.length))
|
const totalDupCount = computed(() => consoleData.value?.totalDup ?? 0)
|
||||||
|
|
||||||
function itemBrand(item: DuplicateItem): string {
|
/** 撞款矩阵的行窗 + 列窗 + 格子视图(B60):状态与算法在 `duplicate-matrix-window.ts`,翻页动作交回这里。 */
|
||||||
for (const occ of item.occurrences || []) if (occ.brand) return occ.brand
|
const {
|
||||||
return ''
|
matrixPage,
|
||||||
}
|
matrixPageSize,
|
||||||
|
columnPage,
|
||||||
|
columnWindowTotal,
|
||||||
|
matrixAllColumns,
|
||||||
|
matrixShops,
|
||||||
|
matrixView,
|
||||||
|
matrixHint,
|
||||||
|
goMatrixPage,
|
||||||
|
changeMatrixSize,
|
||||||
|
goColumnPage,
|
||||||
|
resetMatrixWindows,
|
||||||
|
} = useDuplicateMatrix({
|
||||||
|
rows: dupItems,
|
||||||
|
groupMembers: computed(() => selectedGroupMembers()),
|
||||||
|
groupScoped: computed(() => scope.value === 'group'),
|
||||||
|
selectedGroup,
|
||||||
|
reload: () => void loadConsole(),
|
||||||
|
dataVersion: consoleData,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
// ---- 撞款视图分页(分布/矩阵/撞款详情/抽屉明细;10/20/50/100 可选) ----
|
// ---- 撞款视图分页(分布/矩阵/撞款详情/抽屉明细;10/20/50/100 可选) ----
|
||||||
@@ -147,16 +163,7 @@ const distPageSize = ref(10)
|
|||||||
const pagedDistBars = computed(() =>
|
const pagedDistBars = computed(() =>
|
||||||
storeDistribution.value.list.slice((distPage.value - 1) * distPageSize.value, distPage.value * distPageSize.value),
|
storeDistribution.value.list.slice((distPage.value - 1) * distPageSize.value, distPage.value * distPageSize.value),
|
||||||
)
|
)
|
||||||
const matrixPage = ref(1)
|
|
||||||
const matrixPageSize = ref(10)
|
|
||||||
const matrixRows = computed(() =>
|
|
||||||
dupRows.value.slice((matrixPage.value - 1) * matrixPageSize.value, matrixPage.value * matrixPageSize.value),
|
|
||||||
)
|
|
||||||
const dupCardPage = ref(1)
|
|
||||||
const dupCardPageSize = ref(10)
|
|
||||||
const dupCardRows = computed(() =>
|
|
||||||
dupRows.value.slice((dupCardPage.value - 1) * dupCardPageSize.value, dupCardPage.value * dupCardPageSize.value),
|
|
||||||
)
|
|
||||||
const drawerPage = ref(1)
|
const drawerPage = ref(1)
|
||||||
const drawerPageSize = ref(10)
|
const drawerPageSize = ref(10)
|
||||||
const drawerRows = computed(() =>
|
const drawerRows = computed(() =>
|
||||||
@@ -168,46 +175,15 @@ const groupStatsPageSize = ref(10)
|
|||||||
const pagedGroupStats = computed(() =>
|
const pagedGroupStats = computed(() =>
|
||||||
groupStats.value.slice((groupStatsPage.value - 1) * groupStatsPageSize.value, groupStatsPage.value * groupStatsPageSize.value),
|
groupStats.value.slice((groupStatsPage.value - 1) * groupStatsPageSize.value, groupStatsPage.value * groupStatsPageSize.value),
|
||||||
)
|
)
|
||||||
watch([dupRows, drawerOccurrences, groupStats], () => {
|
watch([drawerOccurrences, groupStats], () => {
|
||||||
matrixPage.value = Math.min(matrixPage.value, Math.max(1, Math.ceil(dupRows.value.length / matrixPageSize.value)))
|
|
||||||
dupCardPage.value = Math.min(dupCardPage.value, Math.max(1, Math.ceil(dupRows.value.length / dupCardPageSize.value)))
|
|
||||||
drawerPage.value = 1
|
drawerPage.value = 1
|
||||||
groupStatsPage.value = Math.min(groupStatsPage.value, Math.max(1, Math.ceil(groupStats.value.length / groupStatsPageSize.value)))
|
groupStatsPage.value = Math.min(groupStatsPage.value, Math.max(1, Math.ceil(groupStats.value.length / groupStatsPageSize.value)))
|
||||||
})
|
})
|
||||||
|
|
||||||
const matrixHint = computed(() =>
|
|
||||||
scope.value === 'global'
|
|
||||||
? '行 = 全店撞款ASIN,列 = 全部店铺;有数字表示该店在售此 ASIN,点击行可看上架时间明细'
|
|
||||||
: selectedGroup.value
|
|
||||||
? `行 = 分组「${selectedGroup.value}」内的撞款ASIN,列 = 该分组店铺;有数字表示组内该店在售此 ASIN`
|
|
||||||
: '行 = 分组内撞款ASIN,列 = 该分组店铺;有数字表示组内该店在售此 ASIN',
|
|
||||||
)
|
|
||||||
|
|
||||||
/* ----- 矩阵单元格辅助 ----- */
|
/* ----- 矩阵单元格辅助 ----- */
|
||||||
function shopKey(name: string): string {
|
function shopKey(name: string): string {
|
||||||
return (name || '').trim().toLowerCase()
|
return (name || '').trim().toLowerCase()
|
||||||
}
|
}
|
||||||
function cellOccurrences(item: DuplicateItem, shop: string): DuplicateOccurrence[] {
|
|
||||||
const key = shopKey(shop)
|
|
||||||
return (item.occurrences || []).filter((occ) => shopKey(occ.shopName) === key)
|
|
||||||
}
|
|
||||||
function cellCount(item: DuplicateItem, shop: string): number {
|
|
||||||
return cellOccurrences(item, shop).length
|
|
||||||
}
|
|
||||||
function cellCountryDots(item: DuplicateItem, shop: string): string[] {
|
|
||||||
const codes = new Set<string>()
|
|
||||||
for (const occ of cellOccurrences(item, shop)) if (occ.country) codes.add(occ.country.toUpperCase())
|
|
||||||
return [...codes]
|
|
||||||
}
|
|
||||||
function cellCountryCount(item: DuplicateItem, shop: string, code: string): number {
|
|
||||||
return cellOccurrences(item, shop).filter((occ) => (occ.country || '').toUpperCase() === code).length
|
|
||||||
}
|
|
||||||
function cellTitle(item: DuplicateItem, shop: string): string {
|
|
||||||
const count = cellCount(item, shop)
|
|
||||||
if (!count) return `${shop} 无此 ASIN`
|
|
||||||
const sites = cellCountryDots(item, shop).map((code) => `${asinCountryLabel(code)} ${cellCountryCount(item, shop, code)}条`).join('、')
|
|
||||||
return `${shop} 在售 ${count} 条 · ${sites}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function activeFilterParams() {
|
function activeFilterParams() {
|
||||||
return { asin: filter.asin.trim(), shopName: filter.shop.trim(), group: filter.group.trim(), country: filter.country, site: '', dateFrom: filter.dateFrom, dateTo: filter.dateTo }
|
return { asin: filter.asin.trim(), shopName: filter.shop.trim(), group: filter.group.trim(), country: filter.country, site: '', dateFrom: filter.dateFrom, dateTo: filter.dateTo }
|
||||||
@@ -217,7 +193,13 @@ async function loadConsole() {
|
|||||||
loading.value = true
|
loading.value = true
|
||||||
loadError.value = ''
|
loadError.value = ''
|
||||||
try {
|
try {
|
||||||
consoleData.value = await fetchDuplicateConsole({ view: '', ...activeFilterParams() }, companyTab.requestCompanyId)
|
consoleData.value = await fetchDuplicateConsole(
|
||||||
|
{ view: '', ...activeFilterParams() },
|
||||||
|
companyTab.requestCompanyId,
|
||||||
|
matrixPage.value,
|
||||||
|
matrixPageSize.value,
|
||||||
|
scope.value === 'group' ? selectedGroup.value : '',
|
||||||
|
)
|
||||||
shopGroups.value = indexShopGroups(orderedShops.value)
|
shopGroups.value = indexShopGroups(orderedShops.value)
|
||||||
if (groupStats.value.length && !groupStats.value.some((group) => group.name === selectedGroup.value)) {
|
if (groupStats.value.length && !groupStats.value.some((group) => group.name === selectedGroup.value)) {
|
||||||
selectedGroup.value = groupChips.value[0] ? groupChips.value[0].name : ''
|
selectedGroup.value = groupChips.value[0] ? groupChips.value[0].name : ''
|
||||||
@@ -270,6 +252,7 @@ function resetQuery() {
|
|||||||
scope.value = 'global'
|
scope.value = 'global'
|
||||||
selectedGroup.value = ''
|
selectedGroup.value = ''
|
||||||
activeTab.value = 'dup'
|
activeTab.value = 'dup'
|
||||||
|
resetMatrixWindows()
|
||||||
applyQuery()
|
applyQuery()
|
||||||
toast('筛选已重置')
|
toast('筛选已重置')
|
||||||
}
|
}
|
||||||
@@ -280,8 +263,21 @@ function switchTab(tab: Tab) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function switchScope(next: Scope) {
|
function switchScope(next: Scope) {
|
||||||
|
if (scope.value === next) return
|
||||||
scope.value = next
|
scope.value = next
|
||||||
if (next === 'group' && !selectedGroup.value && groupChips.value.length) selectedGroup.value = groupChips.value[0].name
|
if (next === 'group' && !selectedGroup.value && groupChips.value.length) selectedGroup.value = groupChips.value[0].name
|
||||||
|
// 行范围换了(全局 ↔ 组内),服务端裁出来的那一窗也就换了 ⇒ 重新请一窗。
|
||||||
|
resetMatrixWindows()
|
||||||
|
void loadConsole()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分组 chip:选中即换行范围,与 switchScope 同一条出口(不再在客户端重裁一遍全集)。 */
|
||||||
|
function selectGroup(name: string) {
|
||||||
|
if (selectedGroup.value === name && scope.value === 'group') return
|
||||||
|
scope.value = 'group'
|
||||||
|
selectedGroup.value = name
|
||||||
|
resetMatrixWindows()
|
||||||
|
void loadConsole()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function reAnalyze() {
|
async function reAnalyze() {
|
||||||
@@ -338,7 +334,7 @@ function openDrawer(asin: string, brand: string, dupFlag: boolean, occurrences:
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openDupDrawer(item: DuplicateItem) {
|
function openDupDrawer(item: DuplicateItem) {
|
||||||
openDrawer(item.asin, itemBrand(item), item.shopCount >= 2, item.occurrences)
|
openDrawer(item.asin, itemBrandOf(item), item.shopCount >= 2, item.occurrences)
|
||||||
}
|
}
|
||||||
|
|
||||||
function openLedgerDrawer(row: LedgerRow) {
|
function openLedgerDrawer(row: LedgerRow) {
|
||||||
@@ -553,7 +549,7 @@ onMounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
<div v-if="scope === 'group'" class="group-chips">
|
<div v-if="scope === 'group'" class="group-chips">
|
||||||
<template v-if="groupChips.length">
|
<template v-if="groupChips.length">
|
||||||
<button v-for="group in groupChips" :key="group.name" type="button" class="g-chip" :class="{ active: selectedGroup === group.name, dup: group.dupCount > 0 }" @click="selectedGroup = group.name">
|
<button v-for="group in groupChips" :key="group.name" type="button" class="g-chip" :class="{ active: selectedGroup === group.name, dup: group.dupCount > 0 }" @click="selectGroup(group.name)">
|
||||||
{{ group.name }} <span class="g-count">{{ group.shopCount }}店 · {{ group.dupCount }}撞款</span>
|
{{ group.name }} <span class="g-count">{{ group.shopCount }}店 · {{ group.dupCount }}撞款</span>
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
@@ -568,9 +564,16 @@ onMounted(() => {
|
|||||||
<div class="gs-item" :class="{ warn: activeGroupStat.dupCount > 0 }"><div class="gs-v">{{ activeGroupStat.dupCount }}</div><div class="gs-l">组内撞款ASIN</div></div>
|
<div class="gs-item" :class="{ warn: activeGroupStat.dupCount > 0 }"><div class="gs-v">{{ activeGroupStat.dupCount }}</div><div class="gs-l">组内撞款ASIN</div></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="section-title">撞款覆盖矩阵 <span class="hint">{{ matrixHint }}</span></div>
|
<div class="section-title">
|
||||||
|
撞款覆盖矩阵 <span class="hint">{{ matrixHint }}</span>
|
||||||
|
<span v-if="columnWindowTotal > 1" class="col-window">
|
||||||
|
<button type="button" class="link-btn" :disabled="columnPage <= 1" @click="goColumnPage(-1)">‹ 上一窗列</button>
|
||||||
|
列 {{ columnPage }}/{{ columnWindowTotal }}(共 {{ matrixAllColumns.length }} 列)
|
||||||
|
<button type="button" class="link-btn" :disabled="columnPage >= columnWindowTotal" @click="goColumnPage(1)">下一窗列 ›</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<div class="matrix-wrap">
|
<div class="matrix-wrap">
|
||||||
<table v-if="dupRows.length" class="matrix">
|
<table v-if="dupItems.length" class="matrix">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>ASIN</th>
|
<th>ASIN</th>
|
||||||
@@ -579,13 +582,13 @@ onMounted(() => {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="item in matrixRows" :key="item.asin" @click="openDupDrawer(item)">
|
<tr v-for="row in matrixView" :key="row.asin" @click="openDupDrawer(row.item)">
|
||||||
<td><span class="asin-code">{{ item.asin }}</span></td>
|
<td><span class="asin-code">{{ row.asin }}</span></td>
|
||||||
<td><span class="m-brand">{{ itemBrand(item) || '—' }}</span></td>
|
<td><span class="m-brand">{{ row.brand }}</span></td>
|
||||||
<td v-for="shop in matrixShops" :key="shop" style="text-align:center">
|
<td v-for="(cell, index) in row.cells" :key="matrixShops[index]" style="text-align:center">
|
||||||
<div class="m-cell" :class="{ empty: cellCount(item, shop) === 0 }" :title="cellTitle(item, shop)">
|
<div class="m-cell" :class="{ empty: cell.count === 0 }" :title="cell.title">
|
||||||
{{ cellCount(item, shop) || '' }}
|
{{ cell.count || '' }}
|
||||||
<span class="dots"><span v-for="code in cellCountryDots(item, shop)" :key="code" class="m-dot" :style="{ background: siteColor(code) }"></span></span>
|
<span class="dots"><span v-for="code in cell.dots" :key="code" class="m-dot" :style="{ background: siteColor(code) }"></span></span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -596,15 +599,15 @@ onMounted(() => {
|
|||||||
调整筛选条件或切换到其他分组查看
|
调整筛选条件或切换到其他分组查看
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<OldPagination :total="dupRows.length" :page="matrixPage" :page-size="matrixPageSize" @change="matrixPage = $event" @size-change="(s: number) => { matrixPageSize = s; matrixPage = 1 }" />
|
<OldPagination :total="totalDupCount" :page="matrixPage" :page-size="matrixPageSize" @change="goMatrixPage" @size-change="changeMatrixSize" />
|
||||||
|
|
||||||
<div class="section-title" style="margin-top:24px">撞款详情 <span class="hint">同一 ASIN 在多家店铺的上架时间明细</span></div>
|
<div class="section-title" style="margin-top:24px">撞款详情 <span class="hint">同一 ASIN 在多家店铺的上架时间明细</span></div>
|
||||||
<div v-if="dupRows.length" class="dup-grid">
|
<div v-if="dupItems.length" class="dup-grid">
|
||||||
<div v-for="item in dupCardRows" :key="item.asin" class="dup-card">
|
<div v-for="item in dupItems" :key="item.asin" class="dup-card">
|
||||||
<div class="dup-head">
|
<div class="dup-head">
|
||||||
<span class="asin-code">{{ item.asin }}</span>
|
<span class="asin-code">{{ item.asin }}</span>
|
||||||
<span class="badge dup">{{ item.shopCount }}店在售</span>
|
<span class="badge dup">{{ item.shopCount }}店在售</span>
|
||||||
<span class="d-brand">{{ itemBrand(item) || '未知品牌' }}</span>
|
<span class="d-brand">{{ itemBrandOf(item) || '未知品牌' }}</span>
|
||||||
<button class="link-btn" type="button" @click="openDupDrawer(item)">查看明细</button>
|
<button class="link-btn" type="button" @click="openDupDrawer(item)">查看明细</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="dup-body">
|
<div class="dup-body">
|
||||||
@@ -620,8 +623,8 @@ onMounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="dup-empty">当前范围下没有撞款ASIN</div>
|
<div v-else class="dup-empty">当前范围下没有撞款ASIN</div>
|
||||||
<OldPagination :total="dupRows.length" :page="dupCardPage" :page-size="dupCardPageSize" @change="dupCardPage = $event" @size-change="(s: number) => { dupCardPageSize = s; dupCardPage = 1 }" />
|
<OldPagination :total="totalDupCount" :page="matrixPage" :page-size="matrixPageSize" @change="goMatrixPage" @size-change="changeMatrixSize" />
|
||||||
<div class="dup-total">共 <b>{{ dupRows.length }}</b> 条{{ scope === 'group' && selectedGroup ? `分组「${selectedGroup}」组内撞款ASIN` : '全店撞款ASIN' }}</div>
|
<div class="dup-total">共 <b>{{ dupItems.length }}</b> 条{{ scope === 'group' && selectedGroup ? `分组「${selectedGroup}」组内撞款ASIN` : '全店撞款ASIN' }}</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- ============ 全部ASIN台账 ============ -->
|
<!-- ============ 全部ASIN台账 ============ -->
|
||||||
@@ -885,6 +888,9 @@ onMounted(() => {
|
|||||||
.dup-ref .section-title { font-size: 14px; font-weight: 700; display: flex; align-items: baseline; gap: 8px; margin-bottom: 12px; }
|
.dup-ref .section-title { font-size: 14px; font-weight: 700; display: flex; align-items: baseline; gap: 8px; margin-bottom: 12px; }
|
||||||
.dup-ref .section-title .hint { font-size: 11px; font-weight: 400; color: var(--text3); }
|
.dup-ref .section-title .hint { font-size: 11px; font-weight: 400; color: var(--text3); }
|
||||||
.dup-ref .matrix-wrap { overflow-x: auto; overflow-y: auto; border-radius: var(--radius); background: var(--surface); border: 1px solid var(--border); max-height: 480px; }
|
.dup-ref .matrix-wrap { overflow-x: auto; overflow-y: auto; border-radius: var(--radius); background: var(--surface); border: 1px solid var(--border); max-height: 480px; }
|
||||||
|
/* 列窗口控件:与 section-title 同行,只在看得到第二窗列时出现。 */
|
||||||
|
.dup-ref .col-window { margin-left: 12px; display: inline-flex; align-items: center; gap: 8px; font-size: 12px; color: var(--text2); }
|
||||||
|
.dup-ref .col-window .link-btn:disabled { color: var(--text3); cursor: not-allowed; }
|
||||||
.dup-ref table.matrix { border-collapse: separate; border-spacing: 0; width: 100%; background: var(--surface); }
|
.dup-ref table.matrix { border-collapse: separate; border-spacing: 0; width: 100%; background: var(--surface); }
|
||||||
.dup-ref table.matrix th {
|
.dup-ref table.matrix th {
|
||||||
background: #F7F9FC; color: var(--text2); font-size: 12px; font-weight: 600; padding: 10px 12px;
|
background: #F7F9FC; color: var(--text2); font-size: 12px; font-weight: 600; padding: 10px 12px;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
|
|
||||||
export const DUPLICATE_CHECK_ENDPOINT = '/api/admin/shop-data-crawl'
|
export const DUPLICATE_CHECK_ENDPOINT = '/api/admin/shop-data-crawl'
|
||||||
|
|
||||||
/** console 端点吃 asin/shop_name/group/country/site/date_from/date_to;多余分页参数后端忽略。 */
|
/** console 端点吃 asin/shop_name/group/country/site/date_from/date_to(行窗口的 page/page_size/dup_group 由调用方另传)。 */
|
||||||
function toConsoleQuery(filter: DuplicateFilter): Record<string, string> {
|
function toConsoleQuery(filter: DuplicateFilter): Record<string, string> {
|
||||||
const query: Record<string, string> = {}
|
const query: Record<string, string> = {}
|
||||||
const asin = (filter.asin || '').trim()
|
const asin = (filter.asin || '').trim()
|
||||||
@@ -32,14 +32,25 @@ function toConsoleQuery(filter: DuplicateFilter): Record<string, string> {
|
|||||||
|
|
||||||
export type LedgerSortKey = 'asin' | 'brand' | 'store_count' | 'record_count' | 'earliest' | 'latest'
|
export type LedgerSortKey = 'asin' | 'brand' | 'store_count' | 'record_count' | 'earliest' | 'latest'
|
||||||
|
|
||||||
/** 加载撞款控制台快照:GET /duplicate-check-console。 */
|
/**
|
||||||
|
* 加载撞款控制台快照:GET /duplicate-check-console。
|
||||||
|
*
|
||||||
|
* 行窗口(B60):`page`/`pageSize` 决定返回的 `dup` 是这一窗,`dupGroup` 非空时行集先按
|
||||||
|
* 该分组成员裁剪(组内 ≥2 店才算撞款)。三者都是**服务端**口径——矩阵与详情卡片共用同一窗口,
|
||||||
|
* 页面不再自己从全集里切片(那需要后端把整份撞款数组发回来,正是 B60 要收掉的那件事)。
|
||||||
|
*/
|
||||||
export async function fetchDuplicateConsole(
|
export async function fetchDuplicateConsole(
|
||||||
filter: DuplicateFilter,
|
filter: DuplicateFilter,
|
||||||
companyId?: number | null,
|
companyId?: number | null,
|
||||||
|
page = 1,
|
||||||
|
pageSize = 100,
|
||||||
|
dupGroup = '',
|
||||||
): Promise<DuplicateConsole> {
|
): Promise<DuplicateConsole> {
|
||||||
// toConsoleQuery 是白名单构造(只点名 asin/shop_name/group/country/site/date_*),
|
// toConsoleQuery 是白名单构造(只点名 asin/shop_name/group/country/site/date_*),
|
||||||
// 公司值只许落在本函数自己的 companyId 形参上。
|
// 公司值只许落在本函数自己的 companyId 形参上。
|
||||||
const query: Record<string, string | number> = toConsoleQuery(filter)
|
const query: Record<string, string | number> = { ...toConsoleQuery(filter), page, page_size: pageSize }
|
||||||
|
const group = (dupGroup || '').trim()
|
||||||
|
if (group) query.dup_group = group
|
||||||
if (companyId != null) query.company_id = companyId
|
if (companyId != null) query.company_id = companyId
|
||||||
const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-console`, { params: query })
|
const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-console`, { params: query })
|
||||||
return parseDuplicateConsole(data)
|
return parseDuplicateConsole(data)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/** 撞款控制台视图派生(分组索引 / 组内撞款子集 / 店铺列并集):纯逻辑。 */
|
/** 撞款控制台视图派生(分组索引 / 店铺列并集 / 矩阵格子预聚合):纯逻辑。 */
|
||||||
import type { DuplicateItem, DuplicateOccurrence, DuplicateShop } from './duplicate-model.ts'
|
import type { DuplicateItem, DuplicateOccurrence, DuplicateShop } from './duplicate-model.ts'
|
||||||
|
|
||||||
export interface ShopGroups {
|
export interface ShopGroups {
|
||||||
@@ -41,27 +41,6 @@ export function indexShopGroups(shops: DuplicateShop[]): ShopGroups {
|
|||||||
return { members, shopGroupNames }
|
return { members, shopGroupNames }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 仅在指定成员店铺(展示名)内保留 occurrences;重算 shop_count,返回 ≥2 店的撞款子集。 */
|
|
||||||
export function dupWithinGroup(items: DuplicateItem[], memberShops: string[]): DuplicateItem[] {
|
|
||||||
const memberKeys = new Set<string>()
|
|
||||||
for (const shop of memberShops || []) memberKeys.add(shopKey(shop))
|
|
||||||
const result: DuplicateItem[] = []
|
|
||||||
for (const item of items || []) {
|
|
||||||
const kept: DuplicateOccurrence[] = []
|
|
||||||
const shops = new Set<string>()
|
|
||||||
for (const occ of item.occurrences || []) {
|
|
||||||
if (memberKeys.has(shopKey(occ.shopName))) {
|
|
||||||
kept.push(occ)
|
|
||||||
shops.add(occ.shopName || '')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (kept.length > 0 && shops.size >= 2) {
|
|
||||||
result.push({ asin: item.asin, shopCount: shops.size, recordCount: kept.length, occurrences: kept })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 撞款行涉及店铺的并集列(出现顺序去重);memberShops 非空时仅取交集成员的子集顺序。 */
|
/** 撞款行涉及店铺的并集列(出现顺序去重);memberShops 非空时仅取交集成员的子集顺序。 */
|
||||||
export function storeColumnsOf(items: DuplicateItem[], memberShops: string[] = []): string[] {
|
export function storeColumnsOf(items: DuplicateItem[], memberShops: string[] = []): string[] {
|
||||||
const restricted = new Set(memberShops.map((shop) => shopKey(shop)))
|
const restricted = new Set(memberShops.map((shop) => shopKey(shop)))
|
||||||
@@ -90,6 +69,74 @@ export function storeColumnsOf(items: DuplicateItem[], memberShops: string[] = [
|
|||||||
return order
|
return order
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 矩阵一格:该店在售此 ASIN 的条数 + 站点(国家)分布。 */
|
||||||
|
export interface MatrixCell {
|
||||||
|
count: number
|
||||||
|
sites: { code: string; count: number }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 空格的单份实例:模板每格都要拿一个,不能每格 new 一个对象。 */
|
||||||
|
export const EMPTY_MATRIX_CELL: MatrixCell = { count: 0, sites: [] }
|
||||||
|
|
||||||
|
function cellKey(asin: string, shop: string): string {
|
||||||
|
// 用 \u0000 拼键:ASIN 与店铺名都可打印,任何可见分隔符都可能出现在店铺名里(那样就会串格)。
|
||||||
|
return `${(asin || '').trim()}\u0000${shopKey(shop)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 撞款矩阵的格子集合:把 rows×columns 一次算完(B60 的「预聚合」)。
|
||||||
|
*
|
||||||
|
* <p>原形状是每格现算:`cellCount`/`cellCountryDots`/`cellTitle` 各自把该行 occurrences 全 filter
|
||||||
|
* 一遍,一格 4~6 次、50 行 × 200 列就是每帧上万次整行扫描,勾选/翻页都要重付。这里每行只按
|
||||||
|
* 店铺分桶一次(O(occurrences)),之后一格一次 Map 取值。
|
||||||
|
*
|
||||||
|
* 只给 `columns` 里点名的列建格:不在列集内的 occurrence 直接不装桶,列窗口收窄时开销跟着降。
|
||||||
|
*/
|
||||||
|
export function buildMatrixCells(items: DuplicateItem[], columns: string[]): Map<string, MatrixCell> {
|
||||||
|
const cells = new Map<string, MatrixCell>()
|
||||||
|
const wanted = new Set<string>()
|
||||||
|
for (const column of columns || []) wanted.add(shopKey(column))
|
||||||
|
if (!wanted.size) return cells
|
||||||
|
for (const item of items || []) {
|
||||||
|
const buckets = new Map<string, DuplicateOccurrence[]>()
|
||||||
|
const siteCounts = new Map<string, Map<string, number>>()
|
||||||
|
for (const occ of item.occurrences || []) {
|
||||||
|
const key = shopKey(occ.shopName)
|
||||||
|
if (!wanted.has(key)) continue
|
||||||
|
const bucket = buckets.get(key)
|
||||||
|
if (bucket) bucket.push(occ)
|
||||||
|
else buckets.set(key, [occ])
|
||||||
|
const code = (occ.country || '').trim().toUpperCase()
|
||||||
|
if (!code) continue
|
||||||
|
let counts = siteCounts.get(key)
|
||||||
|
if (!counts) {
|
||||||
|
counts = new Map<string, number>()
|
||||||
|
siteCounts.set(key, counts)
|
||||||
|
}
|
||||||
|
counts.set(code, (counts.get(code) || 0) + 1)
|
||||||
|
}
|
||||||
|
for (const [key, occurrences] of buckets) {
|
||||||
|
const codes = siteCounts.get(key)
|
||||||
|
cells.set(cellKey(item.asin, key), {
|
||||||
|
count: occurrences.length,
|
||||||
|
sites: codes ? [...codes].map(([code, count]) => ({ code, count })) : [],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cells
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取一格;没有格子时返回同一份空对象(模板里 `cellOf(...).count` 要能直接读)。 */
|
||||||
|
export function matrixCellOf(cells: Map<string, MatrixCell>, asin: string, shop: string): MatrixCell {
|
||||||
|
return cells.get(cellKey(asin, shop)) || EMPTY_MATRIX_CELL
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一个撞款 ASIN 的品牌:取第一条带品牌的上架记录,全空就是"未知品牌"(页面自己决定怎么显示)。 */
|
||||||
|
export function itemBrandOf(item: DuplicateItem): string {
|
||||||
|
for (const occ of item.occurrences || []) if (occ.brand) return occ.brand
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
/** 明细抽屉聚合行:店铺×站点聚合(对齐 reference 抽屉的 店铺/分组/站点/上架时间(升序堆叠)/次数)。 */
|
/** 明细抽屉聚合行:店铺×站点聚合(对齐 reference 抽屉的 店铺/分组/站点/上架时间(升序堆叠)/次数)。 */
|
||||||
export interface DrawerAggRow {
|
export interface DrawerAggRow {
|
||||||
shopName: string
|
shopName: string
|
||||||
|
|||||||
@@ -18,12 +18,19 @@ export interface ConsoleGroupStat {
|
|||||||
dupCount: number
|
dupCount: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 撞款控制台单次快照:总览(指标/店铺分布) + 撞款全集 + 分组统计。 */
|
/**
|
||||||
|
* 撞款控制台单次快照:总览(指标/店铺分布) + 撞款**行窗口** + 分组统计。
|
||||||
|
*
|
||||||
|
* `dup` 是服务端按 page/pageSize 切出来的一窗(B60),`totalDup` 是该范围内未分页的总数;
|
||||||
|
* 两者不是同一个口径,页面分页器读 totalDup、列表读 dup。
|
||||||
|
*/
|
||||||
export interface DuplicateConsole {
|
export interface DuplicateConsole {
|
||||||
overview: DuplicateOverview
|
overview: DuplicateOverview
|
||||||
dup: DuplicateItem[]
|
dup: DuplicateItem[]
|
||||||
groups: ConsoleGroupStat[]
|
groups: ConsoleGroupStat[]
|
||||||
totalDup: number
|
totalDup: number
|
||||||
|
page: number
|
||||||
|
pageSize: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 台账单行(含 occurrences,供明细抽屉还原每店上架时间线)。 */
|
/** 台账单行(含 occurrences,供明细抽屉还原每店上架时间线)。 */
|
||||||
@@ -87,7 +94,14 @@ export function parseDuplicateConsole(payload: unknown): DuplicateConsole {
|
|||||||
const groups = Array.isArray(record.groups)
|
const groups = Array.isArray(record.groups)
|
||||||
? record.groups.map((raw) => parseConsoleGroup(raw)).filter((group): group is ConsoleGroupStat => group !== null)
|
? record.groups.map((raw) => parseConsoleGroup(raw)).filter((group): group is ConsoleGroupStat => group !== null)
|
||||||
: []
|
: []
|
||||||
return { overview, dup, groups, totalDup: count(record.total_dup ?? record.totalDup) }
|
return {
|
||||||
|
overview,
|
||||||
|
dup,
|
||||||
|
groups,
|
||||||
|
totalDup: count(record.total_dup ?? record.totalDup),
|
||||||
|
page: count(record.page) || 1,
|
||||||
|
pageSize: count(record.page_size ?? record.pageSize),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 解析单条台账行。 */
|
/** 解析单条台账行。 */
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
/**
|
||||||
|
* 撞款覆盖矩阵的「行窗 + 列窗」组合式(B60 从 DuplicateCheckPage.vue 拆出)。
|
||||||
|
*
|
||||||
|
* 为什么单独立一支:那一屏矩阵原本是每格现算——`cellCount / cellCountryDots / cellTitle`
|
||||||
|
* 各自把该行 occurrences 全 filter 一遍(一格 4~6 次),而且整份撞款全集一次性铺成
|
||||||
|
* 「全部行 × 全部列」的 DOM。收口后行由服务端切窗、列在本模块切窗,格子的文案与
|
||||||
|
* 国家点一次算完、空格按列共享同一份视图。这些状态(列游标、行游标、三份 computed)
|
||||||
|
* 是一件事,留在页面里会把本页推到可读性基线之外,也更难单测。
|
||||||
|
*
|
||||||
|
* 纯逻辑部分(分桶、取列)在 `duplicate-console-logic.ts`,本文件只做"窗口"这一层,
|
||||||
|
* 数据从页面注入,不认识 store。
|
||||||
|
*/
|
||||||
|
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'
|
||||||
|
import { buildMatrixCells, itemBrandOf, matrixCellOf, storeColumnsOf } from './duplicate-console-logic.ts'
|
||||||
|
import { asinCountryLabel } from '../asin/asin-country.ts'
|
||||||
|
import type { DuplicateItem } from './duplicate-model.ts'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列窗口上限(B60「限制列数」)。一窗 40 列 × 最多 100 行=单帧最多 4,000 格;
|
||||||
|
* 不封顶时 200 列 × 100 行=2 万格 DOM,任何一次勾选/翻页都要重排。
|
||||||
|
* 列没被裁掉,只是切成窗口(`goColumnPage`),所以信息一条不丢。
|
||||||
|
*/
|
||||||
|
export const MATRIX_COLUMN_WINDOW = 40
|
||||||
|
|
||||||
|
/** 模板只读这一份:数字、国家点、悬浮说明都在这里算完。 */
|
||||||
|
export interface MatrixCellView {
|
||||||
|
count: number
|
||||||
|
dots: string[]
|
||||||
|
title: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一行矩阵视图:行对象本身(点开抽屉要用)+ 品牌 + 本窗每一格。 */
|
||||||
|
export interface MatrixRowView {
|
||||||
|
item: DuplicateItem
|
||||||
|
asin: string
|
||||||
|
brand: string
|
||||||
|
cells: MatrixCellView[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatrixWindowSource {
|
||||||
|
/** 当前行窗(服务端切好的那一窗)。 */
|
||||||
|
rows: ComputedRef<DuplicateItem[]>
|
||||||
|
/** 列范围的第二正本=分组页签选中的组员(非分组范围给空数组)。 */
|
||||||
|
groupMembers: ComputedRef<string[]>
|
||||||
|
/** 分组范围与否:决定列要不要与组员取交集。 */
|
||||||
|
groupScoped: Ref<boolean> | ComputedRef<boolean>
|
||||||
|
/** 选中的分组名(只用于矩阵那行说明文案,让"看到的是什么范围"写在屏上)。 */
|
||||||
|
selectedGroup: Ref<string> | ComputedRef<string>
|
||||||
|
/** 行窗换页/换档都要重新请一窗(服务端切,页面不再从全集里自切)。 */
|
||||||
|
reload: () => void
|
||||||
|
/** 数据到达的版本号(一般是 consoleData 本身):新数据 ⇒ 旧游标已指向不存在的位置。 */
|
||||||
|
dataVersion: Ref<unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 空格共用同一份 dots(模板只读不写,共享数组不会被改)。 */
|
||||||
|
const NO_DOTS: string[] = []
|
||||||
|
|
||||||
|
export function useDuplicateMatrix(source: MatrixWindowSource) {
|
||||||
|
const matrixPage = ref(1)
|
||||||
|
const matrixPageSize = ref(10)
|
||||||
|
const columnPage = ref(1)
|
||||||
|
|
||||||
|
/** 本页行里真出现过的店铺=矩阵该配的列(分组范围再与组员取交集)。 */
|
||||||
|
const matrixAllColumns = computed<string[]>(() =>
|
||||||
|
storeColumnsOf(source.rows.value, source.groupScoped.value ? source.groupMembers.value : []),
|
||||||
|
)
|
||||||
|
|
||||||
|
const columnWindowTotal = computed(() =>
|
||||||
|
Math.max(1, Math.ceil(matrixAllColumns.value.length / MATRIX_COLUMN_WINDOW)),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 矩阵列:按窗口切(超出部分用列窗口控件翻)。 */
|
||||||
|
const matrixShops = computed<string[]>(() => {
|
||||||
|
const start = Math.max(0, (columnPage.value - 1) * MATRIX_COLUMN_WINDOW)
|
||||||
|
return matrixAllColumns.value.slice(start, start + MATRIX_COLUMN_WINDOW)
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 一次把「本窗行 × 本窗列」全部算完,模板只读不算。 */
|
||||||
|
const matrixCells = computed(() => buildMatrixCells(source.rows.value, matrixShops.value))
|
||||||
|
|
||||||
|
function cellView(shop: string, cell: ReturnType<typeof matrixCellOf>): MatrixCellView {
|
||||||
|
const sites = cell.sites.map((site) => `${asinCountryLabel(site.code)} ${site.count}条`).join('、')
|
||||||
|
return {
|
||||||
|
count: cell.count,
|
||||||
|
dots: cell.sites.map((site) => site.code),
|
||||||
|
title: sites ? `${shop} 在售 ${cell.count} 条 · ${sites}` : `${shop} 在售 ${cell.count} 条`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每列一份「本格为空」的视图,整列复用同一对象。
|
||||||
|
*
|
||||||
|
* <p>矩阵里绝大多数格是空的(一个 ASIN 只在几家店在售,列却是几十上百家店)。原先一格
|
||||||
|
* 一条 `无此 ASIN` 文案,50 行 × 200 列=1 万条字符串;按列准备一次之后行数再多也不
|
||||||
|
* 乘上去——这条才是"每格现算"剩下的那半开销。
|
||||||
|
*/
|
||||||
|
const emptyColumnViews = computed<MatrixCellView[]>(() =>
|
||||||
|
matrixShops.value.map((shop) => ({ count: 0, dots: NO_DOTS, title: `${shop} 无此 ASIN` })),
|
||||||
|
)
|
||||||
|
|
||||||
|
const matrixView = computed<MatrixRowView[]>(() => {
|
||||||
|
const cells = matrixCells.value
|
||||||
|
const blanks = emptyColumnViews.value
|
||||||
|
return source.rows.value.map((item) => ({
|
||||||
|
item,
|
||||||
|
asin: item.asin,
|
||||||
|
brand: itemBrandOf(item) || '—',
|
||||||
|
cells: matrixShops.value.map((shop, index) => {
|
||||||
|
const cell = matrixCellOf(cells, item.asin, shop)
|
||||||
|
return cell.count ? cellView(shop, cell) : blanks[index]
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 屏上那行说明:把"行/列各是什么范围"写清楚,尤其分组范围是服务端裁过行的那一窗。 */
|
||||||
|
const matrixHint = computed(() =>
|
||||||
|
source.groupScoped.value
|
||||||
|
? source.selectedGroup.value
|
||||||
|
? `行 = 分组「${source.selectedGroup.value}」内的撞款ASIN(服务端裁行+分页),列 = 组内在售店铺;有数字表示组内该店在售此 ASIN`
|
||||||
|
: '行 = 分组内撞款ASIN,列 = 该分组店铺;有数字表示组内该店在售此 ASIN'
|
||||||
|
: '行 = 本页撞款ASIN(服务端分页),列 = 本页撞款涉及店铺;有数字表示该店在售此 ASIN,点击行可看上架时间明细',
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 行窗口翻页:同一页重复点不重新请(翻页控件的当前页也会触发 change)。 */
|
||||||
|
function goMatrixPage(page: number): void {
|
||||||
|
if (page === matrixPage.value) return
|
||||||
|
matrixPage.value = page
|
||||||
|
source.reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeMatrixSize(size: number): void {
|
||||||
|
matrixPageSize.value = size
|
||||||
|
matrixPage.value = 1
|
||||||
|
source.reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列窗口翻页:行不动,只把看得见的店铺换一窗。 */
|
||||||
|
function goColumnPage(step: number): void {
|
||||||
|
const next = columnPage.value + step
|
||||||
|
if (next < 1 || next > columnWindowTotal.value) return
|
||||||
|
columnPage.value = next
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 换了行范围(全局 ↔ 组内、换分组、重置筛选):两个游标都回到第一窗。 */
|
||||||
|
function resetMatrixWindows(): void {
|
||||||
|
matrixPage.value = 1
|
||||||
|
columnPage.value = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(source.dataVersion, () => {
|
||||||
|
columnPage.value = Math.min(columnPage.value, columnWindowTotal.value)
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
MATRIX_COLUMN_WINDOW,
|
||||||
|
matrixPage,
|
||||||
|
matrixPageSize,
|
||||||
|
columnPage,
|
||||||
|
columnWindowTotal,
|
||||||
|
matrixAllColumns,
|
||||||
|
matrixShops,
|
||||||
|
matrixView,
|
||||||
|
matrixHint,
|
||||||
|
goMatrixPage,
|
||||||
|
changeMatrixSize,
|
||||||
|
goColumnPage,
|
||||||
|
resetMatrixWindows,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,15 +52,46 @@ test('align_dup_console_pagination_all_lists', () => {
|
|||||||
// 且分布/矩阵/详情常显(不足一页也显示分页器,反馈:数据少时看不到分页)。
|
// 且分布/矩阵/详情常显(不足一页也显示分页器,反馈:数据少时看不到分页)。
|
||||||
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
|
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
|
||||||
assert.match(page, /:total="distCount"/, '店铺上架分布有分页器(常显)')
|
assert.match(page, /:total="distCount"/, '店铺上架分布有分页器(常显)')
|
||||||
assert.match(page, /:total="dupRows\.length"/, '撞款覆盖矩阵有分页器(常显)')
|
// B60:撞款行改由服务端切窗口,矩阵与详情卡片读同一窗 ⇒ 两个分页器必须共用同一个游标
|
||||||
assert.match(page, /v-for="item in dupCardRows"/, '撞款详情卡片绑定分页切片')
|
// (各自独立翻页在"一窗"的形状下已经不可表示,留着就是界面说一套、请求发另一套)。
|
||||||
assert.match(page, /:total="dupRows\.length"[\s\S]*dupCardPageSize/, '撞款详情卡片有分页器(常显)')
|
assert.match(page, /:total="totalDupCount"[\s\S]*:page="matrixPage"/, '撞款覆盖矩阵分页器绑服务端总数与行窗口游标')
|
||||||
|
assert.match(page, /v-for="item in dupItems"/, '撞款详情卡片绑这一窗行集')
|
||||||
|
assert.match(page, /:total="totalDupCount"[\s\S]*:page-size="matrixPageSize"/, '撞款详情卡片分页器与矩阵同游标')
|
||||||
|
assert.doesNotMatch(page, /dupCardPage/, '卡片不再自持一个分页游标(同窗就是同游标)')
|
||||||
|
assert.doesNotMatch(page, /matrixRows/, '矩阵不再客户端切片(行窗口是服务端切的)')
|
||||||
assert.match(page, /<OldPagination[^>]*:total="distCount"/, '分布分页器无 v-if 条件')
|
assert.match(page, /<OldPagination[^>]*:total="distCount"/, '分布分页器无 v-if 条件')
|
||||||
assert.match(page, /<OldPagination[^>]*:total="dupRows\.length"/, '矩阵/详情分页器无 v-if 条件')
|
assert.match(page, /<OldPagination[^>]*:total="totalDupCount"/, '矩阵/详情分页器无 v-if 条件')
|
||||||
assert.match(page, /v-for="group in pagedGroupStats"/, '分组说明抽屉表绑定分页切片')
|
assert.match(page, /v-for="group in pagedGroupStats"/, '分组说明抽屉表绑定分页切片')
|
||||||
assert.match(page, /:total="groupStats\.length"/, '分组说明抽屉表有分页器')
|
assert.match(page, /:total="groupStats\.length"/, '分组说明抽屉表有分页器')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B60 的前后两处出口:行窗口三键要真发出去,矩阵格子要一次算完。
|
||||||
|
* 反向自证:把 api 改回不带 page/page_size、或把模板改回逐格 filter,即红。
|
||||||
|
*/
|
||||||
|
test('align_dup_console_b60_row_window_and_precomputed_cells', () => {
|
||||||
|
const api = readSource('src/pages/tasks/duplicate-console-api.ts')
|
||||||
|
assert.match(api, /page, page_size: pageSize/, 'console 请求带行窗口参数')
|
||||||
|
assert.match(api, /query\.dup_group = group/, 'console 请求带分组裁行参数')
|
||||||
|
assert.doesNotMatch(api, /多余分页参数后端忽略/, '旧注释说分页参数被后端忽略,现在后端认了')
|
||||||
|
|
||||||
|
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
|
||||||
|
// 矩阵窗口那一层已从页面拆进 `duplicate-matrix-window.ts`(B60 之后本页顶在可读性基线的
|
||||||
|
// 超长文件名单上,只许减)。绊线跟着搬,判据一字不松:改回逐格 filter 照样红。
|
||||||
|
const matrix = readSource('src/pages/tasks/duplicate-matrix-window.ts')
|
||||||
|
assert.match(page, /useDuplicateMatrix\(/, '页面接的是矩阵窗口组合式')
|
||||||
|
assert.match(matrix, /buildMatrixCells\(/, '矩阵格子一次预聚合')
|
||||||
|
assert.match(matrix, /MATRIX_COLUMN_WINDOW = 40/, '列数有窗口上限(按列切窗)')
|
||||||
|
assert.match(page, /v-for="\(cell, index\) in row\.cells"/, '模板只读预聚合好的格子')
|
||||||
|
assert.doesNotMatch(page, /function cellCount\(/, '逐格 filter 那套函数已收掉')
|
||||||
|
assert.doesNotMatch(matrix, /function cellCount\(/, '窗口组合式里也不许再长出逐格 filter')
|
||||||
|
|
||||||
|
const service = readSource('../backend-java/src/main/java/com/nanri/aiimage/modules/shopduplicatecheck/service/ShopDataDuplicateCheckQueryService.java')
|
||||||
|
assert.match(service, /consoleData\(DuplicateScanView view, Set<String> visibleKeys, Filters filters,\s*\n?\s*int page, int pageSize, String dupGroup\)/,
|
||||||
|
'服务端 console 收行窗口与分组参数')
|
||||||
|
assert.match(service, /"total_dup", total,/, 'total_dup 是未分页总数,不是本页行数')
|
||||||
|
})
|
||||||
|
|
||||||
test('align_dup_console_ledger_total_preload', () => {
|
test('align_dup_console_ledger_total_preload', () => {
|
||||||
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
|
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
|
||||||
assert.match(page, /onMounted\(\(\) => \{\s*loadConsole\(\).*loadLedger\(1\)/s, '挂载即预取台账计数')
|
assert.match(page, /onMounted\(\(\) => \{\s*loadConsole\(\).*loadLedger\(1\)/s, '挂载即预取台账计数')
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||||
"totals": {
|
"totals": {
|
||||||
"files": 253,
|
"files": 254,
|
||||||
"cases": 1772,
|
"cases": 1778,
|
||||||
"pins": 457,
|
"pins": 458,
|
||||||
"reads": 652
|
"reads": 656
|
||||||
},
|
},
|
||||||
"files": {
|
"files": {
|
||||||
"admin-scaffold.test.ts": {
|
"admin-scaffold.test.ts": {
|
||||||
@@ -48,9 +48,9 @@
|
|||||||
"reads": 3
|
"reads": 3
|
||||||
},
|
},
|
||||||
"align-dup-console.test.ts": {
|
"align-dup-console.test.ts": {
|
||||||
"cases": 10,
|
"cases": 11,
|
||||||
"pins": 9,
|
"pins": 10,
|
||||||
"reads": 12
|
"reads": 16
|
||||||
},
|
},
|
||||||
"align-edit-user-auth-guard.test.ts": {
|
"align-edit-user-auth-guard.test.ts": {
|
||||||
"cases": 1,
|
"cases": 1,
|
||||||
@@ -272,8 +272,13 @@
|
|||||||
"pins": 5,
|
"pins": 5,
|
||||||
"reads": 6
|
"reads": 6
|
||||||
},
|
},
|
||||||
|
"dup-matrix-window.test.ts": {
|
||||||
|
"cases": 4,
|
||||||
|
"pins": 0,
|
||||||
|
"reads": 0
|
||||||
|
},
|
||||||
"duplicate-console.test.ts": {
|
"duplicate-console.test.ts": {
|
||||||
"cases": 5,
|
"cases": 6,
|
||||||
"pins": 0,
|
"pins": 0,
|
||||||
"reads": 0
|
"reads": 0
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { buildMatrixCells, matrixCellOf, storeColumnsOf } from '../src/pages/tasks/duplicate-console-logic.ts'
|
||||||
|
import type { DuplicateItem, DuplicateOccurrence } from '../src/pages/tasks/duplicate-model.ts'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B60 撞款矩阵:预聚合的等价性与前后读数。
|
||||||
|
*
|
||||||
|
* 审计指的那件事是「每格多次全量 filter」——模板一格要付 cellCount ×2 + cellTitle(内部再
|
||||||
|
* cellCount + cellCountryDots + 每站点一次 cellCountryCount),每次都是把该行 occurrences 整份
|
||||||
|
* filter 一遍,而且**每格都新建一条文案字符串**。下面 `legacyCell` 就是页面原来那几行函数的
|
||||||
|
* 原样搬运,当"前";与新一次算完的 `buildMatrixCells`(空格按列共用一份视图)对撞:
|
||||||
|
* 先证明结果逐字相同(预聚合不是靠少算蒙过去的),再同尺量时间。
|
||||||
|
*/
|
||||||
|
function occ(asin: string, shopName: string, country: string): DuplicateOccurrence {
|
||||||
|
return {
|
||||||
|
asin,
|
||||||
|
date: '2026-09-01',
|
||||||
|
price: '',
|
||||||
|
brand: 'B',
|
||||||
|
shopName,
|
||||||
|
groupName: '',
|
||||||
|
countryCodes: [country],
|
||||||
|
country,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const shopKey = (name: string): string => (name || '').trim().toLowerCase()
|
||||||
|
|
||||||
|
interface CellView {
|
||||||
|
count: number
|
||||||
|
dots: string[]
|
||||||
|
title: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 原页面的逐格算法(一格扫整行 occurrences 若干次,并且每格造一条文案)。 */
|
||||||
|
function legacyCellOccurrences(item: DuplicateItem, shop: string): DuplicateOccurrence[] {
|
||||||
|
const key = shopKey(shop)
|
||||||
|
return (item.occurrences || []).filter((entry) => shopKey(entry.shopName) === key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function legacyCell(item: DuplicateItem, shop: string): CellView {
|
||||||
|
const count = legacyCellOccurrences(item, shop).length
|
||||||
|
const codes = new Set<string>()
|
||||||
|
for (const entry of legacyCellOccurrences(item, shop)) if (entry.country) codes.add(entry.country.toUpperCase())
|
||||||
|
const dots = [...codes]
|
||||||
|
const sites = dots.map((code) => `${code} ${legacyCellOccurrences(item, shop).filter((entry) => (entry.country || '').toUpperCase() === code).length}条`)
|
||||||
|
return {
|
||||||
|
count,
|
||||||
|
dots,
|
||||||
|
title: count ? `${shop} 在售 ${count} 条 · ${sites.join('、')}` : `${shop} 无此 ASIN`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 页面现在的读法:一次取值;空格取该列那一份共用视图(不再造文案)。 */
|
||||||
|
function fastCell(cells: ReturnType<typeof buildMatrixCells>, item: DuplicateItem, shop: string, blank: CellView): CellView {
|
||||||
|
const cell = matrixCellOf(cells, item.asin, shop)
|
||||||
|
if (!cell.count) return blank
|
||||||
|
const sites = cell.sites.map((site) => `${site.code} ${site.count}条`)
|
||||||
|
return {
|
||||||
|
count: cell.count,
|
||||||
|
dots: cell.sites.map((site) => site.code),
|
||||||
|
title: sites.length ? `${shop} 在售 ${cell.count} 条 · ${sites.join('、')}` : `${shop} 在售 ${cell.count} 条`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixtureItem(asin: string, shops: [string, string][]): DuplicateItem {
|
||||||
|
const occurrences = shops.map(([shop, country]) => occ(asin, shop, country))
|
||||||
|
return {
|
||||||
|
asin,
|
||||||
|
shopCount: new Set(occurrences.map((entry) => shopKey(entry.shopName))).size,
|
||||||
|
recordCount: occurrences.length,
|
||||||
|
occurrences,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function blankViews(columns: string[]): CellView[] {
|
||||||
|
return columns.map((shop) => ({ count: 0, dots: [] as string[], title: `${shop} 无此 ASIN` }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 200 列 × 50 行的矩阵夹具。`shopsPerRow` 决定密度:现实中一个撞款 ASIN 落在几家到几十家店,
|
||||||
|
* 而逐格 filter 的代价正是按「行内 occurrences × 列数」乘出来的——密度越高旧算法越吃亏,
|
||||||
|
* 所以两种密度都取读数,不挑对自己有利的那一档。
|
||||||
|
*/
|
||||||
|
function matrixFixture(columns: string[], shopsPerRow: number): DuplicateItem[] {
|
||||||
|
return Array.from({ length: 50 }, (_, index) => {
|
||||||
|
const pairs: [string, string][] = []
|
||||||
|
for (let offset = 0; offset < shopsPerRow; offset++) {
|
||||||
|
const shop = columns[(index * 7 + offset * 61) % columns.length]
|
||||||
|
pairs.push([shop, 'UK'], [shop, 'DE'])
|
||||||
|
}
|
||||||
|
return fixtureItem(`B${String(index).padStart(4, '0')}`, pairs)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
test('矩阵预聚合与逐格 filter 结果逐字相同', () => {
|
||||||
|
const rows = [
|
||||||
|
fixtureItem('A1', [['Shop a', 'UK'], ['Shop a', 'uk'], ['ShopB', ''], ['ShopB', 'DE']]),
|
||||||
|
fixtureItem('A2', [['ShopC', 'FR']]),
|
||||||
|
]
|
||||||
|
const columns = storeColumnsOf(rows)
|
||||||
|
const cells = buildMatrixCells(rows, columns)
|
||||||
|
const blanks = blankViews(columns)
|
||||||
|
columns.forEach((column, index) => {
|
||||||
|
for (const item of rows) {
|
||||||
|
assert.deepEqual(fastCell(cells, item, column, blanks[index]), legacyCell(item, column), `${item.asin}/${column}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// 每行只给「本行真涉及」的列建格:A1 涉及 2 店(大小写/空格归一后同店)+ A2 涉及 1 店。
|
||||||
|
assert.equal(cells.size, 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('列集或行集为空时不建任何格', () => {
|
||||||
|
const rows = [fixtureItem('A1', [['ShopA', 'UK']])]
|
||||||
|
assert.equal(buildMatrixCells(rows, []).size, 0)
|
||||||
|
assert.equal(buildMatrixCells([], ['ShopA']).size, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 列窗口:只给本窗点名的列建格(120 列的夹具切 40 列窗口,格子数就按 40 乘)。 */
|
||||||
|
test('列窗口切窗后每行最多铺满窗口宽度的格', () => {
|
||||||
|
const window = 40
|
||||||
|
const rows = Array.from({ length: 50 }, (_, index) =>
|
||||||
|
fixtureItem(`A${index}`, Array.from({ length: window * 3 }, (_, shop) => [`Shop${shop}`, 'UK'])))
|
||||||
|
const all = storeColumnsOf(rows)
|
||||||
|
assert.equal(all.length, window * 3, '夹具本身就有 120 列(不设上限时的形状)')
|
||||||
|
|
||||||
|
const columns = all.slice(0, window)
|
||||||
|
const cells = buildMatrixCells(rows, columns)
|
||||||
|
assert.equal(columns.length, window, '本窗只铺 40 列')
|
||||||
|
assert.equal(cells.size, rows.length * window, '窗口外的 80 列一格都不建')
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B60 判据的读数:200 列 × 50 行,同一把尺前后各跑一遍(5 轮取最好一次——本机同时有别的路在跑,
|
||||||
|
* 单次读数能被调度噪声放大好几倍)。
|
||||||
|
*
|
||||||
|
* 度量对象是「矩阵格集合的 JS 计算」,审计点名的就是这条。**浏览器首屏/交互耗时本机拿不到**
|
||||||
|
* (没有真实店铺数据、也没有浏览器现场),按准出括注登记为现网复量项,不许拿这条当"首屏已实测"读。
|
||||||
|
*/
|
||||||
|
test('200列×50行:预聚合与按列切窗都必须快过逐格 filter', () => {
|
||||||
|
const columns = Array.from({ length: 200 }, (_, index) => `Shop${index}`)
|
||||||
|
const blanks = blankViews(columns)
|
||||||
|
const windowColumns = columns.slice(0, 40)
|
||||||
|
const windowBlanks = blanks.slice(0, 40)
|
||||||
|
const best = (run: () => unknown): number => {
|
||||||
|
let ms = Number.POSITIVE_INFINITY
|
||||||
|
for (let attempt = 0; attempt < 5; attempt++) {
|
||||||
|
const start = performance.now()
|
||||||
|
run()
|
||||||
|
ms = Math.min(ms, performance.now() - start)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
|
||||||
|
const readings: string[] = []
|
||||||
|
for (const shopsPerRow of [3, 40]) {
|
||||||
|
const rows = matrixFixture(columns, shopsPerRow)
|
||||||
|
const legacySweep = () => {
|
||||||
|
const out: CellView[] = []
|
||||||
|
for (const item of rows) for (const column of columns) out.push(legacyCell(item, column))
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
const precomputedSweep = (cols: string[], cellBlanks: CellView[]) => {
|
||||||
|
const cells = buildMatrixCells(rows, cols)
|
||||||
|
const out: CellView[] = []
|
||||||
|
for (const item of rows) {
|
||||||
|
cols.forEach((column, index) => out.push(fastCell(cells, item, column, cellBlanks[index])))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(precomputedSweep(columns, blanks), legacySweep(), '前后必须同一份格子(快不是靠少算)')
|
||||||
|
|
||||||
|
const beforeMs = best(legacySweep)
|
||||||
|
const precomputeMs = best(() => precomputedSweep(columns, blanks))
|
||||||
|
const shippedMs = best(() => precomputedSweep(windowColumns, windowBlanks))
|
||||||
|
readings.push(`每行${shopsPerRow}店:逐格filter=${beforeMs.toFixed(1)}ms → 预聚合=${precomputeMs.toFixed(1)}ms(${(beforeMs / precomputeMs).toFixed(1)}×) → 预聚合+切窗40列=${shippedMs.toFixed(1)}ms(${(beforeMs / shippedMs).toFixed(1)}×)`)
|
||||||
|
assert.ok(precomputeMs < beforeMs, `预聚合没省下来(每行${shopsPerRow}店):${beforeMs.toFixed(1)}ms → ${precomputeMs.toFixed(1)}ms`)
|
||||||
|
assert.ok(shippedMs * 2 < beforeMs, `切窗后仍不够快(每行${shopsPerRow}店):${beforeMs.toFixed(1)}ms → ${shippedMs.toFixed(1)}ms`)
|
||||||
|
}
|
||||||
|
console.log(`[B60 读数] 200列×50行 ${readings.join(' | ')}`)
|
||||||
|
})
|
||||||
@@ -2,8 +2,9 @@ import test from 'node:test'
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { parseDuplicateConsole, parseLedgerPage, parseConsoleGroup, parseLedgerRow } from '../src/pages/tasks/duplicate-console-model.ts'
|
import { parseDuplicateConsole, parseLedgerPage, parseConsoleGroup, parseLedgerRow } from '../src/pages/tasks/duplicate-console-model.ts'
|
||||||
import {
|
import {
|
||||||
|
buildMatrixCells,
|
||||||
indexShopGroups,
|
indexShopGroups,
|
||||||
dupWithinGroup,
|
matrixCellOf,
|
||||||
storeColumnsOf,
|
storeColumnsOf,
|
||||||
} from '../src/pages/tasks/duplicate-console-logic.ts'
|
} from '../src/pages/tasks/duplicate-console-logic.ts'
|
||||||
|
|
||||||
@@ -49,6 +50,21 @@ test('test_dup_console_model_parses_overview_dup_and_groups', () => {
|
|||||||
assert.deepEqual(group, { name: 'GroupA', shopCount: 2, asinUnique: 4, recordCount: 6, dupCount: 2 })
|
assert.deepEqual(group, { name: 'GroupA', shopCount: 2, asinUnique: 4, recordCount: 6, dupCount: 2 })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** B60:console 多了行窗口三键;缺字段要退得回安全默认(page 至少 1,pageSize 缺省 0=调用方自持)。 */
|
||||||
|
test('test_dup_console_model_parses_row_window', () => {
|
||||||
|
const windowed = parseDuplicateConsole({
|
||||||
|
success: true,
|
||||||
|
data: { pending: false, dup: [], groups: [], total_dup: 2650, page: 3, page_size: 50 },
|
||||||
|
})
|
||||||
|
assert.equal(windowed.totalDup, 2650, 'total_dup 是该范围未分页总数,不是本页行数')
|
||||||
|
assert.equal(windowed.page, 3)
|
||||||
|
assert.equal(windowed.pageSize, 50)
|
||||||
|
|
||||||
|
const legacy = parseDuplicateConsole({ success: true, data: { pending: false, dup: [], groups: [] } })
|
||||||
|
assert.equal(legacy.page, 1, '没有 page 字段时读成第一页,别让分页控件显示第 0 页')
|
||||||
|
assert.equal(legacy.pageSize, 0)
|
||||||
|
})
|
||||||
|
|
||||||
test('test_dup_console_parse_group_ignores_missing_name', () => {
|
test('test_dup_console_parse_group_ignores_missing_name', () => {
|
||||||
assert.equal(parseConsoleGroup({ shop_count: 1 }), null)
|
assert.equal(parseConsoleGroup({ shop_count: 1 }), null)
|
||||||
assert.ok(parseConsoleGroup({ name: 'G', shop_count: 2 }))
|
assert.ok(parseConsoleGroup({ name: 'G', shop_count: 2 }))
|
||||||
@@ -71,15 +87,9 @@ test('test_dup_console_group_derivation_restricts_to_members', () => {
|
|||||||
])
|
])
|
||||||
assert.deepEqual(groups.members.GroupA, ['ShopA', 'ShopB'])
|
assert.deepEqual(groups.members.GroupA, ['ShopA', 'ShopB'])
|
||||||
assert.deepEqual(groups.shopGroupNames.ShopC, ['GroupC'])
|
assert.deepEqual(groups.shopGroupNames.ShopC, ['GroupC'])
|
||||||
|
assert.deepEqual(storeColumnsOf([dupA, dupE], groups.members.GroupA), ['ShopA', 'ShopB'])
|
||||||
const inGroupA = dupWithinGroup([dupA, dupE], groups.members.GroupA)
|
// 「组内 ≥2 店才算撞款」的裁行只剩服务端一处正本(console 的 dup_group)——
|
||||||
assert.equal(inGroupA.length, 2)
|
// 页面原先在客户端用 dupWithinGroup 再裁一遍,那是同一规则的第二个正本,B60 收掉它。
|
||||||
// E 组内只剩 ShopA/ShopB 两条记录。
|
|
||||||
const e = inGroupA.find((item) => item.asin === 'E')
|
|
||||||
assert.equal(e?.shopCount, 2)
|
|
||||||
assert.equal(e?.recordCount, 2)
|
|
||||||
// 单店成员组内不会命中(ShopD 不在数据里)。
|
|
||||||
assert.deepEqual(dupWithinGroup([dupA, dupE], ['ShopD']), [])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('test_dup_console_store_columns_order_and_restriction', () => {
|
test('test_dup_console_store_columns_order_and_restriction', () => {
|
||||||
|
|||||||
@@ -101,11 +101,131 @@
|
|||||||
<groupId>org.apache.rocketmq</groupId>
|
<groupId>org.apache.rocketmq</groupId>
|
||||||
<artifactId>rocketmq-spring-boot-starter</artifactId>
|
<artifactId>rocketmq-spring-boot-starter</artifactId>
|
||||||
<version>${rocketmq-spring.version}</version>
|
<version>${rocketmq-spring.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<!-- 2026-11-03 流程稳定性蓝图 Phase 1(流程稳定性与性能优化)依赖瘦身。
|
||||||
|
判据全部来自 mvn -o dependency:tree + 对 rocketmq 系 jar 的字节码常量池扫描
|
||||||
|
(本机 D:/dev/m2/repository,2026-11-03 实测),不是拍脑袋:
|
||||||
|
|
||||||
|
[CN-04] hamcrest/awaitility:rocketmq-spring-boot 2.3.5 把自家测试库错标成
|
||||||
|
compile 依赖泄进 fat jar;7 支 rocketmq 运行时 jar 扫描 0 引用 ⇒ 排除。
|
||||||
|
|
||||||
|
[S-be-3] 本服务 MQ 只走 name-server remoting(application.yml:
|
||||||
|
rocketmq.name-server=:9876,@RocketMQMessageListener = spring starter
|
||||||
|
的 remoting 路径),gRPC proxy 路径运行期不加载:
|
||||||
|
- rocketmq-proto + protobuf-java(-util):只被 proto 的 gRPC stub 与
|
||||||
|
rocketmq-acl 的 PlainAccessValidator 引用(ACL 未启用不加载);
|
||||||
|
- io.grpc 五件:rocketmq-client/remoting/acl 扫描里只有 common 的
|
||||||
|
GrpcConstants 引用(remoting 路径 0 引用);
|
||||||
|
- zstd-jni:只被 ZstdCompressor 引用(仅消息压缩档配 ZSTD 才加载);
|
||||||
|
- snappy-java:全链 0 引用;
|
||||||
|
- opentelemetry 导出器全家(otlp/prometheus/logging/sender):
|
||||||
|
传输路径类(NettyRemotingAbstract/RemotingMetricsManager/Nop*)
|
||||||
|
只引用 api/+sdk/ 子包,exporter/ 子包 0 引用 ⇒ 排除导出器、
|
||||||
|
保留 api+sdk(remoting 指标门面照常工作)。
|
||||||
|
|
||||||
|
[S-be-2] fastjson2:只被 ACL 模型枚举与 AclUtils 引用(ACL 关闭不加载)。
|
||||||
|
⚠ fastjson1 (com.alibaba:fastjson) 与 guava 必须保留——字节码扫描实锤
|
||||||
|
rocketmq-remoting 的 RemotingCommand/HeartbeatData/SubscriptionData 与
|
||||||
|
NettyRemotingClient 等 10/41 个 remoting 线路类引用它们,排除=生产
|
||||||
|
任务队列运行期 NoClassDefFoundError。审计"src 零 import"只覆盖我们
|
||||||
|
自己的代码,证不了 rocketmq 内部引用,两条放弃并在此留痕。
|
||||||
|
|
||||||
|
红线:发版后必须核对 MQ 真实收发(任务队列 + 结果文件队列各一条),
|
||||||
|
字节码扫描+整量测试+真机启动都盖不到生产 broker 上的线路行为。 -->
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.awaitility</groupId>
|
||||||
|
<artifactId>awaitility</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>com.alibaba.fastjson2</groupId>
|
||||||
|
<artifactId>fastjson2</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.xerial.snappy</groupId>
|
||||||
|
<artifactId>snappy-java</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>com.github.luben</groupId>
|
||||||
|
<artifactId>zstd-jni</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.apache.rocketmq</groupId>
|
||||||
|
<artifactId>rocketmq-proto</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java-util</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.grpc</groupId>
|
||||||
|
<artifactId>grpc-netty-shaded</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.grpc</groupId>
|
||||||
|
<artifactId>grpc-core</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.grpc</groupId>
|
||||||
|
<artifactId>grpc-stub</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.grpc</groupId>
|
||||||
|
<artifactId>grpc-api</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.grpc</groupId>
|
||||||
|
<artifactId>grpc-context</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-otlp</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-otlp-common</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-common</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-sender-okhttp</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-prometheus</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-logging</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-exporter-logging-otlp</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>io.opentelemetry</groupId>
|
||||||
|
<artifactId>opentelemetry-sdk-extension-autoconfigure-spi</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.minio</groupId>
|
<groupId>io.minio</groupId>
|
||||||
<artifactId>minio</artifactId>
|
<artifactId>minio</artifactId>
|
||||||
<version>${minio.version}</version>
|
<version>${minio.version}</version>
|
||||||
|
<!-- 2026-11-03 实录:曾试排除传递的 snappy-java(字节码扫描只见 uploadSnowballObjects
|
||||||
|
一条冷门引用),整量一跑 MinioClient$Builder.<init> 当场
|
||||||
|
NoClassDefFoundError: SnappyFramedOutputStream——minio 在 Builder 构造期就急切
|
||||||
|
解析 snappy 类,静态扫描判不了初始化期的类加载。已撤销,snappy 必须保留。 -->
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.bouncycastle</groupId>
|
<groupId>org.bouncycastle</groupId>
|
||||||
@@ -132,6 +252,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
|
<!-- 2026-11-03 瘦身审计 CN-03:lombok 是纯编译期注解处理器,运行期零用途;
|
||||||
|
原先只有 optional 没 provided,spring-boot repackage 照打进 BOOT-INF/lib
|
||||||
|
(实测 2,054,266 B)。annotationProcessorPaths 已单独钉 1.18.36,编译不受影响。 -->
|
||||||
|
<scope>provided</scope>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
+54
-17
@@ -1,8 +1,11 @@
|
|||||||
package com.nanri.aiimage.common.module;
|
package com.nanri.aiimage.common.module;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -16,6 +19,12 @@ import java.util.stream.Collectors;
|
|||||||
*
|
*
|
||||||
* 心跳与陈旧判死两处是代码分支驱动(switch / 逐模块委派),无法纯数据派生,
|
* 心跳与陈旧判死两处是代码分支驱动(switch / 逐模块委派),无法纯数据派生,
|
||||||
* 新增模块时仍需实现对应 Handler,测试会提示缺失。
|
* 新增模块时仍需实现对应 Handler,测试会提示缺失。
|
||||||
|
*
|
||||||
|
* 建单凭据({@code submitSecret},B72-01)同样登记在本表:「这一类任务要拿用户的哪把密钥跑」
|
||||||
|
* 的唯一出处。`/newApi` 是整包转发的透传面,客户端猜不出载荷要什么凭据,只能由服务端按 type
|
||||||
|
* 逐类登记。这里刻意区分两件事:登记了 = 建单口必须问这把;`Optional.empty()` = **登记过的结论**
|
||||||
|
* 「这一类建单时不需要用户凭据」,不是漏填——`TaskModuleCoverageTest` 把「问了闸门却没登记」与
|
||||||
|
* 「登记了却没问闸门」两个方向都钉红,空壳闸门比没闸门更坏(铁律 27 边界 c)。
|
||||||
*/
|
*/
|
||||||
public final class TaskModuleRegistry {
|
public final class TaskModuleRegistry {
|
||||||
|
|
||||||
@@ -31,28 +40,34 @@ public final class TaskModuleRegistry {
|
|||||||
* @param selfScheduledStaleCheck 该模块的陈旧判死自带更快的调度(publish 60s / collect-data 30s),
|
* @param selfScheduledStaleCheck 该模块的陈旧判死自带更快的调度(publish 60s / collect-data 30s),
|
||||||
* 刻意不并入 2 分钟一轮的巡检线——并入会显著拉长判死时延。
|
* 刻意不并入 2 分钟一轮的巡检线——并入会显著拉长判死时延。
|
||||||
* 这类模块的"不在委托名单"是设计差异,不是漏接;由覆盖面测试固定。
|
* 这类模块的"不在委托名单"是设计差异,不是漏接;由覆盖面测试固定。
|
||||||
|
* @param submitSecret 建单口要问的那把用户密钥;{@code Optional.empty()} 是**登记过的结论**
|
||||||
|
* "这一类不缺凭据也能跑"(例:缺代理在本机执行类是直连降级,
|
||||||
|
* 不是注定失败——铁律 27 边界 c,拦了会把现在能跑的功能判死)。
|
||||||
*/
|
*/
|
||||||
public record Module(String type, String label, boolean resultFileJob, boolean ageCleanup,
|
public record Module(String type, String label, boolean resultFileJob, boolean ageCleanup,
|
||||||
boolean delegatedStaleCheck, boolean selfScheduledStaleCheck) {
|
boolean delegatedStaleCheck, boolean selfScheduledStaleCheck,
|
||||||
|
Optional<UserSecretModule> submitSecret) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final List<Module> MODULES = List.of(
|
private static final List<Module> MODULES = List.of(
|
||||||
new Module("PUBLISH", "上架", true, false, false, true),
|
new Module("PUBLISH", "上架", true, false, false, true, Optional.empty()),
|
||||||
new Module("DEDUPE", "数据去重", false, true, false, false),
|
new Module("DEDUPE", "数据去重", false, true, false, false, Optional.empty()),
|
||||||
new Module("SPLIT", "数据拆分", false, true, false, false),
|
new Module("SPLIT", "数据拆分", false, true, false, false, Optional.empty()),
|
||||||
new Module("CONVERT", "格式转换", false, true, false, false),
|
new Module("CONVERT", "格式转换", false, true, false, false, Optional.empty()),
|
||||||
new Module("DELETE_BRAND", "删除ASIN", true, true, false, false),
|
new Module("DELETE_BRAND", "删除ASIN", true, true, false, false, Optional.empty()),
|
||||||
new Module("PRODUCT_RISK_RESOLVE", "商品风险解决", true, true, false, false),
|
new Module("PRODUCT_RISK_RESOLVE", "商品风险解决", true, true, false, false, Optional.empty()),
|
||||||
new Module("PRICE_TRACK", "跟价", true, true, false, false),
|
new Module("PRICE_TRACK", "跟价", true, true, false, false, Optional.empty()),
|
||||||
new Module("SHOP_MATCH", "定时匹配", true, true, false, false),
|
new Module("SHOP_MATCH", "定时匹配", true, true, false, false, Optional.empty()),
|
||||||
new Module("PATROL_DELETE", "巡店删除", true, true, false, false),
|
new Module("PATROL_DELETE", "巡店删除", true, true, false, false, Optional.empty()),
|
||||||
new Module("QUERY_ASIN", "查询ASIN", true, true, false, false),
|
new Module("QUERY_ASIN", "查询ASIN", true, true, false, false, Optional.empty()),
|
||||||
new Module("WITHDRAW", "取款", true, true, false, false),
|
new Module("WITHDRAW", "取款", true, true, false, false, Optional.empty()),
|
||||||
new Module("APPEARANCE_PATENT", "外观专利检测", true, true, true, false),
|
new Module("APPEARANCE_PATENT", "外观专利检测", true, true, true, false,
|
||||||
new Module("SIMILAR_ASIN", "货源查询", true, true, true, false),
|
Optional.of(UserSecretModule.APPEARANCE_PATENT)),
|
||||||
new Module("COLLECT_DATA", "采集数据", true, true, false, true),
|
new Module("SIMILAR_ASIN", "货源查询", true, true, true, false,
|
||||||
new Module("SHOP_DATA_CRAWL", "店铺数据抓取", true, false, true, false),
|
Optional.of(UserSecretModule.SIMILAR_ASIN)),
|
||||||
new Module("BRAND", "品牌检测", true, false, true, false)
|
new Module("COLLECT_DATA", "采集数据", true, true, false, true, Optional.empty()),
|
||||||
|
new Module("SHOP_DATA_CRAWL", "店铺数据抓取", true, false, true, false, Optional.empty()),
|
||||||
|
new Module("BRAND", "品牌检测", true, false, true, false, Optional.empty())
|
||||||
);
|
);
|
||||||
|
|
||||||
private TaskModuleRegistry() {
|
private TaskModuleRegistry() {
|
||||||
@@ -100,6 +115,28 @@ public final class TaskModuleRegistry {
|
|||||||
.collect(Collectors.toUnmodifiableSet());
|
.collect(Collectors.toUnmodifiableSet());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建单口这一类任务要问的那把用户密钥(B72-01 的唯一出处)。
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException moduleType 根本不在清单里(拼错的常量名)。
|
||||||
|
* 刻意不跟 {@link #labelOf} 一样回落原值:「没登记」与「登记过=不需要」是两件事,
|
||||||
|
* 揉成同一个空值会让调用方把漏接当成结论。
|
||||||
|
*/
|
||||||
|
public static Optional<UserSecretModule> submitSecretModuleOf(String moduleType) {
|
||||||
|
for (Module module : MODULES) {
|
||||||
|
if (module.type().equals(moduleType)) {
|
||||||
|
return module.submitSecret();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("模块不在清单里: " + moduleType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登记了建单凭据的模块(覆盖面测试用它对撞「实际在建单口问闸门的类型」)。 */
|
||||||
|
public static Set<String> submitSecretModuleTypes() {
|
||||||
|
return MODULES.stream().filter(module -> module.submitSecret().isPresent())
|
||||||
|
.map(Module::type).collect(Collectors.toUnmodifiableSet());
|
||||||
|
}
|
||||||
|
|
||||||
public static String labelOf(String moduleType) {
|
public static String labelOf(String moduleType) {
|
||||||
for (Module module : MODULES) {
|
for (Module module : MODULES) {
|
||||||
if (module.type().equals(moduleType)) {
|
if (module.type().equals(moduleType)) {
|
||||||
|
|||||||
+45
-2
@@ -4,10 +4,13 @@ import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResu
|
|||||||
import com.nanri.aiimage.modules.task.service.AbstractPendingRowTaskCacheService;
|
import com.nanri.aiimage.modules.task.service.AbstractPendingRowTaskCacheService;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.redis.core.Cursor;
|
||||||
|
import org.springframework.data.redis.core.ScanOptions;
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,9 +39,45 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
|||||||
super("appearance-patent", AppearancePatentResultRowDto.class, stringRedisTemplate, objectMapper);
|
super("appearance-patent", AppearancePatentResultRowDto.class, stringRedisTemplate, objectMapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 单次清理最多删除多少枚逐行标记(游标侧的安全阀,防止把一次清理变成无界扫描)。 */
|
||||||
|
private static final int ROW_MARK_DELETE_LIMIT = 20_000;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void deleteExtraTaskCacheKeys(Long taskId) {
|
protected void deleteExtraTaskCacheKeys(Long taskId) {
|
||||||
stringRedisTemplate.delete(processedRowsKey(taskId));
|
// B74-01:这里原本删的是 processedRowsKey(taskId)——一枚**从不被写入**的基键。
|
||||||
|
// 真实完成标记是逐行键 ...:processed-rows:{taskId}:{rowKey},所以"清了任务缓存"
|
||||||
|
// 一枚行标记都清不掉:任务清完后 24 小时内重建,行仍被标记挡着不再检测,
|
||||||
|
// 声称保护但不保护。逐行键没有索引,只能按前缀游标扫;用 SCAN 而不是 KEYS
|
||||||
|
// (KEYS 在生产 redis 上是阻塞命令)。
|
||||||
|
String pattern = processedRowsKey(taskId) + ":*";
|
||||||
|
List<String> found = new ArrayList<>();
|
||||||
|
try (Cursor<String> cursor = stringRedisTemplate.scan(
|
||||||
|
ScanOptions.scanOptions().match(pattern).count(500).build())) {
|
||||||
|
while (cursor != null && cursor.hasNext()) {
|
||||||
|
String key = cursor.next();
|
||||||
|
if (key != null && !key.isBlank()) {
|
||||||
|
found.add(key);
|
||||||
|
}
|
||||||
|
if (found.size() >= ROW_MARK_DELETE_LIMIT) {
|
||||||
|
log.warn("[appearance-patent-cache] 行标记清理已达单轮上限,剩余由 TTL 兜底 "
|
||||||
|
+ "taskId={} limit={}", taskId, ROW_MARK_DELETE_LIMIT);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
// 与本类其余降级口径一致:清不掉就报出来,别让调用方以为"已经清干净了"。
|
||||||
|
log.warn("[appearance-patent-cache] delete row marks degraded taskId={} pattern={} msg={}",
|
||||||
|
taskId, pattern, ex.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (found.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 逐行键一起删:基键顺手也删一次(今天它依然不存在,但形状上它是这一族的目录名)。
|
||||||
|
found.add(processedRowsKey(taskId));
|
||||||
|
stringRedisTemplate.delete(found);
|
||||||
|
log.info("[appearance-patent-cache] 行标记已随任务缓存清理 taskId={} rowMarks={}",
|
||||||
|
taskId, found.size() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -58,7 +97,11 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
|||||||
}
|
}
|
||||||
Boolean first = stringRedisTemplate.opsForValue().setIfAbsent(
|
Boolean first = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||||
inFlightRowKey(taskId, rowKey), "1", IN_FLIGHT_TTL);
|
inFlightRowKey(taskId, rowKey), "1", IN_FLIGHT_TTL);
|
||||||
return first == null || first;
|
// B74-01:Redis 回 null(管道/事务态、集群未回包)不等于"抢到了"。旧写法
|
||||||
|
// `first == null || first` 把「没抢到」读成「抢到了」,同一行可能被两个入口同时发出去
|
||||||
|
// ——重复计费,且两路各自 CAS 同一行。读不出就按未抢到处理,让下一轮重新申领。
|
||||||
|
// 注意这不同于 Redis 抛异常:真降级在下面的 catch 里放行,由持久化层 isJudged 兜底。
|
||||||
|
return Boolean.TRUE.equals(first);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
log.warn("[appearance-patent-cache] begin row inspection degraded taskId={} rowKey={} msg={}", taskId, rowKey, ex.getMessage());
|
log.warn("[appearance-patent-cache] begin row inspection degraded taskId={} rowKey={} msg={}", taskId, rowKey, ex.getMessage());
|
||||||
// Redis 降级时放行,由持久化层的 AppearancePatentRowOutcome.isJudged 判据兜底去重。
|
// Redis 降级时放行,由持久化层的 AppearancePatentRowOutcome.isJudged 判据兜底去重。
|
||||||
|
|||||||
+3
-2
@@ -189,10 +189,11 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
|
|||||||
|
|
||||||
public AppearancePatentParseVo parseAndCreateTask(AppearancePatentParseRequest request, String deviceId) {
|
public AppearancePatentParseVo parseAndCreateTask(AppearancePatentParseRequest request, String deviceId) {
|
||||||
// 密钥闸门排在解析之前:Excel 解析与建单四段都要花时间与配额,而缺密钥的单跑完也只是
|
// 密钥闸门排在解析之前:Excel 解析与建单四段都要花时间与配额,而缺密钥的单跑完也只是
|
||||||
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret)。
|
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret;
|
||||||
|
// 这一类要哪把密钥登记在 TaskModuleRegistry,不在本文件写死)。
|
||||||
requireUserId(request.getUserId());
|
requireUserId(request.getUserId());
|
||||||
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
||||||
UserSecretModule.APPEARANCE_PATENT, request.getApiKey());
|
MODULE_TYPE, request.getApiKey());
|
||||||
return parsePipeline().parseAndCreateTask(request, deviceId);
|
return parsePipeline().parseAndCreateTask(request, deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+21
-3
@@ -122,6 +122,13 @@ public class AppearancePatentDeliverySupport {
|
|||||||
*
|
*
|
||||||
* <p>行级重发次数仍受 {@code llmRowMaxRounds} 约束(到顶的行会被判死并写上
|
* <p>行级重发次数仍受 {@code llmRowMaxRounds} 约束(到顶的行会被判死并写上
|
||||||
* 「重发轮次已达上限」的结论,从此不再是空行),所以这条不会无限循环。
|
* 「重发轮次已达上限」的结论,从此不再是空行),所以这条不会无限循环。
|
||||||
|
*
|
||||||
|
* <p>⚠ 那句「不会无限循环」2026-11-02 现网证伪,这里补上缺的那道闸:行级轮次只在行**真的
|
||||||
|
* 被发进 LLM 批次**时才累加,而交付缺口里最常见的形状是「该行没有可比对的图/载荷」——
|
||||||
|
* 它永远进不了批次,轮次永远是 0,于是补检→重组→补检跑个不停(33179 一个 1 行的缺口
|
||||||
|
* 六小时补了 70+ 轮,作业被卡死扫描记到 stuck_requeue_count=20 的判死线上)。所以成功出口
|
||||||
|
* 必须自己吃 {@code recheckMaxRounds}:预算耗尽就不再要补检,直接按已有行账出部分表,
|
||||||
|
* 缺口由行账文案标在表里,而不是让用户永远等一张不来的整表。
|
||||||
*/
|
*/
|
||||||
public boolean requestRecheckForMissingRows(FileTaskEntity task, TaskFileJobEntity job,
|
public boolean requestRecheckForMissingRows(FileTaskEntity task, TaskFileJobEntity job,
|
||||||
AppearancePatentRowOutcome.Facts facts) {
|
AppearancePatentRowOutcome.Facts facts) {
|
||||||
@@ -129,6 +136,14 @@ public class AppearancePatentDeliverySupport {
|
|||||||
|| facts.missingRows() <= 0 || facts.missingKeys().isEmpty()) {
|
|| facts.missingRows() <= 0 || facts.missingKeys().isEmpty()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
int maxRounds = properties.getRecheckMaxRounds();
|
||||||
|
long done = taskCacheService.recheckRounds(task.getId());
|
||||||
|
if (maxRounds > 0 && done >= maxRounds) {
|
||||||
|
log.warn("[appearance-patent] 交付缺口补检预算已耗尽,按已有结果交付"
|
||||||
|
+ " taskId={} jobId={} rounds={}/{} missingRows={} noDataRows={}",
|
||||||
|
task.getId(), job.getId(), done, maxRounds, facts.missingRows(), facts.noDataRows());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
List<String> keys = facts.missingKeys();
|
List<String> keys = facts.missingKeys();
|
||||||
// 只有这条出口允许连完成标记一起撤:结果落过库却又读不回来的行,不撤就永远补不回来。
|
// 只有这条出口允许连完成标记一起撤:结果落过库却又读不回来的行,不撤就永远补不回来。
|
||||||
// 代价(该行可能被重发一次 LLM、多扣一次次数)是这一档修法里用户点名要付的。
|
// 代价(该行可能被重发一次 LLM、多扣一次次数)是这一档修法里用户点名要付的。
|
||||||
@@ -136,6 +151,8 @@ public class AppearancePatentDeliverySupport {
|
|||||||
boolean requeued = taskFileJobService.requeue(job.getId(),
|
boolean requeued = taskFileJobService.requeue(job.getId(),
|
||||||
"有 " + facts.missingRows() + " 行未完成检测,补检一轮后重新组装结果文件");
|
"有 " + facts.missingRows() + " 行未完成检测,补检一轮后重新组装结果文件");
|
||||||
if (requeued) {
|
if (requeued) {
|
||||||
|
// 与失败兜底出口同一套预算、同一条记账纪律:只有重排真的接上才扣一轮。
|
||||||
|
taskCacheService.countRecheckRound(task.getId());
|
||||||
throttleRecheckWarning(task, job, facts);
|
throttleRecheckWarning(task, job, facts);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -148,9 +165,10 @@ public class AppearancePatentDeliverySupport {
|
|||||||
* 补检轮 WARN 的限流出口(AC-21):同一任务在一个窗口内只留一条 WARN,窗口里被压掉的条数
|
* 补检轮 WARN 的限流出口(AC-21):同一任务在一个窗口内只留一条 WARN,窗口里被压掉的条数
|
||||||
* 随下一条 WARN 一起汇总出去({@code suppressedInLastWindow}),窗口内的重复轮次降 DEBUG。
|
* 随下一条 WARN 一起汇总出去({@code suppressedInLastWindow}),窗口内的重复轮次降 DEBUG。
|
||||||
*
|
*
|
||||||
* <p>刻意不去碰 {@code taskCacheService.recheckRounds/countRecheckRound} 那对轮次计数:
|
* <p>{@code taskCacheService.recheckRounds/countRecheckRound} 那对轮次计数不在这里动:
|
||||||
* 那是 {@link #scheduleFallbackRecheck} 的补检预算({@code recheckMaxRounds})。从这条路径
|
* 那是补检预算({@code recheckMaxRounds}),从「日志限流」这条路再计一次会让限流吃掉业务预算,
|
||||||
* 再计一次,会让「日志限流」吃掉业务预算,任务更早被判「补检已耗尽」——那是行为变更,不是治理。
|
* 任务更早被判「补检已耗尽」——那是行为变更,不是治理。记账点在
|
||||||
|
* {@link #requestRecheckForMissingRows} 与 {@link #scheduleFallbackRecheck} 两个业务出口。
|
||||||
*
|
*
|
||||||
* <p>并发口径:读-判-写三步之间有竞争,最坏情况是同窗口多打一条 WARN。限流是为了压日志量,
|
* <p>并发口径:读-判-写三步之间有竞争,最坏情况是同窗口多打一条 WARN。限流是为了压日志量,
|
||||||
* 不是为了恰好一条,不值得为它加锁或把整张表串行化。
|
* 不是为了恰好一条,不值得为它加锁或把整张表串行化。
|
||||||
|
|||||||
+35
-1
@@ -208,7 +208,15 @@ public class AppearancePatentLlmBatchPipeline {
|
|||||||
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, llmRows, batchRows, rowKeyIndex);
|
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, llmRows, batchRows, rowKeyIndex);
|
||||||
// 完成标记只能打在真正落库的行上——这是「发版重启会不会丢行」的分界线
|
// 完成标记只能打在真正落库的行上——这是「发版重启会不会丢行」的分界线
|
||||||
if (batchAnswered) {
|
if (batchAnswered) {
|
||||||
List<String> landed = batchRowKeys.stream().filter(landedKeys::contains).toList();
|
// B74-01:landed(被塞回某个分片载荷)与 isJudged(有结论列)是两套判据,
|
||||||
|
// 谁说了算必须只有一个。候选侧(collectPendingLlmCandidates)用的是 isJudged,
|
||||||
|
// 所以完成标记也必须只打给 isJudged 认的行——否则一行拿到 24 小时标记却没有
|
||||||
|
// 结论列:它既不再是候选(被标记挡着),也没结论可出,只能等补检把标记连根撤掉。
|
||||||
|
Set<String> judgedKeys = judgedRowKeys(llmRows);
|
||||||
|
List<String> landed = batchRowKeys.stream()
|
||||||
|
.filter(landedKeys::contains)
|
||||||
|
.filter(judgedKeys::contains)
|
||||||
|
.toList();
|
||||||
if (!landed.isEmpty()) {
|
if (!landed.isEmpty()) {
|
||||||
taskCacheService.completeRowInspection(task.getId(), landed);
|
taskCacheService.completeRowInspection(task.getId(), landed);
|
||||||
}
|
}
|
||||||
@@ -547,6 +555,32 @@ public class AppearancePatentLlmBatchPipeline {
|
|||||||
return rowKeyer.apply(row);
|
return rowKeyer.apply(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本批里「已经有结论」的行键。候选侧({@code collectPendingLlmCandidates})与完成标记侧
|
||||||
|
* 共用同一枚 {@link AppearancePatentRowOutcome#isJudged},这就是 B74-01 要的同源判据:
|
||||||
|
* 「谁说了算」只能有一个,否则一行会同时「被标记挡住不再是候选」且「没有结论列可出」。
|
||||||
|
*
|
||||||
|
* <p>唯一的例外是 {@code terminalizeRoundExhaustedRows}:那里的行是按**轮次上限**终态化的
|
||||||
|
* (结论列写着「重发轮次已达上限」),它的完成标记正是有界路径的收口闸门,按 isJudged 再筛
|
||||||
|
* 会让这些行永远回到候选——那才是无界循环。
|
||||||
|
*/
|
||||||
|
private Set<String> judgedRowKeys(List<AppearancePatentResultRowDto> rows) {
|
||||||
|
Set<String> keys = new LinkedHashSet<>();
|
||||||
|
if (rows == null) {
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
for (AppearancePatentResultRowDto row : rows) {
|
||||||
|
if (row == null || !AppearancePatentRowOutcome.isJudged(row)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String key = rowKey(row);
|
||||||
|
if (key != null && !key.isBlank()) {
|
||||||
|
keys.add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
private Map<String, AppearancePatentResultRowDto> readChunkRows(TaskChunkEntity chunk) {
|
private Map<String, AppearancePatentResultRowDto> readChunkRows(TaskChunkEntity chunk) {
|
||||||
return chunkRowReader.apply(chunk);
|
return chunkRowReader.apply(chunk);
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -26,6 +26,7 @@ import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
|||||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
|
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||||
|
|
||||||
@@ -227,6 +228,7 @@ public class AppearancePatentResultJobSupport {
|
|||||||
task.setFailedFileCount(failed ? 1 : 0);
|
task.setFailedFileCount(failed ? 1 : 0);
|
||||||
// 缺口只写在消息里,不参与 failed 计算:95% 以上有结论的单仍是成功,但用户要看得见"N 行没检测完"
|
// 缺口只写在消息里,不参与 failed 计算:95% 以上有结论的单仍是成功,但用户要看得见"N 行没检测完"
|
||||||
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(finalError, deliveryFacts));
|
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(finalError, deliveryFacts));
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
|
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -295,6 +297,7 @@ public class AppearancePatentResultJobSupport {
|
|||||||
task.setSuccessFileCount(0);
|
task.setSuccessFileCount(0);
|
||||||
task.setFailedFileCount(1);
|
task.setFailedFileCount(1);
|
||||||
task.setErrorMessage(terminalMessage);
|
task.setErrorMessage(terminalMessage);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(LocalDateTime.now());
|
task.setFinishedAt(LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -472,6 +475,7 @@ public class AppearancePatentResultJobSupport {
|
|||||||
task.setFailedFileCount(failed ? 1 : 0);
|
task.setFailedFileCount(failed ? 1 : 0);
|
||||||
// 成功时也保留缺口文案:用户要看到“N 行抓取失败”,但不能因此把整单判死、逼他重跑。
|
// 成功时也保留缺口文案:用户要看到“N 行抓取失败”,但不能因此把整单判死、逼他重跑。
|
||||||
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(existingError, deliveryFacts));
|
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(existingError, deliveryFacts));
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(LocalDateTime.now());
|
task.setFinishedAt(LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -488,6 +492,7 @@ public class AppearancePatentResultJobSupport {
|
|||||||
boolean finalizeInterruptedDelivery(FileTaskEntity task, TaskFileJobEntity job, int totalProgressUnits,
|
boolean finalizeInterruptedDelivery(FileTaskEntity task, TaskFileJobEntity job, int totalProgressUnits,
|
||||||
String existingError, AppearancePatentRowOutcome.Facts deliveryFacts) {
|
String existingError, AppearancePatentRowOutcome.Facts deliveryFacts) {
|
||||||
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(existingError, deliveryFacts));
|
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(existingError, deliveryFacts));
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
taskCacheService.deleteTaskCache(task.getId());
|
taskCacheService.deleteTaskCache(task.getId());
|
||||||
|
|||||||
+4
-11
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||||
import com.nanri.aiimage.config.InstanceMetadata;
|
import com.nanri.aiimage.config.InstanceMetadata;
|
||||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -82,17 +83,9 @@ public class AppearancePatentTaskOwnership {
|
|||||||
if (task.getOwnerInstanceId() != null && !task.getOwnerInstanceId().isBlank()) {
|
if (task.getOwnerInstanceId() != null && !task.getOwnerInstanceId().isBlank()) {
|
||||||
return task.getOwnerInstanceId();
|
return task.getOwnerInstanceId();
|
||||||
}
|
}
|
||||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
// 回落口径四台共用一处(B74-04):本台此前只读 result_json,店铺采集读 request_json,
|
||||||
return null;
|
// 同一条列缺失的行在两台眼里会有两个归属。
|
||||||
}
|
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "appearance-patent");
|
||||||
try {
|
|
||||||
String owner = objectMapper.readTree(task.getResultJson()).path("ownerInstanceId").asText("");
|
|
||||||
return owner.isBlank() ? null : owner;
|
|
||||||
} catch (Exception ex) {
|
|
||||||
log.warn("[appearance-patent] read task owner failed taskId={} err={}",
|
|
||||||
task.getId(), ex.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String ownerFromScopeKey(String scopeKey) {
|
public String ownerFromScopeKey(String scopeKey) {
|
||||||
|
|||||||
+4
@@ -100,6 +100,7 @@ import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
|
|||||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||||
import com.nanri.aiimage.modules.task.service.StaleTaskHeartbeatPolicy;
|
import com.nanri.aiimage.modules.task.service.StaleTaskHeartbeatPolicy;
|
||||||
import com.nanri.aiimage.modules.task.service.pipeline.AbstractFileTaskPipeline;
|
import com.nanri.aiimage.modules.task.service.pipeline.AbstractFileTaskPipeline;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -538,6 +539,7 @@ public class CollectDataService extends AbstractFileTaskPipeline<CollectDataResu
|
|||||||
.notIn(FileTaskEntity::getStatus, STATUS_SUCCESS, STATUS_FAILED)
|
.notIn(FileTaskEntity::getStatus, STATUS_SUCCESS, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, message)
|
.set(FileTaskEntity::getErrorMessage, message)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(message))
|
||||||
.set(FileTaskEntity::getFailedFileCount, 1)
|
.set(FileTaskEntity::getFailedFileCount, 1)
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
@@ -1185,6 +1187,7 @@ public class CollectDataService extends AbstractFileTaskPipeline<CollectDataResu
|
|||||||
fileResultMapper.updateById(result);
|
fileResultMapper.updateById(result);
|
||||||
task.setStatus(STATUS_FAILED);
|
task.setStatus(STATUS_FAILED);
|
||||||
task.setErrorMessage(error);
|
task.setErrorMessage(error);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setFailedFileCount(1);
|
task.setFailedFileCount(1);
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(LocalDateTime.now());
|
task.setFinishedAt(LocalDateTime.now());
|
||||||
@@ -1262,6 +1265,7 @@ public class CollectDataService extends AbstractFileTaskPipeline<CollectDataResu
|
|||||||
// 「保留 N 行」永远停在组装前的插入计数(task 31253:表里 0 行仍显示 93)。
|
// 「保留 N 行」永远停在组装前的插入计数(task 31253:表里 0 行仍显示 93)。
|
||||||
.set(FileTaskEntity::getResultJson, task.getResultJson())
|
.set(FileTaskEntity::getResultJson, task.getResultJson())
|
||||||
.set(FileTaskEntity::getErrorMessage, null)
|
.set(FileTaskEntity::getErrorMessage, null)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, null)
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated == 0) {
|
if (updated == 0) {
|
||||||
|
|||||||
+2
@@ -56,6 +56,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -457,6 +458,7 @@ public class DedupeRunService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, BOOT_INTERRUPTED_MESSAGE)
|
.set(FileTaskEntity::getErrorMessage, BOOT_INTERRUPTED_MESSAGE)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(BOOT_INTERRUPTED_MESSAGE))
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
||||||
if (updated <= 0) {
|
if (updated <= 0) {
|
||||||
|
|||||||
+9
@@ -49,6 +49,7 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -296,6 +297,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, buildStaleFailReason(task, entry, minutes, nowMillis))
|
.set(FileTaskEntity::getErrorMessage, buildStaleFailReason(task, entry, minutes, nowMillis))
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(buildStaleFailReason(task, entry, minutes, nowMillis)))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
|
|
||||||
@@ -418,6 +420,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -496,6 +499,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -577,6 +581,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -654,6 +659,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -730,6 +736,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -791,6 +798,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
.set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf("长时间未收到 Python 结果回传,任务已自动失败"))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
@@ -908,6 +916,7 @@ public class DeleteBrandStaleTaskService {
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, buildNoResultUploadFailReason(minutes, lastResultAt, lastPosition))
|
.set(FileTaskEntity::getErrorMessage, buildNoResultUploadFailReason(minutes, lastResultAt, lastPosition))
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(buildNoResultUploadFailReason(minutes, lastResultAt, lastPosition)))
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
|
|||||||
+3
-14
@@ -34,6 +34,7 @@ import com.nanri.aiimage.modules.publish.model.vo.PublishTaskBatchVo;
|
|||||||
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskDetailVo;
|
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskDetailVo;
|
||||||
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskVo;
|
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskVo;
|
||||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||||
@@ -1339,20 +1340,8 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
|
|||||||
if (column != null && !column.isBlank()) {
|
if (column != null && !column.isBlank()) {
|
||||||
return column.trim();
|
return column.trim();
|
||||||
}
|
}
|
||||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
// 回落口径四台共用一处(B74-04)
|
||||||
return null;
|
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "publish");
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonNode root = objectMapper.readTree(task.getResultJson());
|
|
||||||
if (root == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String owner = root.path("ownerInstanceId").asText("");
|
|
||||||
return owner.isBlank() ? null : owner;
|
|
||||||
} catch (Exception ex) {
|
|
||||||
log.warn("[publish] read task owner failed taskId={} msg={}", task.getId(), safeMessage(ex));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String currentInstanceId() {
|
private String currentInstanceId() {
|
||||||
|
|||||||
+10
-10
@@ -30,6 +30,7 @@ import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemV
|
|||||||
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
|
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
|
||||||
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
|
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
|
||||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||||
@@ -80,6 +81,7 @@ import java.util.UUID;
|
|||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
|
import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -264,6 +266,7 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
|
|||||||
.eq(FileTaskEntity::getStatus, "RUNNING")
|
.eq(FileTaskEntity::getStatus, "RUNNING")
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, errorMessage)
|
.set(FileTaskEntity::getErrorMessage, errorMessage)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(errorMessage))
|
||||||
.set(FileTaskEntity::getUpdatedAt, now)
|
.set(FileTaskEntity::getUpdatedAt, now)
|
||||||
.set(FileTaskEntity::getFinishedAt, now));
|
.set(FileTaskEntity::getFinishedAt, now));
|
||||||
if (updated <= 0) {
|
if (updated <= 0) {
|
||||||
@@ -3111,8 +3114,12 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 任务归属实例 id:优先读显式列 owner_instance_id(Task 34 迁移),
|
* 任务归属实例 id:优先读显式列 owner_instance_id(Task 34 迁移),列缺失时走四台共用的
|
||||||
* 旧任务列缺失时兼容回退到 request_json.ownerInstanceId。
|
* JSON 回落口径({@link TaskOwnerJsonFallback},B74-04)。
|
||||||
|
*
|
||||||
|
* <p>本台此前只回落到 request_json,而另外三台回落到 result_json——列缺失的存量行
|
||||||
|
* (实测 RUNNING 任务里 39 行)因此在不同校验里会算出不同归属,这正是 2026-11-02
|
||||||
|
* 互斥死锁的家族形状。回落顺序现在只有一个出处。
|
||||||
*/
|
*/
|
||||||
public String ownerInstanceIdOf(FileTaskEntity task) {
|
public String ownerInstanceIdOf(FileTaskEntity task) {
|
||||||
if (task != null && !blank(task.getOwnerInstanceId())) {
|
if (task != null && !blank(task.getOwnerInstanceId())) {
|
||||||
@@ -3126,14 +3133,7 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String ownerFromJson(FileTaskEntity task) {
|
private String ownerFromJson(FileTaskEntity task) {
|
||||||
if (task == null || blank(task.getRequestJson())) return null;
|
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "shop-data-crawl");
|
||||||
try {
|
|
||||||
String owner = objectMapper.readTree(task.getRequestJson()).path("ownerInstanceId").asText("");
|
|
||||||
return blank(owner) ? null : owner;
|
|
||||||
} catch (Exception ex) {
|
|
||||||
log.warn("[shop-data-crawl] read task owner failed taskId={} msg={}", task.getId(), ex.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String currentInstanceId() {
|
private String currentInstanceId() {
|
||||||
|
|||||||
+22
-4
@@ -141,7 +141,7 @@ public class AdminShopDataDuplicateCheckController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/duplicate-check-console")
|
@GetMapping("/duplicate-check-console")
|
||||||
@Operation(summary = "撞款控制台快照:指标/店铺/命中筛选的撞款全集/分组统计")
|
@Operation(summary = "撞款控制台快照:指标/店铺/撞款行窗口(分页)/分组统计")
|
||||||
public ApiResponse<Object> console(
|
public ApiResponse<Object> console(
|
||||||
HttpServletRequest request,
|
HttpServletRequest request,
|
||||||
@RequestParam(name = "asin", required = false) String asin,
|
@RequestParam(name = "asin", required = false) String asin,
|
||||||
@@ -151,13 +151,20 @@ public class AdminShopDataDuplicateCheckController {
|
|||||||
@RequestParam(name = "site", required = false) String site,
|
@RequestParam(name = "site", required = false) String site,
|
||||||
@RequestParam(name = "date_from", required = false) String dateFrom,
|
@RequestParam(name = "date_from", required = false) String dateFrom,
|
||||||
@RequestParam(name = "date_to", required = false) String dateTo,
|
@RequestParam(name = "date_to", required = false) String dateTo,
|
||||||
|
@Parameter(description = "行窗口页码(从 1 起)") @RequestParam(name = "page", required = false) String page,
|
||||||
|
@Parameter(description = "行窗口每页行数(响应体 dup 行数 ≤ 本值)")
|
||||||
|
@RequestParam(name = "page_size", required = false) String pageSize,
|
||||||
|
@Parameter(description = "撞款行范围=指定分组的成员店铺(只裁行,不动指标/店铺/分组统计)")
|
||||||
|
@RequestParam(name = "dup_group", required = false) String dupGroup,
|
||||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||||
RequestOperator operator = requireDuplicateCheckAccess(request);
|
RequestOperator operator = requireDuplicateCheckAccess(request);
|
||||||
|
int safePage = parsePage(page);
|
||||||
|
int safeSize = clamp(parseSize(pageSize, 100), 1, 200);
|
||||||
ShopDataDuplicateCheckQueryService.Filters filters =
|
ShopDataDuplicateCheckQueryService.Filters filters =
|
||||||
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
|
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
|
||||||
DuplicateScanView scan = scanService.loadLatest();
|
DuplicateScanView scan = scanService.loadLatest();
|
||||||
if (scan == null) {
|
if (scan == null) {
|
||||||
return ApiResponse.success(queryService.pendingConsole());
|
return ApiResponse.success(queryService.pendingConsole(safePage, safeSize));
|
||||||
}
|
}
|
||||||
List<Long> companyMemberIds = operator.superAdmin()
|
List<Long> companyMemberIds = operator.superAdmin()
|
||||||
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
|
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
|
||||||
@@ -165,7 +172,8 @@ public class AdminShopDataDuplicateCheckController {
|
|||||||
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
|
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
|
||||||
operator.id(), operator.superAdmin(), companyMemberIds);
|
operator.id(), operator.superAdmin(), companyMemberIds);
|
||||||
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
|
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
|
||||||
return ApiResponse.success(queryService.consoleData(scan, effectiveKeys, filters));
|
return ApiResponse.success(queryService.consoleData(scan, effectiveKeys, filters,
|
||||||
|
safePage, safeSize, dupGroup));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/duplicate-check-ledger")
|
@GetMapping("/duplicate-check-ledger")
|
||||||
@@ -321,12 +329,22 @@ public class AdminShopDataDuplicateCheckController {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页码上限(CR-18/铁律 15 同形,判据参照 {@code KeywordUsageAdminService.MAX_PAGE})。
|
||||||
|
* 只钳下限不够:{@code ShopDataDuplicateCheckQueryService} 四处页窗算的都是
|
||||||
|
* {@code (page - 1) * pageSize},{@code page=11000000 / page_size=200} 会溢出成负数,
|
||||||
|
* {@code Math.min(负数, total)} 仍是负数,喂给 {@code subList(负, 负)} 直接
|
||||||
|
* IndexOutOfBounds = HTTP 500(有至少一行重复数据就能触发)。钳到 10000 页 ×
|
||||||
|
* 本文件最大 page_size 200 = 200 万行,已远超实际可翻范围。
|
||||||
|
*/
|
||||||
|
private static final int MAX_PAGE = 10_000;
|
||||||
|
|
||||||
private static int parsePage(String page) {
|
private static int parsePage(String page) {
|
||||||
if (page == null || page.isBlank()) {
|
if (page == null || page.isBlank()) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return Math.max(1, Integer.parseInt(page.trim()));
|
return clamp(Integer.parseInt(page.trim()), 1, MAX_PAGE);
|
||||||
} catch (NumberFormatException ex) {
|
} catch (NumberFormatException ex) {
|
||||||
throw new BusinessException(400, "page 参数不合法");
|
throw new BusinessException(400, "page 参数不合法");
|
||||||
}
|
}
|
||||||
|
|||||||
+90
-12
@@ -198,14 +198,41 @@ public class ShopDataDuplicateCheckQueryService {
|
|||||||
"total", 0, "page", page, "page_size", pageSize, "scanned_at", "");
|
"total", 0, "page", page, "page_size", pageSize, "scanned_at", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页窗下界(铁律 15 同形,判据参照 {@code KeywordUsageAdminService} 的 CR-18 注释)。
|
||||||
|
*
|
||||||
|
* <p>四处页窗原先算的都是 {@code Math.min((page - 1) * pageSize, total)}:这个乘法先于
|
||||||
|
* {@code min} 发生,{@code page=11000000 / page_size=200} 溢出成 {@code -2094967296},
|
||||||
|
* {@code min} 之后仍是负数,喂给 {@code subList(负, 负)} 就是 IndexOutOfBounds = HTTP 500
|
||||||
|
* ——只要表里有至少一行重复数据就能触发。2026-11-04 Phase 6 CR 在 {@code consoleData}
|
||||||
|
* 那处抓到(Phase 5 的 B60 行窗改的就是这一位),另外三处同形所以一起收进这里。
|
||||||
|
*
|
||||||
|
* <p>先转 {@code long} 再乘:{@code page} 传得再离谱也只会拿到空窗,不会拿到负下标。
|
||||||
|
* 控制器的 {@code parsePage} 那道钳制(上限 10000)是边界卫生,这一位是**算不坏**本身:
|
||||||
|
* 只钳边界的话,下一个直接调本服务的调用方(或一支新用例)能把 500 原样请回来,
|
||||||
|
* 而谁也看不出哪里错了。
|
||||||
|
*/
|
||||||
|
private static int windowFrom(int page, int pageSize, int total) {
|
||||||
|
// `page - 1` 本身也要在 long 上算:page=Integer.MIN_VALUE 时在 int 上会翻成
|
||||||
|
// +2147483647(="最后一窗之后"),升 long 才是"第一窗"。这一位是本支用例第 4 格
|
||||||
|
// 当场抓出来的——判据不是装饰,它先咬到了修的人自己。
|
||||||
|
long start = Math.max(0L, (long) page - 1) * Math.max(0, pageSize);
|
||||||
|
return (int) Math.min(start, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 页窗上界:同样先升 long,`from` 已 ≤ total,加一档 pageSize 也不越 int。 */
|
||||||
|
private static int windowTo(int from, int pageSize, int total) {
|
||||||
|
return (int) Math.min((long) from + Math.max(0, pageSize), total);
|
||||||
|
}
|
||||||
|
|
||||||
public Map<String, Object> itemsData(DuplicateScanView view, Set<String> visibleKeys,
|
public Map<String, Object> itemsData(DuplicateScanView view, Set<String> visibleKeys,
|
||||||
int page, int pageSize, String viewMode, Filters filters) {
|
int page, int pageSize, String viewMode, Filters filters) {
|
||||||
boolean monitor = "monitor".equals(viewMode);
|
boolean monitor = "monitor".equals(viewMode);
|
||||||
List<DuplicateItem> cropped = cropItems(view.payload().items(), visibleKeys);
|
List<DuplicateItem> cropped = cropItems(view.payload().items(), visibleKeys);
|
||||||
List<DuplicateItem> matched = filterItems(cropped, monitor, filters);
|
List<DuplicateItem> matched = filterItems(cropped, monitor, filters);
|
||||||
int total = matched.size();
|
int total = matched.size();
|
||||||
int from = Math.min((page - 1) * pageSize, total);
|
int from = windowFrom(page, pageSize, total);
|
||||||
int to = Math.min(from + pageSize, total);
|
int to = windowTo(from, pageSize, total);
|
||||||
List<DuplicateItem> slice = matched.isEmpty() ? List.of()
|
List<DuplicateItem> slice = matched.isEmpty() ? List.of()
|
||||||
: new ArrayList<>(matched.subList(from, to));
|
: new ArrayList<>(matched.subList(from, to));
|
||||||
List<DuplicateShop> shops = cropShops(view.payload().shops(), visibleKeys);
|
List<DuplicateShop> shops = cropShops(view.payload().shops(), visibleKeys);
|
||||||
@@ -219,8 +246,8 @@ public class ShopDataDuplicateCheckQueryService {
|
|||||||
List<DuplicateItem> matched = filterItems(cropped, true, filters);
|
List<DuplicateItem> matched = filterItems(cropped, true, filters);
|
||||||
matched.sort(detailItemComparator());
|
matched.sort(detailItemComparator());
|
||||||
int total = matched.size();
|
int total = matched.size();
|
||||||
int from = Math.min((page - 1) * pageSize, total);
|
int from = windowFrom(page, pageSize, total);
|
||||||
int to = Math.min(from + pageSize, total);
|
int to = windowTo(from, pageSize, total);
|
||||||
List<Map<String, Object>> pageItems = new ArrayList<>();
|
List<Map<String, Object>> pageItems = new ArrayList<>();
|
||||||
for (int i = from; i < to; i++) {
|
for (int i = from; i < to; i++) {
|
||||||
pageItems.add(detailItem(matched.get(i)));
|
pageItems.add(detailItem(matched.get(i)));
|
||||||
@@ -265,8 +292,8 @@ public class ShopDataDuplicateCheckQueryService {
|
|||||||
}
|
}
|
||||||
rows.sort((a, b) -> ledgerCompare(a, b, key, asc));
|
rows.sort((a, b) -> ledgerCompare(a, b, key, asc));
|
||||||
int total = rows.size();
|
int total = rows.size();
|
||||||
int from = Math.min((page - 1) * pageSize, total);
|
int from = windowFrom(page, pageSize, total);
|
||||||
int to = Math.min(from + pageSize, total);
|
int to = windowTo(from, pageSize, total);
|
||||||
List<Map<String, Object>> slice = new ArrayList<>();
|
List<Map<String, Object>> slice = new ArrayList<>();
|
||||||
for (int i = from; i < to; i++) {
|
for (int i = from; i < to; i++) {
|
||||||
slice.add(ledgerMap(rows.get(i)));
|
slice.add(ledgerMap(rows.get(i)));
|
||||||
@@ -280,22 +307,73 @@ public class ShopDataDuplicateCheckQueryService {
|
|||||||
"page", page, "page_size", pageSize, "scanned_at", "");
|
"page", page, "page_size", pageSize, "scanned_at", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 撞款控制台一次快照:summary/shops(全局可见口径) + 命中筛选的撞款全集 + 分组统计。 */
|
/**
|
||||||
public Map<String, Object> consoleData(DuplicateScanView view, Set<String> visibleKeys, Filters filters) {
|
* 撞款控制台一次快照:summary/shops(全局可见口径) + 命中筛选的撞款**行窗口** + 分组统计。
|
||||||
|
*
|
||||||
|
* <p>B60:{@code dup} 原先返回全集(现网可累到数万行的 JSON),前端翻页/切分组都在这份
|
||||||
|
* 整数组上做客户端切片——分页参数在这里真生效(响应体行数 ≤ pageSize),{@code total_dup}
|
||||||
|
* 仍是<b>该范围内未分页的总数</b>(KPI 与分页控件读它,不是窗口长度)。
|
||||||
|
*
|
||||||
|
* <p>{@code dupGroup} 非空时行集先按该分组裁剪(组内 ≥2 店才算撞款)。判据与
|
||||||
|
* {@link #groupStats} 同源(成员键=可见店铺的 groupName 拆分),而不是前端再算一份:
|
||||||
|
* 原先页面用 {@code dupWithinGroup} 自己裁了一遍,两套规则同名不同实现,分页一上就会分叉。
|
||||||
|
*
|
||||||
|
* <p>排序在切窗<b>之前</b>:行窗口必须稳定,否则同一页每次刷新拿到的是不同行。
|
||||||
|
* ASIN 是 {@code [A-Z0-9]},这里的字符串序与页面原先的 localeCompare 同序。
|
||||||
|
*
|
||||||
|
* <p>蓝图 5A 那句「限制列数」落在<b>渲染侧</b>(后管 {@code duplicate-matrix-window.ts} 的
|
||||||
|
* 列窗 40),服务端<b>不设</b>列窗,别把它当成没做完:矩阵的列本来就是从这份<b>已分页的行</b>
|
||||||
|
* 里数出来的({@code storeColumnsOf(rows)}),而 {@code shops} 是筛选项字典+KPI 的原料、
|
||||||
|
* 每行只有 5 个标量字段(见 {@code DuplicateShop})。给 {@code shops} 再加一层分页,只会把
|
||||||
|
* 「全局指标读全集」和「列窗读本页」两套语义搅成一处——那才是 B60 要防的分叉。
|
||||||
|
*/
|
||||||
|
public Map<String, Object> consoleData(DuplicateScanView view, Set<String> visibleKeys, Filters filters,
|
||||||
|
int page, int pageSize, String dupGroup) {
|
||||||
List<DuplicateShop> shops = cropShops(view.payload().shops(), visibleKeys);
|
List<DuplicateShop> shops = cropShops(view.payload().shops(), visibleKeys);
|
||||||
List<DuplicateItem> cropped = cropItems(view.payload().items(), visibleKeys);
|
List<DuplicateItem> cropped = cropItems(view.payload().items(), visibleKeys);
|
||||||
String source = view.summary() == null ? "" : safe(view.summary().source());
|
String source = view.summary() == null ? "" : safe(view.summary().source());
|
||||||
DuplicateScanSummary summary = recomputeSummary(cropped, shops, source);
|
DuplicateScanSummary summary = recomputeSummary(cropped, shops, source);
|
||||||
List<DuplicateItem> dup = filterItems(cropped, true, filters);
|
List<DuplicateItem> rows = dupRowsInScope(shops, dupGroup, filterItems(cropped, true, filters));
|
||||||
|
rows.sort(Comparator.comparing((DuplicateItem item) -> safe(item.asin())));
|
||||||
List<Map<String, Object>> groups = groupStats(shops, filterItems(cropped, false, filters));
|
List<Map<String, Object>> groups = groupStats(shops, filterItems(cropped, false, filters));
|
||||||
|
int total = rows.size();
|
||||||
|
int from = windowFrom(page, pageSize, total);
|
||||||
|
int to = windowTo(from, pageSize, total);
|
||||||
|
List<DuplicateItem> window = rows.isEmpty() ? List.of() : new ArrayList<>(rows.subList(from, to));
|
||||||
return mapOf("pending", false, "scanned_at", safe(view.scannedAt()), "summary", summary,
|
return mapOf("pending", false, "scanned_at", safe(view.scannedAt()), "summary", summary,
|
||||||
"shops", shops, "dup", dup, "groups", groups, "total_dup", dup.size());
|
"shops", shops, "dup", window, "groups", groups, "total_dup", total,
|
||||||
|
"page", page, "page_size", pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> pendingConsole() {
|
/** 分组范围内的撞款行集:按成员店铺裁剪后仍是 ≥2 店的才算撞款。 */
|
||||||
|
private List<DuplicateItem> dupRowsInScope(List<DuplicateShop> visibleShops, String dupGroup,
|
||||||
|
List<DuplicateItem> matched) {
|
||||||
|
String group = safe(dupGroup).trim();
|
||||||
|
if (group.isEmpty()) {
|
||||||
|
return matched;
|
||||||
|
}
|
||||||
|
Set<String> memberKeys = new LinkedHashSet<>();
|
||||||
|
for (DuplicateShop shop : visibleShops) {
|
||||||
|
for (String g : splitGroups(safe(shop.groupName()))) {
|
||||||
|
if (g.equals(group)) {
|
||||||
|
memberKeys.add(shopKey(shop.shopName()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<DuplicateItem> rows = new ArrayList<>();
|
||||||
|
for (DuplicateItem item : cropItems(matched, memberKeys)) {
|
||||||
|
if (item.shopCount() >= 2) {
|
||||||
|
rows.add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> pendingConsole(int page, int pageSize) {
|
||||||
return mapOf("pending", true, "scanned_at", "", "summary", Collections.emptyMap(),
|
return mapOf("pending", true, "scanned_at", "", "summary", Collections.emptyMap(),
|
||||||
"shops", Collections.emptyList(), "dup", Collections.emptyList(),
|
"shops", Collections.emptyList(), "dup", Collections.emptyList(),
|
||||||
"groups", Collections.emptyList(), "total_dup", 0);
|
"groups", Collections.emptyList(), "total_dup", 0,
|
||||||
|
"page", page, "page_size", pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 单条台账行:品牌取首个非空;店铺/分组/站点保持出现顺序去重;最早/最近上架取归一化时间。 */
|
/** 单条台账行:品牌取首个非空;店铺/分组/站点保持出现顺序去重;最早/最近上架取归一化时间。 */
|
||||||
|
|||||||
+11
-5
@@ -72,10 +72,10 @@ import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
|||||||
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
import com.nanri.aiimage.modules.task.service.TaskVisibleFailureNotice;
|
import com.nanri.aiimage.modules.task.service.TaskVisibleFailureNotice;
|
||||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -392,9 +392,10 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
|||||||
throw new BusinessException("user_id 不合法");
|
throw new BusinessException("user_id 不合法");
|
||||||
}
|
}
|
||||||
// 密钥闸门排在解析之前:解析、建单四段都要花时间与配额,而缺密钥的单跑完只是
|
// 密钥闸门排在解析之前:解析、建单四段都要花时间与配额,而缺密钥的单跑完只是
|
||||||
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret)。
|
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret;
|
||||||
|
// 这一类要哪把密钥登记在 TaskModuleRegistry,不在本文件写死)。
|
||||||
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
||||||
UserSecretModule.SIMILAR_ASIN, request.getApiKey());
|
MODULE_TYPE, request.getApiKey());
|
||||||
if (request.getFiles() == null || request.getFiles().isEmpty()) {
|
if (request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||||
throw new BusinessException("请先上传 Excel 文件");
|
throw new BusinessException("请先上传 Excel 文件");
|
||||||
}
|
}
|
||||||
@@ -1356,6 +1357,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
|||||||
task.setSuccessFileCount(failed ? 0 : 1);
|
task.setSuccessFileCount(failed ? 0 : 1);
|
||||||
task.setFailedFileCount(failed ? 1 : 0);
|
task.setFailedFileCount(failed ? 1 : 0);
|
||||||
task.setErrorMessage(finalError);
|
task.setErrorMessage(finalError);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
|
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -1567,6 +1569,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
|||||||
task.setSuccessFileCount(0);
|
task.setSuccessFileCount(0);
|
||||||
task.setFailedFileCount(1);
|
task.setFailedFileCount(1);
|
||||||
task.setErrorMessage(failureMessage);
|
task.setErrorMessage(failureMessage);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(now);
|
task.setUpdatedAt(now);
|
||||||
task.setFinishedAt(now);
|
task.setFinishedAt(now);
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -1616,9 +1619,11 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
|||||||
task.setFailedFileCount(1);
|
task.setFailedFileCount(1);
|
||||||
// 生产者原文一个字都不在这里重写(支持同学要对着上游响应体查根因);界面上那句中文由
|
// 生产者原文一个字都不在这里重写(支持同学要对着上游响应体查根因);界面上那句中文由
|
||||||
// TaskVisibleFailureNotice 在出口处给,英文原文与上游账户号不进界面。
|
// TaskVisibleFailureNotice 在出口处给,英文原文与上游账户号不进界面。
|
||||||
task.setErrorMessage(raw.isEmpty()
|
String terminalText = raw.isEmpty()
|
||||||
? LlmBalanceGuard.TASK_TERMINAL_GUIDANCE
|
? LlmBalanceGuard.TASK_TERMINAL_GUIDANCE
|
||||||
: raw + ";" + LlmBalanceGuard.TASK_TERMINAL_GUIDANCE);
|
: raw + ";" + LlmBalanceGuard.TASK_TERMINAL_GUIDANCE;
|
||||||
|
task.setErrorMessage(terminalText);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(terminalText));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(LocalDateTime.now());
|
task.setFinishedAt(LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
@@ -1684,6 +1689,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
|||||||
task.setSuccessFileCount(taskAlreadyFailed ? 0 : 1);
|
task.setSuccessFileCount(taskAlreadyFailed ? 0 : 1);
|
||||||
task.setFailedFileCount(taskAlreadyFailed ? 1 : 0);
|
task.setFailedFileCount(taskAlreadyFailed ? 1 : 0);
|
||||||
task.setErrorMessage(taskAlreadyFailed ? existingError : null);
|
task.setErrorMessage(taskAlreadyFailed ? existingError : null);
|
||||||
|
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
|
||||||
task.setUpdatedAt(LocalDateTime.now());
|
task.setUpdatedAt(LocalDateTime.now());
|
||||||
task.setFinishedAt(LocalDateTime.now());
|
task.setFinishedAt(LocalDateTime.now());
|
||||||
fileTaskMapper.updateById(task);
|
fileTaskMapper.updateById(task);
|
||||||
|
|||||||
+2
@@ -15,6 +15,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SimilarAsinTaskService 拆分:心跳/回传停滞判死的迟到回传恢复。
|
* SimilarAsinTaskService 拆分:心跳/回传停滞判死的迟到回传恢复。
|
||||||
@@ -96,6 +97,7 @@ public class SimilarAsinStaleReopenSupport {
|
|||||||
.eq(FileTaskEntity::getErrorMessage, reason)
|
.eq(FileTaskEntity::getErrorMessage, reason)
|
||||||
.set(FileTaskEntity::getStatus, TaskStatuses.FileTask.RUNNING)
|
.set(FileTaskEntity::getStatus, TaskStatuses.FileTask.RUNNING)
|
||||||
.set(FileTaskEntity::getErrorMessage, null)
|
.set(FileTaskEntity::getErrorMessage, null)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, null)
|
||||||
.set(FileTaskEntity::getFinishedAt, null)
|
.set(FileTaskEntity::getFinishedAt, null)
|
||||||
.set(FileTaskEntity::getSuccessFileCount, 0)
|
.set(FileTaskEntity::getSuccessFileCount, 0)
|
||||||
.set(FileTaskEntity::getFailedFileCount, 0)
|
.set(FileTaskEntity::getFailedFileCount, 0)
|
||||||
|
|||||||
+3
-10
@@ -12,6 +12,7 @@ import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
|
|||||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||||
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
|
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
|
||||||
@@ -133,16 +134,8 @@ public class SimilarAsinTaskOwnershipSupport {
|
|||||||
if (column != null && !column.isBlank()) {
|
if (column != null && !column.isBlank()) {
|
||||||
return column.trim();
|
return column.trim();
|
||||||
}
|
}
|
||||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
// 回落口径四台共用一处(B74-04)
|
||||||
return null;
|
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "similar-asin");
|
||||||
}
|
|
||||||
try {
|
|
||||||
String owner = objectMapper.readTree(task.getResultJson()).path("ownerInstanceId").asText("");
|
|
||||||
return owner.isBlank() ? null : owner;
|
|
||||||
} catch (Exception ex) {
|
|
||||||
log.warn("[similar-asin] read task owner failed taskId={} err={}", task.getId(), ex.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+13
@@ -5,6 +5,9 @@ import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
|||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public interface TaskFileJobMapper extends BaseMapper<TaskFileJobEntity> {
|
public interface TaskFileJobMapper extends BaseMapper<TaskFileJobEntity> {
|
||||||
|
|
||||||
@@ -14,4 +17,14 @@ public interface TaskFileJobMapper extends BaseMapper<TaskFileJobEntity> {
|
|||||||
* 语句在 {@code mapper/TaskFileJobMapper.xml}(本仓约定:自定义 SQL 一律进 XML)。
|
* 语句在 {@code mapper/TaskFileJobMapper.xml}(本仓约定:自定义 SQL 一律进 XML)。
|
||||||
*/
|
*/
|
||||||
String selectFileTaskStatus(@Param("taskId") Long taskId);
|
String selectFileTaskStatus(@Param("taskId") Long taskId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link #selectFileTaskStatus} 的批量档(P1-B6):一次问回「状态落在给定终态值域里」的任务 id。
|
||||||
|
*
|
||||||
|
* <p>终态值域由调用方传(正本仍是 {@code TaskStatuses.FileTask.TERMINAL})——不在 XML 里
|
||||||
|
* 再抄一份字符串,否则改值域时两边会悄悄分叉。查不到行的 id 不出现在结果里=非终态,
|
||||||
|
* 与单条档「品牌任务的 job 返回 null」的语义逐字对齐。
|
||||||
|
*/
|
||||||
|
List<Long> selectTerminalFileTaskIds(@Param("taskIds") Collection<Long> taskIds,
|
||||||
|
@Param("terminalStatuses") Collection<String> terminalStatuses);
|
||||||
}
|
}
|
||||||
|
|||||||
+16
@@ -1,6 +1,8 @@
|
|||||||
package com.nanri.aiimage.modules.task.model.entity;
|
package com.nanri.aiimage.modules.task.model.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldStrategy;
|
||||||
import com.baomidou.mybatisplus.annotation.IdType;
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
import com.baomidou.mybatisplus.annotation.TableId;
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
import com.baomidou.mybatisplus.annotation.TableName;
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
@@ -25,6 +27,20 @@ public class FileTaskEntity {
|
|||||||
private String requestJson;
|
private String requestJson;
|
||||||
private String resultJson;
|
private String resultJson;
|
||||||
private String errorMessage;
|
private String errorMessage;
|
||||||
|
/**
|
||||||
|
* 失败分类(V186):值={@code TaskRetryEligibility.Category.name()},空=这一行没登记分类。
|
||||||
|
*
|
||||||
|
* <p>存在理由:重试/重开/判死原先全靠读 {@code error_message} 里的中文子串决定,
|
||||||
|
* 改一句用户可见文案就静默改行为。列是那次判断的**记账**,不是第二套词汇表——
|
||||||
|
* 写入一律经 {@code TaskFailureLedger},词汇表仍只有 {@code TaskRetryEligibility} 一处。
|
||||||
|
*
|
||||||
|
* <p>{@code updateStrategy=ALWAYS} 是给实体式写面兜底的:{@code updateById} 默认跳过 null 字段,
|
||||||
|
* 而 {@code task.setErrorMessage(null)} 这类「清错误」的分支带不动列,会留下一列<b>陈旧</b>的判决。
|
||||||
|
* 让 null 真的落库,最坏情形就是列被抹回「未登记」——读侧按文案判定,逐字等于加列之前的今天;
|
||||||
|
* 反过来(陈旧列活下来)才是会让一单被上一次失败原因判死的那种错。
|
||||||
|
*/
|
||||||
|
@TableField(updateStrategy = FieldStrategy.ALWAYS)
|
||||||
|
private String failureCategory;
|
||||||
private String createdBy;
|
private String createdBy;
|
||||||
private Long userId;
|
private Long userId;
|
||||||
/** 创建任务的客户端设备(JWT 签名 deviceId claim,V138);历史任务为空。 */
|
/** 创建任务的客户端设备(JWT 签名 deviceId claim,V138);历史任务为空。 */
|
||||||
|
|||||||
+2
@@ -21,6 +21,7 @@ import java.time.LocalDateTime;
|
|||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 账号过期停任务巡检(V146,2026-10-05)。
|
* 账号过期停任务巡检(V146,2026-10-05)。
|
||||||
@@ -147,6 +148,7 @@ public class ExpiredAccountTaskStopService {
|
|||||||
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
|
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, STOP_REASON)
|
.set(FileTaskEntity::getErrorMessage, STOP_REASON)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(STOP_REASON))
|
||||||
.set(FileTaskEntity::getFinishedAt, now));
|
.set(FileTaskEntity::getFinishedAt, now));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -35,6 +35,7 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -332,7 +333,8 @@ public class ModuleHistoryCleanupService {
|
|||||||
.in(FileTaskEntity::getId, cleanupTaskIds)
|
.in(FileTaskEntity::getId, cleanupTaskIds)
|
||||||
.set(FileTaskEntity::getResultJson, null)
|
.set(FileTaskEntity::getResultJson, null)
|
||||||
.set(FileTaskEntity::getRequestJson, null)
|
.set(FileTaskEntity::getRequestJson, null)
|
||||||
.set(FileTaskEntity::getErrorMessage, null));
|
.set(FileTaskEntity::getErrorMessage, null)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, null));
|
||||||
|
|
||||||
return fileTaskMapper.delete(new LambdaQueryWrapper<FileTaskEntity>()
|
return fileTaskMapper.delete(new LambdaQueryWrapper<FileTaskEntity>()
|
||||||
.in(FileTaskEntity::getId, cleanupTaskIds));
|
.in(FileTaskEntity::getId, cleanupTaskIds));
|
||||||
|
|||||||
+3
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 陈旧任务自动修复。
|
* 陈旧任务自动修复。
|
||||||
@@ -104,6 +105,7 @@ public class StaleTaskRepairService {
|
|||||||
.eq(FileTaskEntity::getStatus, STATUS_SCHEDULED)
|
.eq(FileTaskEntity::getStatus, STATUS_SCHEDULED)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, reason)
|
.set(FileTaskEntity::getErrorMessage, reason)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(reason))
|
||||||
.set(FileTaskEntity::getFinishedAt, now));
|
.set(FileTaskEntity::getFinishedAt, now));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
log.warn("[stale-task-repair] 陈旧定时任务已标失败 count={} ids={}", updated, ids);
|
log.warn("[stale-task-repair] 陈旧定时任务已标失败 count={} ids={}", updated, ids);
|
||||||
@@ -135,6 +137,7 @@ public class StaleTaskRepairService {
|
|||||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, reason)
|
.set(FileTaskEntity::getErrorMessage, reason)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(reason))
|
||||||
.set(FileTaskEntity::getFinishedAt, now));
|
.set(FileTaskEntity::getFinishedAt, now));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
log.warn("[stale-task-repair] 心跳超时 RUNNING 已标失败 count={} ids={}", updated, ids);
|
log.warn("[stale-task-repair] 心跳超时 RUNNING 已标失败 count={} ids={}", updated, ids);
|
||||||
|
|||||||
+2
@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 客户端兜底拉取:把"页面没推送成功、长期停在 PENDING"的任务交给在线客户端执行。
|
* 客户端兜底拉取:把"页面没推送成功、长期停在 PENDING"的任务交给在线客户端执行。
|
||||||
@@ -283,6 +284,7 @@ public class TaskClientPullService {
|
|||||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, reason)
|
.set(FileTaskEntity::getErrorMessage, reason)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(reason))
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
log.warn("[client-task-pull] 认领后组装载荷失败,已标失败 taskId={} moduleType={} 命中={} 原因={}",
|
log.warn("[client-task-pull] 认领后组装载荷失败,已标失败 taskId={} moduleType={} 命中={} 原因={}",
|
||||||
task.getId(), task.getModuleType(), updated, reason);
|
task.getId(), task.getModuleType(), updated, reason);
|
||||||
|
|||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||||
|
import com.nanri.aiimage.modules.task.mapper.TaskFileJobMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code biz_task_file_job} / {@code biz_file_task} 的<b>批量读</b>(P1-B5/P1-B6):
|
||||||
|
* 一批候选进来,一次往返出 id 集。
|
||||||
|
*
|
||||||
|
* <p>为什么从 {@link TaskFileJobService} 里单立一支:那支服务已经挂在可读性基线的超长文件
|
||||||
|
* 名单上(只许减),而这几条是纯查询——不写状态、不发派发事件、不碰本机在飞表,与服务侧的
|
||||||
|
* 写路径没有任何共享可变状态,所以它是<b>静态工具</b>而不是又一支注入进来的 Bean:
|
||||||
|
* {@code TaskFileJobService} 的构造器已经是别处十几支用例的直接依赖,多加一个参数只会把
|
||||||
|
* 无关用例一起改红。
|
||||||
|
*
|
||||||
|
* <p>把「批量预取」与「逐行 CAS」分成两件事也是有意的:认领的并发正确性只来自逐行 CAS
|
||||||
|
* ({@code markRunning}),批量预取只用来跳过已终态/已在补检的行;两者混进一个方法,
|
||||||
|
* 那个前提就再也读不出来了。
|
||||||
|
*/
|
||||||
|
public final class TaskFileJobBatchQueries {
|
||||||
|
|
||||||
|
private TaskFileJobBatchQueries() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这批任务里「还在补检(名下有未终态的组装作业)」的 id(P1-B5)。
|
||||||
|
*
|
||||||
|
* <p>交付缺口触发的补检轮会把作业排回 PENDING/RUNNING({@link TaskFileJobService#requeue}),
|
||||||
|
* 所以"有活着的组装作业"="这单还在补检"。而任务行可能早就落成 FAILED(心跳超时或交付判死先落),
|
||||||
|
* 此时按任务状态去克隆重跑=同一份活开两份:现网 2026-10-24 一枚 760 行的外观专利因此被克隆成
|
||||||
|
* 4 枚、每枚都全量重跑一遍,四枚卡片的开始时间还都是同一秒(克隆件继承原件 created_at)。
|
||||||
|
* 调用方 {@code TaskResumeService} 就是拿这个集合跳过那一类的。
|
||||||
|
*
|
||||||
|
* <p>原先这是逐条 {@code selectCount}(N 个候选=N 次往返,P1-B5 点名的那处 N+1);巡检按几百个
|
||||||
|
* 候选跑,所以折成一次 {@code selectList} 取 id 列——判据一字未动(同一 jobType、同一两态)。
|
||||||
|
*/
|
||||||
|
public static Set<Long> taskIdsWithUnfinishedAssembleJob(TaskFileJobMapper mapper, Collection<Long> taskIds) {
|
||||||
|
if (taskIds == null || taskIds.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
List<TaskFileJobEntity> rows = mapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||||
|
.select(TaskFileJobEntity::getTaskId)
|
||||||
|
.in(TaskFileJobEntity::getTaskId, taskIds)
|
||||||
|
.eq(TaskFileJobEntity::getJobType, TaskFileJobService.JOB_TYPE_ASSEMBLE_RESULT)
|
||||||
|
.in(TaskFileJobEntity::getStatus, TaskStatuses.Job.PENDING, TaskStatuses.Job.RUNNING));
|
||||||
|
if (rows == null || rows.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
Set<Long> ids = new LinkedHashSet<>();
|
||||||
|
for (TaskFileJobEntity row : rows) {
|
||||||
|
if (row != null && row.getTaskId() != null) {
|
||||||
|
ids.add(row.getTaskId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这批候选作业里「父任务已终态」的任务 id(P1-B6):先折出候选的 taskId,再一次批量读。
|
||||||
|
*
|
||||||
|
* <p>终态值域仍只有 {@code TaskStatuses.FileTask.TERMINAL} 一处正本——它作为参数进 SQL,
|
||||||
|
* 不在 XML 里另抄一份字符串(抄了就又是第二份词汇表)。单条档判据见
|
||||||
|
* {@link TaskFileJobService#isOwningTaskTerminal(Long)},两边同源。
|
||||||
|
*/
|
||||||
|
public static Set<Long> terminalOwningTaskIds(TaskFileJobMapper mapper, List<TaskFileJobEntity> candidates) {
|
||||||
|
Set<Long> taskIds = new LinkedHashSet<>();
|
||||||
|
if (candidates != null) {
|
||||||
|
for (TaskFileJobEntity candidate : candidates) {
|
||||||
|
if (candidate != null && candidate.getTaskId() != null && candidate.getTaskId() > 0) {
|
||||||
|
taskIds.add(candidate.getTaskId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (taskIds.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
List<Long> terminal = mapper.selectTerminalFileTaskIds(taskIds, TaskStatuses.FileTask.TERMINAL);
|
||||||
|
return terminal == null || terminal.isEmpty() ? Set.of() : new LinkedHashSet<>(terminal);
|
||||||
|
}
|
||||||
|
}
|
||||||
+111
-16
@@ -16,9 +16,12 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -38,6 +41,12 @@ public class TaskFileJobService {
|
|||||||
private final TaskFileJobMapper taskFileJobMapper;
|
private final TaskFileJobMapper taskFileJobMapper;
|
||||||
private final ApplicationEventPublisher applicationEventPublisher;
|
private final ApplicationEventPublisher applicationEventPublisher;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本机执行线程正在跑的作业 id(B74-02,见 {@link #isInFlight})。
|
||||||
|
* 只在内存里,进程重启即空——那正是需要的形状:遗骸照旧被扫描回收。
|
||||||
|
*/
|
||||||
|
private final Set<Long> inFlightJobIds = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
public TaskFileJobEntity enqueueAssembleResult(Long taskId, String moduleType, Long resultId, String scopeKey) {
|
public TaskFileJobEntity enqueueAssembleResult(Long taskId, String moduleType, Long resultId, String scopeKey) {
|
||||||
if (taskId == null || taskId <= 0 || moduleType == null || moduleType.isBlank() || resultId == null || resultId <= 0) {
|
if (taskId == null || taskId <= 0 || moduleType == null || moduleType.isBlank() || resultId == null || resultId <= 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -135,22 +144,12 @@ public class TaskFileJobService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 该任务名下还有没有**未终态**的组装作业(PENDING/RUNNING)。
|
* 这批任务里「还在补检」的 id(P1-B5 的批量档):判据与来由都在
|
||||||
*
|
* {@link TaskFileJobBatchQueries#taskIdsWithUnfinishedAssembleJob},这里只是服务侧的门面——
|
||||||
* <p>交付缺口触发的补检轮就是把作业排回这两态({@link #requeue}),所以"有活着的组装作业"
|
* 调用方({@code TaskResumeService})认的是这支服务,不该为了读侧再注入一件东西。
|
||||||
* ="这单还在补检"。而任务行可能早就落成 FAILED(心跳超时或交付判死先落),此时按任务状态
|
|
||||||
* 去克隆重跑,等于同一份活开两份:现网 2026-10-24 一枚 760 行的外观专利因此被克隆成 4 枚、
|
|
||||||
* 每枚都全量重跑一遍,四枚卡片的开始时间还都是同一秒(克隆件继承原件 created_at)。
|
|
||||||
*/
|
*/
|
||||||
public boolean hasUnfinishedAssembleJob(Long taskId) {
|
public Set<Long> taskIdsWithUnfinishedAssembleJob(Collection<Long> taskIds) {
|
||||||
if (taskId == null) {
|
return TaskFileJobBatchQueries.taskIdsWithUnfinishedAssembleJob(taskFileJobMapper, taskIds);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
Long count = taskFileJobMapper.selectCount(new LambdaQueryWrapper<TaskFileJobEntity>()
|
|
||||||
.eq(TaskFileJobEntity::getTaskId, taskId)
|
|
||||||
.eq(TaskFileJobEntity::getJobType, JOB_TYPE_ASSEMBLE_RESULT)
|
|
||||||
.in(TaskFileJobEntity::getStatus, TaskStatuses.Job.PENDING, TaskStatuses.Job.RUNNING));
|
|
||||||
return count != null && count > 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -288,12 +287,15 @@ public class TaskFileJobService {
|
|||||||
if (candidates == null || candidates.isEmpty()) {
|
if (candidates == null || candidates.isEmpty()) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
// P1-B6:父任务状态原本逐条点查(一批 100 个候选=100 次 SELECT),折成一次批量读;
|
||||||
|
// 逐行 CAS 认领不动——那才是并发不重复派发的根据。
|
||||||
|
Set<Long> terminalTaskIds = TaskFileJobBatchQueries.terminalOwningTaskIds(taskFileJobMapper, candidates);
|
||||||
List<Long> claimedIds = new ArrayList<>();
|
List<Long> claimedIds = new ArrayList<>();
|
||||||
for (TaskFileJobEntity candidate : candidates) {
|
for (TaskFileJobEntity candidate : candidates) {
|
||||||
if (candidate == null || candidate.getId() == null) {
|
if (candidate == null || candidate.getId() == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (isOwningTaskTerminal(candidate.getTaskId())) {
|
if (terminalTaskIds.contains(candidate.getTaskId())) {
|
||||||
noteTerminalTaskStillDeliverable(candidate);
|
noteTerminalTaskStillDeliverable(candidate);
|
||||||
}
|
}
|
||||||
if (markRunning(candidate.getId())) {
|
if (markRunning(candidate.getId())) {
|
||||||
@@ -402,6 +404,26 @@ public class TaskFileJobService {
|
|||||||
* 被记成失败次数。PENDING 行的累加保留:那条防的是 dispatch 事件无限重发,与执行快慢无关。
|
* 被记成失败次数。PENDING 行的累加保留:那条防的是 dispatch 事件无限重发,与执行快慢无关。
|
||||||
*/
|
*/
|
||||||
public StuckJobResetResult resetStuckRunningJobsDetailed(int stuckMinutes, int limit) {
|
public StuckJobResetResult resetStuckRunningJobsDetailed(int stuckMinutes, int limit) {
|
||||||
|
return resetStuckRunningJobsDetailed(stuckMinutes, limit, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param currentInstanceId 本机实例 id。给了就启用归属守卫:scope_key 上明确写着
|
||||||
|
* {@code :owner:<别的实例>} 的 RUNNING 行**本轮不碰**(既不重排也不判死)。
|
||||||
|
* 留空=不启用(后管那枚人工复位按钮走这条:人明确点的就是「把它排回去」)。
|
||||||
|
*
|
||||||
|
* <p>为什么必须有这道守卫(2026-11-02 现网 33149/33179):两台各跑一份 @Scheduled,而这一支
|
||||||
|
* 原先不带归属过滤——B 扫到 A 正在跑的 RUNNING 行就把它翻回 PENDING 并 {@code +1}
|
||||||
|
* stuck_requeue_count。A 那边线程还在跑,重新 claim 后就是同一张表两个执行体;更糟的是计数
|
||||||
|
* 由「谁扫得快」决定,A 的 33149 被累到 20=判死线,下一次任何 5 分钟的停顿都会把还能补传的
|
||||||
|
* 单打成「连续 20 次卡死重排,已判失败」。这与刚根治的 owner 死锁是同一个家族:
|
||||||
|
* 归属的两个源(作业行的 owner 与任务行的 owner_instance_id)各读各的。
|
||||||
|
*
|
||||||
|
* <p>不破坏「归属实例永久消失」的恢复:那种行的 owner 标记为空或指向不在路由表里的实例时,
|
||||||
|
* 本守卫依旧放行(判据只看标记是否指向**另一个明确实例**),而任务侧另有
|
||||||
|
* {@code StaleTaskRepairService} 两小时无心跳的整单收尾兜底。
|
||||||
|
*/
|
||||||
|
public StuckJobResetResult resetStuckRunningJobsDetailed(int stuckMinutes, int limit, String currentInstanceId) {
|
||||||
LocalDateTime threshold = LocalDateTime.now().minusMinutes(Math.max(5, stuckMinutes));
|
LocalDateTime threshold = LocalDateTime.now().minusMinutes(Math.max(5, stuckMinutes));
|
||||||
List<TaskFileJobEntity> jobs = taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
List<TaskFileJobEntity> jobs = taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||||
.and(wrapper -> wrapper
|
.and(wrapper -> wrapper
|
||||||
@@ -425,6 +447,8 @@ public class TaskFileJobService {
|
|||||||
.orderByAsc(TaskFileJobEntity::getUpdatedAt)
|
.orderByAsc(TaskFileJobEntity::getUpdatedAt)
|
||||||
.last("limit " + Math.max(1, Math.min(limit, 200))));
|
.last("limit " + Math.max(1, Math.min(limit, 200))));
|
||||||
int reset = 0;
|
int reset = 0;
|
||||||
|
int skippedForeignOwner = 0;
|
||||||
|
int skippedInFlight = 0;
|
||||||
List<TaskFileJobEntity> exhaustedJobs = new ArrayList<>();
|
List<TaskFileJobEntity> exhaustedJobs = new ArrayList<>();
|
||||||
List<Long> eventJobIds = new ArrayList<>();
|
List<Long> eventJobIds = new ArrayList<>();
|
||||||
List<Long> exhaustedJobIds = new ArrayList<>();
|
List<Long> exhaustedJobIds = new ArrayList<>();
|
||||||
@@ -479,6 +503,19 @@ public class TaskFileJobService {
|
|||||||
// 的外观专利被扫描连扣 4 次,逼到「文件生成任务运行超时,已达到最大重试次数」后
|
// 的外观专利被扫描连扣 4 次,逼到「文件生成任务运行超时,已达到最大重试次数」后
|
||||||
// 0 字节收场。卡死次数改用独立列 stuck_requeue_count 记账,达到上限才判死;
|
// 0 字节收场。卡死次数改用独立列 stuck_requeue_count 记账,达到上限才判死;
|
||||||
// 这样既保住"慢执行不扣预算",又不会让无异常挂住的 job 无限重排。
|
// 这样既保住"慢执行不扣预算",又不会让无异常挂住的 job 无限重排。
|
||||||
|
String rowOwner = ownerFromScopeKey(job.getScopeKey());
|
||||||
|
if (belongsToAnotherInstance(rowOwner, currentInstanceId)) {
|
||||||
|
skippedForeignOwner++;
|
||||||
|
log.debug("[task-file-job] stuck reset 跳过另一实例正在跑的作业 jobId={} taskId={} owner={} current={}",
|
||||||
|
job.getId(), job.getTaskId(), rowOwner, currentInstanceId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isInFlight(job.getId())) {
|
||||||
|
skippedInFlight++;
|
||||||
|
log.debug("[task-file-job] stuck reset 跳过本机正在执行的作业 jobId={} taskId={} stuckRequeueCount={}",
|
||||||
|
job.getId(), job.getTaskId(), job.getStuckRequeueCount());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
int stuckCount = job.getStuckRequeueCount() == null ? 0 : job.getStuckRequeueCount();
|
int stuckCount = job.getStuckRequeueCount() == null ? 0 : job.getStuckRequeueCount();
|
||||||
if (stuckCount >= MAX_STUCK_REQUEUE) {
|
if (stuckCount >= MAX_STUCK_REQUEUE) {
|
||||||
@@ -560,6 +597,10 @@ public class TaskFileJobService {
|
|||||||
exhaustedJobs.add(refreshed == null ? originalJobsById.get(jobId) : refreshed);
|
exhaustedJobs.add(refreshed == null ? originalJobsById.get(jobId) : refreshed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (skippedForeignOwner > 0 || skippedInFlight > 0) {
|
||||||
|
log.info("[task-file-job] stuck reset 活性豁免 skippedForeignOwner={} skippedInFlight={} current={} scanned={}",
|
||||||
|
skippedForeignOwner, skippedInFlight, currentInstanceId, jobs.size());
|
||||||
|
}
|
||||||
return new StuckJobResetResult(reset, List.copyOf(exhaustedJobs));
|
return new StuckJobResetResult(reset, List.copyOf(exhaustedJobs));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -728,6 +769,45 @@ public class TaskFileJobService {
|
|||||||
.set(TaskFileJobEntity::getUpdatedAt, now));
|
.set(TaskFileJobEntity::getUpdatedAt, now));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行线程进入 {@code process} 时登记(B74-02)。登记点必须在 {@code activateRunningClaim}
|
||||||
|
* 成功之后——claim 过期没 executing 的行本来就该被扫描回收。
|
||||||
|
*/
|
||||||
|
public void markInFlight(Long jobId) {
|
||||||
|
if (jobId != null && jobId > 0) {
|
||||||
|
inFlightJobIds.add(jobId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 执行线程退出(含异常与终态收口)后注销;漏注销会让这一行永远不被回收,所以调用方必须放 finally。 */
|
||||||
|
public void clearInFlight(Long jobId) {
|
||||||
|
if (jobId != null) {
|
||||||
|
inFlightJobIds.remove(jobId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「本机有线程正在跑这一行」——卡死扫描据此不重排、不累加 {@code stuck_requeue_count}。
|
||||||
|
*
|
||||||
|
* <p>为什么必须由扫描问执行侧,而不是把 stuck 阈值抬大(B74-02 的二选一,2026-11-03 按读数定的):
|
||||||
|
* 心跳在<b>父任务终态</b>时按 CR-08 刻意停止续期({@code TaskResultFileJobWorker#startJobHeartbeat}
|
||||||
|
* 的 {@code stage=TERMINAL_STOP_RENEW}),此时执行线程还在跑但 {@code updated_at} 从此冻结——
|
||||||
|
* 冻结是<b>无限期</b>的,不是「比 5 分钟长一点」。所以阈值抬到 16 分钟也只是把 20 次计满的时间
|
||||||
|
* 从 100 分钟拖到 320 分钟,形状不变。2026-11-03 现网实证:jobId=23815/taskId=33179
|
||||||
|
* 06:07:20 到 {@code stuckRequeueCount=20},06:08 复位恢复、09:20 又同样两条——同一个
|
||||||
|
* 「既不失败也不完成」的环。抬阈值还会把真遗骸的回收从 5 分钟拖到十几分钟,两头都输。
|
||||||
|
*
|
||||||
|
* <p>与刚收口的跨实例归属守卫是同一判据的两半:那一半管「别的机器在跑」,这一半管「本机在跑」。
|
||||||
|
*/
|
||||||
|
public boolean isInFlight(Long jobId) {
|
||||||
|
return jobId != null && inFlightJobIds.contains(jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 供用例断言登记面;生产路径不应依赖它做决策。 */
|
||||||
|
public int inFlightCount() {
|
||||||
|
return inFlightJobIds.size();
|
||||||
|
}
|
||||||
|
|
||||||
public boolean deferRunning(Long jobId, String message) {
|
public boolean deferRunning(Long jobId, String message) {
|
||||||
if (jobId == null || jobId <= 0) {
|
if (jobId == null || jobId <= 0) {
|
||||||
return false;
|
return false;
|
||||||
@@ -1044,6 +1124,21 @@ public class TaskFileJobService {
|
|||||||
return owner.isBlank() ? null : owner;
|
return owner.isBlank() ? null : owner;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「这一行明确归**另一个**实例」——卡死扫描的归属守卫判据(见
|
||||||
|
* {@link #resetStuckRunningJobsDetailed(int, int, String)})。
|
||||||
|
*
|
||||||
|
* <p>只在两侧都非空且不相等时成立:本机 id 未知(单实例部署、元数据缺失、后管人工复位)时
|
||||||
|
* 守卫整体不启用,绝不能因为它拿不到 id 就把所有重排停掉——那会把唯一能救回遗骸的通道一起关死。
|
||||||
|
*/
|
||||||
|
static boolean belongsToAnotherInstance(String rowOwner, String currentInstanceId) {
|
||||||
|
if (currentInstanceId == null || currentInstanceId.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String owner = rowOwner == null ? null : rowOwner.trim();
|
||||||
|
return owner != null && !owner.isBlank() && !owner.equals(currentInstanceId.trim());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@link #ownerFromScopeKey} 的逆操作:把 scope_key 最后一个 {@code :owner:} 之后的尾段换成指定实例。
|
* {@link #ownerFromScopeKey} 的逆操作:把 scope_key 最后一个 {@code :owner:} 之后的尾段换成指定实例。
|
||||||
* 无标记时原样返回——那种 scope_key 本来就不携带归属信息,不该被凭空造出一个 owner 段。
|
* 无标记时原样返回——那种 scope_key 本来就不携带归属信息,不该被凭空造出一个 owner 段。
|
||||||
|
|||||||
+37
-1
@@ -362,10 +362,30 @@ public class TaskHeartbeatPositionService {
|
|||||||
long now = Instant.now().toEpochMilli();
|
long now = Instant.now().toEpochMilli();
|
||||||
String storedFingerprint = stored == null ? "" : value(stored, "pos");
|
String storedFingerprint = stored == null ? "" : value(stored, "pos");
|
||||||
long unchangedSince = stored == null ? 0L : parseMillis(stored.get("at"));
|
long unchangedSince = stored == null ? 0L : parseMillis(stored.get("at"));
|
||||||
if (!fingerprint.equals(storedFingerprint) || unchangedSince <= 0L) {
|
boolean snapshotMissing = stored == null || stored.isEmpty();
|
||||||
|
if (!snapshotMissing && !fingerprint.equals(storedFingerprint)) {
|
||||||
|
// 指纹真的变了=客户端主线程还在干活,起点重锚在「现在」。
|
||||||
writeStallSnapshot(stallKey, fingerprint, now, staleWindowMinutes);
|
writeStallSnapshot(stallKey, fingerprint, now, staleWindowMinutes);
|
||||||
return StallState.ADVANCING;
|
return StallState.ADVANCING;
|
||||||
}
|
}
|
||||||
|
if (snapshotMissing || unchangedSince <= 0L) {
|
||||||
|
// B74-03:这两种形状原先与「指纹变了」共用同一个 ADVANCING 出口,等于把
|
||||||
|
// 「没有证据」当成「证据表明在推进」。现网实证(2026-11-02 任务 33179,20:20–21:02
|
||||||
|
// 每 2 分钟一条「客户端仍在推进」而 lastResultAt 已 3h48m 不动):本键 TTL 是
|
||||||
|
// max(60, window×3)=9 小时,键一过期就重锚到 now,于是每 9 小时白送一轮完整豁免窗口,
|
||||||
|
// 沉默的客户端永远封不了口。
|
||||||
|
// 分流做法:锚点重建成**客户端最后一次上报**的时刻(位置哈希自己的 at,由 record()
|
||||||
|
// 每次心跳刷新),拿不到才退回 now;随后照走同一条时间判据,豁免长度由真实沉默时长决定,
|
||||||
|
// 而不是由「键什么时候消失」决定。客户端确在心跳时 anchor 就是新鲜的 ⇒ 仍判 ADVANCING,
|
||||||
|
// 这一侧不会把还在采集的任务判死(28919 的教训记在 isClientAdvancing 的注释上)。
|
||||||
|
long reportedAt = positionReportedAtMillis(taskId);
|
||||||
|
long anchor = reportedAt > 0L ? reportedAt : now;
|
||||||
|
log.info("[heartbeat-position] 停滞锚点重建 taskId={} reason={} anchor={} anchorAgeMs={}",
|
||||||
|
taskId, snapshotMissing ? "snapshot-missing" : "stamp-unreadable",
|
||||||
|
anchor, now - anchor);
|
||||||
|
writeStallSnapshot(stallKey, fingerprint, anchor, staleWindowMinutes);
|
||||||
|
unchangedSince = anchor;
|
||||||
|
}
|
||||||
long unchangedMillis = now - unchangedSince;
|
long unchangedMillis = now - unchangedSince;
|
||||||
if (unchangedMillis >= Duration.ofMinutes(staleWindowMinutes).toMillis()) {
|
if (unchangedMillis >= Duration.ofMinutes(staleWindowMinutes).toMillis()) {
|
||||||
return StallState.STALLED;
|
return StallState.STALLED;
|
||||||
@@ -375,6 +395,22 @@ public class TaskHeartbeatPositionService {
|
|||||||
return StallState.ADVANCING;
|
return StallState.ADVANCING;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 客户端最后一次上报位置的时刻(毫秒),读不到返回 0。
|
||||||
|
*
|
||||||
|
* <p>与 {@link #readProgressFingerprint} 读的是同一枚哈希,只是多取一个 {@code at} 字段——
|
||||||
|
* 那里只取计数与文本,所以这一枚时间戳此前没有任何人读过,B74-03 的锚点也就一直错到 now 上。
|
||||||
|
*/
|
||||||
|
private long positionReportedAtMillis(Long taskId) {
|
||||||
|
try {
|
||||||
|
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(KEY_PREFIX + taskId);
|
||||||
|
return entries == null ? 0L : parseMillis(entries.get("at"));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.warn("[heartbeat-position] 读取位置上报时刻失败 taskId={} msg={}", taskId, ex.getMessage());
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 便捷判定:客户端是否仍在推进(位置文本仍在变)。
|
* 便捷判定:客户端是否仍在推进(位置文本仍在变)。
|
||||||
*
|
*
|
||||||
|
|||||||
+3
@@ -18,6 +18,7 @@ import java.time.LocalDateTime;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 任务心跳入口。
|
* 任务心跳入口。
|
||||||
@@ -173,6 +174,7 @@ public class TaskHeartbeatService {
|
|||||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||||
.set(FileTaskEntity::getStatus, "FAILED")
|
.set(FileTaskEntity::getStatus, "FAILED")
|
||||||
.set(FileTaskEntity::getErrorMessage, safeReason)
|
.set(FileTaskEntity::getErrorMessage, safeReason)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(safeReason))
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
log.warn("[task-interrupted] file task marked failed by client restart taskId={} moduleType={} reason={}",
|
log.warn("[task-interrupted] file task marked failed by client restart taskId={} moduleType={} reason={}",
|
||||||
@@ -231,6 +233,7 @@ public class TaskHeartbeatService {
|
|||||||
.in(FileTaskEntity::getStatus, TaskStatuses.FileTask.ACTIVE_ORDERED)
|
.in(FileTaskEntity::getStatus, TaskStatuses.FileTask.ACTIVE_ORDERED)
|
||||||
.set(FileTaskEntity::getStatus, TaskStatuses.FileTask.CANCELLED)
|
.set(FileTaskEntity::getStatus, TaskStatuses.FileTask.CANCELLED)
|
||||||
.set(FileTaskEntity::getErrorMessage, message)
|
.set(FileTaskEntity::getErrorMessage, message)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(message))
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||||
if (updated > 0) {
|
if (updated > 0) {
|
||||||
log.warn("[task-cancel] file task cancelled by user taskId={} moduleType={}",
|
log.warn("[task-cancel] file task cancelled by user taskId={} moduleType={}",
|
||||||
|
|||||||
+2
@@ -14,6 +14,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 失败/中断任务「在原任务上重试/继续」的唯一出口(2026-11-01 用户拍板失败重试;
|
* 失败/中断任务「在原任务上重试/继续」的唯一出口(2026-11-01 用户拍板失败重试;
|
||||||
@@ -81,6 +82,7 @@ public class TaskInPlaceRetryService {
|
|||||||
.in(FileTaskEntity::getStatus, STATUS_FAILED, STATUS_CANCELLED)
|
.in(FileTaskEntity::getStatus, STATUS_FAILED, STATUS_CANCELLED)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_PENDING)
|
.set(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||||
.set(FileTaskEntity::getErrorMessage, null)
|
.set(FileTaskEntity::getErrorMessage, null)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, null)
|
||||||
.set(FileTaskEntity::getFinishedAt, null)
|
.set(FileTaskEntity::getFinishedAt, null)
|
||||||
.set(FileTaskEntity::getResumeAttempt, attempt + 1)
|
.set(FileTaskEntity::getResumeAttempt, attempt + 1)
|
||||||
.set(FileTaskEntity::getUpdatedAt, now));
|
.set(FileTaskEntity::getUpdatedAt, now));
|
||||||
|
|||||||
+25
-7
@@ -113,7 +113,7 @@ public class TaskResultFileJobWorker {
|
|||||||
@Scheduled(fixedDelayString = "${aiimage.result-file-job.stuck-scan-delay-ms:60000}")
|
@Scheduled(fixedDelayString = "${aiimage.result-file-job.stuck-scan-delay-ms:60000}")
|
||||||
public void resetStuckJobs() {
|
public void resetStuckJobs() {
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
taskFileJobService.resetStuckRunningJobsDetailed(stuckTimeoutMinutes, batchSize);
|
taskFileJobService.resetStuckRunningJobsDetailed(stuckTimeoutMinutes, batchSize, currentInstanceId());
|
||||||
if (result.resetCount() > 0 || !result.exhaustedJobs().isEmpty()) {
|
if (result.resetCount() > 0 || !result.exhaustedJobs().isEmpty()) {
|
||||||
log.warn("[task-file-job] handled stuck running jobs resetCount={} exhaustedCount={} timeoutMinutes={}",
|
log.warn("[task-file-job] handled stuck running jobs resetCount={} exhaustedCount={} timeoutMinutes={}",
|
||||||
result.resetCount(), result.exhaustedJobs().size(), stuckTimeoutMinutes);
|
result.resetCount(), result.exhaustedJobs().size(), stuckTimeoutMinutes);
|
||||||
@@ -269,15 +269,33 @@ public class TaskResultFileJobWorker {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
AtomicBoolean parentTerminalObserved = new AtomicBoolean(false);
|
AtomicBoolean parentTerminalObserved = new AtomicBoolean(false);
|
||||||
ScheduledFuture<?> heartbeat = startJobHeartbeat(job, parentTerminalObserved);
|
// B74-02:向作业服务登记「本机线程正在跑这一行」。父任务终态时心跳会刻意停续期
|
||||||
|
// (stage=TERMINAL_STOP_RENEW),updated_at 从此无限期冻结,卡死扫描若只看时间戳就会
|
||||||
|
// 每 5 分钟给还在跑的执行线程记一次 stuck_requeue_count,20 次把还能出表的单判死
|
||||||
|
// (2026-11-03 现网 jobId=23815/taskId=33179 正是这个环)。注销必须在 finally。
|
||||||
|
// (2026-11-04 CR-P2)登记与心跳都必须在这道 try **内**起:旧形状把 markInFlight
|
||||||
|
// 放在 try 外、注销放在 finally,而 `startJobHeartbeat` 在容器关闭时会抛
|
||||||
|
// RejectedExecutionException(jobHeartbeatExecutor 已 shutdownNow)——那一跳直接绕过
|
||||||
|
// finally,把这个 jobId 永久留在在飞登记里:卡死扫描从此永远跳过这一行,
|
||||||
|
// 既不失败也不完成=静默停摆,正是下面这段注释本身要防的形状。重启进程才清得掉,
|
||||||
|
// 而"重启即空"不能当兜底——那等于把这一单无限期挂在"看起来还在跑"上。
|
||||||
|
ScheduledFuture<?> heartbeat = null;
|
||||||
try {
|
try {
|
||||||
|
taskFileJobService.markInFlight(job.getId());
|
||||||
|
heartbeat = startJobHeartbeat(job, parentTerminalObserved);
|
||||||
processInternal(job);
|
processInternal(job);
|
||||||
} finally {
|
} finally {
|
||||||
heartbeat.cancel(false);
|
if (heartbeat != null) {
|
||||||
// CR-08:心跳只负责停续期;终态判定必须等执行线程退出后再做。
|
heartbeat.cancel(false);
|
||||||
// 此时若 markSuccess 已落库,finishAfterExecution 会保留 SUCCESS;
|
}
|
||||||
// 只有执行线程没写出成功状态的行才判死并留给兜底扫描出部分结果。
|
try {
|
||||||
finishAfterExecution(job, parentTerminalObserved);
|
// CR-08:心跳只负责停续期;终态判定必须等执行线程退出后再做。
|
||||||
|
// 此时若 markSuccess 已落库,finishAfterExecution 会保留 SUCCESS;
|
||||||
|
// 只有执行线程没写出成功状态的行才判死并留给兜底扫描出部分结果。
|
||||||
|
finishAfterExecution(job, parentTerminalObserved);
|
||||||
|
} finally {
|
||||||
|
taskFileJobService.clearInFlight(job.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+34
-19
@@ -35,6 +35,8 @@ public class TaskResultItemService {
|
|||||||
*/
|
*/
|
||||||
private final ExecutorService snapshotReadPool =
|
private final ExecutorService snapshotReadPool =
|
||||||
com.nanri.aiimage.common.support.ThreadPools.boundedFixed("task-result-read", 8);
|
com.nanri.aiimage.common.support.ThreadPools.boundedFixed("task-result-read", 8);
|
||||||
|
/** 指针化载荷并发读的窗口:见 {@link #listResultSnapshots} 的 P1-B7 说明。 */
|
||||||
|
static final int SNAPSHOT_READ_WINDOW = com.nanri.aiimage.common.support.ThreadPools.DEFAULT_QUEUE_CAPACITY / 2;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final TransientPayloadStorageService transientPayloadStorageService;
|
private final TransientPayloadStorageService transientPayloadStorageService;
|
||||||
|
|
||||||
@@ -95,7 +97,11 @@ public class TaskResultItemService {
|
|||||||
* <p>刻意不加 limit:调用方要用它组装完整的结果文件,截断即漏行(正确性错误,
|
* <p>刻意不加 limit:调用方要用它组装完整的结果文件,截断即漏行(正确性错误,
|
||||||
* 不是性能取舍)。调用方多为「逐任务循环调用」,因此峰值内存 = 单个任务的结果集,
|
* 不是性能取舍)。调用方多为「逐任务循环调用」,因此峰值内存 = 单个任务的结果集,
|
||||||
* 这是本操作固有的代价。若要再降,需要改成「边读边写文件」的流式组装契约,
|
* 这是本操作固有的代价。若要再降,需要改成「边读边写文件」的流式组装契约,
|
||||||
* 涉及 4 个模块的组装实现,属独立工程。
|
* 涉及 4 个模块的组装实现(patroldelete/queryasin/shopdatacrawl/withdraw),属独立工程。
|
||||||
|
*
|
||||||
|
* <p>P1-B7 在本方法里能收的是**另一件事**:整份结果集不需要被读两遍。指针化载荷那条分支
|
||||||
|
* 按窗口提交+收割(见下方 P1-B7 注释),副本只驻留一窗;返回仍是整份 {@code List},
|
||||||
|
* 「流式组装契约」那半没做,别把本段读成 P1-B7 已闭环。
|
||||||
*/
|
*/
|
||||||
public <T> List<T> listResultSnapshots(Long taskId, String moduleType, Class<T> clazz) {
|
public <T> List<T> listResultSnapshots(Long taskId, String moduleType, Class<T> clazz) {
|
||||||
if (taskId == null || taskId <= 0 || isBlank(moduleType)) {
|
if (taskId == null || taskId <= 0 || isBlank(moduleType)) {
|
||||||
@@ -129,26 +135,35 @@ public class TaskResultItemService {
|
|||||||
T value = readPayload(rows.get(0), clazz);
|
T value = readPayload(rows.get(0), clazz);
|
||||||
return value == null ? List.of() : List.of(value);
|
return value == null ? List.of() : List.of(value);
|
||||||
}
|
}
|
||||||
List<Future<T>> futures = new ArrayList<>(rows.size());
|
// P1-B7(2026-11-03):**分窗提交并收割**,不再把整份结果集一次性交进线程池。
|
||||||
for (TaskResultItemEntity row : rows) {
|
// 一次性提交时,每支 Future 完成后仍把解好的载荷扣在自己身上(FutureTask.outcome 不清),
|
||||||
futures.add(snapshotReadPool.submit(() -> readPayload(row, clazz)));
|
// 而这一批 Future 又要等最后一个才释放 ⇒ 峰值=「结果集」+「同样多的另一份副本」。
|
||||||
}
|
// 一窗一收之后,窗内的副本收完就可回收,峰值退化成「结果集」+「一窗」。
|
||||||
|
// 窗口取队列容量的一半:8 线程+512 队列(ThreadPools.DEFAULT_QUEUE_CAPACITY)在窗内永不排满,
|
||||||
|
// 也就不会落到 CallerRunsPolicy 上把请求线程变成同步读对象存储的那个人。
|
||||||
List<T> out = new ArrayList<>(rows.size());
|
List<T> out = new ArrayList<>(rows.size());
|
||||||
for (Future<T> future : futures) {
|
for (int from = 0; from < rows.size(); from += SNAPSHOT_READ_WINDOW) {
|
||||||
try {
|
int to = Math.min(from + SNAPSHOT_READ_WINDOW, rows.size());
|
||||||
T value = future.get();
|
List<Future<T>> window = new ArrayList<>(to - from);
|
||||||
if (value != null) {
|
for (TaskResultItemEntity row : rows.subList(from, to)) {
|
||||||
out.add(value);
|
window.add(snapshotReadPool.submit(() -> readPayload(row, clazz)));
|
||||||
|
}
|
||||||
|
for (Future<T> future : window) {
|
||||||
|
try {
|
||||||
|
T value = future.get();
|
||||||
|
if (value != null) {
|
||||||
|
out.add(value);
|
||||||
|
}
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new BusinessException("读取任务结果明细被中断");
|
||||||
|
} catch (ExecutionException ex) {
|
||||||
|
Throwable cause = ex.getCause();
|
||||||
|
if (cause instanceof BusinessException businessException) {
|
||||||
|
throw businessException;
|
||||||
|
}
|
||||||
|
throw new BusinessException("读取任务结果明细失败", cause);
|
||||||
}
|
}
|
||||||
} catch (InterruptedException ex) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw new BusinessException("读取任务结果明细被中断");
|
|
||||||
} catch (ExecutionException ex) {
|
|
||||||
Throwable cause = ex.getCause();
|
|
||||||
if (cause instanceof BusinessException businessException) {
|
|
||||||
throw businessException;
|
|
||||||
}
|
|
||||||
throw new BusinessException("读取任务结果明细失败", cause);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
|
|||||||
+28
-3
@@ -10,6 +10,8 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.springframework.dao.DuplicateKeyException;
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronization;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
@@ -95,10 +97,33 @@ public class TaskResultPayloadService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
TaskResultPayloadEntity existing = findLatest(taskId, moduleType, hash(scopeKey.trim()));
|
TaskResultPayloadEntity existing = findLatest(taskId, moduleType, hash(scopeKey.trim()));
|
||||||
if (existing != null) {
|
if (existing == null) {
|
||||||
transientPayloadStorageService.deletePayloadIfPresent(existing.getPayloadJson());
|
return;
|
||||||
taskResultPayloadMapper.deleteById(existing.getId());
|
|
||||||
}
|
}
|
||||||
|
// P1-B8:先落库、提交之后再删对象存储。原先的顺序(存储删完再 deleteById)把一次
|
||||||
|
// 网络调用(超时 120s、重试 3 次)连同它的引用计数反查一起塞进 DB 事务:连接被长时间
|
||||||
|
// 占住,且回滚时对象已经没了、行还在=读得到一个不存在的载荷。同一批结果明细行
|
||||||
|
// (TaskResultItemService#deletePayloadsAfterCommit,2026-09)已经改过这个形状,
|
||||||
|
// 这里补齐漏掉的这一处;提交后删还有一层好处——引用反查看到的是行已删除的 DB 状态。
|
||||||
|
taskResultPayloadMapper.deleteById(existing.getId());
|
||||||
|
deletePayloadAfterCommit(existing.getPayloadJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 事务提交后再删对象存储上的载荷;无事务上下文时直接删(与 TaskResultItemService 同口径)。 */
|
||||||
|
private void deletePayloadAfterCommit(String payloadValue) {
|
||||||
|
if (payloadValue == null || payloadValue.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||||
|
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||||
|
@Override
|
||||||
|
public void afterCommit() {
|
||||||
|
transientPayloadStorageService.deletePayloadIfPresent(payloadValue);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
transientPayloadStorageService.deletePayloadIfPresent(payloadValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
private TaskResultPayloadEntity findLatest(Long taskId, String moduleType, String scopeHash) {
|
private TaskResultPayloadEntity findLatest(Long taskId, String moduleType, String scopeHash) {
|
||||||
|
|||||||
+49
-10
@@ -13,12 +13,14 @@ import org.springframework.stereotype.Service;
|
|||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 失败任务的自动重试:把仍可执行的原任务**克隆**成一条新的 PENDING 任务,最多重试 3 代。
|
* 失败任务的自动重试:把仍可执行的原任务**克隆**成一条新的 PENDING 任务,最多重试 3 代。
|
||||||
@@ -66,8 +68,8 @@ public class TaskResumeService {
|
|||||||
|
|
||||||
private final FileTaskMapper fileTaskMapper;
|
private final FileTaskMapper fileTaskMapper;
|
||||||
/**
|
/**
|
||||||
* 查"这单名下还有没有活着的组装作业"——补检轮还活着的意思,见
|
* 查"这批单名下还有没有活着的组装作业"——补检轮还活着的意思,见
|
||||||
* {@link TaskFileJobService#hasUnfinishedAssembleJob(Long)}。
|
* {@link TaskFileJobService#taskIdsWithUnfinishedAssembleJob(Collection)}。
|
||||||
*/
|
*/
|
||||||
private final TaskFileJobService taskFileJobs;
|
private final TaskFileJobService taskFileJobs;
|
||||||
/** moduleType → 克隆重试实现;只有注册了本 SPI 的模块才会自动重试(SPI 现在只作「支持重试」白名单用)。 */
|
/** moduleType → 克隆重试实现;只有注册了本 SPI 的模块才会自动重试(SPI 现在只作「支持重试」白名单用)。 */
|
||||||
@@ -200,6 +202,18 @@ public class TaskResumeService {
|
|||||||
return stats;
|
return stats;
|
||||||
}
|
}
|
||||||
stats.scannedTaskCount = candidates.size();
|
stats.scannedTaskCount = candidates.size();
|
||||||
|
// P1-B5:下面两条判定原先逐行各问一次库(500 个候选=1,000 次往返,且
|
||||||
|
// `resume_of_task_id` 在 V187 之前无索引=每次还是一场全表扫)。折成两次批量查,
|
||||||
|
// 循环里只做集合判定。原地复位不新增子任务行(2026-11-01 起),所以预取的集合
|
||||||
|
// 不会在本轮内被自己写脏。
|
||||||
|
Set<Long> candidateIds = new LinkedHashSet<>();
|
||||||
|
for (FileTaskEntity candidate : candidates) {
|
||||||
|
if (candidate.getId() != null) {
|
||||||
|
candidateIds.add(candidate.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Set<Long> parentsWithChild = parentsWithRetryChild(candidateIds);
|
||||||
|
Set<Long> recheckingTaskIds = taskFileJobs.taskIdsWithUnfinishedAssembleJob(candidateIds);
|
||||||
for (FileTaskEntity original : candidates) {
|
for (FileTaskEntity original : candidates) {
|
||||||
if (original.getUserId() == null || original.getUserId() <= 0) {
|
if (original.getUserId() == null || original.getUserId() <= 0) {
|
||||||
stats.skippedTaskCount++;
|
stats.skippedTaskCount++;
|
||||||
@@ -213,7 +227,13 @@ public class TaskResumeService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
TaskRetryEligibility.Category notRetryable =
|
TaskRetryEligibility.Category notRetryable =
|
||||||
TaskRetryEligibility.forceMajeureCategory(original.getErrorMessage());
|
// 双读(B51-R1)定档是**文案判得出按文案、判不出才按列**,不是"有列读列"
|
||||||
|
// (2026-11-04 CR 纠正本注释:它写的正是被反向验证打回的那份草稿口径,
|
||||||
|
// 留着就是把下一个人引回去把代码改成真 bug)。实体写面
|
||||||
|
// (setErrorMessage+updateById)改文案带不动列,无条件读列=让一列**陈旧**
|
||||||
|
// 的判决判死当前这一单,比它要修的 bug 更糟;背离时逐字等于加列前的今天。
|
||||||
|
// 自动续跑是每天真在跑的判死面,更要按这条读。
|
||||||
|
TaskRetryEligibility.category(original);
|
||||||
if (notRetryable != null) {
|
if (notRetryable != null) {
|
||||||
stats.forceMajeureSkippedCount++;
|
stats.forceMajeureSkippedCount++;
|
||||||
// 这句不再自称"不可抗力":category=STOPPED 是我们自己停的,写成不可抗力会把运维
|
// 这句不再自称"不可抗力":category=STOPPED 是我们自己停的,写成不可抗力会把运维
|
||||||
@@ -223,7 +243,7 @@ public class TaskResumeService {
|
|||||||
abbreviate(original.getErrorMessage()));
|
abbreviate(original.getErrorMessage()));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (hasRetryChild(original.getId())) {
|
if (parentsWithChild.contains(original.getId())) {
|
||||||
stats.skippedTaskCount++;
|
stats.skippedTaskCount++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -231,7 +251,7 @@ public class TaskResumeService {
|
|||||||
// (见 AppearancePatentDeliverySupport.requestRecheckForMissingRows),此时克隆=同一份活
|
// (见 AppearancePatentDeliverySupport.requestRecheckForMissingRows),此时克隆=同一份活
|
||||||
// 开两份、还各按全量重跑一遍。作业真卡死另有 TaskResultFileJobWorker 的 stuck 扫描兜底,
|
// 开两份、还各按全量重跑一遍。作业真卡死另有 TaskResultFileJobWorker 的 stuck 扫描兜底,
|
||||||
// 不会因为这条例外就永远没人管。
|
// 不会因为这条例外就永远没人管。
|
||||||
if (taskFileJobs.hasUnfinishedAssembleJob(original.getId())) {
|
if (recheckingTaskIds.contains(original.getId())) {
|
||||||
stats.skippedTaskCount++;
|
stats.skippedTaskCount++;
|
||||||
log.info("[task-resume] 不重试 taskId={} moduleType={} 原因=组装作业仍在补检(PENDING/RUNNING)",
|
log.info("[task-resume] 不重试 taskId={} moduleType={} 原因=组装作业仍在补检(PENDING/RUNNING)",
|
||||||
original.getId(), original.getModuleType());
|
original.getId(), original.getModuleType());
|
||||||
@@ -302,11 +322,29 @@ public class TaskResumeService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 该原任务是否已经有重试任务(反查 resume_of_task_id)。 */
|
/**
|
||||||
private boolean hasRetryChild(Long originalTaskId) {
|
* 这批原任务里哪些已经有重试子任务(反查 {@code resume_of_task_id})。
|
||||||
Long count = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
*
|
||||||
.eq(FileTaskEntity::getResumeOfTaskId, originalTaskId));
|
* <p>P1-B5:判据与原来的单条档逐字相同(同一列、同一等值),只是把 N 次点查折成一次
|
||||||
return count != null && count > 0;
|
* {@code IN} 批查——那列在 V187 之前没有索引,巡检一轮 500 个候选就是 500 场全表扫。
|
||||||
|
*/
|
||||||
|
private Set<Long> parentsWithRetryChild(Collection<Long> originalTaskIds) {
|
||||||
|
if (originalTaskIds == null || originalTaskIds.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
List<FileTaskEntity> children = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||||
|
.select(FileTaskEntity::getResumeOfTaskId)
|
||||||
|
.in(FileTaskEntity::getResumeOfTaskId, originalTaskIds));
|
||||||
|
if (children == null || children.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
Set<Long> parents = new LinkedHashSet<>();
|
||||||
|
for (FileTaskEntity child : children) {
|
||||||
|
if (child != null && child.getResumeOfTaskId() != null) {
|
||||||
|
parents.add(child.getResumeOfTaskId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parents;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -360,6 +398,7 @@ public class TaskResumeService {
|
|||||||
.in(FileTaskEntity::getStatus, LIVE_STATUSES)
|
.in(FileTaskEntity::getStatus, LIVE_STATUSES)
|
||||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||||
.set(FileTaskEntity::getErrorMessage, DUPLICATE_STOP_REASON)
|
.set(FileTaskEntity::getErrorMessage, DUPLICATE_STOP_REASON)
|
||||||
|
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(DUPLICATE_STOP_REASON))
|
||||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now())
|
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now())
|
||||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
||||||
if (updated == 1) {
|
if (updated == 1) {
|
||||||
|
|||||||
+46
@@ -1,5 +1,7 @@
|
|||||||
package com.nanri.aiimage.modules.task.service;
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
|
||||||
@@ -119,6 +121,50 @@ public final class TaskRetryEligibility {
|
|||||||
return category == null ? "" : category.label();
|
return category == null ? "" : category.label();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 双读入口(B51-R1 的 Expand 半边):文案还判得出就按文案,判不出才轮到
|
||||||
|
* {@code biz_file_task.failure_category} 里登记的那一笔。
|
||||||
|
*
|
||||||
|
* <p>列是「那次判断的结果」,文案是「给人看的一句话」——判生死不该挂在一句话的措辞上,
|
||||||
|
* 所以措辞漂移到 markers 认不出时,判决仍由列钉在原处。存量行的列一律为空,回落就是
|
||||||
|
* 切换前的口径,行为逐字不变。
|
||||||
|
*
|
||||||
|
* <p><b>为什么不写成「有列就无条件读列」</b>:{@code setErrorMessage} 的实体式写入面
|
||||||
|
* (若干 {@code task.setErrorMessage(...)} + {@code updateById})本轮还没接
|
||||||
|
* {@code TaskFailureLedger},它改文案时带不动列(MyBatis-Plus 默认不更新 null 字段),
|
||||||
|
* 于是同一行会出现「列记着上一次判决、文案已是另一次失败」。那种背离里列是<b>陈旧</b>的:
|
||||||
|
* 无条件读列等于让一个已经不代表当前失败原因的值判死这一单——那是本笔改动自己引入的行为漂移,
|
||||||
|
* 比它要修的 bug 更糟。两者都能判出却不同类时按文案读,逐字等于加列之前的今天。
|
||||||
|
*
|
||||||
|
* <p>不在值域内的字符串按「没登记」处理并回落,<b>不</b>写成 {@code valueOf} + catch:
|
||||||
|
* 静默 catch 会计入 {@code CatchSilenceRatchetTest} 的总数上限(铁律 19 的 2026-10-31 实录,
|
||||||
|
* 加 2 处就把后端整量打红),逐值比对同样不抛。
|
||||||
|
*/
|
||||||
|
public static Category category(FileTaskEntity task) {
|
||||||
|
if (task == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Category fromMessage = forceMajeureCategory(task.getErrorMessage());
|
||||||
|
if (fromMessage != null) {
|
||||||
|
return fromMessage;
|
||||||
|
}
|
||||||
|
return categoryByName(task.getFailureCategory());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按值逐个比对枚举名;空串或不在值域内一律返回 null(=未登记),不抛异常。 */
|
||||||
|
public static Category categoryByName(String raw) {
|
||||||
|
if (raw == null || raw.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String name = raw.trim();
|
||||||
|
for (Category category : Category.values()) {
|
||||||
|
if (category.name().equals(name)) {
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean containsAny(String text, List<String> markers) {
|
private static boolean containsAny(String text, List<String> markers) {
|
||||||
for (String marker : markers) {
|
for (String marker : markers) {
|
||||||
if (text.contains(marker)) {
|
if (text.contains(marker)) {
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service.support;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务失败分类的<b>写入口</b>(B51-R1,{@code docs/REFACTOR_PLAN.md} §3.1)。
|
||||||
|
*
|
||||||
|
* <p>它只做一件事:把「这段文案属于哪一类」的判断<b>结果</b>记进
|
||||||
|
* {@code biz_file_task.failure_category},与文案同笔落库。判定逻辑本身仍然只有
|
||||||
|
* {@link TaskRetryEligibility} 一处——本类不复制词汇表,否则就又造出一个第二正本(B52 那一族)。
|
||||||
|
*
|
||||||
|
* <p>为什么列和文案要同时写:判死/重试/重开原先只读中文子串,改一句用户看得见的文案就
|
||||||
|
* 静默改一次整单生死。列落下之后,读侧「文案判得出按文案、判不出按列」,文案怎么改都不再动摇已登记的判定。
|
||||||
|
*
|
||||||
|
* <p>返回 {@code null} 有两种来源,读侧同待:① 文案确实不属于任何一类(普通可重试失败);
|
||||||
|
* ② 这一行还没接上本出口(实体式写入面,Contract 阶段之前分批补齐)。<b>不许</b>把空列读成
|
||||||
|
* 「分类为 UNKNOWN」——那会让存量行在切换日集体变成一种新状态。实体式 {@code setErrorMessage}
|
||||||
|
* 改文案时带不动列(MyBatis-Plus 默认不更新 null 字段),所以那一面在接上 ledger 之前会出现
|
||||||
|
* 「列记着上一次判决、文案已是另一次失败」的背离;读侧按文案优先,正是为了不让这种陈旧列判死这一单。
|
||||||
|
*/
|
||||||
|
public final class TaskFailureLedger {
|
||||||
|
|
||||||
|
private TaskFailureLedger() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 由失败文案推出分类名({@code TaskRetryEligibility.Category.name()});判不出返回 null。 */
|
||||||
|
public static String categoryOf(String errorMessage) {
|
||||||
|
TaskRetryEligibility.Category category = TaskRetryEligibility.forceMajeureCategory(errorMessage);
|
||||||
|
return category == null ? null : category.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service.support;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务归属实例的 <b>JSON 回落</b>——四台(外观专利/相似ASIN/发布/店铺采集)共用的唯一出处(B74-04)。
|
||||||
|
*
|
||||||
|
* <p>列优先是铁律 28 定的:任务转交后只有 {@code owner_instance_id} 会被更新,JSON 快照停在
|
||||||
|
* parse 那一刻。但「列缺失时读哪一枚 JSON」此前四处各写各的——三台读 {@code result_json},
|
||||||
|
* 店铺采集读 {@code request_json}。同一条存量行(实测 RUNNING 任务里 {@code owner_instance_id}
|
||||||
|
* 为空的有 39 行)在四台眼里因此可以算出<b>两个</b>归属,正是 2026-11-02 互斥死锁的家族形状。
|
||||||
|
*
|
||||||
|
* <p>顺序固定为 {@code result_json → request_json}:前者是 parse/交付快照(正档),后者是提交时
|
||||||
|
* 最旧的一手,只有正档确实没有时才作参考,并且必须留下 WARN——它一旦生效就说明列与正档都没写上。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public final class TaskOwnerJsonFallback {
|
||||||
|
|
||||||
|
/** owner 字段名:四台读取与写入侧(payload/result_json)共用同一个拼写。 */
|
||||||
|
public static final String OWNER_FIELD = "ownerInstanceId";
|
||||||
|
|
||||||
|
private TaskOwnerJsonFallback() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param logTag 所属模块的日志前缀,便于现网分辨是哪一台走到了回落
|
||||||
|
* @return 归属实例 id;两枚快照都读不出时返回 null(调用方按「无归属」放行)
|
||||||
|
*/
|
||||||
|
public static String ownerFrom(FileTaskEntity task, ObjectMapper objectMapper, String logTag) {
|
||||||
|
if (task == null || objectMapper == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String fromResult = read(task.getResultJson(), objectMapper);
|
||||||
|
if (fromResult != null) {
|
||||||
|
return fromResult;
|
||||||
|
}
|
||||||
|
String fromRequest = read(task.getRequestJson(), objectMapper);
|
||||||
|
if (fromRequest != null) {
|
||||||
|
log.warn("[{}] 任务归属落到 request_json 提交快照 taskId={} owner={} —— "
|
||||||
|
+ "只有 owner_instance_id 列与 result_json 都读不出时才走到这里",
|
||||||
|
logTag, task.getId(), fromRequest);
|
||||||
|
}
|
||||||
|
return fromRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String read(String json, ObjectMapper objectMapper) {
|
||||||
|
if (json == null || json.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonNode root = objectMapper.readTree(json);
|
||||||
|
if (root == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String owner = root.path(OWNER_FIELD).asText("");
|
||||||
|
return owner.isBlank() ? null : owner.trim();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
// 读不出归属=不认领,绝不抛:抛出去会把一次正常的状态检查变成 500。
|
||||||
|
// 但必须报出来——静默返回 null 会被调用方读成"这行没有归属"从而放行。
|
||||||
|
log.warn("[owner-fallback] 解析任务归属快照失败 msg={}", ex.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -46,9 +46,9 @@ public class InternalUserSecretUsageController {
|
|||||||
return ApiResponse.fail("上报参数不完整");
|
return ApiResponse.fail("上报参数不完整");
|
||||||
}
|
}
|
||||||
boolean accepted = userSecretUsageService.recordReported(
|
boolean accepted = userSecretUsageService.recordReported(
|
||||||
body.getUserId(), body.getModule(), body.getCount());
|
body.getUserId(), body.getModule(), body.getCount(), body.getSource());
|
||||||
log.info("[internal-usage] 计次上报 userId={} module={} count={} accepted={}",
|
log.info("[internal-usage] 计次上报 userId={} module={} count={} source={} accepted={}",
|
||||||
body.getUserId(), body.getModule(), body.getCount(), accepted);
|
body.getUserId(), body.getModule(), body.getCount(), body.getSource(), accepted);
|
||||||
if (!accepted) {
|
if (!accepted) {
|
||||||
return ApiResponse.fail("模块或参数非法,未记录");
|
return ApiResponse.fail("模块或参数非法,未记录");
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-5
@@ -13,27 +13,34 @@ import java.util.List;
|
|||||||
public interface UserSecretUsageMapper extends BaseMapper<UserSecretUsageEntity> {
|
public interface UserSecretUsageMapper extends BaseMapper<UserSecretUsageEntity> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按唯一键 uk_user_module_date 原子累加计次:命中则 call_count 自增,否则插入。
|
* 按唯一键 uk_user_module_date_source(V188:user_id+module_key+business_date+source)
|
||||||
* 并发下无需应用层加锁(引擎层唯一键冲突转更新)。
|
* 原子累加计次:命中则 call_count 自增,否则插入。并发下无需应用层加锁
|
||||||
|
* (引擎层唯一键冲突转更新)。source=上报方自报身份(client/brand16890/brand15126/
|
||||||
|
* pt_worker),Java 自产行=backend,缺省/非法=legacy——同一天多路各占一行,
|
||||||
|
* 读侧按模块聚合对多出的行透明。
|
||||||
*/
|
*/
|
||||||
int increment(@Param("userId") Long userId,
|
int increment(@Param("userId") Long userId,
|
||||||
@Param("moduleKey") String moduleKey,
|
@Param("moduleKey") String moduleKey,
|
||||||
@Param("businessDate") LocalDate businessDate,
|
@Param("businessDate") LocalDate businessDate,
|
||||||
@Param("count") int count);
|
@Param("count") int count,
|
||||||
|
@Param("source") String source);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按唯一键 uk_user_module_date 累加 token 读数。
|
* 按唯一键 uk_user_module_date_source 累加 token 读数。
|
||||||
*
|
*
|
||||||
* <p>刻意与 {@link #increment} 分成两条:计次发生在**发请求之前**(口径含重试,请求没回来也要算一次),
|
* <p>刻意与 {@link #increment} 分成两条:计次发生在**发请求之前**(口径含重试,请求没回来也要算一次),
|
||||||
* 而 token 只有响应回来才知道。合并成一条 upsert 就会把"已发出但超时"的那些请求从计次里漏掉。
|
* 而 token 只有响应回来才知道。合并成一条 upsert 就会把"已发出但超时"的那些请求从计次里漏掉。
|
||||||
* <p>这里是 UPDATE 而不是 upsert:行由前一条 increment 保证存在;真不存在就是 0 行受影响,
|
* <p>这里是 UPDATE 而不是 upsert:行由前一条 increment 保证存在;真不存在就是 0 行受影响,
|
||||||
* token 读数丢掉也不该反过来影响计次。
|
* token 读数丢掉也不该反过来影响计次。
|
||||||
|
* <p>WHERE 必须带 source(V188):唯一键扩成四元组后,同一 (user, module, date) 可能
|
||||||
|
* 有 legacy 与 backend 多行,不带 source 会把 token 记到历史行上造成双计。
|
||||||
*/
|
*/
|
||||||
int addTokens(@Param("userId") Long userId,
|
int addTokens(@Param("userId") Long userId,
|
||||||
@Param("moduleKey") String moduleKey,
|
@Param("moduleKey") String moduleKey,
|
||||||
@Param("businessDate") LocalDate businessDate,
|
@Param("businessDate") LocalDate businessDate,
|
||||||
@Param("promptTokens") long promptTokens,
|
@Param("promptTokens") long promptTokens,
|
||||||
@Param("completionTokens") long completionTokens);
|
@Param("completionTokens") long completionTokens,
|
||||||
|
@Param("source") String source);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当日用量按用户 × 模块聚合(损耗扫描每分钟读一次)。
|
* 当日用量按用户 × 模块聚合(损耗扫描每分钟读一次)。
|
||||||
|
|||||||
+4
@@ -16,4 +16,8 @@ public class UserSecretUsageReportRequest {
|
|||||||
|
|
||||||
@Schema(description = "本次新增调用次数(真实对外请求)", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(description = "本次新增调用次数(真实对外请求)", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
private Integer count;
|
private Integer count;
|
||||||
|
|
||||||
|
@Schema(description = "上报方来源(V188):client/brand16890/brand15126/pt_worker;"
|
||||||
|
+ "缺省或非法落 legacy 桶。旧上报方不带该字段,兼容。", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
|
||||||
|
private String source;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -9,7 +9,7 @@ import java.math.BigDecimal;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
/** 用户密钥调用计次(按天聚合,一行 = 用户 × 模块 × 日期)。 */
|
/** 用户密钥调用计次(按天聚合,一行 = 用户 × 模块 × 日期 × 来源(V188))。 */
|
||||||
@Data
|
@Data
|
||||||
@TableName("biz_user_secret_usage_daily")
|
@TableName("biz_user_secret_usage_daily")
|
||||||
public class UserSecretUsageEntity {
|
public class UserSecretUsageEntity {
|
||||||
@@ -18,6 +18,8 @@ public class UserSecretUsageEntity {
|
|||||||
private Long id;
|
private Long id;
|
||||||
private Long userId;
|
private Long userId;
|
||||||
private String moduleKey;
|
private String moduleKey;
|
||||||
|
/** 计次来源(V188):client/brand16890/brand15126/pt_worker/backend;存量行=legacy。 */
|
||||||
|
private String source;
|
||||||
private LocalDate businessDate;
|
private LocalDate businessDate;
|
||||||
private Integer callCount;
|
private Integer callCount;
|
||||||
/** 输入 token 累计(网关 usage.prompt_tokens)。0 = 该天没有 token 证据,不等于没消耗。 */
|
/** 输入 token 累计(网关 usage.prompt_tokens)。0 = 该天没有 token 证据,不等于没消耗。 */
|
||||||
|
|||||||
+79
-5
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.usersecret.service;
|
|||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.nanri.aiimage.common.exception.BusinessException;
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.module.TaskModuleRegistry;
|
||||||
import com.nanri.aiimage.common.text.SecretMasking;
|
import com.nanri.aiimage.common.text.SecretMasking;
|
||||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||||
@@ -302,8 +303,11 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
|||||||
* 比一句「没配密钥」的失败更难发现。
|
* 比一句「没配密钥」的失败更难发现。
|
||||||
*
|
*
|
||||||
* <p>调用方须先校验 userId(各模块自己的入口文案为准),这里不重复判。
|
* <p>调用方须先校验 userId(各模块自己的入口文案为准),这里不重复判。
|
||||||
|
*
|
||||||
|
* <p>包外不许直接调这一枚:模块→密钥的登记只认 {@link TaskModuleRegistry},
|
||||||
|
* 跨包的入口是下面的按 type 版本(B72-01)。
|
||||||
*/
|
*/
|
||||||
public void requireSubmitSecret(Long userId, UserSecretModule module, String callerSuppliedValue) {
|
void requireSubmitSecret(Long userId, UserSecretModule module, String callerSuppliedValue) {
|
||||||
if (hasText(callerSuppliedValue)) {
|
if (hasText(callerSuppliedValue)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -314,6 +318,24 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
|||||||
+ "缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。");
|
+ "缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建单前置(按 task type 问):这一类任务要拿用户的哪把密钥,唯一出处是
|
||||||
|
* {@link TaskModuleRegistry#submitSecretModuleOf(String)}——不是调用方各写一枚枚举,
|
||||||
|
* 更不是客户端猜({@code /newApi} 是整包转发的透传面,载荷里有什么凭据需求只有服务端按
|
||||||
|
* type 登记才说得清,B72-01)。
|
||||||
|
*
|
||||||
|
* <p>登记成「这一类建单不需要用户凭据」的类型调到这里<b>当场 IllegalStateException</b>,
|
||||||
|
* 不静默放行:空转的闸门比没有闸门更坏,它让下一个人以为这条链已经防住了。
|
||||||
|
* 要把某类任务纳入闸门,先在被判死的形状上有实证、再上册表,不要反过来。
|
||||||
|
*/
|
||||||
|
public void requireSubmitSecret(Long userId, String moduleType, String callerSuppliedValue) {
|
||||||
|
UserSecretModule module = TaskModuleRegistry.submitSecretModuleOf(moduleType)
|
||||||
|
.orElseThrow(() -> new IllegalStateException("模块「" + moduleType
|
||||||
|
+ "」在 TaskModuleRegistry 登记为「建单不需要用户凭据」,不该调这道闸门:"
|
||||||
|
+ "要么把这一类真要的那把密钥登记进表,要么把闸门从这条链上摘掉"));
|
||||||
|
requireSubmitSecret(userId, module, callerSuppliedValue);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 任务执行兜底读取「货源」:未配置返回空串(调用方按模块默认值处理)。
|
* 任务执行兜底读取「货源」:未配置返回空串(调用方按模块默认值处理)。
|
||||||
* 代理模块额外做链接域名识别,兜住老数据(只有链接、没有供应商列)的存量行。
|
* 代理模块额外做链接域名识别,兜住老数据(只有链接、没有供应商列)的存量行。
|
||||||
@@ -696,10 +718,12 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
String groupKey = inspectionGroupKey(row);
|
// 解密提到分组之前:分组键要看链接内容才能认出「这行和那行是同一个账号」
|
||||||
|
// (B73-03)。这是本机 AES,不走网络,代价与一次真实提取不可同日而语。
|
||||||
|
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
|
||||||
|
String groupKey = inspectionGroupKey(row, plainKey);
|
||||||
UserApiSecretCheckService.CheckOutcome outcome = outcomeBySecret.get(groupKey);
|
UserApiSecretCheckService.CheckOutcome outcome = outcomeBySecret.get(groupKey);
|
||||||
if (outcome == null) {
|
if (outcome == null) {
|
||||||
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
|
|
||||||
outcome = plainKey.isEmpty()
|
outcome = plainKey.isEmpty()
|
||||||
? new UserApiSecretCheckService.CheckOutcome(
|
? new UserApiSecretCheckService.CheckOutcome(
|
||||||
UserApiSecretCheckService.STATUS_FAILED,
|
UserApiSecretCheckService.STATUS_FAILED,
|
||||||
@@ -755,12 +779,62 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
|||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 巡检分组键:同模块 + 同密文视为同一把密钥。密文确定性加密,无需解密即可分组。 */
|
/**
|
||||||
private String inspectionGroupKey(UserApiSecretEntity row) {
|
* 巡检分组键。
|
||||||
|
*
|
||||||
|
* <p><b>代理类凭据按供应商账号分组</b>(B73-03):旧写法 {@code moduleKey|channel|密文}
|
||||||
|
* 把同一把青果 key 在多模块/多行配置时算成不同的组,每组都要真打一次提取;而青果整个账号
|
||||||
|
* 只有 1 条通道(2026-11-02 用户在控制台核实),第一枪还占着,后面每一枪必然
|
||||||
|
* {@code channel_busy} —— 巡检自己把用户的代理打成了「代理异常」。现在折成
|
||||||
|
* (供应商, 提取域, 归一化 query):参数顺序不同、多余参数不同都算同一把 key,同账号只出一枪。
|
||||||
|
*
|
||||||
|
* <p><b>非链接型凭据照旧</b> {@code moduleKey|channel|密文}:同一串 LLM 密钥在龙抬头与贞贞上
|
||||||
|
* 是两次独立探测,合并会拿 A 的结论冒充 B —— 那一侧不能跟着一起折。
|
||||||
|
*
|
||||||
|
* <p>分组键会进管理员告警的聚合面,所以账号身份只落摘要,链接里的账密明文绝不落进去。
|
||||||
|
*/
|
||||||
|
private String inspectionGroupKey(UserApiSecretEntity row, String plainValue) {
|
||||||
|
String accountIdentity = proxyAccountIdentity(plainValue);
|
||||||
|
if (accountIdentity != null) {
|
||||||
|
return "proxy-account|" + accountIdentity;
|
||||||
|
}
|
||||||
// 渠道参与分组:同一串密钥在龙抬头与贞贞上是两次独立探测,合并会拿 A 的结论冒充 B
|
// 渠道参与分组:同一串密钥在龙抬头与贞贞上是两次独立探测,合并会拿 A 的结论冒充 B
|
||||||
return row.getModuleKey() + '|' + (row.getChannel() == null ? "" : row.getChannel()) + '|' + row.getSecretValue();
|
return row.getModuleKey() + '|' + (row.getChannel() == null ? "" : row.getChannel()) + '|' + row.getSecretValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提取链接的账号身份=(供应商, 提取域, 排序后的 query) 的摘要;不是链接型凭据时返回 null。
|
||||||
|
*
|
||||||
|
* <p>返回 null 是让调用方退回逐行分组,而不是硬造一个组——把 LLM 密钥误当链接合并才是真事故。
|
||||||
|
*/
|
||||||
|
private String proxyAccountIdentity(String plainValue) {
|
||||||
|
if (plainValue == null || plainValue.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
URI uri;
|
||||||
|
try {
|
||||||
|
uri = new URI(plainValue.trim());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.warn("[user-secret] 巡检分组键解析不出链接,退回逐行分组 msg={}", ex.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (host == null || !host.contains(".")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
ProxyProvider provider = ProxyProvider.detectFromUrl(plainValue);
|
||||||
|
String query = uri.getQuery() == null ? "" : sortedQuery(uri.getQuery());
|
||||||
|
return sha256Hex((provider == null ? "unknown" : provider.name())
|
||||||
|
+ '|' + host.toLowerCase(java.util.Locale.ROOT) + '|' + query);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** query 参数按原文排序,好让「同一把 key 写成不同参数顺序」落到同一个组。 */
|
||||||
|
private static String sortedQuery(String rawQuery) {
|
||||||
|
String[] parts = rawQuery.split("&");
|
||||||
|
java.util.Arrays.sort(parts);
|
||||||
|
return String.join("&", parts);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 巡检告警判定:欠费(insufficient_balance)→ error 级 secret_balance;
|
* 巡检告警判定:欠费(insufficient_balance)→ error 级 secret_balance;
|
||||||
* 密钥无效/被拒(invalid_key/forbidden)→ warning 级 secret_invalid;
|
* 密钥无效/被拒(invalid_key/forbidden)→ warning 级 secret_invalid;
|
||||||
|
|||||||
+36
-7
@@ -49,6 +49,11 @@ public class UserSecretUsageService {
|
|||||||
public static final long PLATFORM_USER_ID = 0L;
|
public static final long PLATFORM_USER_ID = 0L;
|
||||||
static final String PLATFORM_USER_LABEL = "平台自费";
|
static final String PLATFORM_USER_LABEL = "平台自费";
|
||||||
|
|
||||||
|
/** 计次来源(V188):Java 自产行(LLM record/recordTokens)落 backend。 */
|
||||||
|
static final String SOURCE_BACKEND = "backend";
|
||||||
|
/** 存量行与缺省/非法报文的落桶:历史行无法追溯是哪一路报的,不猜测。 */
|
||||||
|
public static final String SOURCE_LEGACY = "legacy";
|
||||||
|
|
||||||
private final UserSecretUsageMapper usageMapper;
|
private final UserSecretUsageMapper usageMapper;
|
||||||
private final AdminUserMapper adminUserMapper;
|
private final AdminUserMapper adminUserMapper;
|
||||||
private final AdminAuthSupport adminAuthSupport;
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
@@ -68,11 +73,16 @@ public class UserSecretUsageService {
|
|||||||
log.warn("[user-secret-usage] 忽略未知模块计次 userId={} module={}", userId, moduleKey);
|
log.warn("[user-secret-usage] 忽略未知模块计次 userId={} module={}", userId, moduleKey);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
recordModule(userId, module, count, 0L, 0L);
|
recordModule(userId, module, count, 0L, 0L, SOURCE_BACKEND);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 内部通道上报入口:模块非法返回 false(供接口回执),写库失败只告警。 */
|
/** 内部通道上报入口(3 参旧形状):source 缺省落 legacy 桶。模块非法返回 false。 */
|
||||||
public boolean recordReported(Long userId, String moduleKey, int count) {
|
public boolean recordReported(Long userId, String moduleKey, int count) {
|
||||||
|
return recordReported(userId, moduleKey, count, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 内部通道上报入口(V188 带 source):模块非法返回 false,写库失败只告警。 */
|
||||||
|
public boolean recordReported(Long userId, String moduleKey, int count, String source) {
|
||||||
if (userId == null || userId < 0 || count <= 0) {
|
if (userId == null || userId < 0 || count <= 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -85,7 +95,8 @@ public class UserSecretUsageService {
|
|||||||
log.warn("[user-secret-usage] 平台自费桶只收 proxy 计次 userId=0 module={}", moduleKey);
|
log.warn("[user-secret-usage] 平台自费桶只收 proxy 计次 userId=0 module={}", moduleKey);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return recordModule(userId, module, Math.min(count, MAX_REPORT_COUNT), 0L, 0L);
|
return recordModule(userId, module, Math.min(count, MAX_REPORT_COUNT), 0L, 0L,
|
||||||
|
normalizeSource(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -106,18 +117,36 @@ public class UserSecretUsageService {
|
|||||||
if (module == null) {
|
if (module == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
recordModule(userId, module, 0, promptTokens, completionTokens);
|
recordModule(userId, module, 0, promptTokens, completionTokens, SOURCE_BACKEND);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* source 规整(V188):小写、^[a-z0-9][a-z0-9_-]{0,23}$ 以外的一律落 legacy——
|
||||||
|
* 上报方是可信内部调用方,但字符串仍可能写错;落 legacy 而不是拒收,
|
||||||
|
* 计次比归因更贵(宁可归因模糊也不丢账)。
|
||||||
|
*/
|
||||||
|
static String normalizeSource(String raw) {
|
||||||
|
if (raw == null) {
|
||||||
|
return SOURCE_LEGACY;
|
||||||
|
}
|
||||||
|
String trimmed = raw.trim().toLowerCase();
|
||||||
|
if (trimmed.isEmpty() || trimmed.length() > 24
|
||||||
|
|| !trimmed.matches("[a-z0-9][a-z0-9_-]*")) {
|
||||||
|
return SOURCE_LEGACY;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean recordModule(Long userId, UserSecretModule module, int count,
|
private boolean recordModule(Long userId, UserSecretModule module, int count,
|
||||||
long promptTokens, long completionTokens) {
|
long promptTokens, long completionTokens, String source) {
|
||||||
LocalDate today = LocalDate.now();
|
LocalDate today = LocalDate.now();
|
||||||
try {
|
try {
|
||||||
if (count > 0) {
|
if (count > 0) {
|
||||||
usageMapper.increment(userId, module.key(), today, count);
|
usageMapper.increment(userId, module.key(), today, count, source);
|
||||||
}
|
}
|
||||||
if (promptTokens > 0 || completionTokens > 0) {
|
if (promptTokens > 0 || completionTokens > 0) {
|
||||||
usageMapper.addTokens(userId, module.key(), today, promptTokens, completionTokens);
|
usageMapper.addTokens(userId, module.key(), today, promptTokens, completionTokens,
|
||||||
|
source);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
-- V186: 任务失败分类列(B51-R1,Expand-and-Contract 的 Expand 半边)
|
||||||
|
--
|
||||||
|
-- 背景(蓝图 docs/REFACTOR_PLAN.md §3.1,立项自 docs/audit/SLIMMING_REPORT.md 的 B51):
|
||||||
|
-- 重试/重开/判死全部读 `biz_file_task.error_message` 里的**中文子串**决定
|
||||||
|
-- (TaskRetryEligibility 六组 markers、TaskResultFileJobWorker 的孤儿判死、
|
||||||
|
-- SimilarAsinStaleReopenSupport 的重开白名单)。后果是"改一句用户看得见的文案"=
|
||||||
|
-- 静默改一次整单生死,而且改的人不会知道——文案是给看的,判定是拿它当枚举用的。
|
||||||
|
--
|
||||||
|
-- 设计口径:
|
||||||
|
-- * 可空:NULL=「这一行没登记分类」。存量行一律不回填(历史行的文案还在,读侧照旧能判),
|
||||||
|
-- 实体式写入面(若干 `task.setErrorMessage(...)`)本轮尚未接 ledger,落库时列为空——
|
||||||
|
-- 这两种 NULL 都是**有意的**,读侧按「文案判得出按文案、判不出按列」双读(列与文案背离时
|
||||||
|
-- 列是陈旧的,按文案才等于加列之前的行为),不许把空列读成「无类别」;
|
||||||
|
-- * 不自造第二套词汇表:值域就是 `TaskRetryEligibility.Category.name()`
|
||||||
|
-- (BALANCE/SERVICE_DOWN/CREDENTIAL/DELIVERY/STOPPED),判定逻辑仍只有那一处;
|
||||||
|
-- * VARCHAR(16) 与 V183 的 `collect_channel` 同档:五个枚举名最长 12(SERVICE_DOWN),
|
||||||
|
-- 留余量给后续分类名,不用 ENUM(ENUM 改值域要再发一次迁移,且 MyBatis 侧映射成字符串更直白);
|
||||||
|
-- * 不加索引:这一列现在只被"读某一行的分类"用到(按主键),没有按分类筛整表的查询;
|
||||||
|
-- 真要按类别统计再说,别让一条推测性索引进基线。
|
||||||
|
--
|
||||||
|
-- Contract 阶段(本轮**不做**,读侧全切之后才许动):
|
||||||
|
-- 把 `contains("<中文>")` 那批判定收掉,并让 `TaskFailureCategoryGuardrailTest`
|
||||||
|
-- 的"文案写点必须同笔写列"绊线继续守着新增点。
|
||||||
|
--
|
||||||
|
-- 回滚(手工):
|
||||||
|
-- ALTER TABLE `biz_file_task` DROP COLUMN `failure_category`;
|
||||||
|
|
||||||
|
ALTER TABLE `biz_file_task`
|
||||||
|
ADD COLUMN `failure_category` VARCHAR(16) NULL
|
||||||
|
COMMENT '失败分类(TaskRetryEligibility.Category 值域):空=未登记,读侧回落到 error_message 文案判定' AFTER `error_message`;
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
-- V187: 自动续跑反查「是否已有重试子任务」的缺失索引(Phase 5 / 审计 P1-B5)
|
||||||
|
--
|
||||||
|
-- 病灶:TaskResumeService 每天真在跑的两条谓词,一条都没有索引可用——
|
||||||
|
-- 1) `WHERE resume_of_task_id = ?`(hasRetryChild,原判「这单已经重试过了」)
|
||||||
|
-- V129 只加了 resume_of_task_id / resume_attempt 两列(:26、:38),**一支索引都没配**,
|
||||||
|
-- 于是巡检每轮对每个候选单各做一次全表扫;500 个候选=500 次全表扫,
|
||||||
|
-- 而这张表是 biz_file_task(现网十万级行)。
|
||||||
|
-- 2) `WHERE resume_of_task_id IS NOT NULL AND status IN (活态)`(stopDuplicateChildren 幂等清账)
|
||||||
|
-- 同一列的另一条谓词,同样裸扫。
|
||||||
|
-- 两条共用一条 `(resume_of_task_id)` 即可:InnoDB 的二级索引带主键尾巴,IS NOT NULL 那支
|
||||||
|
-- 也能走索引范围扫(不是全表)。
|
||||||
|
--
|
||||||
|
-- 有意**不加**的另一支(审计建议的 `(status, module_type, resume_attempt, updated_at)`):
|
||||||
|
-- 候选集那条查询的等值前缀 (status, module_type) 已由 V184 的
|
||||||
|
-- idx_biz_file_task_status_module_created 覆盖;`resume_attempt IS NULL OR resume_attempt < n`
|
||||||
|
-- 是 OR/IS-NULL 残差谓词(不吃索引,只能当过滤条件),`COALESCE(finished_at, updated_at) >= ?`
|
||||||
|
-- 是表达式谓词(同样不吃索引,见 V184 头注释对 collect_channel 的同一口径)。
|
||||||
|
-- 再建一条同前缀索引=只写不读、白白摊在每次 INSERT/UPDATE 上——与 V186「别让一条推测性
|
||||||
|
-- 索引进基线」同判。真库 EXPLAIN 若显示候选集这一支仍需回表扫太多行,抬时间列入索引
|
||||||
|
-- 留到现网复量之后单独立项(本机无 MySQL,未跑过 EXPLAIN,见蓝图 Phase 5 实录)。
|
||||||
|
--
|
||||||
|
-- 风险:ALTER TABLE ADD INDEX 需申请元数据锁(MySQL 8 在线 DDL,INPLACE),建议低峰执行;
|
||||||
|
-- 本迁移按 information_schema 判存,重跑不会因索引已存在而失败。
|
||||||
|
-- 回滚(手工):
|
||||||
|
-- ALTER TABLE biz_file_task DROP INDEX idx_biz_file_task_resume_of;
|
||||||
|
|
||||||
|
SET @db_name = DATABASE();
|
||||||
|
|
||||||
|
-- biz_file_task(resume_of_task_id)
|
||||||
|
SET @idx_exists := (
|
||||||
|
SELECT COUNT(*) FROM information_schema.STATISTICS
|
||||||
|
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_file_task'
|
||||||
|
AND INDEX_NAME = 'idx_biz_file_task_resume_of'
|
||||||
|
);
|
||||||
|
SET @sql := IF(@idx_exists = 0,
|
||||||
|
'ALTER TABLE biz_file_task ADD INDEX idx_biz_file_task_resume_of (resume_of_task_id)',
|
||||||
|
'SELECT 1'
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
-- V188: 给 `biz_user_secret_usage_daily` 加 `source` 列,并把唯一键扩到四元组
|
||||||
|
-- =============================================================
|
||||||
|
-- 1. 变更目的:把「谁在烧」从猜测变成一列读数。四路上报方(客户端 90s flush/16890
|
||||||
|
-- 30s 批量/15126 60s 周期/pt_worker 逐次)此前都只报 {userId, module, count},
|
||||||
|
-- 同一用户同一天被多个面消费时在表里揉成一行,归因只能去扫 MinIO 设备日志与两台
|
||||||
|
-- 机器(2026-11-04 客户反馈「代理IP用的很猛」的归因实测就是这么做的)。加 source
|
||||||
|
-- 后一条 `GROUP BY source` 直接出账。
|
||||||
|
--
|
||||||
|
-- 2. 前提取证(2026-11-04 只读探针):该表 7 天 proxy 19,040 次/95 用户,行数
|
||||||
|
-- =用户×模块×天 量级,加列存储代价可忽略;现键 `uk_user_module_date(user_id,
|
||||||
|
-- module_key, business_date)`(V117)是 increment 的 ON DUPLICATE KEY 幂等键。
|
||||||
|
--
|
||||||
|
-- 3. 形状与数据:`source varchar(24) NOT NULL DEFAULT 'legacy'`——存量行统一落
|
||||||
|
-- 'legacy'(历史行无法追溯是哪一路报的,不猜测);新行由四路上报方自报
|
||||||
|
-- (client/brand16890/brand15126/pt_worker),Java 自产 LLM 行=backend,缺省/非法
|
||||||
|
-- 报文=legacy。唯一键扩成 `(user_id, module_key, business_date, source)`:
|
||||||
|
-- 同一天多路各占一行,读侧 adminPage/SUM 按模块聚合,对多出的行天然透明。
|
||||||
|
--
|
||||||
|
-- 4. 锁表风险:极低。日聚合表、万行量级,MySQL 8 ADD COLUMN NOT NULL DEFAULT
|
||||||
|
-- 走 INSTANT;索引重建在当前行数下毫秒级。
|
||||||
|
--
|
||||||
|
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||||
|
-- SHOW COLUMNS FROM `biz_user_secret_usage_daily` LIKE 'source';
|
||||||
|
-- -> 期望 1 行:source,Type=varchar(24),Null=NO,Default=legacy
|
||||||
|
-- SHOW INDEX FROM `biz_user_secret_usage_daily` WHERE Key_name='uk_user_module_date_source';
|
||||||
|
-- -> 期望 4 行(user_id/module_key/business_date/source),Non_unique=0
|
||||||
|
-- 应用侧:UserSecretUsageServiceTest 全绿(increment/addTokens 带来源、
|
||||||
|
-- 缺省/非法报文落 legacy、Java 自产 LLM 行=backend)。
|
||||||
|
--
|
||||||
|
-- 6. 上线窗口:必须与读写的 jar 同版同窗——旧 jar 的 increment 不带 source,
|
||||||
|
-- INSERT 会落进 DEFAULT 'legacy'(幂等键还是旧三元组形状时列不参与键,行为不变);
|
||||||
|
-- 新 jar 写四元组前 Flyway 已保证新键存在。只发 jar 不发迁移会在第一次 upsert
|
||||||
|
-- 时撞 1054 Unknown column,只发迁移不发 jar 则所有行落 legacy(无损失但无归因)。
|
||||||
|
--
|
||||||
|
-- 7. 可重跑性:加列与建索引都先查 information_schema(列按 V157 款,索引按 V184 款)——
|
||||||
|
-- 迁移中途失败时 flyway repair + 重启会从第一条语句重跑整个文件,裸 ALTER 会撞
|
||||||
|
-- 1060/1061。
|
||||||
|
--
|
||||||
|
-- 8. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||||
|
-- 触发场景是"这列不该加"。顺序:停两台应用 → 跑下面三条 →
|
||||||
|
-- 删 flyway_schema_history 的 version='188' 行 → 回滚 jar → 起应用。
|
||||||
|
-- ALTER TABLE `biz_user_secret_usage_daily` DROP INDEX `uk_user_module_date_source`;
|
||||||
|
-- ALTER TABLE `biz_user_secret_usage_daily` ADD UNIQUE KEY `uk_user_module_date`
|
||||||
|
-- (`user_id`, `module_key`, `business_date`);
|
||||||
|
-- ALTER TABLE `biz_user_secret_usage_daily` DROP COLUMN `source`;
|
||||||
|
-- 注意回滚前须先把四元组里的重行并回(同键多行会让 ADD UNIQUE 失败):
|
||||||
|
-- (按 user_id+module_key+business_date 求 SUM 后重插——正常不会发生,
|
||||||
|
-- 除非回滚前已有多来源同行;真发生时按该日逐行手工核对再并。)
|
||||||
|
-- 仅回滚 jar(代码问题、与列无关)不需要 DROP:旧 jar 不写 source,行形状保持
|
||||||
|
-- DEFAULT 'legacy',读侧聚合不变。
|
||||||
|
-- =============================================================
|
||||||
|
|
||||||
|
SET @col := (
|
||||||
|
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = 'biz_user_secret_usage_daily'
|
||||||
|
AND COLUMN_NAME = 'source'
|
||||||
|
);
|
||||||
|
SET @ddl := IF(@col = 0,
|
||||||
|
'ALTER TABLE `biz_user_secret_usage_daily` ADD COLUMN `source` varchar(24) NOT NULL DEFAULT ''legacy'' COMMENT ''计次来源(client/brand16890/brand15126/pt_worker/backend;存量行=legacy)'' AFTER `module_key`',
|
||||||
|
'SELECT ''biz_user_secret_usage_daily.source already exists, skipped'' AS note');
|
||||||
|
PREPARE stmt FROM @ddl;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @old_key := (
|
||||||
|
SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = 'biz_user_secret_usage_daily'
|
||||||
|
AND INDEX_NAME = 'uk_user_module_date'
|
||||||
|
);
|
||||||
|
SET @new_key := (
|
||||||
|
SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = 'biz_user_secret_usage_daily'
|
||||||
|
AND INDEX_NAME = 'uk_user_module_date_source'
|
||||||
|
);
|
||||||
|
SET @ddl2 := IF(@new_key = 0 AND @old_key > 0,
|
||||||
|
'ALTER TABLE `biz_user_secret_usage_daily` DROP INDEX `uk_user_module_date`, ADD UNIQUE KEY `uk_user_module_date_source` (`user_id`, `module_key`, `business_date`, `source`)',
|
||||||
|
'SELECT ''uk_user_module_date_source already exists (or old key missing), skipped'' AS note');
|
||||||
|
PREPARE stmt2 FROM @ddl2;
|
||||||
|
EXECUTE stmt2;
|
||||||
|
DEALLOCATE PREPARE stmt2;
|
||||||
@@ -7,4 +7,14 @@
|
|||||||
SELECT status FROM biz_file_task WHERE id = #{taskId}
|
SELECT status FROM biz_file_task WHERE id = #{taskId}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<!-- P1-B6:claim 循环的批量档。终态值域由调用方传入(正本=TaskStatuses.FileTask.TERMINAL),
|
||||||
|
这里不写死状态字符串;两个 IN 集合都由服务层保证非空。 -->
|
||||||
|
<select id="selectTerminalFileTaskIds" resultType="java.lang.Long">
|
||||||
|
SELECT id FROM biz_file_task
|
||||||
|
WHERE id IN
|
||||||
|
<foreach collection="taskIds" item="taskId" open="(" separator="," close=")">#{taskId}</foreach>
|
||||||
|
AND status IN
|
||||||
|
<foreach collection="terminalStatuses" item="st" open="(" separator="," close=")">#{st}</foreach>
|
||||||
|
</select>
|
||||||
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
@@ -9,18 +9,21 @@
|
|||||||
LIMIT #{batchSize}
|
LIMIT #{batchSize}
|
||||||
</delete>
|
</delete>
|
||||||
<insert id="increment">
|
<insert id="increment">
|
||||||
INSERT INTO biz_user_secret_usage_daily (user_id, module_key, business_date, call_count, created_at, updated_at)
|
INSERT INTO biz_user_secret_usage_daily (user_id, module_key, business_date, source, call_count, created_at, updated_at)
|
||||||
VALUES (#{userId}, #{moduleKey}, #{businessDate}, #{count}, NOW(), NOW())
|
VALUES (#{userId}, #{moduleKey}, #{businessDate}, #{source}, #{count}, NOW(), NOW())
|
||||||
ON DUPLICATE KEY UPDATE call_count = call_count + #{count}, updated_at = NOW()
|
ON DUPLICATE KEY UPDATE call_count = call_count + #{count}, updated_at = NOW()
|
||||||
</insert>
|
</insert>
|
||||||
<!-- 不是「从注解搬过来」的语句:V157 加 token 两列时新写的,登记在 MigratedSqlEquivalenceTest.NOT_MIGRATED。
|
<!-- 不是「从注解搬过来」的语句:V157 加 token 两列时新写的,登记在 MigratedSqlEquivalenceTest.NOT_MIGRATED。
|
||||||
与上面的 increment 分两条是口径要求:计次先于响应,token 只在响应回来后有读数。 -->
|
与上面的 increment 分两条是口径要求:计次先于响应,token 只在响应回来后有读数。
|
||||||
|
WHERE 带 source(V188):唯一键四元组后同一 (user,module,date) 可能有多行,
|
||||||
|
不钉 source 会把 token 记到 legacy 历史行上造成双计。 -->
|
||||||
<update id="addTokens">
|
<update id="addTokens">
|
||||||
UPDATE biz_user_secret_usage_daily
|
UPDATE biz_user_secret_usage_daily
|
||||||
SET prompt_tokens = prompt_tokens + #{promptTokens},
|
SET prompt_tokens = prompt_tokens + #{promptTokens},
|
||||||
completion_tokens = completion_tokens + #{completionTokens},
|
completion_tokens = completion_tokens + #{completionTokens},
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE user_id = #{userId} AND module_key = #{moduleKey} AND business_date = #{businessDate}
|
WHERE user_id = #{userId} AND module_key = #{moduleKey} AND business_date = #{businessDate}
|
||||||
|
AND source = #{source}
|
||||||
</update>
|
</update>
|
||||||
<select id="sumByUserAndModule" resultType="com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate">
|
<select id="sumByUserAndModule" resultType="com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate">
|
||||||
SELECT user_id AS userId,
|
SELECT user_id AS userId,
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ class MigratedSqlEquivalenceTest {
|
|||||||
// 85 → 84:Phase 5(AC-19/P1-B1)有意把 {@code TaskCenterQueryMapper#selectTaskPage} 从
|
// 85 → 84:Phase 5(AC-19/P1-B1)有意把 {@code TaskCenterQueryMapper#selectTaskPage} 从
|
||||||
// OFFSET 改成 keyset 游标。账本记的是「注解时代原文」,改一行基准就等于让等价性测试照着
|
// OFFSET 改成 keyset 游标。账本记的是「注解时代原文」,改一行基准就等于让等价性测试照着
|
||||||
// 新 SQL 自证 ⇒ 把该行整条摘出账本、点名进下方 NOT_MIGRATED,让基准继续只描述真正未改动的迁移件。
|
// 新 SQL 自证 ⇒ 把该行整条摘出账本、点名进下方 NOT_MIGRATED,让基准继续只描述真正未改动的迁移件。
|
||||||
private static final int LEDGER_ROWS = 84;
|
private static final int LEDGER_ROWS = 83;
|
||||||
// 60 → 59:摘出去那行是一条 select。
|
// 60 → 59:摘出去那行是一条 select。
|
||||||
private static final int LEDGER_SELECTS = 59;
|
private static final int LEDGER_SELECTS = 59;
|
||||||
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
|
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
|
||||||
@@ -76,7 +76,10 @@ class MigratedSqlEquivalenceTest {
|
|||||||
// NOT_MIGRATED(select 总数不变,只是记账位置换了)。
|
// NOT_MIGRATED(select 总数不变,只是记账位置换了)。
|
||||||
// 100 → 102:P1-1 把两条认领查询的通道谓词下推进 SQL,FileTaskMapper 新写 2 条 select,
|
// 100 → 102:P1-1 把两条认领查询的通道谓词下推进 SQL,FileTaskMapper 新写 2 条 select,
|
||||||
// 逐条点名进 NOT_MIGRATED(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 144 → 146)。
|
// 逐条点名进 NOT_MIGRATED(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 144 → 146)。
|
||||||
private static final int XML_SELECT_TOTAL = 102;
|
// 102 → 103:P1-B6 把 claim 循环的「父任务是否终态」折成批量档
|
||||||
|
// TaskFileJobMapper#selectTerminalFileTaskIds,点名进下方 NOT_MIGRATED
|
||||||
|
// (SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 146 → 147)。
|
||||||
|
private static final int XML_SELECT_TOTAL = 103;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||||
@@ -84,6 +87,11 @@ class MigratedSqlEquivalenceTest {
|
|||||||
*/
|
*/
|
||||||
private static final java.util.Set<String> NOT_MIGRATED =
|
private static final java.util.Set<String> NOT_MIGRATED =
|
||||||
java.util.Set.of("AdminUserMapper#countLiveWorkFor",
|
java.util.Set.of("AdminUserMapper#countLiveWorkFor",
|
||||||
|
// V188(2026-11-04)给计次 upsert 加 source 列(唯一键四元组),SQL 文本
|
||||||
|
// 不再是注解时代的逐字原文:整行从 migrated-statements.tsv 摘掉、点名到
|
||||||
|
// 这里(与 selectTaskPage 改写时同款处理,LEDGER_ROWS 84→83);新形状
|
||||||
|
// 由 V188 迁移测试与 UserSecretUsageServiceTest 钉。
|
||||||
|
"UserSecretUsageMapper#increment",
|
||||||
// V157 加 token 两列时新写的累加语句;注解时代没有原文可对撞,等价性这支只能跳过它。
|
// V157 加 token 两列时新写的累加语句;注解时代没有原文可对撞,等价性这支只能跳过它。
|
||||||
// 与 increment 分两条是口径要求(计次先于响应、token 只在响应后有读数),不是随手加的第二条 SQL。
|
// 与 increment 分两条是口径要求(计次先于响应、token 只在响应后有读数),不是随手加的第二条 SQL。
|
||||||
"UserSecretUsageMapper#addTokens",
|
"UserSecretUsageMapper#addTokens",
|
||||||
@@ -118,6 +126,9 @@ class MigratedSqlEquivalenceTest {
|
|||||||
"UserSecretUsageMapper#sumForUser",
|
"UserSecretUsageMapper#sumForUser",
|
||||||
// B28(2026-10-25)新写的 1 条主键点查:父任务是否已终态。
|
// B28(2026-10-25)新写的 1 条主键点查:父任务是否已终态。
|
||||||
"TaskFileJobMapper#selectFileTaskStatus",
|
"TaskFileJobMapper#selectFileTaskStatus",
|
||||||
|
// P1-B6(2026-11-03)新写的 1 条批量档:一次问回这批父任务里已终态的 id
|
||||||
|
// (终态值域由调用方传入,XML 里没有第二份字符串)。
|
||||||
|
"TaskFileJobMapper#selectTerminalFileTaskIds",
|
||||||
// CR-01(2026-10-25)新写的 1 条写侧语句:会话世代原子自增。
|
// CR-01(2026-10-25)新写的 1 条写侧语句:会话世代原子自增。
|
||||||
"LoginUserMapper#incrementSessionEpoch",
|
"LoginUserMapper#incrementSessionEpoch",
|
||||||
// 关键词使用记录管理端(2026-10-25)新写的 10 条只读 select。
|
// 关键词使用记录管理端(2026-10-25)新写的 10 条只读 select。
|
||||||
@@ -167,7 +178,7 @@ class MigratedSqlEquivalenceTest {
|
|||||||
"fixture 里的 Select 条数与基线不符(读侧账本 = 59)");
|
"fixture 里的 Select 条数与基线不符(读侧账本 = 59)");
|
||||||
assertEquals(LEDGER_ROWS - LEDGER_SELECTS,
|
assertEquals(LEDGER_ROWS - LEDGER_SELECTS,
|
||||||
rows.stream().filter(r -> !"Select".equals(r[2])).count(),
|
rows.stream().filter(r -> !"Select".equals(r[2])).count(),
|
||||||
"写侧条数对不上(25 = Insert+Update+Delete)");
|
"写侧条数对不上(24 = Insert+Update+Delete)");
|
||||||
assertTrue(rows.stream().allMatch(r -> !r[1].isEmpty() && !r[BASELINE_COL].isEmpty()),
|
assertTrue(rows.stream().allMatch(r -> !r[1].isEmpty() && !r[BASELINE_COL].isEmpty()),
|
||||||
"fixture 有空方法名或空 SQL,说明抽取器漏了形状");
|
"fixture 有空方法名或空 SQL,说明抽取器漏了形状");
|
||||||
// 基准得是「整条注解串」:半截 <script> 外壳说明抽取被截断(上一轮就是把常量与标签吃了)
|
// 基准得是「整条注解串」:半截 <script> 外壳说明抽取被截断(上一轮就是把常量与标签吃了)
|
||||||
|
|||||||
@@ -95,7 +95,10 @@ class SqlLayeringConventionTest {
|
|||||||
// 原形状是先 limit 取页再 filter(isLocal()),混通道时较老的 N 条是 ONLINE 就把本机单永久饿死。
|
// 原形状是先 limit 取页再 filter(isLocal()),混通道时较老的 N 条是 ONLINE 就把本机单永久饿死。
|
||||||
// FileTaskMapper 新写 2 条 select(客户端兜底拉取 / 服务端内部认领),同轮登记进
|
// FileTaskMapper 新写 2 条 select(客户端兜底拉取 / 服务端内部认领),同轮登记进
|
||||||
// MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 同轮 100 → 102)。
|
// MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 同轮 100 → 102)。
|
||||||
private static final int XML_STATEMENT_TOTAL = 146;
|
// 146 → 147:P1-B6 把 claim 循环里「父任务是否终态」的逐条点查折成批量档
|
||||||
|
// {@code TaskFileJobMapper#selectTerminalFileTaskIds}(终态值域由调用方传入,XML 不抄字符串),
|
||||||
|
// 同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 同轮 102 → 103)。
|
||||||
|
private static final int XML_STATEMENT_TOTAL = 147;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||||
|
|||||||
+3
-1
@@ -95,7 +95,9 @@ class RequestSuppliedIdentityOutletTest {
|
|||||||
// 128 而不是 126:2026-11-01「失败任务在原任务上重试」新增两支写类端点(TaskRetryController
|
// 128 而不是 126:2026-11-01「失败任务在原任务上重试」新增两支写类端点(TaskRetryController
|
||||||
// POST /api/tasks/{taskId}/retry + AppearancePatentController POST /tasks/{taskId}/retry),
|
// POST /api/tasks/{taskId}/retry + AppearancePatentController POST /tasks/{taskId}/retry),
|
||||||
// 两边都是 @RequestParam("user_id") 先过 resolveOwnershipUserId——记账变大是覆盖面变大,不是放宽分母。
|
// 两边都是 @RequestParam("user_id") 先过 resolveOwnershipUserId——记账变大是覆盖面变大,不是放宽分母。
|
||||||
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(128);
|
// 129 而不是 128:2026-11-03 f43ed6f1「任务中断+继续」新增 TaskHeartbeatController
|
||||||
|
// POST /api/tasks/{taskId}/interrupt,鉴权镜像 retry(先过 resolveOwnershipUserId 再比归属)。
|
||||||
|
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(129);
|
||||||
// 64 而不是 63:2026-10-29 随本地采集开关恢复 GET /tasks/{taskId}/queue-payload,
|
// 64 而不是 63:2026-10-29 随本地采集开关恢复 GET /tasks/{taskId}/queue-payload,
|
||||||
// 该 handler 同时接上 resolveOwnershipUserId(不是放宽分母)。
|
// 该 handler 同时接上 resolveOwnershipUserId(不是放宽分母)。
|
||||||
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(64);
|
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(64);
|
||||||
|
|||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
package com.nanri.aiimage.config;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldStrategy;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V186 给 {@code biz_file_task} 补 {@code failure_category} 列,本类钉它的形状(B51-R1 Expand 半边)。
|
||||||
|
*
|
||||||
|
* <p>立账出处是蓝图 {@code docs/REFACTOR_PLAN.md} §3.1 与 SLIMMING 报告的 B51:重试/重开/判死
|
||||||
|
* 原先全靠读 {@code error_message} 的中文子串决定,改一句用户看得见的文案就静默改一次整单生死。
|
||||||
|
* 这一列把「那次判断的结果」记下来,读侧从此有列读列。
|
||||||
|
*
|
||||||
|
* <p>三件事各守一个炸法:
|
||||||
|
* <ol>
|
||||||
|
* <li><b>必须可空且不回填</b>:存量行与尚未接 {@code TaskFailureLedger} 的实体式写入面都是 NULL,
|
||||||
|
* 读侧按「无列则回落文案」处理。加 {@code NOT NULL} 或 {@code DEFAULT ''} 会让存量行在
|
||||||
|
* 迁移那一刻集体变成一种新状态;写一条 {@code UPDATE} 回填更是把「分类」变成
|
||||||
|
* 「按今天的文案重判一遍历史」——历史行的判定不该被后来的词汇表改动。</li>
|
||||||
|
* <li><b>值域不另起炉灶</b>:列宽必须容得下 {@code TaskRetryEligibility.Category} 的全部枚举名,
|
||||||
|
* 且 SQL 里点名的出处就是那一处(否则 B52 那族「词汇表多正本」在这里重生)。</li>
|
||||||
|
* <li><b>列名与实体字段对齐</b>:MyBatis-Plus 靠驼峰↔下划线映射,列名与字段名对不上时
|
||||||
|
* 写入会静默不落库(列存在但恒为 NULL,读侧永远回落,等于白加)。</li>
|
||||||
|
* </ol>
|
||||||
|
*/
|
||||||
|
class TaskFailureCategoryMigrationV186Test {
|
||||||
|
|
||||||
|
private static final Path SQL = Path.of(System.getProperty("user.dir"),
|
||||||
|
"src/main/resources/db/V186__task_failure_category.sql");
|
||||||
|
|
||||||
|
private static String sql() throws IOException {
|
||||||
|
assertTrue(Files.exists(SQL), "V186 迁移脚本不在:" + SQL);
|
||||||
|
return Files.readString(SQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 列是biz_file_task上的可空窄列且紧跟error_message() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
|
||||||
|
assertTrue(text.contains("ALTER TABLE `biz_file_task`"), "迁移对象必须是 biz_file_task");
|
||||||
|
assertTrue(text.contains("ADD COLUMN `failure_category` VARCHAR(16) NULL"),
|
||||||
|
"必须是可空窄列:NOT NULL/DEFAULT 都会让存量行集体变成一种新状态");
|
||||||
|
assertTrue(text.contains("AFTER `error_message`"),
|
||||||
|
"紧跟 error_message:这两列是一件事的记账与文案,读的人要能一眼成对");
|
||||||
|
assertFalse(text.toUpperCase().contains("UPDATE `BIZ_FILE_TASK`"),
|
||||||
|
"Expand 阶段不回填:历史行的判定不能按今天的词汇表重判一遍");
|
||||||
|
assertTrue(text.contains("DROP COLUMN `failure_category`"),
|
||||||
|
"回滚语句必须写在脚本注释里(与 V183 同一口径)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 头注释版本号与文件名一致() throws IOException {
|
||||||
|
String first = sql().lines().findFirst().orElse("");
|
||||||
|
assertTrue(first.startsWith("-- V186:"), "头注释必须写 V186,实际是:" + first);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 列宽容得下词汇表的每一个枚举名() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
int width = Integer.parseInt(text.replaceAll("(?s).*`failure_category` VARCHAR\\((\\d+)\\).*", "$1"));
|
||||||
|
int longest = 0;
|
||||||
|
for (TaskRetryEligibility.Category category : TaskRetryEligibility.Category.values()) {
|
||||||
|
longest = Math.max(longest, category.name().length());
|
||||||
|
}
|
||||||
|
assertTrue(width >= longest,
|
||||||
|
"列宽 " + width + " 装不下最长的枚举名(" + longest + " 字符)⇒ 写入会被截断或报错");
|
||||||
|
assertTrue(text.contains("TaskRetryEligibility.Category"),
|
||||||
|
"SQL 注释必须点明值域出处就是那一处词汇表,不许另造一套");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列名与实体字段对不上时 MyBatis-Plus 会静默不落库:这一格把两者绑死。 */
|
||||||
|
@Test
|
||||||
|
void 实体字段与列名按驼峰下划线一一对应() throws Exception {
|
||||||
|
assertNotNull(FileTaskEntity.class.getDeclaredField("failureCategory"),
|
||||||
|
"实体缺 failureCategory 字段 ⇒ 列永远不会被写");
|
||||||
|
assertEquals("failure_category", camelToSnake("failureCategory"));
|
||||||
|
assertTrue(sql().contains("`failure_category`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code updateStrategy=ALWAYS} 是名单外实体式写面的兜底:默认策略跳过 null 字段,
|
||||||
|
* 于是「partial entity 更新」会把这一列留在旧值上——陈旧的一列比没有列更危险(它会让一单
|
||||||
|
* 被上一次失败的原因判死)。让 null 真的落库,最坏只是退回文案判定,逐字等于加列之前的今天。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void 实体字段必须让_null_真的落库() throws Exception {
|
||||||
|
TableField field = FileTaskEntity.class.getDeclaredField("failureCategory")
|
||||||
|
.getAnnotation(TableField.class);
|
||||||
|
assertNotNull(field, "failureCategory 没标 @TableField ⇒ updateById 会跳过 null,清错误的分支带不动列");
|
||||||
|
assertEquals(FieldStrategy.ALWAYS, field.updateStrategy(),
|
||||||
|
"updateStrategy 不是 ALWAYS ⇒ 实体式更新留下陈旧分类");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String camelToSnake(String name) {
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
for (char c : name.toCharArray()) {
|
||||||
|
if (Character.isUpperCase(c)) {
|
||||||
|
out.append('_').append(Character.toLowerCase(c));
|
||||||
|
} else {
|
||||||
|
out.append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
package com.nanri.aiimage.config;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V187 给 {@code biz_file_task} 补 {@code resume_of_task_id} 索引,本类钉它的形状(Phase 5/审计 P1-B5)。
|
||||||
|
*
|
||||||
|
* <p>来历:自动续跑巡检每轮对每个候选单各做一次「这单是否已有重试子任务」的反查,而那列在
|
||||||
|
* V129 只加了列、一支索引都没配 ⇒ 500 个候选=500 场全表扫。同族的「幂等清账」用的是同一列。
|
||||||
|
*
|
||||||
|
* <p>本类同时钉住**不建**的那一支:审计原文建议 {@code (status, module_type, resume_attempt, updated_at)},
|
||||||
|
* 但候选集查询的等值前缀已由 V184 覆盖,而 {@code resume_attempt} 是 OR/IS-NULL 残差谓词、
|
||||||
|
* {@code COALESCE(finished_at, updated_at)} 是表达式谓词——两者都不吃索引。再建一条同前缀索引
|
||||||
|
* =只写不读,白白摊在 biz_file_task 每次写入上(V186 头注释「别让一条推测性索引进基线」同判)。
|
||||||
|
* 谁要拓宽这条口径,先让这里红一次。
|
||||||
|
*/
|
||||||
|
class TaskResumeIndexMigrationV187Test {
|
||||||
|
|
||||||
|
private static final Path SQL = Path.of(System.getProperty("user.dir"),
|
||||||
|
"src/main/resources/db/V187__file_task_resume_of_index.sql");
|
||||||
|
|
||||||
|
private static final Path RESUME_SERVICE = Path.of(System.getProperty("user.dir"),
|
||||||
|
"src/main/java/com/nanri/aiimage/modules/task/service/TaskResumeService.java");
|
||||||
|
|
||||||
|
private static String sql() throws IOException {
|
||||||
|
assertTrue(Files.exists(SQL), "V187 迁移脚本不在:" + SQL);
|
||||||
|
return Files.readString(SQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 只给反查列建一支索引且按判存包装() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
|
||||||
|
assertTrue(text.contains("ALTER TABLE biz_file_task ADD INDEX idx_biz_file_task_resume_of (resume_of_task_id)"),
|
||||||
|
"迁移对象与列名必须逐字对上:反查用的就是 resume_of_task_id");
|
||||||
|
assertTrue(text.contains("information_schema.STATISTICS"),
|
||||||
|
"必须判存后再建:重跑(或已手工建过)不能因 Duplicate key name 把启动掐断");
|
||||||
|
assertTrue(text.contains("PREPARE stmt FROM @sql"),
|
||||||
|
"判存要落到动态执行,光 SELECT 出计数不改表等于什么都没做");
|
||||||
|
assertEquals(1, occurrences(text, "ADD INDEX idx_biz_file_task_resume_of"),
|
||||||
|
"整份脚本只许建这一支索引");
|
||||||
|
assertTrue(text.contains("DROP INDEX idx_biz_file_task_resume_of"),
|
||||||
|
"回滚语句必须写在脚本注释里(与 V184/V186 同一口径)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 有意不建候选集那一支同前缀索引() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
// 只看真正会执行的行:头注释里必须写下 resume_attempt/V184 的取舍理由,那是文档不是 DDL。
|
||||||
|
StringBuilder executableText = new StringBuilder();
|
||||||
|
for (String line : text.split("\n")) {
|
||||||
|
String trimmed = line.trim();
|
||||||
|
if (!trimmed.startsWith("--")) {
|
||||||
|
executableText.append(trimmed).append('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String executable = executableText.toString().toUpperCase(java.util.Locale.ROOT);
|
||||||
|
|
||||||
|
assertFalse(executable.contains("RESUME_ATTEMPT"),
|
||||||
|
"resume_attempt 是 OR/IS-NULL 残差谓词,不进索引;要加必须先拿出真库 EXPLAIN 读数");
|
||||||
|
assertFalse(executable.contains("MODULE_TYPE"),
|
||||||
|
"(status, module_type, resume_attempt) 那支同前缀索引有意不建:等值前缀已由 V184 覆盖");
|
||||||
|
assertFalse(executable.contains("CREATE INDEX"),
|
||||||
|
"本仓加索引一律走 ALTER TABLE ... ADD INDEX(判存包装的形状)");
|
||||||
|
assertTrue(text.contains("idx_biz_file_task_status_module_created"),
|
||||||
|
"「等值前缀已由 V184 覆盖」这条判断的出处必须写在头注释里,否则下一个人会当成漏配");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 索引列与实体字段同源() throws IOException {
|
||||||
|
// MyBatis-Plus 靠驼峰↔下划线映射:字段名改了而索引列名没改,索引就成了永远命不中的摆设,
|
||||||
|
// 而巡检的反查照样跑得动——只是每次都全表扫。
|
||||||
|
assertTrue(java.util.Arrays.stream(FileTaskEntity.class.getDeclaredFields())
|
||||||
|
.anyMatch(field -> field.getName().equals("resumeOfTaskId")),
|
||||||
|
"实体里必须有 resumeOfTaskId 这个字段;反查一旦改名,V187 的索引与谓词会分叉");
|
||||||
|
assertTrue(sql().contains("ADD INDEX idx_biz_file_task_resume_of (resume_of_task_id)"),
|
||||||
|
"索引列名必须就是这个字段的下划线形(同源),别让它指向一列不存在的历史名");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 巡检里不留逐行反查的形状() throws IOException {
|
||||||
|
assertTrue(Files.exists(RESUME_SERVICE), "续跑服务源码不在:" + RESUME_SERVICE);
|
||||||
|
String text = Files.readString(RESUME_SERVICE);
|
||||||
|
|
||||||
|
assertFalse(text.contains("private boolean hasRetryChild("),
|
||||||
|
"P1-B5 的病灶就是逐行反查;改回单条档=每候选一次全表扫,退回原状即红");
|
||||||
|
assertFalse(text.contains("hasUnfinishedAssembleJob(original.getId())"),
|
||||||
|
"补检判定同样必须走批量档,不许在循环里逐行问库");
|
||||||
|
assertTrue(text.contains("parentsWithRetryChild(candidateIds)"),
|
||||||
|
"循环前一次批量反查");
|
||||||
|
assertTrue(text.contains("taskIdsWithUnfinishedAssembleJob(candidateIds)"),
|
||||||
|
"循环前一次批量补检判定");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int occurrences(String text, String needle) {
|
||||||
|
int count = 0;
|
||||||
|
int index = text.indexOf(needle);
|
||||||
|
while (index >= 0) {
|
||||||
|
count++;
|
||||||
|
index = text.indexOf(needle, index + needle.length());
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
package com.nanri.aiimage.config;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.usersecret.model.entity.UserSecretUsageEntity;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V188 给 {@code biz_user_secret_usage_daily} 加 {@code source} 列并把唯一键扩成四元组,
|
||||||
|
* 本类钉它的形状(Expand 半边,2026-11-04 客户反馈「代理IP用的很猛」的归因前置)。
|
||||||
|
*
|
||||||
|
* <p>四件事各守一个炸法:
|
||||||
|
* <ol>
|
||||||
|
* <li><b>NOT NULL + DEFAULT 'legacy' 且不回填</b>:存量行无法追溯是哪一路报的,
|
||||||
|
* 统一落 legacy(诚实的"不知道"),不按今天的上报方名单猜历史。</li>
|
||||||
|
* <li><b>唯一键必须扩成四元组</b>:不扩键的话同一天多路的上报会在旧三元组上互相
|
||||||
|
* ON DUPLICATE(source 记成"最后写入者"),按来源归因直接失真;只加列不扩键
|
||||||
|
* 等于白加。</li>
|
||||||
|
* <li><b>可重跑</b>:加列与建索引都先查 information_schema(列按 V157 款、索引按
|
||||||
|
* V184 款),迁移中途失败重跑不许撞 1060/1061。</li>
|
||||||
|
* <li><b>列名与实体字段对齐</b>:MyBatis-Plus 驼峰↔下划线,对不上写入会静默不落库。</li>
|
||||||
|
* </ol>
|
||||||
|
*/
|
||||||
|
class UserSecretUsageSourceMigrationV188Test {
|
||||||
|
|
||||||
|
private static final Path SQL = Path.of(System.getProperty("user.dir"),
|
||||||
|
"src/main/resources/db/V188__user_secret_usage_source.sql");
|
||||||
|
|
||||||
|
private static String sql() throws IOException {
|
||||||
|
assertTrue(Files.exists(SQL), "V188 迁移脚本不在:" + SQL);
|
||||||
|
return Files.readString(SQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 列是not_null的窄列且默认落legacy() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
|
||||||
|
assertTrue(text.contains("ALTER TABLE `biz_user_secret_usage_daily`"), "迁移对象必须是本表");
|
||||||
|
// DDL 藏在 SET @ddl 的字符串字面量里,引号按 SQL 规则写成两个单引号(''legacy'')
|
||||||
|
assertTrue(text.contains("ADD COLUMN `source` varchar(24) NOT NULL DEFAULT ''legacy''"),
|
||||||
|
"NOT NULL + DEFAULT 'legacy':存量行诚实落 legacy,NULL 会让 GROUP BY 多出一种真空来源");
|
||||||
|
assertTrue(text.contains("AFTER `module_key`"),
|
||||||
|
"紧跟 module_key:来源是模块的下一级维度,读的人要能一眼成对");
|
||||||
|
assertFalse(text.toUpperCase().contains("UPDATE `BIZ_USER_SECRET_USAGE_DAILY` SET `SOURCE`"),
|
||||||
|
"Expand 阶段不回填:历史行的来源不能按今天的上报方名单猜");
|
||||||
|
assertTrue(text.contains("DROP COLUMN `source`"),
|
||||||
|
"回滚语句必须写在脚本注释里(与 V157 同一口径)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 唯一键必须扩成四元组() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
|
||||||
|
assertTrue(text.contains("DROP INDEX `uk_user_module_date`"),
|
||||||
|
"旧三元组键必须摘除:留着它与新键并存,旧形状的 upsert 会绕过 source 维度");
|
||||||
|
assertTrue(text.contains("ADD UNIQUE KEY `uk_user_module_date_source` "
|
||||||
|
+ "(`user_id`, `module_key`, `business_date`, `source`)"),
|
||||||
|
"新键必须含 source:同一天多路各占一行,读侧 SUM 对多出的行透明");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 加列与建索引都必须判存可重跑() throws IOException {
|
||||||
|
String text = sql();
|
||||||
|
|
||||||
|
assertTrue(text.contains("information_schema.COLUMNS"),
|
||||||
|
"加列前必须查列存在(V157 款)");
|
||||||
|
assertTrue(text.contains("information_schema.STATISTICS"),
|
||||||
|
"建索引前必须查索引存在(V184 款)");
|
||||||
|
assertEquals(2, countMatches(text, "EXECUTE stmt"),
|
||||||
|
"两条 DDL 各自走 PREPARE/EXECUTE 判存重跑(DEALLOCATE 不计)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 头注释版本号与文件名一致() throws IOException {
|
||||||
|
String first = sql().lines().findFirst().orElse("");
|
||||||
|
assertTrue(first.startsWith("-- V188:"), "头注释必须写 V188,实际是:" + first);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 实体字段与列名按驼峰下划线一一对应() throws Exception {
|
||||||
|
assertNotNull(UserSecretUsageEntity.class.getDeclaredField("source"),
|
||||||
|
"实体缺 source 字段 ⇒ 列永远不会被写");
|
||||||
|
assertEquals("source", camelToSnake("source"),
|
||||||
|
"单词列名没有驼峰转换空间,这一格防的是字段名拼错(如 soource)");
|
||||||
|
assertTrue(sql().contains("`source`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countMatches(String text, String needle) {
|
||||||
|
Matcher matcher = Pattern.compile(needle, Pattern.LITERAL).matcher(text);
|
||||||
|
int count = 0;
|
||||||
|
while (matcher.find()) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String camelToSnake(String name) {
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
for (char c : name.toCharArray()) {
|
||||||
|
if (Character.isUpperCase(c)) {
|
||||||
|
out.append('_').append(Character.toLowerCase(c));
|
||||||
|
} else {
|
||||||
|
out.append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -235,6 +235,32 @@ class AppearancePatentRowMarkTimingTest {
|
|||||||
verify(taskCacheService).releaseRowInspection(TASK_ID, List.of("r2"));
|
verify(taskCacheService).releaseRowInspection(TASK_ID, List.of("r2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B74-01:landed(被塞回分片载荷)与 isJudged(有结论列)必须同源,谁说了算只能有一个。
|
||||||
|
*
|
||||||
|
* <p>发 2 行回 2 行、两行都落进分片,但 r2 只带 patentRisk——三列结论全空。旧写法按 landed
|
||||||
|
* 给它打 24 小时完成标记,于是它既不再是候选(被自己的标记挡着)又没有可出的结论,
|
||||||
|
* 只能等补检把标记连根撤掉才回来(现网 33179 的形状)。现在把完成标记打给 isJudged
|
||||||
|
* 不认的行即红。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void landedButUnjudgedRowDoesNotGetACompletionMark() throws Exception {
|
||||||
|
String halfJudged = "[{\"rowToken\":\"r1\",\"asin\":\"B0A0000001\",\"title\":\"RUNNING SHOE\","
|
||||||
|
+ "\"url\":\"http://img/1.jpg\",\"groupKey\":\"g1\","
|
||||||
|
+ "\"titleRisk\":\"无侵权\",\"appearanceRisk\":\"无侵权\",\"conclusion\":\"无侵权\"},"
|
||||||
|
+ "{\"rowToken\":\"r2\",\"asin\":\"B0A0000002\",\"title\":\"COTTON BAG\","
|
||||||
|
+ "\"url\":\"http://img/2.jpg\",\"groupKey\":\"g2\",\"patentRisk\":\"无侵权\"}]";
|
||||||
|
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
|
||||||
|
when(llmClient.inspectRows(any(), any(), any())).thenReturn(rows(halfJudged));
|
||||||
|
stubMergeWrite(2);
|
||||||
|
|
||||||
|
submit();
|
||||||
|
|
||||||
|
verify(taskCacheService).completeRowInspection(TASK_ID, List.of("r1"));
|
||||||
|
verify(taskCacheService, never()).completeRowInspection(TASK_ID, List.of("r2"));
|
||||||
|
verify(taskCacheService).releaseRowInspection(TASK_ID, List.of("r2"));
|
||||||
|
}
|
||||||
|
|
||||||
/** 回来的行一个都落不进分片(rowToken 被网关改写):整批都不能算完成。 */
|
/** 回来的行一个都落不进分片(rowToken 被网关改写):整批都不能算完成。 */
|
||||||
@Test
|
@Test
|
||||||
void rowsThatMatchNoChunkRowStayRetryable() throws Exception {
|
void rowsThatMatchNoChunkRowStayRetryable() throws Exception {
|
||||||
|
|||||||
+47
@@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
|||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.lenient;
|
import static org.mockito.Mockito.lenient;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
@@ -221,4 +222,50 @@ class AppearancePatentTaskCacheServiceRowMarkTest {
|
|||||||
|
|
||||||
assertEquals(0L, cache.rowInspectionRounds(TASK_ID, ROW_KEY));
|
assertEquals(0L, cache.rowInspectionRounds(TASK_ID, ROW_KEY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B74-01:Redis 回 null(管道/事务态、集群未回包)必须按**没抢到**处理。
|
||||||
|
*
|
||||||
|
* <p>旧写法 {@code return first == null || first;} 把「读不出」读成「抢到了」,同一行可能被
|
||||||
|
* 两个入口同时发出去(双扣用户 LLM 次数、两路各自 CAS 同一行)。这与"Redis 抛异常"是两条路:
|
||||||
|
* 真降级在 catch 里放行,由持久化层 isJudged 兜底(见 beginAllowsRowThroughWhenRedisFails)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void beginTreatsNullReplyAsNotClaimed() {
|
||||||
|
when(valueOperations.setIfAbsent(anyString(), anyString(), any(Duration.class))).thenReturn(null);
|
||||||
|
|
||||||
|
assertFalse(cache.beginRowInspection(TASK_ID, ROW_KEY),
|
||||||
|
"null 不是 true:读不出就不能声称拿到了这一行");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B74-01:清任务缓存必须删掉**真实存在**的逐行完成标记。
|
||||||
|
*
|
||||||
|
* <p>旧实现删的是 {@code processedRowsKey(taskId)} 这枚从不被写入的基键=删空气,
|
||||||
|
* 任务清完后 24 小时内重建,行仍被标记挡着不再检测——声称保护但不保护。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void deleteTaskCacheRemovesTheRealPerRowMarks() {
|
||||||
|
org.springframework.data.redis.core.Cursor<String> cursor =
|
||||||
|
mock(org.springframework.data.redis.core.Cursor.class);
|
||||||
|
when(cursor.hasNext()).thenReturn(true, true, false);
|
||||||
|
when(cursor.next()).thenReturn(
|
||||||
|
"appearance-patent:task:processed-rows:" + TASK_ID + ":r1",
|
||||||
|
"appearance-patent:task:processed-rows:" + TASK_ID + ":r2");
|
||||||
|
when(redisTemplate.scan(any())).thenReturn(cursor);
|
||||||
|
|
||||||
|
cache.deleteTaskCache(TASK_ID);
|
||||||
|
|
||||||
|
ArgumentCaptor<java.util.Collection<String>> deleted =
|
||||||
|
ArgumentCaptor.forClass(java.util.Collection.class);
|
||||||
|
verify(redisTemplate).delete(deleted.capture());
|
||||||
|
assertTrue(deleted.getValue().contains(
|
||||||
|
"appearance-patent:task:processed-rows:" + TASK_ID + ":r1"),
|
||||||
|
"逐行标记必须被真的删掉,否则「清完缓存」只是一句注释");
|
||||||
|
assertTrue(deleted.getValue().contains(
|
||||||
|
"appearance-patent:task:processed-rows:" + TASK_ID + ":r2"));
|
||||||
|
assertTrue(deleted.getValue().contains("appearance-patent:task:processed-rows:" + TASK_ID),
|
||||||
|
"基键一并清掉(今天它仍不存在,但它是这一族的目录名,不该留在册上)");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-4
@@ -33,7 +33,6 @@ import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
|||||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
|
||||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
import org.apache.ibatis.session.Configuration;
|
import org.apache.ibatis.session.Configuration;
|
||||||
import org.apache.poi.ss.usermodel.Row;
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
@@ -502,7 +501,7 @@ class AppearancePatentCreateTaskSnapshotTest {
|
|||||||
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
|
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
|
||||||
doThrow(new com.nanri.aiimage.common.exception.BusinessException("该账号还没有配置外观专利密钥"))
|
doThrow(new com.nanri.aiimage.common.exception.BusinessException("该账号还没有配置外观专利密钥"))
|
||||||
.when(harness.userApiSecretService)
|
.when(harness.userApiSecretService)
|
||||||
.requireSubmitSecret(any(), any(), any());
|
.requireSubmitSecret(any(), anyString(), any());
|
||||||
|
|
||||||
assertThrows(com.nanri.aiimage.common.exception.BusinessException.class,
|
assertThrows(com.nanri.aiimage.common.exception.BusinessException.class,
|
||||||
() -> harness.service().parseAndCreateTask(
|
() -> harness.service().parseAndCreateTask(
|
||||||
@@ -519,8 +518,7 @@ class AppearancePatentCreateTaskSnapshotTest {
|
|||||||
|
|
||||||
harness.service().parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d");
|
harness.service().parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d");
|
||||||
|
|
||||||
verify(harness.userApiSecretService).requireSubmitSecret(7L,
|
verify(harness.userApiSecretService).requireSubmitSecret(7L, "APPEARANCE_PATENT", "sk-test-0001");
|
||||||
UserSecretModule.APPEARANCE_PATENT, "sk-test-0001");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+140
@@ -9,12 +9,23 @@ import com.nanri.aiimage.config.ModuleCleanupProperties;
|
|||||||
import com.nanri.aiimage.config.TaskFileJobConfig;
|
import com.nanri.aiimage.config.TaskFileJobConfig;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
@@ -110,4 +121,133 @@ class TaskModuleCoverageTest {
|
|||||||
assertTrue(keys.contains("APPEARANCE_PATENT"));
|
assertTrue(keys.contains("APPEARANCE_PATENT"));
|
||||||
assertTrue(keys.contains("BRAND"));
|
assertTrue(keys.contains("BRAND"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- 建单凭据登记(B72-01,Phase 4) ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「这一类任务建单要拿用户的哪把密钥」登记表,必须与**实际在建单口问闸门的类型**一模一样。
|
||||||
|
*
|
||||||
|
* <p>两个方向都得红,缺一个方向这张表就会烂成摆设:
|
||||||
|
* <ul>
|
||||||
|
* <li>登记了却没人问 = 空转的登记表,下一个人照它判断"这类已经防住了"会做错事
|
||||||
|
* (门禁 1 反 stub 的同一家族:声称保护但不保护);</li>
|
||||||
|
* <li>问了却没登记 = 运行时 {@code IllegalStateException}({@code UserApiSecretService}
|
||||||
|
* 对空登记刻意不静默放行),这里提前把它抓成红,不留到线上。</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>为什么要有这张表:{@code /newApi} 是整包转发的透传面(客户端只搬字节),
|
||||||
|
* 载荷里有什么凭据需求客户端猜不出来,只能由服务端按 type 逐类登记(B72-01)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void submitSecretDeclarationsCoverExactlyTheGatedTypes() {
|
||||||
|
Set<String> gated = gatedSubmitSecretModuleTypes();
|
||||||
|
|
||||||
|
assertFalse(gated.isEmpty(), "一个建单闸门都没扫到 = 源码路径写错了,整支护栏在空转");
|
||||||
|
assertEquals(TaskModuleRegistry.submitSecretModuleTypes(), gated,
|
||||||
|
"登记表与建单口实际问闸门的类型不一致(唯一出处=TaskModuleRegistry.submitSecret)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登记为「不需要凭据」是**结论**而不是漏填,改这个结论要拍板不要顺手。
|
||||||
|
*
|
||||||
|
* <p>缺代理的几类(采集数据/店铺数据抓取/品牌检测/跟价…)在执行侧是「直连降级」,
|
||||||
|
* 不是注定失败——铁律 27 边界 (c) 明确不得顺手拦,拦了会把现在能跑的功能判死。
|
||||||
|
* 要动这一档,先有"这台机器直连能不能采到"的实测读数(欠账记在 B72-01 后半)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void everyRegisteredModuleDeclaresItsCredentialNeed() {
|
||||||
|
Set<String> declared = new LinkedHashSet<>();
|
||||||
|
for (String moduleType : EXPECTED_MODULES) {
|
||||||
|
// 不在清单里的类型这里会抛,所以这一轮循环同时钉住「每个模块都登记过」
|
||||||
|
TaskModuleRegistry.submitSecretModuleOf(moduleType).ifPresent(secret -> declared.add(moduleType));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(Set.of("APPEARANCE_PATENT", "SIMILAR_ASIN"), declared,
|
||||||
|
"建单口要问密钥的只有这两类(外观专利/货源查询的 LLM 检测)。其余几类缺的是代理,"
|
||||||
|
+ "而缺代理在执行侧是「直连降级」不是注定失败——铁律 27 边界 (c) 不得顺手拦,"
|
||||||
|
+ "拦了会把现在能跑的功能判死;要改这一档先有实测读数,拍板走 BACKLOG");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 「没登记」与「登记过=不需要」不许揉成同一个值:不在清单里的 type 必须抛,不能回 null。 */
|
||||||
|
@Test
|
||||||
|
void unknownModuleTypeFailsLoudInsteadOfLookingLikeADeclaration() {
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> TaskModuleRegistry.submitSecretModuleOf("APPEARANCE_PATENTT"),
|
||||||
|
"拼错的类型名被当成「不需要凭据」放行,等于闸门静默消失");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫主源码里每一处 {@code .requireSubmitSecret(...)} 调用,取出它问的那个 task type。
|
||||||
|
*
|
||||||
|
* <p>只认带点号的调用:方法自己的声明、以及服务内部 enum 形态的转调都不带点号,
|
||||||
|
* 数进去会把「实现」当成「调用方」而虚增分母(与 {@code SourceScanTest} 的声明/调用点同族坑)。
|
||||||
|
*/
|
||||||
|
private static Set<String> gatedSubmitSecretModuleTypes() {
|
||||||
|
Set<String> gated = new LinkedHashSet<>();
|
||||||
|
Pattern call = Pattern.compile("\\.requireSubmitSecret\\([^,]+,\\s*([A-Za-z_\"]+),");
|
||||||
|
Pattern ownType = Pattern.compile("MODULE_TYPE\\s*=\\s*\"([A-Z_]+)\"");
|
||||||
|
for (Path file : mainJavaFiles()) {
|
||||||
|
String code = withoutCommentLines(read(file));
|
||||||
|
Matcher matcher = call.matcher(code);
|
||||||
|
if (!matcher.find()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
String token = matcher.group(1);
|
||||||
|
if (token.startsWith("\"")) {
|
||||||
|
gated.add(token.substring(1, token.length() - 1));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assertTrue("MODULE_TYPE".equals(token),
|
||||||
|
file.getFileName() + " 传给建单闸门的第二个参数只认类型常量或字面量: " + token);
|
||||||
|
Matcher own = ownType.matcher(code);
|
||||||
|
assertTrue(own.find(),
|
||||||
|
file.getFileName() + " 调了闸门却没声明 MODULE_TYPE,登记表对不上号");
|
||||||
|
gated.add(own.group(1));
|
||||||
|
} while (matcher.find());
|
||||||
|
}
|
||||||
|
return gated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 注释行与 javadoc 续行不算锚点:在注释里提一句方法名不等于接了线。 */
|
||||||
|
private static String withoutCommentLines(String source) {
|
||||||
|
return source.lines()
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(line -> !line.startsWith("//") && !line.startsWith("*")
|
||||||
|
&& !line.startsWith("/*") && !line.startsWith("*/"))
|
||||||
|
.collect(Collectors.joining("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Path> mainJavaFiles() {
|
||||||
|
try (Stream<Path> walk = Files.walk(mainRoot())) {
|
||||||
|
return walk.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||||
|
.sorted()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("扫描主源码失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 路径解析照抄 {@code common/security/ConsoleWideningGuardrailTest}:定位不到必须抛,不许空扫。 */
|
||||||
|
private static Path mainRoot() {
|
||||||
|
Path here = Path.of("").toAbsolutePath();
|
||||||
|
Path direct = here.resolve("src/main/java/com/nanri/aiimage");
|
||||||
|
if (Files.isDirectory(direct)) {
|
||||||
|
return direct;
|
||||||
|
}
|
||||||
|
Path nested = here.resolve("backend-java").resolve("src/main/java/com/nanri/aiimage");
|
||||||
|
if (Files.isDirectory(nested)) {
|
||||||
|
return nested;
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("无法定位 backend-java 源码目录(cwd=" + here + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String read(Path file) {
|
||||||
|
try {
|
||||||
|
return Files.readString(file, StandardCharsets.UTF_8);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("读取失败: " + file, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
package com.nanri.aiimage.modules.shopduplicatecheck.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.shopduplicatecheck.TestFixtures;
|
||||||
|
import com.nanri.aiimage.modules.shopduplicatecheck.mapper.ShopDuplicateCheckSourceMapper;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页窗算式的溢出档(铁律 15;2026-11-04 Phase 6 Code Review 的 CR-P1)。
|
||||||
|
*
|
||||||
|
* <p>病灶是 {@code Math.min((page - 1) * pageSize, total)}:乘法先于 {@code min} 发生,
|
||||||
|
* {@code page=11000000 / page_size=200} 在 int 上溢出成 {@code -2094967296},
|
||||||
|
* {@code Math.min} 之后还是负数,喂进 {@code subList(负, 负)} 就是 IndexOutOfBounds = HTTP 500。
|
||||||
|
* 表里只要有至少一行重复数据就能打出来,且四个界面入口(撞款明细/行级详情/台账/console 矩阵)
|
||||||
|
* 全是同一个形状。这条不是"深分页慢"那种性能问题,是**正确性**问题:管理员翻到最后一页
|
||||||
|
* 或者被脚本扫一遍,接口就红。
|
||||||
|
*
|
||||||
|
* <p>为什么判据打在服务而不是控制器:控制器的 {@code parsePage} 也加了上限钳制(边界卫生),
|
||||||
|
* 但溢出发生在服务里的那次乘法上——只钳边界的话,下一个直接调本服务的调用方能把 500 原样请回来,
|
||||||
|
* 而没有任何一把尺子知道错在哪。所以这里打真入口,把「算不坏」钉住。
|
||||||
|
*/
|
||||||
|
class ShopDataDuplicateCheckPageWindowTest {
|
||||||
|
|
||||||
|
/** 审计给的现网形状:这一对相乘正好跨过 Integer.MAX_VALUE。 */
|
||||||
|
private static final int OVERFLOW_PAGE = 11_000_000;
|
||||||
|
private static final int OVERFLOW_SIZE = 200;
|
||||||
|
|
||||||
|
private ShopDataDuplicateCheckQueryService service;
|
||||||
|
private ShopDataDuplicateCheckScanService.DuplicateScanView view;
|
||||||
|
private ShopDataDuplicateCheckQueryService.Filters noFilter;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
service = new ShopDataDuplicateCheckQueryService(mock(ShopDuplicateCheckSourceMapper.class));
|
||||||
|
view = TestFixtures.view();
|
||||||
|
noFilter = ShopDataDuplicateCheckQueryService.Filters.clean("", "", "", "", "", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void consoleMatrixWithOverflowShapedPageYieldsEmptyWindowNotHttp500() {
|
||||||
|
// 本 Phase 的 B60 行窗改的就是这一处(c8cd75cf),CR 也是在这里抓到的。
|
||||||
|
int fullTotal = (int) service.consoleData(view, null, noFilter, 1, 100, "").get("total_dup");
|
||||||
|
assertThat(fullTotal).isGreaterThan(0);
|
||||||
|
|
||||||
|
Map<String, Object> data = service.consoleData(
|
||||||
|
view, null, noFilter, OVERFLOW_PAGE, OVERFLOW_SIZE, "");
|
||||||
|
|
||||||
|
assertThat((List<?>) data.get("dup")).isEmpty();
|
||||||
|
assertThat(data.get("total_dup")).isEqualTo(fullTotal);
|
||||||
|
assertThat(data.get("page")).isEqualTo(OVERFLOW_PAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void otherThreeWindowSitesSurviveIntegerMaxValuePage() {
|
||||||
|
for (int page : new int[]{Integer.MAX_VALUE, OVERFLOW_PAGE, 1_073_741_824}) {
|
||||||
|
assertThatCode(() -> {
|
||||||
|
assertThat((List<?>) service.itemsData(view, null, page, 200, "", noFilter).get("items"))
|
||||||
|
.isEmpty();
|
||||||
|
assertThat((List<?>) service.detailData(view, null, page, 200, noFilter).get("items"))
|
||||||
|
.isEmpty();
|
||||||
|
assertThat((List<?>) service.ledgerData(view, null, page, 200, null, null, noFilter)
|
||||||
|
.get("items")).isEmpty();
|
||||||
|
}).as("page=%s 不该把负下标喂给 subList", page).doesNotThrowAnyException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void totalStaysTheUnpaginatedCountBeyondTheLastPage() {
|
||||||
|
// 「越界页=空窗」与「total 仍是全量」必须同时成立:把 total 跟着窗走,界面会显示"没有重复"。
|
||||||
|
int fullTotal = (int) service.itemsData(view, null, 1, 1, "", noFilter).get("total");
|
||||||
|
assertThat(service.itemsData(view, null, 999_999, 100, "", noFilter).get("total"))
|
||||||
|
.isEqualTo(fullTotal);
|
||||||
|
assertThat(service.consoleData(view, null, noFilter, 999_999, 100, "").get("total_dup"))
|
||||||
|
.isEqualTo((int) service.consoleData(view, null, noFilter, 1, 1, "").get("total_dup"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pageBelowOneFallsBackToFirstWindowInsteadOfNegativeIndex() {
|
||||||
|
for (int page : new int[]{0, -1, Integer.MIN_VALUE}) {
|
||||||
|
List<?> items = (List<?>) service.itemsData(view, null, page, 2, "", noFilter).get("items");
|
||||||
|
assertThat(items).as("page=%s 应当按第一窗读", page).isNotEmpty();
|
||||||
|
assertThat((List<?>) service.consoleData(view, null, noFilter, page, 100, "").get("dup"))
|
||||||
|
.as("page=%s 的 console 矩阵同理", page).isNotEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void middleWindowStillReturnsExactlyPageSizeRowsInOrder() {
|
||||||
|
// 反向自证:把溢出修成"整窗返回空"这种过头样子,这条会红。
|
||||||
|
List<?> first = (List<?>) service.itemsData(view, null, 1, 1, "dup", noFilter).get("items");
|
||||||
|
List<?> second = (List<?>) service.itemsData(view, null, 2, 1, "dup", noFilter).get("items");
|
||||||
|
assertThat(first).hasSize(1);
|
||||||
|
assertThat(second).hasSizeLessThanOrEqualTo(1);
|
||||||
|
assertThat(first).isNotEqualTo(second);
|
||||||
|
}
|
||||||
|
}
|
||||||
+69
-3
@@ -156,7 +156,7 @@ class ShopDataDuplicateCheckQueryServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void consoleSuperAdminReturnsDupSetGroupsAndSummary() {
|
void consoleSuperAdminReturnsDupSetGroupsAndSummary() {
|
||||||
Map<String, Object> data = service.consoleData(view, null, noFilter());
|
Map<String, Object> data = service.consoleData(view, null, noFilter(), 1, 100, "");
|
||||||
assertThat(data.get("pending")).isEqualTo(false);
|
assertThat(data.get("pending")).isEqualTo(false);
|
||||||
assertThat(data.get("total_dup")).isEqualTo(3);
|
assertThat(data.get("total_dup")).isEqualTo(3);
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@@ -184,7 +184,7 @@ class ShopDataDuplicateCheckQueryServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void consoleLeaderCropRemovesCrossGroupDupAndKeepsOwnGroups() {
|
void consoleLeaderCropRemovesCrossGroupDupAndKeepsOwnGroups() {
|
||||||
Set<String> visible = Set.of("shopa", "shopb");
|
Set<String> visible = Set.of("shopa", "shopb");
|
||||||
Map<String, Object> data = service.consoleData(view, visible, noFilter());
|
Map<String, Object> data = service.consoleData(view, visible, noFilter(), 1, 100, "");
|
||||||
assertThat(data.get("total_dup")).isEqualTo(2);
|
assertThat(data.get("total_dup")).isEqualTo(2);
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<DuplicateItem> dup = (List<DuplicateItem>) data.get("dup");
|
List<DuplicateItem> dup = (List<DuplicateItem>) data.get("dup");
|
||||||
@@ -201,11 +201,77 @@ class ShopDataDuplicateCheckQueryServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void consolePendingShapes() {
|
void consolePendingShapes() {
|
||||||
Map<String, Object> data = service.pendingConsole();
|
Map<String, Object> data = service.pendingConsole(1, 100);
|
||||||
assertThat(data.get("pending")).isEqualTo(true);
|
assertThat(data.get("pending")).isEqualTo(true);
|
||||||
assertThat(data.get("dup")).isEqualTo(List.of());
|
assertThat(data.get("dup")).isEqualTo(List.of());
|
||||||
assertThat(data.get("groups")).isEqualTo(List.of());
|
assertThat(data.get("groups")).isEqualTo(List.of());
|
||||||
assertThat(data.get("summary")).isEqualTo(Map.of());
|
assertThat(data.get("summary")).isEqualTo(Map.of());
|
||||||
|
assertThat(data.get("page")).isEqualTo(1);
|
||||||
|
assertThat(data.get("page_size")).isEqualTo(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B60:console 的 {@code dup} 从「全集」改成「行窗口」。分页参数必须真生效——
|
||||||
|
* 响应体行数 ≤ pageSize,而 {@code total_dup} 仍是未分页的总数(KPI/分页控件读它)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void consoleRowWindowLimitsRowsButKeepsFullTotal() {
|
||||||
|
Map<String, Object> data = service.consoleData(view, null, noFilter(), 1, 2, "");
|
||||||
|
assertThat(data.get("total_dup")).isEqualTo(3);
|
||||||
|
assertThat(data.get("page")).isEqualTo(1);
|
||||||
|
assertThat(data.get("page_size")).isEqualTo(2);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<DuplicateItem> dup = (List<DuplicateItem>) data.get("dup");
|
||||||
|
assertThat(dup).hasSize(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 行窗口按 ASIN 升序<b>稳定</b>:把窗口翻到第二页必须拿到上一页之外的行,
|
||||||
|
* 而不是每次刷新换一批(排序发生在切窗之前,这是分页可用的前提)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void consoleRowWindowsAreStableAcrossPages() {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<DuplicateItem> first = (List<DuplicateItem>)
|
||||||
|
service.consoleData(view, null, noFilter(), 1, 2, "").get("dup");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<DuplicateItem> second = (List<DuplicateItem>)
|
||||||
|
service.consoleData(view, null, noFilter(), 2, 2, "").get("dup");
|
||||||
|
assertThat(first).extracting(DuplicateItem::asin).containsExactly("A0000001", "E0000001");
|
||||||
|
assertThat(second).extracting(DuplicateItem::asin).containsExactly("F0000001");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分组范围(页面的「分组」chip)由服务端裁行:判据=组内 ≥2 店。
|
||||||
|
* F0000001 是 ShopB(GroupA)×ShopD(GroupD) 的跨组撞款,落在 GroupA 范围内不算组内撞款。
|
||||||
|
*
|
||||||
|
* <p>只裁行:summary/shops/groups 三块必须与不带 dup_group 的那次逐字相同——
|
||||||
|
* 指标跟着行窗口一起缩的话,页面顶部数字就成了「这一页的统计」,那是另一件事。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void consoleDupGroupScopesRowsOnlyAndLeavesStatsAlone() {
|
||||||
|
Map<String, Object> scoped = service.consoleData(view, null, noFilter(), 1, 100, "GroupA");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<DuplicateItem> rows = (List<DuplicateItem>) scoped.get("dup");
|
||||||
|
assertThat(scoped.get("total_dup")).isEqualTo(2);
|
||||||
|
assertThat(rows).extracting(DuplicateItem::asin).containsExactly("A0000001", "E0000001");
|
||||||
|
|
||||||
|
Map<String, Object> plain = service.consoleData(view, null, noFilter(), 1, 100, "");
|
||||||
|
assertThat(scoped.get("summary")).isEqualTo(plain.get("summary"));
|
||||||
|
assertThat(scoped.get("shops")).isEqualTo(plain.get("shops"));
|
||||||
|
assertThat(scoped.get("groups")).isEqualTo(plain.get("groups"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 组内不足 2 店 ⇒ 行集为空(不是「退回全集」);组名不存在同理。 */
|
||||||
|
@Test
|
||||||
|
void consoleDupGroupWithoutPairReturnsEmptyWindow() {
|
||||||
|
Map<String, Object> singleShopGroup = service.consoleData(view, null, noFilter(), 1, 100, "GroupC");
|
||||||
|
assertThat(singleShopGroup.get("total_dup")).isEqualTo(0);
|
||||||
|
assertThat((List<?>) singleShopGroup.get("dup")).isEmpty();
|
||||||
|
|
||||||
|
Map<String, Object> unknownGroup = service.consoleData(view, null, noFilter(), 1, 100, "不存在组");
|
||||||
|
assertThat(unknownGroup.get("total_dup")).isEqualTo(0);
|
||||||
|
assertThat((List<?>) unknownGroup.get("dup")).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+2
-3
@@ -31,7 +31,6 @@ import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
|||||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
|
||||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
import org.apache.poi.ss.usermodel.Row;
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
@@ -408,7 +407,7 @@ class SimilarAsinCreateTaskSnapshotTest {
|
|||||||
@Test
|
@Test
|
||||||
void missingSecretRejectsBeforeParse() {
|
void missingSecretRejectsBeforeParse() {
|
||||||
doThrow(new BusinessException("该账号还没有配置货源查询密钥"))
|
doThrow(new BusinessException("该账号还没有配置货源查询密钥"))
|
||||||
.when(userApiSecretService).requireSubmitSecret(any(), any(), any());
|
.when(userApiSecretService).requireSubmitSecret(any(), anyString(), any());
|
||||||
|
|
||||||
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
||||||
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
||||||
@@ -424,7 +423,7 @@ class SimilarAsinCreateTaskSnapshotTest {
|
|||||||
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
||||||
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
||||||
|
|
||||||
verify(userApiSecretService).requireSubmitSecret(9L, UserSecretModule.SIMILAR_ASIN, "unit-test-key");
|
verify(userApiSecretService).requireSubmitSecret(9L, "SIMILAR_ASIN", "unit-test-key");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 只在显式点名时写 golden:默认跑测试永远不许改是非源。 */
|
/** 只在显式点名时写 golden:默认跑测试永远不许改是非源。 */
|
||||||
|
|||||||
+8
-3
@@ -40,15 +40,20 @@ class ResultFileJobHandlerTest {
|
|||||||
void interfaceMethodsPresent() throws Exception {
|
void interfaceMethodsPresent() throws Exception {
|
||||||
// 2026-09:新增 resolveResultFileUrl(模块自定义结果对象 key 解析,BRAND 用),
|
// 2026-09:新增 resolveResultFileUrl(模块自定义结果对象 key 解析,BRAND 用),
|
||||||
// 接口方法从 8 个增到 9 个,同步更新契约断言。
|
// 接口方法从 8 个增到 9 个,同步更新契约断言。
|
||||||
assertEquals(9, ResultFileJobHandler.class.getDeclaredMethods().length,
|
// 2026-11-03 f43ed6f1「任务中断+继续」:新增 onTaskResumed 钩子(继续在原任务上续跑前
|
||||||
"接口方法数量为 9(moduleType/process/onSuccess/cleanup/onFailure/"
|
// 清模块补检预算,AP 侧删 __recheck__ 哨兵键),9 个增到 10 个。分母变大是覆盖面变大,
|
||||||
+ "fallbackAssembleOnFailure/resolveResultFileUrl/supportsAsyncOffload/isOwnerScoped)");
|
// 不是放宽——少一个钩子=继续跑的任务第一轮就被「补检已耗尽」按部分表收尾。
|
||||||
|
assertEquals(10, ResultFileJobHandler.class.getDeclaredMethods().length,
|
||||||
|
"接口方法数量为 10(moduleType/process/onSuccess/cleanup/onFailure/"
|
||||||
|
+ "fallbackAssembleOnFailure/resolveResultFileUrl/onTaskResumed/"
|
||||||
|
+ "supportsAsyncOffload/isOwnerScoped)");
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "moduleType"));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "moduleType"));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "process", TaskFileJobEntity.class));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "process", TaskFileJobEntity.class));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "onSuccess", TaskFileJobEntity.class));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "onSuccess", TaskFileJobEntity.class));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "cleanup", TaskFileJobEntity.class));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "cleanup", TaskFileJobEntity.class));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "onFailure", TaskFileJobEntity.class, String.class));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "onFailure", TaskFileJobEntity.class, String.class));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "resolveResultFileUrl", TaskFileJobEntity.class));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "resolveResultFileUrl", TaskFileJobEntity.class));
|
||||||
|
assertNotNull(methodOf(ResultFileJobHandler.class, "onTaskResumed", Long.class));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "supportsAsyncOffload"));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "supportsAsyncOffload"));
|
||||||
assertNotNull(methodOf(ResultFileJobHandler.class, "isOwnerScoped"));
|
assertNotNull(methodOf(ResultFileJobHandler.class, "isOwnerScoped"));
|
||||||
}
|
}
|
||||||
|
|||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||||
|
import com.nanri.aiimage.testutil.SourceScan;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败分类列的写入面与读侧面判据(B51-R1,Expand 半边)。
|
||||||
|
*
|
||||||
|
* <p><b>为什么打在源码上而不是四份单测夹具</b>:这一格要守的是「写了文案就必须同笔写列」这条
|
||||||
|
* <em>连线</em>。用 mock 造一枚任务实体测一遍分类,改天新增一处 {@code setErrorMessage} 而忘了
|
||||||
|
* 写列,那份单测照样全绿——而这正是"改一句文案静默改判死"的复发路径。
|
||||||
|
*
|
||||||
|
* <p>四件事各守一个方向:
|
||||||
|
* <ol>
|
||||||
|
* <li>每一处任务失败文案的 wrapper 写点,下一行必须同笔写 {@code failure_category}
|
||||||
|
* (把任一处配对删掉 ⇒ 本类红);</li>
|
||||||
|
* <li>已接线的<b>实体式</b>写面({@code task.setErrorMessage + updateById},名单见
|
||||||
|
* {@code ENTITY_FACE_FILES})必须同笔经 {@link TaskFailureLedger} 派生写列——
|
||||||
|
* 这批写的正是判死/重试消费的那几族文案,漏列=读侧对这一行永远退回中文子串;</li>
|
||||||
|
* <li>列的值只能由 {@link TaskFailureLedger} 从 {@link TaskRetryEligibility} 推导,
|
||||||
|
* ledger 自己不许再抄一份中文 markers(否则 B52 那族「词汇表多正本」在这里重生);</li>
|
||||||
|
* <li>读侧「文案判得出按文案、判不出按列」:措辞漂移时列把判决钉在原处,列不在必须逐字退回
|
||||||
|
* 原判据,存量行为一字不变;列与文案背离(名单外的实体式写点)时按文案——陈旧列不许判死。</li>
|
||||||
|
* </ol>
|
||||||
|
*/
|
||||||
|
class TaskFailureCategoryGuardrailTest {
|
||||||
|
|
||||||
|
private static final String MESSAGE_SET = ".set(FileTaskEntity::getErrorMessage, ";
|
||||||
|
private static final String CATEGORY_SET = ".set(FileTaskEntity::getFailureCategory, ";
|
||||||
|
|
||||||
|
/** 现网在册写点的下限:低于这个数说明扫描面或写法变了,而不是"违规被修完了"。 */
|
||||||
|
private static final int MIN_WRITE_SITES = 20;
|
||||||
|
|
||||||
|
/** 实体式写面的接线名单(第二批):只有列在这里的文件受 {@code 已接线的实体式任务写点...} 那格管。 */
|
||||||
|
private static final List<String> ENTITY_FACE_FILES = List.of(
|
||||||
|
"AppearancePatentResultJobSupport.java",
|
||||||
|
"SimilarAsinTaskService.java",
|
||||||
|
"CollectDataService.java");
|
||||||
|
|
||||||
|
/** 名单内在册写点数(AP 4 +相似ASIN 4 +采集 1);低于它=写点被挪走或改了写法。 */
|
||||||
|
private static final int ENTITY_FACE_MIN_WRITE_SITES = 9;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 任务失败文案写点必须同笔写分类列() {
|
||||||
|
List<String> violations = new ArrayList<>();
|
||||||
|
int sites = 0;
|
||||||
|
for (Path file : mainJavaFiles()) {
|
||||||
|
List<String> lines = readLines(file);
|
||||||
|
for (int i = 0; i < lines.size(); i++) {
|
||||||
|
String line = lines.get(i);
|
||||||
|
if (!line.contains(MESSAGE_SET) || isComment(line)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sites++;
|
||||||
|
String paired = i + 1 < lines.size() ? lines.get(i + 1) : "";
|
||||||
|
String self = line.contains(CATEGORY_SET) ? line : paired;
|
||||||
|
if (!self.contains(CATEGORY_SET)) {
|
||||||
|
violations.add(file.getFileName() + ":" + (i + 1) + " 只写了文案没写列");
|
||||||
|
} else if (!pairingIsForSameMessage(line, paired)) {
|
||||||
|
violations.add(file.getFileName() + ":" + (i + 1) + " 写的列与文案不是同一个来源");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertThat(violations)
|
||||||
|
.as("biz_file_task.error_message 的每一处落库都必须把 TaskRetryEligibility 的判定结果一起记下来"
|
||||||
|
+ "(B51-R1:否则读侧永远只能靠中文子串猜当时判了什么)")
|
||||||
|
.isEmpty();
|
||||||
|
assertThat(sites)
|
||||||
|
.as("扫到的写点数低于下限=扫描面或写法变了,不是违规清零了")
|
||||||
|
.isGreaterThanOrEqualTo(MIN_WRITE_SITES);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 实体式写面({@code task.setErrorMessage(...)} + {@code updateById})第二批接线。
|
||||||
|
*
|
||||||
|
* <p>这三面写出的正是判死/重试真正消费的那些文案(DELIVERY/BALANCE 家族:结果文件多次生成
|
||||||
|
* 失败、LLM 上游欠费)。它们不走 wrapper,上面那格扫不到;漏写列的后果不是崩,而是读侧对这一行
|
||||||
|
* <b>永远</b>退回中文子串——加了一列却没买到任何免疫力,这正是 B51 的病灶形状。
|
||||||
|
*
|
||||||
|
* <p>名单之外(其它实体的 {@code setErrorMessage}、以及尚未接线的 {@code FileTaskEntity} 写面)
|
||||||
|
* 本格不管:按面分批收是 {@code docs/REFACTOR_PLAN.md} §5 登记的口径,Contract 阶段前逐批加进来。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void 已接线的实体式任务写点必须同笔派生写列() {
|
||||||
|
List<String> violations = new ArrayList<>();
|
||||||
|
int sites = 0;
|
||||||
|
for (Path file : mainJavaFiles()) {
|
||||||
|
if (!ENTITY_FACE_FILES.contains(file.getFileName().toString())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> lines = readLines(file);
|
||||||
|
for (int i = 0; i < lines.size(); i++) {
|
||||||
|
String line = lines.get(i).trim();
|
||||||
|
if (isComment(line) || !line.startsWith("task.setErrorMessage(")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sites++;
|
||||||
|
String paired = i + 1 < lines.size() ? lines.get(i + 1).trim() : "";
|
||||||
|
if (!paired.startsWith("task.setFailureCategory(TaskFailureLedger.categoryOf(")) {
|
||||||
|
violations.add(file.getFileName() + ":" + (i + 1) + " 只写了文案没同笔派生写列");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertThat(violations)
|
||||||
|
.as("名单内的任务实体写点必须经 TaskFailureLedger 把分类一起落库(把配对删掉即红)")
|
||||||
|
.isEmpty();
|
||||||
|
assertThat(sites)
|
||||||
|
.as("三面在册写点数低于下限=写法变了或写点被挪走,不是违规清零了")
|
||||||
|
.isGreaterThanOrEqualTo(ENTITY_FACE_MIN_WRITE_SITES);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 分类值只能由词汇表那一处推导_ledger不得再抄一份markers() {
|
||||||
|
String ledger = SourceScan.withoutComments(SourceScan.sourceText("TaskFailureLedger.java"));
|
||||||
|
|
||||||
|
assertThat(ledger)
|
||||||
|
.as("ledger 必须把判定委托给 TaskRetryEligibility,不自己判")
|
||||||
|
.contains("TaskRetryEligibility.forceMajeureCategory");
|
||||||
|
assertThat(ledger)
|
||||||
|
.as("ledger 里出现 contains( =抄了第二份中文 markers 正本,B52 那族的复发形状")
|
||||||
|
.doesNotContain(".contains(");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 列登记过就读列_没登记就逐字退回文案判定() {
|
||||||
|
FileTaskEntity task = new FileTaskEntity();
|
||||||
|
|
||||||
|
// ① 列在、文案已漂移 ⇒ 以列为准:这就是本列存在的意义
|
||||||
|
task.setFailureCategory(TaskRetryEligibility.Category.BALANCE.name());
|
||||||
|
task.setErrorMessage("上游提示已更新,不再含任何已知字样");
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("文案判不出时以登记列为准——判死不随措辞漂移")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
|
||||||
|
// ② 列没登记(存量行 / 尚未接 ledger 的实体式写入面)⇒ 逐字回落到今天的口径
|
||||||
|
task.setFailureCategory(null);
|
||||||
|
task.setErrorMessage("LLM 服务余额欠费(上游账户额度不足,非本行数据问题)");
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("空列不等于「无类别」,必须回落到文案判定")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
|
||||||
|
// ③ 列里是不认识的值(脏数据 / 将来改名)⇒ 同样回落,且不得抛
|
||||||
|
task.setFailureCategory("BALANCE_BUT_TYPO");
|
||||||
|
task.setErrorMessage("任务心跳超时,已自动失败");
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("不可识别的分类名按未登记处理:读侧不许因为一列脏值把判定改成「无可重试」")
|
||||||
|
.isNull();
|
||||||
|
|
||||||
|
// ④ 列与文案都判得出、却不同类 ⇒ 列是<b>陈旧</b>的(实体式 setErrorMessage 改文案带不动列,
|
||||||
|
// 这批写点本轮未接 ledger)。读文案=逐字等于加列之前的今天;读列就是本笔自己引入的漂移。
|
||||||
|
task.setFailureCategory(TaskRetryEligibility.Category.BALANCE.name());
|
||||||
|
task.setErrorMessage("已收到 73 个结果分片,但结果文件生成多次失败,任务已自动结束");
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("背离时按文案:陈旧的一列不许判死这一单")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.DELIVERY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 空列与脏列都不许被读成一种新状态() {
|
||||||
|
assertThat(TaskRetryEligibility.categoryByName(null)).isNull();
|
||||||
|
assertThat(TaskRetryEligibility.categoryByName(" ")).isNull();
|
||||||
|
assertThat(TaskRetryEligibility.categoryByName("UNKNOWN")).isNull();
|
||||||
|
assertThat(TaskRetryEligibility.categoryByName(" balance ")).isNull();
|
||||||
|
// 逐值比对要认得住合法值(大小写敏感:写侧落的是 name())
|
||||||
|
assertThat(TaskRetryEligibility.categoryByName("STOPPED"))
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.STOPPED);
|
||||||
|
assertThat(TaskRetryEligibility.category(null)).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 配对行必须引用同一个表达式来源,防止「写了列但写的是另一句文案的分类」。 */
|
||||||
|
private static boolean pairingIsForSameMessage(String messageLine, String categoryLine) {
|
||||||
|
String messageExpr = expressionOf(messageLine, MESSAGE_SET);
|
||||||
|
String categoryExpr = expressionOf(categoryLine, CATEGORY_SET);
|
||||||
|
if (messageExpr == null || categoryExpr == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isNullish(messageExpr) || isNullish(categoryExpr)) {
|
||||||
|
// 清错误的那一侧同时清列:两边都空才是配对的
|
||||||
|
return isNullish(messageExpr) && isNullish(categoryExpr);
|
||||||
|
}
|
||||||
|
return categoryExpr.contains(messageExpr) || messageExpr.contains(categoryExpr);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String expressionOf(String line, String marker) {
|
||||||
|
if (line == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int idx = line.indexOf(marker);
|
||||||
|
if (idx < 0 || isComment(line)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String tail = line.substring(idx + marker.length());
|
||||||
|
// 从 .set( 的下一位开始配平:深度回到 0 的那个 ')' 才是本 set(...) 的闭括号,
|
||||||
|
// 链尾还挂着 update(...) 的闭括号与分号,不能按"最后一个右括号"倒推(那会把
|
||||||
|
// `null));` 切成 `null)`,读成"不是 null")。
|
||||||
|
int depth = 1;
|
||||||
|
for (int i = 0; i < tail.length(); i++) {
|
||||||
|
char c = tail.charAt(i);
|
||||||
|
if (c == '(') {
|
||||||
|
depth++;
|
||||||
|
} else if (c == ')') {
|
||||||
|
depth--;
|
||||||
|
if (depth == 0) {
|
||||||
|
return tail.substring(0, i).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isNullish(String expression) {
|
||||||
|
return "null".equals(expression) || expression.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isComment(String line) {
|
||||||
|
String stripped = line.trim();
|
||||||
|
return stripped.startsWith("//") || stripped.startsWith("*") || stripped.startsWith("/*");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Path> mainJavaFiles() {
|
||||||
|
Path root = SourceScan.mainSourcesRoot();
|
||||||
|
try (Stream<Path> stream = Files.walk(root)) {
|
||||||
|
return new ArrayList<>(stream.filter(p -> p.toString().endsWith(".java"))
|
||||||
|
.collect(java.util.stream.Collectors.toList()));
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new UncheckedIOException("扫描面读不到:" + root, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> readLines(Path file) {
|
||||||
|
try {
|
||||||
|
return Files.readAllLines(file);
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new UncheckedIOException(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+189
@@ -0,0 +1,189 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||||
|
import com.nanri.aiimage.modules.task.mapper.TaskFileJobMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.isNull;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P1-B6/P1-B5:认领循环与补检判定都必须走批量档,不许退回逐行点查。
|
||||||
|
*
|
||||||
|
* <p>来历:{@code claimCandidates} 原先对每个候选各做一次 {@code selectFileTaskStatus}(一批 100
|
||||||
|
* 个候选=100 次 SELECT),而 P1-13 之后这份结果**只用来打一行日志**——终态父任务的出表作业照旧放行。
|
||||||
|
* 纯开销的 N 次往返折成一次 {@code IN} 批查。逐行 CAS 认领({@code markRunning})一字不动:
|
||||||
|
* 那才是并发不重复派发的根据,不能被"顺手批量化"掉。
|
||||||
|
*
|
||||||
|
* <p>反向自证:把批量档改回循环里逐条 {@code isOwningTaskTerminal},本类第一格即红。
|
||||||
|
* 批量档的本体在 {@link TaskFileJobBatchQueries}(静态只读工具),{@code TaskFileJobService}
|
||||||
|
* 只留一个同名门面——门面不许长回逻辑,否则服务侧又变超长文件。
|
||||||
|
*/
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class TaskFileJobBatchQueryGuardrailTest {
|
||||||
|
|
||||||
|
@Mock private TaskFileJobMapper taskFileJobMapper;
|
||||||
|
@Mock private ApplicationEventPublisher applicationEventPublisher;
|
||||||
|
|
||||||
|
private TaskFileJobService service;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void initializeTableInfo() {
|
||||||
|
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||||
|
TaskFileJobEntity.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TaskFileJobEntity job(Long id, Long taskId, String status) {
|
||||||
|
TaskFileJobEntity entity = new TaskFileJobEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setTaskId(taskId);
|
||||||
|
entity.setResultId(2000L + id);
|
||||||
|
entity.setModuleType("APPEARANCE_PATENT");
|
||||||
|
entity.setJobType("ASSEMBLE_RESULT");
|
||||||
|
entity.setStatus(status);
|
||||||
|
entity.setRetryCount(0);
|
||||||
|
entity.setUpdatedAt(LocalDateTime.now());
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static <T> ArgumentCaptor<T> captorOf(Class<?> type) {
|
||||||
|
return (ArgumentCaptor<T>) ArgumentCaptor.forClass(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 一批候选只问一次父任务状态() {
|
||||||
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||||
|
.thenReturn(List.of(job(21L, 500L, "PENDING"), job(22L, 500L, "PENDING"), job(23L, 501L, "FAILED")));
|
||||||
|
when(taskFileJobMapper.selectTerminalFileTaskIds(any(), any())).thenReturn(List.of(500L));
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1, 1, 1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any()))
|
||||||
|
.thenReturn(List.of(job(21L, 500L, "RUNNING"), job(22L, 500L, "RUNNING"), job(23L, 501L, "RUNNING")));
|
||||||
|
|
||||||
|
List<TaskFileJobEntity> claimed = service.claimRunnableJobs(10);
|
||||||
|
|
||||||
|
assertEquals(3, claimed.size());
|
||||||
|
ArgumentCaptor<Collection<Long>> ids = captorOf(Collection.class);
|
||||||
|
ArgumentCaptor<Collection<String>> statuses = captorOf(Collection.class);
|
||||||
|
verify(taskFileJobMapper, times(1)).selectTerminalFileTaskIds(ids.capture(), statuses.capture());
|
||||||
|
assertEquals(List.of(500L, 501L), List.copyOf(ids.getValue()),
|
||||||
|
"同一父任务的多个作业必须去重后一次问回;出现两次以上调用就是退回逐行点查");
|
||||||
|
verify(taskFileJobMapper, never()).selectFileTaskStatus(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 终态值域的唯一正本仍是 {@code TaskStatuses}:它作为参数进 SQL,XML 里不许抄第二份字符串。 */
|
||||||
|
@Test
|
||||||
|
void 终态值域取自词表单点() {
|
||||||
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||||
|
.thenReturn(List.of(job(21L, 500L, "PENDING")));
|
||||||
|
when(taskFileJobMapper.selectTerminalFileTaskIds(any(), any())).thenReturn(List.of());
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any())).thenReturn(List.of(job(21L, 500L, "RUNNING")));
|
||||||
|
|
||||||
|
service.claimRunnableJobs(10);
|
||||||
|
|
||||||
|
ArgumentCaptor<Collection<String>> statuses = captorOf(Collection.class);
|
||||||
|
verify(taskFileJobMapper).selectTerminalFileTaskIds(any(), statuses.capture());
|
||||||
|
assertEquals(TaskStatuses.FileTask.TERMINAL, Set.copyOf(statuses.getValue()),
|
||||||
|
"批量档的终态值域必须逐字等于 TaskStatuses.FileTask.TERMINAL");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 空候选不发批量查() {
|
||||||
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||||
|
|
||||||
|
assertEquals(List.of(), service.claimRunnableJobs(10));
|
||||||
|
|
||||||
|
verify(taskFileJobMapper, never()).selectTerminalFileTaskIds(any(), any());
|
||||||
|
verify(taskFileJobMapper, never()).selectFileTaskStatus(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查不到行的 taskId(品牌任务的 job)按非终态走,与单条档「返回 null ⇒ 非终态」逐字同语义。 */
|
||||||
|
@Test
|
||||||
|
void 查不到行的任务照常被认领() {
|
||||||
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||||
|
.thenReturn(List.of(job(31L, 900L, "PENDING")));
|
||||||
|
when(taskFileJobMapper.selectTerminalFileTaskIds(any(), any())).thenReturn(List.of());
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any())).thenReturn(List.of(job(31L, 900L, "RUNNING")));
|
||||||
|
|
||||||
|
List<TaskFileJobEntity> claimed = service.claimRunnableJobs(10);
|
||||||
|
|
||||||
|
assertEquals(1, claimed.size());
|
||||||
|
assertEquals("RUNNING", claimed.get(0).getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 补检批量档的空入参不发SQL() {
|
||||||
|
assertEquals(Set.of(), service.taskIdsWithUnfinishedAssembleJob(List.of()));
|
||||||
|
assertEquals(Set.of(), service.taskIdsWithUnfinishedAssembleJob(null));
|
||||||
|
assertEquals(Set.of(), TaskFileJobBatchQueries.terminalOwningTaskIds(taskFileJobMapper, List.of()));
|
||||||
|
assertEquals(Set.of(), TaskFileJobBatchQueries.terminalOwningTaskIds(taskFileJobMapper, null));
|
||||||
|
|
||||||
|
verify(taskFileJobMapper, never()).selectList(any(LambdaQueryWrapper.class));
|
||||||
|
verify(taskFileJobMapper, never()).selectTerminalFileTaskIds(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量档与它替代的单条档必须同判据:同一 jobType、同两个未终态状态。
|
||||||
|
* 分叉的形状是「批量档少筛一项」=把已完成的作业也当成在补检,续跑会被永久饿死。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void 补检批量档与单条档判据同源() {
|
||||||
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||||
|
.thenReturn(List.of(job(41L, 700L, "PENDING")));
|
||||||
|
|
||||||
|
assertEquals(Set.of(700L), service.taskIdsWithUnfinishedAssembleJob(List.of(700L, 701L)));
|
||||||
|
|
||||||
|
ArgumentCaptor<LambdaQueryWrapper<TaskFileJobEntity>> captured = captorOf(LambdaQueryWrapper.class);
|
||||||
|
verify(taskFileJobMapper).selectList(captured.capture());
|
||||||
|
// MP 把参数装配推迟到生成 SQL 那一刻;不先取一次 sqlSegment,paramNameValuePairs 是空的。
|
||||||
|
String where = captured.getValue().getSqlSegment();
|
||||||
|
assertTrue(where.contains("task_id IN") || where.contains("task_id in"),
|
||||||
|
"批量档必须按 task_id 一整批问,实参段=" + where);
|
||||||
|
java.util.Set<Object> values = new java.util.HashSet<>();
|
||||||
|
for (Object value : captured.getValue().getParamNameValuePairs().values()) {
|
||||||
|
if (value instanceof java.util.Collection<?> nested) {
|
||||||
|
values.addAll(nested);
|
||||||
|
} else {
|
||||||
|
values.add(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(values.contains("ASSEMBLE_RESULT"), "批量档必须仍按 ASSEMBLE_RESULT 过滤,实参=" + values + " sql=" + where);
|
||||||
|
assertTrue(values.contains("PENDING") && values.contains("RUNNING"),
|
||||||
|
"批量档必须仍只看 PENDING/RUNNING 两态,实参=" + values);
|
||||||
|
assertTrue(values.contains(700L) && values.contains(701L),
|
||||||
|
"批量档必须把这批 taskId 一起带进 IN,实参=" + values);
|
||||||
|
assertTrue(String.valueOf(captured.getValue().getSqlSelect()).contains("task_id"),
|
||||||
|
"批量档只取 task_id 投影,别把整行拉回来");
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
@@ -17,6 +17,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
|||||||
import org.springframework.context.ApplicationEventPublisher;
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
@@ -222,4 +223,107 @@ class TaskFileJobOwnerHandOffTest {
|
|||||||
|
|
||||||
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 卡死扫描的归属守卫(B74-02,同一「两处各读各的」家族) ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_归属谓词只在两侧都非空且不相等时成立() {
|
||||||
|
assertTrue(TaskFileJobService.belongsToAnotherInstance(STALE_OWNER, TASK_OWNER));
|
||||||
|
assertFalse(TaskFileJobService.belongsToAnotherInstance(TASK_OWNER, TASK_OWNER),
|
||||||
|
"自己的行必须照旧被扫——关掉守卫等于把唯一能回收遗骸的通道一起关死");
|
||||||
|
assertFalse(TaskFileJobService.belongsToAnotherInstance(null, TASK_OWNER),
|
||||||
|
"老行/未领取行没有 owner 段,不得被守卫永久排除在外");
|
||||||
|
assertFalse(TaskFileJobService.belongsToAnotherInstance(" ", TASK_OWNER));
|
||||||
|
assertFalse(TaskFileJobService.belongsToAnotherInstance(STALE_OWNER, null),
|
||||||
|
"本机 id 未知(单实例部署、元数据缺失、后管人工复位)时守卫整体不启用");
|
||||||
|
assertFalse(TaskFileJobService.belongsToAnotherInstance(STALE_OWNER, " "));
|
||||||
|
assertTrue(TaskFileJobService.belongsToAnotherInstance(" " + STALE_OWNER + " ", TASK_OWNER),
|
||||||
|
"两侧都要 trim:owner 段带空白是 scope_key 拼接的既有形状");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_卡死扫描不得翻另一实例正在跑的作业() {
|
||||||
|
TaskFileJobEntity foreignRunning = job(23784L, 33149L, "RUNNING", STALE_OWNER);
|
||||||
|
foreignRunning.setStuckRequeueCount(20);
|
||||||
|
when(taskFileJobMapper.selectList(any())).thenReturn(List.of(foreignRunning));
|
||||||
|
|
||||||
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
|
service.resetStuckRunningJobsDetailed(5, 10, TASK_OWNER);
|
||||||
|
|
||||||
|
assertEquals(0, result.resetCount());
|
||||||
|
assertTrue(result.exhaustedJobs().isEmpty(),
|
||||||
|
"到 20 的行也不得由非归属机判死:兜底出表只在归属机跑得动,先判死就把还能补传的单钉死了");
|
||||||
|
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||||
|
verify(applicationEventPublisher, never()).publishEvent(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_卡死扫描仍必须翻自己的陈旧作业() {
|
||||||
|
TaskFileJobEntity ownRunning = job(23784L, 33149L, "RUNNING", TASK_OWNER);
|
||||||
|
ownRunning.setStuckRequeueCount(3);
|
||||||
|
when(taskFileJobMapper.selectList(any())).thenReturn(List.of(ownRunning));
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any())).thenReturn(List.of(ownRunning));
|
||||||
|
|
||||||
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
|
service.resetStuckRunningJobsDetailed(5, 10, TASK_OWNER);
|
||||||
|
|
||||||
|
assertEquals(1, result.resetCount());
|
||||||
|
verify(applicationEventPublisher).publishEvent(any(TaskFileJobDispatchEvent.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_不带实例id的扫描入口保持原行为_人工复位不受守卫() {
|
||||||
|
TaskFileJobEntity foreignRunning = job(23784L, 33149L, "RUNNING", STALE_OWNER);
|
||||||
|
when(taskFileJobMapper.selectList(any())).thenReturn(List.of(foreignRunning));
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any())).thenReturn(List.of(foreignRunning));
|
||||||
|
|
||||||
|
TaskFileJobService.StuckJobResetResult result = service.resetStuckRunningJobsDetailed(5, 10);
|
||||||
|
|
||||||
|
assertEquals(1, result.resetCount(),
|
||||||
|
"后管那枚人工复位按钮点的就是「把它排回去」,不得被归属守卫悄悄拒掉");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== B74-02 本机执行活性豁免(与上面「他机在跑」是同一判据的两半) ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_本机正在执行的作业不得被卡死扫描重排或判死() {
|
||||||
|
// 现网形状:2026-11-03 jobId=23815/taskId=33179 在 06:07:20 到 stuckRequeueCount=20,
|
||||||
|
// 而执行线程一直在跑——父任务终态后心跳按 CR-08 刻意停续期,updated_at 从此无限期冻结,
|
||||||
|
// 扫描只看时间戳就每 5 分钟扣一次计数。抬阈值救不了它(冻结不是「比 5 分钟长一点」)。
|
||||||
|
TaskFileJobEntity ownRunning = job(23815L, 33179L, "RUNNING", TASK_OWNER);
|
||||||
|
ownRunning.setStuckRequeueCount(20);
|
||||||
|
when(taskFileJobMapper.selectList(any())).thenReturn(List.of(ownRunning));
|
||||||
|
|
||||||
|
service.markInFlight(23815L);
|
||||||
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
|
service.resetStuckRunningJobsDetailed(5, 10, TASK_OWNER);
|
||||||
|
|
||||||
|
assertEquals(0, result.resetCount());
|
||||||
|
assertTrue(result.exhaustedJobs().isEmpty(),
|
||||||
|
"线程还在跑就不许把它判死:判死后 markSuccess 的 .eq(status,RUNNING) 会丢掉成功状态");
|
||||||
|
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||||
|
verify(applicationEventPublisher, never()).publishEvent(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_注销之后同一行必须回到可回收形状() {
|
||||||
|
// 登记面必须是"线程在跑期间"这一有界区间:漏注销=这行永远不被回收,遗骸比误判更贵。
|
||||||
|
TaskFileJobEntity ownRunning = job(23815L, 33179L, "RUNNING", TASK_OWNER);
|
||||||
|
ownRunning.setStuckRequeueCount(3);
|
||||||
|
when(taskFileJobMapper.selectList(any())).thenReturn(List.of(ownRunning));
|
||||||
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||||
|
when(taskFileJobMapper.selectBatchIds(any())).thenReturn(List.of(ownRunning));
|
||||||
|
|
||||||
|
service.markInFlight(23815L);
|
||||||
|
service.clearInFlight(23815L);
|
||||||
|
assertFalse(service.isInFlight(23815L));
|
||||||
|
|
||||||
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
|
service.resetStuckRunningJobsDetailed(5, 10, TASK_OWNER);
|
||||||
|
|
||||||
|
assertEquals(1, result.resetCount(), "注销后必须照旧被回收,活性豁免不是豁免的通行证");
|
||||||
|
assertEquals(0, service.inFlightCount());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -107,8 +107,8 @@ class TaskFileJobTerminalTaskGuardTest {
|
|||||||
TaskFileJobEntity active = job(22L, 501L);
|
TaskFileJobEntity active = job(22L, 501L);
|
||||||
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
when(taskFileJobMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||||
.thenReturn(List.of(terminal, active));
|
.thenReturn(List.of(terminal, active));
|
||||||
when(taskFileJobMapper.selectFileTaskStatus(500L)).thenReturn("FAILED");
|
// P1-B6:claim 循环的父任务状态改为一次批量档(500=500L 已终态)。
|
||||||
when(taskFileJobMapper.selectFileTaskStatus(501L)).thenReturn("RUNNING");
|
when(taskFileJobMapper.selectTerminalFileTaskIds(any(), any())).thenReturn(List.of(500L));
|
||||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1, 1);
|
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1, 1);
|
||||||
TaskFileJobEntity claimedTerminal = job(21L, 500L);
|
TaskFileJobEntity claimedTerminal = job(21L, 500L);
|
||||||
claimedTerminal.setStatus("RUNNING");
|
claimedTerminal.setStatus("RUNNING");
|
||||||
|
|||||||
+232
@@ -0,0 +1,232 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.data.redis.core.HashOperations;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 活性谓词三出口的「现状」快照(流程稳定性蓝图 P0-C2,2026-11-03)。
|
||||||
|
*
|
||||||
|
* <p>{@link TaskHeartbeatPositionService#evaluateStall} 是封口/判死前的唯一豁免闸:
|
||||||
|
* {@code ADVANCING}(仍在推进,不得封口)、{@code STALLED}(真卡死)、{@code UNKNOWN}
|
||||||
|
* (没有豁免依据,调用方保留原判据——它<b>不是</b>判死证据)。本类照快收四个事实:</p>
|
||||||
|
* <ul>
|
||||||
|
* <li>三出口的触发形状(指纹变 / 超窗 / 无位置或读失败);</li>
|
||||||
|
* <li>「未变化起点」只在指纹变化时重写——豁免窗口内的重读<b>不得</b>刷新起点,
|
||||||
|
* 否则真卡死永远到不了 {@code STALLED};</li>
|
||||||
|
* <li>B74-03 的病灶现状:快照存在但时间戳读不出({@code at} 不可解析 ⇒
|
||||||
|
* {@code unchangedSince<=0})时,与「指纹变了」共用 {@code ADVANCING} 出口。
|
||||||
|
* Phase 2 收口改分流后本格翻红属预期,按新口径改写并登记,不许静默;</li>
|
||||||
|
* <li>影子判官写独立键({@code shadow-stall}),指纹含计数/阶段,且<b>不得</b>触碰
|
||||||
|
* 正式线的快照键(影子的观测时刻不得改变正式线的未变化起点)。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
class TaskHeartbeatPositionStallExitsSnapshotTest {
|
||||||
|
|
||||||
|
private static final String POSITION_KEY = "task:heartbeat:position:7";
|
||||||
|
private static final String STALL_KEY = "task:progress:stall:7";
|
||||||
|
private static final String SHADOW_KEY = "task:progress:shadow-stall:7";
|
||||||
|
|
||||||
|
private final StringRedisTemplate redis = mock(StringRedisTemplate.class);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private final HashOperations<String, Object, Object> hash = mock(HashOperations.class);
|
||||||
|
private final TaskHeartbeatPositionService service = new TaskHeartbeatPositionService(redis);
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void wire() {
|
||||||
|
when(redis.opsForHash()).thenReturn((HashOperations) hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<Object, Object> stallSnapshot(String pos, long unchangedSinceMillis) {
|
||||||
|
Map<Object, Object> stored = new HashMap<>();
|
||||||
|
if (pos != null) {
|
||||||
|
stored.put("pos", pos);
|
||||||
|
}
|
||||||
|
if (unchangedSinceMillis > 0) {
|
||||||
|
stored.put("at", String.valueOf(unchangedSinceMillis));
|
||||||
|
}
|
||||||
|
return stored;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void givenPositionText(String text) {
|
||||||
|
Map<Object, Object> position = new HashMap<>();
|
||||||
|
position.put("progressText", text);
|
||||||
|
position.put("at", String.valueOf(Instant.now().toEpochMilli()));
|
||||||
|
when(hash.entries(POSITION_KEY)).thenReturn(position);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 无位置信息与非法窗口一律_UNKNOWN_不得作为判死证据() {
|
||||||
|
when(hash.entries(POSITION_KEY)).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("心跳位置全空 ⇒ UNKNOWN:调用方保留原判据,位置缺失本身不是证据")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
assertThat(service.evaluateStall(null, 30L)).isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
assertThat(service.evaluateStall(7L, 0L)).isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
assertThat(service.evaluateStall(7L, -1L)).isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 指纹变化_重写快照并放行_ADVANCING() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY)).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("首次观测(无快照)=指纹变了这一侧 ⇒ 放行并落快照")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
verify(hash).putAll(eq(STALL_KEY), any());
|
||||||
|
verify(redis).expire(eq(STALL_KEY), any(Duration.class));
|
||||||
|
|
||||||
|
givenPositionText("正在抓取第 4 页");
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("文本变了就是主线程在干活:分片只是攒着没回传,不得封口")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
verify(redis, org.mockito.Mockito.times(2)).expire(eq(STALL_KEY), any(Duration.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 未变化但在豁免窗口内_ADVANCING_且不得重写快照() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY))
|
||||||
|
.thenReturn(stallSnapshot("正在抓取第 3 页", Instant.now().toEpochMilli() - Duration.ofMinutes(2).toMillis()));
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("未变化起点之后 2 分钟,30 分钟的豁免窗口远未走完 ⇒ 放行")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
verify(hash, never()).putAll(anyString(), any());
|
||||||
|
verify(redis, never()).expire(anyString(), any(Duration.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 未变化超过停滞窗口_STALLED() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY))
|
||||||
|
.thenReturn(stallSnapshot("正在抓取第 3 页", Instant.now().toEpochMilli() - Duration.ofMinutes(31).toMillis()));
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("同一指纹持续超过 staleWindowMinutes ⇒ 真卡死,封口/判死线可以行动")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.STALLED);
|
||||||
|
verify(hash, never()).putAll(anyString(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 快照存在但时间戳读不出_现状与指纹变化共用_ADVANCING_出口_B74_03病灶快照() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY)).thenReturn(stallSnapshot("正在抓取第 3 页", 0L));
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("B74-03 现状:快照在、`at` 读不出(unchangedSince<=0)时按「指纹变了」处理"
|
||||||
|
+ "(重写起点 + 放行)。Phase 2 分流改判后本格翻红属预期,更新即登记")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
verify(hash).putAll(eq(STALL_KEY), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void Redis读异常一律_UNKNOWN_读不到不许当证据() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY)).thenThrow(new IllegalStateException("redis down"));
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("快照读失败 ≠ 卡死证据:UNKNOWN 让调用方退回原判据")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
verify(hash, never()).putAll(anyString(), any());
|
||||||
|
|
||||||
|
when(hash.entries(anyString())).thenThrow(new IllegalStateException("redis down"));
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("连位置读都失败时同样 UNKNOWN")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.UNKNOWN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 影子线独立键_指纹含计数_且不触碰正式快照键() {
|
||||||
|
Map<Object, Object> position = new HashMap<>();
|
||||||
|
position.put("progressText", "长页面滚动中");
|
||||||
|
position.put("current", "5");
|
||||||
|
position.put("total", "10");
|
||||||
|
position.put("grain", "units");
|
||||||
|
position.put("at", String.valueOf(Instant.now().toEpochMilli()));
|
||||||
|
when(hash.entries(POSITION_KEY)).thenReturn(position);
|
||||||
|
when(hash.entries(SHADOW_KEY)).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
assertThat(service.evaluateProgressForShadow(7L, 30L))
|
||||||
|
.as("影子观测落独立键并放行")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
org.mockito.ArgumentCaptor<Map<String, String>> written =
|
||||||
|
org.mockito.ArgumentCaptor.forClass((Class) Map.class);
|
||||||
|
verify(hash).putAll(eq(SHADOW_KEY), written.capture());
|
||||||
|
assertThat(written.getValue().get("pos"))
|
||||||
|
.as("影子指纹 = grain|current|total|text:计数变了也是推进(长页面里文本可能长时间不变)")
|
||||||
|
.isEqualTo("units|5|10|长页面滚动中");
|
||||||
|
verify(hash, never()).putAll(eq(STALL_KEY), any());
|
||||||
|
verify(redis, org.mockito.Mockito.never()).expire(eq(STALL_KEY), any(Duration.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== B74-03 分流(2026-11-03 按现网取证改判;更新即登记,不静默) ====================
|
||||||
|
|
||||||
|
private void givenPositionTextAt(String text, long reportedAtMillis) {
|
||||||
|
Map<Object, Object> position = new HashMap<>();
|
||||||
|
position.put("progressText", text);
|
||||||
|
position.put("at", String.valueOf(reportedAtMillis));
|
||||||
|
when(hash.entries(POSITION_KEY)).thenReturn(position);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 停滞快照缺失但客户端已沉默超窗_不得再白送一轮豁免() {
|
||||||
|
// 现网形状(2026-11-02 任务 33179):本键 TTL = max(60, window×3) = 9 小时,键一消失
|
||||||
|
// 旧代码就把起点重锚到 now 并直接放行,于是每 9 小时白送一轮完整豁免窗口,沉默的客户端永远封不了口。
|
||||||
|
long anchor = Instant.now().toEpochMilli() - Duration.ofMinutes(40).toMillis();
|
||||||
|
givenPositionTextAt("正在抓取第 3 页", anchor);
|
||||||
|
when(hash.entries(STALL_KEY)).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("键消失只是没人记账,不等于「证据表明在推进」;最后一次上报已在 30 分钟窗口外 ⇒ STALLED")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.STALLED);
|
||||||
|
|
||||||
|
org.mockito.ArgumentCaptor<Map<String, String>> written =
|
||||||
|
org.mockito.ArgumentCaptor.forClass((Class) Map.class);
|
||||||
|
verify(hash).putAll(eq(STALL_KEY), written.capture());
|
||||||
|
assertThat(written.getValue().get("at"))
|
||||||
|
.as("重建的锚点必须锚到客户端最后一次上报时刻;锚到 now 就是每轮重发免死牌")
|
||||||
|
.isEqualTo(String.valueOf(anchor));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 快照在而时间戳读不出_走同一条时间判据_不再借用真进展出口() {
|
||||||
|
long anchor = Instant.now().toEpochMilli() - Duration.ofMinutes(45).toMillis();
|
||||||
|
givenPositionTextAt("正在抓取第 3 页", anchor);
|
||||||
|
when(hash.entries(STALL_KEY)).thenReturn(stallSnapshot("正在抓取第 3 页", 0L));
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("`at` 读不出(管道/事务态)与「指纹变了」共用出口就是 B74-03 的病灶本体;"
|
||||||
|
+ "分流后两种形状都必须落到真实沉默时长上")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.STALLED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 客户端仍在心跳时锚点重建照旧放行_分流不得把判死线提前() {
|
||||||
|
givenPositionText("正在抓取第 3 页");
|
||||||
|
when(hash.entries(STALL_KEY)).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
assertThat(service.evaluateStall(7L, 30L))
|
||||||
|
.as("分流只吃掉「白送的豁免」:客户端刚刚上报过 ⇒ 锚点就是新鲜的,仍判 ADVANCING。"
|
||||||
|
+ "把仍在采集的任务判死会丢整批分片(28919 教训写在 isClientAdvancing 注释上)")
|
||||||
|
.isEqualTo(TaskHeartbeatPositionService.StallState.ADVANCING);
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -70,6 +70,47 @@ class TaskOwnerReadSourceGuardrailTest {
|
|||||||
// 真正不允许的是反过来——只读快照,那正是相似ASIN 与发布当时的形状。
|
// 真正不允许的是反过来——只读快照,那正是相似ASIN 与发布当时的形状。
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B74-04 的另一半尺子:上面那支只钉住「列优先」,没钉「列缺失时读哪枚 JSON」。
|
||||||
|
*
|
||||||
|
* <p>四台此前各有写法——三台回落 result_json、店铺采集回落 request_json,列缺失的存量行
|
||||||
|
* (实测 RUNNING 里 39 行)在不同校验里算出不同归属。回落顺序现在只有
|
||||||
|
* {@code TaskOwnerJsonFallback} 一个出处:任何一台改回本地读法,本格即红。
|
||||||
|
*/
|
||||||
|
@ParameterizedTest(name = "{0} 的任务归属回落必须走唯一出处")
|
||||||
|
@CsvSource({
|
||||||
|
"AppearancePatentTaskOwnership.java",
|
||||||
|
"SimilarAsinTaskOwnershipSupport.java",
|
||||||
|
"PublishTaskService.java",
|
||||||
|
"ShopDataCrawlTaskService.java",
|
||||||
|
})
|
||||||
|
void fallbackMustDelegateToOneSharedSource(String fileName) {
|
||||||
|
String source = SourceScan.withoutComments(SourceScan.sourceText(fileName));
|
||||||
|
|
||||||
|
assertThat(source)
|
||||||
|
.as(fileName + " 不得再有本地的任务归属 JSON 回落写法(result_json 侧)")
|
||||||
|
.doesNotContain("readTree(task.getResultJson()).path(\"ownerInstanceId\")");
|
||||||
|
assertThat(source)
|
||||||
|
.as(fileName + " 不得再有本地的任务归属 JSON 回落写法(request_json 侧)")
|
||||||
|
.doesNotContain("readTree(task.getRequestJson()).path(\"ownerInstanceId\")");
|
||||||
|
assertThat(source)
|
||||||
|
.as(fileName + " 必须经 TaskOwnerJsonFallback 读回落,四台共用同一个顺序")
|
||||||
|
.contains("TaskOwnerJsonFallback.ownerFrom(");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 回落顺序在唯一出处里钉死_result_json_先于_request_json() {
|
||||||
|
String source = SourceScan.withoutComments(SourceScan.sourceText("TaskOwnerJsonFallback.java"));
|
||||||
|
int resultRead = source.indexOf("task.getResultJson()");
|
||||||
|
int requestRead = source.indexOf("task.getRequestJson()");
|
||||||
|
|
||||||
|
assertThat(resultRead).as("正档必须真的读 result_json").isGreaterThan(-1);
|
||||||
|
assertThat(requestRead).as("提交快照仍作次档(列与正档都没写上时还得兜住)").isGreaterThan(-1);
|
||||||
|
assertThat(resultRead)
|
||||||
|
.as("result_json 必须先于 request_json:它是 parse/交付快照,request_json 是提交时最旧的一手")
|
||||||
|
.isLessThan(requestRead);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void 转交作业的目标实例必须来自异常携带的任务当前_owner() {
|
void 转交作业的目标实例必须来自异常携带的任务当前_owner() {
|
||||||
String source = SourceScan.withoutComments(SourceScan.sourceText("TaskResultFileJobWorker.java"));
|
String source = SourceScan.withoutComments(SourceScan.sourceText("TaskResultFileJobWorker.java"));
|
||||||
|
|||||||
+2
-1
@@ -44,6 +44,7 @@ import java.util.List;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.doThrow;
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
@@ -173,7 +174,7 @@ class TaskResultFileJobWorkerFailureNotifyTest {
|
|||||||
job.setErrorMessage("文件生成任务运行超时,已达到最大重试次数");
|
job.setErrorMessage("文件生成任务运行超时,已达到最大重试次数");
|
||||||
TaskFileJobService.StuckJobResetResult resetResult =
|
TaskFileJobService.StuckJobResetResult resetResult =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(resetResult);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(resetResult);
|
||||||
doThrow(new IllegalStateException("owner mismatch"))
|
doThrow(new IllegalStateException("owner mismatch"))
|
||||||
.when(similar).handleResultFileJobFailure(any(), anyString());
|
.when(similar).handleResultFileJobFailure(any(), anyString());
|
||||||
|
|
||||||
|
|||||||
+72
-16
@@ -30,6 +30,7 @@ import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
|||||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||||
import com.nanri.aiimage.modules.withdraw.service.WithdrawTaskService;
|
import com.nanri.aiimage.modules.withdraw.service.WithdrawTaskService;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.InOrder;
|
||||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
import org.springframework.context.event.EventListener;
|
import org.springframework.context.event.EventListener;
|
||||||
|
|
||||||
@@ -52,6 +53,7 @@ import static org.mockito.ArgumentMatchers.contains;
|
|||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.after;
|
import static org.mockito.Mockito.after;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.timeout;
|
import static org.mockito.Mockito.timeout;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
@@ -126,11 +128,11 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
setInt(worker, "batchSize", 30);
|
setInt(worker, "batchSize", 30);
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(2, List.of());
|
new TaskFileJobService.StuckJobResetResult(2, List.of());
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(45, 30)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(45), eq(30), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
verify(taskFileJobService).resetStuckRunningJobsDetailed(45, 30);
|
verify(taskFileJobService).resetStuckRunningJobsDetailed(eq(45), eq(30), anyString());
|
||||||
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +142,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(1L, 11L, null);
|
TaskFileJobEntity job = exhaustedJob(1L, 11L, null);
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -154,7 +156,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(2L, 12L, " ");
|
TaskFileJobEntity job = exhaustedJob(2L, 12L, " ");
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -168,7 +170,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(3L, 13L, "上游 API 限流,重试耗尽");
|
TaskFileJobEntity job = exhaustedJob(3L, 13L, "上游 API 限流,重试耗尽");
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -182,7 +184,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(4L, 14L, null);
|
TaskFileJobEntity job = exhaustedJob(4L, 14L, null);
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -196,11 +198,11 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskResultFileJobWorker worker = buildWorker();
|
TaskResultFileJobWorker worker = buildWorker();
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of());
|
new TaskFileJobService.StuckJobResetResult(0, List.of());
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
verify(taskFileJobService).resetStuckRunningJobsDetailed(0, 0);
|
verify(taskFileJobService).resetStuckRunningJobsDetailed(eq(0), eq(0), anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -208,11 +210,11 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskResultFileJobWorker worker = buildWorker();
|
TaskResultFileJobWorker worker = buildWorker();
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of());
|
new TaskFileJobService.StuckJobResetResult(0, List.of());
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
verify(taskFileJobService).resetStuckRunningJobsDetailed(0, 0);
|
verify(taskFileJobService).resetStuckRunningJobsDetailed(eq(0), eq(0), anyString());
|
||||||
verify(similar, never()).handleResultFileJobFailure(any(), anyString());
|
verify(similar, never()).handleResultFileJobFailure(any(), anyString());
|
||||||
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
||||||
}
|
}
|
||||||
@@ -223,13 +225,13 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(5L, 15L, null);
|
TaskFileJobEntity job = exhaustedJob(5L, 15L, null);
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0))
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString()))
|
||||||
.thenReturn(result, new TaskFileJobService.StuckJobResetResult(0, List.of()));
|
.thenReturn(result, new TaskFileJobService.StuckJobResetResult(0, List.of()));
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
verify(taskFileJobService, times(2)).resetStuckRunningJobsDetailed(0, 0);
|
verify(taskFileJobService, times(2)).resetStuckRunningJobsDetailed(eq(0), eq(0), anyString());
|
||||||
verify(taskFileJobService).markFailureFinalized(5L, "文件生成任务运行超时,已达到最大重试次数");
|
verify(taskFileJobService).markFailureFinalized(5L, "文件生成任务运行超时,已达到最大重试次数");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,7 +241,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity job = exhaustedJob(6L, 16L, null);
|
TaskFileJobEntity job = exhaustedJob(6L, 16L, null);
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
org.mockito.Mockito.doThrow(new IllegalStateException("db down"))
|
org.mockito.Mockito.doThrow(new IllegalStateException("db down"))
|
||||||
.when(similar).handleResultFileJobFailure(job, "文件生成任务运行超时,已达到最大重试次数");
|
.when(similar).handleResultFileJobFailure(job, "文件生成任务运行超时,已达到最大重试次数");
|
||||||
|
|
||||||
@@ -255,7 +257,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
TaskFileJobEntity second = exhaustedJob(8L, 18L, "超时");
|
TaskFileJobEntity second = exhaustedJob(8L, 18L, "超时");
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(first, second));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(first, second));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -298,7 +300,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
job.setModuleType("UNKNOWN_X");
|
job.setModuleType("UNKNOWN_X");
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -528,7 +530,7 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
job.setScopeKey("appearance-patent:19:owner:instance-b");
|
job.setScopeKey("appearance-patent:19:owner:instance-b");
|
||||||
TaskFileJobService.StuckJobResetResult result =
|
TaskFileJobService.StuckJobResetResult result =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(result);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(result);
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
|
|
||||||
@@ -536,6 +538,60 @@ class TaskResultFileJobWorkerStuckScanTest {
|
|||||||
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
verify(taskFileJobService, never()).markFailureFinalized(any(), anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B74-02 活性登记的半边判据:登记必须在 {@code activateRunningClaim} 成功之后、执行之前,
|
||||||
|
* 注销必须在 finally——顺序反了要么把没跑起来的行登记成在飞(永不可回收),要么让还在跑的行
|
||||||
|
* 被扫描扣计数(现网 jobId=23815/taskId=33179 的形状)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void test_执行线程在跑期间登记在飞且退出必注销() throws Exception {
|
||||||
|
TaskResultFileJobWorker worker = buildWorker();
|
||||||
|
TaskFileJobEntity job = runningJob(91L, 19L, "SIMILAR_ASIN");
|
||||||
|
TaskFileJobEntity claim = runningJob(91L, 19L, "SIMILAR_ASIN");
|
||||||
|
claim.setUpdatedAt(LocalDateTime.now());
|
||||||
|
when(taskFileJobService.activateRunningClaim(claim)).thenReturn(true);
|
||||||
|
|
||||||
|
invokeProcessClaimedWithHeartbeat(worker, job, claim);
|
||||||
|
|
||||||
|
InOrder inOrder = inOrder(taskFileJobService);
|
||||||
|
inOrder.verify(taskFileJobService).activateRunningClaim(claim);
|
||||||
|
inOrder.verify(taskFileJobService).markInFlight(91L);
|
||||||
|
inOrder.verify(taskFileJobService).clearInFlight(91L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test_claim已过期时不得登记在飞() throws Exception {
|
||||||
|
// 队里的 claim 在执行前就过期(行已被扫描翻走)——这一行不归本机跑,登记它等于永久豁免。
|
||||||
|
TaskResultFileJobWorker worker = buildWorker();
|
||||||
|
TaskFileJobEntity job = runningJob(92L, 20L, "SIMILAR_ASIN");
|
||||||
|
TaskFileJobEntity claim = runningJob(92L, 20L, "SIMILAR_ASIN");
|
||||||
|
claim.setUpdatedAt(LocalDateTime.now());
|
||||||
|
when(taskFileJobService.activateRunningClaim(claim)).thenReturn(false);
|
||||||
|
|
||||||
|
invokeProcessClaimedWithHeartbeat(worker, job, claim);
|
||||||
|
|
||||||
|
verify(taskFileJobService, never()).markInFlight(92L);
|
||||||
|
verify(taskFileJobService, never()).clearInFlight(92L);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TaskFileJobEntity runningJob(Long id, Long taskId, String moduleType) {
|
||||||
|
TaskFileJobEntity entity = new TaskFileJobEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setTaskId(taskId);
|
||||||
|
entity.setModuleType(moduleType);
|
||||||
|
entity.setStatus("RUNNING");
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void invokeProcessClaimedWithHeartbeat(TaskResultFileJobWorker worker,
|
||||||
|
TaskFileJobEntity job,
|
||||||
|
TaskFileJobEntity claim) throws Exception {
|
||||||
|
java.lang.reflect.Method method = TaskResultFileJobWorker.class.getDeclaredMethod(
|
||||||
|
"processClaimedWithHeartbeat", TaskFileJobEntity.class, TaskFileJobEntity.class);
|
||||||
|
method.setAccessible(true);
|
||||||
|
method.invoke(worker, job, claim);
|
||||||
|
}
|
||||||
|
|
||||||
private static void setLong(TaskResultFileJobWorker worker, String fieldName, long value) throws Exception {
|
private static void setLong(TaskResultFileJobWorker worker, String fieldName, long value) throws Exception {
|
||||||
Field field = TaskResultFileJobWorker.class.getDeclaredField(fieldName);
|
Field field = TaskResultFileJobWorker.class.getDeclaredField(fieldName);
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
|||||||
+4
-3
@@ -35,6 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
|||||||
|
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.inOrder;
|
import static org.mockito.Mockito.inOrder;
|
||||||
import static org.mockito.Mockito.doThrow;
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.lenient;
|
import static org.mockito.Mockito.lenient;
|
||||||
@@ -220,7 +221,7 @@ class TaskResultFileJobWorkerTest {
|
|||||||
job.setErrorMessage("文件生成任务运行超时,已达到最大重试次数");
|
job.setErrorMessage("文件生成任务运行超时,已达到最大重试次数");
|
||||||
TaskFileJobService.StuckJobResetResult resetResult =
|
TaskFileJobService.StuckJobResetResult resetResult =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(resetResult);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(resetResult);
|
||||||
stubSimilarAsinRegistry();
|
stubSimilarAsinRegistry();
|
||||||
|
|
||||||
worker.resetStuckJobs();
|
worker.resetStuckJobs();
|
||||||
@@ -235,7 +236,7 @@ class TaskResultFileJobWorkerTest {
|
|||||||
TaskFileJobEntity second = exhaustedSimilarAsinJob(13859L, 20554L);
|
TaskFileJobEntity second = exhaustedSimilarAsinJob(13859L, 20554L);
|
||||||
TaskFileJobService.StuckJobResetResult resetResult =
|
TaskFileJobService.StuckJobResetResult resetResult =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(first, second));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(first, second));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0)).thenReturn(resetResult);
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString())).thenReturn(resetResult);
|
||||||
stubSimilarAsinRegistry();
|
stubSimilarAsinRegistry();
|
||||||
doThrow(new IllegalStateException("owner mismatch"))
|
doThrow(new IllegalStateException("owner mismatch"))
|
||||||
.doNothing()
|
.doNothing()
|
||||||
@@ -255,7 +256,7 @@ class TaskResultFileJobWorkerTest {
|
|||||||
TaskFileJobEntity job = exhaustedSimilarAsinJob(13860L, 20555L);
|
TaskFileJobEntity job = exhaustedSimilarAsinJob(13860L, 20555L);
|
||||||
TaskFileJobService.StuckJobResetResult resetResult =
|
TaskFileJobService.StuckJobResetResult resetResult =
|
||||||
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
new TaskFileJobService.StuckJobResetResult(0, List.of(job));
|
||||||
when(taskFileJobService.resetStuckRunningJobsDetailed(0, 0))
|
when(taskFileJobService.resetStuckRunningJobsDetailed(eq(0), eq(0), anyString()))
|
||||||
.thenReturn(resetResult, resetResult);
|
.thenReturn(resetResult, resetResult);
|
||||||
stubSimilarAsinRegistry();
|
stubSimilarAsinRegistry();
|
||||||
doThrow(new IllegalStateException("temporary database failure"))
|
doThrow(new IllegalStateException("temporary database failure"))
|
||||||
|
|||||||
+208
@@ -0,0 +1,208 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.support.ThreadPools;
|
||||||
|
import com.nanri.aiimage.modules.task.mapper.TaskResultItemMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.TaskResultItemEntity;
|
||||||
|
import com.nanri.aiimage.testutil.SourceScan;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P1-B7:指针化载荷的结果集读取必须**分窗提交并收割**,同时整份一行不许漏。
|
||||||
|
*
|
||||||
|
* <p>来历:审计把 {@code listResultSnapshots} 的「无 limit」记成性能项,但**截断是正确性错误不是性能取舍**
|
||||||
|
* ——调用方(patroldelete/queryasin/shopdatacrawl/withdraw)拿它组装完整结果文件。真正能收的是
|
||||||
|
* 「整份结果集被读两遍」:原先把 N 行一次性交进线程池,每支 Future 完成后把解好的载荷扣在自己身上
|
||||||
|
* ({@code FutureTask.outcome} 不清),而这一整批要到收割完才释放 ⇒ 峰值=结果集+同样多的另一份副本。
|
||||||
|
* 分窗之后副本只驻留一窗。
|
||||||
|
*
|
||||||
|
* <p>判据为什么打在源码上而不是只打行为:窗口效应体现在**堆**上(同时在飞的载荷数),
|
||||||
|
* 线程池本身只有 8 个线程,"同时开始读几行"这个observable 在改前改后都是 ≤8,用 mock 数不出来;
|
||||||
|
* 行为侧能钉住的只有「不漏行、不乱序、异常口径不变」这三件——那些恰恰是拆窗最容易被改坏的地方,
|
||||||
|
* 所以两类都要,缺一个就是半只眼睛。
|
||||||
|
*
|
||||||
|
* <p>反向自证:把窗口改回 {@code for (row : rows) futures.add(submit(...))} 整量一次性提交,
|
||||||
|
* <b>只有源码绊线那一格红</b>(实测 6 例中 1 失败),行为四格照样全绿——窗口化本来就不改可观察行为,
|
||||||
|
* 这恰恰是上面那段「行为侧钉不住它」的实证,不是本类在凑数。
|
||||||
|
*/
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class TaskResultItemReadWindowTest {
|
||||||
|
|
||||||
|
@Mock private TaskResultItemMapper taskResultItemMapper;
|
||||||
|
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||||
|
|
||||||
|
private TaskResultItemService service;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void initializeTableInfo() {
|
||||||
|
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||||
|
TaskResultItemEntity.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
service = new TaskResultItemService(taskResultItemMapper, new ObjectMapper(), transientPayloadStorageService);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 指针化载荷行:payloadJson 只放指针形状,真正的内容由 resolvePayload 现编。 */
|
||||||
|
private static List<TaskResultItemEntity> pointerRows(int count) {
|
||||||
|
List<TaskResultItemEntity> rows = new ArrayList<>(count);
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
TaskResultItemEntity row = new TaskResultItemEntity();
|
||||||
|
row.setId((long) i + 1);
|
||||||
|
row.setTaskId(9001L);
|
||||||
|
row.setModuleType("APPEARANCE_PATENT");
|
||||||
|
row.setResultId((long) i + 1);
|
||||||
|
row.setItemKey("result:" + (i + 1));
|
||||||
|
row.setPayloadJson("pointer-" + i);
|
||||||
|
rows.add(row);
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从指针串里还原行号:让第 i 行的载荷就是 {"n":i},顺序对不对一眼可见。 */
|
||||||
|
private static int indexOfArgument(String pointer) {
|
||||||
|
return Integer.parseInt(pointer.substring("pointer-".length()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 行为:拆窗不许改掉「整份、按序、口径不变」 ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void crossWindowResultIsCompleteAndKeepsRowOrder() {
|
||||||
|
int total = TaskResultItemService.SNAPSHOT_READ_WINDOW * 2 + 3;
|
||||||
|
when(taskResultItemMapper.selectList(any())).thenReturn(pointerRows(total));
|
||||||
|
when(transientPayloadStorageService.extractPointer(anyString())).thenReturn("pointer");
|
||||||
|
when(transientPayloadStorageService.resolvePayload(anyString(), anyString()))
|
||||||
|
.thenAnswer(inv -> "{\"n\":" + indexOfArgument(inv.getArgument(0)) + "}");
|
||||||
|
|
||||||
|
List<Map> out = service.listResultSnapshots(9001L, "APPEARANCE_PATENT", Map.class);
|
||||||
|
|
||||||
|
assertThat(out).as("跨了三个窗口也不能少一行").hasSize(total);
|
||||||
|
for (int i = 0; i < total; i++) {
|
||||||
|
assertThat(out.get(i).get("n")).as("第 " + i + " 行的位置").isEqualTo(i);
|
||||||
|
}
|
||||||
|
verify(transientPayloadStorageService, times(total)).resolvePayload(anyString(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blankPayloadSkipsOnlyThatRowAndDoesNotTruncateTheRest() {
|
||||||
|
int total = TaskResultItemService.SNAPSHOT_READ_WINDOW + 5;
|
||||||
|
List<TaskResultItemEntity> rows = pointerRows(total);
|
||||||
|
rows.get(3).setPayloadJson(""); // 首窗内的一行空载荷
|
||||||
|
rows.get(total - 1).setPayloadJson(" "); // 末窗内的一行空载荷
|
||||||
|
when(taskResultItemMapper.selectList(any())).thenReturn(rows);
|
||||||
|
when(transientPayloadStorageService.extractPointer(anyString())).thenReturn("pointer");
|
||||||
|
when(transientPayloadStorageService.resolvePayload(anyString(), anyString()))
|
||||||
|
.thenAnswer(inv -> "{\"n\":" + indexOfArgument(inv.getArgument(0)) + "}");
|
||||||
|
|
||||||
|
List<Map> out = service.listResultSnapshots(9001L, "APPEARANCE_PATENT", Map.class);
|
||||||
|
|
||||||
|
assertThat(out).as("空载荷只跳这一行,后面的行必须照样来").hasSize(total - 2);
|
||||||
|
assertThat(out).extracting(m -> m.get("n"))
|
||||||
|
.containsExactlyElementsOf(rows.stream()
|
||||||
|
.filter(r -> r.getPayloadJson() != null && !r.getPayloadJson().trim().isEmpty())
|
||||||
|
.map(r -> indexOfArgument(r.getPayloadJson())).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void businessFailureFromTheStoreStillSurfacesUnchanged() {
|
||||||
|
int total = TaskResultItemService.SNAPSHOT_READ_WINDOW + 2;
|
||||||
|
when(taskResultItemMapper.selectList(any())).thenReturn(pointerRows(total));
|
||||||
|
when(transientPayloadStorageService.extractPointer(anyString())).thenReturn("pointer");
|
||||||
|
when(transientPayloadStorageService.resolvePayload(anyString(), anyString()))
|
||||||
|
.thenAnswer(inv -> "{\"n\":" + indexOfArgument(inv.getArgument(0)) + "}");
|
||||||
|
when(transientPayloadStorageService.resolvePayload(org.mockito.ArgumentMatchers.eq("pointer-1"), anyString()))
|
||||||
|
.thenThrow(new BusinessException("读取任务结果明细失败"));
|
||||||
|
|
||||||
|
BusinessException thrown = assertThrows(BusinessException.class,
|
||||||
|
() -> service.listResultSnapshots(9001L, "APPEARANCE_PATENT", Map.class));
|
||||||
|
|
||||||
|
assertThat(thrown).hasMessage("读取任务结果明细失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unexpectedStoreFailureIsWrappedIntoBusinessExceptionAsBefore() {
|
||||||
|
when(taskResultItemMapper.selectList(any())).thenReturn(pointerRows(TaskResultItemService.SNAPSHOT_READ_WINDOW + 2));
|
||||||
|
when(transientPayloadStorageService.extractPointer(anyString())).thenReturn("pointer");
|
||||||
|
when(transientPayloadStorageService.resolvePayload(anyString(), anyString()))
|
||||||
|
.thenThrow(new IllegalStateException("对象存储 500"));
|
||||||
|
|
||||||
|
BusinessException thrown = assertThrows(BusinessException.class,
|
||||||
|
() -> service.listResultSnapshots(9001L, "APPEARANCE_PATENT", Map.class));
|
||||||
|
|
||||||
|
assertThat(thrown).hasMessage("读取任务结果明细失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 源码绊线:窗口这道闸本身 ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void submissionIsWindowBoundedNotWholeResultSetAtOnce() {
|
||||||
|
String body = methodBody(SourceScan.withoutComments(SourceScan.sourceText("TaskResultItemService.java")),
|
||||||
|
"List<T> listResultSnapshots(Long taskId, String moduleType, Class<T> clazz)");
|
||||||
|
|
||||||
|
assertThat(body).as("提交循环必须由窗口常量钳制").contains("from += SNAPSHOT_READ_WINDOW");
|
||||||
|
assertThat(body).as("每次只提交一窗的行").contains("Math.min(from + SNAPSHOT_READ_WINDOW");
|
||||||
|
assertThat(body.indexOf("from += SNAPSHOT_READ_WINDOW"))
|
||||||
|
.as("submit 必须落在窗口循环里面,不是回到整量 for (row : rows)")
|
||||||
|
.isLessThan(body.indexOf("snapshotReadPool.submit("));
|
||||||
|
assertThat(countOf(body, "snapshotReadPool.submit("))
|
||||||
|
.as("提交点只许一处:多一处就多一份没人收割的副本").isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void windowMustStayBelowThePoolQueueSoTheCallerNeverReadsInline() {
|
||||||
|
assertThat(TaskResultItemService.SNAPSHOT_READ_WINDOW)
|
||||||
|
.as("窗口大于线程池队列就会撞上 CallerRunsPolicy,把调用线程变成同步读对象存储的那个人")
|
||||||
|
.isBetween(1, ThreadPools.DEFAULT_QUEUE_CAPACITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从方法签名起做括号配对,取出方法体(注释已由 withoutComments 剥掉)。 */
|
||||||
|
private static String methodBody(String source, String signature) {
|
||||||
|
int start = source.indexOf(signature);
|
||||||
|
assertThat(start).as("必须存在方法 " + signature).isGreaterThan(-1);
|
||||||
|
int open = source.indexOf('{', start);
|
||||||
|
assertThat(open).as(signature + " 的方法体起点").isGreaterThan(-1);
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = open; i < source.length(); i++) {
|
||||||
|
char c = source.charAt(i);
|
||||||
|
if (c == '{') {
|
||||||
|
depth++;
|
||||||
|
} else if (c == '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth == 0) {
|
||||||
|
return source.substring(open + 1, i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new AssertionError(signature + " 括号未闭合");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countOf(String haystack, String needle) {
|
||||||
|
int count = 0;
|
||||||
|
for (int at = haystack.indexOf(needle); at >= 0; at = haystack.indexOf(needle, at + needle.length())) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.mapper.TaskResultPayloadMapper;
|
||||||
|
import com.nanri.aiimage.modules.task.model.entity.TaskResultPayloadEntity;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronization;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P1-B8:结果载荷的<b>对象存储删除</b>不得落在 DB 事务里。
|
||||||
|
*
|
||||||
|
* <p>原形状是 {@code @Transactional} 的 {@code deleteLatest} 里先同步删对象、再删行。两头的代价都真:
|
||||||
|
* 一次删除超时 120s、重试 3 次,还要带一次引用计数反查——DB 连接被这段时间占住(连接池单节点 30,
|
||||||
|
* 几次并发删除即可打满并波及其它请求);而回滚时对象已经没了、行还在=读得到一个不存在的载荷。
|
||||||
|
* 结果明细行({@link TaskResultItemService} 的 deletePayloadsAfterCommit,2026-09)早已改成提交后删,
|
||||||
|
* 本类钉的是当时漏掉的这一处。
|
||||||
|
*
|
||||||
|
* <p>反向自证:把 {@code deletePayloadIfPresent} 挪回事务内(或去掉 afterCommit 分支),第一格即红;
|
||||||
|
* 把顺序倒回来(先删对象再删行),第三格即红。
|
||||||
|
*/
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class TaskResultPayloadDeleteTxBoundaryTest {
|
||||||
|
|
||||||
|
private static final String POINTER = "rustfs:task-payload/APPEARANCE_PATENT/9001/abc.json";
|
||||||
|
|
||||||
|
@Mock private TaskResultPayloadMapper taskResultPayloadMapper;
|
||||||
|
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||||
|
|
||||||
|
private TaskResultPayloadService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
service = new TaskResultPayloadService(taskResultPayloadMapper, new ObjectMapper(),
|
||||||
|
transientPayloadStorageService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void clearSynchronizationIfLeftActive() {
|
||||||
|
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||||
|
TransactionSynchronizationManager.clearSynchronization();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubRowWithPayload(String payloadJson) {
|
||||||
|
TaskResultPayloadEntity existing = new TaskResultPayloadEntity();
|
||||||
|
existing.setId(11L);
|
||||||
|
existing.setTaskId(9001L);
|
||||||
|
existing.setModuleType("APPEARANCE_PATENT");
|
||||||
|
existing.setPayloadJson(payloadJson);
|
||||||
|
when(taskResultPayloadMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 没有活动同步器时 Spring 直接抛 IllegalState;测试里按「没注册任何同步器」读成空。 */
|
||||||
|
private static List<TransactionSynchronization> registered() {
|
||||||
|
return TransactionSynchronizationManager.isSynchronizationActive()
|
||||||
|
? TransactionSynchronizationManager.getSynchronizations()
|
||||||
|
: List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 有事务上下文时对象存储要等提交之后才动() {
|
||||||
|
stubRowWithPayload(POINTER);
|
||||||
|
TransactionSynchronizationManager.initSynchronization();
|
||||||
|
|
||||||
|
service.deleteLatest(9001L, "APPEARANCE_PATENT", "scope-a");
|
||||||
|
|
||||||
|
verify(taskResultPayloadMapper, times(1)).deleteById(11L);
|
||||||
|
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(anyString());
|
||||||
|
|
||||||
|
List<TransactionSynchronization> synchronizations = registered();
|
||||||
|
assertEquals(1, synchronizations.size(), "提交后删除必须挂在事务同步器上,否则回滚也会照删");
|
||||||
|
synchronizations.forEach(TransactionSynchronization::afterCommit);
|
||||||
|
verify(transientPayloadStorageService, times(1)).deletePayloadIfPresent(POINTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 没有事务上下文(被非事务调用方直接用)时**立即删**——静默不删就是留孤儿对象。 */
|
||||||
|
@Test
|
||||||
|
void 无事务上下文时仍然删到() {
|
||||||
|
stubRowWithPayload(POINTER);
|
||||||
|
|
||||||
|
service.deleteLatest(9001L, "APPEARANCE_PATENT", "scope-a");
|
||||||
|
|
||||||
|
verify(taskResultPayloadMapper, times(1)).deleteById(11L);
|
||||||
|
verify(transientPayloadStorageService, times(1)).deletePayloadIfPresent(POINTER);
|
||||||
|
assertEquals(0, registered().size(), "不在事务里就别往线程上挂同步器(挂了也没人触发它)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 落库失败=这单还没删:对象存储一次都不许碰(否则回滚后行还在、载荷已经没了)。 */
|
||||||
|
@Test
|
||||||
|
void 落库失败不留半成品() {
|
||||||
|
stubRowWithPayload(POINTER);
|
||||||
|
when(taskResultPayloadMapper.deleteById(11L)).thenThrow(new IllegalStateException("db down"));
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class,
|
||||||
|
() -> service.deleteLatest(9001L, "APPEARANCE_PATENT", "scope-a"));
|
||||||
|
|
||||||
|
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 行里没有载荷值时不注册提交后删除:一次空的网络往返都不该发。 */
|
||||||
|
@Test
|
||||||
|
void 空载荷不注册提交后删除() {
|
||||||
|
stubRowWithPayload(null);
|
||||||
|
TransactionSynchronizationManager.initSynchronization();
|
||||||
|
|
||||||
|
service.deleteLatest(9001L, "APPEARANCE_PATENT", "scope-a");
|
||||||
|
|
||||||
|
verify(taskResultPayloadMapper, times(1)).deleteById(11L);
|
||||||
|
assertEquals(0, registered().size(), "没有指针就没有要删的对象,别挂一个注定空跑的同步器");
|
||||||
|
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 没有这一行=什么都不做(既不删库也不注册删除)。 */
|
||||||
|
@Test
|
||||||
|
void 行不存在时整条链路不动() {
|
||||||
|
when(taskResultPayloadMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
|
||||||
|
TransactionSynchronizationManager.initSynchronization();
|
||||||
|
|
||||||
|
service.deleteLatest(9001L, "APPEARANCE_PATENT", "scope-a");
|
||||||
|
|
||||||
|
verify(taskResultPayloadMapper, never()).deleteById(11L);
|
||||||
|
assertEquals(0, registered().size());
|
||||||
|
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(anyString());
|
||||||
|
}
|
||||||
|
}
|
||||||
+48
-5
@@ -10,11 +10,13 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
|||||||
import com.nanri.aiimage.modules.task.spi.ClientTaskRetrySpi;
|
import com.nanri.aiimage.modules.task.spi.ClientTaskRetrySpi;
|
||||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.test.util.ReflectionTestUtils;
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
@@ -23,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
|||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.Mockito.doThrow;
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
@@ -143,10 +146,18 @@ class TaskResumeServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void 已有重试任务时跳过避免重复克隆() {
|
void 已有重试任务时跳过避免重复克隆() {
|
||||||
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||||
when(mapper.selectList(any())).thenReturn(List.of(
|
FileTaskEntity origin = failedTask(28587L, "SIMILAR_ASIN", "任务心跳超时,已自动失败");
|
||||||
failedTask(28587L, "SIMILAR_ASIN", "任务心跳超时,已自动失败")));
|
FileTaskEntity child = new FileTaskEntity();
|
||||||
// 第一次是"不支持重试的中断任务数",第二次是"是否已有重试子任务"
|
child.setId(28600L);
|
||||||
when(mapper.selectCount(any())).thenReturn(0L, 1L);
|
child.setResumeOfTaskId(28587L);
|
||||||
|
// P1-B5 之后「是否已有重试子任务」不再是每行一次 selectCount,而是循环前一次批量 selectList。
|
||||||
|
// 候选查询与反查都落在同一个 selectList 上,按投影列区分:反查那一支只取 resume_of_task_id。
|
||||||
|
when(mapper.selectList(any())).thenAnswer(invocation -> {
|
||||||
|
com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> wrapper = invocation.getArgument(0);
|
||||||
|
String projection = String.valueOf(wrapper.getSqlSelect());
|
||||||
|
return projection.contains("resume_of_task_id") ? List.of(child) : List.of(origin);
|
||||||
|
});
|
||||||
|
when(mapper.selectCount(any())).thenReturn(0L);
|
||||||
ClientTaskRetrySpi spi = mock(ClientTaskRetrySpi.class);
|
ClientTaskRetrySpi spi = mock(ClientTaskRetrySpi.class);
|
||||||
when(spi.moduleType()).thenReturn("SIMILAR_ASIN");
|
when(spi.moduleType()).thenReturn("SIMILAR_ASIN");
|
||||||
TaskResumeService service = service(mapper, List.of(spi), true, 3);
|
TaskResumeService service = service(mapper, List.of(spi), true, 3);
|
||||||
@@ -157,6 +168,37 @@ class TaskResumeServiceTest {
|
|||||||
assertEquals(0, stats.resumedTaskCount);
|
assertEquals(0, stats.resumedTaskCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P1-B6 同族:反查子任务与「补检中」两条判定都必须**批量**取(循环前一次),不许退回逐行点查——
|
||||||
|
* 逐行形状在 500 个候选时是 1,000 次往返,且 {@code resume_of_task_id} 那列在 V187 之前无索引。
|
||||||
|
* 判据=selectList 只发生「清账 + 候选 + 反查」三次、selectCount 只发生一次(不支持重试的计数),
|
||||||
|
* 且批量档拿到的是这一轮的全部候选 id。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void 两条前置判定按批量档取不逐行点查() {
|
||||||
|
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||||
|
when(mapper.selectList(any())).thenReturn(List.of(
|
||||||
|
failedTask(28587L, "SIMILAR_ASIN", "任务心跳超时,已自动失败"),
|
||||||
|
failedTask(28588L, "SIMILAR_ASIN", "任务心跳超时,已自动失败")));
|
||||||
|
when(mapper.selectCount(any())).thenReturn(0L);
|
||||||
|
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||||
|
ClientTaskRetrySpi spi = mock(ClientTaskRetrySpi.class);
|
||||||
|
when(spi.moduleType()).thenReturn("SIMILAR_ASIN");
|
||||||
|
TaskResumeService service = service(mapper, jobs, List.of(spi), true, 3);
|
||||||
|
|
||||||
|
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
|
||||||
|
|
||||||
|
assertEquals(2, stats.resumedTaskCount);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
ArgumentCaptor<Collection<Long>> captor =
|
||||||
|
(ArgumentCaptor<Collection<Long>>) (ArgumentCaptor<?>) ArgumentCaptor.forClass(Collection.class);
|
||||||
|
verify(jobs).taskIdsWithUnfinishedAssembleJob(captor.capture());
|
||||||
|
assertTrue(captor.getValue().containsAll(List.of(28587L, 28588L)),
|
||||||
|
"批量档必须一次带走本轮全部候选,漏一个就是退回逐行点查");
|
||||||
|
verify(mapper, times(3)).selectList(any());
|
||||||
|
verify(mapper, times(1)).selectCount(any());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 现网 2026-10-24:一枚 760 行的外观专利任务因交付缺口把组装作业排回补检(作业还在
|
* 现网 2026-10-24:一枚 760 行的外观专利任务因交付缺口把组装作业排回补检(作业还在
|
||||||
* PENDING/RUNNING),任务行却已是 FAILED,于是被巡检连克隆成 4 枚、每枚全量重跑一遍,
|
* PENDING/RUNNING),任务行却已是 FAILED,于是被巡检连克隆成 4 枚、每枚全量重跑一遍,
|
||||||
@@ -170,7 +212,8 @@ class TaskResumeServiceTest {
|
|||||||
failedTask(32201L, "APPEARANCE_PATENT", "有 3 行抓取失败(未取得商品页数据):B07P5TR7Q5")));
|
failedTask(32201L, "APPEARANCE_PATENT", "有 3 行抓取失败(未取得商品页数据):B07P5TR7Q5")));
|
||||||
when(mapper.selectCount(any())).thenReturn(0L);
|
when(mapper.selectCount(any())).thenReturn(0L);
|
||||||
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||||
when(jobs.hasUnfinishedAssembleJob(32201L)).thenReturn(true);
|
// P1-B5:补检判定从逐行 hasUnfinishedAssembleJob 折成循环前一次批量档。
|
||||||
|
when(jobs.taskIdsWithUnfinishedAssembleJob(any())).thenReturn(java.util.Set.of(32201L));
|
||||||
ClientTaskRetrySpi spi = mock(ClientTaskRetrySpi.class);
|
ClientTaskRetrySpi spi = mock(ClientTaskRetrySpi.class);
|
||||||
when(spi.moduleType()).thenReturn("APPEARANCE_PATENT");
|
when(spi.moduleType()).thenReturn("APPEARANCE_PATENT");
|
||||||
TaskResumeService service = service(mapper, jobs, List.of(spi), true, 3);
|
TaskResumeService service = service(mapper, jobs, List.of(spi), true, 3);
|
||||||
|
|||||||
+190
@@ -0,0 +1,190 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判死 markers 词汇表的「现状」快照(流程稳定性蓝图 P0-C5,2026-11-03)。
|
||||||
|
*
|
||||||
|
* <p>整单的自动重试/重开/判死生死全押在 {@link TaskRetryEligibility} 这几组中文
|
||||||
|
* markers 与 {@code TaskResultFileJobWorker#isOrphanJobFailure} 的孤儿文案上——
|
||||||
|
* 改一个词就是静默改一批任务的生死(B51 的立案原因:判据靠文案,改文案=改行为)。
|
||||||
|
* Phase 2 (B51-R1) 把判据切到 {@code failure_category} 列时,本快照就是切换前后
|
||||||
|
* 双读对撞的正本:</p>
|
||||||
|
* <ul>
|
||||||
|
* <li>六组 markers 逐字锁定(含顺序敏感的判定优先级:STOPPED → DELIVERY →
|
||||||
|
* BALANCE/KEY → SERVICE → CREDENTIAL);</li>
|
||||||
|
* <li>每个 marker 都要真的能通过真入口 {@code forceMajeureCategory} 落到它的类
|
||||||
|
* ——清单与判定函数必须同源,防「加词忘接线」;</li>
|
||||||
|
* <li>孤儿判死的四条文案逐字锁定:那四条命中即 {@code markFailedPermanent}
|
||||||
|
* (重试 5 次也救不回的 job 拉满跳过),改词即改生死。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
class TaskRetryEligibilityMarkersSnapshotTest {
|
||||||
|
|
||||||
|
private static List<String> markers(String field) {
|
||||||
|
try {
|
||||||
|
Field f = TaskRetryEligibility.class.getDeclaredField(field);
|
||||||
|
assertThat(Modifier.isStatic(f.getModifiers()) && Modifier.isPrivate(f.getModifiers()))
|
||||||
|
.as("%s 应为 private static(形状变了要同步更新本契约)", field).isTrue();
|
||||||
|
f.setAccessible(true);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<String> list = (List<String>) f.get(null);
|
||||||
|
return list;
|
||||||
|
} catch (ReflectiveOperationException ex) {
|
||||||
|
throw new IllegalStateException("TaskRetryEligibility." + field + " 读不到(字段改名要同步更新本契约)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 六组markers逐字快照() {
|
||||||
|
assertThat(markers("BALANCE_MARKERS")).containsExactly(
|
||||||
|
"余额不足", "欠费", "套餐不存在", "套餐已过期", "套餐过期", "未开通",
|
||||||
|
"insufficient_user_quota", "insufficient_quota", "quota exceeded",
|
||||||
|
"预扣费额度");
|
||||||
|
assertThat(markers("KEY_MARKERS")).containsExactly(
|
||||||
|
"密钥无效", "密钥失效", "无效的密钥", "密钥不可用",
|
||||||
|
"invalid api key", "invalid_api_key", "api key 无效", "apikey 无效");
|
||||||
|
assertThat(markers("SERVICE_MARKERS")).containsExactly(
|
||||||
|
"服务不可用", "服务宕机", "service unavailable",
|
||||||
|
"connection refused", "连接被拒绝",
|
||||||
|
"502 bad gateway", "503 service", "504 gateway", "upstream connect error",
|
||||||
|
"对象存储不可达", "对象存储出口不可达", "存储出口不可达",
|
||||||
|
"数据库连接失败", "数据库不可用");
|
||||||
|
assertThat(markers("CREDENTIAL_MARKERS")).containsExactly(
|
||||||
|
"aiprice 未登录", "未登录且自动登录失败", "自动登录失败",
|
||||||
|
"会话失效且重新登录失败");
|
||||||
|
assertThat(markers("DELIVERY_MARKERS")).containsExactly(
|
||||||
|
"结果文件生成多次失败", "结果文件生成失败", "卡死重排");
|
||||||
|
// 停止文案不在这里抄字面量——引用 TaskResumeService 的同一份常量(抄一份改一处就静默失效)。
|
||||||
|
assertThat(markers("STOPPED_MARKERS"))
|
||||||
|
.containsExactly(TaskResumeService.DUPLICATE_STOP_REASON);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 每个marker经真入口都落到它的类() {
|
||||||
|
for (String marker : markers("BALANCE_MARKERS")) {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(marker))
|
||||||
|
.as("余额/密钥类 marker %r 应判 BALANCE", marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
}
|
||||||
|
for (String marker : markers("SERVICE_MARKERS")) {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(marker))
|
||||||
|
.as("服务类 marker %r 应判 SERVICE_DOWN", marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.SERVICE_DOWN);
|
||||||
|
}
|
||||||
|
for (String marker : markers("CREDENTIAL_MARKERS")) {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(marker))
|
||||||
|
.as("账号类 marker %r 应判 CREDENTIAL", marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.CREDENTIAL);
|
||||||
|
}
|
||||||
|
for (String marker : markers("DELIVERY_MARKERS")) {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(marker))
|
||||||
|
.as("交付侧 marker %r 应判 DELIVERY(重跑整单修不好组装器)", marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.DELIVERY);
|
||||||
|
}
|
||||||
|
for (String marker : markers("STOPPED_MARKERS")) {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(marker))
|
||||||
|
.as("停止 marker %r 应判 STOPPED(再克隆等于把双跑捡回来)", marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.STOPPED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 判定优先级_STOPPED_先于_DELIVERY_先于_BALANCE_先于_SERVICE() {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(
|
||||||
|
TaskResumeService.DUPLICATE_STOP_REASON + ",余额不足"))
|
||||||
|
.as("停止文案先判:被欠费类抢走会把「不该再跑」说成「服务不可用」,运维按反方向调整")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.STOPPED);
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("结果文件生成失败,账户余额不足"))
|
||||||
|
.as("交付侧先于欠费:采集已完成、组装失败,重跑整单修不好")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.DELIVERY);
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("余额不足,服务不可用"))
|
||||||
|
.as("欠费先于服务不可用")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("服务不可用,aiprice 未登录"))
|
||||||
|
.as("服务不可用先于账号类")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.SERVICE_DOWN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 判定大小写不敏感且空文案可重试() {
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("Insufficient_Quota"))
|
||||||
|
.as("英文 marker 大小写混写也要接住(errorMessage 会按小写比对)")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("Invalid API Key"))
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE);
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(null)).isNull();
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory(" ")).as("空白文案=可重试").isNull();
|
||||||
|
assertThat(TaskRetryEligibility.forceMajeureCategory("未知的新失败形态")).isNull();
|
||||||
|
assertThat(TaskRetryEligibility.skipReason("余额不足"))
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.BALANCE.label());
|
||||||
|
assertThat(TaskRetryEligibility.skipReason(null)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 孤儿作业判死文案逐字快照_命中即拉满不再重试() {
|
||||||
|
Object worker = new TaskResultFileJobWorker(null, null, null, null, null, null);
|
||||||
|
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new BusinessException("任务不存在"), "任务不存在"))
|
||||||
|
.as("「任务不存在」命中孤儿判死:fileTask 已删的 job 重试 5 次也救不回来");
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new BusinessException("task not found: 123"), "task not found: 123")).isTrue();
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new BusinessException("result record not found"), "result record not found")).isTrue();
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new BusinessException("记录不存在"), "记录不存在")).isTrue();
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new BusinessException("组装失败:列溢出"), "组装失败:列溢出"))
|
||||||
|
.as("普通失败不进孤儿通道,必须留给重试")
|
||||||
|
.isFalse();
|
||||||
|
assertThat((Boolean) ReflectionTestUtils.invokeMethod(worker, "isOrphanJobFailure",
|
||||||
|
new RuntimeException("任务不存在"), "任务不存在"))
|
||||||
|
.as("只有 BusinessException 才算业务判据,运行时异常必须走正常失败重试")
|
||||||
|
.isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 2026-11-03 Phase 2 ⑤(B51-R1)——<b>更新即登记</b>,不是静默改绿。
|
||||||
|
*
|
||||||
|
* <p>六组 markers 本体一字未改(上面那几格仍是正本),但读侧多了一层:<b>任务行上登记过
|
||||||
|
* {@code failure_category} 就以列为准,没登记才回落到这些 markers</b>。这一格把"切换是渐进的"
|
||||||
|
* 写死——Expand 阶段存量行与未接 ledger 的写入面列都是 NULL,回落必须逐字等于今天的判定,
|
||||||
|
* 否则加一列就把历史任务的续跑口径整体改掉。
|
||||||
|
*
|
||||||
|
* <p>仍留在文案判定上的三处是<b>边界</b>不是漏网,后续 Contract 阶段也不该顺手"切列":
|
||||||
|
* {@code TaskResultFileJobWorker#isOrphanJobFailure} 判的是查库抛回来的异常文本
|
||||||
|
* ("任务不存在"/"task not found"),不是任务失败原因,{@code Category} 值域里也没有这一类;
|
||||||
|
* {@code AppearancePatentResultJobSupport#isFatalLlmArrearsFailure} 与
|
||||||
|
* {@code SimilarAsinTaskService#terminalizeOnFatalLlmFailure} 判的是<b>刚生成、尚未落库</b>的
|
||||||
|
* 消息,那一刻列还不存在。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void 列登记后判定不随文案漂移_未登记则逐字回落() {
|
||||||
|
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity task =
|
||||||
|
new com.nanri.aiimage.modules.task.model.entity.FileTaskEntity();
|
||||||
|
task.setFailureCategory(TaskRetryEligibility.Category.SERVICE_DOWN.name());
|
||||||
|
task.setErrorMessage("这句文案后来被改成了任何人话");
|
||||||
|
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("列登记过就以列为准:这正是本列存在的唯一理由")
|
||||||
|
.isEqualTo(TaskRetryEligibility.Category.SERVICE_DOWN);
|
||||||
|
|
||||||
|
task.setFailureCategory(null);
|
||||||
|
for (String marker : List.of("余额不足", "密钥无效", "服务不可用", "aiprice 未登录",
|
||||||
|
"结果文件生成多次失败", "卡死重排")) {
|
||||||
|
task.setErrorMessage(marker);
|
||||||
|
assertThat(TaskRetryEligibility.category(task))
|
||||||
|
.as("列不在时必须逐字退回 markers 判定:" + marker)
|
||||||
|
.isEqualTo(TaskRetryEligibility.forceMajeureCategory(marker));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+184
@@ -0,0 +1,184 @@
|
|||||||
|
package com.nanri.aiimage.modules.task.service;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.yaml.snakeyaml.Yaml;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stuck 判定与重排的「现状时序」快照(流程稳定性蓝图 P0-C1,2026-11-03)。
|
||||||
|
*
|
||||||
|
* <p>锁的是 Phase 2(B74-02 收口)<b>动手前</b>的时序事实:作业心跳 60 秒一次、
|
||||||
|
* 卡死扫描 60 秒一轮、卡死阈值出厂 5 分钟,而外观专利与相似 ASIN 的单批 LLM 读取
|
||||||
|
* 预算都是 600 秒 ⇒ 长批次在当前口径下<b>必然</b>被另一台的陈旧扫描翻回 PENDING
|
||||||
|
* (现网 33149 计数 6→13、33179 0→8、到 20 次判死的那条链)。这些数字之间的大小
|
||||||
|
* 关系就是 B74-02 的病灶本身,先照快收进尺子:
|
||||||
|
* </p>
|
||||||
|
* <ul>
|
||||||
|
* <li>Phase 2 抬 {@code stuck-timeout-minutes} 或加批内 {@code touchRunningIfStale} 时,
|
||||||
|
* 「卡死阈值 < LLM 预算」这一格会翻红 —— 那是<b>预期内的更新</b>:按新口径改写
|
||||||
|
* 断言并在蓝图登记,不许静默改绿;</li>
|
||||||
|
* <li>与之配套:{@link StaleTaskRepairService} 的 2 小时天花板、worker 两个 @Value
|
||||||
|
* 出厂档与 application.yml 必须互相同源,改一处不同步另一处即红。</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>刻意<b>不</b>锁 {@code resetStuckRunningJobsDetailed} 的调用签名:该处正被另一路
|
||||||
|
* 会话在飞改造(2026-11-03 工作树实录),签名级断言会锁住移动靶。签名形状已有
|
||||||
|
* {@code TaskResultFileJobWorkerStuckScanTest} 与既有守卫族覆盖,本类只锁时序数字。</p>
|
||||||
|
*/
|
||||||
|
class TaskStuckRequeueTimingSnapshotTest {
|
||||||
|
|
||||||
|
private static final Pattern ENV_DEFAULT = Pattern.compile("^\\$\\{[^:}]+:([^}]*)}$");
|
||||||
|
|
||||||
|
/** 读取 application.yml(合并所有 --- 文档段),返回顶层 Map。 */
|
||||||
|
private static Map<String, Object> loadAppYml() {
|
||||||
|
Path yml = Path.of("src", "main", "resources", "application.yml");
|
||||||
|
assertThat(yml).as("application.yml 必须能从 backend-java 模块根读到(surefire 的 cwd)").exists();
|
||||||
|
Yaml yaml = new Yaml();
|
||||||
|
Map<String, Object> merged = new LinkedHashMap<>();
|
||||||
|
try {
|
||||||
|
for (Object doc : yaml.loadAll(Files.newInputStream(yml))) {
|
||||||
|
if (doc instanceof Map<?, ?> map) {
|
||||||
|
merge(merged, (Map<String, Object>) map);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new IllegalStateException("读 application.yml 失败: " + yml.toAbsolutePath(), ex);
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static void merge(Map<String, Object> into, Map<String, Object> from) {
|
||||||
|
for (Map.Entry<String, Object> e : from.entrySet()) {
|
||||||
|
if (e.getValue() instanceof Map<?, ?> sub && into.get(e.getKey()) instanceof Map<?, ?> oldSub) {
|
||||||
|
merge((Map<String, Object>) oldSub, (Map<String, Object>) sub);
|
||||||
|
} else {
|
||||||
|
into.put(e.getKey(), e.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取 `aiimage.<path...>` 下的出厂值;`${ENV:default}` 形态取 default 段。 */
|
||||||
|
private static String factoryDefault(Map<String, Object> root, String... path) {
|
||||||
|
Object node = root.get("aiimage");
|
||||||
|
for (String key : path) {
|
||||||
|
assertThat(node)
|
||||||
|
.as("application.yml 里 aiimage.%s 应为 Map", String.join(".", path))
|
||||||
|
.isInstanceOf(Map.class);
|
||||||
|
node = ((Map<String, Object>) node).get(key);
|
||||||
|
}
|
||||||
|
assertThat(node)
|
||||||
|
.as("application.yml 里 aiimage.%s 必须存在", String.join(".", path))
|
||||||
|
.isNotNull();
|
||||||
|
String raw = String.valueOf(node);
|
||||||
|
Matcher m = ENV_DEFAULT.matcher(raw.trim());
|
||||||
|
return m.matches() ? m.group(1) : raw.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 递归收集全树同名 key 的出厂值(llm-read-timeout-millis 有外观专利/相似 ASIN 两处)。 */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static List<String> collectDefaults(Object node, String key, List<String> into) {
|
||||||
|
if (node instanceof Map<?, ?> map) {
|
||||||
|
for (Map.Entry<?, ?> e : map.entrySet()) {
|
||||||
|
if (key.equals(String.valueOf(e.getKey())) && e.getValue() != null) {
|
||||||
|
Matcher m = ENV_DEFAULT.matcher(String.valueOf(e.getValue()).trim());
|
||||||
|
into.add(m.matches() ? m.group(1) : String.valueOf(e.getValue()).trim());
|
||||||
|
} else {
|
||||||
|
collectDefaults(e.getValue(), key, into);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return into;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static String fieldDefault(Class<?> owner, String field) {
|
||||||
|
try {
|
||||||
|
Value annotation = owner.getDeclaredField(field).getAnnotation(Value.class);
|
||||||
|
assertThat(annotation)
|
||||||
|
.as("%s.%s 必须保留 @Value 出厂档注解", owner.getSimpleName(), field)
|
||||||
|
.isNotNull();
|
||||||
|
Matcher m = ENV_DEFAULT.matcher(annotation.value());
|
||||||
|
return m.matches() ? m.group(1) : annotation.value();
|
||||||
|
} catch (NoSuchFieldException ex) {
|
||||||
|
throw new IllegalStateException(owner.getSimpleName() + "." + field + " 字段没了(形状变了要同步更新本契约)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 卡死档位与心跳档位的出厂值() {
|
||||||
|
Map<String, Object> root = loadAppYml();
|
||||||
|
|
||||||
|
assertThat(factoryDefault(root, "result-file-job", "stuck-timeout-minutes"))
|
||||||
|
.as("stuck 判定阈值出厂 5 分钟(B74-02 的靶点,Phase 2 收口时更新本格并登记)")
|
||||||
|
.isEqualTo("5");
|
||||||
|
assertThat(factoryDefault(root, "result-file-job", "heartbeat-interval-ms"))
|
||||||
|
.as("作业心跳 60 秒一次")
|
||||||
|
.isEqualTo("60000");
|
||||||
|
assertThat(factoryDefault(root, "result-file-job", "stuck-scan-delay-ms"))
|
||||||
|
.as("卡死扫描 60 秒一轮")
|
||||||
|
.isEqualTo("60000");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 单批LLM读取预算现状为600秒() {
|
||||||
|
List<String> budgets = collectDefaults(loadAppYml(), "llm-read-timeout-millis", new ArrayList<>());
|
||||||
|
|
||||||
|
assertThat(budgets)
|
||||||
|
.as("外观专利与相似 ASIN 两处单批 LLM 预算都必须在册(读出 0 处=尺子架错树)")
|
||||||
|
.hasSize(2)
|
||||||
|
.allSatisfy(v -> assertThat(v)
|
||||||
|
.as("单批 LLM 读取预算出厂 600 秒——卡死阈值快照就是拿它当分母")
|
||||||
|
.isEqualTo("600000"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 现状卡死阈值小于单批LLM预算_B74_02病灶快照() {
|
||||||
|
Map<String, Object> root = loadAppYml();
|
||||||
|
long stuckMillis = Long.parseLong(factoryDefault(root, "result-file-job", "stuck-timeout-minutes")) * 60_000L;
|
||||||
|
long minLlmBudget = collectDefaults(root, "llm-read-timeout-millis", new ArrayList<>()).stream()
|
||||||
|
.mapToLong(Long::parseLong).min().orElseThrow();
|
||||||
|
|
||||||
|
assertThat(stuckMillis)
|
||||||
|
.as("现状:卡死阈值(%dms) < 单批 LLM 预算(%dms) ⇒ 长批次必被另一台陈旧扫描翻回 PENDING。"
|
||||||
|
+ "Phase 2 (B74-02) 收口后本格翻红属预期,按新口径改写并在蓝图登记,不许静默改绿",
|
||||||
|
stuckMillis, minLlmBudget)
|
||||||
|
.isLessThan(minLlmBudget);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void worker注解出厂档与application_yml同源() {
|
||||||
|
Map<String, Object> root = loadAppYml();
|
||||||
|
|
||||||
|
assertThat(fieldDefault(TaskResultFileJobWorker.class, "stuckTimeoutMinutes"))
|
||||||
|
.as("worker 的 stuck 阈值注解读的必须是同一个 key 的同一个出厂值")
|
||||||
|
.isEqualTo(factoryDefault(root, "result-file-job", "stuck-timeout-minutes"));
|
||||||
|
assertThat(fieldDefault(TaskResultFileJobWorker.class, "heartbeatIntervalMillis"))
|
||||||
|
.as("worker 的心跳间隔注解读的必须是同一个 key 的同一个出厂值")
|
||||||
|
.isEqualTo(factoryDefault(root, "result-file-job", "heartbeat-interval-ms"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 陈旧任务修复的天花板是两小时() throws Exception {
|
||||||
|
java.lang.reflect.Field idle = StaleTaskRepairService.class.getDeclaredField("STALE_IDLE_MINUTES");
|
||||||
|
idle.setAccessible(true);
|
||||||
|
|
||||||
|
assertThat((Long) idle.get(null))
|
||||||
|
.as("SCHEDULED/RUNNING 的判死天花板出厂 120 分钟:各模块心跳线的放宽都盖不过它,"
|
||||||
|
+ "PENDING(排队)不在其判死范围(产品口径 2026-10-29)")
|
||||||
|
.isEqualTo(120L);
|
||||||
|
}
|
||||||
|
}
|
||||||
+98
@@ -366,6 +366,54 @@ class UserApiSecretServiceTest {
|
|||||||
service.requireSubmitSecret(7L, UserSecretModule.APPEARANCE_PATENT, null);
|
service.requireSubmitSecret(7L, UserSecretModule.APPEARANCE_PATENT, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 task type 问闸门(B72-01):要哪把密钥的出处只有 {@code TaskModuleRegistry},
|
||||||
|
* 调用方不再各写一枚枚举——{@code /newApi} 是整包转发的透传面,客户端猜不出载荷需求,
|
||||||
|
* 服务端也不许两处各判各的(铁律 27 边界 a「同源」)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void requireSubmitSecretByTypeResolvesTheModuleFromTheRegistry() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
when(mapper.selectOne(any())).thenReturn(null);
|
||||||
|
|
||||||
|
BusinessException error = assertThrows(BusinessException.class,
|
||||||
|
() -> service.requireSubmitSecret(7L, "SIMILAR_ASIN", " "));
|
||||||
|
|
||||||
|
// 文案仍然点名"缺哪把、去哪配",且那把钥匙是登记表选出来的而不是调用方给的
|
||||||
|
assertThat(error.getMessage()).contains("货源查询密钥").contains("密钥设置");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requireSubmitSecretByTypePassesWhenCallerCarriesKey() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
|
||||||
|
service.requireSubmitSecret(7L, "APPEARANCE_PATENT", "sk-caller");
|
||||||
|
|
||||||
|
verify(mapper, never()).selectOne(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登记为「这一类不需要用户凭据」的类型调到这里必须炸,不能静默放行成空闸门。 */
|
||||||
|
@Test
|
||||||
|
void requireSubmitSecretByTypeRefusesTypeDeclaredAsNeedingNoCredential() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
|
||||||
|
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||||
|
() -> service.requireSubmitSecret(7L, "COLLECT_DATA", null));
|
||||||
|
|
||||||
|
assertThat(error.getMessage()).contains("COLLECT_DATA");
|
||||||
|
// 空转的闸门比没有闸门更坏:走到这里一字节都不该碰库
|
||||||
|
verify(mapper, never()).selectOne(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 「没登记」与「登记过=不需要」是两个结论:不在清单里的类型名当场抛,不许当成空需求。 */
|
||||||
|
@Test
|
||||||
|
void requireSubmitSecretByTypeRejectsModuleThatIsNotRegistered() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.requireSubmitSecret(7L, "APPEARANCE_PATENTT", null));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void migrateSkipsWhenServerValueExists() {
|
void migrateSkipsWhenServerValueExists() {
|
||||||
UserApiSecretService service = newService();
|
UserApiSecretService service = newService();
|
||||||
@@ -1102,6 +1150,56 @@ class UserApiSecretServiceTest {
|
|||||||
assertThat(inspectionWrites.values()).containsOnly("passed");
|
assertThat(inspectionWrites.values()).containsOnly("passed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* B73-03:代理凭据的分组身份=**供应商账号**,不是「哪个模块里的哪一行配置」。
|
||||||
|
*
|
||||||
|
* <p>同一把青果 key 只是参数顺序写得不一样(或配在两行上),旧口径按 moduleKey|channel|密文
|
||||||
|
* 算成两组 ⇒ 一轮真打两枪提取;而青果整个账号只有 1 条通道(2026-11-02 用户在控制台核实),
|
||||||
|
* 第一枪还占着 ⇒ 第二枪必然 channel_busy,巡检自己把用户的代理打成「代理异常」。
|
||||||
|
* 现在折成 (供应商, 提取域, 归一化 query) ⇒ 同账号只出一枪。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void schedulerProbesSameProxyAccountOnceAcrossParamOrder() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
String linkA = "enc:https://overseas.proxy.qg.net/get?key=QK&pwd=QP";
|
||||||
|
String linkB = "enc:https://overseas.proxy.qg.net/get?pwd=QP&key=QK";
|
||||||
|
stubInspectionStore(Map.of(
|
||||||
|
11L, storedRow(11L, "proxy", linkA),
|
||||||
|
12L, storedRow(12L, "proxy", linkB)));
|
||||||
|
when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "代理可用", 120));
|
||||||
|
when(mapper.selectList(any())).thenReturn(List.of(
|
||||||
|
inspectionRow(1L, 11L, "proxy", linkA),
|
||||||
|
inspectionRow(2L, 12L, "proxy", linkB)), List.of());
|
||||||
|
|
||||||
|
var summary = service.checkAllForScheduler(500, 20);
|
||||||
|
|
||||||
|
verify(checkService, times(1)).probe(any(), anyString(), any());
|
||||||
|
assertThat(summary.probed()).isEqualTo(1);
|
||||||
|
assertThat(summary.checked()).isEqualTo(2);
|
||||||
|
assertThat(inspectionWrites.keySet()).containsExactlyInAnyOrder(11L, 12L);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 另一半边界:非链接型凭据(LLM 密钥)**不得**跟着一起折——
|
||||||
|
* 同一串密钥在两个模块/两条渠道上是两次独立探测,合并会拿 A 的结论冒充 B。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void schedulerKeepsPerModuleGroupingForNonLinkSecrets() {
|
||||||
|
UserApiSecretService service = newService();
|
||||||
|
String sharedApiKey = "enc:sk-shared-LLMKEY";
|
||||||
|
stubInspectionStore(Map.of(
|
||||||
|
11L, storedRow(11L, "similar-asin", sharedApiKey),
|
||||||
|
12L, storedRow(12L, "appearance-patent", sharedApiKey)));
|
||||||
|
when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "可用", 90));
|
||||||
|
when(mapper.selectList(any())).thenReturn(List.of(
|
||||||
|
inspectionRow(1L, 11L, "similar-asin", sharedApiKey),
|
||||||
|
inspectionRow(2L, 12L, "appearance-patent", sharedApiKey)), List.of());
|
||||||
|
|
||||||
|
service.checkAllForScheduler(500, 20);
|
||||||
|
|
||||||
|
verify(checkService, times(2)).probe(any(), anyString(), any());
|
||||||
|
}
|
||||||
|
|
||||||
/** 失败结论同样整组复用:否则一把欠费的 key 会按账号数重复付费提取。 */
|
/** 失败结论同样整组复用:否则一把欠费的 key 会按账号数重复付费提取。 */
|
||||||
@Test
|
@Test
|
||||||
void schedulerReusesFailedOutcomeAcrossSharedSecretGroup() {
|
void schedulerReusesFailedOutcomeAcrossSharedSecretGroup() {
|
||||||
|
|||||||
+69
-19
@@ -35,6 +35,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
|||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@@ -67,11 +68,13 @@ class UserSecretUsageServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void recordIncrementsByModuleWithTodayDate() {
|
void recordIncrementsByModuleWithTodayDate() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.increment(any(), any(), any(), eq(1))).thenReturn(1);
|
when(usageMapper.increment(any(), any(), any(), eq(1), any())).thenReturn(1);
|
||||||
|
|
||||||
service.record(7L, "similar-asin", 1);
|
service.record(7L, "similar-asin", 1);
|
||||||
|
|
||||||
verify(usageMapper).increment(eq(7L), eq("similar-asin"), eq(LocalDate.now()), eq(1));
|
// Java 自产 LLM 行落 backend 来源(V188)
|
||||||
|
verify(usageMapper).increment(eq(7L), eq("similar-asin"), eq(LocalDate.now()), eq(1),
|
||||||
|
eq("backend"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -83,44 +86,47 @@ class UserSecretUsageServiceTest {
|
|||||||
service.record(7L, "not-a-module", 1);
|
service.record(7L, "not-a-module", 1);
|
||||||
service.record(7L, "similar-asin", 0);
|
service.record(7L, "similar-asin", 0);
|
||||||
|
|
||||||
verify(usageMapper, never()).increment(any(), any(), any(), any(Integer.class));
|
verify(usageMapper, never()).increment(any(), any(), any(), any(Integer.class), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recordSwallowsMapperFailure() {
|
void recordSwallowsMapperFailure() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.increment(any(), any(), any(), eq(1)))
|
when(usageMapper.increment(any(), any(), any(), eq(1), any()))
|
||||||
.thenThrow(new IllegalStateException("db down"));
|
.thenThrow(new IllegalStateException("db down"));
|
||||||
|
|
||||||
// 计次失败绝不影响任务主流程
|
// 计次失败绝不影响任务主流程
|
||||||
service.record(7L, "proxy", 1);
|
service.record(7L, "proxy", 1);
|
||||||
|
|
||||||
verify(usageMapper).increment(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(1));
|
verify(usageMapper).increment(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(1),
|
||||||
|
eq("backend"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recordReportedCapsCountAndRejectsUnknownModule() {
|
void recordReportedCapsCountAndRejectsUnknownModule() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.increment(any(), any(), any(), any(Integer.class))).thenReturn(1);
|
when(usageMapper.increment(any(), any(), any(), any(Integer.class), any())).thenReturn(1);
|
||||||
|
|
||||||
assertThat(service.recordReported(7L, "proxy", 50_000)).isTrue();
|
assertThat(service.recordReported(7L, "proxy", 50_000)).isTrue();
|
||||||
assertThat(service.recordReported(7L, "not-a-module", 3)).isFalse();
|
assertThat(service.recordReported(7L, "not-a-module", 3)).isFalse();
|
||||||
assertThat(service.recordReported(7L, "proxy", 0)).isFalse();
|
assertThat(service.recordReported(7L, "proxy", 0)).isFalse();
|
||||||
|
|
||||||
// 超出上限按 10000 截断,防止异常客户端写爆计数
|
// 超出上限按 10000 截断,防止异常客户端写爆计数;3 参旧形状缺省落 legacy
|
||||||
verify(usageMapper).increment(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(10_000));
|
verify(usageMapper).increment(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(10_000),
|
||||||
|
eq("legacy"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recordReportedAllowsPlatformBucketOnlyForProxy() {
|
void recordReportedAllowsPlatformBucketOnlyForProxy() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.increment(any(), any(), any(), any(Integer.class))).thenReturn(1);
|
when(usageMapper.increment(any(), any(), any(), any(Integer.class), any())).thenReturn(1);
|
||||||
|
|
||||||
assertThat(service.recordReported(0L, "proxy", 3)).isTrue();
|
assertThat(service.recordReported(0L, "proxy", 3)).isTrue();
|
||||||
assertThat(service.recordReported(0L, "appearance-patent", 3)).isFalse();
|
assertThat(service.recordReported(0L, "appearance-patent", 3)).isFalse();
|
||||||
assertThat(service.recordReported(-1L, "proxy", 3)).isFalse();
|
assertThat(service.recordReported(-1L, "proxy", 3)).isFalse();
|
||||||
|
|
||||||
verify(usageMapper).increment(eq(0L), eq("proxy"), eq(LocalDate.now()), eq(3));
|
verify(usageMapper).increment(eq(0L), eq("proxy"), eq(LocalDate.now()), eq(3),
|
||||||
|
eq("legacy"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -404,8 +410,9 @@ class UserSecretUsageServiceTest {
|
|||||||
|
|
||||||
service.recordTokens(7L, "appearance-patent", 1234L, 56L);
|
service.recordTokens(7L, "appearance-patent", 1234L, 56L);
|
||||||
|
|
||||||
verify(usageMapper).addTokens(eq(7L), eq("appearance-patent"), eq(LocalDate.now()), eq(1234L), eq(56L));
|
verify(usageMapper).addTokens(eq(7L), eq("appearance-patent"), eq(LocalDate.now()),
|
||||||
verify(usageMapper, never()).increment(any(), any(), any(), any(Integer.class));
|
eq(1234L), eq(56L), eq("backend"));
|
||||||
|
verify(usageMapper, never()).increment(any(), any(), any(), any(Integer.class), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -416,7 +423,7 @@ class UserSecretUsageServiceTest {
|
|||||||
service.recordTokens(7L, "appearance-patent", 0L, 0L);
|
service.recordTokens(7L, "appearance-patent", 0L, 0L);
|
||||||
service.recordTokens(7L, "appearance-patent", -5L, 0L);
|
service.recordTokens(7L, "appearance-patent", -5L, 0L);
|
||||||
|
|
||||||
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong());
|
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -426,7 +433,8 @@ class UserSecretUsageServiceTest {
|
|||||||
|
|
||||||
service.recordTokens(7L, "similar-asin", 900L, 0L);
|
service.recordTokens(7L, "similar-asin", 900L, 0L);
|
||||||
|
|
||||||
verify(usageMapper).addTokens(eq(7L), eq("similar-asin"), eq(LocalDate.now()), eq(900L), eq(0L));
|
verify(usageMapper).addTokens(eq(7L), eq("similar-asin"), eq(LocalDate.now()), eq(900L),
|
||||||
|
eq(0L), eq("backend"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -438,31 +446,73 @@ class UserSecretUsageServiceTest {
|
|||||||
service.recordTokens(0L, "proxy", 10L, 10L);
|
service.recordTokens(0L, "proxy", 10L, 10L);
|
||||||
service.recordTokens(7L, "not-a-module", 10L, 10L);
|
service.recordTokens(7L, "not-a-module", 10L, 10L);
|
||||||
|
|
||||||
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong());
|
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("recordTokens:写库失败只告警,绝不把任务带崩")
|
@DisplayName("recordTokens:写库失败只告警,绝不把任务带崩")
|
||||||
void recordTokensSwallowsMapperFailure() {
|
void recordTokensSwallowsMapperFailure() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.addTokens(any(), any(), any(), anyLong(), anyLong()))
|
when(usageMapper.addTokens(any(), any(), any(), anyLong(), anyLong(), any()))
|
||||||
.thenThrow(new IllegalStateException("db down"));
|
.thenThrow(new IllegalStateException("db down"));
|
||||||
|
|
||||||
service.recordTokens(7L, "proxy", 10L, 2L);
|
service.recordTokens(7L, "proxy", 10L, 2L);
|
||||||
|
|
||||||
verify(usageMapper).addTokens(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(10L), eq(2L));
|
verify(usageMapper).addTokens(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(10L), eq(2L),
|
||||||
|
eq("backend"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("计次那一路不许顺手写 token:两条语句分开是口径要求(计次先于响应)")
|
@DisplayName("计次那一路不许顺手写 token:两条语句分开是口径要求(计次先于响应)")
|
||||||
void countPathNeverWritesTokens() {
|
void countPathNeverWritesTokens() {
|
||||||
UserSecretUsageService service = newService();
|
UserSecretUsageService service = newService();
|
||||||
when(usageMapper.increment(any(), any(), any(), eq(1))).thenReturn(1);
|
when(usageMapper.increment(any(), any(), any(), eq(1), any())).thenReturn(1);
|
||||||
|
|
||||||
service.record(7L, "appearance-patent", 1);
|
service.record(7L, "appearance-patent", 1);
|
||||||
service.recordReported(7L, "proxy", 3);
|
service.recordReported(7L, "proxy", 3);
|
||||||
|
|
||||||
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong());
|
verify(usageMapper, never()).addTokens(any(), any(), any(), anyLong(), anyLong(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- source 维度(V188):「谁在烧」是一列读数,不再靠扫设备日志归因 ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("recordReported:上报方自报的 source 规整后落库(trim+小写)")
|
||||||
|
void recordReportedCarriesReportedSource() {
|
||||||
|
UserSecretUsageService service = newService();
|
||||||
|
when(usageMapper.increment(any(), any(), any(), any(Integer.class), any())).thenReturn(1);
|
||||||
|
|
||||||
|
assertThat(service.recordReported(7L, "proxy", 3, "Client")).isTrue();
|
||||||
|
|
||||||
|
verify(usageMapper).increment(eq(7L), eq("proxy"), eq(LocalDate.now()), eq(3),
|
||||||
|
eq("client"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("recordReported:source 缺省/空/脏值一律落 legacy,不拒收不猜身份")
|
||||||
|
void recordReportedFallsBackToLegacyOnDirtySource() {
|
||||||
|
UserSecretUsageService service = newService();
|
||||||
|
when(usageMapper.increment(any(), any(), any(), any(Integer.class), any())).thenReturn(1);
|
||||||
|
|
||||||
|
assertThat(service.recordReported(7L, "proxy", 1, null)).isTrue();
|
||||||
|
assertThat(service.recordReported(7L, "proxy", 1, " ")).isTrue();
|
||||||
|
assertThat(service.recordReported(7L, "proxy", 1, "dirty; DROP TABLE x")).isTrue();
|
||||||
|
assertThat(service.recordReported(7L, "proxy", 1, "x".repeat(25))).isTrue();
|
||||||
|
|
||||||
|
// 计次比归因更贵:宁可归因模糊(legacy)也不丢账
|
||||||
|
verify(usageMapper, times(4)).increment(eq(7L), eq("proxy"), eq(LocalDate.now()),
|
||||||
|
any(Integer.class), eq("legacy"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("recordTokens 必须钉在 backend 来源上:唯一键四元组后不钉 source 会把 token 记到 legacy 历史行造成双计")
|
||||||
|
void recordTokensPinsBackendSource() {
|
||||||
|
UserSecretUsageService service = newService();
|
||||||
|
|
||||||
|
service.recordTokens(7L, "appearance-patent", 1234L, 56L);
|
||||||
|
|
||||||
|
verify(usageMapper).addTokens(eq(7L), eq("appearance-patent"), eq(LocalDate.now()),
|
||||||
|
eq(1234L), eq(56L), eq("backend"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|||||||
* <p><b>一处与 plan 原文不符的读数,按"先怀疑尺子"的流程处理并留在脸上</b>:plan/AGENTS §1 记的是「9 支文件」,
|
* <p><b>一处与 plan 原文不符的读数,按"先怀疑尺子"的流程处理并留在脸上</b>:plan/AGENTS §1 记的是「9 支文件」,
|
||||||
* 那条数是 {@code grep -rl 'sourceText('} 数出来的,而第 9 支是 {@code SourceScan.java:22} 里
|
* 那条数是 {@code grep -rl 'sourceText('} 数出来的,而第 9 支是 {@code SourceScan.java:22} 里
|
||||||
* {@code public static String sourceText(String fileName)} 这行<b>被调方自己的声明</b>——它不是调用点。
|
* {@code public static String sourceText(String fileName)} 这行<b>被调方自己的声明</b>——它不是调用点。
|
||||||
* 所以真实形状是 <b>调用点/调用方/引用方三类数各自成立</b>(2026-10-28 v1.1 Phase 0 起调用方 16 支、
|
* 所以真实形状是 <b>调用点/调用方/引用方三类数各自成立</b>(2026-11-03 Phase 5C 起调用方 19 支、
|
||||||
* 裸名 23 个,增量逐笔登记在 {@code REGISTERED_BARE_NAMES} 的注释里)。下面第 3 格把这些数同时钉住,
|
* 裸名 26 个,增量逐笔登记在 {@code REGISTERED_BARE_NAMES} 的注释里)。下面第 3 格把这些数同时钉住,
|
||||||
* 免得下一个人拿 {@code grep} 再数一遍又把声明算进去。</p>
|
* 免得下一个人拿 {@code grep} 再数一遍又把声明算进去。</p>
|
||||||
*/
|
*/
|
||||||
class SourceScanTest {
|
class SourceScanTest {
|
||||||
@@ -82,7 +82,25 @@ class SourceScanTest {
|
|||||||
// TaskOwnerReadSourceGuardrailTest 要钉「被拒时必须先改挂再退回」这一枚顺序,
|
// TaskOwnerReadSourceGuardrailTest 要钉「被拒时必须先改挂再退回」这一枚顺序,
|
||||||
// 顺序错在 deferRunning 把行翻成 PENDING 之后 handOffToOwner 的 CAS 就打不中,
|
// 顺序错在 deferRunning 把行翻成 PENDING 之后 handOffToOwner 的 CAS 就打不中,
|
||||||
// 用 mock 造不出这个先后(它要跑的正是 catch 块里两行的次序),只能打在源码连线上。
|
// 用 mock 造不出这个先后(它要跑的正是 catch 块里两行的次序),只能打在源码连线上。
|
||||||
"TaskResultFileJobWorker.java");
|
"TaskResultFileJobWorker.java",
|
||||||
|
// —— 2026-11-03 Phase 2 ④(B74-04 归属回落收成唯一出处)追加(1 名)——
|
||||||
|
// TaskOwnerReadSourceGuardrailTest 除了钉「列优先」,还必须钉住回落顺序本身:
|
||||||
|
// 四台此前各读各的 JSON(三台 result_json、店铺采集 request_json),列缺失的存量行
|
||||||
|
// 因此能算出两个归属。回落口径合并成 TaskOwnerJsonFallback 一处之后,判据只能打在
|
||||||
|
// "那一处确实按 result_json → request_json 的顺序读"这条源码连线上——mock 造不出
|
||||||
|
// "谁先谁后",四份夹具各测一遍照样全绿。
|
||||||
|
"TaskOwnerJsonFallback.java",
|
||||||
|
// —— 2026-11-03 Phase 2 ⑤(B51-R1 failure_category)追加(1 名)——
|
||||||
|
// TaskFailureCategoryGuardrailTest 要钉「写了失败文案就必须同笔写分类列」这条连线:
|
||||||
|
// 用 mock 造任务实体测分类,挡不住"新增一处 setErrorMessage 忘了写列"——
|
||||||
|
// 那正是"改一句文案静默改判死"的复发路径,只能打在源码上。顺带钉 ledger 不抄第二份 markers。
|
||||||
|
"TaskFailureLedger.java",
|
||||||
|
// —— 2026-11-03 Phase 5C(P1-B7 结果集分窗读取)追加(1 名)——
|
||||||
|
// TaskResultItemReadWindowTest 要钉「提交必须被窗口钳住」这条:线程池只有 8 个线程,
|
||||||
|
// 一次提交 600 行与一次提交 256 行在"同时开始读几行"这个 observable 上读数相同
|
||||||
|
// (都被 8 卡住),差异只体现在**堆**上(同时在飞的载荷副本),mock 数不出来;
|
||||||
|
// 行为四格只能钉住"不漏行/不乱序/异常口径不变",窗口这道闸本身必须打在源码上。
|
||||||
|
"TaskResultItemService.java");
|
||||||
|
|
||||||
@TempDir
|
@TempDir
|
||||||
Path tmp;
|
Path tmp;
|
||||||
@@ -98,7 +116,7 @@ class SourceScanTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void census_唯一裸名恰为23且与已登记集合相等() {
|
void census_唯一裸名恰为26且与已登记集合相等() {
|
||||||
Set<String> found = SourceScan.censusSourceTextCallSites().stream()
|
Set<String> found = SourceScan.censusSourceTextCallSites().stream()
|
||||||
.map(SourceScan.CallSite::bareName)
|
.map(SourceScan.CallSite::bareName)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
@@ -106,11 +124,11 @@ class SourceScanTest {
|
|||||||
assertThat(found)
|
assertThat(found)
|
||||||
.as("唯一裸名集合必须与类头台账逐字相等——多一个说明有人新引了单文件口径,少一个说明尺子漏扫")
|
.as("唯一裸名集合必须与类头台账逐字相等——多一个说明有人新引了单文件口径,少一个说明尺子漏扫")
|
||||||
.isEqualTo(REGISTERED_BARE_NAMES)
|
.isEqualTo(REGISTERED_BARE_NAMES)
|
||||||
.hasSize(23);
|
.hasSize(26);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void census_调用方文件恰为17而声明件在外() {
|
void census_调用方文件恰为19而声明件在外() {
|
||||||
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites();
|
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites();
|
||||||
Set<String> callerFiles = sites.stream()
|
Set<String> callerFiles = sites.stream()
|
||||||
.map(SourceScan.CallSite::relativeFile)
|
.map(SourceScan.CallSite::relativeFile)
|
||||||
@@ -119,9 +137,10 @@ class SourceScanTest {
|
|||||||
String declarationFile = "src/test/java/com/nanri/aiimage/testutil/SourceScan.java";
|
String declarationFile = "src/test/java/com/nanri/aiimage/testutil/SourceScan.java";
|
||||||
|
|
||||||
assertThat(callerFiles)
|
assertThat(callerFiles)
|
||||||
.as("真实字面量调用点落在 17 支调用方文件里(8 支既有 + 2026-10-28 v1.1 Phase 0 预置契约 8 支"
|
.as("真实字面量调用点落在 19 支调用方文件里(8 支既有 + 2026-10-28 v1.1 Phase 0 预置契约 8 支"
|
||||||
+ " + 2026-11-02 归属死锁绊线 1 支)")
|
+ " + 2026-11-02 归属死锁绊线 1 支 + 2026-11-03 B51-R1 双写绊线 1 支"
|
||||||
.hasSize(17);
|
+ " + 2026-11-03 Phase 5C P1-B7 窗口绊线 1 支)")
|
||||||
|
.hasSize(19);
|
||||||
assertThat(callerFiles)
|
assertThat(callerFiles)
|
||||||
.as("plan 原文记的「9 支」= grep -rl 'sourceText(' 的条数,第 9 支是被调方自己的声明行"
|
.as("plan 原文记的「9 支」= grep -rl 'sourceText(' 的条数,第 9 支是被调方自己的声明行"
|
||||||
+ "(SourceScan.java:22 的 `public static String sourceText(String fileName)`),"
|
+ "(SourceScan.java:22 的 `public static String sourceText(String fileName)`),"
|
||||||
|
|||||||
@@ -81,4 +81,3 @@ UserColumnPermissionMapper selectByUserId Select PURE SELECT user_id, column_id
|
|||||||
UserNotificationMapper deleteReadBeforeBatch Delete PURE DELETE FROM biz_user_notification\nWHERE read_at IS NOT NULL AND created_at < #{cutoff}\nLIMIT #{batchSize}
|
UserNotificationMapper deleteReadBeforeBatch Delete PURE DELETE FROM biz_user_notification\nWHERE read_at IS NOT NULL AND created_at < #{cutoff}\nLIMIT #{batchSize}
|
||||||
UserNotificationMapper deleteUnreadBeforeBatch Delete PURE DELETE FROM biz_user_notification\nWHERE read_at IS NULL AND created_at < #{cutoff}\nLIMIT #{batchSize}
|
UserNotificationMapper deleteUnreadBeforeBatch Delete PURE DELETE FROM biz_user_notification\nWHERE read_at IS NULL AND created_at < #{cutoff}\nLIMIT #{batchSize}
|
||||||
UserSecretUsageMapper deleteBefore Delete PURE DELETE FROM biz_user_secret_usage_daily\nWHERE business_date < #{cutoff}\nLIMIT #{batchSize}
|
UserSecretUsageMapper deleteBefore Delete PURE DELETE FROM biz_user_secret_usage_daily\nWHERE business_date < #{cutoff}\nLIMIT #{batchSize}
|
||||||
UserSecretUsageMapper increment Insert PURE INSERT INTO biz_user_secret_usage_daily (user_id, module_key, business_date, call_count, created_at, updated_at)\nVALUES (#{userId}, #{moduleKey}, #{businessDate}, #{count}, NOW(), NOW())\nON DUPLICATE KEY UPDATE call_count = call_count + #{count}, updated_at = NOW()
|
|
||||||
|
|||||||
|
Can't render this file because it contains an unexpected character in line 1 and column 222.
|
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB |
@@ -135,7 +135,13 @@ import { checkParseResult, checkQueuePayload } from '@/shared/dispatch-guard'
|
|||||||
import { passGuard } from '@/shared/dispatch-guard-ui'
|
import { passGuard } from '@/shared/dispatch-guard-ui'
|
||||||
import { formatDateTime } from '@/shared/utils/datetime'
|
import { formatDateTime } from '@/shared/utils/datetime'
|
||||||
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||||
import { ensureBrandCheckProxy, getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
import {
|
||||||
|
ensureBrandCheckProxy,
|
||||||
|
getApiSecretGateState,
|
||||||
|
getStoredApiSecret,
|
||||||
|
getStoredApiSecretSnapshot,
|
||||||
|
listApiSecretModules,
|
||||||
|
} from '@/shared/utils/api-secret-store'
|
||||||
|
|
||||||
// ---- 文件选择 / 上传(公共组合式函数)----
|
// ---- 文件选择 / 上传(公共组合式函数)----
|
||||||
const {
|
const {
|
||||||
@@ -536,15 +542,42 @@ async function ensureBrandCheckProxyReady(): Promise<boolean> {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 模块名取服务端下发的 label,前端不再另起一份叫法;默认清单里必有本模块,兜底句只为满足类型。 */
|
||||||
|
function llmKeyModuleLabel(): string {
|
||||||
|
return listApiSecretModules().find((info) => info.moduleKey === 'appearance-patent')?.moduleLabel || '对应模块密钥'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建任务前确认这个模块的 LLM 密钥已配置:服务端建单口(UserApiSecretService#requireSubmitSecret)
|
||||||
|
* 也会拒,但那时 Excel 已上传、单已建一半,用户白等一趟,所以把同一句话提到提交前说。
|
||||||
|
* 门禁状态 unknown(从未成功拉到服务端数据)不拦——网络抖动不等于未配置,与 ensureBrandCheckProxy 同口径。
|
||||||
|
*/
|
||||||
|
async function ensureLlmApiKeyReady(): Promise<boolean> {
|
||||||
|
if (getApiSecretGateState() === 'unknown') return true
|
||||||
|
const snapshot = getStoredApiSecretSnapshot('appearance-patent')
|
||||||
|
// exists + 检测通过才算配好;error(上游无法判定)按放行,与 computeApiSecretsComplete 同一判据
|
||||||
|
const configured = (snapshot.exists && (snapshot.checkStatus === 'passed' || snapshot.checkStatus === 'error'))
|
||||||
|
|| Boolean(effectiveLlmApiKey())
|
||||||
|
if (configured) return true
|
||||||
|
await ElMessageBox.alert(
|
||||||
|
`该账号还没有配置${llmKeyModuleLabel()}:这一单要用它跑 LLM 检测,`
|
||||||
|
+ '缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。',
|
||||||
|
'未配置密钥,无法创建任务',
|
||||||
|
{ type: 'warning', confirmButtonText: '知道了' },
|
||||||
|
).then(
|
||||||
|
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
|
||||||
|
() => undefined,
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
async function parseFiles() {
|
async function parseFiles() {
|
||||||
if (!uploadedFiles.value.length) {
|
if (!uploadedFiles.value.length) {
|
||||||
ElMessage.warning('请先选择 Excel')
|
ElMessage.warning('请先选择 Excel')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!effectiveLlmApiKey()) {
|
if (!(await ensureLlmApiKeyReady())) return
|
||||||
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
|
|
||||||
console.log('[appearance-patent] 本地无密钥明文,提交时由服务端按用户密钥兜底')
|
|
||||||
}
|
|
||||||
parsing.value = true
|
parsing.value = true
|
||||||
try {
|
try {
|
||||||
if (!(await ensureBrandCheckProxyReady())) {
|
if (!(await ensureBrandCheckProxyReady())) {
|
||||||
|
|||||||
@@ -132,7 +132,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||||
import { userNotice } from '@/shared/utils/user-notice'
|
import { userNotice } from '@/shared/utils/user-notice'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import { retryClientTask } from '@/shared/api/task-retry'
|
import { retryClientTask } from '@/shared/api/task-retry'
|
||||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||||
@@ -170,7 +170,12 @@ import { passGuard } from '@/shared/dispatch-guard-ui'
|
|||||||
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
|
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
|
||||||
import { formatDateTime } from '@/shared/utils/datetime'
|
import { formatDateTime } from '@/shared/utils/datetime'
|
||||||
import { isCompletedTask, resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
import { isCompletedTask, resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||||
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
import {
|
||||||
|
getApiSecretGateState,
|
||||||
|
getStoredApiSecret,
|
||||||
|
getStoredApiSecretSnapshot,
|
||||||
|
listApiSecretModules,
|
||||||
|
} from '@/shared/utils/api-secret-store'
|
||||||
|
|
||||||
// ---- 文件选择 / 上传(公共组合式函数)----
|
// ---- 文件选择 / 上传(公共组合式函数)----
|
||||||
const {
|
const {
|
||||||
@@ -529,15 +534,42 @@ function toTaskSummary(result: SimilarAsinParseVo): TaskSummary {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 模块名取服务端下发的 label,前端不再另起一份叫法;默认清单里必有本模块,兜底句只为满足类型。 */
|
||||||
|
function llmKeyModuleLabel(): string {
|
||||||
|
return listApiSecretModules().find((info) => info.moduleKey === 'similar-asin')?.moduleLabel || '对应模块密钥'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建任务前确认这个模块的 LLM 密钥已配置:服务端建单口(UserApiSecretService#requireSubmitSecret)
|
||||||
|
* 也会拒,但那时 Excel 已上传、单已建一半,用户白等一趟,所以把同一句话提到提交前说。
|
||||||
|
* 门禁状态 unknown(从未成功拉到服务端数据)不拦——网络抖动不等于未配置,与商标 Tab 的代理前置同口径。
|
||||||
|
*/
|
||||||
|
async function ensureLlmApiKeyReady(): Promise<boolean> {
|
||||||
|
if (getApiSecretGateState() === 'unknown') return true
|
||||||
|
const snapshot = getStoredApiSecretSnapshot('similar-asin')
|
||||||
|
// exists + 检测通过才算配好;error(上游无法判定)按放行,与 computeApiSecretsComplete 同一判据
|
||||||
|
const configured = (snapshot.exists && (snapshot.checkStatus === 'passed' || snapshot.checkStatus === 'error'))
|
||||||
|
|| Boolean(effectiveLlmApiKey())
|
||||||
|
if (configured) return true
|
||||||
|
await ElMessageBox.alert(
|
||||||
|
`该账号还没有配置${llmKeyModuleLabel()}:这一单要用它跑 LLM 检测,`
|
||||||
|
+ '缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。',
|
||||||
|
'未配置密钥,无法创建任务',
|
||||||
|
{ type: 'warning', confirmButtonText: '知道了' },
|
||||||
|
).then(
|
||||||
|
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
|
||||||
|
() => undefined,
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
async function parseFiles() {
|
async function parseFiles() {
|
||||||
if (!uploadedFiles.value.length) {
|
if (!uploadedFiles.value.length) {
|
||||||
ElMessage.warning('请先选择 Excel')
|
ElMessage.warning('请先选择 Excel')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!effectiveLlmApiKey()) {
|
if (!(await ensureLlmApiKeyReady())) return
|
||||||
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
|
|
||||||
console.log('[similar-asin] 本地无密钥明文,提交时由服务端按用户密钥兜底')
|
|
||||||
}
|
|
||||||
if (!getRequiredAlipriceCredentials()) return
|
if (!getRequiredAlipriceCredentials()) return
|
||||||
parsing.value = true
|
parsing.value = true
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { createCategorizedTimers } from '../utils/categorized-timers.ts'
|
|||||||
import { saveUrlWithProgress } from '../utils/download-progress.ts'
|
import { saveUrlWithProgress } from '../utils/download-progress.ts'
|
||||||
import { runBatchDelete } from '../utils/batch-delete.ts'
|
import { runBatchDelete } from '../utils/batch-delete.ts'
|
||||||
import { isTerminalTaskStatus } from '../utils/task-terminal.ts'
|
import { isTerminalTaskStatus } from '../utils/task-terminal.ts'
|
||||||
|
import { resolveTaskDeleteTarget } from '../utils/task-delete-target.ts'
|
||||||
|
import { isRecordMissingError } from '../utils/task-queue-state.ts'
|
||||||
import { confirmTaskDeletion } from '../task-delete-confirm.ts'
|
import { confirmTaskDeletion } from '../task-delete-confirm.ts'
|
||||||
import type { TaskItemView } from '../components/tasks/types'
|
import type { TaskItemView } from '../components/tasks/types'
|
||||||
|
|
||||||
@@ -638,31 +640,49 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteTaskRecord(item: T) {
|
async function deleteTaskRecord(item: T, opts: { skipConfirm?: boolean } = {}) {
|
||||||
if (!(await confirmTaskDeletion(item))) return
|
if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
|
||||||
|
const deleteOptions = options.deleteTask
|
||||||
try {
|
try {
|
||||||
const status = normalizeTaskStatus(item)
|
const status = normalizeTaskStatus(item)
|
||||||
const deleteOptions = options.deleteTask
|
const target = resolveTaskDeleteTarget({
|
||||||
if (deleteOptions && deleteOptions.shouldDeleteTask(item, status)) {
|
hasDeleteOptions: Boolean(deleteOptions),
|
||||||
await deleteOptions.deleteTask(item.taskId as number)
|
taskId: item.taskId,
|
||||||
deleteOptions.onTaskDeleted?.(item)
|
resultId: item.resultId,
|
||||||
} else if (item.resultId && deleteOptions) {
|
shouldDeleteTask: Boolean(deleteOptions && deleteOptions.shouldDeleteTask(item, status)),
|
||||||
await deleteOptions.deleteHistory(item.resultId)
|
})
|
||||||
deleteOptions.onHistoryDeleted?.(item)
|
if (target === 'task') {
|
||||||
|
await deleteOptions!.deleteTask(item.taskId as number)
|
||||||
|
deleteOptions!.onTaskDeleted?.(item)
|
||||||
|
} else if (target === 'history') {
|
||||||
|
await deleteOptions!.deleteHistory(item.resultId as number)
|
||||||
|
deleteOptions!.onHistoryDeleted?.(item)
|
||||||
|
} else {
|
||||||
|
// 没有任务也没有结果标识:宁可报错也不能假报「已删除」把用户挡在死胡同里
|
||||||
|
throw new Error('该记录缺少任务/结果标识,无法删除,请刷新后重试')
|
||||||
}
|
}
|
||||||
await loadDashboard()
|
await loadDashboard()
|
||||||
await loadHistory({ force: true })
|
await loadHistory({ force: true })
|
||||||
ElMessage.success('已删除')
|
ElMessage.success('已删除')
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if (isRecordMissingError(e)) {
|
||||||
|
// 记录已被别处删掉(多标签/多端):本地同步移除并刷新,别让「记录不存在」被当成删除失败
|
||||||
|
if (item.taskId != null) deleteOptions?.onTaskDeleted?.(item)
|
||||||
|
await loadDashboard().catch(() => undefined)
|
||||||
|
await loadHistory({ force: true }).catch(() => undefined)
|
||||||
|
ElMessage.success('记录已不存在,已同步移除本地记录')
|
||||||
|
return
|
||||||
|
}
|
||||||
ElMessage.error(e instanceof Error ? e.message : '删除失败')
|
ElMessage.error(e instanceof Error ? e.message : '删除失败')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
|
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)。
|
||||||
|
* 批量入口已经弹过一次确认,逐条不再重复弹框。
|
||||||
*/
|
*/
|
||||||
async function batchDeleteHistory(views: TaskItemView[]) {
|
async function batchDeleteHistory(views: TaskItemView[]) {
|
||||||
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T))
|
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T, { skipConfirm: true }))
|
||||||
if (!total) return
|
if (!total) return
|
||||||
if (failed > 0) {
|
if (failed > 0) {
|
||||||
ElMessage.warning(`删除完成,${failed} 条失败`)
|
ElMessage.warning(`删除完成,${failed} 条失败`)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* 任务/历史记录删除的目标判定(纯函数,供 useLiveTaskBoard 与各 Tab 共用)。
|
||||||
|
*
|
||||||
|
* 背景(2026-10-29 现网):外观专利只有 RUNNING 才走「删任务」,其余只删结果行。
|
||||||
|
* 失败任务一旦被自动克隆重试(克隆件没有结果行),列表里既删不掉那条任务,
|
||||||
|
* 批量删除时还会静默跳过、只弹「已删除」——用户看到的就是「删不了」。
|
||||||
|
* 这里把判定收成三条:能删任务就删任务(整条记录含统计与重试链),
|
||||||
|
* 没有任务才回退删结果行,两者都没有必须显式失败,不允许假成功。
|
||||||
|
*/
|
||||||
|
export type TaskDeleteTarget = 'task' | 'history' | 'none'
|
||||||
|
|
||||||
|
export interface TaskDeleteTargetInput {
|
||||||
|
/** options.deleteTask 是否配置(未配置的看板只能回退删结果行) */
|
||||||
|
hasDeleteOptions: boolean
|
||||||
|
taskId?: number | null
|
||||||
|
resultId?: number | null
|
||||||
|
/** 调用方对「这一条该不该删任务」的判定结果(各 Tab 口径不同) */
|
||||||
|
shouldDeleteTask: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveTaskDeleteTarget(input: TaskDeleteTargetInput): TaskDeleteTarget {
|
||||||
|
if (!input.hasDeleteOptions) return 'none'
|
||||||
|
if (input.taskId != null && input.shouldDeleteTask) return 'task'
|
||||||
|
if (input.resultId != null) return 'history'
|
||||||
|
return 'none'
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* 外观专利删除链路的守卫(2026-10-29 现网「删不了」)。
|
||||||
|
*
|
||||||
|
* 现网证据:失败任务被自动克隆重试后(克隆件复制源结果行、开始时间逐字相同、
|
||||||
|
* 后几代克隆连结果行都没有),旧口径只给 RUNNING 删任务、其余只删结果行——
|
||||||
|
* 没有结果行的任务在列表里既没有删除按钮,批量全选删到它也静默跳过只弹「已删除」,
|
||||||
|
* 用户看到的就是「删不了」。这与巡店删除页已经收敛的正确口径不一致。
|
||||||
|
*
|
||||||
|
* 这里钉住四件事:
|
||||||
|
* ①外观专利改为「有任务就删任务」,不再用 RUNNING 当门;
|
||||||
|
* ②历史行只要有任务/结果标识就出删除按钮;
|
||||||
|
* ③缺标识必须显式报错,不允许假报「已删除」;
|
||||||
|
* ④批量删除只弹一次确认,不再逐条二次弹框。
|
||||||
|
*
|
||||||
|
* 跑法:`node --test tests/appearance-patent-task-delete.test.ts`
|
||||||
|
*/
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { resolve, dirname } from 'node:path'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const tabSource = readFileSync(
|
||||||
|
resolve(here, '../src/pages/brand/components/BrandAppearancePatentTab.vue'),
|
||||||
|
'utf-8',
|
||||||
|
)
|
||||||
|
const boardSource = readFileSync(
|
||||||
|
resolve(here, '../src/shared/composables/useLiveTaskBoard.ts'),
|
||||||
|
'utf-8',
|
||||||
|
)
|
||||||
|
|
||||||
|
function slot(name: string): string {
|
||||||
|
const match = tabSource.match(
|
||||||
|
new RegExp(`<template #${name}="\\{ item \\}">([\\s\\S]*?)</template>`),
|
||||||
|
)
|
||||||
|
assert.ok(match, `找不到 #${name} 插槽`)
|
||||||
|
return match[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
test('外观专利删任务不再限定 RUNNING:有 taskId 就删任务', () => {
|
||||||
|
const match = tabSource.match(/shouldDeleteTask:\s*\(item\)\s*=>\s*([^,\n]+),/)
|
||||||
|
assert.ok(match, '找不到 shouldDeleteTask 谓词')
|
||||||
|
assert.match(match[1], /item\.taskId\s*!=\s*null/, '谓词必须认 taskId')
|
||||||
|
assert.doesNotMatch(match[1], /RUNNING/, '用 RUNNING 当门会让失败/克隆任务永远删不掉')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('历史行有任务或结果标识就要出删除按钮(克隆件没有结果行)', () => {
|
||||||
|
const history = slot('history-item-actions')
|
||||||
|
assert.match(
|
||||||
|
history,
|
||||||
|
/v-if="itemSource\(item\)\.taskId \|\| itemSource\(item\)\.resultId"/,
|
||||||
|
'只按 resultId 出按钮时,没有结果行的任务在列表里无法删除',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('缺标识必须报错而不是假报已删除', () => {
|
||||||
|
assert.match(boardSource, /resolveTaskDeleteTarget\(/, '删除目标必须走统一判定')
|
||||||
|
assert.match(
|
||||||
|
boardSource,
|
||||||
|
/throw new Error\('该记录缺少任务\/结果标识/,
|
||||||
|
'none 分支必须抛错,否则点击删除既不请求也不报错,用户以为删掉了',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('记录已不存在时自愈:同步移除本地记录而不是报删除失败', () => {
|
||||||
|
assert.match(boardSource, /isRecordMissingError\(e\)/, '必须识别「任务不存在/记录不存在」')
|
||||||
|
assert.match(boardSource, /记录已不存在,已同步移除本地记录/, '记录已不存在要有可见的同步提示')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('批量删除不再逐条弹二次确认', () => {
|
||||||
|
assert.match(
|
||||||
|
boardSource,
|
||||||
|
/deleteTaskRecord\(.*\{ skipConfirm: true \}\)/,
|
||||||
|
'批量入口已确认过一次,逐条再弹框会让用户以为批量删除没生效',
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { resolve, dirname } from 'node:path'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交前置:没配 LLM 密钥就别把单建出去(BACKLOG B72-02 / 蓝图 Phase 4 ③)。
|
||||||
|
*
|
||||||
|
* 服务端建单口 `UserApiSecretService#requireSubmitSecret` 已经会拒这一单,但那是用户上传完
|
||||||
|
* Excel、点了提交之后才吃到的错误;执行侧的老写法更是直接「保留原始行」把单跑完——表照样出、
|
||||||
|
* 行数照样扣,只是整列 LLM 检测结论是空的(AGENTS.md 铁律 27)。所以这里要在**建单之前**把
|
||||||
|
* 同一句话说清,且文案与服务端同源:模块名取服务端下发的 `moduleLabel`,前端不另起一份叫法。
|
||||||
|
*
|
||||||
|
* 三把尺子:① 接线次序(前置必须早于 `parsing.value = true` 与建单调用);② 弹窗文案的四个
|
||||||
|
* 服务端片段+不硬编模块名;③ `unknown`(从未成功拉到服务端数据)必须软失败放行——网络抖动
|
||||||
|
* 不等于未配置。反向自证逐条把实现改坏,确认每条都真的会红。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||||
|
const read = (rel: string) => readFileSync(resolve(repoRoot, rel), 'utf-8')
|
||||||
|
|
||||||
|
interface TabSpec {
|
||||||
|
name: string
|
||||||
|
file: string
|
||||||
|
moduleKey: string
|
||||||
|
/** 建单落库的那次调用,用于判「前置是否早于建单」。 */
|
||||||
|
createCall: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABS: TabSpec[] = [
|
||||||
|
{
|
||||||
|
name: '外观专利 Tab',
|
||||||
|
file: 'src/pages/brand/components/BrandAppearancePatentTab.vue',
|
||||||
|
moduleKey: 'appearance-patent',
|
||||||
|
createCall: 'parseAppearancePatent(',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '相似 ASIN Tab',
|
||||||
|
file: 'src/pages/brand/components/BrandSimilarAsinTab.vue',
|
||||||
|
moduleKey: 'similar-asin',
|
||||||
|
createCall: 'parseSimilarAsin(',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const GATE_CALL = 'if (!(await ensureLlmApiKeyReady())) return'
|
||||||
|
|
||||||
|
/** 截取函数体:先按括号配平跳过参数列表,再按花括号配平取函数体;找不到签名返回 null 交给调用方判红。 */
|
||||||
|
function functionBodyOrNull(source: string, signature: string): string | null {
|
||||||
|
const start = source.indexOf(signature)
|
||||||
|
if (start < 0) return null
|
||||||
|
const openParen = source.indexOf('(', start)
|
||||||
|
let parenDepth = 0
|
||||||
|
let cursor = openParen
|
||||||
|
for (; cursor < source.length; cursor += 1) {
|
||||||
|
if (source[cursor] === '(') parenDepth += 1
|
||||||
|
else if (source[cursor] === ')') {
|
||||||
|
parenDepth -= 1
|
||||||
|
if (parenDepth === 0) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const openBrace = source.indexOf('{', cursor)
|
||||||
|
let depth = 0
|
||||||
|
for (let i = openBrace; i < source.length; i += 1) {
|
||||||
|
if (source[i] === '{') depth += 1
|
||||||
|
else if (source[i] === '}') {
|
||||||
|
depth -= 1
|
||||||
|
if (depth === 0) return source.slice(openBrace, i + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 对整份 Tab 源码取违规清单:空清单=接线正确。反向自证喂进来的也是同一份判据,不另写一套。 */
|
||||||
|
function gateViolations(source: string, spec: TabSpec): string[] {
|
||||||
|
const out: string[] = []
|
||||||
|
const parseBody = functionBodyOrNull(source, 'async function parseFiles(')
|
||||||
|
const guardBody = functionBodyOrNull(source, 'async function ensureLlmApiKeyReady(')
|
||||||
|
const labelBody = functionBodyOrNull(source, 'function llmKeyModuleLabel(')
|
||||||
|
if (!parseBody) out.push(`${spec.name} 找不到 parseFiles`)
|
||||||
|
if (!guardBody) out.push(`${spec.name} 缺少密钥前置函数 ensureLlmApiKeyReady`)
|
||||||
|
if (!labelBody) out.push(`${spec.name} 缺少模块名取数函数 llmKeyModuleLabel`)
|
||||||
|
|
||||||
|
if (parseBody) {
|
||||||
|
const gateIdx = parseBody.indexOf('ensureLlmApiKeyReady()')
|
||||||
|
const createIdx = parseBody.indexOf(spec.createCall)
|
||||||
|
const parsingIdx = parseBody.indexOf('parsing.value = true')
|
||||||
|
if (gateIdx < 0) out.push(`${spec.name} 的 parseFiles 没接密钥前置`)
|
||||||
|
if (createIdx < 0) out.push(`${spec.name} 的 parseFiles 找不到建单调用 ${spec.createCall}`)
|
||||||
|
if (gateIdx >= 0 && createIdx >= 0 && gateIdx > createIdx) {
|
||||||
|
out.push(`${spec.name}:密钥前置落在了建单之后,单已经建出去了才提示`)
|
||||||
|
}
|
||||||
|
if (gateIdx >= 0 && parsingIdx >= 0 && gateIdx > parsingIdx) {
|
||||||
|
out.push(`${spec.name}:密钥前置晚于 parsing.value = true,没做在昂贵动作之前`)
|
||||||
|
}
|
||||||
|
if (parseBody.includes('本地无密钥明文')) {
|
||||||
|
out.push(`${spec.name}:parseFiles 仍留着「本地无明文不再阻断」的死分支(console.log 不等于拦住用户)`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (guardBody) {
|
||||||
|
if (!/getApiSecretGateState\(\)\s*===\s*'unknown'\s*\)\s*return true/.test(guardBody)) {
|
||||||
|
out.push(`${spec.name}:unknown 没有 return true 放行——门禁状态读不到时不该拦用户提交`)
|
||||||
|
}
|
||||||
|
const unknownIdx = guardBody.indexOf("'unknown'")
|
||||||
|
const alertIdx = guardBody.indexOf('ElMessageBox.alert')
|
||||||
|
if (alertIdx < 0) out.push(`${spec.name}:缺密钥时没有弹窗提示,只是静默 return`)
|
||||||
|
if (unknownIdx >= 0 && alertIdx >= 0 && unknownIdx > alertIdx) {
|
||||||
|
out.push(`${spec.name}:unknown 的放行判断晚于弹窗,等于仍然拦人`)
|
||||||
|
}
|
||||||
|
// 文案四个片段与服务端 requireSubmitSecret 逐字同源
|
||||||
|
for (const fragment of ['该账号还没有配置', '这一单要用它跑 LLM 检测', '没有检测结论的结果表', '请先在「密钥设置」里填好并保存']) {
|
||||||
|
if (!guardBody.includes(fragment)) out.push(`${spec.name}:弹窗文案缺服务端同源片段「${fragment}」`)
|
||||||
|
}
|
||||||
|
if (!guardBody.includes('密钥设置')) out.push(`${spec.name}:弹窗没告诉用户去哪里补密钥`)
|
||||||
|
if (!guardBody.includes('${llmKeyModuleLabel()}')) {
|
||||||
|
out.push(`${spec.name}:弹窗模块名没有取 listApiSecretModules 的 label(前端另起叫法=两套文案)`)
|
||||||
|
}
|
||||||
|
if (!guardBody.includes(`getStoredApiSecretSnapshot('${spec.moduleKey}')`)) {
|
||||||
|
out.push(`${spec.name}:前置应查本模块(${spec.moduleKey})的快照,不能拿全局完整性一档误伤别的模块`)
|
||||||
|
}
|
||||||
|
if (!guardBody.includes("checkStatus === 'passed'") || !guardBody.includes("checkStatus === 'error'")) {
|
||||||
|
out.push(`${spec.name}:检测状态判据与 computeApiSecretsComplete 不同源(error=无法判定应按放行)`)
|
||||||
|
}
|
||||||
|
for (const hardcoded of ['外观专利密钥', '货源查询密钥']) {
|
||||||
|
if (guardBody.includes(hardcoded) || labelBody?.includes(hardcoded)) {
|
||||||
|
out.push(`${spec.name}:模块名「${hardcoded}」被硬编进前端文案`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tail = guardBody.slice(Math.max(alertIdx, 0))
|
||||||
|
const swallowed = (tail.match(/\(\) => undefined,/g) ?? []).length
|
||||||
|
if (alertIdx >= 0 && swallowed < 2) {
|
||||||
|
out.push(`${spec.name}:弹窗关闭会以 reject 收尾,必须用 .then(成功, 失败) 双回调接住(两个 () => undefined)`)
|
||||||
|
}
|
||||||
|
if (/catch\s*[({]/.test(guardBody)) {
|
||||||
|
out.push(`${spec.name}:给弹窗 reject 加了 catch——本仓对无声出口有棘轮,请用 .then 双回调`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (labelBody) {
|
||||||
|
if (!labelBody.includes('listApiSecretModules()')) {
|
||||||
|
out.push(`${spec.name}:模块名不是从 listApiSecretModules()(服务端下发 label)取的`)
|
||||||
|
}
|
||||||
|
if (!labelBody.includes(`moduleKey === '${spec.moduleKey}'`)) {
|
||||||
|
out.push(`${spec.name}:模块名查错了 key,应当查 ${spec.moduleKey}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const spec of TABS) {
|
||||||
|
test(`${spec.name}:提交前密钥门禁已接线(次序+文案+unknown 放行)`, () => {
|
||||||
|
assert.deepEqual(gateViolations(read(spec.file), spec), [], '接线不合规')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 摘掉前置这一行——接线判据必须报「没接密钥前置」。 */
|
||||||
|
function dropGate(source: string): string {
|
||||||
|
return source.replace(` ${GATE_CALL}\n`, '')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把前置挪到建单调用之后——单已经建出去了才提示,次序判据必须报「建单之后」。 */
|
||||||
|
function moveGateAfterCreate(source: string, spec: TabSpec): string {
|
||||||
|
const withoutGate = dropGate(source)
|
||||||
|
const createIdx = withoutGate.indexOf(spec.createCall)
|
||||||
|
assert.ok(createIdx >= 0, '建单调用锚点丢了')
|
||||||
|
const lineEnd = withoutGate.indexOf('\n', createIdx)
|
||||||
|
return withoutGate.slice(0, lineEnd + 1) + ` ${GATE_CALL}\n` + withoutGate.slice(lineEnd + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 让 unknown 也拦人——放行判据必须报 unknown。 */
|
||||||
|
function unknownBlocks(source: string): string {
|
||||||
|
const mutated = source.replace(
|
||||||
|
"if (getApiSecretGateState() === 'unknown') return true",
|
||||||
|
"if (getApiSecretGateState() === 'unknown') return false",
|
||||||
|
)
|
||||||
|
assert.notEqual(mutated, source, 'unknown 分支锚点丢了,注入没生效')
|
||||||
|
return mutated
|
||||||
|
}
|
||||||
|
|
||||||
|
test('反向自证:摘掉前置/挪到建单之后/让 unknown 拦人,判据逐条变红且红在该红的原因上', () => {
|
||||||
|
for (const spec of TABS) {
|
||||||
|
const source = read(spec.file)
|
||||||
|
assert.deepEqual(gateViolations(source, spec), [], `${spec.name} 正本本就该是零违规,否则下面的自证不可信`)
|
||||||
|
|
||||||
|
const dropped = dropGate(source)
|
||||||
|
assert.notEqual(dropped, source, `${spec.name} 的前置调用行没被摘掉,注入是假的`)
|
||||||
|
const droppedViolations = gateViolations(dropped, spec)
|
||||||
|
assert.ok(droppedViolations.length > 0, `${spec.name}:摘掉前置后判据仍全绿=这条判据是摆设`)
|
||||||
|
assert.ok(droppedViolations.some((v) => v.includes('没接密钥前置')),
|
||||||
|
`${spec.name}:摘掉前置的读数应落在「没接密钥前置」,实测 ${droppedViolations.join(' / ')}`)
|
||||||
|
|
||||||
|
const moved = moveGateAfterCreate(source, spec)
|
||||||
|
assert.notEqual(moved, source, `${spec.name} 的前置没被挪动,注入是假的`)
|
||||||
|
const movedViolations = gateViolations(moved, spec)
|
||||||
|
assert.ok(movedViolations.some((v) => v.includes('建单之后')),
|
||||||
|
`${spec.name}:前置挪到建单之后应落在「建单之后」,实测 ${movedViolations.join(' / ')}`)
|
||||||
|
|
||||||
|
const blocked = unknownBlocks(source)
|
||||||
|
const blockedViolations = gateViolations(blocked, spec)
|
||||||
|
assert.ok(blockedViolations.length > 0, `${spec.name}:unknown 改成拦人后判据仍全绿=这条判据是摆设`)
|
||||||
|
assert.ok(blockedViolations.some((v) => v.includes('unknown')),
|
||||||
|
`${spec.name}:unknown 拦人应落在 unknown 那条,实测 ${blockedViolations.join(' / ')}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('反向自证:把模块名硬编回文案,判据要报「被硬编」', () => {
|
||||||
|
for (const spec of TABS) {
|
||||||
|
const source = read(spec.file)
|
||||||
|
const hardcoded = source.replace('${llmKeyModuleLabel()}', '外观专利密钥')
|
||||||
|
assert.notEqual(hardcoded, source, '插值锚点丢了')
|
||||||
|
const violations = gateViolations(hardcoded, spec)
|
||||||
|
assert.ok(violations.some((v) => v.includes('没有取 listApiSecretModules')),
|
||||||
|
`硬编模块名后应报「没有取 label」,实测 ${violations.join(' / ')}`)
|
||||||
|
assert.ok(violations.some((v) => v.includes('被硬编进前端文案')),
|
||||||
|
`硬编模块名后应报「被硬编」,实测 ${violations.join(' / ')}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/**
|
||||||
|
* 删除目标判定的回归用例(2026-10-29 现网「外观专利删不了」)。
|
||||||
|
*
|
||||||
|
* 症状:失败任务被自动克隆重试后,克隆件没有结果行;旧口径只给 RUNNING 删任务、
|
||||||
|
* 其余只删结果行,于是这些任务在列表里删不掉,批量全选时还静默跳过、仍弹「已删除」。
|
||||||
|
* 这里钉住三条:有任务且允许删任务 → 删任务;否则有结果行 → 删结果行;
|
||||||
|
* 两者都没有必须返回 none(调用方据此报错,不许假成功)。
|
||||||
|
*
|
||||||
|
* 跑法:`node --test tests/task-delete-target.test.ts`
|
||||||
|
*/
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { resolveTaskDeleteTarget } from '../src/shared/utils/task-delete-target.ts'
|
||||||
|
|
||||||
|
test('有任务且调用方允许删任务时优先删任务(失败任务/克隆件也能整条删除)', () => {
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: true, taskId: 32744, resultId: undefined, shouldDeleteTask: true }),
|
||||||
|
'task',
|
||||||
|
)
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: true, taskId: 32699, resultId: 35621, shouldDeleteTask: true }),
|
||||||
|
'task',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('不允许删任务时回退删结果行(相似 ASIN 的终态口径)', () => {
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: true, taskId: 32699, resultId: 35621, shouldDeleteTask: false }),
|
||||||
|
'history',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('只有任务、不允许删任务、也没有结果行时返回 none,不得当成已删除', () => {
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: true, taskId: 32744, resultId: undefined, shouldDeleteTask: false }),
|
||||||
|
'none',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('没有任何任务/结果标识时返回 none', () => {
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: true, shouldDeleteTask: true }),
|
||||||
|
'none',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('看板未配置删除选项时返回 none', () => {
|
||||||
|
assert.equal(
|
||||||
|
resolveTaskDeleteTarget({ hasDeleteOptions: false, taskId: 1, resultId: 2, shouldDeleteTask: true }),
|
||||||
|
'none',
|
||||||
|
)
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user