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

+25 -14
View File
@@ -112,6 +112,9 @@ internal sealed record LearningView
public int PairsNeeded { get; init; }
/// <summary>No strategy with capital had examples when the model in charge was trained.</summary>
public bool GainOnReference { get; init; }
public string TrialTitle { get; init; } = "";
public string TrialText { get; init; } = "";
@@ -169,7 +172,7 @@ internal sealed record LearningView
: state.Aside is not null ? LearningStates.Aside
: state.ActivatedAt is not null ? LearningStates.Active
: LearningStates.Observation;
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : Format.Day(DayOf(last.TrainedAt)),
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now),
champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null));
}
@@ -213,7 +216,8 @@ internal sealed record LearningView
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
var (title, text) = Words(summary, state, now);
var live = activation.Scores.Bands;
// What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene".
var live = Judge.Bands(inCharge);
var history = !live.Any(b => b.Cases >= Judge.BandMin);
var verified = Verified(champion);
var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList();
@@ -224,7 +228,7 @@ internal sealed record LearningView
Text = text,
Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null,
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
LastTraining = last is null ? "mai" : $"{Format.Day(DayOf(last.TrainedAt))}, versione {last.Version}",
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
Bands = bands,
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
BandsFromHistory = history && bands.Count > 0,
@@ -239,6 +243,7 @@ internal sealed record LearningView
UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null,
Anomaly = state.Aside is not null,
Checked = state.Health is not null,
GainOnReference = champion?.Report.AllStrategiesCounted == true,
Found = discoveries.Found,
News = discoveries.News,
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
@@ -248,13 +253,15 @@ internal sealed record LearningView
{
view = view with
{
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Points(w.Precision)!.Value))],
Checks = state.Health is { } health ? ChecksOf(health, snapshot, champion, verified, events, now) : [],
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Health.Shown(w.Precision)))],
Checks = state.Health is not { } health ? []
: health.Version is { } seen && seen != champion.Version ? [new("wait", "Il modello in carica è cambiato: il primo controllo è alle 03:00. " + AlarmText(events, now))]
: ChecksOf(health, snapshot, champion, verified, events, now),
};
}
return champion is not null && challenger is not null
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), champion.Version, challenger.Version)
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), challenger.ThresholdDone, summary.NextCheck, champion.Version, challenger.Version)
: view with
{
TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.",
@@ -274,7 +281,7 @@ internal sealed record LearningView
$"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."),
LearningStates.Aside => ("Per ora è messo da parte.",
$"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."),
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione. Si riattiva da Impostazioni."),
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione nuova; quelle già rimpicciolite restano così fino alla chiusura. Si riattiva da Impostazioni."),
_ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.",
$"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"),
_ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"),
@@ -363,7 +370,7 @@ internal sealed record LearningView
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : cases.ToString(_it) + " casi, troppo pochi")} per contarci.";
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : Format.Number(cases) + " casi, troppo pochi")} per contarci.";
return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") +
(between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : "");
}
@@ -380,6 +387,7 @@ internal sealed record LearningView
var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share);
var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share);
var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
: news + fear == 0 && weights.Any(w => Clues.NewsGroups.Contains(w.Name) || w.Name == Fear) ? "Notizie, paura e avidità le studia già, ma per ora non pesano."
: news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono."
: news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100."
: $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100.";
@@ -396,17 +404,17 @@ internal sealed record LearningView
? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2))
: new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null);
private static LearningView WithTrial(LearningView view, TrialCheck check, int? champion, int? challenger)
/// <param name="done">The last threshold already judged: at the next one, passed or not, there is a decision (SPEC 11.4).</param>
private static LearningView WithTrial(LearningView view, TrialCheck check, int done, string nextCheck, int? champion, int? challenger)
{
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > check.Pairs, TrialCheck.Thresholds[^1]);
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, TrialCheck.Thresholds[^1]);
var first = TrialCheck.Thresholds[0];
var thresholds = string.Join(", ", TrialCheck.Thresholds.SkipLast(1)) + " e " + TrialCheck.Thresholds[^1];
var text = check.Pairs switch
{
0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.",
_ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " +
$"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.",
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. Si decide solo quando i casi superano {thresholds}: " +
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. {(check.Pairs >= next ? $"Si decide {At(nextCheck)}" : $"Si decide di nuovo a {next} casi")}: " +
$"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.",
};
return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text };
@@ -422,7 +430,7 @@ internal sealed record LearningView
health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it))
: known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}")
: new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
PrecisionCheck(Points(health.Precision), health.Cases, Points(verified?.Precision)),
PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)),
};
if (health.ErrorDrift)
{
@@ -500,7 +508,7 @@ internal sealed record LearningView
Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))],
};
var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList();
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), champion.Version, challenger.Version);
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
}
// ---- Words --------------------------------------------------------------------------------------------------
@@ -536,6 +544,9 @@ internal sealed record LearningView
private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome);
/// <summary>"domenica 4 ottobre", with the year when it is another one.</summary>
private static string LongDay(DateOnly day, DateTimeOffset now) => Format.Day(day) + (day.Year == DayOf(now).Year ? "" : day.ToString(" yyyy", CultureInfo.InvariantCulture));
/// <summary>"4 ottobre", with the year when it is another one.</summary>
private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day);