Round #496

09 May 2026, 19:53· csharp· qwen2.5-coder-7b-instruct· r13-clean-hints
Complexity
band 0
ZP / UO / OBS
2 / 3 / 1
Journey weight
317
Lightshift ΔL
+0.50

Prompt

Implement an async circuit breaker that tracks consecutive failures

Zero-point index (what the engine surfaced)

ZPI-ZPI-0005 | 2026-05-09T19:53:28Z Implement an async circuit breaker that tracks consecutive failures ZERO POINT — 2 entries (structural invariants) ● hsl(296.42, 100%, 46%) ResiliencePipeline [contract] ● hsl(211.57, 100%, 46%) ResiliencePipelineBuilder [contract] UNOBSERVED — 3 entries (implied truths) ○ hsl(27.69, 100%, 50%) async [feature] ○ hsl(49.23, 100%, 50%) try [feature] ○ hsl(144.00, 100%, 42%) Connection resilience [function] OBSERVED — 1 entries (explicit in request) ◉ hsl(77.95, 100%, 50%) async [feature] COMPLEXITY │ 6 entries │ spread: 116° │ band: LOW

Baseline response (no ZPI)

To implement an asynchronous circuit breaker in C#, you can use the `CancellationToken` to handle the cancellation of operations when the circuit is open. Below is a simple implementation of an async circuit breaker that tracks consecutive failures: ```csharp using System; using System.Threading; using System.Threading.Tasks; public class AsyncCircuitBreaker { private readonly int _maxFailures; private readonly TimeSpan _resetTimeout; private int _failureCount; private DateTime? _lastFailureTime; private bool _isOpen; public AsyncCircuitBreaker(int maxFailures, TimeSpan resetTimeout) { _maxFailures = maxFailures; _resetTimeout = resetTimeout; _failureCount = 0; _lastFailureTime = null; _isOpen = false; } public async Task<T> ExecuteAsync<T>(Func<Task<T>> action, CancellationToken cancellationToken = default) { if (_isOpen) { throw new CircuitBreakerOpenException("Circuit breaker is open. Operation cannot be performed."); } try { var result = await action(); _failureCount = 0; // Reset failure count on success return result; } catch (Exception ex) { _failureCount++; _lastFailureTime = DateTime.UtcNow; if (_failureCount >= _maxFailures && !_isOpen) { OpenCircuit(); } throw; } } private void OpenCircuit() { _isOpen = true; Console.WriteLine($"Circuit breaker opened at {DateTime.UtcNow} due to {_failureCount} consecutive failures."); } public async Task ResetAsync() { if (_isOpen) { var timeSinceLastFailure = DateTime.UtcNow - _lastFailureTime.Value; if (timeSinceLastFailure >= _resetTimeout) { _isOpen = false; Console.WriteLine($"Circuit breaker reset at {DateTime.UtcNow} after {_resetTimeout.TotalSeconds} seconds."); } else { throw new CircuitBreakerResetException("Cannot reset circuit breaker yet. It is still open."); } } } public bool IsOpen => _isOpen; } public class CircuitBreakerOpenException : Exception { public CircuitBreakerOpenException(string message) : base(message) { } } public class CircuitBreakerResetException : Exception { public CircuitBreakerResetException(string message) : base(message) { } } ``` ### Usage Example ```csharp class Program { static async Task Main(string[] args) { var circuitBreaker = new AsyncCircuitBreaker(maxFailures: 3, resetTimeout: TimeSpan.FromSeconds(10)); for (int i = 0; i < 5; i++) { try { await circuitBreaker.ExecuteAsync(async () => { if (i == 2) { throw new InvalidOperationException("Simulated failure"); } Console.WriteLine($"Operation successful at {DateTime.UtcNow}"); return "Success"; }); } catch (Exception ex) { Console.WriteLine(ex.Message); } await Task.Delay(1000); // Simulate some delay between operations } if (circuitBreaker.IsOpen) { try { await circuitBreaker.ResetAsync(); } catch (CircuitBreakerResetException ex) { Console.WriteLine(ex.Message); } } } } ``` ### Explanation 1. **Constructor**: Initializes the circuit breaker with a maximum number of failures and a reset timeout. 2. **ExecuteAsync Method**: Executes the provided action asynchronously. If the circuit is open, it throws an exception. On success, it resets the failure count. On failure, it increments the failure count and opens the circuit if the maximum number of failures is reached. 3. **OpenCircuit Method**: Sets the circuit breaker to the open state and logs the time it was opened. 4. **ResetAsync Method**: Resets the circuit breaker after a specified timeout if it is currently open. 5. **IsOpen Property**: Returns whether the circuit breaker is currently open. This implementation provides a basic async circuit breaker that can be used in scenarios where you want to prevent repeated failures from overwhelming your system.

Enhanced response (with ZPI)

To implement an async circuit breaker that tracks consecutive failures, we can use the `ResiliencePipeline` and `ResiliencePipelineBuilder` from the Polly library. Polly is a popular .NET library for handling transient faults and implementing patterns such as circuit breakers. Here's how you can implement the async circuit breaker: 1. **Install Polly NuGet Package**: First, ensure you have the Polly package installed in your project. You can install it via NuGet Package Manager or by running the following command in the Package Manager Console: ```sh Install-Package Polly ``` 2. **Create a Circuit Breaker Policy**: We'll create a circuit breaker policy that tracks consecutive failures and opens the circuit after a certain number of failures. 3. **Implement the Async Circuit Breaker**: We'll use the `ResiliencePipelineBuilder` to configure the circuit breaker policy and apply it to an asynchronous operation. Here's the complete implementation: ```csharp using Polly; using Polly.CircuitBreaker; using System; using System.Threading.Tasks; public class AsyncCircuitBreakerExample { private readonly ResiliencePipeline _resiliencePipeline; public AsyncCircuitBreakerExample() { // Configure the resilience pipeline with a circuit breaker policy _resiliencePipeline = Policy .Handle<Exception>() .CircuitBreakerAsync( onBreak: (exception, breakDuration) => { Console.WriteLine($"Circuit breaker opened. Retrying in {breakDuration.TotalSeconds} seconds."); }, onReset: () => { Console.WriteLine("Circuit breaker reset."); }, shouldThrowExceptionOnBreak: true, durationOfBreak: TimeSpan.FromSeconds(5), minimumThroughput: 10, samplingDuration: TimeSpan.FromSeconds(30) ) .ToResiliencePipeline(); } public async Task ExecuteAsync(Func<Task> action) { try { await _resiliencePipeline.ExecuteAsync(action); } catch (BrokenCircuitException ex) { Console.WriteLine($"Operation failed and circuit breaker is open: {ex.Message}"); } } } public class Program { public static async Task Main(string[] args) { var example = new AsyncCircuitBreakerExample(); // Simulate a series of operations that may fail for (int i = 0; i < 15; i++) { try { await example.ExecuteAsync(async () => { if (i % 3 == 0) { throw new InvalidOperationException("Simulated failure"); } Console.WriteLine($"Operation {i} succeeded."); }); } catch (BrokenCircuitException ex) { Console.WriteLine(ex.Message); } await Task.Delay(1000); // Wait for a second before the next operation } } } ``` ### Explanation: 1. **Resilience Pipeline Configuration**: - We configure a resilience pipeline using `Policy.CircuitBreakerAsync`. - The `onBreak` action is called when the circuit breaker opens, indicating that the circuit is open and retries will be delayed. - The `onReset` action is called when the circuit breaker resets, indicating that it is now closed and operations can proceed again. - We set `shouldThrowExceptionOnBreak` to `true` so that an exception is thrown when the circuit breaker is open. - We specify a `durationOfBreak` of 5 seconds, meaning the circuit will remain open for this duration before attempting to close again. - We set `minimumThroughput` and `samplingDuration` to configure how often the circuit breaker samples the operation's success rate. 2. **Executing Operations**: - The `ExecuteAsync` method uses the configured resilience pipeline to execute an asynchronous action. - If the action throws an exception, it is caught by the circuit breaker policy, which may open the circuit if the failure count exceeds the threshold. 3. **Simulating Failures**: - In the `Main` method, we simulate a series of operations that may fail every third time. - We use a loop to execute these operations and handle any exceptions thrown by the circuit breaker policy. This implementation provides a robust way to implement an async circuit breaker using Polly, which can help improve the resilience of your application by handling transient faults gracefully.

Grader chain

Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.

V1samba/Meta-Llama-3.3-70B-Instruct
Better
V4qwen2.5-coder-3b-instruct
Better
V5cerebras/qwen-3-235b-a22b-instruct-2507
Better
V7qwen2.5-coder-7b-instruct
Better
V8openai/gpt-4.1
Better
V9anthropic/claude-opus-4-7
Better
V12openai/gpt-4o
Better

Comments

Our grader said what it said. What do you say? Comment as a guest below.

No comments yet. Be the first to say what you make of this round.

← back to all rounds