Course outline

Rust / Advanced / Lesson 21

Mutex poisoning and recovery

Handle Rust mutex poisoning and verify protected invariants.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Interpret a poisoned lock result.
  • Test a domain-specific recovery policy.
  • Distinguish advisory poison, lock contention, worker failure, and domain invalidity.
  • Design and test a guarded recovery or refusal policy with explicit completion.

Understand poisoning

A Mutex protects access to shared data, but its lock method can report poisoning if a thread panicked while holding the lock. Poisoning is advisory: it warns that a protected invariant may have been interrupted, not that the data is automatically invalid or repaired. Decide in advance whether the application should stop, inspect and recover, or replace the affected state.

Scope the lock guard

A successful lock returns a guard that grants access and releases the lock when dropped. Keep the guard’s scope as small as the invariant allows. The first example handles the result explicitly and updates one integer. A real invariant may span several fields; protect and update them together so another thread cannot observe a partially committed state.

rust Mutex outcome
use std::sync::Mutex;

fn main() {
    let count = Mutex::new(0);
    match count.lock() {
        Ok(mut guard) => {
            *guard += 1;
            println!("{}", *guard);
        }
        Err(_) => println!("poisoned"),
    };
}
Expected output
1

The guard updates the protected count and releases the lock on drop.

Observe a poisoned lock

The second example causes a worker to panic while holding a lock, waits for the worker, and then observes a poisoned result. Its panic hook is silenced only to keep this synthetic example’s output stable. In a real system keep useful diagnostics. A poisoned error can provide access to the guard, but inspecting and repairing data requires domain knowledge; blindly unwrapping or clearing poison does not restore an invariant.

rust Mutex outcome
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    std::panic::set_hook(Box::new(|_| {}));
    let value = Arc::new(Mutex::new(0));
    let shared = Arc::clone(&value);
    let worker = thread::spawn(move || {
        let _guard = shared.lock().unwrap();
        panic!("synthetic failure");
    });
    let _ = worker.join();
    println!("{}", value.lock().is_err());
}
Expected output
true

The worker panics while holding the guard, so the subsequent lock reports poison.

Choose recovery deliberately

Recovery should verify every invariant that might have been interrupted, then explicitly decide whether the value is safe to reuse. If no reliable repair is possible, propagate a failure or discard the affected state according to the application contract. Do not rely on poisoning as the sole safety mechanism: not every possible invariant violation necessarily causes a detectable poisoned lock.

Test the failure path

Test normal access and a controlled panic while the lock is held, then verify the selected recovery or failure policy. Join the worker before checking its result and use synthetic state. Avoid timing-dependent assertions about when a thread runs. Also test the data invariants after recovery; observing a successful lock alone does not prove that the protected state is correct.

Interpret the warning precisely

A Mutex protects access to a value through a guard, but it does not make every business transition correct. If a thread panics while holding the guard, the mutex will usually become poisoned and a later lock returns a PoisonError containing the acquired guard. This is an advisory warning that an invariant may have been interrupted; it does not prove that the data is invalid and it does not repair the data. Poison detection is not exhaustive, so a non-poisoned lock is not proof of valid state either. A sound unsafe abstraction must not rely on poisoning as its only safety mechanism.

Choose a policy before the failure: stop and propagate an error, inspect and repair, or replace the protected state from a trusted source. The correct choice depends on the domain. An integer counter may be easy to reset, while a partially updated ledger may require reconciliation that cannot be inferred from a lock flag. Document the invariant, what can be interrupted, and which layer owns the decision. A panic, a poison report, and a business-validation error are distinct events, even when a single incident causes more than one of them.

Guard scope and complete invariants

lock returns LockResult<MutexGuard<T>>. On success the guard gives exclusive access and releases the mutex when dropped. Keep the guard for the whole read, validation, and update needed to preserve a shared invariant. For a pair of balances, protecting each field separately or releasing the guard between checking and updating can expose a partial transition. Conversely, holding a guard during unknown callbacks, blocking I/O, or an await can delay progress or create a deadlock under some protocols. Extract what is needed and release it when the invariant permits, then revalidate if the state may change before a later commit.

A poisoned lock result is still associated with a guard obtainable from PoisonError::into_inner. Acquiring that guard gives access, not proof of correctness. Inspect every relevant field and either repair to a documented valid state or refuse reuse. clear_poison changes the mutex’s poison flag; it does not perform validation, undo side effects, or repair data. Clear it only after the application has established its recovery condition, while preserving the intended synchronization. An unexpected poison error should not be blindly unwrapped in a service unless terminating is the documented policy.

Repair is a domain operation

Recovery requires evidence that the protected invariant holds again. A cache whose authoritative data exists elsewhere may be safely discarded and rebuilt under an explicit policy; a financial balance cannot be reset to zero merely because that makes a test pass. If a two-field transition may have stopped halfway, compare against a trusted source or reject further operations until a domain-specific repair is available. Log safe diagnostic context without disclosing sensitive data. A repair must also account for external effects that a mutex cannot roll back.

After a verified repair, an application may clear poison and release the guard so future lock attempts no longer report that old warning. If verification or repair fails, retain the failure state or discard the whole component according to the contract; do not clear the flag to conceal the problem. Another panic can poison the mutex again, so recovery is not a permanent guarantee. Test the actual post-repair fields and business invariants as well as the flag. A successful lock after clearing only demonstrates access and the flag state, not a proof that the application chose the right repair.

Reproduce failure without timing guesses

A controlled test can use synthetic state, start a worker that panics while holding a guard, and join it before inspecting the mutex. A successful completion of join is not expected for that panicking worker: join returns Err, and the later lock is expected to report poison in the stated ordinary unwinding scenario. Joining provides a completion boundary instead of assuming a sleep was long enough. The test should also exercise the selected recovery or refusal policy and verify resulting data. Avoid changing a global panic hook in concurrent tests unless the harness deliberately isolates that process-wide state.

Test a normal lock, a controlled poisoned path, a failed repair, and successful validated recovery where the application supports them. When two workers contend, coordinate them with deterministic synchronization rather than asserting a particular scheduler order. Use timeouts only as bounded failure detection, not proof that deadlock is impossible. Mutex::try_lock can report WouldBlock when another guard holds the lock or a poison error when it acquires a poisoned mutex; distinguish these outcomes rather than treating every error as corruption. All examples below are synthetic and unexecuted in this environment; their conditional outcomes assume the stated setup and ordinary unwinding behavior.

Separate safety, liveness, and reporting

Poisoning is only one part of a concurrency design. Safe Rust can prevent data races while the program still deadlocks, starves a worker, loses a logical update, or reports an incorrect total. A consistent order for multiple locks can eliminate a particular circular wait but does not prove all liveness properties. Arc shares ownership, while Mutex protects access; joining workers and closing channels remain explicit responsibilities. A shared result should not be reported as complete until required workers have completed and their failures have been handled.

A safe public interface should state whether it returns an error on poison, repairs or replaces state, and what callers can assume afterward. Avoid exposing private representation merely to bypass the lock. Record the toolchain, target, profile, panic strategy, and test command when reproducing a failure; aborting panics do not unwind to a later recovery path in the same process. The course baseline is stable Rust 1.85 or newer, edition 2024. Standard-library Mutex and PoisonError documentation governs these examples; no local compiler execution, scheduling order, or production recovery is claimed.

20 worked examples

1. Normal guarded update

Problem: Trace the value across two guard scopes.

  1. The first guard changes the protected value from two to five.
  2. It is dropped before the second lock reads five.
rust Normal guarded update
let count = std::sync::Mutex::new(2_u32);
{ let mut guard = count.lock().unwrap(); *guard += 3; }
let n = *count.lock().unwrap();

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: if both locks succeed, n = 5

Why this result follows: A guard controls exclusive access for the update.

2. Guard a pair transition

Problem: Trace both fields under the same guard.

  1. The source decreases from ten to seven.
  2. The destination increases from five to eight before the guard drops.
rust Guard a pair transition
let state = std::sync::Mutex::new((10_u32, 5_u32));
{ let mut p = state.lock().unwrap(); p.0 -= 3; p.1 += 3; }

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: if the lock succeeds, state becomes (7, 8)

Why this result follows: One guard protects the complete two-field transition.

3. Interrupted transition

Problem: Identify the partial state and warning.

  1. The first update changed ten to seven.
  2. The second update did not happen before the stated panic.
text Interrupted transition
initial pair = (10, 5)
worker holds lock; first field becomes 7
worker panics before second field changes

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: under ordinary unwinding, later lock may report poison; pair is (7, 5)

Why this result follows: Poison warns that the invariant may have been interrupted.

4. Warning is not corruption proof

Problem: Assess the value in this controlled scenario.

  1. The worker did not modify the protected integer.
  2. The panic while holding the guard can still poison the mutex.
text Warning is not corruption proof
initial value = 4
worker acquires guard, changes nothing, then panics
worker is joined before inspection

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: poison is possible even though the stated value remains 4

Why this result follows: Poison signals possible interruption rather than proving invalid data.

5. No poison is not validation

Problem: Compare the stated invariant with the fixture.

  1. The stored total is nine.
  2. The entries sum to eight, so the equality rule fails.
text No poison is not validation
mutex reports no poison
application invariant: total must equal sum of entries
fixture: total = 9, entries sum = 8

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the invariant is violated despite no poison report

Why this result follows: A clear poison flag does not prove domain correctness.

6. Handle the lock result

Problem: Identify the normal path without assuming all locks succeed.

  1. The mutex is newly created and no worker has panicked with it.
  2. The normal lock returns a guard for the value four.
rust Handle the lock result
use std::sync::Mutex;
let state = Mutex::new(4_u32);
let result = state.lock();
// Match Ok(guard) and Err(poison) according to the policy.

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: a fresh mutex has a successful normal lock in this fixture

Why this result follows: Matching both variants leaves room for a poison policy.

7. Propagate poison

Problem: Apply the stated stop policy to a poisoned lock.

  1. The lock reports the advisory poison error.
  2. The policy returns failure rather than assuming the state is valid.
text Propagate poison
later lock result: Err(PoisonError)
policy: stop processing and report failure

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: no protected value is used as a successful result

Why this result follows: Refusal is a legitimate recovery policy when repair is not justified.

8. Inspect a poisoned guard

Problem: Explain what into_inner establishes in this situation.

  1. The poison error contains the acquired guard.
  2. Extracting it allows inspection but does not validate the data.
text Inspect a poisoned guard
lock result: Err(poison)
action: guard = poison.into_inner()
next action: inspect invariant

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the guard grants access; validity is still undecided

Why this result follows: Recovery requires a separate domain-specific check.

9. Validated cache repair

Problem: Trace the repair under the stated assumptions.

  1. The policy replaces the cache from the trusted source.
  2. It verifies the invariant before clearing the warning.
text Validated cache repair
protected cache: inconsistent
trusted source: available
policy: rebuild cache under guard, verify, then clear poison

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: reuse is allowed only after the stated verification succeeds

Why this result follows: A domain-specific repair can justify clearing poison.

10. Unrepairable state

Problem: Choose the outcome under this recovery policy.

  1. The fixture gives no trusted reconstruction for the ledger.
  2. The policy refuses reuse rather than guessing a replacement.
text Unrepairable state
protected ledger: inconsistent
trusted reconstruction: unavailable
policy: refuse reuse

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: return failure; do not clear poison merely to continue

Why this result follows: A poison flag cannot supply missing domain information.

11. Clearing is not repair

Problem: Distinguish the flag from the protected invariant.

  1. The stated action only changes the poison flag.
  2. No action corrects the invalid protected data.
text Clearing is not repair
state = invalid
action: clear_poison without repair

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: flag may be cleared; state remains invalid

Why this result follows: clear_poison does not validate or repair the value.

12. Join before inspection

Problem: Explain what ordering the join supplies.

  1. The coordinator waits for the worker to finish.
  2. Only then does it inspect the lock result in this sequence.
text Join before inspection
worker: panic while holding guard
coordinator: join worker
coordinator: inspect lock result

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: join establishes worker completion before inspection

Why this result follows: Completion is explicit rather than inferred from a delay.

13. Timing assumption

Problem: Evaluate this proposed synchronization step.

  1. A scheduler can delay the worker beyond the chosen sleep.
  2. The coordinator can inspect before the panic or guard release occurs.
text Timing assumption
worker: panic while holding guard
coordinator: sleep briefly, then inspect

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the sleep alone does not prove the worker has completed

Why this result follows: A duration is not a completion protocol.

14. Try-lock contention

Problem: Determine the nonblocking result under the held guard.

  1. The first lock holds the mutex guard.
  2. A second try_lock cannot acquire the mutex and returns WouldBlock.
rust Try-lock contention
use std::sync::{Mutex, TryLockError};
let lock = Mutex::new(1_u32);
let guard = lock.lock().unwrap();
let blocked = matches!(lock.try_lock(), Err(TryLockError::WouldBlock));

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: blocked = true while guard remains held

Why this result follows: WouldBlock describes contention rather than a poison diagnosis.

15. Try-lock poison

Problem: Interpret the stated fallible lock result.

  1. The fixture says the underlying lock is available and obtained.
  2. The returned variant is Poisoned rather than WouldBlock.
text Try-lock poison
mutex: poisoned and currently available
try_lock: obtains the underlying lock
result: Err(TryLockError::Poisoned(_))

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the error indicates poison, not ordinary WouldBlock contention

Why this result follows: Different error variants require different application handling.

16. Callback under lock

Problem: Explain the liveness risk in this trace.

  1. The outer operation retains the guard during the callback.
  2. The callback waits for the same lock before it can return.
text Callback under lock
guard held across unknown callback
callback attempts to acquire same mutex
callback cannot finish until it acquires the lock

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: a circular wait is possible in this stated protocol

Why this result follows: Releasing the guard before reentry can remove this particular wait when valid.

17. Opposite lock order

Problem: Identify the circular wait in this fixture.

  1. A waits for L2 held by B.
  2. B waits for L1 held by A.
text Opposite lock order
worker A holds L1 and waits for L2
worker B holds L2 and waits for L1

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the workers can deadlock

Why this result follows: A consistent lock order can prevent this particular cycle.

18. Clear after verified recovery

Problem: Trace the intended flag and guard sequence.

  1. The cache invariant is verified before the flag is cleared.
  2. Dropping the guard releases the mutex for a later attempt.
text Clear after verified recovery
poisoned state: cache rebuilt and verified
action: clear_poison while holding recovery guard
action: drop guard

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: a later successful lock need not report the old poison flag

Why this result follows: Clearing the flag is justified by the separate repair, not a repair itself.

19. Abort boundary

Problem: Explain why an unwind-based recovery test does not apply.

  1. The stated configuration aborts the process on panic.
  2. The process does not continue to a later in-process lock check.
text Abort boundary
panic strategy: abort
worker encounters panic
assumption: process aborts immediately

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: no same-process post-panic recovery path is claimed

Why this result follows: Panic strategy is part of the reproducibility and recovery contract.

20. Access is not invariant proof

Problem: Evaluate the conclusion in this synthetic test.

  1. The test has observed access after clearing the flag.
  2. It has not checked the ledger fields or their required relationship.
text Access is not invariant proof
test result: lock succeeds after clear_poison
assertion: all ledger invariants are valid

Illustrative fragment or synthetic trace; not compiled or executed here.

Expected result: the lock result alone does not establish the assertion

Why this result follows: Recovery tests must assert the actual domain invariant.

Common errors and fixes

A poisoned lock causes another panic

Why it happens
The lock result was unwrapped without a policy.
How to fix it
Handle the error according to the application contract.
Prevent it next time
Test a panic while the guard is held.

Corrupt state is reused

Why it happens
Poison was ignored without checking invariants.
How to fix it
Validate and repair or discard the state.
Prevent it next time
Document recovery invariants.

A test races the worker

Why it happens
The test reads before the worker ends.
How to fix it
Join the worker before asserting its result.
Prevent it next time
Control thread completion in tests.

20 practice exercises

1. Does a poisoned lock prove the protected data is invalid?

Show hint

Separate a warning from a domain validation result.

Show worked solution

No. It warns that a panic occurred while locked. Inspect the domain invariants before deciding whether recovery is safe.

Poison indicates that a panic may have interrupted work while a guard was held; it does not prove the data is invalid. Inspect the protected domain invariant and apply the documented repair, replacement, or refusal policy before reuse.

Check your solution

  • Poison is an advisory warning, not proof of invalidity
  • The domain invariant is checked before recovery

2. Why join the worker before checking for poison?

Show hint

Establish completion without guessing a delay.

Show worked solution

Joining establishes that the worker has finished, making the check independent of which thread happened to run first.

Joining the controlled worker waits for it to finish and returns Err when it panicked. The later lock check then follows worker completion, so the test does not rely on which thread happened to run first.

Check your solution

  • The worker join is observed before the lock check
  • A panicking worker produces a join error

3. A worker panics while holding a mutex but had not changed the protected value. Explain what poison means and what a recovery policy must still check.

Show hint

A warning does not prove corruption.

Show worked solution

The mutex may report poison even though the stated value is unchanged. Inspect the documented domain invariant and choose whether reuse is allowed; do not equate the poison flag with either proven corruption or automatic repair.

Check your solution

  • The value is not automatically proven invalid
  • Recovery checks the domain invariant

4. A mutex is not poisoned, but its stored total is 9 while entries sum to 8. Explain why the lock flag is insufficient and identify the failure.

Show hint

Check the application invariant directly.

Show worked solution

The invariant total == sum(entries) fails because 9 differs from 8, regardless of the poison flag. Validate domain state independently; absence of poison is not a correctness certificate.

Check your solution

  • The total invariant fails
  • A clear poison flag does not prove validity

5. A lock returns PoisonError for a partially updated pair. Explain what into_inner provides and the next decision before using the pair.

Show hint

Access to a guard is not validation.

Show worked solution

into_inner recovers the acquired guard so the application can inspect the protected pair. It must then verify or repair every relevant invariant, or refuse reuse; extracting the guard does not restore the pair automatically.

Check your solution

  • The guard permits inspection
  • Validity is decided by a separate domain check

6. A cache can be rebuilt from a trusted source after poison. Describe a guarded recovery sequence and the conditions for clearing poison.

Show hint

Repair and verify before changing the flag.

Show worked solution

Obtain the poisoned guard under the application’s policy, replace the cache from the trusted source, and verify its invariant. Only after successful repair clear poison and release the guard; otherwise report failure without pretending recovery succeeded.

Check your solution

  • The cache invariant is verified before clearing
  • Failure does not claim successful recovery

7. A ledger is poisoned after an interrupted transfer, and no trusted reconstruction exists. Choose a response and explain why resetting both balances to zero is unjustified.

Show hint

A repair must preserve domain meaning.

Show worked solution

Return or escalate a failure and prevent normal reuse until a domain-approved recovery is available. Resetting to zero changes financial state without evidence and clearing poison would not make that guess correct.

Check your solution

  • Normal reuse is refused
  • The balances are not guessed or silently reset

8. A developer clears poison immediately, then observes a successful lock. Explain what this demonstrates and what it does not.

Show hint

Separate the flag from the protected data.

Show worked solution

The successful later lock can show that the old poison flag no longer blocks a normal result. It does not prove the data’s invariant was checked or repaired; test the protected fields against the domain rule.

Check your solution

  • The flag state changed
  • The domain invariant still needs verification

9. Two balances begin at (10, 5). A worker must transfer 3 atomically with respect to other lock users. Give the successful result and guard scope.

Show hint

Protect validation and both updates together.

Show worked solution

Hold one guard for the pair, verify the source has at least 3, subtract 3, and add 3 before releasing it. On success the pair is (7, 8); define checked arithmetic and failure behavior where needed.

Check your solution

  • The successful pair is (7, 8)
  • One guard covers the complete transition

10. A worker checks a balance under a lock, releases it, and later subtracts under a second lock. Give a possible logical failure and repair.

Show hint

The state can change between lock scopes.

Show worked solution

Another worker can change the balance after the check, so the later subtraction may act on stale assumptions despite data-race freedom. Keep the check and update in one guard or revalidate under the later guard.

Check your solution

  • The prior check may become stale
  • The final update is protected by a current validation

11. A controlled worker panics while holding a mutex. Explain why the test should join it before checking poison and what join returns.

Show hint

Joining supplies a completion boundary.

Show worked solution

join waits until the panicking worker finishes and returns Err for its panic. The subsequent lock check is then ordered after that worker’s completion, rather than depending on a guessed sleep duration.

Check your solution

  • join returns Err for the worker panic
  • The poison check follows worker completion

12. A test waits 10 milliseconds before assuming a worker has poisoned a lock. Explain the flaw and replace the timing assumption.

Show hint

Scheduling may delay the worker.

Show worked solution

A fixed sleep does not guarantee that the worker has acquired the guard or panicked. Join the controlled worker, or use a defined synchronization protocol, then inspect the result and state.

Check your solution

  • The sleep does not prove completion
  • Completion is synchronized explicitly

13. try_lock returns WouldBlock while another guard is held. Explain why treating it as poisoned data is incorrect and give a response option.

Show hint

Contention and poisoning are different variants.

Show worked solution

WouldBlock means the nonblocking attempt could not acquire the currently held lock; it does not itself report poison. The caller may retry later, return busy, or choose another documented liveness policy.

Check your solution

  • WouldBlock is contention
  • The caller uses an explicit retry or busy policy

14. A try_lock acquires a mutex but returns Poisoned. Explain how this differs from WouldBlock and what the error can contain.

Show hint

The error variants reflect different situations.

Show worked solution

Poisoned reports that the acquired mutex is poisoned and carries a poison error containing the guard. WouldBlock means the lock could not be acquired immediately; handle each according to the application policy.

Check your solution

  • Poisoned provides a guard through its error
  • WouldBlock indicates immediate acquisition failed

15. A recovery callback tries to acquire the same mutex while the recovery guard is held. Explain a possible liveness failure and a safe restructuring condition.

Show hint

Reentry can wait on the outer guard.

Show worked solution

The callback may block waiting for the mutex that the outer code will not release until the callback returns. Complete a valid transition and release the guard before the callback when the domain protocol permits that order.

Check your solution

  • A circular wait is possible
  • The guard is released before reentry when valid

16. Two workers need locks L1 and L2. Specify a consistent acquisition rule and state one limitation of that rule.

Show hint

Remove opposite-order circular wait.

Show worked solution

Require every relevant path to acquire L1 before L2 and release guards appropriately. This removes the particular cycle caused by reversed ordering but does not prove absence of starvation or all other deadlocks.

Check your solution

  • All paths use L1 then L2
  • Other liveness risks remain

17. A panic strategy aborts the process. Explain why a same-process test cannot expect to inspect poison after that abort.

Show hint

Abort does not unwind back to the test.

Show worked solution

An aborting panic terminates the process rather than continuing to the subsequent lock check. Test any unwind-based recovery in a supported configuration and use an isolated process if the abort behavior itself must be observed.

Check your solution

  • The process does not continue to the lock check
  • The panic strategy is recorded

18. A test clears poison and checks only is_poisoned. Propose two additional checks for a repaired cache.

Show hint

Check both the flag and the data contract.

Show worked solution

Assert that the cache contents match the trusted source and that its internal index or other documented invariant is consistent. A clear flag alone cannot establish either property.

Check your solution

  • The repaired contents match the trusted source
  • The internal invariant is verified

19. A mutex protects local state but a worker already sent an external request before panicking. Explain why poison recovery cannot automatically undo that request.

Show hint

The external side effect is outside the guard’s rollback.

Show worked solution

Repairing local data or clearing poison does not retract a request already sent. The application needs the external system’s transaction, idempotency, or compensation policy and must handle uncertain outcomes explicitly.

Check your solution

  • The external request is not automatically undone
  • The external recovery policy is explicit

20. Design a small test matrix for a public mutex-protected API with a documented repair policy. Include normal access and a failed repair.

Show hint

Test outcomes and resulting state.

Show worked solution

Test a normal successful update, a controlled poisoned lock after a joined worker, a verified repair followed by valid state, and an unrepairable case that returns failure. Inspect the protected invariant and poison policy in each applicable case.

Check your solution

  • Normal and poisoned paths are covered
  • Successful and failed recovery outcomes are distinguished

Key takeaways

  • Poisoning is a warning, not automatic repair.
  • Test invariants and worker completion explicitly.
  • Poison is neither proof of corruption nor automatic repair.
  • Recover a guard only to inspect and apply a domain-specific policy.
  • Join workers and check resulting invariants without relying on scheduling guesses.

Official references