Fase 9 — Rifinitura e consegna in Docker #111

Merged
Alby96 merged 18 commits from fase-9 into main 2026-12-03 14:07:16 +01:00
8 changed files with 199 additions and 23 deletions
Showing only changes of commit 8d7efe425d - Show all commits

No files matched your search

+6 -2
View File
@@ -23,8 +23,12 @@ expected=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' "$root/Directory.Build.
name="$REGISTRY/balbosoft/anubis" name="$REGISTRY/balbosoft/anubis"
# The image says what it was made from (its labels): only what comes from the commit of the tag is published as that tag. # The image says what it was made from (its labels): only what comes from the commit of the tag is published as that tag.
# Without the tag here, as in the CI, the commit checked out is the tag's. # Without the tag here, as in the CI, the repository on Gitea says its commit: the line with ^{} for an annotated tag.
commit=$(git -C "$root" rev-parse --verify --quiet "refs/tags/$tag^{commit}" || git -C "$root" rev-parse --verify --quiet HEAD) || fail "non riesco a leggere il commit del tag." commit=$(git -C "$root" rev-parse --verify --quiet "refs/tags/$tag^{commit}") || {
found=$(git -C "$root" ls-remote origin "refs/tags/$tag" "refs/tags/$tag^{}") || fail "non riesco a leggere i tag del repository."
commit=$(printf '%s\n' "$found" | sort -k 2 | tail -n 1 | cut -f 1)
}
[ -n "$commit" ] || fail "il tag $tag non c'è, né qui né nel repository: crealo prima di pubblicare."
label() { label() {
docker image inspect --format "{{ index .Config.Labels \"org.opencontainers.image.$1\" }}" "$image" docker image inspect --format "{{ index .Config.Labels \"org.opencontainers.image.$1\" }}" "$image"
} }
+3 -2
View File
@@ -275,14 +275,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var live = (await learning.Store.AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList(); var live = (await learning.Store.AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList();
var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false); var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false);
var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false); var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false);
var restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false);
var report = new ReviewReport var report = new ReviewReport
{ {
Missing = missing, Missing = missing,
RatesBefore = before, RatesBefore = before,
RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)), RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)),
RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome), RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome),
Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false), Restrictions = restrictions,
RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, now, cancellationToken).ConfigureAwait(false), RestrictionsEver = RestrictionBalance.Add(previous?.Report?.RestrictionsEver, restrictions),
}; };
var lines = new List<ReviewLine>(); var lines = new List<ReviewLine>();
foreach (var stage in all) foreach (var stage in all)
+27 -11
View File
@@ -85,20 +85,19 @@ public static class RestrictionBalance
foreach (var (example, blocks) in cases.Values) foreach (var (example, blocks) in cases.Values)
{ {
var code = Codes.First(c => blocks.Any(b => b.Code == c)); // A later block, or a purchase, can still change it: it is settled with the outcome, and what comes after no
var line = lines[code]; // longer counts.
var first = blocks[0].At; var first = blocks[0].At;
var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue; var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue;
DateTimeOffset? settled = example.Label is null ? null : example.LabelledAt > first ? example.LabelledAt : last > first ? last : first;
var counted = blocks.Where(b => settled is null || b.At <= settled).ToList();
var code = Codes.First(c => counted.Any(b => b.Code == c));
var line = lines[code];
// In observation nothing is ever bought: an entry only put off would have been made at its end. A later block of // In observation nothing is ever bought: an entry only put off would have been made at its end.
// the same example can still stop it, so it is settled with the outcome. var delayed = example.Stage == StrategyStages.Observation
var observed = example.Stage == StrategyStages.Observation; ? counted.All(b => b.Postponed)
var delayed = observed : trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last && (settled is null || t.OpenedAt <= settled));
? blocks.All(b => b.Postponed)
: trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last);
DateTimeOffset? settled = delayed && !observed
? trades.Where(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first).Min(t => t.OpenedAt)
: example.Label is null ? null : example.LabelledAt > first ? example.LabelledAt : last > first ? last : first;
if (settled is not { } known || known > until) if (settled is not { } known || known > until)
{ {
lines[code] = line with { Open = line.Open + 1 }; lines[code] = line with { Open = line.Open + 1 };
@@ -125,6 +124,23 @@ public static class RestrictionBalance
return new RestrictionReport([.. Codes.Select(c => lines[c]).Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]); return new RestrictionReport([.. Codes.Select(c => lines[c]).Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]);
} }
/// <summary>
/// The whole up to now: what the last review published plus the period after it, with the cases open now. The past is
/// not counted again, so it stays at the capital and the prices it was published with.
/// </summary>
public static RestrictionReport Add(RestrictionReport? before, RestrictionReport period)
{
ArgumentNullException.ThrowIfNull(period);
var lines = Codes.Select(code =>
{
var then = before?.Lines.FirstOrDefault(l => l.Code == code) ?? new RestrictionLine(code, 0, 0m, 0m, 0, 0, 0, 0);
var now = period.Lines.FirstOrDefault(l => l.Code == code) ?? new RestrictionLine(code, 0, 0m, 0m, 0, 0, 0, 0);
return new RestrictionLine(code, then.Stopped + now.Stopped, then.Avoided + now.Avoided, then.GivenUp + now.GivenUp, now.Open,
then.NeverStarted + now.NeverStarted, then.Delayed + now.Delayed, then.Increases + now.Increases);
});
return new RestrictionReport([.. lines.Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]);
}
/// <summary>The balance of the entries blocked whose outcome became known in a period.</summary> /// <summary>The balance of the entries blocked whose outcome became known in a period.</summary>
public static async Task<RestrictionReport> LoadAsync(Database db, IClock clock, DateTimeOffset from, DateTimeOffset until, CancellationToken cancellationToken) public static async Task<RestrictionReport> LoadAsync(Database db, IClock clock, DateTimeOffset from, DateTimeOffset until, CancellationToken cancellationToken)
{ {
+10 -1
View File
@@ -126,6 +126,9 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
/// <summary>The user has chosen and only a stop is missing: nothing is left to ask, the account returns to normal when it is back.</summary> /// <summary>The user has chosen and only a stop is missing: nothing is left to ask, the account returns to normal when it is back.</summary>
public const string StopReason = "waiting_for_stop"; public const string StopReason = "waiting_for_stop";
// A difference the user has not chosen about came while the stop was awaited: its kind follows.
private const string StopAndOther = StopReason + "+";
/// <summary>How long a difference may take to explain itself before the user is asked.</summary> /// <summary>How long a difference may take to explain itself before the user is asked.</summary>
public TimeSpan Grace { get; init; } = TimeSpan.FromMinutes(15); public TimeSpan Grace { get; init; } = TimeSpan.FromMinutes(15);
@@ -599,7 +602,13 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
{ {
// Something the user has not chosen about: it has its own 15 minutes to explain itself (SPEC 7.4). // Something the user has not chosen about: it has its own 15 minutes to explain itself (SPEC 7.4).
since = now; since = now;
reason = other.Kind; reason = StopAndOther + other.Kind;
}
else if (reason is not null && reason.StartsWith(StopAndOther, StringComparison.Ordinal) && since is { } came && now - came < Grace && differences.All(d => d.Kind == DifferenceKinds.Stop))
{
// It explained itself in time: only the stop is missing again, and nothing is left to ask.
since = now;
reason = StopReason;
} }
} }
else if (mode == AccountModes.Prudent && (reason == StopReason || (reason != KeyReason && since is { } start && now - start < Grace))) else if (mode == AccountModes.Prudent && (reason == StopReason || (reason != KeyReason && since is { } start && now - start < Grace)))
+40 -4
View File
@@ -324,6 +324,16 @@ public sealed partial class DeliveryTests
StringAssert.Contains(tasks, "$\"ANUBIS_VERSION={Version()}\""); StringAssert.Contains(tasks, "$\"ANUBIS_VERSION={Version()}\"");
StringAssert.Contains(tasks, "$\"ANUBIS_COMMIT={Commit()}\""); StringAssert.Contains(tasks, "$\"ANUBIS_COMMIT={Commit()}\"");
StringAssert.Contains(tasks, "\"-dirty\""); StringAssert.Contains(tasks, "\"-dirty\"");
// Only what goes into the image makes it unclean: a file of the user's, or a note, does not.
var parts = Regex.Match(tasks, "string\\[\\] imageSources = \\[(.*?)\\];", RegexOptions.Singleline).Groups[1].Value;
var copied = Text("deploy/docker/Dockerfile").Split('\n').Where(l => l.StartsWith("COPY ", StringComparison.Ordinal) && !l.Contains("--from", StringComparison.Ordinal))
.SelectMany(l => l.Split(' ', StringSplitOptions.RemoveEmptyEntries).Skip(1).SkipLast(1)).Where(p => !p.StartsWith("--", StringComparison.Ordinal)).ToList();
Assert.IsNotEmpty(copied);
foreach (var path in copied.Append(".dockerignore").Append("deploy/docker/Dockerfile"))
{
Assert.IsTrue(Regex.Matches(parts, "\"([^\"]+)\"").Any(m => path.TrimEnd('/') == m.Groups[1].Value || path.StartsWith(m.Groups[1].Value + "/", StringComparison.Ordinal)), path);
}
var build = (string)Steps("image").Single(s => ((string)s["run"]).Contains("docker build", StringComparison.Ordinal))["run"]; var build = (string)Steps("image").Single(s => ((string)s["run"]).Contains("docker build", StringComparison.Ordinal))["run"];
StringAssert.Contains(build, "version=${REF_NAME#v}"); StringAssert.Contains(build, "version=${REF_NAME#v}");
StringAssert.Contains(build, "\"ANUBIS_VERSION=$version\""); StringAssert.Contains(build, "\"ANUBIS_VERSION=$version\"");
@@ -412,6 +422,7 @@ public sealed partial class DeliveryTests
[DataRow("v0.9.0", "0.9.0", "fedcba9876543210fedcba9876543210fedcba98", false)] [DataRow("v0.9.0", "0.9.0", "fedcba9876543210fedcba9876543210fedcba98", false)]
[DataRow("v0.9.0", "0.9.0", "", false)] [DataRow("v0.9.0", "0.9.0", "", false)]
[DataRow("v0.9.0", "0.9.0", PublishRun.Commit, true)] [DataRow("v0.9.0", "0.9.0", PublishRun.Commit, true)]
[DataRow("v0.9.0", "0.9.0", PublishRun.TagObject, false)]
public async Task TheScriptRefusesAnImageThatIsNotTheOneOfTheTag(string tag, string version, string revision, bool tagged) public async Task TheScriptRefusesAnImageThatIsNotTheOneOfTheTag(string tag, string version, string revision, bool tagged)
{ {
using var run = new PublishRun("v0.7.0", version: version, revision: revision, tagged: tagged); using var run = new PublishRun("v0.7.0", version: version, revision: revision, tagged: tagged);
@@ -427,25 +438,48 @@ public sealed partial class DeliveryTests
[OSCondition(OperatingSystems.Linux)] [OSCondition(OperatingSystems.Linux)]
[DataRow("v0.9.0", PublishRun.TagCommit, true)] [DataRow("v0.9.0", PublishRun.TagCommit, true)]
[DataRow("v0.9.0-rc.1", PublishRun.TagCommit, true)] [DataRow("v0.9.0-rc.1", PublishRun.TagCommit, true)]
[DataRow("v0.9.0-rc.1", PublishRun.Commit, false)] [DataRow("v0.9.0-rc.1", PublishRun.RemoteCommit, false)]
public async Task TheScriptTakesTheImageOfTheTasksAtTheCommitOfTheTag(string tag, string revision, bool tagged) public async Task TheScriptTakesTheImageOfTheTasksAtTheCommitOfTheTag(string tag, string revision, bool tagged)
{ {
// The commit of the tag when the tag is here, otherwise the one checked out: in the workflow they are the same. // The commit of the tag when the tag is here, otherwise the one the repository on Gitea has for it.
using var run = new PublishRun("v0.7.0", version: "0.9.0", revision: revision, tagged: tagged); using var run = new PublishRun("v0.7.0", version: "0.9.0", revision: revision, tagged: tagged);
var (code, output) = await run.RunAsync(tag, PublishRun.Token); var (code, output) = await run.RunAsync(tag, PublishRun.Token);
Assert.AreEqual(0, code, output); Assert.AreEqual(0, code, output);
Assert.IsNotEmpty(run.Pushed()); Assert.IsNotEmpty(run.Pushed());
} }
[TestMethod]
[TestCategory(Category.Integration)]
[OSCondition(OperatingSystems.Linux)]
public async Task TheScriptRefusesATagThatIsNowhere()
{
// The commit checked out is not asked: an image of it would be published under a tag nobody made.
using var run = new PublishRun("v0.7.0", revision: PublishRun.Commit, pushed: false);
var (code, output) = await run.RunAsync("v0.9.0", PublishRun.Token);
Assert.AreEqual(1, code, output);
StringAssert.Contains(output, "Pubblicazione non riuscita: il tag v0.9.0 non c'è");
Assert.IsEmpty(run.Pushed());
Assert.AreEqual("", run.Input, "Not even the login.");
// A light tag names its commit directly.
using var light = new PublishRun("v0.7.0", revision: PublishRun.TagObject, light: true);
(code, output) = await light.RunAsync("v0.9.0", PublishRun.Token);
Assert.AreEqual(0, code, output);
}
private sealed class PublishRun : IDisposable private sealed class PublishRun : IDisposable
{ {
// The annotated tag on Gitea, and the commit it names.
public const string TagObject = "1111111111222222222233333333334444444444";
public const string RemoteCommit = "5555555555666666666677777777778888888888";
public const string Token = "a-token-only-for-the-test"; public const string Token = "a-token-only-for-the-test";
public const string Commit = "0123456789abcdef0123456789abcdef01234567"; public const string Commit = "0123456789abcdef0123456789abcdef01234567";
public const string TagCommit = "89abcdef0123456789abcdef0123456789abcdef"; public const string TagCommit = "89abcdef0123456789abcdef0123456789abcdef";
private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N")); private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N"));
public PublishRun(string others, bool gitFails = false, string? version = null, string revision = Commit, bool tagged = false) public PublishRun(string others, bool gitFails = false, string? version = null, string revision = RemoteCommit, bool tagged = false, bool pushed = true, bool light = false)
{ {
Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker")); Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker"));
Directory.CreateDirectory(Path.Combine(_root, "bin")); Directory.CreateDirectory(Path.Combine(_root, "bin"));
@@ -455,7 +489,8 @@ public sealed partial class DeliveryTests
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n" + Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n" +
$"case \"$*\" in *image.version*) printf '%s\\n' \"$VERSION\" ;; *image.revision*) printf '%s\\n' '{revision}' ;; esac\n"); $"case \"$*\" in *image.version*) printf '%s\\n' \"$VERSION\" ;; *image.revision*) printf '%s\\n' '{revision}' ;; esac\n");
var tagCommit = tagged ? $"printf '%s\\n' {TagCommit}; exit 0" : "exit 1"; var tagCommit = tagged ? $"printf '%s\\n' {TagCommit}; exit 0" : "exit 1";
Tool("git", $"case \"$*\" in *rev-parse*refs/tags/*) {tagCommit} ;; *rev-parse*HEAD*) printf '%s\\n' {Commit}; exit 0 ;; esac\n" + var remote = !pushed ? "" : $"printf '{TagObject}\\t%s\\n' \"refs/tags/$TAGGED\"; " + (light ? "" : $"printf '{RemoteCommit}\\t%s\\n' \"refs/tags/$TAGGED^{{}}\"; ");
Tool("git", $"case \"$*\" in *rev-parse*refs/tags/*) {tagCommit} ;; *rev-parse*HEAD*) printf '%s\\n' {Commit}; exit 0 ;; *ls-remote*\\^{{}}*) {(gitFails ? "exit 128" : remote + "exit 0")} ;; esac\n" +
(gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n")))); (gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n"))));
} }
@@ -478,6 +513,7 @@ public sealed partial class DeliveryTests
info.ArgumentList.Add(tag); info.ArgumentList.Add(tag);
info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH"); info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH");
info.Environment["RECORD"] = _root; info.Environment["RECORD"] = _root;
info.Environment["TAGGED"] = tag;
info.Environment["VERSION"] = _version ?? tag[1..]; info.Environment["VERSION"] = _version ?? tag[1..];
info.Environment["REGISTRY"] = "registry.test"; info.Environment["REGISTRY"] = "registry.test";
info.Environment["REGISTRY_USER"] = "someone"; info.Environment["REGISTRY_USER"] = "someone";
+80 -1
View File
@@ -69,6 +69,9 @@ public sealed class QuarterlyReviewTests
public Exception? Failure { get; set; } public Exception? Failure { get; set; }
/// <summary>The program is stopped while the history is prepared.</summary>
public CancellationTokenSource? StopWhilePreparing { get; set; }
public List<DateOnly> Prepared { get; } = []; public List<DateOnly> Prepared { get; } = [];
public Database Db => Live.Rig.Db; public Database Db => Live.Rig.Db;
@@ -101,6 +104,8 @@ public sealed class QuarterlyReviewTests
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) => Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
{ {
Prepared.Add(to); Prepared.Add(to);
StopWhilePreparing?.Cancel();
StopWhilePreparing?.Token.ThrowIfCancellationRequested();
return Failure is { } failure ? Task.FromException<string?>(failure) : Task.FromResult(Missing); return Failure is { } failure ? Task.FromException<string?>(failure) : Task.FromResult(Missing);
}); });
Lab.ReviewTrialEnded = Review.ConcludeAsync; Lab.ReviewTrialEnded = Review.ConcludeAsync;
@@ -246,8 +251,11 @@ public sealed class QuarterlyReviewTests
await rig.NightAsync(At(2027, 1, 6)); await rig.NightAsync(At(2027, 1, 6));
rig.Clock.Set(At(2027, 1, 17)); rig.Clock.Set(At(2027, 1, 17));
using var stop = new CancellationTokenSource(); using var stop = new CancellationTokenSource();
await stop.CancelAsync(); rig.StopWhilePreparing = stop;
var prepared = rig.Prepared.Count;
await Assert.ThrowsAsync<OperationCanceledException>(() => rig.Review.RunIfDueAsync(stop.Token)); await Assert.ThrowsAsync<OperationCanceledException>(() => rig.Review.RunIfDueAsync(stop.Token));
rig.StopWhilePreparing = null;
Assert.HasCount(prepared + 1, rig.Prepared, "Stopped while preparing, not before.");
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status); Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
rig.Failure = new InvalidOperationException("broken archive at C:\\x"); rig.Failure = new InvalidOperationException("broken archive at C:\\x");
@@ -768,6 +776,77 @@ public sealed class QuarterlyReviewTests
Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent)); Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent));
} }
/// <summary>What was said of a period stays: later blocks, and trades, of the same example do not move it.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void WhatWasSettledStaysUnderTheRowOfThen()
{
var first = _t0.AddDays(3);
var never = Case("AAA", null, null, null) with { LabelledAt = _t0.AddDays(2) };
var delayed = Case("BBB", false, -0.1, 2) with { LabelledAt = _t0.AddDays(2.5) };
IReadOnlyList<BlockedEntry> before = [Block(never, NewsReasons.Negative), Block(delayed, NewsReasons.Negative)];
IReadOnlyList<BlockedEntry> after = [.. before, Block(never, NewsReasons.Severe, minutes: 5 * 24 * 60)];
RestrictionReport Of(IReadOnlyList<BlockedEntry> blocks, IReadOnlyList<HeldTrade> trades, DateTimeOffset from, DateTimeOffset until) =>
RestrictionBalance.Of(blocks, [never, delayed], trades, _capital, from, until);
var one = Of(before, [], DateTimeOffset.UnixEpoch, first);
Assert.AreEqual(new RestrictionLine(NewsReasons.Negative, 1, 80m, 0m, 0, 1, 0, 0), one.Lines.Single());
HeldTrade[] bought = [new(Crypto, "AAA", _t0.AddDays(8), null), new(Crypto, "BBB", _t0.AddDays(8), null)];
Assert.IsTrue(Of(after, bought, first, _t0.AddDays(30)).IsEmpty);
Assert.AreEqual(one.Lines.Single(), Of(after, bought, DateTimeOffset.UnixEpoch, _t0.AddDays(30)).Lines.Single());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheWholeIsWhatWasPublishedPlusThePeriod()
{
var before = new RestrictionReport([new(NewsReasons.Severe, 2, 80m, 20m, 3, 1, 2, 4), new(CorrectiveReasons.CalendarEvent, 0, 0m, 0m, 2, 0, 0, 0)]);
var period = new RestrictionReport([new(NewsReasons.Severe, 1, 0m, 5m, 1, 2, 3, 1), new(NewsReasons.Negative, 1, 7m, 0m, 0, 0, 0, 0)]);
var ever = RestrictionBalance.Add(before, period);
CollectionAssert.AreEqual(new RestrictionLine[] { new(NewsReasons.Severe, 3, 80m, 25m, 1, 3, 5, 5), new(NewsReasons.Negative, 1, 7m, 0m, 0, 0, 0, 0) }, ever.Lines.ToList(),
"What is open is what is open now.");
CollectionAssert.AreEqual(period.Lines.ToList(), RestrictionBalance.Add(null, period).Lines.ToList());
}
/// <summary>Capital and prices change between two reviews: what the first one published is not counted again at the new ones.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWholeDoesNotMoveWithTheCapitalOfToday()
{
await using var rig = await ReviewRig.CreateAsync();
async Task StoppedAsync(string symbol, DateTimeOffset at)
{
rig.Clock.Set(at);
var decision = Guid.NewGuid();
await rig.Db.WriteAsync(s => DecisionLog.WriteAsync(s, rig.Clock, new DecisionRow(decision, Crypto, null, symbol, DecisionStages.Order, DecisionOutcomes.Refused, [NewsReasons.Severe],
new Dictionary<string, object?>(), at), _none), _none);
var example = new Example(Guid.NewGuid(), Crypto, symbol, CaseSources.Live, DateOnly.FromDateTime(at.UtcDateTime).AddDays(-1), at, "trend_entry", 0.2m, null, null, new Dictionary<string, double>())
{
Stage = StrategyStages.Simulation,
DecisionId = decision,
};
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, _none), _none);
rig.Clock.Set(at.AddDays(5));
await rig.Db.WriteAsync(s => LearningStore.AddLabelAsync(s, rig.Clock, example.Id, new CaseLabel(false, -0.1, example.Day.AddDays(1), example.Day.AddDays(4), "x"), _none), _none);
}
await StoppedAsync("ETH-EUR", new DateTimeOffset(2026, 10, 1, 10, 0, 0, TimeSpan.Zero));
var one = (await rig.ReviewAsync(passed: false)).Report!;
Assert.IsGreaterThan(0m, one.RestrictionsEver.Avoided);
Assert.AreEqual(one.Restrictions.Avoided, one.RestrictionsEver.Avoided);
await StoppedAsync("SOL-EUR", rig.Clock.UtcNow.AddDays(20));
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET capital = 12345", _none), _none);
await rig.NightAsync(At(2027, 4, 5));
var second = (await QuarterlyReview.ListAsync(rig.Db, _none))[0];
await rig.EndAsync(second, passed: false);
await rig.Review.ConcludeAsync(_none);
var two = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(r => r.Id == second.Id).Report!;
Assert.IsGreaterThan(0m, two.Restrictions.Avoided);
Assert.AreNotEqual(one.Restrictions.Avoided, two.Restrictions.Avoided);
Assert.AreEqual(one.RestrictionsEver.Avoided + two.Restrictions.Avoided, two.RestrictionsEver.Avoided);
Assert.AreEqual(2, two.RestrictionsEver.Lines.Single().Stopped);
}
[TestMethod] [TestMethod]
[TestCategory(Category.Integration)] [TestCategory(Category.Integration)]
public async Task TheFirstReviewCountsTheRestrictionsFromTheStart() public async Task TheFirstReviewCountsTheRestrictionsFromTheStart()
+29
View File
@@ -329,11 +329,40 @@ public sealed class ReconcilerTests
Assert.IsFalse(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace), "It may still explain itself."); Assert.IsFalse(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace), "It may still explain itself.");
s.Rig.Clock.Advance(TimeSpan.FromMinutes(16)); s.Rig.Clock.Advance(TimeSpan.FromMinutes(16));
s.Broker.Missing.Clear(); s.Broker.Missing.Clear();
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
Assert.AreEqual(DifferenceKinds.Stop, state.Differences.Single().Kind);
Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace), "Gone too late.");
Assert.AreNotEqual(Reconciler.StopReason, state.ModeReason);
s.Broker.RefuseStops = false; s.Broker.RefuseStops = false;
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode); Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
Assert.AreEqual(ReconcileResolution.Normal, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false)); Assert.AreEqual(ReconcileResolution.Normal, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false));
} }
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ADifferenceThatComesAndGoesDoesNotMakeTheStopAwaitedAskAgain()
{
await using var s = await HoldingAsync().ConfigureAwait(false);
var stop = (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single();
await s.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none).ConfigureAwait(false);
s.Broker.RefuseStops = true;
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
s.Rig.Clock.Advance(TimeSpan.FromMinutes(16));
Assert.AreEqual(ReconcileResolution.StopsMissing, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false));
// Coin leaves the account and is back 5 minutes later, the stop still refused: the user has nothing to choose.
s.Broker.Missing["BTC-EUR"] = 0.004m;
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
s.Rig.Clock.Advance(TimeSpan.FromMinutes(5));
s.Broker.Missing.Clear();
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
Assert.AreEqual(Reconciler.StopReason, (await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).ModeReason);
s.Rig.Clock.Advance(TimeSpan.FromMinutes(20));
s.Broker.RefuseStops = false;
Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
}
[TestMethod] [TestMethod]
[TestCategory(Category.Simulation)] [TestCategory(Category.Simulation)]
public async Task AKeyThatMayWithdrawStopsPurchasesUntilItIsReplaced() public async Task AKeyThatMayWithdrawStopsPurchasesUntilItIsReplaced()
+4 -2
View File
@@ -86,11 +86,13 @@ int BuildImage(string tag) =>
"-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0; "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0;
// The commit written in the image, so a diagnostics report says which code it comes from and only the commit of a tag is // The commit written in the image, so a diagnostics report says which code it comes from and only the commit of a tag is
// published as that tag; with something not committed it is marked, and empty without git. // published as that tag; with something of the image not committed it is marked, and empty without git.
string Commit() string Commit()
{ {
// What the Dockerfile copies, and what decides it.
string[] imageSources = ["Directory.Build.props", "Directory.Packages.props", "global.json", ".dockerignore", "src", "deploy/docker", "docs/design/logo", "docs/backtests", "docs/learning"];
var commit = Git("rev-parse", "HEAD"); var commit = Git("rev-parse", "HEAD");
return commit is null ? "" : Git("status", "--porcelain") is "" ? commit : commit + "-dirty"; return commit is null ? "" : Git(["status", "--porcelain", "--", .. imageSources]) is "" ? commit : commit + "-dirty";
} }
// What a git command answers; null when it fails or git is not there. // What a git command answers; null when it fails or git is not there.