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

+1 -1
View File
@@ -437,7 +437,7 @@ internal sealed partial class AnubisHost(
}
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger, ct => LaboratorySettings.WorkersAsync(settings, ct));
if (_lab is { } laboratory && _trading is { } running && _market is { } market)
{
async Task<bool> HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet;
@@ -4,6 +4,7 @@
@inject ShellData Shell
@inject SecondFactorDrafts Drafts
@inject Anubis.Core.IClock Clock
@using Anubis.Backtest
@using Anubis.Data
@using Anubis.Trading
@@ -646,6 +647,16 @@
</dl>
<p class="hint">Motore e connessione del database si cambiano solo nella configurazione del container. Per passare a un altro database c'è l'esportazione e l'importazione: il manuale dice come.</p>
<h3>Laboratorio</h3>
<form method="post" action="/azioni/impostazioni/@LaboratorySettings.Workers.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#sistema" />
<label for="lab-workers">@LaboratorySettings.Workers.Label</label>
<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>
<h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
@@ -722,6 +733,7 @@
private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
private SettingValue _labWorkers = new(LaboratorySettings.Workers.Key, LaboratorySettings.Workers.Default, false, null);
private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft;
private string? _draftUri;
@@ -784,6 +796,7 @@
_telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
_heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
_telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
_labWorkers = await services.Settings.GetAsync(LaboratorySettings.Workers.Key, ct);
_queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
@@ -818,6 +831,7 @@
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
"impostazione" => "Questa impostazione non si può cambiare così.",
"operai" => $"Gli operai del Laboratorio sono un numero intero da 1 a {LaboratorySettings.MaxWorkers}.",
"riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».",
"bot" => "Comando non ammesso nello stato attuale del bot.",
"motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.",
+6 -1
View File
@@ -274,7 +274,7 @@ internal static partial class Forms
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
var rules = key == Anubis.News.ExternalRules.Setting.Key;
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key &&
!news && !model && !rules)
key != Anubis.Backtest.LaboratorySettings.Workers.Key && !news && !model && !rules)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
@@ -324,6 +324,11 @@ internal static partial class Forms
return Results.Redirect(With(back, "errore", refusal));
}
if (key == Anubis.Backtest.LaboratorySettings.Workers.Key && Anubis.Backtest.LaboratorySettings.Workers.Check!(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "operai"));
}
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "riunioni"));
+69 -59
View File
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Channels;
using Anubis.Core;
@@ -41,9 +42,11 @@ public static class TrialRequestErrors
}
/// <summary>
/// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time on a
/// dedicated thread with low priority, so trading and the interface never wait for a backtest, and writes the report
/// back. Only the asynchronous side touches the database. After a restart, trials left halfway start again.
/// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time, and writes
/// the report back. The engine executions of a trial (its units) run on a pool of low-priority threads, one by default
/// (<see cref="LaboratorySettings.Workers"/>, read at the start of every trial), so trading and the interface never wait for a
/// backtest. Each unit is recorded in the database when it is done: after a restart a trial left halfway starts again and
/// runs only the units it had not finished. Only the asynchronous side touches the database.
/// </summary>
public sealed partial class Laboratory : IDisposable
{
@@ -60,19 +63,32 @@ public sealed partial class Laboratory : IDisposable
private readonly ILogger _logger;
private readonly Channel<Guid> _queue = Channel.CreateUnbounded<Guid>(new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary<Guid, string> _progress = new();
private readonly LowPriorityWorker _worker = new("anubis-laboratory");
private readonly Func<CancellationToken, Task<int>> _workers;
private readonly Lock _poolGate = new();
private LowPriorityPool _pool = new(PoolName, 1);
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null)
/// <param name="workers">How many threads the next trial gets (<see cref="LaboratorySettings.WorkersAsync"/>); one when null.</param>
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null, Func<CancellationToken, Task<int>>? workers = null)
{
_db = db;
_clock = clock;
_researchRoot = researchRoot;
_logger = logger ?? NullLogger.Instance;
_workers = workers ?? (_ => Task.FromResult(1));
Trials = new TrialStore(db, clock);
Units = new TrialUnitStore(db, clock);
}
private const string PoolName = "anubis-laboratory";
public TrialStore Trials { get; }
/// <summary>The units of the trials: one row per engine execution.</summary>
public TrialUnitStore Units { get; }
/// <summary>The engine of a trial: the daily one. Tests put one in between to count or stop the executions.</summary>
internal Func<TrialPlan, IStrategyFamily, BacktestDataset, ITrialEngine> EngineFor { get; set; } = (plan, family, data) => new DailyTrialEngine(plan, family, data);
/// <summary>Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did.</summary>
public Func<CancellationToken, Task>? ReviewTrialEnded { get; set; }
@@ -86,8 +102,35 @@ public sealed partial class Laboratory : IDisposable
}
}
/// <summary>Heavy work on the thread of the trials.</summary>
public Task<T> ComputeAsync<T>(Func<T> work) => _worker.RunAsync(work);
/// <summary>Heavy work on the threads of the trials.</summary>
public Task<T> ComputeAsync<T>(Func<T> work)
{
lock (_poolGate)
{
return _pool.RunAsync(work);
}
}
/// <summary>The pool with <paramref name="workers"/> threads: the one in use, or a new one when the number changed.</summary>
private LowPriorityPool PoolOf(int workers)
{
LowPriorityPool? old = null;
LowPriorityPool pool;
lock (_poolGate)
{
if (_pool.Workers != workers)
{
old = _pool;
_pool = new LowPriorityPool(PoolName, workers);
}
pool = _pool;
}
// The old threads finish what they were given (heavy work of a review, at most) and stop.
old?.Dispose();
return pool;
}
/// <summary>What the running trial is doing, in words; null when it is not running here.</summary>
public string? Progress(Guid id) => _progress.GetValueOrDefault(id);
@@ -236,7 +279,10 @@ public sealed partial class Laboratory : IDisposable
}
}
/// <summary>One trial: load its data, compute on the worker thread, write the report. A failure is recorded, not thrown.</summary>
/// <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.
/// </summary>
public async Task ProcessAsync(Guid id, CancellationToken cancellationToken)
{
if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false))
@@ -263,8 +309,17 @@ public sealed partial class Laboratory : IDisposable
var data = await LoadAsync(_db, _clock, _researchRoot, trial.Plan.Data, cancellationToken).ConfigureAwait(false);
var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false);
var now = _clock.UtcNow;
var (report, summary) = await _worker.RunAsync(
() => TrialRunner.Run(id, trial.Plan, trial.PlanHash, family, data, prior, now, text => _progress[id] = text, cancellationToken)).ConfigureAwait(false);
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 watch = Stopwatch.StartNew();
var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, null, done), text => _progress[id] = text,
cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
_progress[id] = "convalide";
var elapsed = watch.Elapsed;
var (report, summary) = await pool.RunAsync(
() => TrialRunner.Judge(id, trial.Plan, trial.PlanHash, family, engine, runs, prior, now, elapsed)).ConfigureAwait(false);
await Trials.FinishAsync(id, report.DataFingerprint, summary, report.ToJson(), report.Passed, cancellationToken).ConfigureAwait(false);
LogFinished(_logger, id, trial.Strategy, report.Passed);
}
@@ -379,7 +434,10 @@ public sealed partial class Laboratory : IDisposable
public void Dispose()
{
_queue.Writer.TryComplete();
_worker.Dispose();
lock (_poolGate)
{
_pool.Dispose();
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")]
@@ -391,51 +449,3 @@ public sealed partial class Laboratory : IDisposable
[LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")]
private static partial void LogFailed(ILogger logger, Guid id, Exception exception);
}
/// <summary>
/// One thread with low priority that runs heavy work in order. Its callers await the result on their own side: the
/// thread never touches the database.
/// </summary>
internal sealed class LowPriorityWorker : IDisposable
{
private readonly BlockingCollection<Action> _work = [];
private readonly Thread _thread;
public LowPriorityWorker(string name)
{
_thread = new Thread(Loop) { IsBackground = true, Name = name, Priority = ThreadPriority.BelowNormal };
_thread.Start();
}
public Task<T> RunAsync<T>(Func<T> work)
{
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
public void Dispose()
{
_work.CompleteAdding();
_thread.Join(TimeSpan.FromSeconds(10));
_work.Dispose();
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Globalization;
using Anubis.Core;
namespace Anubis.Backtest;
/// <summary>
/// The settings of the laboratory (Phase 13): how many threads run the units of a trial together. One by default; at most
/// one less than the processors, so trading always has one, and never fewer than one (a container with a single processor).
/// </summary>
public static class LaboratorySettings
{
public static readonly SettingDefinition Workers = new("laboratory.workers", "Operai del Laboratorio", "1", Check: Whole);
public static readonly IReadOnlyList<SettingDefinition> All = [Workers];
/// <summary>The most threads this computer allows, read when asked: the processors can change with the container.</summary>
public static int MaxWorkers => Math.Max(1, Environment.ProcessorCount - 1);
/// <summary>The threads for the next trial: the saved value, kept within the bounds of this computer.</summary>
public static async Task<int> WorkersAsync(SettingsStore settings, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(settings);
var value = (await settings.GetAsync(Workers.Key, cancellationToken).ConfigureAwait(false)).Value;
return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var workers) ? Math.Clamp(workers, 1, MaxWorkers) : 1;
}
private static string? Whole(string text)
{
var max = MaxWorkers;
return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= 1 && value <= max
? null
: $"Serve un numero intero tra 1 e {max}.";
}
}
+86
View File
@@ -0,0 +1,86 @@
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Anubis.Backtest;
/// <summary>
/// A few background threads with low priority (<c>name-1</c> … <c>name-N</c>) that take heavy work in the order it arrives:
/// with one thread the work runs in that order. Callers await the result on their own side: the threads never touch the
/// database. On Linux the priority is mostly ignored by the scheduler, so what keeps the laboratory light there is the number
/// of threads.
/// </summary>
internal sealed class LowPriorityPool : IDisposable
{
private static readonly TimeSpan JoinWait = TimeSpan.FromSeconds(10);
private readonly BlockingCollection<Action> _work = [];
private readonly Thread[] _threads;
private int _disposed;
public LowPriorityPool(string name, int workers)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentOutOfRangeException.ThrowIfLessThan(workers, 1);
_threads = new Thread[workers];
for (var i = 0; i < workers; i++)
{
_threads[i] = new Thread(Loop) { IsBackground = true, Name = $"{name}-{i + 1}", Priority = ThreadPriority.BelowNormal };
_threads[i].Start();
}
}
/// <summary>How many threads take work.</summary>
public int Workers => _threads.Length;
public Task<T> RunAsync<T>(Func<T> work)
{
ArgumentNullException.ThrowIfNull(work);
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
/// <summary>
/// Takes no more work and lets the threads finish what was handed over, waiting for them a while. The queue is released only
/// when every thread has left it: a thread still busy with a long piece of work must not find it gone.
/// </summary>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_work.CompleteAdding();
var watch = Stopwatch.StartNew();
var stopped = true;
foreach (var thread in _threads)
{
var left = JoinWait - watch.Elapsed;
stopped &= thread.Join(left > TimeSpan.Zero ? left : TimeSpan.Zero);
}
if (stopped)
{
_work.Dispose();
}
}
}
+135 -41
View File
@@ -107,11 +107,14 @@ public sealed record BacktestReport(
}
/// <summary>
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan
/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice,
/// the overfitting and the number of tries. The engine that runs the variants is an <see cref="ITrialEngine"/>: the daily one
/// Runs a trial from its plan, on data already loaded (pure computation, no database), in two steps. <see cref="Variants"/>
/// does every engine execution, each one a unit with its own key (<see cref="TrialUnitKey"/>): every variant of the grid on
/// the whole period, the variant in use when the grid does not have it, then, once the plateau rule has chosen, the chosen
/// (or judged) variant with doubled and tripled costs, the benchmark and the look-ahead check. <see cref="Judge"/> then
/// computes the validations, the checks and the report from those runs alone, assembled by key: the same report whether the
/// units ran in order on one thread, on several threads (<see cref="VariantsAsync"/>) or came back from the database after
/// a restart. A plan that names the variant to judge has the figures, the checks and the curve of that one: the grid still
/// gives the choice, the overfitting and the number of tries. The engine is an <see cref="ITrialEngine"/>: the daily one
/// (<see cref="DailyTrialEngine"/>) unless the caller gives another.
/// </summary>
public static class TrialRunner
@@ -132,7 +135,7 @@ public static class TrialRunner
return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken);
}
/// <summary>A trial of any family on any engine: the same validations, checks and report whatever the engine.</summary>
/// <summary>A trial of any family on any engine: <see cref="Judge"/> of <see cref="Variants"/>, on the caller's thread.</summary>
public static (BacktestReport Report, TrialSummary Summary) Run(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now,
Action<string>? progress = null, CancellationToken cancellationToken = default)
@@ -142,57 +145,125 @@ public static class TrialRunner
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
}
var runs = Variants(plan, family, engine, progress, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
return Judge(trialId, plan, planHash, family, engine, runs, prior, now, watch.Elapsed);
}
var variants = ParameterGrid.Of(family, plan.Grid);
if (variants.Count == 0)
{
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
var runs = new BacktestRun[variants.Count];
for (var i = 0; i < variants.Count; i++)
/// <summary>
/// Every engine execution of a trial, one after the other on the caller's thread, in the order the engine has always been
/// called: the grid, the variant in use outside it, the costed runs, the benchmark, the look-ahead check.
/// </summary>
public static TrialRuns Variants(TrialPlan plan, IResearchFamily family, ITrialEngine engine, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
var stages = new TrialStages(plan, family, engine);
var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
foreach (var key in stages.First)
{
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke($"variante {i + 1} di {variants.Count}");
runs[i] = engine.Run(variants[i].Parameters);
progress?.Invoke(key.Kind == TrialUnitKind.Variant ? $"variante {key.Index + 1} di {stages.Grid.Count}" : "variante in uso");
results[key.Text] = stages.Execute(key);
}
var returns = runs.Select(r => r.DailyReturns()).ToArray();
var said = false;
foreach (var key in stages.Second(results))
{
cancellationToken.ThrowIfCancellationRequested();
if (key.Kind == TrialUnitKind.LookAhead)
{
progress?.Invoke("test anti sguardo in avanti");
}
else if (!said)
{
progress?.Invoke("costi doppi e tripli, comprare e tenere");
said = true;
}
results[key.Text] = stages.Execute(key);
}
return stages.Assemble(results);
}
/// <summary>
/// The same executions handed to <paramref name="units"/> one stage at a time (a pool of threads, a store of finished
/// units): the grid and the variant in use first, the rest once the plateau rule has chosen. The results are assembled by
/// key, never in the order they finish, so the runs are those of <see cref="Variants"/>.
/// </summary>
public static async Task<TrialRuns> VariantsAsync(
TrialPlan plan, IResearchFamily family, ITrialEngine engine, ITrialUnits units, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(units);
var stages = new TrialStages(plan, family, engine);
var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
var total = stages.First.Count + stages.SecondCount;
var finished = 0;
TrialUnitResult Execute(TrialUnitKey key)
{
cancellationToken.ThrowIfCancellationRequested();
var result = stages.Execute(key);
progress?.Invoke($"passo {Interlocked.Increment(ref finished)} di {total}");
return result;
}
foreach (var result in await units.RunAsync(stages.First, Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
Interlocked.Exchange(ref finished, results.Count);
foreach (var result in await units.RunAsync(stages.Second(results), Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
return stages.Assemble(results);
}
/// <summary>
/// The judge of a trial on runs already done: the plateau choice, the validations, the checks and the report. Pure: the
/// engine gives only its facts (sessions, currency, year, fingerprint, instruments, limitations) and what it expects of
/// the judged run. <paramref name="elapsed"/> is the time the runs took; the report adds the time of the judge.
/// </summary>
public static (BacktestReport Report, TrialSummary Summary) Judge(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, TrialRuns runs, PriorTrials prior, DateTimeOffset now, TimeSpan elapsed)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(runs);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = engine.Sessions;
var variants = runs.Variants;
if (runs.Grid.Count != variants.Count)
{
throw new InvalidOperationException("Every variant of the grid needs its run.");
}
var returns = runs.Grid.Select(r => r.DailyReturns()).ToArray();
var sharpes = returns.Select(r => Moments.Of(r).Sharpe).ToArray();
var scores = Validation.PlateauScores(variants, sharpes);
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var (chosenIndex, judged, judgedIndex) = Choose(plan, family, variants, sharpes);
var chosen = variants[chosenIndex];
var judged = plan.Judged is null ? chosen.Parameters : StrategyParameters.Of(family, plan.Judged);
var judgedIndex = plan.Judged is null ? chosenIndex : variants.ToList().FindIndex(x => x.ToString() == judged.ToString());
if (judgedIndex < 0)
{
progress?.Invoke("variante in uso");
}
var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex];
var run = judgedIndex < 0 ? runs.OutsideGrid ?? throw new InvalidOperationException("The variant in use outside the grid has no run.") : runs.Grid[judgedIndex];
var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var year = engine.PeriodsPerYear;
var metrics = BacktestMetrics.Of(run, year);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List<ReportCosts>();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{
var costed = multiplier == 1m ? run : engine.Run(judged, multiplier);
var costed = multiplier == 1m ? run : runs.Costed[multiplier];
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
}
var benchmarkRun = engine.Benchmark();
var benchmarkRun = runs.Benchmark;
var benchmark = BacktestMetrics.Of(benchmarkRun, year);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
var days = run.Equity.Select(p => p.Day).ToArray();
DateOnly DayOf(int returnIndex) => days[Math.Clamp(returnIndex + 1, 0, days.Length - 1)];
var v = plan.Validation;
@@ -212,8 +283,7 @@ public static class TrialRunner
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti");
var look = engine.LookAhead(judged, v.LookAheadCuts);
var look = runs.LookAhead;
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -253,8 +323,8 @@ public static class TrialRunner
metrics,
benchmark,
costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs.Grid[i].NetResult,
BacktestMetrics.Of(runs.Grid[i], year).MaxDrawdown, runs.Grid[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
.. judgedIndex >= 0 ? Array.Empty<ReportVariant>()
: [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward,
@@ -271,20 +341,44 @@ public static class TrialRunner
[.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now,
watch.Elapsed.TotalSeconds)
0)
{
Judged = plan.Judged is null ? null : judged.ToString(),
Baskets = run.Baskets.Count == 0 ? null
: [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))],
};
var expected = engine.Expected(run, judgedReturns);
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 };
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5, Seconds = (elapsed + watch.Elapsed).TotalSeconds };
var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes);
return (report, summary);
}
/// <summary>
/// The plateau choice and the variant judged: the chosen one, or the one the plan names, with its place in the grid (-1
/// when the grid does not have it). The same rule for both stages of the runs and for the judge.
/// </summary>
internal static (int ChosenIndex, StrategyParameters Judged, int JudgedIndex) Choose(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants, IReadOnlyList<double> sharpes)
{
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var chosen = variants[chosenIndex];
var (named, namedIndex) = Named(plan, family, variants);
return named is null ? (chosenIndex, chosen.Parameters, chosenIndex) : (chosenIndex, named, namedIndex);
}
/// <summary>The variant the plan names, with its place in the grid (-1 when the grid does not have it); null when it names none.</summary>
internal static (StrategyParameters? Judged, int Index) Named(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants)
{
if (plan.Judged is null)
{
return (null, -1);
}
var judged = StrategyParameters.Of(family, plan.Judged);
return (judged, variants.ToList().FindIndex(x => x.ToString() == judged.ToString()));
}
/// <summary>What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it).</summary>
public static IReadOnlyList<string> Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data)
{
+4 -2
View File
@@ -14,8 +14,10 @@ public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList<double
/// <summary>
/// What the trial judge (<see cref="TrialRunner"/>) asks of an engine, so the same judge, with the same validations and the
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in
/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check.
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset. Each execution is a unit
/// (<see cref="TrialUnitKey"/>); on one thread they come in a fixed order: every variant, the judged one outside the grid,
/// the costed runs, the benchmark, the look-ahead check. The laboratory may run several at once on its pool, so an engine
/// must not keep state between runs.
/// </summary>
public interface ITrialEngine
{
+392
View File
@@ -0,0 +1,392 @@
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>What one engine execution of a trial is (<see cref="TrialUnitKey"/>).</summary>
public enum TrialUnitKind
{
/// <summary>A variant of the grid at plain costs.</summary>
Variant,
/// <summary>The variant in use when the grid does not have it (<see cref="TrialPlan.Judged"/>).</summary>
OutsideGrid,
/// <summary>The judged variant with costs multiplied.</summary>
Costed,
/// <summary>The term of comparison of the engine.</summary>
Benchmark,
/// <summary>The look-ahead check of the judged variant.</summary>
LookAhead,
}
/// <summary>
/// The identity of one engine execution of a trial: its kind, its place among the units of that kind (the grid index for a
/// variant, 0 otherwise), its parameters and its cost multiplier. <see cref="Text"/> is the invariant key the database keeps
/// (<c>variant:3:a=1;kind=0:x1</c>).
/// </summary>
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 Text => string.Create(CultureInfo.InvariantCulture,
$"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}");
}
/// <summary>The outcome of one unit: a run, or the result of the look-ahead check.</summary>
public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead);
/// <summary>
/// Every engine execution a trial needs, done: what <see cref="TrialRunner.Judge"/> reads. <see cref="Grid"/> is in the order
/// of <see cref="Variants"/>; <see cref="Costed"/> holds the multipliers other than 1.
/// </summary>
public sealed record TrialRuns(
IReadOnlyList<Variant> Variants,
IReadOnlyList<BacktestRun> Grid,
BacktestRun? OutsideGrid,
IReadOnlyDictionary<decimal, BacktestRun> Costed,
BacktestRun Benchmark,
LookAheadResult LookAhead);
/// <summary>
/// Where the units of a stage run: on the caller's thread, on a pool of threads, or on a pool that keeps finished units in the
/// database. The results come back in the order of <paramref name="keys"/>, whatever the order they finished in.
/// </summary>
public interface ITrialUnits
{
Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken);
}
/// <summary>Units one after the other on the caller's thread: the task it returns is already finished.</summary>
public sealed class InlineTrialUnits : ITrialUnits
{
public static InlineTrialUnits Instance { get; } = new();
public Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var results = new List<TrialUnitResult>(keys.Count);
foreach (var key in keys)
{
cancellationToken.ThrowIfCancellationRequested();
results.Add(execute(key));
}
return Task.FromResult<IReadOnlyList<TrialUnitResult>>(results);
}
}
/// <summary>
/// Units on a pool of low-priority threads, handed over in order: with one thread they run in the order of the keys. After a
/// unit fails, the ones not yet started are skipped.
/// </summary>
internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
using var failed = new CancellationTokenSource();
var tasks = keys.Select(key => pool.RunAsync(() => Guarded(key, execute, failed))).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>Runs a unit unless another one has failed; a failure stops the units not yet started.</summary>
internal static TrialUnitResult Guarded(TrialUnitKey key, Func<TrialUnitKey, TrialUnitResult> execute, CancellationTokenSource failed)
{
failed.Token.ThrowIfCancellationRequested();
try
{
return execute(key);
}
catch
{
failed.Cancel();
throw;
}
}
}
/// <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.
/// </summary>
internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary<string, byte[]> done) : ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var missing = keys.Where(k => !done.ContainsKey(k.Text)).ToList();
if (missing.Count > 0)
{
await store.ClaimAsync(trialId, tournamentId, missing, cancellationToken).ConfigureAwait(false);
}
using var failed = new CancellationTokenSource();
async Task<TrialUnitResult> OneAsync(TrialUnitKey key)
{
var (result, outcome, seconds) = await pool.RunAsync(() =>
{
var watch = Stopwatch.StartNew();
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);
return result;
}
var tasks = keys.Select(key => done.TryGetValue(key.Text, out var outcome) ? Task.FromResult(TrialUnitOutcomes.Decode(key, outcome)) : OneAsync(key)).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
/// <summary>
/// The two stages of the units of a trial. The first: every variant of the grid in grid order, then the variant in use when
/// the grid does not have it. The second, once the plateau rule has chosen on the first: the costed runs of the judged
/// variant (multipliers other than 1, in increasing order), the benchmark, the look-ahead check. Parameters always come
/// from the grid or from the plan, never from the text of a key.
/// </summary>
internal sealed class TrialStages
{
private readonly TrialPlan _plan;
private readonly IResearchFamily _family;
private readonly ITrialEngine _engine;
private readonly StrategyParameters? _named;
private readonly IReadOnlyList<decimal> _multipliers;
private StrategyParameters? _judged;
private IReadOnlyList<TrialUnitKey>? _second;
public TrialStages(TrialPlan plan, IResearchFamily family, ITrialEngine engine)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
_plan = plan;
_family = family;
_engine = engine;
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
}
Grid = ParameterGrid.Of(family, plan.Grid);
if (Grid.Count == 0)
{
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
var (named, namedIndex) = TrialRunner.Named(plan, family, Grid);
_named = namedIndex < 0 ? named : null;
_multipliers = [.. plan.CostMultipliers.Distinct().Order().Where(m => m != 1m)];
First =
[
.. Grid.Select((v, i) => new TrialUnitKey(TrialUnitKind.Variant, i, v.ToString(), 1m)),
.. _named is null ? Array.Empty<TrialUnitKey>() : [new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, _named.ToString(), 1m)],
];
}
public IReadOnlyList<Variant> Grid { get; }
public IReadOnlyList<TrialUnitKey> First { get; }
/// <summary>How many units the second stage has: it does not depend on the choice.</summary>
public int SecondCount => _multipliers.Count + 2;
private StrategyParameters Judged => _judged ?? throw new InvalidOperationException("The second stage needs the choice of the first.");
/// <summary>The plateau choice on the runs of the first stage, and the keys of the second.</summary>
public IReadOnlyList<TrialUnitKey> Second(IReadOnlyDictionary<string, TrialUnitResult> first)
{
ArgumentNullException.ThrowIfNull(first);
var sharpes = First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => Moments.Of(RunOf(first, k).DailyReturns()).Sharpe).ToArray();
_judged = TrialRunner.Choose(_plan, _family, Grid, sharpes).Judged;
var judged = _judged.ToString();
_second =
[
.. _multipliers.Select(m => new TrialUnitKey(TrialUnitKind.Costed, 0, judged, m)),
new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m),
new TrialUnitKey(TrialUnitKind.LookAhead, 0, judged, 1m),
];
return _second;
}
/// <summary>One engine execution.</summary>
public TrialUnitResult Execute(TrialUnitKey key)
{
ArgumentNullException.ThrowIfNull(key);
return key.Kind switch
{
TrialUnitKind.Variant => new TrialUnitResult(key, _engine.Run(VariantOf(key).Parameters), null),
TrialUnitKind.OutsideGrid => new TrialUnitResult(key, _engine.Run(_named ?? throw new InvalidOperationException("The judged variant is in the grid.")), null),
TrialUnitKind.Costed => new TrialUnitResult(key, _engine.Run(Judged, key.CostMultiplier), null),
TrialUnitKind.Benchmark => new TrialUnitResult(key, _engine.Benchmark(), null),
TrialUnitKind.LookAhead => new TrialUnitResult(key, null, _engine.LookAhead(Judged, _plan.Validation.LookAheadCuts)),
_ => throw new ArgumentOutOfRangeException(nameof(key), key.Kind, "Not a unit of a trial."),
};
}
/// <summary>The runs of both stages, by key.</summary>
public TrialRuns Assemble(IReadOnlyDictionary<string, TrialUnitResult> results)
{
ArgumentNullException.ThrowIfNull(results);
var second = _second ?? throw new InvalidOperationException("The second stage was not planned.");
var outside = First.FirstOrDefault(k => k.Kind == TrialUnitKind.OutsideGrid);
return new TrialRuns(
Grid,
[.. First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => RunOf(results, k))],
outside is null ? null : RunOf(results, outside),
second.Where(k => k.Kind == TrialUnitKind.Costed).ToDictionary(k => k.CostMultiplier, k => RunOf(results, k)),
RunOf(results, second.Single(k => k.Kind == TrialUnitKind.Benchmark)),
ResultOf(results, second.Single(k => k.Kind == TrialUnitKind.LookAhead)).LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."));
}
private Variant VariantOf(TrialUnitKey key)
{
var variant = Grid[key.Index];
return variant.ToString() == key.Parameters ? variant : throw new InvalidOperationException("The key " + key.Text + " is not the variant " + variant + ".");
}
private static TrialUnitResult ResultOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
results.TryGetValue(key.Text, out var result) ? result : throw new InvalidOperationException("The unit " + key.Text + " has no result.");
private static BacktestRun RunOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
ResultOf(results, key).Run ?? throw new InvalidOperationException("The unit " + key.Text + " has no run.");
}
/// <summary>
/// The outcome of a unit as the database keeps it: the gzip of its JSON, with the options of the plans (decimals keep their
/// scale, doubles their exact value). A run is kept without its decisions, which only the look-ahead check reads; the order
/// of fills, trades and notes is kept, so a run read back gives the same report byte for byte.
/// </summary>
internal static class TrialUnitOutcomes
{
private sealed record StoredRun(
string Currency,
decimal InitialCapital,
IReadOnlyList<EquityPoint> Equity,
IReadOnlyList<BacktestFill> Fills,
IReadOnlyList<BacktestTrade> Trades,
IReadOnlyList<BacktestNote> Notes,
decimal Dividends,
decimal WrittenOff,
IReadOnlyList<BacktestBasket> Baskets);
public static byte[] Encode(TrialUnitResult result)
{
ArgumentNullException.ThrowIfNull(result);
var json = result.Key.Kind == TrialUnitKind.LookAhead
? JsonSerializer.SerializeToUtf8Bytes(result.LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."), TrialPlan.Json)
: JsonSerializer.SerializeToUtf8Bytes(Stored(result.Run ?? throw new InvalidOperationException("The unit " + result.Key.Text + " has no run.")), TrialPlan.Json);
using var buffer = new MemoryStream();
using (var zip = new GZipStream(buffer, CompressionLevel.Optimal, leaveOpen: true))
{
zip.Write(json);
}
return buffer.ToArray();
}
public static TrialUnitResult Decode(TrialUnitKey key, byte[] outcome)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(outcome);
using var zip = new GZipStream(new MemoryStream(outcome), CompressionMode.Decompress);
if (key.Kind == TrialUnitKind.LookAhead)
{
return new TrialUnitResult(key, null, JsonSerializer.Deserialize<LookAheadResult>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome"));
}
var run = JsonSerializer.Deserialize<StoredRun>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome");
return new TrialUnitResult(key, new BacktestRun(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, [], run.Notes)
{
Dividends = run.Dividends,
WrittenOff = run.WrittenOff,
Baskets = run.Baskets,
}, null);
}
private static StoredRun Stored(BacktestRun run) =>
new(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, run.Notes, run.Dividends, run.WrittenOff, run.Baskets);
}
/// <summary>States of a row of <c>tournament_units</c>.</summary>
public static class TrialUnitStatuses
{
public const string Running = "running";
public const string Done = "done";
}
/// <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);
/// <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.
/// </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.
/// </summary>
public async Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, CancellationToken cancellationToken)
{
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);
}, 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)
{
ArgumentNullException.ThrowIfNull(keys);
return db.WriteAsync(async s =>
{
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) " +
"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);
}
}, 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)
{
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),
("r", TrialUnitStatuses.Running)), cancellationToken);
}
/// <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",
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", trialId)), cancellationToken).ConfigureAwait(false);
}
+25 -10
View File
@@ -226,21 +226,36 @@ 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>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(s => s.ExecuteAsync(
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r",
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint),
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)), cancellationToken);
db.WriteAsync(async s =>
{
await s.ExecuteAsync(
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r",
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint),
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>A trial failed, with the reason. A trial outside a tournament drops the outcomes of its units, as when it is done.</summary>
public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)",
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned),
("r", TrialStatuses.Running)), cancellationToken);
db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)",
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
// The units of a tournament keep their outcome until the tournament ends: it judges them again.
private static Task<int> ReleaseUnitsAsync(DbSession s, Guid id, CancellationToken cancellationToken) =>
s.ExecuteAsync("UPDATE tournament_units SET outcome = NULL WHERE trial_id = @id AND tournament_id IS NULL AND outcome IS NOT NULL", cancellationToken, ("id", id));
/// <summary>
/// After a restart: trials left running go back to planned (their work was lost with the process), and every planned
/// trial is returned oldest first, to run again from the start with the same plan.
/// After a restart: trials left running go back to planned, and every planned trial is returned oldest first, to run again
/// with the same plan. The units they had finished are kept (<see cref="TrialUnitStore.ResumeAsync"/>): only the rest runs
/// again.
/// </summary>
public async Task<IReadOnlyList<Guid>> ResumeAsync(CancellationToken cancellationToken) =>
await db.WriteAsync(async s =>
+1 -1
View File
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All, .. Backtest.LaboratorySettings.All];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
@@ -0,0 +1,39 @@
-- The tournament of the strategies (ADR 0026): its plan, written before any result and never changed, its state and its
-- verdict. The final tract of the data is opened once: holdout_opened_at and finalists are written together, only once.
CREATE TABLE tournaments (
id {uuid} PRIMARY KEY,
name TEXT NOT NULL,
plan {json} NOT NULL,
plan_hash TEXT NOT NULL,
status TEXT NOT NULL,
verdict TEXT,
finalists {json},
report {json},
error TEXT,
holdout_opened_at {timestamp},
created_at {timestamp} NOT NULL,
started_at {timestamp},
finished_at {timestamp}
){strict};
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.
CREATE TABLE tournament_units (
id {uuid} PRIMARY KEY,
trial_id {uuid} NOT NULL REFERENCES backtest_trials (id),
tournament_id {uuid} REFERENCES tournaments (id),
unit_key TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL,
outcome {bytes},
seconds {float},
created_at {timestamp} NOT NULL,
finished_at {timestamp},
UNIQUE (trial_id, unit_key)
){strict};
CREATE INDEX tournament_units_trial ON tournament_units (trial_id, status);
-- The tournament a contender trial belongs to. No foreign key: backtest_trials is imported before tournaments.
ALTER TABLE backtest_trials ADD COLUMN tournament_id {uuid};