From 61878c2023c0cae542c78728594be40a0e853995 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 09:24:36 +0100 Subject: [PATCH 1/2] Keep broken model answers and articles from stopping the news (refs #58, refs #61) The independent review of phase 7 found that an answer with half a Unicode character, or of an unexpected shape, escaped the validation as an exception: its cost was lost, it was paid again every two minutes past the daily cap, and the diary of the news stopped. The same happened to the whole round with an article cut in the middle of an emoji. Such answers are now refused like any other, the cost is written before the request leaves and settled with what the service used, never clamped to the estimate, and neither the analyst nor one source can stop the others. The estimate counts every byte as a token, so it is a true worst case. Summaries with bare domains or invisible characters are refused. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/News/Feeds.cs | 37 ++++- src/Anubis/News/LanguageModel.cs | 19 ++- src/Anubis/News/NewsAnalyst.cs | 67 ++++++-- src/Anubis/News/NewsCollector.cs | 21 ++- src/Anubis/News/NewsVerdicts.cs | 42 ++++- tests/Anubis.Tests/NewsAnalystTests.cs | 21 ++- tests/Anubis.Tests/NewsRobustnessTests.cs | 186 ++++++++++++++++++++++ 7 files changed, 353 insertions(+), 40 deletions(-) create mode 100644 tests/Anubis.Tests/NewsRobustnessTests.cs diff --git a/src/Anubis/News/Feeds.cs b/src/Anubis/News/Feeds.cs index f518de4..05eb7f9 100644 --- a/src/Anubis/News/Feeds.cs +++ b/src/Anubis/News/Feeds.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Net; +using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; @@ -119,13 +120,45 @@ public static partial class FeedParser } var text = WebUtility.HtmlDecode(Tags().Replace(WebUtility.HtmlDecode(Tags().Replace(html, " ")), " ")); - text = Spaces().Replace(text, " ").Trim(); + text = Spaces().Replace(Printable(text), " ").Trim(); if (text.Length == 0) { return null; } - return text.Length <= max ? text : text[..(max - 1)].TrimEnd() + "…"; + return Cut(text, max); + } + + /// At most characters, never ending with half an emoji: half a character cannot be stored. + public static string Cut(string text, int max) + { + ArgumentNullException.ThrowIfNull(text); + if (text.Length <= max) + { + return text; + } + + var end = max - 1; + return text[..(char.IsHighSurrogate(text[end - 1]) ? end - 1 : end)].TrimEnd() + "…"; + } + + // Control characters (PostgreSQL refuses the zero) and halves of characters become spaces. + private static string Printable(string text) + { + var clean = new StringBuilder(text.Length); + for (var i = 0; i < text.Length; i++) + { + if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) + { + clean.Append(text[i]).Append(text[++i]); + } + else + { + clean.Append(char.IsSurrogate(text[i]) || char.IsControl(text[i]) ? ' ' : text[i]); + } + } + + return clean.ToString(); } private static string? Language(string? code) => diff --git a/src/Anubis/News/LanguageModel.cs b/src/Anubis/News/LanguageModel.cs index 11ea3bb..f79d980 100644 --- a/src/Anubis/News/LanguageModel.cs +++ b/src/Anubis/News/LanguageModel.cs @@ -49,11 +49,7 @@ public sealed class LanguageModel(HttpClient http, NewsModelConfig config, strin } var body = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false); - return config.Provider == NewsModelProviders.Anthropic ? ReadAnthropic(body) : ReadOpenAi(body); - } - catch (JsonException) - { - return new ModelReply(null, 0, 0, "risposta del servizio illeggibile", Billed: true); + return Read(body); } catch (Exception ex) when (ex is HttpRequestException or IOException or FormatException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) { @@ -62,6 +58,19 @@ public sealed class LanguageModel(HttpClient http, NewsModelConfig config, strin } } + // Whatever the service sent back, of any shape: what does not fit is an answer that cannot be used, never an exception. + private ModelReply Read(string body) + { + try + { + return config.Provider == NewsModelProviders.Anthropic ? ReadAnthropic(body) : ReadOpenAi(body); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException) + { + return new ModelReply(null, 0, 0, "risposta del servizio illeggibile", Billed: true); + } + } + private HttpRequestMessage Anthropic(ModelRequest request) { var body = new JsonObject diff --git a/src/Anubis/News/NewsAnalyst.cs b/src/Anubis/News/NewsAnalyst.cs index 328dcd8..c71352b 100644 --- a/src/Anubis/News/NewsAnalyst.cs +++ b/src/Anubis/News/NewsAnalyst.cs @@ -69,17 +69,20 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore } /// - /// The most a request can cost: every character read counted as half a token (real text takes three or four - /// characters a token) and every token it may write. Asked only while this still fits under the cap, so the cap - /// holds even if the service bills the worst case. + /// The most a request can cost: every byte read counted as a token (a token is one byte or more; real text takes + /// three or four characters), a margin for what the service adds, and every token it may write. Asked only while + /// this still fits under the cap. /// public static decimal Estimate(NewsModelConfig config, ModelRequest request) { ArgumentNullException.ThrowIfNull(request); - var characters = request.Instructions.Length + request.Message.Length + request.Schema.ToJsonString().Length; - return Cost(config, (characters / 2) + 1, request.MaxOutput); + var bytes = Encoding.UTF8.GetByteCount(request.Instructions) + Encoding.UTF8.GetByteCount(request.Message) + Encoding.UTF8.GetByteCount(request.Schema.ToJsonString()); + return Cost(config, bytes + ServiceMargin, request.MaxOutput); } + // Tokens a service may add around the request: the turns, its own words about the schema. + private const int ServiceMargin = 1000; + /// The room for the answer: thinking included, eight verdicts fit with margin. public static int MaxOutput(int items) => 2000 + (400 * items); @@ -137,14 +140,32 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore return new AnalystRound(calls, judged, cached.Count, spentNow, "tetto di spesa raggiunto"); } - var reply = await model.AskAsync(request, cancellationToken).ConfigureAwait(false); + // Counted before it leaves, settled after: a stop of the bot or a fault in between cannot lose the cost. + var call = await ReserveAsync(config, batch.Sum(g => g.Count), estimate, cancellationToken).ConfigureAwait(false); + ModelReply reply; + try + { + reply = await model.AskAsync(request, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogUnforeseen(_logger, ex); + reply = new ModelReply(null, 0, 0, "errore imprevisto", Billed: true); + } + + // What the service says it used, even above the estimate: the cap is compared with the real spending. var known = reply.InputTokens > 0 || reply.OutputTokens > 0; - var cost = !reply.Billed ? 0m : known ? Math.Min(Cost(config, reply.InputTokens, reply.OutputTokens), estimate) : estimate; + var cost = !reply.Billed ? 0m : known ? Cost(config, reply.InputTokens, reply.OutputTokens) : estimate; + if (cost > estimate) + { + LogAbove(_logger, config.Provider, cost, estimate); + } + // Without any answer the stories are asked again later; an answer out of the schema is final, it is not paid twice. var lost = reply.Text is null && !known; var outcomes = reply.Text is null ? [.. items.Select(i => new VerdictOutcome(i.Item, null, reply.Problem ?? "risposta senza testo"))] : NewsVerdicts.Parse(reply.Text, items); - await StoreAsync(config, batch, outcomes, reply, cost, lost, cancellationToken).ConfigureAwait(false); + await StoreAsync(call, batch, outcomes, reply, cost, lost, cancellationToken).ConfigureAwait(false); calls++; spentNow += cost; if (lost) @@ -214,7 +235,7 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore return [.. result.Take(BatchSize * MaxCallsPerRound)]; } - private static string Cut(string text, int length) => text.Length <= length ? text : text[..(length - 1)] + "…"; + private static string Cut(string text, int length) => FeedParser.Cut(text, length); // Stories whose very question was already answered take that verdict at no cost. private Task> FromCacheAsync(IReadOnlyList candidates, CancellationToken cancellationToken) => @@ -235,18 +256,26 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore return hit; }, cancellationToken); - private Task StoreAsync(NewsModelConfig config, IReadOnlyList> batch, IReadOnlyList outcomes, ModelReply reply, decimal cost, bool lost, + private Task ReserveAsync(NewsModelConfig config, int stories, decimal estimate, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var call = Ids.NewId(clock); + await s.ExecuteAsync( + "INSERT INTO news_model_calls (id, provider, model, stories, input_tokens, output_tokens, cost, problem, created_at) " + + "VALUES (@id, @p, @m, @n, 0, 0, @c, 'senza risposta', @now)", + cancellationToken, ("id", call), ("p", config.Provider), ("m", config.Model), ("n", (long)stories), ("c", estimate), ("now", clock.UtcNow)).ConfigureAwait(false); + return call; + }, cancellationToken); + + private Task StoreAsync(Guid call, IReadOnlyList> batch, IReadOnlyList outcomes, ModelReply reply, decimal cost, bool lost, CancellationToken cancellationToken) => db.WriteAsync(async s => { var now = clock.UtcNow; - var call = Ids.NewId(clock); var problems = outcomes.Where(o => o.Problem is not null).Select(o => o.Problem).Distinct().ToList(); - await s.ExecuteAsync( - "INSERT INTO news_model_calls (id, provider, model, stories, input_tokens, output_tokens, cost, problem, created_at) " + - "VALUES (@id, @p, @m, @n, @in, @out, @c, @pr, @now)", - cancellationToken, ("id", call), ("p", config.Provider), ("m", config.Model), ("n", (long)batch.Sum(g => g.Count)), ("in", reply.InputTokens), - ("out", reply.OutputTokens), ("c", cost), ("pr", problems.Count == 0 ? null : string.Join("; ", problems)), ("now", now)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE news_model_calls SET input_tokens = @in, output_tokens = @out, cost = @c, problem = @pr WHERE id = @id", cancellationToken, + ("id", call), ("in", reply.InputTokens), ("out", reply.OutputTokens), ("c", cost), + ("pr", problems.Count == 0 ? null : string.Join("; ", problems))).ConfigureAwait(false); if (lost) { return 0; @@ -305,6 +334,12 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore [LoggerMessage(Level = LogLevel.Warning, Message = "Language model ({Provider}) gave no answer, next try in 15 minutes: {Problem}")] private static partial void LogFailed(ILogger logger, string provider, string problem); + [LoggerMessage(Level = LogLevel.Error, Message = "Language model: the request failed in an unforeseen way")] + private static partial void LogUnforeseen(ILogger logger, Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Language model ({Provider}) used more than the request allowed: {Cost} against an estimate of {Estimate}")] + private static partial void LogAbove(ILogger logger, string provider, decimal cost, decimal estimate); + [LoggerMessage(Level = LogLevel.Warning, Message = "Language model: {Rejected} of {Total} verdicts thrown away: {Problems}")] private static partial void LogRejected(ILogger logger, int rejected, int total, string problems); } diff --git a/src/Anubis/News/NewsCollector.cs b/src/Anubis/News/NewsCollector.cs index 024abd2..b6f08cf 100644 --- a/src/Anubis/News/NewsCollector.cs +++ b/src/Anubis/News/NewsCollector.cs @@ -5,7 +5,6 @@ using Anubis.Data; using Anubis.Db; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.ML.OnnxRuntime; namespace Anubis.News; @@ -85,9 +84,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c catch (OperationCanceledException) when (stopping.IsCancellationRequested) { } - catch (Exception e) when (e is HttpRequestException or IOException or InvalidDataException or OperationCanceledException or OnnxRuntimeException - or UnauthorizedAccessException) + catch (Exception e) when (!stopping.IsCancellationRequested) { + // Of any kind, a native library that does not load included: without the model the keywords work alone. LogModelFailed(_logger, e.Message); } }, CancellationToken.None); @@ -121,7 +120,15 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c // The second judgement first (10.2 point 5), so the rules read it in the same round. if (Analyst is not null) { - await Analyst.RunOnceAsync(cancellationToken).ConfigureAwait(false); + try + { + await Analyst.RunOnceAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // The analyst is optional (10.3): whatever happens to it, the diary of the news is written. + LogAnalystFailed(_logger, ex); + } } if (Watcher is not null) @@ -193,8 +200,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c return result; } - catch (Exception ex) when (ex is HttpRequestException or FormatException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { + // Of any kind: a source that cannot be read is tried again later and never stops the others. LogFailed(_logger, source.Name, ex.Message); await _store.RecordCheckAsync(source, ok: false, null, null, ex is OperationCanceledException ? "Nessuna risposta in 30 secondi." : ex.Message, cancellationToken) .ConfigureAwait(false); @@ -238,6 +246,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c [LoggerMessage(Level = LogLevel.Information, Message = "News from {Source}: {Added} new articles in {Stories} stories")] private static partial void LogRead(ILogger logger, string source, int added, int stories); + [LoggerMessage(Level = LogLevel.Error, Message = "The news analyst failed, the rules go on without it")] + private static partial void LogAnalystFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Warning, Message = "News source {Source} failed: {Error}")] private static partial void LogFailed(ILogger logger, string source, string error); diff --git a/src/Anubis/News/NewsVerdicts.cs b/src/Anubis/News/NewsVerdicts.cs index 81586dd..6653026 100644 --- a/src/Anubis/News/NewsVerdicts.cs +++ b/src/Anubis/News/NewsVerdicts.cs @@ -1,5 +1,7 @@ +using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.RegularExpressions; namespace Anubis.News; @@ -24,7 +26,7 @@ public sealed record VerdictOutcome(int Item, NewsVerdict? Verdict, string? Prob /// inside a tag, so it cannot close the tag or pass for instructions, and nothing in the answer can act except the /// fields of the schema, each checked here. Whatever does not fit is thrown away. /// -public static class NewsVerdicts +public static partial class NewsVerdicts { /// Changes with the instructions or the schema: answers cached under an older version are asked again. public const int Version = 1; @@ -142,13 +144,26 @@ public static class NewsVerdicts return All("risposta non in JSON"); } + try + { + return ReadAll(document, items, All); + } + catch (InvalidOperationException) + { + // Valid JSON, but a name that is not valid Unicode: reading it throws. + return All("testo non valido"); + } + } + + private static List ReadAll(JsonDocument document, IReadOnlyList items, Func> all) + { using (document) { var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Count() != 1 || !root.TryGetProperty("verdicts", out var verdicts) || verdicts.ValueKind != JsonValueKind.Array) { - return All("risposta fuori dallo schema"); + return all("risposta fuori dallo schema"); } var byItem = items.ToDictionary(i => i.Item); @@ -158,16 +173,23 @@ public static class NewsVerdicts if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty("item", out var number) || number.ValueKind != JsonValueKind.Number || !number.TryGetInt32(out var item) || !byItem.TryGetValue(item, out var source)) { - return All("giudizio senza un numero valido"); + return all("giudizio senza un numero valido"); } if (found.ContainsKey(item)) { - return All("due giudizi per la stessa notizia"); + return all("due giudizi per la stessa notizia"); } - var (verdict, problem) = Read(element, source); - found[item] = new VerdictOutcome(item, verdict, problem); + try + { + var (verdict, problem) = Read(element, source); + found[item] = new VerdictOutcome(item, verdict, problem); + } + catch (InvalidOperationException) + { + found[item] = new VerdictOutcome(item, null, "testo non valido"); + } } return [.. items.Select(i => found.TryGetValue(i.Item, out var outcome) ? outcome : new VerdictOutcome(i.Item, null, "nessun giudizio"))]; @@ -236,11 +258,17 @@ public static class NewsVerdicts { var text = value?.Trim(); if (string.IsNullOrEmpty(text) || text.Length > MaxSummary || text.Any(c => char.IsControl(c) || c is '<' or '>' or '[' or ']' or '{' or '}' or '*' or '`' or '#' or '|' or - '\\' or '_' or '~' or '@') || text.Contains("://", StringComparison.Ordinal) || text.Contains("www.", StringComparison.OrdinalIgnoreCase)) + '\\' or '_' or '~' or '@') || text.Contains("://", StringComparison.Ordinal) || text.Contains("www.", StringComparison.OrdinalIgnoreCase) || + Address().IsMatch(text) || text.Any(c => char.GetUnicodeCategory(c) is UnicodeCategory.Format or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator or + UnicodeCategory.PrivateUse)) { return null; } return text; } + + // "coinbase-support.com", "t.me/x"; not "3.5%", not "milioni.La" (a missing space after a full stop). + [GeneratedRegex(@"[\p{L}\p{N}-]{2,}\.(?:[a-z]{2,}|[A-Z]{3,})(?!\p{L})|\.[A-Za-z]{2,}/")] + private static partial Regex Address(); } diff --git a/tests/Anubis.Tests/NewsAnalystTests.cs b/tests/Anubis.Tests/NewsAnalystTests.cs index e97681d..5cd46eb 100644 --- a/tests/Anubis.Tests/NewsAnalystTests.cs +++ b/tests/Anubis.Tests/NewsAnalystTests.cs @@ -13,7 +13,7 @@ namespace Anubis.Tests; /// news as untrusted data, a restriction that can only be added, the daily cap, the cache and the batches. /// [TestClass] -public sealed class NewsAnalystTests +public sealed partial class NewsAnalystTests { private static readonly CancellationToken _none = CancellationToken.None; @@ -190,22 +190,23 @@ public sealed class NewsAnalystTests await using var test = await DatabaseTests.MigratedAsync(); var (clock, settings, specs) = await SetUpAsync(test.Db); // Prices that make one request of eight cost about 0.30 € in the worst case: the second would pass 0.50. - await settings.SetAsync(NewsModelSettings.PriceIn.Key, "10", "test", _none); + await settings.SetAsync(NewsModelSettings.PriceIn.Key, "5", "test", _none); await settings.SetAsync(NewsModelSettings.PriceOut.Key, "50", "test", _none); for (var i = 0; i < 20; i++) { await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], $"Solana story number {i}", Now.AddMinutes(-5 - i), 2, 0.1, "CoinDesk", trusted: true); } - // A service that bills far more than it should: the analyst never counts more than the estimate it checked. - var model = new FakeModel(r => new ModelReply(Answer(r, item => Verdict(item, ["SOL"], "neutral", 2)), 50_000_000, 50_000_000, null, true)); + // A service that bills the worst case it was allowed: every byte a token and the whole room for the answer. + var model = new FakeModel(r => new ModelReply(Answer(r, item => Verdict(item, ["SOL"], "neutral", 2)), + System.Text.Encoding.UTF8.GetByteCount(r.Instructions + r.Message + r.Schema.ToJsonString()), r.MaxOutput, null, true)); var analyst = Analyst(test.Db, clock, settings, TestKey, model); var first = await analyst.RunOnceAsync(_none); Assert.AreEqual(1, first.Calls); Assert.AreEqual("tetto di spesa raggiunto", first.Skipped); var estimate = NewsAnalyst.Estimate(await NewsModelSettings.LoadAsync(settings, _none), model.Requests[0]); - Assert.AreEqual(estimate, first.Spent); + Assert.IsTrue(first.Spent <= estimate && first.Spent > estimate * 0.9m, "The estimate is a true worst case."); Assert.IsTrue(estimate is > 0.25m and < 0.50m, estimate.ToString(CultureInfo.InvariantCulture)); var second = await analyst.RunOnceAsync(_none); @@ -230,6 +231,16 @@ public sealed class NewsAnalystTests Assert.IsTrue(next.Calls >= 1, "Asked again, as far as the new day allows."); Assert.IsTrue((await analyst.SpendingAsync(_none)).Spent <= 0.50m); + // A service that ignores its own limits: what it billed is shown whole, and nothing more is asked that day. + clock.Advance(TimeSpan.FromDays(1)); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana story with a greedy service", clock.UtcNow, 2, 0.1, "CoinDesk", trusted: true); + var greedy = new FakeModel(r => new ModelReply(Answer(r, item => Verdict(item, ["SOL"], "neutral", 2)), 10, 20_000, null, true)); + var eager = Analyst(test.Db, clock, settings, TestKey, greedy); + await eager.RunOnceAsync(_none); + Assert.AreEqual(1.00005m, (await eager.SpendingAsync(_none)).Spent, "Never shown as less than it was."); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana story after the greedy service", clock.UtcNow, 2, 0.1, "CoinDesk", trusted: true); + Assert.AreEqual(0, (await eager.RunOnceAsync(_none)).Calls); + // A free model: the cap of zero stops every request that may cost something. await settings.SetAsync(NewsModelSettings.DailyCap.Key, "0", "test", _none); clock.Advance(TimeSpan.FromMinutes(1)); diff --git a/tests/Anubis.Tests/NewsRobustnessTests.cs b/tests/Anubis.Tests/NewsRobustnessTests.cs new file mode 100644 index 0000000..dd1e3ef --- /dev/null +++ b/tests/Anubis.Tests/NewsRobustnessTests.cs @@ -0,0 +1,186 @@ +using System.Text.Json.Nodes; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; + +namespace Anubis.Tests; + +/// +/// Broken input never stops the news (issue #61, the independent review): answers of the model that are not valid +/// Unicode or have another shape, requests that fail in unforeseen ways, articles that cannot be stored. +/// +public sealed partial class NewsAnalystTests +{ + // Six characters of JSON: an escape that stands for half a character (a lone surrogate). + private const string Lone = "\\" + "ud83d"; + + /// + /// Valid JSON that is not valid Unicode, which a hostile title can ask for, is refused like any other value outside + /// the schema, wherever it stands. + /// + [TestMethod] + [TestCategory(Category.Unit)] + public void BrokenUnicodeInAnAnswerIsRefusedNotThrown() + { + AnalystItem[] items = [new(1, "Solana upgrade delayed", [], ["SOL"]), new(2, "Ether ETF approved", [], ["ETH"])]; + static JsonObject V(int item) => Verdict(new JsonObject { ["item"] = item }, ["SOL"], "negative", 3); + var first = V(1).ToJsonString(); + var second = V(2).ToJsonString(); + static string Answer(string one, string two) => "{\"verdicts\":[" + one + "," + two + "]}"; + Assert.IsTrue(NewsVerdicts.Parse(Answer(first, second), items).All(o => o.Verdict is not null)); + + foreach (var field in new[] { "summary_it", "scope", "event_type", "direction" }) + { + var start = $"\"{field}\":\""; + StringAssert.Contains(first, start); + var outcomes = NewsVerdicts.Parse(Answer(first.Replace(start, start + Lone, StringComparison.Ordinal), second), items); + Assert.IsTrue(outcomes[0].Verdict is null && outcomes[0].Problem is not null, field); + Assert.IsNotNull(outcomes[1].Verdict, "The other verdict stands: " + field); + } + + foreach (var (what, broken) in new[] + { + ("instrument", first.Replace("[\"SOL\"]", $"[\"{Lone}\"]", StringComparison.Ordinal)), + ("field name", first.Replace("\"scope\"", $"\"{Lone}\"", StringComparison.Ordinal)), + }) + { + Assert.AreNotEqual(first, broken, what); + var outcomes = NewsVerdicts.Parse(Answer(broken, second), items); + Assert.IsTrue(outcomes[0].Verdict is null && outcomes[0].Problem is not null, what); + } + + var root = NewsVerdicts.Parse(Answer(first, second).Replace("\"verdicts\"", $"\"{Lone}\"", StringComparison.Ordinal), items); + Assert.IsTrue(root.All(o => o.Verdict is null && o.Problem is not null), "root name"); + } + + /// The summary carries no address in any form, and no character that changes the direction of the text. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheSummaryHasNoAddressAndNoInvisibleCharacter() + { + foreach (var bad in new[] { "Verifica su coinbase-support.com", "Vai su t.me/aiuto", "Scrivi a evil.example/x", "Testo‮alla rovescia", "Testo​nascosto" }) + { + Assert.IsNull(NewsVerdicts.CleanSummary(bad), bad); + } + + foreach (var good in new[] { "Solana rinvia l'aggiornamento di una settimana.", "Il titolo scende del 3.5% dopo i conti.", "Utile a 1.200 milioni.La guida resta." }) + { + Assert.IsNotNull(NewsVerdicts.CleanSummary(good), good); + } + } + + /// A service answer of any shape cannot be used: it is billed, with a problem, never an exception. + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AServiceAnswerOfAnyShapeNeverThrows() + { + string[] bodies = + [ + "[]", "\"x\"", "1", "null", "{}", "{\"content\":[\"x\"]}", "{\"content\":[{\"type\":1,\"text\":\"x\"}]}", "{\"content\":[{\"type\":\"text\",\"text\":5}]}", + "{\"content\":[{\"type\":\"text\",\"text\":\"" + Lone + "\"}]}", "{\"stop_reason\":\"" + Lone + "\"}", "{\"choices\":[\"x\"]}", "{\"choices\":[null]}", + "{\"choices\":[{\"finish_reason\":\"" + Lone + "\"}]}", "{\"choices\":[{\"message\":{\"content\":\"" + Lone + "\"}}]}", "{\"choices\":[{\"message\":[]}]}", + ]; + foreach (var provider in new[] { NewsModelProviders.Anthropic, NewsModelProviders.OpenAi }) + { + var config = new NewsModelConfig(provider, "m", NewsModelProviders.DefaultAddress(provider), 1m, 1m, 1m); + foreach (var body in bodies) + { + var answer = await new LanguageModel(new FakeHttp().On(_ => true, _ => FakeHttp.Respond(body)).Client(), config, "k").AskAsync(Request(), _none); + Assert.IsTrue(answer.Billed && answer.Text is null && answer.Problem is not null, provider + " " + body); + } + } + } + + /// + /// A billed answer that cannot be read is counted and never paid twice, a model that fails in an unforeseen way + /// pauses, and in both cases the diary of the news is written in the same round (10.5). + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ABrokenAnswerIsPaidOnceAndNeverStopsTheDiary() + { + await using var test = await DatabaseTests.MigratedAsync(); + var (clock, settings, specs) = await SetUpAsync(test.Db); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true); + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_sources SET enabled = @off", _none, ("off", false)), _none); + using var http = new FakeHttp(); + var model = new FakeModel(r => Reply(Answer(r, i => Verdict(i, ["SOL"], "negative", 4)).Replace("\"summary_it\":\"", "\"summary_it\":\"" + Lone, StringComparison.Ordinal))); + using (var collector = Collector(http, test.Db, clock, settings, model)) + { + await collector.RunOnceAsync(_none); + clock.Advance(TimeSpan.FromMinutes(2)); + await collector.RunOnceAsync(_none); + } + + Assert.AreEqual(1, model.Requests.Count, "Paid once."); + Assert.AreEqual(1, await CountAsync(test.Db, "news_model_calls")); + Assert.AreEqual(1, await CountAsync(test.Db, "journal"), "The restriction is in the diary."); + + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana validator fraud case opened", clock.UtcNow.AddMinutes(-5), 4, -0.9, "CoinDesk", trusted: true); + var failing = new FakeModel(_ => throw new InvalidOperationException("prova")); + using (var collector = Collector(http, test.Db, clock, settings, failing)) + { + await collector.RunOnceAsync(_none); + await collector.RunOnceAsync(_none); + } + + Assert.AreEqual(1, failing.Requests.Count, "Not asked again at once: the pause after a failure."); + Assert.AreEqual(2, await CountAsync(test.Db, "news_model_calls"), "What may have been billed is counted."); + Assert.AreEqual(2, await CountAsync(test.Db, "journal")); + } + + /// A stop of the bot while the model answers keeps the cost: the estimate is written before the request leaves. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStopDuringARequestKeepsItsCost() + { + await using var test = await DatabaseTests.MigratedAsync(); + var (clock, settings, specs) = await SetUpAsync(test.Db); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana story", Now.AddHours(-1), 2, 0.1, "CoinDesk", trusted: true); + using var stop = new CancellationTokenSource(); + var model = new FakeModel(_ => + { + stop.Cancel(); + throw new OperationCanceledException(stop.Token); + }); + var analyst = Analyst(test.Db, clock, settings, TestKey, model); + await Assert.ThrowsExactlyAsync(() => analyst.RunOnceAsync(stop.Token)); + var spending = await analyst.SpendingAsync(_none); + Assert.IsTrue(spending.Spent > 0m); + Assert.AreEqual(0, spending.Judged); + } + + /// An article cut in the middle of an emoji or with a zero character is stored, and one bad source never stops the others. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ABadArticleNeverStopsTheRound() + { + var emoji = string.Concat(Enumerable.Repeat("\U0001F600", 400)); + foreach (var offset in new[] { "", "a" }) + { + var cut = FeedParser.Text(offset + emoji, 300)!; + Assert.IsTrue(cut.Length <= 300); + Assert.AreEqual(cut, cut.Normalize(), "Whole characters only."); + } + + Assert.AreEqual("a b", FeedParser.Text("a�b", 100)); + + await using var test = await DatabaseTests.MigratedAsync(); + var (clock, settings, specs) = await SetUpAsync(test.Db); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true); + var feed = "x" + emoji + "https://example.test/emojia&#0;" + emoji + + ""; + using var http = new FakeHttp().On(_ => true, r => r.RequestUri!.Host.Contains("coindesk", StringComparison.Ordinal) ? throw new InvalidOperationException("prova") : FakeHttp.Respond(feed)); + using var collector = new NewsCollector(http.Client(), test.Db, clock) { Pause = TimeSpan.Zero, Watcher = new NewsWatcher(test.Db, clock, settings) }; + await collector.RunOnceAsync(_none); + + var sources = await collector.Store.ListSourcesAsync(_none); + Assert.IsTrue(sources.Where(s => s.Enabled && s.Kind == NewsSourceKinds.Rss).All(s => s.LastCheckedAt is not null), "Every source was tried."); + Assert.IsTrue(sources.Any(s => s.Failures > 0) && sources.Any(s => s.LastOkAt is not null)); + Assert.AreEqual(2, await CountAsync(test.Db, "news_items")); + Assert.AreEqual(1, await CountAsync(test.Db, "journal"), "The diary line is written anyway."); + } + + private static NewsCollector Collector(FakeHttp http, Database db, Core.IClock clock, Core.SettingsStore settings, FakeModel model) => + new(http.Client(), db, clock) { Pause = TimeSpan.Zero, Analyst = Analyst(db, clock, settings, TestKey, model), Watcher = new NewsWatcher(db, clock, settings) }; +} From a3ff8ea6b71df17e51eca97be5b63cd01ce769ee Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 09:49:14 +0100 Subject: [PATCH 2/2] Fix what the independent review of Phase 7 found and close the phase (refs #61) Linking missed Italian elisions, "The" names and common aliases; keywords missed words after an apostrophe; stories about two companies merged and confirmed each other; a story that became serious late was measured from its first article. The news round delayed the engine and the risk check, and the classifier ran inside the database writer. The earnings row started and ended on the wrong sessions, the one-step comparison ignored it, and a purchase was said to be put off when it was not, or sent at the open. ADR 0017 records the choices; what depends on the user is in #107 and #55. Co-Authored-By: Claude Opus 5.5 --- docs/API-NOTES.md | 1 + docs/ROADMAP.md | 30 +-- docs/STATE.md | 13 +- docs/adr/0014-scelte-fase-7.md | 2 +- docs/adr/0017-revisione-fase-7.md | 54 +++++ src/Anubis/Core/Scheduling.cs | 76 +++++-- src/Anubis/Data/FreeSources.cs | 3 + src/Anubis/Data/MarketDataService.cs | 2 +- src/Anubis/News/Judgement.cs | 5 +- src/Anubis/News/Linker.cs | 138 ++++++++++--- src/Anubis/News/NewsBoard.cs | 19 +- src/Anubis/News/NewsCollector.cs | 2 +- src/Anubis/News/NewsDesk.cs | 56 ++++- src/Anubis/News/NewsRules.cs | 17 +- src/Anubis/News/NewsStore.cs | 88 ++++++-- src/Anubis/Trading/DiaryText.cs | 8 +- src/Anubis/Trading/LiveEngine.cs | 70 +++++-- tests/Anubis.Tests/CoreTests.cs | 45 ++++ tests/Anubis.Tests/LiveStockSupport.cs | 7 + tests/Anubis.Tests/NewsReviewTests.cs | 273 +++++++++++++++++++++++++ tests/Anubis.Tests/NewsRulesTests.cs | 75 +++++++ tests/Anubis.Tests/NewsTests.cs | 1 + 22 files changed, 862 insertions(+), 123 deletions(-) create mode 100644 docs/adr/0017-revisione-fase-7.md create mode 100644 tests/Anubis.Tests/NewsReviewTests.cs diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index 371a46f..904d414 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -131,6 +131,7 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio | M3 | 10–20 ms per titolo su CPU | misurato | Il 15/11/2026, con ONNX Runtime 1.31.1 per .NET e il modello quantizzato su un solo thread: 23–24 ms per titolo sul PC di sviluppo (test `TheModelReadsTheToneOfFinancialHeadlines`). Con più thread scende, ma Anubis ne usa uno (ADR 0014, punto 8). | — | | M4 | Claude Haiku 5.5: 0,10 $ in ingresso e 0,50 $ in uscita per milione di token (fino a 100.000 token); batch a metà prezzo; non ancora nella panoramica dei modelli | cambiato | Ora **è** nella panoramica, con identificativo `claude-haiku-5-5`. Prezzi confermati. Oltre i 100.000 token costa 0,50 $ e 2,50 $. | https://platform.claude.com/docs/en/about-claude/models/overview · https://platform.claude.com/docs/en/about-claude/pricing | | M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing | +| M6 | API Messages di Anthropic: intestazioni `x-api-key` e `anthropic-version` | confermato | Anubis manda `anthropic-version: 2026-10-21`, la più recente alla verifica del 01/12/2026. Questa versione rifiuta `temperature`, `top_p` e `top_k`: Anubis non li manda ad Anthropic. Non è stata provata con una chiave vera: i test usano risposte d'esempio. | https://platform.claude.com/docs/en/api/versioning | L'identificativo del modello resta una voce di configurazione, mai una costante nel codice (SPEC 4.5). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2612dbd..c1b19d9 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -212,24 +212,24 @@ Le notizie usate per evitare guai, mai per comprare. **Lavori** -- [ ] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013) -- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013) -- [ ] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti -- [ ] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave -- [ ] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa -- [ ] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza -- [ ] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario -- [ ] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7` +- [x] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013) +- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013) — **in attesa dell'utente** +- [x] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti +- [x] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave +- [x] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa +- [x] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza +- [x] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario +- [x] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7` **Criteri di accettazione** -- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013) -- [ ] Su un archivio di notizie registrate la deduplica e il collegamento superano i test -- [ ] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (test dedicato) -- [ ] Senza chiave del modello linguistico tutto funziona -- [ ] Il tetto di spesa viene rispettato -- [ ] Ogni restrizione generata da una notizia compare nel diario con il suo motivo -- [ ] La schermata Notizie e mercato corrisponde al mockup +- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013) — **in attesa dell'utente** (#55) +- [x] Su un archivio di notizie registrate la deduplica e il collegamento superano i test (`TheRecordedArchiveIsGroupedAndLinkedOnBothEngines`, `NamesAreFoundInTheWaysNewspapersWriteThem`, `StoriesAboutDifferentInstrumentsAreNotOne`) +- [x] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (`MaliciousInstructionsInTheNewsHaveNoEffectOutsideTheSchema`, `BrokenUnicodeInAnAnswerIsRefusedNotThrown`, `AServiceAnswerOfAnyShapeNeverThrows`, `TheSummaryHasNoAddressAndNoInvisibleCharacter`) +- [x] Senza chiave del modello linguistico tutto funziona (`WithoutAKeyNothingIsAskedAndEverythingWorks`) +- [x] Il tetto di spesa viene rispettato (`TheDailyCapIsNeverExceeded`, `ABrokenAnswerIsPaidOnceAndNeverStopsTheDiary`, `AStopDuringARequestKeepsItsCost`) +- [x] Ogni restrizione generata da una notizia compare nel diario con il suo motivo (`TheDiarySaysEachRestrictionOnceAndChecksARumourTwoHoursLater`, `ARestrictionLeavesOutThePurchaseAndTheDiarySaysWhy`) +- [x] La schermata Notizie e mercato corrisponde al mockup (`TheDemoShowsTheNewsAndTheMarketAsInTheMockup` e confronto a 1440 e 390 px con il mockup 05) ## Fase 8 — Apprendimento diff --git a/docs/STATE.md b/docs/STATE.md index 141f9a5..9498f5e 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -1,10 +1,10 @@ # Stato del progetto -Aggiornato: 2026-11-28 +Aggiornato: 2026-12-01 ## Fase corrente -**Fase 7 — Notizie: in corso.** La Fase 6 è completata. La sua prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. +**Fase 7 — Notizie: completata**, tranne un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prossima è la Fase 8 — Apprendimento. La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. ## Fatto @@ -85,7 +85,7 @@ Aggiornato: 2026-11-28 - Telegram: coda con stato, nuovi tentativi e abbandono dopo un giorno; comandi dal telefono solo dalla chat configurata e solo se recenti, `/ferma` con `/conferma`; riepilogo del mattino, stato facoltativo, segnale di vita ogni minuto. Sezione in Impostazioni. - Schermate Panoramica e Diario e sistema come i mockup 01, 08 e 09. - `anubis soak`: il rapporto di una prova di durata, letto dai registri del bot mentre lavora. -- **Fase 7, in corso** (ADR 0013): +- **Fase 7** (ADR 0013, 0014, 0015, 0016 e 0017): - Raccolta dei dati per l'analisi (#95). Ogni 5 minuti, e a ogni avvio, il bot scrive una fotografia del processo in `diagnostic_samples`: memoria, GC, thread, handle, CPU, eccezioni, dimensione del database, avvisi ed errori dei registri, chiamate HTTP in uscita per destinazione con le durate. Ogni esecuzione di ogni lavoro va in `job_runs`. Si tiene tutto per 30 giorni. - Il rapporto da incollare, in Markdown fino a 60 KB e senza segreti, si ottiene in tre modi: dal pulsante «Scarica i dati per l'analisi» in Diario e sistema, da `/api/diagnostica.md` e da `anubis diagnostics`. - Release di prova per Windows con `tasks release-win`: uno zip con il server, `Avvia Anubis.cmd`, `Prepara i dati da incollare.cmd` e un `LEGGIMI.txt`. @@ -111,6 +111,8 @@ Aggiornato: 2026-11-28 - il testo delle notizie viaggia come dato; della risposta vale solo lo schema dell'appendice B, e un giudizio può solo aggiungere una restrizione; - tetto di spesa giornaliero controllato sul costo peggiore prima di ogni richiesta, cache per hash, otto storie per richiesta; - senza chiave non parte nessuna richiesta e tutto funziona come prima. + - Esercitazione della guardia: aspetta che la vendita sia partita (#100) e il motore della prova non esce mai dal computer (#102, ADR 0016). + - Correzioni della revisione indipendente (#61, ADR 0017): risposte malformate del modello e tetto di spesa, giro delle notizie accanto alla coda dei lavori, nomi e parole chiave, storie di società diverse, inizio delle finestre, trimestrali, acquisti rimandati, confronto a un passo. ## In corso @@ -119,7 +121,7 @@ Nulla. ## Prossimo passo 1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55. -2. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56), primo giudizio con il classificatore (#57), analista facoltativo (#58), regole di 10.5 (#59) e schermata Notizie (#60) sono fatti. Resta la chiusura della fase (#61), dopo il controllo della prova (#55). +2. La Fase 8 — Apprendimento, in una nuova sessione, sul branch `fase-8` da `main`. 3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. ## Da sapere @@ -149,12 +151,13 @@ Nulla. | Cosa | Da quando serve | Senza | |---|---|---| | Far girare la release `v0.7.0` e incollare il rapporto in chat | Ora, per il tempo che vuoi | La prova di durata (#55) resta aperta | -| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa | +| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria e Alpaca News (#107) spente; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa | | Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | | Token del bot Telegram e chat autorizzata (facoltativi), da Impostazioni → Telegram | Fase 6 | Nessun avviso sul telefono; comandi provati con un finto server | | Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme | | Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | +| Se mandare alla SEC un nome e un contatto, e quali (facoltativo, #107) | Fase 7 | Niente comunicati EDGAR dei singoli titoli; resta il feed generale della SEC | | Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale | | Prova del template su Unraid | Fase 9 | Criterio in attesa | | Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa | diff --git a/docs/adr/0014-scelte-fase-7.md b/docs/adr/0014-scelte-fase-7.md index 6199c35..fabbc58 100644 --- a/docs/adr/0014-scelte-fase-7.md +++ b/docs/adr/0014-scelte-fase-7.md @@ -1,6 +1,6 @@ # 0014 — Scelte della Fase 7: raccolta e collegamento delle notizie -Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5, 10.2, 10.5 e 5.6 per le issue #56–#60. Usa solo i componenti già ammessi dall'ADR 0004 +Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5, 10.2, 10.5 e 5.6 per le issue #56–#60. Usa solo i componenti già ammessi dall'ADR 0004 · Punti 3, 4, 7, 9, 10, 13 e 15 precisati dall'ADR 0017 ## Contesto diff --git a/docs/adr/0017-revisione-fase-7.md b/docs/adr/0017-revisione-fase-7.md new file mode 100644 index 0000000..85a639b --- /dev/null +++ b/docs/adr/0017-revisione-fase-7.md @@ -0,0 +1,54 @@ +# 0017 — Correzioni della revisione indipendente della Fase 7 + +Data: 2026-12-01 · Stato: accettata · Precisa l'ADR 0014 (punti 3, 4, 7, 9, 10, 13 e 15) e SPEC 4.4, 5.5, 8.3, 10.2, 10.3, 10.5 e 12.3 + +## Contesto + +La revisione con un subagent a contesto pulito (issue #61) ha letto tutto il codice della Fase 7 dopo l'unione di #58 in `main`. Ha trovato difetti veri, alcuni dei quali smentivano le prove date per #58. Ogni difetto è stato riprodotto con un test che falliva, oppure verificato leggendo il codice, e poi corretto. + +## Decisione + +**1. L'analista con il modello linguistico (ADR 0014, punto 15).** +- Una risposta che è JSON valido ma non testo valido (mezzo carattere Unicode, una forma inattesa) si scarta come ogni valore fuori dallo schema. Prima generava un'eccezione: la richiesta si ripagava a ogni giro fuori dal tetto e il diario delle notizie si fermava. +- Il costo stimato si scrive **prima** della richiesta e si sostituisce con quello vero alla risposta. Uno spegnimento a metà conta la stima. +- La stima conta un token per ogni byte mandato, più 1.000 token di margine del servizio. Il costo vero si registra sempre intero, anche se supera la stima: prima veniva tagliato alla stima e la spesa poteva superare il tetto senza che si vedesse. +- Qualunque guasto dell'analista o di una fonte resta suo: le altre fonti si leggono e il diario si scrive. +- Il riassunto rifiuta anche gli indirizzi senza `http` e i caratteri invisibili o che invertono il testo. + +**2. Il giro delle notizie non rallenta il motore.** +- Il lavoro "notizie" gira accanto alla coda dei lavori e mai due volte insieme. Prima una fonte lenta o il modello ritardavano il battito del motore e il controllo del rischio di diversi minuti. Alla chiusura del bot si aspetta che finisca. +- Il classificatore legge gli articoli prima di prendere la scrittura del database, che è una sola per tutto il bot. + +**3. Parole e nomi.** +- L'apostrofo separa le parole chiave come ogni altro segno: "un'indagine" e 'fraud' tra apici si trovano. +- Un nome si trova anche dopo un articolo con l'apostrofo ("dell'Apple"), con il possessivo inglese e nella prima parte di una parola composta ("Apple-led"). Un nome che contiene il possessivo resta intero: "Wendy's" non è "Wendy". +- "The" non fa parte del nome, davanti o tra parentesi. Se dopo "The" resta una parola sola (The Metals Company) il nome non collega da solo: serve il ticker o l'elenco degli alias. +- Gli alias sono un elenco breve nel codice dei modi comuni di chiamare le grandi società (Google, Facebook, JPMorgan, Coca-Cola, Boeing…). Valgono solo se il ticker è nel catalogo. +- Due classi di azioni con lo stesso nome (Alphabet) si collegano tutte e due. + +**4. Storie.** +- Un articolo entra in una storia solo se parla di almeno uno degli stessi strumenti, o se uno dei due non ne nomina nessuno. Prima "Apple batte le stime" e "Microsoft batte le stime" erano la stessa storia, e una confermava l'altra. +- Le finestre di 10.5 si contano dal primo articolo con l'importanza della storia, non dal primo in assoluto: una storia diventata grave dopo 40 ore vale 72 ore da allora. Quello che solo il modello alza conta dall'inizio, perché il modello legge la storia com'era al primo arrivo. Il tono resta contato dall'inizio. +- Il caso grave mostrato segue l'ordine di 10.2 e non l'alfabeto. +- Cambiare l'etichetta "affidabile" di una fonte vale anche per le storie già lette. + +**5. Trimestrali.** +- Conti usciti prima dell'apertura o durante la seduta liberano l'ingresso della seduta dopo; quelli dopo la chiusura, o senza orario, lo fermano (10.5). Prima fermavano tutti. +- La riga del diario si scrive quando la restrizione comincia davvero: seduta d'ingresso più tre, cioè quattro giorni lavorativi. Una festività in mezzo può ritardare la riga di un giorno, ma non la regola, che conta le sedute di borsa. Senza un calendario fresco di Finnhub la riga non si scrive, come la regola non agisce. +- Una notizia su un titolo tenuto o candidato con i conti in arrivo si **mostra** con importanza 3 e "evento in arrivo" (10.2, punto 4). L'importanza salvata non cambia: una notizia con il tono non letto diventerebbe altrimenti "negativa" solo per il calendario. + +**6. Acquisti fermati e confronto a un passo.** +- Una restrizione che finisce prima dell'ora dell'acquisto non cambia niente e il diario tace. Quando il giorno è un altro, il diario lo dice. +- Un acquisto di azioni rimandato a mercato chiuso va cinque minuti dopo l'apertura, come tutti (5.5), non all'apertura. +- Il confronto a un passo (12.3) rifà la decisione con lo stesso calendario delle trimestrali. Prima segnava come differenza ogni acquisto tolto per i conti, e quel conto serve per passare di stadio. + +**7. Quello che manca di 10.2, punto 1.** +- Il flusso Alpaca News richiede le chiavi del conto paper, che non ci sono. Resta facoltativo (API-NOTES, A5). +- I comunicati SEC dei titoli in portafoglio vengono da EDGAR, che chiede nell'intestazione un nome e un contatto (API-NOTES, F8). Il contatto è un dato dell'utente: non si manda senza il suo permesso. Il feed generale dei comunicati SEC resta tra le fonti. +- Le due parti sono nella issue #107, in attesa dell'utente. + +## Conseguenze + +- Più collegamenti giusti vogliono dire più restrizioni giuste, e anche qualche restrizione in più: la direzione resta prudente. +- Gli alias vanno aggiornati a mano se una grande società cambia nome. +- Le storie e gli articoli già salvati non si rileggono: valgono le nuove regole per quelli che arrivano. diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index 1c8bdcb..3c7f7d5 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -119,6 +119,12 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche /// public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15); + /// + /// A job that can take long (the round of the news): it runs beside the others, never with itself. The queue, where + /// the engine and the risk check are, does not wait for it. + /// + public bool Beside { get; init; } + /// A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job. public bool IsMove { get; init; } @@ -165,6 +171,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger _jobs = new(StringComparer.Ordinal); private readonly Dictionary _recovering = new(StringComparer.Ordinal); private readonly List _missed = []; + private readonly Dictionary _beside = new(StringComparer.Ordinal); private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously); /// Moment of the last loop iteration; the health check uses it to see the loop is alive. @@ -230,6 +237,28 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILoggerWaits for the jobs that run beside the queue. + public Task BesideAsync() + { + lock (_gate) + { + return Task.WhenAll(_beside.Values); + } + } + + private async Task LoopAsync(CancellationToken cancellationToken) { while (true) { @@ -308,44 +337,57 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger job.MaxLateness) + if (!recovering && started - dueAt > job.MaxLateness) { LogSkipped(_logger, job.Name, dueAt); bus.Publish(new JobRun(job.Name, dueAt, started, started, JobOutcome.Skipped, "Orario superato di troppo: il lavoro non è stato eseguito.")); continue; } - try + if (!job.Beside) { - await job.Run(cancellationToken).ConfigureAwait(false); - bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null)); + await RunOneAsync(job, dueAt, started, recovering, cancellationToken).ConfigureAwait(false); + continue; } - catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + + lock (_gate) { - LogFailed(_logger, ex, job.Name); - bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message)); + if (_beside.TryGetValue(job.Name, out var running) && !running.IsCompleted) + { + continue; // The round before is not over: this one is not needed. + } + + _beside[job.Name] = Task.Run(async () => + { + try + { + await RunOneAsync(job, dueAt, started, recovering, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + }, CancellationToken.None); } } } - /// A run missed while the bot was off, made once now: never skipped for lateness, reported as recovered. - private async Task RecoverAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, CancellationToken cancellationToken) + /// One run. One missed while the bot was off and made now is reported as recovered. + private async Task RunOneAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, bool recovering, CancellationToken cancellationToken) { + void Publish(JobOutcome outcome, string? error) => bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, outcome, error) + { + Missed = recovering, + Description = recovering ? job.Description : null, + }); try { await job.Run(cancellationToken).ConfigureAwait(false); - bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null) { Missed = true, Description = job.Description }); + Publish(JobOutcome.Completed, null); } catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { LogFailed(_logger, ex, job.Name); - bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message) { Missed = true, Description = job.Description }); + Publish(JobOutcome.Failed, ex.Message); } } diff --git a/src/Anubis/Data/FreeSources.cs b/src/Anubis/Data/FreeSources.cs index b225f57..e595bba 100644 --- a/src/Anubis/Data/FreeSources.cs +++ b/src/Anubis/Data/FreeSources.cs @@ -473,6 +473,9 @@ public static class Zones public static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + /// The calendar day of a moment in a zone. + public static DateOnly DayIn(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime); + public static DateTimeOffset At(DateOnly day, TimeOnly time, TimeZoneInfo zone) { ArgumentNullException.ThrowIfNull(zone); diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index 9134589..9c7c8b0 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -80,7 +80,7 @@ public sealed partial class MarketDataService : IDisposable News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"), - Watcher = new News.NewsWatcher(db, clock, settings), + Watcher = new News.NewsWatcher(db, clock, settings) { EarningsActive = References.EarningsFilterActiveAsync }, Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_http, config, key), _logger), }; } diff --git a/src/Anubis/News/Judgement.cs b/src/Anubis/News/Judgement.cs index 63e8137..f7e4f86 100644 --- a/src/Anubis/News/Judgement.cs +++ b/src/Anubis/News/Judgement.cs @@ -99,7 +99,7 @@ public static partial class NewsJudge /// The first serious case named by the text, in the order of 10.2, or null. public static string? Severe(string title, string? summary) { - var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant().Replace('’', '\''), " "), " ") + " "; + var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant(), " "), " ") + " "; foreach (var (kind, phrases) in Keywords) { if (phrases.Any(p => text.Contains(" " + p + " ", StringComparison.Ordinal))) @@ -121,7 +121,8 @@ public static partial class NewsJudge return new NewsJudgement(score, severe, importance); } - [GeneratedRegex(@"[^\p{L}\p{N}']+")] + // An apostrophe ends a word like any other sign: "un'indagine" and 'fraud' in quotes carry the keyword. + [GeneratedRegex(@"[^\p{L}\p{N}]+")] private static partial Regex NonWord(); [GeneratedRegex(@"\s+")] diff --git a/src/Anubis/News/Linker.cs b/src/Anubis/News/Linker.cs index 6f90b09..5a8f5da 100644 --- a/src/Anubis/News/Linker.cs +++ b/src/Anubis/News/Linker.cs @@ -65,6 +65,19 @@ public sealed partial class NewsLinker ["Arbitrum"] = "ARB", }; + // How newspapers call a company whose name in the catalogue is longer or written in another way. Used only when the + // ticker is in the catalogue. Ordinary words are left out: "Metals" or "Joint" would link the wrong stories. + private static readonly (string Ticker, string[] Names)[] Aliases = + [ + ("ALL", ["Allstate"]), ("AMD", ["AMD"]), ("BA", ["Boeing"]), ("BAC", ["BofA"]), ("C", ["Citi"]), ("CI", ["Cigna"]), ("CLX", ["Clorox"]), + ("COIN", ["Coinbase"]), ("COST", ["Costco"]), ("DIS", ["Disney"]), ("GM", ["GM"]), ("GOOG", ["Google"]), ("GOOGL", ["Google"]), + ("GS", ["Goldman Sachs", "Goldman"]), ("HD", ["Home Depot"]), ("HOOD", ["Robinhood"]), ("HSY", ["Hershey"]), ("IBM", ["IBM"]), ("JPM", ["JPMorgan", "J.P. Morgan", "JP Morgan"]), + ("KHC", ["Kraft Heinz"]), ("KO", ["Coca-Cola", "Coca Cola"]), ("KR", ["Kroger"]), ("LLY", ["Eli Lilly"]), ("MCD", ["McDonald's"]), ("META", ["Meta", "Facebook"]), + ("MSTR", ["MicroStrategy"]), ("MU", ["Micron"]), ("MRVL", ["Marvell"]), ("PEP", ["Pepsi"]), ("PG", ["Procter & Gamble", "P&G"]), ("PLTR", ["Palantir"]), + ("RIVN", ["Rivian"]), ("RTX", ["Raytheon"]), ("SCHW", ["Charles Schwab"]), ("SHW", ["Sherwin-Williams"]), ("SMCI", ["Super Micro", "Supermicro"]), + ("TMUS", ["T-Mobile"]), ("UBER", ["Uber"]), ("VZ", ["Verizon"]), ("WFC", ["Wells Fargo"]), ("XOM", ["Exxon", "ExxonMobil"]), + ]; + // Words of a theme, lower case: one of them in a title or summary links the story to the class or to the market. private static readonly (string Scope, string Target, string[] Words)[] Themes = [ @@ -98,7 +111,7 @@ public sealed partial class NewsLinker private static readonly string[] Suffixes = [ ", Inc.", " Inc.", " Inc", ", Inc", " Incorporated", " Corporation", " Corp.", " Corp", " Company", " Co.", " Holdings", " Holding", " Group", - " Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com", + " Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com", " (The)", " -", ]; private readonly Dictionary _equityTickers = new(StringComparer.Ordinal); @@ -143,6 +156,17 @@ public sealed partial class NewsLinker } } + foreach (var (ticker, names) in Aliases) + { + if (dictionary._equityTickers.TryGetValue(ticker, out var target)) + { + foreach (var name in names) + { + dictionary.AddName(name, target, alias: true); + } + } + } + foreach (var (name, coin) in CoinNames) { if (dictionary._coins.TryGetValue(coin, out var targets)) @@ -157,7 +181,11 @@ public sealed partial class NewsLinker return dictionary; } - /// "Apple Inc. Common Stock" → "Apple"; null when what remains is too short or an ordinary word. + /// + /// "Apple Inc. Common Stock" → "Apple", "The Goldman Sachs Group, Inc." → "Goldman Sachs"; null when what remains is + /// too short or an ordinary word. A name with "The" of which one word remains (The Metals Company) is often an ordinary + /// word too: it needs its ticker or a place among the aliases. + /// public static string? CompanyName(string? name) { if (string.IsNullOrWhiteSpace(name)) @@ -188,7 +216,13 @@ public sealed partial class NewsLinker } } - return clean.Length < 3 || Ambiguous.Contains(clean) ? null : clean; + var article = name.Contains("(The)", StringComparison.OrdinalIgnoreCase); + if (clean.StartsWith("The ", StringComparison.OrdinalIgnoreCase)) + { + (clean, article) = (clean[4..].TrimStart(), true); + } + + return clean.Length < 3 || Ambiguous.Contains(clean) || (article && !clean.Contains(' ', StringComparison.Ordinal)) ? null : clean; } /// @@ -234,29 +268,47 @@ public sealed partial class NewsLinker } } - var words = Words().Matches(text).Select(m => Possessive().Replace(m.Value, "").TrimEnd('.')).Where(w => w.Length > 0).ToList(); + var words = Tokens(text); for (var i = 0; i < words.Count; i++) { // A coin's ticker in capitals (BTC, ETH, SOL) is a link: news write them that way. - if (words[i].Length >= 3 && words[i].All(char.IsUpper) && _coins.TryGetValue(words[i], out var coins)) + foreach (var form in words[i]) { - coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker)); - } - - if (!char.IsUpper(words[i][0]) || !_names.TryGetValue(words[i], out var candidates)) - { - continue; - } - - foreach (var (nameWords, target) in candidates.OrderByDescending(c => c.Words.Length)) - { - if (i + nameWords.Length <= words.Count - && nameWords.Select((w, k) => string.Equals(w, words[i + k], StringComparison.OrdinalIgnoreCase)).All(x => x)) + if (form.Length >= 3 && form.All(char.IsUpper) && _coins.TryGetValue(form, out var coins)) { - Add(LinkScopes.Instrument, target, LinkVia.Name); - break; + coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker)); } } + + var longest = 0; + var found = new List(); + foreach (var form in words[i].Where(f => char.IsUpper(f[0]) && _names.ContainsKey(f))) + { + foreach (var (nameWords, target) in _names[form]) + { + // Two share classes have the same name (Alphabet): the longest name wins, with every instrument it names. + if (nameWords.Length >= longest && i + nameWords.Length <= words.Count + && !nameWords.Where((w, k) => !words[i + k].Contains(w, StringComparer.OrdinalIgnoreCase)).Any()) + { + if (nameWords.Length > longest) + { + longest = nameWords.Length; + found.Clear(); + } + + found.Add(target); + } + } + } + + // "Apple-led", "Nvidia-backed": the first part, when it is a whole name of its own. + if (longest == 0 && words[i][^1].IndexOf('-', StringComparison.Ordinal) is var dash and > 0 && char.IsUpper(words[i][^1][0]) + && _names.TryGetValue(words[i][^1][..dash], out var parts)) + { + found.AddRange(parts.Where(p => p.Words.Length == 1).Select(p => p.Target)); + } + + found.ForEach(t => Add(LinkScopes.Instrument, t, LinkVia.Name)); } // "(NASDAQ: AAPL)" names the listing of one company, not the stock market as a whole. @@ -278,10 +330,44 @@ public sealed partial class NewsLinker return links; } - private void AddName(string name, string target) + /// + /// The words of a text, each in the forms a name can have in it: as written ("McDonald's"), without the Italian article + /// before the apostrophe ("dell'Apple" is also "Apple"), without the possessive ("Apple's" is also "Apple"). + /// + private static List Tokens(string text) { - var words = Words().Matches(name).Select(m => m.Value.TrimEnd('.')).Where(w => w.Length > 0).ToArray(); - if (words.Length == 0 || (words.Length == 1 && (words[0].Length < 3 || Ambiguous.Contains(words[0])))) + var tokens = new List(); + foreach (Match match in Words().Matches(Curly().Replace(text, "'"))) + { + var forms = new List(); + void Form(string form) + { + if (form.TrimEnd('.', '-', '\'') is { Length: > 0 } clean && !forms.Contains(clean)) + { + forms.Add(clean); + } + } + + foreach (var form in new[] { match.Value, Elision().Replace(match.Value, "") }) + { + Form(form); + Form(Possessive().Replace(form, "")); + } + + if (forms.Count > 0) + { + tokens.Add([.. forms]); + } + } + + return tokens; + } + + private void AddName(string name, string target, bool alias = false) + { + // The name as the catalogue writes it: "Wendy's" is never just "Wendy". + var words = Words().Matches(Curly().Replace(name, "'")).Select(m => m.Value.TrimEnd('.', '-', '\'')).Where(w => w.Length > 0).ToArray(); + if (words.Length == 0 || (words.Length == 1 && ((words[0].Length < 3 && !alias) || Ambiguous.Contains(words[0])))) { return; } @@ -306,9 +392,15 @@ public sealed partial class NewsLinker [GeneratedRegex(@"[\p{L}\p{N}][\p{L}\p{N}&'.\-]*")] private static partial Regex Words(); - [GeneratedRegex(@"['’]s$")] + [GeneratedRegex(@"'s$")] private static partial Regex Possessive(); + [GeneratedRegex(@"^(?:l|un|dell|all|nell|dall|sull|coll|quest|quell|d)'(?=.)", RegexOptions.IgnoreCase)] + private static partial Regex Elision(); + + [GeneratedRegex("[’‘`´]")] + private static partial Regex Curly(); + [GeneratedRegex(@"[^\p{L}\p{N}&]+")] private static partial Regex NonWord(); diff --git a/src/Anubis/News/NewsBoard.cs b/src/Anubis/News/NewsBoard.cs index 0b6341c..e955f77 100644 --- a/src/Anubis/News/NewsBoard.cs +++ b/src/Anubis/News/NewsBoard.cs @@ -43,13 +43,13 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings var now = clock.UtcNow; var since = now - Window; var switches = await NewsRuleSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); - // A restriction lasts at most 72 hours: stories older than that and the window are never in force. - var oldest = since - NewsRules.Longest; + // A restriction lasts at most 72 hours from an article, and articles join a story for 48: older ones are never in force. + var oldest = since - NewsRules.Longest - NewsMatching.StoryWindow; var (all, links, notes, held) = await db.ReadAsync(async s => { const string Recent = "st.first_seen_at >= @oldest"; var st = await s.QueryAsync( - "SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + + "SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + NewsDesk.RaisedAt + "v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, v.summary AS model_summary, " + "(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id ORDER BY i.created_at, i.id LIMIT 1) AS publisher " + "FROM news_stories st LEFT JOIN news_verdicts v ON v.id = st.verdict_id WHERE " + Recent, @@ -70,6 +70,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings return (st, l, n, h); }, cancellationToken).ConfigureAwait(false); + // An event in the calendar about a held or candidate stock is worth 3 (10.2 point 4). Only what is shown: the rules of + // 10.5 for a report are their own row, and a story with an unread tone must not restrict because of the calendar. + var watched = (await NewsWatcher.WatchedAsync(db, cancellationToken).ConfigureAwait(false)).Select(w => w.Target).ToHashSet(StringComparer.Ordinal); + var reporting = (await NewsDesk.NearEarningsAsync(db, clock, now, cancellationToken).ConfigureAwait(false)).Select(e => Venues.Alpaca + ":" + e.Symbol) + .Where(watched.Contains).ToHashSet(StringComparer.Ordinal); + var holding = held.Where(h => h.Quantity > 0m).ToList(); var heldTargets = holding.Select(h => h.Target).ToHashSet(StringComparer.Ordinal); var heldClasses = holding.Select(h => h.Class).ToHashSet(StringComparer.Ordinal); @@ -104,12 +110,13 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings var (action, active) = Act(story, instruments, storyNotes.Select(n => (n.Kind, n.Action, n.Until)).ToList(), heldTargets, switches, now); var verdict = verdicts[story.Id]; + var coming = storyNotes.Any(n => n.Kind == NewsReasons.Earnings) || instruments.Any(reporting.Contains); // An Italian title has no tone of the classifier: the direction of the model, when there is one, takes its place. var modelDirection = verdict.Importance is null ? null : verdict.Direction; var tone = (story.Score is null && modelDirection is not null ? ModelToneText(modelDirection) : ToneText(story.Score)) + - (NewsRules.Unconfirmed(story) ? ", non confermata" : "") + (storyNotes.Any(n => n.Kind == NewsReasons.Earnings) ? ", evento in arrivo" : ""); + (NewsRules.Unconfirmed(story) ? ", non confermata" : "") + (coming ? ", evento in arrivo" : ""); // The importance shown is the one the rules use: the model's counts only when negative and about this story's instruments. - var importance = story.RuleImportance; + var importance = coming ? Math.Max(3, story.RuleImportance) : story.RuleImportance; rows.Add(new NewsBoardRow(story.Id, story.Start, story.Publisher, About(own, instruments), story.Sources <= 1 && !story.Trusted, story.Title, tone, story.Score is null && modelDirection is not null ? ModelDirection(modelDirection) : Direction(story.Score), Math.Clamp(importance, 1, 5), action, active, onPositions) { Summary = verdict.Summary }); @@ -222,7 +229,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings return ("Niente, perché nessun'altra fonte la riportava.", false); } - var matched = NewsRules.Active([story], story.Start, NewsRuleSwitches.AllOn) is { Count: > 0 } found ? found[0] : null; + var matched = NewsRules.Active([story], story.EffectStart > story.FirstSeenAt ? story.EffectStart : story.FirstSeenAt, NewsRuleSwitches.AllOn) is { Count: > 0 } found ? found[0] : null; if (matched is not null) { if (matched.Code == NewsReasons.Severe ? !switches.Severe : !switches.Negative) diff --git a/src/Anubis/News/NewsCollector.cs b/src/Anubis/News/NewsCollector.cs index b6f08cf..1f16da9 100644 --- a/src/Anubis/News/NewsCollector.cs +++ b/src/Anubis/News/NewsCollector.cs @@ -92,7 +92,7 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c }, CancellationToken.None); } - public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval }; + public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval, Beside = true }; /// One round over the sources that are due. public async Task RunOnceAsync(CancellationToken cancellationToken) diff --git a/src/Anubis/News/NewsDesk.cs b/src/Anubis/News/NewsDesk.cs index 725e5d7..0dff816 100644 --- a/src/Anubis/News/NewsDesk.cs +++ b/src/Anubis/News/NewsDesk.cs @@ -24,7 +24,7 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings /// The stories linked to seen since , oldest first. public async Task> StoriesAsync(string target, DateTimeOffset since, CancellationToken cancellationToken) => await db.ReadAsync(s => s.QueryAsync( - "SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + + "SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + RaisedAt + "v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, " + "(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id ORDER BY i.created_at, i.id LIMIT 1) AS publisher " + "FROM news_stories st JOIN news_links l ON l.story_id = st.id LEFT JOIN news_verdicts v ON v.id = st.verdict_id " + @@ -49,8 +49,9 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings } /// - /// The next earnings date of each stock from on, as the calendar of 4.4 has it: the day in - /// New York. equity_meanrev reads it (10.5, fourth row; 8.3 for its exit). + /// The next earnings date of each stock after the close of , as the calendar of 4.4 has it: the + /// day in New York. equity_meanrev reads it (10.5, fourth row; 8.3 for its exit). A report of that day before the + /// open or during the session is already out: the next session is free. /// public async Task> EarningsAsync(DateOnly from, CancellationToken cancellationToken) { @@ -59,18 +60,51 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings var next = new Dictionary(StringComparer.Ordinal); foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { Length: > 0 }).OrderBy(e => e.OccursAt)) { - next.TryAdd(e.Symbol!, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime)); + var day = Zones.DayIn(e.OccursAt, Zones.NewYork); + if (day > from || e.TimeHint is not ("bmo" or "dmh")) + { + next.TryAdd(e.Symbol!, day); + } } return next; } + /// + /// The last day of a report that already keeps equity_meanrev out at : the entry session + /// and the three after it, so four working days from today in New York. A holiday in between only delays the line of + /// the diary by a day: the strategy counts from the sessions of the broker's calendar. + /// + public static DateOnly EarningsReach(DateTimeOffset now) + { + var day = Zones.DayIn(now, Zones.NewYork); + for (var sessions = 0; sessions < 4;) + { + day = day.AddDays(1); + sessions += day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday ? 0 : 1; + } + + return day; + } + + /// The reports from on that keep equity_meanrev out already. + internal static async Task> NearEarningsAsync(Database db, IClock clock, DateTimeOffset now, CancellationToken cancellationToken) + { + var reach = EarningsReach(now); + var events = await new CalendarEventStore(db, clock).BetweenAsync(now, now.AddDays(8), cancellationToken).ConfigureAwait(false); + return [.. events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { Length: > 0 } && Zones.DayIn(e.OccursAt, Zones.NewYork) <= reach)]; + } + + /// When the first article with the story's own importance came out (). + internal const string RaisedAt = "(SELECT MIN(i.published_at) FROM news_items i WHERE i.story_id = st.id AND i.importance = st.importance) AS raised_at, "; + /// A story with the verdict of the model joined as model_direction, model_importance, model_instruments, model_problem. internal static StoryFact ReadStory(DbRow r, IReadOnlyCollection targets) => new(r.Id("id"), r.Text("title"), r.TextOrNull("publisher") ?? "", r.Moment("published_at"), r.Moment("first_seen_at"), (int)r.Number("sources"), r.Bool("trusted"), r.IsNull("score") ? null : r.Measure("score"), r.TextOrNull("severe"), (int)r.Number("importance"), Escalation(r.TextOrNull("model_direction"), r.IsNull("model_importance") ? null : (int)r.Number("model_importance"), r.TextOrNull("model_instruments"), - r.TextOrNull("model_problem"), targets)); + r.TextOrNull("model_problem"), targets)) + { RaisedAt = r.MomentOrNull("raised_at") }; /// /// What a verdict adds for an instrument: its importance when it is valid, negative and names one of @@ -164,6 +198,9 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin public TimeZoneInfo Zone { get; init; } = Zones.Rome; + /// Whether the earnings calendar is fresh, as the strategies ask (4.4): without it their row does nothing and the diary says nothing. + public Func>? EarningsActive { get; init; } + /// One round over the instruments watched now: those held by any strategy and those of the latest universes. public async Task RunOnceAsync(CancellationToken cancellationToken) { @@ -204,7 +241,7 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin } } - if (switches.Earnings) + if (switches.Earnings && (EarningsActive is null || await EarningsActive(cancellationToken).ConfigureAwait(false))) { written += await EarningsAsync(watched, now, cancellationToken).ConfigureAwait(false); } @@ -225,7 +262,7 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin return $"Ho cambiato una regola per 24 ore: {what}. Motivo: {EntryGate.Motive(r.Story)}."; } - // Earnings of a watched stock in the next five days (three sessions and a weekend): said once, with the day. + // Earnings of a watched stock that already keep mean reversion out: said once, with the day. private async Task EarningsAsync(IReadOnlyList<(string Target, string Symbol, bool Held)> watched, DateTimeOffset now, CancellationToken cancellationToken) { var stocks = watched.Where(w => w.Target.StartsWith(Venues.Alpaca + ":", StringComparison.Ordinal)).ToDictionary(w => w.Symbol, w => w.Target, StringComparer.Ordinal); @@ -235,10 +272,9 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin } var written = 0; - var events = await new CalendarEventStore(db, clock).BetweenAsync(now, now.AddDays(5), cancellationToken).ConfigureAwait(false); - foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { } s && stocks.ContainsKey(s))) + foreach (var e in (await NewsDesk.NearEarningsAsync(db, clock, now, cancellationToken).ConfigureAwait(false)).Where(e => stocks.ContainsKey(e.Symbol!))) { - var dayText = Format.Day(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime)); + var dayText = Format.Day(Zones.DayIn(e.OccursAt, Zones.NewYork)); var (when, until) = e.TimeHint switch { "bmo" => (" prima dell'apertura", $"fino a {dayText}"), diff --git a/src/Anubis/News/NewsRules.cs b/src/Anubis/News/NewsRules.cs index 1ef0eca..2db2f2c 100644 --- a/src/Anubis/News/NewsRules.cs +++ b/src/Anubis/News/NewsRules.cs @@ -48,6 +48,16 @@ public sealed record StoryFact(Guid Id, string Title, string Publisher, DateTime /// public DateTimeOffset Start => PublishedAt < FirstSeenAt ? PublishedAt : FirstSeenAt; + /// When the first article with the importance of the story came out, when a later one raised it. + public DateTimeOffset? RaisedAt { get; init; } + + /// + /// From when the windows of 10.5 count: the article that made the story what it is. The verdict of the model is about + /// the story as first read, so what only the model raises counts from the start; a case the keywords call serious + /// counts from its article whatever the model says. + /// + public DateTimeOffset EffectStart => RaisedAt is { } raised && raised > Start && Importance >= Math.Min(4, ModelImportance ?? 0) ? raised : Start; + /// The importance the rules use: the higher of the two judgements (10.2 point 5). public int RuleImportance => Math.Max(Importance, ModelImportance ?? 0); @@ -118,10 +128,11 @@ public static class NewsRules } var (on, code, window) = story.IsSevere ? (switches.Severe, NewsReasons.Severe, SevereWindow) : (switches.Negative, NewsReasons.Negative, NegativeWindow); - var until = story.Start + window; - if (on && story.Start <= now && now < until) + var from = story.EffectStart; + var until = from + window; + if (on && from <= now && now < until) { - active.Add(new NewsRestriction(code, story.Start, until, story)); + active.Add(new NewsRestriction(code, from, until, story)); } } diff --git a/src/Anubis/News/NewsStore.cs b/src/Anubis/News/NewsStore.cs index a548556..7800502 100644 --- a/src/Anubis/News/NewsStore.cs +++ b/src/Anubis/News/NewsStore.cs @@ -104,6 +104,13 @@ public sealed class NewsStore(Database db, IClock clock) await s.ExecuteAsync("UPDATE news_sources SET enabled = @e, trusted = @t, updated_at = @now WHERE id = @id", cancellationToken, ("e", enabled), ("t", trusted), ("now", now), ("id", id)).ConfigureAwait(false); + if (before.Trusted != trusted) + { + // The stories already read count the label as it is now. + await s.ExecuteAsync("UPDATE news_stories SET updated_at = @now, trusted = " + TrustedNow + " WHERE id IN (SELECT story_id FROM news_items WHERE source_id = @id)", + cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false); + } + static string Words(bool on, bool sure) => (on ? "attiva" : "spenta") + (sure ? ", affidabile" : ", non affidabile"); if (before.Enabled != enabled || before.Trusted != trusted) { @@ -141,31 +148,62 @@ public sealed class NewsStore(Database db, IClock clock) ArgumentNullException.ThrowIfNull(items); ArgumentNullException.ThrowIfNull(dictionary); var now = clock.UtcNow; + + // The judgement first: the classifier takes its time, and the single writer of the database is the engine's too. + int old = 0, known = 0; + var fresh = new List<(FeedItem Item, string Key, DateTimeOffset Published, string Language, IReadOnlyList Links, NewsJudgement Judgement)>(); + foreach (var item in items.OrderBy(i => i.PublishedAt ?? now)) + { + cancellationToken.ThrowIfCancellationRequested(); + var published = item.PublishedAt is { } p && p <= now ? p : now; + if (now - published > MaxAge) + { + old++; + continue; + } + + var key = NewsMatching.UrlKey(item.Link); + if (fresh.Any(f => f.Key == key) || + await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)), cancellationToken).ConfigureAwait(false) > 0) + { + known++; + continue; + } + + var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary); + var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic); + fresh.Add((item, key, published, language, links, + NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier))); + } + + if (fresh.Count == 0) + { + return new IngestResult(0, known, 0, old); + } + return await db.WriteAsync(async s => { - int added = 0, duplicates = 0, old = 0; + int added = 0, duplicates = known; var touched = new HashSet(); - var stories = await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t", - r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")), - ("t", now - MaxAge - NewsMatching.StoryWindow)).ConfigureAwait(false); - foreach (var item in items.OrderBy(i => i.PublishedAt ?? now)) + var since = now - MaxAge - NewsMatching.StoryWindow; + var about = (await s.QueryAsync("SELECT l.story_id, l.target FROM news_links l JOIN news_stories st ON st.id = l.story_id WHERE l.scope = @sc AND st.published_at >= @t", + r => (Story: r.Id("story_id"), Target: r.Text("target")), ("sc", LinkScopes.Instrument), ("t", since)).ConfigureAwait(false)).ToLookup(l => l.Story, l => l.Target); + var stories = (await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t", + r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")), ("t", since)).ConfigureAwait(false)) + .Select(st => (st.Id, st.Words, st.Published, Instruments: about[st.Id].ToHashSet(StringComparer.Ordinal))).ToList(); + foreach (var (item, key, published, language, links, judgement) in fresh) { - var published = item.PublishedAt is { } p && p <= now ? p : now; - if (now - published > MaxAge) - { - old++; - continue; - } - - var key = NewsMatching.UrlKey(item.Link); if (await s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)).ConfigureAwait(false) > 0) { duplicates++; continue; } + // The same words about two companies are two stories: one must never confirm or restrict the other. var words = NewsMatching.Words(item.Title); - var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words)) + var instruments = links.Where(l => l.Scope == LinkScopes.Instrument).Select(l => l.Target).ToHashSet(StringComparer.Ordinal); + var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words) + && (instruments.Count == 0 || st.Instruments.Count == 0 || instruments.Overlaps(st.Instruments))) .OrderByDescending(st => NewsMatching.Score(words, st.Words)).Select(st => (Guid?)st.Id).FirstOrDefault(); if (story is null) { @@ -175,12 +213,13 @@ public sealed class NewsStore(Database db, IClock clock) "VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, 1, @now, @now)", cancellationToken, ("id", story), ("title", item.Title), ("key", NewsMatching.TitleKey(item.Title)), ("p", published), ("now", now), ("trusted", source.Trusted)) .ConfigureAwait(false); - stories.Add((story.Value, words, published)); + stories.Add((story.Value, words, published, instruments)); + } + else + { + stories.Single(st => st.Id == story).Instruments.UnionWith(instruments); } - var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary); - var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic); - var judgement = NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier); await s.ExecuteAsync( "INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, score, severe, importance, created_at) " + "VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @score, @severe, @importance, @now)", cancellationToken, @@ -204,9 +243,9 @@ public sealed class NewsStore(Database db, IClock clock) await s.ExecuteAsync( "UPDATE news_stories SET last_seen_at = @now, updated_at = @now, " + "sources = (SELECT COUNT(DISTINCT publisher) FROM news_items WHERE story_id = @id), " + - "trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0, " + + "trusted = " + TrustedNow + ", " + "score = (SELECT AVG(score) FROM news_items WHERE story_id = @id), " + - "severe = (SELECT MIN(severe) FROM news_items WHERE story_id = @id), " + + "severe = (SELECT i.severe FROM news_items i WHERE i.story_id = @id AND i.severe IS NOT NULL ORDER BY " + SevereOrder + ", i.id LIMIT 1), " + "importance = (SELECT MAX(importance) FROM news_items WHERE story_id = @id) " + "WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false); } @@ -215,6 +254,15 @@ public sealed class NewsStore(Database db, IClock clock) }, cancellationToken).ConfigureAwait(false); } + // Whether a trusted source told the story, in an UPDATE of news_stories. + private const string TrustedNow = + "(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0"; + + // The serious cases in the order of 10.2. + private const string SevereOrder = + "CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" + + SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END"; + private static NewsSource Rss(string url, string name, bool trusted, string? topic) => new(Guid.Empty, url, name, NewsSourceKinds.Rss, trusted, Enabled: true, topic); diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs index 728ac24..9cc907d 100644 --- a/src/Anubis/Trading/DiaryText.cs +++ b/src/Anubis/Trading/DiaryText.cs @@ -148,8 +148,12 @@ public static class DiaryText $"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm})."; /// A purchase a rule of SPEC 10.5 put off: it goes when the restriction ends. - public static string EntryPostponed(string symbol, DateTimeOffset until, TimeZoneInfo zone, string reason, string motive) => - $"Ho rimandato l'acquisto di {Shown(symbol)} alle {TimeZoneInfo.ConvertTime(until, zone):HH:mm}. {reason} Motivo: {motive}."; + public static string EntryPostponed(string symbol, DateTimeOffset until, DateTimeOffset now, TimeZoneInfo zone, string reason, string motive) + { + var day = Data.Zones.DayIn(until, zone); + var when = day == Data.Zones.DayIn(now, zone) ? "" : $"a {Format.Day(day)} "; + return $"Ho rimandato l'acquisto di {Shown(symbol)} {when}alle {TimeZoneInfo.ConvertTime(until, zone):HH:mm}. {reason} Motivo: {motive}."; + } /// A purchase a rule of SPEC 10.5 left out: the restriction lasts past its deadline (SPEC 5.6). public static string EntryRestricted(string symbol, string reason, string motive) => $"Non compro {Shown(symbol)}. {reason} Motivo: {motive}."; diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index cfa48df..a1d4198 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -492,16 +492,7 @@ public sealed partial class LiveEngine : IDisposable var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters); var data = loaded.Data; - var options = StrategyPipeline.For(m.Strategy, data, new BacktestOptions()); - if (Earnings is not null && m.Strategy != StrategyNames.CryptoTrend && await Earnings(m.Day, cancellationToken).ConfigureAwait(false) is { } earnings) - { - options = options with - { - NextEarnings = symbol => earnings.Next.TryGetValue(symbol, out var date) ? date : null, - EarningsEntries = earnings.BlockEntries, - }; - } - + var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false); DecisionRecord record; if (observation) { @@ -561,6 +552,42 @@ public sealed partial class LiveEngine : IDisposable } } + /// The earnings calendar as the decision of reads it (SPEC 10.5, fourth row; 8.3). + private async Task WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, CancellationToken cancellationToken) + { + if (Earnings is null || strategy == StrategyNames.CryptoTrend || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings) + { + return options; + } + + return options with + { + NextEarnings = symbol => earnings.Next.TryGetValue(symbol, out var date) ? date : null, + EarningsEntries = earnings.BlockEntries, + }; + } + + /// + /// When a purchase held until can go. A stock goes five minutes after the open at the + /// earliest, as every purchase (SPEC 5.5): a restriction that ends with the market closed leaves it to the next open. + /// + private DateTimeOffset ReleaseAt(bool crypto, DateTimeOffset until) + { + if (crypto || _calendar is null) + { + return until; + } + + var day = Zones.DayIn(until, Zones.NewYork); + if (_calendar.SessionOn(day) is { } session && until < session.CloseUtc) + { + var first = session.OpenUtc + Options.OrdersAfterOpen; + return until > first ? until : first; + } + + return NextSession(day) is { } next ? next.OpenUtc + Options.OrdersAfterOpen : until; + } + private async Task NoDataAsync(Moment m, StrategyStage stage, CancellationToken cancellationToken) { var observation = stage.Stage == StrategyStages.Observation; @@ -627,11 +654,19 @@ public sealed partial class LiveEngine : IDisposable continue; } - var dropped = order.ValidUntil is { } until && hold.Until > until; - holds.Add((order.Symbol, hold, dropped)); + var release = ReleaseAt(order.Crypto, hold.Until); + if (release <= order.Due) + { + // The restriction is over before the purchase is due: nothing changes, and nothing is said. + orders.Add(order); + continue; + } + + var dropped = order.ValidUntil is { } until && release > until; + holds.Add((order.Symbol, hold with { Until = release }, dropped)); if (!dropped) { - orders.Add(hold.Until > order.Due ? order with { Due = hold.Until, FirstDue = order.Due } : order); + orders.Add(order with { Due = release, FirstDue = order.Due }); } } @@ -812,7 +847,7 @@ public sealed partial class LiveEngine : IDisposable if (!observation) { var text = dropped ? DiaryText.EntryRestricted(symbol, ReasonCatalog.Text(hold.Code), hold.Motive) - : DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive); + : DiaryText.EntryPostponed(symbol, hold.Until, now, Zone, ReasonCatalog.Text(hold.Code), hold.Motive); await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, text, new { decision = decisionId, symbol }, cancellationToken).ConfigureAwait(false); } } @@ -945,7 +980,8 @@ public sealed partial class LiveEngine : IDisposable } var state = snapshot.ToState(); - var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day).Proposed; + var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, cancellationToken).ConfigureAwait(false); + var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day, options).Proposed; var different = OneStep.Compare(state, recorded.Select(p => (p.Symbol, p.Weight)).ToList(), again.Select(i => (i.Symbol, i.TargetWeight)).ToList(), data, previous.Day); return (previous.Id, different.Count == 0, different); } @@ -1017,7 +1053,7 @@ public sealed partial class LiveEngine : IDisposable if (order.Side == OrderSide.Buy && Gate is not null && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold) { - await HoldAsync(order, instrument.Symbol, hold, now, cancellationToken).ConfigureAwait(false); + await HoldAsync(order, instrument.Symbol, hold with { Until = ReleaseAt(instrument.IsCrypto, hold.Until) }, now, cancellationToken).ConfigureAwait(false); return; } @@ -1181,7 +1217,7 @@ public sealed partial class LiveEngine : IDisposable await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, symbol, DecisionStages.Order, DecisionOutcomes.Postponed, [hold.Code], new Dictionary { ["planned"] = order.Id, ["until"] = hold.Until, ["motive"] = hold.Motive }, now), cancellationToken).ConfigureAwait(false); - await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive), + await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, DiaryText.EntryPostponed(symbol, hold.Until, now, Zone, ReasonCatalog.Text(hold.Code), hold.Motive), new { planned = order.Id }, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } diff --git a/tests/Anubis.Tests/CoreTests.cs b/tests/Anubis.Tests/CoreTests.cs index a835ac6..1f5ff24 100644 --- a/tests/Anubis.Tests/CoreTests.cs +++ b/tests/Anubis.Tests/CoreTests.cs @@ -218,6 +218,51 @@ public sealed class SchedulerTests Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc); } + /// A long job beside the queue (the news) never delays the others, never runs twice at once, and is waited for. + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AJobBesideTheQueueNeverDelaysTheOthers() + { + var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)); + var bus = new EventBus(); + using var runs = bus.Subscribe(); + var scheduler = new Scheduler(clock, bus); + int slow = 0, quick = 0; + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + scheduler.Add(new ScheduledJob("a-notizie", "Lunga", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => + { + Interlocked.Increment(ref slow); + await release.Task.WaitAsync(ct).ConfigureAwait(false); + }) + { Beside = true }); + scheduler.Add(new ScheduledJob("rischio", "Breve", Schedule.Every(TimeSpan.FromMinutes(1)), _ => + { + quick++; + return Task.CompletedTask; + })); + for (var minute = 22; minute <= 24; minute++) + { + clock.Set(new DateTimeOffset(2026, 10, 9, 6, minute, 0, TimeSpan.Zero)); + await scheduler.RunDueAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + } + + await WaitUntil(() => Volatile.Read(ref slow) == 1).ConfigureAwait(false); + Assert.AreEqual((1, 3), (slow, quick)); + release.SetResult(); + await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)); + await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false); + await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + Assert.AreEqual(2, slow); + var done = new List(); + while (runs.TryRead(out var run)) + { + done.Add(run!); + } + + Assert.AreEqual(2, done.Count(r => r.Name == "a-notizie" && r.Outcome == JobOutcome.Completed)); + } + [TestMethod] [TestCategory(Category.Unit)] public async Task LoopWaitsOnTheInjectedClock() diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs index 9c227a1..aa5d0a4 100644 --- a/tests/Anubis.Tests/LiveStockSupport.cs +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -111,6 +111,13 @@ internal sealed class StockRig : IAsyncDisposable Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Earnings = earnings }; } + /// The engine again, with the rules of SPEC 10.5 on single purchases. + public void UseGate(News.IEntryGate gate) + { + Engine.Dispose(); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Gate = gate }; + } + /// /// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the /// close under its 5-session average, so equity_meanrev buys and sells a few sessions later. diff --git a/tests/Anubis.Tests/NewsReviewTests.cs b/tests/Anubis.Tests/NewsReviewTests.cs new file mode 100644 index 0000000..782b230 --- /dev/null +++ b/tests/Anubis.Tests/NewsReviewTests.cs @@ -0,0 +1,273 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; + +namespace Anubis.Tests; + +/// +/// The findings of the independent review of Phase 7 (issue #61): names and keywords the text writes in other ways, +/// stories that become serious later, stories about two companies, the earnings row, the trusted label. +/// +[TestClass] +public sealed class NewsReviewTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero); + + private static InstrumentSpec Stock(string symbol, string name) => new(Venues.Alpaca, symbol, name, AssetClasses.Equity, "USD"); + + [TestMethod] + [TestCategory(Category.Unit)] + public void KeywordsAfterAnApostropheOrInQuotesAreFound() + { + Assert.AreEqual(SevereKinds.Investigation, NewsJudge.Severe("Aperta un'indagine sulla banca", null)); + Assert.AreEqual(SevereKinds.Investigation, NewsJudge.Severe("Le carte dell’inchiesta", null)); + Assert.AreEqual(SevereKinds.Bankruptcy, NewsJudge.Severe("Il rischio dell'insolvenza", null)); + Assert.AreEqual(SevereKinds.Fraud, NewsJudge.Severe("Regulator alleges 'fraud' at the lender", null)); + Assert.IsNull(NewsJudge.Severe("Life hacks for investors", null), "Whole words only, as before."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NamesAreFoundInTheWaysNewspapersWriteThem() + { + var linker = NewsLinker.Build( + [ + Stock("AAPL", "Apple Inc. Common Stock"), Stock("GS", "The Goldman Sachs Group, Inc. Common Stock"), Stock("JPM", "JPMorgan Chase & Co. Common Stock"), + Stock("MCD", "McDonald's Corporation Common Stock"), Stock("WEN", "Wendy's Company Common Stock"), Stock("META", "Meta Platforms, Inc. Class A Common Stock"), + Stock("GOOGL", "Alphabet Inc. Class A Common Stock"), Stock("GOOG", "Alphabet Inc. Class C Capital Stock"), Stock("BA", "Boeing Company (The) Common Stock"), + Stock("COIN", "Coinbase Global, Inc. Class A Common Stock"), Stock("SO", "The Southern Company Common Stock"), Stock("NVDA", "NVIDIA Corporation Common Stock"), + Stock("TGT", "Target Corporation Common Stock"), Stock("TMC", "The Metals Company Common Stock"), Stock("KO", "Coca-Cola Company (The) Common Stock"), + Stock("LLY", "Eli Lilly and Company Common Stock"), Stock("XOM", "Exxon Mobil Corporation Common Stock"), + ]); + string[] Targets(string title) => [.. linker.Link(title, null).Where(l => l.Scope == LinkScopes.Instrument).Select(l => l.Target[7..]).Order(StringComparer.Ordinal)]; + void Is(string title, params string[] expected) => CollectionAssert.AreEqual(expected, Targets(title), $"{title}: {string.Join(", ", Targets(title))}"); + + Is("L'Apple rinvia il nuovo telefono", "AAPL"); + Is("I conti dell’Apple battono le attese", "AAPL"); + Is("Un'indagine sull'Apple", "AAPL"); + Is("Apple’s suppliers rebound", "AAPL"); + Is("Apple-led rally lifts the market", "AAPL"); + Is("Nvidia-backed startup raises money", "NVDA"); + Is("Goldman Sachs cuts jobs", "GS"); + Is("Goldman Sachs' profit falls", "GS"); + Is("JPMorgan raises its outlook", "JPM"); + Is("J.P. Morgan raises its outlook", "JPM"); + Is("McDonald's recalls a burger", "MCD"); + Is("McDonald’s recalls a burger", "MCD"); + Is("Meta faces a fine", "META"); + Is("Facebook faces a fine", "META"); + Is("Google loses an appeal", "GOOG", "GOOGL"); + Is("Alphabet loses an appeal", "GOOG", "GOOGL"); + Is("Boeing delays a delivery", "BA"); + Is("Coinbase suspends withdrawals", "COIN"); + Is("Coca-Cola raises prices", "KO"); + Is("Eli Lilly halts a trial", "LLY"); + Is("Exxon Mobil cuts spending", "XOM"); + Is("Exxon cuts spending", "XOM"); + + Is("Wendy Williams talks about her show"); + Is("McDonald wins the race"); + Is("Southern states vote"); + Is("The Southern district opens a case"); + Is("Metals rally on demand from China"); + Is("Target-date funds see inflows"); + Is("why your apple-pie recipe needs more cinnamon"); + } + + /// A story that becomes serious with a later article restricts for 72 hours from that article, not from the first one. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheWindowStartsFromTheArticleThatMakesTheStorySerious() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var linker = NewsLinker.Build([MarketDataStoreTests.Okx("SOL-EUR")]); + var (trusted, _) = await SourcesAsync(test.Db, clock).ConfigureAwait(false); + var store = new NewsStore(test.Db, clock); + await store.IngestAsync(trusted, [Item("Solana exchange Alpha reports an outage of its wallets", "1", Now)], linker, _none).ConfigureAwait(false); + clock.Set(Now.AddHours(40)); + var later = await store.IngestAsync(trusted, [Item("Solana exchange Alpha reports an outage of its wallets, hacked", "2", clock.UtcNow)], linker, _none).ConfigureAwait(false); + Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_stories")).ConfigureAwait(false), $"The same story: {later}"); + + var desk = new NewsDesk(test.Db, clock); + clock.Set(Now.AddHours(111)); + var active = (await desk.RestrictionsAsync("okx:SOL-EUR", clock.UtcNow, _none).ConfigureAwait(false)).Single(); + Assert.AreEqual(Now.AddHours(40), active.From); + Assert.AreEqual(Now.AddHours(112), active.Until); + var row = (await new NewsBoard(test.Db, clock).LoadAsync(_none).ConfigureAwait(false)).Rows.Single(); + Assert.IsTrue(row.Active, row.Action); + Assert.IsEmpty(await desk.RestrictionsAsync("okx:SOL-EUR", Now.AddHours(112), _none).ConfigureAwait(false)); + } + + /// Two companies told with the same words are two stories: one's trouble never confirms nor restricts the other's. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task StoriesAboutDifferentInstrumentsAreNotOne() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var linker = NewsLinker.Build([Stock("AAPL", "Apple Inc. Common Stock"), Stock("MSFT", "Microsoft Corporation Common Stock")]); + var (trusted, other) = await SourcesAsync(test.Db, clock).ConfigureAwait(false); + var store = new NewsStore(test.Db, clock); + await store.IngestAsync(trusted, [Item("Apple beats quarterly revenue estimates on cloud demand", "1", Now)], linker, _none).ConfigureAwait(false); + await store.IngestAsync(other, + [ + Item("Microsoft beats quarterly revenue estimates on cloud demand", "2", Now), + Item("Apple beats quarterly revenue estimates on cloud demand, shares up", "3", Now), + Item("Quarterly revenue estimates on cloud demand beats", "4", Now), + ], linker, _none).ConfigureAwait(false); + + var stories = await test.Db.ReadAsync(s => s.QueryAsync( + "SELECT l.target, COUNT(DISTINCT i.id) AS n FROM news_stories st JOIN news_links l ON l.story_id = st.id JOIN news_items i ON i.story_id = st.id " + + "WHERE l.scope = 'instrument' GROUP BY st.id, l.target", r => (Target: r.Text("target"), Items: r.Number("n")))).ConfigureAwait(false); + Assert.HasCount(2, stories, string.Join(", ", stories)); + Assert.AreEqual(2, stories.Select(s => s.Target).Distinct().Count()); + Assert.AreEqual(4L, stories.Sum(s => s.Items), "An article that names no instrument still joins one of the two."); + Assert.IsTrue(stories.Single(s => s.Target == "alpaca:AAPL").Items >= 2); + } + + /// The classifier works before the database writer is taken: a slow one never holds back the engine's writes. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheClassifierNeverHoldsTheDatabaseWriter() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var (trusted, _) = await SourcesAsync(test.Db, clock).ConfigureAwait(false); + using var classifier = new BlockedClassifier(); + var ingest = Task.Run(() => new NewsStore(test.Db, clock).IngestAsync(trusted, [Item("Solana network slows", "1", Now)], NewsLinker.Build([]), _none, classifier)); + Assert.IsTrue(await classifier.Started.Task.WaitAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false)); + var write = test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_sources SET failures = 0", _none), _none); + var won = await Task.WhenAny(write, Task.Delay(TimeSpan.FromSeconds(3))).ConfigureAwait(false); + classifier.Release.Set(); + await ingest.ConfigureAwait(false); + await write.ConfigureAwait(false); + Assert.AreSame(write, won, "The write went while the classifier was still reading."); + Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items WHERE score IS NOT NULL")).ConfigureAwait(false)); + } + + /// The label of a source counts for the stories already read; the serious case shown is the first of 10.2. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheTrustedLabelAndTheSeriousCaseFollowTheRules() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var linker = NewsLinker.Build([MarketDataStoreTests.Okx("SOL-EUR")]); + var (_, untrusted) = await SourcesAsync(test.Db, clock).ConfigureAwait(false); + var store = new NewsStore(test.Db, clock); + await store.IngestAsync(untrusted, + [ + Item("Solana lender Alpha files for bankruptcy after a week of losses", "1", Now), + Item("Solana lender Alpha files for bankruptcy after a week of losses, hacked", "2", Now), + ], linker, _none).ConfigureAwait(false); + + async Task<(bool Trusted, string? Severe)> StoryAsync() => (await test.Db.ReadAsync(s => s.QueryAsync("SELECT trusted, severe FROM news_stories", + r => (r.Bool("trusted"), r.TextOrNull("severe")))).ConfigureAwait(false)).Single(); + Assert.AreEqual((false, SevereKinds.Cyberattack), await StoryAsync().ConfigureAwait(false), "The order of 10.2: the cyberattack first, not the alphabet."); + await store.SetSourceAsync(untrusted.Id, enabled: true, trusted: true, "test", _none).ConfigureAwait(false); + Assert.IsTrue((await StoryAsync().ConfigureAwait(false)).Trusted); + Assert.HasCount(1, await new NewsDesk(test.Db, clock).RestrictionsAsync("okx:SOL-EUR", Now, _none).ConfigureAwait(false)); + await store.SetSourceAsync(untrusted.Id, enabled: true, trusted: false, "test", _none).ConfigureAwait(false); + Assert.IsFalse((await StoryAsync().ConfigureAwait(false)).Trusted); + } + + /// + /// A report before the open or during the session frees the next session, one after the close or without a time + /// blocks it too (10.5, fourth row); the diary says the row only when it is in force, weekends included. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheEarningsRowStartsAndEndsWithItsSessions() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + // Friday 20 November, 17:00 in New York: the entry is on Monday, so the row reaches Thursday 26. + var clock = new ManualClock(new DateTimeOffset(2026, 11, 20, 22, 0, 0, TimeSpan.Zero)); + var catalog = new InstrumentCatalog(test.Db, clock); + string[] symbols = ["AAA", "BBB", "CCC", "DDD", "EEE"]; + await catalog.SyncAsync(Venues.Alpaca, [.. symbols.Select(s => Stock(s, s + " Corp"))], complete: false, _none).ConfigureAwait(false); + foreach (var i in await catalog.ListAsync(Venues.Alpaca, _none).ConfigureAwait(false)) + { + await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, '2026-11-16', @i, 1, @now)", + _none, ("id", Ids.NewId(clock)), ("u", Universes.Equity), ("i", i.Id), ("now", clock.UtcNow)), _none).ConfigureAwait(false); + } + + static CalendarEvent Report(string symbol, int day, int hour, string? hint) => + new(CalendarEventKinds.Earnings, "Trimestrale " + symbol, new DateTimeOffset(2026, 11, day, hour, 0, 0, TimeSpan.Zero), false, "test", "earnings:" + symbol) + { Symbol = symbol, TimeHint = hint }; + await new CalendarEventStore(test.Db, clock).UpsertAsync( + [Report("AAA", 26, 21, "amc"), Report("BBB", 27, 12, "bmo"), Report("CCC", 20, 12, "bmo"), Report("DDD", 20, 21, "amc"), Report("EEE", 20, 18, "dmh")], _none).ConfigureAwait(false); + + var desk = new NewsDesk(test.Db, clock); + var next = await desk.EarningsAsync(new DateOnly(2026, 11, 20), _none).ConfigureAwait(false); + CollectionAssert.AreEquivalent(new[] { "AAA", "BBB", "DDD" }, next.Keys.ToList(), "CCC and EEE published before today's close: the next session is free."); + + await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false); + var diary = await NewsRulesTests.DiaryAsync(test.Db).ConfigureAwait(false); + Assert.HasCount(1, diary, string.Join(" | ", diary)); + StringAssert.Contains(diary[0], "niente mean reversion su AAA"); + + clock.Set(new DateTimeOffset(2026, 11, 23, 22, 0, 0, TimeSpan.Zero)); + var off = new NewsWatcher(test.Db, clock) { EarningsActive = _ => Task.FromResult(false) }; + Assert.AreEqual(0, await off.RunOnceAsync(_none).ConfigureAwait(false), "Without a fresh calendar the strategies ignore the row, and so does the diary."); + Assert.AreEqual(1, await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false), "BBB, when its row starts."); + } + + /// A story on a held or candidate stock whose report is near is shown with importance 3 (10.2 point 4), and restricts nothing for that. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStoryOnAStockWithAReportNearIsShownWithImportanceThree() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var (jpm, gs) = (Stock("JPM", "JPMorgan Chase & Co. Common Stock"), Stock("GS", "The Goldman Sachs Group, Inc. Common Stock")); + var catalog = new InstrumentCatalog(test.Db, clock); + await catalog.SyncAsync(Venues.Alpaca, [jpm, gs], complete: false, _none).ConfigureAwait(false); + var id = (await catalog.ListAsync(Venues.Alpaca, _none).ConfigureAwait(false)).Single(i => i.Symbol == "JPM").Id; + await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, '2026-11-16', @i, 1, @now)", + _none, ("id", Ids.NewId(clock)), ("u", Universes.Equity), ("i", id), ("now", Now)), _none).ConfigureAwait(false); + foreach (var (spec, title) in new[] { (jpm, "JPMorgan opens a branch"), (gs, "Goldman opens a branch") }) + { + await NewsRulesTests.StoryAsync(test.Db, clock, spec, title, Now.AddHours(-1), 2, 0.1, "CNBC", trusted: true).ConfigureAwait(false); + await new CalendarEventStore(test.Db, clock).UpsertAsync( + [new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale", Now.AddDays(2), false, "test", "earnings:" + spec.Symbol) { Symbol = spec.Symbol, TimeHint = "bmo" }], _none) + .ConfigureAwait(false); + } + + var rows = (await new NewsBoard(test.Db, clock).LoadAsync(_none).ConfigureAwait(false)).Rows.ToDictionary(r => r.Title); + Assert.AreEqual(3, rows["JPMorgan opens a branch"].Importance); + Assert.AreEqual("Neutra, evento in arrivo", rows["JPMorgan opens a branch"].Tone); + Assert.IsFalse(rows["JPMorgan opens a branch"].Active); + Assert.AreEqual(2, rows["Goldman opens a branch"].Importance, "Neither held nor a candidate."); + Assert.IsEmpty(await new NewsDesk(test.Db, clock).RestrictionsAsync("alpaca:JPM", Now, _none).ConfigureAwait(false)); + } + + private static FeedItem Item(string title, string id, DateTimeOffset at) => + new(title, "https://www.example.test/" + id) { PublishedAt = at, Language = "en" }; + + private static async Task<(NewsSource Trusted, NewsSource Other)> SourcesAsync(Database db, IClock clock) + { + var store = new NewsStore(db, clock); + await store.EnsureDefaultsAsync(_none).ConfigureAwait(false); + var sources = await store.ListSourcesAsync(_none).ConfigureAwait(false); + return (sources.Single(s => s.Name == "CNBC"), sources.Single(s => s.Name == "Investing.com")); + } + + private sealed class BlockedClassifier : IToneClassifier, IDisposable + { + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public ManualResetEventSlim Release { get; } = new(false); + + public ToneScore Classify(string text) + { + Started.TrySetResult(true); + Release.Wait(TimeSpan.FromSeconds(30)); + return new ToneScore(0.2, 0.2, 0.6); + } + + public void Dispose() => Release.Dispose(); + } +} diff --git a/tests/Anubis.Tests/NewsRulesTests.cs b/tests/Anubis.Tests/NewsRulesTests.cs index 09ce72a..dddc545 100644 --- a/tests/Anubis.Tests/NewsRulesTests.cs +++ b/tests/Anubis.Tests/NewsRulesTests.cs @@ -306,6 +306,81 @@ public sealed class NewsRulesTests } } + /// + /// The decision of the day before, made again for the one-step comparison (SPEC 12.3), reads the same earnings: a + /// purchase left out for a report is not a difference. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheOneStepComparisonReadsTheSameEarnings() + { + var day = new DateOnly(2026, 9, 1); + await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)).ConfigureAwait(false); + await new CalendarEventStore(stocks.Rig.Db, stocks.Rig.Clock).UpsertAsync( + [new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale BBB", new DateTimeOffset(2026, 9, 3, 11, 0, 0, TimeSpan.Zero), false, "test", "earnings:BBB") + { Symbol = "BBB", TimeHint = "bmo" }], _none).ConfigureAwait(false); + var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock); + stocks.UseEarnings(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct).ConfigureAwait(false), true)); + await stocks.SessionAsync(day).ConfigureAwait(false); + await stocks.SessionAsync(day.AddDays(1)).ConfigureAwait(false); + + var checks = await stocks.Rig.QueryAsync("SELECT outcome, data FROM decisions WHERE stage = @st", r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), + ("st", DecisionStages.OneStep)).ConfigureAwait(false); + Assert.AreNotEqual(0, checks.Count); + Assert.IsTrue(checks.All(c => c.Outcome == DecisionOutcomes.Same), string.Join(" | ", checks)); + } + + /// + /// A restriction that ends before the purchase is due changes nothing and the diary is silent; one that ends while the + /// market is closed or opening sends it five minutes after the open, as every other purchase (5.5). + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task OnlyAPurchaseReallyPutOffIsSaidToBe() + { + var day = new DateOnly(2026, 9, 1); + var due = new DateTimeOffset(2026, 9, 2, 13, 35, 0, TimeSpan.Zero); + foreach (var (until, expected) in new[] { (due.AddHours(-12), due), (due.AddMinutes(-2), due), (due.AddMinutes(10), due.AddMinutes(10)) }) + { + await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)).ConfigureAwait(false); + stocks.UseGate(new FixedGate(new EntryHold(CorrectiveReasons.CalendarEvent, until, "Inflazione USA"))); + await stocks.SessionAsync(day).ConfigureAwait(false); + var planned = await stocks.Rig.QueryAsync("SELECT due_at, first_due_at FROM planned_orders WHERE side = 'buy'", r => (Due: r.Moment("due_at"), First: r.MomentOrNull("first_due_at"))) + .ConfigureAwait(false); + Assert.AreEqual(1, planned.Count); + Assert.AreEqual(expected, planned[0].Due); + Assert.AreEqual(expected > due ? due : null, planned[0].First); + var diary = await DiaryAsync(stocks.Rig.Db).ConfigureAwait(false); + Assert.AreEqual(expected > due, diary.Any(d => d.StartsWith("Ho rimandato", StringComparison.Ordinal)), string.Join(" | ", diary)); + if (expected > due) + { + Assert.IsTrue(diary.Any(d => d.StartsWith("Ho rimandato l'acquisto di BBB a mercoledì 2 settembre alle 15:45.", StringComparison.Ordinal)), string.Join(" | ", diary)); + } + } + } + + /// A restriction that ends at night sends a weekly purchase five minutes after the next open, not at the open. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task APurchaseHeldWithTheMarketClosedGoesFiveMinutesAfterTheOpen() + { + var friday = new DateOnly(2026, 9, 4); + await using var stocks = await StockRig.CreateAsync(friday, friday.AddDays(20), StrategyNames.EquityMomentum).ConfigureAwait(false); + stocks.UseGate(new FixedGate(new EntryHold(CorrectiveReasons.CalendarEvent, new DateTimeOffset(2026, 9, 7, 23, 0, 0, TimeSpan.Zero), "Inflazione USA"))); + await stocks.SessionAsync(friday).ConfigureAwait(false); + var planned = await stocks.Rig.QueryAsync("SELECT due_at FROM planned_orders WHERE side = 'buy'", r => r.Moment("due_at")).ConfigureAwait(false); + Assert.AreNotEqual(0, planned.Count); + Assert.IsTrue(planned.All(d => d == new DateTimeOffset(2026, 9, 8, 13, 35, 0, TimeSpan.Zero)), string.Join(", ", planned)); + Assert.IsTrue((await DiaryAsync(stocks.Rig.Db).ConfigureAwait(false)).Any(d => d.Contains("a martedì 8 settembre alle 15:35.", StringComparison.Ordinal))); + } + + private sealed class FixedGate(EntryHold hold) : IEntryGate + { + public Task HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(at < hold.Until ? hold : null); + + public Task KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(null); + } + /// A story linked to one instrument, with one article from the named publisher. internal static async Task StoryAsync(Database db, IClock clock, InstrumentSpec spec, string title, DateTimeOffset published, int importance, double? score, string publisher, bool trusted, int sources = 1, DateTimeOffset? seen = null) diff --git a/tests/Anubis.Tests/NewsTests.cs b/tests/Anubis.Tests/NewsTests.cs index ceba2f4..ff527a4 100644 --- a/tests/Anubis.Tests/NewsTests.cs +++ b/tests/Anubis.Tests/NewsTests.cs @@ -241,6 +241,7 @@ public sealed class NewsTests }); http.On(u => u.Host != "search.cnbc.com", _ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); var collector = new NewsCollector(http.Client(), test.Db, clock) { Pause = TimeSpan.Zero }; + Assert.IsTrue(collector.Job().Beside, "The round of the news never delays the engine and the risk check."); await collector.RunOnceAsync(CancellationToken.None).ConfigureAwait(false); Assert.HasCount(NewsStore.Defaults.Count, http.Requests, "One request per source.");