lua: data race + engine deadlock — Execute/ExecuteString/CallFunction return on ctx cancellation without waiting for the goroutine that owns the pooled LState
Thanks for go-scripts — the Lua/JS unification and the
SyncExecutor/QuotaControllerdesign are genuinely nice. This report is about the async execution paths (Execute/ExecuteString/CallFunction), which behave differently fromExecuteSync.
Summary
Execute, ExecuteString and CallFunction each spawn a goroutine that takes e.mu and runs on the pooled *LState, then select on ctx.Done(). When the caller's context is cancelled the function returns immediately, while that goroutine is still running — and still holds both e.mu and the pooled LState.
Because the LState is pooled and reused, the leaked goroutine can outlive its engine and end up sharing an LState with a later engine. go test -race reports this as a data race between (*LState).callR (read) and (*LState).SetContext (write).
There is a second, arguably worse consequence: none of the three functions call L.SetContext, so the VM runs the non-context-checking mainLoop. A runaway script is therefore never interrupted, e.mu is never released, and the engine deadlocks.
Reproduction
go-scripts/lua v0.0.9, gopher-lua v1.1.2. Create, exercise and close an engine twice:
func TestLeak(t *testing.T) {
for i := 0; i < 2; i++ {
e := lua.NewEngine(lua.DefaultConfig(), logger)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
_ = e.LoadString(ctx, "x", "while true do end")
_, _ = e.ExecuteString(ctx, "x", "while true do end") // returns on cancel
cancel()
_ = e.Close()
}
}
Run with go test -race. Reported frames:
Read at 0x... by goroutine N:
github.com/yuin/gopher-lua.(*LState).callR() state.go:1269
github.com/yuin/gopher-lua.(*LState).Call() state.go:2026
github.com/tx7do/go-scripts/lua.(*virtualMachine).openAllowedLibs.func1()
virtual_machine.go:157
...
github.com/tx7do/go-scripts/lua.(*engine).Init() lua_engine.go:105
Previous write at 0x... by goroutine N-1:
github.com/yuin/gopher-lua.(*LState).SetContext() state.go:2262
Note the shape: the read side is a brand-new engine initialising, and the write side is a leftover goroutine from a previously cancelled call — on the same LState, because the pool handed it back out.
Root cause
All three functions share this shape (lua_engine.go):
done := make(chan error, 1)
go func() {
e.mu.Lock()
defer e.mu.Unlock()
if !e.initialized { done <- ErrLuaEngineNotInitialized; return }
done <- e.vm.Execute() // runs on the pooled LState
}()
select {
case <-ctx.Done():
e.setLastError(ctx.Err())
return nil, ctx.Err() // <-- returns without waiting for the goroutine
case err := <-done:
...
}
e.mu is held for the goroutine's whole lifetime, which is why the wedge is total rather than intermittent.
Suggested fix
Two changes, and both are needed:
// 1) in the goroutine, before running — let the VM actually be interrupted
L := e.vm.L
L.SetContext(ctx)
defer L.RemoveContext()
// 2) on the cancellation branch — do not leak the goroutine
case <-ctx.Done():
<-done
e.setLastError(ctx.Err())
return nil, ctx.Err()
Adding only (2) turns the leak into a hang for a runaway script: with no ctx check on the LState the VM has nothing to abort on, so <-done blocks forever. Adding only (1) stops the hang but still leaks the goroutine.
ExecuteSync already does exactly this — it takes e.mu for the whole run and calls L.SetContext(runCtx) (lua_engine.go:631) — so this would make the async paths consistent with the sync one.
Affected versions
v0.0.8, v0.0.9, v0.0.10 and v0.0.11 all have the same early return. Note that lua_engine.go is byte-identical across v0.0.9, v0.0.10 and v0.0.11 (sha256 0d3cf5bf9093b91e092d861bc0342f6c...), so upgrading does not help.
Impact in practice
We hit this as a -race failure in our own test suite (5 tests), and separately as a hung go test that only ended at the 600s timeout — the goroutine dump showed lua_engine.go:367 (RegisterGlobal) waiting on e.mu. Worth noting that per-test isolation hides the race: each test passes on its own, and it only shows up when several engines are created and closed in one process, which is the normal shape for an integration suite.
Happy to test a patch if that helps.