- /api/library/days in «Tutte le foto» faceva due volte il passaggio su tutta la tabella media a ogni aggiornamento del mosaico: il totale dei file è ora la somma dei giorni (CountLibraryFilesAsync tolto). - I totali e i conteggi per giorno di «Foto» e «Video» su tutta la libreria non pagano più un EXISTS per post (1,3-1,6 s): elenco degli elementi con file di quel tipo su un indice di copertura, 86-141 ms su 200.000 elementi; nuove misure con limite 600 ms in LibraryScaleTests. - La quota di chi aspetta non è un minimo per tipo: corretti commento e decisioni, prova con un arretrato più vecchio di un altro tipo. - Visualizzatore in «Tutte le foto»: le frecce saltano i file che non sono tessere (foto sotto «Video» e simili) e l'intestazione non dà il numero di un altro file; la voce già scelta dell'interruttore non ridisegna il mosaico. Prova d'interfaccia nuova (solo CI). - «Ricetta sospesa» dice di riattivarla dalla Dashboard, non da Attività; commenti aggiornati. - Nomi accessibili distinti nella scheda account, variabile in inglese in download-order.js, icona activity tolta perché nessuna pagina la usa. - Schermate 06, 11 e 14 rifatte con /dashboard e nuova 01-libreria-tutte-le-foto, confrontate con i mockup in docs/schermate/differenze.md (con quattro difetti visivi ancora da sistemare). - LEGGIMI del web (mode, cursore, files, moduli riusabili) e guida della Libreria (la scelta del mosaico resta nel browser, a differenza del tema). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
170 lines
13 KiB
C#
170 lines
13 KiB
C#
using System.Diagnostics;
|
||
using Febe.Core.Domain;
|
||
using Febe.Core.Storage;
|
||
using Febe.Data;
|
||
using Febe.Tests.Support;
|
||
|
||
namespace Febe.Tests.Data;
|
||
|
||
/// <summary>
|
||
/// 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).
|
||
/// </summary>
|
||
[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;
|
||
|
||
// «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail.
|
||
private const double FilteredAggregateBoundMs = 600;
|
||
|
||
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<long>();
|
||
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<NewEntry>(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<Media> { 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<long> accountIds, string label, CancellationToken ct)
|
||
{
|
||
var times = new List<(string Name, double Bound, Timing<object?> Timing)>();
|
||
async Task<T> Measure<T>(string name, double bound, Func<Task<T>> query)
|
||
{
|
||
var timing = await TestWait.BestTimeAsync(query, bound, ct: ct);
|
||
times.Add((name, bound, new Timing<object?>(timing.BestMs, timing.Runs, null)));
|
||
return timing.Result;
|
||
}
|
||
|
||
var first = await Measure("prima finestra", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200 }));
|
||
Assert.HasCount(200, first.Tiles);
|
||
var middleCursor = LibraryCursor.At(new DateTimeOffset(2021, 6, 1, 0, 0, 0, TimeSpan.Zero));
|
||
var middle = await Measure("finestra a metà (salto a una data)", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Cursor = middleCursor }));
|
||
Assert.HasCount(200, middle.Tiles);
|
||
Assert.IsTrue(middle.Tiles.All(t => t.PublishedAt < middleCursor.PublishedAt));
|
||
await Measure("finestra più recente da metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Cursor = middleCursor, Direction = LibraryDirection.Newer }));
|
||
await Measure("filtro Video", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } }));
|
||
await Measure("filtro Storie", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Stories } }));
|
||
await Measure("filtro In evidenza", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Highlights } }));
|
||
await Measure("filtro un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } }));
|
||
await Measure("filtro tre account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3], accountIds[9], accountIds[30]] } }));
|
||
await Measure("filtro periodo e provenienza", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery
|
||
{
|
||
Limit = 200,
|
||
Filter = new LibraryFilter { From = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero), To = new DateTimeOffset(2020, 2, 1, 0, 0, 0, TimeSpan.Zero), Provenance = Provenance.Imported },
|
||
}));
|
||
var rare = await Measure("ricerca rara nella didascalia", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "PAROLARARA" } }));
|
||
Assert.HasCount(1, rare.Tiles);
|
||
await Measure("ricerca comune", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "caffe" } }));
|
||
await Measure("ricerca per account", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "account07" } }));
|
||
var totals = await Measure("totali", AggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter()));
|
||
Assert.AreEqual(new LibraryTotals(Entries, Accounts), totals);
|
||
var days = await Measure("conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome));
|
||
Assert.AreEqual(Entries, days.Sum(d => d.Count));
|
||
// «Tutte le foto» (spec §4.6): one tile per file, in the same times as the grouped mosaic.
|
||
var files = await Measure("tutte le foto: prima finestra", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files }));
|
||
Assert.HasCount(200, files.Tiles);
|
||
Assert.IsTrue(files.Tiles.All(t => t.FilePosition is not null));
|
||
var insidePost = files.Tiles.First(t => t.MediaCount == 2 && t.FilePosition == 1);
|
||
var resumed = await Measure("tutte le foto: finestra dentro un post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery
|
||
{
|
||
Limit = 200,
|
||
Mode = MosaicMode.Files,
|
||
Cursor = new LibraryCursor(insidePost.PublishedAt, insidePost.EntryId, 1),
|
||
}));
|
||
Assert.AreEqual((insidePost.EntryId, (int?)2), (resumed.Tiles[0].EntryId, resumed.Tiles[0].FilePosition));
|
||
var filesMiddle = await Measure("tutte le foto: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor }));
|
||
Assert.HasCount(200, filesMiddle.Tiles);
|
||
await Measure("tutte le foto: più recente da metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor, Direction = LibraryDirection.Newer }));
|
||
await Measure("tutte le foto: filtro Video", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } }));
|
||
await Measure("tutte le foto: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } }));
|
||
await Measure("tutte le foto: ricerca comune", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Search = "caffe" } }));
|
||
// The days give the total of the files too (/api/library/days): one pass over the media table per request.
|
||
var fileDays = await Measure("tutte le foto: conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files));
|
||
Assert.AreEqual(Entries + (Entries / 5), fileDays.Sum(d => d.Count));
|
||
var accountFiles = await Measure("tutte le foto: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, TestZones.Rome, MosaicMode.Files));
|
||
Assert.AreEqual(Enumerable.Range(0, Entries).Where(n => n % Accounts == 3).Sum(n => n % 5 == 0 ? 2 : 1), accountFiles.Sum(d => d.Count));
|
||
// «Foto» and «Video» in the grouped mosaic: the totals and the days of a whole library must not pay an EXISTS
|
||
// per post (over a second); a list of the entries with such files keeps them near a tenth of a second.
|
||
var videoTotals = await Measure("totali del filtro Video", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }));
|
||
var videoDays = await Measure("conteggi per giorno del filtro Video", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome));
|
||
Assert.AreEqual(videoTotals.Entries, videoDays.Sum(d => d.Count));
|
||
Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && n % 7 == 0), videoTotals.Entries);
|
||
var photoTotals = await Measure("totali del filtro Foto", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Photos }));
|
||
Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && (n % 7 != 0 || n % 5 == 0)), photoTotals.Entries);
|
||
await Measure("scheda account: Post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
|
||
await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
|
||
await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome));
|
||
await Measure("tutte le foto: conteggi del filtro Video", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files));
|
||
await Measure("è già noto? (pagina di 12)", IndexBoundMs, async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList()));
|
||
await Measure("SHA-256 in tutta la libreria", IndexBoundMs, () => db.Media.FindBySha256Async(Make.Sha(150_001)));
|
||
var summaries = await Measure("elenco account con conteggi", AggregateBoundMs, () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero)));
|
||
Assert.AreEqual(Entries, summaries.Sum(s => s.EntriesInLibrary));
|
||
await Measure("scheda account", AggregateBoundMs, () => db.Accounts.GetStatsAsync(accountIds[2]));
|
||
await Measure("coda degli scaricamenti", IndexBoundMs, () => db.Media.ListPendingDownloadsAsync(50));
|
||
var hashes = await Measure("caricamento impronte", AggregateBoundMs, () => db.Media.LoadPerceptualHashesAsync());
|
||
Assert.IsGreaterThan(150_000, hashes.Count);
|
||
|
||
foreach (var (name, bound, timing) in times)
|
||
{
|
||
TestContext.WriteLine($"[{label}] {name,-40} {timing.BestMs,8:F1} ms (limite {bound:F0}, {timing.Runs} prove)");
|
||
}
|
||
|
||
foreach (var (name, bound, timing) in times)
|
||
{
|
||
Assert.IsLessThan(bound, timing.BestMs, $"[{label}] {name}");
|
||
}
|
||
}
|
||
}
|