Fix the phase 2 review findings (refs #20 #23 #25)
ci / test (postgres) (push) Successful in 2m10s
ci / test (sqlite) (push) Successful in 2m14s
ci / image (push) Successful in 31s
ci / test (postgres) (pull_request) Failing after 2m50s
ci / test (sqlite) (pull_request) Successful in 2m27s
ci / image (pull_request) Skipped

- Gaps between the last stored bar and the first new one were never found,
  so a minute the live feed skipped, or a day missing right after the stored
  history, was lost for good. A gap is now new when it ends after the last
  bar held, and is downloaded again like any other.
- When one OKX connection dropped while the other kept writing, the write to
  the closed feed threw out of the live loop and left it marked connected.
  Writes now stop quietly, and the loop treats any failure (database
  included) as a drop: marked down, back off, reconnect.
- The background worker now survives a failed round instead of stopping for
  the life of the process.
- Alpaca gives adjusted prices on the basis of the download day, so a later
  split looked like a crash. Each download re-reads the last stored day and,
  if its adjusted/real ratio changed, rescales all older adjusted prices.
- Stock days are fetched up to the last closed New York session, so the job
  after the close collects that day; missing stock days are checked against
  the exchange calendar; delisted stocks with history are not asked again.
- Smaller: a lock in the freshness monitor, no NaN mood readings (SQLite
  stored them as NULL), and the network proof runs only with
  ANUBIS_LIVE_PROOF=1. The test wait is 30 s for busy machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 17:06:39 +01:00
1 parent 68fdd0baee
commit de2cc0eedf
10 files changed
+281 -36

No files matched your search

+85
View File
@@ -127,6 +127,91 @@ public sealed class CollectorTests
Assert.AreEqual(1, next.Confirmed);
Assert.AreEqual(BarQuality.Confirmed, (await bars.DailyAsync(btc.Id, day0.AddDays(120), day0.AddDays(120), CancellationToken.None).ConfigureAwait(false))[0].Quality);
Assert.AreEqual(CollectionResult.None, await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false), "nothing new");
// The first day after the stored history is missing on the first read: the hole between what is held and
// what arrived is a gap like any other, read again and recovered.
var basis = source.Days[day0.AddDays(120)];
foreach (var day in new[] { day0.AddDays(121), day0.AddDays(122) })
{
source.Days[day] = basis with { Day = day, Open = basis.Close, High = basis.Close * 1.002, Low = basis.Close * 0.998, Quality = BarQuality.Ok };
}
source.MissingOnFirstRead.Add(day0.AddDays(121));
clock.Advance(TimeSpan.FromDays(2));
var after = await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual((1, 1), (after.Gaps, after.Recovered), after.ToString());
Assert.AreEqual(3, (await bars.DailyAsync(btc.Id, day0.AddDays(120), day0.AddDays(122), CancellationToken.None).ConfigureAwait(false)).Count);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task LiveMinuteSkippedByTheFeedIsDownloadedAgain()
{
var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 10, 0, 30, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var bus = new EventBus();
var btc = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None).ConfigureAwait(false);
var source = new FakeMarketSource(clock);
var collector = new MarketCollector(source, test.Db, clock, bus, new FreshnessMonitor(clock, bus));
var bars = new BarStore(test.Db, clock);
var issues = new DataIssueStore(test.Db, clock);
using var stop = new CancellationTokenSource();
var live = collector.RunLiveAsync([btc], stop.Token);
await OkxTests.WaitForAsync(() => source.Connections == 1).ConfigureAwait(false);
Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 9, 59, 0, TimeSpan.Zero), await bars.LastMinuteAsync(btc.Id, CancellationToken.None).ConfigureAwait(false));
// The stream was subscribed too late for the 10:00 candle and sends 10:01 first.
var skipped = new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero);
clock.Advance(TimeSpan.FromMinutes(2));
await source.Live!.Writer.WriteAsync(new BarEvent("BTC-EUR", FakeMarketSource.MinuteBar(skipped.AddMinutes(1)), true)).ConfigureAwait(false);
await OkxTests.WaitForAsync(() =>
bars.MinuteAsync(btc.Id, skipped, skipped.AddMinutes(2), CancellationToken.None).GetAwaiter().GetResult().Count == 2).ConfigureAwait(false);
var gap = (await issues.SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).ConfigureAwait(false)).Single();
Assert.AreEqual((IssueKinds.Gap, IssueStatus.Recovered, skipped), (gap.Kind, gap.Status, gap.StartsAt));
await stop.CancelAsync().ConfigureAwait(false);
await live.ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ASplitAfterTheHistoryRebasesTheStoredAdjustedPrices()
{
var day0 = new DateOnly(2026, 6, 1);
var clock = new FastClock(new DateTimeOffset(day0.AddDays(100).ToDateTime(new TimeOnly(6, 0)), TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var bus = new EventBus();
var stock = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("ACME-EUR"), CancellationToken.None).ConfigureAwait(false);
static DailyBar Adjusted(DailyBar bar, double factor) =>
bar with { Adjusted = new Ohlc(bar.Open * factor, bar.High * factor, bar.Low * factor, bar.Close * factor) };
var walk = MarketDataLogicTests.Walk(100, day0);
var source = new FakeMarketSource(clock);
foreach (var bar in walk)
{
source.Days[bar.Day] = Adjusted(bar, 1);
}
var collector = new MarketCollector(source, test.Db, clock, bus, new FreshnessMonitor(clock, bus));
Assert.AreEqual(100, (await collector.BackfillDailyAsync(stock, day0, CancellationToken.None).ConfigureAwait(false)).Stored);
// A 2-for-1 split on day 100: the source now gives every older adjusted price halved, and the real price halves.
foreach (var bar in walk)
{
source.Days[bar.Day] = Adjusted(bar, 0.5);
}
var close = walk[^1].Close / 2;
source.Days[day0.AddDays(100)] = Adjusted(new DailyBar(day0.AddDays(100), close, close * 1.003, close * 0.997, close * 1.001, 2000), 1);
clock.Advance(TimeSpan.FromDays(1));
var result = await collector.BackfillDailyAsync(stock, day0, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual((1, 0), (result.Stored, result.Suspect), "the split is not a jump");
var stored = await new BarStore(test.Db, clock).DailyAsync(stock.Id, day0, day0.AddDays(100), CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(walk[50].Close, stored[50].Close, 1e-9, "real prices stay as they were");
Assert.AreEqual(walk[50].Close / 2, stored[50].Adjusted!.Value.Close, 1e-9, "older adjusted prices are on the new basis");
Assert.IsEmpty(await new DataIssueStore(test.Db, clock).SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).ConfigureAwait(false));
}
}
+48 -1
View File
@@ -220,6 +220,52 @@ public sealed class OkxTests
Assert.IsTrue(sockets.All(s => s.Disposed), "both connections are closed when the feed ends");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task OneConnectionDroppingEndsTheFeedWithoutAnError()
{
var sockets = new List<FakeSocket>();
var okx = new OkxClient(new FakeHttp().Client(), new ManualClock(_now), sockets: () =>
{
var socket = new FakeSocket();
lock (sockets)
{
sockets.Add(socket);
}
return socket;
});
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(20));
var reading = Task.Run(async () =>
{
await foreach (var item in okx.StreamAsync(["BTC-EUR"], stop.Token).ConfigureAwait(false))
{
await Task.Delay(1).ConfigureAwait(false); // A slow reader: tickers pile up in the channel.
}
});
await WaitForAsync(() => sockets.Count == 2 && sockets.All(s => s.Sent.Count == 1)).ConfigureAwait(false);
var publicSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/public", StringComparison.Ordinal));
var businessSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/business", StringComparison.Ordinal));
const string ticker = """{"arg":{"channel":"tickers","instId":"BTC-EUR"},"data":[{"instType":"SPOT","instId":"BTC-EUR","last":"66148.9","askPx":"66134.7","askSz":"0.01847","bidPx":"66129.6","bidSz":"0.0193605","ts":"1794318514123"}]}""";
for (var i = 0; i < 300; i++)
{
publicSocket.Push(ticker);
}
// The candle connection drops while tickers keep arriving: the feed ends cleanly, so the collector marks it
// down and reconnects, instead of failing on a write to the closed feed.
businessSocket.Close();
for (var i = 0; i < 300; i++)
{
publicSocket.Push(ticker);
}
await reading.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsTrue(sockets.All(s => s.Disposed));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void StreamErrorsStopTheFeed()
@@ -232,7 +278,8 @@ public sealed class OkxTests
internal static async Task WaitForAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
// Generous: on a busy machine (CI, PostgreSQL in Docker) the first backfill alone can take several seconds.
var deadline = DateTime.UtcNow.AddSeconds(30);
while (!condition())
{
if (DateTime.UtcNow > deadline)
+8 -3
View File
@@ -6,9 +6,9 @@ namespace Anubis.Tests;
/// <summary>
/// The Phase 2 proof on the real public sources (no keys): the whole daily history of the main OKX EUR pairs and the
/// Binance BTCUSDT archives since 2017, then the quality report. Needs the network, so it never runs in the normal
/// suite: <c>dotnet test --filter FullyQualifiedName~RealHistoryProof</c>. With ANUBIS_PROOF_OUT set, the report is
/// written there.
/// Binance BTCUSDT archives since 2017, then the quality report. Needs the network, so it runs only when asked:
/// ANUBIS_LIVE_PROOF=1 and <c>dotnet test --filter FullyQualifiedName~RealHistoryProof</c>. With ANUBIS_PROOF_OUT set,
/// the report is written there.
/// </summary>
[TestClass]
public sealed class RealHistoryProof
@@ -17,6 +17,11 @@ public sealed class RealHistoryProof
[TestCategory(Category.LiveDemo)]
public async Task DownloadsTheRealDailyHistoryAndReportsItsQuality()
{
if (Environment.GetEnvironmentVariable("ANUBIS_LIVE_PROOF") != "1")
{
Assert.Inconclusive("Needs the network: set ANUBIS_LIVE_PROOF=1 to run it.");
}
var clock = new SystemClock();
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };