Skip to main content

Draw-Call Detective Work and the Memory Safety Boundary

devlog
programming
memory
A profiling trace that disproved a table-allocation theory, a guarded field-call pass with no measurable win, and leak harnesses that still do not prove zero leaks.
Published

November 26, 2026

I went looking for a temporary table in the draw path. I found eight numbers, a guarded call path that did not pay off, and a much more important lesson about where I am willing to let automation make decisions.

This is one of those logs where the most useful result is a negative one.


The trace that refused to confirm my theory

The Lumen logic stub had an opt-in trace mode. Set LUMEN_STUB_TRACE=1 and the no-op graphics wrappers record each call name plus the Lua type of every argument. Nothing is rasterized; the trace only describes what the game Lua asked for.

At 300 frames:

Mode Traced calls Shapes Draw calls
idle 237,604 12 112,500
demo 242,502 13 114,140

The output was byte-identical between luacomp and LuaJIT. That mattered more than the raw counts: before comparing speed, I wanted both engines to be asking for the same work.

Draw-call traces are dominated by scalar shapes

The two dominant shapes were:

Shape Count across both modes
setColor(number,number,number,number) 201,146
polygon(string,eight numbers) 147,000 combined

The suspected temporary-table path did not exist. iso.corners returns eight numbers, not a table. The only table argument in the whole traced set was the persistent font object passed to setFont.

That killed a plausible story. I had been thinking in terms of escape analysis and stack allocation for corner tables. There were no corner tables.

The real per-frame literal-table churn is in Lumen’s shadow color and depth-list entries. That is a plain-Lua source concern, not evidence that the compiler needs whole-program escape analysis. I deliberately did not build a large optimization for a shape the trace did not show.


Why a GPU backend would not fix Lua execution

It is tempting to say “draw calls are slow, put them on the GPU”. That would answer a different problem.

The existing GPU shader demo is for stock LÖVE 11.x. It checks a million fake AST nodes per frame on the GPU, and it explicitly does not run under luacomp because luacomp has no shaders or canvas. The headless LÖVE path uses a small software renderer for correctness checks. Neither of those removes the Lua work I was measuring.

When I replaced drawing with no-ops, the gap stayed:

Case Lua 5.4 LuaJIT luacomp
Lumen baseline 251.5 ms 70.6 ms 181.5 ms
Lumen no draw 26.7 ms 15.1 ms 19.6 ms
Starfall baseline 73.9 ms 22.3 ms 43.9 ms
Starfall no draw 52.6 ms 17.0 ms 31.7 ms

With drawing disabled, the three engines are much closer on Lumen. The remaining work is argument construction, table.sort, temporary tables, coroutines, and module state. A faster rasterizer would not execute one fewer Lua bytecode or build one fewer argument array.

That is why the no-op stub exists. It keeps the game logic and removes the pixel-pushing that was hiding it. The software renderer is still useful: it showed rendered frame 300 was byte-identical before and after a compiler change in both games. It is just the wrong instrument for Lua stability.


The guarded scalar field-call pass

Once I knew the draw calls were mostly scalar arguments, I added a narrow path in backend/gen.ml for obj.field(...):

  • no multi-value or spread trailing argument;
  • every fixed argument proven numeric;
  • read the field once through the Stage 5 metatable-safe string probe;
  • write raw number payloads straight into the native argument array;
  • call canonical lr_call.

A simplified before/after sketch:

; Before: each numeric argument becomes a boxed %V slot.
%arg0 = alloca %V
call void @set_int(ptr %arg0, i64 2)
%arg1 = alloca %V
call void @set_double(ptr %arg1, double 0.4)
call i32 @lr_call(ptr %callee, ptr %args, i32 2)

; After sketch: evaluate the field first, then store raw payloads.
%callee = call ptr @string_index_slot(ptr %obj, ptr %key)  ; guarded
%a0ptr  = getelementptr inbounds %V, ptr %args, i64 0
%bits   = getelementptr inbounds %V, ptr %a0ptr, i32 0, i32 0
store i64 2, ptr %bits
call i32 @lr_call(ptr %callee, ptr %args, i32 2)           ; still canonical

The sketch keeps the important boundary: the call still goes through lr_call. Metatables, __index, __call, coercion cases, dynamic keys, multiple returns, varargs, and nil/non-function errors keep their existing paths. There is no new function variant and no new runtime ABI.

Evaluation order stays Lua order. The field is read before the arguments.

local function replace()
  api.add = function(a, b) return -a, -b end
  return 10
end

print("order", api.add(replace(), 7))

The call must use the old function with 10 and 7. The test also covers two returns, string coercion, dynamic equal-content keys, __index, __call, multi-return spread, varargs, and return context.

tests/ir-defines.ps1 now checks the IR structurally for three things:

direct scalar argument stores present?        yes
lr_call_ext multi-return fallback present?    yes
lr_index canonical field fallback present?    yes
every emitted function variant defined once?  yes

The honest performance result

This is where the story stops being a win.

Workload Before After Runs
draw_calls (real eight-number spread) 5.53 ms 5.62 ms 21 interleaved
Lumen logic, idle 37.04 ms 37.24 ms 101 A/B
Lumen logic, demo 38.49 ms 38.82 ms 101 A/B
field_call_scalars 5.38 ms 5.40 ms interleaved

There is no measurable win on this machine. The corrected draw_calls benchmark models the real eight-number spread, and it got very slightly worse. The Lumen A/B is flat within noise, but slightly the wrong direction.

I kept the pass anyway, and I want to be precise about why. It is low-risk groundwork for a future typed native call: the scalar payloads are already in the argument array without going through boxing helpers. If a later stage removes the generic call boundary, this shape is ready. Today it is not a speed claim.

This is also why I report distributions instead of a favorite run. The one-number version of this result would have been “field calls are faster now” if I had cherry-picked the right sample. The 101-run Lumen A/B does not let me say that.


Memory safety: two lanes, one boundary

The other half of this work was leak regression coverage. I did not add a single magic detector. I added two lanes because the platforms genuinely differ.

Two deterministic memory lanes

The four churn programs are plain Lua 5.1/5.4 compatible and use no assets:

Program What it churns
table_string_closure_churn rows, formatted strings, upvalue closures
meta_coroutine_churn fresh metatables with closures, resumed coroutine
pcall_error_churn caught error messages, successful pcall calls
draw_call_churn no-op vararg draw calls and corner tables

Each program prints forced-GC checkpoints like CHECKPOINT <program> warmup kb=<n>. Expected files replace only the live number with kb=<n>, so labels and deterministic checksums still have to match.

On Windows, tests/leak.ps1:

  • builds each program into a private temp folder;
  • runs a warm-up process and repeated measured processes;
  • checks final - warmup against a retained-growth limit;
  • checks monotonic checkpoint growth with a noise allowance;
  • samples PrivateMemorySize64 and WorkingSet64 about every 40 ms;
  • fails on a private-bytes slope only when the net rise and lower envelope also rise.

That lower-envelope condition is not decorative. CRT heaps commit and decommit during churn, so a raw private-bytes slope is often positive with no live leak. A sustained leak raises the minimum as well as the peak.

Windows LeakSanitizer is unsupported by both clang-cl and MSVC ASan in this toolchain. ASAN_OPTIONS=detect_leaks=1 prints detect_leaks is not supported on this platform. Windows ASan can still report heap errors and UBSan can report UB, but leak detection belongs on Linux. The Windows ASan build also sometimes prints an interception_win instruction warning during UCRT calls; the harness filters that known warning.

Generalized commands:

powershell -NoProfile -ExecutionPolicy Bypass -File .\tests\leak.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\tests\leak.ps1 -Lua 5.1 -Repeat 5

On Linux, tests/leak.sh builds with LUACOMP_SANITIZE=address, runs with ASAN_OPTIONS=detect_leaks=1:report_reachable=0, compares normalized output, and fails on any LSan/ASan finding. --valgrind adds a second pass over a plain build when Valgrind is installed.

LUACOMP=./luacomp sh tests/leak.sh
LUACOMP=./luacomp sh tests/leak.sh --valgrind

report_reachable=0 matters. Runtime globals such as the GC mark set, string pool, and package.loaded can legitimately be live at process exit. Those are “still reachable”, not definite leaks. If I enable them for inspection I compare sizes across repeated runs; steady globals are expected, growth is not.

The Windows checks passed 12/12 by default and 4/4 under Lua 5.1. ASan and ASan+UBSan suites stayed at 6 passed / 0 failed. To check that the harness was not just a rubber stamp, I used a temporary deliberately leaky program. It was caught at retained +22971 KiB, then removed.

That is a regression check for gross leaks. It is not proof that leaks are impossible. I will keep saying that.


The advisor boundary

I sketched a Stage 8 memory-risk advisor, but I have not implemented it. The design exists mainly to keep the ownership boundary clear before any model touches the build. I go deeper into the reasoning in What the Advisors Are Actually Doing.

The memory-risk advisor has a narrow boundary

Deterministic tools remain authoritative:

  • tests/asan.ps1 for ASan and UBSan findings;
  • Linux LSan and Valgrind for real leak findings;
  • tests/leak.ps1 for Windows retained-growth regressions;
  • existing guards, GC rules, and runtime helpers for correctness.

The advisor may rank sites for review or choose which deterministic check to run next. It may never declare a program safe, suppress a finding, remove a guard, change emitted IR, or approve a build.

Suspicious allocation site
├── deterministic finding?  → fail, regardless of score
├── evidence stale/missing? → fail closed in strict mode
├── enough evidence?        → rank for review
└── no finding, weak rank   → still not "safe"; just not next in line

The first features would come from emitted IR text: lr_box_new, lr_closure_new, lr_table_new, error sites inside loops, fallible helpers after a site store, global/module retention, coroutine shapes. Ground truth would come only from sanitizer findings, LSan/Valgrind findings, and growth failures, split by whole workload rather than by site.

I would start with regularized logistic regression, then maybe a small gradient-boosted tree if there are enough labeled sites. No training inside luacomp build. No opt pass. No learned approval.


What I am taking forward

The draw-call trace changed the plan. There was no temporary table to remove, so I did not build an optimizer for one. The guarded scalar field-call pass is correct and structurally useful, but it did not make the program faster. The leak harnesses catch gross regressions on two platforms, and the Windows lane is explicit about not being LSan.

The common thread is that I want tools which can say “I do not know” without embarrassing me. A trace that says eight numbers, an A/B that says no win, a leak check that says gross-only, and an advisor that says ranked-for-review are all more useful than a confident story built on the wrong shape.

For the measurement side of that habit, see Stability Over Bragging Rights. For the guarded fast paths that the field-call pass builds on, see Making Dynamic Lua Values Fast Without Asking Programmers to Help.