/foundationdb-dotnet-skills:snowbank-contractsfrom foundationdb-dotnet-skills
Documents SnowBank.Diagnostics.Contracts: argument guards (NotNull, Positive, GreaterThan) and condition assertions (Requires, Assert, Ensures) with compile-level selection and NUnit integration.
Ships in foundationdb-dotnet-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Contract is the guard and assertion family used across SnowBank.Core and FoundationDB.Client. It
replaces raw throw new ArgumentNullException(...), ArgumentNullException.ThrowIfNull(...),
ArgumentOutOfRangeException.ThrowIf*, and System.Diagnostics.Debug.Assert(...). The namespace is
SnowBank.Diagnostics.Contracts; it is a global using in the SnowBank projects, add
using SnowBank.Diagnostics.Contracts; in a consumer.
There are two families, and they are not interchangeable:
Contract.NotNull, Positive, GreaterThan, ...) validate arguments that
come from OUTSIDE the method. They are the logical equivalent of
if (cond) throw new Argument...Exception(...). A failure means the CALLER passed a bad argument.
Always on (Debug and Release). Each throws the matching Argument* exception.Contract.Requires, Assert, Ensures, Invariant, Fail) check a
condition that must NEVER be false, an invariant of your own code. A failure means the component
itself has a bug. Each throws ContractException.The rule for choosing: ask who can trigger it. A caller outside the type gets an argument guard. Your
own code breaking its own invariant gets Contract.Debug.Requires for a dev-time check, or an
explicit if (...) throw when the invariant must hold at run time (section 3).
Use these to validate public-API arguments. Each captures the argument name on its own (see section 5),
takes an optional message as the second argument, and throws the exception below.
| Guard | Replaces | Throws |
|---|---|---|
Contract.NotNull(x) | if (x == null) throw new ArgumentNullException(...) | ArgumentNullException |
Contract.NotNullOrEmpty(s) (string) | null + s.Length == 0 | ArgumentNullException (null) / ArgumentException (empty) |
Contract.NotNullOrWhiteSpace(s) | string.IsNullOrWhiteSpace(s) | ArgumentNullException (null) / ArgumentException (blank) |
Contract.NotNullOrEmpty(collection) | null + empty | ArgumentNullException / ArgumentException |
Contract.NotEmpty(collection) | .Count == 0 | ArgumentException |
Contract.Positive(n) | if (n <= 0) throw ... | ArgumentException |
Contract.PowerOfTwo(n) | bit check | ArgumentException |
Contract.GreaterThan(n, t) / GreaterOrEqual / LessThan / LessOrEqual | compare + throw | ArgumentOutOfRangeException |
Contract.EqualTo(x, v) / NotEqualTo(x, v) | compare + throw | ArgumentException |
Contract.ValueNotNull(x) | null check that returns x | ArgumentNullException |
Contract.PointerNotNull(p) (unsafe) | p == null | ArgumentNullException |
public void Load(Root root, int count)
{
Contract.NotNull(root);
Contract.Positive(count);
// root is non-null from here (section 5)
}
ValueNotNull returns its argument, for a single-line setter:
public string Name
{
get => this.name;
set => this.name = Contract.ValueNotNull(value, "Name cannot be null");
}
Numeric guards exist for int, long, double, float (and uint / ulong for PowerOfTwo).
NotNullOrEmpty / NotEmpty have overloads for arrays, collections, Slice, and ArraySegment<T>.
NotNullAllowStructs<T> is [Obsolete]; call NotNull.
Non-trivial check: when the check is heavy (for example a SequenceCompareTo bound check at a
public entry point), write a plain if (...) throw with a message, not a Contract call.
Use these for a condition that must never be false. They throw ContractException.
| Method | Meaning |
|---|---|
Contract.Requires(cond) | precondition at the start of a method |
Contract.Assert(cond) | assertion inside a method body |
Contract.Ensures(cond) | postcondition at the end |
Contract.Invariant(cond) | an invariant that must always hold |
Contract.Fail(message, ex?) | fail unconditionally (returns never) |
Do NOT use Contract.Requires to validate a public argument. It throws ContractException, which
signals an internal bug, not a caller error. Public arguments get the typed guards in section 1, which
throw the correct Argument* exception.
For an internal invariant, the common form is the Debug variant Contract.Debug.Requires (section 3),
not the always-on Contract.Requires. See section 3 for when to use an explicit if (...) throw
instead.
The same method set exists at three compile levels. Pick by how much you are willing to pay at run time.
| Level | Compiled | Use for |
|---|---|---|
Contract.X(...) | always (Debug and Release) | the argument guards (section 1) |
Contract.Debug.X(...) | Debug only ([Conditional("DEBUG")], removed from the Release binary) | state invariants inside private/internal methods |
Paranoid.X(...) | only when the PARANOID_ANDROID symbol is defined | the hottest paths, where even a Debug check is too costly |
Paranoid.IsParanoid is a runtime flag for code that wants to skip expensive setup when Paranoid
checks are off.
Default for a state invariant: Contract.Debug.Requires. It is the equivalent of Debug.Assert:
it catches a regression during day-to-day development (Debug) and costs no CPU in Release, where the
public boundary already validated. A failure means a bug in the component itself, not a caller error.
private void Apply(Node node, int position)
{
Contract.Debug.Requires(node is not null && position >= 0); // state invariant, Debug only
// ...
}
An invariant that must hold at run time gets an explicit if (...) throw, not Contract.Requires.
A condition worth checking in Release is important enough to deserve an explicit check and a meaningful
exception. The always-on Contract.Requires / Assert exist, but are rarely the right tool: use
Contract.Debug.Requires for a dev-time check, or if (...) throw for a real runtime invariant.
Every guard and assertion carries [CallerArgumentExpression], so the compiler puts the source text
in the message. Do not write a message just to name the argument or restate the condition.
Contract.NotNull(root) puts the name root in the ArgumentNullException.Contract.Debug.Requires(node is not null && position >= 0) puts the literal condition
"node is not null && position >= 0" in the ContractException.The optional message argument is for extra context only: Contract.NotNull(root, "Root is required").
[NotNull] and [DoesNotReturnIf(false)], and the JetBrains
[AssertionMethod] / [AssertionCondition] attributes. After Contract.NotNull(x), both the C#
compiler and ReSharper treat x as non-null for the rest of the method, which removes
"possible null dereference" (CS8602) false positives.[StackTraceHidden], so the guard frame does not appear in the
stack trace. The trace points at the caller.AggressiveInlining; a value-type argument to NotNull is optimized away with no
boxing.Under a unit-test runner, a Contract failure becomes a test assertion, and debugger breakpoints are
muted so an unattended CI run does not block. Contract.IsUnitTesting is set true when the runner is
detected.
Only NUnit is detected today (the failure maps to NUnit.Framework.AssertionException). xUnit,
MSTest, and TUnit each throw their own assertion type and are not yet mapped.
ArgumentNullException.ThrowIfNull does not exist on .NET Framework, and a static extension method
cannot shim it, so it is not portable to the netstandard 2.0 / net472 consumers.Contract changes mode by environment: it breaks into the debugger when one is attached, and raises
a formatted assertion under a test runner (section 6).[CallerArgumentExpression] removes the boilerplate message (section 4).Contract. prefix aligns a stack of parameter checks at the top of a method.(Historical: the helpers once aided JIT inlining, because a new FooException in the body blocked it.
The modern JIT handles this, so do not cite inlining as a reason today.)
Contract.NotNull / Positive / ...), which throws the
matching Argument* exception. Never Contract.Requires for that: it throws ContractException, the
wrong signal.Contract.Debug.Requires / Debug.Assert inside
private/internal methods. Debug only, the equivalent of Debug.Assert: catches regressions in
development, zero Release cost.if (...) throw, not the always-on
Contract.Requires. A condition worth checking in Release deserves an explicit check and a
meaningful exception.System.Diagnostics.Debug.Assert(...) in this codebase; use Contract.Debug.Assert(...).ArgumentNullException.ThrowIfNull(...) or ArgumentOutOfRangeException.ThrowIf*; use the
guards (portability, section 7).if (...) throw, not a Contract call dressed over it.Positive, EqualTo, NotEqualTo, and the empty-string /
empty-collection cases throw ArgumentException; GreaterThan / GreaterOrEqual / LessThan /
LessOrEqual throw ArgumentOutOfRangeException; the null cases throw ArgumentNullException.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
contracts, argument-validation, code-contracts, snowbank, dotnet
npx claudepluginhub snowbanksdk/foundationdb-dotnet-client --plugin foundationdb-dotnet-skills9 skills in this plugin
/crystaljsonHow to use CrystalJson, the custom JSON library in SnowBank.Core (namespace SnowBank.Data.Json). Covers the JsonValue DOM (JsonObject / JsonArray / JsonString / JsonNumber / JsonBoolean / JsonNull / JsonDateTime), the read-only vs mutable model, the CrystalJson static API (Serialize / Parse / Deserialize) and CrystalJsonSettings, the Roslyn source generator for fast reflection-free serializers and read-only/writable proxies ([CrystalJsonConverter] / [CrystalSerializable]), the IJsonSerializable / IJsonPackable / IJsonDeserializable interfaces, MutableJsonValue / ObservableJsonValue and JsonPath. Use whenever code parses, builds, reads, mutates, or serializes JSON with these types, reads optional fields with defaults, declares a generated JSON converter/proxy, or implements custom JSON (de)serialization. Use it even when the request only says "serializer", "converter", or "serialize/deserialize a record, document, or model" without naming JSON: in SnowBank-based code (document stores, sync layers, Layers, models) document and message (de)serialization goes through CrystalJson, not System.Text.Json or Newtonsoft./foundationdb-advanced-layersAdvanced engineering for sophisticated FoundationDB layers with the .NET client (FoundationDB.Client / SnowBank) — the cluster model and transaction lifecycle (proxies, resolvers, tlogs, storage servers, the sequencer/version clock), latency/throughput optimization (batching reads with GetValuesAsync / Task.WhenAll, removing round-trip dependencies, snapshot reads), high-contention avoidance, and distributed patterns (change feeds, version-stamp logs, watch fan-out, version-as-clock leases, retention, fencing/tombstones). Use when building or reviewing a performance-sensitive or distributed layer (a change feed, queue, pub/sub, worker pool, multi-node observable view), tuning transaction latency/throughput, or reasoning about conflicts, the 5-second limit, or cross-node liveness. Builds on the foundationdb-keys-and-layers and foundationdb-transactions skills — read those first./foundationdb-aspireHow to run a FoundationDB cluster and connect to it from .NET — getting the IFdbDatabaseProvider that the keys/transactions/layers skills assume you already have. Covers the ways to get a provider (plain DI services.AddFoundationDb, FdbDatabaseProvider.Create, or Aspire), the Aspire AppHost integration (FoundationDB.Aspire.Hosting — builder.AddFoundationDb starts a Docker cluster, AddFoundationDbCluster connects to an existing one), the Aspire client integration (FoundationDB.Aspire — builder.AddFoundationDb reads the injected connection), wiring with WithReference and WaitFor, launching with the aspire CLI vs plain dotnet run plus launchSettings, the native client (libfdb_c via UseNativeClient, the platforms FoundationDB.Client.Native ships, and the macOS system-library fallback), and the client-vs-cluster version-compatibility rule (FoundationDB.Client.Native follows the cluster's major.minor, FoundationDB.Client is independent of it, apiVersion stays within what both the binding and the native client support). Use whenever code opens or connects to a cluster, registers AddFoundationDb, runs an Aspire host, or hits libfdb_c load failures or transactions that hang on a fresh cluster./foundationdb-keys-and-layersHow to correctly encode keys and values, use subspaces and the Directory layer, and write custom "Layers" with the FoundationDB .NET client (FoundationDB.Client / SnowBank). Covers the lazy strongly-typed key structs (subspace.Key(...), FdbTupleKey, FdbRawKey, FdbKey.Increment / Successor / Dump), the tuple encoding (TuPack, IVarTuple, STuple), value encodings (FdbValue.ToBytes / ToTextUtf8 / FromTuple / ToJson / ToFixed64LittleEndian and which one a given access pattern requires), subspaces and ISubspaceLocation, the Directory layer (FdbDirectoryLayer, FdbPath, FdbDirectorySubspace), and the IFdbLayer contract with its per-transaction Resolve(tr) State that must never escape the transaction. Use whenever code reads or writes FoundationDB keys, builds or decodes a tuple key, picks a value encoding, resolves a subspace or location, designs a key layout for a table / secondary index / queue / document collection, reasons about key ordering, prefixes and range boundaries, or defines a class that stores data in FoundationDB. Also use it for "how do I model X in FoundationDB", for range scans that return too much or nothing, and for keys that are too big. Read this BEFORE writing or reviewing any such code./foundationdb-transactionsHow to correctly run transactions with the FoundationDB .NET client (FoundationDB.Client / SnowBank): the db.ReadAsync / WriteAsync / ReadWriteAsync retry loop and why a handler must be safe to run more than once, the 5-second and size limits, conflicts and how to avoid them, snapshot reads, explicit conflict ranges, atomic mutations (AtomicAdd32/64, AtomicIncrement, AtomicMin/Max and the lexicographic ByteMin/ByteMax, AtomicAnd/Or/Xor, AtomicCompareAndClear, AtomicAppendIfFits), and watches. Use whenever code opens a transaction or calls BeginTransaction, writes a read-modify-write, increments a counter, waits on a key with a watch, pages a large range scan across transactions, or hits an FdbException: NotCommitted, TransactionTooOld ("Transaction is too old to perform reads"), CommitUnknownResult, TransactionTimedOut, transaction_too_large. Also use it for "why does my transaction keep retrying / conflict / run twice", for high-contention or write-hot keys, and before deciding that a value must be read and written back. Pairs with the foundationdb-keys-and-layers skill./snowbank-betterhttpHow to make outbound HTTP calls with BetterHttpClient (SnowBank.Networking.Http) in an ASP.NET Core or generic-host .NET application - the DI story and the request API. Covers the one-policy-plane model where a client NAME maps to one effective policy that lives in the pooled handler chain, so every client gets the same behavior: a typed client, a keyed client, IHttpClientFactory.CreateClient(name), and the bare IHttpMessageHandlerFactory.CreateHandler(name). Covers AddBetterHttpClientDefaults (routes every factory client through the map), AddBetterHttpClient(name, ...) returning an IBetterHttpClientBuilder for standard chaining (AddHttpMessageHandler, AddAsKeyed, typed clients), the AddBetterHttpClientConfiguration override layer bound from an appsettings section, the mandatory INetworkMap transport seam (NetworkMap in production, the virtual network inside distributed tests, with packet capture on every chain automatically), BetterHttpClientOptions (default headers and UserAgent, cookies, credentials, TLS server-certificate callbacks and the self-signed/trusted-roots helpers, hooks, delegating handlers), the universal SendAsync(request, ctx => ...) lifecycle with BetterHttpClientContext that now runs the request stage on any client, the Create*Request builders, typed protocols (RestHttpProtocol, BetterHttpProtocolFactoryBase, the AddFooClient extension-method pattern), how to port legacy HttpWebRequest / WebClient (.NET Framework) code to this stack, and which 7.4.3 members are now soft-obsolete (IBetterHttpClientFactory, the BetterHttpClient shell, BetterHttpShellOptions, IBetterHttpFilter/Filters, AddGlobalHttpFilter/AddGlobalHttpHandler) and their native replacements. Use whenever application code registers or injects an HttpClient in a SnowBank-based app, declares a named client, configures user agents or HTTPS certificate validation, binds HTTP options from configuration, ports HttpWebRequest/.NET Framework 4.7.2 networking code to net8+/net10, or hits "You must register an implementation for INetworkMap".Other plugins' skills for the same job