unis-oa/backend/app/engine/conditions.py

592 lines
23 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""路由条件的静态口径:两条分支能不能在同一张单上一起走到。
条件分支和适用条件写的是「用印类别是合作类协议」「金额超过 10 万」这种话,图本身
看不出来:画布上两条线都通,真跑起来却只会走一条。以前凡是往后看的判定(前瞻去重、
设计期体检)都把带条件的出口一律当成「可能走」,于是配得再准的分支也只换来一句
「后面有一条分支不经过他」——设计者明明把条件写死了,体检却装作没看见。
本模块把条件式读成可以比对的形式,只回答三件事:
- ``decide(guard, known)``:在已知 ``known``(走到这里必须满足的那些条件)之下,
这一条条件是**一定成立**、**一定不成立**,还是**说不准**;
- ``possible(term)``:一组条件凑在一起**有没有可能同时成立**(自相矛盾就走到头了);
- ``pick(...)``:一个环节的出口里,哪几条在这一单上还真走得通(口径抄 ``_pick_choice``:
条件分支取第一条成立的那条,没人成立就走没写条件的那条)。
看不懂的条件一律降级成一个「整句原子」:只跟一模一样的整句(含取反)对消,别的一概
不让步。**判断只做减法**——只有证得死「这两条不可能同时成立」才剪枝,证不出来就当可能,
所以永远不会因为读不懂条件而少报一次重复。
"""
from __future__ import annotations
import ast
from dataclasses import dataclass, field
from typing import Iterable, Sequence
#: ``decide()`` 的三档结论。
TRUE = "true"
FALSE = "false"
UNKNOWN = "unknown"
#: 原子按域分开比对:跨域(同一个字段既当文本又当数值)不互相让步,宁可算不出。
DOMAIN_VALUE = "value" #: 单值:``==`` / ``in`` / ``!=`` / ``not in``
DOMAIN_NUMBER = "number" #: 数值区间:``>`` / ``>=`` / ``<`` / ``<=``
DOMAIN_TEXT = "text" #: 子串:``'经营管理中心' in 字段``
DOMAIN_MEMBERS = "members" #: 多选:``contains([...], 字段)`` / ``字段 in [...]``
DOMAIN_OPAQUE = "opaque" #: 读不懂的整句,只按文本对消
#: ``X or ''`` 这类兜底里被丢掉的假值:``truthy`` 与它撞上才算矛盾。
FALSY_TEXTS = frozenset({"", "none", "false", "null"})
#: 比较式的取反:``not (x > 5)`` 就是 ``x <= 5``,翻完还能接着比区间。
_FLIP_COMPARE = {
ast.Lt: ast.GtE,
ast.LtE: ast.Gt,
ast.Gt: ast.LtE,
ast.GtE: ast.Lt,
}
_COMPARE_OP = {
ast.Lt: "lt",
ast.LtE: "le",
ast.Gt: "gt",
ast.GtE: "ge",
}
#: 上下文里本来就有的名字,不能当成表单字段。
_CONTEXT_NAMES = frozenset({"data", "form", "work", "user", "variables", "context", "true", "false", "null"})
#: 一个环节往下最多摊开多少条「已知条件」:分支画得太碎就到此为止,按说不准处理。
MAX_TERMS = 24
@dataclass(frozen=True)
class Atom:
"""一条最小说明,比如「用印类别属于 {QTYYWJ}」「部门路径里含经营管理中心」。
``field`` 是 ``data:sealCategory`` / ``work:creator_unit`` 这种带来源的键,
读不懂的整句用 ``opaque:<归一化文本>``,于是 ``not X`` 与 ``X`` 天然对消。
"""
field: str
domain: str
op: str
values: tuple[str | float, ...] = ()
@property
def key(self) -> tuple[str, str]:
return (self.field, self.domain)
def describe(self) -> str:
"""读不懂的整句就照原样念;认得出的式子由 :meth:`Lit.describe` 说。"""
if self.domain == DOMAIN_OPAQUE:
return self.field[len("opaque:") :]
return self.field.split(":", 1)[-1]
@dataclass(frozen=True)
class Lit:
"""一个原子,可能带着「不成立」这层否定。"""
atom: Atom
negated: bool = False
def flipped(self) -> "Lit":
return Lit(self.atom, not self.negated)
def describe(self) -> str:
"""给人看的一句话:``用印类别=QTYYWJ`` / ``部门不含经营管理中心``。"""
name = self.atom.field.split(":", 1)[-1]
if self.atom.domain == DOMAIN_OPAQUE:
return ("非" if self.negated else "") + self.atom.describe()
joined = "/".join(str(item) for item in self.atom.values)
table = {
("eq", False): f"{name}={joined}",
("eq", True): f"{name}≠{joined}",
("in", False): f"{name}∈{joined}",
("in", True): f"{name}∉{joined}",
("contains", False): f"{name}含{joined}",
("contains", True): f"{name}不含{joined}",
("substr", False): f"{name}含{joined}",
("substr", True): f"{name}不含{joined}",
("truthy", False): f"{name}填了",
("truthy", True): f"{name}没填",
("gt", False): f"{name}>{joined}",
("ge", False): f"{name}≥{joined}",
("lt", False): f"{name}<{joined}",
("le", False): f"{name}≤{joined}",
}
return table.get((self.atom.op, self.negated), f"{name}{'≠' if self.negated else '='}{joined}")
#: 一条合取式(这些条件同时成立),以及一个条件式的范式(若干条里有一条成立即可)。
Term = tuple[Lit, ...]
def _text(value: object) -> str:
return " ".join(str(value or "").split())
def opaque(source: str) -> Atom:
return Atom(f"opaque:{_text(source)}", DOMAIN_OPAQUE, "opaque")
@dataclass(frozen=True)
class Guard:
"""一条路由上写的条件,读成了「几条可能走法,每条是一组合取条件」。
``terms`` 为空 = 这条条件永远不成立;只有一条空合取式 = 没写条件/永远成立。
"""
source: str = ""
terms: tuple[Term, ...] = ((),)
@property
def blank(self) -> bool:
"""没写条件,或者写的就是一句恒真。"""
return not _text(self.source)
@property
def always(self) -> bool:
return self.terms == ((),)
@property
def never(self) -> bool:
return self.terms == ()
@property
def fields(self) -> tuple[str, ...]:
"""这条条件在看哪几个字段/上下文(只用来措辞,不参与判定)。"""
names = {item.atom.field for term in self.terms for item in term if not item.atom.field.startswith("opaque:")}
return tuple(sorted(name.split(":", 1)[-1] for name in names))
@property
def readable(self) -> bool:
"""整句里有没有真读出点东西(全是不透明原子的就算读不懂)。"""
return any(item.atom.domain != DOMAIN_OPAQUE for term in self.terms for item in term)
def describe(self) -> str:
"""给人看的一句话:几条可能走法用「或」连,读不懂就退回原式。"""
if self.blank:
return "没写条件"
if not self.readable:
return _text(self.source)
parts = []
for term in self.terms:
if not term:
parts.append("恒成立")
continue
parts.append(" 且 ".join(item.describe() for item in term))
return " 或 ".join(parts) if parts else "恒不成立"
def parse(source: object) -> Guard:
"""把一条路由条件读成 :class:`Guard`。读不懂不报错,整句退化成不透明原子。"""
raw = str(source or "")
text = raw.strip()
if not text:
return Guard(source=raw)
try:
tree = ast.parse(text, mode="eval")
except SyntaxError:
return Guard(source=raw, terms=((Lit(opaque(text)),),))
return Guard(source=raw, terms=_dnf(tree.body, False))
# ---------------------------------------------------------------------------
# 判定
# ---------------------------------------------------------------------------
def possible(term: Term) -> bool:
"""一组条件有没有可能同时成立。"""
return _satisfiable(term)
def conjoin(known: tuple[Term, ...], guard: Guard) -> tuple[Term, ...]:
"""把一条条件并到「已经知道的条件」上(叉乘,摊不开就退回原样当说不准)。"""
if guard.always:
return known
if guard.never:
return ()
merged: list[Term] = []
for base in known:
for term in guard.terms:
merged.append(base + term)
if len(merged) > MAX_TERMS:
# 摊得太开:留着已知那份继续判,只是别再把这条新条件当成已知事实。
return known
out = tuple(item for item in merged if _satisfiable(item))
return out if out else ()
def decide(guard: Guard, known: tuple[Term, ...] = ((),)) -> str:
"""在 ``known`` 之下这条条件一定成立 / 一定不成立 / 说不准。
``known`` 是「能走到这儿」必须满足的条件(DNF)。判「一定成立」用的是
「已知条件 ∧ 这条条件不成立」有没有可能成立:证不出矛盾就当说不准。
"""
if guard.never:
return FALSE
if guard.always:
return TRUE
bases = known or ((),)
sat = any(_satisfiable(base + term) for base in bases for term in guard.terms)
if not sat:
return FALSE
for base in bases:
for term in guard.terms:
if _satisfiable(base + tuple(item.flipped() for item in term)):
return UNKNOWN
return TRUE
def pick(states: Sequence[str], *, deterministic: bool) -> list[int]:
"""一个环节的出口里哪些还真可能走:``states`` 是每条出口的 :func:`decide` 结果。
口径与引擎一致(``engine._pick_choice`` / ``engine._resolve_route``):
- 条件分支(``deterministic``)由引擎自己挑:取第一条**成立**的出口,都不成立就走
没写条件的那条。所以一旦某条被证成,排在它后面的出口就不可能走了;排在它前面
那些「说不准」的还得留着——万一将来那句条件成立,被选走的就是它。
- 人工环节的出口是人点的,引擎只负责拦下「适用条件不成立」的那几条:剩下都算可能。
"""
alive = [index for index, state in enumerate(states) if state != FALSE]
if not alive:
return list(range(len(states))) # 一条都走不了=图画错了,别在这里替它做主
if not deterministic:
return alive
for index in alive:
if states[index] == TRUE:
return [item for item in alive if item <= index]
return alive
def hint(guard: Guard) -> str:
"""给措辞用的一句「这条要看什么」:字段名,读不懂就回原式。"""
fields = guard.fields
if fields:
return "、".join(fields[:3]) + ("…" if len(fields) > 3 else "")
return _text(guard.source) or "没写条件"
# ---------------------------------------------------------------------------
# 读式子
# ---------------------------------------------------------------------------
def _dnf(node: ast.expr, negate: bool) -> tuple[Term, ...]:
"""把条件式摊成「或」套「且」。摊不开的部分变成一个整句原子。"""
if isinstance(node, ast.BoolOp):
parts = [_dnf(item, negate) for item in node.values]
if isinstance(node.op, ast.Or):
if negate:
return _cross(parts)
return tuple(item for part in parts for item in part)
if negate:
return tuple(item for part in parts for item in part)
return _cross(parts)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
return _dnf(node.operand, not negate)
if isinstance(node, ast.Constant):
truth = bool(node.value) if isinstance(node.value, bool) else str(node.value).strip().lower() not in FALSY_TEXTS
if truth != negate:
return ((),)
return ()
lit = _literal(node, negate)
if lit is not None:
return ((lit,),)
return ((Lit(opaque(ast.unparse(node)), negate),),)
def _cross(parts: Iterable[tuple[Term, ...]]) -> tuple[Term, ...]:
out: tuple[Term, ...] = ((),)
for part in parts:
if not part:
return ()
out = tuple(base + term for base in out for term in part)
if len(out) > MAX_TERMS:
return out[:MAX_TERMS]
return out
def _literal(node: ast.expr, negate: bool) -> Lit | None:
"""认得出的一次判断,认不出返回 ``None``。"""
node = _unwrap(node)
if isinstance(node, ast.Compare):
return _from_compare(node, negate)
if isinstance(node, ast.Call):
return _from_call(node, negate)
name = _field(node)
if name:
return Lit(Atom(name, DOMAIN_VALUE, "truthy"), negate)
return None
def _unwrap(node: ast.expr) -> ast.expr:
"""剥掉 ``str(X or '')`` / ``bool(X)`` / ``X or ''`` 这些为拼字符串穿的壳。"""
for _ in range(6):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in {"str", "bool"} and len(node.args) == 1:
node = node.args[0]
continue
if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or) and len(node.values) == 2 and _is_empty(node.values[1]):
node = node.values[0]
continue
return node
return node
def _is_empty(node: ast.expr) -> bool:
"""``X or ''`` / ``X or []`` / ``X or None``:兜底那一侧是空值才算壳,别把 ``X or 'A'`` 也剥了。"""
if isinstance(node, ast.Constant):
return node.value is None or node.value is False or str(node.value).strip() == ""
return isinstance(node, (ast.List, ast.Tuple, ast.Set, ast.Dict)) and not node.elts
def _from_compare(node: ast.Compare, negate: bool) -> Lit | None:
if len(node.ops) != 1:
return None
op = node.ops[0]
left, right = node.left, node.comparators[0]
if isinstance(op, (ast.Eq, ast.NotEq)):
pair = _field_with_literal(left, right)
if pair is None:
return None
name, values = pair
negated = isinstance(op, ast.NotEq)
return Lit(Atom(name, _value_domain(values), "eq", values), negated != negate)
if isinstance(op, (ast.In, ast.NotIn)):
if isinstance(right, (ast.Tuple, ast.List, ast.Set)):
values = _literal_values(right)
name = _field(left)
if name and values:
return Lit(Atom(name, _value_domain(values), "in", values), isinstance(op, ast.NotIn) != negate)
if isinstance(left, ast.Constant) and isinstance(left.value, str):
name = _field(right)
if name:
return Lit(Atom(name, DOMAIN_TEXT, "substr", (left.value,)), isinstance(op, ast.NotIn) != negate)
return None
if type(op) in _COMPARE_OP:
pair = _field_with_literal(left, right, numbers_only=True)
if pair is None:
return None
name, values = pair
kind = _COMPARE_OP[type(op)]
if negate:
kind = { # 取反之后还是区间,照样能比
"lt": "ge",
"le": "gt",
"gt": "le",
"ge": "lt",
}[kind]
return Lit(Atom(name, DOMAIN_NUMBER, kind, values), False)
return None
def _from_call(node: ast.Call, negate: bool) -> Lit | None:
if isinstance(node.func, ast.Name) and node.func.id == "contains" and len(node.args) == 2:
values = _literal_values(node.args[0]) or _as_literal_tuple(node.args[0])
name = _field(node.args[1])
if name and values:
return Lit(Atom(name, DOMAIN_MEMBERS, "contains", values), negate)
return None
return None
def _field_with_literal(node: ast.expr, other: ast.expr, *, numbers_only: bool = False) -> tuple[str, tuple] | None:
"""``字段 == 值``(写法反着也认),返回字段与那一侧的字面值。"""
for left, right in ((node, other), (other, node)):
name = _field(left)
values = _as_literal_tuple(right)
if not name or not values:
continue
if numbers_only and not all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in values):
continue
return name, values
return None
def _as_literal_tuple(node: ast.expr) -> tuple:
if isinstance(node, ast.Constant) and isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool):
return (node.value,)
if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
return _literal_values(node)
return ()
def _literal_values(node: ast.expr) -> tuple:
if not isinstance(node, (ast.Tuple, ast.List, ast.Set)):
return ()
out = []
for item in node.elts:
if isinstance(item, ast.Constant) and isinstance(item.value, (str, int, float)) and not isinstance(item.value, bool):
out.append(item.value)
else:
return ()
return tuple(out)
def _field(node: ast.expr) -> str:
"""这个式子说的是哪个来源:``data:xxx`` / ``work:xxx``,说不清就回空。"""
node = _unwrap(node)
if isinstance(node, ast.Name):
if node.id in _CONTEXT_NAMES:
return ""
return f"data:{node.id}"
if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id in {"data", "form", "work", "variables", "user"}:
key = node.slice
if isinstance(key, ast.Constant) and isinstance(key.value, str):
return f"{node.value.id}:{key.value}"
return ""
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "get":
owner = node.func.value
if isinstance(owner, ast.Name) and owner.id in {"data", "form", "work", "variables", "user", "context"} and node.args:
key = node.args[0]
if isinstance(key, ast.Constant) and isinstance(key.value, str):
return f"{owner.id}:{key.value}"
return ""
return ""
def _value_domain(values: Sequence[object]) -> str:
"""跟数字比就是数值域,跟文本比就是单值域;两种混着写就当说不准。"""
numbers = [item for item in values if isinstance(item, (int, float)) and not isinstance(item, bool)]
if numbers and len(numbers) == len(values):
return DOMAIN_NUMBER
return DOMAIN_VALUE
# ---------------------------------------------------------------------------
# 矛盾检查
# ---------------------------------------------------------------------------
@dataclass
class _Bucket:
"""同一个(字段,域)上攒下来的正/负条件,逐个往里收,收出矛盾就报。"""
domain: str
values: set | None = None #: 值域:还可能是哪几个值;``None`` = 没限定
low: float = float("-inf")
high: float = float("inf")
low_open: bool = True
high_open: bool = True
positive: set = field(default_factory=set) #: 文本/成员/不透明域:必须出现的
negative: set = field(default_factory=set) #: 必须不出现的
truthy: bool = False
falsy_only: bool = False
broken: bool = False
def add(self, lit: Lit) -> None:
atom = lit.atom
if self.domain == DOMAIN_VALUE:
self._value(lit)
elif self.domain == DOMAIN_NUMBER:
self._number(lit)
elif self.domain == DOMAIN_MEMBERS:
wanted = set(atom.values)
if lit.negated:
self.negative |= wanted
else:
self.positive |= wanted
else: # text / opaque:整句或子串,只跟同一句对消
wanted = set(atom.values) or {atom.field}
if lit.negated:
self.negative |= wanted
else:
self.positive |= wanted
def _value(self, lit: Lit) -> None:
atom = lit.atom
if atom.op == "truthy":
if lit.negated:
self.falsy_only = True
else:
self.truthy = True
return
wanted = {str(item) for item in atom.values}
if lit.negated:
self.negative |= wanted
return
if self.values is None:
self.values = set(wanted)
else:
self.values &= wanted
if not self.values:
self.broken = True
def _number(self, lit: Lit) -> None:
atom = lit.atom
if not atom.values:
return
bound = float(atom.values[0]) # type: ignore[arg-type]
kind = atom.op
if lit.negated:
# 取反的区间还是区间:not (x > 5) 就是 x <= 5,判「这条条件一定成立」全靠这一步
kind = {"gt": "le", "ge": "lt", "lt": "ge", "le": "gt"}[kind]
if kind == "gt":
self._raise(bound, True)
elif kind == "ge":
self._raise(bound, False)
elif kind == "lt":
self._lower(bound, True)
elif kind == "le":
self._lower(bound, False)
elif kind == "eq":
self._raise(bound, False)
self._lower(bound, False)
def _raise(self, bound: float, open_: bool) -> None:
# 同一条边界上「开区间」比闭区间更紧,谁紧听谁的
if bound > self.low or (bound == self.low and open_ and not self.low_open):
self.low, self.low_open = bound, open_
self._narrow()
def _lower(self, bound: float, open_: bool) -> None:
if bound < self.high or (bound == self.high and open_ and not self.high_open):
self.high, self.high_open = bound, open_
self._narrow()
def _narrow(self) -> None:
if self.low > self.high or (self.low == self.high and (self.low_open or self.high_open)):
self.broken = True
def conflicts(self) -> bool:
if self.broken:
return True
if self.domain == DOMAIN_VALUE:
if self.values is not None and self.values <= self.negative:
return True
if self.values is not None and self.truthy and all(item in FALSY_TEXTS for item in self.values):
return True
if self.falsy_only and self.values is not None and all(item not in FALSY_TEXTS for item in self.values):
return True
return False
if self.domain == DOMAIN_NUMBER:
return self.low > self.high or (self.low == self.high and (self.low_open or self.high_open))
if self.positive & self.negative:
return True
# 多选:「含这几个里的某一个」被「这几个一个都不许含」整个盖住
return self.domain == DOMAIN_MEMBERS and bool(self.positive) and self.positive <= self.negative
def _satisfiable(term: Term) -> bool:
"""一组条件能不能同时成立:按字段分桶收一遍,收出矛盾就是走不到。"""
buckets: dict[tuple[str, str], _Bucket] = {}
for lit in term:
bucket = buckets.get(lit.atom.key)
if bucket is None:
bucket = buckets[lit.atom.key] = _Bucket(lit.atom.domain)
bucket.add(lit)
for bucket in buckets.values():
if bucket.conflicts():
return False
# 数值取反(``not (x > 5)`` 这种在范式里已是反向区间)不需要再看一眼
return True
def describe(guards: Iterable[Guard]) -> str:
"""几条条件合起来的一句话说明(只在提示语里用)。"""
parts = [guard.describe() for guard in guards if not guard.always]
return ";".join(part for part in parts if part)