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 codepanics while holding a std::sync::Mutex, the mutex is poisoned. That meansthat any further call to lock() returns a PoisonError. The motivation forthis feature is that an object might have some internal invariants that need tobe upheld and panicking in the wrong moment might invalidate reasonable at and leave anobject behind in a broken state.Personally I absolutely hate this feature as it has bitten me so many times andI cannot once remember it helping me. The libs team isdiscussing making thenon-poisoning locks the default in the next edition but entirely expectedly ithas 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 eitherbe entirely removed or be made the exception.Primarily this is because I have yet to come across code in the wild thathandles a poisoned lock correctly. On the other hand I have come across enoughcode that mishandles it and as a result behaves worse than aparking_lot lock would which does not supportpoisoning.Josh Triplett put it quitestrongly in a hackernews comment: “In the entire history of the standardlibrary, we have never once seen a single report of anyone attempting to recoverfrom poison.”When a panic happens with a lock held, there are two reasonable reactions: shutthe process down, or carry on and ignore the flag. With panic = "abort" youget 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 turnevery further lock into a panic with sometimes disastrous effects. But thatis not the only issue with the system today. So here I want to share some ofthe issues and with some references to real world code of how people got bitten.The Error Holds the LockOne 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 guardfrom 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 adeadlock hazard. The innocent looking m.lock()? in a function returningBox or similar keeps the mutex locked for as long as the errorlives (#159930).This can also happen with if let. For instance incc-switchyou can see that they had a test hung because a if let Ok(..) = lock() { .. } else { .. } fallback locked the same mutex again while the unnamedPoisonError from the condition still owned the guard.PC-AI had the same bugin a match arm. Another case can be found inox-embed-server.Panic To OutageDeviously poisoning does not fail fast and done wrong, it fails forever. Theoriginal panic happens once, on one thread, often somewhere unrelated from futurefailures. Every later lock().unwrap() on that lock now however panics aswell, and because so much Rust code survives panics (thread pools, requesthandlers, tokio tasks, FFI boundaries), the process stays up and becomesuseless:In RLS a failed cargo build panicked with ENV_LOCK held which made anysubsequent runs impossible.Mozilla’sapplication-servicessaw PoisonError rise to rank5 in crashstats and moved toparking_lot afterthey concluded they did not benefit of poisoning handling.A Neon safekeeper onstaging 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 failingtest poisons a shared static and every test after it fails with PoisonError.This problem showed up forcargo,deno,polars andrustcitself.Attempt At RecoveryIf you recover with into_inner(), the flag stays set and every later accesstakes the recovery path again. And remember that for the first nine years ofRust after the poisoning feature landed, you could not even clear it asclear_poison arrived only in 1.77. Not clearing the flag means that potentiallyexpensive side effects will happen from that point onwards:goose-in-a-pondrebuilt its decoder state on every transcription after a single panic,librefanglogged the same warning on every access, and apool threw itsmodel away on every return.Nobody Relies on It, Not Even stdSo 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 March2015, two months before1.0, because “any poison must have been the result of user code which the lockisn’t protecting”. A common issue with a lot of poisoning errors that neverhad anything to do with the mutex that was held.Same with the panic outputcapture, the backtracelock and the WASIenvironment lock. Theyall do the same and unsurprisingly there is an openPR to move std’s internalmutexes 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 athing.” Inone case Eliza Weisman neededinto_innerto unlink a waiter during drop, or “we’ll leave the list with a potentiallydangling 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 toparking_lot aftercancellation poisoned its solver like RLS did before. The parking_lot maintainerdescribed itas an anti-feature that hurts usability and reliability to which I stronglyconcur.Why Only Mutex?Another aspect here is why this is done on Mutex but not on RefCell. Surelyif the case for poisoning is that some code temporarily breaks an invariant, panics, andsomeone else observes the broken state, then this should apply to more cases.Take the usual example that argues in favor of poisoning and replace Mutexwith RefCell, and you have exactly the sameproblem.Threads are not needed at all and this is not hypothetical either as tokiocatches every task panic. Paired with a LocalSet the panic comes back as aJoinError, the next borrow() succeeds and reads a nullpointerexactly like the mutex example from the issue.Given how much panic catching goes on in async code, much of which is !Sendfor performance reasons, I’m not even convinced that panics get caught moreoften in multi-threaded code yet nobody asks for RefCell to poison.The standard library isn’t consistent with itself either as LazyLock poisonsfor good, OnceLock never poisons, Mutex poisons but lets you recover.Also remember that poisoning only tracks panics and a more common early returnhas the same issue. The ? operator (as well as the try! macro before) thatreturns early from the middle of a critical section leaves the same brokeninvariant behind an unpoisoned lock.Note also that the coupling of poisoning of mutexes ishistoricaland an explicit Poison type would allow you to opt into this for anyinterior mutability wrapper.What I wantPersonally I hope the rust team stabilizes std::sync::nonpoison, havestd::sync::Mutex resolve to it bydefault. If someone wantspoisoning add that separate Poison wrapper then anyone who believes theyneed and can handle it, can opt into it for any type including RefCell ortokio threads.What I think would be the worst of all outcomes is the counter-proposal is tokeep poisoning but have lock() panic instead of returning a Result. Thatwould only fix the held guard lock semantics, and to a smaller degree theergonomics, but it makes the slow outage the only option. That is what everylock().unwrap() does today, and the issues above should be plenty of evidenceof this being a problematic behavior in light of the existence of catch_unwind.The post In defense of lockpoisoning is the best argument forthe other side and worth reading but I believe the evidence all points the otherway, and most of what Oxide ships aborts on panic anyway which is also areasonable behavior.