Files
Febe/tests/Febe.Tests/Data/LibraryScaleTests.cs
T
Alby96andClaude Opus 5.5 724db13e1b E2: misure del filtro Copie, migrazione 0004 e prove di web e Docker
Il filtro «Copie» con 200.000 elementi stava al limite dei 250 ms
(«Copiati» 249 ms): la migrazione 0004 aggiunge solo l'indice
ix_media_sha256_entry e la finestra scende a 160 ms. Totali e giorni
contano «Copiati» partendo dalle copie e gli altri valori con un solo
passaggio sui file dietro gli elenchi degli SHA-256 copiati (1,5 s ->
0,7 s); hanno un limite loro di 3 s, scritto in decisioni.md con le
misure.

«Copia di nuovo» sceglie un file dell'account che è sul disco: prima
prendeva il primo con quello SHA-256 e, nella demo, a certe ore non
scriveva nulla.

Nuove prove: API delle copie, coerenza della demo, interfaccia nel
browser, opzioni del server, avvio del contenitore con /esporta,
contenuto dell'immagine e modelli, migrazione 4 e scala.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:29:59 +01:00

291 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Export;
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). Tappa E2 adds the «Copie»
/// filter (§15: «filtro Copie con 200.000 elementi entro 250 ms»): a general folder, an own folder that takes only the
/// photos of its account, an account with «Esporta questo account» off, a third of the due files copied, 2 % removed
/// and 1 % superseded.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class LibraryScaleTests
{
private const int Entries = 200_000;
private const int Accounts = 40;
// Tappa E2: the account with its own folder (posts, photos only) and the account with «Esporta questo account» off.
private const int OwnAccount = 4;
private const int OffAccount = 7;
// 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;
// «Copie» over the whole library (tappa E2, WP5b): every due file is classified against the copies, 240,000 files
// at about 4 µs each; measured 0.23-1.1 s (docs/decisioni.md), «Non ancora copiati» the slowest. The design asked for
// the 600 ms of the filtered aggregates: not reachable without a column of state per file, which E2 does not add.
private const double CopiesAggregateBoundMs = 3000;
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);
}
var copies = await FillCopiesAsync(db, temp, accountIds, 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, copies, "senza statistiche", ct);
await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
await MeasureAll(db, accountIds, copies, "con ANALYZE", ct);
}
/// <summary>
/// The export side of the library: the general folder for every account, an own folder for account 4 (post photos
/// only, so its videos are not due), account 7 switched off. The copies are written in bulk on the due files only,
/// chosen by a hash of the media id: a third Copied, then 2 % Removed and 1 % Superseded by the file now in the
/// library. Not by the media id itself: the fill repeats every 40 entries (48 files), so «m.id % 3» (or any linear
/// hash of it) would copy all the files of some accounts and none of others; a square mixes the ids.
/// </summary>
private static async Task<CopiesWorld> FillCopiesAsync(FebeDatabase db, TempFolder temp, List<long> accountIds, CancellationToken ct)
{
const string Hash = "((m.id * 2654435761) % 1000003)";
const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
var general = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct);
var own = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.Account, AccountId = accountIds[OwnAccount], RootPath = temp.Combine("sua"), ContentTypes = ContentTypes.PostPhotos, CreatedAt = Make.T0 },
ct);
await db.Exports.SetAccountExportEnabledAsync(accountIds[OffAccount], false, ct);
var destination = $"(CASE e.account_id WHEN {accountIds[OwnAccount]} THEN {own.Id} ELSE {general.Id} END)";
var due = $"m.sha256 IS NOT NULL AND e.account_id <> {accountIds[OffAccount]} AND (e.account_id <> {accountIds[OwnAccount]} OR m.kind = 'Photo')";
int Insert(WriteContext w, string state, string source, string supersededBy, string which) => w.Command(
$"""
INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, state, superseded_by_sha256,
origin, relative_path, bytes, copy_sha256, copied_at)
SELECT {destination}, e.account_id, m.id, {source}, 'Whole', 'Original', '{state}', {supersededBy},
'Written', 'p/' || m.id || '.jpg', 1000, {source}, 1767225600000
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE {due} AND {which}
""").ExecuteNonQuery();
return await db.WriteAsync(
w => new CopiesWorld(
Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0"),
Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"),
// The old original of a file replaced in the library («Tieni il più grande», a rebuild).
Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"),
DueFiles(),
accountIds[OwnAccount]),
ct);
}
/// <summary>The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4.</summary>
private static int DueFiles() => Enumerable.Range(0, Entries).Sum(n => (n % Accounts) switch
{
OffAccount => 0,
OwnAccount => (n % 7 != 0 ? 1 : 0) + (n % 5 == 0 ? 1 : 0),
_ => 1 + (n % 5 == 0 ? 1 : 0),
});
private async Task MeasureAll(FebeDatabase db, List<long> accountIds, CopiesWorld copies, 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);
// The times are printed even when a result of the «Copie» filter is wrong (the measures are the point of #46).
AssertFailedException? copiesProblem = null;
try
{
await MeasureCopiesAsync(Measure<object>, db, accountIds, copies);
}
catch (AssertFailedException e)
{
copiesProblem = e;
}
foreach (var (name, bound, timing) in times)
{
TestContext.WriteLine($"[{label}] {name,-40} {timing.BestMs,8:F1} ms (limite {bound:F0}, {timing.Runs} prove)");
}
if (copiesProblem is not null)
{
throw copiesProblem;
}
foreach (var (name, bound, timing) in times)
{
Assert.IsLessThan(bound, timing.BestMs, $"[{label}] {name}");
}
}
/// <summary>
/// The «Copie» filter (tappa E2): the window of each of its three values at the bound of the windows, in the
/// grouped mosaic, in «Tutte le foto» and on one account (§15: 250 ms); totals and days at their own bound.
/// In «Tutte le foto» the three values split the due files (D3), so their days add up to the copies written.
/// </summary>
private static async Task MeasureCopiesAsync(
Func<string, double, Func<Task<object>>, Task<object>> measure, FebeDatabase db, List<long> accountIds, CopiesWorld copies)
{
var values = new (LibraryCopiesFilter Value, string Name)[]
{
(LibraryCopiesFilter.Copied, "copiati"),
(LibraryCopiesFilter.NotCopied, "non ancora copiati"),
(LibraryCopiesFilter.RemovedOrSuperseded, "tolti o superati"),
};
var files = new Dictionary<LibraryCopiesFilter, int>();
foreach (var (value, name) in values)
{
var filter = new LibraryFilter { Copies = value };
var window = (LibraryPage)await measure($"Copie {name}", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = filter }));
Assert.HasCount(200, window.Tiles, name);
Assert.IsFalse(window.Tiles.Any(t => t.AccountId == accountIds[OffAccount]), name);
var fileWindow = (LibraryPage)await measure($"Copie {name}: tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = filter }));
Assert.HasCount(200, fileWindow.Tiles, name);
var own = new LibraryFilter { Copies = value, AccountIds = [copies.OwnAccountId] };
var ownWindow = (LibraryPage)await measure($"Copie {name}: un account", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = own }));
Assert.IsNotEmpty(ownWindow.Tiles, name);
Assert.IsTrue(ownWindow.Tiles.All(t => t.AccountId == copies.OwnAccountId), name);
await measure($"Copie {name}: un account, tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = own }));
var totals = (LibraryTotals)await measure($"Copie {name}: totali", CopiesAggregateBoundMs, async () => await db.Entries.GetLibraryTotalsAsync(filter));
var days = (IReadOnlyList<DayCount>)await measure($"Copie {name}: giorni", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome));
Assert.AreEqual(totals.Entries, days.Sum(d => d.Count), name);
Assert.AreEqual(Accounts - 1, totals.Accounts, name);
var fileDays = (IReadOnlyList<DayCount>)await measure($"Copie {name}: giorni, tutte le foto", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files));
files[value] = fileDays.Sum(d => d.Count);
}
Assert.AreEqual(copies.Copied, files[LibraryCopiesFilter.Copied]);
Assert.AreEqual(copies.Removed + copies.Superseded, files[LibraryCopiesFilter.RemovedOrSuperseded]);
Assert.AreEqual(copies.Due - copies.Copied - copies.Removed - copies.Superseded, files[LibraryCopiesFilter.NotCopied]);
}
/// <summary>What the export fill wrote: copies by state, the due files, and the account with its own folder.</summary>
private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId);
}