Skip to content
Edit this page

Proving a store with the conformance suite

A Bellhop store implements IJobStore, whose documentation states what each member must do. The Bellhop.Storage.Conformance package checks that a store does it: every member, the races between nodes (claims, unique keys, recurring triggers, the job index, the notification lease) and seeded random runs. It is the suite Bellhop's own stores run: the in-memory store and PostgreSQL pass it in CI, from the packed package, and SQLite, SQL Server and Redis pass it from their own test projects. A store author runs it from the store's own test project.

Installing

The suite is a set of xUnit v3 test classes, so it runs only in an xUnit v3 test project, one that references the xunit.v3 package. The package brings xUnit v3's library parts (xunit.v3.extensibility.core and xunit.v3.assert), AwesomeAssertions and FakeTimeProvider; the project brings the runner. In the store's test project:

dotnet add package Bellhop.Storage.Conformance --prerelease

The package depends on Bellhop at exactly its own version. Install the version of the Bellhop your store builds on.

Writing the ConformanceStore

The suite reaches the store through a ConformanceStore: the store under test, on an empty storage with its schema in place, and the few writes no store member makes, such as a state no single call ends in, or time passing. Each test creates one and disposes it after. Here is one for MyStore, which keeps its jobs in a database and reads its time from a TimeProvider:

/// <summary>MyStore under the conformance suite: a database of its own for each test, on a clock only the suite moves.</summary>
public sealed class MyConformanceStore : ConformanceStore
{
    private readonly FakeTimeProvider _clock;
    private readonly MyStoreDatabase _database;

    private MyConformanceStore(FakeTimeProvider clock, MyStoreDatabase database) => (_clock, _database) = (clock, database);

    public override IJobStore Store => _database.Store;

    // The database keeps microseconds.
    public override TimeSpan TimeResolution => TimeSpan.FromTicks(TimeSpan.TicksPerMicrosecond);

    // MyStore reads its time from a TimeProvider, so a fake one is its clock, and passing time moves it.
    public static async Task<MyConformanceStore> CreateAsync(CancellationToken ct)
    {
        var clock = new FakeTimeProvider();
        return new MyConformanceStore(clock, await MyStoreDatabase.CreateAsync(clock, ct));
    }

    public override Task PassTimeAsync(TimeSpan time, CancellationToken ct)
    {
        _clock.Advance(time);
        return Task.CompletedTask;
    }

    // A store with its own connection pool, as a second node opens one, so racing callers do not share connections.
    public override Task<IJobStore> OpenNodeAsync(CancellationToken ct) => _database.OpenStoreAsync(ct);

    public override Task SetJobStateAsync(JobId id, JobState state, CancellationToken ct) =>
        UpdateJobAsync(id, $"UPDATE jobs SET state = {(int)state} WHERE id = {id.Value}", ct);

    public override Task SetJobCreatedAtAsync(JobId id, DateTimeOffset createdAt, CancellationToken ct) =>
        UpdateJobAsync(id, $"UPDATE jobs SET created_at = {createdAt} WHERE id = {id.Value}", ct);

    public override async Task RemoveOccurrencesAsync(string recurringName, CancellationToken ct) =>
        await _database.ExecuteAsync($"DELETE FROM recurring_occurrences WHERE recurring_name = {recurringName}", ct);

    // Read from the table, not through QueryJobsAsync: some checks test QueryJobsAsync against this.
    public override async Task<IReadOnlyList<JobInfo>> ReadAllJobsAsync(CancellationToken ct)
    {
        var jobs = new List<JobInfo>();
        foreach (var id in await _database.QueryAsync($"SELECT id FROM jobs ORDER BY id", ct))
        {
            jobs.Add(await Store.GetJobAsync(new JobId(id), ct) ?? throw new InvalidOperationException($"Job {id} is gone."));
        }

        return jobs;
    }

    protected override async ValueTask DisposeAsyncCore()
    {
        await _database.DisposeAsync();
        await base.DisposeAsyncCore();
    }

    private async Task UpdateJobAsync(JobId id, FormattableString sql, CancellationToken ct)
    {
        if (await _database.ExecuteAsync(sql, ct) == 0)
        {
            throw new InvalidOperationException($"The store has no job {id}.");
        }
    }
}

MyStoreDatabase stands for the store's own test helper: it creates an empty database with the schema, opens the store on it and runs SQL. Every store has its own; the suite needs none.

The members a ConformanceStore overrides:

Member Needed What it does
Store always The store under test, bound to the default namespace.
PassTimeAsync always Lets at least the given time pass for everything the store holds, and at most a second more: every wait, lease, due time, cooldown and retention it judges has that much longer behind it.
SetJobStateAsync always Rewrites only the stored state of a job the suite has just created, recording no transition, for the states no single call ends in (Unroutable, Awaiting).
SetJobCreatedAtAsync always Rewrites only the job's creation time, which no store member sets.
RemoveOccurrencesAsync always Drops every stored occurrence of a recurring job of the default namespace and keeps their jobs.
ReadAllJobsAsync always Every job of the default namespace in the order they were created, read from the store's own data.
TimeResolution when the store keeps less than a tick The finest time the store keeps, such as a database's microsecond.
ClockStepBack when the clock can step back and cannot be frozen How far the store's clock can step back between two calls. See the store's time.
OpenNodeAsync when the store has per-node state Another store on the same storage, with its own connections and caches, as a second node opens it. The race checks spread their callers over these. By default it is Store itself, so a store with connection pools or caches that does not override it races against itself only.
ForNamespaceAsync with StoreCapabilities.Namespaces The store bound to another namespace on the same storage.
BeginTransactionAsync with StoreCapabilities.TransactionalEnqueue A transaction on a connection of its own, as an application begins one to create a job in it. The suite commits or rolls back and disposes the transaction; the adapter disposes the connection.
FreezeTimeAsync, ExpireLeaseAsync, AgeAsync depends on the clock See the store's time.
SettleAsync when reads lag committed writes Waits until a read sees every write committed before the call. By default it does nothing. A store that positions what it reads by what has ended, such as a database's transaction horizon, overrides it.
DisposeAsyncCore when it holds anything Releases the storage and every store it opened.

Stores that OpenNodeAsync and ForNamespaceAsync return are the adapter's to dispose. The suite calls one adapter from one test, but a race check calls it from several tasks at once, so what it opens on demand must be safe to call that way.

A store that reports Namespaces or TransactionalEnqueue but does not override the member it needs fails those tests with NotSupportedException, naming the member.

The store's time

The suite reads the store's time only through IJobStore.GetUtcNowAsync, moves it only through PassTimeAsync, and never waits for wall-clock time to pass. A correct store passes it the same way every run.

  • A store that reads its time from a TimeProvider, as MyStore and the in-memory store do, runs on a FakeTimeProvider that PassTimeAsync advances. Nothing else about time needs overriding.
  • A store whose clock is a database server's cannot move that clock forward. Its PassTimeAsync may instead move every time the store holds back, in every table, by the time passed. That moves the times the store reports too, so the suite never compares a time it read before a pass with one read after it: it reads again.
  • ExpireLeaseAsync and AgeAsync pass time by default: one until the job's lease has ended, the other until the job's latest transition is old enough. Some checks compare times read on either side of them, so a store that moves its stored times back overrides both to move only the times of the job they name: its lease end, or its transitions and creation time.
  • FreezeTimeAsync is for a clock that can step back between two calls, such as a database server's on a virtual machine. From the call on, the store's time moves only through PassTimeAsync. The suite calls it before it reads Store in a check that compares two times the store took from its clock in separate calls, so it may give a different Store from then on. By default it does nothing.
  • ClockStepBack is for a clock that can step back but cannot be frozen, such as SQL Server's SYSUTCDATETIME(), which no session can replace. It is an allowance for a test clock, not a promise about the order of the store's times. A check that bounds the time a call took by the store's times read just before and just after it in other calls widens both edges by it, since a step back on either side of the call moves the call's time past one edge. A check that reads as due what an earlier call made due at once first passes this much time. Bounds within one call stay exact. It is zero by default, which keeps those checks exact.

The PostgreSQL store's adapter, PostgresConformanceStore, does all of this with the server's clock, on the public API only.

One class per suite

The suite comes in areas. Run an area by deriving a sealed test class from its suite and creating the store in CreateStoreAsync; every test of the class then runs on a store of its own:

public sealed class MyStoreBatchTests : BatchConformance
{
    protected override async Task<ConformanceStore> CreateStoreAsync(CancellationToken ct) => await MyConformanceStore.CreateAsync(ct);
}

Derive one for each of the 27 suites, also those whose capability the store leaves out. ConformanceStore and StoreConformance are in Bellhop.Storage.Conformance; the suites are in its area namespaces: Jobs, Batches, Recurring, Notifications and Operations (API keys, launches, node samples, tags and throttle keys). A class may add the store's own tests after the suite's.

Suite What it proves
ApiKeyConformance Dashboard API keys are stored with their hash only, each name and hash is held once per namespace in every state, revoked and expired are final, an expiry marks exactly the active keys past it, and racing creates and revokes each land once.
BatchConformance A batch is kept whole, moves in the same write as its last member's outcome or removal, releases its continuations once, and is removed with its members once each is past its retention.
BatchPropertyConformance Seeded random runs of batches mixed with every state change, checked after each step: each batch moves only by its members, each continuation is released once, and nothing awaits what is gone.
BulkCreateConformance CreateJobsAsync stores all its jobs or none, in the order of its list, each under its unique key policy.
CapabilityConformance What a store with transactional enqueue or push notifications does, and what a store without them does.
ClaimByIdConformance Claiming one job by its id under the processing controls and throttles: the refusals and their order, the concurrency keys it holds and the starts it records for rate limits.
ClaimConformance Claimers on several nodes never give a job two claims, recovery on several nodes takes each expired lease back once and no live one, and a token taken back no longer moves its job.
ContinuationConformance Continuations and chains wait, resolve in the same write as their parent's outcome, cascade cancellations, and are refused where the contract forbids them.
JobIndexConformance IJobIndex entries are added and removed once, also from several nodes at once, paged in one strict order and counted as paged.
JobLogConformance A job's captured log and progress: lines kept in order up to the limit, written only by the run that holds the job, and removed with it.
LaunchConformance Dashboard launches are recorded under ids above every earlier one of their namespace, read back exactly, listed newest first, and pruned to the newest a record keeps in the same step, also when several nodes record at once; a launch touches no job and outlives the one it names.
NamespaceConformance Jobs and what belongs to them are kept per namespace, and the rest is shared by name.
NodeSampleConformance Node metrics samples read back exactly, ordered by node and time, one per node and time however often written, and a removal takes only samples older than its time, each once when removals race.
NotificationConformance The notification lease has one holder at a time, only the holder renews or releases it, deliveries are written and read as the contract says, and a race for it is won once.
NotificationCooldownConformance A rule's firing is pending, duplicate, capped or suppressed as its open cooldowns decide, by the store's time, and decided once when firings race.
NotificationEvaluationConformance Alert rules evaluated by the store alert each event once per rule version, and judge failure rate, queue depth and throttle starvation by the store's time.
NotificationEvaluationRaceConformance Evaluations stay once per event as the notification lease moves between nodes, through pauses, crashes and rule edits.
PagedReadConformance Nodes, recurring jobs, dashboard API keys and queues are read a page at a time after a cursor, ascending by name in one order for every page, ordinal or by code point, so walking the pages gives each record once as the unpaged read gives it; a queue is listed for an enqueued job of the namespace or a setting alone; the samples and last outcomes of a page's nodes and recurring jobs are read for the names given alone, per namespace.
ParameterConformance Typed parameters are stored exactly as given, carried by claims, replaced only by an outcome that gives them, and kept by a requeue.
PromotionConformance Due scheduled jobs and retries are promoted once however many nodes promote at once, and each promotion reports how soon the next one of its namespace falls due by the store's clock, within the look-ahead it is given and never beyond it.
QueryJobsConformance The jobs list reads newest first, page by page from a cursor, under every filter, matching what the store holds.
RecurringDefinitionConformance A recurring job's validity window and configuration origin are kept by every write.
RecurringHistoryConformance A recurring job's latest occurrences are read newest first by id, at most the count asked for, each as GetOccurrencesAsync gives it, with its job's state and the start and end of the job's latest attempt; no other name's or namespace's occurrences are read, and the read changes nothing.
RecurringTriggerConformance Triggers of one due instant from several nodes land once through the compare-and-set, a stale read or the maintenance pause makes a write lose, and the sweeps beside them do each piece of work once.
ResultConformance Results are stored by the success write, read back as written, and removed with the job.
SchemaConformance The schema is at the version the store expects, migrating again applies nothing however many nodes migrate at once, and the capabilities read the same every time.
TagConformance Tags, correlation ids and parameters are stored by every creating member, filed in the job index, added while a run holds the job, and removed with it.
TagSummaryConformance The tags in use are listed per namespace with their jobs, succeeded and dead-lettered counted apart when the call is made, and only while they have an index entry; paging by the store's own cursor gives each tag in use once, in one order whatever the page size.
ThrottleKeyConformance Every key with a setting or a processing holder is listed ordinally by key with its settings, its holders of every namespace counted, the namespace's own listed by id, and the namespace's enqueued jobs waiting for it and since when the longest has.
UniqueKeyConformance Creates, reschedules and requeues with one key from several nodes at once leave exactly one active job holding it, and the key is free again once that job finishes.

xUnit runs the classes in parallel, and each test opens its own store, with OpenNodeAsync's stores beside it. A store whose server allows few connections limits that with maxParallelThreads in the project's xunit.runner.json; Bellhop's own run of the packages on PostgreSQL runs eight classes at a time.

Capabilities a store may leave out

A store reports what it can do beyond the operations every store has in GetCapabilitiesAsync. It may leave out any of the four:

  • TransactionalEnqueue: creating a job in the application's own database transaction.
  • PushNotifications: waking idle workers when work arrives.
  • ResultStorage: keeping the results of jobs that produce one.
  • Namespaces: keeping jobs, recurring jobs and nodes per namespace.

The suite reads the capabilities before each test that needs one. A test that needs a capability the store does not report is skipped, and the skip names the store and the capability, for example: MyJobStore does not report StoreCapabilities.ResultStorage, so it keeps no job result for the result checks to read. A test of what a store without a capability does is skipped for a store that reports it. So the classes for ResultConformance and NamespaceConformance stay in the project; a store without those capabilities sees their tests skipped, not failed. Read the skip reasons once: each should name a capability the store leaves out on purpose.

Race and random sizes

Two sizes set how hard the suite pushes, and each class can raise them:

  • RaceRounds (15): how many rounds each race check runs. Callers start at once on the stores OpenNodeAsync gives, and each round is judged on its own.
  • RandomRuns (8): how many seeded random runs each property check makes. A failure names the seed that reproduces it.

A store whose calls are cheap raises them, so a rare interleaving is likelier to be met:

public sealed class MyStoreClaimTests : ClaimConformance
{
    // MyStore's calls are cheap, so more rounds meet rarer interleavings; a listing needs at least the defaults.
    protected override int RaceRounds => 50;

    protected override async Task<ConformanceStore> CreateStoreAsync(CancellationToken ct) => await MyConformanceStore.CreateAsync(ct);
}

Lower values make a slow store's local runs shorter, but they prove less. A community store is listed only after a green run of every suite with the defaults or higher.