跳到正文
Microsoft Research·· 2026-11-06精选

微软详解PDD Kit:先明确需求,再用形式证明约束Agent代码

AI 导读

微软研究团队展示PDD Kit工作流:先澄清需求并生成可审阅规范,再由Agent编写代码与证明,使用Verus检查,证明之外的依赖则通过测试验证。案例来自约5000行Rust全栈应用,但本文实际验证的是登录逻辑。目前工具仍为研究原型,仅验证Rust,保证受规范及数据库、密码校验等可信假设约束。

推荐理由

提供需求澄清、规范审阅、变异检查和持续验证的具体做法,值得Agent编码团队参考。微软原文与发布时间已核对;案例范围有限,尚未独立复现。

正文 · AI 翻译
PDDKit decision flowchart on green gradient background

概览

  • 面向日常软件的形式化方法。PDD Kit 帮助你将意图转化为形式化规约,然后证明智能体编写的代码对每一种输入都符合规约,并在证明无法覆盖的地方使用测试。它让形式化方法走出小众的专业领域,走向没有形式化方法背景的工程师,以及日常应用,例如这里展示的全栈 Web 应用。
  • 随着 AI 智能体生成的代码量越来越大,详尽的逐行人工审查可能变得难以规模化。计划本应是你与编程智能体之间的契约,但实际上没有任何机制强制智能体遵守它。智能体编写的测试通常检查的是它构建出来的东西,而非你要求的东西。 
  • PDD Kit 让智能体遵守计划。它与你协作,将你的意图转化为用 Verus(在新标签页中打开) 编写的形式化规约,证明智能体的代码对每一种输入都满足该规约,并在证明无法覆盖的地方转用测试。
  • 我们在一个全栈 Web 应用上进行了尝试。在 GitHub Next 的 Chopin(在新标签页中打开) 中,我们使用 PDD Kit 对 Rust 商城应用 Pet Store 的登录逻辑进行了形式化验证,该应用使用 Rust(在新标签页中打开) 编写。Verus 增强了代码的健壮性,并发现了已有的缺陷,证明登录逻辑不存在违反该规约的缺陷。开发者审查了意图,全程没有逐行阅读生成的代码。 

计划是智能体应该遵守的契约,但没有任何机制约束智能体遵守它。

如今,编程智能体常常一次就交付完整功能,涉及数万行乃至数十万行代码。因此,逐行阅读拉取请求中的代码,已无法适应这种新的工作方式。现在,大多数团队转而把精力投入计划和相关测试:向智能体描述需求,反复沟通,直到计划和拟议测试看起来合适,再将它们交给智能体实现。 

这份计划或自然语言规约,本应是智能体必须遵守的契约。然而在实践中,智能体可能偏离它。它实现了略有不同的东西,然后编写能让自己的实现通过的测试,而非检查你原本希望它编写的代码。持续集成(CI)因大量低质量测试而膨胀,覆盖率看起来很健康,而需求与实际交付之间的差距一直隐藏着,直到出现缺陷报告或棘手的边界情况。

那么,当智能体生成的代码量越来越大时,如何可靠地扩展审查能力?智能体代码有两种失败方式,细心的审查者通常都能发现:遗漏明显必要的内容,或做出明显错误的行为。单靠测试无法弥合这一差距,因为测试只会触及程序所有可能行为中的极小一部分。要弥合差距,需要另一类机制,这正是证明发挥作用的地方。

学术会议

ICLR event page header - abstract shapes on a purple gradient background

微软亮相 SOSP 2026

来自学术界和产业界的参与者将介绍研究论文和经验论文,涵盖计算机系统软件理论与实践的各个方面。

审查问的是“这看起来对吗?”证明回答的是“这对吗?”数学证明表明,代码对每一种输入都满足其规约,包括测试套件可能遗漏的输入。与单靠测试相比,这能为规约中指定的性质提供更强的保证,尤其是在逐行审查不切实际的情况下。

过去,证明对于日常软件来说成本过高。你需要专家、不熟悉的语言、体量数倍于代码的证明,而且编写证明需要数年时间。但此后有两件事发生了变化。首先,编程智能体近来的进步,让它们根据定义清晰的规约协助生成形式化证明变得越来越可行。其次,智能体如今能更好地帮助你编写形式化规约。我们将这种新的软件开发范式称为证明驱动开发(Proof-Driven Development,PDD)。PDD Kit 就是我们为此打造的工具包。

PDD Kit 的工作原理

PDD Kit 之于形式化方法,大致相当于 Spec Kit(在新标签页中打开) 之于规约驱动开发。它作为协作伙伴运行在 Chopin(在新标签页中打开) 内。Chopin 是 GitHub Next 的实时多人规划环境,团队和智能体可以在同一份共享文档中制定计划。

工作流分为两部分(图 1)。首先,团队成员用通俗语言审查意图。PDD Kit 会提出细心的审查者会问的问题,在过程中解释相关代码,并将答案记录在一份意图文档中,用它连接用户意图与形式化规约或测试。用户意图中可以形式化的部分会被转化为形式化规约,其余必须依赖信任的部分则转化为用于测试的非形式化规约。PDD Kit 会自动生成证明,证明代码满足推导出的形式化规约,并为非形式化规约生成高质量测试。完成这一切都不需要你具备形式化方法背景。 

Flow diagram showing the PDD Kit workflow for formally verifying agent-written code. Team members review intent by expressing requirements in plain language, which are formalized in a pdd-plan containing decision cards, intent artifacts, trusted boundaries, and reviewer approvals. The plan generates a formal specification with Verus ensures clauses. Machines then check the code through pdd-prove, which includes Verus proofs, tests for trusted components, and LLM gap review. Verified code and receipts are submitted as a pull request. Dashed feedback loops return specification contradictions and verification gaps to earlier planning and coding stages.
图 1. 使用 PDD Kit 进行证明驱动开发。团队成员确定意图。Verus 和测试套件确保代码遵守这些意图。

因此,PDD Kit 中的每项结果都会说明它依赖哪种验证: 

  • 形式化验证通过数学证明表明,代码对每一种可能的输入都满足其规约,并由一种称为验证器的工具检查。目前,PDD Kit 使用的验证器是 Verus(在新标签页中打开)。这是一种面向 Rust 的证明语言,由微软研究院、卡内基梅隆大学、VMware Research、苏黎世联邦理工学院、马克斯·普朗克软件系统研究所(MPI-SWS)、悉尼新南威尔士大学、得克萨斯大学奥斯汀分校、密歇根大学、不列颠哥伦比亚大学、威斯康星大学麦迪逊分校和魏茨曼科学研究所共同开发。
  • 实证验证通过运行代码并观察其行为来检查代码。它覆盖证明无法触及的部分,例如第三方密码学库或用户界面。它使用单元测试、端到端测试、终端自动化、浏览器智能体,以及用于操作浏览器无法驱动的部分的计算机操作智能体。测试通过只能说明代码在已尝试的输入上正常工作,因此 PDD Kit 将其标记为证据,而非证明。

两者之间的分界是可信计算基(Trusted Computing Base,TCB),即证明假定会按照描述运行的代码。PDD Kit 会明确这条边界,并请你逐项确认。 

综合示例:一个全栈 Web 应用

为了展示 PDD Kit 如何集成到现有代码库中,我们构建了 Pet Store,这是一个完全用 Rust(在新标签页中打开) 编写的全栈 Web 应用。后端使用 Axum(在新标签页中打开) 和 SQLite(在新标签页中打开),处理库存、促销、订单和结账。商城前端是一个编译为 WebAssembly(在新标签页中打开) 的 Leptos(在新标签页中打开) 应用。两者合计约 5,000 行 Rust 代码。

为使这篇博客简洁,我们重点介绍如何对应用的登录逻辑进行形式化验证,但同样的流程也可用于验证整个应用的功能正确性。PDD Kit 建议从应用中最敏感的部分开始,逐步验证整个应用。登录缺陷可能让攻击者获得客户账户或管理员控制权,因此在这里投入证明工作最先能带来回报。开发者在 Chopin 中的完整请求只有两句话: 

Verify the login logic in backend/src/handlers/auth.rs. Here are my requirements:

  1. You only get a token with the right password.
  2. Only admin accounts get admin tokens.

我们刻意让请求保持粗略。捕捉用户意图,并将用户请求转化为证明能够检查的内容,是 PDD Kit 的工作。

第 1 步:先提问,再写代码

PDD Kit 的规划工作流 pdd-plan 会阅读代码,在编写任何内容之前,先在 Decisions(决策)选项卡中提出问题。如果某个问题取决于代码的工作方式,卡片会先解释那部分内容:目标、各部分如何配合,以及涉及的具体函数,让你无需打开源码就能回答。 

Screenshot of a verification tool evaluating a login authentication requirement. The prompt asks, “Must the right password always get a token?” A flow diagram shows a login request leading to a password check, where matching passwords receive a token and non-matching passwords are refused. Option A, highlighted as recommended, proves both outcomes: the correct password receives a token and an incorrect password is refused. Option B proves only that incorrect passwords are refused, leaving the result for the correct password unspecified.
图 2. 第一张决策卡片。一个拒绝所有人的登录系统,也满足单独的“只有密码正确才行”。证明两个方向都成立,就能排除这种情况。

这个问题看起来有些咬文嚼字,但它很重要。“只有密码正确才能获得令牌”排除了错误密码获得令牌的坏情况,而拒绝所有人的登录系统也完全遵守这一承诺。“正确密码始终有效”是排除这种情况的另一半。从形式上说,前者是一个蕴含关系(令牌 ⇒ 正确密码),后者是它的逆命题。两者合起来构成“当且仅当”。如果让智能体自行处理,它会在不告知你的情况下选一个,但这里开发者选择了两个方向。

第 2 步:人能读懂的意图图谱

随着对话推进,PDD Kit 会持续更新计划顶部的工作草稿部分,让用户无需翻阅冗长的聊天记录寻找已达成的共识,就能跟上重要概念。它包括正在定义的登录流程图、展示哪些内容将被证明以及哪些内容将被信任的规约全景,以及在图示有帮助时提供的心智模型。对于登录,PDD Kit 画了一个售票处(图 3)。

Three-panel illustration comparing login outcomes. In the first panel, a customer logs in with the correct email and password and receives a “customer” ticket. In the second panel, the same email is paired with an incorrect password and access is refused. In the third panel, an administrator logs in with the correct username and password and receives an “admin” ticket. The diagram uses a ticket-counter analogy to explain authentication and role-based access.
图 3. PDD Kit 对登录的心智模型。你发送的字段决定窗口,窗口决定数据表及其对应角色,只有密码匹配后才会打印票据。

在其下方,意图图谱将每项需求对应到开发者的原话,并记录该需求是如何确定的(图 4)。每个条目都链接到为其建模的形式化规约章节,以及覆盖它的测试。规约章节展示 Verus 契约片段,并附带注释,让开发者看清形式化规约如何对自己的意图建模。

Intent map showing the login authentication flow for issuing a token. If an account exists and bcrypt verifies the correct password, the user receives claims for that account. If the account does not exist or the password is incorrect, the result is “401 Unauthorized.” If the password hash cannot be read, the result is “500 unreadable hash.”
图 4. 决策完成后的一条意图图谱记录:登录只有在该账户的密码正确时才能获得令牌,且密码正确时始终能获得令牌。流程图展示了密码检查可能结束的每一种方式。

图 2 中的决策卡片展示了一类原本会被智能体默默决定的歧义。图 5 说明这种差异在纸面上看起来有多小:两种解读只在一个单元格上不同,即密码正确却没有获得令牌。

Side-by-side comparison of two authentication policies. The left panel, “Only when,” shows that a token implies the correct password but does not guarantee a token for a correct password. The right panel, “Exactly when,” shows a two-way relationship in which a token is issued if and only if the correct password is provided. The highlighted difference is that denying a token to a user with the correct password is allowed under the first policy but forbidden under the second.
图 5. 同一句话的两种解读。它们只在一个单元格上不同,而这个单元格改变了证明必须确立的内容。

第 3 步:证明登录函数

在构建任何内容之前,PDD Kit 会请团队对整个计划进行确认。第一版计划证明了登录核心的决策逻辑,即选择数据表并根据密码决定是否放行,而外围处理函数则仍作为可信部分,通过测试检查。这是合理的默认做法,也是 PDD Kit 的建议,但开发者希望覆盖更多内容。等待查询结果和签发令牌都发生在处理函数中,而这种衔接代码恰恰可能在重构时被悄悄调换两行。因此,在意图审查阶段,开发者选择为登录处理函数提供独立的异步规约,让证明也覆盖这些衔接逻辑,而无需信任它们(图 6)。

Comparison of two approaches to verifying a login handler. Option A, recommended, keeps the login handler trusted and verifies only the login decision logic, while database lookups and token signing remain tested but trusted components. Option B gives the login handler its own formal specification, proving the orchestration logic but requiring additional trusted wrappers and assumed contracts around database lookups, clocks, and JWT signing.
图 6. 证明更多登录逻辑,意味着需要信任更多小型封装函数。卡片会在开发者做出选择前说明这一点。 

这一选择将几乎所有内容都纳入了证明,登录处理函数只需解包请求。一个新的异步函数 login_flow 承载了从请求字段一直到令牌或 HTTP 错误的契约。随后,PDD Kit 将修订后的计划再次交回确认,因为符合你的意图并不等于证明,也不代表你批准了新的信任假设或更大的范围。 

第 4 步:证明止于何处

程序中有很多事情无法证明,而登录几乎会遇到其中的大多数:

  • 验证器看不到的代码。bcrypt 的哈希运算、sqlx 的查询和 jsonwebtoken 的签名位于其他 crate 中,不在证明范围内。 
  • 关于外部世界的事实。SQLite 当前存储的内容和时钟显示的时间是程序的输入,并非其代码本身能够确立的事实。 
  • 某件事是否完成,以及多快完成。规约描述的是登录作出响应时会得到什么。查询挂起或运行缓慢都不会违反其中任何内容。 
  • 任何需要人来判断的事情,例如错误信息是否有帮助,或某个界面是否合理。 
  • 任何没有人写下来的要求。证明覆盖的是它的规约,对规约之外的需求不作任何说明。 

这时就需要实证验证。PDD Kit 会明确写出可信边界,即该证明所依赖的 TCB 部分。它使用 Verus 的 #[verifier::external_body] 或 external_fn_specification,将每个可信部分封装在一个带有假定契约的小函数中,请开发者逐项接受,并在计划中为每个假定条款编写测试。对于登录,开发者确认了六个部分:

  • 两个查询函数,Customer::find_by_email 和 Admin::find_by_username。对每个查询执行 await 后,如果查询成功,返回的结果恰好是各自数据表中与该电子邮箱或用户名对应的行;若没有对应行,则不返回任何行。 
  • check_password,对 bcrypt::verify 的一层轻量封装。它仅在存储的哈希值无法被 bcrypt 读取时返回错误,而 Ok(true) 恰好表示密码正确。 
  • generate_token,使用配置的密钥,仅对传入的声明进行签名,并在签名失败时返回 500。 
  • expiry_from_now,读取时钟,并将过期时间设为恰好 24 小时之后。 
  • database_error,将查询失败转换为当前的 500 响应,并附带 sqlx 的消息。 
  • 登录处理函数的外壳,负责解包请求,并将其字段原样传给 login_flow。 

在规约中,查询函数的代码保留在原处,通过 external_fn_specification 从外部为其附加契约: 

/// Looks up a customer by exact email. 
/// Trusted, not proved: the SQL query runs in sqlx, which Verus cannot check. 
/// Every customer promise of `login_flow` rests on it. 
#[verifier::external_fn_specification] 
pub async fn ex_customer_find_by_email(pool: &sqlx::SqlitePool, email: &str) 
    -> (r: Result, sqlx::Error>) 
    ensures 
        // When the query succeeds, it returns the customers row on 
        // file for exactly this email, or None when there is none. 
        r matches Ok(found) ==> found == customer_on_file(email@), 
{ 
    Customer::find_by_email(pool, email).await 
} 

时钟是一个标记为 #[verifier::external_body] 的小型封装函数。Verus 使用它的 ensures 子句,绝不读取函数体: 

/// Reads the clock and computes a token's expiry 24 hours ahead. 
/// Trusted, not proved: chrono's clock is outside the proof. 
/// It panics if the time is out of range, as today's login does; 
/// that panic is not promised against. 
#[verifier::external_body] 
pub fn expiry_from_now() -> (r: Expiry) 
    ensures 
        // The expiry is exactly 24 hours (86,400 seconds) after the clock reading. 
        r.exp as int == r.now as int + 86_400, 
{ 
    ... 
} 

图 7 将三个层次放在一起:Verus 证明的内容、由人接受并由测试检查的内容,以及没有人承诺的内容。 

Diagram showing the proof boundary for a formally verified login system. Functionality outside the proof is either not promised or trusted and validated through human review and testing, including SQLite lookups, bcrypt, the system clock, JWT signing, database error handling, and request parsing. At the center, the formally verified portion consists of the login_flow and its components login_core, lookup_target, decide_login, and issue_token, which are proven by Verus for every input.
图 7. 登录证明止于何处。Verus 证明核心逻辑对每一种输入都成立。人接受外围的可信部分,测试则对其进行检查。计划列出了没有人承诺的内容。 

图 8 展示哪些内容被证明、哪些内容被信任。每项信任决策都有独立的卡片。卡片展示 Verus 将直接采信的条款、开发者接受的内容,以及假设错误时哪项承诺会失效(图 9)。随后,每个假定条款都会在计划的“实证验证”部分获得一项实证检查,在任何测试编写之前,就以 Given/When/Then 场景的形式写下(图 10)。条目在运行之前一直标记为已计划,运行后则记录命令结果及运行时对应的提交。

Proof map showing how a verified login system is divided between formally proved code and trusted, tested components. Five core functions, including login_flow, login_core, lookup_target, decide_login, and issue_token, are formally verified with Verus. Supporting functions for database queries, password verification, token signing, clock access, and error handling are treated as trusted contracts that are reviewed and tested.
图 8. 登录中哪些内容被证明、哪些内容被信任。绿色函数由 Verus 证明对每一种输入都成立。琥珀色部分被视为可信,由开发者接受,并由计划 §4.1 中拟定的测试进行检查。
Proof map showing how a verified login system is divided between formally proved code and trusted, tested components. Five core functions, including login_flow, login_core, lookup_target, decide_login, and issue_token, are formally verified with Verus. Supporting functions for database queries, password verification, token signing, clock access, and error handling are treated as trusted contracts that are reviewed and tested.
图 9. check_password 的信任卡片。Verus 直接采信这两个条款,因此由人接受它们,并用两个测试检查它们。 
Screenshot of a test plan for verifying password validation behavior. The section, “check_password_answers_with_bcrypts_verdict,” describes unit tests confirming that password checks return true for the correct password and false for incorrect or empty passwords. Example test cases use bcrypt hashes for customer and administrator accounts.
图 10. 针对可信部分 check_password 拟定的测试,在测试编写之前就已写下。计划将通过的测试标记为证据,而非证明。 

计划也同样明确地列出了没有人承诺的内容:登录 future 最终一定完成、超出范围的时钟值不会触发 panic、尝试的时机或频率方面的任何性质,以及其他端点如何读取角色。 

第 5 步:阅读规约

意图文档是团队审查的对象。它是 PDD Kit 以 Verus 契约编写的形式化规约的通俗语言版本。你可能会想,现在是否需要有人转而阅读证明,而非代码。无需任何人这样做,因为编程智能体负责编写证明,Verus 负责检查证明的每一步。如果 Verus 接受证明,那么无论是否有人阅读,它都成立。证明必须符合规约,因此人们审查的是规约,而这份规约足够简短,几分钟就能学会阅读。每个函数都有一个 ensures 块:其中关于结果 r 的陈述,必须对每一种可能的输入都成立。Verus 在构建时检查它们,只要有任一条款可能对哪怕一个输入不成立,构建就会失败,Verus 会指出该条款。每个条款都可以读作一个“如果……那么……”陈述,图 11 拆解了对应开发者第一项需求的条款。

Annotated code snippet explaining a formal verification clause for login tokens. The clause states that if a login returns a token, then the request names a valid account, the password matches the stored hash, the token contains valid claims, and the token’s subject and role match the authenticated account. Numbered callouts explain each part of the expression.
图 11. login_flow 中对应“只有密码正确才能获得令牌”的 ensures 子句。每一行都出现同一个账户 a,从而将密码检查与令牌关联起来。

请注意,每一行都出现了同一个 a,这将密码检查与令牌关联起来。例如,设想这样一个缺陷:登录时针对一个账户检查密码,却为另一个账户签发令牌。Bob 用自己正确的密码登录,拿到的却是 Alice 账户的令牌。每一步单独看都没问题,但这个条款能发现它,因为密码检查和令牌必须指向同一个账户。这类衔接错误很少会被测试套件考虑到。规约还必须在不运行 SQLite、bcrypt 和 JWT 的情况下描述它们。它通过未解释函数来做到这一点,也就是没有函数体的名称:customer_on_file(email) 和 admin_on_file(username) 表示数据库存储的行,bcrypt_verdict(password, hash) 表示 bcrypt 会给出的结果,token_claims(token, secret) 表示令牌携带的内容。除了第 4 步中的可信契约所承诺的内容,Verus 对它们一无所知。证明说的是“无论数据库存储什么,登录都会正确处理它”,而可信契约说的是“查询返回数据库存储的内容”。 

/// The customers row the database holds for 
/// exactly this email, if any, when login looks. 
/// Left abstract: only `Customer::find_by_email`'s 
/// trusted contract says what it is. 
pub uninterp spec fn customer_on_file(email: Seq) -> Option; 
... 
/// What bcrypt says about `password` against a 
/// stored `hash`: Some(true) when it is the password 
/// the hash was made from, Some(false) when it is 
/// not, None when bcrypt cannot read the hash. 
/// Left abstract: its meaning is bcrypt's, taken on trust through `check_password`. 
pub uninterp spec fn bcrypt_verdict(password: Seq, hash: Seq) 
    -> Option; 

 /// The password is the right one for the stored hash, by bcrypt's verdict. 
pub open spec fn password_matches(password: Seq

, hash: Seq) -> bool { 
    bcrypt_verdict(password, hash) == Some(true) 
} 

在这些函数之上,named_account(email, username) 指明一次登录对应哪个账户:如果发送了电子邮箱,就对应 customers 表中该邮箱的行;否则,对应 admins 表中该用户名的行;再否则,不对应任何账户。它写起来像 Rust,但它是一个永不运行、只出现在契约中的数学定义。这类代码称为幽灵代码,因为验证器会检查它,但编译器会将它从程序中擦除。借助它,开发者两句话的请求最终变成了 login_flow 上的八个 ensures 子句(图 12)。 

/// The account a login names: the customers row for 
/// the email when one is sent (role "customer"), 
/// otherwise the admins row for the username (role "admin"), otherwise none. 
pub open spec fn named_account(email: Option, username: Option) 
    -> Option { 
    match email { 
        Some(e) => match customer_on_file(e@) { 
            Some(c) => Some(NamedAccount { 
                id: c.id@, password_hash: c.password_hash@, role: customer_role() }), 
            None => None, 
        }, 
        None => match username { 
            Some(u) => match admin_on_file(u@) { 
                Some(a) => Some(NamedAccount { 
                    id: a.id@, password_hash: a.password_hash@, role: admin_role() }), 
                None => None, 
            }, 
            None => None, 
        }, 
    } 
} 

Traceability diagram showing how formal verification promises are derived from requirements. Statements made by developers and decisions recorded in design cards are mapped to eight specific guarantees in the login_flow specification, covering token issuance, account roles, invalid credentials, missing accounts, malformed requests, and error handling.
图 12. 两句话的请求和“两个方向都成立”的决策,最终变成了 login_flow 上的八个 ensures 子句。其中四个保留了当前的拒绝行为,使商城前端和现有 API 测试继续正常工作。 

下面是完整契约,其文档注释经过删减。每个条款上方都有一条通俗英语注释,与意图文档向团队展示的内容一致: 

/// The whole login, awaited end to end: from the 
/// request's fields to the token or the HTTP error. 
/// ... 
pub async fn login_flow(pool: &sqlx::SqlitePool, config: &Config, 
    email: Option, username: Option, password: &str) 
    -> (r: Result) 
    ensures 
        // Neither an email nor a username: 400 with today's message. 
        email is None && username is None 
            ==> (r matches Err(AppError::BadRequest(m)) 
                && m@ == missing_identity_text()), 
        // A token only for the account the login names, with its right 
        // password; it carries that account's id and its table's role. 
        r matches Ok(t) ==> (named_account(email, username) matches Some(a) 
            && password_matches(password@, a.password_hash) 
            && token_claims(t@, config.jwt_secret@) matches Some(c) 
            && c.sub@ == a.id && c.role@ == a.role), 
        // The right password for the named account always gets a 
        // token, unless a lookup or signing failure gives 500. 
        (named_account(email, username) matches Some(a) 
            && password_matches(password@, a.password_hash)) 
            ==> (r is Ok || r matches Err(AppError::Internal(_))), 
        // A login naming an account nobody holds gets 
        // 401, unless the lookup fails with 500. 
        ((email is Some || username is Some) && named_account(email, username) is None) 
            ==> (r matches Err(AppError::Unauthorized) 
                || r matches Err(AppError::Internal(_))), 
        // A wrong password for an account whose hash bcrypt 
        // can read gets 401, unless the lookup fails with 500. 
        (named_account(email, username) matches Some(a) 
            && bcrypt_verdict(password@, a.password_hash) == Some(false)) 
            ==> (r matches Err(AppError::Unauthorized) 
                || r matches Err(AppError::Internal(_))), 
        // An account whose stored hash bcrypt cannot read gets 500 and no token. 
        (named_account(email, username) matches Some(a) 
            && bcrypt_verdict(password@, a.password_hash) is None) 
            ==> r matches Err(AppError::Internal(_)), 
        // The admin role only for an admins row 
        // found by username, with no email sent. 
        (r matches Ok(t) && token_claims(t@, config.jwt_secret@) matches Some(c) 
            && c.role@ == admin_role()) 
            ==> (email is None && username matches Some(u) 
                && admin_on_file(u@) is Some), 
        // An email login's token always carries the customer role. 
        (r matches Ok(t) && email is Some) 
            ==> (token_claims(t@, config.jwt_secret@) matches Some(c) 
                && c.role@ == customer_role()), 
{ 
    unimplemented!() 
} 

可信边界也体现在代码中。check_password 是 Verus 不检查函数体的函数之一。其契约将它与 bcrypt_verdict 关联,后者是一个不带任何公理的 bcrypt 未解释模型:

/// Asks bcrypt whether `password` matches the stored `hash`. 
/// Trusted, not proved: Verus cannot check bcrypt's hashing, 
/// so this wrapper's contract is assumed. 
/// Every password promise of `login_flow` rests on it. 
#[verifier::external_body] 
pub fn check_password(password: &str, hash: &str) -> (r: Result) 
    ensures 
        // bcrypt answers (Ok) exactly when it can read the stored hash. 
        r is Ok <==> bcrypt_verdict(password@, hash@) is Some, 
        // Its answer is its verdict: true for the 
        // right password, false for any other. 
        r matches Ok(b) ==> bcrypt_verdict(password@, hash@) == Some(b), 
{ 
    bcrypt::verify(password, hash).map_err(|e| e.to_string()) 
} 

它上方的文档注释说明了哪些承诺依赖它:login_flow 的每一项密码承诺。 每次登录都会在少数几种结果之一结束,其中只有一种带有令牌(图 13)。证明同时覆盖所有这些结果。 

Flowchart showing the end-to-end login process. A login request selects an account table based on an email or username, looks up the account, verifies the password, and issues a signed token when authentication succeeds. Error paths return appropriate HTTP responses: 400 for missing credentials, 401 for invalid credentials or missing accounts, and 500 for lookup or password-hash failures.
图 13. 计划中列出的登录可能结束的每一种方式。 

login_flow 是异步函数:它会等待数据库查询。Verus 可以为异步函数附加契约,其中有一条值得了解的规则(图 14)。requires 在调用创建 future 时检查。ensures 描述对其执行 await 后得到的值。没有任何承诺保证 future 会完成,因此查询挂起不会违反任何条款。 

login_flow 的文档注释明确说明了这一点: 

/// ... No promise the future completes. 
pub async fn login_flow(...) -> (r: Result) 

Diagram comparing how formal verification applies to synchronous and asynchronous functions. For both types, preconditions are checked when the function is called and postconditions are guaranteed when a result is returned. In an asynchronous login flow, the function may pause while awaiting a database lookup, and the specification makes no guarantee about whether or how quickly the operation completes.
图 14. sync fn 和 async fn 的契约何时接受检查。 

login_flow 保持简短,因为它由更小的、已经证明的部分构成。lookup_target 选择数据表。login_core 等待查询结果,并调用密码关卡 decide_login。issue_token 签发令牌,或将拒绝结果映射为当前的 HTTP 错误。每个部分都有自己的契约,Verus 只使用这些契约来证明 login_flow,无需重新读取它们的函数体。修改 decide_login 的函数体后,只有 decide_login 需要重新证明。 

下面是最小部分的完整代码,以及密码关卡的开头和结尾: 

pub fn lookup_target(email: Option, username: Option) 
    -> (r: Result) 
    ensures 
        // An email, when sent, wins: customers are searched for exactly that email. 
        email matches Some(e) 
            ==> r == Ok::(LookupTarget::CustomerByEmail(e)), 
        // With no email, a username sends the search 
        // to admins for exactly that username. 
        email is None && username matches Some(u) 
            ==> r == Ok::(LookupTarget::AdminByUsername(u)), 
        // With neither, the login is refused for missing an identity. 
        email is None && username is None 
            ==> r == Err::(LoginError::MissingIdentity), 

pub fn decide_login(target: &LookupTarget, found: Option, password: &str) 
    -> (r: Result) 
    ensures 
        // No row found: refused as Unauthorized, 
        // the same answer as a wrong password. 
        found is None 
            ==> r == Err::(LoginError::Unauthorized), 
        // Claims come back only for a found row 
        // whose stored hash matches the password. 
        r is Ok ==> found is Some 
            && password_matches(password@, found->Some_0.password_hash@), 
        // The right password for a found row always gets claims. 
        found matches Some(a) && password_matches(password@, a.password_hash@) 
            ==> r is Ok, 
        ... 
        // An admins-table search gives the role text "admin". 
        r matches Ok(c) && target is AdminByUsername ==> c.role@ == admin_role(), 
        // A customers-table search gives the role text "customer". 
        r matches Ok(c) && target is CustomerByEmail ==> c.role@ == customer_role(), 

login.rs 概览 

图 15 展示了整个规约文件 verified/src/login.rs。它从上到下分为四层:Verus 需要了解的头部、导入和类型,对外部世界的抽象视图,将该视图连接到真实代码的可信契约,以及证明必须满足的五个契约。  

Annotated map of the verified/src/login.rs file showing the structure of a formally verified login implementation. The diagram categorizes sections as specification-only definitions, trusted external contracts, data types, and five functions formally proved with Verus: login_flow, login_core, issue_token, lookup_target, and decide_login.
图 15. login.rs 的各部分,按文件顺序排列。灰色是头部和类型,紫色是只出现在契约中的数学内容,琥珀色是可信部分,绿色是已证明部分。

下面节选了其中两个不那么直观的部分。external_type_specification 引入了一个并非由 Verus 定义的类型。连接池保持不透明,而 customers 表中行的字段则保持可见: 

/// The connection pool, opaque to the proof: only 
/// the lookups' contracts say what it returns. 
#[verifier::external_type_specification] 
#[verifier::external_body] 
#[verifier::reject_recursive_types(DB)] 
pub struct ExPool(sqlx::Pool); 
... 
/// A customers row, with its fields visible to the proof. 
#[verifier::external_type_specification] 
pub struct ExCustomer(Customer); 

LoginError 则将决策与 HTTP 响应分开,从而让 issue_token 能将每种拒绝结果固定映射到当前的状态码: 

/// Why a login gets no token. 
pub enum LoginError { 
    /// Neither an email nor a username was sent: 400 Bad Request. 
    MissingIdentity, 
    /// No such account, or the password does not match: 401 Unauthorized. 
    Unauthorized, 
    /// bcrypt could not read the stored hash, with its message: 500 Internal. 
    UnreadableHash(String), 
    /// The lookup query failed: 500 Internal, with sqlx's message. 
    Database(sqlx::Error), 
} 

在计划交回给你之前,两个审查智能体会对从意图文档推导出的形式化规约挑错,以确保转化质量,让规约符合你的要求,并且不会承诺超出证明能力范围的内容。规约完善过程在后台运行,并接收用户的实时反馈,不断迭代,直到审查者一致认为规约是可靠的。 

第 6 步:证明、检查、弥补缺口 

开发者对规约的确认,就是其审查工作的终点。此后的一切,包括实现和证明,都由机器检查,这也是本文着重讨论规约而非证明的原因。开发者确认后,Build plan(构建计划)阶段(图 16)会将批准的计划交给 pdd-prove,由它转化为一个小型任务图(图 16)。对于登录,这包含七项任务:先让 login.rs 在后端 crate 内通过 Verus 构建,再证明决策、令牌和整个流程,最后为可信封装函数和端到端登录编写测试。 

Screenshot of a PDD Kit build plan for a login-token issuance specification. The build workflow contains seven tasks, with the first task focused on making verified/src/login.rs successfully build under Verus while preserving contract meanings. Subsequent tasks cover proving login-related functions, testing trusted wrappers, running end-to-end login tests, and validating token-signing behavior.
图 16. Build plan 将批准的规约转化为开发机器上的七项任务。第一项让 login.rs 在 Verus 下完成构建,同时不改变任何契约的承诺;遇到问题时会停下来询问,而非弱化契约。 

每项任务都运行同样的循环: 

  • 编程智能体编写实现和证明,Verus 依据推导出的形式化规约检查它们。 
  • 可信边界内的所有部分都要接受计划要求的测试。 
  • 一个 LLM 验证器会对照阅读计划、规约和结果,寻找缺口:既没有证明、也没有通过检查的需求。缺口会被交回编程智能体处理,直到全部消除。如果规约本身存在缺口,例如两项需求相互矛盾,则会作为待决策问题交回开发者。 

证明的质量取决于规约,因此 pdd-prove 也会检查规约。当模型编写自己的规约,或经过调优以生成证明时,它往往会采用较弱的不变量:条款可以通过验证,却几乎排除不了任何情况。它们确实证明了某些事情,只是很少是你关心的事情。我们称之为“凭感觉验证”(vibe verification)。这就是为什么确保你的意图与智能体一致如此重要,也是 PDD Kit 的长处所在。 

这个循环严格禁止中途改变标准。如果固定版本的 Verus 无法表达某个异步结构,任务就会停下来询问团队,而非改用非异步辅助函数或弱化契约。 

PDD Kit 如何消除整类缺陷?变异检查是 PDD Kit 防止凭感觉验证的方式。pdd-prove 会在代码的临时副本中,为每个 ensures 子句植入一个缺陷,例如拒绝所有人,或先检查用户名再检查电子邮箱,而 Verus 必须针对所对应的子句拒绝每个变异版本。如果某个变异版本通过,就说明该条款没有形成约束,它会作为缺口被交回处理。 

第 7 步:对照已验证代码审查意图

任务通过后,pdd-prove 会创建拉取请求。这些请求添加一个 verified/ crate,其中包含 login_flow、其各个组成部分、它们的证明,以及可信封装函数和相应测试,并让真实的登录处理函数通过 login_flow 执行,同时保留现有的 HTTP 状态码。经过验证的逻辑集成到生产环境的登录路径中,增强的是这条真实路径,而非它的副本。 

开发者得以合并代码,无需依赖对生成代码进行详尽的逐行审查。审查在整个过程中已经围绕意图文档展开,团队拥有最终决定权。我们将更多审查重心从代码审查转向了意图审查。拉取请求起到回执的作用,其描述将每项登录需求标记为已完成形式化验证或实证检查。 

合并让证明进入团队的常规工作流。PDD Kit 的 pdd-ship 工作流会将 Verus 检查与实证测试一起加入 CI,因此此后任何人或智能体对登录的修改,都必须继续依据同一份规约完成证明;证明失效会像测试失败一样导致构建失败。由于证明覆盖每一种输入,PDD Kit 会删去那些仅仅重复检查已证明内容的测试,例如密码关卡中基于示例的测试,同时保留守护可信边界的测试,让 CI 变得更强,也更精简。 

证明说明了什么,又没有说明什么 

“完全验证”很容易被夸大,因此下面明确列出我们所作的主张。

  • 已证明。login_flow、login_core、lookup_target、decide_login 和 issue_token 的函数体对每一种输入都满足其契约。登录会选择正确的数据表,将请求中的密码与其对应账户存储的哈希值进行比较,签发包含该账户 id 和其数据表所赋予角色的令牌,并对其余所有情况返回当前的 400、401 或 500 响应,且不提供令牌。 
  • 已信任并测试。两个数据库查询、对 bcrypt 的封装 check_password 、时钟、令牌签名、数据库错误消息,以及处理函数对请求的解包都位于证明范围之外,每一项都由开发者接受的假定契约约束。使用真实 bcrypt、真实 SQLite 数据库模式和真实路由器运行的测试覆盖了这些部分。 
  • 作为假设。Verus、Rust 编译器和 Z3(在新标签页中打开) 工具链,以及 Verus 的标准库 vstd(在新标签页中打开)。 

为什么选择 Rust 

目前 PDD Kit 只验证 Rust,因为这是 Verus 支持的语言。如果你的代码库已经使用 Rust,就无需迁移。其他语言的代码可以移植到 Rust,再依据同一份规约进行检查;非 Rust 项目则可以通过绑定调用经过验证的 Rust 代码。 

还有一个不那么明显的好处。当对详尽逐行审查的依赖降低后,可读性就不再是选择语言的主要原因。你可以根据速度和安全性来选择语言,并尽可能优化,因为任何违反规约的改动都会导致证明失败。 

对 PDD Kit 可以有哪些期待

PDD Kit 是一个研究原型,目前只验证 Rust,因为这是 Verus 支持的语言。其他语言的代码可以移植到 Rust,再依据同一份规约进行检查;非 Rust 项目则可以通过绑定调用经过验证的 Rust 代码。证明仍然需要实实在在的投入,主要花在生成证明本身,而清晰的规约能够降低这种投入,这也是 PDD Kit 如此重视首先准确理解意图的原因。我们会从缺陷代价最大的地方入手,例如登录、支付或权限,再逐块验证代码库的其余部分。

Pet Store 的登录只是一个应用中的一部分:一份任何人都能阅读的规约、一份证明代码符合该规约的 Verus 证明,以及覆盖证明中所有依赖信任部分的测试。我们希望坦诚说明最薄弱的环节。这些保证的强度受制于六个可信部分,其中两类承担了大部分责任:check_password 支撑每一项密码承诺,两个查询则支撑关于令牌对应哪个账户的每一项承诺。测试为它们提供支持,但没有任何证明对它们作出保证。我们预计,这条可信边界会随着时间显著收缩,让越来越多的代码可以接受形式化验证,也希望探索这种方法能够扩展到什么程度。

我们真正改变的是人们审查的对象。团队用通俗语言审查代码应当表达的意图,而不再主要依赖对智能体生成的代码逐行审查,再由证明确保代码遵守意图。计划一直以来都应该是契约,而现在智能体确实必须遵守它。

致谢

这项工作由微软研究院 Catalyst Lab、GitHub Next 和软件工程研究(Research in Software Engineering,RiSE)团队合作完成。我们感谢 GitHub Next 的 Maggie Appleton 和 Krzysztof Cieślak 在 Chopin 上的合作,也感谢 Nikhil Swamy、Lef Ioannidis、Janardhan Kulkarni 和 Shuvendu Lahiri 围绕形式化验证和意图形式化提供的反馈与讨论。我们还感谢 F*/Pulse 和 Verus 团队的支持。最后,感谢 GitHub Next 的 Idan Gazit 对此次合作的支持。

常见问题

  • 确实需要,而且确实会。证明表明代码满足规约,并不表明规约就是你的本意。因此,PDD Kit 围绕现有的意图形式化研究构建。pdd-plan 工作流会阅读你的代码,在编写任何内容之前先提问,再将你的回答转化为 Verus 规约和一份由你批准的通俗语言计划,标出歧义而非自行猜测。两个审查智能体检查规约,pdd-prove 工作流则为每个条款植入一个缺陷,以发现那些能够通过验证却排除不了任何情况的条款。规约仍有可能出错,因此 PDD Kit 强调明确需求、识别歧义,并让开发者在验证开始前持续参与规约的审查与批准。 

  • 区别在于,靠什么确保代码遵守计划。

    方法由什么检查代码
    规约驱动开发没有任何机制强制遵守规约
    测试驱动开发针对部分输入样本的测试,往往为了匹配已构建的实现而编写 
    智能体检查自己的工作编写代码的同一个模型
    证明驱动开发Verus 自动验证证明,确认你的代码满足你已批准的规约

    PDD 保留了 SDD 的规划循环,并在证明无法覆盖的地方继续使用测试。测试检查一部分输入,而证明则在明确列出的假设下,确立代码对形式化模型覆盖的所有输入都满足指定性质。 

  • 证明是带有 Verus 结构注解的 Rust 代码,由 Verus 使用 Z3 求解器进行机械检查。只要能构建 Rust,就能运行它:pdd-prove 工作流在证明过程中运行它,pdd-ship 工作流则将它加入构建和 CI,使失效的证明导致构建失败。这项检查是确定性的,没有模型参与。模型负责编写规约、代码和证明,但是否通过只由一次确定性的 Verus 运行来决定。检查耗时取决于代码规模和证明难度:小型模块通常需要数秒,较大的代码库则可能需要数分钟。

  • PDD Kit 将更多审查工作转向确认代码应该做什么,同时利用形式化验证,为实现满足这些需求提供额外保证。开发者审查自然语言计划、形式化规约,以及证明范围之外的可信组件。最终的拉取请求会记录哪些内容经过了形式化验证、哪些内容经过了测试,以及哪些地方可能需要额外审查。在 Pet Store 全栈 Web 应用上,这种方法降低了对生成代码进行详尽逐行审查的依赖。

  • 我们选择 Verus,是因为它允许直接验证 Rust 代码,这与 PDD Kit 将形式化验证融入现有 Rust 开发工作流的重点一致。 其他证明语言,例如 Lean、F*、Rocq,对形式化验证采用了不同的方法,各有取舍。PDD Kit 背后的技术也可能帮助它们投入使用。

来源:Microsoft Research · microsoft.com