Fix locking and cancellation cleanup handling.