Abolish Lock Poisoning
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Armin Ronacher’s Thoughts and Writings blog archive projects talks about Abolish Lock Poisoning written on November 25, 2026 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.
Armin Ronacher 的博客文章《废除锁中毒》(Abolish Lock Poisoning)写于 2026 年 11 月 25 日。Rust 有一个奇怪的特性,如果不是因为存在已久,我认为它今天不会被引入语言中:互斥锁中毒(mutex poisoning)。当某些 Rust 代码在持有 std::sync::Mutex 时发生恐慌(panic),该互斥锁就会被“中毒”。这意味着后续任何对 lock() 的调用都会返回一个 PoisonError。引入该特性的初衷是,对象可能具有需要维护的内部不变量,而在错误时刻发生的恐慌可能会破坏这些不变量,使对象处于损坏状态。
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.
另一方面,我见过太多代码处理不当,导致其表现比不支持中毒机制的 parking_lot 锁还要糟糕。Josh Triplett 在 Hacker News 的评论中表达得非常强烈:“在标准库的整个历史上,我们从未见过任何关于有人试图从中毒状态中恢复的报告。”当持有锁时发生恐慌,有两种合理的反应:关闭进程,或者继续运行并忽略该标志。如果设置 panic = “abort”,你会得到前者,而中毒问题永远不会出现。
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.
根据我所见的所有证据,在栈展开(unwinding)的情况下,惯用的 lock().unwrap() 选择了最糟糕的方案。因为它既没有停止进程,也没有让它继续运行,而是会将后续的每一次锁操作都变成恐慌,有时会产生灾难性的后果。但这并不是当前系统存在的唯一问题。因此,我想在这里分享一些问题,并引用一些现实世界的代码,说明人们是如何被它坑害的。
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
错误持有锁:中毒机制的一个微妙之处在于 PoisonError 需要持有锁守卫(guard)。这是因为为了忽略中毒标志,你需要从错误对象中获取守卫。持有错误就意味着持有锁!这可能导致执行错误包装或错误转换的常用代码陷入死锁风险。在返回 Box
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.
这种情况也可能发生在 if let 中。例如,在 cc-switch 中,你可以看到他们的一个测试挂起了,因为 if let Ok(..) = lock() { .. } else { .. } 的回退逻辑再次锁定了同一个互斥锁,而条件中未命名的 PoisonError 仍然拥有该守卫。PC-AI 在 match 分支中也有同样的错误。另一个案例可以在 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.
从恐慌到宕机:狡猾的是,中毒机制并不会快速失败,如果处理不当,它会永久失败。最初的恐慌发生一次,在一个线程上,通常与未来的失败无关。然而,该锁上后续的每一个 lock().unwrap() 现在也都会恐慌,而且由于许多 Rust 代码都能在恐慌中存活(线程池、请求处理器、tokio 任务、FFI 边界),进程会保持运行但变得毫无用处:在 RLS 中,一次失败的 cargo 构建在持有 ENV_LOCK 时发生恐慌,导致后续所有运行都无法进行。
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.
Mozilla 的 application-services 发现 PoisonError 在崩溃统计中上升到了第 5 位,在得出中毒处理对他们没有帮助的结论后,他们转向了 parking_lot。Neon 的一个 safekeeper 在持有全局锁时发生恐慌,导致后续所有时间线查找都失败,且最初的恐慌甚至无法在日志中找到。虽然不是在线服务,但测试套件也显示了同样的问题。一个失败的测试会毒化共享的静态变量,导致其后的每个测试都因 PoisonError 而失败。这个问题在 cargo、deno、polars 和 rustc 本身中都出现过。
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.
尝试恢复:如果你使用 into_inner() 进行恢复,标志位仍然保持设置,后续的每一次访问都会再次走恢复路径。请记住,在中毒特性引入后的前九年里,你甚至无法清除它,因为 clear_poison 直到 1.77 版本才出现。不清除标志意味着从那时起可能会发生昂贵的副作用:goose-in-a-pond 在一次恐慌后,在每次转录时都会重建其解码器状态;librefang 在每次访问时都会记录相同的警告;一个池在每次返回时都会丢弃其模型。
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.
没人依赖它,连标准库也不例外:那么到底是谁在处理中毒问题?我真的不确定,肯定不是标准库。标准库自己的代码在每一处都忽略了它。标准 I/O 自 2015 年 3 月(1.0 版本发布前两个月)以来就一直这样做,因为“任何中毒必然是用户代码的结果,而锁并不保护这些代码”。许多中毒错误的一个常见问题是,它们与所持有的互斥锁毫无关系。恐慌输出捕获、回溯锁和 WASI 环境锁也是如此。它们都采取了同样的做法,不出所料,目前有一个开放的 PR 旨在将 std 的内部互斥锁改为非中毒锁。
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.
我认为整个生态系统在很大程度上已经得出了同样的结论。Tokio 自己的锁不会中毒。它在内部将 std 的锁包装在一个适配器中,从而消除了中毒。当它落地时,Carl Lerche 评论道:“我宁愿假装锁中毒不存在。”在一种情况下,Eliza Weisman 需要使用 into_inner 在 drop 期间取消链接一个等待者,否则“我们将留下一个可能悬空的指针”。我特别想指出这一点,因为这是一个中毒机制阻碍了内存安全的案例,而内存安全通常被认为是人们想要中毒机制的原因。Wasmtime、crossbeam-channel 和 tracing-subscriber 总是忽略锁中毒。rust-analyzer 在取消操作毒化了其求解器后,也像之前的 RLS 一样切换到了 parking_lot。