using System.Globalization; using System.Text.Json; namespace FinalToken.Core; public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts); public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts); public sealed record ModelTokenPoint(DateTimeOffset Time, string? Model, TokenCounts Counts); public sealed record TokenBreakdown(string? Name, TokenCounts Counts); public enum SeriesInterval { Hour, Day } public sealed class ScanCursor { public long Offset { get; set; } public long CreationTicks { get; set; } public string PrefixHash { get; set; } = ""; public int PrefixLength { get; set; } public string TailHash { get; set; } = ""; public string? SessionId { get; set; } public string? Model { get; set; } public string? Project { get; set; } public List LatestLimits { get; set; } = []; public long ObservedLength { get; set; } = -1; public long LastWriteTicks { get; set; } } /// UTC hourly storage; queries use [from,to), including whole boundary hours (D5). /// Data partitions load on demand with a three-month cache; journal replay is bounded by compaction. /// Claude imports and dedupe keys have a 60-day horizon, longer than the CLI's default 30-day cleanup. /// Scanner/session metadata scales with the local source files, not with their token events. public sealed class HistoryStore { public const int ClaudeRetentionDays = 60; private const long CompactBytes = 8 * 1024 * 1024; private readonly Lock gate = new(); private readonly string directory; private readonly TimeProvider clock; private readonly HistoryState state; private readonly Dictionary overlays = []; private readonly Dictionary pendingPartitions = []; private readonly Dictionary cache = []; private readonly LinkedList cacheOrder = []; private readonly HashSet months = []; private HistoryTransaction pending = new(); private long journalBytes; private DateTimeOffset prunedDay = DateTimeOffset.MinValue; private string JournalPath => Path.Combine(directory, "history.journal.jsonl"); private string StatePath => Path.Combine(directory, "history.state.json"); private string PartitionPath(string month) => Path.Combine(directory, "history", month + ".json"); public HistoryStore(string directory, DiagnosticLog diagnostics) : this(directory, diagnostics, TimeProvider.System) { } public HistoryStore(string directory, DiagnosticLog diagnostics, TimeProvider timeProvider) { this.directory = directory; clock = timeProvider; try { state = File.Exists(StatePath) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(StatePath), CoreJsonContext.Default.HistoryState) ?? throw new JsonException() : new(); ValidateState(state); if (Directory.Exists(Path.Combine(directory, "history"))) foreach (var path in Directory.GetFiles(Path.Combine(directory, "history"), "*.json")) { var month = Path.GetFileNameWithoutExtension(path); if (!DateTime.TryParseExact(month, "yyyy-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) throw new JsonException(); months.Add(month); } journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction); PruneKeys(); } catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { diagnostics.Add(null, "history-invalid", "History cannot be loaded; refusing to overwrite it."); throw new InvalidDataException("History cannot be loaded; restore or move the invalid history file.", e); } } internal ScanCursor Cursor(string path) { lock (gate) { if (!state.Cursors.TryGetValue(path, out var cursor)) state.Cursors[path] = cursor = new(); return cursor; } } internal void CursorChanged(string path) { lock (gate) pending.Cursors[path] = CloneCursor(state.Cursors[path]); } private static ScanCursor CloneCursor(ScanCursor c) => new() { Offset = c.Offset, CreationTicks = c.CreationTicks, PrefixHash = c.PrefixHash, PrefixLength = c.PrefixLength, TailHash = c.TailHash, SessionId = c.SessionId, Model = c.Model, Project = c.Project, LatestLimits = c.LatestLimits.ToList(), ObservedLength = c.ObservedLength, LastWriteTicks = c.LastWriteTicks }; public bool Add(UsageEvent usage) { lock (gate) { PruneKeys(); if (usage.Provider == Provider.Claude && usage.Time < clock.GetUtcNow().AddDays(-ClaudeRetentionDays)) return false; if (state.ClaudeKeys.ContainsKey(usage.DedupeKey)) return false; AddBucket(usage); state.ClaudeKeys[usage.DedupeKey] = usage.Time; pending.ClaudeKeys[usage.DedupeKey] = usage.Time; return true; } } internal bool AddCodex(string session, UsageEvent cumulative) { lock (gate) { var previous = state.CodexTotals.GetValueOrDefault(session); var previousTime = state.CodexTimes.GetValueOrDefault(session, DateTimeOffset.MinValue); // Archive copies and rescans replay earlier totals. A later counter reset is retained, // so its subsequent increases still count, without keeping a key for every token event. if (cumulative.Time < previousTime || cumulative.Time == previousTime && cumulative.Counts.Total <= previous.Total) return false; var delta = cumulative.Counts.IncreaseFrom(previous); if (delta.Total > 0) AddBucket(cumulative with { Counts = delta }); state.CodexTotals[session] = pending.CodexTotals[session] = cumulative.Counts; state.CodexTimes[session] = pending.CodexTimes[session] = cumulative.Time; return delta.Total > 0; } } private void PruneKeys() { var now = clock.GetUtcNow(); var day = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero); if (day == prunedDay) return; prunedDay = day; var cutoff = now.AddDays(-ClaudeRetentionDays); foreach (var key in state.ClaudeKeys.Where(k => k.Value < cutoff).Select(k => k.Key).ToArray()) { state.ClaudeKeys.Remove(key); pending.ClaudeKeys.Remove(key); pending.ExpiredClaudeKeys.Add(key); } } private void AddBucket(UsageEvent usage) { var bucket = new TokenBucket(usage.Provider, FloorHour(usage.Time), usage.Model, usage.Project, usage.Counts); var key = BucketKey.For(bucket); var month = Month(bucket.Hour); var partition = GetPartition(month); if (partition.Buckets.TryGetValue(key, out var previous)) bucket = bucket with { Counts = previous.Counts + usage.Counts }; partition.Buckets[key] = bucket; PendingPartition(month).Buckets[key] = bucket; } public void AddLimits(IEnumerable windows) { lock (gate) { var batch = windows.ToArray(); HashSet changedSets = []; foreach (var group in batch.GroupBy(w => w.Provider)) { var newest = group.Max(w => w.SampleTime); if (!state.LatestWindows.TryGetValue(group.Key, out var old) || old.Count == 0 || newest >= old.Max(w => w.SampleTime)) { var next = group.Where(w => w.SampleTime == newest).GroupBy(w => w.Id).Select(g => g.Last()).ToList(); if (old is null || !old.Select(WindowValue).SequenceEqual(next.Select(WindowValue))) changedSets.Add(group.Key); state.LatestWindows[group.Key] = next; } } foreach (var window in batch) { var key = WindowKey(window); var previous = state.LastSamples.GetValueOrDefault(key); var month = Month(window.SampleTime); var partition = GetPartition(month); if (partition.Limits.Contains(window)) continue; var chronologicalPrevious = previous; LimitWindow? chronologicalNext = null; if (previous is not null && window.SampleTime < previous.SampleTime) { chronologicalPrevious = partition.PreviousLimit(window); if (chronologicalPrevious is null) foreach (var earlier in months.Where(m => string.CompareOrdinal(m, month) < 0).OrderDescending()) if (GetPartition(earlier).PreviousLimit(window) is { } found) { chronologicalPrevious = found; break; } chronologicalNext = partition.NextLimit(window); if (chronologicalNext is null) foreach (var later in months.Where(m => string.CompareOrdinal(m, month) > 0).Order()) if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; } } if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent && LimitAnalysis.SameInstance(window, chronologicalPrevious) && window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue; if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent && LimitAnalysis.SameInstance(window, chronologicalNext) && chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue; if (previous is null || window.SampleTime >= previous.SampleTime) state.LastSamples[key] = pending.LastSamples[key] = window; changedSets.Add(window.Provider); if (partition.AddLimit(window)) PendingPartition(month).Limits.Add(window); } foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider]; } } // D5: retain exact probe metadata; D7 tolerance applies only to instance identity and sampling. private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) => (window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source); public IReadOnlyList LatestLimits(Provider provider) { lock (gate) return state.LatestWindows.GetValueOrDefault(provider, []).OrderBy(w => w.Length).ToArray(); } public IReadOnlyList LimitSamples(Provider provider, string windowId, DateTimeOffset from, DateTimeOffset to) { lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits) .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, TimeZoneInfo? zone) { lock (gate) { Dictionary points = []; foreach (var bucket in Range(provider, from, to)) { var key = interval == SeriesInterval.Hour ? bucket.Hour : CalendarDays.Start(bucket.Hour, zone); points[key] = points.GetValueOrDefault(key) + bucket.Counts; } return points.OrderBy(p => p.Key).Select(p => new TokenPoint(p.Key, p.Value)).ToArray(); } } public IReadOnlyList ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true); public IReadOnlyList TokenSeriesByModel(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, TimeZoneInfo? zone = null) { lock (gate) return Range(provider, from, to) .GroupBy(b => (Time: interval == SeriesInterval.Hour ? b.Hour : CalendarDays.Start(b.Hour, zone), b.Model)) .OrderBy(g => g.Key.Time).ThenBy(g => g.Key.Model, StringComparer.Ordinal) .Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model, Sum(g.Select(b => b.Counts)))).ToArray(); } public IReadOnlyList ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false); private IReadOnlyList Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model) { lock (gate) return Range(provider, from, to).GroupBy(b => model ? b.Model : b.Project) .Select(g => new TokenBreakdown(g.Key, Sum(g.Select(b => b.Counts)))).OrderByDescending(b => b.Counts.Total).ToArray(); } public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to) { lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); } public (TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart, string? WeekWindow) Totals(Provider provider, DateTimeOffset now, LimitWindow? session, TimeZoneInfo? zone = null, LimitWindow? weekWindow = null) { zone ??= TimeZoneInfo.Local; var local = TimeZoneInfo.ConvertTime(now, zone); var today = local.Date; var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7)); var todayUtc = CalendarDays.Start(today, zone); var followsLimit = weekWindow is { ResetsAt: { } r, Length: { Ticks: > 0 } l } && r > now; var weekUtc = followsLimit ? weekWindow!.ResetsAt!.Value - weekWindow.Length!.Value : CalendarDays.Start(week, zone); return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now), weekUtc, followsLimit ? weekWindow!.Id : null); } private IEnumerable Range(Provider provider, DateTimeOffset from, DateTimeOffset to) => SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values) .Where(b => b.Provider == provider && b.Hour >= FloorHour(from) && b.Hour < to); private string[] SelectMonths(DateTimeOffset from, DateTimeOffset to) => to <= from ? [] : months.Where(m => string.CompareOrdinal(m, Month(from)) >= 0 && string.CompareOrdinal(m, Month(to)) <= 0).Order().ToArray(); private static string Month(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM", CultureInfo.InvariantCulture); private static string WindowKey(LimitWindow window) => ((int)window.Provider).ToString(CultureInfo.InvariantCulture) + ":" + window.Id; private static DateTimeOffset FloorHour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero); private static TokenCounts Sum(IEnumerable values) => values.Aggregate(new TokenCounts(), (a, b) => a + b); private PartitionIndex PendingPartition(string month) { months.Add(month); if (!pendingPartitions.TryGetValue(month, out var partition)) pendingPartitions[month] = partition = new(); return partition; } private PartitionIndex GetPartition(string month) { if (!cache.TryGetValue(month, out var partition)) { partition = new(); var path = PartitionPath(month); if (File.Exists(path)) { var data = JsonSerializer.Deserialize(SharedFile.ReadAllText(path), CoreJsonContext.Default.HistoryPartition) ?? throw new JsonException(); if (data.V != 1 || data.Buckets is null || data.Limits is null) throw new JsonException(); partition.Apply(data); } if (overlays.TryGetValue(month, out var overlay)) partition.Apply(overlay); if (pendingPartitions.TryGetValue(month, out var changes)) partition.Apply(changes); cache[month] = partition; while (cache.Count > 3) { var first = cacheOrder.First!.Value; cacheOrder.RemoveFirst(); cache.Remove(first); } } cacheOrder.Remove(month); cacheOrder.AddLast(month); return partition; } public Task SaveAsync(CancellationToken cancellationToken = default) => Task.Run(() => Save(false, cancellationToken), cancellationToken); /// Explicit bounded-journal maintenance; ordinary idle SaveAsync does no I/O. public Task CompactAsync(CancellationToken cancellationToken = default) => Task.Run(() => Save(true, cancellationToken), cancellationToken); private void Save(bool compact, CancellationToken token) { lock (gate) { PruneKeys(); pending.Buckets = pendingPartitions.Values.SelectMany(p => p.Buckets.Values).ToList(); pending.Limits = pendingPartitions.Values.SelectMany(p => p.Limits).ToList(); var changed = pending.Buckets.Count + pending.Limits.Count + pending.ClaudeKeys.Count + pending.ExpiredClaudeKeys.Count + pending.CodexTotals.Count + pending.Cursors.Count + pending.LatestWindows.Count + pending.LastSamples.Count > 0; if (changed) { pending.Sequence = state.Sequence + 1; journalBytes = HistoryJournal.Append(JournalPath, journalBytes, pending, token); foreach (var (month, changes) in pendingPartitions) { if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new(); overlay.Apply(changes); } state.Sequence = pending.Sequence; pending = new(); pendingPartitions.Clear(); } if ((changed && journalBytes >= CompactBytes || compact) && journalBytes > 0) { foreach (var month in overlays.Keys.ToArray()) { token.ThrowIfCancellationRequested(); AtomicFile.WriteAsync(PartitionPath(month), JsonSerializer.Serialize(GetPartition(month).Export(), CoreJsonContext.Default.HistoryPartition), token).GetAwaiter().GetResult(); } // Checkpoint last. If interrupted, absolute bucket upserts and exact sample sets replay idempotently. AtomicFile.WriteAsync(StatePath, JsonSerializer.Serialize(state, CoreJsonContext.Default.HistoryState), token).GetAwaiter().GetResult(); AtomicFile.WriteAsync(JournalPath, "", token).GetAwaiter().GetResult(); journalBytes = 0; overlays.Clear(); } } } private void ApplyTransaction(HistoryTransaction transaction) { if (transaction.Sequence <= state.Sequence) return; if (transaction.Sequence != state.Sequence + 1 || transaction.Buckets is null || transaction.Limits is null || transaction.ClaudeKeys is null || transaction.ExpiredClaudeKeys is null || transaction.CodexTotals is null || transaction.CodexTimes is null || transaction.Cursors is null || transaction.LatestWindows is null || transaction.LastSamples is null) throw new JsonException(); foreach (var key in transaction.ExpiredClaudeKeys) state.ClaudeKeys.Remove(key); foreach (var (key, value) in transaction.ClaudeKeys) state.ClaudeKeys[key] = value; foreach (var (key, value) in transaction.CodexTotals) state.CodexTotals[key] = value; foreach (var (key, value) in transaction.CodexTimes) state.CodexTimes[key] = value; foreach (var (key, value) in transaction.Cursors) state.Cursors[key] = value; foreach (var (key, value) in transaction.LatestWindows) state.LatestWindows[key] = value; foreach (var (key, value) in transaction.LastSamples) state.LastSamples[key] = value; foreach (var bucket in transaction.Buckets) { var month = Month(bucket.Hour); if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new(); overlay.Buckets[BucketKey.For(bucket)] = bucket; months.Add(month); } foreach (var sample in transaction.Limits) { var month = Month(sample.SampleTime); if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new(); overlay.Limits.Add(sample); months.Add(month); } state.Sequence = transaction.Sequence; } private static void ValidateState(HistoryState value) { if (value.V != 1 || value.Sequence < 0 || value.ClaudeKeys is null || value.CodexTotals is null || value.CodexTimes is null || value.Cursors is null || value.LatestWindows is null || value.LastSamples is null) throw new JsonException(); } }