Prove che cadevano con il runner carico (#46)
verifica / controlli (push) Successful in 25s
verifica / prove (push) Successful in 25m9s
verifica / installatore (push) Successful in 7m37s
verifica / immagine (push) Successful in 20m21s

Le prove cadevano a ogni carico della CI, ogni volta prove diverse. Dietro alcune c'erano
difetti veri: FebeDatabase lasciava i file aperti dopo DisposeAsync (comandi SQLite non
chiusi, pool di lettura chiuso dopo lo scrittore), e il WAL spariva durante lo spostamento
della cartella Dati; la scheda dell'account senza statistiche leggeva i file di tutta la
libreria; l'arresto di FebeApp non aspettava i lavori aggiunti da un avvio in corso.
Chromium ha 120 s per avviarsi e aprire la prima scheda, e il ricollegamento smette appena
il processo cambia.

Nelle prove i limiti di tempo diventano protezioni contro un blocco: attese per condizione
con un aiuto comune, limiti per classe nella prova di scala con il tempo migliore, porta 0 e
stderr di Chromium nel browser delle prove, e la prova di «Scollega» di WebView2 controlla
che il processo esca davvero. Provato su Windows con tutti i core occupati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 19:50:40 +01:00
1 parent e2e64c09e8
commit 0775a1460f
34 files changed
+875 -245

No files matched your search

+78 -14
View File
@@ -37,6 +37,8 @@ public sealed class FebeApp : IAsyncDisposable
private readonly FebeAppOptions _options;
private readonly IFebePlatform _platform;
private readonly CancellationTokenSource _lifetime = new();
// The start adds to these lists from its background tasks while a stop may already be running (#46): one lock.
private readonly Lock _gate = new();
private readonly List<Task> _background = [];
private readonly List<IDisposable> _disposables = [];
private readonly List<Action> _unsubscribe = [];
@@ -261,14 +263,14 @@ public sealed class FebeApp : IAsyncDisposable
services.Diagnostics = diagnostics;
EventHandler<Permit> permitDenied = (_, permit) => diagnostics.PermitDenied(null, permit.Kind, permit.Reason);
services.Governor.Denied += permitDenied;
_unsubscribe.Add(() => services.Governor.Denied -= permitDenied);
OnStop(() => services.Governor.Denied -= permitDenied);
var runner = new DeferredRecipeRunner();
var engine = new EngineHost(services, runner);
Engine = engine;
connection.AttachEngine(engine);
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
browser.UserDriving.Changed += drivingChanged;
_unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged);
OnStop(() => browser.UserDriving.Changed -= drivingChanged);
_telegram = new TelegramClient(hooks.TelegramHandler);
var telegramChannel = new TelegramAlertChannel(_telegram);
@@ -320,10 +322,43 @@ public sealed class FebeApp : IAsyncDisposable
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
var lifetime = _lifetime.Token;
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
_background.Add(Task.Run(() => Alerts.WatchDiskSpaceAsync(lifetime), CancellationToken.None));
InBackground(() => CleanTemporaryFilesAsync(staging, layout, lifetime));
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime));
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
}
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
private void InBackground(Func<Task> work)
{
lock (_gate)
{
_background.Add(Task.Run(work, CancellationToken.None));
}
}
/// <summary>Keeps <paramref name="disposable"/> for the stop; disposes it at once when the stop already took its list.</summary>
private void DisposeOnStop(IDisposable disposable)
{
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 0)
{
_disposables.Add(disposable);
return;
}
}
disposable.Dispose();
}
/// <summary>Keeps <paramref name="unsubscribe"/> for the stop.</summary>
private void OnStop(Action unsubscribe)
{
lock (_gate)
{
_unsubscribe.Add(unsubscribe);
}
}
private async Task StartWebAsync(FebeAppHooks hooks, Action<IServiceCollection> register)
@@ -392,8 +427,8 @@ public sealed class FebeApp : IAsyncDisposable
runner.Target = Pipeline.Runner;
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
var changes = Web.Services.GetRequiredService<LibraryChanges>();
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
DisposeOnStop(changes.Attach(Pipeline.Downloads, Clock));
InBackground(() => DownloadLoopAsync(Pipeline.Downloads, ct));
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
var downloads = Pipeline.Downloads;
@@ -406,7 +441,7 @@ public sealed class FebeApp : IAsyncDisposable
}
services.Events.Notified += WakeDownloads;
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
OnStop(() => services.Events.Notified -= WakeDownloads);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
@@ -414,7 +449,7 @@ public sealed class FebeApp : IAsyncDisposable
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
InBackground(() => Connection.RunAsync(ct));
await engine.StartAsync(ct).ConfigureAwait(false);
Log.Info("motore", Connection.IsConnected == true
? "Motore avviato: il browser è collegato."
@@ -634,17 +669,46 @@ public sealed class FebeApp : IAsyncDisposable
}
await _lifetime.CancelAsync().ConfigureAwait(false);
foreach (var task in _background.ToArray())
// A start still in progress adds tasks while the first ones are awaited: look again until nothing new appears,
// so nothing still reads the database once it is closed (#46).
var awaited = 0;
while (true)
{
await Quietly(() => task).ConfigureAwait(false);
Task[] pending;
lock (_gate)
{
pending = _background.Skip(awaited).ToArray();
}
if (pending.Length == 0)
{
break;
}
foreach (var task in pending)
{
await Quietly(() => task).ConfigureAwait(false);
}
awaited += pending.Length;
}
foreach (var disposable in _disposables)
IDisposable[] disposables;
Action[] unsubscribes;
lock (_gate)
{
disposables = [.. _disposables];
unsubscribes = [.. _unsubscribe];
_disposables.Clear();
}
foreach (var disposable in disposables)
{
disposable.Dispose();
}
foreach (var unsubscribe in _unsubscribe)
foreach (var unsubscribe in unsubscribes)
{
unsubscribe();
}
@@ -29,7 +29,12 @@ public sealed record ChromiumLaunchOptions
/// <summary>Start page: always the rest page.</summary>
public string StartUrl { get; init; } = "about:blank";
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>
/// How long a Chromium that is alive may take to open its debugging port and its first tab. A crash fails the start
/// at once; this only bounds a browser that hangs, so it is generous for a loaded machine (docs/decisioni.md, #46).
/// </summary>
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(120);
public RestartPolicy Restart { get; init; } = RestartPolicy.Default;
+53 -13
View File
@@ -255,27 +255,37 @@ public sealed class ChromiumProcessHost : IBrowserHost
$"La porta di debug {port} non è limitata a 127.0.0.1 ({listeners.Count} punti di ascolto): avvio annullato (specifica §6.1).");
}
await ConnectAsync(port, ct).ConfigureAwait(false);
await ConnectAsync(
port,
deadline,
() => process.HasExited ? $"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd() : null,
ct).ConfigureAwait(false);
}
private async Task ConnectAsync(int port, CancellationToken ct)
/// <summary>
/// Connects to the first page target. The first tab may appear a while after the port opens on a loaded machine:
/// the wait shares the start deadline, and ends at once when <paramref name="gone"/> says the process is no longer the
/// one to connect to (it exited, or the supervisor replaced it): nobody waits on the connect lock for a dead browser.
/// </summary>
private async Task ConnectAsync(int port, DateTimeOffset deadline, Func<string?> gone, CancellationToken ct)
{
await _connectLock.WaitAsync(ct).ConfigureAwait(false);
try
{
CdpTarget? page = null;
for (var attempt = 0; attempt < 50 && page is null; attempt++)
CdpTarget? page;
while ((page = await TryFindPageAsync(port, ct).ConfigureAwait(false)) is null)
{
page = await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
if (page is null)
if (gone() is { } reason)
{
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
throw new InvalidOperationException(reason);
}
}
if (page is null)
{
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
if (_clock.Now >= deadline)
{
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
}
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
var client = await CdpClient.ConnectAsync(page.WebSocketDebuggerUrl, _log, null, ct).ConfigureAwait(false);
@@ -304,6 +314,23 @@ public sealed class ChromiumProcessHost : IBrowserHost
}
}
/// <summary>The page target, or null when there is none yet or the endpoint did not answer this time.</summary>
private static async Task<CdpTarget?> TryFindPageAsync(int port, CancellationToken ct)
{
try
{
return await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
}
catch (HttpRequestException)
{
return null;
}
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
{
return null; // a slow answer of /json/list, not a missing one
}
}
private void OnClientDisconnected(object? sender, Exception? reason)
{
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
@@ -330,11 +357,19 @@ public sealed class ChromiumProcessHost : IBrowserHost
return;
}
for (var attempt = 0; attempt < 3; attempt++)
// The process that dropped the connection: if it exits or the supervisor restarts it, stop at once and leave
// the connect lock to the restart, which connects by itself.
var processId = supervisor.ProcessId;
string? Gone() => supervisor.State != SupervisedState.Running || supervisor.ProcessId != processId
? "Chromium è stato riavviato o si è chiuso durante il ricollegamento."
: null;
var deadline = _clock.Now + _launch.StartupTimeout;
for (var attempt = 0; attempt < 3 && Gone() is null; attempt++)
{
try
{
await ConnectAsync(_options.DebugPort, ct).ConfigureAwait(false);
await ConnectAsync(_options.DebugPort, deadline, Gone, ct).ConfigureAwait(false);
_log.Info("Collegamento con Chromium ripristinato.");
return;
}
@@ -344,6 +379,11 @@ public sealed class ChromiumProcessHost : IBrowserHost
}
}
if (Gone() is not null)
{
return;
}
_log.Warn("Collegamento con Chromium perso: riavvio del browser.");
supervisor.KillCurrent();
}
+37
View File
@@ -0,0 +1,37 @@
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>
/// Keeps the commands that <see cref="Sql.Command"/> creates on this thread while a read runs, and disposes them when the
/// read ends. Reads build their commands inline (<c>c.Command(...).ExecuteReader()</c>); left to the garbage collector,
/// a command keeps its SQLite statement alive until the finalizer runs, so the connection closed by
/// <see cref="FebeDatabase.DisposeAsync"/> would only really close then, keeping the files open (#46).
/// </summary>
internal sealed class CommandScope : IDisposable
{
[ThreadStatic]
private static CommandScope? t_current;
private readonly CommandScope? _outer;
private readonly List<SqliteCommand> _commands = [];
private CommandScope(CommandScope? outer) => _outer = outer;
/// <summary>Starts tracking the commands created on this thread until the scope is disposed.</summary>
public static CommandScope Begin() => t_current = new CommandScope(t_current);
/// <summary>Adds <paramref name="command"/> to the open scope of this thread, if any.</summary>
public static void Track(SqliteCommand command) => t_current?._commands.Add(command);
public void Dispose()
{
t_current = _outer;
foreach (var command in _commands)
{
command.Dispose();
}
_commands.Clear();
}
}
+16 -11
View File
@@ -118,16 +118,16 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
try
{
connection.Open();
var mode = connection.Command("PRAGMA journal_mode = WAL").ExecuteScalar() as string;
var mode = connection.Scalar("PRAGMA journal_mode = WAL") as string;
if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase))
{
throw new DatabaseMigrationException(
$"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale.");
}
connection.Command("PRAGMA synchronous = NORMAL").ExecuteNonQuery();
connection.Command($"PRAGMA busy_timeout = {BusyTimeoutMs}").ExecuteNonQuery();
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
connection.Execute("PRAGMA synchronous = NORMAL");
connection.Execute($"PRAGMA busy_timeout = {BusyTimeoutMs}");
connection.Execute("PRAGMA foreign_keys = ON");
var version = MigrationRunner.Apply(connection, migrations);
return new FebeDatabase(path, connection, readConnectionString, version);
}
@@ -155,6 +155,7 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
try
{
using var connection = OpenReadConnection();
using var commands = CommandScope.Begin(); // disposed first: the connection then really closes
return Task.FromResult(work(connection));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
@@ -184,7 +185,8 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
connection =>
{
// VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer.
connection.Command("VACUUM INTO @destination").With("@destination", destination).ExecuteNonQuery();
using var vacuum = connection.Command("VACUUM INTO @destination").With("@destination", destination);
vacuum.ExecuteNonQuery();
return true;
},
ct);
@@ -210,9 +212,17 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
}
Writer.Dispose();
// The idle read connections close first, so the writer is the last connection: only the writer can checkpoint
// and delete febe.sqlite-wal and -shm when it closes (a read-only connection leaves them behind).
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
try
{
_writerConnection.Command("PRAGMA wal_checkpoint(TRUNCATE)").ExecuteNonQuery();
_writerConnection.Execute("PRAGMA wal_checkpoint(TRUNCATE)");
}
catch (SqliteException)
{
@@ -220,11 +230,6 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
}
_writerConnection.Dispose();
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
return ValueTask.CompletedTask;
}
}
+7 -7
View File
@@ -77,7 +77,7 @@ internal static partial class MigrationRunner
}
public static int GetVersion(SqliteConnection connection) =>
(int)connection.Command("PRAGMA user_version").ScalarInt64();
Convert.ToInt32(connection.Scalar("PRAGMA user_version"), CultureInfo.InvariantCulture);
/// <summary>Applies the pending migrations. Returns the resulting version.</summary>
public static int Apply(SqliteConnection connection, IReadOnlyList<Migration> migrations)
@@ -97,7 +97,7 @@ internal static partial class MigrationRunner
}
// Table rebuilds in later migrations need foreign keys off; they are checked before each commit instead.
connection.Command("PRAGMA foreign_keys = OFF").ExecuteNonQuery();
connection.Execute("PRAGMA foreign_keys = OFF");
try
{
foreach (var migration in migrations.Where(m => m.Version > current))
@@ -105,8 +105,9 @@ internal static partial class MigrationRunner
using var transaction = connection.BeginTransaction(deferred: false);
try
{
connection.Command(migration.Sql, transaction).ExecuteNonQuery();
using (var check = connection.Command("PRAGMA foreign_key_check", transaction).ExecuteReader())
connection.Execute(migration.Sql, transaction);
using (var checkCommand = connection.Command("PRAGMA foreign_key_check", transaction))
using (var check = checkCommand.ExecuteReader())
{
if (check.Read())
{
@@ -115,8 +116,7 @@ internal static partial class MigrationRunner
}
}
connection.Command(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction)
.ExecuteNonQuery();
connection.Execute(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction);
transaction.Commit();
}
catch (Exception ex) when (ex is SqliteException or DatabaseMigrationException)
@@ -130,7 +130,7 @@ internal static partial class MigrationRunner
}
finally
{
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
connection.Execute("PRAGMA foreign_keys = ON");
}
return GetVersion(connection);
+19
View File
@@ -75,9 +75,28 @@ internal static class Sql
var command = connection.CreateCommand();
command.CommandText = sql;
command.Transaction = transaction;
CommandScope.Track(command);
return command;
}
/// <summary>
/// Runs a statement and disposes its command at once. A command left to the garbage collector keeps its SQLite
/// statement alive until the finalizer runs, and a connection closed meanwhile only closes then: the WAL and its
/// handles outlive <see cref="FebeDatabase.DisposeAsync"/> (#46).
/// </summary>
public static int Execute(this SqliteConnection connection, string sql, SqliteTransaction? transaction = null)
{
using var command = connection.Command(sql, transaction);
return command.ExecuteNonQuery();
}
/// <summary>Runs a query for one value and disposes its command at once (see <see cref="Execute"/>).</summary>
public static object? Scalar(this SqliteConnection connection, string sql)
{
using var command = connection.Command(sql);
return command.ExecuteScalar();
}
/// <summary>Sets a parameter, adding it the first time: a prepared command can be run again with new values.</summary>
public static SqliteCommand With(this SqliteCommand command, string name, object? value)
{
+15 -8
View File
@@ -221,14 +221,21 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
}
}
var bytes = c.Command("""
SELECT COALESCE(SUM(m.bytes), 0) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.state IN ('Downloaded', 'Imported')
""").With("@a", accountId).ScalarInt64();
var pending = c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.state IN ('ToDownload', 'Expired')
""").With("@a", accountId).ScalarInt64();
// One pass over the account's files, driven from its entries (CROSS JOIN keeps entry as the outer loop):
// without ANALYZE statistics SQLite otherwise starts from the media state index and reads the files of
// the whole library for one account's card (#46).
long bytes, pending;
using (var r = c.Command("""
SELECT COALESCE(SUM(CASE WHEN m.state IN ('Downloaded', 'Imported') THEN m.bytes END), 0),
COALESCE(SUM(m.state IN ('ToDownload', 'Expired')), 0)
FROM entry e CROSS JOIN media m ON m.entry_id = e.id
WHERE e.account_id = @a
""").With("@a", accountId).ExecuteReader())
{
r.Read();
bytes = r.GetInt64(0);
pending = r.GetInt64(1);
}
var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL")
.With("@a", accountId).ScalarInt64();