Copilot commented on code in PR #535:
URL: https://github.com/apache/arrow-dotnet/pull/535#discussion_r4795238914


##########
src/Apache.Arrow.Scalars/Variant/VariantValidator.cs:
##########
@@ -0,0 +1,424 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO;
+using System.Runtime.CompilerServices;
+
+namespace Apache.Arrow.Scalars.Variant
+{
+    /// <summary>
+    /// Structural checks a variant value must pass before code walks all of 
it recursively.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// Code that visits every nested value (materializing, copying, 
collecting field names or
+    /// writing JSON) relies on two properties that the encoding does not 
enforce by itself:
+    /// </para>
+    /// <list type="bullet">
+    /// <item>Nesting is bounded, so the recursion cannot exhaust the 
stack.</item>
+    /// <item>
+    /// The values of an object's fields lie inside the object and do not 
overlap, so every
+    /// nested value has its own bytes and the walk does work proportional to 
the size of the
+    /// value. The spec lets field values appear in any order, so offsets need 
not increase,
+    /// but two fields must not share bytes.
+    /// </item>
+    /// </list>
+    /// <para>
+    /// Validation recurses only after checking the depth, so it is itself 
bounded. It does not
+    /// check primitive values or field IDs; readers check those when they are 
accessed.
+    /// </para>
+    /// </remarks>
+    internal static class VariantValidator
+    {
+        /// <summary>
+        /// The default maximum number of nested objects and arrays. The 
variant spec sets no
+        /// limit. This allows four times the nesting <c>System.Text.Json</c> 
reads by default
+        /// while staying far below the depth at which recursion overflows a 
small thread stack.
+        /// </summary>
+        internal const int DefaultMaxDepth = 128;
+
+        /// <summary>
+        /// Validates <paramref name="value"/> with the default maximum depth.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value) => 
Validate(value, DefaultMaxDepth);
+
+        /// <summary>
+        /// Validates <paramref name="value"/>, allowing at most <paramref 
name="maxDepth"/>
+        /// nested objects and arrays.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value, int maxDepth)
+        {
+            if (maxDepth < 1)
+            {
+                throw new ArgumentOutOfRangeException(nameof(maxDepth), 
maxDepth, "The maximum depth must be at least 1.");
+            }
+
+            ValidateValue(value, 0, maxDepth);
+        }
+
+        private static void ValidateValue(ReadOnlySpan<byte> value, int depth, 
int maxDepth)
+        {
+            if (value.IsEmpty)
+            {
+                throw Invalid("a value is empty");
+            }
+
+            switch (VariantEncodingHelper.GetBasicType(value[0]))
+            {
+                case VariantBasicType.Object:
+                    CheckDepth(depth, maxDepth);
+                    ValidateObject(value, depth, maxDepth);
+                    break;
+
+                case VariantBasicType.Array:
+                    CheckDepth(depth, maxDepth);
+                    ValidateArray(value, depth, maxDepth);
+                    break;
+            }
+        }
+
+        /// <summary>
+        /// Objects and arrays have basic types 2 and 3; primitives and short 
strings need no
+        /// validation here.
+        /// </summary>
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private static bool IsContainer(byte header) => (header & 0x02) != 0;
+
+        private static void CheckDepth(int depth, int maxDepth)
+        {
+            if (depth >= maxDepth)
+            {
+                throw new InvalidDataException(
+                    $"Invalid variant value: objects and arrays are nested 
more than {maxDepth} deep.");
+            }
+        }
+
+        private static void ValidateObject(ReadOnlySpan<byte> value, int 
depth, int maxDepth)
+        {
+            ObjectLayout layout = ReadObjectLayout(value);
+            ReadOnlySpan<byte> data = value.Slice(layout.ValuesStart, 
layout.DataLength);
+
+            // Kept out of this method so that its buffers are not on the 
stack while we recurse.
+            CheckFieldRanges(value, layout, data);
+
+            for (int i = 0; i < layout.FieldCount; i++)
+            {
+                // CheckFieldRanges has verified that every value lies inside 
the object, and
+                // a nested value's own header bounds what is validated within 
it.
+                ReadOnlySpan<byte> field = 
data.Slice((int)layout.GetFieldOffset(value, i));
+                if (IsContainer(field[0]))
+                {
+                    ValidateValue(field, depth + 1, maxDepth);
+                }
+            }
+        }
+
+        private const int StackRangeThreshold = 32;
+
+        private static void CheckFieldRanges(ReadOnlySpan<byte> value, 
ObjectLayout layout, ReadOnlySpan<byte> data)
+        {
+            int count = layout.FieldCount;
+            if (count == 0)
+            {
+                return;
+            }
+
+            long[] rented = null;
+            Span<long> ranges = count <= StackRangeThreshold
+                ? stackalloc long[StackRangeThreshold]
+                : (rented = ArrayPool<long>.Shared.Rent(count));
+            try
+            {
+                // Each range packs the value's start into the high half and 
its end into the low
+                // half, so ordering ranges orders them by start. Both fit in 
31 bits.
+                bool ordered = true;
+                long previous = 0;
+                for (int i = 0; i < count; i++)
+                {
+                    int start = CheckedFieldOffset(value, layout, data, i);
+                    long end = start + ValueSize(data.Slice(start));

Review Comment:
   Passing the entire remaining data span makes an omitted-offset empty object 
consume the next field's first byte as its offset. For example, `02 02 00 01 00 
02 03 02 00 00` previously materializes as {"a":{},"b":null}, but now produces 
ranges [0,3) and [2,3) and throws for overlap. Preserve the promised 
empty-container compatibility by determining each field's physical boundary 
before interpreting an empty container's optional offset; apply the same 
boundary during recursive validation.



##########
src/Apache.Arrow.Scalars/Variant/VariantValidator.cs:
##########
@@ -0,0 +1,424 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO;
+using System.Runtime.CompilerServices;
+
+namespace Apache.Arrow.Scalars.Variant
+{
+    /// <summary>
+    /// Structural checks a variant value must pass before code walks all of 
it recursively.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// Code that visits every nested value (materializing, copying, 
collecting field names or
+    /// writing JSON) relies on two properties that the encoding does not 
enforce by itself:
+    /// </para>
+    /// <list type="bullet">
+    /// <item>Nesting is bounded, so the recursion cannot exhaust the 
stack.</item>
+    /// <item>
+    /// The values of an object's fields lie inside the object and do not 
overlap, so every
+    /// nested value has its own bytes and the walk does work proportional to 
the size of the
+    /// value. The spec lets field values appear in any order, so offsets need 
not increase,
+    /// but two fields must not share bytes.
+    /// </item>
+    /// </list>
+    /// <para>
+    /// Validation recurses only after checking the depth, so it is itself 
bounded. It does not
+    /// check primitive values or field IDs; readers check those when they are 
accessed.
+    /// </para>
+    /// </remarks>
+    internal static class VariantValidator
+    {
+        /// <summary>
+        /// The default maximum number of nested objects and arrays. The 
variant spec sets no
+        /// limit. This allows four times the nesting <c>System.Text.Json</c> 
reads by default
+        /// while staying far below the depth at which recursion overflows a 
small thread stack.
+        /// </summary>
+        internal const int DefaultMaxDepth = 128;
+
+        /// <summary>
+        /// Validates <paramref name="value"/> with the default maximum depth.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value) => 
Validate(value, DefaultMaxDepth);
+
+        /// <summary>
+        /// Validates <paramref name="value"/>, allowing at most <paramref 
name="maxDepth"/>
+        /// nested objects and arrays.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value, int maxDepth)
+        {
+            if (maxDepth < 1)
+            {
+                throw new ArgumentOutOfRangeException(nameof(maxDepth), 
maxDepth, "The maximum depth must be at least 1.");
+            }
+
+            ValidateValue(value, 0, maxDepth);
+        }
+
+        private static void ValidateValue(ReadOnlySpan<byte> value, int depth, 
int maxDepth)
+        {
+            if (value.IsEmpty)
+            {
+                throw Invalid("a value is empty");
+            }
+
+            switch (VariantEncodingHelper.GetBasicType(value[0]))
+            {
+                case VariantBasicType.Object:
+                    CheckDepth(depth, maxDepth);
+                    ValidateObject(value, depth, maxDepth);
+                    break;
+
+                case VariantBasicType.Array:
+                    CheckDepth(depth, maxDepth);
+                    ValidateArray(value, depth, maxDepth);
+                    break;
+            }
+        }
+
+        /// <summary>
+        /// Objects and arrays have basic types 2 and 3; primitives and short 
strings need no
+        /// validation here.
+        /// </summary>
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private static bool IsContainer(byte header) => (header & 0x02) != 0;
+
+        private static void CheckDepth(int depth, int maxDepth)
+        {
+            if (depth >= maxDepth)
+            {
+                throw new InvalidDataException(
+                    $"Invalid variant value: objects and arrays are nested 
more than {maxDepth} deep.");
+            }
+        }
+
+        private static void ValidateObject(ReadOnlySpan<byte> value, int 
depth, int maxDepth)
+        {
+            ObjectLayout layout = ReadObjectLayout(value);
+            ReadOnlySpan<byte> data = value.Slice(layout.ValuesStart, 
layout.DataLength);
+
+            // Kept out of this method so that its buffers are not on the 
stack while we recurse.
+            CheckFieldRanges(value, layout, data);
+
+            for (int i = 0; i < layout.FieldCount; i++)
+            {
+                // CheckFieldRanges has verified that every value lies inside 
the object, and
+                // a nested value's own header bounds what is validated within 
it.
+                ReadOnlySpan<byte> field = 
data.Slice((int)layout.GetFieldOffset(value, i));
+                if (IsContainer(field[0]))
+                {
+                    ValidateValue(field, depth + 1, maxDepth);
+                }
+            }
+        }
+
+        private const int StackRangeThreshold = 32;
+
+        private static void CheckFieldRanges(ReadOnlySpan<byte> value, 
ObjectLayout layout, ReadOnlySpan<byte> data)
+        {
+            int count = layout.FieldCount;
+            if (count == 0)
+            {
+                return;
+            }
+
+            long[] rented = null;
+            Span<long> ranges = count <= StackRangeThreshold
+                ? stackalloc long[StackRangeThreshold]
+                : (rented = ArrayPool<long>.Shared.Rent(count));
+            try
+            {
+                // Each range packs the value's start into the high half and 
its end into the low
+                // half, so ordering ranges orders them by start. Both fit in 
31 bits.
+                bool ordered = true;
+                long previous = 0;
+                for (int i = 0; i < count; i++)
+                {
+                    int start = CheckedFieldOffset(value, layout, data, i);
+                    long end = start + ValueSize(data.Slice(start));
+                    long range = ((long)start << 32) | end;
+                    ordered &= range > previous;
+                    ranges[i] = previous = range;
+                }
+
+                if (!ordered)
+                {
+                    // The spec lets values appear in any order, and our own 
writer stores them in
+                    // insertion order rather than field order, so this path 
is common.
+                    if (rented != null)
+                    {
+                        Array.Sort(rented, 0, count);
+                    }
+                    else
+                    {
+                        InsertionSort(ranges.Slice(0, count));
+                    }
+                }
+
+                for (int i = 1; i < count; i++)
+                {
+                    if ((int)(ranges[i] >> 32) < (int)ranges[i - 1])
+                    {
+                        throw Invalid("the values of two object fields 
overlap");
+                    }
+                }
+            }
+            finally
+            {
+                if (rented != null)
+                {
+                    ArrayPool<long>.Shared.Return(rented);
+                }
+            }
+        }
+
+        private static void InsertionSort(Span<long> items)
+        {
+            for (int i = 1; i < items.Length; i++)
+            {
+                long item = items[i];
+                int j = i - 1;
+                while (j >= 0 && items[j] > item)
+                {
+                    items[j + 1] = items[j];
+                    j--;
+                }
+                items[j + 1] = item;
+            }
+        }
+
+        private static int CheckedFieldOffset(ReadOnlySpan<byte> value, 
ObjectLayout layout, ReadOnlySpan<byte> data, int index)
+        {
+            long start = layout.GetFieldOffset(value, index);
+            if (start >= data.Length)
+            {
+                throw Invalid($"object field {index} starts outside the 
object");
+            }
+
+            return (int)start;
+        }
+
+        private static void ValidateArray(ReadOnlySpan<byte> value, int depth, 
int maxDepth)
+        {
+            VariantEncodingHelper.ParseArrayHeader(value[0], out int 
offsetSize, out bool isLarge);
+            int countSize = isLarge ? 4 : 1;
+            RequireLength(value, 1 + countSize);
+            long count = ReadUnsigned(value.Slice(1), countSize);
+
+            long offsetsStart = 1 + countSize;
+            if (IsBareEmptyContainer(value, count, offsetsStart, offsetSize))
+            {
+                return;
+            }
+
+            long valuesStart = offsetsStart + (count + 1) * offsetSize;
+            RequireLength(value, valuesStart);
+
+            long dataLength = value.Length - valuesStart;
+            long previous = ReadUnsigned(value.Slice((int)offsetsStart), 
offsetSize);

Review Comment:
   For an empty array, `count == 0` skips the loop containing the only offset 
bounds check. Consequently, `{ 0x03, 0x00, 0xFF }` passes validation and 
materializes as `[]`, although its sole offset points 255 bytes past an empty 
data region. Check the initial offset against `dataLength` before entering the 
loop so empty arrays also reject out-of-bounds offsets.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to