E2: prove del motore, dell'archivio e del servizio delle copie

Le prove della tappa E2 (WP5a) coprono il montaggio di /esporta, la
radice, il controllo delle cartelle, le destinazioni, i percorsi, la
copia, gli stati «Tolto» e «Superato», lo stesso post in due account,
il lavoro in sottofondo (interrompi, riprendi, annulla, riavvio, porta
condivisa con importazione e ricostruzione, sessione del motore,
interruttore dell'account, Docker senza montaggio) e il filtro «Copie».
Si appoggiano a un banco comune con falsi per disco, sessione, montaggi
e file system, senza permessi dei file, così girano anche da root.

Le prove hanno trovato due difetti, corretti:
- MarkCopiesRemovedAsync riusava il comando in cache del primo blocco
  di 900 id: «Controlla le copie» falliva con più di 900 file mancanti
  in una pagina.
- ReplacedStatesSql senza statistiche leggeva tutte le copie tolte o
  superate della destinazione: «+state» la tiene sul suo indice.

Il controllo delle cartelle accetta una scrittura di prova sostituibile,
per provare il guasto della sonda senza permessi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 13:28:20 +01:00
1 parent 31cfdac051
commit 736d241a38
18 files changed
+3124 -12

No files matched your search

@@ -564,6 +564,9 @@ public sealed class ExportConstraintTests
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await FillAsync(db, w);
// Two copies of the files of the world, so that the «Copie» filter has copies and history to look at.
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Removed });
// Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity.
var setShape = await PlanAsync(
@@ -627,6 +630,51 @@ public sealed class ExportConstraintTests
}
}
// The lookups of tappa E2 (WP1.11). The handful of destinations in use may be read whole; never the copies.
var shas = string.Join(", ", Enumerable.Range(0, 3).Select(i => $"@x{i}"));
(string, object?)[] Shas(params (string, object?)[] more) => [.. Enumerable.Range(0, 3).Select(i => ($"@x{i}", (object?)Make.Sha(i * 7))), .. more];
// «Una copia sola» may sort the few rows of one SHA-256 (its key is in the index the planner picks either way).
var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
{
("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false),
("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original")], true),
("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false),
("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false),
};
foreach (var (name, sql, parameters, sortAllowed) in lookupsE2)
{
var plan = await PlanAsync(db, sql, parameters);
var copies = plan.Replace("SCAN export_destination", string.Empty, StringComparison.Ordinal);
var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan;
if (!plan.Contains("SEARCH export_copy USING", StringComparison.Ordinal) || !plan.Contains("sha256=?", StringComparison.Ordinal)
|| copies.Contains("SCAN", StringComparison.Ordinal) || withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal))
{
problems.Add($"{name}: {plan}");
}
}
// The «Copie» filter: the two prefilter lists of the grouped mosaic read the copies of the destinations in use
// through ix_export_copy_destination, and the files through their SHA-256.
var x = await db.ReadAsync(ExportFilterSql.Load, default);
foreach (var filter in new[] { Core.Storage.LibraryCopiesFilter.Copied, Core.Storage.LibraryCopiesFilter.RemovedOrSuperseded })
{
var term = ExportFilterSql.EntryTerm(x, filter);
var start = term.IndexOf("+e.id IN (", StringComparison.Ordinal) + "+e.id IN (".Length;
var end = term.IndexOf(") AND EXISTS", start, StringComparison.Ordinal);
Assert.IsGreaterThan(start, end, term);
var plan = await PlanAsync(db, term[start..end]);
// With statistics that say the files are fewer than the copies (this small world), the planner may walk the
// SHA-256 index of the files first; the copies are always searched by destination and state.
var searchesCopies = plan.Contains("SEARCH c USING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal)
|| plan.Contains("SEARCH c USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal);
var otherScans = plan.Replace("SCAN m2 USING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal)
.Replace("SCAN m2 USING COVERING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal).Contains("SCAN", StringComparison.Ordinal);
if (!searchesCopies || !plan.Contains("m2 USING", StringComparison.Ordinal) || otherScans || plan.Contains("TEMP B-TREE", StringComparison.Ordinal))
{
problems.Add($"prefiltro {filter}: {plan}");
}
}
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
}
+186
View File
@@ -1,4 +1,5 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
@@ -482,6 +483,191 @@ public sealed class ExportStoreTests
Assert.AreEqual(0, await db.Exports.RelinkOrphanCopiesAsync(again.Id));
}
[TestMethod]
public async Task AccountSwitchesAreListedInBulk()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var third = await db.Accounts.AddAsync(Make.Account("anna.demo", "300"));
Assert.IsEmpty(await db.Exports.ListAccountExportSwitchesAsync());
await db.Exports.SetAccountExportEnabledAsync(w.Marta, false);
await db.Exports.SetAccountExportEnabledAsync(third.Id, true);
var switches = await db.Exports.ListAccountExportSwitchesAsync();
Assert.HasCount(2, switches);
Assert.IsFalse(switches[w.Marta]);
Assert.IsTrue(switches[third.Id]);
Assert.IsFalse(switches.ContainsKey(w.Luca), "no row: «Esporta questo account» is on by default");
// Removing an account takes its switch with it.
await db.Accounts.DeleteAsync(third.Id);
CollectionAssert.AreEquivalent(new[] { w.Marta }, (await db.Exports.ListAccountExportSwitchesAsync()).Keys.ToArray());
}
[TestMethod]
public async Task ReplacedCopiesAreFoundBySupersedingSha()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var older = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) });
var newer = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) });
await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(6) });
Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!.Id, "the newest row first");
Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5).ToUpperInvariant()))!.Id);
Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(5)), "another account");
Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Marta, Make.Sha(5)), "another destination");
Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(1)), "by the file now in the library, not by the old one");
// «Controlla le copie» turned it into Removed: it keeps the SHA-256 that replaced it and is still found.
Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([newer.Id], Make.T0.AddDays(1)));
var removed = (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!;
Assert.AreEqual((newer.Id, ExportCopyState.Removed, Make.Sha(5)), (removed.Id, removed.State, removed.SupersededBySha256));
Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(older.Id))!.State);
}
[TestMethod]
public async Task CopiesElsewhereIgnoreRetiredDestinations()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original));
var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
var general = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed });
Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id, "the newest Copied row");
Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Jpg), "another format");
Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2), ExportVariant.Whole, ExportFormat.Original));
await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1));
Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id);
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original), "a retired folder is not in use");
// A copy whose account was removed has no account to be «per un altro account».
var third = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"G:\Nuova"));
var orphan = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg", destination: third.Id));
await db.Accounts.DeleteAsync(w.Marta);
Assert.IsNull((await db.Exports.GetCopyAsync(orphan.Id))!.AccountId);
Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original));
}
[TestMethod]
public async Task CopyStatesAreReadInBatch()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
// 1,000 originals of marta.demo in the general folder (more than one chunk of 900 parameters): every tenth is
// Removed, every tenth plus one Superseded, every tenth plus two Failed, the rest Copied; none for luca.demo.
await InsertCopiesAsync(db, w, i => (i % 10) switch { 0 => "Removed", 1 => "Superseded", 2 => "Failed", _ => "Copied" });
var keys = Enumerable.Range(0, 1000).Select(i => (w.Marta, Make.Sha(100 + i)))
.Append((w.Luca, Make.Sha(100)))
.Append((w.Marta, Make.Sha(5001))) // the file that superseded the copy of number 1
.Append((w.Marta, Make.Sha(4000)))
.ToList();
var states = await db.Exports.GetCopyStatesAsync(w.General, keys);
Assert.HasCount(1001, states);
for (var i = 0; i < 1000; i++)
{
var expected = (i % 10) switch { 0 => ExportCopyState.Removed, 1 => ExportCopyState.Superseded, 2 => ExportCopyState.Failed, _ => ExportCopyState.Copied };
Assert.AreEqual(expected, states[(w.Marta, Make.Sha(100 + i))], i.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
Assert.AreEqual(ExportCopyState.Superseded, states[(w.Marta, Make.Sha(5001))]);
Assert.IsFalse(states.ContainsKey((w.Luca, Make.Sha(100))));
Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(4000))));
Assert.IsEmpty(await db.Exports.GetCopyStatesAsync(w.Own, keys));
// A new Copied row of a removed copy is the current state; the history stays behind it.
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/0 (2).jpg") with { SourceSha256 = Make.Sha(100), CopySha256 = Make.Sha(100) });
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.General, [(w.Marta, Make.Sha(100))]))[(w.Marta, Make.Sha(100))]);
}
[TestMethod]
public async Task MissingCopiesAreMarkedRemovedInOneTransaction()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await InsertCopiesAsync(db, w, i => (i % 4) switch { 0 => "Superseded", 1 => "Failed", 2 => "Removed", _ => "Copied" });
var all = await db.Exports.ListCopiesAsync(w.General, limit: 2000);
Assert.HasCount(1000, all);
Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync([], Make.T0));
// Every id, twice, over two chunks: only the Copied and Superseded rows change, each once.
var ids = all.Select(c => c.Id).Concat(all.Select(c => c.Id)).ToList();
Assert.AreEqual(500, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(3)));
var after = (await db.Exports.ListCopiesAsync(w.General, limit: 2000)).ToDictionary(c => c.Id);
foreach (var before in all)
{
var now = after[before.Id];
if (before.State is ExportCopyState.Copied or ExportCopyState.Superseded)
{
Assert.AreEqual((ExportCopyState.Removed, Make.T0.AddDays(3)), (now.State, now.StateChangedAt));
Assert.AreEqual(before.SupersededBySha256, now.SupersededBySha256, "a superseded copy keeps the file that replaced it");
}
else
{
Assert.AreEqual(before, now);
}
}
Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(4)), "idempotent");
}
[TestMethod]
public async Task CandidatesFollowTheLibraryFilter()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var story = await db.Entries.AddAsync(Make.Entry(w.Luca, "556", Make.T0.AddDays(1), EntryKind.Story), [Make.Stored(Make.Photo(1), Make.Sha(3), "storie/s.jpg"), Make.Stored(Make.Photo(2), Make.Sha(4), "storie/s2.jpg")]);
var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = w.Luca, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 });
await db.Highlights.AddItemAsync(highlight.Id, story.Stored.Entry.Id);
var waiting = await db.Entries.AddAsync(Make.Entry(w.Luca, "557", Make.T0.AddDays(2)), [Make.Photo(1)]);
var lucaFilter = new ExportSelection.Filter(new LibraryFilter { AccountIds = [w.Luca] }, MosaicMode.Grouped);
var luca = await db.Exports.ListCandidatesAsync(lucaFilter, 0, 100);
CollectionAssert.AreEqual(new[] { w.LucaMedia, story.Stored.Media[0].Id, story.Stored.Media[1].Id }, luca.Select(c => c.MediaId).ToArray(), "an entry still to download is not in the library");
var first = luca.Single(c => c.MediaId == story.Stored.Media[0].Id);
Assert.AreEqual((story.Stored.Entry.Id, w.Luca, EntryKind.Story, MediaKind.Photo, Make.Sha(3), "storie/s.jpg", 1, true),
(first.EntryId, first.AccountId, first.EntryKind, first.MediaKind, first.Sha256, first.RelativePath, first.Position, first.InHighlight));
Assert.IsFalse(luca[0].InHighlight);
// Pages by media id.
var page = await db.Exports.ListCandidatesAsync(lucaFilter, w.LucaMedia, 1);
Assert.AreEqual(story.Stored.Media[0].Id, page.Single().MediaId);
// An explicit choice of an entry that is not downloaded yet: listed, to be counted «non presente in libreria».
var chosen = await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([waiting.Stored.Entry.Id]), 0, 100);
Assert.AreEqual((waiting.Stored.Media[0].Id, MediaState.ToDownload, (string?)null), (chosen.Single().MediaId, chosen[0].State, chosen[0].Sha256));
}
/// <summary>1,000 whole copies of marta.demo in the general folder, SHA-256 100.. with the state chosen per number (a Superseded one by 5000 + n).</summary>
private static Task InsertCopiesAsync(FebeDatabase db, ExportWorld w, Func<int, string> stateOf) =>
db.WriteAsync(
x =>
{
var insert = x.Command("""
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256, relative_path, bytes, copy_sha256, copied_at)
VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, CASE WHEN @p IS NULL THEN NULL ELSE 10 END, CASE WHEN @p IS NULL THEN NULL ELSE @h END, 0)
""");
for (var i = 0; i < 1000; i++)
{
var state = stateOf(i);
insert.With("@d", w.General).With("@a", w.Marta).With("@h", Make.Sha(100 + i)).With("@s", state)
.With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null)
.With("@p", state == "Failed" ? null : $"marta.demo/{i}.jpg").ExecuteNonQuery();
}
},
default);
private static Task<(string? InstagramId, string? Username)> RemovedAccountAsync(FebeDatabase db, long copyId) =>
db.ReadAsync(
c =>