From b0901c02482b422b60b35d096a5c12f6e6d6e768 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 24 Nov 2026 12:24:14 +0100 Subject: [PATCH] Esportazioni a memoria costante, di fondo e annullabili (#25) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cadevano con molti dati: ogni riga del periodo finiva in un dizionario in memoria prima del campionamento, il file intero in una stringa, le letture avevano il limite di 15 s delle pagine e non si potevano annullare, e la puntata di risposta si cercava con ABS(price_after - x) < 0,005, che non usa l'indice. Ora: - CsvExport apre una sua connessione in sola lettura (REPEATABLE READ, tempo massimo ExportTimeoutMinutes), conta le righe per esito e chiede a PostgreSQL solo quelle scelte da SamplePlan (quota proporzionale, almeno una per gruppo, righe equidistanti nel tempo, stessa regola in SQL e in C#); le scrive una alla volta su nome.tmp, rinominato alla fine. Annullare, sforare il tempo o restare sotto ExportMinFreeMb cancella il .tmp e ferma la lettura sul server. Oltre ExportZipAboveMb il file esce in .zip. - Puntata di risposta con l'uguaglianza su price_after (numeric(10,2)) e una finestra su created_at: indice (auction_id, price_after) in ogni partizione, anche in AuctionRecorder alla chiusura. Storico con le colonne che servono e un solo passaggio sulle decisioni per i tre conteggi. Indice nuovo su my_bids(decision_id) (0003, tabella piccola). - ExportJobs: un'esportazione alla volta, di fondo, comandi export.start e export.cancel; lo stato arriva come blocco «export» del WebSocket, così sopravvive a una ricarica. exports.js è la finestra unica (fase, righe, Annulla, file pronti) per Storico, Apprendimento e Prodotti, e si riapre da sola quando un'esportazione finisce a finestra chiusa. - Apprendimento: i tre rapporti di confronto con una sola lettura in streaming invece di tre caricamenti interi; ShadowReport accumula media e varianza in corsa (stesso intervallo al 95%). Verifica: build con avvisi come errori, 306 prove verdi; le nuove prove su PostgreSQL (campione in SQL, zip, annullamento e spazio senza file residui) girano nella CI, qui Docker non parte. Le interrogazioni nuove sono state pianificate con EXPLAIN sul database vero in sola lettura: nessuna scansione intera di bids. Non fatto: le schermate dell'interfaccia con il bot in locale (manca un PostgreSQL); da rifare prima della chiusura. La pausa durante le puntate vere prevista dal piano non serve: il percorso caldo non tocca il database né il disco delle esportazioni. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + docs/architettura.md | 3 +- src/Mimante/Data/AuctionRecorder.cs | 10 +- src/Mimante/Data/CsvExport.cs | 527 ++++++++++++++---- src/Mimante/Data/Db.cs | 13 + src/Mimante/Data/ExportJobs.cs | 144 +++++ .../Migrations/0003_indice_mie_puntate.sql | 4 + src/Mimante/Data/SamplePlan.cs | 45 ++ src/Mimante/Host/Bot.Services.cs | 4 + src/Mimante/Ml/LearningData.cs | 44 +- src/Mimante/Ml/ShadowReport.cs | 77 ++- src/Mimante/Settings/AppSettings.cs | 9 + src/Mimante/Settings/SettingsStore.cs | 5 +- src/Mimante/Web/Api.cs | 9 +- src/Mimante/Web/Views.cs | 17 + src/Mimante/Web/WebSocketHub.Commands.cs | 17 +- src/Mimante/Web/WebSocketHub.cs | 4 + src/Mimante/wwwroot/js/app.js | 1 + src/Mimante/wwwroot/js/exports.js | 86 +++ src/Mimante/wwwroot/js/pages/apprendimento.js | 2 +- src/Mimante/wwwroot/js/pages/impostazioni.js | 5 +- src/Mimante/wwwroot/js/pages/prodotti.js | 7 +- src/Mimante/wwwroot/js/pages/storico.js | 28 +- src/Mimante/wwwroot/js/state.js | 5 +- tests/Mimante.Tests/ServiceTests.cs | 221 +++++++- 25 files changed, 1070 insertions(+), 223 deletions(-) create mode 100644 src/Mimante/Data/ExportJobs.cs create mode 100644 src/Mimante/Data/Migrations/0003_indice_mie_puntate.sql create mode 100644 src/Mimante/Data/SamplePlan.cs create mode 100644 src/Mimante/wwwroot/js/exports.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 3302071..7d478a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,12 @@ copia nella release la sezione della versione. - **CI su Gitea come Febe**: verifica a ogni push (controlli, segreti, tutte le prove con PostgreSQL, immagine provata e scansionata), rilascio sul tag, pulizia notturna. Nessun flusso pubblica porte sul Docker di Unraid. +- **Esportazioni a memoria costante**: non cadono più con molti dati. Il campione per esito lo sceglie + PostgreSQL e le righe vanno sul file una alla volta, con un tempo massimo e un controllo dello spazio + libero (Impostazioni ▸ Dati e conservazione); sopra 50 MB il file si scarica in `.zip`. Un'esportazione + alla volta, di fondo: la finestra mostra fase e righe, si chiude e si riapre, ha **Annulla** e non + lascia file a metà. Le puntate di risposta si cercano con l'indice (anche alla chiusura delle aste), e + la pagina Apprendimento legge i suoi tre rapporti con una sola lettura invece di tre. ## 1.2.0 diff --git a/docs/architettura.md b/docs/architettura.md index 21f8743..68c6c3f 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -330,6 +330,7 @@ confronta lo stato con l'ultimo spedito e manda solo ciò che è cambiato: | `auction.detail` | il pannello dell'asta selezionata (`auction.watch`), al più ogni 250 ms quando cambia | | `account`, `session`, `risk`, `mode` | quando cambiano | | `net`, `db` | quando cambiano, al più ogni 2 s | +| `export` | l'esportazione in corso o l'ultima (`ExportJobs`): stato, fase, righe scritte su quelle da scrivere, file pronti, messaggio; quando cambia | | `event` | righe del registro (livello ≥ informazione) | | `learning` | ogni 5 s, solo ai client sulla pagina Apprendimento | | `login.frame`, `login.state` | screencast del browser del bot (con l'indirizzo della pagina), a tutti i client | @@ -339,7 +340,7 @@ Dal client: `snapshot`, `page`, `auction.watch`, `auction.add/remove/set_mode/se `all.set_mode`, `auctions.remove_finished`, `resume`, `settings.get/save`, `telegram.test`, `maintenance.run`, `session.verify/paste/logout`, `login.open/close/reload/input/back/forward/navigate/add_current`, `product.follow/save/set/delete`, `products.refresh_stats/recompute_limits/apply_limits/backfill_winners`, -`learning.study_now/recalc/rebuild_bandit/reset_challenger/evaluate/forget`, `export.run`. Con `rid` +`learning.study_now/recalc/rebuild_bandit/reset_challenger/evaluate/forget`, `export.start/cancel` (l'esportazione gira di fondo, una alla volta: la risposta dice solo se è partita). Con `rid` ricevono `{"t":"ack","rid":…,"ok":…,"msg":…,"data":…}`. Due comandi hanno un'anteprima per la conferma: con `preview: true` rispondono solo con il conto, diff --git a/src/Mimante/Data/AuctionRecorder.cs b/src/Mimante/Data/AuctionRecorder.cs index 2687d7a..c5f99e6 100644 --- a/src/Mimante/Data/AuctionRecorder.cs +++ b/src/Mimante/Data/AuctionRecorder.cs @@ -262,12 +262,12 @@ public sealed class AuctionRecorder new object?[] { a.ProductKey, c.BuyNow, c.Shipping }), ("UPDATE my_bids SET " + - " answered_by = (SELECT b.username FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1), " + - " answered_type = (SELECT b.bid_type FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1), " + + " answered_by = (SELECT b.username FROM bids b WHERE b.auction_id = my_bids.auction_id AND b.price_after = my_bids.price + 0.02 LIMIT 1), " + + " answered_type = (SELECT b.bid_type FROM bids b WHERE b.auction_id = my_bids.auction_id AND b.price_after = my_bids.price + 0.02 LIMIT 1), " + " answered_after_s = COALESCE(" + - " (SELECT b2.server_ts - b1.server_ts FROM bids b1, bids b2 WHERE b1.auction_id = my_bids.auction_id AND ABS(b1.price_after - (my_bids.price + 0.01)) < 0.005 AND b1.server_ts > 0 " + - " AND b2.auction_id = my_bids.auction_id AND ABS(b2.price_after - (my_bids.price + 0.02)) < 0.005 AND b2.server_ts > 0 LIMIT 1), " + - " (SELECT b.seen_t - my_bids.t FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1)), " + + " (SELECT b2.server_ts - b1.server_ts FROM bids b1, bids b2 WHERE b1.auction_id = my_bids.auction_id AND b1.price_after = my_bids.price + 0.01 AND b1.server_ts > 0 " + + " AND b2.auction_id = my_bids.auction_id AND b2.price_after = my_bids.price + 0.02 AND b2.server_ts > 0 LIMIT 1), " + + " (SELECT b.seen_t - my_bids.t FROM bids b WHERE b.auction_id = my_bids.auction_id AND b.price_after = my_bids.price + 0.02 LIMIT 1)), " + " unanswered = (my_bids.price + 0.01 >= $2 - 0.005) " + "WHERE auction_id = $1 AND success AND NOT manual", new object?[] { a.Id, c.FinalPrice }), diff --git a/src/Mimante/Data/CsvExport.cs b/src/Mimante/Data/CsvExport.cs index d800164..71bab04 100644 --- a/src/Mimante/Data/CsvExport.cs +++ b/src/Mimante/Data/CsvExport.cs @@ -1,10 +1,13 @@ +using System.Data.Common; using System.Globalization; +using System.IO.Compression; using System.Text; using System.Text.Json; using Mimante.Config; using Mimante.Ml; using Mimante.Products; using Mimante.Settings; +using Npgsql; namespace Mimante.Data; @@ -13,6 +16,12 @@ namespace Mimante.Data; /// ;, UTF-8 con BOM, virgola decimale, intestazioni in italiano, una colonna /// motivazione per riga e un legenda.txt accanto che spiega ogni colonna, i /// filtri, le righe totali ed esportate e, se si è campionato, come. +/// +/// A memoria costante, qualunque sia l'archivio: una connessione dedicata in sola lettura +/// (una transazione REPEATABLE READ, così conteggi e righe vedono gli stessi dati) con il suo +/// tempo massimo, prima i conteggi per esito (), poi solo le righe scelte, +/// lette una alla volta e scritte subito su nome.tmp, rinominato alla fine. Annullare, +/// sforare il tempo o restare senza spazio non lascia file a metà. /// public sealed class CsvExport { @@ -20,10 +29,19 @@ public sealed class CsvExport public sealed record Result(bool Ok, string Message, IReadOnlyList Files, int Rows, bool Sampled); + /// A che punto è: in italiano, righe scritte su quelle da scrivere. + public sealed record Progress(string Phase, long Rows, long Total); + public const string ModelData = "dati_modello"; public const string AuctionHistory = "storico_aste"; public const string ProductsWhat = "prodotti"; + /// Il tetto delle righe di un file, anche quando la richiesta chiede «nessun limite». + public const int MaxRowsCap = 1_000_000; + + /// Ogni quante righe si aggiorna l'avanzamento e si ricontrolla lo spazio libero. + private const int CheckEvery = 5000; + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); private static readonly UTF8Encoding Bom = new(encoderShouldEmitUTF8Identifier: true); @@ -32,34 +50,100 @@ public sealed class CsvExport private readonly ConfigPaths _paths; private readonly Func _settings; private readonly Func _learning; + private readonly Func _freeBytes; - public CsvExport(Db db, WriteQueue queue, ConfigPaths paths, Func settings, Func learning) + public CsvExport(Db db, WriteQueue queue, ConfigPaths paths, Func settings, Func learning, + Func? freeBytes = null) { _db = db; _queue = queue; _paths = paths; _settings = settings; _learning = learning; + _freeBytes = freeBytes ?? FreeBytes; } - public async Task RunAsync(Request req, CancellationToken ct) + /// + /// Esegue l'esportazione. Un annullamento da esce con + /// , il tempo massimo con , + /// la mancanza di spazio con : in tutti i casi senza file a metà. + /// + public async Task RunAsync(Request req, CancellationToken ct, IProgress? progress = null) { Directory.CreateDirectory(_paths.Exports); - await _queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); - var to = (req.To ?? AppInfo.LocalNow.Date).Date; - var from = (req.From ?? to.AddDays(-30)).Date; - if (from > to) (from, to) = (to, from); - var maxRows = req.MaxRows <= 0 ? int.MaxValue : req.MaxRows; - - return req.What switch + var settings = _settings(); + var timeout = TimeSpan.FromMinutes(Math.Max(1, settings.ExportTimeoutMinutes)); + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + limit.CancelAfter(timeout); + try { - ModelData => await ModelDataAsync(req, from, to, maxRows, ct).ConfigureAwait(false), - AuctionHistory => await HistoryAsync(req, from, to, maxRows, ct).ConfigureAwait(false), - ProductsWhat => await ProductsAsync(ct).ConfigureAwait(false), - _ => new Result(false, $"Esportazione sconosciuta: {req.What}", Array.Empty(), 0, false) - }; + progress?.Report(new Progress("Scrivo le righe in coda", 0, 0)); + await _queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + EnsureSpace(settings); + var to = (req.To ?? AppInfo.LocalNow.Date).Date; + var from = (req.From ?? to.AddDays(-30)).Date; + if (from > to) (from, to) = (to, from); + var maxRows = req.MaxRows <= 0 ? MaxRowsCap : Math.Min(req.MaxRows, MaxRowsCap); + + return req.What switch + { + ModelData => await ModelDataAsync(req, from, to, maxRows, settings, progress, limit.Token).ConfigureAwait(false), + AuctionHistory => await HistoryAsync(req, from, to, maxRows, settings, progress, limit.Token).ConfigureAwait(false), + ProductsWhat => await ProductsAsync(settings, limit.Token).ConfigureAwait(false), + _ => new Result(false, $"Esportazione sconosciuta: {req.What}", Array.Empty(), 0, false) + }; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested && limit.IsCancellationRequested) + { + throw new TimeoutException($"L'esportazione ha superato il tempo massimo di {timeout.TotalMinutes:0} minuti (Impostazioni ▸ Dati e conservazione)."); + } + catch (NpgsqlException e) when (!ct.IsCancellationRequested && e.InnerException is TimeoutException) + { + throw new TimeoutException($"L'esportazione ha superato il tempo massimo di {timeout.TotalMinutes:0} minuti (Impostazioni ▸ Dati e conservazione)."); + } } + // ── connessione di sola lettura ────────────────────────────────────── + + /// + /// Una connessione fuori dalle sorgenti del programma (non toglie posti alle pagine né alla coda), + /// con il tempo massimo dell'esportazione, dentro una transazione REPEATABLE READ READ ONLY. + /// + private async Task OpenAsync(AppSettings settings, CancellationToken ct) + { + var builder = _db.Config.Builder(commandTimeoutSeconds: Math.Max(1, settings.ExportTimeoutMinutes) * 60); + builder.Pooling = false; + builder.ApplicationName = "mimante-esportazione"; + var conn = new NpgsqlConnection(builder.ConnectionString); + try + { + await conn.OpenAsync(ct).ConfigureAwait(false); + await using var begin = new NpgsqlCommand("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY", conn); + await begin.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + return conn; + } + catch + { + await conn.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private static async Task> CountsAsync(NpgsqlConnection conn, string sql, object?[] args, CancellationToken ct) + { + var list = new List<(string, long)>(); + await using var cmd = Db.Command(conn, sql, args); + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) list.Add((reader.GetString(0), reader.GetInt64(1))); + return list; + } + + /// I tre parametri del piano per unnest($a::text[], $b::bigint[], $c::bigint[]). + private static object?[] PlanArgs(SamplePlan plan) => new object?[] + { + plan.Groups.Select(g => g.Key).ToArray(), plan.Groups.Select(g => g.Count).ToArray(), plan.Groups.Select(g => g.Quota).ToArray() + }; + // ── dati del modello ───────────────────────────────────────────────── private static readonly string[] ModelHead = @@ -76,84 +160,121 @@ public sealed class CsvExport "previsione_chiusura", "previsione_p10", "previsione_p90", "chiusura_reale", "esito_asta", "motivazione" }; - private async Task ModelDataAsync(Request req, DateTime from, DateTime to, int maxRows, CancellationToken ct) - { - const string sql = - "SELECT d.decision_id, d.ts, d.auction_id, a.name, a.product_key, d.state::text AS state, d.shadow, d.executed, d.price, d.timer, " + - " d.value, a.buy_now_price, a.shipping, d.bid_cost, d.p_model, d.p_bandit, d.own_bid_factor, d.p_win, d.ev, d.action, d.kind, " + - " d.reason_detail, d.champion, d.outcome, a.final_price, a.won_by_me, a.my_bids AS auction_my_bids, " + - " mb.success AS mb_success, mb.planned_lead_ms, mb.actual_lead_ms, mb.ping_ms AS mb_ping, mb.rtt_ms, mb.bids_used, " + - " nb.username AS next_user, nb.bid_type AS next_type, nb.server_ts AS next_ts, pb.server_ts AS prev_ts, " + - " f.forecast_close, f.forecast_close_p10, f.forecast_close_p90 " + - "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + - "LEFT JOIN my_bids mb ON mb.decision_id = d.decision_id " + - "LEFT JOIN LATERAL (SELECT b.username, b.bid_type, b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + - " AND ABS(b.price_after - (d.price + CASE WHEN mb.success THEN 0.02 ELSE 0.01 END)) < 0.005 LIMIT 1) nb ON true " + - "LEFT JOIN LATERAL (SELECT b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + - " AND ABS(b.price_after - (d.price + CASE WHEN mb.success THEN 0.01 ELSE 0 END)) < 0.005 LIMIT 1) pb ON true " + - "LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + - " WHERE x.auction_id = d.auction_id AND x.ts <= d.ts ORDER BY x.ts DESC LIMIT 1) f ON true " + - "WHERE a.type = $1 AND d.ts >= $2 AND d.ts < $3 AND ($4 = false OR a.my_bids > 0) ORDER BY d.ts"; + // ts = created_at su ogni decisione: la condizione su created_at fa scartare le partizioni fuori periodo. + private const string ModelFilter = + "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + + "WHERE a.type = $1 AND d.ts >= $2 AND d.ts < $3 AND d.created_at >= $2 - interval '1 day' AND d.created_at < $3 + interval '1 day' " + + "AND ($4 = false OR a.my_bids > 0)"; - var rows = await _db.QueryAsync(sql, r => r.ToDictionary(), req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids).ConfigureAwait(false); - ct.ThrowIfCancellationRequested(); - var total = rows.Count; - var (kept, sampled, sampleNote) = Stratify(rows, maxRows, r => (r.GetValueOrDefault("outcome") as string) ?? "senza esito"); + private const string ModelGroup = "coalesce(d.outcome, 'senza esito')"; + + // La puntata dopo la decisione e quella che aveva fatto il prezzo: uguaglianza esatta su price_after (numeric(10,2), usa + // l'indice (auction_id, price_after)) e una finestra su created_at, che lascia leggere solo le partizioni vicine. + private const string ModelSelect = + "SELECT d.decision_id, d.ts, d.auction_id, a.name, a.product_key, d.state::text AS state, d.shadow, d.executed, d.price, d.timer, " + + " d.value, a.buy_now_price, a.shipping, d.bid_cost, d.p_model, d.p_bandit, d.own_bid_factor, d.p_win, d.ev, d.action, d.kind, " + + " d.reason_detail, d.champion, d.outcome, a.final_price, a.won_by_me, a.my_bids AS auction_my_bids, " + + " mb.success AS mb_success, mb.planned_lead_ms, mb.actual_lead_ms, mb.ping_ms AS mb_ping, mb.rtt_ms, mb.bids_used, " + + " nb.username AS next_user, nb.bid_type AS next_type, nb.server_ts AS next_ts, pb.server_ts AS prev_ts, " + + " f.forecast_close, f.forecast_close_p10, f.forecast_close_p90 "; + + private const string ModelJoins = + "LEFT JOIN my_bids mb ON mb.decision_id = d.decision_id " + + "LEFT JOIN LATERAL (SELECT b.username, b.bid_type, b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + + " AND b.price_after = d.price + CASE WHEN mb.success THEN 0.02 ELSE 0.01 END " + + " AND b.created_at >= d.ts - interval '2 days' AND b.created_at < d.ts + interval '2 days' LIMIT 1) nb ON true " + + "LEFT JOIN LATERAL (SELECT b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + + " AND b.price_after = d.price + CASE WHEN mb.success THEN 0.01 ELSE 0 END " + + " AND b.created_at >= d.ts - interval '2 days' AND b.created_at < d.ts + interval '2 days' LIMIT 1) pb ON true " + + "LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + + " WHERE x.auction_id = d.auction_id AND x.ts <= d.ts ORDER BY x.ts DESC LIMIT 1) f ON true "; + + /// L'interrogazione delle righe: tutte, oppure solo quelle scelte dal piano (stessa regola di ). + internal static string ModelRowsSql(bool sampled) => sampled + ? "WITH pick AS (SELECT x.decision_id, x.created_at FROM (" + + $" SELECT d.decision_id, d.created_at, {ModelGroup} AS grp, row_number() OVER (PARTITION BY {ModelGroup} ORDER BY d.ts, d.decision_id) AS rn " + + $" {ModelFilter}) x " + + " JOIN unnest($5::text[], $6::bigint[], $7::bigint[]) AS p(grp, n, q) ON p.grp = x.grp " + + " WHERE ((x.rn - 1) * p.q) % p.n < p.q) " + + ModelSelect + + "FROM pick k JOIN bot_decisions d ON d.decision_id = k.decision_id AND d.created_at = k.created_at " + + "JOIN auctions a ON a.auction_id = d.auction_id " + ModelJoins + "ORDER BY d.ts, d.decision_id" + : ModelSelect + ModelFilter.Replace("WHERE", ModelJoins + "WHERE") + " ORDER BY d.ts, d.decision_id"; + + private async Task ModelDataAsync(Request req, DateTime from, DateTime to, int maxRows, AppSettings settings, + IProgress? progress, CancellationToken ct) + { + var args = new object?[] { req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids }; + await using var conn = await OpenAsync(settings, ct).ConfigureAwait(false); + progress?.Report(new Progress("Conto le decisioni", 0, 0)); + var counts = await CountsAsync(conn, $"SELECT {ModelGroup} AS grp, count(*) AS n {ModelFilter} GROUP BY 1 ORDER BY 1", args, ct).ConfigureAwait(false); + var plan = SamplePlan.For(counts, maxRows); var learning = _learning(req.World); var brier = learning?.BrierScores; var calibration = learning?.CalibrationFactor; var name = $"dati-modello-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}.csv"; - var sb = new StringBuilder(); - Line(sb, ModelHead.Concat(BidFeatures.Names).Concat(ModelTail)); - foreach (var r in kept) + await using var cmd = Db.Command(conn, ModelRowsSql(plan.Sampled), plan.Sampled ? args.Concat(PlanArgs(plan)).ToArray() : args); + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + var r = Row.Of(reader); + await using var file = new CsvFile(Path.Combine(_paths.Exports, name)); + file.Line(ModelHead.Concat(BidFeatures.Names).Concat(ModelTail)); + using var stop = new CancelUnlessDone(cmd); + var cells = new List(ModelHead.Length + BidFeatures.Size + ModelTail.Length); + var written = 0; + progress?.Report(new Progress("Scrivo le decisioni", 0, plan.Kept)); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) { - var ctx = ReadContext(r.GetValueOrDefault("state") as string, out var stateBalance, out var statePaid, out var stateFree); + var ctx = ReadContext(r["state"] as string, out var stateBalance, out var statePaid, out var stateFree); var features = ctx is { } c ? BidFeatures.Build(c) : null; var shadow = (bool)(r["shadow"] ?? true); var executed = (bool)(r["executed"] ?? false); - var outcome = r.GetValueOrDefault("outcome") as string; + var outcome = r["outcome"] as string; var unanswered = outcome != null ? ShadowReport.Unanswered(outcome) : (bool?)null; var verdict = (r["action"] as string) == "BID" ? ((r["kind"] as string) == LossReasons.Kind.Esplora ? "esplora" : "punta") : "no"; var nextTs = Long(r, "next_ts"); var prevTs = Long(r, "prev_ts"); double? after = nextTs is > 0 && prevTs is > 0 ? nextTs - prevTs : null; - var champion = r.GetValueOrDefault("champion") as string; + var champion = r["champion"] as string; var wonByMe = (bool)(r["won_by_me"] ?? false); var outcomeAuction = r["final_price"] == null ? "in corso" : wonByMe ? "vinta" : Int(r, "auction_my_bids") > 0 ? "persa" : "osservata"; - var cells = new List + cells.Clear(); + cells.AddRange(new[] { Str(r, "decision_id"), Ts(r, "ts"), Str(r, "auction_id"), Str(r, "name"), Str(r, "product_key"), "", shadow ? "osserva" : "attiva", shadow ? "no" : "si", Num(r, "price", 2), Num(r, "timer", 2), Num(r, "value", 2), Num(r, "buy_now_price", 2), Num(r, "shipping", 2), Num(r, "bid_cost", 3), stateBalance?.ToString(It), statePaid?.ToString(It), stateFree?.ToString(It) - }; - if (features != null) cells.AddRange(features.Select(v => v.ToString("0.####", It))); - else cells.AddRange(Enumerable.Repeat("", BidFeatures.Size)); + }); + if (features != null) foreach (var v in features) cells.Add(v.ToString("0.####", It)); + else for (var i = 0; i < BidFeatures.Size; i++) cells.Add(""); - var motivation = Motivation(verdict, r, unanswered, after); cells.AddRange(new[] { Num(r, "p_model", 5), Num(r, "p_bandit", 5), Num(r, "own_bid_factor", 3), Num(r, "p_win", 5), Num(r, "ev", 3), verdict, KindLabel(r["kind"] as string), Str(r, "reason_detail"), champion == "rete" ? "rete" : champion == null ? "" : "logit", brier is { } b ? Fmt(champion == "rete" ? b.Net : b.Logit, 5) : "", calibration is { } cal ? Fmt(cal, 3) : "", - unanswered is { } u ? (u ? "si" : "no") : "", Str(r, "next_user"), TypeLabel(r.GetValueOrDefault("next_type") as string), + unanswered is { } u ? (u ? "si" : "no") : "", Str(r, "next_user"), TypeLabel(r["next_type"] as string), after is { } a ? Fmt(a, 0) : "", executed ? "si" : "no", r["mb_success"] is bool ok ? (ok ? "si" : "no") : "", Num(r, "planned_lead_ms", 0), Num(r, "actual_lead_ms", 1), Num(r, "mb_ping", 0), Num(r, "rtt_ms", 0), Num(r, "bids_used", 0), Num(r, "forecast_close", 2), Num(r, "forecast_close_p10", 2), Num(r, "forecast_close_p90", 2), Num(r, "final_price", 2), - outcomeAuction, motivation + outcomeAuction, Motivation(verdict, r, unanswered, after) }); - Line(sb, cells); + file.Line(cells); + if (++written % CheckEvery == 0) Checkpoint(settings, progress, "Scrivo le decisioni", written, plan.Kept); } + stop.Done = true; + await reader.DisposeAsync().ConfigureAwait(false); + await CommitAsync(conn, ct).ConfigureAwait(false); - await WriteAsync(name, sb, ct).ConfigureAwait(false); - var legend = await WriteLegendAsync("dati-modello", from, to, req, total, kept.Count, sampleNote, ModelLegend(), ct).ConfigureAwait(false); - return new Result(true, Summary(name, kept.Count, total, sampled), new[] { name, legend }, kept.Count, sampled); + var csv = await FinishAsync(file, settings, progress, ct).ConfigureAwait(false); + var legend = await WriteLegendAsync("dati-modello", from, to, req, plan.Total, written, plan.Note, ModelLegend(), ct).ConfigureAwait(false); + return new Result(true, Summary(csv, written, plan.Total, plan.Sampled), new[] { csv, legend }, written, plan.Sampled); } - private static string Motivation(string verdict, Dictionary r, bool? unanswered, double? after) + private static string Motivation(string verdict, Row r, bool? unanswered, double? after) { var shadow = (bool)(r["shadow"] ?? true); var price = Num(r, "price", 2); @@ -254,29 +375,56 @@ public sealed class CsvExport "errore_previsione", "nell_intervallo", "motivo_perdita", "motivazione" }; - private async Task HistoryAsync(Request req, DateTime from, DateTime to, int maxRows, CancellationToken ct) - { - const string sql = - "SELECT a.*, " + - " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id) AS dec_total, " + - " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id AND d.action = 'BID' AND d.kind <> 'esplora') AS dec_bid, " + - " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id AND d.kind = 'esplora') AS dec_explore, " + - " f.forecast_close AS f_close, f.forecast_close_p10 AS f_p10, f.forecast_close_p90 AS f_p90 " + - "FROM auctions a LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + - " WHERE x.auction_id = a.auction_id ORDER BY x.is_initial DESC, x.ts LIMIT 1) f ON true " + - "WHERE a.type = $1 AND a.outcome IS NOT NULL AND a.end_time >= $2 AND a.end_time < $3 AND ($4 = false OR a.my_bids > 0) " + - "ORDER BY a.end_time"; + private const string HistoryFilter = + "FROM auctions a WHERE a.type = $1 AND a.outcome IS NOT NULL AND a.end_time >= $2 AND a.end_time < $3 AND ($4 = false OR a.my_bids > 0)"; - var rows = await _db.QueryAsync(sql, r => r.ToDictionary(), req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids).ConfigureAwait(false); - ct.ThrowIfCancellationRequested(); - var total = rows.Count; - var (kept, sampled, note) = Stratify(rows, maxRows, r => (bool)(r["won_by_me"] ?? false) ? "vinta" : Int(r, "my_bids") > 0 ? "persa" : "osservata"); - var fee = _settings().TransactionFeeEuro; + private const string HistoryGroup = "CASE WHEN a.won_by_me THEN 'vinta' WHEN a.my_bids > 0 THEN 'persa' ELSE 'osservata' END"; + + // Solo le colonne che servono (non price_series, bids_by_user e config, che sono jsonb grandi) e un solo passaggio sulle + // decisioni dell'asta per i tre conteggi. + private const string HistorySelect = + "SELECT a.auction_id, a.name, a.product_key, a.opened_at, a.first_seen_at, a.end_time, a.observed_minutes, a.observed_from_start, " + + " a.observed_to_end, a.mode_at_close, a.final_price, a.winner_user, a.won_by_me, a.my_bids, a.my_bids_cost, a.winner_bids_paid, " + + " a.winner_bids_free, a.total_observed_bids, a.distinct_bidders, a.top_bidder_share, a.resets, a.buy_now_price, a.market_value, " + + " a.shipping, a.transaction_fee, a.price_velocity_per_minute, a.avg_ping_ms, a.p95_ping_ms, a.p99_ping_ms, a.configured_lead_ms, " + + " a.lead_is_manual, a.successful_bids, a.failed_bids, a.loss_reason, " + + " dc.dec_total, dc.dec_bid, dc.dec_explore, f.forecast_close AS f_close, f.forecast_close_p10 AS f_p10, f.forecast_close_p90 AS f_p90 "; + + private const string HistoryJoins = + "LEFT JOIN LATERAL (SELECT count(*) AS dec_total, count(*) FILTER (WHERE d.action = 'BID' AND d.kind <> 'esplora') AS dec_bid, " + + " count(*) FILTER (WHERE d.kind = 'esplora') AS dec_explore FROM bot_decisions d WHERE d.auction_id = a.auction_id) dc ON true " + + "LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + + " WHERE x.auction_id = a.auction_id ORDER BY x.is_initial DESC, x.ts LIMIT 1) f ON true "; + + internal static string HistoryRowsSql(bool sampled) => sampled + ? "WITH pick AS (SELECT x.auction_id FROM (" + + $" SELECT a.auction_id, {HistoryGroup} AS grp, row_number() OVER (PARTITION BY {HistoryGroup} ORDER BY a.end_time, a.auction_id) AS rn " + + $" {HistoryFilter}) x " + + " JOIN unnest($5::text[], $6::bigint[], $7::bigint[]) AS p(grp, n, q) ON p.grp = x.grp " + + " WHERE ((x.rn - 1) * p.q) % p.n < p.q) " + + HistorySelect + "FROM pick k JOIN auctions a ON a.auction_id = k.auction_id " + HistoryJoins + "ORDER BY a.end_time, a.auction_id" + : HistorySelect + HistoryFilter.Replace("WHERE", HistoryJoins + "WHERE") + " ORDER BY a.end_time, a.auction_id"; + + private async Task HistoryAsync(Request req, DateTime from, DateTime to, int maxRows, AppSettings settings, + IProgress? progress, CancellationToken ct) + { + var args = new object?[] { req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids }; + await using var conn = await OpenAsync(settings, ct).ConfigureAwait(false); + progress?.Report(new Progress("Conto le aste", 0, 0)); + var counts = await CountsAsync(conn, $"SELECT {HistoryGroup} AS grp, count(*) AS n {HistoryFilter} GROUP BY 1 ORDER BY 1", args, ct).ConfigureAwait(false); + var plan = SamplePlan.For(counts, maxRows); + var fee = settings.TransactionFeeEuro; var name = $"storico-aste-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}.csv"; - var sb = new StringBuilder(); - Line(sb, HistoryHead); - foreach (var r in kept) + await using var cmd = Db.Command(conn, HistoryRowsSql(plan.Sampled), plan.Sampled ? args.Concat(PlanArgs(plan)).ToArray() : args); + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + var r = Row.Of(reader); + await using var file = new CsvFile(Path.Combine(_paths.Exports, name)); + file.Line(HistoryHead); + using var stop = new CancelUnlessDone(cmd); + var written = 0; + progress?.Report(new Progress("Scrivo le aste", 0, plan.Kept)); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) { var final = Dbl(r, "final_price") ?? 0; var myCost = Dbl(r, "my_bids_cost") ?? 0; @@ -288,12 +436,12 @@ public sealed class CsvExport var fClose = Dbl(r, "f_close"); var p10 = Dbl(r, "f_p10"); var p90 = Dbl(r, "f_p90"); - var decTotal = Int(r, "dec_total") ?? 0; - var decBid = Int(r, "dec_bid") ?? 0; - var decExplore = Int(r, "dec_explore") ?? 0; + var decTotal = Long(r, "dec_total") ?? 0; + var decBid = Long(r, "dec_bid") ?? 0; + var decExplore = Long(r, "dec_explore") ?? 0; var loss = Str(r, "loss_reason"); - Line(sb, new[] + file.Line(new[] { Str(r, "auction_id"), Str(r, "name"), Str(r, "product_key"), "", Ts(r, "opened_at") is { Length: > 0 } o ? o : Ts(r, "first_seen_at"), Ts(r, "end_time"), Num(r, "observed_minutes", 1), YesNo(r, "observed_from_start"), YesNo(r, "observed_to_end"), Str(r, "mode_at_close"), @@ -308,14 +456,18 @@ public sealed class CsvExport p10 is { } lo && p90 is { } hi ? (final >= lo - 0.005 && final <= hi + 0.005 ? "si" : "no") : "", loss, HistoryMotivation(r, won, final, value, realCost, fClose, loss) }); + if (++written % CheckEvery == 0) Checkpoint(settings, progress, "Scrivo le aste", written, plan.Kept); } + stop.Done = true; + await reader.DisposeAsync().ConfigureAwait(false); + await CommitAsync(conn, ct).ConfigureAwait(false); - await WriteAsync(name, sb, ct).ConfigureAwait(false); - var legend = await WriteLegendAsync("storico-aste", from, to, req, total, kept.Count, note, HistoryLegend(), ct).ConfigureAwait(false); - return new Result(true, Summary(name, kept.Count, total, sampled), new[] { name, legend }, kept.Count, sampled); + var csv = await FinishAsync(file, settings, progress, ct).ConfigureAwait(false); + var legend = await WriteLegendAsync("storico-aste", from, to, req, plan.Total, written, plan.Note, HistoryLegend(), ct).ConfigureAwait(false); + return new Result(true, Summary(csv, written, plan.Total, plan.Sampled), new[] { csv, legend }, written, plan.Sampled); } - private static string HistoryMotivation(Dictionary r, bool won, double final, double? value, double realCost, double? forecast, string? loss) + private static string HistoryMotivation(Row r, bool won, double final, double? value, double realCost, double? forecast, string? loss) { var sb = new StringBuilder(); var winner = Str(r, "winner_user"); @@ -359,15 +511,16 @@ public sealed class CsvExport // ── prodotti ───────────────────────────────────────────────────────── - private async Task ProductsAsync(CancellationToken ct) + private async Task ProductsAsync(AppSettings settings, CancellationToken ct) { - var settings = _settings(); - var products = await _db.QueryAsync("SELECT * FROM products ORDER BY display_name", r => r.ToDictionary()).ConfigureAwait(false); + // Poche centinaia di righe: bastano le letture normali. + var products = (await _db.QueryAsync("SELECT * FROM products ORDER BY display_name", r => r.ToDictionary()).ConfigureAwait(false)) + .Select(Row.Of).ToList(); var stats = await ProductStatsRepository.LoadAllAsync(_db).ConfigureAwait(false); var keys = products.Select(p => Str(p, "product_key")).Union(stats.Keys).Where(k => !string.IsNullOrEmpty(k)).Distinct().ToList(); var name = $"prodotti-{AppInfo.LocalNow:yyyy-MM-dd}.csv"; - var sb = new StringBuilder(); - Line(sb, new[] + await using var file = new CsvFile(Path.Combine(_paths.Exports, name)); + file.Line(new[] { "chiave_prodotto", "prodotto", "seguito", "prezzo_max", "puntate_max", "valore_reale", "orizzonte_min", "modo_aggiunta", "aste_concluse", "vinte", "con_mie_puntate", "mie_puntate", "costo_mie_puntate", "chiusura_media", "chiusura_min", "chiusura_max", @@ -385,7 +538,7 @@ public sealed class CsvExport s.RecentCloses, s.RecentWinnerBids, value ?? s.BuyNow, s.Shipping, maxBids ?? settings.DefaultMaxClicks, settings.AverageBidCostEuro, settings.SuggestedValueTolerancePercent, settings.SuggestedCoveragePercent / 100.0, settings.SuggestedMinPercentile / 100.0)); - Line(sb, new[] + file.Line(new[] { key, p != null ? Str(p, "display_name") : s?.Name, p != null ? YesNo(p, "followed") : "no", p != null ? Num(p, "max_price", 2) : "", maxBids?.ToString(It), value is { } v ? Fmt(v, 2) : "", p != null ? Num(p, "horizon_minutes", 0) : "", p != null ? Str(p, "auto_state") : "", @@ -396,7 +549,7 @@ public sealed class CsvExport advice is { HasAdvice: true, MaxPrice: { } am } ? Fmt(am, 2) : "", advice?.MaxBids?.ToString(It), advice?.Explanation }); } - await WriteAsync(name, sb, ct).ConfigureAwait(false); + var csv = await FinishAsync(file, settings, null, ct).ConfigureAwait(false); var legend = await WriteLegendAsync("prodotti", AppInfo.LocalNow.Date, AppInfo.LocalNow.Date, new Request(ProductsWhat, null, null, false, 0, Worlds.Real), keys.Count, keys.Count, null, new List { @@ -408,39 +561,143 @@ public sealed class CsvExport "costo_reale_medio_vinte, risparmio_medio_vinte: sulle aste vinte da me", "consigliato_prezzo_max, consigliato_puntate_max, motivazione: il consiglio e il suo ragionamento (solo un consiglio)" }, ct).ConfigureAwait(false); - return new Result(true, $"Esportati {keys.Count} prodotti in {name}", new[] { name, legend }, keys.Count, false); + return new Result(true, $"Esportati {keys.Count} prodotti in {csv}", new[] { csv, legend }, keys.Count, false); } - // ── aiuti ──────────────────────────────────────────────────────────── + // ── file ───────────────────────────────────────────────────────────── /// - /// Se le righe superano il tetto si tiene, per ogni gruppo (esito), una quota proporzionale - /// (almeno una riga per gruppo), prendendo righe equidistanti nel tempo: il campione - /// conserva sia le proporzioni sia la distribuzione nel periodo. + /// Se la scrittura si ferma a metà (spazio, errore) la lettura va interrotta sul server: chiudere il lettore + /// altrimenti farebbe scorrere a Npgsql tutte le righe restanti. Va dichiarato dopo il lettore, così si chiude prima. /// - internal static (List Kept, bool Sampled, string? Note) Stratify(List rows, int max, Func group) + private sealed class CancelUnlessDone(NpgsqlCommand cmd) : IDisposable { - if (rows.Count <= max) return (rows, false, null); - var groups = rows.Select((r, i) => (r, i)).GroupBy(x => group(x.r)).ToList(); - var kept = new List<(T Row, int Index)>(); - var notes = new List(); - foreach (var g in groups) + public bool Done { get; set; } + + public void Dispose() { - var items = g.ToList(); - var quota = Math.Max(1, (int)Math.Round((double)items.Count * max / rows.Count)); - quota = Math.Min(quota, items.Count); - var step = (double)items.Count / quota; - for (var k = 0; k < quota; k++) kept.Add((items[(int)(k * step)].r, items[(int)(k * step)].i)); - notes.Add($"{g.Key}: {quota} su {items.Count}"); + if (Done) return; + try { cmd.Cancel(); } catch (Exception e) when (e is NpgsqlException or InvalidOperationException) { } } - var list = kept.OrderBy(x => x.Index).Select(x => x.Row).ToList(); - return (list, true, $"Campionamento stratificato per esito (righe equidistanti nel tempo dentro ogni gruppo): {string.Join("; ", notes)}"); } - private async Task WriteAsync(string name, StringBuilder sb, CancellationToken ct) => - await File.WriteAllTextAsync(Path.Combine(_paths.Exports, name), sb.ToString(), Bom, ct).ConfigureAwait(false); + /// + /// Un CSV scritto riga per riga su nome.tmp: una sola riga alla volta in memoria. + /// lo rinomina nel nome vero; chiuso senza (annullamento, errore) cancella il .tmp. + /// + private sealed class CsvFile : IAsyncDisposable + { + private readonly StreamWriter _writer; + private readonly StringBuilder _line = new(4096); + private bool _done; - private async Task WriteLegendAsync(string prefix, DateTime from, DateTime to, Request req, int total, int exported, string? note, + public string Path { get; } + public string TempPath { get; } + + public CsvFile(string path) + { + Path = path; + TempPath = path + ".tmp"; + _writer = new StreamWriter(new FileStream(TempPath, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: false), Bom, 1 << 16); + } + + public void Line(IEnumerable cells) + { + _line.Clear(); + CsvExport.Line(_line, cells); + _writer.Write(_line); + } + + public async Task CompleteAsync(CancellationToken ct) + { + await _writer.FlushAsync(ct).ConfigureAwait(false); + await _writer.DisposeAsync().ConfigureAwait(false); + File.Move(TempPath, Path, overwrite: true); + _done = true; + } + + public async ValueTask DisposeAsync() + { + if (_done) return; + try { await _writer.DisposeAsync().ConfigureAwait(false); } catch (IOException) { } + try { File.Delete(TempPath); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + } + + /// Rinomina il file e, se supera la soglia delle impostazioni, lo consegna in .zip. Restituisce il nome da scaricare. + private async Task FinishAsync(CsvFile file, AppSettings settings, IProgress? progress, CancellationToken ct) + { + await file.CompleteAsync(ct).ConfigureAwait(false); + var size = new FileInfo(file.Path).Length; + if (settings.ExportZipAboveMb <= 0 || size <= (long)settings.ExportZipAboveMb << 20) return System.IO.Path.GetFileName(file.Path); + + progress?.Report(new Progress("Comprimo il file", 0, 0)); + EnsureSpace(settings); + var zip = file.Path + ".zip"; + var tmp = zip + ".tmp"; + try + { + await using (var output = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true)) + using (var archive = new ZipArchive(output, ZipArchiveMode.Create)) + { + var entry = archive.CreateEntry(System.IO.Path.GetFileName(file.Path), CompressionLevel.Optimal); + await using var to = entry.Open(); + await using var from = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, useAsync: true); + await from.CopyToAsync(to, ct).ConfigureAwait(false); + } + File.Move(tmp, zip, overwrite: true); + File.Delete(file.Path); + return System.IO.Path.GetFileName(zip); + } + catch + { + try { File.Delete(tmp); } catch (IOException) { } + throw; + } + } + + private static async Task CommitAsync(NpgsqlConnection conn, CancellationToken ct) + { + await using var commit = new NpgsqlCommand("COMMIT", conn); + await commit.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + } + + private void Checkpoint(AppSettings settings, IProgress? progress, string phase, long rows, long total) + { + progress?.Report(new Progress(phase, rows, total)); + EnsureSpace(settings); + } + + private void EnsureSpace(AppSettings settings) + { + if (settings.ExportMinFreeMb <= 0) return; + if (_freeBytes(_paths.Exports) is { } free && free < (long)settings.ExportMinFreeMb << 20) + throw new IOException($"Spazio libero insufficiente per l'esportazione: {free >> 20} MB, ne servono almeno {settings.ExportMinFreeMb} (Impostazioni ▸ Dati e conservazione)."); + } + + /// + /// Lo spazio libero del volume che contiene : su Linux il punto di montaggio più lungo che lo + /// contiene (per /config/esportazioni è il volume di /config, non la radice del contenitore). Null se non si sa. + /// + internal static long? FreeBytes(string dir) + { + try + { + var full = System.IO.Path.GetFullPath(dir); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var drive = DriveInfo.GetDrives() + .Where(d => full.StartsWith(d.RootDirectory.FullName, comparison)) + .OrderByDescending(d => d.RootDirectory.FullName.Length) + .FirstOrDefault(d => d.IsReady); + return drive?.AvailableFreeSpace; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private async Task WriteLegendAsync(string prefix, DateTime from, DateTime to, Request req, long total, long exported, string? note, List columns, CancellationToken ct) { var name = $"{prefix}-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}-legenda.txt"; @@ -448,18 +705,18 @@ public sealed class CsvExport sb.AppendLine($"{AppInfo.Name} {AppInfo.Version}, variabili del modello versione {BidFeatures.Version}"); sb.AppendLine($"Esportato il {AppInfo.LocalNow:dd/MM/yyyy HH:mm}"); sb.AppendLine($"Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy} compreso; mondo: {(req.World == Worlds.Simulator ? "simulatore" : "sito vero")}"); - sb.AppendLine($"Filtri: {(req.OnlyMyBids ? "solo aste con mie puntate" : "tutte le aste")}; limite di righe {(req.MaxRows > 0 ? req.MaxRows.ToString("N0", It) : "nessuno")}"); + sb.AppendLine($"Filtri: {(req.OnlyMyBids ? "solo aste con mie puntate" : "tutte le aste")}; limite di righe {(req.MaxRows > 0 ? Math.Min(req.MaxRows, MaxRowsCap).ToString("N0", It) : MaxRowsCap.ToString("N0", It))}"); sb.AppendLine($"Righe trovate: {total.ToString("N0", It)}; esportate: {exported.ToString("N0", It)}"); if (note != null) sb.AppendLine(note); sb.AppendLine("Formato: delimitatore punto e virgola, UTF-8 con BOM, virgola decimale, date in ora locale (gg/mm/aaaa hh:mm:ss)"); sb.AppendLine(); sb.AppendLine("Colonne:"); foreach (var c in columns) sb.AppendLine("- " + c); - await File.WriteAllTextAsync(Path.Combine(_paths.Exports, name), sb.ToString(), Bom, ct).ConfigureAwait(false); + await File.WriteAllTextAsync(System.IO.Path.Combine(_paths.Exports, name), sb.ToString(), Bom, ct).ConfigureAwait(false); return name; } - private static string Summary(string name, int kept, int total, bool sampled) => + private static string Summary(string name, long kept, long total, bool sampled) => sampled ? $"Esportate {kept:N0} righe su {total:N0} (campione stratificato) in {name}" : $"Esportate {kept:N0} righe in {name}"; internal static void Line(StringBuilder sb, IEnumerable cells) @@ -481,17 +738,45 @@ public sealed class CsvExport return clean.IndexOfAny(new[] { ';', '"' }) >= 0 ? "\"" + clean.Replace("\"", "\"\"") + "\"" : clean; } + // ── righe ──────────────────────────────────────────────────────────── + + /// + /// La riga corrente letta per nome di colonna: NULL e colonne assenti valgono null, numeric diventa double. + /// Su un lettore legge sempre la riga su cui si trova, senza copiarla. + /// + private sealed class Row + { + private readonly Func _get; + private Row(Func get) => _get = get; + + public object? this[string column] => _get(column); + + public static Row Of(Dictionary d) => new(k => d.GetValueOrDefault(k)); + + public static Row Of(DbDataReader reader) + { + var ordinals = new Dictionary(reader.FieldCount, StringComparer.Ordinal); + for (var i = 0; i < reader.FieldCount; i++) ordinals.TryAdd(reader.GetName(i), i); + return new Row(k => + { + if (!ordinals.TryGetValue(k, out var i) || reader.IsDBNull(i)) return null; + var v = reader.GetValue(i); + return v is decimal m ? (double)m : v; + }); + } + } + private static DateTime Utc(DateTime localDate) => TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(localDate, DateTimeKind.Unspecified), AppInfo.TimeZone); - private static string? Str(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v ? Convert.ToString(v, CultureInfo.InvariantCulture) : null; - private static double? Dbl(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToDouble(v, CultureInfo.InvariantCulture) : null; - private static int? Int(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToInt32(v, CultureInfo.InvariantCulture) : null; - private static long? Long(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToInt64(v, CultureInfo.InvariantCulture) : null; - private static string Num(Dictionary r, string k, int digits) => Dbl(r, k) is { } d ? Fmt(d, digits) : ""; + private static string? Str(Row r, string k) => r[k] is { } v ? Convert.ToString(v, CultureInfo.InvariantCulture) : null; + private static double? Dbl(Row r, string k) => r[k] is { } v ? Convert.ToDouble(v, CultureInfo.InvariantCulture) : null; + private static int? Int(Row r, string k) => r[k] is { } v ? Convert.ToInt32(v, CultureInfo.InvariantCulture) : null; + private static long? Long(Row r, string k) => r[k] is { } v ? Convert.ToInt64(v, CultureInfo.InvariantCulture) : null; + private static string Num(Row r, string k, int digits) => Dbl(r, k) is { } d ? Fmt(d, digits) : ""; private static string Fmt(double v, int digits) => double.IsNaN(v) ? "" : v.ToString(digits == 0 ? "0" : "0." + new string('#', digits), It); - private static string YesNo(Dictionary r, string k) => r.GetValueOrDefault(k) is bool b ? (b ? "si" : "no") : ""; + private static string YesNo(Row r, string k) => r[k] is bool b ? (b ? "si" : "no") : ""; - private static string Ts(Dictionary r, string k) => r.GetValueOrDefault(k) switch + private static string Ts(Row r, string k) => r[k] switch { DateTime d => AppInfo.ToLocal(d.Kind == DateTimeKind.Utc ? d : DateTime.SpecifyKind(d, DateTimeKind.Utc)).ToString("dd/MM/yyyy HH:mm:ss", It), DateTimeOffset o => AppInfo.ToLocal(o.UtcDateTime).ToString("dd/MM/yyyy HH:mm:ss", It), diff --git a/src/Mimante/Data/Db.cs b/src/Mimante/Data/Db.cs index bd47ef1..ea826fc 100644 --- a/src/Mimante/Data/Db.cs +++ b/src/Mimante/Data/Db.cs @@ -88,6 +88,19 @@ public sealed class Db : IAsyncDisposable return list; } + /// + /// Le righe di una lettura una alla volta, senza tenerle: per i riepiloghi su molte righe. Usa la sorgente + /// delle letture con un tempo massimo suo (), perché scorre più dati di una pagina. + /// + public async Task ForEachAsync(string sql, Action row, int timeoutSeconds, CancellationToken ct, params object?[] args) + { + await using var conn = await Reader.OpenConnectionAsync(ct).ConfigureAwait(false); + await using var cmd = Command(conn, sql, args); + cmd.CommandTimeout = timeoutSeconds; + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) row(reader); + } + public async Task QueryOneAsync(string sql, Func map, params object?[] args) where T : class { var rows = await QueryAsync(sql, map, args).ConfigureAwait(false); diff --git a/src/Mimante/Data/ExportJobs.cs b/src/Mimante/Data/ExportJobs.cs new file mode 100644 index 0000000..74001ce --- /dev/null +++ b/src/Mimante/Data/ExportJobs.cs @@ -0,0 +1,144 @@ +using Mimante.Logging; + +namespace Mimante.Data; + +/// +/// Le esportazioni come lavoro di fondo: una alla volta, annullabile, con lo stato sempre leggibile +/// (). L'interfaccia lo riceve come blocco del WebSocket, così l'avanzamento +/// sopravvive a una ricarica della pagina e la richiesta non resta appesa a un comando con il suo +/// tempo massimo. Lo spegnimento del bot annulla il lavoro in corso. +/// +public sealed class ExportJobs +{ + /// + /// Lo stato. : idle (mai partita), running, done, + /// failed, cancelled. + /// + public sealed record Status( + string State, string What, string Phase, long Rows, long Total, IReadOnlyList Files, string? Message, bool Sampled, + DateTime? StartedUtc, DateTime? EndedUtc) + { + public bool Running => State == "running"; + } + + public static readonly Status Idle = new("idle", "", "", 0, 0, Array.Empty(), null, false, null, null); + + private readonly Func, Task> _run; + private readonly AppLog _log; + private readonly CancellationToken _lifetime; + private readonly object _gate = new(); + private CancellationTokenSource? _cts; + private volatile Status _status = Idle; + + public ExportJobs(CsvExport export, AppLog log, CancellationToken lifetime) + : this((req, ct, progress) => export.RunAsync(req, ct, progress), log, lifetime) + { + } + + /// Con un esecutore qualsiasi: per le prove. + internal ExportJobs(Func, Task> run, AppLog log, + CancellationToken lifetime) + { + _run = run; + _log = log; + _lifetime = lifetime; + } + + public Status Current => _status; + + /// Il lavoro in corso, per chi deve aspettarlo (prove, spegnimento). + public Task Running { get; private set; } = Task.CompletedTask; + + /// Fa partire l'esportazione; false con il motivo se ce n'è già una in corso. + public (bool Ok, string Message) Start(CsvExport.Request req) + { + lock (_gate) + { + if (_status.Running) return (false, $"C'è già un'esportazione in corso ({Label(_status.What)}): aspetta che finisca o annullala."); + var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime); + _cts = cts; + var started = DateTime.UtcNow; + _status = new Status("running", req.What, "In partenza", 0, 0, Array.Empty(), null, false, started, null); + var progress = new Reporter(this, req.What, started); + Running = Task.Run(() => RunAsync(req, cts, progress, started)); + return (true, $"Esportazione partita: {Label(req.What)}"); + } + } + + /// Annulla l'esportazione in corso; false se non ce n'è. + public bool Cancel() + { + lock (_gate) + { + if (!_status.Running || _cts == null) return false; + _status = _status with { Phase = "Annullamento in corso" }; + _cts.Cancel(); + return true; + } + } + + private async Task RunAsync(CsvExport.Request req, CancellationTokenSource cts, Reporter progress, DateTime started) + { + Status end; + try + { + var r = await _run(req, cts.Token, progress).ConfigureAwait(false); + end = new Status(r.Ok ? "done" : "failed", req.What, r.Ok ? "Finita" : "Non riuscita", r.Rows, r.Rows, r.Files, r.Message, r.Sampled, + started, DateTime.UtcNow); + if (r.Ok) _log.Info("ESPORTAZIONE", r.Message); + else _log.Warn("ESPORTAZIONE", r.Message); + } + catch (OperationCanceledException) when (cts.IsCancellationRequested) + { + var p = _status; + end = new Status("cancelled", req.What, "Annullata", p.Rows, p.Total, Array.Empty(), + _lifetime.IsCancellationRequested ? "Esportazione interrotta dallo spegnimento del bot" : "Esportazione annullata: nessun file lasciato a metà", + false, started, DateTime.UtcNow); + _log.Info("ESPORTAZIONE", $"{Label(req.What)}: annullata dopo {p.Rows:N0} righe"); + } + catch (Exception e) when (e is TimeoutException or IOException) + { + end = Failed(req, started, e.Message); + } + catch (Exception e) + { + end = Failed(req, started, $"Esportazione non riuscita: {e.Message}"); + } + lock (_gate) + { + _status = end; + if (ReferenceEquals(_cts, cts)) _cts = null; + } + cts.Dispose(); + } + + private Status Failed(CsvExport.Request req, DateTime started, string message) + { + var clean = LogText.Clean(message); + _log.Warn("ESPORTAZIONE", $"{Label(req.What)}: {clean}"); + var p = _status; + return new Status("failed", req.What, "Non riuscita", p.Rows, p.Total, Array.Empty(), clean, false, started, DateTime.UtcNow); + } + + internal static string Label(string what) => what switch + { + CsvExport.ModelData => "dati del modello", + CsvExport.AuctionHistory => "storico delle aste", + CsvExport.ProductsWhat => "prodotti", + _ => what + }; + + /// L'avanzamento scritto direttamente nello stato, senza contesto di sincronizzazione. + private sealed class Reporter(ExportJobs jobs, string what, DateTime started) : IProgress + { + public void Report(CsvExport.Progress value) + { + lock (jobs._gate) + { + if (!jobs._status.Running || jobs._status.What != what || jobs._status.StartedUtc != started) return; + if (jobs._status.Phase == "Annullamento in corso") return; + jobs._status = jobs._status with { Phase = value.Phase, Rows = value.Rows, Total = value.Total }; + } + } + } +} diff --git a/src/Mimante/Data/Migrations/0003_indice_mie_puntate.sql b/src/Mimante/Data/Migrations/0003_indice_mie_puntate.sql new file mode 100644 index 0000000..3c316b3 --- /dev/null +++ b/src/Mimante/Data/Migrations/0003_indice_mie_puntate.sql @@ -0,0 +1,4 @@ +-- 2.0.0: le esportazioni dei dati del modello uniscono ogni decisione alla sua puntata vera +-- (my_bids.decision_id). Senza indice ogni decisione rileggeva tutta my_bids; la tabella è +-- piccola (qualche migliaio di righe), quindi l'indice si crea subito. +CREATE INDEX IF NOT EXISTS ix_my_bids_decision ON my_bids (decision_id); diff --git a/src/Mimante/Data/SamplePlan.cs b/src/Mimante/Data/SamplePlan.cs new file mode 100644 index 0000000..966aa2c --- /dev/null +++ b/src/Mimante/Data/SamplePlan.cs @@ -0,0 +1,45 @@ +namespace Mimante.Data; + +/// +/// Il campionamento stratificato delle esportazioni, deciso dai soli conteggi per gruppo (esito): +/// quando le righe superano il tetto, ogni gruppo tiene una quota proporzionale, almeno una riga, +/// con righe equidistanti nel tempo. Le righe vere non passano di qui: la scelta la fa PostgreSQL con +/// la stessa regola di , così in memoria restano solo i conteggi. +/// +public sealed record SamplePlan(bool Sampled, IReadOnlyList Groups, long Total) +{ + /// Un gruppo: quante righe ha () e quante se ne tengono (). + public sealed record Group(string Key, long Count, long Quota); + + /// Le righe che si scriveranno. + public long Kept => Groups.Sum(g => g.Quota); + + /// + /// Il piano per con il tetto : sotto il tetto si tiene + /// tutto; sopra, quota = max(1, arrotondamento di righe del gruppo × tetto / totale), al più le righe del gruppo. + /// + public static SamplePlan For(IReadOnlyList<(string Key, long Count)> counts, long max) + { + var total = counts.Sum(c => c.Count); + if (total <= max) + return new SamplePlan(false, counts.Select(c => new Group(c.Key, c.Count, c.Count)).ToList(), total); + var groups = counts + .Where(c => c.Count > 0) + .Select(c => new Group(c.Key, c.Count, Math.Min(c.Count, Math.Max(1, (long)Math.Round((double)c.Count * max / total))))) + .ToList(); + return new SamplePlan(true, groups, total); + } + + /// + /// Se la riga numero (da 1, in ordine di tempo dentro il gruppo) di un gruppo di + /// righe entra in un campione di : esattamente q righe su n, + /// distribuite in modo uniforme. In SQL è la condizione ((rn - 1) * q) % n < q. + /// + public static bool Keep(long rn, long n, long q) => q >= n || ((rn - 1) * q) % n < q; + + /// La riga della legenda che spiega il campione; null se non si è campionato. + public string? Note => Sampled + ? "Campionamento stratificato per esito (righe equidistanti nel tempo dentro ogni gruppo): " + + string.Join("; ", Groups.Select(g => $"{g.Key}: {g.Quota} su {g.Count}")) + : null; +} diff --git a/src/Mimante/Host/Bot.Services.cs b/src/Mimante/Host/Bot.Services.cs index 6a67ae4..687c5f9 100644 --- a/src/Mimante/Host/Bot.Services.cs +++ b/src/Mimante/Host/Bot.Services.cs @@ -33,6 +33,9 @@ public sealed partial class Bot public AssistedLogin Login { get; private set; } = null!; public CsvExport Exports { get; private set; } = null!; + /// L'esportazione in corso o l'ultima fatta: una alla volta, annullabile. + public ExportJobs ExportJobs { get; private set; } = null!; + /// Il mondo in uso (sito vero o simulatore). public BotWorld World => _world ?? throw new InvalidOperationException("servizi non ancora avviati"); public BotWorld? WorldOrNull => _world; @@ -63,6 +66,7 @@ public sealed partial class Bot Sessions = new SessionStore(Paths.Session); Hub = new WebSocketHub(this); Exports = new CsvExport(Db, Queue, Paths, () => Settings.Current, name => _world is { } w && w.Name == name ? w.Learning : null); + ExportJobs = new ExportJobs(Exports, Log, Lifetime); Login = new AssistedLogin(Paths.Browser, () => ReferencesProvider.Current, Log); Login.Frame += (data, w, h, url) => Hub.Broadcast(new Dictionary diff --git a/src/Mimante/Ml/LearningData.cs b/src/Mimante/Ml/LearningData.cs index 3859d94..2fa8760 100644 --- a/src/Mimante/Ml/LearningData.cs +++ b/src/Mimante/Ml/LearningData.cs @@ -191,15 +191,39 @@ public sealed class DbLearningData : ILearningData return rows.GroupBy(LossReasons.Group).Select(g => (g.Key, g.Count())).OrderByDescending(t => t.Item2).ToList(); } + private const string ShadowSelect = + "SELECT d.action, d.alt_action, d.outcome, d.ev, d.price, d.shadow, d.executed, d.bid_cost, " + + " COALESCE(a.market_value, a.buy_now_price, d.value, 0) AS v, COALESCE(a.shipping, 0) AS ship, " + + " d.ts >= now() - make_interval(days => $3) AS recent " + + "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + + "WHERE a.type = $2 AND d.ts >= now() - make_interval(days => $1) AND d.outcome IS NOT NULL " + + " AND d.created_at >= now() - make_interval(days => $1 + 1) " + + " AND d.kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto')"; + + private static ShadowReport.Row ShadowRow(System.Data.Common.DbDataReader r, double defaultBidCost) => + new(r.Str("action"), r.StrOrNull("alt_action"), r.Str("outcome"), r.DblOrNull("ev"), r.Dbl("price"), + r.Dbl("v"), r.Dbl("ship"), r.DblOrNull("bid_cost") is > 0 ? r.Dbl("bid_cost") : defaultBidCost, r.Bool("shadow"), r.Bool("executed")); + public Task> ShadowRowsAsync(int days, bool? shadow, double defaultBidCost) => - _db.QueryAsync( - "SELECT d.action, d.alt_action, d.outcome, d.ev, d.price, d.shadow, d.executed, d.bid_cost, " + - " COALESCE(a.market_value, a.buy_now_price, d.value, 0) AS v, COALESCE(a.shipping, 0) AS ship " + - "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + - "WHERE a.type = $2 AND d.ts >= now() - make_interval(days => $1) AND d.outcome IS NOT NULL " + - " AND d.kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto')" + - (shadow is { } s ? (s ? " AND d.shadow" : " AND NOT d.shadow") : ""), - r => new ShadowReport.Row(r.Str("action"), r.StrOrNull("alt_action"), r.Str("outcome"), r.DblOrNull("ev"), r.Dbl("price"), - r.Dbl("v"), r.Dbl("ship"), r.DblOrNull("bid_cost") is > 0 ? r.Dbl("bid_cost") : defaultBidCost, r.Bool("shadow"), r.Bool("executed")), - days, _world); + _db.QueryAsync(ShadowSelect + (shadow is { } s ? (s ? " AND d.shadow" : " AND NOT d.shadow") : ""), + r => ShadowRow(r, defaultBidCost), days, _world, days); + + /// + /// I tre rapporti della pagina Apprendimento (Osserva e Attiva degli ultimi giorni, + /// tutto degli ultimi ) con una sola lettura in streaming: nessuna riga resta in memoria. + /// + public async Task<(ShadowReport.Report Shadow, ShadowReport.Report Live, ShadowReport.Report All)> ShadowReportsAsync( + int recentDays, int allDays, double defaultBidCost, double transactionFee, CancellationToken ct = default) + { + var shadow = new ShadowReport.Accumulator(transactionFee); + var live = new ShadowReport.Accumulator(transactionFee); + var all = new ShadowReport.Accumulator(transactionFee); + await _db.ForEachAsync(ShadowSelect, r => + { + var row = ShadowRow(r, defaultBidCost); + all.Add(row); + if (r.Bool("recent")) (row.Shadow ? shadow : live).Add(row); + }, 60, ct, Math.Max(recentDays, allDays), _world, recentDays).ConfigureAwait(false); + return (shadow.Finish(recentDays), live.Finish(recentDays), all.Finish(allDays)); + } } diff --git a/src/Mimante/Ml/ShadowReport.cs b/src/Mimante/Ml/ShadowReport.cs index 56d7ff0..88afaa2 100644 --- a/src/Mimante/Ml/ShadowReport.cs +++ b/src/Mimante/Ml/ShadowReport.cs @@ -24,7 +24,20 @@ public static class ShadowReport public double Spent { get; set; } public double Gained { get; set; } public double ForecastEv { get; set; } - public List PerBid { get; } = new(); + + // Media e somma dei quadrati degli scarti del guadagno per puntata, aggiornate a ogni puntata (Welford): + // memoria costante anche con milioni di decisioni. + private long _n; + private double _mean, _m2; + + /// Aggiunge il guadagno netto di una puntata (vincita meno costo, oppure meno il costo). + public void AddPerBid(double x) + { + _n++; + var d = x - _mean; + _mean += d / _n; + _m2 += d * (x - _mean); + } public double Net => Gained - Spent; public double RoiPerBid => Bids > 0 ? Net / Bids : 0; @@ -34,11 +47,10 @@ public static class ShadowReport { get { - if (PerBid.Count < 2) return null; - var m = PerBid.Average(); - var sd = Math.Sqrt(PerBid.Sum(x => (x - m) * (x - m)) / (PerBid.Count - 1)); - var half = 1.96 * sd / Math.Sqrt(PerBid.Count); - return (m - half, m + half); + if (_n < 2) return null; + var sd = Math.Sqrt(_m2 / (_n - 1)); + var half = 1.96 * sd / Math.Sqrt(_n); + return (_mean - half, _mean + half); } } @@ -58,16 +70,28 @@ public static class ShadowReport public static bool Unanswered(string outcome) => outcome is "won" or "would_win" or "missed"; - public static Report Compute(IReadOnlyList rows, double transactionFee, int days) + public static Report Compute(IEnumerable rows, double transactionFee, int days) { - var acting = new PolicyStats { Name = "modello (in uso)" }; - var alt = new PolicyStats { Name = "bandit Thompson (shadow)" }; - var always = new PolicyStats { Name = "punta sempre" }; - var never = new PolicyStats { Name = "non punta mai" }; - int liveBids = 0, liveWins = 0; + var acc = new Accumulator(transactionFee); + foreach (var r in rows) acc.Add(r); + return acc.Finish(days); + } - foreach (var r in rows) + /// + /// Il rapporto costruito una riga alla volta, senza tenere le righe: per leggerle in streaming + /// dall'archivio ( è la stessa cosa su un elenco). + /// + public sealed class Accumulator(double transactionFee) + { + private readonly PolicyStats _acting = new() { Name = "modello (in uso)" }; + private readonly PolicyStats _alt = new() { Name = "bandit Thompson (shadow)" }; + private readonly PolicyStats _always = new() { Name = "punta sempre" }; + private readonly PolicyStats _never = new() { Name = "non punta mai" }; + private int _rows, _liveBids, _liveWins; + + public void Add(Row r) { + _rows++; var unanswered = Unanswered(r.Outcome); var gainIfWin = r.Value - (r.Price + Theory.PriceIncrement) - transactionFee - r.Shipping; @@ -82,27 +106,30 @@ public static class ShadowReport { s.Wins++; s.Gained += gainIfWin; - s.PerBid.Add(gainIfWin - r.BidCost); + s.AddPerBid(gainIfWin - r.BidCost); } - else s.PerBid.Add(-r.BidCost); + else s.AddPerBid(-r.BidCost); } - Apply(acting, r.Action == "BID", r.Ev); - Apply(alt, r.AltAction == "BID", null); - Apply(always, true, null); - Apply(never, false, null); + Apply(_acting, r.Action == "BID", r.Ev); + Apply(_alt, r.AltAction == "BID", null); + Apply(_always, true, null); + Apply(_never, false, null); if (!r.Shadow && r.Executed) { - liveBids++; - if (r.Outcome == "won") liveWins++; + _liveBids++; + if (r.Outcome == "won") _liveWins++; } } - var report = new Report { Days = days, WithOutcome = rows.Count, LiveBids = liveBids, LiveWins = liveWins }; - report.Policies.AddRange(new[] { acting, alt, always, never }); - report.Text = Format(report); - return report; + public Report Finish(int days) + { + var report = new Report { Days = days, WithOutcome = _rows, LiveBids = _liveBids, LiveWins = _liveWins }; + report.Policies.AddRange(new[] { _acting, _alt, _always, _never }); + report.Text = Format(report); + return report; + } } public static string Format(Report r) diff --git a/src/Mimante/Settings/AppSettings.cs b/src/Mimante/Settings/AppSettings.cs index 1819a6b..b0bd6e7 100644 --- a/src/Mimante/Settings/AppSettings.cs +++ b/src/Mimante/Settings/AppSettings.cs @@ -218,6 +218,15 @@ public sealed class AppSettings public bool RecordAuctions { get; set; } = true; public int ExportMaxRows { get; set; } = 5000; + /// Tempo massimo di un'esportazione intera (letture comprese), in minuti. + public int ExportTimeoutMinutes { get; set; } = 30; + + /// Un file esportato più grande di così (MB) si consegna compresso in .zip; 0 = mai. + public int ExportZipAboveMb { get; set; } = 50; + + /// Spazio libero minimo (MB) nella cartella delle esportazioni: sotto, l'esportazione si ferma. + public int ExportMinFreeMb { get; set; } = 500; + // ── Aspetto (predefiniti per un browser nuovo: ogni browser ricorda le sue scelte) ─ public bool DarkMode { get; set; } = true; diff --git a/src/Mimante/Settings/SettingsStore.cs b/src/Mimante/Settings/SettingsStore.cs index 8f36230..d87e6d6 100644 --- a/src/Mimante/Settings/SettingsStore.cs +++ b/src/Mimante/Settings/SettingsStore.cs @@ -218,7 +218,10 @@ public sealed class SettingsStore s.DataCapGb = Math.Clamp(s.DataCapGb, 1, 10_000); s.LogRetentionDays = Math.Clamp(s.LogRetentionDays, 0, 3650); s.BackupRetentionDays = Math.Clamp(s.BackupRetentionDays, 1, 365); - s.ExportMaxRows = Math.Clamp(s.ExportMaxRows, 100, 1_000_000); + s.ExportMaxRows = Math.Clamp(s.ExportMaxRows, 100, Data.CsvExport.MaxRowsCap); + s.ExportTimeoutMinutes = Math.Clamp(s.ExportTimeoutMinutes, 1, 24 * 60); + s.ExportZipAboveMb = Math.Clamp(s.ExportZipAboveMb, 0, 100_000); + s.ExportMinFreeMb = Math.Clamp(s.ExportMinFreeMb, 0, 1_000_000); return s; } diff --git a/src/Mimante/Web/Api.cs b/src/Mimante/Web/Api.cs index 34a8741..a58c98e 100644 --- a/src/Mimante/Web/Api.cs +++ b/src/Mimante/Web/Api.cs @@ -333,12 +333,7 @@ public static class Api net = Math.Round(p.Net, 2), perBid = Math.Round(p.RoiPerBid, 3), ciLow = p.Ci95?.Low, ciHigh = p.Ci95?.High, beatsNull = p.BeatsNullModel }; - var shadowRows = await data.ShadowRowsAsync(7, true, cost).ConfigureAwait(false); - var liveRows = await data.ShadowRowsAsync(7, false, cost).ConfigureAwait(false); - var allRows = await data.ShadowRowsAsync(30, null, cost).ConfigureAwait(false); - var shadowReport = ShadowReport.Compute(shadowRows, s.TransactionFeeEuro, 7); - var liveReport = ShadowReport.Compute(liveRows, s.TransactionFeeEuro, 7); - var allReport = ShadowReport.Compute(allRows, s.TransactionFeeEuro, 30); + var (shadowReport, liveReport, allReport) = await data.ShadowReportsAsync(7, 30, cost, s.TransactionFeeEuro).ConfigureAwait(false); var fcRows = await bot.Db.QueryAsync( "SELECT f.forecast_close, f.forecast_close_p10, f.forecast_close_p90, f.actual_close, f.forecast_winner_bids, f.actual_winner_bids " + @@ -408,7 +403,7 @@ public static class Api private static object ExportList(Bot bot) => Directory.Exists(bot.Paths.Exports) - ? new DirectoryInfo(bot.Paths.Exports).EnumerateFiles().Where(f => f.Extension is ".csv" or ".txt").OrderByDescending(f => f.LastWriteTimeUtc).Take(100) + ? new DirectoryInfo(bot.Paths.Exports).EnumerateFiles().Where(f => f.Extension is ".csv" or ".txt" or ".zip").OrderByDescending(f => f.LastWriteTimeUtc).Take(100) .Select(f => new { name = f.Name, size = f.Length, at = f.LastWriteTimeUtc }).ToList() : new List(); diff --git a/src/Mimante/Web/Views.cs b/src/Mimante/Web/Views.cs index 91085ee..fbdca4c 100644 --- a/src/Mimante/Web/Views.cs +++ b/src/Mimante/Web/Views.cs @@ -154,6 +154,23 @@ public static class Views ["maintenanceAt"] = m.LastRunUtc }; + /// L'esportazione in corso o l'ultima: fase, righe scritte su quelle da scrivere, file pronti. + public static Dictionary Export(ExportJobs.Status s) => new() + { + ["t"] = "export", + ["state"] = s.State, + ["what"] = s.What, + ["label"] = s.What.Length > 0 ? ExportJobs.Label(s.What) : "", + ["phase"] = s.Phase, + ["rows"] = s.Rows, + ["total"] = s.Total, + ["files"] = s.Files, + ["message"] = s.Message, + ["sampled"] = s.Sampled, + ["startedAt"] = s.StartedUtc, + ["endedAt"] = s.EndedUtc + }; + /// Il pannello dettagli dell'asta selezionata. public static Dictionary AuctionDetail(AuctionInfo a, BotWorld world, AppSettings settings) { diff --git a/src/Mimante/Web/WebSocketHub.Commands.cs b/src/Mimante/Web/WebSocketHub.Commands.cs index c9837cc..a395a66 100644 --- a/src/Mimante/Web/WebSocketHub.Commands.cs +++ b/src/Mimante/Web/WebSocketHub.Commands.cs @@ -383,14 +383,21 @@ public sealed partial class WebSocketHub return new Ack(true, "Il modello ha dimenticato tutto: si riparte da zero (l'archivio resta)"); // ── esportazioni ────────────────────────────────────────── - case "export.run": + // Il lavoro gira di fondo: la risposta dice solo se è partito; avanzamento e file arrivano col blocco «export». + case "export.start": { - var req = new CsvExport.Request( - Str(m, "what") ?? "", Date(m, "from"), Date(m, "to"), Bool(m, "onlyMyBids"), + var what = Str(m, "what") ?? ""; + if (what is not (CsvExport.ModelData or CsvExport.AuctionHistory or CsvExport.ProductsWhat)) + return new Ack(false, $"Esportazione sconosciuta: {what}"); + var req = new CsvExport.Request(what, Date(m, "from"), Date(m, "to"), Bool(m, "onlyMyBids"), Int(m, "maxRows") ?? _bot.Settings.Current.ExportMaxRows, world.Name); - var result = await _bot.Exports.RunAsync(req, ct).ConfigureAwait(false); - return new Ack(result.Ok, result.Message, new { files = result.Files, rows = result.Rows, sampled = result.Sampled }); + var (ok, message) = _bot.ExportJobs.Start(req); + return new Ack(ok, message); } + case "export.cancel": + return _bot.ExportJobs.Cancel() + ? new Ack(true, "Annullamento chiesto: l'esportazione si ferma senza lasciare file a metà") + : new Ack(false, "Nessuna esportazione in corso"); default: return new Ack(false, $"Comando sconosciuto: {t}"); diff --git a/src/Mimante/Web/WebSocketHub.cs b/src/Mimante/Web/WebSocketHub.cs index be75e98..4d3b556 100644 --- a/src/Mimante/Web/WebSocketHub.cs +++ b/src/Mimante/Web/WebSocketHub.cs @@ -217,6 +217,8 @@ public sealed partial class WebSocketHub : IAsyncDisposable Block(outgoing, "session", Views.Session(world)); Block(outgoing, "risk", Views.Risk(_bot.Risk, settings)); Block(outgoing, "mode", Views.Mode(settings, world)); + // L'esportazione: a ogni giro mentre è in corso (cambia solo se avanza), così la barra si muove. + Block(outgoing, "export", Views.Export(_bot.ExportJobs.Current)); if (_tick % 20 == 0) { Block(outgoing, "net", Views.Net(world), ignore: "nowUnixMs"); @@ -304,6 +306,7 @@ public sealed partial class WebSocketHub : IAsyncDisposable ["clockSynced"] = w?.Monitor.Clock.IsSynced ?? false, ["simulator"] = w?.IsSimulator ?? false, ["canBid"] = w?.Monitor.CanBid ?? false, + ["exportMaxRows"] = s.ExportMaxRows, ["db"] = _bot.Queue.DownSince == null ? "ok" : "giu" }; } @@ -321,6 +324,7 @@ public sealed partial class WebSocketHub : IAsyncDisposable ["mode"] = Views.Mode(settings, world), ["net"] = Views.Net(world), ["db"] = Views.Db(_bot.Queue, _bot.Maintenance), + ["export"] = Views.Export(_bot.ExportJobs.Current), ["log"] = _bot.Log.Snapshot(200).Select(EventMessage).ToList() }; } diff --git a/src/Mimante/wwwroot/js/app.js b/src/Mimante/wwwroot/js/app.js index 1d9ee77..007b509 100644 --- a/src/Mimante/wwwroot/js/app.js +++ b/src/Mimante/wwwroot/js/app.js @@ -7,6 +7,7 @@ import { el, $, num, euro, bytes, store, notice, pingLevel, pingText, PING_COLORS } from './util.js'; import { conn, state, subscribe, post } from './state.js'; import { icon } from './icons.js'; +import './exports.js'; // il risultato di un'esportazione si apre anche da un'altra pagina const pages = [ { id: 'aste', label: 'Aste', ic: 'gavel', title: 'Le aste in elenco: stato, timer, verdetto del modello, puntate, registro', load: () => import('./pages/aste.js') }, diff --git a/src/Mimante/wwwroot/js/exports.js b/src/Mimante/wwwroot/js/exports.js new file mode 100644 index 0000000..c99d8dd --- /dev/null +++ b/src/Mimante/wwwroot/js/exports.js @@ -0,0 +1,86 @@ +// Le esportazioni CSV: una finestra sola per tutte (dati del modello, storico delle aste, prodotti). +// Il bot le esegue di fondo, una alla volta (ExportJobs): il comando dice solo se è partita, +// l'avanzamento arriva con il blocco «export» del WebSocket e sopravvive a una ricarica. La +// finestra si può chiudere mentre lavora; quando finisce, il risultato si apre da solo (è +// un'informazione importante: file pronti o motivo dell'errore). + +import { el, num, field, modal, parseNum, report } from './util.js'; +import { send, state, subscribe } from './state.js'; + +const DESCRIPTIONS = { + dati_modello: ['Esporta dati del modello', 'Una riga per decisione, con tutte le variabili del modello, le probabilità, il verdetto e l\'esito reale. È il file da incollare in chat per rivedere la logica del modello.'], + storico_aste: ['Esporta storico aste', 'Una riga per asta conclusa con riepilogo, previsione ↔ realtà ed esito, più il perché.'] +}; + +let open = false; +let lastState = null; + +/** Apre il modulo dell'esportazione (o, se ce n'è una in corso, il suo avanzamento) e la fa partire. */ +export async function exportDialog(what) { + if (state.export?.state === 'running') return progressDialog(); + let msg; + if (what === 'prodotti') msg = { t: 'export.start', what }; + else { + const today = new Date().toISOString().slice(0, 10); + const monthAgo = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10); + const from = el('input', { type: 'date', value: monthAgo, title: 'Primo giorno compreso (ora di Roma)' }); + const to = el('input', { type: 'date', value: today, title: 'Ultimo giorno compreso (ora di Roma)' }); + const mine = el('input', { type: 'checkbox', title: 'Solo le aste in cui ho puntato almeno una volta' }); + const max = el('input', { value: String(state.hello?.exportMaxRows ?? 5000), inputmode: 'numeric', title: 'Righe massime del file' }); + const [title, help] = DESCRIPTIONS[what] || [what, '']; + const content = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, + el('p', { class: 'help', style: { margin: 0 } }, help), + field('Dal', from), field('Al', to), + el('label', { class: 'row', title: 'Solo le aste in cui ho puntato almeno una volta' }, mine, 'solo aste con mie puntate'), + field('Righe massime', max, { help: 'oltre si campiona per esito', title: 'Oltre questo numero di righe si tiene un campione stratificato per esito, dichiarato nella legenda; al più 1.000.000' })); + msg = await modal({ title, content, buttons: [{ text: 'Annulla', value: null }, { text: 'Esporta', kind: 'primary', value: () => ({ t: 'export.start', what, from: from.value, to: to.value, onlyMyBids: mine.checked, maxRows: parseNum(max.value) ?? 5000 }) }] }); + if (!msg) return; + } + const ack = await send(msg, 15000); + if (!ack.ok) { report(ack); return; } + lastState = 'running'; + progressDialog(); +} + +/** La finestra dell'esportazione: fase, barra, righe, Annulla; alla fine i file o il motivo dell'errore. */ +function progressDialog() { + if (open) return; + open = true; + const phase = el('p', { style: { margin: 0 }, title: 'Che cosa sta facendo l\'esportazione' }); + const barFill = el('i'); + const bar = el('div', { class: 'bar', style: { height: '6px' }, title: 'Righe scritte su quelle da scrivere' }, barFill); + const rows = el('p', { class: 'help', style: { margin: 0 }, title: 'Righe scritte nel file su quelle scelte' }); + const files = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }); + const cancel = el('button', { class: 'btn danger', type: 'button', title: 'Ferma l\'esportazione: il file a metà viene cancellato' }, 'Annulla esportazione'); + cancel.onclick = async () => { cancel.disabled = true; report(await send({ t: 'export.cancel' }, 15000)); }; + const content = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px', minWidth: '340px' } }, phase, bar, rows, files, cancel); + + const render = s => { + const running = s.state === 'running'; + phase.textContent = running ? `${s.label}: ${s.phase}…` : (s.message || s.phase || ''); + phase.className = s.state === 'failed' ? 'notice bad' : ''; + const share = s.total > 0 ? Math.min(1, s.rows / s.total) : 0; + bar.hidden = !running; + barFill.style.width = (running ? Math.max(2, share * 100) : 100).toFixed(1) + '%'; + rows.textContent = s.total > 0 ? `${num(s.rows)} di ${num(s.total)} righe` : running ? 'Preparo l\'elenco delle righe' : ''; + rows.hidden = !rows.textContent; + cancel.hidden = !running; + files.replaceChildren(...(s.state === 'done' ? [ + ...(s.files || []).map(f => el('a', { href: '/esportazioni/' + encodeURIComponent(f), download: f, title: 'Scarica ' + f }, f)), + el('p', { class: 'help', style: { margin: 0 } }, 'Restano anche in /config/esportazioni: li conservi tu.') + ] : [])); + }; + + let unsub = () => {}; + modal({ + title: 'Esportazione', content, buttons: [{ text: 'Chiudi', value: null }], + onOpen: () => { render(state.export || {}); unsub = subscribe('export', render); } + }).finally(() => { unsub(); open = false; }); +} + +// Quando un'esportazione finisce a finestra chiusa (o dopo aver cambiato pagina), il risultato si apre da solo. +subscribe('export', s => { + const prev = lastState; + lastState = s.state; + if (prev === 'running' && s.state !== 'running' && !open) progressDialog(); +}); diff --git a/src/Mimante/wwwroot/js/pages/apprendimento.js b/src/Mimante/wwwroot/js/pages/apprendimento.js index 5dd8b74..471af9c 100644 --- a/src/Mimante/wwwroot/js/pages/apprendimento.js +++ b/src/Mimante/wwwroot/js/pages/apprendimento.js @@ -6,7 +6,7 @@ import { el, num, euro, signedEuro, pct, time, report, getJson, confirmDialog, modal } from '../util.js'; import { send, subscribe } from '../state.js'; import { icon } from '../icons.js'; -import { exportDialog } from './storico.js'; +import { exportDialog } from '../exports.js'; let root, timer, unsub = [], data = null, busy = false, evaluating = false; let bar = null, progressBox = null; diff --git a/src/Mimante/wwwroot/js/pages/impostazioni.js b/src/Mimante/wwwroot/js/pages/impostazioni.js index 1ee1585..e5b3ba1 100644 --- a/src/Mimante/wwwroot/js/pages/impostazioni.js +++ b/src/Mimante/wwwroot/js/pages/impostazioni.js @@ -97,7 +97,10 @@ const sections = [ ['BackupRetentionDays', 'Backup: giorni', I, 'Backup logico notturno in /config/backup'], ['RecordAuctions', 'Registra le aste', B, 'Senza, il modello non ha nulla da imparare'], ['WriteAppLog', 'Registro applicativo su file', B, 'Scrive il registro generale anche su file, oltre che nell\'interfaccia'], - ['ExportMaxRows', 'Esportazioni: righe massime', I, 'Oltre si campiona per esito'] + ['ExportMaxRows', 'Esportazioni: righe massime', I, 'Oltre si campiona per esito, in proporzione e con righe equidistanti nel tempo'], + ['ExportTimeoutMinutes', 'Esportazioni: tempo massimo min', I, 'Oltre questo tempo l\'esportazione si ferma e non lascia file a metà'], + ['ExportZipAboveMb', 'Esportazioni: comprimi oltre MB', I, 'Un file più grande si scarica in .zip; 0 = mai'], + ['ExportMinFreeMb', 'Esportazioni: spazio libero minimo MB', I, 'Sotto questo spazio libero su /config l\'esportazione si ferma'] ] }, { title: 'Registri e aspetto', hint: 'Quante righe di registro tenere e come appare l\'interfaccia in un browser nuovo', fields: [ ['MinLogLevel', 'Livello minimo del registro', L, 'Le righe meno importanti di questo livello non si registrano', [['Debug', 'Tutto (debug)'], ['Normal', 'Normale'], ['Warning', 'Solo avvisi'], ['Error', 'Solo errori']]], diff --git a/src/Mimante/wwwroot/js/pages/prodotti.js b/src/Mimante/wwwroot/js/pages/prodotti.js index b34bb86..1f52f15 100644 --- a/src/Mimante/wwwroot/js/pages/prodotti.js +++ b/src/Mimante/wwwroot/js/pages/prodotti.js @@ -13,6 +13,7 @@ import { send, subscribe } from '../state.js'; import { Grid } from '../grid.js'; import { verticalSplit } from '../split.js'; import { icon } from '../icons.js'; +import { exportDialog } from '../exports.js'; let grid, panel, split, counts, selected = null, info = null, tab = store.get('prodotti.tab', 'paletti'), rows = []; @@ -275,11 +276,7 @@ async function applyLimits(key) { if (selected) select(selected, true); } -async function exportCsv() { - const ack = await send({ t: 'export.run', what: 'prodotti' }, 120000); - report(ack); - if (ack.ok && ack.data?.files?.[0]) window.location.href = '/esportazioni/' + encodeURIComponent(ack.data.files[0]); -} +const exportCsv = () => exportDialog('prodotti'); async function select(key, quiet = false) { selected = key; diff --git a/src/Mimante/wwwroot/js/pages/storico.js b/src/Mimante/wwwroot/js/pages/storico.js index cafb494..3f43b09 100644 --- a/src/Mimante/wwwroot/js/pages/storico.js +++ b/src/Mimante/wwwroot/js/pages/storico.js @@ -7,6 +7,7 @@ import { send } from '../state.js'; import { Grid } from '../grid.js'; import { verticalSplit } from '../split.js'; import { icon } from '../icons.js'; +import { exportDialog } from '../exports.js'; let grid, panel, split, countEl, moreBtn, filters, selected = null, detail = null, tab = store.get('storico.tab', 'riepilogo'); let loaded = [], total = 0; @@ -230,30 +231,3 @@ function exportButton(what, cls, title) { return el('button', { class: 'icon-btn' + (cls ? ' ' + cls : ''), type: 'button', title, 'aria-label': title, onclick: () => exportDialog(what) }, icon('download')); } -export async function exportDialog(what) { - const today = new Date().toISOString().slice(0, 10); - const monthAgo = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10); - const from = el('input', { type: 'date', value: monthAgo }); - const to = el('input', { type: 'date', value: today }); - const mine = el('input', { type: 'checkbox' }); - const max = el('input', { value: '5000', inputmode: 'numeric' }); - const title = what === 'dati_modello' ? 'Esporta dati del modello' : 'Esporta storico aste'; - const content = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, - el('p', { class: 'help', style: { margin: 0 } }, what === 'dati_modello' - ? 'Una riga per decisione, con tutte le variabili del modello, le probabilità, il verdetto e l\'esito reale. È il file da incollare in chat per rivedere la logica del modello.' - : 'Una riga per asta conclusa con riepilogo, previsione ↔ realtà ed esito, più il perché.'), - field('Dal', from), field('Al', to), - el('label', { class: 'row' }, mine, 'solo aste con mie puntate'), - field('Righe massime', max, { help: 'oltre si campiona per esito', title: 'Oltre questo numero di righe si tiene un campione stratificato per esito, dichiarato nella legenda' })); - const msg = await modal({ title, content, buttons: [{ text: 'Annulla', value: null }, { text: 'Esporta', kind: 'primary', value: () => ({ t: 'export.run', what, from: from.value, to: to.value, onlyMyBids: mine.checked, maxRows: parseNum(max.value) ?? 5000 }) }] }); - if (!msg) return; - const ack = await send(msg, 300000); - report(ack); - if (!ack.ok || !ack.data?.files) return; - await modal({ - title: 'File pronti', content: el('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, - el('p', { style: { margin: 0 } }, ack.msg), - ack.data.files.map(f => el('a', { href: '/esportazioni/' + encodeURIComponent(f), download: f }, f)), - el('p', { class: 'help', style: { margin: 0 } }, 'Restano anche in /config/esportazioni: li conservi tu.')) - }); -} diff --git a/src/Mimante/wwwroot/js/state.js b/src/Mimante/wwwroot/js/state.js index ec69eb7..7634ed4 100644 --- a/src/Mimante/wwwroot/js/state.js +++ b/src/Mimante/wwwroot/js/state.js @@ -15,6 +15,7 @@ export const state = { mode: {}, net: {}, db: {}, + export: {}, // l'esportazione in corso o l'ultima (ExportJobs) log: [], hello: null, offsetMs: 0, // ora di Bidoo = Date.now() + offsetMs @@ -64,7 +65,7 @@ conn.on('snapshot', m => { state.auctions.clear(); state.order = []; for (const a of m.auctions || []) { state.auctions.set(a.id, a); state.order.push(a.id); } - for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db']) { + for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export']) { if (m[k]) { state[k] = m[k]; if (k === 'net') clock(m[k]); publish(k, state[k]); } } state.log = (m.log || []).slice(-300); @@ -91,7 +92,7 @@ conn.on('auction.removed', m => { publish('auction.removed', m.id); }); -for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db']) { +for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export']) { conn.on(k, m => { const { t, ...rest } = m; state[k] = rest; diff --git a/tests/Mimante.Tests/ServiceTests.cs b/tests/Mimante.Tests/ServiceTests.cs index b9dc007..59da765 100644 --- a/tests/Mimante.Tests/ServiceTests.cs +++ b/tests/Mimante.Tests/ServiceTests.cs @@ -307,19 +307,105 @@ public class CsvExportPureTests [Fact] public void Il_campionamento_tiene_le_proporzioni_e_almeno_una_riga_per_gruppo() { - var rows = Enumerable.Range(0, 1000).Select(i => i < 900 ? "osservata" : i < 998 ? "persa" : "vinta").ToList(); - var (kept, sampled, note) = CsvExport.Stratify(rows, 100, r => r); - Assert.True(sampled); - Assert.InRange(kept.Count, 98, 103); - Assert.InRange(kept.Count(r => r == "osservata"), 88, 92); - Assert.InRange(kept.Count(r => r == "persa"), 9, 11); - Assert.Equal(1, kept.Count(r => r == "vinta")); - Assert.Contains("stratificato", note); + var counts = new List<(string, long)> { ("osservata", 900), ("persa", 98), ("vinta", 2) }; + var plan = SamplePlan.For(counts, 100); + Assert.True(plan.Sampled); + Assert.Equal(1000, plan.Total); + Assert.InRange(plan.Kept, 98, 103); + Assert.Equal(90, plan.Groups.Single(g => g.Key == "osservata").Quota); + Assert.Equal(10, plan.Groups.Single(g => g.Key == "persa").Quota); + Assert.Equal(1, plan.Groups.Single(g => g.Key == "vinta").Quota); + Assert.Contains("stratificato", plan.Note); + Assert.Contains("vinta: 1 su 2", plan.Note); - var (all, s2, n2) = CsvExport.Stratify(rows, 5000, r => r); - Assert.False(s2); - Assert.Null(n2); - Assert.Equal(1000, all.Count); + var all = SamplePlan.For(counts, 5000); + Assert.False(all.Sampled); + Assert.Null(all.Note); + Assert.Equal(1000, all.Kept); + } + + [Theory] + [InlineData(900, 90)] + [InlineData(98, 10)] + [InlineData(7, 3)] + [InlineData(5, 5)] + [InlineData(1_000_003, 999)] + public void La_regola_di_sql_sceglie_esattamente_q_righe_ben_distribuite(long n, long q) + { + var kept = new List(); + for (long rn = 1; rn <= n; rn++) + if (SamplePlan.Keep(rn, n, q)) kept.Add(rn); + Assert.Equal(q, kept.Count); + Assert.Equal(1, kept[0]); + // Fra una riga tenuta e la successiva c'è al più un passo intero in più della media. + var step = (double)n / q; + for (var i = 1; i < kept.Count; i++) Assert.InRange(kept[i] - kept[i - 1], Math.Floor(step), Math.Ceiling(step)); + } + + [Fact] + public async Task Le_esportazioni_vanno_una_alla_volta_e_si_annullano() + { + var gate = new TaskCompletionSource(); + var jobs = new ExportJobs(async (req, ct, progress) => + { + progress.Report(new CsvExport.Progress("Scrivo le decisioni", 10, 100)); + await gate.Task.WaitAsync(ct); + return new CsvExport.Result(true, "fatto", new[] { "a.csv", "a-legenda.txt" }, 100, false); + }, new AppLog(null), CancellationToken.None); + var req = new CsvExport.Request(CsvExport.ModelData, null, null, false, 5000, Worlds.Real); + + Assert.Equal("idle", jobs.Current.State); + Assert.True(jobs.Start(req).Ok); + var (again, why) = jobs.Start(req); + Assert.False(again); + Assert.Contains("già un'esportazione in corso", why); + await WaitUntil(() => jobs.Current.Rows == 10); + Assert.Equal("running", jobs.Current.State); + Assert.Equal(100, jobs.Current.Total); + + Assert.True(jobs.Cancel()); + await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("cancelled", jobs.Current.State); + Assert.Empty(jobs.Current.Files); + Assert.False(jobs.Cancel()); + + Assert.True(jobs.Start(req).Ok); + gate.SetResult(); + await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("done", jobs.Current.State); + Assert.Equal(new[] { "a.csv", "a-legenda.txt" }, jobs.Current.Files); + } + + [Fact] + public async Task Un_errore_dell_esportazione_finisce_nello_stato_senza_far_cadere_nulla() + { + var jobs = new ExportJobs((_, _, _) => throw new IOException("Spazio libero insufficiente"), new AppLog(null), CancellationToken.None); + Assert.True(jobs.Start(new CsvExport.Request(CsvExport.AuctionHistory, null, null, false, 0, Worlds.Real)).Ok); + await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("failed", jobs.Current.State); + Assert.Contains("Spazio libero insufficiente", jobs.Current.Message); + } + + [Fact] + public void Il_rapporto_in_streaming_dà_lo_stesso_intervallo_dell_elenco() + { + var rows = Enumerable.Range(0, 200).Select(i => new ShadowReport.Row(i % 3 == 0 ? "BID" : "NO-OP", null, + i % 7 == 0 ? "would_win" : "would_be_answered", 0.01, 1 + i * 0.01, 50, 0, 0.13, true, false)).ToList(); + var once = ShadowReport.Compute(rows, 1.0, 7).Policies[0]; + // Lo stesso calcolo a due passate, come faceva la versione con l'elenco delle puntate. + var perBid = rows.Where(r => r.Action == "BID") + .Select(r => ShadowReport.Unanswered(r.Outcome) ? r.Value - (r.Price + Theory.PriceIncrement) - 1.0 - r.Shipping - r.BidCost : -r.BidCost).ToList(); + var m = perBid.Average(); + var half = 1.96 * Math.Sqrt(perBid.Sum(x => (x - m) * (x - m)) / (perBid.Count - 1)) / Math.Sqrt(perBid.Count); + Assert.Equal(m - half, once.Ci95!.Value.Low, 9); + Assert.Equal(m + half, once.Ci95!.Value.High, 9); + } + + private static async Task WaitUntil(Func condition) + { + var until = DateTime.UtcNow.AddSeconds(5); + while (!condition() && DateTime.UtcNow < until) await Task.Delay(10); + Assert.True(condition()); } [Fact] @@ -442,4 +528,115 @@ public class CsvExportTests(DatabaseFixture fx) Assert.Contains("Persa a 3,21", hRow[^1]); Assert.Contains("coperta", hRow[Array.IndexOf(hHeader, "motivo_perdita")]); } + + /// 10.000 decisioni sintetiche su un'asta: 1.000 «missed» e 9.000 «right_skip». + private static async Task SeedDecisionsAsync(Db db) + { + await db.ExecuteAsync( + "INSERT INTO auctions(auction_id, name, product_key, type, outcome, final_price, end_time, my_bids) " + + "VALUES ('S1', 'Sintetica', 'sintetica', 'normal', 'lost', 5.00, now() - interval '1 hour', 0)"); + await db.ExecuteAsync( + "INSERT INTO bot_decisions(decision_id, auction_id, ts, price, action, kind, outcome, shadow, reason_detail) " + + "SELECT g, 'S1', now() - interval '4 hours' + g * interval '1 second', 1.00 + g * 0.01, 'NO-OP', 'ev-negativo', " + + " CASE WHEN g % 10 = 0 THEN 'missed' ELSE 'right_skip' END, true, 'valore atteso negativo, servirebbe una probabilità più alta' " + + "FROM generate_series(1, 10000) g"); + } + + [DbFact] + public async Task Il_campione_si_sceglie_in_sql_con_le_proporzioni_per_esito() + { + await fx.TruncateAsync(); + var db = fx.Db!; + using var dir = new TempDir(); + var paths = new ConfigPaths(dir.Path); + await using var queue = new WriteQueue(db.Writer, new AppLog(null)); + await SeedDecisionsAsync(db); + + var export = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null); + var today = AppInfo.LocalNow.Date; + var steps = new List(); + var r = await export.RunAsync(new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 100, Worlds.Real), + CancellationToken.None, new SyncProgress(steps)); + + Assert.True(r.Ok, r.Message); + Assert.True(r.Sampled); + Assert.Equal(100, r.Rows); + var lines = File.ReadAllLines(Path.Combine(paths.Exports, r.Files[0]), Encoding.UTF8); + var header = lines[0].TrimStart('').Split(';'); + var unanswered = Array.IndexOf(header, "esito_senza_risposta"); + Assert.Equal(101, lines.Length); + Assert.Equal(10, lines.Skip(1).Count(l => l.Split(';')[unanswered] == "si")); + // In ordine di tempo, e distribuite su tutto il periodo (non le prime 100). + var ids = lines.Skip(1).Select(l => long.Parse(l.Split(';')[0])).ToList(); + Assert.Equal(ids.OrderBy(x => x), ids); + Assert.True(ids[^1] > 9000); + Assert.Contains("missed: 10 su 1000", File.ReadAllText(Path.Combine(paths.Exports, r.Files[1]))); + Assert.Contains(steps, s => s.Phase == "Conto le decisioni"); + Assert.Empty(Directory.GetFiles(paths.Exports, "*.tmp")); + } + + [DbFact] + public async Task Un_file_grande_si_consegna_in_zip() + { + await fx.TruncateAsync(); + var db = fx.Db!; + using var dir = new TempDir(); + var paths = new ConfigPaths(dir.Path); + await using var queue = new WriteQueue(db.Writer, new AppLog(null)); + await SeedDecisionsAsync(db); + + var export = new CsvExport(db, queue, paths, () => new AppSettings { ExportZipAboveMb = 1 }, _ => null); + var today = AppInfo.LocalNow.Date; + var r = await export.RunAsync(new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 0, Worlds.Real), CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(10_000, r.Rows); + Assert.EndsWith(".csv.zip", r.Files[0]); + Assert.False(File.Exists(Path.Combine(paths.Exports, r.Files[0][..^4]))); + using var zip = System.IO.Compression.ZipFile.OpenRead(Path.Combine(paths.Exports, r.Files[0])); + var entry = Assert.Single(zip.Entries); + using var reader = new StreamReader(entry.Open(), Encoding.UTF8); + var count = 0; + while (reader.ReadLine() != null) count++; + Assert.Equal(10_001, count); + } + + [DbFact] + public async Task Annullare_a_metà_o_restare_senza_spazio_non_lascia_file() + { + await fx.TruncateAsync(); + var db = fx.Db!; + using var dir = new TempDir(); + var paths = new ConfigPaths(dir.Path); + await using var queue = new WriteQueue(db.Writer, new AppLog(null)); + await SeedDecisionsAsync(db); + var today = AppInfo.LocalNow.Date; + var req = new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 0, Worlds.Real); + + // Annullata quando ha scritto le prime 5.000 righe (il primo avanzamento con righe). + using var cts = new CancellationTokenSource(); + var export = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null); + var started = DateTime.UtcNow; + await Assert.ThrowsAnyAsync(() => + export.RunAsync(req, cts.Token, new SyncProgress(null, p => { if (p.Rows > 0) cts.Cancel(); }))); + Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(30)); + Assert.Empty(Directory.GetFiles(paths.Exports)); + + // Lo spazio finisce durante la scrittura: nessun .tmp, nessun csv. + long free = 10L << 30; + var full = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null, _ => Interlocked.Exchange(ref free, 0)); + var e = await Assert.ThrowsAsync(() => full.RunAsync(req, CancellationToken.None)); + Assert.Contains("Spazio libero insufficiente", e.Message); + Assert.Empty(Directory.GetFiles(paths.Exports)); + } + + /// Un IProgress che chiama subito, sullo stesso thread (Progress<T> passa dal pool). + private sealed class SyncProgress(List? into, Action? on = null) : IProgress + { + public void Report(CsvExport.Progress value) + { + into?.Add(value); + on?.Invoke(value); + } + } }