Il registro delle decisioni era insieme troppo grande e troppo povero: 102.656 aste fermate dalla soglia delle puntate residue scrivevano una riga identica a ogni ciclo, mentre di una puntata non si sapeva a quanti millisecondi dalla scadenza fosse partita né perché una puntata decisa non fosse partita. In Osserva un paletto zittiva il modello, così non si poteva sapere se il paletto costava aste. Migrazione 0004 (solo colonne nuove): - bot_decisions: repeat_count, last_ts, last_price (Data/DecisionRuns: la stessa decisione senza parere ciclo dopo ciclo resta una riga; il conteggio si scrive a fine serie, ogni 60 ripetizioni e alla chiusura), model_action, fire_note. ts è ora l'istante della decisione, non della scrittura (anche per bids, resets e my_bids.local_ts). - my_bids: millisecondi alla scadenza al verdetto, all'invio e alla risposta, stato HTTP, risposta di Bidoo ripulita, qualità dell'orologio e trace con le ultime letture prima e dopo. Tutto calcolato dopo la risposta: nulla di nuovo sul percorso caldo. - auctions: decisions, decisions_bid, decisions_model_bid alla chiusura, che restano anche quando il tetto dei dati cancella le decisioni. BidStrategy: in Osserva, con l'apprendimento acceso, un paletto ferma la puntata ma il modello dà lo stesso il parere (numeri, model_action, motivo «senza il paletto il modello punterebbe…»). Il verdetto non cambia. Scelta voluta: queste decisioni hanno la chiave del contesto, quindi il bandit impara anche da loro. La pausa dopo una puntata ora viene prima della soglia delle puntate residue. Lettori aggiornati: esito di una serie sull'ultimo prezzo, LossReasons pesato per le ripetizioni e con il parere del modello, Storico, esportazioni (quattro colonne nuove e conteggi pesati), LEGGIMI dello scaricamento. my_bids.trace contiene nomi: nello scaricamento il campo «ultimo» diventa pseudonimo. Test: DecisionRuns, parere sotto i paletti (Osserva sì, dal vivo e con l'apprendimento spento no), motivi pesati, pseudonimi del trace e una prova su PostgreSQL (200 cicli bloccati = una riga con 200, esito dall'ultimo prezzo, conteggi dell'asta, tempi della puntata, fire_note). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
381 lines
15 KiB
C#
381 lines
15 KiB
C#
using System.Diagnostics;
|
|
using Mimante.Bidoo;
|
|
using Mimante.Engine;
|
|
using Mimante.Logging;
|
|
using Mimante.Net;
|
|
using Mimante.Settings;
|
|
using Mimante.Simulator;
|
|
using Xunit;
|
|
|
|
namespace Mimante.Tests;
|
|
|
|
/// <summary>L'orologio del server: l'errore residuo resta piccolo e non cresce (portati dal legacy).</summary>
|
|
public class ServerClockTests
|
|
{
|
|
private static readonly long Freq = Stopwatch.Frequency;
|
|
|
|
[Fact]
|
|
public void Serve_piu_di_un_campione_prima_di_fidarsi()
|
|
{
|
|
var clock = new ServerClock();
|
|
clock.AddSample(1000, Freq * 1000, 0);
|
|
clock.AddSample(1001, Freq * 1001, 0);
|
|
Assert.False(clock.IsSynced);
|
|
clock.AddSample(1002, Freq * 1002, 0);
|
|
Assert.True(clock.IsSynced);
|
|
Assert.Equal(3, clock.SampleCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void La_media_segue_la_finestra_e_dimentica_il_passato()
|
|
{
|
|
var clock = new ServerClock();
|
|
for (var i = 0; i < 256; i++) clock.AddSample(1000 + i, Freq * (1000 + i), 500);
|
|
Assert.Equal(500, clock.AverageLatencyMs, 3);
|
|
for (var i = 0; i < 256; i++) clock.AddSample(2000 + i, Freq * (2000 + i), 50);
|
|
Assert.Equal(50, clock.AverageLatencyMs, 3);
|
|
Assert.Equal(256, clock.SampleCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void Ignora_i_campioni_privi_di_senso()
|
|
{
|
|
var clock = new ServerClock();
|
|
clock.AddSample(0, Freq, 0);
|
|
clock.AddSample(-5, Freq, 0);
|
|
clock.AddSample(1000, 0, 0);
|
|
Assert.Equal(0, clock.SampleCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void Con_zero_latenza_ricostruisce_esattamente_l_origine()
|
|
{
|
|
const long origin = 500;
|
|
var clock = new ServerClock();
|
|
for (var sec = 1000; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq, 0);
|
|
Assert.Equal(origin, clock.Origin);
|
|
Assert.Equal(origin + 2000 * Freq, clock.ToLocalTicks(2000));
|
|
}
|
|
|
|
[Fact]
|
|
public void Sottrae_meta_del_tempo_di_andata_e_ritorno()
|
|
{
|
|
const int latency = 100;
|
|
var half = (long)(latency / 2.0 / 1000.0 * Freq);
|
|
var clock = new ServerClock();
|
|
for (var sec = 1000; sec < 1005; sec++) clock.AddSample(sec, sec * Freq + half, latency);
|
|
Assert.Equal(0, clock.Origin);
|
|
}
|
|
|
|
[Fact]
|
|
public void Il_filtro_al_minimo_scarta_le_risposte_lente()
|
|
{
|
|
const long origin = 1_000_000;
|
|
var clock = new ServerClock();
|
|
clock.AddSample(1000, origin + 1000 * Freq, 0);
|
|
for (var sec = 1001; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq + Freq / 2, 0);
|
|
Assert.Equal(origin, clock.Origin);
|
|
}
|
|
|
|
[Fact]
|
|
public void L_errore_resta_entro_il_millisecondo_dal_campione_migliore()
|
|
{
|
|
const long origin = 5_000_000;
|
|
var clock = new ServerClock();
|
|
var delays = new long[] { 3, 17, 5, 40, 9, 22, 1, 31 };
|
|
for (var i = 0; i < delays.Length; i++)
|
|
{
|
|
var sec = 2000 + i;
|
|
clock.AddSample(sec, origin + sec * Freq + delays[i] * Freq / 1000, 0);
|
|
}
|
|
Assert.True(clock.Origin <= origin + Freq / 1000);
|
|
}
|
|
|
|
[Fact]
|
|
public void La_dispersione_misura_la_finestra_dei_campioni()
|
|
{
|
|
var clock = new ServerClock();
|
|
clock.AddSample(1000, 1000 * Freq, 0);
|
|
clock.AddSample(1001, 1001 * Freq + Freq / 100, 0);
|
|
clock.AddSample(1002, 1002 * Freq, 0);
|
|
Assert.InRange(clock.SpreadMs, 9.0, 11.0);
|
|
}
|
|
|
|
[Fact]
|
|
public void Reset_e_finestra_scorrevole()
|
|
{
|
|
var clock = new ServerClock();
|
|
for (var sec = 1000; sec < 1400; sec++) clock.AddSample(sec, sec * Freq, 0);
|
|
Assert.Equal(256, clock.SampleCount);
|
|
clock.Reset();
|
|
Assert.False(clock.IsSynced);
|
|
Assert.Equal(0, clock.Origin);
|
|
Assert.Equal(0, clock.AverageLatencyMs);
|
|
}
|
|
}
|
|
|
|
public class PollCadenceTests
|
|
{
|
|
private static readonly AppSettings S = new();
|
|
private static readonly BidooReferences R = BidooReferences.Default;
|
|
|
|
[Theory]
|
|
[InlineData(RunMode.Watch, 120_000, 2000)]
|
|
[InlineData(RunMode.Watch, 30_000, 900)]
|
|
[InlineData(RunMode.Watch, 8_000, 400)]
|
|
[InlineData(RunMode.Watch, 3_000, 400)] // la finestra critica vale solo in Attiva
|
|
[InlineData(RunMode.Active, 3_000, 220)]
|
|
[InlineData(RunMode.Active, 8_000, 400)]
|
|
public void La_cadenza_si_stringe_verso_la_scadenza(RunMode mode, double ms, int expected)
|
|
{
|
|
Assert.Equal(expected, PollCadence.NextDelayMs(mode, AuctionStatus.Running, ms, S, R));
|
|
}
|
|
|
|
[Fact]
|
|
public void Un_asta_programmata_non_si_interroga_di_continuo_ma_non_si_perde_l_apertura()
|
|
{
|
|
Assert.Equal(1_200_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 3 * 3_600_000, S, R));
|
|
Assert.Equal(120_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 30 * 60_000, S, R));
|
|
Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 8 * 60_000, S, R));
|
|
|
|
// A 130 s dall'apertura: al massimo fino al risveglio (120 s prima), cioè 10 s.
|
|
Assert.Equal(10_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 130_000, S, R));
|
|
|
|
// Dentro il risveglio: cadenza normale.
|
|
Assert.Equal(900, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Pending, 50_000, S, R));
|
|
}
|
|
|
|
[Fact]
|
|
public void Un_asta_sospesa_di_notte_si_guarda_ogni_30_secondi()
|
|
{
|
|
Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Active, AuctionStatus.Paused, 8 * 3_600_000, S, R));
|
|
}
|
|
}
|
|
|
|
public class PrecisionWaitTests
|
|
{
|
|
[Fact]
|
|
public void L_attesa_arriva_puntuale()
|
|
{
|
|
var errors = new List<double>();
|
|
for (var i = 0; i < 25; i++)
|
|
{
|
|
var target = Stopwatch.GetTimestamp() + PrecisionWait.MsToTicks(30 + i % 7);
|
|
PrecisionWait.Until(target, CancellationToken.None);
|
|
errors.Add(-PrecisionWait.MsUntil(target));
|
|
}
|
|
|
|
errors.Sort();
|
|
// Mai in anticipo; in ritardo di poco. Soglia larga: in CI i core sono condivisi.
|
|
Assert.All(errors, e => Assert.True(e >= 0));
|
|
Assert.True(errors.Average() < 3, $"errore medio {errors.Average():F3} ms");
|
|
Assert.True(errors[^2] < 15, $"errore quasi massimo {errors[^2]:F3} ms");
|
|
}
|
|
}
|
|
|
|
public class AuctionLogTests
|
|
{
|
|
[Fact]
|
|
public void Una_decisione_ripetuta_e_una_riga_sola()
|
|
{
|
|
var log = new AuctionLog();
|
|
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,10 EUR");
|
|
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,12 EUR");
|
|
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,08 EUR");
|
|
|
|
var rows = log.Snapshot();
|
|
Assert.Single(rows);
|
|
Assert.Equal(3, rows[0].Count);
|
|
Assert.Contains("-0,08", rows[0].Message);
|
|
|
|
log.AddDecision("punta", "Punto a 1,20 EUR");
|
|
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,20 EUR");
|
|
Assert.Equal(3, log.Snapshot().Count);
|
|
}
|
|
|
|
[Fact]
|
|
public void Le_righe_passano_dal_pulitore_e_le_uguali_si_contano()
|
|
{
|
|
var log = new AuctionLog();
|
|
var sunk = new List<AuctionLogEntry>();
|
|
log.Sink = sunk.Add;
|
|
|
|
log.Add("Puntata ✓ riuscita → 1,20 €", LogLevel.Success, AuctionLogCategory.Bid);
|
|
log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing);
|
|
log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing);
|
|
|
|
var rows = log.Snapshot();
|
|
Assert.Equal("Puntata riuscita -> 1,20 EUR", rows[0].Message);
|
|
Assert.Equal(2, rows[1].Count);
|
|
Assert.Equal(2, sunk.Count); // sul file solo le righe nuove
|
|
}
|
|
}
|
|
|
|
/// <summary>Il simulatore risponde con lo stesso formato del sito: lo leggono i parser veri.</summary>
|
|
public class SimulatorTests
|
|
{
|
|
[Fact]
|
|
public async Task Le_risposte_del_simulatore_si_leggono_con_i_parser_veri()
|
|
{
|
|
await using var sim = await SimulatedBidoo.StartAsync(new SimWorld(seed: 7));
|
|
var refs = sim.References();
|
|
using var transport = new BidooTransport(() => refs, 0);
|
|
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
|
var api = new BidooApi(transport, lane, () => refs) { Username = "utente_demo" };
|
|
|
|
var running = sim.World.Read(w => w.Auctions.First(a => a.Started && a.Status == "ON"));
|
|
var poll = await api.PollAsync(running.Id, null, 50, CancellationToken.None);
|
|
Assert.NotNull(poll.State);
|
|
Assert.Equal(AuctionStatus.Running, poll.State!.Status);
|
|
Assert.Equal(running.PriceCents / 100.0, poll.State.Price, 3);
|
|
Assert.NotNull(poll.State.RecentBidsHistory);
|
|
Assert.Equal(running.LastBidder, poll.State.RecentBidsHistory![0].Username);
|
|
|
|
var scheduled = sim.World.Read(w => w.Auctions.First(a => !a.Started));
|
|
var sched = await api.PollAsync(scheduled.Id, null, 50, CancellationToken.None);
|
|
Assert.Equal(AuctionStatus.Scheduled, sched.State!.Status);
|
|
|
|
var account = await api.GetUserInfoAsync(CancellationToken.None);
|
|
Assert.Equal("utente_demo", account!.Username);
|
|
Assert.Equal(1407, account.RemainingBids);
|
|
Assert.Equal(1, await api.GetAuctionsWonAsync(CancellationToken.None));
|
|
|
|
var page = await api.GetAuctionPageAsync(running.Id, null, CancellationToken.None);
|
|
Assert.Equal(running.Name, page!.Name);
|
|
Assert.Equal(running.Value, page.BuyNowPrice);
|
|
|
|
var catalog = new CatalogClient(transport, () => refs, null);
|
|
var categories = await catalog.GetCategoriesAsync(true, CancellationToken.None);
|
|
Assert.Contains(categories, c => c.DisplayName == "Buoni" && c.TagId == 6);
|
|
var all = await catalog.GetAllAuctionsAsync(CatalogCategory.AllAuctions, 500, 0, CancellationToken.None);
|
|
Assert.Equal(sim.World.Read(w => w.Auctions.Count(a => a.Status != "OFF")), all.Count);
|
|
await catalog.UpdateStatesAsync(all, CancellationToken.None);
|
|
Assert.Contains(all, a => a.CurrentPrice > 0.01m);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Un_asta_conclusa_porta_le_puntate_del_vincitore()
|
|
{
|
|
var world = new SimWorld(seed: 3, populate: false);
|
|
await using var sim = await SimulatedBidoo.StartAsync(world);
|
|
var a = world.AddRunningAuction(seconds: 1);
|
|
await Task.Delay(1600);
|
|
|
|
var refs = sim.References();
|
|
using var transport = new BidooTransport(() => refs, 0);
|
|
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
|
var poll = await new BidooApi(transport, lane, () => refs).PollAsync(a.Id, null, 50, CancellationToken.None);
|
|
|
|
Assert.Equal(AuctionStatus.EndedLost, poll.State!.Status);
|
|
Assert.Equal(1, poll.State.WinnerBidsTotal);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task La_mia_puntata_da_la_risposta_di_bid_php()
|
|
{
|
|
var world = new SimWorld(seed: 3, populate: false);
|
|
await using var sim = await SimulatedBidoo.StartAsync(world);
|
|
var a = world.AddRunningAuction(seconds: 8);
|
|
|
|
var refs = sim.References();
|
|
using var transport = new BidooTransport(() => refs, 0);
|
|
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
|
var api = new BidooApi(transport, lane, () => refs);
|
|
|
|
var bid = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None);
|
|
Assert.True(bid.Success, bid.Error);
|
|
Assert.Equal(1406, bid.Response.Remaining);
|
|
Assert.Equal(1, bid.Response.UsedOnAuction);
|
|
|
|
var again = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None);
|
|
Assert.False(again.Success);
|
|
Assert.Contains("miglior offerente", again.Error);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Il motore vero contro il simulatore: una sola puntata per ciclo, partita all'anticipo
|
|
/// voluto (misurato dal «server») e con l'attesa di precisione che sbaglia di poco.
|
|
/// </summary>
|
|
public class RunnerAgainstSimulatorTests
|
|
{
|
|
private sealed class Host : IAuctionRunnerHost
|
|
{
|
|
private readonly BidooApi _api;
|
|
public readonly ServerClock Clock = new();
|
|
public readonly List<double> WaitErrors = new();
|
|
public int Evaluations;
|
|
|
|
public Host(BidooApi api, BidooReferences refs)
|
|
{
|
|
_api = api;
|
|
References = refs;
|
|
}
|
|
|
|
public AppSettings Settings { get; } = new();
|
|
public BidooReferences References { get; }
|
|
public int Lead { get; set; } = 400;
|
|
|
|
public async Task<AuctionState?> PollAsync(AuctionInfo auction, CancellationToken ct) =>
|
|
(await _api.PollAsync(auction.Id, null, 50, ct)).State;
|
|
|
|
public void ApplySnapshot(AuctionInfo auction, AuctionState s)
|
|
{
|
|
Clock.AddSample(s.ServerUnixSeconds, s.ReceivedTicks, s.PollingLatencyMs);
|
|
if (s.ExpiryUnixSeconds > 0 && Clock.IsSynced) auction.DeadlineTicks = Clock.ToLocalTicks(s.ExpiryUnixSeconds);
|
|
auction.LastState = s;
|
|
if (s.IsTerminal) auction.Outcome = s.Status == AuctionStatus.EndedWon ? "won" : "lost";
|
|
}
|
|
|
|
public bool IsFinished(AuctionInfo auction) => auction.IsFinished;
|
|
public readonly List<string> NotFired = new();
|
|
public void NoteNotFired(AuctionInfo auction, string note) => NotFired.Add(note);
|
|
public bool IsShadow(AuctionInfo auction) => false;
|
|
public int EffectiveLeadMs(AuctionInfo auction) => Lead;
|
|
|
|
public bool EvaluateBid(AuctionInfo auction, AuctionState state, bool shadow)
|
|
{
|
|
Evaluations++;
|
|
return true;
|
|
}
|
|
|
|
public void FireBid(AuctionInfo auction, AuctionState state, int leadMs, long fireTicks)
|
|
{
|
|
lock (WaitErrors) WaitErrors.Add((Stopwatch.GetTimestamp() - fireTicks) * 1000.0 / Stopwatch.Frequency);
|
|
_api.PlaceBidAsync(auction.Id, null, null, 0, CancellationToken.None).GetAwaiter().GetResult();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Il_cecchino_punta_una_volta_per_ciclo_prima_della_scadenza()
|
|
{
|
|
var world = new SimWorld(seed: 11, populate: false);
|
|
await using var sim = await SimulatedBidoo.StartAsync(world);
|
|
var target = world.AddRunningAuction(seconds: 6, freq: 4);
|
|
|
|
var refs = sim.References();
|
|
using var transport = new BidooTransport(() => refs, 0);
|
|
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
|
var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername };
|
|
var host = new Host(api, refs);
|
|
|
|
var auction = new AuctionInfo(target.Id) { Name = target.Name, Mode = RunMode.Active };
|
|
var runner = new AuctionRunner(auction, host);
|
|
runner.Start();
|
|
|
|
// Nessun avversario: la nostra puntata resta l'ultima e l'asta chiude vinta.
|
|
var deadline = DateTime.UtcNow.AddSeconds(20);
|
|
while (!auction.IsFinished && DateTime.UtcNow < deadline) await Task.Delay(100);
|
|
await runner.StopAsync();
|
|
|
|
var mine = world.MyBids.Where(b => b.AuctionId == target.Id).ToList();
|
|
Assert.Equal("won", auction.Outcome);
|
|
Assert.Single(mine, b => b.Accepted);
|
|
|
|
var bid = mine.First(b => b.Accepted);
|
|
// Arrivata prima della scadenza, non prima del doppio dell'anticipo voluto.
|
|
Assert.InRange(bid.LeadMs, 1, host.Lead * 2 + 1000);
|
|
Assert.All(host.WaitErrors, e => Assert.InRange(e, 0, 5));
|
|
}
|
|
}
|