Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.2 5c176fec6e test(guard): the measurement case prints the numbers it parsed, never a line of the log as it stands (SonarCloud cppsecurity:S5145)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 16:38:25 +07:00
poli0981 95ded194ef Merge commit '4f02a17380ebdb39095c7f6e43d15114b41c58ab' into feat/watchdog-grid 2026-11-14 16:15:12 +07:00
poli0981 d2c2ca0464 Merge branch 'feat/latency-frames-log' into feat/watchdog-grid 2026-11-14 15:56:58 +07:00
poli0981andClaude Fable 5.2 58e7b3e556 fix(overlay): the watchdog's periodic tick is on a grid of one second, and a tick the loader woke no longer takes the driver read or publishes region 5 - a read a second whatever a tick's work took (D150, the Overlay's half; in no release yet)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:56:57 +07:00
poli0981andClaude Fable 5.2 207a0c7cdb test(guard): the log case's expected words are widened before they are multiplied (Qodana native: bugprone-implicit-widening-of-multiplication-result, two)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:51:01 +07:00
poli0981andClaude Fable 5.2 e9ff143cc9 feat(overlay): the frames of NVIDIA's latency report are counted for the native log - each by its GPU span and the driver's active time, in batches that belong to one state of the sleep status (D148, D151; nothing published, no new call, no further member; in no release yet)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:26:03 +07:00
13 changed files with 500 additions and 44 deletions

No files matched your search

+11
View File
@@ -49,6 +49,17 @@ numeric core and does not move; the heading is the full version — corrected 20
batch, under a minute. A bug report carries those logs, as it carried them before. Measured: 65 billionths of a
second more for each reading of the report, once a second; a presented frame costs what it did.
### Fixed
- **NVIDIA's latency report is read on a grid of one second, and a busy loader no longer leaves holes in it**
(owner decision D150; the Overlay's half). After a session's first report, 0.4 to 16 % of its samples carried
none — the *Latency* charts had gaps. The Overlay's background thread waited a second *after* each round of its
work, so it fell behind the capture agent, which samples exactly every second; and whenever the game loaded a
library that thread was woken early, published what it had and asked for no new reading, so the round after it
had nothing to publish. Its once-a-second round is now due at fixed moments whatever the work took, and a round
woken early no longer publishes or takes a reading. Two readings are never less than half a second apart.
Nothing on a game's own threads changed.
## Releases
Newest first. Each file holds that release's section exactly as it stood here.
+13 -2
View File
@@ -117,8 +117,19 @@ What the region is, as a contract between the two sides:
(`FlAdvancedState.request`, the word that was `reserved0`). The reader returns only a publication that names the
value it wrote: what a second session of the same game finds in the region before the first tick is the first
session's, and is not read. After an "off" the region keeps its last publication, untouched.
- **One writer, once a second.** The detours keep process-local accumulators; the watchdog copies them here at its
tick. No game thread writes the region, so the seqlock has a single writer: `seq` odd, the fields, `seq` even.
- **One writer, once a second — on a grid since 0.1.0-beta.49 (owner decision D150).** The detours keep
process-local accumulators; the watchdog copies them here at its **periodic** tick, one a second by the
performance counter (`fl_watchdog_tick.h`). Until then it published at *every* tick, and a tick was a second
and its own work after the one before — or at once, whenever the LoadLibrary detour woke the thread. So a
session's publications fell behind the Agent's samples a little with every tick, and a woken tick's publication
took the driver read with it and armed none: the publication after it was empty (0.4 to 16 % of a session's
samples carried no report, HANDOFF item 46; under a loader that never stops, 35 720 publications in eight
seconds and nine reads). A tick woken early still follows the request, installs and takes the census; it writes
nothing here. **A request first seen on a woken tick is published by the periodic tick that follows, however
soon that is**: a session's first publication may hold a moment's worth — one dispatch of a range that has two
ends — and every one after it a second's. A reader takes ranges and "seen" words as *since the request*, which
they are, and never reads a single publication as complete. No game thread writes the region, so the seqlock has a single writer: `seq` odd, the fields,
`seq` even.
- **The reader keeps its last consistent copy** (`ShmRingReader.AdvancedState`): null until something was published
for its request;
the same copy while `seq` has not moved, without copying 1472 bytes again; and that copy still when the writer is
+9 -3
View File
@@ -177,9 +177,15 @@ ids that start again, and the ten words of a publication — and since 0.1.0-bet
refuse nothing) and the bit a multiplier has — and since 0.1.0-beta.49 the counts for the native log: every place
a summed frame can be in, a span of a microsecond, an active time as long as the span, a refused frame, when a
batch is due, a batch closed by a change of state and the thirty-two such closings a request has, the six lines
and what each carries; a hidden `[.bench]` case is the measurement of one report's cost. `fl_guard`'s eight
`[latency]` cases (the eighth reads the log: the first batch after ten reads, by number, and what is left when a
flush is asked for — against the stand-in's `kModeGpuShapes`) inject the Overlay
and what each carries; a hidden `[.bench]` case is the measurement of one report's cost. `fl_watchdog_tick`
(Catch2, no thread and no clock) drives the grid the watchdog's periodic tick is on: sixty ticks each late and
each followed by work keep whole seconds, a wait is never rounded down, a tick woken early is not periodic and
moves nothing, a late tick is not followed by another within half a period. `fl_guard`'s nine `[latency]` cases
(the eighth reads the log: the first batch after ten reads, by number, and what is left when a flush is asked for
— against the stand-in's `kModeGpuShapes`; the ninth keeps the loader waking the watchdog without pause — a
thread that asks for `opengl32.dll` for as long as the target lives — and holds one publication a second, each
with a read, none within half a second of another: 35 720 publications in eight seconds on the code before it; a
hidden `[.measure]` case prints ninety reads' own lines) inject the Overlay
into a Direct3D 12 target that has loaded a stand-in `nvapi64.dll`, and read that module's call counts from outside
through its named section (`fl_stub_nvapi_shared.h`) — so "the driver was not called" is a count: not asked → not
even asked for the addresses; asked → about one read a second, sums equal to the stand-in's, every counted read a
+19 -3
View File
@@ -228,6 +228,20 @@ counts to a batch and writes the batch to the log. **Measured** (the same instru
twice): 424–435 ns before, 490–499 ns after — **+65 ns a read**, once a second, after the call's time has been
taken. `fl_reflex_summary_test "[.bench]"` is that measurement in the tree. The present path is unchanged.
**Since 0.1.0-beta.49 the read is on a grid of one second** (owner decision D150; `fl_watchdog_tick.h`). The
watchdog used to wait a second *after* each tick's work, and a tick the LoadLibrary detour woke was a tick like
any other: it took what the last read left, published it and — less than a second having passed since the last
arm — armed nothing, so the next publication carried no read. The Agent samples on a period of exactly one second
since 0.1.0-beta.48, and its sessions showed the holes: 0.4 to 16 % of a session's samples without a report
(HANDOFF, item 46). Now the watchdog's **periodic** tick is due at a deadline by the performance counter, and the
next deadline is one period after the one that was due, not after the moment the tick ran; a tick woken early
does everything it did — the request is followed and the hooks a session asks for go in at once — **except take
the driver read and publish region 5**, which are the periodic tick's. One read is armed at every periodic tick
(`g_latArmedQpc` and its "a second since the last arm" are gone). A periodic tick that ran more than half a
second late is not followed by another on the grid's next mark: the grid starts again from it, so **two reads are
never less than half a second apart** — "about once a second" still, and no longer "at most". Nothing on a game
thread changed: the presenting thread makes the read when it finds the gate armed, as before. **Measured** on `hook-harness` with the stand-in module, by the batches' own lines (`fl_guard_test "[.measure]"`): ten reads in 9 996 ms, the next twenty in 20 002, the next sixty in 59 997, each batch with as many periodic ticks as reads; and with a thread asking the loader for a module without pause — 18 240, 36 427 and 143 424 early wakes in the three batches — 9 997, 20 000 and 59 999 ms for the same reads. On the code before it the second case published 35 720 times in eight seconds, with nine reads. **Not measured in a game**, and not the whole of the holes: the Agent overwrote a reading that waited for a sample, which is its own change (`07_IPC` §Region 5).
**The gate.** One word, four states — idle, armed, reading, off (`dllmain.cpp`, above `ReadLatencyOnce`). Only the
watchdog arms; a presenting thread takes *armed* to *reading* by compare-exchange and owns the 15.4 KB report
buffer (static storage, never a game thread's stack) and the read's result until it stores *idle* or *off*; the
@@ -950,7 +964,7 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> own two numbers, the span between its two GPU marks and the driver's active render time: no start mark, a span
> of no length, an active time with no span, a span with no active time, and — where a frame has both — *active
> longer than the span* or *active within the span*, each with its count and both sums in microseconds. No
> threshold: a span of one microsecond is a span. **A batch is six lines and belongs to one state of the driver's
> threshold: a span of one microsecond is a span. **A batch is seven lines and belongs to one state of the driver's
> sleep status** — its low-latency switch, its "the game sleeps" switch and its frame-generation multiplier —
> because the counts mean nothing apart from it: a read in another state closes the batch first (thirty-two such
> closings a request, after which a batch runs to its length and its first line says what it held). A batch is
@@ -958,8 +972,10 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> a flush, at a new request and at a stop. `a` is printed in decimal and `b` in hex: *reads* and the switches
> seen on, off (`<<8`) and the multipliers seen (`<<16`); *frames summed* and refused; *GPU span absent* and of no
> length; *active time with no span* and span with no active time; then the two heaps, `a` their frames and `b`
> their span sum (`<<32`) and active sum. **A game that exits by itself takes the batch in hand with it** — under
> a minute of reads. About six lines a minute while a session with *Advanced metrics* reads the driver; none
> their span sum (`<<32`) and active sum; and the watchdog's own line — the *milliseconds the batch spans* and its
> ticks in them, on time (`<<32`) and woken early: a read a second is a thousand milliseconds a read and as many
> periodic ticks as reads (D150). **A game that exits by itself takes the batch in hand with it** — under a
> minute of reads. About seven lines a minute while a session with *Advanced metrics* reads the driver; none
> otherwise.
> **Three flush points — four since beta.42, the same note —, none on a present path:** the end of `InitThread` (so the
> file exists from the start of the session and a crash mid-session still leaves it), the watchdog when
+1 -1
View File
@@ -852,7 +852,7 @@ public enum FlLatencyState : uint
/// <summary>A getter faulted: off until the game exits.</summary>
Faulted = 8,
/// <summary>A call had not returned after a second: nothing can stop it.</summary>
/// <summary>A call had not returned after two seconds: nothing can stop it.</summary>
Stalled = 9,
}
@@ -892,6 +892,10 @@ inline uint32_t LatencyMultiplierBit(uint32_t value) noexcept {
//
// A batch is also closed after the request's tenth read, its thirtieth, and every sixtieth from there: a game that
// exits takes the watchdog with it, and what was not written by then is lost -- under a minute of it.
//
// AND HOW EVENLY THE READS CAME (owner decision D150): the milliseconds the batch spans and the watchdog's ticks in
// them, periodic and woken early. A read a second is a thousand milliseconds a read and as many periodic ticks as
// reads; anything else says which side of it was uneven.
// ---------------------------------------------------------------------------------------------------------------------
inline constexpr uint32_t kLatBatchFirst = 10u;
inline constexpr uint32_t kLatBatchSecond = 30u;
@@ -909,6 +913,10 @@ struct LatencyBatch {
uint32_t sleepOff = 0; // ... and off
uint32_t multipliers = 0; // LatencyMultiplierBit of every multiplier it gave
uint32_t state = kLatStateUnknown; // LatencyStateOf its first read
// The watchdog's own, set by it: not a read's.
uint32_t spannedMs = 0; // from the batch before -- or the request -- to this one's writing
uint32_t ticksOnTime = 0; // its periodic ticks in that time
uint32_t ticksEarly = 0; // ... and the ticks something woke early
};
struct LatencyBatchBook {
@@ -971,7 +979,7 @@ inline void LatencyBatchAdd(LatencyBatchBook& book, const LatencyTally& tally, b
}
// The batch as lines of the native log: a text, the line's `a` (printed in decimal) and its `b` (printed in hex).
inline constexpr uint32_t kLatBatchLines = 6u;
inline constexpr uint32_t kLatBatchLines = 7u;
struct LatencyLogLine {
const char* text;
@@ -997,9 +1005,12 @@ constexpr LatencyLogLine LatencyBatchLine(const LatencyBatch& batch, uint32_t li
case 4u:
return {"active longer than span: frames / span us<<32 | active us", batch.gpu.longerFrames,
LatencyPair(batch.gpu.longerSpanUs, batch.gpu.longerActiveUs)};
default:
case 5u:
return {"active within span: frames / span us<<32 | active us", batch.gpu.withinFrames,
LatencyPair(batch.gpu.withinSpanUs, batch.gpu.withinActiveUs)};
default:
return {"ms spanned / watchdog ticks on time<<32 | woken early", batch.spannedMs,
LatencyPair(batch.ticksOnTime, batch.ticksEarly)};
}
}
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// When the Overlay's watchdog makes its PERIODIC tick (0.1.0-beta.49, owner decision D150).
//
// WHAT WAS WRONG. The watchdog waited a second AFTER each tick's work, so its ticks were a second and that work
// apart -- and a tick the LoadLibrary detour woke early counted as a tick like any other. The driver's latency
// report is read once for each tick that arms it, and region 5 is published once a tick; the Agent samples on a
// period of exactly one second. So the Overlay fell behind the Agent a little with every tick, a woken tick took a
// read and armed none, and a session's samples had holes: 0.4 to 16 % of them carried no report (HANDOFF, item 46).
//
// WHAT THIS IS. A grid in performance-counter ticks: the periodic tick is due at a deadline, and the next deadline is
// one period after the one that was due -- not after the moment the tick ran, so nothing accumulates. A tick woken
// early is still a tick (the loader's signals must be acted on at once) but not a periodic one: it does not move the
// grid. A periodic tick that ran more than half a period late does not get a second one right behind it: the grid
// starts again from that tick, so two periodic ticks are never less than half a period apart.
//
// Pure arithmetic, no call: the watchdog's loop (dllmain.cpp) is the only user, and fl_watchdog_tick_test drives it
// without a thread.
#ifndef FRAMELEDGER_FL_WATCHDOG_TICK_H
#define FRAMELEDGER_FL_WATCHDOG_TICK_H
#include <cstdint>
namespace fl::watchdog {
struct Grid {
int64_t period = 1; // performance-counter ticks between two periodic ticks
int64_t deadline = 0; // the counter value the next periodic tick is due at
};
inline void StartGrid(Grid& grid, int64_t now, int64_t period) noexcept {
grid.period = period > 0 ? period : 1;
grid.deadline = now + grid.period;
}
// How long to wait for the periodic tick, in whole milliseconds ROUNDED UP -- a wait rounded down ends before the
// deadline and would have to be followed by another of a millisecond -- and never more than `ceilingMs`. Zero when
// the tick is due.
inline uint32_t WaitMs(const Grid& grid, int64_t now, int64_t frequency, uint32_t ceilingMs) noexcept {
if (now >= grid.deadline || frequency <= 0) {
return 0u;
}
const int64_t ms = ((grid.deadline - now) * 1000 + frequency - 1) / frequency;
return ms > static_cast<int64_t>(ceilingMs) ? ceilingMs : static_cast<uint32_t>(ms);
}
// Whether the tick that begins at `now` is the periodic one. A wait that timed out is: Windows counts a timeout in
// its own clock's ticks, so it may end a little short of the deadline by this counter, and that tick is the one the
// wait was for. A wait a signal ended is periodic only when the deadline has passed all the same.
inline bool IsPeriodic(const Grid& grid, int64_t now, bool timedOut) noexcept {
return timedOut || now >= grid.deadline;
}
// The grid after a periodic tick that began at `now`.
inline void Advance(Grid& grid, int64_t now) noexcept {
const int64_t next = grid.deadline + grid.period;
grid.deadline = next - now < grid.period / 2 ? now + grid.period : next;
}
} // namespace fl::watchdog
#endif // FRAMELEDGER_FL_WATCHDOG_TICK_H
+59 -24
View File
@@ -61,6 +61,7 @@
#include <fl_sl_inputs.h>
#include <fl_sl_seen.h>
#include <fl_tolerance.h>
#include <fl_watchdog_tick.h>
#include <knownfolders.h>
#include <MinHook.h>
#include <shlobj_core.h>
@@ -758,10 +759,12 @@ void PublishD3D12Device(ID3D12Device* device) noexcept {
// Nothing is hooked for it and nothing is loaded for it.
//
// WHO DOES WHAT. The WATCHDOG finds the module and the two addresses, once for the process, and arms the gate at
// most once a second. A PRESENTING THREAD that finds the gate armed makes the read, after its frame's record is
// published: a call the driver holds stops the thread that made it, and the watchdog -- which supervises, installs
// and flushes -- must never be that thread (spike-notes §31, M2). So the call delays one present a second by its own
// length: 0.5-2.6 us measured, and one of 2 ms or more is the last one this process makes (D141).
// each of its PERIODIC ticks -- one a second on a grid, never two within half a second (fl_watchdog_tick.h; until
// 0.1.0-beta.49 "at most once a second", on ticks a second and their own work apart). A PRESENTING THREAD that finds
// the gate armed makes the read, after its frame's record is published: a call the driver holds stops the thread that
// made it, and the watchdog -- which supervises, installs and flushes -- must never be that thread (spike-notes §31,
// M2). So the call delays one present a second by its own length: 0.5-2.6 us measured, and one of 2 ms or more is the
// last one this process makes (D141).
//
// THE GATE, four states in one word, is what makes that safe without a lock:
// idle nobody is reading. g_latRead is the watchdog's: it takes what the last read left, then may arm.
@@ -809,11 +812,11 @@ fl::adv::LatencyOut g_latOut;
bool g_latResolved = false; // the two addresses are in g_latApi
bool g_latFinal = false; // the module was looked at and will not be read; g_latOut.state says why
bool g_latStalled = false;
int64_t g_latArmedQpc = 0;
int64_t g_latReadingSinceQpc = 0;
uint32_t g_latLoggedState = FL_LAT_NONE;
// The frame counts of the reads, for the native log only (fl_adv_fields.h; owner decisions D148, D151).
fl::adv::LatencyBatchBook g_latBook;
int64_t g_latBatchBeganQpc = 0; // the request's start, or the batch before's writing
// One read, on a presenting thread that found the gate armed. Not inlined: RecordPresent stays as small as it was.
__declspec(noinline) void ReadLatencyOnce() noexcept {
@@ -907,19 +910,27 @@ void WriteLatencyBatch() noexcept {
if (g_latBook.batch.reads == 0u) {
return;
}
const int64_t now = QpcNow();
const uint64_t ticks = now > g_latBatchBeganQpc ? static_cast<uint64_t>(now - g_latBatchBeganQpc) : 0u;
const uint64_t millis = g_logQpcFreq != 0u ? ticks * 1000ull / g_logQpcFreq : 0u;
g_latBook.batch.spannedMs = millis > 0xFFFFFFFFull ? 0xFFFFFFFFu : static_cast<uint32_t>(millis);
for (uint32_t line = 0; line < fl::adv::kLatBatchLines; ++line) {
const fl::adv::LatencyLogLine entry = fl::adv::LatencyBatchLine(g_latBook.batch, line);
LogNote(kLogLatencyFrames, entry.text, entry.a, entry.b);
}
g_latBook.batch = fl::adv::LatencyBatch{};
g_latBatchBeganQpc = now;
}
// THE WATCHDOG'S HALF, once a tick while a session asks. `now` is this tick's QPC.
// THE WATCHDOG'S HALF, once a PERIODIC tick while a session asks -- never on a tick something woke early, so that
// what it takes is the read its last call armed and what it arms is taken by its next (owner decision D150). `now`
// is this tick's QPC.
void TickLatency(bool newRequest, int64_t now) noexcept {
if (newRequest) {
// What the session before left of a batch is its own, written before this one's counts begin.
WriteLatencyBatch();
g_latBook = fl::adv::LatencyBatchBook{};
g_latBatchBeganQpc = now;
// A session's counts are its own; where the read stands is the process's and stays.
g_latOut.reads = 0u;
g_latOut.worstUs = 0u;
@@ -1037,10 +1048,10 @@ void TickLatency(bool newRequest, int64_t now) noexcept {
return;
}
}
if (g_latArmedQpc == 0 || static_cast<uint64_t>(now - g_latArmedQpc) >= g_logQpcFreq) {
g_latArmedQpc = now;
g_latGate.store(kLatGateArmed, std::memory_order_release);
}
// One read for each periodic tick. Until 0.1.0-beta.49 this asked that a second had passed since the last arm:
// a tick a moment early then armed nothing, and the publication after it carried no read. The grid is what keeps
// two of these apart now -- half a second at the least.
g_latGate.store(kLatGateArmed, std::memory_order_release);
}
// The request went off: a read that was wanted and not yet made is not made in a session that never asked.
@@ -1964,7 +1975,7 @@ PFN_LoadLibraryExW g_origLoadLibraryExW = nullptr;
constexpr uint32_t kLoaderInstalledBit = 0x8000u;
constexpr uint32_t kLoaderCountMask = 0x7FFFu;
std::atomic<uint32_t> g_loaderSignals{0};
// Auto-reset; the watchdog waits on it with its 1 s timeout, so a signal ends the
// Auto-reset; the watchdog waits on it until its periodic tick is due, so a signal ends the
// wait early and a missing event (creation failed) degrades to the plain sleep.
HANDLE g_watchdogWake = nullptr;
@@ -3570,13 +3581,30 @@ bool InstallRtHooks() noexcept {
// exists; see the block comment above for why a thread is acceptable in the
// Overlay and was not in the Vulkan layer.
DWORD WatchdogLoop() noexcept {
// THE PERIODIC TICK IS ON A GRID (fl_watchdog_tick.h; owner decision D150): one a second by the performance
// counter, whatever a tick's work took and however often the loader woke this thread in between.
const auto frequency = static_cast<int64_t>(g_logQpcFreq);
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, QpcNow(), frequency * kWatchdogIntervalMs / 1000);
bool latencyRequestIsNew = false; // a request not yet handed to TickLatency, which runs on periodic ticks
for (;;) {
// The 1 s tick, OR the LoadLibrary detour's wake -- whichever comes first.
// An event that failed to create degrades to the plain sleep.
// The periodic tick's deadline, OR the LoadLibrary detour's wake -- whichever comes first. An event that
// failed to create, or a wait that failed, degrades to the plain sleep.
const DWORD waitMs = fl::watchdog::WaitMs(grid, QpcNow(), frequency, kWatchdogIntervalMs);
bool timedOut = true;
if (g_watchdogWake != nullptr) {
WaitForSingleObject(g_watchdogWake, kWatchdogIntervalMs);
const DWORD waited = WaitForSingleObject(g_watchdogWake, waitMs);
if (waited == WAIT_FAILED) {
Sleep(waitMs);
}
timedOut = waited != WAIT_OBJECT_0;
} else {
Sleep(kWatchdogIntervalMs);
Sleep(waitMs);
}
const int64_t tickQpc = QpcNow();
const bool periodic = fl::watchdog::IsPeriodic(grid, tickQpc, timedOut);
if (periodic) {
fl::watchdog::Advance(grid, tickQpc);
}
if (g_observing.load(std::memory_order_acquire) == 0) {
@@ -3606,24 +3634,31 @@ DWORD WatchdogLoop() noexcept {
// one writer. With the word at 0 nothing more is read in any hook and the region is never touched. A request
// not seen before is a new session's: the summaries start afresh BEFORE the detours are let in, so a range or
// a count never spans two sessions of a game that kept running.
//
// THE REQUEST IS FOLLOWED ON EVERY TICK, THE REGION IS WRITTEN ON THE PERIODIC ONE (0.1.0-beta.49, D150). The
// installers below put in the hooks a session asked for in the very tick that saw the request -- a tick the
// loader woke, when the game has just loaded Streamline -- so the word is read and the flag stored whatever
// the tick. The read of the driver and the publication are once a second: a tick woken early used to take the
// read, publish it and arm nothing, and the publication after it had no read in it.
std::atomic_ref<uint32_t> advancedReq{g_control->advancedRequested};
const uint32_t advancedNow = advancedReq.load(std::memory_order_acquire);
const bool advancedIsNew = advancedNow != 0u && advancedNow != g_advancedSeen;
if (advancedIsNew) {
if (advancedNow != 0u && advancedNow != g_advancedSeen) {
fl::adv::Reset(g_adv);
g_advancedSeen = advancedNow;
latencyRequestIsNew = true;
}
g_advancedRequested.store(advancedNow != 0u ? 1u : 0u, std::memory_order_relaxed);
if (advancedNow != 0u) {
// Initialised through QuadPart, the member read below, so that it is the active one (cpp:S6232).
LARGE_INTEGER advancedQpc{.QuadPart = 0};
QueryPerformanceCounter(&advancedQpc);
if (advancedNow == 0u) {
DisarmLatency();
} else if (periodic) {
++g_latBook.batch.ticksOnTime;
// The driver's latency report (train C): what the last read left is taken, and the next one armed,
// BEFORE the publication -- so the publication carries the read, and carries it once.
TickLatency(advancedIsNew, advancedQpc.QuadPart);
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(advancedQpc.QuadPart), &g_latOut);
TickLatency(latencyRequestIsNew, tickQpc);
latencyRequestIsNew = false;
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(tickQpc), &g_latOut);
} else {
DisarmLatency();
++g_latBook.batch.ticksEarly;
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
+1 -1
View File
@@ -1003,7 +1003,7 @@ enum FlLatencyState : uint32_t {
FL_LAT_ERROR = 6, // the last read returned an NVAPI status that is not OK; reading goes on
FL_LAT_SLOW = 7, // one call took 2 ms or more: off until the game exits (D141)
FL_LAT_FAULTED = 8, // a getter faulted: off until the game exits, and counted once in faultCount
FL_LAT_STALLED = 9, // a call had not returned after a second: nothing can stop it; reported and left
FL_LAT_STALLED = 9, // a call had not returned after two seconds: nothing can stop it; reported and left
};
// latState, above the state: the driver's sleep status as SEEN -- a switch can be in both groups in one session.
+10
View File
@@ -207,6 +207,16 @@ target_compile_definitions(fl_reflex_summary_test PRIVATE WIN32_LEAN_AND_MEAN NO
add_test(NAME fl_reflex_summary COMMAND fl_reflex_summary_test)
fl_catch2_test_completes(fl_reflex_summary)
# fl_watchdog_tick.h (0.1.0-beta.49, D150): when the Overlay's watchdog makes its periodic tick -- a grid that does
# not drift with a tick's work, a tick woken early that does not move it, a wait never rounded down, and two
# periodic ticks never within half a period. Pure arithmetic: no thread, no clock, no Windows header.
add_executable(fl_watchdog_tick_test watchdog_tick_test.cpp)
target_include_directories(fl_watchdog_tick_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_link_libraries(fl_watchdog_tick_test PRIVATE fl_native_flags Catch2::Catch2WithMain)
target_compile_options(fl_watchdog_tick_test PRIVATE /EHsc)
add_test(NAME fl_watchdog_tick COMMAND fl_watchdog_tick_test)
fl_catch2_test_completes(fl_watchdog_tick)
# fl_ffx_types.h (0.1.0-beta.42, D121): the descriptor types an ffx-api module was handed, kept by the detours for
# the native log. The header the Overlay compiles, driven without the Overlay -- including from eight threads.
add_executable(fl_ffx_types_test ffx_types_test.cpp)
+194 -5
View File
@@ -21,6 +21,7 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <cwchar>
@@ -6198,6 +6199,38 @@ bool LogHasLine(const std::string& text, const char* code, const std::string& na
return false;
}
// The `a` and `b` of the LAST line of this code whose text starts with `name`; false when there is none.
bool LogLineWords(const std::string& text, const char* code, const std::string& name, uint32_t& a, uint64_t& b) {
const std::string head = std::string("s ") + code + " ";
bool found = false;
std::size_t at = 0;
while (at < text.size()) {
std::size_t end = text.find('\n', at);
if (end == std::string::npos) {
end = text.size();
}
const std::string line = text.substr(at, end - at);
const std::size_t h = line.find(head);
const std::size_t words = line.rfind(" a=");
if (h != std::string::npos && words != std::string::npos) {
std::size_t n = h + head.size();
while (n < line.size() && line[n] == ' ') {
++n;
}
unsigned first = 0;
unsigned long long second = 0;
if (line.compare(n, name.size(), name) == 0 &&
sscanf_s(line.c_str() + words, " a=%u b=0x%llx", &first, &second) == 2) {
a = first;
b = second;
found = true;
}
}
at = end + 1;
}
return found;
}
std::size_t CountOf(const std::string& text, const char* needle) {
std::size_t n = 0;
for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) {
@@ -7344,6 +7377,13 @@ TEST_CASE("FSR's plane at infinity (beta.42, D119): a far plane of FLT_MAX reach
SetAdvancedRequest(r, 11u);
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 11u, a, 0u, fl::FL_ADV_VALID_FFX_UPSCALE));
// The ranges are since the request, and the first publication that carries the descriptor may hold one dispatch
// of it: since 0.1.0-beta.49 a request seen on a tick the loader woke is published by the periodic tick that
// follows, however soon that is. The field of view alternates, so both of its values have been seen once the
// range is one.
for (int i = 0; i < 5 && a.ffxFovMinBits == a.ffxFovMaxBits; ++i) {
REQUIRE(ReadAdvanced(r, 11u, a, a.samples, fl::FL_ADV_VALID_FFX_UPSCALE));
}
INFO("near 0x" << std::hex << a.ffxNearBits << " far 0x" << a.ffxFarBits);
CHECK(a.ffxFarBits == FL_ADV_FLOAT_INFINITE);
CHECK(std::bit_cast<float>(a.ffxFarBits) > 3.0e38f); // the float it decodes to IS infinity
@@ -7904,7 +7944,7 @@ TEST_CASE("the frames a read summed are counted in the native log, each by its G
continue;
}
text = ReadWholeFile(log);
complete = CountOf(text, "LATENCY_FRAMES") >= 6u;
complete = CountOf(text, "LATENCY_FRAMES") >= 7u;
}
INFO("log " << Narrow(log) << ":\n" << text);
REQUIRE(complete);
@@ -7912,7 +7952,17 @@ TEST_CASE("the frames a read summed are counted in the native log, each by its G
INFO("line " << line << ": " << names[line] << " ..." << tails[line]);
CHECK(LogHasLine(text, "LATENCY_FRAMES", names[line], tails[line]));
}
CHECK(CountOf(text, "LATENCY_FRAMES") == 6u); // one batch: the next is twenty reads away
// The seventh line is the watchdog's own: ten reads took about ten seconds and ten periodic ticks or a few more
// (the ticks before the module was found), and the loader woke it at most a few times.
uint32_t spannedMs = 0;
uint64_t ticks = 0;
REQUIRE(LogLineWords(text, "LATENCY_FRAMES", "ms spanned", spannedMs, ticks));
CHECK(spannedMs >= 9000u);
CHECK(spannedMs <= 16000u);
CHECK((ticks >> 32) >= 10u);
CHECK((ticks >> 32) <= 16u);
CHECK((ticks & 0xFFFFFFFFu) <= 8u);
CHECK(CountOf(text, "LATENCY_FRAMES") == 7u); // one batch: the next is twenty reads away
CHECK(r.ctl->logFlushRequested == 0u); // nobody asked for it
// What is published is what it was: these counts are the log's.
@@ -7924,7 +7974,7 @@ TEST_CASE("the frames a read summed are counted in the native log, each by its G
}
// ---- THE REST, WHEN THE AGENT ASKS. A few reads more, then a flush request: the batch in hand is written with
// the log, six lines whose frames are ten a read.
// the log, seven lines whose frames are ten a read.
TickFor(r, 3200);
++r.ctl->logFlushRequested;
complete = false;
@@ -7933,12 +7983,12 @@ TEST_CASE("the frames a read summed are counted in the native log, each by its G
Sleep(50);
if (i % 10 == 9) {
text = ReadWholeFile(log);
complete = CountOf(text, "LATENCY_FRAMES") >= 12u;
complete = CountOf(text, "LATENCY_FRAMES") >= 14u;
}
}
INFO("log after the flush request:\n" << text);
REQUIRE(complete);
CHECK(CountOf(text, "LATENCY_FRAMES") == 12u);
CHECK(CountOf(text, "LATENCY_FRAMES") == 14u);
bool rest = false;
for (uint32_t reads = 1u; reads < 20u && !rest; ++reads) { // the thirtieth read would close it itself
char frames[32]{};
@@ -7949,6 +7999,145 @@ TEST_CASE("the frames a read summed are counted in the native log, each by its G
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("a watchdog the loader keeps waking reads the driver once a second all the same, and every publication "
"carries a read",
"[guard][inject][shm][advanced][latency][log]") {
// WHAT A REAL SESSION SHOWED (HANDOFF, item 46): 0.4 to 16 % of a session's samples carried no report. The
// watchdog's ticks were a second and their own work apart, and a tick the LoadLibrary detour woke took the read,
// published it and armed none. Here a thread asks the loader for opengl32.dll for as long as the target lives --
// a module the detour wakes the watchdog for, and one the harness already holds, so nothing is ever unloaded
// under a hook: the watchdog is woken without pause. Until 0.1.0-beta.49 every such tick published region 5.
// (sl.common.dll, D123's churn, wakes nobody: it is in neither the inventory nor the census.)
LatencyTarget t;
const std::wstring presenting = L"--churn-module opengl32.dll --hold-presenting-d3d12 30";
REQUIRE(StartLatencyTarget(t, LatencyArgs(presenting.c_str()), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return; // not reached after the REQUIRE; said in the form a static analyser follows (cpp:S2259)
}
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState first{};
REQUIRE(ReadAdvanced(r, 7u, first, 0u, fl::FL_ADV_VALID_LATENCY)); // the first publication with a read
// Eight seconds of publications, looked for every 20 ms: far finer than the half second two may be apart.
uint32_t lastSamples = first.samples;
uint32_t withFrames = 0;
uint32_t withoutFrames = 0;
bool twoAtOnce = false;
long long closestMs = 1'000'000;
const auto began = std::chrono::steady_clock::now();
auto lastAt = began;
bool haveLast = false;
while (std::chrono::steady_clock::now() - began < std::chrono::milliseconds(8000)) {
++r.ctl->guardTicks;
Sleep(20);
fl::FlAdvancedState a{};
if (!CopyAdvanced(r, a) || a.request != 7u || a.samples == lastSamples) {
continue;
}
const auto at = std::chrono::steady_clock::now();
twoAtOnce = twoAtOnce || a.samples != lastSamples + 1u;
if (haveLast) {
const long long apart = std::chrono::duration_cast<std::chrono::milliseconds>(at - lastAt).count();
closestMs = apart < closestMs ? apart : closestMs;
}
haveLast = true;
lastAt = at;
lastSamples = a.samples;
if ((a.latFrames & 0xFFFFu) != 0u) {
++withFrames;
} else {
++withoutFrames;
}
}
const uint32_t publications = lastSamples - first.samples;
INFO("publications " << publications << " in eight seconds: " << withFrames << " with frames, " << withoutFrames
<< " without; the two closest " << closestMs << " ms apart; stub calls "
<< StubWord(stub->latencyCalls));
CHECK(publications >= 6u);
CHECK(publications <= 9u); // one a second: not one for every time the loader woke the thread
CHECK_FALSE(twoAtOnce); // never two inside one look
CHECK(closestMs >= 400); // half a second at the least, less what the looking itself costs
CHECK(withoutFrames <= 1u); // a publication carries the read its tick's predecessor armed
CHECK(withFrames + 1u >= publications);
CHECK(StubWord(stub->latencyCalls) + 2u >= publications);
CHECK(StubWord(stub->latencyCalls) <= publications + 3u);
// THE FIXTURE DID WAKE IT: the batch's own line says how many ticks were on time and how many were woken early.
++r.ctl->logFlushRequested;
std::wstring log;
std::string text;
uint32_t spannedMs = 0;
uint64_t ticks = 0;
bool written = false;
for (int i = 0; i < 100 && !written; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 10 != 9 || (log.empty() && !FindOverlayLog(t.child.pi.dwProcessId, t.child.pi.hProcess, log))) {
continue;
}
text = ReadWholeFile(log);
written = LogLineWords(text, "LATENCY_FRAMES", "ms spanned", spannedMs, ticks);
}
INFO("log " << Narrow(log) << ":\n" << text);
REQUIRE(written);
const auto onTime = static_cast<uint32_t>(ticks >> 32);
const auto wokenEarly = static_cast<uint32_t>(ticks & 0xFFFFFFFFu);
INFO("the batch spans " << spannedMs << " ms: " << onTime << " ticks on time, " << wokenEarly << " woken early");
CHECK(wokenEarly > 20u); // or this case proved nothing about a woken watchdog
CHECK(onTime >= 6u);
CHECK(onTime * 1000u <= spannedMs + 1500u); // a tick a second, by the batch's own clock
CHECK(r.st->faultCount == 0u);
}
// A number for a pull request, not a gate: how evenly the reads come over a minute and a half, by the batches' own
// seventh line. Hidden: `fl_guard_test "[.measure]"`.
TEST_CASE("how evenly the driver is read over ninety reads, with a quiet loader and with one that never stops",
"[.measure]") {
for (const wchar_t* presenting :
{L"--hold-presenting-d3d12 110", L"--churn-module opengl32.dll --hold-presenting-d3d12 110"}) {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(presenting), true));
const MappedRing& r = t.r;
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
std::wstring log;
std::string text;
for (int i = 0; i < 2100 && CountOf(text, "ms spanned") < 3u; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 20 == 19 && (!log.empty() || FindOverlayLog(t.child.pi.dwProcessId, t.child.pi.hProcess, log))) {
text = ReadWholeFile(log);
}
}
// The numbers of each batch's first and last line, parsed: what a file held is never printed as it stands
// (SonarCloud's cppsecurity:S5145 on a line of the log handed to printf).
std::printf("%ls\n", presenting);
std::size_t at = 0;
while (at < text.size()) {
std::size_t end = text.find('\n', at);
end = end == std::string::npos ? text.size() : end;
const std::string line = text.substr(at, end - at);
const std::size_t words = line.rfind(" a=");
unsigned first = 0;
unsigned long long second = 0;
if (line.find("LATENCY_FRAMES") != std::string::npos && words != std::string::npos &&
sscanf_s(line.c_str() + words, " a=%u b=0x%llx", &first, &second) == 2) {
if (line.find("reads /") != std::string::npos) {
std::printf(" %u reads", first);
} else if (line.find("ms spanned") != std::string::npos) {
std::printf(" in %u ms: %llu ticks on time, %llu woken early\n", first, second >> 32,
second & 0xFFFFFFFFull);
}
}
at = end + 1;
}
CHECK(CountOf(text, "ms spanned") >= 3u);
}
}
TEST_CASE("the driver's latency report is read only while a session asks, once a second, and stops with the request "
"and with the hooks",
"[guard][inject][shm][advanced][latency]") {
+7 -3
View File
@@ -485,7 +485,7 @@ TEST_CASE("a batch belongs to one state of the sleep status: another state close
CHECK(sum == 0xFFFFFFFFu);
}
TEST_CASE("a batch is six lines of the log: a text that fits, a count in decimal, and a word in hex", "[latency]") {
TEST_CASE("a batch is seven lines of the log: a text that fits, a count in decimal, and a word in hex", "[latency]") {
fl::adv::LatencyBatch batch;
batch.reads = 10u;
batch.frames = 152u;
@@ -503,10 +503,14 @@ TEST_CASE("a batch is six lines of the log: a text that fits, a count in decimal
batch.gpu.withinFrames = 26u;
batch.gpu.withinSpanUs = 96200u;
batch.gpu.withinActiveUs = 91000u;
batch.spannedMs = 10012u;
batch.ticksOnTime = 10u;
batch.ticksEarly = 3u;
const std::uint64_t expectedB[fl::adv::kLatBatchLines] = {
0x41609ull, 3ull, 61ull, 31ull, (111000ull << 32) | 120000ull, (96200ull << 32) | 91000ull};
const std::uint32_t expectedA[fl::adv::kLatBatchLines] = {10u, 152u, 5u, 30u, 30u, 26u};
0x41609ull, 3ull, 61ull, 31ull, (111000ull << 32) | 120000ull, (96200ull << 32) | 91000ull,
(10ull << 32) | 3ull};
const std::uint32_t expectedA[fl::adv::kLatBatchLines] = {10u, 152u, 5u, 30u, 30u, 26u, 10012u};
for (std::uint32_t line = 0; line < fl::adv::kLatBatchLines; ++line) {
const fl::adv::LatencyLogLine entry = fl::adv::LatencyBatchLine(batch, line);
INFO("line " << line << ": " << entry.text);
+99
View File
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// fl_watchdog_tick.h: when the Overlay's watchdog makes its periodic tick (0.1.0-beta.49, owner decision D150),
// driven without a thread and without a clock -- the header the Overlay compiles, on counter values written here.
//
// What it holds: the grid does not drift with the work of a tick or with the lateness of a wake; a tick woken early
// is not the periodic one and does not move the grid; a wait is never rounded down to end before its deadline; and
// two periodic ticks are never less than half a period apart, however late one ran.
#include <catch2/catch_test_macros.hpp>
#include <cstdint>
#include <fl_watchdog_tick.h>
namespace {
constexpr std::int64_t kFrequency = 10'000'000; // the performance counter's on the machines this runs on
constexpr std::int64_t kPeriod = kFrequency; // one second
constexpr std::int64_t kMs = kFrequency / 1000;
} // namespace
TEST_CASE("the periodic tick keeps a grid of one period whatever each tick's work and lateness were", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 5 * kPeriod, kPeriod);
CHECK(grid.deadline == 6 * kPeriod);
// Sixty ticks, each begun 3 to 17 ms after its deadline (the timer's own granularity and a busy machine) and each
// followed by work of up to 240 ms: the deadlines stay whole seconds.
std::int64_t now = 5 * kPeriod;
for (std::int64_t tick = 0; tick < 60; ++tick) {
const std::uint32_t wait = fl::watchdog::WaitMs(grid, now, kFrequency, 1000u);
CHECK(wait <= 1000u);
CHECK(now + wait * kMs >= grid.deadline); // never rounded down to end short of it
now = grid.deadline + (3 + tick % 15) * kMs;
REQUIRE(fl::watchdog::IsPeriodic(grid, now, true));
fl::watchdog::Advance(grid, now);
CHECK(grid.deadline == (7 + tick) * kPeriod);
now += (tick % 5) * 60 * kMs; // the tick's work
}
}
TEST_CASE("a wait is whole milliseconds rounded up, zero when the tick is due, and never longer than its ceiling",
"[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
CHECK(fl::watchdog::WaitMs(grid, 0, kFrequency, 1000u) == 1000u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 5 * kMs, kFrequency, 1000u) == 5u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 5 * kMs + 1, kFrequency, 1000u) == 5u); // 4.9999 ms: five, not four
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 1, kFrequency, 1000u) == 1u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod, kFrequency, 1000u) == 0u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod + 40 * kMs, kFrequency, 1000u) == 0u);
CHECK(fl::watchdog::WaitMs(grid, -3 * kPeriod, kFrequency, 1000u) == 1000u); // a counter that went back
CHECK(fl::watchdog::WaitMs(grid, 0, 0, 1000u) == 0u); // no frequency: no wait to compute
}
TEST_CASE("a tick something woke early is not the periodic one and leaves the grid where it was", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
const std::int64_t deadline = grid.deadline;
// Five wakes inside one period: none is periodic, and the wait after each is what is left to the same deadline.
for (std::int64_t wake = 1; wake <= 5; ++wake) {
const std::int64_t now = wake * 150 * kMs;
CHECK_FALSE(fl::watchdog::IsPeriodic(grid, now, false));
CHECK(grid.deadline == deadline);
CHECK(fl::watchdog::WaitMs(grid, now, kFrequency, 1000u) == static_cast<std::uint32_t>(1000 - wake * 150));
}
// A signal that came when the deadline had passed all the same: that tick is the periodic one.
CHECK(fl::watchdog::IsPeriodic(grid, deadline + 2 * kMs, false));
// And a wait that timed out a little short of the deadline, by this counter, is the tick the wait was for.
CHECK(fl::watchdog::IsPeriodic(grid, deadline - kMs / 2, true));
fl::watchdog::Advance(grid, deadline - kMs / 2);
CHECK(grid.deadline == deadline + kPeriod); // on the grid, not a period after the early moment
}
TEST_CASE("a periodic tick that ran late is not followed by another within half a period", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
// 400 ms late: the next is on the grid, 600 ms away.
fl::watchdog::Advance(grid, kPeriod + 400 * kMs);
CHECK(grid.deadline == 2 * kPeriod);
// 600 ms late: the grid's next would be 400 ms away, so the grid starts again from this tick.
fl::watchdog::Advance(grid, 2 * kPeriod + 600 * kMs);
CHECK(grid.deadline == 3 * kPeriod + 600 * kMs);
// A tick whose work took seconds (an install batch on a loaded machine): one tick follows, a period on -- not
// one for each deadline that passed.
fl::watchdog::Advance(grid, 9 * kPeriod);
CHECK(grid.deadline == 10 * kPeriod);
CHECK(fl::watchdog::WaitMs(grid, 9 * kPeriod, kFrequency, 1000u) == 1000u);
// A period that is not a positive number is one tick, not a division by zero or a wait without end.
fl::watchdog::StartGrid(grid, 100, 0);
CHECK(grid.period == 1);
CHECK(grid.deadline == 101);
}