diff --git a/docs/MANUALE.md b/docs/MANUALE.md index 278539b..3866cdc 100644 --- a/docs/MANUALE.md +++ b/docs/MANUALE.md @@ -264,6 +264,8 @@ Per ripartire, togli il file e conferma dalla pagina Rischio. **Parametri delle strategie.** Non si toccano dall'interfaccia: sono quelli con cui ogni strategia è stata provata. Un cambio è una nuova prova in Laboratorio. Si cambiano invece capitale, ripartizione, limiti di rischio, regole sulle notizie e del modello. +**Operai del Laboratorio.** In Impostazioni → Sistema dici quanti calcoli di una prova del Laboratorio girano insieme: uno all'inizio, al massimo uno in meno dei processori. Alzalo solo dopo averne misurato l'effetto, perché il Laboratorio non deve togliere tempo al trading; vale dalla prossima prova. Se il bot si ferma a metà di una prova, alla ripartenza rifà solo i calcoli che non aveva finito. + **Notizie, calendario e trimestrali: solo misurate o attive.** In Impostazioni → Notizie l'interruttore sopra le cinque regole dice se agiscono. «Solo misurate» è il predefinito: le decisioni guardano solo i prezzi, e ogni regola scrive in ombra che cosa avrebbe fatto. «Attive» è il comportamento delle versioni precedenti: le regole accese possono fermare o rinviare un acquisto. Il bot non le riaccende mai da solo. Prima di farlo guarda nel Laboratorio la tabella delle regole in ombra: una regola merita di agire solo dopo almeno 6 mesi di misura, almeno 30 ingressi cambiati e un effetto tutto sopra lo zero (la riga dice «Criterio raggiunto»). Per riaccenderne una sola, spegni le altre righe e poi scegli «Attive». Passare da «Attive» a «Solo misurate» toglie protezioni: se una strategia usa soldi veri chiede la frase, la password e, se l'hai attivato, il codice a sei cifre, come quando spegni una regola. Ogni cambio lascia una riga nel Diario. Con le regole solo misurate un modello in carica che usa indizi delle notizie, delle trimestrali o di paura e avidità viene messo da parte subito. La domenica ne addestra uno senza, che prende il posto solo dopo aver vinto i confronti con il modello in carica; nel frattempo nessun modello conta. Chi aggiorna da una versione precedente trova nel Diario una riga sola: da questa versione le regole sono solo misurate. Le decisioni prese prima restano come erano, con le regole attive. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 79d6068..845c410 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -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 HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index a3faaf0..813ade6 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -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 @@

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.

+

Laboratorio

+
+ + + + + + +

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.

+

Salvataggi

Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.

@@ -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.", diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index c01d21b..1ed7adc 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -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")); diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 0323bea..7c83721 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -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 } /// -/// 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 +/// (, 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. /// public sealed partial class Laboratory : IDisposable { @@ -60,19 +63,32 @@ public sealed partial class Laboratory : IDisposable private readonly ILogger _logger; private readonly Channel _queue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); private readonly ConcurrentDictionary _progress = new(); - private readonly LowPriorityWorker _worker = new("anubis-laboratory"); + private readonly Func> _workers; + private readonly Lock _poolGate = new(); + private LowPriorityPool _pool = new(PoolName, 1); - public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null) + /// How many threads the next trial gets (); one when null. + public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null, Func>? 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; } + /// The units of the trials: one row per engine execution. + public TrialUnitStore Units { get; } + + /// The engine of a trial: the daily one. Tests put one in between to count or stop the executions. + internal Func EngineFor { get; set; } = (plan, family, data) => new DailyTrialEngine(plan, family, data); + /// Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did. public Func? ReviewTrialEnded { get; set; } @@ -86,8 +102,35 @@ public sealed partial class Laboratory : IDisposable } } - /// Heavy work on the thread of the trials. - public Task ComputeAsync(Func work) => _worker.RunAsync(work); + /// Heavy work on the threads of the trials. + public Task ComputeAsync(Func work) + { + lock (_poolGate) + { + return _pool.RunAsync(work); + } + } + + /// The pool with threads: the one in use, or a new one when the number changed. + 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; + } /// What the running trial is doing, in words; null when it is not running here. public string? Progress(Guid id) => _progress.GetValueOrDefault(id); @@ -236,7 +279,10 @@ public sealed partial class Laboratory : IDisposable } } - /// One trial: load its data, compute on the worker thread, 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 come back from the database), judge on + /// the pool, write the report. A failure is recorded, not thrown. + /// 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); } - -/// -/// 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. -/// -internal sealed class LowPriorityWorker : IDisposable -{ - private readonly BlockingCollection _work = []; - private readonly Thread _thread; - - public LowPriorityWorker(string name) - { - _thread = new Thread(Loop) { IsBackground = true, Name = name, Priority = ThreadPriority.BelowNormal }; - _thread.Start(); - } - - public Task RunAsync(Func work) - { - var done = new TaskCompletionSource(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(); - } -} diff --git a/src/Anubis/Backtest/LaboratorySettings.cs b/src/Anubis/Backtest/LaboratorySettings.cs new file mode 100644 index 0000000..ebee4c3 --- /dev/null +++ b/src/Anubis/Backtest/LaboratorySettings.cs @@ -0,0 +1,34 @@ +using System.Globalization; +using Anubis.Core; + +namespace Anubis.Backtest; + +/// +/// 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). +/// +public static class LaboratorySettings +{ + public static readonly SettingDefinition Workers = new("laboratory.workers", "Operai del Laboratorio", "1", Check: Whole); + + public static readonly IReadOnlyList All = [Workers]; + + /// The most threads this computer allows, read when asked: the processors can change with the container. + public static int MaxWorkers => Math.Max(1, Environment.ProcessorCount - 1); + + /// The threads for the next trial: the saved value, kept within the bounds of this computer. + public static async Task 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}."; + } +} diff --git a/src/Anubis/Backtest/LowPriorityPool.cs b/src/Anubis/Backtest/LowPriorityPool.cs new file mode 100644 index 0000000..d107073 --- /dev/null +++ b/src/Anubis/Backtest/LowPriorityPool.cs @@ -0,0 +1,86 @@ +using System.Collections.Concurrent; +using System.Diagnostics; + +namespace Anubis.Backtest; + +/// +/// A few background threads with low priority (name-1 … name-N) 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. +/// +internal sealed class LowPriorityPool : IDisposable +{ + private static readonly TimeSpan JoinWait = TimeSpan.FromSeconds(10); + + private readonly BlockingCollection _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(); + } + } + + /// How many threads take work. + public int Workers => _threads.Length; + + public Task RunAsync(Func work) + { + ArgumentNullException.ThrowIfNull(work); + var done = new TaskCompletionSource(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(); + } + } + + /// + /// 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. + /// + 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(); + } + } +} diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index c0e1b95..c5f4b9e 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -107,11 +107,14 @@ public sealed record BacktestReport( } /// -/// 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 : the daily one +/// Runs a trial from its plan, on data already loaded (pure computation, no database), in two steps. +/// does every engine execution, each one a unit with its own key (): 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. 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 () 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 : the daily one /// () unless the caller gives another. /// 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); } - /// A trial of any family on any engine: the same validations, checks and report whatever the engine. + /// A trial of any family on any engine: of , on the caller's thread. public static (BacktestReport Report, TrialSummary Summary) Run( Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now, Action? 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++) + /// + /// 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. + /// + public static TrialRuns Variants(TrialPlan plan, IResearchFamily family, ITrialEngine engine, Action? progress = null, CancellationToken cancellationToken = default) + { + var stages = new TrialStages(plan, family, engine); + var results = new Dictionary(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); + } + + /// + /// The same executions handed to 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 . + /// + public static async Task VariantsAsync( + TrialPlan plan, IResearchFamily family, ITrialEngine engine, ITrialUnits units, Action? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(units); + var stages = new TrialStages(plan, family, engine); + var results = new Dictionary(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); + } + + /// + /// 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. is the time the runs took; the report adds the time of the judge. + /// + 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(); 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() : [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); } + /// + /// 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. + /// + internal static (int ChosenIndex, StrategyParameters Judged, int JudgedIndex) Choose(TrialPlan plan, IResearchFamily family, IReadOnlyList variants, IReadOnlyList 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); + } + + /// The variant the plan names, with its place in the grid (-1 when the grid does not have it); null when it names none. + internal static (StrategyParameters? Judged, int Index) Named(TrialPlan plan, IResearchFamily family, IReadOnlyList 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())); + } + /// What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it). public static IReadOnlyList Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data) { diff --git a/src/Anubis/Backtest/TrialEngines.cs b/src/Anubis/Backtest/TrialEngines.cs index fbc1313..16a6368 100644 --- a/src/Anubis/Backtest/TrialEngines.cs +++ b/src/Anubis/Backtest/TrialEngines.cs @@ -14,8 +14,10 @@ public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList /// What the trial judge () 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 +/// (); 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. /// public interface ITrialEngine { diff --git a/src/Anubis/Backtest/TrialUnits.cs b/src/Anubis/Backtest/TrialUnits.cs new file mode 100644 index 0000000..368dbe0 --- /dev/null +++ b/src/Anubis/Backtest/TrialUnits.cs @@ -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; + +/// What one engine execution of a trial is (). +public enum TrialUnitKind +{ + /// A variant of the grid at plain costs. + Variant, + + /// The variant in use when the grid does not have it (). + OutsideGrid, + + /// The judged variant with costs multiplied. + Costed, + + /// The term of comparison of the engine. + Benchmark, + + /// The look-ahead check of the judged variant. + LookAhead, +} + +/// +/// 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. is the invariant key the database keeps +/// (variant:3:a=1;kind=0:x1). +/// +public sealed record TrialUnitKey(TrialUnitKind Kind, int Index, string Parameters, decimal CostMultiplier) +{ + /// The kind in snake case, as the database keeps it (outside_grid). + public string KindText => JsonNamingPolicy.SnakeCaseLower.ConvertName(Kind.ToString()); + + public string Text => string.Create(CultureInfo.InvariantCulture, + $"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}"); +} + +/// The outcome of one unit: a run, or the result of the look-ahead check. +public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead); + +/// +/// Every engine execution a trial needs, done: what reads. is in the order +/// of ; holds the multipliers other than 1. +/// +public sealed record TrialRuns( + IReadOnlyList Variants, + IReadOnlyList Grid, + BacktestRun? OutsideGrid, + IReadOnlyDictionary Costed, + BacktestRun Benchmark, + LookAheadResult LookAhead); + +/// +/// 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 , whatever the order they finished in. +/// +public interface ITrialUnits +{ + Task> RunAsync(IReadOnlyList keys, Func execute, CancellationToken cancellationToken); +} + +/// Units one after the other on the caller's thread: the task it returns is already finished. +public sealed class InlineTrialUnits : ITrialUnits +{ + public static InlineTrialUnits Instance { get; } = new(); + + public Task> RunAsync(IReadOnlyList keys, Func execute, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(keys); + ArgumentNullException.ThrowIfNull(execute); + var results = new List(keys.Count); + foreach (var key in keys) + { + cancellationToken.ThrowIfCancellationRequested(); + results.Add(execute(key)); + } + + return Task.FromResult>(results); + } +} + +/// +/// 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. +/// +internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits +{ + public async Task> RunAsync(IReadOnlyList keys, Func 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); + } + + /// Runs a unit unless another one has failed; a failure stops the units not yet started. + internal static TrialUnitResult Guarded(TrialUnitKey key, Func execute, CancellationTokenSource failed) + { + failed.Token.ThrowIfCancellationRequested(); + try + { + return execute(key); + } + catch + { + failed.Cancel(); + throw; + } + } +} + +/// +/// Units on a pool that records each one in tournament_units: a claim before it runs, its outcome once done. The units +/// already done (, from ) come back from their outcome and do +/// not run again. +/// +internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary done) : ITrialUnits +{ + public async Task> RunAsync(IReadOnlyList keys, Func 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 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); + } +} + +/// +/// 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. +/// +internal sealed class TrialStages +{ + private readonly TrialPlan _plan; + private readonly IResearchFamily _family; + private readonly ITrialEngine _engine; + private readonly StrategyParameters? _named; + private readonly IReadOnlyList _multipliers; + private StrategyParameters? _judged; + private IReadOnlyList? _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() : [new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, _named.ToString(), 1m)], + ]; + } + + public IReadOnlyList Grid { get; } + + public IReadOnlyList First { get; } + + /// How many units the second stage has: it does not depend on the choice. + public int SecondCount => _multipliers.Count + 2; + + private StrategyParameters Judged => _judged ?? throw new InvalidOperationException("The second stage needs the choice of the first."); + + /// The plateau choice on the runs of the first stage, and the keys of the second. + public IReadOnlyList Second(IReadOnlyDictionary 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; + } + + /// One engine execution. + 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."), + }; + } + + /// The runs of both stages, by key. + public TrialRuns Assemble(IReadOnlyDictionary 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 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 results, TrialUnitKey key) => + ResultOf(results, key).Run ?? throw new InvalidOperationException("The unit " + key.Text + " has no run."); +} + +/// +/// 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. +/// +internal static class TrialUnitOutcomes +{ + private sealed record StoredRun( + string Currency, + decimal InitialCapital, + IReadOnlyList Equity, + IReadOnlyList Fills, + IReadOnlyList Trades, + IReadOnlyList Notes, + decimal Dividends, + decimal WrittenOff, + IReadOnlyList 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(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome")); + } + + var run = JsonSerializer.Deserialize(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); +} + +/// States of a row of tournament_units. +public static class TrialUnitStatuses +{ + public const string Running = "running"; + public const string Done = "done"; +} + +/// A unit as the database keeps it, without its outcome. +public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId); + +/// +/// The units of the trials in tournament_units (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 (, ); a unit never counts as a +/// trial. +/// +public sealed class TrialUnitStore(Database db, IClock clock) +{ + /// + /// 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. + /// + public async Task> 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); + } + + /// Claims the units about to run, in one transaction. A unit already claimed stays as it is. + public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList 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); + } + + /// A unit done: its outcome and the seconds it took. + 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); + } + + /// The units of a trial, in the order they were claimed. + public async Task> 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); +} diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 93366f5..48794ad 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -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; + /// A trial done, with its report. A trial outside a tournament drops the outcomes of its units: the rows stay as a record. 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); + /// A trial failed, with the reason. A trial outside a tournament drops the outcomes of its units, as when it is done. 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 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)); /// - /// 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 (): only the rest runs + /// again. /// public async Task> ResumeAsync(CancellationToken cancellationToken) => await db.WriteAsync(async s => diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index 9d447c3..21501f0 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -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 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 _overrides = overrides ?? new Dictionary(); diff --git a/src/Anubis/Db/Migrations/0016_tournaments.sql b/src/Anubis/Db/Migrations/0016_tournaments.sql new file mode 100644 index 0000000..bcf6125 --- /dev/null +++ b/src/Anubis/Db/Migrations/0016_tournaments.sql @@ -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}; diff --git a/tests/Anubis.Tests/ArchiveTests.cs b/tests/Anubis.Tests/ArchiveTests.cs index b108ee5..99ed401 100644 --- a/tests/Anubis.Tests/ArchiveTests.cs +++ b/tests/Anubis.Tests/ArchiveTests.cs @@ -35,6 +35,21 @@ public sealed class ArchiveTests ("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false); await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)", ("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false); + + // A tournament, one of its trials and a unit with its outcome: JSON, bytes and a measure across engines (Phase 13). + var tournament = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(40)); + var trial = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(41)); + await s.ExecuteAsync( + "INSERT INTO tournaments (id, name, plan, plan_hash, status, finalists, created_at, started_at) VALUES (@id, 'Campionato', @p, 'abc', 'running', @f, @t, @t)", + ("id", tournament), ("p", new DbJson("{\"name\": \"Campionato\", \"cost_multipliers\": [1, 2, 3]}")), ("f", new DbJson("[\"a\", \"b\"]")), + ("t", _clock.UtcNow)).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, tournament_id) VALUES (@id, 'sma_cross', '1', @p, 'def', 4, 'running', @t, @tour)", + ("id", trial), ("p", new DbJson("{\"strategy\": \"sma_cross\"}")), ("t", _clock.UtcNow), ("tour", tournament)).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', @o, @sec, @t, @t)", + ("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(42))), ("tr", trial), ("tour", tournament), ("o", new byte[] { 31, 139, 8, 0, 255, 0 }), ("sec", 0.1234567890123), + ("t", _clock.UtcNow)).ConfigureAwait(false); }).ConfigureAwait(false); } diff --git a/tests/Anubis.Tests/TrialUnitTests.cs b/tests/Anubis.Tests/TrialUnitTests.cs new file mode 100644 index 0000000..dd27edb --- /dev/null +++ b/tests/Anubis.Tests/TrialUnitTests.cs @@ -0,0 +1,410 @@ +using System.Globalization; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The units of a trial and the pool of the laboratory (Phase 13, issue #122): the judge works on runs already done, assembled +/// by key, so one thread, four threads and units read back from the database give the same report as the golden ones; a trial +/// stopped halfway runs again only what it had not finished. +/// +[TestClass] +public sealed class TrialUnitTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero); + private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12"); + private static readonly DateOnly Through = new(2026, 12, 31); + private static readonly TrialUnitKey RunKey = new(TrialUnitKind.Variant, 0, "", 1m); + private static readonly TrialUnitKey LookKey = new(TrialUnitKind.LookAhead, 0, "", 1m); + + private sealed record Golden(string Name, TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data, PriorTrials Prior) + { + public string Hash => TrialPlan.Hash(Plan.ToJson()); + + public DailyTrialEngine Engine() => new(Plan, Family, Data); + } + + [TestMethod] + [TestCategory(Category.Golden)] + public async Task JudgeOfVariantsGivesTheJsonOfRun() + { + foreach (var golden in await GoldensAsync().ConfigureAwait(false)) + { + var engine = golden.Engine(); + var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine); + Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report); + } + } + + [TestMethod] + [TestCategory(Category.Golden)] + public async Task FourWorkersGiveTheReportOfOne() + { + using var pool = new LowPriorityPool("anubis-test-four", 4); + foreach (var golden in await GoldensAsync().ConfigureAwait(false)) + { + var engine = golden.Engine(); + var runs = await TrialRunner.VariantsAsync(golden.Plan, golden.Family, engine, new PooledTrialUnits(pool), null, _none).ConfigureAwait(false); + Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report); + } + } + + [TestMethod] + [TestCategory(Category.Golden)] + public async Task ARunReloadedFromItsStoredUnitGivesTheSameReport() + { + foreach (var golden in await GoldensAsync().ConfigureAwait(false)) + { + var engine = golden.Engine(); + var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine); + var reloaded = new TrialRuns( + runs.Variants, + [.. runs.Grid.Select(Again)], + runs.OutsideGrid is null ? null : Again(runs.OutsideGrid), + runs.Costed.ToDictionary(c => c.Key, c => Again(c.Value)), + Again(runs.Benchmark), + TrialUnitOutcomes.Decode(LookKey, TrialUnitOutcomes.Encode(new TrialUnitResult(LookKey, null, runs.LookAhead))).LookAhead!); + Assert.IsTrue(reloaded.Grid.All(r => r.Decisions.Count == 0), "The decisions are not kept: only the look-ahead check reads them."); + Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, reloaded, golden.Prior, Now, TimeSpan.Zero).Report); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AStoredUnitIsTheSameBytesWhenWrittenAgain() + { + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: Through.AddDays(-399))); + var run = BacktestEngine.Run(new MovingAverageCross(5, 20), data); + var stored = TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null)); + var back = TrialUnitOutcomes.Decode(RunKey, stored).Run!; + CollectionAssert.AreEqual(stored, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, back, null))); + Assert.AreEqual(run.Fees, back.Fees); + Assert.AreEqual(run.FinalEquity, back.FinalEquity); + CollectionAssert.AreEqual(run.Fills.ToList(), back.Fills.ToList()); + CollectionAssert.AreEqual(run.Trades.ToList(), back.Trades.ToList()); + CollectionAssert.AreEqual(run.Notes.ToList(), back.Notes.ToList()); + Assert.IsTrue(stored.Length < 200_000, "The outcome is compressed."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheKeyOfAUnitIsTheSameTextInEveryCulture() + { + var before = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT"); + Assert.AreEqual("variant:3:a=1;kind=0:x1", new TrialUnitKey(TrialUnitKind.Variant, 3, "a=1;kind=0", 1m).Text); + Assert.AreEqual("costed:0:a=1;kind=0:x2", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1;kind=0", 2.00m).Text); + Assert.AreEqual("costed:0:a=1:x1.5", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1", 1.50m).Text); + Assert.AreEqual("outside_grid:0:a=4;kind=1:x1", new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, "a=4;kind=1", 1m).Text); + Assert.AreEqual("benchmark:0::x1", new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m).Text); + Assert.AreEqual("look_ahead", new TrialUnitKey(TrialUnitKind.LookAhead, 0, "a=1", 1m).KindText); + } + finally + { + CultureInfo.CurrentCulture = before; + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task OnOneWorkerThePoolCallsTheEngineInTheOrderOfToday() + { + var (plan, family, data) = SmallCross(); + var inline = new List(); + var sequential = TrialRunner.Variants(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), inline)); + using var pool = new LowPriorityPool("anubis-test-one", 1); + var pooled = new List(); + var parallel = await TrialRunner.VariantsAsync(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), pooled), new PooledTrialUnits(pool), + null, _none).ConfigureAwait(false); + Assert.HasCount(4 + 2 + 2, inline); + CollectionAssert.AreEqual(inline, pooled); + StringAssert.StartsWith(inline[^1], "look_ahead "); + Assert.AreEqual("benchmark", inline[^2]); + + var inlineUnits = await TrialRunner.VariantsAsync(plan, family, new DailyTrialEngine(plan, family, data), InlineTrialUnits.Instance, null, _none).ConfigureAwait(false); + var hash = TrialPlan.Hash(plan.ToJson()); + var one = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), sequential, PriorTrials.None, Now, TimeSpan.Zero).Report; + foreach (var other in new[] { parallel, inlineUnits }) + { + var report = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), other, PriorTrials.None, Now, TimeSpan.Zero).Report; + Assert.AreEqual((one with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson()); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AUnitThatFailsStopsTheOnesNotYetStartedAndItsErrorComesBack() + { + var (plan, family, data) = SmallCross(); + using var pool = new LowPriorityPool("anubis-test-fail", 1); + var calls = new List(); + var engine = new RecordingEngine(new DailyTrialEngine(plan, family, data), calls, _ => throw new InvalidOperationException("rotto")); + var error = await Assert.ThrowsAsync(() => TrialRunner.VariantsAsync(plan, family, engine, new PooledTrialUnits(pool), null, _none)) + .ConfigureAwait(false); + Assert.AreEqual("rotto", error.Message, "The error of the unit comes back, not the skip of the others."); + Assert.HasCount(1, calls, "After a failure the units still queued do not run."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task ThePoolRunsOnNamedLowPriorityBackgroundThreadsAndFinishesWhatItWasGiven() + { + using var pool = new LowPriorityPool("anubis-test-pool", 2); + using var both = new Barrier(2); + (bool Together, string? Name, ThreadPriority Priority, bool Background) Probe() => + (both.SignalAndWait(TimeSpan.FromSeconds(30)), Thread.CurrentThread.Name, Thread.CurrentThread.Priority, Thread.CurrentThread.IsBackground); + var seen = await Task.WhenAll(pool.RunAsync(Probe), pool.RunAsync(Probe)).ConfigureAwait(false); + Assert.AreEqual(2, pool.Workers); + Assert.IsTrue(seen.All(s => s.Together), "Two threads run two pieces of work at once."); + CollectionAssert.AreEquivalent(new[] { "anubis-test-pool-1", "anubis-test-pool-2" }, seen.Select(s => s.Name).ToArray()); + Assert.IsTrue(seen.All(s => s.Priority == ThreadPriority.BelowNormal && s.Background)); + await Assert.ThrowsAsync(() => pool.RunAsync(() => throw new ArithmeticException())).ConfigureAwait(false); + + // Work handed over before the pool stops still runs; nothing more is taken; stopping twice is harmless. + using var release = new ManualResetEventSlim(); + var slow = pool.RunAsync(() => release.Wait(TimeSpan.FromSeconds(30))); + var queued = pool.RunAsync(() => 7); + var stopping = Task.Run(pool.Dispose); + release.Set(); + await stopping.ConfigureAwait(false); + Assert.IsTrue(await slow.ConfigureAwait(false)); + Assert.AreEqual(7, await queued.ConfigureAwait(false)); + Assert.Throws(() => pool.RunAsync(() => 1)); + pool.Dispose(); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AfterAnInterruptionTheFinishedUnitsAreNotRunAgain() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false); + var workers = 1; + using var lab = new Laboratory(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers)); + var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false); + var family = StrategyCatalog.Find(trial.Strategy)!; + var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false); + var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report; + + // The process stops while the third variant runs, after the first two are recorded. + using var stop = new CancellationTokenSource(); + var first = new List(); + lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n => + { + if (n == 3) + { + for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++) + { + Thread.Sleep(20); + } + + stop.Cancel(); + } + }); + await Assert.ThrowsAsync(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false); + Assert.AreEqual(TrialStatuses.Running, (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.Status); + var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false); + var finished = rows.Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList(); + var left = rows.Where(r => r.Status == TrialUnitStatuses.Running).Select(r => r.Key).ToList(); + Assert.IsGreaterThanOrEqualTo(2, finished.Count); + Assert.IsNotEmpty(left, "The units claimed and not finished stay running."); + Assert.IsTrue(rows.All(r => r.Status != TrialUnitStatuses.Done || (r.HasOutcome && r.Seconds is >= 0))); + Assert.IsTrue(rows.All(r => r.TournamentId is null)); + + // The next start plans it again and runs only what was not finished, now on two threads. + CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id); + workers = 2; + var second = new List(); + lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second); + await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false); + var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error); + + var total = 4 + 2 + 1 + 1; + Assert.HasCount(total - finished.Count, second); + foreach (var key in finished) + { + CollectionAssert.DoesNotContain(second, CallOf(key), "A finished unit does not run again: " + key); + } + + foreach (var key in left) + { + CollectionAssert.Contains(second, CallOf(key), "A unit left running runs again: " + key); + } + + var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!); + Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson()); + Assert.AreEqual(clock.UtcNow, report.ComputedAt); + + // A trial outside a tournament keeps its units as a record, without their outcomes. + var after = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false); + Assert.HasCount(total, after); + Assert.IsTrue(after.All(r => r.Status == TrialUnitStatuses.Done && !r.HasOutcome)); + CollectionAssert.AreEquivalent(new[] { "variant", "costed", "benchmark", "look_ahead" }, after.Select(r => r.Kind).Distinct().ToArray()); + Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors() + { + var workers = LaboratorySettings.Workers; + Assert.AreEqual("laboratory.workers", workers.Key); + Assert.AreEqual("1", workers.Default); + Assert.AreEqual("Operai del Laboratorio", workers.Label); + Assert.AreSame(workers, SettingsStore.Definition(workers.Key)); + var max = Math.Max(1, Environment.ProcessorCount - 1); + Assert.AreEqual(max, LaboratorySettings.MaxWorkers); + Assert.IsNull(workers.Check!("1")); + Assert.IsNull(workers.Check(max.ToString(CultureInfo.InvariantCulture))); + foreach (var wrong in new[] { "0", (max + 1).ToString(CultureInfo.InvariantCulture), "", "due", "1.5", "-1", "+2", " 2" }) + { + Assert.AreEqual($"Serve un numero intero tra 1 e {max}.", workers.Check(wrong), wrong); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheWorkersOfTheLaboratoryAreSetInTheSystemSettings() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var page = await server.TextAsync("/impostazioni"); + StringAssert.Contains(page, "Operai del Laboratorio"); + StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading"); + StringAssert.Contains(page, "Vale dalla prossima prova."); + + async Task Save(string value) + { + using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LaboratorySettings.Workers.Key, ("ritorno", "/impostazioni#sistema"), ("valore", value)); + return ServerHarness.Location(answer); + } + + var settings = server.Host.Services!.Settings; + Assert.AreEqual("/impostazioni#sistema", await Save("1")); + Assert.AreEqual(1, await LaboratorySettings.WorkersAsync(settings, _none)); + StringAssert.Contains(await Save("0"), "errore=operai"); + StringAssert.Contains(await Save((LaboratorySettings.MaxWorkers + 1).ToString(CultureInfo.InvariantCulture)), "errore=operai"); + StringAssert.Contains(await Save("tanti"), "errore=operai"); + Assert.AreEqual("1", (await settings.GetAsync(LaboratorySettings.Workers.Key, _none)).Value); + StringAssert.Contains(await server.TextAsync("/impostazioni?errore=operai#sistema"), "Gli operai del Laboratorio sono un numero intero da 1 a"); + } + + private static BacktestRun Again(BacktestRun run) => TrialUnitOutcomes.Decode(RunKey, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null))).Run!; + + /// The call of the recording engine a unit key stands for. + private static string CallOf(string key) + { + var parts = key.Split(':'); + return parts[0] switch + { + "benchmark" => "benchmark", + "look_ahead" => $"look_ahead {parts[2]} {TrialValidation.Default.LookAheadCuts}", + _ => $"run {parts[2]} {parts[3]}", + }; + } + + private static (TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data) SmallCross() + { + var first = new DateOnly(2024, 1, 1); + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: first)); + var grid = new Dictionary> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] }; + var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"], + first.AddDays(60), first.AddDays(399), 10_000m, grid), Now).Plan; + return (plan, MovingAverageCrossFamily.Instance, data); + } + + /// The inputs of the three golden reports of , built the same way. + private static async Task> GoldensAsync() + { + var walk = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03)); + var cross = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"], + new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan; + var folder = TempFolder.Create("golden-units"); + try + { + var store = new ResearchStore(folder); + var seed = 21u; + foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" }) + { + var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), + (decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList(); + await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false); + } + + var trend = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, + CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan; + var data = await Laboratory.LoadResearchAsync(folder, trend.Data, _none).ConfigureAwait(false); + var family = StrategyCatalog.Find(StrategyNames.CryptoTrend)!; + return + [ + new("sma_cross", cross, MovingAverageCrossFamily.Instance, walk, new PriorTrials(2, 18, [0.4, 0.9, -0.1])), + new("crypto_trend", trend, family, data, PriorTrials.None), + new("crypto_trend_judged", trend with { Judged = "coin_vol=12;max_stop=15" }, family, data, PriorTrials.None), + ]; + } + finally + { + TempFolder.Delete(folder); + } + } + + private static void Same(string name, BacktestReport report) => + Assert.AreEqual(Fixture.Text(Path.Combine("golden", name + ".report.json")), (report with { Seconds = 0 }).ToJson(), $"The report of {name} changed."); + + /// An engine in between: it records every call (safe from several threads) and may act on the n-th one. + private sealed class RecordingEngine(ITrialEngine inner, List calls, Action? onCall = null) : ITrialEngine + { + private int _count; + + public string Currency => inner.Currency; + + public int PeriodsPerYear => inner.PeriodsPerYear; + + public int Sessions => inner.Sessions; + + public string Fingerprint() => inner.Fingerprint(); + + public IReadOnlyList Instruments() => inner.Instruments(); + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) + { + Record(FormattableString.Invariant($"run {parameters} x{costMultiplier}")); + return inner.Run(parameters, costMultiplier); + } + + public BacktestRun Benchmark() + { + Record("benchmark"); + return inner.Benchmark(); + } + + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) + { + Record(FormattableString.Invariant($"look_ahead {parameters} {cuts}")); + return inner.LookAhead(parameters, cuts); + } + + public IReadOnlyList Limitations() => inner.Limitations(); + + public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns); + + private void Record(string call) + { + lock (calls) + { + calls.Add(call); + } + + onCall?.Invoke(Interlocked.Increment(ref _count)); + } + } +}