FDB1001: Subspace or layer state stored across transactions

Analyzer FoundationDB.Client
Severity Warning (correctness)
Code fix No

Message

A directory can move, so '{0}' may point at a stale prefix in a later transaction. Store the location (db.Root[...]) and call Resolve(tr) inside each transaction.

Why

A directory subspace maps a path to a key prefix, and that mapping can change when the directory is moved or removed. A subspace resolved in one transaction is only valid in that transaction. A field, an auto-property, a static, or a singleton that keeps it writes under a stale prefix once the directory moves, and nothing fails: the data lands in the wrong place. The same applies to the State object of a layer (IFdbLayer<TState>), which holds a resolved subspace.

The rule reports a field or an auto-property whose type is a subspace (IKeySubspace, FdbDirectorySubspace) or the TState of a layer implemented in the compilation, and a services.AddSingleton<T> registration of such a type. It reports after a build (the layer states are known only once every type has been seen), so the IDE shows it after a build or under full-solution analysis.

Exempt, because the member cannot outlive a transaction or cannot go stale:

  • the State class of a layer itself, and any type that the compilation creates only inside a transaction (inside a handler, or a method or local function that receives the transaction): an instance lives as long as its transaction;
  • an interface or abstract property, which declares a member without storing anything;
  • a readonly struct (a key or a range holds its subspace by design; a field that stores the struct is reported for its own type);
  • a member initialized with KeySubspace.FromKey(...) or new KeySubspace(...), a fixed prefix that the directory layer never moves.

Bad

class Store
{
	private IKeySubspace? subspace;

	public async Task InitAsync(IFdbDatabase db, CancellationToken ct)
	{
		this.subspace = await db.ReadWriteAsync(tr => db.Root["Store"].CreateOrOpenAsync(tr), ct);
	}
}

Good

class Store
{
	private readonly FdbDirectorySubspaceLocation location;

	public Store(IFdbDatabase db) => this.location = db.Root["Store"];

	public Task WriteAsync(IFdbDatabase db, int id, Slice value, CancellationToken ct) => db.WriteAsync(async tr =>
	{
		var subspace = await this.location.Resolve(tr);
		tr.Set(subspace.Key(id), value);
	}, ct);
}

Keep the location, which is a path, and resolve it inside each transaction.

Suppress

#pragma warning disable FDB1001 // reason

or, for a whole project, in .editorconfig:

dotnet_diagnostic.FDB1001.severity = none