Add idempotent reuse to simulation create to prevent double billing

This commit is contained in:
gitea committed 2026-09-28 14:39:38 +08:00
1 parent b8fd304f0d
commit fffa0cf2e4
9 files changed
+495 -182

No files matched your search

+2
View File
@@ -93,6 +93,8 @@ export async function handleSimulationCommand(
endTime: numberOption(args.options.endTime) ?? numberOption(args.options["end-time"]),
status: splitOption(args.options.status),
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
reuseWindow: stringOption(args.options["reuse-window"]) ?? stringOption(args.options.reuseWindow),
noWait,
rawParams: inputPayload
}
+2 -2
View File
@@ -603,9 +603,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "create",
summary: "Trigger a new simulation batch",
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window)",
usage: [
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp <corpId>]",
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
]
+194 -1
View File
@@ -11,9 +11,10 @@ import {
listSimulationTemplates,
uploadMaterialPackage
} from "./api.js";
import { buildSimulationBatchParams, sealTools } from "./tools.js";
import { buildSimulationBatchParams, findReusableSimulationBatch, sealTools } from "./tools.js";
import {
MaterialPackageSchema,
SimulationBatch,
SimulationBatchSchema,
SimulationIntegrationStatusSchema,
SimulationTemplateSchema
@@ -461,6 +462,71 @@ describe("simulation API client", () => {
});
});
describe("findReusableSimulationBatch", () => {
const NOW = Date.parse("2026-09-28T08:00:00.000Z");
const WINDOW_MS = 5 * 60 * 1000;
const reusableBatch: SimulationBatch = SimulationBatchSchema.parse({
...hosecloudBatchFixture,
id: "01a0e699-existing",
status: "running",
createdAt: "2026-09-28T07:57:30.000Z"
});
test("reuses a batch with the same flow ids inside the window", () => {
const match = findReusableSimulationBatch([reusableBatch], { flowIds: ["B26017701"] }, WINDOW_MS, NOW);
expect(match?.id).toBe("01a0e699-existing");
});
test("matches regardless of flow id order or duplicates", () => {
const batch = { ...reusableBatch, params: { ...reusableBatch.params!, flowIds: ["B26028572", "B26022501"] } };
const match = findReusableSimulationBatch([batch], { flowIds: ["B26022501", "B26028572", "B26028572"] }, WINDOW_MS, NOW);
expect(match?.id).toBe("01a0e699-existing");
});
test("ignores batches created outside the reuse window", () => {
const old = { ...reusableBatch, createdAt: "2026-09-28T07:50:00.000Z" };
expect(findReusableSimulationBatch([old], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
});
test("ignores failed and cancelled batches but reuses completed ones", () => {
const failed = { ...reusableBatch, status: "FAILED" };
const cancelled = { ...reusableBatch, status: "Cancelled" };
const completed = { ...reusableBatch, status: "COMPLETED" };
expect(findReusableSimulationBatch([failed], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
expect(findReusableSimulationBatch([cancelled], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
expect(findReusableSimulationBatch([completed], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)?.status).toBe("COMPLETED");
});
test("ignores different flow ids, missing createdAt, and mismatched signKey", () => {
expect(findReusableSimulationBatch([reusableBatch], { flowIds: ["B99999999"] }, WINDOW_MS, NOW)).toBeNull();
const undated = { ...reusableBatch, createdAt: undefined };
expect(findReusableSimulationBatch([undated], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
const otherSignKey = { ...reusableBatch, params: { ...reusableBatch.params!, signKey: "other-key" } };
expect(
findReusableSimulationBatch([otherSignKey], { flowIds: ["B26017701"], signKey: SIGN_KEY }, WINDOW_MS, NOW)
).toBeNull();
});
test("matches material pack batches by package ids", () => {
const packBatch = {
...reusableBatch,
params: { approvalCode: "material_pack", packageIds: ["pkg-1", "pkg-2"] }
};
const match = findReusableSimulationBatch([packBatch], { packageIds: ["pkg-2", "pkg-1"] }, WINDOW_MS, NOW);
expect(match?.id).toBe("01a0e699-existing");
expect(findReusableSimulationBatch([packBatch], { packageIds: ["pkg-9"] }, WINDOW_MS, NOW)).toBeNull();
});
test("accepts epoch millis createdAt", () => {
const batch = { ...reusableBatch, createdAt: NOW - 60_000 };
expect(findReusableSimulationBatch([batch], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)?.id).toBe("01a0e699-existing");
});
test("returns null without an identity key", () => {
expect(findReusableSimulationBatch([reusableBatch], {}, WINDOW_MS, NOW)).toBeNull();
});
});
describe("simulation tool handlers", () => {
test("create tool resolves signKey automatically and posts the payload", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
@@ -477,6 +543,9 @@ describe("simulation tool handlers", () => {
})
};
}
if (url === "api/v1/simulation/batches") {
return { json: async () => ({ data: [] }) };
}
throw new Error(`unexpected url ${url}`);
},
post: (url: string, options: { json: Record<string, unknown> }) => {
@@ -509,6 +578,130 @@ describe("simulation tool handlers", () => {
});
});
test("create tool reuses a recent identical batch instead of creating a new one", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
expect(tool).toBeDefined();
let postCalls = 0;
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/hosecloud-integrations") {
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
}
if (url === "api/v1/simulation/batches") {
return {
json: async () => ({
data: [{
...hosecloudBatchFixture,
id: "01a0e699-existing",
status: "running",
createdAt: new Date(Date.now() - 90_000).toISOString()
}]
})
};
}
throw new Error(`unexpected url ${url}`);
},
post: () => {
postCalls += 1;
throw new Error("must not create a new batch when an identical one is reusable");
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {
mode: "hosecloud",
flowIds: ["B26017701"]
}, fakeContext()) as Record<string, unknown>;
expect(postCalls).toBe(0);
expect(result).toMatchObject({
batchId: "01a0e699-existing",
created: false,
reused: true,
asyncTicket: "01a0e699-existing"
});
expect(result.message).toContain("复用");
});
test("create tool force bypasses the reuse check", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
let posted = false;
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/hosecloud-integrations") {
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
}
if (url === "api/v1/simulation/batches") {
return {
json: async () => ({
data: [{
...hosecloudBatchFixture,
id: "01a0e699-existing",
status: "running",
createdAt: new Date(Date.now() - 90_000).toISOString()
}]
})
};
}
throw new Error(`unexpected url ${url}`);
},
post: (url: string) => {
posted = url === "api/v1/simulation/create-batch";
return { json: async () => ({ data: { batchId: "batch-new" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {
mode: "hosecloud",
flowIds: ["B26017701"],
force: true
}, fakeContext()) as Record<string, unknown>;
expect(posted).toBe(true);
expect(result).toMatchObject({ batchId: "batch-new", created: true });
expect(result.reused).toBeUndefined();
});
test("create tool creates a new batch when the identical batch is outside the reuse window", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
let posted = false;
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/hosecloud-integrations") {
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
}
if (url === "api/v1/simulation/batches") {
return {
json: async () => ({
data: [{
...hosecloudBatchFixture,
id: "01a0e699-old",
status: "running",
createdAt: new Date(Date.now() - 10 * 60_000).toISOString()
}]
})
};
}
throw new Error(`unexpected url ${url}`);
},
post: (url: string) => {
posted = url === "api/v1/simulation/create-batch";
return { json: async () => ({ data: { batchId: "batch-new" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {
mode: "hosecloud",
flowIds: ["B26017701"]
}, fakeContext()) as Record<string, unknown>;
expect(posted).toBe(true);
expect(result).toMatchObject({ batchId: "batch-new", created: true });
});
test("create tool surface exposes mode, flowIds, and rawParams", () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
const { z } = require("zod") as typeof import("zod");
+51
View File
@@ -407,6 +407,57 @@ export function summarizeSimulationBatch(batch: SimulationBatch) {
};
}
const REUSE_BLOCKED_BATCH_STATUSES = new Set(["failed", "cancelled", "canceled"]);
export type SimulationBatchReuseKey = {
flowIds?: string[];
packageIds?: string[];
signKey?: string;
};
function normalizedIdSet(ids?: string[]): string[] | undefined {
const cleaned = (ids ?? []).map((id) => id.trim()).filter(Boolean);
return cleaned.length ? [...new Set(cleaned)].sort() : undefined;
}
function sameIdSet(left?: string[], right?: string[]): boolean {
const leftSet = normalizedIdSet(left);
const rightSet = normalizedIdSet(right);
if (!leftSet || !rightSet) return false;
return leftSet.length === rightSet.length && leftSet.every((id, index) => id === rightSet[index]);
}
export function simulationBatchCreatedAtMs(batch: SimulationBatch): number | null {
const raw = batch.createdAt;
if (raw === undefined) return null;
const ms = typeof raw === "number" ? raw : Date.parse(raw);
return Number.isFinite(ms) && ms > 0 ? ms : null;
}
// 幂等复用: 同一组单号/材料包在时间窗内已有非失败终态的批次则复用, 防止 agent 打断后重发导致同一笔单重复扣费
export function findReusableSimulationBatch(
batches: SimulationBatch[],
key: SimulationBatchReuseKey,
windowMs: number,
nowMs: number = Date.now()
): SimulationBatch | null {
const flowIds = normalizedIdSet(key.flowIds);
const packageIds = normalizedIdSet(key.packageIds);
if (!flowIds && !packageIds) return null;
return batches.find((batch) => {
if (REUSE_BLOCKED_BATCH_STATUSES.has((batch.status ?? "").toLowerCase())) return false;
const createdAtMs = simulationBatchCreatedAtMs(batch);
if (createdAtMs === null) return false;
const ageMs = nowMs - createdAtMs;
if (ageMs < 0 || ageMs > windowMs) return false;
if (flowIds && !sameIdSet(batch.params?.flowIds, flowIds)) return false;
if (packageIds && !sameIdSet(batch.params?.packageIds, packageIds)) return false;
if (key.signKey && batch.params?.signKey && batch.params.signKey !== key.signKey) return false;
return true;
}) ?? null;
}
export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
const sourceDocumentSN = record.sourceDocumentSN;
const humanResult = extractHumanResult(record);
+55 -1
View File
@@ -83,10 +83,12 @@ const {
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
findReusableSimulationBatch,
firstPath,
countPathCandidates,
getPath,
setPath,
simulationBatchCreatedAtMs,
compactObject,
asRecord,
numberFromUnknown,
@@ -169,7 +171,7 @@ export const simulationTools = [
},
{
name: "seal_simulation_batch_create",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;默认幂等:复用窗口内同 flow-ids/packageIds 的既有批次直接返回不重复扣费(--force 跳过);其他取数模式通过 rawParams 预留透传。",
parameters: z.object({
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
@@ -183,6 +185,8 @@ export const simulationTools = [
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),
force: z.boolean().optional().describe("跳过同单幂等复用检查, 强制创建新批次"),
reuseWindow: z.string().optional().describe("幂等复用检查时间窗(如 5m/10m), 默认 5m, 设为 0 关闭复用检查"),
rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")
}),
handler: async (
@@ -200,6 +204,8 @@ export const simulationTools = [
templateId?: string;
schemaConfig?: Record<string, unknown>;
noWait?: boolean;
force?: boolean;
reuseWindow?: string;
rawParams?: Record<string, unknown>;
}
) => {
@@ -228,6 +234,54 @@ export const simulationTools = [
rawParams: params.rawParams
});
// 幂等复用: 打断/重试场景下避免同一组单号重复创建批次导致重复扣费
const reuseWindowMs = params.force ? 0 : parseDurationMs(params.reuseWindow ?? "5m");
if (reuseWindowMs > 0 && (params.flowIds?.length || params.packageIds?.length)) {
let reusable: SimulationBatch | null = null;
try {
reusable = findReusableSimulationBatch(
await api.listSimulationBatches(client, { limit: 50 }),
{ flowIds: params.flowIds, packageIds: params.packageIds, signKey },
reuseWindowMs
);
} catch (error) {
console.error(
`⚠️ [Simulation] 幂等复用检查失败, 将按原计划创建新批次: ${error instanceof Error ? error.message : String(error)}`
);
}
if (reusable) {
const createdAtMs = simulationBatchCreatedAtMs(reusable);
const ageSeconds = createdAtMs === null ? undefined : Math.max(0, Math.round((Date.now() - createdAtMs) / 1000));
console.error(
`♻️ [Simulation] 检测到 ${ageSeconds ?? "?"}s 前已创建同单批次 ${reusable.id}(status=${reusable.status ?? "unknown"}),复用该批次, 不重复创建以避免重复扣费;确需重跑请加 --force`
);
return {
batchId: reusable.id,
created: false,
reused: true,
reuseWindow: params.reuseWindow ?? "5m",
message: "已存在同单批次, 已复用既有批次, 未创建新批次(不重复扣费)",
matchedBatch: {
id: reusable.id,
status: reusable.status,
createdAt: reusable.createdAt,
ageSeconds,
flowIds: reusable.params?.flowIds,
packageIds: reusable.params?.packageIds
},
noWait: params.noWait ?? true,
asyncTicket: reusable.id,
next: {
status: `seal-use simulation status ${reusable.id}`,
wait: `seal-use simulation wait ${reusable.id}`,
getBatch: `seal-use simulation get ${reusable.id}`,
getRecords: `seal-use simulation batch-records ${reusable.id}`,
listBatches: "seal-use simulation list"
}
};
}
}
const result = mode === "material_pack"
? await api.createMaterialPackBatch(client, payload)
: await api.createSimulationBatch(client, payload);