Files
frameledger/tests/FrameLedger.App.Tests/SessionExporterTests.cs
poli0981andClaude Fable 5.2 94eec7831c refactor: .NET 11's API where it reads better, and why no C# 15 construct is used yet - the canary, the table, the dispatch trigger for CodeQL (D96) (beta.37 PR-3) (#380)
The owner asked for C# 15 in the release that moved the main line to
.NET 11. The rule approved with the plan: a construct is used only
where the build, CodeQL and Qodana all read it. Each of the four was
written once, in a file of its own, and shown to each tool (draft pull
request #377, closed unmerged; spike-notes section 29):

- The compiler and every analyzer take collection expression arguments,
  closed hierarchies and labeled jumps; a union draws CA1815 from the
  SDK's own rules.
- ReSharper's engine - InspectCode 2026.2.3.1, which Qodana 2026.2
  runs, and 2026.3.0 - reads none: `closed` and `union` are not parsed,
  the other two are called preview features. On a gate of zero every
  file using one would be an error.
- What CodeQL extracts of them is not established: a pull request's C#
  analysis is an overlay on main's database and prints no per-file
  result.

So beta.37 takes API, not syntax:
- sixteen char searches name their comparison through
  string.StartsWith/EndsWith/LastIndexOf(char, StringComparison), where
  they went through a span to satisfy .NET 10 and 11 alike;
- AgentLauncher finds the Agent it started with
  Process.TryGetProcessById instead of a caught ArgumentException.
Nothing changes in what the software does.

codeql.yml takes workflow_dispatch, so a branch can have a full
analysis. 13_CI_CD (C# 15 and the analyses), 20_OPEN_QUESTIONS (a new
row, with what answers it), CLAUDE.md, the decisions index.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 00:04:05 +00:00

162 lines
9.3 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Globalization;
using System.IO;
using System.Text.Json;
using FluentAssertions;
using FrameLedger.App.Charts;
using FrameLedger.App.Services;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Domain.Metrics;
using FrameLedger.Domain.Sessions;
namespace FrameLedger.App.Tests;
/// <summary>FR-9: the CSV's header block and column list are <c>03_METRICS</c> §Export schema's, every row is InvariantCulture, a Tier-2 export has no rows; the JSON carries metadata, aggregates, segments and the annotation.</summary>
public sealed class SessionExporterTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task TheCsvFollowsTheSchemaAndIsCultureInvariant()
{
CultureInfo previous = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("vi-VN"); // a comma decimal separator, to prove invariance
try
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long id = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 40, spikeEvery: 0);
SessionRow row = (await s.Sessions.FindByIdAsync(id, Ct))!;
IReadOnlyList<SegmentRow> segments = await s.Sessions.FindSegmentsAsync(id, Ct);
SessionSeries series = (await new SessionSeriesLoader(s.Sessions).LoadAsync(id, Ct))!;
using var writer = new StringWriter();
SessionExporter.WriteCsv(writer, row, game, new HardwareSnapshot { GpuName = "RTX 5080" }, segments, series);
string[] lines = writer.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().Contain(static l => l.StartsWith("# capture_tier: 1", StringComparison.Ordinal));
lines.Should().Contain(static l => l.StartsWith("# hardware: RTX 5080", StringComparison.Ordinal));
lines.Should().Contain(static l => l.StartsWith("# segment: frames 0-39", StringComparison.Ordinal));
string header = lines.First(static l => !l.StartsWith('#', StringComparison.Ordinal));
header.Should().Be(SessionExporter.CsvColumns);
string[] rows = [.. lines.SkipWhile(static l => l.StartsWith('#', StringComparison.Ordinal)).Skip(1)];
rows.Should().HaveCount(40);
string[] second = rows[1].Split(',');
second.Should().HaveCount(16);
second[0].Should().Be("1");
second[1].Should().Be("16.667", "qpc_ms is relative to the first present, invariant");
second[2].Should().Be("16.667");
second[3].Should().Be("native");
second[8].Should().Be("dlss", "joined from the segment by frame index");
rows.Should().OnlyContain(static r => !r.Contains("16,667", StringComparison.Ordinal), "never the vi-VN decimal comma");
}
finally
{
CultureInfo.CurrentCulture = previous;
}
}
[Fact]
public async Task ATierTwoCsvHasTheHeaderAndNoRowsAndTheJsonCarriesTheRecord()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, hooked: false,
shape: static r => r with { GameVramDedicatedAvgMb = 1000, GameVramDedicatedMedianMb = 1024, GameVramDedicatedMaxMb = 2048, GameMemoryProcesses = 1, GameMemorySource = "counters" });
SessionRow row = (await s.Sessions.FindByIdAsync(id, Ct))!;
await s.Annotations.UpsertAsync(new SessionAnnotation { SessionId = id, Tags = ["bench"], Notes = "n" }, Ct);
using var writer = new StringWriter();
SessionExporter.WriteCsv(writer, row, game, null, [], null);
string[] lines = writer.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().Contain(static l => l.StartsWith("# capture_tier: 2", StringComparison.Ordinal) && l.Contains("no per-frame rows", StringComparison.Ordinal));
lines[^1].Should().Be(SessionExporter.CsvColumns, "the column line is the last line: nothing was measured");
lines.Should().Contain("# display: N/A (not recorded: a session recorded before beta.10, or recovered from its crash file)");
lines.Should().Contain("# game_memory: vram_dedicated_mb avg=1000 median=1024 max=2048; vram_shared_mb max=N/A; ram_private_ws_mb avg=N/A median=N/A max=N/A; ram_ws_mb max=N/A; commit_mb max=N/A; processes=1; source=counters",
"a Tier-2 session has the game's memory too (beta.12): a header line, the session's figure, never a per-frame column");
lines.Should().Contain("# fg_mix: N/A", "beta.24: a session with no stored mix says so");
lines.Should().Contain("# quality_mode: N/A", "beta.24 (D63): no mode was known");
SessionExportDocument doc = SessionExporter.Document(row, game, null, [], await s.Annotations.FindAsync(id, Ct));
using var stream = new MemoryStream();
SessionExporter.WriteJson(stream, doc);
using JsonDocument json = JsonDocument.Parse(stream.ToArray());
json.RootElement.GetProperty("schema").GetString().Should().Be("frameledger-session/1");
json.RootElement.GetProperty("capture_tier").GetInt32().Should().Be(2);
json.RootElement.GetProperty("exit_status").GetString().Should().Be("normal");
json.RootElement.GetProperty("tags")[0].GetString().Should().Be("bench");
json.RootElement.GetProperty("aggregates").GetProperty("session_guid").GetGuid().Should().Be(row.SessionGuid);
json.RootElement.GetProperty("aggregates").TryGetProperty("native_fps", out _).Should().BeFalse("N/A is omitted, never written as 0");
json.RootElement.GetProperty("game").GetString().Should().Be("Alpha");
_ = CaptureTier.NotHooked;
}
/// <summary>beta.24 (D62): the CSV's <c># fg_mix:</c> line is every stored row, invariant; the JSON's aggregates carry the column.</summary>
[Fact]
public async Task TheFgMixHeaderLineIsEveryStoredRowAndTheJsonCarriesTheColumn()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
string mix = FgMixRecord.ToJson(new FgMix([
new FgMixRow(FgMixKind.Generated, 4.0, 70.5, 282, 90, 0.75, 18),
new FgMixRow(FgMixKind.None, null, 118, 118, 30, 0.25, 6),
]))!;
long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, fgMode: "dlssg", native: 70.5, displayed: 282, factor: 4.0, shape: r => r with { FgMixJson = mix });
SessionRow row = (await s.Sessions.FindByIdAsync(id, Ct))!;
using var writer = new StringWriter();
SessionExporter.WriteCsv(writer, row, game, null, [], null);
writer.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
.Should().Contain("# fg_mix: generated x4.00 75.00% native 70.5 displayed 282.0 90.0 s; none 25.00% native 118.0 displayed 118.0 30.0 s");
using var stream = new MemoryStream();
SessionExporter.WriteJson(stream, SessionExporter.Document(row, game, null, [], null));
using JsonDocument json = JsonDocument.Parse(stream.ToArray());
json.RootElement.GetProperty("aggregates").GetProperty("fg_mix_json").GetString().Should().Be(mix);
}
/// <summary>beta.10: the CSV's <c># display:</c> line is the stored milliseconds by name, invariant in every UI language.</summary>
[Fact]
public async Task TheDisplayHeaderLineIsTheStoredMillisecondsByName()
{
CultureInfo previous = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("vi-VN");
try
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, display: new Domain.Display.DisplaySummary
{
ExclusiveMs = 1_500,
BorderlessMs = 60_000,
Changes = 2,
Source = Domain.Display.DisplaySource.SwapChain,
WindowWidth = 2560,
WindowHeight = 1440,
BufferWidth = 2560,
BufferHeight = 1440,
MonitorWidth = 2560,
MonitorHeight = 1440,
MonitorHz = 165,
SwapEffect = "flip_discard",
});
SessionRow row = (await s.Sessions.FindByIdAsync(id, Ct))!;
using var writer = new StringWriter(CultureInfo.InvariantCulture);
SessionExporter.WriteCsv(writer, row, game, null, [], null);
writer.ToString().Split(Environment.NewLine).Should().Contain(
"# display: exclusive_ms=1500; borderless_ms=60000; covers_ms=0; windowed_ms=0; minimized_ms=0; nowindow_ms=0; changes=2; source=swapchain;"
+ " window=2560x1440; buffer=2560x1440; monitor=2560x1440@165");
writer.ToString().Should().Contain("swap_effect: flip_discard", "the swap chain's own description is sessions.swap_effect's first writer");
}
finally
{
CultureInfo.CurrentCulture = previous;
}
}
}