clockworklabs/SpacetimeDB · error · ArgumentException

Must be 16 bytes

Error message

Must be 16 bytes

What it means

Uuid.FromRandomBytesV4 builds a version-4 UUID by overwriting the version and variant nibbles of exactly 16 caller-supplied random bytes. UUIDs are fixed-width 128-bit values, so any length other than 16 is rejected with ArgumentException.

Solutions

  1. Request exactly 16 bytes: RandomNumberGenerator.GetBytes(new byte[16]) or stackalloc Span<byte> of 16
  2. Slice the entropy source to 16 bytes before calling
  3. Centralize UUID creation in one helper so buffer sizing is owned in one place

Example fix

// before
var bytes = RandomNumberGenerator.GetBytes(8);
var id = Uuid.FromRandomBytesV4(bytes); // ArgumentException: Must be 16 bytes

// after
var bytes = RandomNumberGenerator.GetBytes(16);
var id = Uuid.FromRandomBytesV4(bytes);
Defensive patterns

Strategy: validation

Validate before calling

static bool IsUuidV4RandomBytes(ReadOnlySpan<byte> b) => b.Length == 16;

Prevention

When it happens

Trigger: Passing a random span of length != 16, e.g. RandomNumberGenerator.GetBytes(8), reusing a 32-byte entropy buffer, or slicing a randomness pool incorrectly.

Common situations: Custom RNG plumbing shared across features; test fixtures with stub byte arrays of arbitrary size; converting from other systems' variable-length random identifiers.

Related errors


AI-assisted analysis of clockworklabs/SpacetimeDB@6dee26c6ef (2026-08-20). Data as JSON: /api/errors/9921d14caa50cab3. Report an issue: GitHub.

Appendix: source

Thrown at crates/bindings-csharp/BSATN.Runtime/BSATN/Uuid.cs:55

    /// 16 random bytes used for entropy.
    /// </param>
    /// <example>
    /// <code>
    /// var randomBytes = new byte[16];
    /// RandomNumberGenerator.Fill(randomBytes);
    /// var uuid = Uuid.FromRandomBytesV4(randomBytes);
    /// Console.WriteLine(uuid);
    /// // Output: 166a036f-90f3-714a-9731-c8814b70e326
    /// </code>
    /// </example>
    /// <exception cref="ArgumentException">
    /// Thrown if <paramref name="randomBytes"/> is not exactly 16 bytes long.
    /// </exception>
    public static Uuid FromRandomBytesV4(ReadOnlySpan<byte> randomBytes)
    {
        if (randomBytes.Length != 16)
        {
            throw new ArgumentException("Must be 16 bytes", nameof(randomBytes));
        }

        Span<byte> bytes = stackalloc byte[16];
        randomBytes.CopyTo(bytes);
        bytes[6] = (byte)((bytes[6] & 0x0F) | 0x40); // version 4
        bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80); // variant RFC 4122

        return new(U128.FromBytesBigEndian(bytes));
    }

    /// <summary>
    /// Generate a <see cref="Uuid"/> `v7` using a monotonic counter from 0 to 2^31-1,
    /// a Unix timestamp in milliseconds, and 4 random bytes.
    ///
    /// <example>
    /// <code>
    /// int counter = 1;
    /// var now = new Timestamp(1_686_000_000_000);

View on GitHub (pinned to 6dee26c6ef)