Skip to content
This repository was archived by the owner on Jan 11, 2024. It is now read-only.
This repository was archived by the owner on Jan 11, 2024. It is now read-only.

Xunit: Provide a Retry attribute #654

Closed

Description

@ianhays

In some libraries we have tests that are prone to intermittent failure due to the characteristics of the library being tested. An example of this is FileSystemWatcher: the tests assert that an event is fired by the OS but that isn't always done with 100% certainty. Events only may fire. We don't need to be as strict with our assertions because there isn't a guarantee that the tested behavior is going to execute as expected. However, we still do want to test that behavior so we need a way to retry the test.

Xunit has a RetryFact that accomplishes this. I'm proposing we do something similar but slightly different:

[Fact]
[RetryTest(10)] // If the test fails, retry it up to 10 times
public void test1() {..}

[Theory]
[RetryTest(10)] // If the test fails, retry it up to 10 times
[InlineData(1)]
public void test2(int inline1) {..}

This way we could prioritize test failures differently. If we retry what was previously an unreliable test 10 times and it still fails then there's probably something actually wrong. What worries me about our current situation is that test failures in some libraries get shrugged off because of how prone to failure they are and that's leaving us open to actual product bugs getting ignored.

more discussion in dotnet/corefx#7934

@stephentoub @mellinoe @CIPop

Activity

  1. self-assigned this
    on Apr 21, 2016
  2. CIPop commented on Apr 21, 2016

    @CIPop

    /cc @ericeil @davidsh

    This is a really good idea. We though need some more sophisticated system for Networking which can fail reaching external resources for multiple reasons some of which:

    1. local machine is busy
    2. the remote resource is busy or has transient failures
    3. the network is busy
    4. the local resource has failed (i.e. incorrectly configured)
    5. the remote resource has failed
    6. the network is partitioned

    For points 4 - 6 we need to use diagnosis to avoid retries if they will result in the same outcome.

    For points 1 - 3 we need an exponential back-off algorithm to allow the resources to go through the queued work.
    Immediately retrying 10 times will increase queue lengths thus making things worse, probably causing other tests to fail.

    Found this earlier this week:
    https://msdn.microsoft.com/en-us/library/dn589788.aspx and https://msdn.microsoft.com/library/hh680934(v=pandp.50).aspx. These analyze and propose retry patterns for Networking purposes. Code/binaries are available part of the Enterprise Library/Topaz on NuGet.

  3. ericeil commented on Apr 21, 2016

    @ericeil

    This is effectively a proposal that we add support for "unreliable" test cases. To that end, I'd suggest calling this something like [UnreliableFact] rather than naming it for some implementation detail like "retries," etc.

    That said, I'm not sure how I feel about having unreliable test cases. 😬 Isn't it typically just one operation within the test case that we want to treat as "unreliable," and don't we typically expect such operations to fail only in certain well-defined ways? For example, if I'm connecting to a remote server, the call to Socket.Connect might legitimately fail because the server's down or busy, in which case the sort of logic @CIPop suggests might be a reasonable way to recover. But if it, for example, throws a NullReferenceException intermittently, I would not want to retry the whole test and miss those failures. And once connected, I'd want to be rigid about validating things like the remote endpoint address/port reported by the socket, and again wouldn't want to automatically hide intermittent failures in those areas.

    To me this argues for simple library support for retry/backoff/etc. logic, to be used as appropriate around operations that have known legitimate intermittent failure modes.

  4. ianhays commented on Apr 21, 2016

    @ianhays
    Author

    For points 1 - 3 we need an exponential back-off algorithm to allow the resources to go through the queued work.

    I've got a prototype working that does dumb-retries without any back-off and I don't think back-off will be difficult to add. I had planned on making it specifiable as an optional parameter on the Retry tag e.g.

    [ExtensibleFact]
    [Retry(10, backOff: 200)] // Retry this test up to 10 times but wait at least 200 ms between iterations
    public void test() {...}
    

    but looking into it more it seems like having exponential backoff toggle-able through a bool parameter would be more useful:

    [ExtensibleFact]
    [Retry(10, backOff: true)] // Retry this test up to 10 times and use exponential backoff to space out the iterations
    public void test() {...}
    

    I was looking at Wikipedia for the gist of the algorithm. Using this, a backoff test method would catch failures, wait an amount of time dependent on the current iteration, then try again. How does that sound to you? Which of those two options would be more useful?

    For points 4 - 6 we need to use diagnosis to avoid retries if they will result in the same outcome.

    This is somewhat more difficult to accomplish in an API-friendly way. Off the top of my head the best way to do it would be to allow filtering of the Retry e.g.:

    [ExtensibleFact]
    [Retry(10, typeof(ArgumentException))] // If an ArgumentException is thrown, retry this test up to 10 times.
    public void test() {...}
    

    but that doesn't seem very good and I'm not sure how feasible it is.

  5. ianhays commented on Apr 21, 2016

    @ianhays
    Author

    This is effectively a proposal that we add support for "unreliable" test cases. To that end, I'd suggest calling this something like [UnreliableFact] rather than naming it for some implementation detail like "retries," etc.

    That's essentially what it is, yes.

    That said, I'm not sure how I feel about having unreliable test cases. 😬 Isn't it typically just one operation within the test case that we want to treat as "unreliable," and don't we typically expect such operations to fail only in certain well-defined ways?

    It does sort of go against the spirit of a unit test. And I admit that I'm concerned about possible abuse of the attribute by lazy devs not wanting to fix intermittent failures :) But I'd rather have the power to do that easily if it's the right thing.

    To me this argues for simple library support for retry/backoff/etc. logic, to be used as appropriate around operations that have known legitimate intermittent failure modes.

    The problem is that those operations tend to have nontrivial amounts of setup and teardown that (in the case of FileSystemWatcher at least) can make up the entirety of the unit test. In that case, I could either mark those tests as Unreliable/Retry/Whatever or I could add a bunch of loops to do it. For libraries prone to intermittent expected failures, there isn't a great way to reduce the strictness of the tests.

  6. bartonjs commented on Apr 21, 2016

    @bartonjs
    Member

    Yeah, I'm in agreement with @ericeil. We should be striving for reliable tests. If a test expects some amount of variability it should self-guard against it. Maybe that's facilitated by a RetryHelper, or some other utility types.

    About the only thing I like about the attribute notion is that we can automatically move any such tests to outerloop. Because if it's documented as unreliable, it shouldn't be a checkin test.

  7. bartonjs commented on Apr 21, 2016

    @bartonjs
    Member
    // Given:
    public static class RetryHelper
    {
        public static void ExponentialBackoff(Action retryableSegment, Predicate<Exception> retryAnalyzer) { /* ... */ }
    }
    
    [Fact]
    public static void SomeTest()
    {
        // Optional one-shot setup goes here.
    
        RetryHelper.ExponentialBackoff(
            () =>
            {
                Task t = SomeSlowOrFlakyThing();
                bool finished = Task.WaitAll(t, 3000);
    
                if (!finished)
                {
                    throw new ConnectionTimeoutException();
                }
            },
            ex =>
            {
                HttpException httpException = ex as HttpException;
    
                if (httpException != null)
                {
                    return httpException.InnerException is SocketException;
                }
    
                return ex is SocketException || ex is ConnectionTimeoutException || ex is SomeOtherException);
            });
    
        // Optional stuff to do after the retryable segment goes here.
  8. ianhays commented on Apr 21, 2016

    @ianhays
    Author

    It'd be a nightmare to modify all of our existing tests to follow that pattern though. And even then it's not immediately obvious what the test is doing.

    It does seem like the ability to control when the test retries is important. What do yall think of this:

            [ExtensibleTheory]
            [Retry(10, typeof(ConnectionTimeoutException))]
            [Retry(10, typeof(SocketException))]
            [Retry(10, typeof(SomeOtherException))]
            public static void SomeTest()
            {
                // Optional one-shot setup goes here.
    
                Task<int> t = SomeSlowOrFlakyThing();
                bool finished = Task.WaitAll(t, 3000);
    
                if (!finished)
                {
                    throw new ConnectionTimeoutException();
                }
    
                Assert.True(t.Result < 0);  // If this fails, the test is not retried.
    
                // Optional stuff to do after the retryable segment goes here.
            }
    

    The only issue then would be that the filtering would be limited to failures from exceptions. Assertions would be treated differently and not be filterable (unless I guess you filtered the exception that a failed assertion throws maybe?).

  9. bartonjs commented on Apr 21, 2016

    @bartonjs
    Member

    Well, that missed the inspection check of the HttpException wrapping a SocketException (and other "i need to look at this Exception object" checks). And, if anything, it should be one retry attribute with a params Exceptions array. Otherwise you have "what happens if not all the retry values agree?"

    I'm personally okay with the retry being a pain to use; it means you have more incentive to write tests that don't need it. And, failing anything else, you can just wrap the existing methods:

    private static readonly Predicate<Exception> s_isTimeout = e => e is TimeoutException;
    
    [Fact]
    public static void SomeTest()
    {
        RetryHelper.ExponentialBackoff(SomeTestCore, s_isTimeout);
    }
    
    private static void SomeTestCore()
    {
        // The code that used to be SomeTest
    }
  10. ianhays commented on Apr 21, 2016

    @ianhays
    Author

    Well, that missed the inspection check of the HttpException wrapping a SocketException (and other "i need to look at this Exception object" checks).

    That it did. Any retry-check more complicated than a basic exception catching would have to do something more explicit like the example you posted.

    And, if anything, it should be one retry attribute with a params Exceptions array. Otherwise you have "what happens if not all the retry values agree?"

    Yeah, it would make more sense as a params array because otherwise we'd have to manually parse the other attributes searching for more instances of Retry

    I'm personally okay with the retry being a pain to use; it means you have more incentive to write tests that don't need it.

    There's a not insignificant adoption cost with that though. If it's too much of a pain to fix tests that contain intermittent failures then they just don't get fixed. I'd rather we have these tests explicitly marked as prone to intermittent failure than do what we're currently doing which is (maybe) file a bug for the failure, call dotnet-bot test this please, then never look at it again.

  11. ianhays commented on Apr 21, 2016

    @ianhays
    Author

    Adding some people who have been active in testing or been involved in a Retry discussion lately: @ellismg @hughbe @ericstj

  12. CIPop commented on Apr 21, 2016

    @CIPop

    I'm personally okay with the retry being a pain to use; it means you have more incentive to write tests that don't need it.

    I agree: I think that the test should present best practices for developers using our framework. If a retry mechanism is required for certain scenarios, we should either include it in a contract or reference existing components such as the Enterprise Library.

    Well, that missed the inspection check of the HttpException wrapping a SocketException (and other "i need to look at this Exception object" checks).

    It can get complex very fast: For System.Net Desktop tests we have a module that runs a set of checks whenever it's asked for the endpoint descriptor (Uri or hostname/port). This is done once, before the tests are executed and it pings the endpoint by submitting a simple request using the specified protocol. If these checks fail, the entire suite is aborted with a clear message (there's no point in getting thousands of failures all from the same cause).

    There's a not insignificant adoption cost with that though. If it's too much of a pain to fix tests that contain intermittent failures then they just don't get fixed. I'd rather we have these tests explicitly marked as prone to intermittent failure than do what we're currently doing which is (maybe) file a bug for the failure, call dotnet-bot test this please, then never look at it again.

    One more thing to consider: given Azure's SLA, it is expected that our CI system will fail from time to time. Failure rates and history can be found here: https://azure.microsoft.com/en-us/status/
    Blindly retrying during downtime would unnecessarily load the CI system.

  13. ianhays commented on Jun 27, 2016

    @ianhays
    Author

    It can get complex very fast:

    Agreed. Retrying is a bit too much based on the individual test's needs to be easily generalized like the above examples. I ended up adding a little bit of custom code in FileSystemWatcher to retry tests in a format similar to the one Jeremy posted and it ended up being more robust than an xunit attribute would have been. Closing this.

  14. jeroenheijmans commented on Jun 19, 2019

    @jeroenheijmans

    For future visitors, that (like me) landed on this thread via Google looking for an [UnreliableFact]: I have tried to create such a Fact (and associated plumbing).

    My sample is basic, you can use it to specify for example this:

    [UnreliableFact(RetryableException = "System.InvalidOperationException")]
    

    This indicates that any occurrence of that specific exception type should trigger retries.

    It's useful (we use it ourselves) in integration tests relying on Azure Search, which every so often has spurious failures.

    The nitty gritty is inside the UnreliableTestCase class and the ExceptionTrackingMessageBus, with the UnreliableFact and the UnreliableFactDiscoverer merely passing on the exception type.

    What's (currently) left as an exercise to the reader:

    • More precisely sniffing/checking the exception (e.g. only retry on "Error: service n/a, try again in a bit")
    • Multiple exception types
    • Support for Theory in addition to Fact
    • Thorough review of the example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions