Skip to main content

What the Advisors Are Actually Doing

devlog
programming
compilers
ml
A shipped profile advisor, a memory-risk advisor that is only designed, and what I learned about letting a compiler choose without letting it approve itself.
Published

November 26, 2026

I keep using the word advisor, so it deserves its own note. I do not have a model that decides Lua is safe. I do not have a compiler that approves itself. What I have is one small deterministic advisor that shipped, and one memory-risk advisor that exists only as a design document.

That distinction is the whole point.

An advisor can make a narrow choice between paths that are already correct. It cannot invent a new correctness rule, delete a guard because a score looked good, or tell a CI job that a memory finding is fine. The deterministic runtime and the sanitizer/leak tools still own those answers.

An advisor chooses among legal paths. It is not the authority on whether the path is legal.

One family, two very different jobs

Two advisors, not one

It is easy to collapse these into “the AI part of the compiler”. That would be wrong, and it would make the shipped code sound more magical than it is.

Stage 7 guard-outcome advisor Stage 8 memory-risk advisor
Status implemented and tested design only
Input hit/fall counters from real runs emitted IR features plus normalized deterministic evidence
Decision skip an optional inline string probe rank sites and choose the next check
Learning none at runtime; fixed thresholds possible small offline model, not implemented
Authority none over semantics none over semantics
Default IR unchanged unchanged when off

Calling both of them advisors is intentional. Calling both of them machine learning would not be.

The Stage 7 advisor is a fixed rule over measured guard outcomes. The Stage 8 idea might use a small model later, but only as a triage queue. Neither one is allowed to say “safe”.


Advisor 1: the profiler that only deletes a shortcut

By Stage 7, one guarded choice had started to look silly. The shared inline string-field probe reads an object field once, then tries a cheap pointer identity check on a string key. If the pointer matches, it uses a native shortcut. If it does not, it calls the canonical lr_index, which handles metatables, equal-content strings, coercion, and errors.

That is a good shape when the pointer matches. It is dead weight when it never matches.

Baked tables rebuild string keys with str_new. A key that was a compile-time constant in source therefore has a different LStr pointer from the runtime key. The probe was correct, but every inline probe in those tables fell back. I could have guessed that. Instead I made the compiler measure it.

Guard outcomes become a versioned profile, not a vague hunch

What the training build emits

LUACOMP_PROFILE=<path> builds a training binary. That binary calls lr_profile_init once at entry and lr_profile_event(id, hit|fall) at every inline string probe. At exit it dumps a small, sorted text file:

luacomp-profile-v1
<source-digest>
142   0   418
287   5   611

The rows are id hits falls. Ids are source lines, not pointers or hash-table order. That is boring on purpose: the id does not move when an advisor decision changes emission. The digest covers the compiler version, Lua dialect, LÖVE mode, and all source texts.

Generalized usage:

# collect guard outcomes
LUACOMP_PROFILE=guard-profile.txt luacomp build game.lua

# consume them
LUACOMP_ADVISOR=auto luacomp build game.lua

LUACOMP_ADVISOR=conservative skips the optional probe without a profile. It is useful for correctness checks and bisecting. A normal build emits no counters at all.

The decision is deliberately dumb

The actual rule is a handful of lines:

let should_skip_entry entry =
  let total = entry.hits + entry.falls in
  entry.falls >= 100 && entry.falls * 20 > total * 19

In plain words: skip only when there are at least 100 samples and more than 95% of them fall back. There are no learned weights in the shipped compiler. No model is embedded in build or emit-ir. A high fallback count does not prove a fast path is wrong; it only proves that this optional shortcut is not paying for itself at that site.

The most important word there is optional. Skipping the inline probe does not remove a guard. The canonical lr_index still runs and still owns all Lua semantics.

Mode Emitted behavior
default inline probe kept, no counters
training counters emitted, decision not applied
auto with valid profile selected probes skipped, canonical helper kept
auto with stale/malformed profile warning, default emission
conservative all optional probes skipped without needing a profile

Stale, truncated, unknown-version, missing, or malformed profiles warn and fall back to today’s exact emission. If the evidence is not trustworthy, the compiler does not get clever.

What it bought

The checks mattered more than the speed number:

Gate Result
Default IR byte-identical to the previous stage
Full suite 45 passed, 2 known failures, in default and conservative modes
tests/advisor.ps1 all forced-decision checks passed
field_access, 11 interleaved runs each 19.7 ms to 18.3 ms median
Game benchmark early -0.3%/+1.6%, repeat +0.6%/+0.2%; called noise
ASan and ASan+UBSan 6 passed / 0 failed

The field_access win was believable because the profile explained it. The game result was not a win, and I said so. Default IR was unchanged, so a sub-percent move there was not a compiler victory. It was the same lesson the stability harness kept teaching me: a number without a distribution is a story, not evidence.


What Stage 7 actually taught me

The useful learning was not “profiles make code faster”. It was more specific.

  1. A guard has a hit rate. A cheap check is not cheap if it misses every time. That sounds obvious, but it only became actionable once I counted outcomes at the exact source site.
  2. A boring id is a feature. Source lines survived advisor decisions. Pointer-based ids would have made profiles fragile and hard to diff.
  3. A digest is part of correctness. Compiler version, dialect, LÖVE mode, and sources have to match. Otherwise an old profile can quietly describe a different program.
  4. An advisor can be deterministic. Fixed thresholds earned their place by being explainable and testable. I did not need a model to skip a probe that fell back 999 times out of 1000.
  5. Output parity is the gate. The skipped shortcut still lands in the same canonical helper. Correctness tests compare behavior, not vibes.

If any one of those had been missing, I would not have kept the advisor.


Advisor 2: memory-risk ranking, still on paper

The second advisor exists because profiling and safety are both big parts of this project. I want to find likely memory trouble early, but I do not want a model deciding that a program is clean.

Windows makes that boundary especially clear. LeakSanitizer is not supported in this toolchain. The Windows harness uses forced-GC checkpoints and private bytes, with a lower-envelope condition because heaps commit and decommit during normal churn. Linux can use LSan and Valgrind. Those are different kinds of evidence, and neither is a mathematical proof of zero leaks.

Evidence has to climb a ladder before it can even be ranked

What the advisor would look at

The smallest version extracts features offline from emitted LLVM IR text and joins them with normalized sanitizer and leak summaries. No new LLVM pass, no runtime instrumentation, and no change to generated code.

Feature family Examples Why it is interesting
Allocation lr_box_new, lr_closure_new, lr_table_new where lifetime pressure starts
Mutation lr_table_seti, lr_table_rawset, lr_setindex retention through tables
Results and varargs lr_ret_array, lr_ret_spread, lr_call_ext, lr_va_get temporary arrays with less obvious owners
Error sites store ptr @sN, ptr @lr_site inside loops error paths can hide skipped cleanup
Global retention lr_getglobal_c, lr_setglobal_c, module registration objects live past the local scope
Coroutines create/resume/yield plus allocation in loops lifetime crosses a suspend boundary
Deterministic evidence normalized ASan/LSan/Valgrind/growth results labels, not guesses

Ground truth would come only from sanitizer findings, LSan/Valgrind findings, and growth-check failures. Training splits would happen by whole workload, not by individual site. Otherwise the same program leaks into both training and test sets and the model learns the workload instead of the risk.

The model shape I would try first

Start small:

  1. regularized logistic regression;
  2. a small gradient-boosted tree model only if labels justify it;
  3. a versioned artifact with schema, feature digest, compiler/runtime digests, and calibration data.

The artifact has to be small enough to inspect and old enough to expire. A model/schema/digest mismatch is not a warning to ignore. It is a failure to use.

The interface would be opt-in

Mode Meaning
off default; no report, no behavior change
rank write a JSON report; never gate CI
strict run extra deterministic checks and fail on missing/stale evidence

strict does not mean “the model approves this build”. It means “ask the deterministic tools more questions, and fail closed if their evidence is not there”. Any finding still fails regardless of score.

A score changes order, not truth

The report language would be just as constrained as the code:

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

I do not want the words “safe” or “approved” in that report. “Ranked for review” and “needs deterministic follow-up” are slower to read, but they do not make a promise the tool cannot keep.


Why let ML near this at all

Because ranking is not judging.

A deterministic leak harness can tell me that a workload grew across repeated runs. LSan can tell me a pointer was definitely leaked. Valgrind can tell me about invalid access and leak classes. What they do not give me is a cheap, stable ordering of hundreds of sites in a large generated program.

A model could make that ordering less arbitrary. The cost of a false positive is that a human looks at a site. The cost of a false negative is that we do not run the next check on that site, while the deterministic tools still run later. The cost of a false safe claim is unacceptable, so that output is not in the vocabulary.

That is the difference between an advisor and an authority.

The learning loop is about trust, not larger models

What the learning was

The biggest lesson is that an advisor is most useful when its power is tiny.

The shipped advisor changes one optional probe. It has fixed thresholds, a versioned profile, source-line ids, and a canonical fallback. It cannot touch metatables, coercion, errors, Lua 5.1 versus 5.4 number rules, multiple returns, varargs, or the emitted IR when disabled. Because its blast radius is small, I can trust what it does.

The designed memory advisor is even more constrained on paper. It would rank work for humans and deterministic tools. It would not train inside the build, change codegen, remove guards, alter the ABI or layout, become a raw-log model, or approve a release. I have not written it because the labels are not good enough yet. That is a feature of the plan, not a delay in the marketing.

Plain Lua stays the contract through all of this. No pragmas, typed arrays, ffi, special calling conventions, or “write Lua the way the compiler likes”. If a fast path cannot keep that contract, it does not ship.

So when I say advisor, I mean a tool that says one of three things:

  • “this optional shortcut did not pay for itself; use the canonical helper”;
  • “this site is worth checking next”;
  • “I do not know”.

I do not mean “trust me”.


For the measurements that made the threshold meaningful, see Stability Over Bragging Rights. For the guard machinery around it, see Making Dynamic Lua Values Fast Without Asking Programmers to Help. For the leak lanes and the trace that changed the draw-call plan, see Draw-Call Detective Work and the Memory Safety Boundary.