觉
AI觉醒星球
Awakening is here
全球热点解读 · 阅读档案
2026-11-25 2 浏览 公开

废除锁中毒机制:Rust 里的一个应当被推翻的默认值

作者(Flask 作者、Rust 社区知名开发者 Armin Ronacher)系统论证 Rust 的 std::sync::Mutex 中毒机制应当被移除或降为例外:现实中几乎无人正确使用它,反而制造死锁、雪崩式 panic 与隐形的重复副作用。标准库自身在 stdio、panic 输出捕获、backtrace、WASI 环境锁等多处早已忽略中毒,Tokio、Wasmtime、crossbeam-channel、tracing-subscriber 等关键生态项目同样如此,rust-analyzer、Mozilla application-services 则干脆改用不中毒的 parking_lot。libs 团队正在讨论在下一个 edition 把非中毒锁设为默认,本文是为这一改动提供的实战证据与立场。

全球热点解读 约 4 分钟读完 公开 原文 2026-11-25 08:00:00

原贴

查看原文
作者:Armin Ronacher 来源站点:lucumr.pocoo.org 原贴时间:

原文

Rust has a curious feature that I don’t think the language would land today, if it was not there for a long time: mutex poisoning. When some Rust code panics while holding a std::sync::Mutex , the mutex is poisoned . That means that any further call to lock() returns a PoisonError . The motivation for this feature is that an object might have some internal invariants that need to be upheld and panicking in the wrong moment might invalidate reasonable at and leave an object behind in a broken state. Personally I absolutely hate this feature as it has bitten me so many times and I cannot once remember it helping me. The libs team is discussing making the non-poisoning locks the default in the next edition but entirely expectedly it has caused quite a few people to jump to the defence of the feature. In this post I want to make my personal case why poisoned locks should either be entirely removed or be made the exception. Primarily this is because I have yet to come across code in the wild that handles a poisoned lock correctly. On the other hand I have come across enough code that mishandles it and as a result behaves worse than a parking_lot lock would which does not support poisoning. Josh Triplett put it quite strongly in a hackernews comment: “In the entire history of the standard library, we have never once seen a single report of anyone attempting to recover from poison.” When a panic happens with a lock held, there are two reasonable reactions: shut the process down, or carry on and ignore the flag. With panic = "abort" you get the former and poisoning never comes up. From all the evidence I have seen, with unwinding, the idiomatic lock().unwrap() picks the worst option of all. That’s because it neither stops the process nor lets it continue as it will turn every further lock into a panic with sometimes disastrous effects. But that is not the only issue with the system today. So here I want to share some of the issues and with some references to real world code of how people got bitten. The Error Holds the Lock One subtle aspect to the poisoning is that the PoisonError needs to hold the guard. That’s because in order to ignore the poison flag, you need to fetch the guard from the error object. Holding on to the error means holding on to the lock! That can cause common code that does error wrapping / error conversions into a deadlock hazard. The innocent looking m.lock()? in a function returning Box<dyn Error> or similar keeps the mutex locked for as long as the error lives ( #159930 ). This can also happen with if let. For instance in cc-switch you can see that they had a test hung because a if let Ok(..) = lock() { .. } else { .. } fallback locked the same mutex again while the unnamed PoisonError from the condition still owned the guard. PC-AI had the same bug in a match arm. Another case can be found in ox-embed-server . Panic To Outage Deviously poisoning does not fail fast and done wrong, it fails forever. The original panic happens once, on one thread, often somewhere unrelated from future failures. Every later lock().unwrap() on that lock now however panics as well, and because so much Rust code survives panics (thread pools, request handlers, tokio tasks, FFI boundaries), the process stays up and becomes useless: In RLS a failed cargo build panicked with ENV_LOCK held which made any subsequent runs impossible . Mozilla’s application-services saw PoisonError rise to rank 5 in crash stats and moved to parking_lot after they concluded they did not benefit of poisoning handling. A Neon safekeeper on staging failed every timeline lookup after a panic with a global lock held, and the original panic could not even be found in the logs. While not live services, test suites show the same general issue. One failing test poisons a shared static and every test after it fails with PoisonError . This problem showed up for cargo , deno , polars and rustc itself. Attempt At Recovery If you recover with into_inner() , the flag stays set and every later access takes the recovery path again. And remember that for the first nine years of Rust after the poisoning feature landed, you could not even clear it as clear_poison arrived only in 1.77. Not clearing the flag means that potentially expensive side effects will happen from that point onwards: goose-in-a-pond rebuilt its decoder state on every transcription after a single panic, librefang logged the same warning on every access, and a pool threw its model away on every return. Nobody Relies on It, Not Even std So who is handling poisonings? I’m really not sure, definitely not the standard library. Every place where the standard library’s own code ignores it. Standard I/O has done so since March 2015 , two months before 1.0, because “any poison must have been the result of user code which the lock isn’t protecting”. A common issue with a lot of poisoning errors that never had anything to do with the mutex that was held. Same with the panic output capture , the backtrace lock and the WASI environment lock . They all do the same and unsurprisingly there is an open PR to move std’s internal mutexes to nonpoison . And I would argue the ecosystem has largely come to the same conclusion. Tokio’s own locks don’t poison. Internally it wraps the std one in an adapter that removes poison . When it landed Carl Lerche remarked “ I rather pretend lock poisoning isn’t a thing .” In one case Eliza Weisman needed into_inner to unlink a waiter during drop, or “we’ll leave the list with a potentially dangling pointer”. I want to point to this in particular because this is a case where poisoning stood in the way of memory safety which is commonly argued as a reason you want poisoning. Wasmtime, crossbeam-channel, tracing-subscriber always ignores lock poisoning. rust-analyzer switched to parking_lot after cancellation poisoned its solver like RLS did before. The parking_lot maintainer described it as an anti-feature that hurts usability and reliability to which I strongly concur. Why Only Mutex? Another aspect here is why this is done on Mutex but not on RefCell . Surely if the case for poisoning is that some code temporarily breaks an invariant, panics, and someone else observes the broken state, then this should apply to more cases. Take the usual example that argues in favor of poisoning and replace Mutex with RefCell , and you have exactly the same problem . Threads are not needed at all and this is not hypothetical either as tokio catches every task panic. Paired with a LocalSet the panic comes back as a JoinError , the next borrow() succeeds and reads a null pointer exactly like the mutex example from the issue. Given how much panic catching goes on in async code, much of which is !Send for performance reasons, I’m not even convinced that panics get caught more often in multi-threaded code yet nobody asks for RefCell to poison. The standard library isn’t consistent with itself either as LazyLock poisons for good, OnceLock never poisons, Mutex poisons but lets you recover. Also remember that poisoning only tracks panics and a more common early return has the same issue. The ? operator (as well as the try! macro before) that returns early from the middle of a critical section leaves the same broken invariant behind an unpoisoned lock. Note also that the coupling of poisoning of mutexes is historical and an explicit Poison<T> type would allow you to opt into this for any interior mutability wrapper. What I want Personally I hope the rust team stabilizes std::sync::nonpoison , have std::sync::Mutex resolve to it by default . If someone wants poisoning add that separate Poison<T> wrapper then anyone who believes they need and can handle it, can opt into it for any type including RefCell or tokio threads. What I think would be the worst of all outcomes is the counter-proposal is to keep poisoning but have lock() panic instead of returning a Result . That would only fix the held guard lock semantics, and to a smaller degree the ergonomics, but it makes the slow outage the only option. That is what every lock().unwrap() does today, and the issues above should be plenty of evidence of this being a problematic behavior in light of the existence of catch_unwind . The post In defense of lock poisoning is the best argument for the other side and worth reading but I believe the evidence all points the other way, and most of what Oxide ships aborts on panic anyway which is also a reasonable behavior.

中文翻译

Rust 有一个奇怪的功能,我认为如果它不是在语言里存在了这么久,今天就不会被接受:互斥锁中毒(mutex poisoning)。当某些 Rust 代码在持有 std::sync::Mutex 时发生 panic,这个互斥锁就被“中毒”了。这意味着之后任何对 lock() 的调用都会返回一个 PoisonError。这个功能的动机是:一个对象可能有一些需要维持的内部不变式,而在错误的时刻 panic 可能会破坏它们,使对象处于损坏状态。

就个人而言,我绝对讨厌这个功能,因为它已经咬过我很多次,而我不记得它哪怕帮过我一次。libs 团队正在讨论在下一个 edition 中把非中毒锁设为默认,而完全在意料之中的是,这已经让不少人跳出来为这个功能辩护。在这篇文章里,我想给出我个人的论据,说明为什么中毒锁要么应当被完全移除,要么应当成为例外。

主要原因在于,我至今还没有在实际代码中遇到过正确处理中毒锁的代码。另一方面,我遇到过足够多错误处理它的代码,其结果是表现得比不支持中毒的 parking_lot 锁还要糟糕。

核心信息

作者(Flask 作者、Rust 社区知名开发者 Armin Ronacher)系统论证 Rust 的 std::sync::Mutex 中毒机制应当被移除或降为例外:现实中几乎无人正确使用它,反而制造死锁、雪崩式 panic 与隐形的重复副作用。标准库自身在 stdio、panic 输出捕获、backtrace、WASI 环境锁等多处早已忽略中毒,Tokio、Wasmtime、crossbeam-channel、tracing-subscriber 等关键生态项目同样如此,rust-analyzer、Mozilla application-services 则干脆改用不中毒的 parking_lot。libs 团队正在讨论在下一个 edition 把非中毒锁设为默认,本文是为这一改动提供的实战证据与立场。

  • 作者(Flask 作者、Rust 社区知名开发者 Armin Ronacher)系统论证 Rust 的 std::sync::Mutex 中毒机制应当被移除或降为例外:现实中几乎无人正确使用它,反而制造死锁、雪崩式 panic 与隐形的重复副作用。标准库自身在 stdio、panic 输出捕获、backtrace、WASI 环境锁等多处早已忽略中毒,Tokio、Wasmtime、crossbeam-channel、tracing-subscriber 等关键生态项目同样如此,rust-analyzer、Mozilla application-services 则干脆改用不中毒的 parking_lot。libs 团队正在讨论在下一个 edition 把非中毒锁设为默认,本文是为这一改动提供的实战证据与立场。
  • 原贴提到:Rust has a curious feature that I don’t think the language would l
  • 来源:lucumr.pocoo.org

详细解读

这是什么信号

这是一篇来自 Rust 生态核心实践者(Armin Ronacher,Flask 作者、长期 Rust 使用者)的公开技术主张:Rust 标准库中 std::sync::Mutex 的“中毒”机制应当被废除或降为可选项。中毒的规则是——一旦某个线程在持锁期间 panic,该互斥锁即被标记为已中毒,后续所有 lock() 调用都会返回 PoisonError。设计初衷是保护被锁对象的内部不变式不被破坏。

但作者指出一个关键事实:传闻中的官方讨论并非孤立事件——标准库的 libs 团队正在讨论在下一个 edition 中把“非中毒锁”设为默认,而这一讨论已经引发了社区中相当一部分人的公开辩护。也就是说,这不是个人抱怨,而是语言默认值正在被重新评估的信号。

为什么重要

中毒机制的问题不在于“是否安全”,而在于它制造了一类难以察觉的系统性故障模式,作者给出了四条具体证据:

  • 错误对象持有锁。 PoisonError 必须携带 guard,因为要用 into_inner() 取出锁就得从错误对象里拿。于是错误在传递过程中会把锁一并带着走:一个看起来无害的 m.lock()? 在返回 Box<dyn Error> 的函数中,会让互斥锁在错误存活期间一直处于加锁状态;if let Ok(..) = lock() {..} else {..} 的 else 分支若再次锁同一个互斥锁,会直接死锁(cc-switch 曾因此挂起测试,PC-AI 在 match 分支中遇到同一个问题,ox-embed-server 亦有类似案例)。
  • 从 panic 演化为永久故障。 中毒不是 fail-fast,而是 fail-forever。原始 panic 只发生一次、在一个线程上,但因为大量 Rust 代码会“吞下”panic 继续运行(线程池、请求处理器、tokio task、FFI 边界),进程既不退出也不工作:RLS 中一次失败的 cargo build 在持有 ENV_LOCK 时 panic,导致此后任何一次运行都无法进行;Mozilla 的 application-services 在判定自己并未从中受益后改用 parking_lot,此前 PoisonError 已升至崩溃统计第 5 位;Neon 的一个 safekeeper 在全局锁 panic 后,所有 timeline 查询都失败,而原始 panic 在日志中根本找不到。
  • “恢复”并不恢复。 用 into_inner() 拿到锁后,中毒标记仍然存在,之后每次访问依旧走恢复路径。而 Rust 在中毒特性落地后的头九年里根本没有 clear_poison,该 API 到 1.77 才出现。结果是重复执行昂贵副作用:某项目在单次 panic 后每次转写都重建解码器状态,某项目每次访问都重复打印同一条警告,某个连接池每次归还都丢弃模型。
  • 没人真的依赖它,包括标准库自己。 stdio 自 2015 年起就忽略中毒,理由是“任何中毒都源于用户代码,而那并不是锁所保护的对象”;panic 输出捕获、backtrace 锁、WASI 环境锁同样如此,且已有 PR 要把 std 内部互斥锁迁移到非中毒实现。生态侧,Tokio 自己的锁不中毒(内部用适配器剥掉中毒语义),Carl Lerche 直言“我宁愿假装锁中毒不存在”;Wasmtime、crossbeam-channel、tracing-subscriber 一律忽略中毒;rust-analyzer 在取消操作引发中毒后切换到 parking_lot。

对谁有价值

直接相关的是所有用 Rust 写并发系统的人:服务端、数据库/存储引擎、编译器与工具链、以及任何把 lock().unwrap() 当作惯用法的代码库。次相关的是做基础设施选型的技术负责人——这条信号的实质是“一个语言级默认值被判为负资产”,它提醒任何设计公共 API 或内部框架的人:一个为了防御理论风险而设的强制机制,如果在其生命周期内几乎无人正确使用,它的净收益就是负的。panic = "abort" 的部署方受影响较小,因为进程直接终止,中毒永不出现。

可以怎么行动

  • 审计现有代码中所有 lock().unwrap() 和 .lock()?:前者在中毒时会把单次故障放大为全局 panic 循环,后者可能把锁随错误一起带走,形成死锁风险。这是最容易产生真实收益的两类写法。
  • 对不需要中毒语义的共享状态,评估改用 parking_lot 等不中毒实现,或在 tokio 运行时内部统一使用其自带的锁。
  • 如果确实要“忽略中毒”,显式使用 into_inner() 并用 clear_poison(Rust 1.77+)清标记,避免副作用被反复重放;同时明确写下“为什么这里的对象在 panic 后仍然可用”的判断,而不是靠 unwrap 侥幸。
  • 把“锁中毒策略”写进团队 Rust 编码规范:默认不依赖中毒语义,panic 处理策略(abort 还是 unwind)与锁策略必须一起决定,而不是各自默认。

风险与限制

首先,这是立场鲜明的技术评论,不是中立评测:作者明确表示自己“绝对讨厌”这个功能,且样本主要来自他所接触的开源代码,缺少“中毒机制避免了一次真实数据损坏”的反例统计——尽管他也引用了 Josh Triplett 在 Hacker News 上的说法:“在标准库的整个历史中,我们从未见过任何一份报告说有人尝试从中毒中恢复。”其次,废除中毒确实会削弱对对象不变式的强制保护,对少数依赖该语义的代码是行为变更,迁移需要适配;这也是社区辩护方的合理关切。第三,原文在末尾处被截断,rust-analyzer 切换 parking_lot 的完整论述及其他案例细节未能完整呈现,实施决策前应回到原文与相关 issue 讨论核对。

信息差价值

这条内容的真正价值,不只是“有人发布了一个新功能”,而是它揭示了 lucumr.pocoo.org 背后的产品方向、工作流变化或竞争信号。对 OPC 来说,这种信息可以转化成持续追踪的栏目选题。

如果把《废除锁中毒机制:Rust 里的一个应当被推翻的默认值》放到你的内容系统里,它最大的价值在于帮助读者更快看懂“为什么值得关注”,而不是只看到一条碎片化动态。

参考来源

AI SUMMARY

这篇文章回答了什么

废除锁中毒机制:Rust 里的一个应当被推翻的默认值主要讲什么?

作者(Flask 作者、Rust 社区知名开发者 Armin Ronacher)系统论证 Rust 的 std::sync::Mutex 中毒机制应当被移除或降为例外:现实中几乎无人正确使用它,反而制造死锁、雪崩式 panic 与隐形的重复副作用。标准库自身在 stdio、panic 输出捕获、backtrace、WASI 环境锁等多处早已忽略中毒,Tok…

这篇文章最值得关注的要点是什么?

作者(Flask 作者、Rust 社区知名开发者 Armin Ronacher)系统论证 Rust 的 std::sync::Mutex 中毒机制应当被移除或降为例外:现实中几乎无人正确使用它,反而制造死锁、雪崩式 panic 与隐形的重…;原贴提到:Rust has a curious feature that I don’t think the language would l;来源:lucumr.pocoo.org

这篇文章和哪些AI专题相关?

它适合放在AI日报、AI副业、AI工具专题里阅读。 关联原因:这篇内容命中「热点解读」等主题信号。;这篇内容命中「项目」等主题信号。;这篇内容来自该专题长期覆盖的栏目。

阅读这篇文章建议先理解哪些关键词?

建议先理解AI日报、每日AI日报、AI信号、热点解读、BuilderPulse这些关键词,再结合正文判断工具、机会或风险是否值得进入自己的工作流。

上一篇 已经是本栏目第一篇
下一篇 十二个月里的三个 LLM 拐点
北竹游乐场 免费玩小游戏 免费玩