RynthSuite as of 2026-12-02 (internal 152e13d): release 2026.12.1.1

This commit is contained in:
Tom Bohar 2026-12-02 06:45:07 -05:00
commit 6b5a9c7e99
65 changed files with 3920 additions and 237 deletions

View file

@ -139,6 +139,10 @@ public sealed partial class RynthLuaPlugin
/// <summary>Test harness only: whether a script's Lua state is still alive.</summary>
internal bool ScriptIsLoaded(string name) => _scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded;
/// <summary>Test harness only: worker coroutines a running script has made (-1 when it isn't running).</summary>
internal int ScriptWorkersCreated(string name) =>
_scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded ? ctx.Host.WorkersCreated : -1;
private void RegisterGame(Script s, ScriptContext ctx)
{
var game = new Table(s);

View file

@ -32,15 +32,127 @@ internal sealed class LuaScriptHost
private sealed class LuaThread
{
public DynValue Co = DynValue.Nil;
public DynValue Co = DynValue.Nil; // set when the thread first runs (TakeCoroutine)
public DynValue Fn = DynValue.Nil; // the function, until then
public long WakeAt;
public Func<bool>? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty<DynValue>();
public bool Started;
/// <summary>Runs on a pooled worker coroutine (see <see cref="RentWorker"/>): it ends by yielding the done token.</summary>
public bool Pooled;
/// <summary>Called once when the thread ends: its return values, or the error message.</summary>
public Action<DynValue?, string?>? OnDone;
}
// ── Worker coroutines ───────────────────────────────────────────────────
//
// MoonSharp 2.0 gives every coroutine two 131,072-slot stacks the moment it is created:
// about 1 MB in the 32-bit client (2 MB in a 64-bit process), all on the Large Object Heap,
// which only a full collection frees. RynthLua used to make one per event handler call and
// per hud pass, so a 194-line /myquests read cost each script with a chat handler ~200 MB and
// a 20-per-second window 20 MB/s. The heap figure the memory guard reads then passed 800 MB
// and the guard stopped scripts that had done nothing wrong (2026-11-30).
// Now a thread runs on a worker: a Lua loop that calls the function it is given, yields the
// done token with the results, and waits for the next function. A worker whose function
// ended normally goes back to a small pool; one that raised an error, or was aborted or
// stopped part-way, is simply dropped (it can't be reused).
private const string WorkerCode = @"
local DONE, yield, select, unpack = ...
local function packn(...) return { n = select('#', ...), ... } end
return function(fn, args)
while true do
fn, args = yield(DONE, packn(fn(unpack(args, 1, args.n))))
end
end";
/// <summary>Idle workers kept per script; more than this are left to the GC.</summary>
internal const int MaxIdleWorkers = 8;
private DynValue _workerFn = DynValue.Nil;
private Table? _doneToken;
private readonly Stack<DynValue> _idleWorkers = new();
/// <summary>Test hook: workers made since the script started (a fresh coroutine each).</summary>
internal int WorkersCreated { get; private set; }
/// <summary>
/// Makes the worker function from the state's own coroutine.yield, select and table.unpack,
/// taken before any script code runs (a script that replaces them later doesn't touch workers).
/// </summary>
private void CreateWorkers(Script s)
{
_idleWorkers.Clear();
_workerFn = DynValue.Nil;
_doneToken = null;
WorkersCreated = 0;
try
{
DynValue co = s.Globals.Get("coroutine");
DynValue tbl = s.Globals.Get("table");
DynValue yield = co.Type == DataType.Table ? co.Table.Get("yield") : DynValue.Nil;
DynValue select = s.Globals.Get("select");
DynValue unpack = tbl.Type == DataType.Table ? tbl.Table.Get("unpack") : DynValue.Nil;
if (unpack.IsNil()) unpack = s.Globals.Get("unpack");
if (yield.IsNil() || select.IsNil() || unpack.IsNil()) return; // old behaviour: a coroutine per thread
var token = new Table(s);
DynValue factory = s.LoadString(WorkerCode, new Table(s), "rynth worker");
DynValue fn = s.Call(factory, DynValue.NewTable(token), yield, select, unpack);
if (fn.Type != DataType.Function) return;
_doneToken = token;
_workerFn = fn;
}
catch { _workerFn = DynValue.Nil; _doneToken = null; }
}
/// <summary>An idle worker, or a new one; null when workers aren't available (a coroutine per thread then).</summary>
internal DynValue? RentWorker()
{
if (_script == null || _workerFn.Type != DataType.Function) return null;
while (_idleWorkers.Count > 0)
{
DynValue w = _idleWorkers.Pop();
if (w.Coroutine.State is CoroutineState.Suspended or CoroutineState.NotStarted) return w;
}
WorkersCreated++;
return _script.CreateCoroutine(_workerFn);
}
/// <summary>Puts a worker that yielded the done token back in the pool.</summary>
internal void ReturnWorker(DynValue worker)
{
if (_script == null || worker.Coroutine.State is not (CoroutineState.Suspended or CoroutineState.NotStarted)) return;
if (_idleWorkers.Count < MaxIdleWorkers) _idleWorkers.Push(worker);
}
/// <summary>What a worker is resumed with to run <paramref name="fn"/>(<paramref name="args"/>...).</summary>
internal DynValue[] WorkerArgs(DynValue fn, DynValue[] args)
{
var t = new Table(_script);
for (int i = 0; i < args.Length; i++) t.Set(i + 1, args[i]);
t.Set("n", DynValue.NewNumber(args.Length));
return new[] { fn, DynValue.NewTable(t) };
}
/// <summary>True when <paramref name="r"/> (a worker's Resume result) says its function returned.</summary>
internal bool IsWorkerDone(DynValue r) =>
_doneToken != null && r.Type == DataType.Tuple && r.Tuple is { Length: 2 } tu
&& tu[0].Type == DataType.Table && ReferenceEquals(tu[0].Table, _doneToken);
/// <summary>The function's return values from a done worker's result: Void for none, the value for one, else a tuple.</summary>
internal static DynValue WorkerResults(DynValue r)
{
DynValue packed = r.Tuple[1];
if (packed.Type != DataType.Table) return DynValue.Void;
Table t = packed.Table;
DynValue nv = t.RawGet("n") ?? DynValue.Nil;
int n = nv.Type == DataType.Number ? (int)nv.Number : 0;
if (n <= 0) return DynValue.Void;
if (n == 1) return t.Get(1);
var values = new DynValue[n];
for (int i = 0; i < n; i++) values[i] = t.Get(i + 1);
return DynValue.NewTuple(values);
}
private readonly Action<string> _log;
private readonly Action<Script, LuaScriptHost> _registerApi;
private readonly List<LuaThread> _threads = new();
@ -157,6 +269,7 @@ internal sealed class LuaScriptHost
try
{
RegisterCore(script);
CreateWorkers(script);
_registerApi(script, this);
DynValue chunk = script.LoadString(code, null, ScriptName.Length > 0 ? ScriptName : "editor");
Start(chunk, Array.Empty<DynValue>());
@ -198,6 +311,9 @@ internal sealed class LuaScriptHost
bool was = _script != null;
_threads.Clear();
_handlers.Clear();
_idleWorkers.Clear();
_workerFn = DynValue.Nil;
_doneToken = null;
_current = null;
_botTickThread = null;
_script = null;
@ -223,13 +339,29 @@ internal sealed class LuaScriptHost
public object? Start(DynValue fn, DynValue[] args, Action<DynValue?, string?>? onDone)
{
if (_script == null || fn.Type != DataType.Function) return null;
DynValue co = _script.CreateCoroutine(fn);
co.Coroutine.AutoYieldCounter = AutoYieldCounter;
var t = new LuaThread { Co = co, Args = args, OnDone = onDone };
// The coroutine is taken when the thread first runs (Tick), not here: a burst of events
// (194 /myquests lines between two ticks) then runs one after another on the same few
// workers instead of holding a worker each while they wait for their turn.
var t = new LuaThread { Fn = fn, Args = args, OnDone = onDone };
_threads.Add(t);
return t;
}
/// <summary>Gives a thread that is about to run for the first time its coroutine.</summary>
private void TakeCoroutine(LuaThread t)
{
DynValue? worker = RentWorker();
if (worker != null)
{
t.Co = worker;
t.Args = WorkerArgs(t.Fn, t.Args);
t.Pooled = true;
}
else t.Co = _script!.CreateCoroutine(t.Fn);
t.Fn = DynValue.Nil;
t.Co.Coroutine.AutoYieldCounter = AutoYieldCounter;
}
/// <summary>
/// Ends the thread <paramref name="handle"/> (from <see cref="Start(DynValue, DynValue[], Action{DynValue?, string?}?)"/>)
/// without resuming it again; its onDone is not called. Returns false when it had already ended.
@ -239,7 +371,7 @@ internal sealed class LuaScriptHost
if (handle is not LuaThread t) return false;
t.OnDone = null;
if (ReferenceEquals(_botTickThread, t)) _botTickThread = null;
return _threads.Remove(t);
return _threads.Remove(t); // a worker stopped part-way is dropped with it
}
private static void Done(LuaThread t, DynValue? result, string? error)
@ -401,9 +533,10 @@ internal sealed class LuaScriptHost
{
while (_script != null)
{
if (!t.Started) TakeCoroutine(t);
r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
t.Started = true;
if (t.Co.Coroutine.State == CoroutineState.Dead) break;
if (t.Co.Coroutine.State == CoroutineState.Dead || (t.Pooled && IsWorkerDone(r))) break;
// A thread allocating fast pauses far more often, so the guard sees it before
// a single stretch of 5,000 instructions can use a gigabyte (string.rep in a loop).
if (t.Co.Coroutine.AutoYieldCounter > FastAllocYieldCounter
@ -445,6 +578,14 @@ internal sealed class LuaScriptHost
_threads.Remove(t);
Done(t, r, null);
}
else if (t.Pooled && IsWorkerDone(r))
{
// The function returned: the worker waits at its yield for the next one.
_threads.Remove(t);
if (ReferenceEquals(_botTickThread, t)) _botTickThread = null;
ReturnWorker(t.Co);
Done(t, WorkerResults(r), null);
}
if (OverBudget()) break;
}
}

View file

@ -530,10 +530,17 @@ public sealed partial class RynthLuaPlugin
long alloc0 = LuaScriptHost.AllocationMark();
try
{
DynValue co = s.CreateCoroutine(runner);
// A pooled worker (LuaScriptHost: a new coroutine is ~1 MB) when the host has them.
LuaScriptHost host = hud.Ctx.Host;
DynValue? worker = host.RentWorker();
DynValue co = worker ?? s.CreateCoroutine(runner);
co.Coroutine.AutoYieldCounter = PassInstructionCap;
DynValue r = co.Coroutine.Resume(DynValue.NewTable(list));
if (co.Coroutine.State != CoroutineState.Dead)
DynValue r = worker != null
? co.Coroutine.Resume(host.WorkerArgs(runner, new[] { DynValue.NewTable(list) }))
: co.Coroutine.Resume(DynValue.NewTable(list));
if (worker != null && host.IsWorkerDone(r))
host.ReturnWorker(co); // the pass ran to its end; anything else drops the worker
else if (co.Coroutine.State != CoroutineState.Dead)
{
error = r.Type == DataType.YieldRequest
? $"OnRender ran too long (over {PassInstructionCap} instructions); the last good frame stays"