Add the guard that watches the engine and protects positions (refs #48)

The guard (SPEC 9.3, 9.4) is now the container's main process and the parent
of the engine. It listens on a named pipe for the engine's heartbeat and
startup steps, and steps in after two minutes of silence, ten minutes of a
startup that does not move, or an exit without notice. It stops the engine,
cancels our purchases and sales left open on demo accounts, puts back the
stops the positions need from the state file the engine writes every ten
seconds, writes a note, warns the user and restarts the engine without any
injected fault. The third forced restart within an hour writes the STOP
file. The container's stop is passed on to the engine, which closes in order.

At restart the engine adopts the guard's stops before reconciling, cancels
the orders it left open and plans again the exits already decided, so the
rules of SPEC 5.6 apply to them.

The acceptance test blocks the main loop right after a sale leaves: in
process on a demo-like broker, and with real processes in the drill, which
also runs inside the Docker image (tasks ci and the CI workflow). The guard
uses the ASP.NET shared runtime so both programs share /app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:36:32 +01:00
1 parent 680cab4bb6
commit d00dfbd32f
26 files changed
+2607 -19

No files matched your search

+36 -1
View File
@@ -5,6 +5,7 @@ using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Supervision;
using Anubis.Trading;
namespace Anubis.Server;
@@ -72,6 +73,9 @@ internal sealed partial class AnubisHost(
public StartupConfig Config { get; private set; } = initialConfig;
/// <summary>The channel to the guard that started this engine (SPEC 9.3); null without one.</summary>
public GuardLink? Guard { get; init; }
public bool IsDemo => options.Demo;
public HostStatus Status => _status;
@@ -176,6 +180,12 @@ internal sealed partial class AnubisHost(
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
}
// With trading the beat of a running engine comes from the trading loop, so a blocked loop is noticed.
if (_status.Mode != HostMode.Ready || _trading is null)
{
Guard?.Beat();
}
await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false);
}
@@ -213,6 +223,7 @@ internal sealed partial class AnubisHost(
}
Config.Data.Ensure();
Guard?.Step("database");
// A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20).
_db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile));
@@ -234,6 +245,8 @@ internal sealed partial class AnubisHost(
return;
}
Guard?.Step("migrazioni e identità");
// Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays
// empty, so a backup taken with an older schema can still be restored into it.
var backups = new Backups(Config.Data, clock);
@@ -271,6 +284,7 @@ internal sealed partial class AnubisHost(
return;
}
Guard?.Step("servizi");
var key = Config.SecretKey.GetOrCreateKey();
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
@@ -288,12 +302,20 @@ internal sealed partial class AnubisHost(
var scheduler = new Scheduler(clock, bus);
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger)
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger,
Guard is null ? null : GuardDrill.DrillOkx(environment))
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct),
Path.Combine(Config.Data.Root, "STOP"))
{
Guard = Guard,
GuardFiles = Guard is null ? null : new GuardPaths(Config.Data.Root),
// The drill's fault is honored only under a guard, which never passes it to an engine it restarts.
Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable),
}
: null;
if (_trading is not null)
{
@@ -610,6 +632,19 @@ internal sealed partial class AnubisHost(
var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1;
var since = previous.Mode == mode ? previous.Since : clock.UtcNow;
_status = new HostStatus(mode, detail, identity, since, attempts);
if (mode == HostMode.Ready)
{
// Trading tells the guard by itself when its own startup steps are done.
if (_trading is null || _trading.IsStarted)
{
Guard?.Set(GuardStages.Running);
}
}
else
{
Guard?.Set(mode == HostMode.Starting ? GuardStages.Starting : GuardStages.Waiting);
}
if (previous.Mode != mode)
{
LogMode(logger, mode);
+13 -1
View File
@@ -4,6 +4,7 @@ using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Server.Components;
using Anubis.Supervision;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
@@ -52,8 +53,12 @@ internal static class ServerApp
services.AddSingleton(clock);
services.AddSingleton(overrides ?? new ServerOverrides());
services.AddSingleton<EventBus>();
// Started by the guard (SPEC 9.3): the channel to it. Never in demo mode, which protects nothing.
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides));
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides)
{
Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService<ILogger<GuardLink>>()),
});
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
services.AddSingleton(new LoginLimiter(clock));
services.AddSingleton<ShellData>();
@@ -82,6 +87,13 @@ internal static class ServerApp
var app = builder.Build();
var host = app.Services.GetRequiredService<AnubisHost>();
if (host.Guard is { } guard)
{
// The guard asks for an orderly stop when the container stops; every stop of the engine is announced to it.
guard.StopRequested = app.Lifetime.StopApplication;
app.Lifetime.ApplicationStopping.Register(() => guard.AnnounceAsync("uscita").GetAwaiter().GetResult());
app.Lifetime.ApplicationStopped.Register(() => guard.DisposeAsync().AsTask().GetAwaiter().GetResult());
}
app.Use(SecurityHeaders);
app.Use((context, next) => LocalOnly(context, next, options, config));