gpu: preserve range-set nodes when subtracting partial ranges #2123

Closed
github-bot wants to merge 1 commit from gh-pr/2123/head into gh-pr/2123/base
Owner

@⁠tikD1337 on GitHub · 2026-11-05 08:20 UTC · original
tikD1337:codex/rangeset-subtract → main · +62 −5 · 2 files · 1 commits · closed without merging

Change

RangeSet::Subtract erased an overlapping map node and allocated replacements even when only trimming one edge. Keep the left tail in place; rekey the right tail with a C++17 map node handle; when splitting, retain one node and allocate only the second tail. Fully covered nodes are still erased.

RangeSet is used by the buffer cache for GPU-modified byte ranges and checked colour metadata. There are no game-specific conditions or changes to locking or synchronization.

Draft: no game-level performance or bug-fix result is established. The allocation savings below are a CPU-only candidate for further profiling; I understand the project's contribution rules ask for evidence tied to a concrete game.

Checked locally

Windows, Intel Core i7-1185G7; portable Zig 0.15.2 C++ compiler.

  • Extended the existing TestRangeSet in MemoryTrackerTests.cpp: 20000 seeded add/subtract operations compared with a 256-byte oracle, plus 20808 exhaustive single-interval subtraction cases with 17 byte-membership queries each.
  • Original and changed production headers pass this same expanded test in a standalone CPU harness.
  • Changed header passes C++20 -O3 and -O0 -g builds with -Wall -Wextra -Werror.
  • Two deliberate wrong-boundary mutations are caught by the test.
  • git diff --check origin/main: passed.
  • A cross-PR file/hunk scan examined 206 open PRs. It exited 2 because #1150, #1282, #1284, #1307, #1430, #1469, #1495 and #1886 conflict with the base. Their shared files were inspected manually: all retain the same RangeSet::Subtract body as current main; none implements node reuse. #1469 adds Find tests at the end of TestRangeSet, so combining those test additions may require a rebase. The automated scan is not claimed as passed.

This was not a run of the full memory_tracker_tests executable. The harness includes the actual production header and extracts the actual TestRangeSet function; it supplies a minimal generated platform config, the pinned fmt dependency in header-only mode, and an abort-only Common::DbgExitHandler. No emulator, GPU, full build or CTest run was performed.

Allocation counts and synthetic timings

Seven alternating executable runs; medians of average ns/call per run. Each run times 204800 Subtract calls in 200 separately initialized sets, with setup and destruction outside timers and final contents checked. An operator new counter is enabled only during Subtract.

Operation Before ns/call After ns/call Before allocations After allocations
Prefix trim 256.604 35.759 204600 0
Suffix trim 199.229 17.332 204600 0
Split 685.048 661.669 409600 204800
No overlap 19.812 13.015 0 0

The removed allocations are stronger evidence than these noisy laptop timings. The sample patterns are synthetic; their frequency in real game workloads was not measured. No FPS or frame-time gain is claimed.

Reproduce CPU test and benchmark

Keep the checkout named kyty-perf. Save the two Python scripts below in its parent directory. Initialize the repository's pinned 3rdparty/fmt submodule. In that parent directory, create range-cpu-config/cmake_config.h with:

#define KYTY_PLATFORM 1
#define KYTY_COMPILER 2
#define KYTY_BUILD 2

Run:

python prepare-range-cpu.py
zig c++ -std=c++20 -O3 -Wall -Wextra -Werror -DFMT_HEADER_ONLY -I range-cpu-config -I kyty-perf/src -I kyty-perf/3rdparty/fmt/include range-cpu.cpp -o range-new.exe
zig c++ -std=c++20 -O3 -Wall -Wextra -Werror -DFMT_HEADER_ONLY -I range-old -I range-cpu-config -I kyty-perf/src -I kyty-perf/3rdparty/fmt/include range-cpu.cpp -o range-old.exe
python range-cpu-repeat.py

prepare-range-cpu.py:

import subprocess
from pathlib import Path

base = Path(__file__).parent
root = base / "kyty-perf"
source = (root / "tests/MemoryTrackerTests.cpp").read_text()
function = source[source.index("void TestRangeSet() {"):source.index("void TestGuestRange()")]
header = subprocess.check_output(["git", "show", "07e87b950a9cbe590c13e8dcc5346bc1f5480506:src/graphics/host_gpu/rangeSet.h"], cwd=root).decode()
old = base / "range-old/graphics/host_gpu/rangeSet.h"
old.parent.mkdir(parents=True, exist_ok=True)
old.write_text(header)
harness = r'''
#include "graphics/host_gpu/rangeSet.h"
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <new>
#include <string_view>

bool counting = false;
size_t allocations = 0;
void* operator new(size_t size) {
  if (counting) ++allocations;
  if (auto* result = std::malloc(size ? size : 1)) return result;
  throw std::bad_alloc();
}
void operator delete(void* ptr) noexcept { std::free(ptr); }
void operator delete(void* ptr, size_t) noexcept { std::free(ptr); }
namespace Common {
[[noreturn]] void DbgExitHandler(char const*, int, std::string_view) { std::abort(); }
}
using Libs::Graphics::RangeSet;
void Check(bool value, const char* text) {
  if (!value) { std::fprintf(stderr, "%s\n", text); std::abort(); }
}
'''
harness += function + r'''
int main() {
  TestRangeSet();
  std::puts("Production TestRangeSet: passed");
  for (int mode = 0; mode < 4; ++mode) {
    double ns = 0;
    allocations = 0;
    for (int batch = 0; batch < 200; ++batch) {
      RangeSet ranges;
      ranges.Add(0, 4096);
      const auto begin = std::chrono::steady_clock::now();
      counting = true;
      for (uint64_t i = 0; i < 1024; ++i) {
        if (mode == 0) ranges.Subtract(i * 4, 4);
        if (mode == 1) ranges.Subtract(4092 - i * 4, 4);
        if (mode == 2) ranges.Subtract(i * 4 + 1, 1);
        if (mode == 3) ranges.Subtract(5000 + i * 4, 1);
      }
      counting = false;
      ns += std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - begin).count();
      if (mode < 2) Check(ranges.Empty(), "trim did not empty set");
      if (mode == 2) Check(!ranges.Contains(1, 1) && ranges.Contains(0, 1) &&
                           ranges.Contains(4094, 2), "split result incorrect");
      if (mode == 3) Check(ranges.Contains(0, 4096), "no-op changed set");
    }
    std::printf("mode=%d ns/op=%.3f allocations=%zu\n", mode, ns / (200 * 1024), allocations);
  }
}
'''
(base / "range-cpu.cpp").write_text(harness)

range-cpu-repeat.py:

import json
import re
import statistics
import subprocess
from pathlib import Path

base = Path(__file__).parent
measurements = {"old": [[] for _ in range(4)], "new": [[] for _ in range(4)]}
counts = {}
for repeat in range(7):
    for side in (("old", "new") if repeat % 2 else ("new", "old")):
        output = subprocess.check_output([str(base / f"range-{side}.exe")], text=True)
        assert "Production TestRangeSet: passed" in output
        for mode, ns, allocations in re.findall(r"mode=(\d+) ns/op=([\d.]+) allocations=(\d+)", output):
            measurements[side][int(mode)].append(float(ns))
            counts[side, int(mode)] = int(allocations)
results = []
for mode in range(4):
    row = {"mode": ("prefix", "suffix", "split", "no-op")[mode],
           "old_ns": statistics.median(measurements["old"][mode]),
           "new_ns": statistics.median(measurements["new"][mode]),
           "old_allocations": counts["old", mode], "new_allocations": counts["new", mode],
           "operations": 204800}
    results.append(row)
    print(json.dumps(row), flush=True)
(base / "range-cpu-repeat.json").write_text(json.dumps(results, indent=2))

Remaining validation

  • Full supported Windows clang-cl build and Linux build.
  • Full MemoryTracker/PageManager integration tests.
  • A real game or captured tracker workload to measure the frequency of these subtraction shapes and unchanged ownership/protection behavior.
  • Same-scene before/after frame times if a game-performance claim is later made.

No Linux/macOS run, real game trace or GPU validation has been performed for this patch.

AI assistance

AI-assisted: yes. Codex wrote the patch, tests, harness, benchmark and this description and ran the reported local checks. Human review and the validation above are still needed.

**@⁠tikD1337** on GitHub · 2026-11-05 08:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2123) `tikD1337:codex/rangeset-subtract` → `main` · +62 −5 · 2 files · 1 commits · closed without merging ## Change `RangeSet::Subtract` erased an overlapping map node and allocated replacements even when only trimming one edge. Keep the left tail in place; rekey the right tail with a C++17 map node handle; when splitting, retain one node and allocate only the second tail. Fully covered nodes are still erased. `RangeSet` is used by the buffer cache for GPU-modified byte ranges and checked colour metadata. There are no game-specific conditions or changes to locking or synchronization. **Draft: no game-level performance or bug-fix result is established.** The allocation savings below are a CPU-only candidate for further profiling; I understand the project's contribution rules ask for evidence tied to a concrete game. ## Checked locally Windows, Intel Core i7-1185G7; portable Zig 0.15.2 C++ compiler. - Extended the existing `TestRangeSet` in `MemoryTrackerTests.cpp`: 20000 seeded add/subtract operations compared with a 256-byte oracle, plus 20808 exhaustive single-interval subtraction cases with 17 byte-membership queries each. - Original and changed production headers pass this same expanded test in a standalone CPU harness. - Changed header passes C++20 `-O3` and `-O0 -g` builds with `-Wall -Wextra -Werror`. - Two deliberate wrong-boundary mutations are caught by the test. - `git diff --check origin/main`: passed. - A cross-PR file/hunk scan examined 206 open PRs. It exited 2 because #1150, #1282, #1284, #1307, #1430, #1469, #1495 and #1886 conflict with the base. Their shared files were inspected manually: all retain the same `RangeSet::Subtract` body as current main; none implements node reuse. #1469 adds `Find` tests at the end of `TestRangeSet`, so combining those test additions may require a rebase. The automated scan is **not claimed as passed**. **This was not a run of the full `memory_tracker_tests` executable.** The harness includes the actual production header and extracts the actual `TestRangeSet` function; it supplies a minimal generated platform config, the pinned fmt dependency in header-only mode, and an abort-only `Common::DbgExitHandler`. No emulator, GPU, full build or CTest run was performed. ## Allocation counts and synthetic timings Seven alternating executable runs; medians of average ns/call per run. Each run times 204800 Subtract calls in 200 separately initialized sets, with setup and destruction outside timers and final contents checked. An `operator new` counter is enabled only during Subtract. | Operation | Before ns/call | After ns/call | Before allocations | After allocations | | --- | ---: | ---: | ---: | ---: | | Prefix trim | 256.604 | 35.759 | 204600 | 0 | | Suffix trim | 199.229 | 17.332 | 204600 | 0 | | Split | 685.048 | 661.669 | 409600 | 204800 | | No overlap | 19.812 | 13.015 | 0 | 0 | The removed allocations are stronger evidence than these noisy laptop timings. The sample patterns are synthetic; their frequency in real game workloads was not measured. No FPS or frame-time gain is claimed. <details> <summary>Reproduce CPU test and benchmark</summary> Keep the checkout named `kyty-perf`. Save the two Python scripts below in its parent directory. Initialize the repository's pinned `3rdparty/fmt` submodule. In that parent directory, create `range-cpu-config/cmake_config.h` with: ```cpp #define KYTY_PLATFORM 1 #define KYTY_COMPILER 2 #define KYTY_BUILD 2 ``` Run: ```text python prepare-range-cpu.py zig c++ -std=c++20 -O3 -Wall -Wextra -Werror -DFMT_HEADER_ONLY -I range-cpu-config -I kyty-perf/src -I kyty-perf/3rdparty/fmt/include range-cpu.cpp -o range-new.exe zig c++ -std=c++20 -O3 -Wall -Wextra -Werror -DFMT_HEADER_ONLY -I range-old -I range-cpu-config -I kyty-perf/src -I kyty-perf/3rdparty/fmt/include range-cpu.cpp -o range-old.exe python range-cpu-repeat.py ``` `prepare-range-cpu.py`: ```python import subprocess from pathlib import Path base = Path(__file__).parent root = base / "kyty-perf" source = (root / "tests/MemoryTrackerTests.cpp").read_text() function = source[source.index("void TestRangeSet() {"):source.index("void TestGuestRange()")] header = subprocess.check_output(["git", "show", "07e87b950a9cbe590c13e8dcc5346bc1f5480506:src/graphics/host_gpu/rangeSet.h"], cwd=root).decode() old = base / "range-old/graphics/host_gpu/rangeSet.h" old.parent.mkdir(parents=True, exist_ok=True) old.write_text(header) harness = r''' #include "graphics/host_gpu/rangeSet.h" #include <array> #include <chrono> #include <cstdio> #include <cstdlib> #include <new> #include <string_view> bool counting = false; size_t allocations = 0; void* operator new(size_t size) { if (counting) ++allocations; if (auto* result = std::malloc(size ? size : 1)) return result; throw std::bad_alloc(); } void operator delete(void* ptr) noexcept { std::free(ptr); } void operator delete(void* ptr, size_t) noexcept { std::free(ptr); } namespace Common { [[noreturn]] void DbgExitHandler(char const*, int, std::string_view) { std::abort(); } } using Libs::Graphics::RangeSet; void Check(bool value, const char* text) { if (!value) { std::fprintf(stderr, "%s\n", text); std::abort(); } } ''' harness += function + r''' int main() { TestRangeSet(); std::puts("Production TestRangeSet: passed"); for (int mode = 0; mode < 4; ++mode) { double ns = 0; allocations = 0; for (int batch = 0; batch < 200; ++batch) { RangeSet ranges; ranges.Add(0, 4096); const auto begin = std::chrono::steady_clock::now(); counting = true; for (uint64_t i = 0; i < 1024; ++i) { if (mode == 0) ranges.Subtract(i * 4, 4); if (mode == 1) ranges.Subtract(4092 - i * 4, 4); if (mode == 2) ranges.Subtract(i * 4 + 1, 1); if (mode == 3) ranges.Subtract(5000 + i * 4, 1); } counting = false; ns += std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - begin).count(); if (mode < 2) Check(ranges.Empty(), "trim did not empty set"); if (mode == 2) Check(!ranges.Contains(1, 1) && ranges.Contains(0, 1) && ranges.Contains(4094, 2), "split result incorrect"); if (mode == 3) Check(ranges.Contains(0, 4096), "no-op changed set"); } std::printf("mode=%d ns/op=%.3f allocations=%zu\n", mode, ns / (200 * 1024), allocations); } } ''' (base / "range-cpu.cpp").write_text(harness) ``` `range-cpu-repeat.py`: ```python import json import re import statistics import subprocess from pathlib import Path base = Path(__file__).parent measurements = {"old": [[] for _ in range(4)], "new": [[] for _ in range(4)]} counts = {} for repeat in range(7): for side in (("old", "new") if repeat % 2 else ("new", "old")): output = subprocess.check_output([str(base / f"range-{side}.exe")], text=True) assert "Production TestRangeSet: passed" in output for mode, ns, allocations in re.findall(r"mode=(\d+) ns/op=([\d.]+) allocations=(\d+)", output): measurements[side][int(mode)].append(float(ns)) counts[side, int(mode)] = int(allocations) results = [] for mode in range(4): row = {"mode": ("prefix", "suffix", "split", "no-op")[mode], "old_ns": statistics.median(measurements["old"][mode]), "new_ns": statistics.median(measurements["new"][mode]), "old_allocations": counts["old", mode], "new_allocations": counts["new", mode], "operations": 204800} results.append(row) print(json.dumps(row), flush=True) (base / "range-cpu-repeat.json").write_text(json.dumps(results, indent=2)) ``` </details> ## Remaining validation - Full supported Windows clang-cl build and Linux build. - Full MemoryTracker/PageManager integration tests. - A real game or captured tracker workload to measure the frequency of these subtraction shapes and unchanged ownership/protection behavior. - Same-scene before/after frame times if a game-performance claim is later made. No Linux/macOS run, real game trace or GPU validation has been performed for this patch. ## AI assistance AI-assisted: yes. Codex wrote the patch, tests, harness, benchmark and this description and ran the reported local checks. Human review and the validation above are still needed.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:15:07 +00:00
github-bot closed this pull request 2026-11-26 10:15:07 +00:00

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.