Files
Anubis/src/Anubis/Diagnostics/DiagnosticSampler.cs
T
Alby96andClaude Opus 5.5 6e365673b8
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
Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
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>
2026-11-14 17:57:03 +01:00

182 lines
7.4 KiB
C#

using System.Diagnostics;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Diagnostics;
public static class SampleKinds
{
/// <summary>The first sample of a process, written as soon as the bot is ready.</summary>
public const string Start = "start";
public const string Periodic = "periodic";
}
/// <summary>One look at the process (issue #95). Counters are totals since the process started.</summary>
public sealed record ProcessSample
{
public required DateTimeOffset TakenAt { get; init; }
public required DateTimeOffset ProcessStartedAt { get; init; }
public required string Kind { get; init; }
public string Version { get; init; } = AnubisInfo.Version;
public long WorkingSet { get; init; }
public long PrivateBytes { get; init; }
public long ManagedHeap { get; init; }
public long GcCommitted { get; init; }
public long Gen0 { get; init; }
public long Gen1 { get; init; }
public long Gen2 { get; init; }
public double GcPauseMs { get; init; }
public int Threads { get; init; }
public int Handles { get; init; }
public double CpuMs { get; init; }
public int PoolThreads { get; init; }
public long PoolPending { get; init; }
public long LockContentions { get; init; }
public long Exceptions { get; init; }
public long? DbBytes { get; init; }
public int Warnings { get; init; }
public int Errors { get; init; }
public IReadOnlyList<HttpCallStats> Calls { get; init; } = [];
}
/// <summary>
/// Every 5 minutes, and once at each start, a sample of the process goes to <c>diagnostic_samples</c>, with the log
/// warnings and errors and the outbound calls since the previous one (issue #95, ADR 0013). Samples and job runs older
/// than 30 days are deleted once a day. It only measures: nothing here changes what the bot does.
/// </summary>
public sealed class DiagnosticSampler(Database db, IClock clock, HttpCallMeter meter)
{
public const string JobName = "diagnostica";
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(5);
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
internal static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private DateTimeOffset? _lastPrune;
public ScheduledJob Job() => new(JobName, "Raccolta dei dati per l'analisi", Schedule.Every(Interval), ct => TakeAsync(SampleKinds.Periodic, ct))
{
MaxLateness = Interval,
};
public async Task<ProcessSample> TakeAsync(string kind, CancellationToken cancellationToken)
{
var (warnings, errors) = LogCounter.Take();
var sample = Probe(clock.UtcNow, kind) with
{
DbBytes = await DatabaseBytesAsync(db, cancellationToken).ConfigureAwait(false),
Warnings = warnings,
Errors = errors,
Calls = meter.Take(),
};
var prune = _lastPrune is not { } last || sample.TakenAt - last >= TimeSpan.FromDays(1);
await db.WriteAsync(async s =>
{
await WriteAsync(s, clock, sample, cancellationToken).ConfigureAwait(false);
if (prune)
{
var before = sample.TakenAt - Keep;
await s.ExecuteAsync("DELETE FROM diagnostic_samples WHERE taken_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
await s.ExecuteAsync("DELETE FROM job_runs WHERE started_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
if (prune)
{
_lastPrune = sample.TakenAt;
}
return sample;
}
/// <summary>The process as it is now. Process times come from the system clock: they measure the machine, not the market.</summary>
public static ProcessSample Probe(DateTimeOffset now, string kind)
{
using var process = Process.GetCurrentProcess();
var gc = GC.GetGCMemoryInfo();
return new ProcessSample
{
TakenAt = now,
ProcessStartedAt = new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero),
Kind = kind,
WorkingSet = process.WorkingSet64,
PrivateBytes = process.PrivateMemorySize64,
ManagedHeap = GC.GetTotalMemory(forceFullCollection: false),
GcCommitted = gc.TotalCommittedBytes,
Gen0 = GC.CollectionCount(0),
Gen1 = GC.CollectionCount(1),
Gen2 = GC.CollectionCount(2),
GcPauseMs = Math.Round(GC.GetTotalPauseDuration().TotalMilliseconds, 1),
Threads = process.Threads.Count,
Handles = process.HandleCount,
CpuMs = Math.Round(process.TotalProcessorTime.TotalMilliseconds, 1),
PoolThreads = ThreadPool.ThreadCount,
PoolPending = ThreadPool.PendingWorkItemCount,
LockContentions = Monitor.LockContentionCount,
Exceptions = ExceptionCounter.Count,
};
}
public static async Task WriteAsync(DbSession s, IClock clock, ProcessSample sample, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(sample);
await s.ExecuteAsync(
"INSERT INTO diagnostic_samples (id, taken_at, process_started_at, kind, version, working_set, private_bytes, managed_heap, gc_committed, gc_gen0, gc_gen1, gc_gen2, " +
"gc_pause_ms, threads, handles, cpu_ms, pool_threads, pool_pending, lock_contentions, exceptions, db_bytes, warnings, errors, calls, created_at) VALUES " +
"(@id, @t, @ps, @k, @v, @ws, @pb, @mh, @gcc, @g0, @g1, @g2, @gp, @th, @h, @cpu, @pt, @pp, @lc, @ex, @db, @w, @e, @calls, @now)",
cancellationToken,
("id", Ids.NewId(clock)), ("t", sample.TakenAt), ("ps", sample.ProcessStartedAt), ("k", sample.Kind), ("v", sample.Version), ("ws", sample.WorkingSet),
("pb", sample.PrivateBytes), ("mh", sample.ManagedHeap), ("gcc", sample.GcCommitted), ("g0", sample.Gen0), ("g1", sample.Gen1), ("g2", sample.Gen2),
("gp", sample.GcPauseMs), ("th", sample.Threads), ("h", sample.Handles), ("cpu", sample.CpuMs), ("pt", sample.PoolThreads), ("pp", sample.PoolPending),
("lc", sample.LockContentions), ("ex", sample.Exceptions), ("db", sample.DbBytes), ("w", sample.Warnings), ("e", sample.Errors),
("calls", sample.Calls.Count == 0 ? null : new DbJson(JsonSerializer.Serialize(sample.Calls, Json))), ("now", clock.UtcNow)).ConfigureAwait(false);
}
/// <summary>The size of the database: its files on SQLite (with the journal), what PostgreSQL reports for it.</summary>
public static async Task<long?> DatabaseBytesAsync(Database db, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
try
{
if (db.Engine == DbEngine.Sqlite)
{
return db.SqlitePath is not { } path ? null
: new[] { path, path + "-wal", path + "-shm" }.Where(File.Exists).Sum(f => new FileInfo(f).Length);
}
return await db.ReadAsync(s => s.CountAsync("SELECT pg_database_size(current_database())"), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
{
return null;
}
}
}