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

@@ -655,7 +655,7 @@
<input id="lab-workers" name="valore" inputmode="numeric" autocomplete="off" value="@_labWorkers.Value" readonly="@(_labWorkers.ReadOnly || Shell.IsDemo)" />
<button class="btn btn-small" type="submit">Salva</button>
</form>
<p class="hint">Quante prove del Laboratorio girano insieme. Alzalo solo dopo averne misurato l'effetto: il Laboratorio non deve togliere tempo al trading. Vale dalla prossima prova. Su questo computer va da 1 a @LaboratorySettings.MaxWorkers.</p>
<p class="hint">Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta. Alzalo solo dopo averne misurato l'effetto: il Laboratorio non deve togliere tempo al trading. Vale dalla prossima prova. Su questo computer va da 1 a @LaboratorySettings.MaxWorkers.</p>
<h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
+13 -6
View File
@@ -297,13 +297,19 @@ public sealed partial class Laboratory : IDisposable
}
/// <summary>
/// One trial: load its data, run its units on the pool (those done before a restart come back from the database), judge on
/// the pool, write the report. A failure is recorded, not thrown.
/// One trial: load its data, run its units on the pool (those done before a restart on the same data, engine and build come
/// back from the database), judge on the pool, write the report. A failure is recorded, not thrown. A trial of a tournament
/// already finished that comes back to the queue brings its tournament to the judge, when it is not judged yet.
/// </summary>
public async Task ProcessAsync(Guid id, CancellationToken cancellationToken)
{
if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false))
{
if (await Trials.FinishedTournamentAsync(id, cancellationToken).ConfigureAwait(false) is { } waiting)
{
await JudgeFromQueueAsync(waiting, id, cancellationToken).ConfigureAwait(false);
}
return;
}
@@ -332,11 +338,12 @@ public sealed partial class Laboratory : IDisposable
var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false);
var now = _clock.UtcNow;
var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false)));
var done = await Units.ResumeAsync(id, cancellationToken).ConfigureAwait(false);
var engine = EngineFor(trial.Plan, family, data);
var fingerprint = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false);
var done = await Units.ResumeAsync(id, fingerprint, cancellationToken).ConfigureAwait(false);
var watch = Stopwatch.StartNew();
var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done), text => _progress[id] = text,
cancellationToken).ConfigureAwait(false);
var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done, fingerprint),
text => _progress[id] = text, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
_progress[id] = "convalide";
var elapsed = watch.Elapsed;
@@ -367,7 +374,7 @@ public sealed partial class Laboratory : IDisposable
// The last trial of a tournament to finish brings it to its judge.
if (trial?.TournamentId is { } judged)
{
await JudgeTournamentAsync(judged, cancellationToken).ConfigureAwait(false);
await JudgeFromQueueAsync(judged, id, cancellationToken).ConfigureAwait(false);
}
}
+89 -21
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Text.Json;
using Anubis.Core;
using Anubis.Strategies;
using Microsoft.Extensions.Logging;
@@ -46,33 +47,59 @@ public sealed partial class Laboratory
return;
}
// An error that escapes the judge (the database out of reach while recording a failure) does not stop the queue: the
// tournament stays to judge, at the next start or when one of its trials comes back to the queue.
foreach (var id in ids)
{
await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false);
try
{
await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
LogJudgeDeferred(_logger, id, ex);
}
}
}
// The judge called from the queue, after trial `trial` of the tournament: an error that escapes it does not stop the queue.
// As an error of the queue itself, the trial comes back after RetryDelay and brings the tournament to its judge again.
private async Task JudgeFromQueueAsync(Guid tournament, Guid trial, CancellationToken cancellationToken)
{
try
{
await JudgeTournamentAsync(tournament, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
LogQueueFailed(_logger, ex);
await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false);
_queue.Writer.TryWrite(trial);
}
}
/// <summary>
/// Judges a tournament whose trials are all finished; nothing when one is still to run or the tournament is finished. A
/// failure is recorded, not thrown; a stop leaves it being judged, and the next start goes on from the units done.
/// failure is recorded, not thrown, a plan that can no longer be read included; a stop leaves it being judged, and the next
/// start goes on from the units done. Only an error while recording the failure (the database out of reach) comes out.
/// </summary>
public async Task JudgeTournamentAsync(Guid id, CancellationToken cancellationToken)
{
var tournament = await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false);
if (tournament is null || tournament.IsFinished)
{
return;
}
var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false);
if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false))
{
return;
}
_progress[id] = "scelta dei finalisti";
try
{
var tournament = await ReadTournamentAsync(id, cancellationToken).ConfigureAwait(false);
if (tournament is null || tournament.IsFinished)
{
return;
}
var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false);
if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false))
{
return;
}
_progress[id] = "scelta dei finalisti";
var watch = Stopwatch.StartNew();
if (!tournament.PlanIntact)
{
@@ -127,12 +154,34 @@ public sealed partial class Laboratory
}
}
// A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept.
// The tournament with its plan; a plan text that no longer reads (changed by hand, or by a version that cannot read it) fails it.
private async Task<Tournament?> ReadTournamentAsync(Guid id, CancellationToken cancellationToken)
{
try
{
return await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
throw new InvalidOperationException("Il piano registrato del campionato non si può più leggere: il campionato non si giudica.", ex);
}
}
// A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept. Its trial
// must be the one the plan of the tournament wrote: plan intact, and the same rule, grid, data, capital and costs.
private async Task<ContenderOutcome> ContenderAsync(TournamentPlan plan, TournamentContender contender, Trial trial, LowPriorityPool pool, CancellationToken cancellationToken)
{
if (!trial.PlanIntact)
{
throw new InvalidOperationException("Il piano registrato della prova di «" + contender.Label + "» non corrisponde più alla sua impronta: il campionato non si giudica.");
}
var data = trial.Plan.Data;
if (trial.Strategy != contender.Strategy || trial.StrategyVersion != contender.StrategyVersion || data.To != plan.SearchTo || data.From != contender.Data.From
|| !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || trial.Variants != contender.Variants)
|| !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || data.Source != contender.Data.Source
|| data.FullHistory != contender.Data.FullHistory || trial.Variants != contender.Variants || !SameGrid(trial.Plan.Grid, contender.Grid)
|| trial.Plan.InitialCapital != plan.InitialCapital || trial.Plan.Slippage != plan.Slippage
|| trial.Plan.ReferenceShare != StrategyPipeline.ResearchShare(contender.Strategy))
{
throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano.");
}
@@ -165,13 +214,21 @@ public sealed partial class Laboratory
var chosenText = contender.Chosen.Parameters;
var chosen = ParameterGrid.Of(family, trial.Plan.Grid).FirstOrDefault(v => v.ToString() == chosenText)?.Parameters
?? throw new InvalidOperationException("La variante scelta di «" + contender.Contender.Label + "» non è nella sua griglia.");
var done = await Units.ResumeAsync(trial.Id, cancellationToken).ConfigureAwait(false);
var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done);
// Every finalist draws the signs of a day from the same first day, so a day has one sign across the whole field.
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var engine = EngineFor(trial.Plan, family, await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false));
var centred = engine.LongOnly;
// The repetitions of the control done on other search data, by another engine or build run again. The runs on the final
// tract done by another engine or build too; on other data of the tract, only when it is read again for a run not done.
var search = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false);
var controlKind = TrialUnitKey.TextOf(TrialUnitKind.Control);
var holdoutKind = TrialUnitKey.TextOf(TrialUnitKind.Holdout);
var done = await Units.ResumeAsync(trial.Id, (kind, stored) =>
kind == controlKind ? stored == search
: kind != holdoutKind || (stored is not null && stored.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)), cancellationToken).ConfigureAwait(false);
var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done, search);
List<TrialUnitKey> control = [.. Enumerable.Range(0, plan.Control.Repetitions).Select(k => new TrialUnitKey(TrialUnitKind.Control, k, chosenText, 1m))];
string? unavailable = null;
if (control.Any(k => !done.ContainsKey(k.Text)))
@@ -205,11 +262,16 @@ public sealed partial class Laboratory
List<TrialUnitKey> holdout = [.. HoldoutCosts.Select(m => new TrialUnitKey(TrialUnitKind.Holdout, 0, chosenText, m))];
ITrialEngine? tract = null;
var finals = units;
if (holdout.Any(k => !done.ContainsKey(k.Text)))
{
var data = trial.Plan.Data with { From = plan.HoldoutFrom, To = contender.Contender.Data.To };
var holdoutPlan = trial.Plan with { Data = data };
tract = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false));
var opened = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false));
tract = opened;
var read = await pool.RunAsync(() => TrialUnitStore.Fingerprint(opened)).ConfigureAwait(false);
var again = await Units.ResumeAsync(trial.Id, (kind, stored) => kind != holdoutKind || stored == read, cancellationToken).ConfigureAwait(false);
finals = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, again, read);
}
TrialUnitResult Final(TrialUnitKey key)
@@ -218,10 +280,13 @@ public sealed partial class Laboratory
return new TrialUnitResult(key, (tract ?? throw new InvalidOperationException("The final tract was not read.")).Run(chosen, key.CostMultiplier), null);
}
var runs = await units.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false);
var runs = await finals.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false);
return new FinalistOutcome(contender.Contender.Label, centred, replicas, unavailable, runs.ToDictionary(r => r.Key.CostMultiplier, r => r.Run!));
}
private static bool SameGrid(IReadOnlyDictionary<string, IReadOnlyList<decimal>> a, IReadOnlyDictionary<string, IReadOnlyList<decimal>> b) =>
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var values) && p.Value.SequenceEqual(values));
private IStrategyFamily FamilyOf(TournamentContender contender)
{
var family = Families(contender.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + contender.Strategy);
@@ -234,4 +299,7 @@ public sealed partial class Laboratory
[LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} failed")]
private static partial void LogTournamentFailed(ILogger logger, Guid id, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} could not be judged now: it is judged at the next start or when one of its trials comes back to the queue")]
private static partial void LogJudgeDeferred(ILogger logger, Guid id, Exception exception);
}
+77 -26
View File
@@ -44,7 +44,10 @@ public enum TrialUnitKind
public sealed record TrialUnitKey(TrialUnitKind Kind, int Index, string Parameters, decimal CostMultiplier)
{
/// <summary>The kind in snake case, as the database keeps it (<c>outside_grid</c>).</summary>
public string KindText => JsonNamingPolicy.SnakeCaseLower.ConvertName(Kind.ToString());
public string KindText => TextOf(Kind);
/// <summary>A kind in snake case, as the database keeps it.</summary>
public static string TextOf(TrialUnitKind kind) => JsonNamingPolicy.SnakeCaseLower.ConvertName(kind.ToString());
public string Text => string.Create(CultureInfo.InvariantCulture,
$"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}");
@@ -130,11 +133,13 @@ internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits
}
/// <summary>
/// Units on a pool that records each one in <c>tournament_units</c>: a claim before it runs, its outcome once done. The units
/// already done (<paramref name="done"/>, from <see cref="TrialUnitStore.ResumeAsync"/>) come back from their outcome and do
/// not run again.
/// Units on a pool that records each one in <c>tournament_units</c>: a claim before it runs, its outcome once done, both with
/// <paramref name="fingerprint"/>, what they are computed on (<see cref="TrialUnitStore.Fingerprint"/>). The units already
/// done (<paramref name="done"/>, from <see cref="TrialUnitStore.ResumeAsync(Guid, string, CancellationToken)"/>, on the same
/// fingerprint) come back from their outcome and do not run again.
/// </summary>
internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary<string, byte[]> done) : ITrialUnits
internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary<string, byte[]> done, string fingerprint)
: ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
@@ -143,7 +148,7 @@ internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore stor
var missing = keys.Where(k => !done.ContainsKey(k.Text)).ToList();
if (missing.Count > 0)
{
await store.ClaimAsync(trialId, tournamentId, missing, cancellationToken).ConfigureAwait(false);
await store.ClaimAsync(trialId, tournamentId, missing, fingerprint, cancellationToken).ConfigureAwait(false);
}
using var failed = new CancellationTokenSource();
@@ -155,7 +160,7 @@ internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore stor
var unit = PooledTrialUnits.Guarded(key, execute, failed);
return (unit, TrialUnitOutcomes.Encode(unit), watch.Elapsed.TotalSeconds);
}).ConfigureAwait(false);
await store.DoneAsync(trialId, key, outcome, seconds, cancellationToken).ConfigureAwait(false);
await store.DoneAsync(trialId, key, outcome, seconds, fingerprint, cancellationToken).ConfigureAwait(false);
return result;
}
@@ -354,34 +359,77 @@ public static class TrialUnitStatuses
}
/// <summary>A unit as the database keeps it, without its outcome.</summary>
public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId);
public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId)
{
/// <summary>What the unit was computed on (<see cref="TrialUnitStore.Fingerprint"/>).</summary>
public string? Fingerprint { get; init; }
}
/// <summary>
/// The units of the trials in <c>tournament_units</c> (Phase 13): one row per engine execution, claimed before it runs and
/// done with its outcome, so a trial stopped halfway runs again only what it had not finished. A plain trial drops its
/// outcomes when it ends (<see cref="TrialStore.FinishAsync"/>, <see cref="TrialStore.FailAsync"/>); a unit never counts as a
/// trial.
/// done with its outcome, so a trial stopped halfway runs again only what it had not finished. Every row keeps what it was
/// computed on (<see cref="Fingerprint"/>): a unit done on other data, by another engine or another build of Anubis is not
/// reused. A plain trial drops its outcomes when it ends (<see cref="TrialStore.FinishAsync"/>, <see cref="TrialStore.FailAsync"/>);
/// a unit never counts as a trial.
/// </summary>
public sealed class TrialUnitStore(Database db, IClock clock)
{
/// <summary>
/// A trial that starts, or starts again after a restart: the units left running (their work was lost with the process) and
/// those without an outcome are dropped; the outcomes of the units done are returned by key.
/// The engine and the code that compute a unit, the second half of <see cref="Fingerprint"/>: the version of the engine and
/// the identity of this build of Anubis, which changes with any change to its code.
/// </summary>
public async Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, CancellationToken cancellationToken)
public static string Build { get; } = "|" + BacktestEngine.Version + "|" + typeof(BacktestEngine).Assembly.ManifestModule.ModuleVersionId.ToString("N");
/// <summary>What the units of <paramref name="engine"/> are computed on: the fingerprint of the data it read, then <see cref="Build"/>.</summary>
public static string Fingerprint(ITrialEngine engine)
{
ArgumentNullException.ThrowIfNull(engine);
return engine.Fingerprint() + Build;
}
/// <summary>
/// A trial that starts, or starts again after a restart: the units left running (their work was lost with the process),
/// those without an outcome and those done on another <paramref name="fingerprint"/> are dropped, so they run again; the
/// outcomes of the units done on the same one are returned by key.
/// </summary>
public Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, string fingerprint, CancellationToken cancellationToken) =>
ResumeAsync(trialId, (_, stored) => stored == fingerprint, cancellationToken);
/// <summary>
/// The same, when the units of a trial were computed on different inputs (the judge of a tournament): a unit done is kept
/// when <paramref name="current"/> says so for its kind (as the database keeps it) and its stored fingerprint.
/// </summary>
public async Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, Func<string, string?, bool> current, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(current);
var rows = await db.WriteAsync(async s =>
{
await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND (status <> @d OR outcome IS NULL)", cancellationToken,
("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
return await s.QueryAsync("SELECT unit_key, outcome FROM tournament_units WHERE trial_id = @t AND status = @d",
r => (Key: r.Text("unit_key"), Outcome: r.Bytes("outcome")), ("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
var done = await s.QueryAsync("SELECT unit_key, kind, fingerprint, outcome FROM tournament_units WHERE trial_id = @t AND status = @d",
r => (Key: r.Text("unit_key"), Kind: r.Text("kind"), Fingerprint: r.TextOrNull("fingerprint"), Outcome: r.Bytes("outcome")),
("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
var kept = new List<(string Key, byte[] Outcome)>(done.Count);
foreach (var row in done)
{
if (current(row.Kind, row.Fingerprint))
{
kept.Add((row.Key, row.Outcome));
}
else
{
await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND unit_key = @k", cancellationToken, ("t", trialId), ("k", row.Key))
.ConfigureAwait(false);
}
}
return kept;
}, cancellationToken).ConfigureAwait(false);
return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal);
}
/// <summary>Claims the units about to run, in one transaction. A unit already claimed stays as it is.</summary>
public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList<TrialUnitKey> keys, CancellationToken cancellationToken)
/// <summary>Claims the units about to run, in one transaction, with what they are computed on. A unit already claimed stays as it is.</summary>
public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList<TrialUnitKey> keys, string fingerprint, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
return db.WriteAsync(async s =>
@@ -389,21 +437,21 @@ public sealed class TrialUnitStore(Database db, IClock clock)
foreach (var key in keys)
{
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @now) " +
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @f, @now) " +
"ON CONFLICT (trial_id, unit_key) DO NOTHING",
cancellationToken, ("id", Ids.NewId(clock)), ("t", trialId), ("tour", tournamentId), ("k", key.Text), ("kind", key.KindText),
("r", TrialUnitStatuses.Running), ("now", clock.UtcNow)).ConfigureAwait(false);
("r", TrialUnitStatuses.Running), ("f", fingerprint), ("now", clock.UtcNow)).ConfigureAwait(false);
}
}, cancellationToken);
}
/// <summary>A unit done: its outcome and the seconds it took.</summary>
public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, CancellationToken cancellationToken)
/// <summary>A unit done: its outcome, the seconds it took and what it was computed on.</summary>
public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, string fingerprint, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(key);
return db.WriteAsync(s => s.ExecuteAsync(
"UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r",
cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text),
"UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, fingerprint = @f, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r",
cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("f", fingerprint), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text),
("r", TrialUnitStatuses.Running)), cancellationToken);
}
@@ -418,8 +466,11 @@ public sealed class TrialUnitStore(Database db, IClock clock)
/// <summary>The units of a trial, in the order they were claimed.</summary>
public async Task<IReadOnlyList<TrialUnitRow>> ListAsync(Guid trialId, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT unit_key, kind, status, outcome, seconds, tournament_id FROM tournament_units WHERE trial_id = @t ORDER BY id",
"SELECT unit_key, kind, status, outcome, seconds, tournament_id, fingerprint FROM tournament_units WHERE trial_id = @t ORDER BY id",
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")),
r.IdOrNull("tournament_id"))
{
Fingerprint = r.TextOrNull("fingerprint"),
},
("t", trialId)), cancellationToken).ConfigureAwait(false);
}
+5
View File
@@ -238,6 +238,11 @@ public sealed class TrialStore(Database db, IClock clock)
await db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @r, started_at = @now WHERE id = @id AND status = @p",
cancellationToken, ("r", TrialStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned)), cancellationToken).ConfigureAwait(false) == 1;
/// <summary>The tournament of a finished trial; null when the trial is not finished or belongs to none. The plan is not read.</summary>
public Task<Guid?> FinishedTournamentAsync(Guid id, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT tournament_id FROM backtest_trials WHERE id = @id AND status IN (@d, @f)", r => r.IdOrNull("tournament_id"),
("id", id), ("d", TrialStatuses.Done), ("f", TrialStatuses.Failed)), cancellationToken);
/// <summary>A trial done, with its report. A trial outside a tournament drops the outcomes of its units: the rows stay as a record.</summary>
public Task FinishAsync(Guid id, string fingerprint, TrialSummary summary, string reportJson, bool passed, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
@@ -19,7 +19,8 @@ CREATE INDEX tournaments_status ON tournaments (status);
-- One engine execution of a trial of the laboratory (a variant, a costed run, the benchmark, the look-ahead check), so a
-- trial stopped halfway runs again only what it had not finished. The outcome is the gzip of its JSON; a plain trial
-- (tournament_id NULL) drops it when it ends, the row stays as a record.
-- (tournament_id NULL) drops it when it ends, the row stays as a record. The fingerprint is what the unit was computed on
-- (the data, the engine version, the build): a unit done on other inputs is not reused.
CREATE TABLE tournament_units (
id {uuid} PRIMARY KEY,
trial_id {uuid} NOT NULL REFERENCES backtest_trials (id),
@@ -27,6 +28,7 @@ CREATE TABLE tournament_units (
unit_key TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL,
fingerprint TEXT,
outcome {bytes},
seconds {float},
created_at {timestamp} NOT NULL,