using System.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Data;
///
/// Spec §4.6: the library must stay fluid with 200,000 entries. The class runs alone, after the parallel tests, so the
/// timings do not compete with the other workers and the long fill does not load them (#46).
///
[TestClass]
[DoNotParallelize]
public sealed class LibraryScaleTests
{
private const int Entries = 200_000;
private const int Accounts = 40;
// Bounds per class of query, about 5-8× the values measured on an unloaded machine (docs/decisioni.md, #46).
// Index seeks and windows measure 2-30 ms; aggregates over the whole library or an account 60-220 ms.
private const double IndexBoundMs = 250;
private const double AggregateBoundMs = 1500;
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(1_200_000, CooperativeCancellation = true)] // only a hang guard: under heavy load the fill took 7.5 minutes
public async Task LibraryQueriesStayFastWith200000Entries()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var accountIds = new List();
for (var a = 0; a < Accounts; a++)
{
accountIds.Add((await db.Accounts.AddAsync(Make.Account($"account{a:00}.demo", $"{1000 + a}"), ct)).Id);
}
var words = new[] { "mare", "montagna", "città", "tramonto", "cena", "amici", "viaggio", "festa", "libro", "caffè" };
var random = new Random(7);
var start = new DateTimeOffset(2016, 1, 1, 0, 0, 0, TimeSpan.Zero);
var span = (long)(new DateTimeOffset(2026, 10, 13, 0, 0, 0, TimeSpan.Zero) - start).TotalSeconds;
var fill = Stopwatch.StartNew();
for (var batch = 0; batch < Entries / 5000; batch++)
{
var items = new List(5000);
for (var i = 0; i < 5000; i++)
{
var n = (batch * 5000) + i;
var kind = (n % 10) switch { 0 or 1 => EntryKind.Story, 2 => EntryKind.Highlight, 3 => EntryKind.Tagged, _ => EntryKind.Post };
var caption = string.Join(' ', Enumerable.Range(0, 12).Select(_ => words[random.Next(words.Length)])) + (n == 123_456 ? " parolarara" : string.Empty);
var media = new List { Make.Stored(n % 7 == 0 ? Make.Video() : Make.Photo() with { PerceptualHash = (ulong)n * 0x9E3779B97F4A7C15UL }, Make.Sha(n + 1), $"x/{n}.jpg") };
if (n % 5 == 0)
{
media.Add(Make.Stored(Make.Photo(2), Make.Sha(n + 10_000_000), $"x/{n}_2.jpg"));
}
items.Add(new NewEntry(
Make.Entry(accountIds[n % Accounts], $"id{n}", start.AddSeconds(random.NextInt64(span)), kind, caption) with { Provenance = n % 13 == 0 ? Provenance.Imported : Provenance.Downloaded },
media));
}
await db.Entries.AddManyAsync(items, ct);
}
fill.Stop();
TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s");
// Plans differ with and without ANALYZE statistics: both must be fast.
// The fill stays outside the timings.
await MeasureAll(db, accountIds, "senza statistiche", ct);
await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
await MeasureAll(db, accountIds, "con ANALYZE", ct);
}
private async Task MeasureAll(FebeDatabase db, List accountIds, string label, CancellationToken ct)
{
var times = new List<(string Name, double Bound, Timing