diff --git a/docs/MANUALE.md b/docs/MANUALE.md index 3866cdc..10e3bb5 100644 --- a/docs/MANUALE.md +++ b/docs/MANUALE.md @@ -264,7 +264,7 @@ 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. +**Operai del Laboratorio.** In Impostazioni → Sistema dici quanti calcoli di una prova del Laboratorio girano insieme (le prove restano una alla volta): 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; li rifà tutti se nel frattempo sono cambiati i dati della prova o il bot è stato aggiornato, così una prova non mescola mai calcoli fatti su dati o versioni diversi. **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. diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 813ade6..ce114f5 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -655,7 +655,7 @@ -

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.

+

Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta. Alzalo solo dopo averne misurato l'effetto: il Laboratorio non deve togliere tempo al trading. Vale dalla prossima prova. Su questo computer va da 1 a @LaboratorySettings.MaxWorkers.

Salvataggi

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

diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 6306c47..1b963f6 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -297,13 +297,19 @@ public sealed partial class Laboratory : IDisposable } /// - /// One trial: load its data, run its units on the pool (those done before a restart come back from the database), judge on - /// the pool, write the report. A failure is recorded, not thrown. + /// One trial: load its data, run its units on the pool (those done before a restart on the same data, engine and build come + /// back from the database), judge on the pool, write the report. A failure is recorded, not thrown. A trial of a tournament + /// already finished that comes back to the queue brings its tournament to the judge, when it is not judged yet. /// public async Task ProcessAsync(Guid id, CancellationToken cancellationToken) { if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false)) { + if (await Trials.FinishedTournamentAsync(id, cancellationToken).ConfigureAwait(false) is { } waiting) + { + await JudgeFromQueueAsync(waiting, id, cancellationToken).ConfigureAwait(false); + } + return; } @@ -332,11 +338,12 @@ public sealed partial class Laboratory : IDisposable var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false); var now = _clock.UtcNow; var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false))); - var done = await Units.ResumeAsync(id, cancellationToken).ConfigureAwait(false); var engine = EngineFor(trial.Plan, family, data); + var fingerprint = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false); + var done = await Units.ResumeAsync(id, fingerprint, cancellationToken).ConfigureAwait(false); var watch = Stopwatch.StartNew(); - var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done), text => _progress[id] = text, - cancellationToken).ConfigureAwait(false); + var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done, fingerprint), + text => _progress[id] = text, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); _progress[id] = "convalide"; var elapsed = watch.Elapsed; @@ -367,7 +374,7 @@ public sealed partial class Laboratory : IDisposable // The last trial of a tournament to finish brings it to its judge. if (trial?.TournamentId is { } judged) { - await JudgeTournamentAsync(judged, cancellationToken).ConfigureAwait(false); + await JudgeFromQueueAsync(judged, id, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Anubis/Backtest/LaboratoryTournaments.cs b/src/Anubis/Backtest/LaboratoryTournaments.cs index 2d38993..38b1483 100644 --- a/src/Anubis/Backtest/LaboratoryTournaments.cs +++ b/src/Anubis/Backtest/LaboratoryTournaments.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Text.Json; using Anubis.Core; using Anubis.Strategies; using Microsoft.Extensions.Logging; @@ -46,33 +47,59 @@ public sealed partial class Laboratory return; } + // An error that escapes the judge (the database out of reach while recording a failure) does not stop the queue: the + // tournament stays to judge, at the next start or when one of its trials comes back to the queue. foreach (var id in ids) { - await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false); + try + { + await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogJudgeDeferred(_logger, id, ex); + } + } + } + + // The judge called from the queue, after trial `trial` of the tournament: an error that escapes it does not stop the queue. + // As an error of the queue itself, the trial comes back after RetryDelay and brings the tournament to its judge again. + private async Task JudgeFromQueueAsync(Guid tournament, Guid trial, CancellationToken cancellationToken) + { + try + { + await JudgeTournamentAsync(tournament, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogQueueFailed(_logger, ex); + await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false); + _queue.Writer.TryWrite(trial); } } /// /// Judges a tournament whose trials are all finished; nothing when one is still to run or the tournament is finished. A - /// failure is recorded, not thrown; a stop leaves it being judged, and the next start goes on from the units done. + /// failure is recorded, not thrown, a plan that can no longer be read included; a stop leaves it being judged, and the next + /// start goes on from the units done. Only an error while recording the failure (the database out of reach) comes out. /// public async Task JudgeTournamentAsync(Guid id, CancellationToken cancellationToken) { - var tournament = await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false); - if (tournament is null || tournament.IsFinished) - { - return; - } - - var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false); - if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false)) - { - return; - } - - _progress[id] = "scelta dei finalisti"; try { + var tournament = await ReadTournamentAsync(id, cancellationToken).ConfigureAwait(false); + if (tournament is null || tournament.IsFinished) + { + return; + } + + var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false); + if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false)) + { + return; + } + + _progress[id] = "scelta dei finalisti"; var watch = Stopwatch.StartNew(); if (!tournament.PlanIntact) { @@ -127,12 +154,34 @@ public sealed partial class Laboratory } } - // A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept. + // The tournament with its plan; a plan text that no longer reads (changed by hand, or by a version that cannot read it) fails it. + private async Task ReadTournamentAsync(Guid id, CancellationToken cancellationToken) + { + try + { + return await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is JsonException or NotSupportedException) + { + throw new InvalidOperationException("Il piano registrato del campionato non si può più leggere: il campionato non si giudica.", ex); + } + } + + // A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept. Its trial + // must be the one the plan of the tournament wrote: plan intact, and the same rule, grid, data, capital and costs. private async Task ContenderAsync(TournamentPlan plan, TournamentContender contender, Trial trial, LowPriorityPool pool, CancellationToken cancellationToken) { + if (!trial.PlanIntact) + { + throw new InvalidOperationException("Il piano registrato della prova di «" + contender.Label + "» non corrisponde più alla sua impronta: il campionato non si giudica."); + } + var data = trial.Plan.Data; if (trial.Strategy != contender.Strategy || trial.StrategyVersion != contender.StrategyVersion || data.To != plan.SearchTo || data.From != contender.Data.From - || !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || trial.Variants != contender.Variants) + || !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || data.Source != contender.Data.Source + || data.FullHistory != contender.Data.FullHistory || trial.Variants != contender.Variants || !SameGrid(trial.Plan.Grid, contender.Grid) + || trial.Plan.InitialCapital != plan.InitialCapital || trial.Plan.Slippage != plan.Slippage + || trial.Plan.ReferenceShare != StrategyPipeline.ResearchShare(contender.Strategy)) { throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano."); } @@ -165,13 +214,21 @@ public sealed partial class Laboratory var chosenText = contender.Chosen.Parameters; var chosen = ParameterGrid.Of(family, trial.Plan.Grid).FirstOrDefault(v => v.ToString() == chosenText)?.Parameters ?? throw new InvalidOperationException("La variante scelta di «" + contender.Contender.Label + "» non è nella sua griglia."); - var done = await Units.ResumeAsync(trial.Id, cancellationToken).ConfigureAwait(false); - var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done); // Every finalist draws the signs of a day from the same first day, so a day has one sign across the whole field. var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart()); var engine = EngineFor(trial.Plan, family, await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false)); var centred = engine.LongOnly; + + // The repetitions of the control done on other search data, by another engine or build run again. The runs on the final + // tract done by another engine or build too; on other data of the tract, only when it is read again for a run not done. + var search = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false); + var controlKind = TrialUnitKey.TextOf(TrialUnitKind.Control); + var holdoutKind = TrialUnitKey.TextOf(TrialUnitKind.Holdout); + var done = await Units.ResumeAsync(trial.Id, (kind, stored) => + kind == controlKind ? stored == search + : kind != holdoutKind || (stored is not null && stored.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)), cancellationToken).ConfigureAwait(false); + var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done, search); List control = [.. Enumerable.Range(0, plan.Control.Repetitions).Select(k => new TrialUnitKey(TrialUnitKind.Control, k, chosenText, 1m))]; string? unavailable = null; if (control.Any(k => !done.ContainsKey(k.Text))) @@ -205,11 +262,16 @@ public sealed partial class Laboratory List holdout = [.. HoldoutCosts.Select(m => new TrialUnitKey(TrialUnitKind.Holdout, 0, chosenText, m))]; ITrialEngine? tract = null; + var finals = units; if (holdout.Any(k => !done.ContainsKey(k.Text))) { var data = trial.Plan.Data with { From = plan.HoldoutFrom, To = contender.Contender.Data.To }; var holdoutPlan = trial.Plan with { Data = data }; - tract = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false)); + var opened = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false)); + tract = opened; + var read = await pool.RunAsync(() => TrialUnitStore.Fingerprint(opened)).ConfigureAwait(false); + var again = await Units.ResumeAsync(trial.Id, (kind, stored) => kind != holdoutKind || stored == read, cancellationToken).ConfigureAwait(false); + finals = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, again, read); } TrialUnitResult Final(TrialUnitKey key) @@ -218,10 +280,13 @@ public sealed partial class Laboratory return new TrialUnitResult(key, (tract ?? throw new InvalidOperationException("The final tract was not read.")).Run(chosen, key.CostMultiplier), null); } - var runs = await units.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false); + var runs = await finals.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false); return new FinalistOutcome(contender.Contender.Label, centred, replicas, unavailable, runs.ToDictionary(r => r.Key.CostMultiplier, r => r.Run!)); } + private static bool SameGrid(IReadOnlyDictionary> a, IReadOnlyDictionary> b) => + a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var values) && p.Value.SequenceEqual(values)); + private IStrategyFamily FamilyOf(TournamentContender contender) { var family = Families(contender.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + contender.Strategy); @@ -234,4 +299,7 @@ public sealed partial class Laboratory [LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} failed")] private static partial void LogTournamentFailed(ILogger logger, Guid id, Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} could not be judged now: it is judged at the next start or when one of its trials comes back to the queue")] + private static partial void LogJudgeDeferred(ILogger logger, Guid id, Exception exception); } diff --git a/src/Anubis/Backtest/TrialUnits.cs b/src/Anubis/Backtest/TrialUnits.cs index f58f2f5..de50845 100644 --- a/src/Anubis/Backtest/TrialUnits.cs +++ b/src/Anubis/Backtest/TrialUnits.cs @@ -44,7 +44,10 @@ public enum TrialUnitKind 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 KindText => TextOf(Kind); + + /// A kind in snake case, as the database keeps it. + public static string TextOf(TrialUnitKind kind) => JsonNamingPolicy.SnakeCaseLower.ConvertName(kind.ToString()); public string Text => string.Create(CultureInfo.InvariantCulture, $"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}"); @@ -130,11 +133,13 @@ internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits } /// -/// 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. +/// Units on a pool that records each one in tournament_units: a claim before it runs, its outcome once done, both with +/// , what they are computed on (). The units already +/// done (, from , on the same +/// fingerprint) 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 +internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary done, string fingerprint) + : ITrialUnits { public async Task> RunAsync(IReadOnlyList keys, Func execute, CancellationToken cancellationToken) { @@ -143,7 +148,7 @@ internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore stor var missing = keys.Where(k => !done.ContainsKey(k.Text)).ToList(); if (missing.Count > 0) { - await store.ClaimAsync(trialId, tournamentId, missing, cancellationToken).ConfigureAwait(false); + await store.ClaimAsync(trialId, tournamentId, missing, fingerprint, cancellationToken).ConfigureAwait(false); } using var failed = new CancellationTokenSource(); @@ -155,7 +160,7 @@ internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore stor var unit = PooledTrialUnits.Guarded(key, execute, failed); return (unit, TrialUnitOutcomes.Encode(unit), watch.Elapsed.TotalSeconds); }).ConfigureAwait(false); - await store.DoneAsync(trialId, key, outcome, seconds, cancellationToken).ConfigureAwait(false); + await store.DoneAsync(trialId, key, outcome, seconds, fingerprint, cancellationToken).ConfigureAwait(false); return result; } @@ -354,34 +359,77 @@ public static class TrialUnitStatuses } /// 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); +public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId) +{ + /// What the unit was computed on (). + public string? Fingerprint { get; init; } +} /// /// 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. +/// done with its outcome, so a trial stopped halfway runs again only what it had not finished. Every row keeps what it was +/// computed on (): a unit done on other data, by another engine or another build of Anubis is not +/// reused. A plain trial drops its outcomes when it ends (, ); +/// 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. + /// The engine and the code that compute a unit, the second half of : the version of the engine and + /// the identity of this build of Anubis, which changes with any change to its code. /// - public async Task> ResumeAsync(Guid trialId, CancellationToken cancellationToken) + public static string Build { get; } = "|" + BacktestEngine.Version + "|" + typeof(BacktestEngine).Assembly.ManifestModule.ModuleVersionId.ToString("N"); + + /// What the units of are computed on: the fingerprint of the data it read, then . + public static string Fingerprint(ITrialEngine engine) { + ArgumentNullException.ThrowIfNull(engine); + return engine.Fingerprint() + Build; + } + + /// + /// A trial that starts, or starts again after a restart: the units left running (their work was lost with the process), + /// those without an outcome and those done on another are dropped, so they run again; the + /// outcomes of the units done on the same one are returned by key. + /// + public Task> ResumeAsync(Guid trialId, string fingerprint, CancellationToken cancellationToken) => + ResumeAsync(trialId, (_, stored) => stored == fingerprint, cancellationToken); + + /// + /// The same, when the units of a trial were computed on different inputs (the judge of a tournament): a unit done is kept + /// when says so for its kind (as the database keeps it) and its stored fingerprint. + /// + public async Task> ResumeAsync(Guid trialId, Func current, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(current); var rows = await db.WriteAsync(async s => { await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND (status <> @d OR outcome IS NULL)", cancellationToken, ("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false); - return await s.QueryAsync("SELECT unit_key, outcome FROM tournament_units WHERE trial_id = @t AND status = @d", - r => (Key: r.Text("unit_key"), Outcome: r.Bytes("outcome")), ("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false); + var done = await s.QueryAsync("SELECT unit_key, kind, fingerprint, outcome FROM tournament_units WHERE trial_id = @t AND status = @d", + r => (Key: r.Text("unit_key"), Kind: r.Text("kind"), Fingerprint: r.TextOrNull("fingerprint"), Outcome: r.Bytes("outcome")), + ("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false); + var kept = new List<(string Key, byte[] Outcome)>(done.Count); + foreach (var row in done) + { + if (current(row.Kind, row.Fingerprint)) + { + kept.Add((row.Key, row.Outcome)); + } + else + { + await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND unit_key = @k", cancellationToken, ("t", trialId), ("k", row.Key)) + .ConfigureAwait(false); + } + } + + return kept; }, cancellationToken).ConfigureAwait(false); return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal); } - /// 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) + /// Claims the units about to run, in one transaction, with what they are computed on. A unit already claimed stays as it is. + public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList keys, string fingerprint, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(keys); return db.WriteAsync(async s => @@ -389,21 +437,21 @@ public sealed class TrialUnitStore(Database db, IClock clock) foreach (var key in keys) { await s.ExecuteAsync( - "INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @now) " + + "INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @f, @now) " + "ON CONFLICT (trial_id, unit_key) DO NOTHING", cancellationToken, ("id", Ids.NewId(clock)), ("t", trialId), ("tour", tournamentId), ("k", key.Text), ("kind", key.KindText), - ("r", TrialUnitStatuses.Running), ("now", clock.UtcNow)).ConfigureAwait(false); + ("r", TrialUnitStatuses.Running), ("f", fingerprint), ("now", clock.UtcNow)).ConfigureAwait(false); } }, cancellationToken); } - /// A unit done: its outcome and the seconds it took. - public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, CancellationToken cancellationToken) + /// A unit done: its outcome, the seconds it took and what it was computed on. + public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, string fingerprint, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(key); return db.WriteAsync(s => s.ExecuteAsync( - "UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r", - cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text), + "UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, fingerprint = @f, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r", + cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("f", fingerprint), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text), ("r", TrialUnitStatuses.Running)), cancellationToken); } @@ -418,8 +466,11 @@ public sealed class TrialUnitStore(Database db, IClock clock) /// 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", + "SELECT unit_key, kind, status, outcome, seconds, tournament_id, fingerprint FROM tournament_units WHERE trial_id = @t ORDER BY id", r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), - r.IdOrNull("tournament_id")), + r.IdOrNull("tournament_id")) + { + Fingerprint = r.TextOrNull("fingerprint"), + }, ("t", trialId)), cancellationToken).ConfigureAwait(false); } diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 568fd7f..c313b1b 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -238,6 +238,11 @@ public sealed class TrialStore(Database db, IClock clock) await db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @r, started_at = @now WHERE id = @id AND status = @p", cancellationToken, ("r", TrialStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned)), cancellationToken).ConfigureAwait(false) == 1; + /// The tournament of a finished trial; null when the trial is not finished or belongs to none. The plan is not read. + public Task FinishedTournamentAsync(Guid id, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT tournament_id FROM backtest_trials WHERE id = @id AND status IN (@d, @f)", r => r.IdOrNull("tournament_id"), + ("id", id), ("d", TrialStatuses.Done), ("f", TrialStatuses.Failed)), cancellationToken); + /// 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(async s => diff --git a/src/Anubis/Db/Migrations/0016_tournaments.sql b/src/Anubis/Db/Migrations/0016_tournaments.sql index bcf6125..7652285 100644 --- a/src/Anubis/Db/Migrations/0016_tournaments.sql +++ b/src/Anubis/Db/Migrations/0016_tournaments.sql @@ -19,7 +19,8 @@ CREATE INDEX tournaments_status ON tournaments (status); -- One engine execution of a trial of the laboratory (a variant, a costed run, the benchmark, the look-ahead check), so a -- trial stopped halfway runs again only what it had not finished. The outcome is the gzip of its JSON; a plain trial --- (tournament_id NULL) drops it when it ends, the row stays as a record. +-- (tournament_id NULL) drops it when it ends, the row stays as a record. The fingerprint is what the unit was computed on +-- (the data, the engine version, the build): a unit done on other inputs is not reused. CREATE TABLE tournament_units ( id {uuid} PRIMARY KEY, trial_id {uuid} NOT NULL REFERENCES backtest_trials (id), @@ -27,6 +28,7 @@ CREATE TABLE tournament_units ( unit_key TEXT NOT NULL, kind TEXT NOT NULL, status TEXT NOT NULL, + fingerprint TEXT, outcome {bytes}, seconds {float}, created_at {timestamp} NOT NULL, diff --git a/tests/Anubis.Tests/ArchiveTests.cs b/tests/Anubis.Tests/ArchiveTests.cs index 99ed401..fbaef41 100644 --- a/tests/Anubis.Tests/ArchiveTests.cs +++ b/tests/Anubis.Tests/ArchiveTests.cs @@ -47,7 +47,7 @@ public sealed class ArchiveTests "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)", + "INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', 'abc|2|def', @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/TournamentTests.cs b/tests/Anubis.Tests/TournamentTests.cs index 906b9d2..e38005a 100644 --- a/tests/Anubis.Tests/TournamentTests.cs +++ b/tests/Anubis.Tests/TournamentTests.cs @@ -2,7 +2,10 @@ using System.Globalization; using Anubis.Backtest; using Anubis.Core; using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; using Anubis.Strategies; +using Anubis.Trading; namespace Anubis.Tests; @@ -350,6 +353,193 @@ public sealed class TournamentTests } } + /// + /// The repetitions of the control done before a stop by another build (or on other data) are not reused: the judge started + /// again runs every repetition, so the control of a finalist is never a mix of two engines. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AResumedJudgingRunsAgainTheControlUnitsOfAnotherBuild() + { + var clock = new ManualClock(Now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var field = Small(); + using var lab = Lab(test, clock, field); + var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none) + .ConfigureAwait(false); + var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false); + var plan = tournament.Plan; + var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart()); + var replicas = Enumerable.Range(0, plan.Control.Repetitions) + .ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal); + + // The judge stops while the eighth repetition of the control runs, after at least five are recorded. + using var stop = new CancellationTokenSource(); + lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), [], replicas, p.Data.Symbols[0], null, n => + { + if (n == 8) + { + for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++) + { + Thread.Sleep(20); + } + + stop.Cancel(); + } + }); + await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false); + await Assert.ThrowsAsync(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false); + Assert.IsGreaterThanOrEqualTo(5, DoneControls(test, tournament.Id)); + + // They were computed by another build. + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournament_units SET fingerprint = @f WHERE tournament_id = @t AND kind = @k", _none, + ("f", "altra|2|build"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false); + + var after = new List(); + lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null); + await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false); + var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error); + var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList(); + Assert.HasCount(2 * plan.Control.Repetitions, controls, "Every repetition runs again."); + Assert.HasCount(2 * plan.Control.Repetitions, controls.Distinct().ToList()); + Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList()); + var fingerprints = await test.Db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT fingerprint FROM tournament_units WHERE tournament_id = @t AND kind = @k", + r => r.Text("fingerprint"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false); + Assert.HasCount(2, fingerprints, "One fingerprint for the search data of each finalist."); + Assert.IsTrue(fingerprints.All(f => f.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal))); + } + + /// + /// The plan of a tournament that no longer reads (changed by hand, or after an update that cannot read it) fails the + /// tournament with a reason in Italian, when its last contender finishes and when it is found being judged at a start; the + /// laboratory goes on with the rest of the queue. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnUnreadableTournamentPlanFailsTheTournamentAndTheQueueGoesOn() + { + const string Unreadable = "Il piano registrato del campionato non si può più leggere: il campionato non si giudica."; + var clock = new ManualClock(Now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + using var lab = Lab(test, clock, Small()); + var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)); + + var broken = await lab.PlanTournamentAsync(request with { Name = "Illeggibile" }, _none).ConfigureAwait(false); + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan = @p WHERE id = @id", _none, ("p", new DbJson("[1]")), ("id", broken.Id)), _none) + .ConfigureAwait(false); + await RunAllAsync(lab, broken.Id).ConfigureAwait(false); + Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false)); + + // Found being judged at a start: it fails again, and the trials of the queue run and are judged. + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @j, error = NULL, finished_at = NULL WHERE id = @id", _none, + ("j", TournamentStatuses.Judging), ("id", broken.Id)), _none).ConfigureAwait(false); + var good = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false); + using var run = new CancellationTokenSource(); + var running = lab.RunAsync(run.Token); + for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!.IsFinished && !running.IsCompleted; i++) + { + await Task.Delay(50).ConfigureAwait(false); + } + + Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped."); + await run.CancelAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(() => running).ConfigureAwait(false); + var judged = (await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TournamentStatuses.Done, judged.Status, judged.Error); + Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false)); + } + + /// + /// The database refuses every change of the tournament while its last contender finishes, so neither the judge nor the + /// record of its failure can write: the queue goes on, and the trial that comes back to it after the pause brings the + /// tournament to its judge, though the trial itself is finished. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ARequeuedFinishedContenderStillReachesTheJudge() + { + var clock = new ManualClock(Now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + using var lab = Lab(test, clock, Small()); + var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none) + .ConfigureAwait(false); + var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false); + await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false); + + await RefuseTournamentChangesAsync(test, true).ConfigureAwait(false); + using var run = new CancellationTokenSource(); + var running = lab.RunAsync(run.Token); + for (var i = 0; i < 1200 && clock.Waiting == 0 && !running.IsCompleted; i++) + { + await Task.Delay(50).ConfigureAwait(false); + } + + Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped."); + Assert.AreEqual(1, clock.Waiting, "The queue waits before trying again."); + Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(trials[1].Id, _none).ConfigureAwait(false))!.Status); + Assert.AreEqual(TournamentStatuses.Running, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status); + + // The database is back: after the pause the finished trial comes back to the queue and the tournament is judged. + await RefuseTournamentChangesAsync(test, false).ConfigureAwait(false); + clock.Advance(Laboratory.RetryDelay); + for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++) + { + await Task.Delay(50).ConfigureAwait(false); + } + + await run.CancelAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(() => running).ConfigureAwait(false); + var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error); + } + + /// + /// The judge checks that every contender trial is the one the plan of the tournament wrote: a trial plan changed by hand + /// (its hash no longer matches) or rewritten with its hash on another capital, grid, slippage, source or reference share + /// fails the tournament. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AContenderTrialWhosePlanChangedFailsTheTournament() + { + var clock = new ManualClock(Now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + using var lab = Lab(test, clock, Small()); + var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)); + + var tampered = await lab.PlanTournamentAsync(request with { Name = "Impronta" }, _none).ConfigureAwait(false); + var last = (await lab.Trials.OfTournamentAsync(tampered.Id, _none).ConfigureAwait(false))[1]; + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", last.Id)), _none) + .ConfigureAwait(false); + await RunAllAsync(lab, tampered.Id).ConfigureAwait(false); + var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TournamentStatuses.Failed, refused.Status); + Assert.AreEqual("Il piano registrato della prova di «b» non corrisponde più alla sua impronta: il campionato non si giudica.", refused.Error); + + (string Name, Func Change)[] changes = + [ + ("Capitale", p => p with { InitialCapital = 20_000m }), + ("Griglia", p => p with { Grid = new Dictionary> { ["entry"] = [1m], ["lookback"] = [30m] } }), + ("Slittamento", p => p with { Slippage = new SlippageTable(9m, 9m, 25m) }), + ("Origine", p => p with { Data = p.Data with { Source = TrialSources.Research } }), + ("Quota", p => p with { ReferenceShare = 0.5m }), + ]; + foreach (var (name, change) in changes) + { + var tournament = await lab.PlanTournamentAsync(request with { Name = name }, _none).ConfigureAwait(false); + var trial = (await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false))[1]; + var json = change(trial.Plan).ToJson(); + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan = @p, plan_hash = @h WHERE id = @id", _none, + ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("id", trial.Id)), _none).ConfigureAwait(false); + Assert.IsTrue((await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.PlanIntact, name); + await RunAllAsync(lab, tournament.Id).ConfigureAwait(false); + var failed = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!; + Assert.AreEqual(TournamentStatuses.Failed, failed.Status, name); + Assert.AreEqual("Le prove del campionato non corrispondono al suo piano.", failed.Error, name); + } + } + [TestMethod] [TestCategory(Category.Unit)] public void TheFinalistsAreTheBestOfEachGroupAndMarketAndAtMostEight() @@ -519,6 +709,30 @@ public sealed class TournamentTests r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), r.IdOrNull("tournament_id")), ("t", tournament)), _none).ConfigureAwait(false); + /// State and error of a tournament, read without its plan. + private static Task<(string Status, string? Error)> StateAsync(TestDb test, Guid id) => + test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT status, error FROM tournaments WHERE id = @id", r => (r.Text("status"), r.TextOrNull("error")), ("id", id))); + + /// Makes the database refuse, or accept again, every change of a row of the tournaments: a trigger on both engines. + private static Task RefuseTournamentChangesAsync(TestDb test, bool refuse) => test.Db.WriteAsync(async s => + { + string[] statements = (test.Db.Engine, refuse) switch + { + (DbEngine.Sqlite, true) => ["CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments BEGIN SELECT RAISE(ABORT, 'database non raggiungibile'); END"], + (DbEngine.Sqlite, false) => ["DROP TRIGGER refuse_tournaments"], + (_, true) => + [ + "CREATE FUNCTION refuse_tournaments() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'database non raggiungibile'; END $$", + "CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments FOR EACH ROW EXECUTE FUNCTION refuse_tournaments()", + ], + (_, false) => ["DROP TRIGGER refuse_tournaments ON tournaments", "DROP FUNCTION refuse_tournaments()"], + }; + foreach (var sql in statements) + { + await s.ExecuteAsync(sql, _none).ConfigureAwait(false); + } + }, _none); + private static Task<(string Plan, string Hash)> RawPlanAsync(TestDb test, Guid id) => test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM tournaments WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id))); diff --git a/tests/Anubis.Tests/TrialUnitTests.cs b/tests/Anubis.Tests/TrialUnitTests.cs index dd27edb..edf59db 100644 --- a/tests/Anubis.Tests/TrialUnitTests.cs +++ b/tests/Anubis.Tests/TrialUnitTests.cs @@ -252,6 +252,72 @@ public sealed class TrialUnitTests Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials."); } + /// + /// A trial stopped halfway whose bars change before the next start (a bar collected again, a corporate action): the units + /// done on the old bars are not reused, every unit runs again on the new ones and the report is that of a run without a stop. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task UnitsComputedOnOtherDataAreRunAgainOnResume() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var btc = await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false); + using var lab = new Laboratory(test.Db, clock, Path.GetTempPath()); + var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false); + var family = StrategyCatalog.Find(trial.Strategy)!; + var before = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false); + + // 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); + var finished = (await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false)).Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList(); + Assert.IsGreaterThanOrEqualTo(2, finished.Count); + + // The bars are collected again with other prices before the next start. + await new BarStore(test.Db, clock).UpsertDailyAsync(btc.Id, BacktestData.Walk(400, 4, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)), + "test", _none).ConfigureAwait(false); + var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false); + Assert.AreNotEqual(before.Fingerprint(), data.Fingerprint()); + var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report; + + CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id); + 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, second, "Every unit runs again on the new bars."); + foreach (var key in finished) + { + CollectionAssert.Contains(second, CallOf(key), "A unit done on the old bars 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()); + + // Every unit keeps what it was computed on: the new bars, the engine and this build. + var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false); + Assert.HasCount(total, rows); + Assert.IsTrue(rows.All(r => r.Fingerprint == data.Fingerprint() + TrialUnitStore.Build), string.Join(", ", rows.Select(r => r.Fingerprint))); + StringAssert.StartsWith(TrialUnitStore.Build, "|" + BacktestEngine.Version + "|"); + } + [TestMethod] [TestCategory(Category.Unit)] public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors() @@ -279,6 +345,7 @@ public sealed class TrialUnitTests await server.SignInFirstTimeAsync(); var page = await server.TextAsync("/impostazioni"); StringAssert.Contains(page, "Operai del Laboratorio"); + StringAssert.Contains(page, "Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta."); StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading"); StringAssert.Contains(page, "Vale dalla prossima prova.");