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))); } }