fix(scripted-alarms): #995 K-3 a deploy reuses unchanged alarm predicates and compiles new ones outside the engine gate

Every LoadAsync cleared the compile cache and recompiled every predicate serially while holding _evalGate
(and, uncontended, on the ScriptedAlarmHostActor thread). Now the compile phase runs first on the thread
pool (bounded parallelism) without the gate, reusing source-hash-cached compiles; only the swap holds the
gate, and CompiledScriptCache.RetainOnly disposes just the retired predicates' ALCs. Out of process the
host's validation compile is remembered per source too.

Measured, 500 alarms (distinct predicates, in process, Release): reload of unchanged defs 1303 ms -> 15 ms;
one edited 1040 -> 16 ms; all-new reload 1002 -> 748 ms; ack issued during that reload waited 800 -> 1 ms.
This commit is contained in:
Joseph Doherty
2026-12-03 10:54:10 -05:00
parent 6822fd3f5c
commit e99df14665
6 changed files with 437 additions and 19 deletions
@@ -401,4 +401,26 @@ public sealed class CompiledScriptCacheTests
cache.Dispose();
Should.Throw<ObjectDisposedException>(() => cache.GetOrCompile("""return 2;"""));
}
/// <summary>
/// #995 K-3: RetainOnly keeps (and does not recompile) the kept sources, and disposes + drops the rest.
/// </summary>
[Fact]
public async Task RetainOnly_keeps_kept_entries_and_disposes_the_rest()
{
var cache = new CompiledScriptCache<FakeScriptContext, int>();
var kept = cache.GetOrCompile("""return 1;""");
var dropped = cache.GetOrCompile("""return 2;""");
cache.CompileCount.ShouldBe(2);
cache.RetainOnly(["""return 1;""", """return 3;"""]).ShouldBe(1);
cache.Count.ShouldBe(1);
cache.Contains("""return 1;""").ShouldBeTrue();
cache.GetOrCompile("""return 1;""").ShouldBeSameAs(kept);
cache.CompileCount.ShouldBe(2);
(await kept.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)).ShouldBe(1);
await Should.ThrowAsync<ObjectDisposedException>(
() => dropped.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken));
}
}