From f86c794fa4d9ac7229125c281900e012d4c6c2c9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 15:23:55 +0200 Subject: [PATCH 1/5] Il motore chiude lo storico anche se la corsa finisce con un segnale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quando il cammino dello Storico arriva in fondo, la ricetta segna lo storico come completato e lo dice al motore (BackfillFinished). Il motore però chiudeva lo storico (stato «Aggiornato» o «In pausa» e riga «Storico completato») solo se la corsa finiva «Completata»: un segnale o un'interruzione arrivati subito dopo l'ultima pagina lasciavano l'account «Storico in corso» per sempre, senza che nessuno lo riprendesse. Ora la chiusura sta in un solo punto (FinishBackfillAsync) e scatta ogni volta che il cammino è arrivato in fondo, comunque sia finita la corsa. Prova nuova per il segnale e per l'interruzione. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Engine/SessionComposer.cs | 55 ++++++++++------- .../Engine/BackfillCompletedTests.cs | 59 +++++++++++++++++++ 2 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 tests/Febe.Tests/Engine/BackfillCompletedTests.cs diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index df2017e..9d62a89 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -771,6 +771,14 @@ internal sealed class SessionComposer var now = Clock.Now; var kind = request.Kind; var writes = new List(); + + // The walk reached the beginning of the profile: the history is complete however the run ended (a signal or a + // cancellation can come right after the last page was stored, and that account would not be walked again). + if (kind == RecipeKind.Backfill && outcome.BackfillFinished && account is not null) + { + await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); + } + switch (outcome.Status) { case RecipeStatus.Completed: @@ -947,27 +955,8 @@ internal sealed class SessionComposer break; } - case RecipeKind.Backfill when outcome.BackfillFinished: - { - var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; - await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); - var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; - await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); - var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); - var tail = fresh.KeepUpdated - ? " Da ora lo tengo aggiornato." - : " «Tieni aggiornato» è spento: l'account resta in pausa."; - await _s.Events.WriteAsync( - EventSeverity.Success, - EngineEventCodes.BackfillCompleted, - $"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}", - account.Id, - state.Context.SessionId, - ct).ConfigureAwait(false); - break; - } - - case RecipeKind.Backfill: + // A history completed: FinishBackfillAsync, from ApplyOutcomeAsync. + case RecipeKind.Backfill when !outcome.BackfillFinished: if (contactable) { // Behind the other accounts «Storico in corso»: they alternate. @@ -980,6 +969,30 @@ internal sealed class SessionComposer } } + /// + /// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one + /// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their + /// own for it. + /// + private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) + { + var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; + await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); + var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; + await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); + var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); + var tail = fresh.KeepUpdated + ? " Da ora lo tengo aggiornato." + : " «Tieni aggiornato» è spento: l'account resta in pausa."; + await _s.Events.WriteAsync( + EventSeverity.Success, + EngineEventCodes.BackfillCompleted, + $"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}", + account.Id, + state.Context.SessionId, + ct).ConfigureAwait(false); + } + private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct) { await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false); diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs new file mode 100644 index 0000000..50b191b --- /dev/null +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -0,0 +1,59 @@ +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; +using Febe.Tests.Alerts.Support; +using Febe.Tests.Engine.Support; + +namespace Febe.Tests.Engine; + +/// +/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers, +/// also for the runs that end otherwise right after the last page. +/// +[TestClass] +public sealed class BackfillCompletedTests +{ + private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); + + /// + /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the + /// run ended: the history is complete all the same and keeps its line (it would never be walked again). + /// + [TestMethod] + [DataRow(RecipeStatus.StoppedBySignal)] + [DataRow(RecipeStatus.Cancelled)] + public async Task AHistoryCompletedRightBeforeARunEndsOtherwiseKeepsItsLine(RecipeStatus status) + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30); + await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false }); + var runner = new ScriptedRunner(engine.Governor, engine.Clock); + var backfills = 0; + runner.Before = async r => + { + if (r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && ++backfills == 1) + { + // What the recipe stores when the walk meets the end of the list. + await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + } + }; + runner.Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && backfills == 1 + ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } + : null; + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(2)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + Assert.AreEqual(1, backfills, "Never walked again."); + var finished = await engine.Db.Accounts.GetAsync(account.Id); + Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused."); + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines); + Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message); + Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); + } +} From afbd0b4a1ad8974e7ef02cb8be3fc04954d22eda Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 15:30:24 +0200 Subject: [PATCH 2/5] Storico completato: una riga sola, quella del motore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provando Febe per Windows contro il sito di prova, alla fine dello storico di marta.prova la sezione «Avvisi» di Attività mostrava due righe per lo stesso fatto, entrambe «storico-completato»: quella del motore («Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.») e una della ricetta Storico («Storico di marta.prova completato.», senza @ e senza numeri). La notifica di Windows partiva una volta sola, ma con il testo corto, perché la riga della ricetta arrivava prima. Resta solo la riga del motore, che è anche quella che cambia lo stato dell'account e che usano la dimostrazione e la simulazione. La ricetta segna lo storico come completato e lo dice al motore, senza scrivere altro. Prova nuova con le ricette vere sul sito finto sotto il motore vero: una riga negli Avvisi, una notifica e un messaggio Telegram, con il testo intero. Riga in docs/decisioni.md. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + .../Recipes/RecipeRunner.Profile.cs | 3 +- .../Engine/BackfillCompletedTests.cs | 86 ++++++++++++++++++- 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..75b276e 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-13 | Prove dell'interfaccia in un Chromium senza finestra guidato col protocollo DevTools diretto (`UiBrowser`, solo 127.0.0.1), inconcludenti senza Chromium | Come `tools/schermate`; il client CDP di Febe accetta solo letture | | 2026-10-14 | Revisione avversaria di tutto il codice (7 aree, ogni rilievo verificato da un secondo revisore indipendente): 54 rilievi confermati e corretti con prove di regressione, 2 smentiti, 3 incerti corretti dove il rimedio era sicuro | §14, regola 14: resoconti onesti | | 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano | +| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe in «Avvisi» per lo stesso storico (@marta.prova, 14:31) e la notifica col testo corto, partito per primo; con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index dbdf9c5..c7c577b 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -394,9 +394,10 @@ public sealed partial class RecipeRunner run.Finished = true; if (walk.IsGrid) { + // «Storico completato» in Attività, and the new state of the account, are the engine's: one line per + // history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished). await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false); - await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); } else { diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 50b191b..7aab63d 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -1,22 +1,71 @@ using Febe.Core.Abstractions; using Febe.Core.Alerts; +using Febe.Core.Collection; +using Febe.Core.Collection.Readers; +using Febe.Core.Collection.Recipes; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; using Febe.Tests.Alerts.Support; +using Febe.Tests.Collection.Support; using Febe.Tests.Engine.Support; +using Febe.Web.Api; namespace Febe.Tests.Engine; /// -/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers, -/// also for the runs that end otherwise right after the last page. +/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers: +/// the real recipes on the scripted site (no browser) under the real engine, and the runs that end otherwise right +/// after the last page. /// [TestClass] public sealed class BackfillCompletedTests { private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); + /// Found testing Febe for Windows on the test site: two lines in «Avvisi» for one history, at 14:31. + [TestMethod] + public async Task AHistoryCompletedByTheRecipesIsOneLineOfAvvisiWithItsNumbersAndOneNotification() + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var (runner, site) = RealRecipes(engine); + var marta = site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false }); + marta.Posts.AddRange(ScriptedBed.Posts(0, 18, Morning.AddDays(-30))); + var account = await AddBackfillingAsync(engine, marta, postCount: 18); + + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(2)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + const string Expected = "Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato."; + var done = await engine.Db.Accounts.GetAsync(account.Id); + Assert.IsNotNull(done!.BackfillCompletedAt, "The history reached the beginning of the profile."); + Assert.AreEqual(AccountState.UpToDate, done.State); + Assert.HasCount(18, await engine.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })); + + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines, "One line for one history: " + string.Join(" | ", lines.Select(e => e.Message))); + Assert.AreEqual(Expected, lines[0].Message); + Assert.AreEqual(EventSeverity.Success, lines[0].Severity); + Assert.AreEqual(account.Id, lines[0].AccountId); + Assert.IsNotNull(lines[0].SessionId); + + // The «Avvisi» list of Attività. + var alerts = (await ActivityApi.AlertsAsync(engine.Db, engine.Clock, CancellationToken.None)).Items.Where(i => i.Kind == "backfillDone").ToList(); + Assert.HasCount(1, alerts); + Assert.AreEqual(Expected, alerts[0].Message); + + // One Windows notification and one Telegram message, with the same full text. + var notification = bed.Shell.Notifications.Single(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)); + Assert.AreEqual(Expected, notification.Message); + var telegram = bed.Telegram.Requests.Where(r => r.Text.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList(); + Assert.HasCount(1, telegram); + Assert.AreEqual("Febe · Storico completato\n" + Expected, telegram[0].Text); + Assert.HasCount(1, bed.Outcomes.Where(o => o.Alert.Kind == AlertKind.BackfillDone), "Nothing held back as a repeat either."); + } + /// /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the /// run ended: the history is complete all the same and keeps its line (it would never be walked again). @@ -56,4 +105,37 @@ public sealed class BackfillCompletedTests Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message); Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); } + + /// The real recipes over the scripted site, on the engine's database, clock, Governor and breaker. + private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine) + { + var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), engine.Clock); + var site = new ScriptedSite(capture, engine.Clock); + var runner = new RecipeRunner(new RecipeEnvironment + { + Driver = site, + Capture = capture, + Governor = engine.Governor, + Budget = engine.Governor, + DataBudget = engine.Governor, + Signals = new SignalDetector(SignalRules.LoadTestSite(), engine.Breaker, engine.Clock), + Storage = engine.Db, + SiteMap = SiteMap.LoadTestSite(), + Clock = engine.Clock, + Random = new SeededRandom(7), + Breaker = engine.Breaker, + }); + return (runner, site); + } + + /// An account «Storico in corso» for a scripted account: posts only, so that a visit is the profile check. + private static Task AddBackfillingAsync(EngineTestBed engine, ScriptedAccount scripted, int postCount) => + engine.Db.Accounts.AddAsync(Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with + { + InstagramId = scripted.Id, + IsFollowed = scripted.Followed, + State = AccountState.Backfilling, + ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos, + PostCount = postCount, + }); } From 9d959f910b4ba5a1c3a14b565eb72a0be400ca2c Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:00:04 +0200 Subject: [PATCH 3/5] Storico chiuso dal controllo del profilo: il motore lo chiude subito, con la sua riga MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Se un profilo sta tutto nella prima pagina, il controllo del profilo segnava lo storico come completato ma non cambiava lo stato e non scriveva righe. Dalla sessione dopo l'account usciva dai candidati dello Storico, quindi nessuno lo chiudeva più: restava «Storico in corso» per sempre, senza riga e senza avviso. Con due account in «Storico in corso» succedeva sempre (rilievo F1 della revisione). - Il controllo del profilo lo dice al motore con BackfillFinished, solo per un account «Storico in corso»: chi tiene solo i post nuovi non ha uno storico da annunciare. - Il motore chiude lo storico anche dopo il controllo del profilo, con la stessa FinishBackfillAsync, e prosegue con l'account aggiornato. - La fase dello Storico rilegge gli account invece di usare quelli di inizio sessione: altrimenti tornava a scorrere lo storico appena chiuso e scriveva una seconda riga. - A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato (Febe fermata a metà, o lasciati così dalla 0.1.0). Co-Authored-By: Claude Opus 5.5 --- .../Recipes/RecipeRunner.Profile.cs | 4 + src/Febe.Core/Engine/Contracts.cs | 5 +- src/Febe.Core/Engine/SessionComposer.cs | 53 +++++++++-- .../Engine/BackfillCompletedTests.cs | 90 +++++++++++++++++++ 4 files changed, 142 insertions(+), 10 deletions(-) diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index c7c577b..414ed97 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -184,7 +184,11 @@ public sealed partial class RecipeRunner } else if (page?.HasMore == false) { + // The whole profile is on the first page, saved just now. For an account «Storico in corso» its history + // is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that + // keeps only the new posts had no history to announce. await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); + run.Finished = account.State == AccountState.Backfilling; } } else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null)) diff --git a/src/Febe.Core/Engine/Contracts.cs b/src/Febe.Core/Engine/Contracts.cs index 7efcf6b..fffe4ba 100644 --- a/src/Febe.Core/Engine/Contracts.cs +++ b/src/Febe.Core/Engine/Contracts.cs @@ -89,7 +89,10 @@ public sealed record RecipeOutcome( /// Accounts where the sweep saw new posts (FollowingSweep). public IReadOnlyList AccountsWithNewPosts { get; init; } = []; - /// For Backfill: true when the beginning of the profile has been reached. + /// + /// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the + /// whole profile of an account «Storico in corso» on its first page (its history is complete as well). + /// public bool BackfillFinished { get; init; } } diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index 9d62a89..e736465 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -51,6 +51,7 @@ internal sealed class SessionComposer public async Task RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct) { var state = new SessionState(context); + await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false); var accounts = await SyncQueueAsync(ct).ConfigureAwait(false); if (outsideWindowTask is not null) @@ -145,12 +146,41 @@ internal sealed class SessionComposer // 5. A few pages of history on one account. if (!light && !Over(state, ct)) { - await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false); + await RunBackfillAsync(state, ct).ConfigureAwait(false); } return state.Summary(); } + /// + /// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded + /// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with + /// their line (); nothing towards the site. + /// + private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct) + { + var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)) + .Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null) + .ToList(); + if (complete.Count == 0) + { + return; + } + + await _queueGate.WaitAsync(ct).ConfigureAwait(false); + try + { + foreach (var account in complete) + { + await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false); + } + } + finally + { + _queueGate.Release(); + } + } + /// /// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for /// every contactable account, a look at each highlight collection on its profile, a backfill task for every account @@ -568,14 +598,16 @@ internal sealed class SessionComposer /// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its /// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3). /// - private async Task RunBackfillAsync(Dictionary accounts, SessionState state, CancellationToken ct) + private async Task RunBackfillAsync(SessionState state, CancellationToken ct) { if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage)) { return; } - var candidates = accounts.Values + // Read again, not taken from the start of the session: a profile check of this session may have completed a + // history already (its line is written), and that account is not walked again. + var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)) .Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a)) .ToList(); if (candidates.Count == 0) @@ -772,11 +804,12 @@ internal sealed class SessionComposer var kind = request.Kind; var writes = new List(); - // The walk reached the beginning of the profile: the history is complete however the run ended (a signal or a - // cancellation can come right after the last page was stored, and that account would not be walked again). - if (kind == RecipeKind.Backfill && outcome.BackfillFinished && account is not null) + // The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or + // a cancellation can come right after the last page was stored, and that account would not be walked again), + // or a profile check that found the whole profile on its first page. What follows sees the account as it is now. + if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null) { - await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); + account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); } switch (outcome.Status) @@ -972,9 +1005,10 @@ internal sealed class SessionComposer /// /// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one /// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their - /// own for it. + /// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account + /// as it is now. /// - private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) + private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) { var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); @@ -991,6 +1025,7 @@ internal sealed class SessionComposer account.Id, state.Context.SessionId, ct).ConfigureAwait(false); + return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh; } private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct) diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 7aab63d..3eedbd5 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -106,6 +106,96 @@ public sealed class BackfillCompletedTests Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); } + /// + /// A profile that fits on its first page: the profile check completes its history. When the walk of the session + /// went to another account «Storico in corso», the small one stayed so for ever, with no line and no alert (review + /// F1). Added first, the small one is the walk's next pick in that very session: it must not get a second line. + /// An account that keeps only the new posts has no history to announce. + /// + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task AHistoryCompletedByTheProfileCheckIsClosedAtOnceWithOneLine(bool smallFirst) + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var (runner, site) = RealRecipes(engine); + var big = site.Add(new ScriptedAccount("3003", "grande.prova") { Followed = false }); + big.Posts.AddRange(ScriptedBed.Posts(0, 400, Morning.AddDays(-30), prefix: "g")); + var small = site.Add(new ScriptedAccount("4004", "piccolo.prova") { Followed = false }); + small.Posts.AddRange(ScriptedBed.Posts(0, 5, Morning.AddDays(-30), prefix: "s")); + var news = site.Add(new ScriptedAccount("5005", "nuovi.prova") { Followed = false }); + news.Posts.AddRange(ScriptedBed.Posts(0, 3, Morning.AddDays(-30), prefix: "n")); + + // Among the accounts «Storico in corso» the walk takes the lowest id first. + Account smallAccount; + if (smallFirst) + { + smallAccount = await AddBackfillingAsync(engine, small, postCount: 5); + await AddBackfillingAsync(engine, big, postCount: 400); + } + else + { + await AddBackfillingAsync(engine, big, postCount: 400); + smallAccount = await AddBackfillingAsync(engine, small, postCount: 5); + } + + var newsAccount = await engine.Db.Accounts.AddAsync(Account.Create(news.Username, StartingPoint.OnlyNewFromToday, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with + { + InstagramId = news.Id, + IsFollowed = news.Followed, + ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos, + PostCount = 3, + }); + Assert.AreEqual(AccountState.UpToDate, newsAccount.State); + + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(4)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + var all = string.Join(" | ", lines.Select(e => e.Message)); + var done = await engine.Db.Accounts.GetAsync(smallAccount.Id); + Assert.IsNotNull(done!.BackfillCompletedAt, "The whole profile is on its first page."); + Assert.AreEqual(AccountState.UpToDate, done.State, all); + const string Expected = "Storico di @piccolo.prova completato: 5 post in libreria. Da ora lo tengo aggiornato."; + Assert.HasCount(1, lines.Where(e => e.AccountId == smallAccount.Id).ToList(), all); + Assert.AreEqual(Expected, lines.Single(e => e.AccountId == smallAccount.Id).Message); + Assert.AreEqual(1, bed.Shell.Notifications.Count(n => n.Message == Expected)); + + Assert.IsFalse(lines.Any(e => e.AccountId == newsAccount.Id), "«Solo i nuovi»: no history. " + all); + Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(newsAccount.Id))!.State); + Assert.IsTrue(lines.GroupBy(e => e.AccountId).All(g => g.Count() == 1), "One line per history: " + all); + } + + /// + /// An account «Storico in corso» whose history is already complete (a profile check closed it and Febe stopped + /// before recording the outcome, or a version that left it so): closed when the next session starts, with its + /// line, without walking anything. + /// + [TestMethod] + public async Task AnAccountLeftStoricoInCorsoWithItsHistoryCompleteIsClosedWhenASessionStarts() + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var account = await engine.AddAccountAsync("anna.prova", followed: true, state: AccountState.Backfilling, postCount: 7); + await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + var runner = new ScriptedRunner(engine.Governor, engine.Clock); + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(1)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(account.Id))!.State); + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines); + Assert.AreEqual("Storico di @anna.prova completato: 0 post in libreria. Da ora lo tengo aggiornato.", lines[0].Message); + Assert.IsNotNull(lines[0].SessionId); + Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill), "Nothing left to walk."); + Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); + } + /// The real recipes over the scripted site, on the engine's database, clock, Governor and breaker. private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine) { From 9ce61d26cedc73fc4cbfa6e7bf9a023bc4cc42ad Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:02:23 +0200 Subject: [PATCH 4/5] =?UTF-8?q?Storico=20chiuso:=20la=20Coda=20non=20mostr?= =?UTF-8?q?a=20pi=C3=B9=20uno=20=C2=ABStorico=C2=BB=20da=20fare=20per=20qu?= =?UTF-8?q?ell'account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quando lo storico si chiudeva con una corsa finita per un segnale o un'interruzione, il compito dello Storico tornava in coda come «Fermata da un segnale» o «Interrotta». Fino alla sessione dopo (dopo una verifica, fino a «Riprendi») la Coda mostrava uno Storico da fare per un account già «Aggiornato» o «In pausa». Lo stesso accadeva con lo storico chiuso dal controllo del profilo, e per un account rimasto in pausa restavano in coda anche i suoi controlli (rilievo F3 della revisione). - La corsa dello Storico arrivata in fondo chiude il suo compito anche se poi si è fermata. - FinishBackfillAsync toglie dalla coda lo Storico dell'account e, se l'account resta in pausa, tutto ciò che era pianificato per lui, come farebbe la sessione dopo. I comandi di Alberto restano. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Engine/SessionComposer.cs | 20 +++++++- .../Engine/BackfillCompletedTests.cs | 49 ++++++++++++++----- 2 files changed, 54 insertions(+), 15 deletions(-) diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index e736465..cd18075 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -839,7 +839,12 @@ internal sealed class SessionComposer case RecipeStatus.StoppedBySignal: case RecipeStatus.Cancelled: - if (task is not null) + if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished) + { + // The walk got to the end before the run stopped: nothing to take up again (closed above). + writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct)); + } + else if (task is not null) { await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false); } @@ -1014,7 +1019,18 @@ internal sealed class SessionComposer await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); - var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); + + // The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned + // for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome. + foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false)) + { + if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill)) + { + await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false); + } + } + + var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); var tail = fresh.KeepUpdated ? " Da ora lo tengo aggiornato." : " «Tieni aggiornato» è spento: l'account resta in pausa."; diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 3eedbd5..2973ee0 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -67,37 +67,60 @@ public sealed class BackfillCompletedTests } /// - /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the - /// run ended: the history is complete all the same and keeps its line (it would never be walked again). + /// A run that completes the history: the walk reached the beginning of the profile and stored it, then a signal or + /// a cancellation changed how the run ended; or a profile check found the whole profile on its first page. The + /// history is closed with its line (it would never be walked again), and right after that run the Coda shows + /// nothing planned for the account, now paused: no «Storico» put back in the queue (review F3). /// [TestMethod] - [DataRow(RecipeStatus.StoppedBySignal)] - [DataRow(RecipeStatus.Cancelled)] - public async Task AHistoryCompletedRightBeforeARunEndsOtherwiseKeepsItsLine(RecipeStatus status) + [DataRow(RecipeKind.Backfill, RecipeStatus.StoppedBySignal)] + [DataRow(RecipeKind.Backfill, RecipeStatus.Cancelled)] + [DataRow(RecipeKind.ProfileCheck, RecipeStatus.Completed)] + public async Task AHistoryCompletedByARunIsClosedWithItsLineAndLeavesNothingInTheQueue(RecipeKind kind, RecipeStatus status) { await using var bed = await AlertBed.CreateAsync(start: Morning); var engine = bed.Engine; var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30); await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false }); var runner = new ScriptedRunner(engine.Governor, engine.Clock); - var backfills = 0; + RecipeRequest? closing = null; + var walksAfter = 0; runner.Before = async r => { - if (r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && ++backfills == 1) + if (r.AccountId != account.Id) { - // What the recipe stores when the walk meets the end of the list. + return; + } + + if (closing is not null) + { + walksAfter += r.Kind == RecipeKind.Backfill ? 1 : 0; + } + else if (r.Kind == kind) + { + // What the recipe stores: the walk met the end of the list, or the whole profile is on its first page. await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + closing = r; } }; - runner.Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && backfills == 1 - ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } - : null; + runner.Script = r => ReferenceEquals(r, closing) ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } : null; engine.Start(runner); - await engine.RunUntilAsync(Morning.AddDays(2)); + var end = Morning.AddDays(2); + while (closing is null && engine.Clock.Now < end) + { + await engine.RunForAsync(TimeSpan.FromMinutes(1)); + } + + // Right after that run, before the next session tidies the queue. + Assert.IsNotNull(closing); + var queued = (await engine.Db.Tasks.ListPendingAsync(1000)).Where(t => t.AccountId == account.Id).ToList(); + Assert.HasCount(0, queued, "Planned for a paused account: " + string.Join(", ", queued.Select(t => $"{t.Kind} «{t.LastError}»"))); + + await engine.RunUntilAsync(end); await engine.StopAsync(); await bed.Alerts.FlushAsync(); - Assert.AreEqual(1, backfills, "Never walked again."); + Assert.AreEqual(0, walksAfter, "Never walked again."); var finished = await engine.Db.Accounts.GetAsync(account.Id); Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused."); var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); From 3bcbbbf7c10bdb286b88f6335b8912d4bf5574da Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:03:08 +0200 Subject: [PATCH 5/5] Decisioni: corretto il motivo della riga doppia, aggiunte le due scelte nuove MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La riga del 20 ottobre diceva che la notifica partiva col testo corto della ricetta. Era falso: la riga della ricetta (CollectionWriter.EventAsync) va direttamente nell'archivio, non passa da EngineEvents e AlertService non la vede; la notifica e il messaggio Telegram avevano già il testo intero del motore. Il doppione riguardava solo la cronologia e gli «Avvisi» (rilievo F2 della revisione). Il messaggio del commit afbd0b4 ripete la stessa idea sbagliata: vale questa riga. Aggiunte due righe: lo storico completato dal controllo del profilo lo chiude il motore, anche a inizio sessione (F1); quando chiude uno storico il motore toglie subito dalla coda il suo Storico (F3). Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 75b276e..40ca1a3 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,4 +226,6 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-13 | Prove dell'interfaccia in un Chromium senza finestra guidato col protocollo DevTools diretto (`UiBrowser`, solo 127.0.0.1), inconcludenti senza Chromium | Come `tools/schermate`; il client CDP di Febe accetta solo letture | | 2026-10-14 | Revisione avversaria di tutto il codice (7 aree, ogni rilievo verificato da un secondo revisore indipendente): 54 rilievi confermati e corretti con prove di regressione, 2 smentiti, 3 incerti corretti dove il rimedio era sicuro | §14, regola 14: resoconti onesti | | 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano | -| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe in «Avvisi» per lo stesso storico (@marta.prova, 14:31) e la notifica col testo corto, partito per primo; con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | +| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | +| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso | +| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |