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; /// /// 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. /// [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(); 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); } var copies = await FillCopiesAsync(db, temp, accountIds, ct); var still = await FillStillVideosAsync(db, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); TestContext.WriteLine($"Video fermi: {still.Analyses:N0} analisi, {still.Still:N0} «Fermo» (di cui {still.Overruled:N0} superati da un algoritmo più nuovo), {still.Entries:N0} elementi e {still.Files:N0} file nel filtro"); Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill"); Assert.IsGreaterThan(0, copies.Frames, "frames in the fill"); Assert.IsGreaterThan(0, still.Overruled, "still videos overruled by a newer algorithm in the fill"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. await MeasureAll(db, accountIds, copies, still, "senza statistiche", ct); await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct); await MeasureAll(db, accountIds, copies, still, "con ANALYZE", ct); } /// /// 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. /// private static async Task FillCopiesAsync(FebeDatabase db, TempFolder temp, List accountIds, CancellationToken ct) { 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, Form? form = null) { var f = form ?? Form.Whole; return w.Command( $""" INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state, superseded_by_sha256, origin, relative_path, bytes, copy_sha256, copied_at) SELECT {destination}, e.account_id, m.id, {source}, '{f.Variant}', {f.Format}, {f.FrameAt}, '{state}', {supersededBy}, 'Written', 'p/' || m.id || '{f.Suffix}', 1000, {f.CopySha ?? source}, 1767225600000 FROM media m JOIN entry e ON e.id = m.entry_id WHERE {due} AND {which} """).ExecuteNonQuery(); } // Tappa E3: three in ten of the copied files are converted copies (PNG, or MP4 for a video), which count as // copied; one video in fifty has a frame in its folder, copied or not, and one in a hundred a frame «Tolto»: // frames never count in the «Copie» filter (D4), so the counts asserted stay those of the whole copies. var converted = new Form("Converted", "(CASE m.kind WHEN 'Video' THEN 'Mp4' ELSE 'Png' END)", "NULL", ".c", "'c' || substr(m.sha256, 2)"); var frame = new Form("Frame", "'Png'", "1000", "_t0m01s000.png", "'f' || substr(m.sha256, 2)"); return await db.WriteAsync( w => { var whole = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 >= 3"); var convertedCopies = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 < 3", converted); var removed = 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). var superseded = Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"); var frames = Insert(w, "Copied", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 50 = 7", frame) + Insert(w, "Removed", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 100 = 9", frame); return new CopiesWorld(whole + convertedCopies, removed, superseded, DueFiles(), accountIds[OwnAccount], convertedCopies, frames); }, ct); } // A hash of the media id that mixes the ids (see FillCopiesAsync). private const string Hash = "((m.id * 2654435761) % 1000003)"; private const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)"; /// /// Tappa E4, the filter «Video fermi»: seven videos in ten analysed (about 20,000 of the 28,600 videos), half of them /// «Fermo» (about 10,000, frame at 1 s) and half «In movimento»; one «Fermo» in ten has a newer algorithm that says /// «In movimento», so it is out of the filter. The expected entries and files are counted here with a join on the /// highest algorithm, another form than the filter's own. /// private static Task FillStillVideosAsync(FebeDatabase db, List accountIds, CancellationToken ct) => db.WriteAsync( w => { var videos = $"FROM media m WHERE m.kind = 'Video' AND m.sha256 IS NOT NULL AND {Spread} % 10 < 7"; var analyses = w.Command($""" INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) SELECT m.sha256, 1, CASE WHEN {Spread} % 2 = 0 THEN 'Still' ELSE 'Moving' END, 1767225600000, CASE WHEN {Spread} % 2 = 0 THEN 1000 END, NULL {videos} """).ExecuteNonQuery(); var overruled = w.Command($""" INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) SELECT m.sha256, 2, 'Moving', 1767225600000, NULL, NULL {videos} AND {Spread} % 2 = 0 AND {Spread} % 20 < 2 """).ExecuteNonQuery(); var still = (int)w.Command("SELECT COUNT(*) FROM video_analysis WHERE outcome = 'Still'").ScalarInt64(); const string Latest = """ FROM media m JOIN video_analysis va ON va.sha256 = m.sha256 WHERE m.kind = 'Video' AND m.state IN ('Downloaded', 'Imported') AND va.outcome = 'Still' AND va.algorithm = (SELECT MAX(x.algorithm) FROM video_analysis x WHERE x.sha256 = va.sha256) """; var entries = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest}").ScalarInt64(); var files = (int)w.Command($"SELECT COUNT(*) {Latest}").ScalarInt64(); var account = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)") .With("@a", accountIds[3]).ScalarInt64(); var accountFiles = (int)w.Command($"SELECT COUNT(*) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)") .With("@a", accountIds[3]).ScalarInt64(); return new StillWorld(analyses + overruled, still, overruled, entries, files, account, accountFiles); }, ct); /// /// What the fill of the analyses wrote: rows, «Fermo» rows, those overruled by a newer algorithm, and the entries /// and files the filter must find ( and : those of /// account 3). /// private sealed record StillWorld(int Analyses, int Still, int Overruled, int Entries, int Files, int AccountEntries, int AccountFiles); /// The form of the copies an insert writes: variant, format and instant (SQL), name suffix, copy SHA (SQL). private sealed record Form(string Variant, string Format, string FrameAt, string Suffix, string? CopySha) { public static readonly Form Whole = new("Whole", "'Original'", "NULL", ".jpg", null); } /// The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4. 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 accountIds, CopiesWorld copies, StillWorld still, string label, CancellationToken ct) { var times = new List<(string Name, double Bound, Timing Timing)>(); async Task Measure(string name, double bound, Func> query) { var timing = await TestWait.BestTimeAsync(query, bound, ct: ct); times.Add((name, bound, new Timing(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)); // «Video fermi» (tappa E4): the windows at the bound of the windows, totals and days at those of «Foto» and «Video». var stillFilter = new LibraryFilter { Kind = LibraryKindFilter.StillVideos }; var stillWindow = await Measure("filtro Video fermi", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter })); Assert.HasCount(200, stillWindow.Tiles); var stillMiddle = await Measure("Video fermi: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter, Cursor = middleCursor })); Assert.HasCount(200, stillMiddle.Tiles); var stillFiles = await Measure("Video fermi: tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillFilter })); Assert.HasCount(200, stillFiles.Tiles); Assert.IsTrue(stillFiles.Tiles.All(t => t.CoverKind == MediaKind.Video)); var stillAccount = stillFilter with { AccountIds = [accountIds[3]] }; var stillOwn = await Measure("Video fermi: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillAccount })); Assert.HasCount(Math.Min(200, still.AccountEntries), stillOwn.Tiles); await Measure("Video fermi: un account, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillAccount })); var stillTotals = await Measure("totali del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(stillFilter)); Assert.AreEqual(still.Entries, stillTotals.Entries); var stillDays = await Measure("conteggi per giorno del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome)); Assert.AreEqual(still.Entries, stillDays.Sum(d => d.Count)); var stillFileDays = await Measure("Video fermi: conteggi, tutte le foto", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome, MosaicMode.Files)); Assert.AreEqual(still.Files, stillFileDays.Sum(d => d.Count)); var stillAccountDays = await Measure("Video fermi: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome)); Assert.AreEqual(still.AccountEntries, stillAccountDays.Sum(d => d.Count)); // With accounts «Tutte le foto» counts each entry apart: a count that went from the SHA-256 index would walk // every still video for each entry (107 s for one account in the first version). var stillAccountFiles = await Measure("Video fermi: conteggi di un account, tutte le foto", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome, MosaicMode.Files)); Assert.AreEqual(still.AccountFiles, stillAccountFiles.Sum(d => d.Count)); 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, 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}"); } } /// /// 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. /// private static async Task MeasureCopiesAsync( Func>, Task> measure, FebeDatabase db, List 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(); 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)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)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]); } /// /// What the export fill wrote: copies by state ( with the converted ones), the due files, the /// account with its own folder, and of tappa E3 the converted copies and the frames (copied and «Tolto»). /// private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId, int Converted, int Frames); }