Python 与 SQLite 实战:为 2-SAT 求解器生成可重放的真假证书
一个配置检查器回答无解,运维同事仍然会追问:究竟是哪几条规则互相冲突?把布尔表达式交给求解器,只拿回一个真假值,并不能解释这件事。本篇实现一个小型证书流水线:可满足时交付完整赋值;不可满足时交付两条带子句编号的蕴含路径;结果写入 SQLite 后,另一段不运行强连通分量算法的程序可以重新核验。
示例面向每条规则最多含两个文字的合取范式,即 2-CNF。文字是变量或其否定,子句内部用或连接,子句之间用且连接。这里用正整数表示变量,用负整数表示否定,例如列表 [1, -2] 表示 x₁ 或非 x₂。它可以表达开关互斥、依赖关系和至少选择一个等条件,但不能把任意三个选项的或约束直接塞进来;输入不符合约定时应拒绝。
下面九段程序均可分别保存并运行,不需要先执行前文,也不依赖第三方包。测试环境为 Python 3.12.14、SQLite 3.53.1;代码只使用标准库。重复出现的基础函数是为了保证每个例子独立。输出块来自实际运行,不包含计时或随机路径。磁盘示例使用临时目录,关闭并重新连接后才验证,退出示例时自动清理文件。

一、先把空值与非法文字说清楚
输入契约决定证书到底在证明什么。变量总数 n 必须是非负整数;合法文字属于正负一到正负 n,零不是变量。Python 中布尔值是整数的子类,因此只写 isinstance(x, int) 会意外接受 True。本实现使用精确类型检查,同时拒绝浮点数、字符串、越界编号和长度超过二的子句。
空公式与空子句必须分开:没有任何子句时,没有条件需要违反,因此可满足;公式中出现空子句时,这个或表达式没有任何真项,因此不可满足。单文字子句 [1] 强制 x₁ 为真;[1, -1] 是永真式;[1, 1] 与 [1] 语义相同。重复子句不改变满足性,但会影响来源编号,后续持久化时保留原样。
第一段使用真值表直接解释这些规则。这个方法只适合很少的变量,却特别适合当测试裁判:它完全不理解图、分量或路径,不容易和后面的求解器共享同一种错误。零变量时唯一赋值是空元组,不应该误判成没有赋值。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
from itertools import product
def models(n, clauses):
cs = normalize(n, clauses)
return [bits for bits in product((False, True), repeat=n)
if all(any(bits[abs(x)-1] == (x > 0) for x in c) for c in cs)]
for label, n, cs in [
("empty formula", 0, []), ("empty clause", 1, [[]]),
("unit", 1, [[1]]), ("tautology", 1, [[1, -1]]),
("duplicate", 1, [[1], [1]]), ("repeated literal", 1, [[1, 1]])]:
print(label, models(n, cs))
invalid = [0, True, 1.0, "1", 2]
for literal in invalid:
try:
normalize(1, [[literal]])
except ValueError:
print(repr(literal), "rejected")运行结果:
empty formula [()] empty clause [] unit [(True,)] tautology [(False,), (True,)] duplicate [(True,)] repeated literal [(True,)] 0 rejected True rejected 1.0 rejected '1' rejected 2 rejected
二、蕴含边必须带上原子句编号
子句 a 或 b 的含义是:如果 a 为假,b 就必须为真;反方向同理。因此加入非 a 到 b、非 b 到 a 两条边。单文字子句可视作 a 或 a,代码会保留两条相同的边,虽然遍历时重复到达同一节点也不会改变结论。永真子句则生成自环,不会凭空制造冲突。
经典的蕴含图与强连通分量判据见 剑桥大学 Martin Richards 的算法讲义,第 3、4、7、17 页。这里增加的是工程记录:每条邻接边携带从零开始的 cid。证书不能只说从一到二,还必须指出是哪一条原始子句允许这一步。即使两条子句完全重复,它们也拥有不同编号。
本例将单位子句、依赖、永真式与重复子句放在一起。输出中的有序二元组依次表示目标文字和来源编号。不要为了去重而先排序全部子句,否则业务规则的原始编号会发生漂移;需要简化时,应另建明确的来源映射。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
def graph(n, clauses):
g = {x: [] for i in range(1, n + 1) for x in (i, -i)}
for cid, c in enumerate(clauses):
if not c:
continue
a, b = c[0], c[-1]
g[-a].append((b, cid))
g[-b].append((a, cid))
return g
cs = normalize(2, [[1], [-1, 2], [2, -2], [-1, 2]])
g = graph(2, cs)
for u in g:
print(u, g[u])
print("edges", sum(map(len, g.values())))运行结果:
1 [(2, 1), (2, 3)] -1 [(1, 0), (1, 0)] 2 [(2, 2)] -2 [(-1, 1), (-2, 2), (-1, 3)] edges 8
三、求解器负责寻找,赋值负责解释
如果某个变量与其否定处于同一强连通分量,就能相互到达,无法给它们分配相反的真假值。否则可以利用分量的拓扑次序构造赋值。下面采用两遍非递归深度优先遍历,避免长依赖链耗尽 Python 递归栈。第一遍在原图记录退出次序,第二遍按逆退出次序遍历反图。
这份实现的分量编号沿原图的跨分量边递增,因此使用 comp[x] 大于 comp[-x] 来决定 x 为真。这个比较方向依赖具体编号约定,不能从另一份 SCC 实现里照搬。若有蕴含 u 到 v,而 u 真、v 假,结合反向否定边非 v 到非 u 以及编号顺序,会得到编号严格绕回的矛盾,所以构造出的赋值满足全部蕴含。
返回 None 表示不可满足,返回空列表则表示零变量空公式的合法赋值。两者不能统一用 if not result 判断。本节先展示寻找结果的核心;后面真正交付时还会加上输入指纹与证据类型,而不是把一个孤立的分量编号当成证明。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
def graph(n, clauses):
g = {x: [] for i in range(1, n + 1) for x in (i, -i)}
for cid, c in enumerate(clauses):
if not c:
continue
a, b = c[0], c[-1]
g[-a].append((b, cid))
g[-b].append((a, cid))
return g
def components(g):
reverse = {u: [] for u in g}
for u in g:
for v, _ in g[u]:
reverse[v].append(u)
seen, order = set(), []
for root in g:
if root in seen:
continue
seen.add(root)
stack = [(root, iter(g[root]))]
while stack:
u, edges = stack[-1]
edge = next(edges, None)
if edge is None:
order.append(u)
stack.pop()
elif edge[0] not in seen:
seen.add(edge[0])
stack.append((edge[0], iter(g[edge[0]])))
comp = {}
number = 0
for root in reversed(order):
if root in comp:
continue
comp[root] = number
todo = [root]
while todo:
for v in reverse[todo.pop()]:
if v not in comp:
comp[v] = number
todo.append(v)
number += 1
return comp
def assignment(n, clauses):
cs = normalize(n, clauses)
if any(not c for c in cs):
return None
comp = components(graph(n, cs))
if any(comp[x] == comp[-x] for x in range(1, n + 1)):
return None
return [comp[x] > comp[-x] for x in range(1, n + 1)]
print("SAT", assignment(3, [[1], [-1, 2], [-2, 3]]))
print("UNSAT", assignment(1, [[1], [-1]]))
print("zero variables", assignment(0, []))运行结果:
SAT [True, True, True] UNSAT None zero variables []
四、建立不依赖求解器的验证器
验证器接受调用方提供的原始 n 与子句,再检查证书,既不调用 components,也不相信证书自报的图。SAT 证书要求恰好 n 个真正的布尔值,并逐条计算原始子句。EMPTY 证书只需给出一个实际为空的子句编号。UNSAT 分支稍后使用,但这里一次完整列出,以便每个示例可单独运行。
指纹的输入为固定版本号、变量数和原始有序子句列表,经紧凑 JSON 编码后计算 SHA-256。元组与列表经校验统一为列表;子句次序、文字次序、重复次数以及单位子句的写法均被保留,所以语义等价不代表同一输入快照。编码与摘要接口依据 Python JSON 文档和 hashlib 文档。
摘要不是签名,也不证明是谁生成了结果。它用于绑定快照;真正的逻辑正确性来自对子句和路径的检查。调用方必须掌握可信原始公式,不能从同一份可篡改数据库里取出公式、证书和摘要,再把三者相互一致当成外部真实性保证。本例故意把整数一冒充布尔值,也会被拒绝。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
import hashlib
import json
def fingerprint(n, clauses):
raw = json.dumps([1, n, clauses], separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def verify(n, clauses, proof):
try:
cs = normalize(n, clauses)
if type(proof) is not dict or proof.get("version") != 1:
return False
if type(proof["version"]) is not int:
return False
if proof.get("input_sha256") != fingerprint(n, cs):
return False
kind = proof.get("kind")
if kind == "SAT":
values = proof["values"]
return (type(values) is list and len(values) == n
and all(type(v) is bool for v in values)
and all(any(values[abs(x)-1] == (x > 0) for x in c)
for c in cs))
if kind == "EMPTY":
cid = proof["cid"]
return type(cid) is int and 0 <= cid < len(cs) and cs[cid] == []
if kind != "UNSAT":
return False
x, paths = proof["x"], proof["paths"]
if type(x) is not int or not 1 <= x <= n:
return False
if type(paths) is not list or len(paths) != 2:
return False
for edges, start, end in zip(paths, (x, -x), (-x, x)):
if type(edges) is not list or not 1 <= len(edges) < 2*n:
return False
current = start
for edge in edges:
if type(edge) is not list or len(edge) != 3:
return False
u, v, cid = edge
if any(type(t) is not int for t in edge):
return False
if u != current or not 0 <= cid < len(cs):
return False
c = cs[cid]
if not c:
return False
a, b = c[0], c[-1]
if not ((u == -a and v == b) or (u == -b and v == a)):
return False
current = v
if current != end:
return False
return True
except (KeyError, TypeError, ValueError, IndexError):
return False
cs = [[1], [-1, 2]]
p = {"version": 1, "input_sha256": fingerprint(2, cs),
"kind": "SAT", "values": [True, True]}
print("valid assignment", verify(2, cs, p))
p["values"] = [True, False]
print("wrong assignment", verify(2, cs, p))
p["values"] = [1, 1]
print("integers as booleans", verify(2, cs, p))
e = {"version": 1, "input_sha256": fingerprint(0, [[]]),
"kind": "EMPTY", "cid": 0}
print("empty-clause proof", verify(0, [[]], e))运行结果:
valid assignment True wrong assignment False integers as booleans False empty-clause proof True
五、无解时交付两条可逐步核验的路径
选一个冲突变量 x,给出 x 到非 x、非 x 到 x 两条路径。如果 x 真,第一条路径迫使非 x 真;如果 x 假,非 x 真,第二条路径又迫使 x 真。真假两个分支都会矛盾,因此原公式无解。只有一条路径通常只是强制一个变量取值,不能证明不可满足。
每个步骤是来源文字、目标文字、子句编号。验证器逐步检查起点衔接、编号范围和那一条子句允许的两种蕴含,最后核对终点。它没有复用建图函数,也没有查询求解器的 SCC 标签。广度优先搜索只用于生成证据;验证时不重新搜索,因而生成器与检查器的职责清楚分开。
广度优先搜索返回简单路径,在二倍变量数个节点的图中,每条路径最多含二倍变量数减一条边。验证器据此限制路径长度。本例的正向路径经过两个子句,反向路径使用单位子句;把第一步伪装成由另一个子句推出,会立即失败。合法证书不保证最小冲突子集,也不保证最适合人阅读。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
import hashlib
import json
def fingerprint(n, clauses):
raw = json.dumps([1, n, clauses], separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def verify(n, clauses, proof):
try:
cs = normalize(n, clauses)
if type(proof) is not dict or proof.get("version") != 1:
return False
if type(proof["version"]) is not int:
return False
if proof.get("input_sha256") != fingerprint(n, cs):
return False
kind = proof.get("kind")
if kind == "SAT":
values = proof["values"]
return (type(values) is list and len(values) == n
and all(type(v) is bool for v in values)
and all(any(values[abs(x)-1] == (x > 0) for x in c)
for c in cs))
if kind == "EMPTY":
cid = proof["cid"]
return type(cid) is int and 0 <= cid < len(cs) and cs[cid] == []
if kind != "UNSAT":
return False
x, paths = proof["x"], proof["paths"]
if type(x) is not int or not 1 <= x <= n:
return False
if type(paths) is not list or len(paths) != 2:
return False
for edges, start, end in zip(paths, (x, -x), (-x, x)):
if type(edges) is not list or not 1 <= len(edges) < 2*n:
return False
current = start
for edge in edges:
if type(edge) is not list or len(edge) != 3:
return False
u, v, cid = edge
if any(type(t) is not int for t in edge):
return False
if u != current or not 0 <= cid < len(cs):
return False
c = cs[cid]
if not c:
return False
a, b = c[0], c[-1]
if not ((u == -a and v == b) or (u == -b and v == a)):
return False
current = v
if current != end:
return False
return True
except (KeyError, TypeError, ValueError, IndexError):
return False
def graph(n, clauses):
g = {x: [] for i in range(1, n + 1) for x in (i, -i)}
for cid, c in enumerate(clauses):
if not c:
continue
a, b = c[0], c[-1]
g[-a].append((b, cid))
g[-b].append((a, cid))
return g
from collections import deque
def path(g, start, end):
previous = {start: None}
queue = deque([start])
while queue and end not in previous:
u = queue.popleft()
for v, cid in g[u]:
if v not in previous:
previous[v] = (u, cid)
queue.append(v)
if end not in previous:
raise ValueError("no implication path")
edges, v = [], end
while v != start:
u, cid = previous[v]
edges.append([u, v, cid])
v = u
return list(reversed(edges))
cs = [[-1, 2], [-2, -1], [1]]
g = graph(2, cs)
p = {"version": 1, "input_sha256": fingerprint(2, cs),
"kind": "UNSAT", "x": 1,
"paths": [path(g, 1, -1), path(g, -1, 1)]}
print("forward", p["paths"][0])
print("backward", p["paths"][1])
print("verified", verify(2, cs, p))
p["paths"][0][0][2] = 2
print("wrong clause source", verify(2, cs, p))运行结果:
forward [[1, 2, 0], [2, -1, 1]] backward [[-1, 1, 2]] verified True wrong clause source False
六、提交到 SQLite,再从磁盘重放
数据库保存一次运行的变量数、原始子句和证书 JSON。演示使用单行承载一整个不可分割的快照,避免读到一半新子句、一半旧证书。SQL 的值统一通过占位符绑定;不把 JSON 拼接进 SQL。写入后显式提交并关闭连接,再建立新连接读取。
代码设 isolation_level=None,并显式执行 BEGIN IMMEDIATE、COMMIT 和 ROLLBACK,使事务边界直接可见。这里遵循 Python sqlite3 的显式事务用法;运行基于当前默认的 legacy 事务模式,未来若改用 autocommit 参数,需要统一设计连接方式。SQLite 的 事务文档也说明了 BEGIN 与提交、回滚的行为。
重点在最后一行:verify 接收的是程序里可信的 cs,而不是任由数据库里的公式替换它。重新打开文件只能证明读写流程发生过,只有语义验证通过才能把结果交给调用方。生产中应把可信公式保存在任务系统、受控配置或经认证的提交记录里,并对缺行、JSON 解析错误和数据库读取失败分别报告。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
import hashlib
import json
def fingerprint(n, clauses):
raw = json.dumps([1, n, clauses], separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def verify(n, clauses, proof):
try:
cs = normalize(n, clauses)
if type(proof) is not dict or proof.get("version") != 1:
return False
if type(proof["version"]) is not int:
return False
if proof.get("input_sha256") != fingerprint(n, cs):
return False
kind = proof.get("kind")
if kind == "SAT":
values = proof["values"]
return (type(values) is list and len(values) == n
and all(type(v) is bool for v in values)
and all(any(values[abs(x)-1] == (x > 0) for x in c)
for c in cs))
if kind == "EMPTY":
cid = proof["cid"]
return type(cid) is int and 0 <= cid < len(cs) and cs[cid] == []
if kind != "UNSAT":
return False
x, paths = proof["x"], proof["paths"]
if type(x) is not int or not 1 <= x <= n:
return False
if type(paths) is not list or len(paths) != 2:
return False
for edges, start, end in zip(paths, (x, -x), (-x, x)):
if type(edges) is not list or not 1 <= len(edges) < 2*n:
return False
current = start
for edge in edges:
if type(edge) is not list or len(edge) != 3:
return False
u, v, cid = edge
if any(type(t) is not int for t in edge):
return False
if u != current or not 0 <= cid < len(cs):
return False
c = cs[cid]
if not c:
return False
a, b = c[0], c[-1]
if not ((u == -a and v == b) or (u == -b and v == a)):
return False
current = v
if current != end:
return False
return True
except (KeyError, TypeError, ValueError, IndexError):
return False
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory
cs = [[1], [-1]]
p = {"version": 1, "input_sha256": fingerprint(1, cs),
"kind": "UNSAT", "x": 1, "paths": [[[1, -1, 1]], [[-1, 1, 0]]]}
with TemporaryDirectory() as folder:
file = Path(folder) / "proofs.sqlite3"
db = sqlite3.connect(file, isolation_level=None)
db.execute("CREATE TABLE runs(id INTEGER PRIMARY KEY, n INTEGER, clauses TEXT, proof TEXT)")
db.execute("BEGIN IMMEDIATE")
try:
db.execute("INSERT INTO runs VALUES(?,?,?,?)",
(1, 1, json.dumps(cs), json.dumps(p)))
db.execute("COMMIT")
except BaseException:
db.execute("ROLLBACK")
raise
db.close()
db = sqlite3.connect(file, isolation_level=None)
n, stored_cs, stored_p = db.execute(
"SELECT n,clauses,proof FROM runs WHERE id=?", (1,)).fetchone()
db.close()
try:
loaded = normalize(n, json.loads(stored_cs))
same_input = fingerprint(n, loaded) == fingerprint(1, cs)
except (TypeError, ValueError):
same_input = False
print("reopened", file.is_file())
print("same input", same_input)
print("verified", same_input and verify(1, cs, json.loads(stored_p)))运行结果:
reopened True same input True verified True
七、主动篡改证据,确认失败发生在正确位置
只验证正常样本,容易把一个总返回 True 的检查器当成成功实现。本例直接更新 SQLite 中的证书内容,首先将蕴含边的来源编号换成不支持它的子句;随后用另一份公式的有效 SAT 证书替换整个结果。第一种攻击应在路径语义检查处失败,第二种应在输入指纹绑定处失败。
这里采用内存数据库便于隔离篡改测试,上一节负责磁盘关闭重开的生命周期。两项测试验证不同责任:数据库能忠实保存错误内容,应用仍然必须拒绝。数据库约束可以保证字段非空、主键唯一,却不能仅靠一个 kind 字段证明无解,更不会自动判断一条路径是否真的来自规则。
如果攻击者同时改写全部数据库内容,可信原始公式仍应来自数据库之外。反过来,若用户确实修改了业务规则,就必须建立新输入版本并重新求解,不能沿用旧证书。摘要不应被当成不可篡改日志或权限控制方案,备份、访问授权和来源认证是另一层工作。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
import hashlib
import json
def fingerprint(n, clauses):
raw = json.dumps([1, n, clauses], separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def verify(n, clauses, proof):
try:
cs = normalize(n, clauses)
if type(proof) is not dict or proof.get("version") != 1:
return False
if type(proof["version"]) is not int:
return False
if proof.get("input_sha256") != fingerprint(n, cs):
return False
kind = proof.get("kind")
if kind == "SAT":
values = proof["values"]
return (type(values) is list and len(values) == n
and all(type(v) is bool for v in values)
and all(any(values[abs(x)-1] == (x > 0) for x in c)
for c in cs))
if kind == "EMPTY":
cid = proof["cid"]
return type(cid) is int and 0 <= cid < len(cs) and cs[cid] == []
if kind != "UNSAT":
return False
x, paths = proof["x"], proof["paths"]
if type(x) is not int or not 1 <= x <= n:
return False
if type(paths) is not list or len(paths) != 2:
return False
for edges, start, end in zip(paths, (x, -x), (-x, x)):
if type(edges) is not list or not 1 <= len(edges) < 2*n:
return False
current = start
for edge in edges:
if type(edge) is not list or len(edge) != 3:
return False
u, v, cid = edge
if any(type(t) is not int for t in edge):
return False
if u != current or not 0 <= cid < len(cs):
return False
c = cs[cid]
if not c:
return False
a, b = c[0], c[-1]
if not ((u == -a and v == b) or (u == -b and v == a)):
return False
current = v
if current != end:
return False
return True
except (KeyError, TypeError, ValueError, IndexError):
return False
import sqlite3
from copy import deepcopy
trusted = [[1], [-1]]
p = {"version": 1, "input_sha256": fingerprint(1, trusted),
"kind": "UNSAT", "x": 1, "paths": [[[1, -1, 1]], [[-1, 1, 0]]]}
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE proof(payload TEXT)")
db.execute("INSERT INTO proof VALUES(?)", (json.dumps(p),))
def replay():
stored = json.loads(db.execute("SELECT payload FROM proof").fetchone()[0])
return verify(1, trusted, stored)
print("original", replay())
bad = deepcopy(p)
bad["paths"][0][0][2] = 0
with db:
db.execute("UPDATE proof SET payload=?", (json.dumps(bad),))
print("tampered edge", replay())
replacement = {"version": 1, "input_sha256": fingerprint(1, [[1]]),
"kind": "SAT", "values": [True]}
with db:
db.execute("UPDATE proof SET payload=?", (json.dumps(replacement),))
print("substituted formula", replay())
db.close()运行结果:
original True tampered edge False substituted formula False
八、把完整求解器交给穷举真值表审判
这一段完整整合了输入校验、建图、非递归 SCC、证书生成和独立验证,仍然可以单独运行。测试范围明确限定为两个变量、最多三个有序子句;子句池包含一个空子句、四个单位子句和十六个有序二元子句,共二十一种。由此一共检查一加二十一加二十一平方加二十一立方,即九千七百二十四份输入。
这些输入保留重复和顺序,因此不仅覆盖普通二元约束,还覆盖空子句、永真式、重复文字、重复规则与直接冲突。裁判枚举四种布尔赋值,逐字面计算公式;求解器给出的 SAT 与否必须与裁判相同,产生的任意类型证书还必须通过另一套验证逻辑。断言失败就立即停止,输出 PASS 只表示这个有限范围全部通过。
itertools.product 提供笛卡尔积枚举。穷举不能替代数学证明,也不能外推为所有规模都正确;它的价值是让边界组合系统化。部署前还应增加更长的依赖链、随机大实例、数据库异常、证书字段损坏和输入版本迁移测试,而不是盲目增大穷举变量数。
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError("n must be a nonnegative integer")
if not isinstance(clauses, (list, tuple)):
raise ValueError("clauses must be a list or tuple")
result = []
for c in clauses:
if not isinstance(c, (list, tuple)) or len(c) > 2:
raise ValueError("each clause must contain 0, 1 or 2 literals")
if any(type(x) is not int or not 1 <= abs(x) <= n for x in c):
raise ValueError("invalid literal")
result.append(list(c))
return result
import hashlib
import json
def fingerprint(n, clauses):
raw = json.dumps([1, n, clauses], separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def graph(n, clauses):
g = {x: [] for i in range(1, n + 1) for x in (i, -i)}
for cid, c in enumerate(clauses):
if not c:
continue
a, b = c[0], c[-1]
g[-a].append((b, cid))
g[-b].append((a, cid))
return g
def components(g):
reverse = {u: [] for u in g}
for u in g:
for v, _ in g[u]:
reverse[v].append(u)
seen, order = set(), []
for root in g:
if root in seen:
continue
seen.add(root)
stack = [(root, iter(g[root]))]
while stack:
u, edges = stack[-1]
edge = next(edges, None)
if edge is None:
order.append(u)
stack.pop()
elif edge[0] not in seen:
seen.add(edge[0])
stack.append((edge[0], iter(g[edge[0]])))
comp = {}
number = 0
for root in reversed(order):
if root in comp:
continue
comp[root] = number
todo = [root]
while todo:
for v in reverse[todo.pop()]:
if v not in comp:
comp[v] = number
todo.append(v)
number += 1
return comp
from collections import deque
def path(g, start, end):
previous = {start: None}
queue = deque([start])
while queue and end not in previous:
u = queue.popleft()
for v, cid in g[u]:
if v not in previous:
previous[v] = (u, cid)
queue.append(v)
if end not in previous:
raise ValueError("no implication path")
edges, v = [], end
while v != start:
u, cid = previous[v]
edges.append([u, v, cid])
v = u
return list(reversed(edges))
def solve(n, clauses):
cs = normalize(n, clauses)
proof = {"version": 1, "input_sha256": fingerprint(n, cs)}
for cid, c in enumerate(cs):
if not c:
return dict(proof, kind="EMPTY", cid=cid)
g = graph(n, cs)
comp = components(g)
for x in range(1, n + 1):
if comp[x] == comp[-x]:
return dict(proof, kind="UNSAT", x=x,
paths=[path(g, x, -x), path(g, -x, x)])
values = [comp[x] > comp[-x] for x in range(1, n + 1)]
return dict(proof, kind="SAT", values=values)
def verify(n, clauses, proof):
try:
cs = normalize(n, clauses)
if type(proof) is not dict or proof.get("version") != 1:
return False
if type(proof["version"]) is not int:
return False
if proof.get("input_sha256") != fingerprint(n, cs):
return False
kind = proof.get("kind")
if kind == "SAT":
values = proof["values"]
return (type(values) is list and len(values) == n
and all(type(v) is bool for v in values)
and all(any(values[abs(x)-1] == (x > 0) for x in c)
for c in cs))
if kind == "EMPTY":
cid = proof["cid"]
return type(cid) is int and 0 <= cid < len(cs) and cs[cid] == []
if kind != "UNSAT":
return False
x, paths = proof["x"], proof["paths"]
if type(x) is not int or not 1 <= x <= n:
return False
if type(paths) is not list or len(paths) != 2:
return False
for edges, start, end in zip(paths, (x, -x), (-x, x)):
if type(edges) is not list or not 1 <= len(edges) < 2*n:
return False
current = start
for edge in edges:
if type(edge) is not list or len(edge) != 3:
return False
u, v, cid = edge
if any(type(t) is not int for t in edge):
return False
if u != current or not 0 <= cid < len(cs):
return False
c = cs[cid]
if not c:
return False
a, b = c[0], c[-1]
if not ((u == -a and v == b) or (u == -b and v == a)):
return False
current = v
if current != end:
return False
return True
except (KeyError, TypeError, ValueError, IndexError):
return False
from itertools import product
literals = (-2, -1, 1, 2)
pool = [[]] + [[x] for x in literals] + [list(c) for c in product(literals, repeat=2)]
checked = 0
for size in range(4):
for clauses in product(pool, repeat=size):
oracle = any(all(any(bits[abs(x)-1] == (x > 0) for x in c)
for c in clauses)
for bits in product((False, True), repeat=2))
p = solve(2, clauses)
assert (p["kind"] == "SAT") == oracle
assert verify(2, clauses, p)
checked += 1
print("formulas checked", checked)
print("oracle and certificates", "PASS")运行结果:
formulas checked 9724 oracle and certificates PASS
九、事务成功与证书有效是两道不同检查
最后故意在同一事务里插入重复主键。第二次插入失败后,显式回滚,第一次插入也不应留下孤立记录。再执行一个成功事务并重新连接,确认提交的行仍然存在。这段只演示存储原子性:保存的占位 JSON 尚未验证,所以即使数据库操作全部成功,也不能对外宣布 SAT 或 UNSAT。
业务代码可以先在内存中生成并验证证书,再在一个事务中写入公式和结果;读取时重新绑定可信输入并复验。若需要多张表保存规则和路径,应让它们共用一次事务,并在读取时使用一致的读事务。不要把连接上下文管理器理解为自动关闭连接;这里每条正常路径都显式 close。
本教程的求解与证据生成在变量数加子句数的规模上线性增长,前提是每条子句最多两个文字;验证 SAT 需要检查全部赋值与子句,验证 UNSAT 则检查两条路径并计算输入摘要。SQLite 序列化、磁盘同步与锁等待另行计费。面对外部不可信文件,还需限制 JSON 字节数、变量数和规则数;本文的小型验证器不是隔离恶意资源消耗的安全沙箱。
import json
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
file = Path(folder) / "batch.sqlite3"
db = sqlite3.connect(file, isolation_level=None)
db.execute("CREATE TABLE runs(id INTEGER PRIMARY KEY, formula TEXT NOT NULL, proof TEXT NOT NULL)")
db.execute("BEGIN IMMEDIATE")
try:
db.execute("INSERT INTO runs VALUES(?,?,?)", (1, "[]", "{}"))
db.execute("INSERT INTO runs VALUES(?,?,?)", (1, "[]", "{}"))
db.execute("COMMIT")
except sqlite3.IntegrityError:
db.execute("ROLLBACK")
print("duplicate key rolled back")
print("rows after failure", db.execute("SELECT COUNT(*) FROM runs").fetchone()[0])
db.execute("BEGIN IMMEDIATE")
db.execute("INSERT INTO runs VALUES(?,?,?)",
(2, json.dumps([[1], [-1]]), json.dumps({"pending_verification": True})))
db.execute("COMMIT")
db.close()
db = sqlite3.connect(file, isolation_level=None)
print("rows after reopen", db.execute("SELECT id FROM runs ORDER BY id").fetchall())
db.close()运行结果:
duplicate key rolled back rows after failure 0 rows after reopen [(2,)]
交付的不是一个结论,而是一份可检查的结果
这条流水线最有价值的部分,是让正确性证据跨越求解器与存储边界:SAT 有完整赋值,普通 UNSAT 有双向蕴含路径,空子句有明确来源;三者都绑定到同一份原始输入。生成器可以升级、缓存可以重建,验证器仍然只需要理解简单的子句语义。
实际接入时,先给每条业务规则保存稳定标识,并将本次输入的位置编号映射回这些标识。用户看到冲突路径时,就能定位对应的配置行。不过路径上的所有子句合起来只是一份充分的无解证据,删除其中任何一条后是否能恢复可满足,仍需额外分析。可验证、可追溯与最小解释是三个独立目标,不应混为一谈。

