Python sqlite3 有向图拓扑证书:稳定 Kahn 排序、真实环见证与独立验证

10-19 4阅读

把有向关系排成一列并不难,难的是解释这列为什么可信,以及失败时拿出真正能核对的证据。本篇把 SQLite 当作节点与边的存储,使用 Python 标准库实现确定性的拓扑排序,然后分别输出成功排列证书或失败有向环证书。目标是构建一个可审查的静态图检查器,适用于配置依赖、导入顺序和规则编排等需要先验证再使用的场景。

全文关注三个容易混淆的边界:层次批次不等于唯一的线性顺序,Kahn 剩余节点不全是环节点,排序器返回结果也不等于已经独立验证。算法必须把孤立节点、自环、重复边、方向和同优先级选择规则说清楚;否则一次看似合理的输出,很可能只是输入顺序碰巧帮了忙。

Python sqlite3 有向图拓扑证书:稳定 Kahn 排序、真实环见证与独立验证
AI 生成的概念配图:数据库中的有向关系被排列并接受检查,旁侧闭环象征失败证据;不是精确图结构或真实软件界面。

运行环境为 Python 3.12 及以上,使用标准库 sqlite3、heapq 等模块,无需安装第三方包。九段示例各自包含导入、建表、数据和断言,可分别保存并执行 python -X dev -W error example_01.py,不要添加会关闭断言的优化选项。连接统一设置 autocommit=True,显式用 SQL 的 BEGIN、COMMIT、ROLLBACK 管理读事务,并通过 closing 确保关闭。这里没有依赖未来版本的默认事务模式,参数说明见 Python sqlite3 官方文档。示例函数假设输入来自本文受约束的表,而非未经检查的任意对象。

一、先声明边方向与存储不变量

本文约定一行 edge(src, dst) 表示 src 必须位于 dst 之前,箭头从前置节点指向后继节点。节点表独立存在,因而完全没有边的孤立节点不会丢失。priority 是当前可选集合中的选择优先级,数字越小越先选;它不能推翻边约束,也不是实际运行时长。节点标识统一为字符串,示例仅使用 ASCII 标识,从而让比较规则清楚可见。

联合主键使存储模型成为无重复边的有向图,同方向的重复边被拒绝,反方向的两条边则可以共存。外键负责保证端点存在,不能证明无环。这里特意允许自环,因为导入审查器需要把它作为长度为一的真实环报告,而不是在存储层就丢掉诊断对象。生产系统也可以禁止自环,但算法仍应理解其含义。每次连接都显式开启外键并读取确认,相关行为见 SQLite 外键官方说明。

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [("a", 0), ("b", 0), ("isolated", 7)], [("a", "b")])
    for edge in [("a", "b"), ("a", "missing")]:
        try:
            con.execute("INSERT INTO edge VALUES(?, ?)", edge)
        except sqlite3.IntegrityError:
            print("拒绝", edge)
        else:
            raise AssertionError("invalid edge accepted")
    con.execute("INSERT INTO edge VALUES(?, ?)", ("b", "b"))
    nodes, edges = snapshot(con)
    print("节点", [u for u, _ in nodes])
    print("边", list(edges))
    assert con.execute("PRAGMA foreign_key_check").fetchall() == []

运行结果:

拒绝 ('a', 'b')
拒绝 ('a', 'missing')
节点 ['a', 'b', 'isolated']
边 [('a', 'b'), ('b', 'b')]

最后成功写入的 b 到 b 不代表数据已经通过拓扑验证,只表示它符合关系结构。将结构约束、图论约束和业务策略分开,可以避免把一次插入成功误解成整个图可排序。示例里的反例写入发生在显式自动提交模式,单条失败不会撤销之前成功的记录;批量正式导入通常应额外包在一个事务中。

二、读取一个图快照,再开始计算

算法需要同时知道完整节点集合和完整边集合。如果两个查询各自读取不同提交版本,可能看到新边却看不到对应节点,或者把已经删除的边带入计算。下面在显式读事务中读取两张表,结果物化为元组,然后结束事务。对普通文件数据库,这样的多个读取来自同一个读事务视图;本例使用内存库来展示接口,不用线程时序伪造并发结果。事务语义参见 SQLite 事务文档。

ORDER BY 让导出的行顺序确定,但它本身并不进行拓扑排序。之后还会根据相同快照构造规范化摘要,用来标识证书究竟针对哪一份输入。摘要同时覆盖节点、优先级和边,避免只比较边数或节点数造成误判。这里只使用整型优先级与字符串标识,不把浮点数、时间对象或自定义排序函数放进序列化契约。

import sqlite3
from contextlib import closing
import hashlib
import json

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def fingerprint(nodes, edges):
    payload = {"nodes": sorted(nodes), "edges": sorted(edges)}
    raw = json.dumps(payload, ensure_ascii=False,
                     separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [("b", 2), ("a", 1), ("z", 9)], [("a", "b")])
    nodes, edges = snapshot(con)
    reversed_hash = fingerprint(tuple(reversed(nodes)), tuple(reversed(edges)))
    print("节点快照", nodes)
    print("边快照", edges)
    print("规范摘要一致", fingerprint(nodes, edges) == reversed_hash)
    print("事务已结束", not con.in_transaction)

运行结果:

节点快照 (('a', 1), ('b', 2), ('z', 9))
边快照 (('a', 'b'),)
规范摘要一致 True
事务已结束 True

读事务只保证读取期间的一致性,并不会永久冻结数据库。计算过程中其他连接可以产生新的图版本;本次输出仍然只属于手里的快照。后面如果要把结果用于写操作,还需要在使用点重新核对版本或摘要,不能因为算法曾经成功就认为未来数据库一直无环。

三、用最小堆规定 Kahn 算法的确定性选择

Kahn 算法维护尚未移除的入边数量,每次只能取当前入度为零的节点。选中节点后,删除它对后继的影响;某个后继的计数恰好降为零时,才进入候选集合。只把全部零入度节点初始排序一次并不够,因为新候选会在过程中不断加入。最小堆适合表达这种动态选择,Python 官方 heapq 优先队列说明也专门讨论了相同优先级的平局处理。

这里的堆项是二元组 priority、id,先比数字,再比持久化标识。所谓稳定平局,具体指同一图和同一优先级总能得到相同结果,与 SQL 插入顺序无关;并不是宣称 heapq 自带稳定排序,也不是按节点进入候选队列的先后决定平局。若业务要求保留录入顺序,应新增不可变序号并把它纳入比较键和输入摘要。

import sqlite3
from contextlib import closing
import heapq

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def kahn(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        outgoing[u].append(v)
        incoming[v] += 1
    ready = [(priority[u], u) for u in priority if incoming[u] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        _, u = heapq.heappop(ready)
        order.append(u)
        for v in outgoing[u]:
            incoming[v] -= 1
            if incoming[v] == 0:
                heapq.heappush(ready, (priority[v], v))
    residual = sorted(u for u in priority if incoming[u] > 0)
    return order, residual

nodes = [("z", 0), ("a", 0), ("b", 0), ("c", -1)]
edges = [("b", "c"), ("a", "b")]
results = []
for reverse in (False, True):
    with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
        store(con, nodes[::-1] if reverse else nodes,
              edges[::-1] if reverse else edges)
        order, residual = kahn(*snapshot(con))
        assert residual == []
        results.append(order)
print("确定顺序", results[0])
print("逆序写入相同", results[0] == results[1])

运行结果:

确定顺序 ['a', 'b', 'c', 'z']
逆序写入相同 True

c 的优先级最小,却不能越过 a 和 b,因为它最初尚不可选;b 一旦解锁,又能排到原来已经就绪的 z 之前。这正是每一步在合法候选中做最小选择的含义。算法不会改写 SQLite 的边,也不会给节点追加执行状态,它输出的是一个静态排列证据。

四、同一张 DAG 的分层与线性顺序不是一回事

拓扑序把所有节点放进一条线,层次则把同一轮开始时已经就绪的节点放在一起。计算层次时,本轮新解锁的节点必须留给下一轮;如果立刻加入当前批次,就把两种概念混在了一起。对无权有向无环图,按这种规则得到的层号等于从任意根出发到该节点的最长路径边数,但它不包含持续时间和资源容量信息。

下面只给 a 到 b 一条边,z 是孤立节点。逐次取堆顶可以得到 a、b、z;按整轮分层则得到首层 a、z,第二层 b。把这些层顺序展开依然是合法拓扑序,却不一定满足前面逐步选择最小键的确定性规则。层内没有依赖路径,也不意味着这些任务已经获得同时运行所需的线程、连接或额度。

import sqlite3
from contextlib import closing
import heapq

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def kahn(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        outgoing[u].append(v)
        incoming[v] += 1
    ready = [(priority[u], u) for u in priority if incoming[u] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        _, u = heapq.heappop(ready)
        order.append(u)
        for v in outgoing[u]:
            incoming[v] -= 1
            if incoming[v] == 0:
                heapq.heappush(ready, (priority[v], v))
    residual = sorted(u for u in priority if incoming[u] > 0)
    return order, residual

def layers(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        incoming[v] += 1
        outgoing[u].append(v)
    key = lambda u: (priority[u], u)
    ready = sorted((u for u in priority if incoming[u] == 0), key=key)
    result = []
    while ready:
        result.append(ready)
        following = []
        for u in ready:
            for v in outgoing[u]:
                incoming[v] -= 1
                if incoming[v] == 0:
                    following.append(v)
        ready = sorted(following, key=key)
    if sum(map(len, result)) != len(priority):
        raise ValueError("graph has a cycle")
    return result

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [("a", 0), ("b", 0), ("z", 0)], [("a", "b")])
    graph = snapshot(con)
    order, residual = kahn(*graph)
    assert not residual
    batches = layers(*graph)
    print("逐次选择", order)
    print("整轮分层", batches)
    print("层次展开", [u for batch in batches for u in batch])

运行结果:

逐次选择 ['a', 'b', 'z']
整轮分层 [['a', 'z'], ['b']]
层次展开 ['a', 'z', 'b']

因此接口应明确返回的是 order 还是 layers,而不要都命名为 schedule。本文只证明前置关系满足,不处理失败重试、并发领取或任务运行状态;这也避免将静态图审查与在线依赖执行器混为一谈。

五、失败时的残留集合,不能直接命名为环节点

当就绪堆变空,而输出节点数少于总数时,图中必有有向环。不过,此时剩下的节点不一定个个都属于环。考虑 a 与 b 相互指向,b 还指向 c,c 再指向 d:a 和 b 构成环,c 和 d 只是被环阻塞的下游。它们的剩余入度依旧非零,因此同样不会被 Kahn 算法取走。

下面另加一个完全独立的 x 到 y 分量,验证可消去的部分仍会返回。这个部分顺序不是整张图的成功证书;如果调用方忽略 residual 就直接使用 order,会把失败伪装成少量节点的成功结果。应该显式区分完整排序、部分消去结果、阻塞残留和实际闭环证据。

import sqlite3
from contextlib import closing
import heapq

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def kahn(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        outgoing[u].append(v)
        incoming[v] += 1
    ready = [(priority[u], u) for u in priority if incoming[u] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        _, u = heapq.heappop(ready)
        order.append(u)
        for v in outgoing[u]:
            incoming[v] -= 1
            if incoming[v] == 0:
                heapq.heappush(ready, (priority[v], v))
    residual = sorted(u for u in priority if incoming[u] > 0)
    return order, residual

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [(u, 0) for u in "abcdxy"],
          [("a", "b"), ("b", "a"), ("b", "c"),
           ("c", "d"), ("x", "y")])
    order, residual = kahn(*snapshot(con))
    print("已消去", order)
    print("阻塞残留", residual)
    print("本图环外下游", [u for u in residual if u in {"c", "d"}])
    assert order == ["x", "y"]
    assert residual == ["a", "b", "c", "d"]

运行结果:

已消去 ['x', 'y']
阻塞残留 ['a', 'b', 'c', 'd']
本图环外下游 ['c', 'd']

为什么非空残留必然含环?结束时每个残留节点都还有来自残留集合的入边。任选一个节点不断逆向追溯前驱,有限集合中必然重复某个节点,于是形成有向闭合路径。这个论证只证明集合里存在环,并没有证明每个残留节点都处在环上。若要列出所有真正的环节点,应进一步计算强连通分量,而不是给残留集合换个名字。

六、从残留子图提取一条真实有向环

失败证据应是能够逐条核对的闭合节点列表,例如 a、b、a 表示 a 到 b 和 b 到 a 两条边确实存在。下面在残留诱导子图中做深度优先搜索,灰色代表当前搜索路径上的节点,黑色代表已经完全退出的节点。只有指向灰色节点的边才能沿当前路径截出环;单纯遇到已访问节点是不够的,跨向另一条已结束分支并不构成环。

实现使用显式栈而非递归,避免长链先撞上 Python 的递归深度限制。根和邻接边按标识排序,只是为了让诊断结果可复现;返回的环不保证最短,也不保证包含全部环。自环会自然返回两次同一个节点,首尾相同是闭合表达式的一部分,不应被去重成单个元素。

import sqlite3
from contextlib import closing
import heapq

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def kahn(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        outgoing[u].append(v)
        incoming[v] += 1
    ready = [(priority[u], u) for u in priority if incoming[u] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        _, u = heapq.heappop(ready)
        order.append(u)
        for v in outgoing[u]:
            incoming[v] -= 1
            if incoming[v] == 0:
                heapq.heappush(ready, (priority[v], v))
    residual = sorted(u for u in priority if incoming[u] > 0)
    return order, residual

def cycle_witness(nodes, edges, allowed):
    allowed = set(allowed)
    outgoing = {u: [] for u, _ in nodes if u in allowed}
    for u, v in sorted(edges):
        if u in allowed and v in allowed:
            outgoing[u].append(v)
    color = {u: 0 for u in outgoing}
    for root in sorted(outgoing):
        if color[root] != 0:
            continue
        path, position = [root], {root: 0}
        color[root] = 1
        stack = [(root, iter(outgoing[root]))]
        while stack:
            u, children = stack[-1]
            try:
                v = next(children)
            except StopIteration:
                stack.pop()
                path.pop()
                position.pop(u)
                color[u] = 2
                continue
            if color[v] == 1:
                return path[position[v]:] + [v]
            if color[v] == 0:
                color[v] = 1
                position[v] = len(path)
                path.append(v)
                stack.append((v, iter(outgoing[v])))
    return []

cases = [
    ([(u, 0) for u in "abcdxy"],
     [("a", "b"), ("b", "a"), ("b", "c"), ("c", "d"), ("x", "y")]),
    ([("s", 0)], [("s", "s")]),
]
for rows, links in cases:
    with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
        store(con, rows, links)
        nodes, edges = snapshot(con)
        order, residual = kahn(nodes, edges)
        cycle = cycle_witness(nodes, edges, residual)
        assert residual and cycle
        print("真实环", cycle)

运行结果:

真实环 ['a', 'b', 'a']
真实环 ['s', 's']

这段代码把环定位收窄到失败残留,已经消去的独立分量不会干扰诊断。实际展示错误时,可以同时附带残留数量和一条环,帮助读者理解影响范围;但不要写成“以下节点全部互相依赖”。对于多个独立环,一条证据足以否定 DAG 性质,却不足以支持完整修复清单。

七、写一个不调用排序器的独立证书校验器

可信的证书校验不应该再次调用相同的 Kahn 函数,然后比较两个输出是否一样,那样会把实现中的共同错误复制两次。成功证书的校验只需确认:所有节点恰好出现一次,且每条边的起点位置严格早于终点。失败证书则检查首尾相等、中间节点不重复、所有节点存在,并逐一确认每条有向边存在。两种校验都不需要执行图搜索。

校验器面向已经通过数据库结构约束的图以及由字符串列表组成的证书。接收不可信网络 JSON 时,还应在进入这里之前校验容器类型、字符串长度和资源上限;它不是任意 Python 对象的安全反序列化器。尤其要分清合法性与规范性:任何满足边约束的完整排列都是成功证书,但只有额外验证逐步最小候选策略,才能证明它恰好是本教程约定的规范输出。

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def valid_order(nodes, edges, order):
    ids = {u for u, _ in nodes}
    if len(order) != len(ids) or set(order) != ids:
        return False
    position = {u: i for i, u in enumerate(order)}
    return all(u in ids and v in ids and position[u] < position[v]
               for u, v in edges)

def valid_cycle(nodes, edges, cycle):
    ids = {u for u, _ in nodes}
    if len(cycle) < 2 or cycle[0] != cycle[-1]:
        return False
    body = cycle[:-1]
    if len(set(body)) != len(body) or not set(body) <= ids:
        return False
    edge_set = set(edges)
    return all((u, v) in edge_set for u, v in zip(cycle, cycle[1:]))

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [(u, 0) for u in "abz"], [("a", "b")])
    nodes, edges = snapshot(con)
    for label, order in [
        ("规范序", ["a", "b", "z"]),
        ("另一合法序", ["z", "a", "b"]),
        ("重复遗漏", ["a", "b", "b"]),
        ("反向约束", ["b", "a", "z"]),
    ]:
        print(label, valid_order(nodes, edges, order))
    print("虚假闭环", valid_cycle(nodes, edges, ["a", "b", "a"]))
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [("a", 0), ("b", 0)], [("a", "b"), ("b", "a")])
    nodes, edges = snapshot(con)
    print("真实闭环", valid_cycle(nodes, edges, ["a", "b", "a"]))

运行结果:

规范序 True
另一合法序 True
重复遗漏 False
反向约束 False
虚假闭环 False
真实闭环 True

失败列表里的 a、b、a 看起来像环,但在只有 a 到 b 的数据库中无法通过检查。校验器检查实际方向,不会把无向连接当作有向边。完整拓扑序与真实有向环也不会同时成立:环上的每条边都要求位置严格增加,回到起点时就会产生不可能的严格不等式。

八、把证书绑定到输入,而不是绑定到一次日志

如果一张图更新后仍沿用旧证书,即便节点数和边数恰好相同,也不能证明新图正确。下面为证书携带规范输入摘要。验证时先核对当前快照的摘要,再检查排列。新增一条 a 到 c 的边不会破坏原来的 a、b、c 排列,但它改变了输入,因此旧证书仍应被识别为过期;重新针对新快照出证后才可以继续。

这是一种内容绑定协议,不是签名系统。SHA-256 摘要能让普通输入变更被检测出来,却不能证明证书作者是谁,也不能阻止有权修改证书的人同步替换摘要。如果需要对外证明来源,应另外设计签名和密钥管理;如果要执行更新,应把版本校验与更新放在适当的同一写事务中,避免检查之后再次发生变化。

import sqlite3
from contextlib import closing
import hashlib
import json

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def fingerprint(nodes, edges):
    payload = {"nodes": sorted(nodes), "edges": sorted(edges)}
    raw = json.dumps(payload, ensure_ascii=False,
                     separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()

def valid_order(nodes, edges, order):
    ids = {u for u, _ in nodes}
    if len(order) != len(ids) or set(order) != ids:
        return False
    position = {u: i for i, u in enumerate(order)}
    return all(u in ids and v in ids and position[u] < position[v]
               for u, v in edges)

def valid_cycle(nodes, edges, cycle):
    ids = {u for u, _ in nodes}
    if len(cycle) < 2 or cycle[0] != cycle[-1]:
        return False
    body = cycle[:-1]
    if len(set(body)) != len(body) or not set(body) <= ids:
        return False
    edge_set = set(edges)
    return all((u, v) in edge_set for u, v in zip(cycle, cycle[1:]))

def accepts(nodes, edges, certificate):
    return (certificate.get("kind") == "order"
            and certificate.get("snapshot") == fingerprint(nodes, edges)
            and valid_order(nodes, edges, certificate["order"]))

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    store(con, [(u, 0) for u in "abc"], [("a", "b")])
    nodes, edges = snapshot(con)
    certificate = {"kind": "order", "snapshot": fingerprint(nodes, edges),
                   "order": ["a", "b", "c"]}
    certificate = json.loads(json.dumps(certificate))
    print("原快照接受", accepts(nodes, edges, certificate))
    con.execute("INSERT INTO edge VALUES(?, ?)", ("a", "c"))
    fresh_nodes, fresh_edges = snapshot(con)
    print("排列仍合法", valid_order(fresh_nodes, fresh_edges, certificate["order"]))
    print("旧证书接受", accepts(fresh_nodes, fresh_edges, certificate))

运行结果:

原快照接受 True
排列仍合法 True
旧证书接受 False

摘要中也包含 priority,因此仅调整优先级会让旧证书过期,这与确定性选择策略属于输入契约相一致。若系统只关心存在某个合法排列,可以设计更窄的证书格式,但应明确删去哪些输入及其原因,不能无意间把规则变更排除在版本检测之外。

九、穷举三节点有向图,让独立 oracle 检查边界

几个手写例子很容易漏掉自环、多个环或孤立点。三个有标签节点共有九个可能的有向边位,包括自环;逐一枚举是否存在,总计五百一十二张图。对每张图,暴力列举全部六个排列并直接核验每条边,得到完全独立的合法排列集合。若集合非空,Kahn 必须成功且在相同优先级时返回字典序最小排列;若集合为空,算法必须失败并给出可验证的真实环。

这是适合小规模回归测试的穷举,不是大图求解方法。程序还分别测试空图和两个孤立节点,并固定打乱插入顺序,避免恰好依赖数据加载顺序。测试输出包含 DAG 数量,但断言依据是逐图的独立枚举与证书检查,不是只比较一个预先记住的统计数字。

import sqlite3
from contextlib import closing
import heapq
import itertools
import random

SCHEMA = """
CREATE TABLE node(
    id TEXT PRIMARY KEY NOT NULL,
    priority INTEGER NOT NULL CHECK(typeof(priority) = 'integer')
);
CREATE TABLE edge(
    src TEXT NOT NULL REFERENCES node(id),
    dst TEXT NOT NULL REFERENCES node(id),
    PRIMARY KEY(src, dst)
);
CREATE INDEX edge_by_dst ON edge(dst, src);
"""

def store(con, nodes, edges):
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?, ?)", nodes)
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(con.execute(
            "SELECT id, priority FROM node ORDER BY id"))
        edges = tuple(con.execute(
            "SELECT src, dst FROM edge ORDER BY src, dst"))
        con.execute("COMMIT")
    except BaseException:
        con.execute("ROLLBACK")
        raise
    return nodes, edges

def kahn(nodes, edges):
    priority = dict(nodes)
    incoming = {u: 0 for u in priority}
    outgoing = {u: [] for u in priority}
    for u, v in edges:
        outgoing[u].append(v)
        incoming[v] += 1
    ready = [(priority[u], u) for u in priority if incoming[u] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        _, u = heapq.heappop(ready)
        order.append(u)
        for v in outgoing[u]:
            incoming[v] -= 1
            if incoming[v] == 0:
                heapq.heappush(ready, (priority[v], v))
    residual = sorted(u for u in priority if incoming[u] > 0)
    return order, residual

def cycle_witness(nodes, edges, allowed):
    allowed = set(allowed)
    outgoing = {u: [] for u, _ in nodes if u in allowed}
    for u, v in sorted(edges):
        if u in allowed and v in allowed:
            outgoing[u].append(v)
    color = {u: 0 for u in outgoing}
    for root in sorted(outgoing):
        if color[root] != 0:
            continue
        path, position = [root], {root: 0}
        color[root] = 1
        stack = [(root, iter(outgoing[root]))]
        while stack:
            u, children = stack[-1]
            try:
                v = next(children)
            except StopIteration:
                stack.pop()
                path.pop()
                position.pop(u)
                color[u] = 2
                continue
            if color[v] == 1:
                return path[position[v]:] + [v]
            if color[v] == 0:
                color[v] = 1
                position[v] = len(path)
                path.append(v)
                stack.append((v, iter(outgoing[v])))
    return []

def valid_order(nodes, edges, order):
    ids = {u for u, _ in nodes}
    if len(order) != len(ids) or set(order) != ids:
        return False
    position = {u: i for i, u in enumerate(order)}
    return all(u in ids and v in ids and position[u] < position[v]
               for u, v in edges)

def valid_cycle(nodes, edges, cycle):
    ids = {u for u, _ in nodes}
    if len(cycle) < 2 or cycle[0] != cycle[-1]:
        return False
    body = cycle[:-1]
    if len(set(body)) != len(body) or not set(body) <= ids:
        return False
    edge_set = set(edges)
    return all((u, v) in edge_set for u, v in zip(cycle, cycle[1:]))

rng = random.Random(20261019)
ids = ("a", "b", "c")
possible = list(itertools.product(ids, repeat=2))
dag_count = 0
for mask in range(1 << len(possible)):
    rows = [(u, 0) for u in ids]
    links = [edge for bit, edge in enumerate(possible) if mask & (1 << bit)]
    rng.shuffle(rows)
    rng.shuffle(links)
    with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
        store(con, rows, links)
        nodes, edges = snapshot(con)
    candidates = [list(p) for p in itertools.permutations(ids)
                  if all(p.index(u) < p.index(v) for u, v in edges)]
    order, residual = kahn(nodes, edges)
    if candidates:
        dag_count += 1
        assert not residual
        assert order == min(candidates)
        assert valid_order(nodes, edges, order)
    else:
        assert residual
        witness = cycle_witness(nodes, edges, residual)
        assert valid_cycle(nodes, edges, witness)
for rows, expected in [([], []), ([("z", 0), ("a", 0)], ["a", "z"])]:
    with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
        store(con, rows, [])
        nodes, edges = snapshot(con)
    order, residual = kahn(nodes, edges)
    assert order == expected and not residual
    assert valid_order(nodes, edges, order)
print("穷举图", 1 << len(possible))
print("无环图", dag_count)
print("空图与孤立节点通过")

运行结果:

穷举图 512
无环图 25
空图与孤立节点通过

测试通过说明当前实现覆盖了全部三节点输入,并不构成对任意规模代码的形式化证明。复杂度也要拆开看:数据已加载后,Kahn 主过程的时间为 O(E + V log V),空间为 O(V + E)。这里为了可重复诊断而排序边,提取环的实现另有 O(E log E + V log V) 的准备成本,搜索本身为线性;数据库 ORDER BY 的成本则取决于实际索引和查询计划。不要把 Python 主循环复杂度当作整条数据管线的性能保证。

交付前的检查清单

先确认边的方向、节点全集与优先级含义,再确认每条边只存一次且两个端点存在。读节点和边时要共享一个快照,输出全序时要固定每一步的平局规则;如果改为分层,就明确新解锁节点只能进入下一轮。成功证书必须覆盖所有节点,失败证书必须能在原图中逐边闭合,而残留列表只描述阻塞范围。

最后,让校验器和生成器保持不同的实现思路,并把证书绑定到规范输入。Python 标准库 graphlib 官方文档也给出了拓扑排序、就绪节点和环异常的接口语义,可作为对照阅读;本文显式实现算法,是为了把确定性策略、真实环证据与独立验证过程暴露出来。验证完成之后,调用方仍需决定如何处理多个合法顺序、过期输入以及受环影响的业务操作。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。