Fix what the independent review of Phase 8 found and close the phase
ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s

Two reviewers with a clean context read the engine and the screens. The
isotonic calibration took its floor from the first step, even of two cases, so
with few winners it flattened every estimate: the first model is rebuilt with
the fix. Learning failures no longer forget the multiplier an operation was
born with, nor stop a decision or the nightly check; recovered decisions read
the outside world as it was when due; models estimate only the strategies they
studied; a newer history does not repeat what was lived. The screens count
examples instead of verifications, show the next threshold and never round an
alarm to 50%; two forms now check the antiforgery token.

Each defect has its test, on both engines. ADR 0018 point 17 has the list.

refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 13:36:26 +01:00
1 parent f69943f70a
commit 0b0f4a5e75
33 files changed
+659 -145

No files matched your search

@@ -98,6 +98,18 @@ public sealed class LaboratoryScreenTests
}
var confirmed = await PendingAsync(8m);
// Without the token of the page nothing is decided.
using (var forged = await server.Http.PostAsync(new Uri($"/azioni/stime-di-costo/{confirmed}/conferma", UriKind.Relative), new FormUrlEncodedContent([])))
{
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, forged.StatusCode);
}
using (var seen = await server.Http.PostAsync(new Uri($"/azioni/assenza/{confirmed}/vista", UriKind.Relative), new FormUrlEncodedContent([])))
{
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, seen.StatusCode);
}
using (var yes = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{confirmed}/conferma", []))
{
Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(yes));
+1 -1
View File
@@ -16,7 +16,7 @@ public sealed class LearningCycleTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateOnly From = new(2026, 6, 1);
internal static readonly DateOnly From = new(2026, 6, 1);
/// <summary>A model that always answers <paramref name="probability"/>.</summary>
internal static TrainedModel Always(double probability) => new()
+1 -1
View File
@@ -148,7 +148,7 @@ public sealed class LearningModelTests
[TestMethod]
public void IsotonicNeverGoesDown()
{
var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true]);
var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true], 1);
Assert.AreEqual(0.5, known.Probability(2.5), 1e-9);
var gen = new Gen(4);
var scores = Enumerable.Range(0, 1500).Select(_ => gen.Normal()).ToList();
+1 -1
View File
@@ -86,7 +86,7 @@ public sealed class LearningMoreTests
var row = (await book.ListAsync(_none).ConfigureAwait(false)).Single();
Assert.AreEqual((SlippageTiers.Major, CostStatuses.Applied, 5m, 7.5m, 40), (row.Tier, row.Status, row.PreviousBp, row.Bp, row.Cases));
Assert.AreEqual(SlippageTable.Standard with { Major = 7.5m }, await book.TableAsync(_none).ConfigureAwait(false));
Assert.AreEqual("Scostamento misurato su 40 esecuzioni (Bitcoin, Ethereum e Solana): 7,2 punti base invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.",
Assert.AreEqual("Scostamento misurato su 40 esecuzioni (Bitcoin, Ethereum e Solana): 7,2 punti base (centesimi di punto percentuale) invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.",
(await NewsRulesTests.DiaryAsync(rig.Db).ConfigureAwait(false))[^1]);
// The next month the estimate in force is the new one: nothing to say.
+279
View File
@@ -0,0 +1,279 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>What the independent review of Phase 8 found (issue #67): each defect has the case that shows it.</summary>
[TestClass]
public sealed class LearningReviewTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4, [StrategyNames.EquityMomentum] = 0.5 } };
/// <summary>The same stretch of days as the tests of the cycle, with entries inside.</summary>
private static readonly DateOnly From = LearningCycleTests.From;
/// <summary>With few winners the lowest step is one or two losses: it must not become the floor of every other one.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheIsotonicCalibrationOrdersEvenWhenWinnersAreFew()
{
var gen = new Gen(23);
var scores = Enumerable.Range(0, 1800).Select(_ => gen.Normal()).ToList();
double Truth(double s) => 0.03 + (0.30 * Odds.Probability(2 * s));
var wins = scores.Select(s => gen.Double() < Truth(s)).ToList();
// The two smallest scores lose and the largest wins, as in the history that was shipped.
scores.AddRange([-9, -8, 9]);
wins.AddRange([false, false, true]);
var fitted = Calibration.Fit(scores, wins);
Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind);
Assert.AreEqual((double)wins.Count(w => w) / wins.Count, scores.Average(fitted.Probability), 0.01, "on the whole it says the base rate");
foreach (var s in new[] { -1.5, -0.5, 0, 0.5, 1.5 })
{
Assert.AreEqual(Truth(s), fitted.Probability(s), 0.07, $"at {s}");
}
Assert.IsTrue(fitted.Probability(-20) is > 0.02 and < 0.15 && fitted.Probability(20) is > 0.2 and < 0.5, "one case at the edge says nothing");
}
/// <summary>The model shipped must tell signals apart, and be as well calibrated as 11.5 asks on cases it had not studied.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFirstModelTellsSignalsApart()
{
var file = FirstModel.Embedded!;
var rate = file.BaseRates[StrategyNames.CryptoTrend];
var said = file.Examples.Where(e => e.IsLabelled).Select(e => file.Model!.Probability(e.Features)).ToList();
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p < rate - 0.01));
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p > rate + 0.01));
Assert.AreEqual(rate, said.Average(), 0.02);
var verified = file.Report!.Chosen!.Combined;
Assert.IsLessThan(ActivationCheck.MaxCalibrationError, verified.CalibrationError!.Value);
Assert.AreEqual(file.Report.Examples, verified.Bands.Sum(b => b.Cases), 10, "an example verified five times is one case");
}
/// <summary>Five combinations verify the same thirty examples: the band has thirty cases, not one hundred and fifty.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AnExampleVerifiedFiveTimesIsOneCase()
{
var cases = Enumerable.Range(0, 30).Select(i => Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with { Label = new CaseLabel(i < 6, 0.1, From.AddDays(i + 1), From.AddDays(i + 9), "x") }).ToList();
var band = Judge.Bands([.. Enumerable.Range(0, 5).SelectMany(_ => cases.Select(c => new Estimate(c, 0.22, 0.2, 1)))]).Single();
Assert.AreEqual(30, band.Cases);
Assert.AreEqual(0.2, band.Observed, 1e-9);
}
/// <summary>SPEC 11.1: who knows nothing of a strategy leaves its operations as they are, even when it has a base rate.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AModelEstimatesOnlyTheStrategiesItStudied()
{
ModelRow Row(string status, params string[] studied) => new(Guid.NewGuid(), 1, LearnerNames.Logistic, status, "test", default, 500, 0, null, LearningCycleTests.Always(0.1) with { Strategies = studied }, new ModelReport());
Example Case(string strategy) => new(Guid.NewGuid(), strategy, "X", CaseSources.Live, From, default, "x", 0.2m, null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
var gate = new ModelGate(Row(ModelStatuses.Champion, StrategyNames.CryptoTrend), Row(ModelStatuses.Challenger, StrategyNames.CryptoTrend, StrategyNames.EquityMomentum), MultiplierRule.Standard, Rates.BaseRates, true);
Assert.HasCount(2, gate.Estimate(Case(StrategyNames.CryptoTrend)));
var only = gate.Estimate(Case(StrategyNames.EquityMomentum)).Single();
Assert.IsFalse(only.InCharge, "the one in charge has nothing to say");
Assert.HasCount(0, gate.Estimate(Case(StrategyNames.EquityMeanrev)), "no base rate");
}
private static async Task<string> FillsAsync(LiveRig rig) => string.Join('\n', await rig.Rig.QueryAsync(
"SELECT i.symbol, f.side, f.quantity, f.executed_at FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, i.symbol",
r => $"{r.Text("symbol")} {r.Text("side")} {r.Money("quantity")} {r.Moment("executed_at"):MM-dd HH:mm}").ConfigureAwait(false));
private static async Task<(string Fills, int Failures)> RunAsync(Func<LiveRig, DateOnly, Task>? before = null)
{
var last = From.AddDays(20);
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
rig.UseFirst(Rates);
await LearningCycleTests.AddModelAsync(rig.Rig.Db, rig.Rig.Clock, LearningCycleTests.Always(0.35), ModelStatuses.Champion).ConfigureAwait(false);
await rig.Rig.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, rig.Rig.Clock, CycleState.Key, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }, _none), _none).ConfigureAwait(false);
for (var day = From; day <= last; day = day.AddDays(1))
{
if (before is not null)
{
await before(rig, day).ConfigureAwait(false);
}
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
return (await FillsAsync(rig).ConfigureAwait(false), rig.Failures);
}
private static Task<int> ExecuteAsync(LiveRig rig, string sql, params (string, object?)[] parameters) => rig.Rig.Db.WriteAsync(s => s.ExecuteAsync(sql, _none, parameters), _none);
/// <summary>
/// SPEC 11.1: the multiplier of birth holds to the close. The world outside cannot be read any more, or the clues of the
/// archive are damaged: operations born halved must trade as before, not be bought whole.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFailureOfLearningNeverForgetsTheMultiplierOfBirth()
{
var (whole, _) = await RunAsync().ConfigureAwait(false);
var (blind, failures) = await RunAsync((rig, day) => day == From.AddDays(10) ? ExecuteAsync(rig, "ALTER TABLE market_mood RENAME TO market_mood_away") : Task.CompletedTask).ConfigureAwait(false);
Assert.AreEqual((whole, 0), (blind, failures), "without the outside");
var (damaged, again) = await RunAsync((rig, day) => day >= From.AddDays(10) ? ExecuteAsync(rig, "UPDATE ml_features SET features = @j", ("j", new DbJson("\"damaged\""))) : Task.CompletedTask)
.ConfigureAwait(false);
Assert.AreEqual((whole, 0), (damaged, again), "with damaged clues");
}
/// <summary>ADR 0018, point 2: a failure while saving the examples takes back only the examples, on both engines.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnExampleThatCannotBeSavedNeverStopsTheDecision()
{
var runs = 0L;
var kept = 0L;
var (fills, failures) = await RunAsync(async (rig, day) =>
{
if (day == From)
{
await ExecuteAsync(rig, "ALTER TABLE ml_predictions RENAME TO ml_predictions_away").ConfigureAwait(false);
}
runs = await rig.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM engine_runs"), _none).ConfigureAwait(false);
kept = await rig.Learning.Store.CountAsync(CaseSources.Live, _none).ConfigureAwait(false);
}).ConfigureAwait(false);
Assert.AreEqual(0, failures);
Assert.IsGreaterThan(15, runs, "one decision a day");
Assert.AreEqual(0, kept, "the examples were taken back whole");
Assert.IsGreaterThan(0, fills.Length);
}
/// <summary>SPEC 11.2, 5.6: a decision recovered in the afternoon must not know more than the operation that started at midnight.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue()
{
var last = From.AddDays(20);
DateOnly born;
await using (var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false))
{
rig.UseFirst(Rates);
for (var day = From; day <= last; day = day.AddDays(1))
{
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
born = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day > From.AddDays(2)).Day;
}
await using var late = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
late.UseFirst(Rates);
for (var day = From; day <= born; day = day.AddDays(1))
{
await late.DayAsync(day, morning: 8).ConfigureAwait(false);
}
// Off until the afternoon after the close: at noon a value of the mood was published and saved.
var midnight = new DateTimeOffset(born.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
await late.StoreBarAsync(born).ConfigureAwait(false);
var mood = new MoodStore(late.Rig.Db, late.Rig.Clock);
await mood.UpsertAsync([new(MoodIndicators.Vix, midnight.AddHours(-10), 18, null, "t")], _none).ConfigureAwait(false);
late.Rig.Clock.Set(midnight.AddHours(12));
await mood.UpsertAsync([new(MoodIndicators.FearGreed, midnight.AddHours(11), 99, null, "t")], _none).ConfigureAwait(false);
late.Rig.Clock.Set(midnight.AddHours(15));
late.Quotes(born.AddDays(1), b => b.Close);
await late.MinutesAsync(5).ConfigureAwait(false);
var example = (await late.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day == born);
Assert.IsFalse(example.Features.ContainsKey(Clues.FearGreed), "published after the operation had started");
Assert.AreEqual(18d, example.Features[Clues.Vix], "known when it was due");
}
/// <summary>A strategy whose labels cannot be made must not keep a model that counts from being checked.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ALabelThatFailsDoesNotStopTheCheck()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero));
var desk = new LearningDesk(rig.Db, rig.Clock) { First = Rates };
await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From), _none), _none).ConfigureAwait(false);
var cycle = new LearningCycle(rig.Db, rig.Clock, desk, (_, _, _) => throw new InvalidDataException("bars"));
await Assert.ThrowsExactlyAsync<AggregateException>(() => cycle.RunAsync(_none)).ConfigureAwait(false);
var state = await desk.CycleAsync(_none).ConfigureAwait(false);
Assert.AreEqual(new DateOnly(2027, 3, 3), state.LastNight);
Assert.AreEqual(1, state.Health!.Version);
Assert.IsNotNull(state.LastSunday);
}
private static Example Open(string strategy, string symbol, DateOnly day) => new(Guid.Empty, strategy, symbol, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "x", 0.2m,
null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
/// <summary>SPEC 5.6: the computer slept for twenty hours with the process alive; the night is made once at the waking.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheNightIsMadeAfterALongSleep()
{
var clock = new ManualClock(new DateTimeOffset(2027, 3, 3, 0, 0, 0, TimeSpan.Zero));
var runs = 0;
var scheduler = new Scheduler(clock, new EventBus());
scheduler.Add(TradingService.ModelJob(_ =>
{
runs++;
return Task.CompletedTask;
}), clock.UtcNow);
clock.Set(new DateTimeOffset(2027, 3, 3, 22, 0, 0, TimeSpan.Zero));
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
for (var i = 0; i < 200 && runs == 0; i++)
{
await Task.Delay(20, _none).ConfigureAwait(false);
}
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
Assert.AreEqual(1, runs);
}
/// <summary>SPEC 11.2: one example for each potential operation, even when a newer history reaches days already lived.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ANewerHistoryDoesNotCountTwiceWhatWasLived()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From) with { Label = new CaseLabel(true, 0.1, From.AddDays(1), From.AddDays(20), "x") }, _none), _none)
.ConfigureAwait(false);
Example Past(string symbol, int from, int to) => Open(StrategyNames.CryptoTrend, symbol, From.AddDays(from)) with
{
Id = Guid.NewGuid(),
Source = CaseSources.History,
Label = new CaseLabel(false, -0.1, From.AddDays(from + 1), From.AddDays(to), "x"),
};
var desk = new LearningDesk(rig.Db, rig.Clock)
{
First = new FirstModelFile { Examples = [Past("BTCEUR", 1, 19), Past("BTCEUR", -3, 5), Past("BTCEUR", -30, 0), Past("BTCEUR", 20, 30), Past("ETHEUR", 1, 19)] },
};
await desk.PrepareHistoryAsync(_none).ConfigureAwait(false);
var kept = (await desk.Store.AllAsync(_none).ConfigureAwait(false)).Where(e => e.Source == CaseSources.History).Select(e => e.Symbol + (e.Day.DayNumber - From.DayNumber)).Order(StringComparer.Ordinal);
Assert.AreEqual("BTCEUR-30 BTCEUR20 ETHEUR1", string.Join(' ', kept));
}
/// <summary>The label leaves before the report the decision knew of, whatever the calendar says months later.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportOfALabelIsTheOneKnownAtTheDecision()
{
Example With(string strategy, double? days) => Open(strategy, "AAPL", From) with { Features = days is { } d ? new Dictionary<string, double> { [Clues.EarningsDays] = d } : [] };
Assert.AreEqual(From.AddDays(6), Clues.ReportOf(With(StrategyNames.EquityMeanrev, 6)));
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, Clues.FarReport)));
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, null)));
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMomentum, 6)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APrecisionUnderTheAlarmNeverReadsFiftyPercent()
{
Assert.AreEqual((49, 49, 50, 45, 56), (Health.Shown(0.4999), Health.Shown(0.496), Health.Shown(0.5), Health.Shown(0.451), Health.Shown(0.556)));
Assert.AreEqual("Precisione scesa al 49% su 41 casi.", LearningCycle.AsideText(AsideCodes.Precision, new HealthCheck { Precision = 0.4967, Cases = 41 }));
}
}
+46 -4
View File
@@ -54,6 +54,19 @@ public sealed class LearningScreenTests
Assert.IsFalse(page.Contains("/azioni/modello", StringComparison.Ordinal), "nothing to change in the demo");
HasAll(await server.TextAsync("/"), "Il modello osserva e impara, ma non decide ancora.", "su 300 necessari", "56% su dati mai visti", "domenica 11 ottobre, 03:00");
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%): solo osservazione, non ha cambiato la dimensione");
// The signal was born three days before the purchase, held back meanwhile: same example, same estimate.
var (db, clock) = (server.Host.Services!.Db, server.Host.Clock);
var earlier = Ids.NewId(clock);
await db.WriteAsync(async s =>
{
var at = (await s.FirstOrDefaultAsync("SELECT created_at FROM decisions WHERE stage = 'model' AND symbol = 'MSFT'", r => (DateTimeOffset?)r.Moment("created_at")))!.Value.AddDays(-3);
await s.ExecuteAsync("UPDATE decisions SET decision_id = @d, created_at = @at WHERE stage = 'model' AND symbol = 'MSFT'", _none, ("d", earlier), ("at", at));
await LearningStore.AddAsync(s, clock, new Example(Guid.Empty, StrategyNames.EquityMeanrev, "MSFT", CaseSources.Live, DateOnly.FromDateTime(at.UtcDateTime), at, "x", 0.2m, null, null,
new Dictionary<string, double>())
{ DecisionId = earlier }, _none);
}, _none);
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
using var post = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
Assert.AreEqual("/apprendimento?errore=motore", ServerHarness.Location(post));
using var settings = await server.PostFormAsync("/impostazioni", "/azioni/modello", (LearningSettings.Aside.Key, "on"));
@@ -118,7 +131,7 @@ public sealed class LearningScreenTests
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { Health = new HealthCheck { At = clock.UtcNow, Precision = 1, Cases = 60 } }, _none);
}, _none);
var page = await server.TextAsync("/apprendimento");
HasAll(page, "<strong>120</strong> <span class=\"muted\">su 300 necessari</span>", "Sfidante, versione 2", "120 su 150", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto.",
HasAll(page, "<strong>120</strong> <span class=\"muted\">su 300 necessari</span>", "Sfidante, versione 2", "120 su 100", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto. Si decide ",
"Prossima verifica dello sfidante", "Al ritmo attuale, tra", "tra 45% e 50%", "Precisione sugli ultimi 60 casi: 100%, sopra il", "Nessun allarme finora", "Nessuna anomalia");
Assert.IsFalse(page.Contains("Per ora sono i casi storici", StringComparison.Ordinal), "the live bands count now");
Assert.IsFalse(page.Contains("Annulla l'ultima promozione", StringComparison.Ordinal));
@@ -247,6 +260,10 @@ public sealed class LearningScreenTests
events: [new ModelEvent(ModelEvents.SetAside, 1, "a", Now.AddDays(-20)), new ModelEvent(ModelEvents.Back, 1, "b", Now.AddDays(-17))], models: champion);
StringAssert.EndsWith(back.Checks[^1].Text, "Ultimo controllo oggi alle 03:21. Ultimo allarme il 19 settembre, rientrato in 3 giorni");
Assert.AreEqual("wait", back.Checks[0].State, "too few live signals to compare the market");
// A check of another version says nothing of the one in charge now.
var changed = View(new CycleState { Health = health with { Version = 7 } }, models: champion);
StringAssert.StartsWith(changed.Checks.Single().Text, "Il modello in carica è cambiato: il primo controllo è alle 03:00.");
Assert.IsTrue(View(new CycleState { Health = health with { DriftingClues = ["Volumi scambiati"] } }, models: champion).Checks[0] is { State: "warn" });
}
@@ -279,6 +296,28 @@ public sealed class LearningScreenTests
Assert.AreEqual("Al ritmo attuale, più di un anno.", LearningView.PaceWords(80));
}
/// <summary>What is shown as happened is counted, not weighed by maturation.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheBandsSayWhatReallyHappened()
{
var champion = Row(ModelStatuses.Champion, 1);
var view = View(new CycleState(), estimates: [.. Enumerable.Range(0, 20).Select(i => Seen(champion.Id, 3, i == 0, 0.41))], models: champion);
Assert.AreEqual(new LearningBand(40, 45, 20, 41, 5), view.Bands.Single());
Assert.IsFalse(view.BandsFromHistory);
}
/// <summary>What the trade card says when the model would count but is set aside.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTradeCardSaysWhyTheModelChangedNothing()
{
string Line(string tail) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":1" + tail + "}")!;
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":true"), ": era messo da parte, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":false"), ": solo osservazione, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":true,\"aside\":false"), ": taglia piena");
}
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
@@ -333,9 +372,12 @@ public sealed class LearningScreenTests
StringAssert.StartsWith(few.TrialText, "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100");
StringAssert.StartsWith(View(new CycleState(), estimates: Pairs(1, false), models: [champion, challenger]).TrialText, "Per ora non sembra meglio, e ha solo un caso di confronto su 100");
var more = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger]);
Assert.AreEqual((130, 150), (more.Pairs, more.PairsNeeded));
StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide solo quando i casi superano 100, 150, 200, 250 e 300");
Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger]).PairsNeeded);
Assert.AreEqual((130, 100), (more.Pairs, more.PairsNeeded), "passed, and not judged yet");
StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide domenica 11 ottobre alle 03:00: prende il posto della 1 se");
var judged = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger with { ThresholdDone = 100 }]);
Assert.AreEqual((130, 150), (judged.Pairs, judged.PairsNeeded));
StringAssert.StartsWith(judged.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide di nuovo a 150 casi:");
Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger with { ThresholdDone = 250 }]).PairsNeeded);
Assert.AreEqual((5.84m, 6m), (more.Champion!.GainWithout, more.Challenger!.GainWithout));
Assert.AreEqual((56, 0.241m, 7.9m, "4 ottobre"), (more.Champion.Precision, more.Champion.Error, more.Champion.Gain, more.Champion.Trained));
Assert.AreEqual("Nessuno sfidante in prova.", View(new CycleState(), models: champion).TrialTitle);