Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped

The 48-hour soak run at home kept being cut short by the host, never by Anubis.
The user will instead run a release for as long as they like and paste back a
report, so the bot now records what that report needs (ADR 0013).

- Every 5 minutes and at each start, a process sample goes to diagnostic_samples:
  memory, GC, threads, handles, CPU, exceptions, database size, log warnings and
  errors, and outbound HTTP calls by destination with duration buckets, read from
  the System.Net.Http meter without any new package.
- Every scheduled job run goes to job_runs. Both tables keep 30 days.
- The Markdown report (at most 60 KB, redacted, user folders masked) adds
  findings, the soak checks, starts and silences, jobs, calls, grouped log
  warnings and errors, and resources over time with their slopes. It comes from
  "anubis diagnostics", GET /api/diagnostica.md and a button in Diario e sistema.
- New {long} column token: SQLite STRICT tables reject BIGINT.
- "tasks release-win" builds the trial zip with a start script, a script that
  writes the report, and Italian instructions. Version 0.7.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-14 17:57:03 +01:00
1 parent 32673007a2
commit 6e365673b8
26 files changed
+1678 -18

No files matched your search

+21 -1
View File
@@ -4,6 +4,7 @@ using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Diagnostics;
using Anubis.Platform;
using Anubis.Supervision;
using Anubis.Trading;
@@ -72,6 +73,7 @@ internal sealed partial class AnubisHost(
private TradingService? _trading;
private TelegramServices? _telegram;
private Laboratory? _lab;
private DiagnosticSampler? _sampler;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
@@ -156,6 +158,10 @@ internal sealed partial class AnubisHost(
LogDemo(logger, Config.Data.Root);
}
// From the first moment: every exception and every outbound call of the process is counted (issue #95).
ExceptionCounter.Start();
_ = HttpCallMeter.Shared;
while (!stoppingToken.IsCancellationRequested)
{
Task wake;
@@ -349,6 +355,9 @@ internal sealed partial class AnubisHost(
: new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram);
// The data for the analysis of a long run (issue #95, ADR 0013); the demo has nothing to analyse.
_sampler = options.Demo ? null : new DiagnosticSampler(_db, clock, HttpCallMeter.Shared);
// Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6).
var lastDues = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
try
@@ -363,6 +372,11 @@ internal sealed partial class AnubisHost(
{
lastDues[name] = due;
}
if (_sampler is not null)
{
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
@@ -494,7 +508,7 @@ internal sealed partial class AnubisHost(
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
{
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
@@ -618,6 +632,12 @@ internal sealed partial class AnubisHost(
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
}
// Every run, for the lateness and the durations in the diagnostics report (issue #95).
await s.ExecuteAsync(
"INSERT INTO job_runs (id, job, due_at, started_at, finished_at, outcome, missed, error, created_at) VALUES (@id, @n, @d, @s, @f, @o, @m, @e, @f)",
("id", Ids.NewId(clock)), ("n", run.Name), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
("o", run.Outcome.ToString().ToLowerInvariant()), ("m", run.Missed), ("e", run.Error is null ? null : Redactor.Redact(run.Error))).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
@@ -116,6 +116,8 @@
}
<p class="note">@s.Running</p>
<a class="btn" href="/api/registri.zip" download><Icon Name="download" Size="18" />Scarica i registri tecnici</a>
<a class="btn" href="/api/diagnostica.md" download><Icon Name="download" Size="18" />Scarica i dati per l'analisi</a>
<p class="note">I dati per l'analisi sono un testo da incollare a chi segue lo sviluppo: risorse, lavori, chiamate ed errori, senza chiavi né password.</p>
</section>
</div>
</div>
+139
View File
@@ -0,0 +1,139 @@
using System.Collections;
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
using Anubis.Diagnostics;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>The diagnostics report (issue #95, ADR 0013) as the command, the download and the Diario button make it.</summary>
internal static class DiagnosticsExport
{
/// <summary>Thirty days: as long as the samples are kept.</summary>
public const double MaxHours = 720;
/// <summary>
/// The report over the last <paramref name="hours"/> hours up to <paramref name="to"/>, or from
/// <paramref name="from"/>; without either, from the first sample kept, so a run of a release is covered whole.
/// </summary>
public static async Task<string> BuildAsync(Database db, StartupConfig config, IReadOnlyDictionary<string, string?> environment, DateTimeOffset now,
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
{
var end = to ?? now;
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours ?? MaxHours, 0.25, MaxHours));
if (from is null && hours is null)
{
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(taken_at) AS t FROM diagnostic_samples", r => r.MomentOrNull("t")), cancellationToken)
.ConfigureAwait(false);
if (first is { } f && f > start && f < end)
{
start = f;
}
}
var request = new DiagnosticsRequest(start, end, config.TimeZone)
{
LogsFolder = config.Data.Logs,
Setup = Setup(config, environment),
GeneratedAt = now,
};
return await DiagnosticsReporter.BuildAsync(db, request, cancellationToken).ConfigureAwait(false);
}
/// <summary>The startup settings, and which ANUBIS_ variables are set: values only for those that cannot hold a secret.</summary>
internal static IReadOnlyList<KeyValuePair<string, string>> Setup(StartupConfig config, IReadOnlyDictionary<string, string?> environment)
{
var lines = new List<KeyValuePair<string, string>>
{
new("Piattaforma", config.Platform.ToString().ToLowerInvariant()),
new("Database", config.Db?.Describe() ?? "non configurato"),
new("Cartella dei dati", config.Data.Root),
new("Rete consentita", config.AllowNetwork ? "sì" : "no"),
new("Ordini reali consentiti", config.AllowLive ? "sì" : "no"),
};
var variables = environment
.Where(e => e.Key.StartsWith(AnubisInfo.EnvironmentPrefix, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(e.Value))
.OrderBy(e => e.Key, StringComparer.Ordinal)
.Select(e => e.Key + (Secretive(e.Key) ? "" : "=" + e.Value))
.ToList();
lines.Add(new("Variabili impostate", variables.Count == 0 ? "nessuna" : string.Join(", ", variables)));
return lines;
}
private static readonly string[] _secretWords = ["KEY", "SECRET", "PASS", "TOKEN", "URL"];
private static bool Secretive(string name) => _secretWords.Any(word => name.Contains(word, StringComparison.OrdinalIgnoreCase));
public static IReadOnlyDictionary<string, string?> ProcessEnvironment() =>
Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
}
/// <summary>
/// "anubis diagnostics": the report to paste back after a long run of a release (issue #95, ADR 0013). It only reads,
/// so it runs while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
/// </summary>
internal static class DiagnosticsCommand
{
private const string Usage =
"Uso: anubis diagnostics [--hours 72] [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--out file.md]\n" +
" senza --hours né --from copre tutto ciò che è stato raccolto (al massimo 30 giorni).\n" +
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
/// <summary>0 when the report was made, 1 when it could not be, 2 for the usage.</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 ??= DiagnosticsExport.ProcessEnvironment();
try
{
double? hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : null;
DateTimeOffset? to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
DateTimeOffset? from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
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 text = await DiagnosticsExport.BuildAsync(db, config, environment, clock.UtcNow, hours, from, to, CancellationToken.None).ConfigureAwait(false);
if (own.TryGetValue("--out", out var file))
{
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
}
await output.WriteAsync(text).ConfigureAwait(false);
return 0;
}
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;
}
}
}
+9
View File
@@ -183,6 +183,15 @@ internal static partial class Endpoints
return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip");
});
// The data collected for the analysis of a long run, as one Markdown report to paste (issue #95, ADR 0013).
api.MapGet("/diagnostica.md", async (AnubisHost host, ShellData shell, IClock clock, double? ore, CancellationToken ct) =>
{
var now = clock.UtcNow;
var text = await DiagnosticsExport.BuildAsync(host.Services!.Db, host.Config, DiagnosticsExport.ProcessEnvironment(), now, ore, null, null, ct).ConfigureAwait(false);
var day = TimeZoneInfo.ConvertTime(now, shell.Zone).ToString("yyyy-MM-dd-HHmm", System.Globalization.CultureInfo.InvariantCulture);
return Results.File(System.Text.Encoding.UTF8.GetBytes(text), "text/markdown; charset=utf-8", $"anubis-diagnostica-{day}.md");
});
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
{
+2
View File
@@ -3,6 +3,7 @@ using System.Globalization;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Diagnostics;
namespace Anubis.Server;
@@ -33,6 +34,7 @@ internal sealed class JsonLogProvider : ILoggerProvider
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
{
LogCounter.Record(level);
var now = _clock.UtcNow;
using var buffer = new MemoryStream();
using (var json = new Utf8JsonWriter(buffer))
+6
View File
@@ -24,6 +24,12 @@ if (args.Length >= 1 && args[0] == "soak")
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
if (args.Length >= 1 && args[0] == "diagnostics")
{
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;