app: redesign the panel and add limit forecasts and daily week use #6

Merged
schmidt.florian merged 14 commits from 5-panel-redesign into master 2026-10-15 19:06:05 +02:00
6 changed files with 346 additions and 40 deletions
Showing only changes of commit e687a40346 - Show all commits
+1
View File
@@ -45,6 +45,7 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
Codex replay protection uses the last session timestamp and cumulative counts, with no Codex replay protection uses the last session timestamp and cumulative counts, with no
per-event dedupe keys. A later counter reset still permits subsequent increases. per-event dedupe keys. A later counter reset still permits subsequent increases.
- Store changed percent/reset samples and at most one unchanged sample per window per hour. - Store changed percent/reset samples and at most one unchanged sample per window per hour.
A reset that moves within 15 minutes is unchanged for sampling and instance identity (D7).
Late observations from archived files use neighbouring timestamps so they keep real changes Late observations from archived files use neighbouring timestamps so they keep real changes
without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have
a per-window time index for ordered lookup. a per-window time index for ordered lookup.
+7 -39
View File
@@ -3,12 +3,12 @@ namespace FinalToken.Core;
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit, public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
double Increase = 0, TimeSpan Span = default); double Increase = 0, TimeSpan Span = default);
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative, public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative,
bool IsToday, bool IsFuture); bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured);
public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous, public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous,
double? Today, double EvenPace, double? DailyBudget); double? Today, double EvenPace, double? DailyBudget, UseOrigin TodayOrigin = UseOrigin.Measured);
/// <summary>Pure D7 calculations. Missing historical baselines stay unknown rather than inventing use.</summary> /// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary>
public static class LimitAnalysis public static partial class LimitAnalysis
{ {
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary> /// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
public static bool SameInstance(LimitWindow first, LimitWindow second) => public static bool SameInstance(LimitWindow first, LimitWindow second) =>
@@ -19,12 +19,12 @@ public static class LimitAnalysis
public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now) public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now)
{ {
var pace = Pace.Calculate(window, now); var pace = Pace.Calculate(window, now);
return pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : null; return Pace.CanForecast(window, now) && pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : null;
} }
public static RateForecast? Recent(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now) 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 || if (!Pace.CanForecast(window, now) || window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || reset <= now ||
Pace.Calculate(window, now).State == PaceState.Unknown) return null; Pace.Calculate(window, now).State == PaceState.Unknown) return null;
var points = Instance(window, samples).Append(window).Where(s => s.SampleTime >= now.AddHours(-24) && 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(); s.SampleTime >= reset - length && s.SampleTime <= now).OrderBy(s => s.SampleTime).ToArray();
@@ -41,39 +41,7 @@ public static class LimitAnalysis
} }
public static WindowDays? Days(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, TimeZoneInfo? zone = null) public static WindowDays? Days(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, TimeZoneInfo? zone = null)
{ => Analyze(window, samples, [], now, zone)?.Days;
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) => private static IEnumerable<LimitWindow> Instance(LimitWindow window, IEnumerable<LimitWindow> samples) =>
samples.Where(s => SameInstance(window, s) && samples.Where(s => SameInstance(window, s) &&
+143
View File
@@ -0,0 +1,143 @@
namespace FinalToken.Core;
public enum UseOrigin { Measured, Estimated }
public sealed record LimitPoint(DateTimeOffset Time, double Used, UseOrigin Origin);
public sealed record LimitInstance(DateTimeOffset Start, DateTimeOffset Reset, IReadOnlyList<LimitPoint> Points,
IReadOnlyList<LimitDay> Days, double? Scale, double? Peak, DateTimeOffset? ReachedLimit, DateTimeOffset? EndedAt = null, UseOrigin? ReachedOrigin = null)
{
public DateTimeOffset End => EndedAt ?? Reset;
public bool HasData => Points.Count > 1;
}
public sealed record LimitEstimate(LimitInstance Current, IReadOnlyList<LimitInstance> Past, WindowDays? Days)
{
public LimitInstance? Previous => Past.FirstOrDefault();
}
public static partial class LimitAnalysis
{
private static DateTimeOffset Hour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
/// <summary>D7: pure estimates from hourly token buckets, calibrated to the newest sample.
/// Boundary hours are included as in D5; estimates cannot recover sub-hour token timing.</summary>
public static LimitEstimate? Analyze(LimitWindow window, IEnumerable<LimitWindow> samples,
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset now, TimeZoneInfo? zone = null)
{
if (window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || Pace.Calculate(window, now).State == PaceState.Unknown) return null;
zone ??= TimeZoneInfo.Local;
var observations = samples.Append(window).Where(s => s.Provider == window.Provider && s.Id == window.Id &&
s.ResetsAt is not null && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100).OrderBy(s => s.SampleTime).ToArray();
var weighted = tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time)
.Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))).OrderBy(p => p.Time).ToArray();
// Order real instances by observations, not by resets: a replacement can begin early.
var groups = new List<List<LimitWindow>> { new() { window } };
foreach (var observation in observations)
{
var group = groups.FirstOrDefault(g => SameInstance(g[0], observation));
if (group is null) groups.Add([observation]); else group.Add(observation);
}
var spans = groups.Select(g =>
{
var anchor = SameInstance(g[0], window) ? window : g[^1];
return (Anchor: anchor, First: g.Min(s => s.SampleTime), Start: anchor.ResetsAt!.Value - length);
}).OrderBy(g => g.First).ToArray();
for (var i = 1; i < spans.Length; i++)
if (spans[i - 1].Anchor.ResetsAt > spans[i].Start.AddMinutes(15))
spans[i].Start = spans[i].First;
var currentSpan = spans.Single(g => SameInstance(g.Anchor, window));
var current = Build(window, currentSpan.Start, reset, now < reset ? now : reset, null);
var past = new List<LimitInstance>();
var cursor = currentSpan;
for (var i = 0; i < 8; i++)
{
var previous = spans.LastOrDefault(g => g.First < cursor.First);
var known = previous.Anchor is not null && previous.Anchor.ResetsAt >= cursor.Start.AddMinutes(-15);
var anchor = known ? previous.Anchor! : window with { ResetsAt = cursor.Start };
var start = known ? previous.Start : cursor.Start - length;
var first = known ? previous.First : start;
var end = anchor.ResetsAt!.Value < cursor.First ? anchor.ResetsAt.Value : cursor.First;
// Whole boundary hours have one owner (D5): the next instance owns its starting hour.
var tokenEnd = end < cursor.Start ? end : cursor.Start;
var instance = Build(anchor, start, end, end < now ? end : now, current.Scale, tokenEnd);
if (instance.HasData) past.Add(instance);
cursor = (anchor, first, start);
}
WindowDays? days = null;
if (length > TimeSpan.FromDays(1))
{
var today = current.Days.FirstOrDefault(d => d.IsToday);
days = new(current.Days, past.FirstOrDefault()?.Days ?? [], today?.Used, 100 / length.TotalDays,
reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured);
}
return new(current, past, days);
LimitInstance Build(LimitWindow anchor, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until,
double? fallback, DateTimeOffset? tokenEnd = null)
{
double Weight(DateTimeOffset from, DateTimeOffset to)
{
var hour = Hour(from < start ? start : from);
var exclusiveEnd = Hour(tokenEnd ?? end);
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight);
}
var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until)
.GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray();
var last = measured.LastOrDefault();
var denominator = last is null ? 0 : Weight(start, last.SampleTime);
var total = Weight(start, until);
double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback;
var points = new SortedDictionary<DateTimeOffset, LimitPoint> { [start] = new(start, 0, UseOrigin.Measured) };
if (scale is { } k)
{
foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < Hour(tokenEnd ?? end)).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct())
{
var cutoff = time < until ? time : until;
if (cutoff <= start) continue;
// Samples own the measured span; tokens fill before the first sample and after the last.
if (measured.Length == 0 || cutoff < measured[0].SampleTime)
points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated);
else if (last is not null && cutoff > last.SampleTime)
points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated);
}
}
foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured);
DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null;
var raw = points.Values.OrderBy(p => p.Time).ToArray();
for (var i = 1; i < raw.Length; i++)
{
var point = raw[i]; var prior = raw[i - 1];
if (reached is null && point.Used >= 100)
{
reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time
: prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1)));
reachedOrigin = point.Origin;
if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated);
}
if (point.Origin == UseOrigin.Estimated)
points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) };
}
double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached
? 100 : Math.Min(100, factor * Weight(start, time));
var daily = 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 future = day > until;
var baseline = day <= start ? 0 : Last(day);
var cumulative = cutoff >= start ? Last(cutoff) : null;
if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null;
double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null;
var origin = UseOrigin.Measured;
if (!future && use is null && scale is { } factor)
{
use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated;
cumulative ??= EstimatedAt(cutoff, factor);
}
daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin));
}
var series = points.Values.OrderBy(p => p.Time).ToArray();
double? peak = series.Length > 1 ? series.Max(p => p.Used) : null;
return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin);
double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
}
}
}
+6 -1
View File
@@ -2,6 +2,11 @@ namespace FinalToken.Core;
public static class Pace public static class Pace
{ {
// D7: use ticks at the boundary so exactly 10% is eligible despite floating-point rounding.
public static bool CanForecast(LimitWindow window, DateTimeOffset now) =>
window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset &&
reset - now <= TimeSpan.FromTicks(length.Ticks - length.Ticks / 10);
// D7. A reset in the past clamps elapsed to one; it never has a future projection. // D7. A reset in the past clamps elapsed to one; it never has a future projection.
public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10) public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10)
{ {
@@ -14,7 +19,7 @@ public static class Pace
var state = delta >= threshold ? PaceState.Ahead : var state = delta >= threshold ? PaceState.Ahead :
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack; delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
DateTimeOffset? projection = null; DateTimeOffset? projection = null;
if (delta > 0 && window.UsedPercent > 0 && elapsed > 0) if (delta > 0 && window.UsedPercent > 0 && CanForecast(window, now))
{ {
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent; var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds); if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
+28
View File
@@ -0,0 +1,28 @@
namespace FinalToken.Core;
/// <summary>D7 price ratios. Reasoning is already included in output; Codex cached input is a subset of input.</summary>
public static class TokenWeights
{
public const double Input = 1;
public const double ClaudeOutput = 5;
public const double ClaudeCacheWrite = 1.25;
public const double CacheRead = 0.1;
public const double CodexOutput = 8;
private static readonly string[] ClaudeFamilies = ["Fable", "Opus", "Sonnet", "Haiku"];
public static double Weighted(Provider provider, TokenCounts counts) => provider == Provider.Claude
? Math.Max(0, counts.Input) * Input + Math.Max(0, counts.Output) * ClaudeOutput + Math.Max(0, counts.CacheWrite) * ClaudeCacheWrite + Math.Max(0, counts.CacheRead) * CacheRead
: Math.Max(0, counts.Input - counts.CacheRead) * Input + Math.Max(0, counts.CacheRead) * CacheRead + Math.Max(0, counts.Output) * CodexOutput;
public static string? Family(LimitWindow window)
{
// Provider labels expose the family in parentheses; the dashboard also uses a middle dot.
var label = window.Label;
var open = label.LastIndexOf('('); var close = label.LastIndexOf(')');
var separator = label.LastIndexOf('\u00b7');
var family = open >= 0 && close > open ? label[(open + 1)..close].Trim()
: separator >= 0 ? label[(separator + 1)..].Trim() : null;
if (family is { Length: > 0 } && !family.Equals("all models", StringComparison.OrdinalIgnoreCase) &&
!family.Equals("all", StringComparison.OrdinalIgnoreCase) && !char.IsDigit(family[0])) return family;
return ClaudeFamilies.FirstOrDefault(f => label.Contains(f, StringComparison.OrdinalIgnoreCase));
}
public static bool Matches(LimitWindow window, string? model) => Family(window) is not { } family || model?.Contains(family, StringComparison.OrdinalIgnoreCase) == true;
}
@@ -0,0 +1,161 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class TokenEstimateTests
{
private static readonly DateTimeOffset Start = new(2026, 10, 8, 0, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Now = Start.AddDays(6).AddHours(12);
private static LimitWindow Window => new(Provider.Claude, "week", "Week · all models", 65, Start.AddDays(7), TimeSpan.FromDays(7), Now, "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 100, string model = "claude-fable") => new(time, model, new(Input: input, Total: input));
private static ModelTokenPoint[] WeekTokens => Enumerable.Range(0, 6).Select(i => Token(Start.AddDays(i))).Append(Token(Start.AddDays(6), 50)).ToArray();
[Fact] public void ProviderWeightsDoNotDoubleCountCachedInputOrReasoning()
{
var counts = new TokenCounts(Input: 100, CacheRead: 40, CacheWrite: 20, Output: 10, ReasoningOutput: 8);
Assert.Equal(179, TokenWeights.Weighted(Provider.Claude, counts));
Assert.Equal(144, TokenWeights.Weighted(Provider.Codex, counts));
}
[Fact] public void NewestSampleCalibratesScaleAndDaysMixMeasuredAndEstimated()
{
var w = Window;
var baseline = w with { SampleTime = Start.AddDays(6), UsedPercent = 60 };
var result = LimitAnalysis.Analyze(w, [baseline], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Measured, result.Days.TodayOrigin);
Assert.Equal(10, result.Days.Current[0].Used); Assert.Equal(UseOrigin.Estimated, result.Days.Current[0].Origin);
Assert.Contains(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
Assert.Contains(result.Current.Points, p => p.Time == Now && p.Used == 65 && p.Origin == UseOrigin.Measured);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void DriftAndMissingBaselineFallBackToTokens(int drift)
{
var w = Window;
var result = LimitAnalysis.Analyze(w, [w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(drift), SampleTime = Now.AddHours(-2), UsedPercent = 64 }], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Estimated, result.Days.TodayOrigin);
Assert.Contains(result.Current.Points, p => p.Used == 64 && p.Origin == UseOrigin.Measured);
Assert.Equal(.1, result.Current.Scale);
}
[Fact] public void FamilyWindowUsesOnlyMatchingModelsCaseInsensitively()
{
var w = Window with { Label = "Current week (FABLE)", UsedPercent = 50 };
var tokens = new[] { Token(Start, 100, "claude-fable-5"), Token(Start, 10000, "claude-sonnet"), Token(Start, 10000, "unrelated") };
Assert.Equal(.5, LimitAnalysis.Analyze(w, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
Assert.Equal(50d / 20100, LimitAnalysis.Analyze(w with { Label = "Week" }, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Theory]
[InlineData("Current week (Cedar)")]
[InlineData("Week \u00b7 Cedar")]
public void FamilyNamesAreNotLimitedToKnownModelNames(string label)
{
var window = Window with { Label = label, UsedPercent = 50 };
ModelTokenPoint[] tokens = [Token(Start, 100, "claude-CEDAR-7"), Token(Start, 10000, "claude-fable")];
Assert.Equal(.5, LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Fact] public void FinishedInstancesUseOwnSampleOrCurrentScale()
{
var w = Window with { UsedPercent = 50 };
var tokens = new[] { Token(Start, 100), Token(Start.AddDays(-7), 100), Token(Start.AddDays(-14), 300) };
var previous = w with { ResetsAt = Start, SampleTime = Start.AddHours(-1), UsedPercent = 90 };
var result = LimitAnalysis.Analyze(w, [previous], tokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.5, result.Current.Scale); Assert.Equal(.9, result.Past[0].Scale); Assert.Equal(90, result.Past[0].Peak);
Assert.Equal(.5, result.Past[1].Scale); Assert.Equal(100, result.Past[1].Peak); Assert.NotNull(result.Past[1].ReachedLimit);
Assert.All(result.Past[1].Points.Skip(1), p => Assert.Equal(UseOrigin.Estimated, p.Origin));
}
[Fact] public void ExpiredInstanceNeverConsumesTokensFromTheNextWindow()
{
var window = Window;
var afterReset = window.ResetsAt!.Value.AddHours(1);
var tokens = WeekTokens.Append(Token(afterReset, 1000000)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, afterReset.AddHours(1), TimeZoneInfo.Utc)!;
Assert.All(result.Current.Points, p => Assert.True(p.Time <= window.ResetsAt));
Assert.Equal(65, result.Current.Peak);
}
[Fact] public void NewTokensAfterTheLastSampleAddOnlyTheNewBucket()
{
var window = Window with { SampleTime = Now.AddMinutes(-30) };
var tokens = WeekTokens.Append(Token(Now, 100)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, Now.AddMinutes(30), TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(75, result.Current.Points.Last().Used);
Assert.Equal(UseOrigin.Estimated, result.Current.Points.Last().Origin);
}
[Fact] public void EstimatesStopAtTheCrossingAndDailyUseCannotSpendTheLimitTwice()
{
var window = Window with { UsedPercent = 50 };
var pastStart = Start.AddDays(-7);
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 300), Token(pastStart.AddDays(1), 300)];
var result = LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.Equal(100, past.Peak);
Assert.Equal(pastStart.AddMinutes(40), past.ReachedLimit);
Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.All(past.Points, p => Assert.InRange(p.Used, 0, 100));
Assert.Contains(past.Points, p => p.Time == past.ReachedLimit && p.Used == 100);
Assert.Equal(100, past.Days.Sum(d => d.Used ?? 0));
Assert.Equal(0, past.Days[1].Used);
}
[Fact] public void MeasuredSamplesRemainUnchangedWhenLaterEstimatesReachTheLimit()
{
var window = Window;
var pastStart = Start.AddDays(-7);
var measured = window with { ResetsAt = Start, SampleTime = pastStart.AddHours(2), UsedPercent = 10 };
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 100), Token(pastStart.AddDays(1), 10000)];
var past = LimitAnalysis.Analyze(window, [measured], tokens, Now, TimeZoneInfo.Utc)!.Past[0];
Assert.Equal(100, past.Peak); Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.Equal(new(measured.SampleTime, 10, UseOrigin.Measured), past.Points.Single(p => p.Time == measured.SampleTime));
Assert.Equal(10, measured.UsedPercent);
Assert.Equal(pastStart.AddDays(1).AddMinutes(5.4), past.ReachedLimit);
Assert.All(past.Days, day => Assert.InRange(day.Used ?? 0, 0, 100));
Assert.Equal(100, past.Days.Sum(day => day.Used ?? 0));
}
[Fact] public void EarlyReplacementEndsThePreviousInstanceAndOwnsItsBoundaryHour()
{
var transition = new DateTimeOffset(2026, 10, 15, 8, 18, 0, TimeSpan.Zero);
var now = transition.AddHours(1);
var current = Window with { ResetsAt = transition.AddDays(7), SampleTime = now, UsedPercent = 2 };
var first = current with { SampleTime = transition, UsedPercent = 1 };
var previous = current with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 20 };
var previousStart = previous.ResetsAt!.Value - previous.Length!.Value;
ModelTokenPoint[] tokens = [Token(previousStart, 100), Token(transition.AddMinutes(-18), 100), Token(transition.AddMinutes(42), 1000)];
var result = LimitAnalysis.Analyze(current, [previous, first], tokens, now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.All(past.Points, p => Assert.True(p.Time <= transition));
Assert.All(past.Days, d => Assert.True(d.End <= transition));
Assert.Equal(transition, past.End);
Assert.Equal(previousStart, past.Start);
Assert.Equal(20, past.Points.Single(p => p.Time == previous.SampleTime).Used);
Assert.Equal(20, past.Peak);
Assert.Equal(2d / 1100, result.Current.Scale);
Assert.DoesNotContain(result.Past, p => p.Points.Any(v => v.Time > transition));
}
[Theory]
[InlineData(5)]
[InlineData(168)]
public void ForecastsBeginAtExactlyTenPercentWithoutChangingState(int hours)
{
var start = Start; var length = TimeSpan.FromHours(hours);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 10);
var before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 30 };
Assert.Equal(PaceState.Ahead, Pace.Calculate(window, before).State);
var pace = Pace.Calculate(window, before);
Assert.Null(pace.Projection);
var popup = new PopupDecider().Observe(window, pace, new Settings());
Assert.NotNull(popup); Assert.Null(popup.Projection);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, before));
Assert.Null(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], before));
window = window with { SampleTime = atThreshold };
Assert.NotNull(Pace.Calculate(window, atThreshold).Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, atThreshold));
if (hours == 168) Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], atThreshold));
}
[Fact] public void NoTokensMeansNoEstimates()
{
var result = LimitAnalysis.Analyze(Window, [], [], Now, TimeZoneInfo.Utc)!;
Assert.Null(result.Current.Scale); Assert.Null(result.Days!.Today); Assert.Empty(result.Past);
Assert.DoesNotContain(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
}
}