diff --git a/src/FinalToken.Cli/CliApplication.cs b/src/FinalToken.Cli/CliApplication.cs index 3517cb6..797dc15 100644 --- a/src/FinalToken.Cli/CliApplication.cs +++ b/src/FinalToken.Cli/CliApplication.cs @@ -30,7 +30,7 @@ public static class CliApplication await using var engine = engineFactory?.Invoke(directory) ?? new RefreshEngine(directory); snapshot = await engine.RefreshNowAsync(args.Contains("--no-probe"), cancellationToken); foreach (var diagnostic in engine.RecentDiagnostics) - await error.WriteLineAsync($"{diagnostic.Code}: {diagnostic.Summary}"); + await error.WriteLineAsync($"{diagnostic.Code} (x{diagnostic.Count}, last {diagnostic.Time:O}): {diagnostic.Summary}"); } if (args.Contains("--json")) await output.WriteLineAsync(JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot)); else diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index e2ba3fc..c2402f9 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -19,3 +19,34 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root - W3 owns `StreamDeck/`: `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and its stub. 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. + +## Store persistence and scaling + +- Refresh changes append as one durable, newline-terminated transaction to + `history.journal.jsonl`. Ignore a torn final line on load; reject a corrupt complete line. + Before another append, truncate the torn tail. Hosts still hold `StoreLock` (D5). +- At 8 MiB, compact committed changes into UTC monthly `history/yyyy-MM.json` files, then + atomically replace `history.state.json`, then reset the journal. Absolute bucket upserts, + exact sample sets and checkpoint sequences make interrupted compaction replay idempotent. + Ordinary idle saves write nothing. `CompactAsync` is an explicit maintenance operation. +- Keep three monthly partitions in memory. Bucket updates use keyed lookup. Journal overlays + are bounded by compaction; scanner/session metadata remains one entry per observed source or + session. Queries load only overlapping months and preserve their existing public signatures. +- Claude imports and response keys have a 60-day horizon, twice the default 30-day cleanup. + Keys expire daily; entries older than the horizon are ignored even after a key expires. + Legacy stores keep their recorded buckets and retain old keys for 60 days after migration. + Codex replay protection uses the last session timestamp and cumulative counts, with no + per-event dedupe keys. A later counter reset still permits subsequent increases. +- Store changed percent/reset samples and at most one unchanged sample per window per hour. + Late observations from archived files use neighbouring timestamps so they keep real changes + without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have + a per-window time index for ordered lookup. + Successful unchanged probes refresh the in-memory sample age without writing history before + that hourly point. The latest window set remains separate from the history samples. +- A scanner compares length, last-write time and creation time before opening a source file. + Unchanged files stay closed; changed files retain prefix/tail replacement checks. A replacement + that preserves all those metadata fields cannot be distinguished from an unchanged file. +- Readers of replaced files use `FileShare.ReadWrite | FileShare.Delete`. Atomic replacements + use `File.Replace` for existing targets and retry Windows sharing failures for at most 500 ms. +- Diagnostics fold by provider/code; `Count` is additive and `Time` is the latest occurrence. + Synthetic Claude entries are silent. No message text appears in a diagnostic or journal. diff --git a/src/FinalToken.Core/AtomicFile.cs b/src/FinalToken.Core/AtomicFile.cs index 8b9e72c..5f7958b 100644 --- a/src/FinalToken.Core/AtomicFile.cs +++ b/src/FinalToken.Core/AtomicFile.cs @@ -14,12 +14,28 @@ public static class AtomicFile await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.WriteThrough)) { - await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken); - await stream.FlushAsync(cancellationToken); + await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken).ConfigureAwait(false); + await stream.FlushAsync(cancellationToken).ConfigureAwait(false); stream.Flush(true); } cancellationToken.ThrowIfCancellationRequested(); - File.Move(temporary, path, true); + for (var attempt = 0; ; attempt++) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + if (File.Exists(path)) File.Replace(temporary, path, null); + else File.Move(temporary, path); + break; + } + catch (Exception e) when (OperatingSystem.IsWindows() && + e is IOException or UnauthorizedAccessException && (e.HResult & 0xffff) is 5 or 32 or 33) + { + // Windows can report ACCESS_DENIED for an open destination as well as SHARING_VIOLATION. + if (attempt == 10) throw new IOException("Atomic replacement remained blocked after 500 ms.", e); + await Task.Delay(TimeSpan.FromMilliseconds(50), cancellationToken).ConfigureAwait(false); + } + } } finally { if (File.Exists(temporary)) File.Delete(temporary); } } @@ -45,7 +61,19 @@ public static class ActivationFile AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken); public static string? ReadRequest(string directory) { - try { return File.ReadAllText(Path.Combine(directory, "activate.request")); } + try { return SharedFile.ReadAllText(Path.Combine(directory, "activate.request")); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; } } } + +internal static class SharedFile +{ + public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan); + public static string ReadAllText(string path) + { + using var stream = OpenRead(path); + using var reader = new StreamReader(stream, Encoding.UTF8); + return reader.ReadToEnd(); + } +} diff --git a/src/FinalToken.Core/Collectors/IncrementalScanner.cs b/src/FinalToken.Core/Collectors/IncrementalScanner.cs index f4032b1..405f9d3 100644 --- a/src/FinalToken.Core/Collectors/IncrementalScanner.cs +++ b/src/FinalToken.Core/Collectors/IncrementalScanner.cs @@ -45,10 +45,16 @@ public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagn { try { + cancellationToken.ThrowIfCancellationRequested(); + var info = new FileInfo(path); + var cursor = history.Cursor(path); + var length = info.Length; + var lastWrite = info.LastWriteTimeUtc.Ticks; + var creation = info.CreationTimeUtc.Ticks; + if (cursor.ObservedLength == length && cursor.LastWriteTicks == lastWrite && cursor.CreationTicks == creation) + return 0; await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan); - var cursor = history.Cursor(path); - var creation = File.GetCreationTimeUtc(path).Ticks; if (stream.Length < cursor.Offset || cursor.CreationTicks != creation || cursor.PrefixHash != Fingerprint(stream, 0, cursor.PrefixLength) || cursor.TailHash != Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset))) @@ -67,14 +73,17 @@ public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagn int read; while ((read = await stream.ReadAsync(readBuffer, cancellationToken)) > 0) { - for (var i = 0; i < read; i++) + var start = 0; + while (start < read) { + var newline = readBuffer.AsSpan(start, read - start).IndexOf((byte)'\n'); + var segmentLength = newline < 0 ? read - start : newline; + line.Write(readBuffer.AsSpan(start, segmentLength)); + consumed += segmentLength; + start += segmentLength; + if (newline < 0) break; consumed++; - if (readBuffer[i] != (byte)'\n') - { - line.WriteByte(readBuffer[i]); - continue; - } + start++; cancellationToken.ThrowIfCancellationRequested(); // Source entries can contain large tool results. An output-capture bound // belongs to child processes, not to valid transcript records (D3). @@ -108,6 +117,9 @@ public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagn cursor.PrefixLength = (int)Math.Min(256, cursor.Offset); cursor.PrefixHash = Fingerprint(stream, 0, cursor.PrefixLength); cursor.TailHash = Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset)); + cursor.ObservedLength = length; + cursor.LastWriteTicks = lastWrite; + history.CursorChanged(path); return added; } catch (Exception e) when (e is IOException or UnauthorizedAccessException) diff --git a/src/FinalToken.Core/Collectors/TranscriptParser.cs b/src/FinalToken.Core/Collectors/TranscriptParser.cs index b09d343..7a4a59a 100644 --- a/src/FinalToken.Core/Collectors/TranscriptParser.cs +++ b/src/FinalToken.Core/Collectors/TranscriptParser.cs @@ -12,12 +12,15 @@ public static class TranscriptParser var root = document.RootElement; if (root.Text("type") != "assistant") return null; var message = root.Field("message"); + if (message.Text("model") == "") return null; if (message.Field("usage").ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null; + var counts = JsonFields.Counts(message.Field("usage"), true); + if (root.Text("requestId") is not { Length: > 0 } && counts == new TokenCounts()) return null; if (message.Text("id") is not { Length: > 0 } id || root.Text("requestId") is not { Length: > 0 } request || root.Field("timestamp").Timestamp() is not { } time) throw new FormatException(); // Length prefixes avoid collisions between ids that contain separators (D3). return new(Provider.Claude, time, message.Text("model"), root.Text("cwd"), - JsonFields.Counts(message.Field("usage"), true), $"claude:{id.Length}:{id}{request.Length}:{request}"); + counts, $"claude:{id.Length}:{id}{request.Length}:{request}"); } catch (Exception e) when (e is JsonException or FormatException or OverflowException) { diagnostics.Add(Provider.Claude, "transcript-parse", "Malformed assistant usage entry skipped."); return null; } diff --git a/src/FinalToken.Core/HistoryPersistence.cs b/src/FinalToken.Core/HistoryPersistence.cs new file mode 100644 index 0000000..954f7c6 --- /dev/null +++ b/src/FinalToken.Core/HistoryPersistence.cs @@ -0,0 +1,132 @@ +using System.Text.Json; +using System.Text; + +namespace FinalToken.Core; + +internal readonly record struct BucketKey(Provider Provider, DateTimeOffset Hour, string? Model, string? Project) +{ + public static BucketKey For(TokenBucket bucket) => new(bucket.Provider, bucket.Hour, bucket.Model, bucket.Project); +} + +public sealed class HistoryPartition +{ + public int V { get; set; } = 1; + public List Buckets { get; set; } = []; + public List Limits { get; set; } = []; +} + +public sealed class HistoryState +{ + public int V { get; set; } = 1; + public long Sequence { get; set; } + public Dictionary ClaudeKeys { get; set; } = []; + public Dictionary CodexTotals { get; set; } = []; + public Dictionary CodexTimes { get; set; } = []; + public Dictionary Cursors { get; set; } = []; + public Dictionary> LatestWindows { get; set; } = []; + public Dictionary LastSamples { get; set; } = []; +} + +public sealed class HistoryTransaction +{ + public int V { get; set; } = 1; + public long Sequence { get; set; } + public List Buckets { get; set; } = []; + public List Limits { get; set; } = []; + public Dictionary ClaudeKeys { get; set; } = []; + public List ExpiredClaudeKeys { get; set; } = []; + public Dictionary CodexTotals { get; set; } = []; + public Dictionary CodexTimes { get; set; } = []; + public Dictionary Cursors { get; set; } = []; + public Dictionary> LatestWindows { get; set; } = []; + public Dictionary LastSamples { get; set; } = []; +} + +internal sealed class PartitionIndex +{ + private readonly Dictionary<(Provider, string), SortedSet> windowSamples = []; + private static readonly IComparer SampleTimeComparer = Comparer.Create((a, b) => a.SampleTime.CompareTo(b.SampleTime)); + public Dictionary Buckets { get; } = []; + public HashSet Limits { get; } = []; + public void Apply(HistoryPartition partition) + { + foreach (var bucket in partition.Buckets) Buckets[BucketKey.For(bucket)] = bucket; + foreach (var sample in partition.Limits) AddLimit(sample); + } + public void Apply(PartitionIndex other) + { + foreach (var (key, bucket) in other.Buckets) Buckets[key] = bucket; + foreach (var sample in other.Limits) AddLimit(sample); + } + public bool AddLimit(LimitWindow sample) + { + if (!Limits.Add(sample)) return false; + var key = (sample.Provider, sample.Id); + if (!windowSamples.TryGetValue(key, out var samples)) windowSamples[key] = samples = new(SampleTimeComparer); + samples.Add(sample); + return true; + } + public LimitWindow? PreviousLimit(LimitWindow sample) + { + if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == 0) return null; + return samples.GetViewBetween(sample with { SampleTime = DateTimeOffset.MinValue }, + sample with { SampleTime = new(sample.SampleTime.UtcTicks - 1, TimeSpan.Zero) }).Max; + } + public LimitWindow? NextLimit(LimitWindow sample) + { + if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == DateTimeOffset.MaxValue.UtcTicks) return null; + return samples.GetViewBetween(sample with { SampleTime = new(sample.SampleTime.UtcTicks + 1, TimeSpan.Zero) }, + sample with { SampleTime = DateTimeOffset.MaxValue }).Min; + } + public HistoryPartition Export() => new() { Buckets = Buckets.Values.ToList(), Limits = Limits.ToList() }; +} + +internal static class HistoryJournal +{ + /// Only newline-terminated records commit. Returns the byte position of the last complete record. + /// A corrupt completed record is an error; a torn final line is deliberately ignored. + public static long Read(string path, Action apply) + { + if (!File.Exists(path)) return 0; + using var stream = SharedFile.OpenRead(path); + using var line = new MemoryStream(); + var buffer = new byte[65536]; + long position = 0, committed = 0; + int count; + while ((count = stream.Read(buffer)) > 0) + { + var start = 0; + while (start < count) + { + var newline = buffer.AsSpan(start, count - start).IndexOf((byte)'\n'); + var length = newline < 0 ? count - start : newline; + line.Write(buffer.AsSpan(start, length)); + position += length; + start += length; + if (newline < 0) break; + var transaction = JsonSerializer.Deserialize(line.GetBuffer().AsSpan(0, (int)line.Length), CoreJsonContext.Default.HistoryTransaction) + ?? throw new JsonException(); + if (transaction.V != 1 || transaction.Sequence <= 0) throw new JsonException(); + apply(transaction); + committed = ++position; + start++; + line.SetLength(0); + } + } + return committed; + } + public static long Append(string path, long committed, HistoryTransaction transaction, CancellationToken token) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + token.ThrowIfCancellationRequested(); + var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(transaction, CoreJsonContext.Default.HistoryTransaction) + "\n"); + using var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, + 65536, FileOptions.WriteThrough); + // Repair a torn previous append before adding another record. + if (stream.Length != committed) stream.SetLength(committed); + stream.Position = committed; + stream.Write(bytes); + stream.Flush(true); + return stream.Position; + } +} diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 201829e..0359d4f 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Text.Json; namespace FinalToken.Core; @@ -18,8 +19,11 @@ public sealed class ScanCursor 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; } } +// Retained for source compatibility and one-time migration of 14223b0 stores. public sealed class HistoryData { public int V { get; set; } = 1; @@ -30,47 +34,89 @@ public sealed class HistoryData public Dictionary Cursors { get; set; } = []; } -/// D5: UTC hourly storage; queries use [from,to). Day series uses UTC days. -/// Totals use the selected local zone for today and Monday-based calendar week. -/// Boundary hours are included as a whole; finer history is deliberately unavailable. +/// 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 HistoryData data; - public HistoryStore(string directory, DiagnosticLog diagnostics) + 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; - var path = Path.Combine(directory, "history.json"); - if (!File.Exists(path)) { data = new(); return; } + clock = timeProvider; try { - data = JsonSerializer.Deserialize(File.ReadAllText(path), CoreJsonContext.Default.HistoryData) - ?? throw new JsonException(); - if (data.V != 1 || data.Buckets is null || data.Limits is null || data.Cursors is null || - data.CodexTotals is null || data.DedupeKeys is null) throw new JsonException(); + 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); + if (state.Sequence == 0 && File.Exists(Path.Combine(directory, "history.json"))) MigrateLegacy(); + 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."); + throw new InvalidDataException("History cannot be loaded; restore or move the invalid history file.", e); } } + internal ScanCursor Cursor(string path) { lock (gate) { - if (!data.Cursors.TryGetValue(path, out var cursor)) data.Cursors[path] = cursor = new(); + 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) { - if (data.DedupeKeys.Contains(usage.DedupeKey)) return false; + PruneKeys(); + if (usage.Provider == Provider.Claude && usage.Time < clock.GetUtcNow().AddDays(-ClaudeRetentionDays)) return false; + if (state.ClaudeKeys.ContainsKey(usage.DedupeKey)) return false; AddBucket(usage); - data.DedupeKeys.Add(usage.DedupeKey); + state.ClaudeKeys[usage.DedupeKey] = usage.Time; + pending.ClaudeKeys[usage.DedupeKey] = usage.Time; return true; } } @@ -78,56 +124,119 @@ public sealed class HistoryStore { lock (gate) { - var key = $"codex:{session}:{cumulative.Time.UtcTicks}:{cumulative.Counts.Total}"; - if (data.DedupeKeys.Contains(key)) return false; - var previous = data.CodexTotals.GetValueOrDefault(session); + 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 }); - data.CodexTotals[session] = cumulative.Counts; - data.DedupeKeys.Add(key); + 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 hour = FloorHour(usage.Time); - var index = data.Buckets.FindIndex(b => b.Provider == usage.Provider && b.Hour == hour && - b.Model == usage.Model && b.Project == usage.Project); - if (index < 0) data.Buckets.Add(new(usage.Provider, hour, usage.Model, usage.Project, usage.Counts)); - else data.Buckets[index] = data.Buckets[index] with { Counts = data.Buckets[index].Counts + usage.Counts }; + 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) - foreach (var window in windows) - if (!data.Limits.Contains(window)) data.Limits.Add(window); + { + 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 && + window.ResetsAt == chronologicalPrevious.ResetsAt && + window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue; + if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent && + window.ResetsAt == chronologicalNext.ResetsAt && + 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]; + } } + 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) - { - var samples = data.Limits.Where(w => w.Provider == provider).ToArray(); - if (samples.Length == 0) return []; - var newest = samples.Max(w => w.SampleTime); - return samples.Where(w => w.SampleTime == newest).GroupBy(w => w.Id) - .Select(g => g.Last()).OrderBy(w => w.Length).ToArray(); - } + 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 data.Limits.Where(w => w.Provider == provider && w.Id == windowId && - w.SampleTime >= from && w.SampleTime < to).OrderBy(w => w.SampleTime).ToArray(); + 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 TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) { - lock (gate) return Range(provider, from, to).GroupBy(b => interval == SeriesInterval.Hour ? b.Hour : - new DateTimeOffset(b.Hour.UtcDateTime.Date, TimeSpan.Zero)).OrderBy(g => g.Key) - .Select(g => new TokenPoint(g.Key, Sum(g.Select(b => b.Counts)))).ToArray(); + lock (gate) + { + Dictionary points = []; + foreach (var bucket in Range(provider, from, to)) + { + var key = interval == SeriesInterval.Hour ? bucket.Hour : new DateTimeOffset(bucket.Hour.UtcDateTime.Date, TimeSpan.Zero); + 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 ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => - Breakdown(provider, from, to, false); + public IReadOnlyList ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true); + 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) @@ -148,13 +257,159 @@ public sealed class HistoryStore ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now)); } private IEnumerable Range(Provider provider, DateTimeOffset from, DateTimeOffset to) => - to <= from ? [] : data.Buckets.Where(b => b.Provider == provider && b.Hour >= FloorHour(from) && b.Hour < 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); - public Task SaveAsync(CancellationToken cancellationToken = default) + + private PartitionIndex PendingPartition(string month) { - string json; - lock (gate) json = JsonSerializer.Serialize(data, CoreJsonContext.Default.HistoryData); - return AtomicFile.WriteAsync(Path.Combine(directory, "history.json"), json, cancellationToken); + 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(); + } + private void MigrateLegacy() + { + var legacy = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "history.json")), + CoreJsonContext.Default.HistoryData) ?? throw new JsonException(); + if (legacy.V != 1 || legacy.Buckets is null || legacy.Limits is null || legacy.DedupeKeys is null || + legacy.CodexTotals is null || legacy.Cursors is null) throw new JsonException(); + foreach (var bucket in legacy.Buckets) PendingPartition(Month(bucket.Hour)).Buckets[BucketKey.For(bucket)] = bucket; + foreach (var group in legacy.Limits.OrderBy(w => w.SampleTime).GroupBy(w => (w.Provider, w.SampleTime))) AddLimits(group); + foreach (var key in legacy.DedupeKeys) + { + if (!key.StartsWith("codex:", StringComparison.Ordinal)) + state.ClaudeKeys[key] = pending.ClaudeKeys[key] = clock.GetUtcNow(); + else + { + var last = key.LastIndexOf(':'); + var timeStart = key.LastIndexOf(':', last - 1); + if (timeStart > 6 && long.TryParse(key.AsSpan(timeStart + 1, last - timeStart - 1), out var ticks)) + { + var session = key[6..timeStart]; + var time = new DateTimeOffset(ticks, TimeSpan.Zero); + if (time > state.CodexTimes.GetValueOrDefault(session)) + state.CodexTimes[session] = pending.CodexTimes[session] = time; + } + } + } + foreach (var (session, counts) in legacy.CodexTotals) state.CodexTotals[session] = pending.CodexTotals[session] = counts; + foreach (var (path, cursor) in legacy.Cursors) + { + state.Cursors[path] = cursor; + pending.Cursors[path] = CloneCursor(cursor); + } + cache.Clear(); + cacheOrder.Clear(); } } diff --git a/src/FinalToken.Core/Model.cs b/src/FinalToken.Core/Model.cs index 91e019c..fe2e181 100644 --- a/src/FinalToken.Core/Model.cs +++ b/src/FinalToken.Core/Model.cs @@ -33,19 +33,28 @@ public sealed record PaceResult(PaceState State, double? ElapsedFraction = null, DateTimeOffset? Projection = null); public sealed record PopupEvent(Provider Provider, string WindowId, string Label, PaceState State, double Delta, DateTimeOffset? Projection); -public sealed record Diagnostic(DateTimeOffset Time, Provider? Provider, string Code, string Summary); +public sealed record Diagnostic(DateTimeOffset Time, Provider? Provider, string Code, string Summary) +{ + public long Count { get; init; } = 1; +} /// Bounded metadata-only diagnostics. Never pass parser input or process output here (D2). public sealed class DiagnosticLog(TimeProvider? timeProvider = null, int capacity = 100) { private readonly Lock gate = new(); - private readonly Queue entries = new(); + private readonly List entries = []; public void Add(Provider? provider, string code, string summary) { lock (gate) { - entries.Enqueue(new((timeProvider ?? TimeProvider.System).GetUtcNow(), provider, code, summary)); - while (entries.Count > Math.Max(1, capacity)) entries.Dequeue(); + var time = (timeProvider ?? TimeProvider.System).GetUtcNow(); + var index = entries.FindIndex(d => d.Provider == provider && d.Code == code); + if (index >= 0) entries[index] = entries[index] with { Time = time, Count = entries[index].Count + 1 }; + else + { + entries.Add(new(time, provider, code, summary)); + if (entries.Count > Math.Max(1, capacity)) entries.RemoveAt(0); + } } } public IReadOnlyList Recent { get { lock (gate) return entries.ToArray(); } } diff --git a/src/FinalToken.Core/RefreshEngine.cs b/src/FinalToken.Core/RefreshEngine.cs index f6bcc4e..1657dd2 100644 --- a/src/FinalToken.Core/RefreshEngine.cs +++ b/src/FinalToken.Core/RefreshEngine.cs @@ -37,7 +37,7 @@ public sealed class RefreshEngine : IAsyncDisposable clock = timeProvider ?? TimeProvider.System; Diagnostics = new(clock); settings = SettingsFile.Load(directory, Diagnostics); - History = new(directory, Diagnostics); + History = new(directory, Diagnostics, clock); ClaudeDirectory = claudeDirectory ?? DataPaths.ClaudeDirectory; CodexDirectory = codexDirectory ?? DataPaths.CodexDirectory; scanner = new(History, Diagnostics, ClaudeDirectory, CodexDirectory); diff --git a/src/FinalToken.Core/Settings.cs b/src/FinalToken.Core/Settings.cs index 17bf78c..fb422fa 100644 --- a/src/FinalToken.Core/Settings.cs +++ b/src/FinalToken.Core/Settings.cs @@ -48,7 +48,7 @@ public static class SettingsFile { try { - var value = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings); + var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings); if (value is { IsValid: true }) return value; } catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { } diff --git a/src/FinalToken.Core/Snapshot.cs b/src/FinalToken.Core/Snapshot.cs index f01b297..91f132a 100644 --- a/src/FinalToken.Core/Snapshot.cs +++ b/src/FinalToken.Core/Snapshot.cs @@ -28,7 +28,7 @@ public static class SnapshotFile { try { - var snapshot = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(directory, "snapshot.json")), CoreJsonContext.Default.Snapshot); + var snapshot = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "snapshot.json")), CoreJsonContext.Default.Snapshot); if (snapshot is null || snapshot.V != 1 || snapshot.RefreshInterval <= TimeSpan.Zero || snapshot.Providers is null) return new(null, true, "Snapshot schema is invalid or unsupported."); var age = (now ?? DateTimeOffset.UtcNow) - snapshot.MadeAt; @@ -43,4 +43,7 @@ public static class SnapshotFile [JsonSerializable(typeof(Snapshot))] [JsonSerializable(typeof(Settings))] [JsonSerializable(typeof(HistoryData))] +[JsonSerializable(typeof(HistoryState))] +[JsonSerializable(typeof(HistoryPartition))] +[JsonSerializable(typeof(HistoryTransaction))] public partial class CoreJsonContext : JsonSerializerContext; diff --git a/tests/FinalToken.Cli.Tests/CliTests.cs b/tests/FinalToken.Cli.Tests/CliTests.cs index b1784f1..4ce23e8 100644 --- a/tests/FinalToken.Cli.Tests/CliTests.cs +++ b/tests/FinalToken.Cli.Tests/CliTests.cs @@ -66,4 +66,26 @@ public class CliTests } finally { Directory.Delete(directory, true); } } + [Fact] + public async Task PrintsFoldedDiagnosticCountAndLastTime() + { + var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + using var output = new StringWriter(); + using var error = new StringWriter(); + var result = await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, path => + { + var engine = new RefreshEngine(path, claudeDirectory: path, codexDirectory: path, + cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")); + for (var i = 0; i < 20; i++) engine.Diagnostics.Add(Provider.Claude, "fixture-parse", "Malformed usage."); + return engine; + }, TestContext.Current.CancellationToken); + Assert.Equal(0, result); + Assert.Contains("fixture-parse (x20, last ", error.ToString()); + Assert.Equal(1, error.ToString().Split('\n').Count(line => line.StartsWith("fixture-parse", StringComparison.Ordinal))); + } + finally { Directory.Delete(directory, true); } + } } diff --git a/tests/FinalToken.Core.Tests/ParserTests.cs b/tests/FinalToken.Core.Tests/ParserTests.cs index f383035..fc6190d 100644 --- a/tests/FinalToken.Core.Tests/ParserTests.cs +++ b/tests/FinalToken.Core.Tests/ParserTests.cs @@ -101,7 +101,7 @@ public class ParserTests { var diagnostics = new DiagnosticLog(capacity: 2); for (var i = 0; i < 4; i++) TranscriptParser.Parse("private fixture text", diagnostics); - Assert.Equal(2, diagnostics.Recent.Count); + Assert.Equal(4, Assert.Single(diagnostics.Recent).Count); Assert.All(diagnostics.Recent, d => Assert.DoesNotContain("private fixture", d.Summary)); } } diff --git a/tests/FinalToken.Core.Tests/ReworkTests.cs b/tests/FinalToken.Core.Tests/ReworkTests.cs new file mode 100644 index 0000000..e5840ba --- /dev/null +++ b/tests/FinalToken.Core.Tests/ReworkTests.cs @@ -0,0 +1,281 @@ +using System.Diagnostics; +using FinalToken.Core.Collectors; +using Xunit; + +namespace FinalToken.Core.Tests; + +public class ReworkTests +{ + [Theory] + [InlineData("", 10)] + [InlineData("fixture-model", 0)] + public void SyntheticAndUnrequestedZeroUsageAreSilent(string model, int input) + { + var line = """{"type":"assistant","message":{"model":"@model","usage":{"input_tokens":@input,"output_tokens":0}}}""" + .Replace("@model", model).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)); + var log = new DiagnosticLog(); + Assert.Null(TranscriptParser.Parse(line, log)); + Assert.Empty(log.Recent); + } + [Fact] + public async Task IdleSaveDoesNotRewriteAnyHistoryFile() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + store.Add(new(Provider.Claude, DateTimeOffset.UtcNow, "model", "project", new(Total: 10), "key")); + await store.SaveAsync(TestContext.Current.CancellationToken); + var before = Directory.GetFiles(directory.Path, "*", SearchOption.AllDirectories) + .ToDictionary(p => p, p => (File.GetLastWriteTimeUtc(p), new FileInfo(p).Length)); + await store.SaveAsync(TestContext.Current.CancellationToken); + Assert.All(before, p => Assert.Equal(p.Value, (File.GetLastWriteTimeUtc(p.Key), new FileInfo(p.Key).Length))); + } + [Fact] + public void UnchangedLimitsAreSampledAtMostHourly() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var now = DateTimeOffset.UtcNow; + var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "fixture"); + store.AddLimits([window]); + store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]); + store.AddLimits([window with { SampleTime = now.AddHours(1) }]); + Assert.Equal(2, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count); + store.AddLimits([window with { UsedPercent = 11, SampleTime = now.AddHours(1).AddMinutes(1) }]); + Assert.Equal(3, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count); + } + [Fact] + public async Task AtomicReplaceSucceedsWhileDeleteSharingReaderRemainsOpen() + { + using var directory = new TestDirectory(); + var path = directory.Write("shared.json", "old"); + using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + await AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken); + Assert.Equal("new", File.ReadAllText(path)); + } + [Fact] + public async Task SharingViolationRetriesAndFailsWithinBound() + { + if (!OperatingSystem.IsWindows()) return; + using var directory = new TestDirectory(); + var path = directory.Write("blocked.json", "old"); + using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + var watch = Stopwatch.StartNew(); + await Assert.ThrowsAsync(() => AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken)); + Assert.InRange(watch.Elapsed.TotalMilliseconds, 400, 3000); + Assert.Equal("old", File.ReadAllText(path)); + Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp")); + } + [Fact] + public void FoldedDiagnosticPreservesOtherProblemsAndTracksLastOccurrence() + { + var clock = new TestClock(); + var log = new DiagnosticLog(clock, 2); + log.Add(Provider.Claude, "parse", "Malformed usage."); + log.Add(Provider.Codex, "timeout", "Probe timed out."); + clock.Advance(TimeSpan.FromMinutes(1)); + for (var i = 0; i < 20; i++) log.Add(Provider.Claude, "parse", "Malformed usage."); + Assert.Equal(2, log.Recent.Count); + var folded = Assert.Single(log.Recent, d => d.Provider == Provider.Claude); + Assert.Equal(21, folded.Count); + Assert.Equal(clock.GetUtcNow(), folded.Time); + } + [Fact] + public async Task UnchangedSourceIsNotOpenedEvenAfterRestart() + { + using var directory = new TestDirectory(); + var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude()); + var log = new DiagnosticLog(); + var store = new HistoryStore(directory.Path, log); + var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path); + Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); + await store.SaveAsync(TestContext.Current.CancellationToken); + store = new(directory.Path, log); + scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path); + using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None); + Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); + Assert.Empty(log.Recent); + } + [Fact] + public async Task TornJournalTailIsIgnoredAndRepairedBeforeNextAppend() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var store = new HistoryStore(directory.Path, new()); + store.Add(new(Provider.Claude, now, "m", "p", new(Total: 10), "one")); + await store.SaveAsync(TestContext.Current.CancellationToken); + var path = Path.Combine(directory.Path, "history.journal.jsonl"); + await File.AppendAllTextAsync(path, "{\"v\":1,\"sequence\":2", TestContext.Current.CancellationToken); + store = new(directory.Path, new()); + Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + store.Add(new(Provider.Claude, now, "m", "p", new(Total: 7), "two")); + await store.SaveAsync(TestContext.Current.CancellationToken); + store = new(directory.Path, new()); + Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + } + [Fact] + public async Task CompactionAndReplayPreserveBucketsKeysAndLimitSets() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var store = new HistoryStore(directory.Path, new()); + var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one"); + store.Add(usage); + store.AddLimits([new(Provider.Claude, "session", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture")]); + await store.SaveAsync(TestContext.Current.CancellationToken); + var committed = File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl")); + await store.CompactAsync(TestContext.Current.CancellationToken); + // Simulate interruption after checkpoint replacement but before journal reset. + directory.Write("history.journal.jsonl", committed); + store = new(directory.Path, new()); + Assert.False(store.Add(usage)); + Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + Assert.Single(store.LimitSamples(Provider.Claude, "session", now.AddHours(-1), now.AddHours(1))); + store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) }); + await store.SaveAsync(TestContext.Current.CancellationToken); + store = new(directory.Path, new()); + Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + } + [Fact] + public async Task ExpiredClaudeKeysCannotRecountOldResumedEntries() + { + using var directory = new TestDirectory(); + var clock = new TestClock(); + var now = clock.GetUtcNow(); + var store = new HistoryStore(directory.Path, new(), clock); + var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "key"); + Assert.True(store.Add(usage)); + await store.SaveAsync(TestContext.Current.CancellationToken); + clock.Advance(TimeSpan.FromDays(61)); + store = new(directory.Path, new(), clock); + Assert.False(store.Add(usage)); + await store.SaveAsync(TestContext.Current.CancellationToken); + await store.CompactAsync(TestContext.Current.CancellationToken); + var stateJson = File.ReadAllText(Path.Combine(directory.Path, "history.state.json")); + Assert.Contains("\"claudeKeys\":{}", stateJson); + Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + } + [Fact] + public async Task SmallUpdateAppendsOnlyItsChanges() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var store = new HistoryStore(directory.Path, new()); + for (var i = 0; i < 1000; i++) store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "key-" + i)); + await store.SaveAsync(TestContext.Current.CancellationToken); + var path = Path.Combine(directory.Path, "history.journal.jsonl"); + var before = new FileInfo(path).Length; + store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "new-key")); + await store.SaveAsync(TestContext.Current.CancellationToken); + var increase = new FileInfo(path).Length - before; + Assert.InRange(increase, 1, 2048); + Assert.True(increase < before / 10); + } + [Fact] + public async Task UnchangedProbeRefreshesSnapshotAgeWithoutWritingHistoryBeforeHourlySample() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var store = new HistoryStore(directory.Path, new()); + var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "usage"); + store.AddLimits([window]); + await store.SaveAsync(TestContext.Current.CancellationToken); + var journal = new FileInfo(Path.Combine(directory.Path, "history.journal.jsonl")); + var length = journal.Length; + var time = journal.LastWriteTimeUtc; + store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]); + await store.SaveAsync(TestContext.Current.CancellationToken); + journal.Refresh(); + Assert.Equal(length, journal.Length); + Assert.Equal(time, journal.LastWriteTimeUtc); + Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime); + } + [Fact] + public async Task LegacyMigrationPreservesTotalsAndDedupeWithoutCodexEventKeys() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var usage = TranscriptParser.Parse(Fixtures.Claude(time: now.ToString("O")), new())!; + var hour = new DateTimeOffset(now.UtcTicks - now.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero); + var legacy = new HistoryData + { + Buckets = [new(Provider.Claude, hour, usage.Model, usage.Project, usage.Counts)], + DedupeKeys = [usage.DedupeKey, $"codex:session-1:{now.UtcTicks}:12"], + CodexTotals = new() { ["session-1"] = new(Input: 10, Output: 2, Total: 12) } + }; + directory.Write("history.json", System.Text.Json.JsonSerializer.Serialize(legacy, CoreJsonContext.Default.HistoryData)); + var store = new HistoryStore(directory.Path, new()); + Assert.False(store.Add(usage)); + Assert.Equal(19, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + await store.CompactAsync(TestContext.Current.CancellationToken); + store = new(directory.Path, new()); + Assert.False(store.Add(usage)); + var stateJson = File.ReadAllText(Path.Combine(directory.Path, "history.state.json")); + Assert.DoesNotContain("codex:session-1:", stateJson); + Assert.Contains("\"codexTotals\":{\"session-1\":", stateJson); + } + [Fact] + public async Task SharingViolationRetriesUntilReaderReleasesItsHandle() + { + if (!OperatingSystem.IsWindows()) return; + using var directory = new TestDirectory(); + var path = directory.Write("briefly-blocked.json", "old"); + using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken); + await Task.Delay(TimeSpan.FromMilliseconds(120), TestContext.Current.CancellationToken); + reader.Dispose(); + await write; + Assert.Equal("new", File.ReadAllText(path)); + } + [Fact] + public async Task PartiallyWrittenCompactionReplaysAbsoluteBucketUpserts() + { + using var directory = new TestDirectory(); + var now = DateTimeOffset.UtcNow; + var hour = new DateTimeOffset(now.UtcTicks - now.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero); + var store = new HistoryStore(directory.Path, new()); + var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one"); + store.Add(usage); + await store.CompactAsync(TestContext.Current.CancellationToken); + store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) }); + await store.SaveAsync(TestContext.Current.CancellationToken); + var month = now.UtcDateTime.ToString("yyyy-MM", System.Globalization.CultureInfo.InvariantCulture); + var partition = new HistoryPartition { Buckets = [new(Provider.Claude, hour, "m", "p", new(Total: 17))] }; + directory.Write("history/" + month + ".json", System.Text.Json.JsonSerializer.Serialize(partition, CoreJsonContext.Default.HistoryPartition)); + store = new(directory.Path, new()); + Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); + Assert.False(store.Add(usage with { DedupeKey = "two" })); + } + [Fact] + public void CompletedCorruptJournalRecordIsRejected() + { + using var directory = new TestDirectory(); + directory.Write("history.journal.jsonl", "{\n"); + Assert.Throws(() => new HistoryStore(directory.Path, new())); + Assert.Equal("{\n", File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl"))); + } + [Fact] + public void LateHistoricalLimitSamplesAreNotLostBehindNewerWindows() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var now = DateTimeOffset.UtcNow; + var window = new LimitWindow(Provider.Codex, "primary", "Session", 10, now.AddHours(5), TimeSpan.FromHours(5), now, "rollout"); + store.AddLimits([window with { UsedPercent = 30, SampleTime = now.AddHours(3) }]); + store.AddLimits([window]); + store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]); + store.AddLimits([window with { SampleTime = now.AddHours(1) }]); + Assert.Equal(3, store.LimitSamples(Provider.Codex, "primary", now.AddSeconds(-1), now.AddHours(4)).Count); + Assert.Equal(30, Assert.Single(store.LatestLimits(Provider.Codex)).UsedPercent); + } + [Fact] + public void LateUnchangedSampleCannotDuplicateHourlyPointAcrossMonthBoundary() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var now = new DateTimeOffset(2026, 10, 1, 0, 10, 0, TimeSpan.Zero); + var window = new LimitWindow(Provider.Codex, "primary", "Week", 10, now.AddDays(5), TimeSpan.FromDays(7), now, "rollout"); + store.AddLimits([window]); + store.AddLimits([window with { SampleTime = now.AddMinutes(-30) }]); + Assert.Single(store.LimitSamples(Provider.Codex, "primary", now.AddHours(-1), now.AddHours(1))); + } +} diff --git a/tests/FinalToken.Core.Tests/StorageTests.cs b/tests/FinalToken.Core.Tests/StorageTests.cs index 3491fe0..72f761e 100644 --- a/tests/FinalToken.Core.Tests/StorageTests.cs +++ b/tests/FinalToken.Core.Tests/StorageTests.cs @@ -22,7 +22,9 @@ public class StorageTests Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); + var previousWrite = File.GetLastWriteTimeUtc(source); await File.WriteAllTextAsync(source, Fixtures.Claude("c"), cancellationToken: TestContext.Current.CancellationToken); + File.SetLastWriteTimeUtc(source, previousWrite.AddSeconds(1)); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); directory.Write("claude/projects/other/copied.jsonl", Fixtures.Claude("b")); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);