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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 18:52:08 +01:00
1 parent 3da9b00f44
commit 4897594b87
40 files changed
+1871 -90

No files matched your search

+172 -3
View File
@@ -117,7 +117,7 @@ public sealed class ArchiveTests
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.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe");
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);
}
@@ -140,7 +140,7 @@ public sealed class ArchiveTests
var backups = new Backups(new DataDirectory(folder), clock);
for (var i = 0; i < 16; i++)
{
await backups.TakeAsync(test.Db, i == 0 ? "prima-della-migrazione" : "notturno").ConfigureAwait(false);
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
clock.Advance(TimeSpan.FromDays(1));
}
@@ -180,7 +180,176 @@ public sealed class ArchiveTests
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<IOException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
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);
}
}