diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs
index 69a5234..eaae541 100644
--- a/src/Febe.Core/Storage/IExportStore.cs
+++ b/src/Febe.Core/Storage/IExportStore.cs
@@ -275,7 +275,10 @@ public interface IExportStore
/// left out, «Non riuscito» in, each file once as the plan counts it (per account, or once with «Una copia sola»),
/// with their bytes. The destination may be one not stored yet (see ).
/// for an own folder without account, or a history destination that is not the
- /// one in use for that scope and account.
+ /// one in use for that scope and account. The figure is the destination's alone: with «Una copia sola» it can count a
+ /// file that another automatic folder takes for another account in the same job (the job writes it once, the other
+ /// becomes «Già copiato»), so the figures of two folders do not add up until the first job; each is right for its
+ /// folder when that folder copies alone.
///
Task CountAutomaticBacklogAsync(ExportBacklogQuery query, CancellationToken ct = default);
diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs
index 00b562b..e8d608a 100644
--- a/src/Febe.Data/Stores/ExportStore.cs
+++ b/src/Febe.Data/Stores/ExportStore.cs
@@ -1282,20 +1282,26 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
terms.Add(ExportFilterSql.NotCopied(x, bulk: true));
var where = string.Join(" AND ", terms);
- // Each file once, as the plan counts it: per account, or once in all with «Una copia sola». A file counts
- // when no file before it (by id) with the same SHA-256 (and account) counts too: a seek on ix_media_sha256
- // per file, with the terms only for the rare duplicates. A GROUP BY on the SHA-256 took twice as long over
- // 200,000 entries, and with ANALYZE statistics 4 s. CROSS JOIN: one pass over media (see above), except
- // for one account, whose entries the planner then reads first (ix_entry_account_*; 0.2 s instead of 1.4 s).
- var sameKey = x.SamePost == SamePostCopies.OneOnly ? string.Empty : " AND e.account_id = k.account";
+ // Each file once, as the plan counts it: per account, or once in all with «Una copia sola». Only the
+ // SHA-256 that more than one file has (read once from ix_media_sha256) need it: the others count
+ // directly, and the shared ones count their first file (by id) per SHA-256, or per SHA-256 and account,
+ // with a GROUP BY over their few files (SQLite takes the bytes of the row of min(m.id)). A correlated
+ // NOT EXISTS per file was quadratic in the files of the same content: 5-6 s, and 11-14 s with ANALYZE
+ // statistics, for a library with 520 files of one SHA-256 (the demonstration's). CROSS JOIN: one pass
+ // over media (see above), except for one account, whose entries the planner then reads first
+ // (ix_entry_account_*; 0.2 s instead of 1.4 s).
+ var perAccount = x.SamePost == SamePostCopies.OneOnly ? string.Empty : ", e.account_id";
var join = query.AccountId is null ? "CROSS JOIN" : "JOIN";
using var r = c.Command($"""
+ WITH dup(sha) AS MATERIALIZED (SELECT sha256 FROM media WHERE sha256 IS NOT NULL GROUP BY sha256 HAVING count(*) > 1)
SELECT COUNT(*), ifnull(SUM(k.bytes), 0) FROM (
- SELECT m.id AS id, m.sha256 AS sha, e.account_id AS account, ifnull(m.bytes, 0) AS bytes
- FROM media m {join} entry e ON e.id = m.entry_id WHERE {where}) AS k
- WHERE NOT EXISTS (
- SELECT 1 FROM media m CROSS JOIN entry e ON e.id = m.entry_id
- WHERE m.sha256 = k.sha AND m.id < k.id{sameKey} AND {where})
+ SELECT ifnull(m.bytes, 0) AS bytes
+ FROM media m {join} entry e ON e.id = m.entry_id WHERE {where} AND m.sha256 NOT IN (SELECT sha FROM dup)
+ UNION ALL
+ SELECT bytes FROM (
+ SELECT min(m.id), ifnull(m.bytes, 0) AS bytes
+ FROM dup CROSS JOIN media m ON m.sha256 = dup.sha CROSS JOIN entry e ON e.id = m.entry_id
+ WHERE {where} GROUP BY m.sha256{perAccount})) AS k
""").ExecuteReader();
r.Read();
return new ExportBacklog(r.GetInt32(0), r.GetInt64(1));
diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs
index 53b6084..26f45ac 100644
--- a/tests/Febe.Tests/Data/LibraryScaleTests.cs
+++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs
@@ -101,6 +101,68 @@ public sealed class LibraryScaleTests
await MeasureAll(db, accountIds, copies, still, "con ANALYZE", ct);
}
+ ///
+ /// The count of «Copia anche gli N» on a library where many files have the same content (reposts, shared stories; the
+ /// demonstration: about 30,000 files of 131 contents): 30,000 files of 60 contents over 37 accounts, each account's
+ /// files together, as an account is saved at once. The count of each file once per account, and once in all with
+ /// «Una copia sola», stays within the bound of the automatic export, without and with ANALYZE statistics; a NOT
+ /// EXISTS per file took about 5 s here (quadratic in the files of the same content).
+ ///
+ [TestMethod]
+ [Timeout(600_000, CooperativeCancellation = true)] // only a hang guard
+ public async Task TheBacklogCountStaysFastWithManyFilesOfTheSameContent()
+ {
+ const int Files = 30_000;
+ const int Contents = 60;
+ const int Owners = 37;
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var owners = new List();
+ for (var a = 0; a < Owners; a++)
+ {
+ owners.Add((await db.Accounts.AddAsync(Make.Account($"stesso{a:00}.demo", $"{5000 + a}"), ct)).Id);
+ }
+
+ var start = new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ for (var batch = 0; batch < Files / 5000; batch++)
+ {
+ var items = new List(5000);
+ for (var i = 0; i < 5000; i++)
+ {
+ var n = (batch * 5000) + i;
+ var owner = owners[Math.Min(Owners - 1, n / (Files / Owners))];
+ items.Add(new NewEntry(Make.Entry(owner, $"s{n}", start.AddMinutes(n)), [Make.Stored(Make.Photo(), Make.Sha((n % Contents) + 1), $"s/{n}.jpg")]));
+ }
+
+ await db.Entries.AddManyAsync(items, ct);
+ }
+
+ var general = await db.Exports.AddDestinationAsync(
+ new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct);
+ var query = new ExportBacklogQuery(ExportScope.General, null, ContentTypes.All, general.Id, null);
+
+ // Each (content, account) pair once; once per content with «Una copia sola».
+ var pairs = Enumerable.Range(0, Files).Select(n => (n % Contents, Math.Min(Owners - 1, n / (Files / Owners)))).Distinct().Count();
+ foreach (var label in new[] { "senza statistiche", "con ANALYZE" })
+ {
+ if (label == "con ANALYZE")
+ {
+ await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
+ }
+
+ await (ExportSettings.Default with { SamePost = SamePostCopies.OnePerAccount }).SaveAsync(db.Settings, ct);
+ var perAccount = await TestWait.BestTimeAsync(() => db.Exports.CountAutomaticBacklogAsync(query, ct), AutomaticBoundMs, ct: ct);
+ Assert.AreEqual(new ExportBacklog(pairs, pairs * 1000L), perAccount.Result, label);
+ await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly }).SaveAsync(db.Settings, ct);
+ var oneOnly = await TestWait.BestTimeAsync(() => db.Exports.CountAutomaticBacklogAsync(query, ct), AutomaticBoundMs, ct: ct);
+ Assert.AreEqual(new ExportBacklog(Contents, Contents * 1000L), oneOnly.Result, label);
+ TestContext.WriteLine($"{label}: per account {perAccount.BestMs:F0} ms, una copia sola {oneOnly.BestMs:F0} ms (limite {AutomaticBoundMs:F0} ms)");
+ Assert.IsLessThanOrEqualTo(AutomaticBoundMs, perAccount.BestMs, $"{label}: per account");
+ Assert.IsLessThanOrEqualTo(AutomaticBoundMs, oneOnly.BestMs, $"{label}: una copia sola");
+ }
+ }
+
///
/// 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,