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
116 lines
7.4 KiB
C#
116 lines
7.4 KiB
C#
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 spans = RealSpans(window, samples, now);
|
|
var observations = spans.SelectMany(s => s.Samples).ToArray();
|
|
var weighted = WeightedTokens(window, tokens);
|
|
var currentSpan = spans.Single(g => SameInstance(g.Anchor, window));
|
|
var currentTokenEnd = TokenEnd(currentSpan.End, null);
|
|
var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End,
|
|
now < currentSpan.End ? now : currentSpan.End, null, currentTokenEnd, now, zone);
|
|
var past = new List<LimitInstance>();
|
|
foreach (var (span, successorStart) in SpansWithSuccessors(window, spans).Skip(1).Take(8))
|
|
{
|
|
var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End,
|
|
span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, successorStart), now, zone);
|
|
if (instance.HasData) past.Add(instance);
|
|
}
|
|
WindowDays? days = null;
|
|
if (length > TimeSpan.FromDays(1))
|
|
{
|
|
var today = current.Days.FirstOrDefault(d => d.IsToday);
|
|
days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, currentTokenEnd, now, zone);
|
|
}
|
|
return new(current, past, days);
|
|
}
|
|
|
|
private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList<LimitWindow> observations,
|
|
(DateTimeOffset Time, double Weight)[] weighted, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until,
|
|
double? fallback, DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone)
|
|
{
|
|
double Weight(DateTimeOffset from, DateTimeOffset to) => WeightedTokens(weighted, start, tokenEnd, from, to);
|
|
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 < tokenEnd).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;
|
|
}
|
|
}
|