Repository navigation
Suggest retry policies with AI #397
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hamzahalq
merged 5 commits into
releases/r10.0-develop
from
hamza/feat/ai-retry-suggestions
Oct 29, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8b18d84
Merge remote-tracking branch 'origin/releases/r10.0-develop' into ham…
hamzahalq b473fda
Merge remote-tracking branch 'origin/hamza/feat/ai-failure-explanatio…
hamzahalq 9c41d58
feat: suggest retry policies with AI
hamzahalq f88c177
Merge releases/r10.0-develop into hamza/feat/ai-retry-suggestions
hamzahalq 0fccde5
fix: retry suggestion review findings
hamzahalq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| #nullable enable | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using SW.Bitween.Domain; | ||
| using SW.Bitween.Model; | ||
| using SW.Bitween.Services.Ai; | ||
| using SW.Bitween.Services.Metrics; | ||
| using SW.PrimitiveTypes; | ||
|
|
||
| namespace SW.Bitween.Resources.RetrySuggestions; | ||
|
|
||
| public class RetrySuggestionRequest | ||
| { | ||
| public int SubscriptionId { get; set; } | ||
|
|
||
| /// <summary>How far back to look, 1 to 90 days.</summary> | ||
| public int Days { get; set; } = 30; | ||
| } | ||
|
|
||
| /// <summary>One kind of failure, and what the current and the suggested policy each do with it.</summary> | ||
| public class RetrySuggestionCoverage | ||
| { | ||
| /// <summary>The error's first line, masked as it was sent.</summary> | ||
| public string Error { get; set; } = ""; | ||
| public int Count { get; set; } | ||
| public int Retried { get; set; } | ||
| public int FixedByRetry { get; set; } | ||
| public string Now { get; set; } = ""; | ||
| public string Suggested { get; set; } = ""; | ||
| } | ||
|
|
||
| public class RetrySuggestionResponse | ||
| { | ||
| public string Name { get; set; } = ""; | ||
| public string Summary { get; set; } = ""; | ||
|
|
||
| /// <summary>The groups, ready for <c>POST /api/retrypolicies</c>; nothing is saved until then.</summary> | ||
| public List<RetryGroup> Groups { get; set; } = new(); | ||
|
|
||
| public List<RetrySuggestionCoverage> Coverage { get; set; } = new(); | ||
| public int Failures { get; set; } | ||
| public int Days { get; set; } | ||
| public string? Model { get; set; } | ||
|
|
||
| /// <summary>The message that went to the provider, after the fixed <see cref="RetryPolicyPrompt.Instructions"/>.</summary> | ||
| public string Sent { get; set; } = ""; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Proposes a retry policy for a subscription from its own recent failures. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The provider sees each kind of failure as a masked line with counts and how often a retry fixed | ||
| /// it, and the current policy's rules. Never a document or a response body. The suggestion is then | ||
| /// checked as a saved policy would be and run against the real failures here, so the coverage | ||
| /// shows what changes for each before anyone saves it. | ||
| /// </para> | ||
| /// <para> | ||
| /// It saves nothing: saving the suggestion is creating a policy, so asking needs that right too, | ||
| /// and a question nobody could act on isn't sent. Each one is recorded as an operator action, | ||
| /// since it sends something about the subscription to a third party. | ||
| /// </para> | ||
| /// </remarks> | ||
| public class Suggest(RequestContext requestContext, BitweenDbContext dbContext, AiModels models) | ||
| : ICommandHandler<RetrySuggestionRequest, RetrySuggestionResponse> | ||
| { | ||
| public async Task<RetrySuggestionResponse> Handle(RetrySuggestionRequest request) | ||
| { | ||
| await requestContext.EnsurePermission(dbContext, Model.Permissions.Subscriptions.View); | ||
| await requestContext.EnsurePermission(dbContext, Model.Permissions.RetryPolicies.Create); | ||
| var model = models.Current(); | ||
|
|
||
| var subscription = await dbContext.Set<Subscription>().AsNoTracking() | ||
| .Include(s => s.RetryPolicy) | ||
| .FirstOrDefaultAsync(s => s.Id == request.SubscriptionId) | ||
| ?? throw new SWNotFoundException(request.SubscriptionId.ToString()); | ||
| var current = subscription.CustomRetryPolicy?.Groups ?? subscription.RetryPolicy?.Groups; | ||
| var days = Math.Clamp(request.Days, 1, 90); | ||
| var since = DateTime.UtcNow.AddDays(-days); | ||
|
|
||
| // The newest failures, by the (SubscriptionId, FinishedOn) index; only the start of each | ||
| // error, which is where its type and message are. Bad responses are counted apart, so many | ||
| // of them can't crowd the failures out. | ||
| var inWindow = dbContext.Set<XchangeResult>().AsNoTracking() | ||
| .Where(r => r.SubscriptionId == subscription.Id && r.FinishedOn >= since); | ||
| var errors = await inWindow | ||
| .Where(r => !r.Success) | ||
| .OrderByDescending(r => r.FinishedOn) | ||
| .Take(RetryPolicyPrompt.MaxFailures) | ||
| .Select(r => new | ||
| { | ||
| r.Id, r.FinishedOn, | ||
| Exception = r.Exception == null ? null : r.Exception.Substring(0, RetryPolicyPrompt.SampleLength), | ||
| }) | ||
| .ToListAsync(); | ||
| if (errors.Count == 0) | ||
| throw new SWValidationException("NO_FAILURES", | ||
| $"This subscription has no failed exchanges in the last {days} days, so there is nothing to learn a policy from."); | ||
|
|
||
| // Whether each one's retry succeeded: the attempt made from it, by the RetryFor index. | ||
| var ids = errors.Select(e => e.Id).ToList(); | ||
| var retries = await dbContext.Set<Xchange>().AsNoTracking() | ||
| .Where(x => x.RetryFor != null && ids.Contains(x.RetryFor)) | ||
| .Join(dbContext.Set<XchangeResult>(), x => x.Id, r => r.Id, (x, r) => new { x.RetryFor, Fixed = r.Success && !r.ResponseBad }) | ||
| .ToListAsync(); | ||
| var retriedFrom = retries.GroupBy(r => r.RetryFor!).ToDictionary(g => g.Key, g => g.Any(r => r.Fixed)); | ||
|
|
||
| var groups = errors | ||
| .GroupBy(e => ErrorFingerprint.Of(e.Exception ?? "")) | ||
| .OrderByDescending(g => g.Count()) | ||
| .Take(RetryPolicyPrompt.MaxKinds) | ||
| .ToList(); | ||
|
|
||
| // Each kind's newest error in full, as the live retry sees it: a matcher may hit deep in the stack. | ||
| var newestIds = groups.Select(g => g.First().Id).ToList(); | ||
| var full = await dbContext.Set<XchangeResult>().AsNoTracking() | ||
| .Where(r => newestIds.Contains(r.Id)) | ||
| .Select(r => new { r.Id, r.Exception }) | ||
| .ToDictionaryAsync(r => r.Id, r => r.Exception); | ||
|
|
||
| var kinds = groups | ||
| .Select(g => | ||
| { | ||
| var newest = g.First(); | ||
| return new FailureKind(full.GetValueOrDefault(newest.Id) ?? newest.Exception ?? "", | ||
| RetryPolicyPrompt.Mask(ErrorFingerprint.Sample(newest.Exception ?? "")), g.Count(), | ||
| g.Count(e => retriedFrom.ContainsKey(e.Id)), g.Count(e => retriedFrom.TryGetValue(e.Id, out var ok) && ok), | ||
| g.Min(e => e.FinishedOn), g.Max(e => e.FinishedOn)); | ||
| }) | ||
| .ToList(); | ||
| var badResponses = await inWindow.CountAsync(r => r.Success && r.ResponseBad); | ||
|
|
||
| var describe = $"Subscription kind: {subscription.Type}; mapper: {subscription.MapperId ?? "none"}; handler: {subscription.HandlerId ?? "none"}"; | ||
| var message = RetryPolicyPrompt.Message(describe, days, errors.Count, badResponses, kinds, current); | ||
| // Recorded before it goes, so a call that fails or times out after sending is on record too. | ||
| await dbContext.RecordNowAsync(requestContext, OperatorAction.SuggestRetryPolicy, $"subscription {subscription.Id}", | ||
| $"Sent to {models.ModelName}: {errors.Count} failures, errors masked."); | ||
| var suggestion = RetryPolicyPrompt.Parse( | ||
| await model.Complete(new AiPrompt(RetryPolicyPrompt.Instructions, message, Json: true, MaxTokens: 4000))); | ||
|
|
||
| var coverage = new List<RetrySuggestionCoverage>(); | ||
| foreach (var kind in kinds) | ||
| coverage.Add(new RetrySuggestionCoverage | ||
| { | ||
| Error = kind.Masked, | ||
| Count = kind.Count, | ||
| Retried = kind.Retried, | ||
| FixedByRetry = kind.FixedByRetry, | ||
| Now = await RetryPolicyPrompt.Outcome(current, kind.Sample), | ||
| Suggested = await RetryPolicyPrompt.Outcome(suggestion.Groups, kind.Sample), | ||
| }); | ||
|
|
||
| return new RetrySuggestionResponse | ||
| { | ||
| Name = suggestion.Name, | ||
| Summary = suggestion.Summary, | ||
| Groups = suggestion.Groups, | ||
| Coverage = coverage, | ||
| Failures = errors.Count, | ||
| Days = days, | ||
| Model = models.ModelName, | ||
|
hamzahalq marked this conversation as resolved.
|
||
| Sent = message, | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.