dotnet/orleans · error · ArgumentOutOfRangeException

Specified argument was out of the range of valid values.

Error message

Specified argument was out of the range of valid values.

What it means

Thrown by the ReadOnlySequenceStream.Position setter when the assigned value is negative or greater than the sequence length. ReadOnlySequenceStream wraps a fixed ReadOnlySequence<byte>; positions outside [0, length] are invalid because there is no data to read there and the stream cannot grow.

Source

Thrown at src/Azure/Orleans.Journaling.AzureStorage/ReadOnlySequenceStream.cs:39

            ObjectDisposedException.ThrowIf(_disposed, this);
            return _sequence.Length;
        }
    }

    public override long Position
    {
        get
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            return _position;
        }

        set
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            if (value < 0 || value > _sequence.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(value));
            }

            _position = value;
        }
    }

    public override void Flush() => ObjectDisposedException.ThrowIf(_disposed, this);

    public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));

    public override int Read(Span<byte> buffer)
    {
        ObjectDisposedException.ThrowIf(_disposed, this);
        if (buffer.IsEmpty || _position >= _sequence.Length)
        {
            return 0;
        }

View on GitHub (pinned to fca799fa70)

Solutions

  1. Clamp the requested position to [0, stream.Length] before assigning.
  2. Validate the source of the offset (e.g. content-length header) against stream.Length.
  3. Use stream.Seek with SeekOrigin and bounds-check the result.

Example fix

// before
stream.Position = computedOffset; // computedOffset may be -1 or > Length
// after
stream.Position = Math.Clamp(computedOffset, 0, stream.Length);
Defensive patterns

Strategy: validation

Validate before calling

if (value < 0 || value > stream.Length) throw new ArgumentOutOfRangeException(nameof(value));
stream.Position = Math.Clamp(value, 0, stream.Length);

Type guard

static bool IsValidStreamPosition(Stream s, long p) => p >= 0 && p <= s.Length;

Prevention

When it happens

Trigger: Setting stream.Position = -1, or a value larger than the underlying buffer length; or seeking/deriving a position that lands past the end (the setter is also reached via Seek).

Common situations: A deserializer computing an offset from a malformed length prefix; seeking to end+1 instead of end; arithmetic that underflows to negative; passing a stream length from an external source that disagrees with the actual buffer.

Related errors


AI-assisted analysis of dotnet/orleans@fca799fa70 (2026-08-13). Data as JSON: /api/errors/2753ffdb5d8a4d78. Report an issue: GitHub.