core: add limit forecasts, week days and per-model series (D7)
LimitAnalysis computes the use at reset at the average rate, a recent-rate forecast from the last 24 h of samples, and for windows longer than a day the use of each local day, today's use, the even pace and the daily budget. Pace now projects the date of reaching 100 % whenever usage is over pace, not only past the threshold. Samples whose resets lie within 15 minutes form one window instance, because Claude's reset times drift by a minute between probes. TokenSeriesByModel replaces one query per chart point, and a missing settings.json on first start is no longer a diagnostic. Refs #5
This commit is contained in:
@@ -5,6 +5,7 @@ namespace FinalToken.Core;
|
||||
|
||||
public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts);
|
||||
public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts);
|
||||
public sealed record ModelTokenPoint(DateTimeOffset Time, string? Model, TokenCounts Counts);
|
||||
public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
|
||||
public enum SeriesInterval { Hour, Day }
|
||||
|
||||
@@ -185,10 +186,10 @@ public sealed class HistoryStore
|
||||
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
|
||||
}
|
||||
if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent &&
|
||||
window.ResetsAt == chronologicalPrevious.ResetsAt &&
|
||||
LimitAnalysis.SameInstance(window, chronologicalPrevious) &&
|
||||
window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue;
|
||||
if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent &&
|
||||
window.ResetsAt == chronologicalNext.ResetsAt &&
|
||||
LimitAnalysis.SameInstance(window, chronologicalNext) &&
|
||||
chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue;
|
||||
if (previous is null || window.SampleTime >= previous.SampleTime)
|
||||
state.LastSamples[key] = pending.LastSamples[key] = window;
|
||||
@@ -198,6 +199,7 @@ public sealed class HistoryStore
|
||||
foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider];
|
||||
}
|
||||
}
|
||||
// D5: retain exact probe metadata; D7 tolerance applies only to instance identity and sampling.
|
||||
private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) =>
|
||||
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
|
||||
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
|
||||
@@ -227,6 +229,14 @@ public sealed class HistoryStore
|
||||
}
|
||||
}
|
||||
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true);
|
||||
public IReadOnlyList<ModelTokenPoint> TokenSeriesByModel(Provider provider, DateTimeOffset from, DateTimeOffset to,
|
||||
SeriesInterval interval, TimeZoneInfo? zone = null)
|
||||
{
|
||||
lock (gate) return Range(provider, from, to)
|
||||
.GroupBy(b => (Time: interval == SeriesInterval.Hour ? b.Hour : CalendarDays.Start(b.Hour, zone), b.Model))
|
||||
.OrderBy(g => g.Key.Time).ThenBy(g => g.Key.Model, StringComparer.Ordinal)
|
||||
.Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model, Sum(g.Select(b => b.Counts)))).ToArray();
|
||||
}
|
||||
public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false);
|
||||
private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
|
||||
double Increase = 0, TimeSpan Span = default);
|
||||
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative,
|
||||
bool IsToday, bool IsFuture);
|
||||
public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous,
|
||||
double? Today, double EvenPace, double? DailyBudget);
|
||||
|
||||
/// <summary>Pure D7 calculations. Missing historical baselines stay unknown rather than inventing use.</summary>
|
||||
public static class LimitAnalysis
|
||||
{
|
||||
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
|
||||
public static bool SameInstance(LimitWindow first, LimitWindow second) =>
|
||||
first.Provider == second.Provider && first.Id == second.Id &&
|
||||
first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset &&
|
||||
(firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15);
|
||||
|
||||
public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now)
|
||||
{
|
||||
var pace = Pace.Calculate(window, now);
|
||||
return pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : null;
|
||||
}
|
||||
|
||||
public static RateForecast? Recent(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now)
|
||||
{
|
||||
if (window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || reset <= now ||
|
||||
Pace.Calculate(window, now).State == PaceState.Unknown) return null;
|
||||
var points = Instance(window, samples).Append(window).Where(s => s.SampleTime >= now.AddHours(-24) &&
|
||||
s.SampleTime >= reset - length && s.SampleTime <= now).OrderBy(s => s.SampleTime).ToArray();
|
||||
if (points.Length < 2) return null;
|
||||
var first = points[0]; var last = points[^1];
|
||||
var span = last.SampleTime - first.SampleTime;
|
||||
if (span < TimeSpan.FromHours(3) || points.Zip(points.Skip(1)).Any(p => p.Second.UsedPercent < p.First.UsedPercent)) return null;
|
||||
var rate = (last.UsedPercent - first.UsedPercent) / span.TotalDays;
|
||||
var projected = window.UsedPercent + rate * (reset - now).TotalDays;
|
||||
DateTimeOffset? reaches = null;
|
||||
if (rate > 0 && projected > 100)
|
||||
reaches = now.AddDays((100 - window.UsedPercent) / rate);
|
||||
return new(rate, projected, reaches, last.UsedPercent - first.UsedPercent, span);
|
||||
}
|
||||
|
||||
public static WindowDays? Days(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, TimeZoneInfo? zone = null)
|
||||
{
|
||||
if (window.Length is not { } length || length <= TimeSpan.FromDays(1) || window.ResetsAt is not { } reset ||
|
||||
Pace.Calculate(window, now).State == PaceState.Unknown) return null;
|
||||
zone ??= TimeZoneInfo.Local;
|
||||
var all = samples.Where(s => s.Provider == window.Provider && s.Id == window.Id).ToArray();
|
||||
var current = Build(window, Instance(window, all).Append(window).ToArray(), now);
|
||||
var previousWindow = all.Where(s => s.ResetsAt < reset && !SameInstance(window, s))
|
||||
.OrderByDescending(s => s.ResetsAt).ThenByDescending(s => s.SampleTime).FirstOrDefault();
|
||||
var previous = previousWindow is null ? [] : Build(previousWindow, Instance(previousWindow, all).ToArray(), previousWindow.ResetsAt!.Value);
|
||||
return new(current, previous, current.FirstOrDefault(d => d.IsToday)?.Used, 100 / length.TotalDays,
|
||||
reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null);
|
||||
|
||||
LimitDay[] Build(LimitWindow w, LimitWindow[] points, DateTimeOffset until)
|
||||
{
|
||||
if (w.ResetsAt is not { } end || w.Length is not { } duration) return [];
|
||||
var start = end - duration;
|
||||
points = points.Where(s => s.SampleTime >= start && s.SampleTime <= until).OrderBy(s => s.SampleTime).ToArray();
|
||||
var result = new List<LimitDay>();
|
||||
for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone))
|
||||
{
|
||||
var next = CalendarDays.NextStart(day, zone);
|
||||
var dayEnd = next < end ? next : end;
|
||||
var cutoff = dayEnd < until ? dayEnd : until;
|
||||
var baseline = day <= start ? 0 : Last(day);
|
||||
var cumulative = cutoff >= start ? Last(cutoff) : null;
|
||||
var future = day > until;
|
||||
result.Add(new(day, dayEnd, !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null,
|
||||
future ? null : cumulative, day == CalendarDays.Start(now, zone), future));
|
||||
}
|
||||
return result.ToArray();
|
||||
double? Last(DateTimeOffset time) => points.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<LimitWindow> Instance(LimitWindow window, IEnumerable<LimitWindow> samples) =>
|
||||
samples.Where(s => SameInstance(window, s) &&
|
||||
double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ public static class Pace
|
||||
var state = delta >= threshold ? PaceState.Ahead :
|
||||
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
|
||||
DateTimeOffset? projection = null;
|
||||
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0)
|
||||
if (delta > 0 && window.UsedPercent > 0 && elapsed > 0)
|
||||
{
|
||||
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
|
||||
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
|
||||
|
||||
@@ -53,8 +53,10 @@ public static class SettingsFile
|
||||
var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
|
||||
if (value is { IsValid: true }) return value;
|
||||
}
|
||||
catch (FileNotFoundException) { return new(); }
|
||||
catch (DirectoryNotFoundException) { return new(); }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
|
||||
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults.");
|
||||
diagnostics.Add(null, "settings-defaults", "Settings invalid or unreadable; using defaults.");
|
||||
return new();
|
||||
}
|
||||
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
|
||||
|
||||
Reference in New Issue
Block a user