Split the trial judge into units and run them on a resumable worker pool

The tournament of Phase 13 needs many trials to run on more than one thread
and to survive a restart without redoing finished work. The judge was one
monolithic call on one thread, so a restart redid the whole trial.

TrialRunner.Run is now Judge(Variants()): Variants does every engine execution
as a keyed unit in two stages (grid and outside-grid run, then, after the
plateau choice, costed runs, benchmark and look-ahead), and Judge is the old
pure judging code working on runs assembled by key. Both Run overloads keep
their signatures; on one thread the engine is called in the order of today,
and the three golden reports do not move.

The single low-priority worker becomes a pool of N threads (setting
laboratory.workers, default 1, at most one less than the processors, shown in
Impostazioni > Sistema). The Laboratory records each unit in the new
tournament_units table (migration 0016, which also creates tournaments for the
next part of the phase): claimed as running, then done with the gzip of its
run. A resumed trial drops its running units, reloads the done ones and runs
only the rest; a run reloaded from storage gives the same report byte for
byte. Plain trials drop their unit outcomes when they finish or fail. The pool
no longer disposes its queue while a thread may still read it.

refs #122

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 13:07:14 +01:00
1 parent e0a438a0b2
commit b564871391
15 files changed
+1233 -115

No files matched your search

+410
View File
@@ -0,0 +1,410 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The units of a trial and the pool of the laboratory (Phase 13, issue #122): the judge works on runs already done, assembled
/// by key, so one thread, four threads and units read back from the database give the same report as the golden ones; a trial
/// stopped halfway runs again only what it had not finished.
/// </summary>
[TestClass]
public sealed class TrialUnitTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12");
private static readonly DateOnly Through = new(2026, 12, 31);
private static readonly TrialUnitKey RunKey = new(TrialUnitKind.Variant, 0, "", 1m);
private static readonly TrialUnitKey LookKey = new(TrialUnitKind.LookAhead, 0, "", 1m);
private sealed record Golden(string Name, TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data, PriorTrials Prior)
{
public string Hash => TrialPlan.Hash(Plan.ToJson());
public DailyTrialEngine Engine() => new(Plan, Family, Data);
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task JudgeOfVariantsGivesTheJsonOfRun()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task FourWorkersGiveTheReportOfOne()
{
using var pool = new LowPriorityPool("anubis-test-four", 4);
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = await TrialRunner.VariantsAsync(golden.Plan, golden.Family, engine, new PooledTrialUnits(pool), null, _none).ConfigureAwait(false);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task ARunReloadedFromItsStoredUnitGivesTheSameReport()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
var reloaded = new TrialRuns(
runs.Variants,
[.. runs.Grid.Select(Again)],
runs.OutsideGrid is null ? null : Again(runs.OutsideGrid),
runs.Costed.ToDictionary(c => c.Key, c => Again(c.Value)),
Again(runs.Benchmark),
TrialUnitOutcomes.Decode(LookKey, TrialUnitOutcomes.Encode(new TrialUnitResult(LookKey, null, runs.LookAhead))).LookAhead!);
Assert.IsTrue(reloaded.Grid.All(r => r.Decisions.Count == 0), "The decisions are not kept: only the look-ahead check reads them.");
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, reloaded, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AStoredUnitIsTheSameBytesWhenWrittenAgain()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: Through.AddDays(-399)));
var run = BacktestEngine.Run(new MovingAverageCross(5, 20), data);
var stored = TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null));
var back = TrialUnitOutcomes.Decode(RunKey, stored).Run!;
CollectionAssert.AreEqual(stored, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, back, null)));
Assert.AreEqual(run.Fees, back.Fees);
Assert.AreEqual(run.FinalEquity, back.FinalEquity);
CollectionAssert.AreEqual(run.Fills.ToList(), back.Fills.ToList());
CollectionAssert.AreEqual(run.Trades.ToList(), back.Trades.ToList());
CollectionAssert.AreEqual(run.Notes.ToList(), back.Notes.ToList());
Assert.IsTrue(stored.Length < 200_000, "The outcome is compressed.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheKeyOfAUnitIsTheSameTextInEveryCulture()
{
var before = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
Assert.AreEqual("variant:3:a=1;kind=0:x1", new TrialUnitKey(TrialUnitKind.Variant, 3, "a=1;kind=0", 1m).Text);
Assert.AreEqual("costed:0:a=1;kind=0:x2", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1;kind=0", 2.00m).Text);
Assert.AreEqual("costed:0:a=1:x1.5", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1", 1.50m).Text);
Assert.AreEqual("outside_grid:0:a=4;kind=1:x1", new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, "a=4;kind=1", 1m).Text);
Assert.AreEqual("benchmark:0::x1", new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m).Text);
Assert.AreEqual("look_ahead", new TrialUnitKey(TrialUnitKind.LookAhead, 0, "a=1", 1m).KindText);
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnOneWorkerThePoolCallsTheEngineInTheOrderOfToday()
{
var (plan, family, data) = SmallCross();
var inline = new List<string>();
var sequential = TrialRunner.Variants(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), inline));
using var pool = new LowPriorityPool("anubis-test-one", 1);
var pooled = new List<string>();
var parallel = await TrialRunner.VariantsAsync(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), pooled), new PooledTrialUnits(pool),
null, _none).ConfigureAwait(false);
Assert.HasCount(4 + 2 + 2, inline);
CollectionAssert.AreEqual(inline, pooled);
StringAssert.StartsWith(inline[^1], "look_ahead ");
Assert.AreEqual("benchmark", inline[^2]);
var inlineUnits = await TrialRunner.VariantsAsync(plan, family, new DailyTrialEngine(plan, family, data), InlineTrialUnits.Instance, null, _none).ConfigureAwait(false);
var hash = TrialPlan.Hash(plan.ToJson());
var one = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), sequential, PriorTrials.None, Now, TimeSpan.Zero).Report;
foreach (var other in new[] { parallel, inlineUnits })
{
var report = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), other, PriorTrials.None, Now, TimeSpan.Zero).Report;
Assert.AreEqual((one with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AUnitThatFailsStopsTheOnesNotYetStartedAndItsErrorComesBack()
{
var (plan, family, data) = SmallCross();
using var pool = new LowPriorityPool("anubis-test-fail", 1);
var calls = new List<string>();
var engine = new RecordingEngine(new DailyTrialEngine(plan, family, data), calls, _ => throw new InvalidOperationException("rotto"));
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => TrialRunner.VariantsAsync(plan, family, engine, new PooledTrialUnits(pool), null, _none))
.ConfigureAwait(false);
Assert.AreEqual("rotto", error.Message, "The error of the unit comes back, not the skip of the others.");
Assert.HasCount(1, calls, "After a failure the units still queued do not run.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ThePoolRunsOnNamedLowPriorityBackgroundThreadsAndFinishesWhatItWasGiven()
{
using var pool = new LowPriorityPool("anubis-test-pool", 2);
using var both = new Barrier(2);
(bool Together, string? Name, ThreadPriority Priority, bool Background) Probe() =>
(both.SignalAndWait(TimeSpan.FromSeconds(30)), Thread.CurrentThread.Name, Thread.CurrentThread.Priority, Thread.CurrentThread.IsBackground);
var seen = await Task.WhenAll(pool.RunAsync(Probe), pool.RunAsync(Probe)).ConfigureAwait(false);
Assert.AreEqual(2, pool.Workers);
Assert.IsTrue(seen.All(s => s.Together), "Two threads run two pieces of work at once.");
CollectionAssert.AreEquivalent(new[] { "anubis-test-pool-1", "anubis-test-pool-2" }, seen.Select(s => s.Name).ToArray());
Assert.IsTrue(seen.All(s => s.Priority == ThreadPriority.BelowNormal && s.Background));
await Assert.ThrowsAsync<ArithmeticException>(() => pool.RunAsync<int>(() => throw new ArithmeticException())).ConfigureAwait(false);
// Work handed over before the pool stops still runs; nothing more is taken; stopping twice is harmless.
using var release = new ManualResetEventSlim();
var slow = pool.RunAsync(() => release.Wait(TimeSpan.FromSeconds(30)));
var queued = pool.RunAsync(() => 7);
var stopping = Task.Run(pool.Dispose);
release.Set();
await stopping.ConfigureAwait(false);
Assert.IsTrue(await slow.ConfigureAwait(false));
Assert.AreEqual(7, await queued.ConfigureAwait(false));
Assert.Throws<InvalidOperationException>(() => pool.RunAsync(() => 1));
pool.Dispose();
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AfterAnInterruptionTheFinishedUnitsAreNotRunAgain()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
var workers = 1;
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers));
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TrialStatuses.Running, (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.Status);
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
var finished = rows.Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
var left = rows.Where(r => r.Status == TrialUnitStatuses.Running).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
Assert.IsNotEmpty(left, "The units claimed and not finished stay running.");
Assert.IsTrue(rows.All(r => r.Status != TrialUnitStatuses.Done || (r.HasOutcome && r.Seconds is >= 0)));
Assert.IsTrue(rows.All(r => r.TournamentId is null));
// The next start plans it again and runs only what was not finished, now on two threads.
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
workers = 2;
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total - finished.Count, second);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(second, CallOf(key), "A finished unit does not run again: " + key);
}
foreach (var key in left)
{
CollectionAssert.Contains(second, CallOf(key), "A unit left running runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
Assert.AreEqual(clock.UtcNow, report.ComputedAt);
// A trial outside a tournament keeps its units as a record, without their outcomes.
var after = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, after);
Assert.IsTrue(after.All(r => r.Status == TrialUnitStatuses.Done && !r.HasOutcome));
CollectionAssert.AreEquivalent(new[] { "variant", "costed", "benchmark", "look_ahead" }, after.Select(r => r.Kind).Distinct().ToArray());
Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors()
{
var workers = LaboratorySettings.Workers;
Assert.AreEqual("laboratory.workers", workers.Key);
Assert.AreEqual("1", workers.Default);
Assert.AreEqual("Operai del Laboratorio", workers.Label);
Assert.AreSame(workers, SettingsStore.Definition(workers.Key));
var max = Math.Max(1, Environment.ProcessorCount - 1);
Assert.AreEqual(max, LaboratorySettings.MaxWorkers);
Assert.IsNull(workers.Check!("1"));
Assert.IsNull(workers.Check(max.ToString(CultureInfo.InvariantCulture)));
foreach (var wrong in new[] { "0", (max + 1).ToString(CultureInfo.InvariantCulture), "", "due", "1.5", "-1", "+2", " 2" })
{
Assert.AreEqual($"Serve un numero intero tra 1 e {max}.", workers.Check(wrong), wrong);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWorkersOfTheLaboratoryAreSetInTheSystemSettings()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Operai del Laboratorio");
StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading");
StringAssert.Contains(page, "Vale dalla prossima prova.");
async Task<string> Save(string value)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LaboratorySettings.Workers.Key, ("ritorno", "/impostazioni#sistema"), ("valore", value));
return ServerHarness.Location(answer);
}
var settings = server.Host.Services!.Settings;
Assert.AreEqual("/impostazioni#sistema", await Save("1"));
Assert.AreEqual(1, await LaboratorySettings.WorkersAsync(settings, _none));
StringAssert.Contains(await Save("0"), "errore=operai");
StringAssert.Contains(await Save((LaboratorySettings.MaxWorkers + 1).ToString(CultureInfo.InvariantCulture)), "errore=operai");
StringAssert.Contains(await Save("tanti"), "errore=operai");
Assert.AreEqual("1", (await settings.GetAsync(LaboratorySettings.Workers.Key, _none)).Value);
StringAssert.Contains(await server.TextAsync("/impostazioni?errore=operai#sistema"), "Gli operai del Laboratorio sono un numero intero da 1 a");
}
private static BacktestRun Again(BacktestRun run) => TrialUnitOutcomes.Decode(RunKey, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null))).Run!;
/// <summary>The call of the recording engine a unit key stands for.</summary>
private static string CallOf(string key)
{
var parts = key.Split(':');
return parts[0] switch
{
"benchmark" => "benchmark",
"look_ahead" => $"look_ahead {parts[2]} {TrialValidation.Default.LookAheadCuts}",
_ => $"run {parts[2]} {parts[3]}",
};
}
private static (TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data) SmallCross()
{
var first = new DateOnly(2024, 1, 1);
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: first));
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
first.AddDays(60), first.AddDays(399), 10_000m, grid), Now).Plan;
return (plan, MovingAverageCrossFamily.Instance, data);
}
/// <summary>The inputs of the three golden reports of <see cref="TrialSeamTests"/>, built the same way.</summary>
private static async Task<IReadOnlyList<Golden>> GoldensAsync()
{
var walk = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03));
var cross = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan;
var folder = TempFolder.Create("golden-units");
try
{
var store = new ResearchStore(folder);
var seed = 21u;
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" })
{
var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
(decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList();
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false);
}
var trend = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow,
CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan;
var data = await Laboratory.LoadResearchAsync(folder, trend.Data, _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(StrategyNames.CryptoTrend)!;
return
[
new("sma_cross", cross, MovingAverageCrossFamily.Instance, walk, new PriorTrials(2, 18, [0.4, 0.9, -0.1])),
new("crypto_trend", trend, family, data, PriorTrials.None),
new("crypto_trend_judged", trend with { Judged = "coin_vol=12;max_stop=15" }, family, data, PriorTrials.None),
];
}
finally
{
TempFolder.Delete(folder);
}
}
private static void Same(string name, BacktestReport report) =>
Assert.AreEqual(Fixture.Text(Path.Combine("golden", name + ".report.json")), (report with { Seconds = 0 }).ToJson(), $"The report of {name} changed.");
/// <summary>An engine in between: it records every call (safe from several threads) and may act on the n-th one.</summary>
private sealed class RecordingEngine(ITrialEngine inner, List<string> calls, Action<int>? onCall = null) : ITrialEngine
{
private int _count;
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
Record(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark()
{
Record("benchmark");
return inner.Benchmark();
}
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
Record(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
return inner.LookAhead(parameters, cuts);
}
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
private void Record(string call)
{
lock (calls)
{
calls.Add(call);
}
onCall?.Invoke(Interlocked.Increment(ref _count));
}
}
}