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

+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 }));
}
}