Files
Anubis/tests/Anubis.Tests/ArchiveTests.cs
Alby96andClaude Opus 5.5 4897594b87 Rebuild the state from the brokers after a restore and refuse an older copy
A restore, an import or an adopted database restarts protected: the engine
stays stopped, reads from the broker what the archive does not know (orders,
stops, executions, also from the OKX history up to 89 days), cancels orders
left working, protects what it finds and waits for the user. Strategies with
real money stay exit only until confirmed again. The database of before the
restore, put back by mistake, is refused by its fingerprint.

A failed migration leaves the engine off with one backup and a way to try
again; an archive is checked whole before the database is touched; a changed
secret key no longer crashes anything, and "anubis access reset" gives the
access back to whoever holds the computer. The image runs the db and access
commands without the guard.

refs #69

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:52:08 +01:00

356 lines
19 KiB
C#

using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>Export, import and backups (issue #9, SPEC 5.4).</summary>
[TestClass]
public sealed class ArchiveTests
{
private static readonly ManualClock _clock = new(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
/// <summary>Fills a database with rows of every column kind, including accounting rows and a reversal.</summary>
internal static async Task SeedAsync(Database db)
{
var (account, instrument) = await DatabaseTests.SeedAccountAsync(db).ConfigureAwait(false);
await db.WriteAsync(async s =>
{
var fill = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(1));
var reversal = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(2));
await s.ExecuteAsync(
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1', 'buy', @q, @p, @f, 'EUR', @t, @t)",
("id", fill), ("a", account), ("i", instrument), ("q", 0.0182m), ("p", 68950m), ("f", 1.254890000000000001m), ("t", _clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, reverses_id, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1-R', 'buy', @q, @p, @f, 'EUR', @r, @t, @t)",
("id", reversal), ("a", account), ("i", instrument), ("q", -0.0182m), ("p", 68950m), ("f", -1.254890000000000001m), ("r", fill), ("t", _clock.UtcNow)).ConfigureAwait(false);
for (var i = 0; i < 25; i++)
{
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, 'EUR', @v, 'deposit', @n, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(10 + i))), ("a", account), ("v", 100.01m * i - 333.333333333333333333m), ("n", i % 3 == 0 ? null : "nota \"" + i + "\" ;\n"),
("t", _clock.UtcNow.AddDays(-i))).ConfigureAwait(false);
}
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, data, created_at) VALUES (@id, @t, 'Ordini', 'stop_raised', @m, @d, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
}).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ExportThenImportOnTheSameEngineKeepsEverything()
{
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
await RoundTripAsync(source, target).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ExportFromOneEngineImportsIntoTheOtherWithSameCountsAndTotals()
{
if (!await TestDb.PostgresAvailableAsync().ConfigureAwait(false))
{
Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`.");
}
foreach (var (from, to) in new[] { (DbEngine.Sqlite, DbEngine.Postgres), (DbEngine.Postgres, DbEngine.Sqlite) })
{
await using var source = await TestDb.CreateAsync(from).ConfigureAwait(false);
await Migrations.MigrateAsync(source.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
await using var target = await TestDb.CreateAsync(to).ConfigureAwait(false);
await RoundTripAsync(source, target).ConfigureAwait(false);
}
}
private static async Task RoundTripAsync(TestDb source, TestDb target)
{
await SeedAsync(source.Db).ConfigureAwait(false);
var folder = TempFolder.Create("archive");
try
{
var index = await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
Assert.AreEqual(Migrations.Latest, index.SchemaVersion);
Assert.AreEqual(2L, index.Tables.Single(t => t.Name == "fills").Count);
Assert.AreEqual("0", index.AccountingTotals["fills.quantity"], "il fill e il suo storno si annullano");
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
CollectionAssert.AreEquivalent(
(await Archive.CountsAsync(source.Db).ConfigureAwait(false)).ToList(),
(await Archive.CountsAsync(target.Db).ConfigureAwait(false)).ToList(), $"{source.Db.Engine} → {target.Db.Engine}");
CollectionAssert.AreEquivalent(
(await Archive.AccountingTotalsAsync(source.Db).ConfigureAwait(false)).ToList(),
(await Archive.AccountingTotalsAsync(target.Db).ConfigureAwait(false)).ToList());
// A second export of the target is identical row by row.
await Archive.ExportAsync(target.Db, Path.Combine(folder, "b"), _clock).ConfigureAwait(false);
foreach (var table in Schema.Tables)
{
CollectionAssert.AreEqual(
File.ReadAllLines(Path.Combine(folder, "a", table.Name + ".jsonl")),
File.ReadAllLines(Path.Combine(folder, "b", table.Name + ".jsonl")), table.Name);
}
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ImportRefusesANonEmptyDatabaseAndATamperedArchive()
{
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await SeedAsync(source.Db).ConfigureAwait(false);
var folder = TempFolder.Create("archive-bad");
try
{
await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
await Assert.ThrowsAsync<InvalidOperationException>(() => Archive.ImportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
var cash = Path.Combine(folder, "a", "cash_ledger.jsonl");
var lines = File.ReadAllLines(cash);
File.WriteAllLines(cash, lines.Skip(1));
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<InvalidDataException>(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
Assert.IsEmpty(await Archive.CountsAsync(target.Db).ConfigureAwait(false), "un archivio guasto non lascia nemmeno lo schema");
await Assert.ThrowsAsync<IOException>(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task BackupsKeepTheLastFourteenAndCopyTheSqliteFile()
{
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await SeedAsync(test.Db).ConfigureAwait(false);
var folder = TempFolder.Create("backups");
try
{
var clock = new ManualClock(_clock.UtcNow);
var backups = new Backups(new DataDirectory(folder), clock);
for (var i = 0; i < 16; i++)
{
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
clock.Advance(TimeSpan.FromDays(1));
}
var list = backups.List();
Assert.HasCount(Backups.Keep, list);
Assert.AreEqual(clock.UtcNow.AddDays(-1).Date, list[0].TakenAt.UtcDateTime.Date, "la più recente è la prima");
Assert.AreEqual(test.Db.Engine == DbEngine.Sqlite, list[0].HasSqliteCopy);
Assert.IsFalse(Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories).Any(d => d.EndsWith(".partial", StringComparison.Ordinal)));
if (test.Db.Engine == DbEngine.Sqlite)
{
// The copy made with the backup API opens and has the same rows.
await using var copy = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(list[0].Folder, Backups.SqliteCopy) }, allowCreate: false);
CollectionAssert.AreEquivalent((await Archive.CountsAsync(test.Db).ConfigureAwait(false)).ToList(), (await Archive.CountsAsync(copy).ConfigureAwait(false)).ToList());
}
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MigratingADatabaseWithDataTakesABackupFirst()
{
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
var calls = 0;
await Migrations.MigrateAsync(test.Db, _clock, _ =>
{
calls++;
return Task.CompletedTask;
}, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(0, calls, "un database vuoto non ha nulla da salvare");
// A failing backup stops the migration (simulated on an older schema by removing the version row).
await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false);
if (Migrations.Latest > 1)
{
await Assert.ThrowsAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ADamagedArchiveLeavesTheDatabaseUntouchedAndTheGoodOneGoesInAfterwards()
{
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await SeedAsync(source.Db).ConfigureAwait(false);
var folder = TempFolder.Create("archive-retry");
try
{
var good = Path.Combine(folder, "a");
await Archive.ExportAsync(source.Db, good, _clock).ConfigureAwait(false);
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
async Task RefusedAsync(string file, Func<string, string> damage)
{
var path = Path.Combine(good, file);
var before = await File.ReadAllTextAsync(path).ConfigureAwait(false);
await File.WriteAllTextAsync(path, damage(before)).ConfigureAwait(false);
try
{
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
Assert.Fail("Accepted: " + file);
}
catch (Exception ex) when (Anubis.Server.Forms.IsArchiveProblem(ex))
{
}
await File.WriteAllTextAsync(path, before).ConfigureAwait(false);
Assert.IsTrue((await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty, "Not even the schema: " + file);
}
// A row less, a number that is not one, a total that changed, a row that is not an object.
await RefusedAsync("cash_ledger.jsonl", t => t[(t.IndexOf('\n', StringComparison.Ordinal) + 1)..]).ConfigureAwait(false);
await RefusedAsync("fills.jsonl", t => t.Replace("68950", "novanta", StringComparison.Ordinal)).ConfigureAwait(false);
await RefusedAsync("fills.jsonl", t => t.Replace("0.0182", "0.0183", StringComparison.Ordinal).Replace("-0.0183", "-0.0182", StringComparison.Ordinal)).ConfigureAwait(false);
await RefusedAsync("accounts.jsonl", _ => "[]\n").ConfigureAwait(false);
// An index that points outside its folder, or names a table twice.
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills.jsonl\"", "\"../fills.jsonl\"", StringComparison.Ordinal)).ConfigureAwait(false);
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills\"", "\"accounts\"", StringComparison.Ordinal)).ConfigureAwait(false);
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
Assert.AreEqual(2L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["fills"]);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnOlderArchiveGoesInAfterAnImportThatStoppedHalfWay()
{
await using var old = await TestDb.CreateAsync().ConfigureAwait(false);
await Migrations.MigrateAsync(old.Db, _clock, null, CancellationToken.None, upTo: 8).ConfigureAwait(false);
var folder = TempFolder.Create("archive-old");
try
{
await Archive.ExportAsync(old.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
// The first attempt created the schema of the archive and stopped there (power lost).
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
await Migrations.MigrateAsync(target.Db, _clock, null, CancellationToken.None, upTo: 5).ConfigureAwait(false);
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
Assert.AreEqual(Migrations.Latest, (await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).Current);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnImportIsSealedUntilTheInstallationIsRenewedAndSoIsTheSqliteCopy()
{
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var folder = TempFolder.Create("seal");
try
{
var data = new DataDirectory(Path.Combine(folder, "data"));
await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false);
var backup = await new Backups(data, _clock).TakeAsync(source.Db, "a-mano").ConfigureAwait(false);
// The same fingerprint as installation.json is in the archive: without the seal the import would be accepted as it is.
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
await Archive.ImportAsync(target.Db, Path.Combine(backup.Folder, Backups.ArchiveFolder), _clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
if (backup.HasSqliteCopy)
{
var copy = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(backup.Folder, Backups.SqliteCopy) };
await using var byHand = Database.Open(copy, allowCreate: false);
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(byHand, data, _clock).ConfigureAwait(false)).Verdict);
Assert.IsTrue((await Installation.ReadRowAsync(byHand).ConfigureAwait(false))!.ProtectedRestart);
}
// Renewed, the new one is accepted and the source becomes the old copy.
await Installation.RenewAsync(target.Db, data, _clock, "prova").ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false)).Verdict);
Assert.AreEqual(Installation.ReadFile(data)!.InstallationId, (await Installation.ReadRowAsync(source.Db).ConfigureAwait(false))!.Id, "The orders of the ledger keep their installation.");
// Rows without an installation are never taken for an empty database.
await SeedAsync(target.Db).ConfigureAwait(false);
await target.Db.WriteAsync(s => s.ExecuteAsync("DELETE FROM installation")).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ASeriesOfBackupsOfOneKindNeverPushesOutTheNightlyOnes()
{
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var folder = TempFolder.Create("kinds");
try
{
var clock = new ManualClock(_clock.UtcNow);
var data = new DataDirectory(folder);
var backups = new Backups(data, clock);
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
var left = Directory.CreateDirectory(Path.Combine(data.Backups, "20260901-010101-notturno.partial"));
left.LastWriteTimeUtc = clock.UtcNow.UtcDateTime.AddDays(-3);
for (var i = 0; i < Backups.Keep + 3; i++)
{
// The same second twice: the second one takes a number.
await backups.TakeAsync(test.Db, Backups.BeforeMigration).ConfigureAwait(false);
clock.Advance(TimeSpan.FromSeconds(i % 2));
}
Assert.HasCount(1, backups.List().Where(b => b.Reason == "notturno").ToList());
Assert.HasCount(Backups.Keep, backups.List().Where(b => b.Reason.StartsWith(Backups.BeforeMigration, StringComparison.Ordinal)).ToList());
Assert.IsFalse(Directory.Exists(left.FullName), "What a power failure left is cleaned.");
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AMigrationThatFailsIsASchemaProblemAndLeavesTheVersionBefore()
{
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None, upTo: 12).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")).ConfigureAwait(false);
var backups = 0;
var error = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ =>
{
backups++;
return Task.CompletedTask;
}, CancellationToken.None)).ConfigureAwait(false);
Assert.Contains("0013", error.Message);
Assert.AreEqual(1, backups);
Assert.AreEqual(12, (await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).Current);
// Without room for the backup nothing is migrated.
var full = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None))
.ConfigureAwait(false);
Assert.Contains("disco pieno", full.Message);
}
}