Il prodotto prende il nome del repository, come chiesto per allineare la struttura agli altri progetti: soluzione Mimante.slnx, progetti src/Mimante, tests/Mimante.Tests e tools/Mimante.Schermate, spazi dei nomi Mimante.*, immagine alby96/mimante, modello docker/unraid/mimante.xml, compose in docker/, documenti in minuscolo (stato.md, architettura.md, come-funziona.md, schermate/), versioni dei pacchetti in Directory.Packages.props. Versione 2.0.0. Non cambiano database, tabelle, variabili d'ambiente, /config, chiave della sessione e riferimenti del sito: bidoo.default.json è identico e i nomi logici delle risorse incorporate restano quelli che le migrazioni cercano. divSaldoBidBottom è l'id di Bidoo. Compatibilità: il cookie dell'interfaccia diventa mimante_sessione (un accesso in più per browser dopo l'aggiornamento); le preferenze del browser passano da bidbot.* a mimante.* con una copia una tantum. Corretto anche il tema della pagina d'accesso, che leggeva il valore salvato senza togliere le virgolette del JSON. Tolto il codice non compilato: il riferimento del riscatto (lo sostituisce il riscatto nuovo) e il formato SQLite della versione desktop (ora la issue #31); sono leggibili al tag v1.2.0. Nuovi docs/processo.md, docs/decisioni.md, docs/docker.md (con i passi per sostituire il container su Unraid) e ADR 0014. Il Dockerfile copia Directory.Packages.props e .dockerignore esclude dati/. Build con gli avvisi come errori; 288 test verdi, i 14 sul database saltati perché Docker Desktop su questo PC non parte: girano nella CI con il suo PostgreSQL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
838 lines
42 KiB
C#
838 lines
42 KiB
C#
using Mimante.Bidoo;
|
||
using Mimante.Data;
|
||
using Mimante.Engine;
|
||
using Mimante.Ml;
|
||
using Mimante.Products;
|
||
using Mimante.Settings;
|
||
using Mimante.Strategy;
|
||
using Xunit;
|
||
|
||
namespace Mimante.Tests;
|
||
|
||
/// <summary>Dati dell'apprendimento in memoria, per provare servizio e strategia senza PostgreSQL.</summary>
|
||
public sealed class MemoryLearningData : ILearningData
|
||
{
|
||
public Dictionary<string, TrainingReader.Session> Sessions { get; } = new();
|
||
public HashSet<string> Learned { get; } = new();
|
||
public Dictionary<string, string> Reasons { get; } = new();
|
||
public List<(double PWin, string Outcome)> Own { get; } = new();
|
||
|
||
/// <summary>Esiti delle decisioni registrate per asta (chiave del bandit, esito), per rifare il bandit.</summary>
|
||
public Dictionary<string, List<(string ContextKey, string Outcome)>> Outcomes { get; } = new();
|
||
|
||
/// <summary>Se vero, leggere un'asta da studiare fallisce: lo studio si ferma con un errore.</summary>
|
||
public bool FailLoad { get; set; }
|
||
|
||
public Task FlushAsync() => Task.CompletedTask;
|
||
public Task<List<string>> PendingAuctionIdsAsync() => Task.FromResult(Sessions.Keys.Where(k => !Learned.Contains(k)).ToList());
|
||
public Task<int> PendingCountAsync() => Task.FromResult(Sessions.Keys.Count(k => !Learned.Contains(k)));
|
||
public Task<List<string>> ClosedAuctionIdsAsync(int max) => Task.FromResult(Sessions.Keys.ToList());
|
||
public Task<TrainingReader.Session?> LoadSessionAsync(string id, string? me) =>
|
||
FailLoad ? throw new InvalidOperationException("database non raggiungibile") : Task.FromResult(Sessions.GetValueOrDefault(id));
|
||
public Task<bool> IsLearnedAsync(string id) => Task.FromResult(Learned.Contains(id));
|
||
public void MarkLearned(string id) => Learned.Add(id);
|
||
public Task MarkAllUnlearnedAsync() { Learned.Clear(); return Task.CompletedTask; }
|
||
public Task<List<(double PWin, string Outcome)>> OwnBidOutcomesAsync(string? id) => Task.FromResult(id == null ? Own.ToList() : new List<(double, string)>());
|
||
public Task<List<(string ContextKey, string Outcome)>> DecisionOutcomesAsync(string id) =>
|
||
Task.FromResult(Outcomes.TryGetValue(id, out var rows) ? rows.ToList() : new List<(string, string)>());
|
||
public Task<List<string>> AuctionsWithDecisionOutcomesAsync() => Task.FromResult(Outcomes.Keys.ToList());
|
||
public Task<List<LossReasons.DecisionRow>> DecisionsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.DecisionRow>());
|
||
public Task<List<LossReasons.MyBidRow>> MyBidsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.MyBidRow>());
|
||
public void WriteLossReason(string id, string reason) => Reasons[id] = reason;
|
||
public Task<List<ClosedAuctionRow>> ClosedAuctionsAsync(int max) => Task.FromResult(new List<ClosedAuctionRow>());
|
||
public Task<List<(string Reason, int Count)>> LossReasonSummaryAsync(int days) => Task.FromResult(new List<(string, int)>());
|
||
public Task<List<ShadowReport.Row>> ShadowRowsAsync(int days, bool? shadow, double cost) => Task.FromResult(new List<ShadowReport.Row>());
|
||
}
|
||
|
||
internal sealed class ListLedger : IRiskLedger
|
||
{
|
||
public List<(string Kind, double Amount)> Rows { get; } = new();
|
||
public void Append(string kind, double amountEuro, string? auctionId, string? note) => Rows.Add((kind, amountEuro));
|
||
}
|
||
|
||
/// <summary>Il gestore del rischio (portati dal legacy, senza database).</summary>
|
||
public class RiskManagerTests
|
||
{
|
||
private static AuctionInfo Auction(string id, RunMode mode = RunMode.Active, int bids = 0) =>
|
||
new(id) { Name = "Prova", Mode = mode, SessionBidCount = bids };
|
||
|
||
[Fact]
|
||
public void Lo_stop_loss_porta_in_halt_e_l_halt_resta_dopo_il_riavvio()
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
var ledger = new ListLedger();
|
||
var risk = new RiskManager(docs, ledger);
|
||
var s = new AppSettings { DailyStopLossEuro = 1.00 };
|
||
|
||
for (var i = 0; i < 4; i++) risk.NoteBidSpent("a", 0.20);
|
||
Assert.True(risk.Authorize(Auction("a"), s, 0.20).Allowed);
|
||
risk.NoteBidSpent("a", 0.20);
|
||
Assert.False(risk.Authorize(Auction("a"), s, 0.20).Allowed);
|
||
Assert.True(risk.Halted);
|
||
Assert.True(risk.Halt!.Automatic);
|
||
|
||
// Un nuovo gestore sugli stessi documenti (il riavvio) vede ancora l'HALT.
|
||
var again = new RiskManager(docs, ledger);
|
||
Assert.True(again.Halted);
|
||
Assert.False(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
|
||
Assert.True(again.Resume());
|
||
Assert.True(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
|
||
Assert.Contains(ledger.Rows, r => r.Kind == "halt");
|
||
Assert.Contains(ledger.Rows, r => r.Kind == "resume");
|
||
}
|
||
|
||
[Fact]
|
||
public void Vincite_drawdown_e_tetto_del_giorno()
|
||
{
|
||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||
for (var i = 0; i < 5; i++) risk.NoteBidSpent("a", 0.20);
|
||
risk.NoteWin("a", 3.00, "vinta");
|
||
var n = risk.Snapshot();
|
||
Assert.Equal(1.00, n.TodaySpent, 6);
|
||
Assert.Equal(2.00, n.Cumulative, 6);
|
||
Assert.True(risk.Authorize(Auction("a"), new AppSettings { DailyStopLossEuro = 1.0 }, 0.2).Allowed);
|
||
|
||
var dd = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||
dd.NoteWin("a", 5.00, "vinta");
|
||
dd.NoteBidSpent("b", 0.20);
|
||
dd.NoteBidSpent("b", 0.20);
|
||
Assert.True(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
|
||
dd.NoteBidSpent("b", 0.20);
|
||
Assert.False(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
|
||
|
||
var budget = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||
budget.NoteBidSpent("a", 0.20);
|
||
budget.NoteBidSpent("a", 0.20);
|
||
Assert.False(budget.Authorize(Auction("a"), new AppSettings { DailyBudgetEuro = 0.50 }, 0.20).Allowed);
|
||
Assert.False(budget.Halted);
|
||
}
|
||
|
||
[Fact]
|
||
public void Le_aste_in_gioco_insieme_hanno_un_tetto()
|
||
{
|
||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||
var all = new List<AuctionInfo> { Auction("a", bids: 3), Auction("b", bids: 1), Auction("c"), Auction("d", RunMode.Watch, bids: 9) };
|
||
var s = new AppSettings { MaxConcurrentActiveAuctions = 2 };
|
||
Assert.False(risk.Authorize(all[2], s, 0.2, all).Allowed);
|
||
Assert.True(risk.Authorize(all[0], s, 0.2, all).Allowed);
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_giorno_nuovo_azzera_la_spesa_del_giorno()
|
||
{
|
||
var now = new DateTime(2026, 9, 26, 23, 50, 0);
|
||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger(), () => now);
|
||
risk.NoteBidSpent("a", 0.40);
|
||
Assert.Equal(0.40, risk.Snapshot().TodaySpent, 6);
|
||
now = now.AddMinutes(20);
|
||
Assert.Equal(0, risk.Snapshot().TodaySpent, 6);
|
||
Assert.Equal(-0.40, risk.Snapshot().Cumulative, 6);
|
||
}
|
||
}
|
||
|
||
public class BiddingHoursAndCleanupTests
|
||
{
|
||
[Theory]
|
||
[InlineData(0, true)] [InlineData(9, true)] [InlineData(10, false)] [InlineData(23, false)]
|
||
public void La_fascia_0_10(int hour, bool quiet) => Assert.Equal(quiet, BiddingHours.IsQuiet(hour, 0, 10));
|
||
|
||
[Fact]
|
||
public void Mezzanotte_ore_fuori_scala_e_filtro_spento()
|
||
{
|
||
Assert.True(BiddingHours.IsQuiet(23, 22, 6));
|
||
Assert.False(BiddingHours.IsQuiet(6, 22, 6));
|
||
for (var h = 0; h < 24; h++) Assert.False(BiddingHours.IsQuiet(h, 3, 3));
|
||
Assert.Equal(BiddingHours.IsQuiet(1, 0, 10), BiddingHours.IsQuiet(25, 0, 10));
|
||
Assert.Contains("00:00-10:00", BiddingHours.Explanation(0, 10));
|
||
}
|
||
|
||
[Fact]
|
||
public void La_pulizia_trattiene_cio_che_e_costato()
|
||
{
|
||
var o = new FinishedAuctionCleanup.Options();
|
||
Assert.True(FinishedAuctionCleanup.Decide(true, false, 0, false, o).Remove);
|
||
Assert.False(FinishedAuctionCleanup.Decide(false, false, 0, false, o).Remove);
|
||
Assert.Contains("12 puntate", FinishedAuctionCleanup.Decide(true, false, 12, false, o).Reason);
|
||
Assert.Contains("vinta", FinishedAuctionCleanup.Decide(true, true, 30, false, o).Reason);
|
||
Assert.Contains("Attiva", FinishedAuctionCleanup.Decide(true, false, 0, true, o).Reason);
|
||
Assert.False(FinishedAuctionCleanup.Decide(true, false, 0, false, new FinishedAuctionCleanup.Options { Enabled = false }).Remove);
|
||
}
|
||
}
|
||
|
||
public class ProductTests
|
||
{
|
||
[Theory]
|
||
[InlineData("SMARTPHONE XY ", "smartphone xy")]
|
||
[InlineData("Macchina Caffè Espresso", "macchina caffe espresso")]
|
||
[InlineData("Cuffie Wireless (Nero)", "cuffie wireless")]
|
||
[InlineData("Set 24 Pennelli Make-Up", "set 24 pennelli make up")]
|
||
[InlineData("Buono Amazon 50 €", "buono amazon 50")]
|
||
public void La_chiave_prodotto_normalizza(string name, string key) => Assert.Equal(key, ProductKey.From(name));
|
||
|
||
[Fact]
|
||
public void I_numeri_distinguono_i_modelli() =>
|
||
Assert.NotEqual(ProductKey.From("PowerBank 20000"), ProductKey.From("PowerBank 10000"));
|
||
|
||
[Fact]
|
||
public void Le_regole_del_prodotto_vincono_sui_predefiniti()
|
||
{
|
||
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50, AutoAddNewAuctionState = "Osserva" };
|
||
var none = ProductRules.Resolve(null, s, autoAdded: true);
|
||
Assert.Equal(20, none.MaxPrice);
|
||
Assert.Equal(RunMode.Watch, none.Mode);
|
||
|
||
var p = new ProductRecord { ProductKey = "x", MaxPrice = 8, MaxBids = 0, AutoState = "Attiva" };
|
||
var own = ProductRules.Resolve(p, s, autoAdded: true);
|
||
Assert.Equal(8, own.MaxPrice);
|
||
Assert.Equal(0, own.MaxBids); // lo zero esplicito è una scelta vera
|
||
Assert.Equal(RunMode.Active, own.Mode);
|
||
Assert.Equal(RunMode.Watch, ProductRules.ParseMode("boh"));
|
||
}
|
||
|
||
[Fact]
|
||
public void I_paletti_scritti_vincono_sui_calcolati_che_vincono_sui_predefiniti()
|
||
{
|
||
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50 };
|
||
var computed = new ProductAdvice.Advice(true, 6.5, 40, 1.2, 3, 3.5, 85, false, false, 30, "calcolati");
|
||
|
||
var fromHistory = ProductRules.Resolve(null, s, autoAdded: true, computed);
|
||
Assert.Equal(1.2, fromHistory.MinPrice);
|
||
Assert.Equal(6.5, fromHistory.MaxPrice);
|
||
Assert.Equal(40, fromHistory.MaxBids);
|
||
Assert.Equal("calcolati", fromHistory.Source);
|
||
Assert.True(fromHistory.FromProduct);
|
||
|
||
// Un paletto scritto sulla scheda vince solo per il suo campo.
|
||
var p = new ProductRecord { ProductKey = "x", MaxPrice = 5 };
|
||
var mixed = ProductRules.Resolve(p, s, autoAdded: true, computed);
|
||
Assert.Equal(5, mixed.MaxPrice);
|
||
Assert.Equal(40, mixed.MaxBids);
|
||
Assert.Equal(1.2, mixed.MinPrice);
|
||
Assert.Equal("scheda e calcolati", mixed.Source);
|
||
|
||
// Senza storico: i predefiniti, minimo a zero.
|
||
var none = ProductRules.Resolve(null, s, autoAdded: true, new ProductAdvice.Advice(false, null, null, 0, 0, 0, 0, false, false, 2, "pochi dati"));
|
||
Assert.Equal(0, none.MinPrice);
|
||
Assert.Equal(20, none.MaxPrice);
|
||
Assert.Equal("predefiniti", none.Source);
|
||
|
||
// Un minimo sopra il massimo fermerebbe tutto: vince il massimo.
|
||
var wrong = ProductRules.Resolve(new ProductRecord { ProductKey = "y", MinPrice = 9, MaxPrice = 4 }, s, autoAdded: false);
|
||
Assert.Equal(0, wrong.MinPrice);
|
||
|
||
// Il minimo predefinito vale solo senza uno scritto o calcolato.
|
||
var withDefault = new AppSettings { DefaultMaxPrice = 20, DefaultMinPrice = 0.5 };
|
||
Assert.Equal(0.5, ProductRules.Resolve(null, withDefault, autoAdded: true).MinPrice);
|
||
Assert.Equal(1.2, ProductRules.Resolve(null, withDefault, autoAdded: true, computed).MinPrice);
|
||
Assert.Equal(2, ProductRules.Resolve(new ProductRecord { ProductKey = "z", MinPrice = 2 }, withDefault, autoAdded: true, computed).MinPrice);
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_valore_reale_scritto_vince_e_abilita_la_copertura()
|
||
{
|
||
Assert.Equal(11, ProductRules.ValueOf(null, 11));
|
||
Assert.False(ProductRules.HasExplicitValue(new ProductRecord()));
|
||
var p = new ProductRecord { MarketValue = 9.5 };
|
||
Assert.Equal(9.5, ProductRules.ValueOf(p, 11));
|
||
Assert.True(ProductRules.HasExplicitValue(p));
|
||
}
|
||
|
||
[Fact]
|
||
public void L_orizzonte_e_l_asta_gia_cominciata()
|
||
{
|
||
var s = new AppSettings { AutoAddMaxStartMinutes = 60 };
|
||
Assert.Equal(3600, ProductRules.HorizonSeconds(null, s));
|
||
Assert.Equal(0, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 0 }, s));
|
||
Assert.Equal(180 * 60, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 180 }, s));
|
||
Assert.False(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.01m }));
|
||
Assert.True(ProductRules.HasStarted(new CatalogAuction { LastBidder = "tizio" }));
|
||
Assert.True(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.05m }));
|
||
}
|
||
|
||
[Fact]
|
||
public void I_limiti_consigliati_seguono_la_copertura_e_il_budget()
|
||
{
|
||
var closes = new List<double>();
|
||
for (var i = 0; i < 100; i++) closes.Add(0.5 + i * 0.05); // 0,50 .. 5,45
|
||
var input = new ProductAdvice.Input(closes, Enumerable.Range(10, 50).ToList(), 50, 1, 25, 0.13, 10, 0.85, 0.10);
|
||
var advice = ProductAdvice.Suggest(input);
|
||
Assert.True(advice.HasAdvice);
|
||
Assert.InRange(advice.MaxPrice!.Value, 4.5, 4.8);
|
||
Assert.InRange(advice.CoverageReached, 84, 87);
|
||
Assert.NotNull(advice.MaxBids);
|
||
Assert.Contains("aste concluse", advice.Explanation);
|
||
|
||
var tight = ProductAdvice.Suggest(input with { Value = 5, MaxBids = 40 });
|
||
Assert.True(tight.LimitedByBudget);
|
||
|
||
Assert.False(ProductAdvice.Suggest(input with { FinalPrices = closes.Take(3).ToList() }).HasAdvice);
|
||
}
|
||
|
||
[Fact]
|
||
public void Un_budget_esaurito_ferma_le_puntate_invece_di_togliere_il_limite()
|
||
{
|
||
var closes = new List<double>();
|
||
for (var i = 0; i < 100; i++) closes.Add(0.5 + i * 0.05);
|
||
// Valore 5 € + 10%, meno 40 puntate da 0,13 € e 1 € di spedizione: −0,70 €, niente per il prezzo.
|
||
var input = new ProductAdvice.Input(closes, Enumerable.Range(10, 50).ToList(), 5, 1, 40, 0.13, 10, 0.85, 0.10);
|
||
var advice = ProductAdvice.Suggest(input);
|
||
Assert.True(advice.HasAdvice);
|
||
Assert.Equal(ProductAdvice.StopAllMaxPrice, advice.MaxPrice);
|
||
Assert.True(advice.LimitedByBudget);
|
||
Assert.True(advice.NotWorthwhile);
|
||
Assert.Contains("Il budget è esaurito", advice.Explanation);
|
||
Assert.Contains("0,01 €", advice.Explanation);
|
||
|
||
// Sull'asta nuova e sulla scheda vale 0,01, non «nessun limite»; il minimo sopra il massimo sparisce.
|
||
var s = new AppSettings { DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
||
var resolved = ProductRules.Resolve(null, s, autoAdded: true, advice);
|
||
Assert.Equal(0.01, resolved.MaxPrice);
|
||
Assert.Equal(0, resolved.MinPrice);
|
||
Assert.Equal(0.01, LimitsRecompute.Values(advice).MaxPrice);
|
||
|
||
// La strategia allora non punta: il prezzo è oltre il massimo.
|
||
var docs = new MemoryDocumentStore();
|
||
var strategy = new BidStrategy(new RiskManager(docs, new ListLedger()), new LearningService(docs, new MemoryLearningData(), () => s, null),
|
||
new ProductStore(null), () => new AccountBalance(1407, 927, 480));
|
||
var auction = new AuctionInfo("1") { Name = "Buono", ProductKey = "buono", BuyNowPrice = 5, Mode = RunMode.Active, MaxPrice = resolved.MaxPrice };
|
||
var state = new AuctionState { Price = 0.37, ServerUnixSeconds = 1_788_000_019, ExpiryUnixSeconds = 1_788_000_020, Status = AuctionStatus.Running };
|
||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(auction, state, s, null, false, "io", new DateTime(2026, 9, 26, 12, 0, 0)).Kind);
|
||
|
||
// Un calcolo a zero (come lo davano le versioni di prima) non diventa «nessun limite»: vale il predefinito.
|
||
var zero = advice with { MaxPrice = 0, MaxBids = 0 };
|
||
var withDefaults = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50 };
|
||
Assert.Equal(20, ProductRules.Resolve(null, withDefaults, autoAdded: true, zero).MaxPrice);
|
||
Assert.Equal(50, ProductRules.Resolve(null, withDefaults, autoAdded: true, zero).MaxBids);
|
||
}
|
||
|
||
[Fact]
|
||
public void La_coerenza_delle_puntate_del_vincitore()
|
||
{
|
||
Assert.True(AuctionIntegrity.CheckWinnerBids(8.38, 25).IsTrustworthy);
|
||
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, null).IsTrustworthy);
|
||
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, 0).IsTrustworthy);
|
||
Assert.Contains("oltre il totale", AuctionIntegrity.CheckWinnerBids(0.10, 50).Reason);
|
||
Assert.True(AuctionIntegrity.CheckWinnerBids(0.03, 3).IsTrustworthy);
|
||
}
|
||
|
||
[Fact]
|
||
public void La_stellina_toglie_la_scheda_solo_senza_limiti_propri()
|
||
{
|
||
var store = new ProductStore(null);
|
||
store.SetFollowed("buono", "Buono", 1, true);
|
||
Assert.True(store.Find("buono")!.Followed);
|
||
store.SetFollowed("buono", "Buono", 1, false);
|
||
Assert.Null(store.Find("buono"));
|
||
|
||
store.Upsert(new ProductRecord { ProductKey = "caro", DisplayName = "Caro", Followed = true, MaxPrice = 5 });
|
||
store.SetFollowed("caro", "Caro", 0, false);
|
||
Assert.NotNull(store.Find("caro"));
|
||
|
||
store.MarkRemoved("caro", "123");
|
||
Assert.True(store.IsHandled("123"));
|
||
Assert.Equal("caro", store.FindFor(new CatalogAuction { Name = "Caro", ProductId = 0 })!.ProductKey);
|
||
}
|
||
}
|
||
|
||
/// <summary>La strategia: rischio solo dal vivo, poi i paletti, poi il modello.</summary>
|
||
public class BidStrategyTests
|
||
{
|
||
private static (BidStrategy Strategy, LearningService Learning, ProductStore Products, RiskManager Risk) Make(AccountBalance? balance = null)
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
var settings = new AppSettings();
|
||
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, null);
|
||
var products = new ProductStore(null);
|
||
var risk = new RiskManager(docs, new ListLedger());
|
||
return (new BidStrategy(risk, learning, products, () => balance ?? new AccountBalance(1407, 927, 480)), learning, products, risk);
|
||
}
|
||
|
||
private static AuctionInfo Auction()
|
||
{
|
||
var a = new AuctionInfo("1") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", BuyNowPrice = 50, Mode = RunMode.Active };
|
||
lock (a.BidsLock)
|
||
{
|
||
a.RecentBids.Add(new BidHistoryEntry { Price = 4.12m, Username = "marco", Timestamp = 1_788_000_010, BidType = BidHistoryEntry.TypeAuto });
|
||
a.RecentBids.Add(new BidHistoryEntry { Price = 4.11m, Username = "lulu", Timestamp = 1_788_000_001, BidType = BidHistoryEntry.TypeManual });
|
||
}
|
||
return a;
|
||
}
|
||
|
||
private static AuctionState State(double price = 4.12, bool mine = false) =>
|
||
new() { Price = price, ServerUnixSeconds = 1_788_000_019, ExpiryUnixSeconds = 1_788_000_020, Status = AuctionStatus.Running, IsMyBid = mine };
|
||
|
||
[Fact]
|
||
public void Il_costo_effettivo_scala_per_la_quota_di_pagate()
|
||
{
|
||
var s = new AppSettings { AverageBidCostEuro = 0.20 };
|
||
Assert.Equal(0.20 * 927 / 1407, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, 927, 480)), 9);
|
||
Assert.Equal(0.20, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, null, null)), 9);
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_rischio_vale_solo_dal_vivo()
|
||
{
|
||
var (strategy, _, _, risk) = Make();
|
||
risk.SetHalt("prova", automatic: false);
|
||
var live = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: false, "io", new DateTime(2026, 9, 26, 12, 0, 0));
|
||
Assert.Equal(LossReasons.Kind.Rischio, live.Kind);
|
||
var shadow = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: true, "io", new DateTime(2026, 9, 26, 12, 0, 0));
|
||
Assert.NotEqual(LossReasons.Kind.Rischio, shadow.Kind);
|
||
}
|
||
|
||
[Fact]
|
||
public void I_paletti_fermano_prima_del_modello()
|
||
{
|
||
var (strategy, _, _, _) = Make(new AccountBalance(900, 500, 400));
|
||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||
Assert.Equal(LossReasons.Kind.InTesta, strategy.Decide(Auction(), State(mine: true), new AppSettings(), null, true, "io", noon).Kind);
|
||
Assert.Equal(LossReasons.Kind.PuntateResidue, strategy.Decide(Auction(), State(), new AppSettings { MinimumRemainingBids = 1000 }, null, true, "io", noon).Kind);
|
||
|
||
var capped = Auction();
|
||
capped.MaxPrice = 4.00;
|
||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(capped, State(), new AppSettings(), null, true, "io", noon).Kind);
|
||
|
||
var quiet = new AppSettings { QuietHoursEnabled = true, QuietHoursStart = 0, QuietHoursEnd = 10 };
|
||
Assert.Equal(LossReasons.Kind.FasciaOraria, strategy.Decide(Auction(), State(), quiet, null, true, "io", new DateTime(2026, 9, 26, 3, 0, 0)).Kind);
|
||
|
||
var full = Auction();
|
||
full.MaxBids = 2;
|
||
full.BidsUsedOnAuction = 2;
|
||
Assert.Equal(LossReasons.Kind.PuntateAsta, strategy.Decide(full, State(), new AppSettings(), null, true, "io", noon).Kind);
|
||
|
||
// Sotto il prezzo minimo non si punta: a quel prezzo di solito l'asta non chiude.
|
||
var early = Auction();
|
||
early.MinPrice = 5.00;
|
||
var below = strategy.Decide(early, State(price: 4.12), new AppSettings(), null, true, "io", noon);
|
||
Assert.Equal(LossReasons.Kind.PrezzoMinimo, below.Kind);
|
||
Assert.False(below.ShouldBid);
|
||
Assert.NotEqual(LossReasons.Kind.PrezzoMinimo, strategy.Decide(early, State(price: 5.01), new AppSettings(), null, true, "io", noon).Kind);
|
||
}
|
||
|
||
[Fact]
|
||
public void Col_modello_non_pronto_si_punta_entro_i_paletti_e_poi_decide_il_valore_atteso()
|
||
{
|
||
var (strategy, learning, _, _) = Make();
|
||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||
var early = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
|
||
Assert.Equal(LossReasons.Kind.NonPronto, early.Kind);
|
||
Assert.True(early.ShouldBid);
|
||
Assert.NotNull(early.Context);
|
||
|
||
learning.SetLearnedForTests(500);
|
||
var ready = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
|
||
Assert.True(ready.Kind is LossReasons.Kind.Punta or LossReasons.Kind.EvNegativo);
|
||
Assert.Equal(ready.Ev > 0, ready.ShouldBid);
|
||
Assert.Contains("valore atteso", ready.Reason);
|
||
}
|
||
|
||
/// <summary>
|
||
/// I documenti lasciati da un modello della versione 2 delle variabili (86 variabili, 400 aste
|
||
/// studiate) e un archivio di <paramref name="archive"/> aste chiuse da ristudiare.
|
||
/// </summary>
|
||
internal static (MemoryDocumentStore Docs, MemoryLearningData Data) AfterUpgrade(int archive)
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
docs.Set("ml/model", new OnlineLogit(86).ToJson());
|
||
docs.Set("ml/features-version", """{"version":2}""");
|
||
docs.Set("ml/learned", """{"count":400}""");
|
||
var data = new MemoryLearningData();
|
||
var rng = new Random(5);
|
||
for (var i = 0; i < archive; i++) data.Sessions[$"s{i}"] = LearningServiceTests.Session($"s{i}", 30 + rng.Next(30), rng);
|
||
return (docs, data);
|
||
}
|
||
|
||
private static BidStrategy StrategyFor(LearningService learning, MemoryDocumentStore docs) =>
|
||
new(new RiskManager(docs, new ListLedger()), learning, new ProductStore(null), () => new AccountBalance(1407, 927, 480));
|
||
|
||
[Fact]
|
||
public async Task Dopo_un_cambio_delle_variabili_non_si_punta_finche_l_archivio_non_e_ristudiato()
|
||
{
|
||
var (docs, data) = AfterUpgrade(6);
|
||
var settings = new AppSettings();
|
||
var learning = new LearningService(docs, data, () => settings, null);
|
||
await learning.LoadAsync();
|
||
Assert.True(learning.RestudyingAfterUpgrade);
|
||
Assert.Equal(0, learning.AuctionsLearned);
|
||
|
||
var strategy = StrategyFor(learning, docs);
|
||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||
|
||
// Dal vivo e in Osserva: il modello vuoto sarebbe «non pronto» e punterebbe; invece no, e lo dice.
|
||
foreach (var shadow in new[] { false, true })
|
||
{
|
||
var d = strategy.Decide(Auction(), State(), settings, null, shadow, "io", noon);
|
||
Assert.False(d.ShouldBid);
|
||
Assert.Equal(LossReasons.Kind.Ristudio, d.Kind);
|
||
Assert.Equal("il modello sta ristudiando l'archivio dopo un aggiornamento: nessuna puntata finché non finisce", d.Reason);
|
||
Assert.NotNull(d.Context);
|
||
Assert.False(d.FromModel);
|
||
}
|
||
|
||
// Anche senza stima (valore ignoto) e anche se il conto delle aste basterebbe a dirsi pronto.
|
||
var unknown = Auction();
|
||
unknown.BuyNowPrice = null;
|
||
Assert.Equal(LossReasons.Kind.Ristudio, strategy.Decide(unknown, State(), settings, null, false, "io", noon).Kind);
|
||
learning.SetLearnedForTests(500);
|
||
Assert.False(strategy.Decide(Auction(), State(), settings, null, false, "io", noon).ShouldBid);
|
||
learning.SetLearnedForTests(0);
|
||
|
||
// I paletti restano prima: il motivo di un no per il prezzo resta il prezzo.
|
||
var capped = Auction();
|
||
capped.MaxPrice = 4.00;
|
||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(capped, State(), settings, null, false, "io", noon).Kind);
|
||
|
||
// Con l'apprendimento spento il modello non conta: si punta entro i paletti, scelta dell'utente.
|
||
Assert.Equal(LossReasons.Kind.SoloLimiti, strategy.Decide(Auction(), State(), new AppSettings { LearningEnabled = false }, null, false, "io", noon).Kind);
|
||
|
||
// Un riavvio a metà non perde la guardia.
|
||
var restarted = new LearningService(docs, data, () => settings, null);
|
||
await restarted.LoadAsync();
|
||
Assert.True(restarted.RestudyingAfterUpgrade);
|
||
|
||
// Lo studio arriva in fondo: si torna al comportamento di sempre (qui: poche aste, non pronto, punta entro i paletti).
|
||
await learning.StudyNowAsync(null, CancellationToken.None);
|
||
Assert.False(learning.RestudyingAfterUpgrade);
|
||
Assert.Equal(6, learning.AuctionsLearned);
|
||
var after = strategy.Decide(Auction(), State(), settings, null, false, "io", noon);
|
||
Assert.Equal(LossReasons.Kind.NonPronto, after.Kind);
|
||
Assert.True(after.ShouldBid);
|
||
|
||
var third = new LearningService(docs, data, () => settings, null);
|
||
await third.LoadAsync();
|
||
Assert.False(third.RestudyingAfterUpgrade);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Senza_un_modello_di_un_altra_versione_la_guardia_non_si_alza()
|
||
{
|
||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||
|
||
// Installazione nuova, anche con un archivio da studiare: non pronto, si punta entro i paletti.
|
||
var (_, data) = AfterUpgrade(3);
|
||
var freshDocs = new MemoryDocumentStore();
|
||
var fresh = new LearningService(freshDocs, data, () => new AppSettings(), null);
|
||
await fresh.LoadAsync();
|
||
Assert.False(fresh.RestudyingAfterUpgrade);
|
||
Assert.Equal(LossReasons.Kind.NonPronto, StrategyFor(fresh, freshDocs).Decide(Auction(), State(), new AppSettings(), null, false, "io", noon).Kind);
|
||
|
||
// Cambio di versione senza archivio da ristudiare: come un'installazione nuova.
|
||
var (docs, empty) = AfterUpgrade(0);
|
||
var learning = new LearningService(docs, empty, () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
Assert.False(learning.RestudyingAfterUpgrade);
|
||
var d = StrategyFor(learning, docs).Decide(Auction(), State(), new AppSettings(), null, false, "io", noon);
|
||
Assert.Equal(LossReasons.Kind.NonPronto, d.Kind);
|
||
Assert.True(d.ShouldBid);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Se_il_ristudio_si_ferma_resta_il_lato_sicuro_fino_a_Studia_adesso()
|
||
{
|
||
var (docs, data) = AfterUpgrade(4);
|
||
var settings = new AppSettings();
|
||
var learning = new LearningService(docs, data, () => settings, null);
|
||
await learning.LoadAsync();
|
||
var strategy = StrategyFor(learning, docs);
|
||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||
|
||
data.FailLoad = true;
|
||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||
Assert.True(learning.RestudyingAfterUpgrade);
|
||
Assert.True(learning.RestudyStopped);
|
||
|
||
var d = strategy.Decide(Auction(), State(), settings, null, false, "io", noon);
|
||
Assert.False(d.ShouldBid);
|
||
Assert.Equal(LossReasons.Kind.Ristudio, d.Kind);
|
||
Assert.Contains("«Studia adesso»", d.Reason);
|
||
|
||
var status = await learning.GetStatusAsync(settings);
|
||
Assert.Equal(LearningService.StudyState.DaRicalcolare, status.State);
|
||
Assert.Contains("in Attiva non punta", status.Detail);
|
||
Assert.Contains("il bottone con il libro («Studia adesso»)", status.Detail);
|
||
|
||
// Lo studio fallito non abbassa la guardia nemmeno dopo un riavvio.
|
||
var restarted = new LearningService(docs, data, () => settings, null);
|
||
await restarted.LoadAsync();
|
||
Assert.True(restarted.RestudyingAfterUpgrade);
|
||
|
||
// «Studia adesso» arriva in fondo: la guardia si abbassa.
|
||
data.FailLoad = false;
|
||
await learning.StudyNowAsync(null, CancellationToken.None);
|
||
Assert.False(learning.RestudyingAfterUpgrade);
|
||
Assert.False(learning.RestudyStopped);
|
||
Assert.NotEqual(LossReasons.Kind.Ristudio, strategy.Decide(Auction(), State(), settings, null, false, "io", noon).Kind);
|
||
}
|
||
|
||
[Fact]
|
||
public void Senza_valore_del_prodotto_si_punta_entro_i_paletti()
|
||
{
|
||
var (strategy, _, _, _) = Make();
|
||
var a = Auction();
|
||
a.BuyNowPrice = null;
|
||
Assert.Equal(LossReasons.Kind.SenzaStima, strategy.Decide(a, State(), new AppSettings(), null, true, "io", DateTime.Now).Kind);
|
||
}
|
||
|
||
[Fact]
|
||
public void La_correzione_sulle_mie_puntate_e_nei_limiti()
|
||
{
|
||
var (_, learning, _, _) = Make();
|
||
learning.SetOwnBidsForTests(10, 3.0, 6);
|
||
Assert.Equal(1.0, learning.OwnBidFactor);
|
||
learning.SetOwnBidsForTests(30, 3.0, 6);
|
||
Assert.Equal(6.5 / 3.5, learning.OwnBidFactor, 6);
|
||
learning.SetOwnBidsForTests(30, 0.5, 30);
|
||
Assert.Equal(4.0, learning.OwnBidFactor);
|
||
learning.SetOwnBidsForTests(30, 30, 0);
|
||
Assert.Equal(0.25, learning.OwnBidFactor);
|
||
}
|
||
}
|
||
|
||
public class LearningServiceTests
|
||
{
|
||
internal static TrainingReader.Session Session(string id, int bids, Random rng)
|
||
{
|
||
var list = new List<TrainingReader.Bid>();
|
||
long t = 1_788_000_000;
|
||
var users = new[] { "anna", "bruno", "carla", "dino" };
|
||
for (var i = 0; i < bids; i++)
|
||
{
|
||
t += 2 + rng.Next(9);
|
||
list.Add(new TrainingReader.Bid(i, users[rng.Next(users.Length)], t, rng.Next(2) == 0 ? "Auto" : "Manuale", false, (i + 1) / 100.0));
|
||
}
|
||
return TrainingReader.Finish(new TrainingReader.Session
|
||
{
|
||
AuctionId = id, ProductKey = "buono", BuyNowPrice = 50, AddedAtLocal = new DateTime(2026, 9, 7, 11, 0, 0),
|
||
Bids = list, Winner = list[^1].User, FinalPrice = bids / 100.0, HasSummary = true
|
||
});
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Studia_le_aste_chiuse_e_salva_nei_documenti()
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
var data = new MemoryLearningData();
|
||
var rng = new Random(3);
|
||
for (var i = 0; i < 12; i++) data.Sessions[$"a{i}"] = Session($"a{i}", 30 + rng.Next(60), rng);
|
||
|
||
var settings = new AppSettings();
|
||
var learning = new LearningService(docs, data, () => settings, null);
|
||
await learning.LoadAsync();
|
||
var (done, usable) = await learning.StudyNowAsync(null, CancellationToken.None);
|
||
|
||
Assert.Equal(12, done);
|
||
Assert.Equal(12, usable);
|
||
Assert.Equal(12, learning.AuctionsLearned);
|
||
Assert.True(learning.ModelUpdates > 300);
|
||
Assert.NotNull(docs.Get("ml/model"));
|
||
Assert.Contains("\"count\":12", docs.Get("ml/learned"));
|
||
|
||
// Un secondo servizio sugli stessi documenti riparte da dove era.
|
||
var again = new LearningService(docs, data, () => settings, null);
|
||
await again.LoadAsync();
|
||
Assert.Equal(12, again.AuctionsLearned);
|
||
Assert.Equal(learning.ModelUpdates, again.ModelUpdates);
|
||
|
||
// La stessa asta chiusa non si impara due volte: il modello resta com'è, il resto
|
||
// (profilo, bandit, motivo) si aggiorna una volta sola.
|
||
var closed = new ClosedAuctionInfo("a0", "Buono", "buono", DateTime.UtcNow, 0.5, 50, null, null, 3, false, "anna", 10);
|
||
var updates = again.ModelUpdates;
|
||
Assert.StartsWith("già studiata", await again.OnAuctionClosedAsync(closed));
|
||
Assert.Equal(updates, again.ModelUpdates);
|
||
Assert.True(data.Reasons.ContainsKey("a0"));
|
||
Assert.Null(await again.OnAuctionClosedAsync(closed));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Cambiare_le_variabili_fa_ristudiare_tutto()
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
docs.Set("ml/model", new OnlineLogit(BidFeatures.Size).ToJson());
|
||
docs.Set("ml/features-version", """{"version":1}""");
|
||
docs.Set("ml/learned", """{"count":99}""");
|
||
var data = new MemoryLearningData();
|
||
data.Sessions["x"] = new TrainingReader.Session { AuctionId = "x", HasSummary = true };
|
||
|
||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
Assert.Equal(0, learning.AuctionsLearned);
|
||
Assert.True(learning.FullStudyPending);
|
||
Assert.True(learning.RestudyingAfterUpgrade);
|
||
Assert.True(learning.BanditRebuildPending);
|
||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||
}
|
||
|
||
/// <summary>Un modello della versione 2 con un bandit pieno, e decisioni registrate con esito su due aste.</summary>
|
||
private static (MemoryDocumentStore Docs, MemoryLearningData Data) UpgradeWithDecisions()
|
||
{
|
||
var (docs, data) = BidStrategyTests.AfterUpgrade(3);
|
||
var old = new ThompsonBandit();
|
||
for (var i = 0; i < 50; i++) old.Observe("vecchia|chiave", i % 2 == 0);
|
||
docs.Set("ml/bandit", old.ToJson());
|
||
data.Outcomes["s0"] = new() { ("g3|r1|h5|b2|a0", "won"), ("g3|r1|h5|b2|a0", "lost"), ("g1|r0|h2|b1|a1", "would_win") };
|
||
data.Outcomes["s1"] = new() { ("g1|r0|h2|b1|a1", "missed") };
|
||
return (docs, data);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Dopo_il_cambio_delle_variabili_il_bandit_si_rifa_dalle_decisioni_registrate()
|
||
{
|
||
var (docs, data) = UpgradeWithDecisions();
|
||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
Assert.Equal(0, learning.Bandit.Observations);
|
||
Assert.True(learning.BanditRebuildPending);
|
||
|
||
// Un riavvio prima dello studio d'avvio non perde il lavoro in sospeso.
|
||
var restarted = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await restarted.LoadAsync();
|
||
Assert.True(restarted.BanditRebuildPending);
|
||
|
||
// Lo studio d'avvio ristudia l'archivio e poi rifà il bandit, con le fasce di adesso.
|
||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||
Assert.False(learning.RestudyingAfterUpgrade);
|
||
Assert.False(learning.BanditRebuildPending);
|
||
Assert.Equal(3, learning.AuctionsLearned);
|
||
Assert.Equal(4, learning.Bandit.Observations);
|
||
Assert.Equal(2, learning.Bandit.Arms);
|
||
Assert.Null(docs.Get("ml/upgrade"));
|
||
|
||
// Fatto una volta, al prossimo avvio non si rifà.
|
||
var again = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await again.LoadAsync();
|
||
Assert.False(again.BanditRebuildPending);
|
||
Assert.Equal(4, again.Bandit.Observations);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Dimentica_tutto_dimentica_anche_il_bandit_da_rifare()
|
||
{
|
||
var (docs, data) = UpgradeWithDecisions();
|
||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
Assert.True(learning.BanditRebuildPending);
|
||
|
||
await learning.ForgetAsync();
|
||
Assert.False(learning.BanditRebuildPending);
|
||
// Il ristudio resta dovuto: finché l'archivio non è studiato non si punta.
|
||
Assert.True(learning.RestudyingAfterUpgrade);
|
||
|
||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||
Assert.False(learning.RestudyingAfterUpgrade);
|
||
Assert.Equal(0, learning.Bandit.Observations);
|
||
|
||
var restarted = new LearningService(docs, data, () => new AppSettings(), null);
|
||
await restarted.LoadAsync();
|
||
Assert.False(restarted.BanditRebuildPending);
|
||
Assert.Equal(0, restarted.Bandit.Observations);
|
||
|
||
// Un «Dimentica tutto» senza cambio di versione non alza nessuna guardia.
|
||
var plain = new LearningService(new MemoryDocumentStore(), data, () => new AppSettings(), null);
|
||
await plain.LoadAsync();
|
||
await plain.ForgetAsync();
|
||
Assert.False(plain.RestudyingAfterUpgrade);
|
||
Assert.False(plain.BanditRebuildPending);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Un_modello_salvato_con_la_versione_vecchia_non_si_carica_con_la_dimensione_sbagliata()
|
||
{
|
||
// Come li lasciava la versione 2 delle variabili: 86 variabili, 6 fasce orarie larghe.
|
||
const int oldSize = 86;
|
||
var docs = new MemoryDocumentStore();
|
||
var old = new OnlineLogit(oldSize);
|
||
var x = new double[oldSize];
|
||
x[0] = 1;
|
||
for (var i = 0; i < 50; i++) old.Update(x, i % 3 == 0);
|
||
docs.Set("ml/model", old.ToJson());
|
||
docs.Set("ml/challenger", new NeuralNet(new[] { oldSize, 32, 16, 1 }, seed: 42).ToJson());
|
||
var bandit = new ThompsonBandit();
|
||
bandit.Observe("g3|r1|h5|b2|a0", true);
|
||
docs.Set("ml/bandit", bandit.ToJson());
|
||
var profile = new AuctionProfileStats();
|
||
profile.Observe("buono", new DateTime(2026, 9, 7, 22, 0, 0), 30, 0.1);
|
||
docs.Set("ml/profile", profile.ToJson());
|
||
var forecast = new AuctionForecast();
|
||
for (var i = 0; i < 20; i++) forecast.Observe("buono", 3, 50, 5, 30, 10);
|
||
docs.Set("ml/forecast", forecast.ToJson());
|
||
docs.Set("ml/features-version", """{"version":2}""");
|
||
docs.Set("ml/learned", """{"count":40}""");
|
||
|
||
var learning = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
|
||
Assert.Equal(0, learning.ModelUpdates);
|
||
Assert.Equal(0, learning.AuctionsLearned);
|
||
Assert.Equal(BidFeatures.Size, learning.Weights().Count);
|
||
Assert.Equal(0, learning.Bandit.Arms);
|
||
Assert.Equal(0, learning.ProfileAuctions);
|
||
Assert.Equal(0, learning.ForecastObserved);
|
||
Assert.Null(learning.Forecast(new ForecastInput("buono", 1, 50, 5, null, null, 0.13, 1, 0, 3, 0)));
|
||
|
||
// Il modello risponde con il vettore nuovo e i documenti hanno la dimensione nuova.
|
||
var ctx = new BidContext(3, 0.5, 3, 0.05, 23, DayOfWeek.Friday, 0, false, 1, 120, false, "buono");
|
||
Assert.InRange(learning.PredictUnanswered(ctx), 0, 1);
|
||
Assert.Equal(0, OnlineLogit.FromJson(docs.Get("ml/model")!, BidFeatures.Size).Updates);
|
||
Assert.Contains($"\"Sizes\":[{BidFeatures.Size},32,16,1]", docs.Get("ml/challenger"));
|
||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Anche_senza_modello_profilo_e_previsioni_di_un_altra_versione_si_scartano()
|
||
{
|
||
var docs = new MemoryDocumentStore();
|
||
var forecast = new AuctionForecast();
|
||
for (var i = 0; i < 20; i++) forecast.Observe("buono", 3, 50, 5, 30, 10);
|
||
var profile = new AuctionProfileStats();
|
||
profile.Observe("buono", new DateTime(2026, 9, 7, 22, 0, 0), 30, 0.1);
|
||
docs.Set("ml/forecast", forecast.ToJson());
|
||
docs.Set("ml/profile", profile.ToJson());
|
||
docs.Set("ml/features-version", """{"version":2}""");
|
||
|
||
var learning = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||
await learning.LoadAsync();
|
||
Assert.Equal(0, learning.ForecastObserved);
|
||
Assert.Equal(0, learning.ProfileAuctions);
|
||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||
|
||
// Con la versione giusta invece si ricaricano com'erano.
|
||
docs.Set("ml/forecast", forecast.ToJson());
|
||
docs.Set("ml/profile", profile.ToJson());
|
||
var again = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||
await again.LoadAsync();
|
||
Assert.Equal(20, again.ForecastObserved);
|
||
Assert.Equal(1, again.ProfileAuctions);
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_bandit_si_rifa_con_le_fasce_di_adesso_dal_contesto_salvato()
|
||
{
|
||
var ctx = new BidContext(3, 0.8, 2, 0.05, 22, DayOfWeek.Monday, 21, false, 1, 120, false, "buono");
|
||
var json = System.Text.Json.JsonSerializer.Serialize(new DecisionState { Ctx = ctx, Price = 1.2 }, new System.Text.Json.JsonSerializerOptions
|
||
{
|
||
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
|
||
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
|
||
});
|
||
|
||
var key = DbLearningData.CurrentBanditKey(json);
|
||
Assert.Equal(ThompsonBandit.KeyOf(ctx), key);
|
||
Assert.Contains($"|h{BidFeatures.HourBand(22)}|", key);
|
||
Assert.Null(DbLearningData.CurrentBanditKey(null));
|
||
Assert.Null(DbLearningData.CurrentBanditKey("{\"price\":1.2}"));
|
||
Assert.Null(DbLearningData.CurrentBanditKey("non json"));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task L_esplorazione_ha_un_budget_al_giorno()
|
||
{
|
||
var learning = new LearningService(new MemoryDocumentStore(), new MemoryLearningData(), () => new AppSettings(), null);
|
||
var s = new AppSettings { ExplorationBidsPerDay = 2 };
|
||
Assert.True(learning.ExplorationAvailable(s));
|
||
learning.NoteExplorationBid();
|
||
learning.NoteExplorationBid();
|
||
Assert.False(learning.ExplorationAvailable(s));
|
||
Assert.False(learning.ExplorationAvailable(new AppSettings { ExplorationBidsPerDay = 0 }));
|
||
await Task.CompletedTask;
|
||
}
|
||
}
|