Callbacks leak: nothing is ever unpinned #9

Closed
opened 2026-10-23 12:34:18 +01:00 by pedro-bento · 1 comment
Owner

Summary

Every callback passed to raylib is pinned forever. pin() appends to a global list and caches the
closure in a strong table. Nothing ever removes an entry, so replacing or detaching a callback
leaks both the Lua closure and the FFI trampoline.

Current behavior

gen-hate-no-d.lua:769-787 emits:

local pinned = {}
local callback_cache = {}
local function pin(ctype, fn)
  callback_cache[fn] = by_type   -- strong key: closure never collected
  pinned[#pinned + 1] = cb       -- strong value: trampoline never freed
  return cb
end

Consequences:

  • A program that creates one audio processor per scene keeps every closure alive.
  • SetAudioStreamCallback(stream, other) keeps the previous closure and pointer pinned too.
  • DetachAudioStreamProcessor calls pin() again (hate-no-d.lua:8775), so detaching adds
    references instead of removing them.

There are 9 callback parameters in the API; each has this problem.

Why it matters

Long-running programs grow without bound, and there is no way for a caller to release a callback.
The growth is invisible until memory or trampoline count shows up in a profile.

Proposal

Replace the two global tables with a slot registry.

  1. One slot per callback position. Global setters use a string key ("file:data"). Per-stream
    callbacks key on stream.buffer, which is stable and unique per stream.
  2. Setters replace. Set*Callback(fn) overwrites the slot; nil clears it.
  3. Processors refcount. Attach* increments, Detach* decrements and returns the same
    pointer that was attached. Detaching an unpinned function still works, with no retention.
  4. Cast cache is weak. ffi.cast results are cached with __mode = "k" so an unused closure
    can be collected.
  5. Clear on close. CloseWindow clears all slots; M.callbacks.releaseAll() does it manually.

Sketch of the registry:

local slots = {}                                  -- key -> { fn, cb }
local cast_cache = setmetatable({}, { __mode = "k" })

local function set(key, ctype, fn)
  slots[key] = nil
  if fn == nil then return nil end
  local e = { fn = fn, cb = cast(ctype, fn) }
  slots[key] = e
  return e.cb
end

Acceptance criteria

  • SetAudioStreamCallback(s, cb) twice leaves exactly one live entry.
  • Attach/Detach in a loop does not grow memory; detach passes the pinned pointer.
  • After collectgarbage(), a dropped callback closure is collected.
  • 10 000 attach/detach cycles leave collectgarbage("count") flat.
  • make check-bindings passes.

Notes

  • slots must hold fn; the closure has to outlive raylib's use of the pointer.
  • Detach of an unknown function is not an error; it forwards a temporary cast like today.
## Summary Every callback passed to raylib is pinned forever. `pin()` appends to a global list and caches the closure in a strong table. Nothing ever removes an entry, so replacing or detaching a callback leaks both the Lua closure and the FFI trampoline. ## Current behavior `gen-hate-no-d.lua:769-787` emits: ```lua local pinned = {} local callback_cache = {} local function pin(ctype, fn) callback_cache[fn] = by_type -- strong key: closure never collected pinned[#pinned + 1] = cb -- strong value: trampoline never freed return cb end ``` Consequences: - A program that creates one audio processor per scene keeps every closure alive. - `SetAudioStreamCallback(stream, other)` keeps the previous closure and pointer pinned too. - `DetachAudioStreamProcessor` calls `pin()` again (`hate-no-d.lua:8775`), so detaching *adds* references instead of removing them. There are 9 callback parameters in the API; each has this problem. ## Why it matters Long-running programs grow without bound, and there is no way for a caller to release a callback. The growth is invisible until memory or trampoline count shows up in a profile. ## Proposal Replace the two global tables with a slot registry. 1. **One slot per callback position.** Global setters use a string key (`"file:data"`). Per-stream callbacks key on `stream.buffer`, which is stable and unique per stream. 2. **Setters replace.** `Set*Callback(fn)` overwrites the slot; `nil` clears it. 3. **Processors refcount.** `Attach*` increments, `Detach*` decrements and returns the *same* pointer that was attached. Detaching an unpinned function still works, with no retention. 4. **Cast cache is weak.** `ffi.cast` results are cached with `__mode = "k"` so an unused closure can be collected. 5. **Clear on close.** `CloseWindow` clears all slots; `M.callbacks.releaseAll()` does it manually. Sketch of the registry: ```lua local slots = {} -- key -> { fn, cb } local cast_cache = setmetatable({}, { __mode = "k" }) local function set(key, ctype, fn) slots[key] = nil if fn == nil then return nil end local e = { fn = fn, cb = cast(ctype, fn) } slots[key] = e return e.cb end ``` ## Acceptance criteria - [ ] `SetAudioStreamCallback(s, cb)` twice leaves exactly one live entry. - [ ] `Attach`/`Detach` in a loop does not grow memory; detach passes the pinned pointer. - [ ] After `collectgarbage()`, a dropped callback closure is collected. - [ ] 10 000 attach/detach cycles leave `collectgarbage("count")` flat. - [ ] `make check-bindings` passes. ## Notes - `slots` must hold `fn`; the closure has to outlive raylib's use of the pointer. - Detach of an unknown function is not an error; it forwards a temporary cast like today.
Author
Owner

#15

https://git.pbento.pt/pedro-bento/hate-no-d/pulls/15
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: pedro-bento/hate-no-d#9
No description provided.