def tidy_up_profiler_state_on_fail(func: Callable) -> Callable[[], None]:
    """
    Useful inside a test that's flaky in CI, where the check_sampler_state
    fixture only gets to run at the end of all flaky attempts.
    """
    # consider adding to the flasky_in_ci decorator if it's useful elsewhere

    def wrapped():
        try:
            func()
        except BaseException:
            sys.setprofile(None)
            stack_sampler.thread_locals.__dict__.clear()
            raise

    return wrapped

    Useful inside a test that's flaky in CI, where the check_sampler_state
    fixture only gets to run at the end of all flaky attempts.
    
test/util.py