using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
/// Why each session stopped, as the engine tells the diagnostic report (issue #39).
[TestClass]
public sealed class SessionStopCauseTests
{
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
[TestMethod]
public async Task SessionsThatRunTheirCourseEndByTimeByWorkOrByBudgets()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var diagnostics = Record(bed);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
await bed.AddAccountAsync("due.demo", followed: true);
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunUntilAsync(Morning.AddDays(1));
var sessions = await bed.Db.Sessions.ListAsync(Morning, bed.Clock.Now);
var traces = diagnostics.Recent.Where(t => t.Session is not null).ToList();
Assert.IsTrue(traces.Count > 5, $"{traces.Count} traces");
CollectionAssert.AreEquivalent(
sessions.Where(s => s.EndedAt is not null).Select(s => (long?)s.Id).ToList(),
traces.Select(t => t.Session).ToList(),
"One trace for every finished session.");
foreach (var trace in traces)
{
Assert.AreEqual(SessionOutcome.Completed, trace.Outcome);
Assert.IsTrue(trace.StopCause is SessionStopCause.PlannedEnd or SessionStopCause.WorkDone or SessionStopCause.BudgetsExhausted, trace.StopCause.ToString());
Assert.IsNull(trace.StoppedBy);
Assert.IsFalse(trace.InProgress);
Assert.IsTrue(trace.End >= trace.Start);
Assert.IsTrue(trace.Recipes.Count == 0, "The scripted runner bypasses the recipe runner.");
}
Assert.AreEqual(0, diagnostics.Faults);
}
[TestMethod]
public async Task AThrottleEndsTheSessionWithTheBreakerOpen()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var diagnostics = Record(bed);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var throttled = false;
runner.AfterGrant = r =>
{
if (!throttled && r.Kind == RecipeKind.ProfileCheck)
{
throttled = true;
bed.Breaker.Report(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
}
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddHours(12));
Assert.IsTrue(throttled);
var trace = diagnostics.Recent.Single(t => t.Outcome == SessionOutcome.Throttled);
Assert.AreEqual(SessionStopCause.BreakerOpen, trace.StopCause);
Assert.AreEqual("http-429", trace.Signals.Single().Code, "The signal that opened the breaker, reported straight to it.");
}
[TestMethod]
public async Task ALogoutDuringASessionSaysItsCodeInTheTrace()
{
// The connection finds the session cookie gone and tells the breaker directly: the detector never sees it.
var session = default(long?);
var trace = await StopHeldSessionTraceAsync(async (bed, _, _) =>
{
session = bed.Runtime.CurrentSession?.SessionId;
bed.Breaker.Report(new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null, bed.Clock.Now));
// The engine closes the session from a task of its own (the breaker's event may come from a capture thread).
var waited = System.Diagnostics.Stopwatch.StartNew();
while (bed.Runtime.CurrentSession is not null && waited.Elapsed < TimeSpan.FromSeconds(10))
{
await Task.Delay(10);
}
});
Assert.IsNotNull(session);
Assert.AreEqual(SessionStopCause.BreakerOpen, trace.StopCause);
var signal = trace.Signals.Single();
Assert.AreEqual(SignalLevel.Disconnect, signal.Level);
Assert.AreEqual(SignalRules.SessionCookieMissingCode, signal.Code, "A logout does not look like any other stop.");
}
[TestMethod]
public async Task AMissingTargetStopsTheSessionEarlyAndSaysWhichStatus()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var diagnostics = Record(bed);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var missed = false;
runner.Script = r =>
{
if (!missed && r.Kind == RecipeKind.ProfileCheck)
{
missed = true;
return new RecipeOutcome(RecipeStatus.TargetNotFound, 1, 0);
}
return null;
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddHours(12));
Assert.IsTrue(missed);
var trace = diagnostics.Recent.Single(t => t.StoppedBy is not null);
Assert.AreEqual(SessionStopCause.StoppedEarly, trace.StopCause);
Assert.AreEqual(RecipeStatus.TargetNotFound, trace.StoppedBy);
}
[TestMethod]
public async Task ThePauseAlbertoAtTheBrowserAndTheShutdownEndTheSessionInProgress()
{
Assert.AreEqual(SessionStopCause.Paused, await StopHeldSessionAsync((bed, host, _) => host.PauseAsync()));
Assert.AreEqual(SessionStopCause.UserDriving, await StopHeldSessionAsync((bed, host, drive) =>
{
drive();
host.NotifyUserDrivingChanged();
return Task.CompletedTask;
}));
Assert.AreEqual(SessionStopCause.Shutdown, await StopHeldSessionAsync((bed, _, _) => bed.StopAsync()));
}
[TestMethod]
public async Task AShutdownDuringARealRecipeIsAShutdownToo()
{
// The real recipe runner does not let the cancellation out: it answers «Cancelled», and the composer ends as
// if a recipe had stopped the session. The pause still says «Paused».
Assert.AreEqual(SessionStopCause.Shutdown, await StopHeldSessionAsync((bed, _, _) => bed.StopAsync(), answersCancelled: true));
Assert.AreEqual(SessionStopCause.Paused, await StopHeldSessionAsync((bed, host, _) => host.PauseAsync(), answersCancelled: true));
}
/// Starts a session whose first recipe waits an hour, stops it with , returns its cause.
private static async Task StopHeldSessionAsync(Func stop, bool answersCancelled = false) =>
(await StopHeldSessionTraceAsync(stop, answersCancelled)).StopCause;
/// The same as , returning the whole trace.
private static async Task StopHeldSessionTraceAsync(Func stop, bool answersCancelled = false)
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Noon, userIsDriving: () => driving);
var diagnostics = Record(bed);
await bed.AddAccountAsync("uno.demo", followed: true);
var runner = new HoldingRunner(new ScriptedRunner(bed.Governor, bed.Clock), bed.Clock, answersCancelled);
var host = bed.Start(runner);
await bed.RunForAsync(TimeSpan.FromMinutes(20));
Assert.IsTrue(runner.Holding, "A session is in progress.");
var session = bed.Runtime.CurrentSession?.SessionId;
Assert.IsNotNull(session);
await stop(bed, host, () => driving = true);
await bed.RunForAsync(TimeSpan.FromMinutes(1));
await bed.StopAsync();
var trace = diagnostics.Recent.Single(t => t.Session == session);
Assert.IsFalse(trace.InProgress);
Assert.IsTrue(trace.End - trace.Start < TimeSpan.FromMinutes(30), "It ended when it was stopped, not after the hour.");
return trace;
}
private static CollectionDiagnostics Record(EngineTestBed bed)
{
var diagnostics = new CollectionDiagnostics(bed.Clock, () => bed.Runtime.CurrentSession?.SessionId);
bed.Services.Diagnostics = diagnostics;
return diagnostics;
}
///
/// The first recipe waits an hour of virtual time (until cancelled); the others run as scripted. With
/// a cancellation is answered «Cancelled», as RecipeRunner does.
///
private sealed class HoldingRunner(ScriptedRunner inner, IClock clock, bool answersCancelled = false) : IRecipeRunner
{
private int _held;
public bool Holding { get; private set; }
public async Task RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct)
{
if (Interlocked.Exchange(ref _held, 1) == 0)
{
Holding = true;
try
{
await clock.Delay(TimeSpan.FromHours(1), ct);
}
catch (OperationCanceledException) when (answersCancelled)
{
return new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Ricetta interrotta.");
}
}
return await inner.RunAsync(request, session, ct);
}
public Task RestAsync(CancellationToken ct) => inner.RestAsync(ct);
}
}