From 5507ef2f5f5a4b869470d7861ad6fec39daa1422 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:47:27 +0100 Subject: [PATCH 1/4] perf(P1): skip redundant software pacing after VSync presentation --- docs/frame-pacing.md | 47 +++++++++ main.lua | 23 +---- src/core/FrameCap.lua | 44 +++++++++ tests/engine/frame_pacing.lua | 153 ++++++++++++++++++++++++++++++ tools/check_frame_pacing.py | 50 ++++++++++ tools/frame-pacing-check/conf.lua | 7 ++ tools/frame-pacing-check/main.lua | 94 ++++++++++++++++++ 7 files changed, 400 insertions(+), 18 deletions(-) create mode 100644 docs/frame-pacing.md create mode 100644 tests/engine/frame_pacing.lua create mode 100644 tools/check_frame_pacing.py create mode 100644 tools/frame-pacing-check/conf.lua create mode 100644 tools/frame-pacing-check/main.lua diff --git a/docs/frame-pacing.md b/docs/frame-pacing.md new file mode 100644 index 000000000..d3b291cf2 --- /dev/null +++ b/docs/frame-pacing.md @@ -0,0 +1,47 @@ +# P1: VSync and the software deadline + +The run loop records whether it actually presented a frame. After presentation, +`FrameCap.pace` skips the software wait when VSync is active and the FPS cap is +at least the reported display refresh rate. Without presentation, with VSync +off, with an unknown rate, or with a lower FPS cap, the existing carried +deadline, one-millisecond sleep chunks and stall re-anchor remain active. + +The default-on rollback switch is independent of all other performance work: + +```lua +require("src.core.FrameCap").vsyncPacing = false +``` + +Display flags are sampled at most once per second to avoid allocating their +table each frame. Provider/VSync changes invalidate that sample; other display +rate changes are observed on the next periodic sample. Existing option values, +simulation timing, mod interfaces and callback call sites are unchanged. + +`frame pacing: sleep` in the existing F11 FrameProfile measures the helper, +including its software wait. `present (GPU wait / vsync)` retains its original +scope. Removing a redundant software wait can move wall time into present +without changing FPS. + +The owned-window probe runs the real helper and FrameProfile with the switch +off/on, each after 120 warm-up frames and over 120 measured frames. Run through +the guarded launcher: + +```sh +python3 tools/check_frame_pacing.py --love /path/to/love --report /path/to/owned/qa/report.json +``` + +An older public checkout can use `--qa-tools /path/to/fork/tools`. The launcher +pins inputs, uses a separate QA identity, retains raw profile logs and records +SHA-256 hashes of the actual measured source files alongside the Git parent. + +Observed macOS/arm64, 60-Hz display, VSync 1, cap 60: + +| Backend | Software wait off/on, ms/frame | Present off/on, ms/frame | CPU off/on, ms/frame | +| --- | ---: | ---: | ---: | +| LÖVE 11.5 OpenGL | 0.00 / 0.01 | 16.59 / 16.54 | 0.672 / 0.790 | +| LÖVE 12 Metal | 16.43 / 0.01 | 0.13 / 16.56 | 0.769 / 0.629 | + +Both enabled runs made zero extra sleep calls and stayed near 60 FPS, with no +measured interval exceeding 1.5 display periods. These short blank-window +checks establish the pacing decision and its profiler scope. They do not +establish a universal CPU/FPS gain, loaded-world behavior, or handheld results. diff --git a/main.lua b/main.lua index 18325ffdf..3b1f7c1ac 100644 --- a/main.lua +++ b/main.lua @@ -1261,12 +1261,14 @@ function love.run() closeU() end + local presented = false if love.graphics and love.graphics.isActive() then love.graphics.origin() love.graphics.clear(love.graphics.getBackgroundColor()) if love.draw then love.draw() end local closeP = FrameProfile.section("present (GPU wait / vsync)") love.graphics.present() + presented = true closeP() end -- Counted after present, so a frame in the trace means a frame that was @@ -1299,24 +1301,9 @@ function love.run() if love.timer then if paced then - -- Sleep out the remainder of the frame budget, measured from the - -- carried deadline, in small chunks so the OS timer stays - -- responsive. vsync is untouched: when it already paces slower - -- than the cap the remainder is <= 0 and this rounds to a no-op. - local budget = 1 / FrameCap.current - nextFrame = nextFrame + budget - local now = love.timer.getTime() - -- A stall (alt-tab, a GC pause, a blocked import) can leave the - -- deadline more than a full budget in the past; re-anchor to now so - -- we pace the next frame rather than burst uncapped to catch up. - if now - nextFrame > budget then - nextFrame = now - end - while true do - local remaining = nextFrame - love.timer.getTime() - if remaining <= 0 then break end - love.timer.sleep(remaining < 0.001 and remaining or 0.001) - end + local closeSleep = FrameProfile.section("frame pacing: sleep") + nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame) + closeSleep() else love.timer.sleep(0.001) end diff --git a/src/core/FrameCap.lua b/src/core/FrameCap.lua index 2e5b36feb..09dbd7e98 100644 --- a/src/core/FrameCap.lua +++ b/src/core/FrameCap.lua @@ -25,6 +25,50 @@ FrameCap.DEFAULT = 60 -- save editor are paced before any save applies its stored option. FrameCap.current = FrameCap.DEFAULT +-- P1 rollback switch. Each frame still falls back to software pacing when +-- there was no present, VSync is off, or the display rate is unavailable. +FrameCap.vsyncPacing = true +local _refreshWindow, _refreshVsync, _refreshAt, _refreshRate +local REFRESH_POLL_SECONDS = 1 + +local function presentationPaces(window, now) + if not (window and window.getVSync and window.getMode) then return false end + local vsync = window.getVSync() + if type(vsync) ~= "number" or vsync == 0 then + _refreshVsync = vsync + return false + end + -- getMode returns a new flags table: sample it once a second rather than + -- allocate one each frame. Provider/VSync changes invalidate the sample; + -- display-rate changes are observed on the next periodic sample. + if window ~= _refreshWindow or vsync ~= _refreshVsync or not _refreshAt + or now < _refreshAt or now - _refreshAt >= REFRESH_POLL_SECONDS then + local _, _, flags = window.getMode() + local rate = type(flags) == "table" and tonumber(flags.refreshrate) + _refreshWindow, _refreshVsync, _refreshAt = window, vsync, now + _refreshRate = rate and rate > 0 and rate < math.huge and rate or nil + end + return _refreshRate ~= nil and FrameCap.current >= _refreshRate +end + +-- The run loop owns the deadline and passes back the returned value. Keeping +-- the original fallback here lets tests exercise the real pacing operation. +function FrameCap.pace(timer, window, presented, nextFrame) + local now = timer.getTime() + if FrameCap.vsyncPacing and presented and presentationPaces(window, now) then + return now + end + local budget = 1 / FrameCap.current + nextFrame = nextFrame + budget + if now - nextFrame > budget then nextFrame = now end + while true do + local remaining = nextFrame - timer.getTime() + if remaining <= 0 then break end + timer.sleep(remaining < 0.001 and remaining or 0.001) + end + return nextFrame +end + -- Nearest valid step for an arbitrary value (a hand-edited options.lua or -- an old save with no fpsCap key), so a bad number degrades to something -- sane; nil / non-numbers fall back to the default. A value below MIN or diff --git a/tests/engine/frame_pacing.lua b/tests/engine/frame_pacing.lua new file mode 100644 index 000000000..27a96b39e --- /dev/null +++ b/tests/engine/frame_pacing.lua @@ -0,0 +1,153 @@ +local T = require("tests.harness") +local Cap = require("src.core.FrameCap") +local function clock(start) + local now, sleeps, total = start or 0, 0, 0 + return { + getTime = function() + return now + end, + sleep = function(dt) + now = now + dt + sleeps = sleeps + 1 + total = total + dt + end, + advance = function(dt) + now = now + dt + end, + sleeps = function() + return sleeps, total + end, + } +end +local function window(sync, rate) + local calls = 0 + return { + getVSync = function() + return sync + end, + getMode = function() + calls = calls + 1 + return 320, 240, { refreshrate = rate } + end, + modeCalls = function() + return calls + end, + set = function(s, r) + sync, rate = s, r + end, + } +end +Cap.current = 60 +T.eq(Cap.vsyncPacing, true, "P1 switch defaults on") +for _, sync in ipairs({ 1, -1, 2 }) do + local timer, w = clock(), window(sync, 60) + local nextFrame = 0 + for _ = 1, 60 do + timer.advance(1 / 60) + nextFrame = Cap.pace(timer, w, true, nextFrame) + end + T.eq(timer.sleeps(), 0, "active VSync at the cap receives no additional sleep") + T.eq(w.modeCalls(), 1, "display flags are not allocated each frame") +end +for _, case in ipairs({ + { sync = 0, rate = 60, presented = true }, + { sync = 1, rate = 144, presented = true }, + { sync = 1, rate = 0, presented = true }, + { sync = 1, rate = 60, presented = false }, +}) do + local timer, w = clock(), window(case.sync, case.rate) + local deadline = Cap.pace(timer, w, case.presented, 0) + T.check(timer.sleeps() > 0, "software cap remains for disabled/unknown/faster/unpresented cases") + T.check(math.abs(deadline - 1 / 60) < 1e-9, "software deadline remains one frame ahead") +end +local timer, w = clock(), window(1, 60) +Cap.vsyncPacing = false +Cap.pace(timer, w, true, 0) +T.check(timer.sleeps() > 0, "P1 switch restores software pacing") +T.eq(w.modeCalls(), 0, "disabled P1 does not query display flags") +Cap.vsyncPacing = true +timer, w = clock(), window(1, 60) +local deadline = Cap.pace(timer, w, true, 0) +w.set(0, 60) +deadline = Cap.pace(timer, w, true, deadline) +T.check(math.abs(deadline - 1 / 60) < 1e-9, "turning VSync off resumes the carried software deadline") +timer.advance(1) +deadline = Cap.pace(timer, w, true, deadline) +T.eq(deadline, timer.getTime(), "stalls re-anchor instead of accumulating catch-up frames") +deadline = Cap.pace(timer, w, true, deadline) +T.eq(deadline, timer.getTime(), "software pacing resumes after a stall") +timer, w = clock(), window(1, 60) +Cap.pace(timer, w, true, 0) +w.set(1, 144) +timer.advance(1.01) +deadline = Cap.pace(timer, w, true, timer.getTime()) +T.check(timer.sleeps() > 0, "display rate changes refresh the software-cap decision") +T.eq(w.modeCalls(), 2, "display sample refresh is bounded") +timer = clock() +Cap.pace(timer, nil, true, 0) +T.check(timer.sleeps() > 0, "headless provider absence retains the software cap") + +-- Execute the actual run-loop body with native present/timer boundaries +-- substituted, so a correct helper wired to the wrong loop still fails. +local file = assert(io.open("main.lua", "r")) +local source = file:read("*a") +file:close() +local start = assert(source:find("function love.run()", 1, true)) +for _, active in ipairs({ true, false }) do + local fake = clock() + fake.step = function() + return 1 / 60 + end + local presents = 0 + local noop = function() end + local env = { + love = { + timer = fake, + window = window(1, 60), + graphics = { + isActive = function() + return active + end, + origin = noop, + clear = noop, + getBackgroundColor = function() + return 0, 0, 0, 1 + end, + present = function() + presents = presents + 1 + fake.advance(1 / 60 - 0.001) + end, + }, + }, + BootTrace = { mark = noop, frame = noop }, + Frames = { tick = noop }, + FrameProfile = { + section = function() + return noop + end, + }, + WindowFrame = { + draw = function(fn) + fn() + end, + }, + GraphicsStack = { drain = noop }, + pacingEnabled = function() + return true + end, + lastLogFlush = 0, + } + setmetatable(env, { __index = _G }) + local chunk + if setfenv then + chunk = assert(loadstring(source:sub(start), "@main.lua:love.run")) + setfenv(chunk, env) + else + chunk = assert(load(source:sub(start), "@main.lua:love.run", "t", env)) + end + chunk() + env.love.run()() + T.eq(presents, active and 1 or 0, "actual main loop presents only active graphics") + T.eq(fake.sleeps() > 0, not active, "actual main loop bypasses sleep only after native presentation") +end +T.finish() diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py new file mode 100644 index 000000000..952e314da --- /dev/null +++ b/tools/check_frame_pacing.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Run owned-window VSync pacing measurements through the local QA guard.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--love', type=Path, required=True) + parser.add_argument('--report', type=Path, required=True) + parser.add_argument('--qa-tools', type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + sys.path.insert(0, str(args.qa_tools or root / 'tools')) + try: + from qa_storage import qa_source, qa_cache, qa_profile, qa_run + except ImportError: + parser.error('QA storage guard is required; provide --qa-tools') + qa_source(root) + qa_source(args.love.resolve()) + qa_cache(args.report.parent) + args.report.parent.mkdir(parents=True, exist_ok=True) + identity = 'oasc-gen2recomp-qa-frame-pacing-' + str(time.time_ns()) + qa_profile(Path.home() / 'Library/Application Support/LOVE' / identity) + result = qa_run([str(args.love.resolve()), str(root / 'tools/frame-pacing-check')], + cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, + FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1'), + capture_output=True, text=True, timeout=90) + args.report.with_suffix('.log').write_text(result.stdout + result.stderr) + records = [line.removeprefix('P1_NATIVE_RESULT ') for line in result.stdout.splitlines() + if line.startswith('P1_NATIVE_RESULT ')] + if result.returncode or len(records) != 1: + raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) + report = json.loads(records[0]) + report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() + files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', + 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + args.report.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/frame-pacing-check/conf.lua b/tools/frame-pacing-check/conf.lua new file mode 100644 index 000000000..79551e6d7 --- /dev/null +++ b/tools/frame-pacing-check/conf.lua @@ -0,0 +1,7 @@ +function love.conf(t) + assert(os.getenv("FRAME_PACING_QA_GUARDED") == "1", "use tools/check_frame_pacing.py") + t.identity = assert(os.getenv("POKEPORT_IDENTITY")) + t.window.title = "Frame pacing QA" + t.window.width, t.window.height, t.window.vsync = 320, 180, 1 + t.modules.audio = false +end diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua new file mode 100644 index 000000000..e280a2d74 --- /dev/null +++ b/tools/frame-pacing-check/main.lua @@ -0,0 +1,94 @@ +local root = assert(os.getenv("FRAME_PACING_REPO")) +package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path +local Cap = require("src.core.FrameCap") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local phase, frame, deadline, last, started, cpuStarted = 1, 0, 0, 0, 0, 0 +local sleeps, intervals, results = 0, {}, {} +local WINDOW, WARMUP = 120, 120 +local timer = { + getTime = love.timer.getTime, + sleep = function(dt) + sleeps = sleeps + 1 + love.timer.sleep(dt) + end, +} +local _, _, mode = love.window.getMode() +local refresh = tonumber(mode.refreshrate) or 0 +Cap.current = refresh > 0 and refresh or 60 +local function startPhase() + Profile.setEnabled(false) + Cap.vsyncPacing = phase == 2 + frame, sleeps, intervals = 0, 0, {} + deadline = timer.getTime() +end +local function finishPhase() + local long = 0 + for _, interval in ipairs(intervals) do + if refresh > 0 and interval > 1.5 / refresh then + long = long + 1 + end + end + table.sort(intervals) + results[phase] = { + enabled = Cap.vsyncPacing, + frames = WINDOW, + seconds = timer.getTime() - started, + medianMs = intervals[math.floor(#intervals / 2)] * 1000, + p95Ms = intervals[math.ceil(#intervals * 0.95)] * 1000, + maxMs = intervals[#intervals] * 1000, + framesOver1_5Periods = long, + extraSleepCalls = sleeps, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + } + if phase == 2 then + if refresh > 0 and love.window.getVSync() ~= 0 then + assert(sleeps == 0, "VSync phase still slept") + end + print("P1_NATIVE_RESULT " .. Json.encode({ + refresh = refresh, + vsync = love.window.getVSync(), + cap = Cap.current, + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = love.graphics.getRendererInfo(), + phases = results, + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + sleeps = 0 + Profile.setEnabled(true) + started, last = timer.getTime(), timer.getTime() + cpuStarted = os.clock() + end + love.graphics.clear(0.03, 0.04, 0.06) + local close = Profile.section("present (GPU wait / vsync)") + love.graphics.present() + close() + close = Profile.section("frame pacing: sleep") + deadline = Cap.pace(timer, love.window, true, deadline) + close() + frame = frame + 1 + if frame > WARMUP then + local now = timer.getTime() + intervals[#intervals + 1], last = now - last, now + Profile.frame() + end + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end From 65c30879f50bae1e9912f79f227fb45a7b670643 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:12:49 +0100 Subject: [PATCH 2/4] perf(P2): tune incremental GC and spend bounded idle deadline time --- docs/gc-frame-budget.md | 51 ++++++++++++ main.lua | 6 +- src/core/FrameCap.lua | 11 ++- src/core/GCFrameBudget.lua | 86 ++++++++++++++++++++ src/core/Game.lua | 16 ++-- src/core/Performance.lua | 12 +++ tests/engine/gc_frame_budget.lua | 126 ++++++++++++++++++++++++++++++ tools/check_frame_pacing.py | 11 ++- tools/frame-pacing-check/gc.lua | 124 +++++++++++++++++++++++++++++ tools/frame-pacing-check/main.lua | 4 + 10 files changed, 429 insertions(+), 18 deletions(-) create mode 100644 docs/gc-frame-budget.md create mode 100644 src/core/GCFrameBudget.lua create mode 100644 tests/engine/gc_frame_budget.lua create mode 100644 tools/frame-pacing-check/gc.lua diff --git a/docs/gc-frame-budget.md b/docs/gc-frame-budget.md new file mode 100644 index 000000000..abee388ba --- /dev/null +++ b/docs/gc-frame-budget.md @@ -0,0 +1,51 @@ +# P2: incremental GC in unused deadline time + +`Performance.gcBudget` defaults to `true`. At boot the collector uses pause 120 +and step multiplier 300. Each concrete `Performance.CAPS` row additionally has +`gcPause`, `gcStepMul` and `gcBudgetSeconds`; tiers may reduce the default +0.0005-second idle allowance. No options are rewritten. + +The ordinary engine's fixed `step(1)` moves out of `Game:update`. The run loop +uses no-argument incremental steps before its remaining software wait. It starts +no further step after the earlier of the actual deadline and the half-millisecond +allowance, and stops on completion of a cycle. An expired deadline or a stopped +collector receives no work. VSync never gets an invented future budget; only +the actual remainder of its carried deadline is eligible, and no extra sleep +is added after VSync. + +The budget is cooperative: a single indivisible collector step can finish past +the boundary. It is not a preemption guarantee for an arbitrary heap/finalizer. +The F11 child section `frame pacing: gc budget` is nested in the existing +`frame pacing: sleep` section, so the parent includes collection plus waiting. + +The fork's pre-existing Gen3 `Game3.stepGC` delegation stays at its original +update boundary with the original arguments/behavior. A frame owned by that +public seam gets no second idle GC service. Its delegated/custom work remains +outside the engine idle allowance. This preserves consumers that replace it. + +The independent rollback switch is: + +```lua +require("src.core.Performance").gcBudget = false +``` + +The next frame restores the previous pause/multiplier and uses the old native +update step. The separate P1 switch and callback interfaces are unchanged. + +`tools/check_frame_pacing.py --gc --love /path/to/love --report /owned/qa/gc.json` +runs the guarded native comparison. P1 stays enabled for both phases; only P2 +changes. The workload allocates 512 short tables per frame, with 120 warm-up +and 120 measured frames per phase. Raw FrameProfile logs, original tuning, +heap samples and measured-source SHA-256 hashes are retained. + +Observed composed fork, macOS/arm64, 60 Hz, VSync 1, cap 60: + +| Backend | Original fixed step, ms/frame | New idle mean / max, ms | Heap peak before / after, KiB | +| --- | ---: | ---: | ---: | +| LÖVE 11.5 OpenGL | 0.00 (rounded) | 0.098 / 0.499 | 918 / 775 | +| LÖVE 12 Metal | 0.00 (rounded) | 0.120 / 0.278 | 1,179 / 692 | + +Short-workload CPU means were 1.012 → 0.920 ms/frame and 0.717 → 0.651 ms/frame, +respectively. Both retained approximately 60 FPS and restored the original +200/200 tuning when disabled. These are bounded synthetic allocation checks, +not full-game heap, long-session, arbitrary-finalizer or handheld measurements. diff --git a/main.lua b/main.lua index 3b1f7c1ac..0416fe53f 100644 --- a/main.lua +++ b/main.lua @@ -1208,6 +1208,9 @@ end function love.run() BootTrace.mark("love.run enter") + local Performance = require("src.core.Performance") + local GCFrameBudget = require("src.core.GCFrameBudget") + GCFrameBudget.configure(Performance) if love.load then love.load(love.arg.parseGameArguments(arg), arg) end BootTrace.mark("love.load returned") @@ -1245,6 +1248,7 @@ function love.run() -- update dt if love.timer then dt = love.timer.step() end + GCFrameBudget.beginFrame(Performance) -- call update and draw -- @@ -1302,7 +1306,7 @@ function love.run() if love.timer then if paced then local closeSleep = FrameProfile.section("frame pacing: sleep") - nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame) + nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame, GCFrameBudget.idle) closeSleep() else love.timer.sleep(0.001) diff --git a/src/core/FrameCap.lua b/src/core/FrameCap.lua index 09dbd7e98..763e116f2 100644 --- a/src/core/FrameCap.lua +++ b/src/core/FrameCap.lua @@ -53,14 +53,19 @@ end -- The run loop owns the deadline and passes back the returned value. Keeping -- the original fallback here lets tests exercise the real pacing operation. -function FrameCap.pace(timer, window, presented, nextFrame) +function FrameCap.pace(timer, window, presented, nextFrame, idleWork) local now = timer.getTime() + local budget = 1 / FrameCap.current + nextFrame = nextFrame + budget if FrameCap.vsyncPacing and presented and presentationPaces(window, now) then + if idleWork then + idleWork(timer, nextFrame) + return timer.getTime() + end return now end - local budget = 1 / FrameCap.current - nextFrame = nextFrame + budget if now - nextFrame > budget then nextFrame = now end + if idleWork then idleWork(timer, nextFrame) end while true do local remaining = nextFrame - timer.getTime() if remaining <= 0 then break end diff --git a/src/core/GCFrameBudget.lua b/src/core/GCFrameBudget.lua new file mode 100644 index 000000000..146d95f48 --- /dev/null +++ b/src/core/GCFrameBudget.lua @@ -0,0 +1,86 @@ +-- Cooperative incremental collection in otherwise unused frame time. +local Profile = require("src.core.FrameProfile") +local Budget = {} +local MAX_SECONDS = 0.0005 +local _collector, _priorPause, _priorMul, _pause, _mul +local _enabled, _seconds, _canQueryRunning, _facadeStepped = false, 0, false, false + +local function nonnegative(value, fallback) + if type(value) ~= "number" or value ~= value or value < 0 or value == math.huge then + return fallback + end + return value +end + +local function restoreTuning() + if _collector and _priorPause ~= nil then + _collector("setpause", _priorPause) + _collector("setstepmul", _priorMul) + end + _collector, _priorPause, _priorMul, _pause, _mul = nil, nil, nil, nil, nil +end + +function Budget.configure(performance, collector) + collector = collector or collectgarbage + if not performance.gcBudget or type(collector) ~= "function" then + restoreTuning() + _enabled = false + return + end + if _collector ~= collector then + restoreTuning() + end + local caps = performance.CAPS[performance.tier] or {} + local pause = math.floor(nonnegative(caps.gcPause, performance.GC_PAUSE)) + local mul = math.floor(nonnegative(caps.gcStepMul, performance.GC_STEP_MUL)) + if not _collector then + _collector = collector + _priorPause = collector("setpause", pause) + _priorMul = collector("setstepmul", mul) + _canQueryRunning = pcall(collector, "isrunning") + else + if pause ~= _pause then + collector("setpause", pause) + end + if mul ~= _mul then + collector("setstepmul", mul) + end + end + _pause, _mul = pause, mul + _seconds = math.min(MAX_SECONDS, nonnegative(caps.gcBudgetSeconds, performance.GC_BUDGET_SECONDS)) + _enabled = true +end + +function Budget.beginFrame(performance, collector) + _facadeStepped = false + Budget.configure(performance, collector) +end + +-- An existing public compatibility method retains ownership of its frame. +-- Its call, arguments and return behavior are not replaced by idle collection. +function Budget._facadeHandled() + _facadeStepped = true +end + +function Budget.idle(timer, deadline) + if not _enabled or _facadeStepped or _seconds <= 0 then + return 0 + end + local start = timer.getTime() + local stop = math.min(deadline, start + _seconds) + if stop <= start or (_canQueryRunning and not _collector("isrunning")) then + return 0 + end + local close = Profile.section(" frame pacing: gc budget") + local steps = 0 + while timer.getTime() < stop do + steps = steps + 1 + if _collector("step") then + break + end + end + close() + return steps +end + +return Budget diff --git a/src/core/Game.lua b/src/core/Game.lua index 9dc07ce9d..9be08083e 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -10,6 +10,8 @@ local Renderer = require("src.render.Renderer") local SaveData = require("src.core.SaveData") local StateStack = require("src.core.StateStack") local FrameProfile = require("src.core.FrameProfile") +local Performance = require("src.core.Performance") +local GCFrameBudget = require("src.core.GCFrameBudget") local TouchControls = require("src.core.TouchControls") local ModLoader = require("src.mods.Loader") local ModRuntime = require("src.mods.Runtime") @@ -635,19 +637,11 @@ function Game:update(dt) pcall(function() require("src.core.DiscordPresence").update(dt) end) close() end - -- Steady-state memory backstop: advance the incremental collector one - -- small step every rendered frame. The heavy GPU objects are now freed - -- explicitly (map eviction, battle exit, canvas/renderer swaps), so this - -- only has to keep ordinary Lua-heap garbage (per-frame tables/closures) - -- from drifting upward over a long session, and to spread collection out - -- so the default lazy schedule never batches it into a visible pause. - -- ONE INCREMENTAL GC STEP PER FRAME. Cheap on a small heap and not - -- obviously cheap under a mod that allocates a world's worth of geometry, - -- which is exactly the case being measured -- so it is named rather than - -- assumed. + -- Ordinary engine collection moves to spare deadline time in love.run. + -- P2 disabled retains the original native update step. if collectgarbage then local close = FrameProfile.section(" update: gc step") - collectgarbage("step", 1) + if not Performance.gcBudget then collectgarbage("step", 1) end close() end end diff --git a/src/core/Performance.lua b/src/core/Performance.lua index 861121ddd..359ba0811 100644 --- a/src/core/Performance.lua +++ b/src/core/Performance.lua @@ -42,6 +42,13 @@ local Performance = {} +-- P2 is independently reversible. Tier rows can reduce the idle budget or +-- tune the collector without changing the persisted presentation options. +Performance.gcBudget = true +Performance.GC_PAUSE = 120 +Performance.GC_STEP_MUL = 300 +Performance.GC_BUDGET_SECONDS = 0.0005 + -- Option-row order (auto first, then most to least capable). Performance.TIERS = { "auto", "high", "balanced", "low" } @@ -60,6 +67,11 @@ Performance.CAPS = { balanced = { tilt = false, gbcfx = false, survey = true, fpsMax = false }, low = { tilt = false, gbcfx = false, survey = false, fpsMax = 60 }, } +for _, caps in pairs(Performance.CAPS) do + caps.gcPause = Performance.GC_PAUSE + caps.gcStepMul = Performance.GC_STEP_MUL + caps.gcBudgetSeconds = Performance.GC_BUDGET_SECONDS +end -- Live resolved tier (never "auto"); Game:applyOptions sets it and the -- renderer / options row read it back. Defaults to the unclamped tier so diff --git a/tests/engine/gc_frame_budget.lua b/tests/engine/gc_frame_budget.lua new file mode 100644 index 000000000..974ba084e --- /dev/null +++ b/tests/engine/gc_frame_budget.lua @@ -0,0 +1,126 @@ +local T = require("tests.harness") +local Performance = require("src.core.Performance") +local Budget = require("src.core.GCFrameBudget") +local Cap = require("src.core.FrameCap") + +local function setup(cost) + local state = { now = 0, pause = 200, mul = 200, steps = 0, running = true, stepArgs = {}, sleeps = 0 } + local timer = { + getTime = function() + return state.now + end, + sleep = function(dt) + state.now = state.now + dt + state.sleeps = state.sleeps + 1 + end, + } + local function collector(command, ...) + local value = (...) + if command == "setpause" then + local old = state.pause + state.pause = value + return old + end + if command == "setstepmul" then + local old = state.mul + state.mul = value + return old + end + if command == "isrunning" then + return state.running + end + assert(command == "step", "unexpected collector command") + state.steps = state.steps + 1 + state.stepArgs[#state.stepArgs + 1] = select("#", ...) + state.now = state.now + (cost or 0.0001) + return state.completeAt and state.steps >= state.completeAt or false + end + return state, timer, collector +end +T.eq(Performance.gcBudget, true, "P2 defaults on") +T.eq(Performance.GC_PAUSE, 120, "requested collector pause") +T.eq(Performance.GC_STEP_MUL, 300, "requested collector step multiplier") +for _, tier in ipairs({ "high", "balanced", "low" }) do + T.eq(Performance.CAPS[tier].gcBudgetSeconds, 0.0005, "tier carries the default idle budget") +end +local state, timer, gc = setup() +Performance.tier = "high" +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 120, "frame applies requested pause") +T.eq(state.mul, 300, "frame applies requested step multiplier") +local steps = Budget.idle(timer, 0.01) +T.eq(steps, 5, "idle work stops at the half-millisecond budget") +for _, n in ipairs(state.stepArgs) do + T.eq(n, 0, "incremental step has no fixed kilobyte argument") +end +local before = state.steps +T.eq(Budget.idle(timer, state.now), 0, "no collector work starts at an exhausted deadline") +T.eq(state.steps, before, "expired deadline leaves collector untouched") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +T.eq(Budget.idle(timer, 0.00025), 3, "shorter deadline bounds started steps") +T.check(state.now <= 0.00035, "indivisible work can overshoot by at most one tested step") +state, timer, gc = setup() +state.completeAt = 2 +Budget.beginFrame(Performance, gc) +T.eq(Budget.idle(timer, 0.01), 2, "completed cycle does not immediately start another cycle") +state.running = false +T.eq(Budget.idle(timer, 0.01), 0, "a stopped collector is not restarted") +state.running = true +Budget._facadeHandled() +T.eq(Budget.idle(timer, 0.01), 0, "existing public GC delegation retains its frame") +Budget.beginFrame(Performance, gc) +T.check(Budget.idle(timer, 0.01) > 0, "next frame resets compatibility delegation ownership") +Performance.gcBudget = false +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 200, "disable restores previous collector pause") +T.eq(state.mul, 200, "disable restores previous step multiplier") +T.eq(Budget.idle(timer, 0.01), 0, "disabled P2 does no idle collector work") +Performance.gcBudget = true +local caps = Performance.CAPS.low +local oldPause, oldMul, oldSeconds = caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds +caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds = 140, 250, 0.0002 +Performance.tier = "low" +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 140, "tier-specific pause is respected") +T.eq(state.mul, 250, "tier-specific step multiplier is respected") +T.eq(Budget.idle(timer, 0.01), 2, "tier can reduce the idle budget") +caps.gcBudgetSeconds = 0.01 +Budget.beginFrame(Performance, gc) +before = state.steps +Budget.idle(timer, state.now + 0.1) +T.check(state.steps - before <= 6, "tier override cannot exceed the half-millisecond ceiling") +caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds = oldPause, oldMul, oldSeconds +Performance.tier = "high" +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +Cap.current, Cap.vsyncPacing = 60, false +local deadline = Cap.pace(timer, nil, false, 0, Budget.idle) +T.eq(state.steps, 5, "actual software pacing performs bounded GC before sleeping") +T.check(state.sleeps > 0, "software pacing sleeps after collection") +T.check(math.abs(deadline - 1 / 60) < 1e-9, "collection does not move the software deadline") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +Cap.vsyncPacing = true +local window = { + getVSync = function() + return 1 + end, + getMode = function() + return 320, 180, { refreshrate = 60 } + end, +} +state.now = 1 / 60 - 0.0003 +Cap.pace(timer, window, true, 0, Budget.idle) +T.check(state.steps > 0 and state.steps <= 4, "VSync uses only actual remaining deadline time") +T.eq(state.sleeps, 0, "VSync receives no extra sleep after collection") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +state.now = 1 / 60 + 0.001 +Cap.pace(timer, window, true, 0, Budget.idle) +T.eq(state.steps, 0, "late VSync present receives no invented idle budget") +Performance.gcBudget = false +Budget.configure(Performance, gc) +Performance.gcBudget = true +T.finish() diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index 952e314da..f9addab0a 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -15,6 +15,7 @@ def main(): parser.add_argument('--love', type=Path, required=True) parser.add_argument('--report', type=Path, required=True) parser.add_argument('--qa-tools', type=Path) + parser.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') args = parser.parse_args() root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(args.qa_tools or root / 'tools')) @@ -30,17 +31,21 @@ def main(): qa_profile(Path.home() / 'Library/Application Support/LOVE' / identity) result = qa_run([str(args.love.resolve()), str(root / 'tools/frame-pacing-check')], cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, - FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1'), + FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1', + FRAME_PACING_GC='1' if args.gc else '0'), capture_output=True, text=True, timeout=90) args.report.with_suffix('.log').write_text(result.stdout + result.stderr) - records = [line.removeprefix('P1_NATIVE_RESULT ') for line in result.stdout.splitlines() - if line.startswith('P1_NATIVE_RESULT ')] + prefix = 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' + records = [line.removeprefix(prefix) for line in result.stdout.splitlines() if line.startswith(prefix)] if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) report = json.loads(records[0]) report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + if args.gc: + files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', + 'tools/frame-pacing-check/gc.lua') report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} args.report.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2)) diff --git a/tools/frame-pacing-check/gc.lua b/tools/frame-pacing-check/gc.lua new file mode 100644 index 000000000..80067fa1e --- /dev/null +++ b/tools/frame-pacing-check/gc.lua @@ -0,0 +1,124 @@ +local Cap = require("src.core.FrameCap") +local Performance = require("src.core.Performance") +local Budget = require("src.core.GCFrameBudget") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local phase, frame, deadline, started, cpuStarted = 1, 0, 0, 0, 0 +local WINDOW, WARMUP = 120, 120 +local results, _trash = {}, nil +local witness = { key = "retained native data", value = 2712 } +local legacySteps, idleSteps, idleTotal, idleMax, heapPeak = 0, 0, 0, 0, 0 +local timer = { getTime = love.timer.getTime, sleep = love.timer.sleep } +local _, _, mode = love.window.getMode() +Cap.current = tonumber(mode.refreshrate) or 60 +if Cap.current <= 0 then + Cap.current = 60 +end +Cap.vsyncPacing = true +local originalPause = collectgarbage("setpause", 120) +collectgarbage("setpause", originalPause) +local originalMul = collectgarbage("setstepmul", 300) +collectgarbage("setstepmul", originalMul) + +local function resetStats() + legacySteps, idleSteps, idleTotal, idleMax, heapPeak = 0, 0, 0, 0, 0 +end +local function idle(clock, target) + local start = clock.getTime() + local steps = Budget.idle(clock, target) + if steps > 0 then + local duration = clock.getTime() - start + idleSteps, idleTotal = idleSteps + steps, idleTotal + duration + idleMax = math.max(idleMax, duration) + end +end +local function startPhase() + Profile.setEnabled(false) + Performance.gcBudget = phase == 2 + Budget.configure(Performance) + collectgarbage("collect") + frame = 0 + resetStats() + deadline = timer.getTime() +end +local function finishPhase() + assert(witness.key == "retained native data" and witness.value == 2712) + assert(_trash[512][2] == 512) + results[phase] = { + enabled = Performance.gcBudget, + frames = WINDOW, + seconds = timer.getTime() - started, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + legacySteps = legacySteps, + idleSteps = idleSteps, + idleMeanMs = idleTotal / WINDOW * 1000, + idleMaxMs = idleMax * 1000, + heapPeakKiB = heapPeak, + } + if phase == 2 then + Performance.gcBudget = false + Budget.configure(Performance) + local pause = collectgarbage("setpause", originalPause) + local mul = collectgarbage("setstepmul", originalMul) + assert(pause == originalPause and mul == originalMul, "disable did not restore GC tuning") + print("P2_NATIVE_RESULT " .. Json.encode({ + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = love.graphics.getRendererInfo(), + refresh = mode.refreshrate, + vsync = love.window.getVSync(), + cap = Cap.current, + originalPause = originalPause, + originalStepMul = originalMul, + phases = results, + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + resetStats() + Profile.setEnabled(true) + started, cpuStarted = timer.getTime(), os.clock() + end + Budget.beginFrame(Performance) + local close = Profile.section("update: allocation workload") + local rows = {} + for index = 1, 512 do + rows[index] = { frame, index, a = index * 2, b = index * 3 } + end + _trash = rows + close() + if not Performance.gcBudget then + close = Profile.section(" update: gc step") + collectgarbage("step", 1) + legacySteps = legacySteps + 1 + close() + end + love.graphics.clear(0.03, 0.04, 0.06) + close = Profile.section("present (GPU wait / vsync)") + love.graphics.present() + close() + close = Profile.section("frame pacing: sleep") + deadline = Cap.pace(timer, love.window, true, deadline, idle) + close() + frame = frame + 1 + if frame > WARMUP then + heapPeak = math.max(heapPeak, collectgarbage("count")) + Profile.frame() + end + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua index e280a2d74..5bb9948d3 100644 --- a/tools/frame-pacing-check/main.lua +++ b/tools/frame-pacing-check/main.lua @@ -1,5 +1,9 @@ local root = assert(os.getenv("FRAME_PACING_REPO")) package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path +if os.getenv("FRAME_PACING_GC") == "1" then + require("tools.frame-pacing-check.gc") + return +end local Cap = require("src.core.FrameCap") local Profile = require("src.core.FrameProfile") local Json = require("src.link.Json") From 0956e2e1773739fb619475dc8f1d8578532bc8cd Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:32:56 +0100 Subject: [PATCH 3/4] Respect already-loaded native GC delegation without loading a provider --- src/core/Game.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/Game.lua b/src/core/Game.lua index 9be08083e..8aa932b54 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -637,11 +637,14 @@ function Game:update(dt) pcall(function() require("src.core.DiscordPresence").update(dt) end) close() end + -- Keep an already-loaded native GC delegation at its update boundary. -- Ordinary engine collection moves to spare deadline time in love.run. - -- P2 disabled retains the original native update step. if collectgarbage then local close = FrameProfile.section(" update: gc step") - if not Performance.gcBudget then collectgarbage("step", 1) end + local facade = package.loaded["src.core.Game3"] + local handled = type(facade) == "table" and type(facade._stepGC) == "function" and facade._stepGC(self) + if handled then GCFrameBudget._facadeHandled() end + if not handled and not Performance.gcBudget then collectgarbage("step", 1) end close() end end From cb62f9404efd9bfbf34c92c5187d2357c0084cd2 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:42:49 +0100 Subject: [PATCH 4/4] Validate measured source fingerprints before and after native probes --- tools/check_frame_pacing.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index f9addab0a..160706770 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -5,7 +5,6 @@ import json import os from pathlib import Path -import subprocess import sys import time @@ -25,6 +24,14 @@ def main(): parser.error('QA storage guard is required; provide --qa-tools') qa_source(root) qa_source(args.love.resolve()) + files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', + 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + if args.gc: + files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', + 'tools/frame-pacing-check/gc.lua') + hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + source = qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, + capture_output=True, check=True).stdout.strip() qa_cache(args.report.parent) args.report.parent.mkdir(parents=True, exist_ok=True) identity = 'oasc-gen2recomp-qa-frame-pacing-' + str(time.time_ns()) @@ -40,13 +47,15 @@ def main(): if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) report = json.loads(records[0]) - report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() - files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', - 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') - if args.gc: - files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', - 'tools/frame-pacing-check/gc.lua') - report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + if any(hashlib.sha256((root / name).read_bytes()).hexdigest() != digest for name, digest in hashes.items()): + raise RuntimeError('Measured source changed during the pacing probe') + if qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, + capture_output=True, check=True).stdout.strip() != source: + raise RuntimeError('Measured commit changed during the pacing probe') + report['source'] = source + report['sha256'] = hashes + report['minimumFreeGiB'] = 20 + report['playerProfilesUsed'] = False args.report.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2))