Skip to content

fix(agc): stop and join the profile dump thread when the driver stops - #24970

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
Nesyth:fix/agc-profile-dump-thread
Nov 27, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
Nesyth:fix/agc-profile-dump-thread

Conversation

@Nesyth

@Nesyth Nesyth commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

What

Follow-up to #22268, from the two review notes there:

  • The -DAPS5_AGC_PROFILE=generate build started a detached thread that dumped and reset the profile counters every 20 s forever, so it could outlive Driver::stop() and race process teardown. Now the driver starts that thread in its constructor and Driver::stop() stops and joins it, then dumps once more. The other builds keep empty start and stop functions.
  • BUILD.md step 2 now says to check that the recording reached the scenes. A session that stayed in a menu still leaves .gcda files, and the use build reports nothing (-Wno-missing-profile), but the driver it builds is laid out for the menu. The draw commits on the [commits] lines (APS5_PIPELINE_STATS=1) show it. It also says to delete old .gcda files before recording again.

Tested

Windows 11, GCC 15.2 Release: every target builds except 36 shader test executables the local antivirus removes after linking (none in this set), and 11 of 11 driver shutdown and graphics tests pass. Lifecycle.cpp compiles without warnings (-Wall) with and without APS5_PROFILE_GENERATE. A generate build was not run.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: AMD Radeon RX 7900 XTX, AMD Software 26.10.1 (32.0.32015.7029), Windows 11 Pro 26300
  • AI-assisted: yes

@goldrake13

Copy link
Copy Markdown
Contributor

Ran a -DAPS5_AGC_PROFILE=generate build of this PR on Windows, since the Tested section says none was run.

Setup: Windows 11 Pro 10.0.26300, i5-14600K, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. Head 37eed55d2b merged with --no-ff onto main 56d4f9fe7e, no conflict. I built libs and the two shutdown test executables. For the main rows I rebuilt the same tree with main's Lifecycle.cpp, the only code file this PR changes.

Shutdown tests: agc_driver_shutdown_threads_* (8), agc_driver_wait_shutdown and agc_driver_resolution_shutdown, 3 rounds, -j 1. None of them creates a Vulkan instance, so the GPU plays no part here. The .gcda files were deleted before the first round.

Lifecycle.cpp Result .gcda files after the rounds
main 30 of 30 pass 0
this PR 30 of 30 pass 270

On Windows these test processes end through LibcTerminate_nid_no_patch, which calls TerminateProcess, so libgcov's own dump at exit never runs. With main, a process that ends within 20 s records nothing. With this PR, the dump in Driver::stop() records it. Some of these tests take about 0.1 s longer with this PR, in line with the 0.075 s that shutdown takes in the harness below.

Process that runs longer than 20 s: a small harness (below) starts the driver with AgcDriverWaitIdle_nid_postfix(), watches the modification time of Lifecycle.cpp.gcda, and calls LibcRunShutdown_nid_postfix() at 50 s. It then watches for 45 s more. It counts the process's threads with Toolhelp.

main this PR
Dumps before shutdown 20.1 s, 40.2 s 20.1 s, 40.2 s
Dump at shutdown none 50.15 s
Dumps after shutdown 60.3 s, 80.3 s none
LibcRunShutdown_nid_postfix() took 0.000 s 0.075 s
Threads before and after shutdown 3 and 3 3 and 2

So with this PR the thread stops and is joined at shutdown, and shutdown does not wait out the 20 s period.

Step 3 of BUILD.md: I reconfigured the same directory with -DAPS5_AGC_PROFILE=use, keeping the .gcda files from the harness run with this PR. libs builds and the 10 tests pass. I recompiled 15 randomly picked instrumented objects without -Wno-missing-profile -Wno-coverage-mismatch, and none of them gives a warning. Lifecycle.cpp gives errors for two functions:

Lifecycle.cpp:279:1: error: number of counters in profile data for function 'AgcDriver::DriverDetail::Driver::Driver()' does not match its profile data (counter 'arcs', expected 98 and have 96) [-Werror=coverage-mismatch]
Lifecycle.cpp:232:6: error: number of counters in profile data for function 'void AgcDriver::DriverDetail::Driver::stop()' does not match its profile data (counter 'arcs', expected 86 and have 84) [-Werror=coverage-mismatch]

The generate and use builds compile different startProfileDumps and stopProfileDumps bodies (APS5_PROFILE_GENERATE). As a result, Driver() and stop() have different control flow in the two builds, and with -Wno-coverage-mismatch the use build drops their profile. On main, Driver() already differs between the two builds because of the #ifdef thread in the constructor. This PR adds stop() to that. Both functions run once per process, so this should not affect the hot paths.

Harness

Compiled and linked with the flags of agc_driver_wait_shutdown_tests (from ninja -t commands), placed in build/tests, and run from the source directory as profile_dump_harness.exe <...>/Execution/src/Driver/Lifecycle.cpp.gcda 50.

#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include <windows.h>
#include <tlhelp32.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <thread>

namespace {

using Clock = std::chrono::steady_clock;
Clock::time_point start;

double Seconds() {
    return std::chrono::duration<double>(Clock::now() - start).count();
}

int ThreadCount() {
    const auto pid = GetCurrentProcessId();
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
    THREADENTRY32 entry{};
    entry.dwSize = sizeof(entry);
    int count = 0;
    if (Thread32First(snapshot, &entry)) {
        do {
            if (entry.th32OwnerProcessID == pid) ++count;
        } while (Thread32Next(snapshot, &entry));
    }
    CloseHandle(snapshot);
    return count;
}

std::filesystem::file_time_type lastWrite{};

void Watch(const std::filesystem::path& gcda, double untilSeconds) {
    while (Seconds() < untilSeconds) {
        std::error_code error;
        const auto now = std::filesystem::last_write_time(gcda, error);
        if (!error && now != lastWrite) {
            lastWrite = now;
            std::printf("[%6.2f s] gcda written\n", Seconds());
            std::fflush(stdout);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

}

int main(int argc, char** argv) {
    if (argc != 3) {
        std::fprintf(stderr, "usage: %s <file.gcda> <seconds before stop>\n", argv[0]);
        return 2;
    }
    const std::filesystem::path gcda = argv[1];
    const double before = std::atof(argv[2]);
    std::error_code error;
    lastWrite = std::filesystem::last_write_time(gcda, error);
    std::printf("threads before driver: %d\n", ThreadCount());
    start = Clock::now();
    AgcDriverWaitIdle_nid_postfix();
    std::printf("[%6.2f s] driver up, threads: %d\n", Seconds(), ThreadCount());
    std::fflush(stdout);
    Watch(gcda, before);
    const int threadsBeforeStop = ThreadCount();
    const auto stopStart = Clock::now();
    LibcRunShutdown_nid_postfix();
    const double stopTook = std::chrono::duration<double>(Clock::now() - stopStart).count();
    std::printf("[%6.2f s] shutdown took %.3f s, threads: %d before, %d after\n", Seconds(), stopTook, threadsBeforeStop, ThreadCount());
    std::fflush(stdout);
    Watch(gcda, Seconds() + 45.0);
    std::printf("[%6.2f s] threads at exit: %d\n", Seconds(), ThreadCount());
    std::fflush(stdout);
    return 0;
}

AI-assisted: yes

@throny

throny commented Nov 22, 2026

Copy link
Copy Markdown

GPU test run: ✅ no new failures or validation errors on Windows / NVIDIA

Basis: built and ran · this PR's head 37eed55d2b merged onto main 851212fb98 · Windows 11 Pro 26300, RTX 4080 (10de:2704, driver 610.88), WinLibs GCC 15.2.0 r7, Release

Checked

  • The agc_* tests tools/select_tests.py selects for this change: 1966 of 1967 passed, run with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer (Khronos validation layer, nightly 1.4.369, newer than the 1.4.335 minimum).
  • The loader logged Insert instance layer "VK_LAYER_KHRONOS_validation" 1890 times and never was not found but was requested by env var VK_INSTANCE_LAYERS.
  • 0 VUID- messages, the same as a full agc_* run of main 851212fb98 on this machine with the same settings (2081 of 2082 passed, 0 VUID-).
  • The failure is agc_driver_store_over_untracked, which also fails intermittently on main here (agc_driver_store_over_untracked is flaky on Windows: the second-store case sometimes finds no saved guest bytes #22670), not this change.

Findings: none from this run; this is a GPU run, not a code review.

AI-assisted test run (Claude Code) · head 37eed55d2b · base main 851212fb98

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — comments

The lifecycle changes are sound by inspection, but a full review is not justified because no tests or profile-generate build were run here.

What I ran

Read the prepared diff and changed lines at head 37eed55d2b30b5270f271f881a7dc20d5765829c, plus the profile build configuration and shutdown entry point using repo_read.py. No build or tests were run.

Results

Check Result Note
Diff and changed lines passed Both changed files read
Targeted lifecycle context passed Build mode and shutdown caller checked
Build and tests not run Author-reported results only

Findings

Blocking

None.

Non-blocking

  • Consider adding a focused regression test for profile-dump shutdown and final dump behavior. The new thread coordination and final dump are only exercised in the profile-generate build, which the description says was not run.

Not verified

No tests, build, profile-generate execution, or physical-console behavior were verified. Author-reported Windows build and test results were not run by this review. Read core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp, docs/dev/BUILD.md, core/libs/prx/libSceAgcDriver/CMakeLists.txt, and core/libs/prx/libSceAgcDriver/Execution/src/Driver/EntryPoints.cpp. The review bundle's review/files.json was unavailable; the prepared manifest and listing identify both changed files as included. No files were excluded according to that listing.

To get this to a good state

Nothing is required. Optional: add regression coverage for the profile dump thread lifecycle.

@Helldiverr

Copy link
Copy Markdown
Contributor

AMD run of 37eed55d2b: the six focused tests pass 3 of 3 on main 7db4926943, and a standalone probe of the new dump-thread code stops, joins and dumps once. None of these tests creates a Vulkan instance.

Code. I read the diff at 37eed55d2b. It follows the rules:

  • no new code comments;
  • no made-up success;
  • no title special-casing;
  • no debt change, and none is needed.

check_conventions.py --base 7db4926943 passes, and so does debt_fold.py --check.

Outside -DAPS5_AGC_PROFILE=generate, startProfileDumps and stopProfileDumps are empty. The normal builds that CI and my runs use therefore exercise only the new call sites, not the thread code.

startProfileDumps returns without starting a thread once stopping is set. Driver is a function-local static in Driver::Get() (Execution/src/Driver/Lifecycle.cpp:160), so I see no path that constructs it a second time after stop().

Existing runs.

  • goldrake13 ran a generate build (i5-14600K, main 56d4f9fe7e). Their harness shows the dump at shutdown, no dumps after it, and one thread fewer. In their use rebuild, Driver() and stop() lose their profile: their profile counter counts differ between the two builds.
  • throny ran 1966 of 1967 on an RTX 4080 with the layer, with 0 VUID-.
  • The author lists an RX 7900 XTX in GPUs tested, with no validation-layer run.

My run adds an AMD run of the shutdown tests on the current main, plus a direct check of the stop logic, including a mutation that the check catches. I did not run a generate build, so goldrake13's run remains the only one of the instrumented driver.

Probe. p24970.cpp includes the PR's #ifdef APS5_PROFILE_GENERATE block verbatim. It is extracted from Lifecycle.cpp at 37eed55d2b and compiled with stub __gcov_dump and __gcov_reset that count calls (GCC 15.2, -O2). The probe is a plain host program, so it ran without the Vulkan validation environment.

scenario result
start twice, stop at once stop took 0.001 s; 1 dump, 1 reset; thread not joinable after stop
start, wait 1 s, stop stop took 0.000 s; 1 dump
start, wait 21 s, stop 1 periodic dump before stop, 2 after; stop took 0.000 s
second stopProfileDumps() no further dump
startProfileDumps() after stop no thread started

Negative control. In the same probe I removed dumps.wake.notify_one();. With a 1 s wait before the stop, the stop then took 19.014 s, because the thread waits out its 20 s period. The unmodified block took 0.000 s. Starting and stopping at once does not show the difference, because the thread sees stopping before it first waits. The probe files are under C:\tmp\gpu-reviews\logs\gpu-b-probe\ and are not in the worktree.

GPU. ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer ctest --test-dir build -R "^agc_driver_shutdown_threads_(joined|draw_committer|exit_after_start)$|^agc_driver_wait_shutdown$|^agc_driver_resolution_shutdown$|^agc_driver_graphics$" -V

test main head 1 head 2 head 3
agc_driver_graphics (CPU) Passed 14.78 s Passed 11.27 s Passed 11.56 s Passed 11.70 s
agc_driver_shutdown_threads_joined (CPU) Passed 0.09 s Passed 0.07 s Passed 0.06 s Passed 0.06 s
agc_driver_shutdown_threads_draw_committer (CPU) Passed 0.14 s Passed 0.12 s Passed 0.15 s Passed 0.12 s
agc_driver_shutdown_threads_exit_after_start (CPU) Passed 0.08 s Passed 0.06 s Passed 0.08 s Passed 0.06 s
agc_driver_wait_shutdown (CPU) Passed 1.19 s Passed 1.13 s Passed 1.13 s Passed 1.13 s
agc_driver_resolution_shutdown (CPU) Passed 1.07 s Passed 1.07 s Passed 1.08 s Passed 1.09 s

Validation. All four runs used the full environment above, but none of these tests creates a Vulkan instance. So the logs contain no loader output and 0 layer inserts, and the GPU plays no part. None of the logs contains was not found but was requested by env var VK_INSTANCE_LAYERS. VUID- count: 0 in every log. On the same machine and session, the same environment inserts the layer in the GPU tests of #24829 and #24869.

Host:

  • GPU: AMD Radeon AI PRO R9700 (gfx1201, 1002:7551), driver 32.0.31044.16, Vulkan 1.4.349
  • Validation layer: Khronos 1.4.363 (LunarG SDK)
  • CPU: Ryzen 9 9950X3D
  • OS: Windows 11 Pro 26300
  • Toolchain: WinLibs GCC 15.2, Release
  • Commits measured: main 7db4926; head 73a8df2231 (37eed55 merged onto 7db4926)

AI-assisted: yes

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 1835 docs/dev/BUILD.md
PR 5925 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 6188 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 11435 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
docs/dev/BUILD.md
PR 11436 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
docs/dev/BUILD.md
PR 15136 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
docs/dev/BUILD.md
PR 16791 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 16793 docs/dev/BUILD.md
PR 18208 docs/dev/BUILD.md
PR 18210 docs/dev/BUILD.md
PR 18293 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 19557 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
docs/dev/BUILD.md
PR 19562 docs/dev/BUILD.md
PR 19610 docs/dev/BUILD.md
PR 19628 docs/dev/BUILD.md
PR 19635 docs/dev/BUILD.md
PR 19645 docs/dev/BUILD.md
PR 19670 docs/dev/BUILD.md
PR 19720 docs/dev/BUILD.md
PR 20315 docs/dev/BUILD.md
PR 20730 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 21222 docs/dev/BUILD.md
PR 21225 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
PR 21939 docs/dev/BUILD.md
PR 22004 docs/dev/BUILD.md
PR 22594 docs/dev/BUILD.md
PR 24153 docs/dev/BUILD.md
PR 26131 docs/dev/BUILD.md
PR 26173 docs/dev/BUILD.md
PR 27133 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp
docs/dev/BUILD.md
PR 27651 docs/dev/BUILD.md

@oneandonlydean
oneandonlydean merged commit d309fc2 into boykopovar:main Nov 27, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* docs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants