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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 15:29:59 +01:00
1 parent 736d241a38
commit 724db13e1b
14 files changed
+1403 -38

No files matched your search

@@ -0,0 +1,8 @@
-- Febe, schema version 4: the «Copie» filter of the library (tappa E2 of 0.3.0, issue #58; spec §4.6, §4.10, §8.3).
-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
-- Only an index is added: no table, column or data changes.
-- The «Copie» filter joins the copies of the destinations in use to the files of the library by SHA-256, for the list
-- of the entries that have a copy («Copiati»): with the entry in the index the join never reads the row of the file.
-- Over 200,000 entries the window of «Copiati» took 249 ms without it, at the bound of 250 ms (docs/decisioni.md).
CREATE INDEX ix_media_sha256_entry ON media (sha256, entry_id) WHERE sha256 IS NOT NULL;
+11 -5
View File
@@ -343,8 +343,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true, files: files);
var counts = files ? FileCounts(c, filter) : null;
// With the counts of every entry the «Copie» term of the entries adds nothing (an entry without files
// of the class counts 0) and would test each file a second time, once per entry.
var entries = !files ? filter : counts is null ? EntriesOfFiles(filter) : EntriesOfFiles(filter) with { Copies = null };
var where = BuildWhere(c, command, entries, aggregate: true, files: files);
var perEntry = files && counts is null;
command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
@@ -422,14 +425,17 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
/// class of the «Copie» filter. With «Copie» the term reads the entry <c>e</c> of the file too (account and kind), so
/// the caller must have it in scope (<see cref="NeedsEntry"/>).
/// </summary>
internal static string FileTerms(SqliteConnection c, LibraryFilter filter) =>
/// <param name="c">The connection (for the export tables of «Copie»).</param>
/// <param name="filter">The filter.</param>
/// <param name="bulk">The terms are read on every file of the library (the counts per entry): see ExportFilterSql.FileTerm.</param>
internal static string FileTerms(SqliteConnection c, LibraryFilter filter, bool bulk = false) =>
// The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index.
"+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty,
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies) : string.Empty);
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty);
/// <summary>The file terms of this filter read the entry of the file (the «Copie» filter).</summary>
private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null;
@@ -447,7 +453,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
}
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter)} GROUP BY m.entry_id");
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter, bulk: true)} GROUP BY m.entry_id");
var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader();
while (r.Read())
@@ -814,7 +820,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
if (filter.Copies is { } copies)
{
var export = ExportFilterSql.Load(c);
parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies));
parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies, byList));
}
var term = TextSearch.Normalize(filter.Search);
+93 -20
View File
@@ -137,30 +137,44 @@ internal static class ExportFilterSql
/// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was
/// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index.
/// </summary>
public static string Replaced(ExportFilterContext x)
/// <param name="x">The context of the query.</param>
/// <param name="bulk">The term is evaluated on every file of the library (see <see cref="FileTerm"/>).</param>
public static string Replaced(ExportFilterContext x, bool bulk = false) => !x.HasHistory
? "0"
: $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {Failed(x)})";
/// <summary>
/// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). The same partition
/// as <c>NOT Copied AND NOT Replaced</c>, without testing the copy twice.
/// </summary>
/// <param name="x">The context of the query.</param>
/// <param name="bulk">The term is evaluated on every file of the library (see <see cref="FileTerm"/>).</param>
public static string NotCopied(ExportFilterContext x, bool bulk = false)
{
if (!x.HasHistory)
{
return "0";
return $"(NOT {CopiedTerm(x, bulk)})";
}
var destination = DestinationOf(x);
return $"(NOT {Copied(x)} AND NOT {Failed(x)} AND ("
+ $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL) "
+ $"OR EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state IN ('Superseded', 'Removed'))))";
return x.HasFailed
? $"(NOT {CopiedTerm(x, bulk)} AND ({Failed(x)} OR NOT {History(x, bulk)}))"
: $"(NOT {CopiedTerm(x, bulk)} AND NOT {History(x, bulk)})";
}
/// <summary>«Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded).</summary>
public static string NotCopied(ExportFilterContext x) => x.HasHistory ? $"(NOT {Copied(x)} AND NOT {Replaced(x)})" : $"(NOT {Copied(x)})";
/// <summary>The term of «Tutte le foto» on <c>m</c> (with <c>e</c> its entry): a due file of the chosen class.</summary>
public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter) => filter switch
/// <param name="x">The context of the query.</param>
/// <param name="filter">The class.</param>
/// <param name="bulk">
/// The term is evaluated on every file of the library (the counts of «Tutte le foto», the lists of the totals and
/// days) rather than on the few files of a window: each EXISTS then sits behind a list of the SHA-256 of the copies
/// of the destinations in use, read once from ix_export_copy_destination, so most files are settled by that list
/// without a lookup of their own (WP5b of tappa E2, measured over 200,000 entries).
/// </param>
public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool bulk = false) => filter switch
{
LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {Copied(x)})",
LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x)})",
LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x)})",
LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {CopiedTerm(x, bulk)})",
LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x, bulk)})",
LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x, bulk)})",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
};
@@ -169,7 +183,15 @@ internal static class ExportFilterSql
/// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due
/// file removed or superseded, behind the list of the entries with such a row.
/// </summary>
public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter)
/// <param name="x">The context of the query.</param>
/// <param name="filter">The class.</param>
/// <param name="aggregate">
/// A count over the whole library (totals, days) rather than a window: «Copiati» and «Non ancora copiati» then read
/// one list of the entries of the due files of the class, in a single pass over the files with the
/// <see cref="FileTerm"/> bulk terms, instead of an EXISTS per entry (about three times faster over 200,000 entries).
/// A window keeps the EXISTS: it stops after a few hundred entries in index order.
/// </param>
public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool aggregate = false)
{
if (!x.HasDestination)
{
@@ -177,12 +199,15 @@ internal static class ExportFilterSql
}
string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})";
string List(string term) => $"(SELECT m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id WHERE {DueFile(x)} AND {term})";
var withCopy = $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) "
+ "AND c.state = 'Copied' AND c.variant <> 'Frame')";
return filter switch
{
LibraryCopiesFilter.Copied => !x.HasCopies
? "0"
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) "
+ $"AND c.state = 'Copied' AND c.variant <> 'Frame') AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}",
LibraryCopiesFilter.Copied when !x.HasCopies => "0",
LibraryCopiesFilter.Copied when aggregate => CopiedEntries(x),
LibraryCopiesFilter.Copied => $"{withCopy} AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}",
LibraryCopiesFilter.NotCopied when aggregate => $"+e.id IN {List(NotCopied(x, bulk: true))}",
LibraryCopiesFilter.NotCopied => Files(NotCopied(x)),
LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory
? "0"
@@ -214,6 +239,54 @@ internal static class ExportFilterSql
return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString();
}
/// <summary>
/// «Copiati» over the whole library, from the copies rather than from the files: the copied due files of each entry,
/// counted from the Copied rows of the destinations in use (CROSS JOIN keeps that order, with or without ANALYZE),
/// equal to its due files. The same rows as <see cref="Copied"/> per file; a third of the time of a pass over every
/// file of 200,000 entries.
/// </summary>
private static string CopiedEntries(ExportFilterContext x)
{
var match = x.SamePost == SamePostCopies.OneOnly
? string.Empty
: $" AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id";
return "+e.id IN (SELECT m.entry_id FROM export_copy c CROSS JOIN media m CROSS JOIN entry e "
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND m.sha256 = c.source_sha256 AND e.id = m.entry_id{match} "
+ $"AND {DueFile(x)} GROUP BY m.entry_id "
+ $"HAVING COUNT(DISTINCT m.id) = (SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {DueFile(x)}))";
}
/// <summary>
/// Copied (<see cref="Copied"/>); in bulk behind the list of the SHA-256 copied in a destination in use (a superset:
/// any account, any variant), so a file never copied anywhere needs no lookup of its own.
/// </summary>
private static string CopiedTerm(ExportFilterContext x, bool bulk) => !x.HasCopies
? "0"
: bulk
? $"(m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied') AND {Copied(x)})"
: Copied(x);
/// <summary>
/// The removed or superseded part of <see cref="Replaced"/>: the copy of this file in the effective destination was
/// removed, or a copy was superseded (or removed) by this file. In bulk each EXISTS sits behind its list of SHA-256.
/// </summary>
private static string History(ExportFilterContext x, bool bulk)
{
var destination = DestinationOf(x);
var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL)";
var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state IN ('Superseded', 'Removed'))";
if (!bulk)
{
return $"({removed} OR {superseded})";
}
var inUse = InUse(x);
return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state = 'Removed') AND {removed}) "
+ $"OR (m.sha256 IN (SELECT c.superseded_by_sha256 FROM export_copy c WHERE c.superseded_by_sha256 IS NOT NULL AND c.destination_id IN ({inUse})) AND {superseded}))";
}
private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal));
private static string TypeTerm(ContentTypes types) =>
+9 -3
View File
@@ -239,7 +239,7 @@ public static class ExportApi
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
});
endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, CancellationToken ct) =>
endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyAgainRequest).ConfigureAwait(false);
var copy = await storage.Exports.GetCopyAsync(body.CopyId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa copia non è più registrata.");
@@ -261,8 +261,14 @@ public static class ExportApi
throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella.");
}
var location = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
.FirstOrDefault(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
var present = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
.ToList();
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null)
?? present.FirstOrDefault()
?? throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false);