Files
schmidt.florian 0a08b508a2 core: plan the daily budget per day, start forecasts at 2 % and follow the limit week (#15)
The developer's feedback of 2026-10-18 named four problems at the top
of the panel: late forecasts, a daily budget that shrank with every use,
unequal Claude and Codex tiles, and an unclear "This week".

- Core: forecasts start at 2 % of a window (D7). Each day of a long
  instance has a share, an even pace and a budget. Today's budget starts
  from the use at the start of the day and stays put while today is
  spent. An estimated start-of-day use counts only the whole hours before
  the first sample's hour, so later samples and tokens do not move it.
  Week token totals follow the provider's limit week, with the calendar
  week as the named fallback; the snapshot carries `weekStart` and
  `weekWindow` (D9).
- App: tiles of one window kind show the same rows, with muted
  placeholders that say why (D8). The stale warning sits in the Used row.
  Week charts draw even pace and budget as steps per day, mark the
  instance start and reset, and label full-day rates. Token tiles say
  since when.
- CLI: prints which week it uses and since when.

Closes #13
2026-10-18 10:53:00 +02:00

169 lines
9.9 KiB
C#

using Xunit;
namespace FinalToken.Core.Tests;
public sealed class LimitAnalysisTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(double use = 60) => new(Provider.Claude, "week", "Week", use,
Now.AddDays(3.5), TimeSpan.FromDays(7), Now, "fixture");
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void MinuteDriftAcrossMidnightKeepsDaysRecentRateAndPreviousWeek(int minutes)
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var w = Window() with { ResetsAt = new DateTimeOffset(2026, 10, 18, 20, 0, 0, TimeSpan.Zero) };
LimitWindow[] samples =
[
w with { SampleTime = Now.AddDays(-2).AddHours(9), UsedPercent = 30, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-15), UsedPercent = 40, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-6), UsedPercent = 50, ResetsAt = w.ResetsAt!.Value.AddMinutes(-minutes) },
w with { SampleTime = Now.AddDays(-3).AddHours(7), UsedPercent = 90, ResetsAt = w.ResetsAt!.Value.AddDays(-7) }
];
var days = LimitAnalysis.Days(w, samples, Now, zone)!;
Assert.Equal(20, days.Today);
Assert.Equal(20, Assert.Single(days.Current, d => d.IsToday).Used);
Assert.Equal(10, Assert.Single(days.Current, d => d.Start == CalendarDays.Start(Now.AddDays(-1), zone)).Used);
Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
var recent = LimitAnalysis.Recent(w, samples, Now);
Assert.NotNull(recent); Assert.Equal(20, recent.Increase); Assert.Equal(32, recent.PercentPerDay);
Assert.Equal(Now.AddDays(1.25), recent.ReachesLimit);
}
[Fact] public void RealWeekResetStartsAtZeroAndKeepsOldWeekSeparate()
{
var old = Window() with { UsedPercent = 90, SampleTime = Window().ResetsAt!.Value.AddHours(-3) };
var now = old.ResetsAt!.Value.AddHours(1);
var current = old with { ResetsAt = old.ResetsAt.Value.AddDays(7), SampleTime = now, UsedPercent = 5 };
var days = LimitAnalysis.Days(current, [old], now, TimeZoneInfo.Utc)!;
Assert.Equal(5, days.Today); Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
Assert.Null(LimitAnalysis.Recent(current, [old], now));
}
[Theory]
[InlineData(-900, true)]
[InlineData(900, true)]
[InlineData(-901, false)]
[InlineData(901, false)]
[InlineData(604800, false)]
public void InstanceToleranceIsInclusiveAndKeepsWindowAndProviderIdentity(int seconds, bool same)
{
var window = Window();
var other = window with { ResetsAt = window.ResetsAt!.Value.AddSeconds(seconds) };
Assert.Equal(same, LimitAnalysis.SameInstance(window, other));
Assert.Equal(same, LimitAnalysis.SameInstance(other, window));
Assert.False(LimitAnalysis.SameInstance(window, window with { Id = "session" }));
Assert.False(LimitAnalysis.SameInstance(window, window with { Provider = Provider.Codex }));
Assert.False(LimitAnalysis.SameInstance(window with { ResetsAt = null }, window with { ResetsAt = null }));
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void SessionRecentRateSurvivesMinuteDriftAcrossMidnight(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 2, 0, 0, TimeSpan.Zero);
var session = new LimitWindow(Provider.Claude, "session", "Session", 30, now.AddHours(2), TimeSpan.FromHours(5), now, "fixture");
var samples = new[] { session with { UsedPercent = 0, SampleTime = now.AddHours(-3), ResetsAt = session.ResetsAt!.Value.AddMinutes(minutes) },
session with { UsedPercent = 10, SampleTime = now.AddHours(-2), ResetsAt = session.ResetsAt!.Value.AddMinutes(-minutes) } };
var recent = LimitAnalysis.Recent(session, samples, now);
Assert.NotNull(recent); Assert.Equal(240, recent.PercentPerDay); Assert.Equal(50, recent.UseAtReset);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void LateSampleDeduplicatesAgainstDriftingChronologicalNeighbour(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var window = Window();
store.AddLimits([window with { SampleTime = Now.AddHours(2) }]);
store.AddLimits([window with { SampleTime = Now.AddHours(1), UsedPercent = 50 }]);
store.AddLimits([window with { SampleTime = Now.AddMinutes(115), ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) }]);
Assert.Equal(2, store.LimitSamples(window.Provider, window.Id, Now, Now.AddHours(3)).Count);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void UnchangedDriftingResetKeepsHourlySamplingAndLatestMetadata(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var w = Window();
store.AddLimits([w]);
var drifted = w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes), SampleTime = Now.AddMinutes(5) };
store.AddLimits([drifted]);
Assert.Single(store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)));
Assert.Equal(drifted.ResetsAt, Assert.Single(store.LatestLimits(w.Provider)).ResetsAt);
store.AddLimits([drifted with { UsedPercent = 61, SampleTime = Now.AddMinutes(10) }]);
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(7), SampleTime = Now.AddMinutes(15), UsedPercent = 61 }]);
Assert.Equal(3, store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)).Count);
}
[Fact] public void AverageAndRecentAreIndependent()
{
var w = Window();
Assert.Equal(120, LimitAnalysis.AverageUseAtReset(w, Now));
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-12), UsedPercent = 50 }], Now);
Assert.NotNull(recent); Assert.Equal(20, recent.PercentPerDay); Assert.Equal(130, recent.UseAtReset);
Assert.Equal(Now.AddDays(2), recent.ReachesLimit);
}
[Fact] public void RecentRequiresThreeHoursOfSameResetAndLast24Hours()
{
var w = Window();
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-2), UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), ResetsAt = Now, UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-25), UsedPercent = 40 }], Now));
Assert.NotNull(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-3), UsedPercent = 40 }], Now));
}
[Fact] public void FlatRecentRateHasNoLimitDateAndDecreasingSamplesAreUnknown()
{
var w = Window();
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4) }], Now);
Assert.NotNull(recent); Assert.Equal(60, recent.UseAtReset); Assert.Null(recent.ReachesLimit);
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), UsedPercent = 70 }], Now));
}
[Fact] public void DaysUsePriorSampleAndKeepUnknownBaselinesUnknown()
{
var w = Window();
var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!;
Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(49d / 4, days.TodayBudget);
Assert.Contains(days.Current, d => d.IsFuture && d.Used is null);
Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && d.Used is null);
Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today);
}
[Fact] public void FirstDayStartsAtZeroAndPreviousInstanceIsReturned()
{
var w = Window() with { ResetsAt = Now.AddDays(7).AddHours(-2) };
var previous = w with { ResetsAt = w.ResetsAt!.Value.AddDays(-7), SampleTime = Now.AddHours(-3), UsedPercent = 80 };
var days = LimitAnalysis.Days(w, [previous], Now, TimeZoneInfo.Utc)!;
Assert.Equal(60, days.Today); Assert.NotEmpty(days.Previous);
Assert.Null(LimitAnalysis.Days(w with { Length = TimeSpan.FromHours(5) }, [], Now));
}
[Theory]
[InlineData("Europe/Berlin", 2026, 3, 29, 23)]
[InlineData("Europe/Berlin", 2026, 10, 25, 25)]
[InlineData("America/Santiago", 2026, 9, 6, 23)]
public void DaysFollowCalendarIncludingMissingMidnight(string id, int year, int month, int day, int hours)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(id);
var start = CalendarDays.Start(new DateTime(year, month, day), zone);
var now = start.AddHours(12);
var w = Window() with { ResetsAt = start.AddDays(5), SampleTime = now };
var days = LimitAnalysis.Days(w, [w with { SampleTime = start.AddHours(-1), UsedPercent = 50 }], now, zone)!;
var today = Assert.Single(days.Current, d => d.IsToday);
Assert.Equal(hours, (today.End - today.Start).TotalHours); Assert.Equal(10, today.Used);
}
[Fact] public void ModelSeriesGroupsInOnePassAndMatchesTotals()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog(), new TestClock());
store.Add(new(Provider.Claude, Now.AddHours(-2), "a", "p", new(Total: 20), "a"));
store.Add(new(Provider.Claude, Now.AddHours(-2), "b", "p", new(Total: 30), "b"));
store.Add(new(Provider.Claude, Now.AddHours(-1), "a", "p", new(Total: 40), "c"));
store.Add(new(Provider.Codex, Now.AddHours(-1), "a", "p", new(Total: 900), "d"));
var points = store.TokenSeriesByModel(Provider.Claude, Now.AddDays(-1), Now, SeriesInterval.Day, TimeZoneInfo.Utc);
Assert.Equal(2, points.Count); Assert.Equal(90, points.Sum(p => p.Counts.Total));
Assert.Equal(60, points.Single(p => p.Model == "a").Counts.Total);
}
}