From a5a6918daeb529dc48cbf144746b277f4c1cda8f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Mon, 16 Nov 2026 09:41:45 +0100 Subject: [PATCH] Keep the guard drill's engine off the internet (refs #102) Since Phase 7 the drill's child engine read the real news feeds every two minutes and downloaded the ONNX tone model, and it already asked the ECB, the mood and calendar sources and the Binance archives. The drill is meant to stay on the computer (ADR 0012 point 5) and that extra work loaded the slow CI runner while the drill timed the engine. Under a guard with the drill's loopback OKX, the market data now runs offline: no news job, no model, and every request goes through a loopback-only handler that answers anything else with a final 403, so no source retries with back-off and the engine keeps its pace. No new variable: the drill is recognised by the same conditions as its fake OKX. The drill gains an eighth check (no news read, no model downloaded), and a test runs every market data job, a history round and a news round as the drill builds them and finds only loopback requests on the network. ADR 0016. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0016-esercitazione-senza-internet.md | 35 ++++++++++++ src/Anubis.Server/AnubisHost.cs | 8 ++- src/Anubis/Data/MarketDataService.cs | 39 +++++++++---- src/Anubis/Supervision/GuardDrill.cs | 9 ++- src/Anubis/Supervision/LoopbackOnlyHandler.cs | 49 ++++++++++++++++ tests/Anubis.Tests/GuardTests.cs | 57 +++++++++++++++++++ 6 files changed, 184 insertions(+), 13 deletions(-) create mode 100644 docs/adr/0016-esercitazione-senza-internet.md create mode 100644 src/Anubis/Supervision/LoopbackOnlyHandler.cs diff --git a/docs/adr/0016-esercitazione-senza-internet.md b/docs/adr/0016-esercitazione-senza-internet.md new file mode 100644 index 0000000..96d23e5 --- /dev/null +++ b/docs/adr/0016-esercitazione-senza-internet.md @@ -0,0 +1,35 @@ +# 0016 — Il motore dell'esercitazione della guardia non esce dal computer + +Data: 2026-11-16 · Stato: accettata · Precisa l'ADR 0012 (punto 5), issue #102, senza componenti esterni nuovi + +## Contesto + +L'esercitazione della guardia (`Anubis.Guard drill`, nell'immagine `anubis drill`, e il test `TheGuardDrillPassesWithTheRealEngineAsChildProcess`) avvia il motore vero come processo figlio. L'ADR 0012 dice che i prezzi vengono da un finto OKX locale (`ANUBIS_DRILL_OKX_URL`, solo su indirizzi loopback). La documentazione della prova aggiunge che dal computer non esce nulla. + +Dalla Fase 7 non era più vero. Il motore della prova faceva il suo lavoro normale anche sul resto della rete: +- la lettura delle notizie ogni 2 minuti, sui feed RSS veri (ANSA, CNBC, CoinDesk e gli altri); +- lo scaricamento del modello ONNX del tono da Hugging Face; +- e, già da prima, i cambi della BCE, l'umore del mercato, il calendario economico e gli archivi di Binance. + +Si vede nella CI, esecuzione 331, lavoro 1122: righe "News from ANSA…" e "News classifier ready" dal motore della prova. Sull'esecutore lento della CI è lavoro in più proprio mentre la prova misura i tempi del motore. + +## Decisione + +1. **La prova si riconosce da sola, senza variabili nuove.** Il motore è nella prova quando gira sotto la guardia e `ANUBIS_DRILL_OKX_URL` punta a un indirizzo locale: le stesse condizioni per cui usa già il finto OKX. Fuori dalla guardia la variabile non conta, come prima. +2. **Nella prova la raccolta dei dati non esce dal computer** (`MarketDataService` con `offline`): + - il lavoro `notizie` non è in programma; + - il modello del tono non si scarica; + - tutte le richieste della raccolta passano da `LoopbackOnlyHandler`. Quelle verso il computer stesso (il finto OKX) partono. Le altre ricevono subito, senza partire, una risposta 403 con la frase "Esercitazione della guardia: nessuna richiesta esce dal computer.". +3. **Il 403 è una risposta definitiva, non un errore di rete.** Un errore di rete farebbe ripetere la richiesta dopo 2, 4 e 8 secondi. Così invece ogni fonte fallisce subito e lo annota come al solito, e i lavori del motore tengono il loro ritmo. +4. **Un ottavo controllo nella prova**, dopo i sette dell'ADR 0012: nessuna notizia letta e nessun file nella cartella `models`. Vale nei test e nell'immagine Docker. +5. **Un test senza processi** (`TheDrillsEngineReadsNoNewsAndSendsNothingOutsideLoopback`) costruisce la raccolta dei dati come la costruisce il motore nella prova. Su una rete finta esegue una volta ogni lavoro, un giro dello storico e un giro delle notizie, e controlla: + - nessun lavoro `notizie`; + - tutte le richieste arrivate alla rete sono verso loopback; + - ogni feed è stato provato e fermato; + - nessuna notizia e nessun modello. + +## Conseguenze + +- La documentazione della prova torna vera per la raccolta dei dati: i prezzi vengono dal finto OKX e il resto non parte. Il motore della prova non ha chiavi né per Alpaca né per Telegram e non riceve l'indirizzo del segnale di vita: neanche quelle parti mandano richieste. +- Nel registro della prova compaiono le fonti rifiutate (cambi, umore, calendario, Binance) come fonti che non rispondono. È atteso: nella prova non servono. +- Il bot vero non cambia. Senza la guardia, o senza il finto OKX locale, la raccolta dei dati è quella di sempre. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index e3ba775..d14aadb 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -313,9 +313,13 @@ internal sealed partial class AnubisHost( } var scheduler = new Scheduler(clock, bus); + + // The guard drill's engine: prices from the drill's local OKX, and then nothing else leaves the computer either + // (no news, no model, no other source: ADR 0016). Honored only under a guard, like the drill's OKX itself. + var drill = Guard is null ? null : GuardDrill.DrillOkx(environment); _market = MarketDataEnabled - ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, - Guard is null ? null : GuardDrill.DrillOkx(environment)) + ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, drill, + offline: drill is not null) : 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, diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index 268fc0e..7f90b99 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -54,7 +54,7 @@ public sealed partial class MarketDataService : IDisposable private (string Key, string Secret, AlpacaClient Client)? _alpaca; public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data, - HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null, OkxOptions? okx = null) + HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null, OkxOptions? okx = null, bool offline = false) { _db = db; _clock = clock; @@ -63,13 +63,8 @@ public sealed partial class MarketDataService : IDisposable _data = data; _sockets = sockets; _logger = logger ?? NullLogger.Instance; - _http = handler is null - ? new HttpClient(new SocketsHttpHandler - { - PooledConnectionLifetime = TimeSpan.FromMinutes(10), - AutomaticDecompression = System.Net.DecompressionMethods.All, - }) - : new HttpClient(handler, disposeHandler: false); + Offline = offline; + _http = Client(handler, offline); _http.Timeout = TimeSpan.FromSeconds(60); _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); @@ -82,9 +77,15 @@ public sealed partial class MarketDataService : IDisposable _universes = new UniverseStore(db, clock); _builder = new UniverseBuilder(db, clock); _states = new SourceStateStore(db, clock); - News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") }; + News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models") }; } + /// + /// The guard drill's engine (ADR 0016): no news job, no model to download, and no request leaves the computer; + /// prices come from the drill's local OKX. + /// + public bool Offline { get; } + public OkxClient Okx { get; } public FreshnessMonitor Freshness { get; } @@ -125,7 +126,7 @@ public sealed partial class MarketDataService : IDisposable RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync) { MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) }, - News.Job(), + .. Offline ? Array.Empty() : [News.Job()], ]; /// @@ -157,6 +158,24 @@ public sealed partial class MarketDataService : IDisposable _http.Dispose(); } + // The connection pool shared by every source; offline, only this computer's own addresses are reached. + private static HttpClient Client(HttpMessageHandler? handler, bool offline) + { + var owned = handler is null; + var network = handler ?? new SocketsHttpHandler + { + PooledConnectionLifetime = TimeSpan.FromMinutes(10), + AutomaticDecompression = System.Net.DecompressionMethods.All, + }; + if (offline) + { + network = new Supervision.LoopbackOnlyHandler(network, owned); + owned = true; + } + + return new HttpClient(network, disposeHandler: owned); + } + /// The Alpaca client with the paper account keys, or null when they are missing. public async Task AlpacaAsync(CancellationToken cancellationToken) { diff --git a/src/Anubis/Supervision/GuardDrill.cs b/src/Anubis/Supervision/GuardDrill.cs index 33fd486..27bf6b9 100644 --- a/src/Anubis/Supervision/GuardDrill.cs +++ b/src/Anubis/Supervision/GuardDrill.cs @@ -21,7 +21,8 @@ public sealed record DrillResult(bool Passed, IReadOnlyList Lines); /// decided; the engine starts with the fault that blocks its main loop right after the sale leaves, with the stop /// removed. The drill passes when the guard intervened, the engine restarted, the sale left open was canceled, the /// stop came back for the whole quantity and the guard's note reached the diary. Prices come from a small local -/// server that answers like OKX: nothing leaves the computer. Same drill in the tests and in the Docker image. +/// server that answers like OKX, and the engine sends nothing else out (ADR 0016): no news, no model to download, +/// any other source refused before it leaves the computer. Same drill in the tests and in the Docker image. /// public static class GuardDrill { @@ -126,6 +127,12 @@ public static class GuardDrill passed &= Check(stops.Any(q => q == held), $"Lo stop è tornato per tutti i {Format.Quantity(held)} BTC.", "Lo stop non è tornato per l'intera quantità.", Say); passed &= Check(again > 0, "La vendita già decisa è ripartita con un ordine nuovo.", "La vendita già decisa non è ripartita.", Say); passed &= Check(noted > 0, "La nota della guardia è nel diario.", "La nota della guardia non è nel diario.", Say); + + // The engine of the drill stays on this computer (ADR 0016): it reads no news and downloads no model. + var news = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items"), cancellationToken).ConfigureAwait(false); + var model = Directory.Exists(data.Models) && Directory.EnumerateFileSystemEntries(data.Models).Any(); + passed &= Check(news == 0 && !model, "Il motore non ha letto notizie né scaricato il modello: è rimasto sul computer.", + $"Il motore è uscito dal computer: {news} notizie lette{(model ? ", modello scaricato" : "")}.", Say); } return new DrillResult(passed, lines); diff --git a/src/Anubis/Supervision/LoopbackOnlyHandler.cs b/src/Anubis/Supervision/LoopbackOnlyHandler.cs new file mode 100644 index 0000000..a86f493 --- /dev/null +++ b/src/Anubis/Supervision/LoopbackOnlyHandler.cs @@ -0,0 +1,49 @@ +using System.Net; +using System.Text; + +namespace Anubis.Supervision; + +/// +/// The network of the guard drill's engine (ADR 0016): a request to this computer's own addresses (loopback) passes, +/// any other is answered here with 403 and never leaves. The answer is final, not a failure to retry, so a job that +/// would have gone out fails at once and the engine keeps its usual pace. +/// +public sealed class LoopbackOnlyHandler(HttpMessageHandler inner, bool ownsInner) : HttpMessageHandler +{ + public const string Refusal = "Esercitazione della guardia: nessuna richiesta esce dal computer."; + + private readonly HttpMessageInvoker _inner = new(inner, ownsInner); + private int _refused; + + /// How many requests were stopped here. + public int Refused => Volatile.Read(ref _refused); + + public static bool Allowed(Uri? url) => url is { IsAbsoluteUri: true, IsLoopback: true }; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (Allowed(request.RequestUri)) + { + return _inner.SendAsync(request, cancellationToken); + } + + Interlocked.Increment(ref _refused); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden) + { + RequestMessage = request, + ReasonPhrase = "Forbidden in the guard drill", + Content = new StringContent(Refusal, Encoding.UTF8, "text/plain"), + }); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _inner.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/tests/Anubis.Tests/GuardTests.cs b/tests/Anubis.Tests/GuardTests.cs index f7ecb2c..c062659 100644 --- a/tests/Anubis.Tests/GuardTests.cs +++ b/tests/Anubis.Tests/GuardTests.cs @@ -297,6 +297,63 @@ public sealed class GuardTests } } + /// + /// The drill's engine stays on this computer (issue #102, ADR 0016). Its market data, built as the host builds it + /// under a guard with the drill's OKX, has no news job. Every job once, a history round and a news round send + /// nothing outside loopback: the news sources were tried and refused before reaching the network, and no model came. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDrillsEngineReadsNoNewsAndSendsNothingOutsideLoopback() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(new DateTimeOffset(2026, 11, 16, 9, 0, 0, TimeSpan.Zero)); + var folder = TempFolder.Create("drill-data"); + try + { + var data = new Anubis.Platform.DataDirectory(folder); + data.Ensure(); + using var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("""{"code":"0","msg":"","data":[]}""")); + var okx = GuardDrill.DrillOkx(new Dictionary(StringComparer.Ordinal) { [GuardDrill.DrillOkxVariable] = "http://127.0.0.1:9/" }); + Assert.IsNotNull(okx); + var bus = new EventBus(); + using var market = new MarketDataService(test.Db, clock, bus, new SettingsStore(test.Db, clock, bus), new SecretStore(test.Db, clock, new byte[32]), data, + network, () => new FakeSocket(), NullLogger.Instance, okx, offline: true); + + var jobs = market.Jobs(); + Assert.IsFalse(jobs.Any(j => j.Name == Anubis.News.NewsCollector.JobName), "no news job in the drill"); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + foreach (var job in jobs) + { + await job.Run(timeout.Token).ConfigureAwait(false); + } + + await market.HistoryRoundAsync(timeout.Token).ConfigureAwait(false); + + // The news round pauses a second between two feeds, on the manual clock. + var reading = market.News.RunOnceAsync(timeout.Token); + while (!reading.IsCompleted) + { + clock.Advance(TimeSpan.FromSeconds(1)); + await Task.Delay(10, _none).ConfigureAwait(false); + } + + await reading.ConfigureAwait(false); + + var urls = network.Urls.ToList(); + Assert.IsTrue(urls.Count > 0, "the drill's OKX answers"); + Assert.IsTrue(urls.All(LoopbackOnlyHandler.Allowed), string.Join(", ", urls.Select(u => u.Host).Distinct())); + var sources = await market.News.Store.ListSourcesAsync(_none).ConfigureAwait(false); + Assert.IsTrue(sources.Where(s => s.Enabled && s.Kind == Anubis.News.NewsSourceKinds.Rss).All(s => s.Failures > 0), "every feed was stopped here"); + Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items"), _none).ConfigureAwait(false)); + Assert.IsFalse(Directory.EnumerateFileSystemEntries(data.Models).Any(), "no model downloaded"); + } + finally + { + TempFolder.Delete(folder); + } + } + /// /// The same proof with real processes (the drill that also runs in the Docker image): the real guard, the real /// engine as its child, a sale blocked halfway on the internal simulator, then the restart by SPEC 9.4. -- 2.54.1