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) }; +}