Keep the laboratory going and resumed units consistent when judging tournaments

An error while judging a tournament (a plan that no longer reads, the database out
of reach) could stop the whole laboratory queue or leave the tournament unjudged
until a restart. The judge now reads inside its failure handling, so an unreadable
plan fails the tournament with an Italian reason; every call of the judge is
guarded; and a finished contender trial that comes back to the queue brings its
tournament to the judge.

Resumed trials and judges reused finished units without checking they were
computed on the same inputs, so a restart after new bars or an image update mixed
runs of two data sets or two engines. Every unit now records its fingerprint (the
data, the engine version, the build) and only units on the same inputs are reused;
the runs on the final tract are checked on the build and, when the tract is read,
on its data.

The judge also checks that each contender trial is the one the tournament plan
wrote: plan hash, grid, data source, capital, slippage and reference share.

The settings hint now says the workers are calculations of one trial; trials still
run one at a time.

refs #122, refs #123

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 14:20:43 +01:00
1 parent 8aafa5ad32
commit 9ae1e955a4
10 files changed
+471 -57

No files matched your search

+214
View File
@@ -2,7 +2,10 @@ using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
@@ -350,6 +353,193 @@ public sealed class TournamentTests
}
}
/// <summary>
/// The repetitions of the control done before a stop by another build (or on other data) are not reused: the judge started
/// again runs every repetition, so the control of a finalist is never a mix of two engines.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingRunsAgainTheControlUnitsOfAnotherBuild()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The judge stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), [], replicas, p.Data.Symbols[0], null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.IsGreaterThanOrEqualTo(5, DoneControls(test, tournament.Id));
// They were computed by another build.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournament_units SET fingerprint = @f WHERE tournament_id = @t AND kind = @k", _none,
("f", "altra|2|build"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(2 * plan.Control.Repetitions, controls, "Every repetition runs again.");
Assert.HasCount(2 * plan.Control.Repetitions, controls.Distinct().ToList());
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList());
var fingerprints = await test.Db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT fingerprint FROM tournament_units WHERE tournament_id = @t AND kind = @k",
r => r.Text("fingerprint"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
Assert.HasCount(2, fingerprints, "One fingerprint for the search data of each finalist.");
Assert.IsTrue(fingerprints.All(f => f.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)));
}
/// <summary>
/// The plan of a tournament that no longer reads (changed by hand, or after an update that cannot read it) fails the
/// tournament with a reason in Italian, when its last contender finishes and when it is found being judged at a start; the
/// laboratory goes on with the rest of the queue.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnUnreadableTournamentPlanFailsTheTournamentAndTheQueueGoesOn()
{
const string Unreadable = "Il piano registrato del campionato non si può più leggere: il campionato non si giudica.";
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var broken = await lab.PlanTournamentAsync(request with { Name = "Illeggibile" }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan = @p WHERE id = @id", _none, ("p", new DbJson("[1]")), ("id", broken.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, broken.Id).ConfigureAwait(false);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
// Found being judged at a start: it fails again, and the trials of the queue run and are judged.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @j, error = NULL, finished_at = NULL WHERE id = @id", _none,
("j", TournamentStatuses.Judging), ("id", broken.Id)), _none).ConfigureAwait(false);
var good = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!.IsFinished && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var judged = (await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, judged.Status, judged.Error);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
}
/// <summary>
/// The database refuses every change of the tournament while its last contender finishes, so neither the judge nor the
/// record of its failure can write: the queue goes on, and the trial that comes back to it after the pause brings the
/// tournament to its judge, though the trial itself is finished.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ARequeuedFinishedContenderStillReachesTheJudge()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false);
await RefuseTournamentChangesAsync(test, true).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && clock.Waiting == 0 && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
Assert.AreEqual(1, clock.Waiting, "The queue waits before trying again.");
Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(trials[1].Id, _none).ConfigureAwait(false))!.Status);
Assert.AreEqual(TournamentStatuses.Running, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
// The database is back: after the pause the finished trial comes back to the queue and the tournament is judged.
await RefuseTournamentChangesAsync(test, false).ConfigureAwait(false);
clock.Advance(Laboratory.RetryDelay);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
}
/// <summary>
/// The judge checks that every contender trial is the one the plan of the tournament wrote: a trial plan changed by hand
/// (its hash no longer matches) or rewritten with its hash on another capital, grid, slippage, source or reference share
/// fails the tournament.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AContenderTrialWhosePlanChangedFailsTheTournament()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var tampered = await lab.PlanTournamentAsync(request with { Name = "Impronta" }, _none).ConfigureAwait(false);
var last = (await lab.Trials.OfTournamentAsync(tampered.Id, _none).ConfigureAwait(false))[1];
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", last.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
Assert.AreEqual("Il piano registrato della prova di «b» non corrisponde più alla sua impronta: il campionato non si giudica.", refused.Error);
(string Name, Func<TrialPlan, TrialPlan> Change)[] changes =
[
("Capitale", p => p with { InitialCapital = 20_000m }),
("Griglia", p => p with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["entry"] = [1m], ["lookback"] = [30m] } }),
("Slittamento", p => p with { Slippage = new SlippageTable(9m, 9m, 25m) }),
("Origine", p => p with { Data = p.Data with { Source = TrialSources.Research } }),
("Quota", p => p with { ReferenceShare = 0.5m }),
];
foreach (var (name, change) in changes)
{
var tournament = await lab.PlanTournamentAsync(request with { Name = name }, _none).ConfigureAwait(false);
var trial = (await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false))[1];
var json = change(trial.Plan).ToJson();
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan = @p, plan_hash = @h WHERE id = @id", _none,
("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("id", trial.Id)), _none).ConfigureAwait(false);
Assert.IsTrue((await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.PlanIntact, name);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var failed = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, failed.Status, name);
Assert.AreEqual("Le prove del campionato non corrispondono al suo piano.", failed.Error, name);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFinalistsAreTheBestOfEachGroupAndMarketAndAtMostEight()
@@ -519,6 +709,30 @@ public sealed class TournamentTests
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), r.IdOrNull("tournament_id")),
("t", tournament)), _none).ConfigureAwait(false);
/// <summary>State and error of a tournament, read without its plan.</summary>
private static Task<(string Status, string? Error)> StateAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT status, error FROM tournaments WHERE id = @id", r => (r.Text("status"), r.TextOrNull("error")), ("id", id)));
/// <summary>Makes the database refuse, or accept again, every change of a row of the tournaments: a trigger on both engines.</summary>
private static Task RefuseTournamentChangesAsync(TestDb test, bool refuse) => test.Db.WriteAsync(async s =>
{
string[] statements = (test.Db.Engine, refuse) switch
{
(DbEngine.Sqlite, true) => ["CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments BEGIN SELECT RAISE(ABORT, 'database non raggiungibile'); END"],
(DbEngine.Sqlite, false) => ["DROP TRIGGER refuse_tournaments"],
(_, true) =>
[
"CREATE FUNCTION refuse_tournaments() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'database non raggiungibile'; END $$",
"CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments FOR EACH ROW EXECUTE FUNCTION refuse_tournaments()",
],
(_, false) => ["DROP TRIGGER refuse_tournaments ON tournaments", "DROP FUNCTION refuse_tournaments()"],
};
foreach (var sql in statements)
{
await s.ExecuteAsync(sql, _none).ConfigureAwait(false);
}
}, _none);
private static Task<(string Plan, string Hash)> RawPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM tournaments WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));