From bb600530723ee1ea741fff1c1751230632f48afd Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 4 Nov 2026 17:10:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(analysis):=20=E6=96=B0=E5=A2=9E=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6=E8=8A=82=E7=82=B9=E7=A9=BA=E5=80=BC=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E8=A7=84=E5=88=99=20CONDITION=5FNULL=5FUNSAFE=5FCOMPARE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 背景 条件节点对「取值链要先穿过列表再往下取字段」的字段做大于/小于类比较时,上游 列表为空会让字段取到 `null`。MVEL 里 `null < 0` 返回的是 **null 而不是 false**, 引擎对 condition 做强 Boolean 校验,于是直接抛: ``` if 节点(xxx)的 condition 参数的解析结果必须为 Boolean 类型 ``` 流程在这里**中断**,而不是安静地走 false 分支。真实案例中一条链路跑到第 9 步 才炸,报错信息完全指不出是哪次取值拿到了 null。 ## 关键实测结论:AND 不短路 直觉写法是 `AND(列表非空, 额度 < 0)`,指望布尔短路跳过后面的比较。实测证明 这条路走不通——合思引擎**逐叶子求值再合并**: | 输入 | 条件 | 结果 | |---|---|---| | 列表为空 | `AND(列表 notNull, 额度 lt 0)` | FAILED,仍是同一个类型错误 | | 额度 = -5 | 同上 | COMPLETED | 也就是说同一个条件节点里加「不为空」判断**完全无效**,null 比较照样会被算出来。 唯一可靠的是流程控制短路:外层套一个条件节点判「列表不为空」,把原节点放进它的 满足分支——列表为空时外层为 false,内层根本不被求值。 同时确认了判空本身的可用性:`notNull` 对空数组 `[]` 返回 false、对非空数组返回 true,且不需要 `value` 字段;条件为 false 时节点 COMPLETED、子节点跳过、流程继续。 ## 实现 新增 `analysis/condition-null-safety.ts`: - `readChoosePath()` 解析 `@{choose('{...}')}` 描述符,兼容前端多一个右花括号的形态, 取出取值链的根节点与 `properties` 层级; - `goesThroughList()` 判定取值链是否「穿过 `DATA_LINK_LIST` 之后还有层级」—— 单层字段取值和「只判列表本身」都不算风险; - `hasAncestorListGuard()` 沿祖先链找对同一列表做过 `notNull` 判断的条件节点; - 命中「有序比较(`gt/gte/lt/lte`)+ 穿过列表 + 无祖先守卫」时产出 `CONDITION_NULL_UNSAFE_COMPARE` 软提示,消息里明确否掉「用 AND 兜住」这个直觉解法, 并给出守卫上提的正确写法。 `analyzer.ts` 的遍历新增祖先链参数,在条件节点诊断段之后调用该检查。 ## 为什么是软建议而不是硬门禁 静态分析无法确定上游列表一定为空(例如上游刚创建、或业务上保证有数据),硬阻断会 让合法流程无法发布。因此只提示、不改写配置、不推断数据非空。`eq`/`neq` 也不纳入 检查——null 与值做相等比较返回的是布尔,不会中断。 ## 测试 新增 14 个用例:路径解析(含多花括号形态)、穿过列表判定、无守卫告警、同节点内 AND 组合仍告警、外层守卫不告警、守卫判断的是别的列表仍告警、单层取值不告警、 只判列表不告警、`gt/gte/lte` 覆盖、`eq` 不告警、同一路径去重。 另外用真实流程做了前后对照:改造前(无守卫)命中 2 条,加上守卫后命中 0 条。 `bun test` 1082 pass / 0 fail;`bun run check` 零错误;`check:readme` 通过。 --- .../platform/workflow/analysis/analyzer.ts | 8 +- .../analysis/condition-null-safety.test.ts | 143 +++++++++++++ .../analysis/condition-null-safety.ts | 194 ++++++++++++++++++ 3 files changed, 343 insertions(+), 2 deletions(-) create mode 100644 src/domains/platform/workflow/analysis/condition-null-safety.test.ts create mode 100644 src/domains/platform/workflow/analysis/condition-null-safety.ts diff --git a/src/domains/platform/workflow/analysis/analyzer.ts b/src/domains/platform/workflow/analysis/analyzer.ts index 1e802b3..a430d9a 100644 --- a/src/domains/platform/workflow/analysis/analyzer.ts +++ b/src/domains/platform/workflow/analysis/analyzer.ts @@ -12,6 +12,7 @@ import type { } from "./types.js"; import { isKnownGrayNodeType } from "../nodes/gray-nodes-catalog.js"; import { matchAppRequirement } from "./openapi-app-requirements.js"; +import { checkConditionNullSafety } from "./condition-null-safety.js"; const KNOWN_TYPES = new Set([ "webhook", @@ -452,7 +453,7 @@ export function analyzeWorkflow( const taskNameMap = buildTaskNameMap(detail.tasks); - const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => { + const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false, ancestors: WorkflowTask[] = []) => { tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); @@ -692,6 +693,9 @@ export function analyzeWorkflow( } } + // 诊断 5.3 条件节点空值安全(CONDITION_NULL_UNSAFE_COMPARE) + checkConditionNullSafety(task, path, ancestors, diagnostics); + // 诊断 6: HTTP 节点域名、中括号与功能权限校验 if (task.type === "http") { const url = String((task as Record).url || ""); @@ -909,7 +913,7 @@ export function analyzeWorkflow( } } - visit(task.tasks || [], path, insideEvery || task.type === "every"); + visit(task.tasks || [], path, insideEvery || task.type === "every", [...ancestors, task]); }); }; diff --git a/src/domains/platform/workflow/analysis/condition-null-safety.test.ts b/src/domains/platform/workflow/analysis/condition-null-safety.test.ts new file mode 100644 index 0000000..c2dc8e1 --- /dev/null +++ b/src/domains/platform/workflow/analysis/condition-null-safety.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "bun:test"; +import { analyzeWorkflow } from "./index.js"; +import { goesThroughList, readChoosePath } from "./condition-null-safety.js"; + +const LIST_LEAF = + "@{choose('{\"key\":\"action_find\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"},{\"key\":\"0\",\"label\":\"首条数据\",\"type\":\"DATA_LINK\"},{\"key\":\"E_x\",\"label\":\"差旅费剩余额度\",\"type\":\"MONEY\"}],\"label\":\"查找业务数据.结果列表.首条数据.差旅费剩余额度\"}')}"; + +const LIST_SELF = + "@{choose('{\"key\":\"action_find\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"}],\"label\":\"查找业务数据.结果列表\"}')}"; + +const OTHER_LIST_LEAF = + "@{choose('{\"key\":\"action_other\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"},{\"key\":\"0\",\"label\":\"首条数据\",\"type\":\"DATA_LINK\"}],\"label\":\"别的查询.结果列表.首条数据\"}')}"; + +const FLAT_MONEY = + "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"amount\",\"label\":\"金额\",\"type\":\"MONEY\"}],\"label\":\"金额\"}')}"; + +function leaf(key: string, compare: string, value?: unknown) { + return value === undefined ? { key, compare } : { key, compare, value }; +} + +function group(filters: unknown[], condition = "and") { + return { condition, filters }; +} + +function condition(name: string, filters: unknown, children: unknown[] = []) { + return { name, type: "condition", label: "条件节点", combineFilters: filters, tasks: children }; +} + +function wf(tasks: unknown[]) { + return { id: "wf-null", label: "空值安全", state: 1, version: "1", tasks } as any; +} + +describe("choose 路径解析", () => { + it("识别穿过列表的取值链", () => { + const parsed = readChoosePath(LIST_LEAF); + expect(parsed).not.toBeNull(); + expect(parsed!.root).toBe("action_find"); + expect(goesThroughList(parsed!)).toBe(true); + }); + + it("列表位于最后一层时不算穿过", () => { + expect(goesThroughList(readChoosePath(LIST_SELF)!)).toBe(false); + }); + + it("单层字段取值不算穿过", () => { + expect(goesThroughList(readChoosePath(FLAT_MONEY)!)).toBe(false); + }); + + it("兼容前端多一个右花括号的形态", () => { + const tail = "}')}"; + const doubled = LIST_LEAF.slice(0, LIST_LEAF.lastIndexOf(tail)) + "}}" + "')}"; + const parsed = readChoosePath(doubled); + expect(parsed?.root).toBe("action_find"); + expect(goesThroughList(parsed!)).toBe(true); + }); + + it("非 choose 表达式一律忽略", () => { + expect(readChoosePath("trigger_1.amount")).toBeNull(); + expect(readChoosePath(undefined)).toBeNull(); + }); +}); + +describe("CONDITION_NULL_UNSAFE_COMPARE", () => { + it("列表取数 + 数值比较 + 无守卫 → 告警", () => { + const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, "lt", 0)])]))])); + const diag = result.diagnostics.find((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE"); + expect(diag).toBeDefined(); + expect(diag?.severity).toBe("warning"); + expect(diag?.category).toBe("soft_advice"); + expect(diag?.message).toContain("差旅费剩余额度"); + expect(diag?.message).toContain("Boolean"); + // 必须明确否掉「AND 兜住」这个直觉解法 + expect(diag?.message).toContain("不做短路"); + }); + + it("同一节点内用 AND 组合了列表非空判断 → 仍然告警(引擎不短路)", () => { + const result = analyzeWorkflow( + wf([ + condition( + "control_a", + group([group([leaf(LIST_SELF, "notNull")]), group([leaf(LIST_LEAF, "lt", 0)])]) + ), + ]) + ); + const diags = result.diagnostics.filter((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE"); + expect(diags).toHaveLength(1); + }); + + it("外层套了列表非空守卫 → 不告警", () => { + const inner = condition("control_b", group([group([leaf(LIST_LEAF, "lt", 0)])])); + const outer = condition("control_guard", group([group([leaf(LIST_SELF, "notNull")])]), [inner]); + const result = analyzeWorkflow(wf([outer])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false); + }); + + it("守卫判断的是另一个列表 → 仍然告警", () => { + const inner = condition("control_b", group([group([leaf(LIST_LEAF, "lt", 0)])])); + const outer = condition( + "control_guard", + group([group([leaf(OTHER_LIST_LEAF.replace("action_other", "action_zzz"), "notNull")])]), + [inner] + ); + const result = analyzeWorkflow(wf([outer])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(true); + }); + + it("单层字段比较 → 不告警", () => { + const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(FLAT_MONEY, "lt", 0)])]))])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false); + }); + + it("只判列表本身 → 不告警", () => { + const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_SELF, "notNull")])]))])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false); + }); + + it("gte / lte / gt 同样覆盖", () => { + for (const compare of ["gt", "gte", "lte"]) { + const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, compare, 0)])]))])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(true); + } + }); + + it("eq 不属于有序比较 → 不告警", () => { + const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, "eq", 0)])]))])); + expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false); + }); + + it("同一路径重复出现只报一次", () => { + const result = analyzeWorkflow( + wf([ + condition( + "control_a", + group([ + group([leaf(LIST_LEAF, "lt", 0)]), + group([leaf(LIST_LEAF, "gt", 100)]), + ]) + ), + ]) + ); + expect(result.diagnostics.filter((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toHaveLength(1); + }); +}); diff --git a/src/domains/platform/workflow/analysis/condition-null-safety.ts b/src/domains/platform/workflow/analysis/condition-null-safety.ts new file mode 100644 index 0000000..6e81ace --- /dev/null +++ b/src/domains/platform/workflow/analysis/condition-null-safety.ts @@ -0,0 +1,194 @@ +/** + * 条件节点的空值安全校验(CONDITION_NULL_UNSAFE_COMPARE)。 + * + * ── 要解决的问题 ──────────────────────────────────────────────────── + * + * 条件节点里对一个「先经过列表取数」的字段做数值/日期比较时,如果上游列表 + * 为空,取值结果是 null。而 MVEL 中 `null < 0` 返回的是 **null 而不是 false**, + * 引擎对 condition 参数做 Boolean 强校验,于是直接抛: + * + * if 节点(xxx)的 condition 参数的解析结果必须为 Boolean 类型 + * + * 流程到这里**中断**,而不是安静地走 false 分支。真实案例里这类报错排查成本 + * 极高,因为报错信息完全看不出是哪一次取值拿到 null。 + * + * ── 为什么不能靠 AND 兜住(实测结论)──────────────────────────────── + * + * 直觉写法是 `AND(列表非空, 额度 < 0)`,指望布尔短路跳过后面的比较。 + * 但合思引擎是**逐叶子求值再合并**,不做短路:`null < 0` 照样被算出来, + * 合并阶段类型校验失败,一样报错。 + * + * 唯一可靠的写法是把守卫**上提一层**,用流程控制短路: + * + * 条件节点A:结果列表 不为空 + * └─(满足) 条件节点B:OR(差旅 < 0, 招待 < 0) + * └─ 真正的处理动作 + * + * 列表为空时 A 为 false,B 根本不会被求值。 + * + * 本模块只做「有没有守卫」的静态判断,不尝试推断数据是否真的非空。 + */ + +import type { WorkflowTask } from "../types.js"; +import { extractLeafFilters } from "./every.js"; +import { parseChoosePayloadLoose } from "../models/choose-serialization.js"; +import { addDiagnostic } from "./diagnostics.js"; +import type { WorkflowDiagnostic } from "./types.js"; + +/** 需要另一侧提供有序值的比较符;左边是 null 时结果不是布尔。 */ +const ORDERING_COMPARES = new Set(["gt", "gte", "lt", "lte"]); + +/** 「为空 / 不为空」这一对只有它们不要求 value,也不产生 null 污染。 */ +const NULL_CHECKS = new Set(["isnull", "notnull"]); + +interface ChoosePath { + /** 取值链的根节点 key(如 action_5yt4ko) */ + root: string; + /** properties 链,按层级顺序 */ + properties: Array<{ key?: string; type?: string; label?: string }>; + /** 展示用的最后一段标签 */ + label: string; +} + +interface ChooseProperty { + key?: unknown; + type?: unknown; + label?: unknown; +} + +function unquote(raw: string): string | null { + const text = raw.trim(); + if (text.length < 2) return null; + if (text.startsWith('"') && text.endsWith('"')) { + try { + const parsed = JSON.parse(text); + return typeof parsed === "string" ? parsed : null; + } catch { + return null; + } + } + if (text.startsWith("'") && text.endsWith("'")) { + return text.slice(1, -1).replace(/\\'/g, "'"); + } + return null; +} + +/** 解析 `@{choose('{...}')}` 里的描述对象;不是这个形态就返回 null。 */ +export function readChoosePath(key: unknown): ChoosePath | null { + if (typeof key !== "string") return null; + const match = /^@\{\s*choose\s*\(([\s\S]*)\)\s*\}\s*$/.exec(key.trim()); + if (!match) return null; + + const payloadText = unquote(match[1]); + if (payloadText === null) return null; + + const normalized = parseChoosePayloadLoose(payloadText); + if (!normalized) return null; + + let payload: Record; + try { + const parsed: unknown = JSON.parse(normalized); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + payload = parsed as Record; + } catch { + return null; + } + + const root = typeof payload.key === "string" ? payload.key : ""; + if (!root) return null; + + const properties = Array.isArray(payload.properties) + ? payload.properties + .filter((item): item is ChooseProperty => Boolean(item) && typeof item === "object") + .map((item) => ({ + key: typeof item.key === "string" ? item.key : undefined, + type: typeof item.type === "string" ? item.type : undefined, + label: typeof item.label === "string" ? item.label : undefined, + })) + : []; + + const label = + typeof payload.label === "string" ? payload.label : properties.at(-1)?.label ?? properties.at(-1)?.key ?? root; + + return { root, properties, label }; +} + +/** + * 取值链是否「先穿过一个列表,再继续往下取」。 + * + * - `结果列表.首条数据.额度` → 穿过 DATA_LINK_LIST 后还有两层 → 有风险 + * - `金额字段` → 单层取值 → 无风险 + * - `结果列表`(只判列表本身)→ 列表在最后一层 → 无风险 + */ +export function goesThroughList(path: ChoosePath): boolean { + const index = path.properties.findIndex((item) => item.type === "DATA_LINK_LIST"); + return index !== -1 && index < path.properties.length - 1; +} + +function compareOf(raw: unknown): string { + return typeof raw === "string" ? raw.trim().toLowerCase() : ""; +} + +function filterSourceOf(task: WorkflowTask): unknown { + const raw = task as Record; + return raw.combineFilters ?? raw.filters ?? raw.conditions; +} + +/** 祖先链上是否存在「对同一列表做过不为空判断」的条件节点。 */ +function hasAncestorListGuard(ancestors: WorkflowTask[], root: string): boolean { + for (let i = ancestors.length - 1; i >= 0; i -= 1) { + const ancestor = ancestors[i]; + if (ancestor?.type !== "condition") continue; + for (const leaf of extractLeafFilters(filterSourceOf(ancestor))) { + if (compareOf(leaf.compare) !== "notnull") continue; + const guarded = readChoosePath(leaf.key); + if (guarded && guarded.root === root) return true; + } + } + return false; +} + +/** + * 检查单个条件节点。命中「列表取数 + 有序比较 + 上游没有非空守卫」时产出软建议。 + * + * 刻意不产出硬门禁:静态分析无法确定上游列表一定为空,误判会让合法流程 + * 无法发布;但这个消息本身必须把「AND 兜不住」讲清楚,否则作者会按直觉改错。 + */ +export function checkConditionNullSafety( + task: WorkflowTask, + path: string, + ancestors: WorkflowTask[], + diagnostics: WorkflowDiagnostic[] +): void { + if (task.type !== "condition") return; + + const seen = new Set(); + + for (const leaf of extractLeafFilters(filterSourceOf(task))) { + if (!ORDERING_COMPARES.has(compareOf(leaf.compare))) continue; + if (NULL_CHECKS.has(compareOf(leaf.compare))) continue; + + const choosePath = readChoosePath(leaf.key); + if (!choosePath || !goesThroughList(choosePath)) continue; + if (hasAncestorListGuard(ancestors, choosePath.root)) continue; + if (seen.has(choosePath.label)) continue; + seen.add(choosePath.label); + + const compareLabel = { gt: "大于", gte: "大于等于", lt: "小于", lte: "小于等于" }[ + compareOf(leaf.compare) as "gt" | "gte" | "lt" | "lte" + ]; + + addDiagnostic(diagnostics, { + severity: "warning", + category: "soft_advice", + code: "CONDITION_NULL_UNSAFE_COMPARE", + path, + message: + `条件节点 [${task.label || task.name}] (${task.name}) 对字段 [${choosePath.label}] 做「${compareLabel}」比较,` + + `而该字段的取值链要先穿过列表(${choosePath.properties.map((p) => p.label || p.key).join(" → ")})。` + + `上游列表为空时取值是 null,null 参与比较返回的不是布尔,引擎会直接抛「condition 参数的解析结果必须为 Boolean 类型」并中断流程。` + + `注意:把「列表不为空」放进同一个条件节点用 AND 组合没有用 —— 实测引擎逐叶子求值,不做短路,null 比较照样会被算出来。` + + `请在该节点外层再套一个条件节点,先判断「列表不为空」,把本节点放进它的满足分支。`, + }); + } +}