Round #346

08 May 2026, 16:54· csharp· qwen2.5-coder-7b-instruct· r13-clean-hints
Complexity
band 0
ZP / UO / OBS
2 / 3 / 1
Journey weight
373
Lightshift ΔL
+0.00

Prompt

Implement an async circuit breaker that tracks consecutive failures

Zero-point index (what the engine surfaced)

ZPI-ZPI-0005 | 2026-05-08T16:54:53Z Implement an async circuit breaker that tracks consecutive failures ZERO POINT — 2 entries (structural invariants) ● hsl(296.42, 100%, 34%) ResiliencePipeline [contract] ● hsl(211.57, 100%, 34%) 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%, 30%) Connection resilience [function] OBSERVED — 1 entries (explicit in request) ◉ hsl(77.95, 100%, 30%) 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 = true; Console.WriteLine($"Circuit breaker opened due to {_failureCount} consecutive failures."); await Task.Delay(_resetTimeout, cancellationToken); _isOpen = false; Console.WriteLine("Circuit breaker closed after reset timeout."); } throw ex; // Rethrow the exception if circuit is not open } } } public class CircuitBreakerOpenException : Exception { public CircuitBreakerOpenException(string message) : base(message) { } } ``` ### Usage Example ```csharp class Program { static async Task Main(string[] args) { var circuitBreaker = new AsyncCircuitBreaker(maxFailures: 3, resetTimeout: TimeSpan.FromSeconds(5)); for (int i = 0; i < 10; i++) { try { var result = await circuitBreaker.ExecuteAsync(async () => { // Simulate a failing operation if (i % 2 == 0) { throw new InvalidOperationException("Operation failed."); } return $"Success: {i}"; }); Console.WriteLine(result); } catch (CircuitBreakerOpenException ex) { Console.WriteLine(ex.Message); } } } } ``` ### Explanation 1. **AsyncCircuitBreaker Class**: - `maxFailures`: The maximum number of consecutive failures before the circuit breaker opens. - `_resetTimeout`: The time duration after which the circuit breaker will close if it remains open. - `_failureCount`: Tracks the number of consecutive failures. - `_lastFailureTime`: Records the time of the last failure. - `_isOpen`: Indicates whether the circuit breaker is currently open. 2. **ExecuteAsync Method**: - Checks if the circuit breaker is open and throws an exception if it is. - Executes the provided action asynchronously. - If the action fails, increments the failure count and records the time of the last failure. - If the number of consecutive failures reaches or exceeds `_maxFailures`, the circuit breaker opens, and a reset timeout is started. - After the reset timeout, the circuit breaker closes. 3. **CircuitBreakerOpenException Class**: - A custom exception to indicate that the circuit breaker is open. This implementation provides a basic async circuit breaker that can be used to protect against repeated failures in asynchronous operations.

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, minimumThroughputSuccessRate: 90 ) .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."); } } } 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 `minimumThroughputSuccessRate` to ensure that the circuit breaker only opens if there are enough failures within the specified time frame. 2. **Executing Operations**: - The `ExecuteAsync` method uses the configured resilience pipeline to execute an asynchronous action. - If the operation fails, it will be retried according to the circuit breaker policy. - If the circuit breaker is open, a `BrokenCircuitException` will be thrown. This implementation provides a robust way to handle transient faults using a circuit breaker pattern in an async manner.

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.

V1claude-sonnet-4-6
Worse
V4qwen2.5-coder-7b-instruct
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