Ledger: la rotazione mensile delle decisioni va solo in avanti e non sovrascrive mai un file già ruotato

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-01 14:20:23 +02:00
1 parent c618f9fc01
commit 28db7706b0
2 files changed
+81 -6

No files matched your search

+24 -4
View File
@@ -595,7 +595,13 @@ public sealed class Ledger : IDisposable
}
}
/// <summary>Monthly rotation: the current file is moved to <c>decisions_YYYYMM.jsonl</c> when the month changes.</summary>
/// <summary>
/// Monthly rotation: the current file is moved to <c>decisions_YYYYMM.jsonl</c> 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.
/// </summary>
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;
}
/// <summary>
/// <c>decisions_YYYYMM.jsonl</c>, or <c>decisions_YYYYMM_02.jsonl</c> and on when that name is taken: a rotated
/// file is never overwritten, and the suffix sorts right after it in <see cref="DecisionFiles"/>.
/// </summary>
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
+57 -2
View File
@@ -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<string> 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<string> 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()
{