From 28db7706b0dd8887d8a4f2d1daec0b78e438c781 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 1 Oct 2026 14:20:23 +0200 Subject: [PATCH] =?UTF-8?q?Ledger:=20la=20rotazione=20mensile=20delle=20de?= =?UTF-8?q?cisioni=20va=20solo=20in=20avanti=20e=20non=20sovrascrive=20mai?= =?UTF-8?q?=20un=20file=20gi=C3=A0=20ruotato?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Al cambio di mese una riga di decisione porta l'ora della barra (il mese vecchio) mentre eventi e correzioni portano l'ora attuale (il mese nuovo): l'ultima barra del mese valutata dopo la mezzanotte faceva ruotare il file all'indietro, e alla riga successiva lo spostamento falliva sul file già esistente, perdendo la riga. Ora una riga tardiva del mese precedente resta nel file corrente (ogni riga ha la sua ora) e un file ruotato con lo stesso nome prende il primo nome libero (_02), che si ordina subito dopo. Il test che il cambio di mese di oggi aveva rotto legge tutti i file delle decisioni; due test nuovi coprono la riga tardiva e il file già esistente. Co-Authored-By: Claude Opus 5.5 --- .../src/Encelado.Engine/Baskets/Ledger.cs | 28 +++++++-- Encelado/tests/Encelado.Tests/BasketTests.cs | 59 ++++++++++++++++++- 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs index e7baa97..508dcbc 100644 --- a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs +++ b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs @@ -595,7 +595,13 @@ public sealed class Ledger : IDisposable } } - /// Monthly rotation: the current file is moved to decisions_YYYYMM.jsonl when the month changes. + /// + /// Monthly rotation: the current file is moved to decisions_YYYYMM.jsonl when the month changes. It only + /// moves forward: a line of an earlier month that arrives after the rotation (the last bar of a month evaluated + /// after midnight, once an event of the new month has rotated the file) stays in the current file, since every + /// line carries its own time. Rotating back would move the new month's lines aside and then fail on the + /// existing file at the next line, which would be lost. + /// private void RotateIfNeeded(DateTime now) { string month = now.ToString("yyyyMM", CultureInfo.InvariantCulture); @@ -604,7 +610,7 @@ public sealed class Ledger : IDisposable _decisionsMonth = File.Exists(DecisionsPath) ? MonthOfFirstLine() ?? month : month; } - if (_decisionsMonth == month) + if (string.CompareOrdinal(month, _decisionsMonth) <= 0) { return; } @@ -613,13 +619,27 @@ public sealed class Ledger : IDisposable _decisions = null; if (File.Exists(DecisionsPath)) { - string aside = Path.Combine(_directory, $"decisions_{_decisionsMonth}.jsonl"); - File.Move(DecisionsPath, aside, overwrite: false); + File.Move(DecisionsPath, FreeAside(_decisionsMonth), overwrite: false); } _decisionsMonth = month; } + /// + /// decisions_YYYYMM.jsonl, or decisions_YYYYMM_02.jsonl and on when that name is taken: a rotated + /// file is never overwritten, and the suffix sorts right after it in . + /// + private string FreeAside(string month) + { + string aside = Path.Combine(_directory, $"decisions_{month}.jsonl"); + for (int n = 2; File.Exists(aside); n++) + { + aside = Path.Combine(_directory, string.Create(CultureInfo.InvariantCulture, $"decisions_{month}_{n:00}.jsonl")); + } + + return aside; + } + private string? MonthOfFirstLine() { try diff --git a/Encelado/tests/Encelado.Tests/BasketTests.cs b/Encelado/tests/Encelado.Tests/BasketTests.cs index 4c41bfc..13e098f 100644 --- a/Encelado/tests/Encelado.Tests/BasketTests.cs +++ b/Encelado/tests/Encelado.Tests/BasketTests.cs @@ -552,7 +552,8 @@ public sealed class LedgerTests : IDisposable ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(t.AddMinutes(15)), enter, "ingresso", "B1"); ledger.Correction("run1", "B1", "prova di correzione"); - string[] lines = [.. ledger.ReadDecisionLines()]; + // Every decision file: the correction carries today's time, so after September it rotates the file. + string[] lines = AllDecisionLines(); Assert.Equal(3, lines.Length); Assert.Contains("\"decision\":\"Skip\"", lines[0], StringComparison.Ordinal); Assert.Contains("\"rho_W\":-0.7", lines[0], StringComparison.Ordinal); @@ -562,11 +563,65 @@ public sealed class LedgerTests : IDisposable // Appending again never rewrites what was there. ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(t.AddMinutes(30)), skip, "skip", null); - string[] again = [.. ledger.ReadDecisionLines()]; + string[] again = AllDecisionLines(); Assert.Equal(4, again.Length); Assert.Equal(lines, again[..3]); } + [Fact] + public void ALateLineOfThePreviousMonthStaysInTheCurrentFileAndNothingIsLost() + { + // The last bar of a month is evaluated after midnight, once an event of the new month has rotated the file. + // Rotating back would move the new month aside and then fail on the existing file, losing the next line. + using Ledger ledger = new(_dir); + DateTime now = DateTime.UtcNow; + DateTime lastBar = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMinutes(-15); + string previous = lastBar.ToString("yyyyMM", System.Globalization.CultureInfo.InvariantCulture); + BasketDecision skip = new(DecisionKind.Skip, false, null, ["no_signal"], "|z| 0,4 sotto zIn 2", new BasketEvaluation { Z = 0.4 }, null); + + ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(lastBar.AddMinutes(-15)), skip, "skip", null); + ledger.Correction("run1", "B1", "evento del mese nuovo"); + ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(lastBar), skip, "skip", null); + ledger.Correction("run1", "B2", "un altro evento del mese nuovo"); + + List files = Ledger.DecisionFiles(_dir); + Assert.Equal(2, files.Count); + Assert.Equal($"decisions_{previous}.jsonl", Path.GetFileName(files[0])); + Assert.Equal("decisions.jsonl", Path.GetFileName(files[1])); + Assert.Single(Ledger.ReadLines(files[0])); + Assert.Equal(4, AllDecisionLines().Length); + } + + [Fact] + public void ARotatedFileIsNeverOverwritten() + { + // A rotated file of the same month already exists (an old copy put back by hand, a restore): the current + // file goes aside under the next free name, which sorts right after it, and no line is lost. + Directory.CreateDirectory(_dir); + DateTime now = DateTime.UtcNow; + DateTime lastMonth = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(-10); + string previous = lastMonth.ToString("yyyyMM", System.Globalization.CultureInfo.InvariantCulture); + File.WriteAllText(Path.Combine(_dir, $"decisions_{previous}.jsonl"), "{\"ts\":\"vecchia\"}\n"); + BasketDecision skip = new(DecisionKind.Skip, false, null, ["no_signal"], "|z| 0,4 sotto zIn 2", new BasketEvaluation { Z = 0.4 }, null); + + using (Ledger first = new(_dir)) + { + first.Decision("run1", "Demo", "MODERATE", "abcd", Context(lastMonth), skip, "skip", null); + } + + using Ledger ledger = new(_dir); + ledger.Correction("run2", "B1", "evento del mese nuovo"); + + List files = Ledger.DecisionFiles(_dir); + Assert.Equal(3, files.Count); + Assert.Equal($"decisions_{previous}.jsonl", Path.GetFileName(files[0])); + Assert.Equal($"decisions_{previous}_02.jsonl", Path.GetFileName(files[1])); + Assert.Equal("decisions.jsonl", Path.GetFileName(files[2])); + Assert.Equal(3, AllDecisionLines().Length); + } + + private string[] AllDecisionLines() => [.. Ledger.DecisionFiles(_dir).SelectMany(Ledger.ReadLines)]; + [Fact] public void BasketRowsRoundTripAndLinkByBasketId() {