core: add the reset history, API list prices and window series
The developer wants figures for every reset: how long an instance lasted, its tokens, its final use, its API value, what it left unused and what an early reset handed out (D12, D13). Instances come from one window series, so a Codex limit that moves between the primary and secondary slot stays one history (D7). Building the spans once also fixes two D7 cases: the hour in which one instance ends and the next starts goes to the new instance instead of being lost, and a late sample of an old instance no longer places it after a newer one. Refs #14 Refs #9
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static class ApiPrices
|
||||
{
|
||||
public static DateOnly CheckedOn => new(2026, 10, 18);
|
||||
private static readonly Dictionary<string, ApiPrice> 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<string, ApiPrice> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<LimitWindow> 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<LimitWindow> LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) =>
|
||||
LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray();
|
||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
||||
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
|
||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
|
||||
|
||||
@@ -12,7 +12,7 @@ public static partial class LimitAnalysis
|
||||
{
|
||||
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
|
||||
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);
|
||||
|
||||
|
||||
@@ -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<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, 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<LimitInstance>();
|
||||
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<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)
|
||||
{
|
||||
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<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(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;
|
||||
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<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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public static partial class LimitAnalysis
|
||||
{
|
||||
private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList<LimitWindow> Samples,
|
||||
DateTimeOffset Start, DateTimeOffset End);
|
||||
|
||||
private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable<LimitWindow> 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<List<LimitWindow>> { 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<InstanceSpan> { 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<InstanceSpan> 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<ModelTokenPoint> 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();
|
||||
}
|
||||
@@ -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<ResetModel> 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<ResetInstance> Instances, ResetTotals Totals,
|
||||
IReadOnlyList<int> EarlyByHour, IReadOnlyList<int> EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample);
|
||||
|
||||
public static partial class LimitAnalysis
|
||||
{
|
||||
/// <summary>D12: only observed real instances; values cover whole overlapping instances, not a clipped range.</summary>
|
||||
public static ResetHistory Resets(LimitWindow window, IEnumerable<LimitWindow> samples,
|
||||
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null)
|
||||
{
|
||||
zone ??= TimeZoneInfo.Local;
|
||||
var rows = new List<ResetInstance>();
|
||||
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<ResetValue?> source)
|
||||
{
|
||||
var values = source.OfType<ResetValue>().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<decimal?> values)
|
||||
{
|
||||
var known = values.OfType<decimal>().ToArray();
|
||||
return known.Length == 0 ? null : known.Sum();
|
||||
}
|
||||
private static double? Median(IEnumerable<double> 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<decimal> source)
|
||||
{
|
||||
var sorted = source.Order().ToArray(); var n = sorted.Length;
|
||||
return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace FinalToken.Core;
|
||||
|
||||
/// <summary>D7: Codex slots can change; a limit's name and length identify its series.</summary>
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user