Add the endurance run report and record the Phase 6 choices (refs #53 #54)

"anubis soak" reads the bot's records over a time window and says whether
the run kept control. It changes nothing, so it can run beside the working
bot with docker exec. It exits with 4 when something needs a look. It
checks:
- the hours covered and silences longer than 15 minutes;
- orders or decisions made twice;
- unexplained reconciliation differences and each account's last outcome;
- absences and guard interventions;
- one crypto decision per daily close.

ADR 0012 records what the specification leaves open in this phase: the
live engine shares the backtest's decision call, run keys, recovery after
an absence, the guard and its drill seams, the diary templates, the
"senza bot" comparison, Telegram and the heartbeat, the screens and the
endurance run. ROADMAP ticks the Phase 6 items and criteria with the tests
that prove them, STATE moves on to Phase 7, and SVILUPPO explains the
guard and the report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 20:36:22 +01:00
1 parent 9ae107000b
commit 3d174931e9
8 files changed
+549 -19

No files matched your search

+6
View File
@@ -18,6 +18,12 @@ if (args.Length >= 1 && args[0] == "backtest")
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
if (args.Length >= 1 && args[0] == "soak")
{
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;
+77
View File
@@ -0,0 +1,77 @@
using System.Collections;
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
using Anubis.Supervision;
namespace Anubis.Server;
/// <summary>
/// "anubis soak": the report of an endurance run in real time (SPEC 17, phase 6) from the bot's own records. It only
/// reads, so it can run while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
/// </summary>
internal static class SoakCommand
{
private const string Usage =
"Uso: anubis soak [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--hours 48] [--out file.md]\n" +
" senza --from la prova è delle ultime --hours ore fino a --to (o adesso).\n" +
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
/// <summary>0 when the run is in order, 4 when something must be looked at, 1 when the report could not be made.</summary>
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
{
output ??= Console.Out;
clock ??= new SystemClock();
var own = new Dictionary<string, string>(StringComparer.Ordinal);
var rest = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length)
{
own[args[i]] = args[++i];
}
else if (args[i] is "--help" or "-h")
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
else
{
rest.Add(args[i]);
}
}
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
try
{
var hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : 48;
var to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : clock.UtcNow;
var from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : to - TimeSpan.FromHours(hours);
var options = ServerOptions.Parse([.. rest], environment);
var config = options.LoadConfig(environment);
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
return 1;
}
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
var report = await SoakReporter.BuildAsync(db, from, to, TimeSpan.FromHours(hours), config.TimeZone, CancellationToken.None).ConfigureAwait(false);
var text = report.Markdown(config.TimeZone);
if (own.TryGetValue("--out", out var file))
{
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
}
await output.WriteAsync(text).ConfigureAwait(false);
return report.Passed ? 0 : 4;
}
catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException
or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
}
+209
View File
@@ -0,0 +1,209 @@
using System.Globalization;
using System.Text;
using Anubis.Core;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Supervision;
/// <summary>One check of the endurance run: what was looked at and whether it is in order.</summary>
public sealed record SoakCheck(string Text, bool Ok);
/// <summary>
/// The report of an endurance run in real time (SPEC 17, phase 6): over a window of the bot's own records, whether it
/// kept working without losing control. It reads only what the bot wrote; it changes nothing.
/// </summary>
public sealed record SoakReport(DateTimeOffset From, DateTimeOffset To, IReadOnlyList<SoakCheck> Checks, IReadOnlyList<string> Facts)
{
public bool Passed => Checks.All(c => c.Ok);
public string Markdown(TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(zone);
var text = new StringBuilder();
text.AppendLine("# Prova di durata")
.AppendLine()
.AppendLine(CultureInfo.InvariantCulture, $"Dal {Moment(From, zone)} al {Moment(To, zone)} ({Hours(To - From)}).")
.AppendLine()
.AppendLine(Passed ? "**Esito: regolare.**" : "**Esito: da guardare.** Le righe segnate con ✗ dicono cosa.")
.AppendLine()
.AppendLine("## Controlli")
.AppendLine();
foreach (var check in Checks)
{
text.AppendLine(CultureInfo.InvariantCulture, $"- {(check.Ok ? "✓" : "✗")} {check.Text}");
}
text.AppendLine().AppendLine("## Che cosa è successo").AppendLine();
foreach (var fact in Facts)
{
text.AppendLine("- " + fact);
}
return text.ToString();
}
internal static string Moment(DateTimeOffset moment, TimeZoneInfo zone) =>
TimeZoneInfo.ConvertTime(moment, zone).ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
internal static string Hours(TimeSpan span) =>
Format.Number((decimal)Math.Round(span.TotalHours, 1), span.TotalHours % 1 == 0 ? 0 : 1) + " ore";
}
/// <summary>Builds the <see cref="SoakReport"/> from the database.</summary>
public static class SoakReporter
{
/// <summary>The reconciliation runs every 5 minutes: a longer silence than this means the bot stopped working.</summary>
public static readonly TimeSpan MaxSilence = TimeSpan.FromMinutes(15);
public static async Task<SoakReport> BuildAsync(Database db, DateTimeOffset from, DateTimeOffset to, TimeSpan minimum, TimeZoneInfo zone,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(zone);
if (to <= from)
{
throw new ArgumentException("La fine della prova deve venire dopo l'inizio.", nameof(to));
}
return await db.ReadAsync(async s =>
{
var checks = new List<SoakCheck>();
var facts = new List<string>();
(string Name, object? Value)[] window = [("from", from), ("to", to)];
// Continuity: the reconciliation writes a row every 5 minutes, whatever it finds.
var beats = await s.QueryAsync("SELECT occurred_at FROM reconciliations WHERE occurred_at >= @from AND occurred_at <= @to ORDER BY occurred_at",
r => r.Moment("occurred_at"), window).ConfigureAwait(false);
var covered = beats.Count == 0 ? TimeSpan.Zero : beats[^1] - beats[0];
checks.Add(new SoakCheck($"Durata coperta dal lavoro del bot: {SoakReport.Hours(covered)} (servono almeno {SoakReport.Hours(minimum)}).", covered >= minimum));
var silences = new List<(DateTimeOffset Start, TimeSpan Length)>();
var edges = new List<DateTimeOffset> { from };
edges.AddRange(beats);
edges.Add(to);
for (var i = 1; i < edges.Count; i++)
{
if (edges[i] - edges[i - 1] > MaxSilence)
{
silences.Add((edges[i - 1], edges[i] - edges[i - 1]));
}
}
checks.Add(new SoakCheck(silences.Count == 0
? $"Nessun silenzio più lungo di {Minutes(MaxSilence)} ({beats.Count} riconciliazioni)."
: $"Silenzi più lunghi di {Minutes(MaxSilence)}: " +
string.Join(", ", silences.Select(g => $"dal {SoakReport.Moment(g.Start, zone)} per {Minutes(g.Length)}")) + ".", silences.Count == 0));
// No order twice: one order per client id, one execution per order key, one decision per run key.
var doubled = await s.CountAsync("SELECT COUNT(*) FROM (SELECT client_order_id FROM orders GROUP BY client_order_id HAVING COUNT(*) > 1) d").ConfigureAwait(false)
+ await s.CountAsync("SELECT COUNT(*) FROM (SELECT order_key FROM executions GROUP BY order_key HAVING COUNT(*) > 1) d").ConfigureAwait(false)
+ await s.CountAsync("SELECT COUNT(*) FROM (SELECT run_key FROM engine_runs GROUP BY run_key HAVING COUNT(*) > 1) d").ConfigureAwait(false);
checks.Add(new SoakCheck(doubled == 0 ? "Nessun ordine né decisione doppia." : $"Ordini o decisioni doppie: {doubled}.", doubled == 0));
// Reconciliations: never an unexplained difference, and every account ends in agreement.
var outcomes = await s.QueryAsync(
"SELECT a.name AS account, r.outcome AS outcome, COUNT(*) AS n FROM reconciliations r JOIN accounts a ON a.id = r.account_id " +
"WHERE r.occurred_at >= @from AND r.occurred_at <= @to GROUP BY a.name, r.outcome ORDER BY a.name, r.outcome",
r => (Account: r.Text("account"), Outcome: r.Text("outcome"), Count: r.Number("n")), window).ConfigureAwait(false);
var different = outcomes.Where(o => o.Outcome == ReconcileOutcomes.Different).Sum(o => o.Count);
checks.Add(new SoakCheck(different == 0 ? "Nessuna differenza inspiegata tra registro e conti." : $"Riconciliazioni con differenze inspiegate: {different}.", different == 0));
var last = await s.QueryAsync(
"SELECT a.name AS account, r.outcome AS outcome FROM reconciliations r JOIN accounts a ON a.id = r.account_id " +
"WHERE r.occurred_at = (SELECT MAX(x.occurred_at) FROM reconciliations x WHERE x.account_id = r.account_id AND x.occurred_at <= @to) ORDER BY a.name",
r => (Account: r.Text("account"), Outcome: r.Text("outcome")), ("to", to)).ConfigureAwait(false);
var agreed = last.All(l => l.Outcome is ReconcileOutcomes.Clean or ReconcileOutcomes.Healed);
checks.Add(new SoakCheck(last.Count == 0
? "Nessun conto riconciliato."
: "Ultima riconciliazione: " + string.Join(", ", last.Select(l => $"{l.Account} {Outcome(l.Outcome)}")) + ".", last.Count > 0 && agreed));
foreach (var group in outcomes.GroupBy(o => o.Account, StringComparer.Ordinal))
{
facts.Add($"Riconciliazioni di {group.Key}: " + string.Join(", ", group.Select(o => $"{o.Count} {Outcome(o.Outcome)}")) + ".");
}
// The bot was never away and the guard never had to step in.
var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at",
r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false);
checks.Add(new SoakCheck(absences.Count == 0
? "Il bot non si è mai spento."
: "Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Minutes(a.End - a.Start)}")) + ".", absences.Count == 0));
var interventions = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention' AND occurred_at >= @from AND occurred_at <= @to", window)
.ConfigureAwait(false);
checks.Add(new SoakCheck(interventions == 0 ? "La guardia non è mai dovuta intervenire." : $"Interventi della guardia: {interventions}.", interventions == 0));
// A crypto decision at every daily close in the window (00:05 UTC), whatever the stage of the strategy.
var closes = DailyCloses(from, to);
var runs = await s.QueryAsync("SELECT strategy, mode, COUNT(*) AS n FROM engine_runs WHERE created_at >= @from AND created_at <= @to GROUP BY strategy, mode ORDER BY strategy, mode",
r => (Strategy: r.Text("strategy"), Mode: r.Text("mode"), Count: r.Number("n")), window).ConfigureAwait(false);
var crypto = runs.Where(r => r.Strategy == StrategyNames.CryptoTrend).Sum(r => r.Count);
checks.Add(new SoakCheck($"Decisioni di {StrategyNames.CryptoTrend}: {crypto} su {closes} chiusure giornaliere.", crypto >= closes));
facts.Add(runs.Count == 0
? "Nessuna decisione del motore."
: "Decisioni del motore: " + string.Join(", ", runs.Select(r => $"{r.Strategy} {r.Count} ({Mode(r.Mode)})")) + ".");
// What the bot did and wrote, for the record.
facts.Add(Counted("Ordini", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window)
.ConfigureAwait(false)));
facts.Add(Counted("Esecuzioni", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM executions WHERE created_at >= @from AND created_at <= @to GROUP BY status", window)
.ConfigureAwait(false)));
facts.Add(Counted("Ordini pianificati", await GroupAsync(s,
"SELECT status AS k, COUNT(*) AS n FROM planned_orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false)));
facts.Add(Counted("Righe del diario", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM journal WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window)
.ConfigureAwait(false)));
facts.Add(Counted("Messaggi Telegram", await GroupAsync(s,
"SELECT status AS k, COUNT(*) AS n FROM notifications WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false)));
facts.Add(Counted("Eventi di rischio", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM risk_events WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window)
.ConfigureAwait(false)));
facts.Add(Counted("Problemi nei dati", await GroupAsync(s,
"SELECT kind || ' ' || status AS k, COUNT(*) AS n FROM data_issues WHERE created_at >= @from AND created_at <= @to GROUP BY kind, status", window).ConfigureAwait(false)));
var failing = await s.QueryAsync("SELECT name, last_error FROM jobs WHERE last_error IS NOT NULL AND last_finished_at >= @from ORDER BY name",
r => r.Text("name") + " (" + Redactor.Redact(r.Text("last_error")) + ")", ("from", from)).ConfigureAwait(false);
facts.Add(failing.Count == 0 ? "Nessun lavoro in programma è finito con un errore all'ultima esecuzione." : "Lavori con un errore all'ultima esecuzione: " + string.Join("; ", failing) + ".");
return new SoakReport(from, to, checks, facts);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>How many crypto daily decisions (00:05 UTC) fall in the window.</summary>
public static int DailyCloses(DateTimeOffset from, DateTimeOffset to)
{
var count = 0;
for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1))
{
var close = new DateTimeOffset(day.ToDateTime(new TimeOnly(0, 5)), TimeSpan.Zero);
if (close > to)
{
return count;
}
if (close >= from)
{
count++;
}
}
}
private static Task<List<(string Key, long Count)>> GroupAsync(DbSession s, string sql, (string Name, object? Value)[] window) =>
s.QueryAsync(sql, r => (Key: r.TextOrNull("k") ?? "?", Count: r.Number("n")), window);
private static string Counted(string what, List<(string Key, long Count)> groups) =>
groups.Count == 0 ? what + ": nessuno." : $"{what}: {groups.Sum(g => g.Count)} (" + string.Join(", ", groups.Select(g => $"{g.Key} {g.Count}")) + ").";
private static string Minutes(TimeSpan span) =>
span.TotalMinutes < 120 ? Format.Number((decimal)Math.Round(span.TotalMinutes)) + " minuti" : SoakReport.Hours(span);
private static string Outcome(string outcome) => outcome switch
{
ReconcileOutcomes.Clean => "in regola",
ReconcileOutcomes.Healed => "sistemate da sole",
ReconcileOutcomes.Different => "con differenze",
ReconcileOutcomes.Unreachable => "conto non raggiungibile",
_ => outcome,
};
private static string Mode(string mode) => mode switch
{
DecisionModes.Observation => "in osservazione",
DecisionModes.ExitsOnly => "solo uscite",
DecisionModes.Full => "complete",
_ => mode,
};
}