diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index 4c23995..be6b081 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -1,5 +1,5 @@ # Core -UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. +UI-free domain and file/CLI integration. Implements D1–D7, D9 and D11–D13. Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock. Persisted defaults use settable properties: source-generated init-only property factories can overwrite initializers for missing JSON members. Treat settings as values; update them with `with`. @@ -28,6 +28,19 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root No shipped production dependency is needed in Core. Source parsers use temporary memory for one complete line; memory usage therefore scales with the largest transcript entry. +## Limit analysis + +- Use `WindowSeries` (provider, name, length) for all sample queries and instance membership (D7). + Codex `:primary` and `:secondary` suffixes identify slots, not limits. Read across ids with + `HistoryStore.LimitSamples(window, from, to)`; the original id query remains available. +- `LimitAnalysis` shares real spans and burn-up construction between `Analyze` and `Resets`. + Keep the current instance, ignore stale samples and leave gaps unassigned. A boundary hour + belongs to its starting instance, else to its ending instance (D7). +- Reset history lists only real instances overlapping the range, with whole-instance values (D12). + Percent values use the instance at final ≥ 5 %, else the qualifying listed-instance median. +- `ApiPrices` is the dated D13 list-price table. Match exact ids or a valid trailing date. + Unknown models remain unpriced; never infer a price from a family or count token subsets twice. + ## Store persistence and scaling - Refresh changes append as one durable, newline-terminated transaction to diff --git a/src/FinalToken.Core/ApiPrices.cs b/src/FinalToken.Core/ApiPrices.cs new file mode 100644 index 0000000..1f0ff45 --- /dev/null +++ b/src/FinalToken.Core/ApiPrices.cs @@ -0,0 +1,65 @@ +using System.Globalization; + +namespace FinalToken.Core; + +public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output); + +/// D13: USD per million tokens, checked 2026-10-18. Standard short-context prices. +/// https://platform.claude.com/docs/en/about-claude/pricing +/// https://developers.openai.com/api/docs/pricing +/// Claude writes use the 5-minute price; Haiku 5.5 assumes prompts up to 100K. +public static class ApiPrices +{ + public static DateOnly CheckedOn => new(2026, 10, 18); + private static readonly Dictionary Claude = new(StringComparer.Ordinal) + { + ["claude-fable-5-1"] = new(10, 12.50m, .25m, 50), + ["claude-fable-5"] = new(10, 12.50m, 1, 50), + ["claude-opus-5-5"] = new(4, 5, .20m, 20), + ["claude-opus-5"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-8"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-7"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-6"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-5"] = new(5, 6.25m, .50m, 25), + ["claude-sonnet-5-5"] = new(2, 2.50m, .10m, 10), + ["claude-sonnet-5"] = new(2, 2.50m, .20m, 10), + ["claude-sonnet-4-6"] = new(3, 3.75m, .30m, 15), + ["claude-sonnet-4-5"] = new(3, 3.75m, .30m, 15), + ["claude-haiku-5-5"] = new(.10m, .125m, .01m, .50m), + ["claude-haiku-4-5"] = new(1, 1.25m, .10m, 5) + }; + private static readonly Dictionary Codex = new(StringComparer.Ordinal) + { + ["gpt-6-astra"] = new(10, 0, 1, 50), + ["gpt-6.1-sol"] = new(2, 0, .10m, 10), + ["gpt-6-sol"] = new(2, 0, .20m, 10), + ["gpt-6-luna"] = new(.10m, 0, .01m, .50m), + ["gpt-5.6-sol"] = new(4, 0, .40m, 20), + ["gpt-5.6-terra"] = new(2, 0, .20m, 12), + ["gpt-5.6-luna"] = new(.20m, 0, .02m, 1.20m), + ["gpt-5.5"] = new(5, 0, .50m, 30), + ["gpt-5.4"] = new(2.50m, 0, .25m, 15), + ["gpt-5.4-mini"] = new(.75m, 0, .075m, 4.50m), + ["gpt-5.3-codex"] = new(1.75m, 0, .175m, 14), + ["gpt-5.2"] = new(1.75m, 0, .175m, 14), + ["gpt-5.1"] = new(1.25m, 0, .125m, 10), + ["gpt-5"] = new(1.25m, 0, .125m, 10) + }; + public static ApiPrice? Find(Provider provider, string? model) + { + if (model is null) return null; + var prices = provider == Provider.Claude ? Claude : Codex; + if (prices.TryGetValue(model, out var price)) return price; + return model.Length > 9 && model[^9] == '-' && + DateOnly.TryParseExact(model[^8..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) && + prices.TryGetValue(model[..^9], out price) ? price : null; + } + public static decimal? Value(Provider provider, string? model, TokenCounts counts) + { + if (Find(provider, model) is not { } p) return null; + var input = provider == Provider.Claude ? Math.Max(0, counts.Input) : Math.Max(0, counts.Input - counts.CacheRead); + return (input * p.Input + Math.Max(0, counts.CacheRead) * p.CacheRead + + (provider == Provider.Claude ? Math.Max(0, counts.CacheWrite) * p.CacheWrite : 0) + + Math.Max(0, counts.Output) * p.Output) / 1_000_000; + } +} diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 991a85b..9376244 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -212,6 +212,14 @@ public sealed class HistoryStore .Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to) .OrderBy(w => w.SampleTime).ToArray(); } + public IReadOnlyList LimitSamples(Provider provider, DateTimeOffset from, DateTimeOffset to) + { + lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits) + .Where(w => w.Provider == provider && w.SampleTime >= from && w.SampleTime < to) + .OrderBy(w => w.SampleTime).ToArray(); + } + public IReadOnlyList LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) => + LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray(); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) => TokenSeries(provider, from, to, interval, TimeZoneInfo.Local); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, diff --git a/src/FinalToken.Core/LimitAnalysis.cs b/src/FinalToken.Core/LimitAnalysis.cs index d4cd7f8..4a8c776 100644 --- a/src/FinalToken.Core/LimitAnalysis.cs +++ b/src/FinalToken.Core/LimitAnalysis.cs @@ -12,7 +12,7 @@ public static partial class LimitAnalysis { /// D7: minute-rounded probe resets may drift within 15 minutes in either direction. public static bool SameInstance(LimitWindow first, LimitWindow second) => - first.Provider == second.Provider && first.Id == second.Id && + WindowSeries.For(first) == WindowSeries.For(second) && first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset && (firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15); diff --git a/src/FinalToken.Core/LimitEstimates.cs b/src/FinalToken.Core/LimitEstimates.cs index 7fc0e0d..d64e0b5 100644 --- a/src/FinalToken.Core/LimitEstimates.cs +++ b/src/FinalToken.Core/LimitEstimates.cs @@ -24,26 +24,12 @@ public static partial class LimitAnalysis { 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.Length is { Ticks: > 0 } && 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(); - // D7: samples identify real instances; resets and lengths define their boundaries. - var groups = new List> { 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, Start: anchor.ResetsAt!.Value - anchor.Length!.Value, End: anchor.ResetsAt.Value); - }).OrderBy(g => g.Start).ToArray(); - for (var i = 0; i + 1 < spans.Length; i++) - if (spans[i + 1].Start < spans[i].End) spans[i].End = spans[i + 1].Start; + 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 current = Build(window, currentSpan.Start, currentSpan.End, now < currentSpan.End ? now : currentSpan.End, null); + var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End, + now < currentSpan.End ? now : currentSpan.End, null, TokenEnd(currentSpan.End, spans), now, zone); var realPast = spans.Where(g => g.Start < currentSpan.Start).OrderByDescending(g => g.Start).ToArray(); var past = new List(); var realIndex = 0; @@ -57,8 +43,9 @@ public static partial class LimitAnalysis // A shorter gap stays unassigned. Sessions never produce inferred candidates. var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart) ? realPast[realIndex++] - : (Anchor: window with { ResetsAt = cursor }, Start: inferredStart, End: cursor); - var instance = Build(span.Anchor, span.Start, span.End, span.End < now ? span.End : now, current.Scale); + : new InstanceSpan(window with { ResetsAt = cursor }, [], inferredStart, cursor); + var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End, + span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, spans), now, zone); if (instance.HasData) past.Add(instance); cursor = span.Start; } @@ -70,75 +57,76 @@ public static partial class LimitAnalysis 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) + private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList 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) { - double Weight(DateTimeOffset from, DateTimeOffset to) - { - var hour = Hour(from < start ? start : from); - var exclusiveEnd = Hour(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 { [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(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(); - 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; + var hour = Hour(from < start ? start : from); + var exclusiveEnd = tokenEnd; + 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 { [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(); + 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; } } diff --git a/src/FinalToken.Core/LimitSpans.cs b/src/FinalToken.Core/LimitSpans.cs new file mode 100644 index 0000000..3c29c56 --- /dev/null +++ b/src/FinalToken.Core/LimitSpans.cs @@ -0,0 +1,58 @@ +namespace FinalToken.Core; + +public static partial class LimitAnalysis +{ + private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList Samples, + DateTimeOffset Start, DateTimeOffset End); + + private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable samples, DateTimeOffset now) + { + var key = WindowSeries.For(window); + var observations = samples.Append(window).Where(s => key.Matches(s) && s.ResetsAt is not null && + s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && + s.UsedPercent is >= 0 and <= 100).Distinct().OrderByDescending(s => s.SampleTime).ToArray(); + var groups = new List> { new() { window } }; + foreach (var sample in observations) + { + var group = groups.FirstOrDefault(g => SameInstance(g[0], sample)); + if (group is null) groups.Add([sample]); else group.Add(sample); + } + var candidates = groups.Select(g => + { + var anchor = SameInstance(g[0], window) ? window : g.MaxBy(s => s.SampleTime)!; + return new InstanceSpan(anchor, g.Distinct().OrderBy(s => s.SampleTime).ToArray(), + anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).ToArray(); + var current = candidates[0]; + var accepted = new List { current }; + var latestStart = current.Start; + // D7 / #9: earlier observations cannot put an instance after a later observed instance. + // Order by first observation so an interleaved late rollout cannot reorder real resets. + foreach (var span in candidates.Skip(1).OrderByDescending(s => s.Samples.Min(p => p.SampleTime))) + { + if (span.Start > latestStart) continue; + accepted.Add(span); latestStart = span.Start; + } + var result = accepted.OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + // A late sample of the old instance after an early reset is stale too. + result = result.Select(s => + { + var valid = s.Samples.Where(p => p.SampleTime <= s.End).ToArray(); + var anchor = SameInstance(s.Anchor, window) ? window : valid.LastOrDefault() ?? s.Anchor; + return new InstanceSpan(anchor, valid, anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).Where(s => s.Samples.Count > 0 || SameInstance(s.Anchor, window)).OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + return result.Select(s => s with { Samples = s.Samples.Where(p => p.SampleTime <= s.End).ToArray() }).ToArray(); + } + + private static DateTimeOffset TokenEnd(DateTimeOffset end, IReadOnlyList spans) => + end == Hour(end) || spans.Any(s => s.Start >= end && Hour(s.Start) == Hour(end)) ? Hour(end) : Hour(end).AddHours(1); + + private static (DateTimeOffset Time, double Weight)[] WeightedTokens(LimitWindow window, IReadOnlyList tokens) => + 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(); +} diff --git a/src/FinalToken.Core/ResetHistory.cs b/src/FinalToken.Core/ResetHistory.cs new file mode 100644 index 0000000..c36996b --- /dev/null +++ b/src/FinalToken.Core/ResetHistory.cs @@ -0,0 +1,109 @@ +namespace FinalToken.Core; + +public enum PercentBasis { OwnInstance, SeriesMedian } +public sealed record PercentRate(double Tokens, decimal? ApiValue, PercentBasis Basis); +public sealed record ResetValue(double Percent, double? Tokens, decimal? ApiValue); +public sealed record ResetModel(string? Model, TokenCounts Tokens, decimal? ApiValue); +public sealed record ResetInstance(LimitInstance BurnUp, DateTimeOffset End, bool Running, bool Early, + TimeSpan Skipped, TokenCounts Tokens, IReadOnlyList Models, decimal? ApiValue, long UnpricedTokens, + PercentRate? ValuePerPercent = null, ResetValue? Unused = null, ResetValue? Gift = null) +{ + public DateTimeOffset Start => BurnUp.Start; + public DateTimeOffset Reset => BurnUp.Reset; + public TimeSpan Duration => End - Start; + public LimitPoint Final => BurnUp.Points[^1]; + public double? Peak => BurnUp.Peak; + public UseOrigin PeakOrigin => BurnUp.Points.Any(p => p.Used == Peak && p.Origin == UseOrigin.Measured) + ? UseOrigin.Measured : UseOrigin.Estimated; + public DateTimeOffset? ReachedLimit => BurnUp.ReachedLimit; + public TimeSpan TimeAtLimit => ReachedLimit is { } time && End > time ? End - time : TimeSpan.Zero; +} +public sealed record ResetTotals(int Instances, int Finished, int Early, TokenCounts Tokens, decimal? ApiValue, + long UnpricedTokens, ResetValue Unused, ResetValue Gift, TimeSpan Skipped, int ReachedLimit, TimeSpan TimeAtLimit); +public sealed record ResetHistory(LimitWindow Window, IReadOnlyList Instances, ResetTotals Totals, + IReadOnlyList EarlyByHour, IReadOnlyList EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample); + +public static partial class LimitAnalysis +{ + /// D12: only observed real instances; values cover whole overlapping instances, not a clipped range. + public static ResetHistory Resets(LimitWindow window, IEnumerable samples, + IReadOnlyList tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null) + { + zone ??= TimeZoneInfo.Local; + var rows = new List(); + var hours = new int[24]; var weekdays = new int[7]; + var firstSample = window.SampleTime; + if (window.ResetsAt is not null && window.Length is { } length && length > TimeSpan.FromDays(1) && + Pace.Calculate(window, now).State != PaceState.Unknown) + { + var spans = RealSpans(window, samples, now); + firstSample = spans.SelectMany(s => s.Samples).Select(s => s.SampleTime).DefaultIfEmpty(window.SampleTime).Min(); + var weighted = WeightedTokens(window, tokens); + foreach (var span in spans.Where(s => s.Samples.Count > 0 && s.End > from && s.Start <= now).Reverse()) + { + var running = span.End > now; + var end = running ? now : span.End; + var burn = BuildInstance(span.Anchor, span.Samples, weighted, span.Start, span.End, end, + null, TokenEnd(span.End, spans), now, zone); + var models = tokens.Where(p => p.Time >= Hour(span.Start) && p.Time < end && + p.Time < TokenEnd(span.End, spans) && TokenWeights.Matches(window, p.Model)) + .GroupBy(p => p.Model).Select(g => + { + var counts = g.Aggregate(new TokenCounts(), (sum, p) => sum + p.Counts); + return new ResetModel(g.Key, counts, ApiPrices.Value(window.Provider, g.Key, counts)); + }).OrderByDescending(m => m.Tokens.Total).ToArray(); + var early = !running && span.Anchor.ResetsAt!.Value - end > TimeSpan.FromMinutes(15); + rows.Add(new(burn, end, running, early, early ? span.Anchor.ResetsAt!.Value - end : TimeSpan.Zero, + models.Aggregate(new TokenCounts(), (sum, m) => sum + m.Tokens), models, + SumMoney(models.Select(m => m.ApiValue)), models.Where(m => m.ApiValue is null).Sum(m => m.Tokens.Total))); + if (early) + { + var local = TimeZoneInfo.ConvertTime(end, zone); + hours[local.Hour]++; weekdays[((int)local.DayOfWeek + 6) % 7]++; + } + } + var qualifying = rows.Where(r => r.Final.Used >= 5).ToArray(); + var medianTokens = Median(qualifying.Select(r => r.Tokens.Total / r.Final.Used)); + var medianMoney = MedianMoney(qualifying.Where(r => r.ApiValue is not null).Select(r => r.ApiValue!.Value / (decimal)r.Final.Used)); + for (var i = 0; i < rows.Count; i++) + { + var row = rows[i]; + var rate = row.Final.Used >= 5 ? new PercentRate(row.Tokens.Total / row.Final.Used, + row.ApiValue / (decimal)row.Final.Used, PercentBasis.OwnInstance) : medianTokens is { } median + ? new PercentRate(median, medianMoney, PercentBasis.SeriesMedian) : null; + ResetValue Value(double percent) => new(percent, rate?.Tokens * percent, rate?.ApiValue * (decimal)percent); + rows[i] = row with { ValuePerPercent = rate, Unused = row.Running ? null : Value(100 - row.Final.Used), + Gift = row.Early ? Value(100 * row.Skipped.TotalSeconds / length.TotalSeconds) : null }; + } + } + ResetValue TotalValue(IEnumerable source) + { + var values = source.OfType().ToArray(); + return new(values.Sum(v => v.Percent), values.All(v => v.Tokens is not null) ? values.Sum(v => v.Tokens) : null, + values.All(v => v.ApiValue is not null) ? values.Sum(v => v.ApiValue) : null); + } + var totals = new ResetTotals(rows.Count, rows.Count(r => !r.Running), rows.Count(r => r.Early), + rows.Aggregate(new TokenCounts(), (sum, r) => sum + r.Tokens), SumMoney(rows.Select(r => r.ApiValue)), + rows.Sum(r => r.UnpricedTokens), TotalValue(rows.Select(r => r.Unused)), TotalValue(rows.Select(r => r.Gift)), + TimeSpan.FromTicks(rows.Sum(r => r.Skipped.Ticks)), rows.Count(r => r.ReachedLimit is not null), + TimeSpan.FromTicks(rows.Sum(r => r.TimeAtLimit.Ticks))); + return new(window, rows, totals, hours, weekdays, + Median(rows.Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample); + } + + private static decimal? SumMoney(IEnumerable values) + { + var known = values.OfType().ToArray(); + return known.Length == 0 ? null : known.Sum(); + } + private static double? Median(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } + private static decimal? MedianMoney(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } +} diff --git a/src/FinalToken.Core/WindowSeries.cs b/src/FinalToken.Core/WindowSeries.cs new file mode 100644 index 0000000..daa85d7 --- /dev/null +++ b/src/FinalToken.Core/WindowSeries.cs @@ -0,0 +1,15 @@ +namespace FinalToken.Core; + +/// D7: Codex slots can change; a limit's name and length identify its series. +public readonly record struct WindowSeries(Provider Provider, string Name, TimeSpan? Length) +{ + public static WindowSeries For(LimitWindow window) + { + var name = window.Id; + if (window.Provider == Provider.Codex) + foreach (var suffix in new[] { ":primary", ":secondary" }) + if (name.EndsWith(suffix, StringComparison.Ordinal)) { name = name[..^suffix.Length]; break; } + return new(window.Provider, name, window.Length); + } + public bool Matches(LimitWindow window) => this == For(window); +} diff --git a/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs b/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs new file mode 100644 index 0000000..e12d501 --- /dev/null +++ b/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs @@ -0,0 +1,32 @@ +using Xunit; + +namespace FinalToken.Core.Tests; + +public sealed class ResetBoundaryTests +{ + private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero); + private static LimitWindow Window(DateTimeOffset start, DateTimeOffset sample, double used) => + new(Provider.Codex, "codex:primary", "Session", used, start.AddHours(5), TimeSpan.FromHours(5), sample, "fixture"); + + [Fact] public void ResetHourBeforeAGapBelongsToTheEndingInstance() + { + var previous = Window(Day.AddHours(10).AddMinutes(13), Day.AddHours(14), 50); + var current = Window(Day.AddHours(20), Day.AddHours(21), 10); + ModelTokenPoint[] tokens = [new(Day.AddHours(10), "model", new(Input: 100, Total: 100)), + new(Day.AddHours(15), "model", new(Input: 50, Total: 50))]; + var past = Assert.Single(LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!.Past); + Assert.Equal(75, past.Points.Last().Used); + Assert.Equal(UseOrigin.Estimated, past.Points.Last().Origin); + Assert.Equal(previous.ResetsAt, past.Points.Last().Time); + } + + [Fact] public void EarlierSampleCannotPutAnInstanceAfterTheCurrentWindow() + { + var current = Window(Day.AddHours(10), Day.AddHours(12), 10); + var stale = Window(Day.AddHours(11), Day.AddHours(11.5), 90); + var result = LimitAnalysis.Analyze(current, [stale], [], current.SampleTime, TimeZoneInfo.Utc)!; + Assert.Equal(current.ResetsAt, result.Current.End); + Assert.Equal(10, result.Current.Peak); + Assert.Empty(result.Past); + } +} diff --git a/tests/FinalToken.Core.Tests/ResetHistoryTests.cs b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs new file mode 100644 index 0000000..0fe43e7 --- /dev/null +++ b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs @@ -0,0 +1,176 @@ +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(2), history.MedianDuration); + Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped); + } + + [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); + } + + [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); + } +}