app: show the reset history of each long limit window (#16)

The developer asked for a detailed breakdown of every reset (feedback of
2026-10-18). Limits do not only reset at the end of their week: most Codex
weeks in the local history ended early.

- Core: a limit's samples form a window series (provider, limit name and
  length), so the history follows Codex's week across slots (D7). Instance
  spans are built once. One backward walk gives each instance, real or
  inferred, the start of the instance after it. The hour that holds a
  boundary goes to the instance that starts in it, or else to the one that
  ends in it (#9). A stale sample that would put its instance after a later
  one is ignored. The reset history lists the real instances with their
  figures, totals and early-reset hours (D12). API value uses a dated list
  price table; unknown models stay unpriced (D13).
- App: a Resets section per long window with totals, a timeline of
  burn-ups side by side with skipped time in lanes below, early resets by
  hour and weekday, and a sortable table (D8). The reset tooltip lists
  every model with its tokens and API value. Tall tooltips open beside the
  pointer, and Fluent's 320 px tooltip cap no longer wraps data values.
- Docs: D12 and D13 are new; D7 and D8 cover window series, boundary
  hours and the Resets section.

Closes #14
Closes #9
This commit was merged in pull request #16.
This commit is contained in:
2026-10-18 11:12:38 +02:00
parent 0a08b508a2
commit 82fece85f5
29 changed files with 1570 additions and 137 deletions
@@ -0,0 +1,232 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ResetHistoryTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero);
private static readonly TimeSpan Week = TimeSpan.FromDays(7);
private static LimitWindow Window(DateTimeOffset start, double used = 50, double sampleHour = 1) =>
new(Provider.Codex, "codex:primary", "Week", used, start + Week, Week, start.AddHours(sampleHour), "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 1_000_000, string model = "gpt-6.1-sol") =>
new(time, model, new(Input: input, Total: input));
private static ResetHistory History(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens,
DateTimeOffset? from = null, DateTimeOffset? now = null, TimeZoneInfo? zone = null) =>
LimitAnalysis.Resets(current, samples, tokens, from ?? DateTimeOffset.MinValue, now ?? current.SampleTime, zone ?? TimeZoneInfo.Utc);
[Fact] public void SeriesMergesCodexSlotsButSeparatesLengthsNamesAndProviders()
{
var week = Window(Day);
Assert.True(LimitAnalysis.SameInstance(week, week with { Id = "codex:secondary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Length = TimeSpan.FromHours(5) }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Id = "codex_bengalfox:primary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Provider = Provider.Claude }));
var previous = Window(Day - Week, 30) with { Id = "codex:secondary" };
var wrong = previous with { Id = week.Id, Length = TimeSpan.FromHours(5), UsedPercent = 99 };
var other = previous with { Id = "codex_bengalfox:secondary", UsedPercent = 98 };
var analysis = LimitAnalysis.Analyze(week, [previous, wrong, other], [], week.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(30, Assert.Single(analysis.Past).Peak);
Assert.Equal(30, History(week, [previous, wrong, other], []).Instances[1].Final.Used);
Assert.Null(LimitAnalysis.Recent(week, [week with { Length = TimeSpan.FromHours(5), UsedPercent = 0, SampleTime = week.SampleTime.AddHours(-4) }], week.SampleTime));
}
[Fact] public void StoreSeriesQueryKeepsTheOriginalIdQueryWorking()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var week = Window(Day);
var moved = week with { Id = "codex:secondary", SampleTime = week.SampleTime.AddHours(-1) };
var shortWindow = week with { Length = TimeSpan.FromHours(5) };
store.AddLimits([moved, shortWindow, week]);
Assert.Equal(3, store.LimitSamples(Provider.Codex, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(week, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(Provider.Codex, week.Id, Day, Day.AddDays(1)).Count);
}
[Theory]
[InlineData("claude-haiku-4-5")]
[InlineData("claude-haiku-4-5-20251001")]
public void PriceMatchesExactAndDatedModel(string model) => Assert.Equal(1, ApiPrices.Find(Provider.Claude, model)!.Input);
[Theory]
[InlineData("codex-auto-review")]
[InlineData("gpt-6.1-sol-latest")]
[InlineData("gpt-6.1-sol-20261301")]
[InlineData("gpt-6.1-sol-20261018-extra")]
[InlineData(null)]
public void UnknownModelHasNoValue(string? model) => Assert.Null(ApiPrices.Value(Provider.Codex, model, new(Input: 100)));
[Fact] public void ProviderValuesDoNotDoubleCountTokenSubsets()
{
var counts = new TokenCounts(1_000_000, 400_000, 200_000, 100_000, 80_000);
Assert.Equal(17.6m, ApiPrices.Value(Provider.Claude, "claude-fable-5-1", counts));
Assert.Equal(2.24m, ApiPrices.Value(Provider.Codex, "gpt-6.1-sol", counts));
Assert.Null(ApiPrices.Find(Provider.Claude, "gpt-6.1-sol"));
}
[Fact] public void OnTimeEarlyAndRunningInstancesHaveOwnValuesAndTotals()
{
var first = Window(Day, 40);
var second = Window(Day + Week, 50);
var current = Window(Day.AddDays(9), 20);
var history = History(current, [first, second], [Token(Day), Token(second.ResetsAt!.Value - Week), Token(Day.AddDays(9))]);
Assert.Equal(3, history.Instances.Count);
var running = history.Instances[0]; var early = history.Instances[1]; var onTime = history.Instances[2];
Assert.True(running.Running); Assert.Null(running.Unused); Assert.Null(running.Gift);
Assert.Equal(TimeSpan.FromHours(1), running.Duration); Assert.Equal(current.SampleTime, running.End);
Assert.False(onTime.Early); Assert.Equal(Week, onTime.Duration); Assert.Equal(60, onTime.Unused!.Percent);
Assert.True(early.Early); Assert.Equal(TimeSpan.FromDays(2), early.Duration); Assert.Equal(TimeSpan.FromDays(5), early.Skipped);
Assert.Equal(100d * 5 / 7, early.Gift!.Percent, 8); Assert.Equal(50, early.Unused!.Percent);
Assert.Equal(20_000, early.ValuePerPercent!.Tokens); Assert.Equal(.04m, early.ValuePerPercent.ApiValue);
Assert.Equal(PercentBasis.OwnInstance, early.ValuePerPercent.Basis);
Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue);
Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early);
Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue);
Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(4.5), history.MedianDuration);
Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped);
}
[Fact] public void RunningInstanceHasNoFinishedDurationOrResetValues()
{
var history = History(Window(Day), [], []);
Assert.True(Assert.Single(history.Instances).Running);
Assert.Equal(0, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Null(history.MedianDuration);
Assert.Null(history.Instances[0].Unused); Assert.Null(history.Instances[0].Gift);
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void OnTimeFinishedInstancesHaveNoEarlyResetAndExcludeRunningDurationFromMedian()
{
var history = History(Window(Day + Week * 2), [Window(Day), Window(Day + Week)], []);
Assert.Equal(2, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Equal(Week, history.MedianDuration);
Assert.All(history.Instances.Where(r => !r.Running), row => Assert.NotNull(row.Unused));
Assert.All(history.Instances, row => Assert.Null(row.Gift));
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void LowUseUsesMedianOfQualifyingListedInstances()
{
var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4);
var result = History(current, [first, second], [Token(Day), Token(Day + Week), Token(Day + Week * 2)]);
var rate = result.Instances[0].ValuePerPercent!;
Assert.Equal(30_000, rate.Tokens); Assert.Equal(.06m, rate.ApiValue); Assert.Equal(PercentBasis.SeriesMedian, rate.Basis);
var onlyLow = History(current, [first, second], [Token(Day + Week * 2)], from: current.ResetsAt!.Value - Week);
Assert.Null(Assert.Single(onlyLow.Instances).ValuePerPercent);
}
[Fact] public void NoQualifyingInstanceKeepsOnlyUnusedAndGiftPercent()
{
var old = Window(Day, 4); var current = Window(Day.AddDays(2), 0);
var row = History(current, [old], []).Instances[1];
Assert.Null(row.ValuePerPercent); Assert.Equal(96, row.Unused!.Percent);
Assert.Null(row.Unused.Tokens); Assert.Null(row.Unused.ApiValue); Assert.Null(row.Gift!.Tokens);
}
[Fact] public void ReachedLimitAndTimeAtLimitReuseTheBurnUpIncludingEstimates()
{
var old = Window(Day, 50); var current = Window(Day + Week, 20);
var tokens = new[] { Token(Day), Token(Day.AddHours(2), 2_000_000), Token(Day + Week) };
var row = History(current, [old], tokens).Instances[1];
var analysis = LimitAnalysis.Analyze(current, [old], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(analysis.Past[0].Points, row.BurnUp.Points);
Assert.Equal(100, row.Peak); Assert.Equal(100, row.Final.Used); Assert.Equal(UseOrigin.Estimated, row.Final.Origin);
Assert.Equal(Day.AddHours(2.5), row.ReachedLimit);
Assert.Equal(Week - TimeSpan.FromHours(2.5), row.TimeAtLimit);
Assert.Equal(0, row.Unused!.Percent);
var measured = History(current, [old with { UsedPercent = 100 }], [Token(Day), Token(Day + Week)]).Instances[1];
Assert.Equal(old.SampleTime, measured.ReachedLimit); Assert.Equal(UseOrigin.Measured, measured.BurnUp.ReachedOrigin);
}
[Theory]
[InlineData(0, false)]
[InlineData(20, false)]
[InlineData(50, true)]
public void RealWeekKeepsItsEndHourOnlyWhenTheInferredSuccessorStartsInALaterHour(int gapMinutes, bool ownsEndHour)
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var currentStart = start + Week * 2 + TimeSpan.FromMinutes(gapMinutes);
var current = Window(currentStart, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(currentStart.AddMinutes(-currentStart.Minute), 100)];
var analysis = LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
var past = Assert.Single(analysis.Past, p => p.Start == start);
Assert.Equal(ownsEndHour ? 75 : 50, past.Points[^1].Used);
var history = History(current, [previous], tokens);
var row = Assert.Single(history.Instances, r => r.Start == start);
Assert.Equal(past.Points, row.BurnUp.Points);
Assert.Equal(ownsEndHour ? 150 : 100, row.Tokens.Total);
Assert.Equal(row.Tokens, Assert.Single(row.Models).Tokens);
Assert.Equal(previous.ResetsAt, row.End); Assert.False(row.Early);
Assert.Equal(2, history.Instances.Count);
}
[Fact] public void ResetHistoryUsesInferredSuccessorsBeyondTheEightPastChartInstances()
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var current = Window(start + Week * 11, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(Day + Week * 11, 100)];
var row = Assert.Single(History(current, [previous], tokens).Instances, r => r.Start == start);
Assert.Equal(100, row.Tokens.Total); Assert.Equal(50, row.Final.Used);
Assert.Equal(2, History(current, [previous], tokens).Instances.Count);
}
[Fact] public void FamilyFilterAndUnpricedModelsAreExplicit()
{
var current = Window(Day, 20) with { Provider = Provider.Claude, Id = "fable", Label = "Week (Fable)" };
var row = Assert.Single(History(current, [], [Token(Day, 100, "claude-fable-5"), Token(Day, 200, "claude-fable-new"),
Token(Day, 10_000, "claude-sonnet-5")]).Instances);
Assert.Equal(300, row.Tokens.Total); Assert.Equal(200, row.UnpricedTokens); Assert.Equal(.001m, row.ApiValue);
Assert.Equal(2, row.Models.Count);
var zero = Assert.Single(History(current with { UsedPercent = 0 }, [], [Token(Day, 100, "claude-sonnet-5")]).Instances);
Assert.Equal(0, zero.Tokens.Total); Assert.Null(zero.ApiValue); Assert.Null(zero.ValuePerPercent);
}
[Fact] public void RangeIncludesWholeOverlappingRealInstanceAndLeavesInferredOnesOut()
{
var old = Window(Day, 30); var current = Window(Day + Week * 2, 20);
var result = History(current, [old], [Token(Day), Token(Day + Week), Token(Day + Week * 2)], from: Day.AddDays(3));
Assert.Equal(2, result.Instances.Count); Assert.Equal(Day, result.Instances[1].Start);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.Single(History(current, [old], [], from: Day + Week).Instances);
Assert.Equal(old.SampleTime, result.FirstSample);
}
[Fact] public void JitterAndInterleavedOldRolloutAfterEarlyResetDoNotCreateAnotherInstance()
{
var transition = Day.AddHours(10).AddMinutes(48).AddSeconds(56);
var old = Window(Day.AddDays(-2), 90);
var current = Window(transition, 2);
var newFirst = current with { SampleTime = transition, UsedPercent = 0, ResetsAt = current.ResetsAt!.Value.AddSeconds(-11) };
var stale = old with { SampleTime = transition.AddSeconds(4), UsedPercent = 98, ResetsAt = old.ResetsAt!.Value.AddSeconds(9) };
var jitter = old with { SampleTime = old.SampleTime.AddHours(1), UsedPercent = 95, ResetsAt = old.ResetsAt.Value.AddSeconds(11) };
var result = History(current, [old, jitter, newFirst, stale], [Token(Day.AddDays(-2)), Token(Day.AddHours(10))]);
Assert.Equal(2, result.Instances.Count); Assert.Equal(95, result.Instances[1].Final.Used);
Assert.Equal(transition, result.Instances[1].End); Assert.Equal(1_000_000, result.Instances[0].Tokens.Total);
Assert.Equal(jitter.ResetsAt, result.Instances[1].Reset);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.DoesNotContain(result.Instances[1].BurnUp.Points, p => p.Used == 98);
}
[Fact] public void HistogramsUseLocalEndHourAndMondayBasedWeekday()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +03", TimeSpan.FromHours(3), "Fixture", "Fixture");
var old = Window(Day); var transition = Day.AddDays(1).AddHours(22); // Saturday locally.
var result = History(Window(transition), [old], [], zone: zone);
Assert.Equal(1, result.EarlyByHour[1]); Assert.Equal(1, result.EarlyByHour.Sum());
Assert.Equal(1, result.EarlyByWeekday[5]); Assert.Equal(1, result.EarlyByWeekday.Sum());
}
[Theory]
[InlineData(15, false)]
[InlineData(16, true)]
public void EarlyThresholdIsStrictlyMoreThanFifteenMinutes(int minutes, bool early)
{
var old = Window(Day); var next = Window(Day + Week - TimeSpan.FromMinutes(minutes));
Assert.Equal(early, History(next, [old], []).Instances[1].Early);
}
}