Copilot commented on code in PR #535: URL: https://github.com/apache/arrow-dotnet/pull/535#discussion_r4801176908
########## src/Apache.Arrow.Scalars/Variant/VariantValidator.cs: ########## @@ -0,0 +1,474 @@ +// 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 checks + /// that every primitive fits in the space it is given, but not its contents 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> + /// The size of the value each header byte starts, for short strings and primitives of + /// fixed size, or zero for the rest. + /// </summary> + private static readonly byte[] s_fixedSizes = BuildFixedSizes(); + + private static byte[] BuildFixedSizes() + { + byte[] sizes = new byte[256]; + byte[] headerByte = new byte[1]; + for (int header = 0; header < 256; header++) + { + switch (VariantEncodingHelper.GetBasicType((byte)header)) + { + case VariantBasicType.ShortString: + sizes[header] = (byte)(1 + VariantEncodingHelper.GetShortStringLength((byte)header)); + break; + + case VariantBasicType.Primitive: + VariantPrimitiveType type = VariantEncodingHelper.GetPrimitiveType((byte)header); + if (type <= VariantPrimitiveType.Uuid && + type != VariantPrimitiveType.Binary && + type != VariantPrimitiveType.String) + { + headerByte[0] = (byte)header; + sizes[header] = (byte)PrimitiveSize(headerByte); + } + break; + } + } + + return sizes; + } + + /// <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; + + default: + ValueSize(value); + break; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsContainer(byte header) => + VariantEncodingHelper.GetBasicType(header) >= VariantBasicType.Object; Review Comment: `IsContainer` depends on the relative ordering of `VariantBasicType` enum values (`>= Object`). This is fragile if enum ordering ever changes. Recommend making the check explicit (e.g., `== VariantBasicType.Object || == VariantBasicType.Array`) to avoid coupling correctness to enum ordering. ########## src/Apache.Arrow.Scalars/Variant/VariantValidator.cs: ########## @@ -0,0 +1,474 @@ +// 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 checks + /// that every primitive fits in the space it is given, but not its contents 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> + /// The size of the value each header byte starts, for short strings and primitives of + /// fixed size, or zero for the rest. + /// </summary> + private static readonly byte[] s_fixedSizes = BuildFixedSizes(); + + private static byte[] BuildFixedSizes() + { + byte[] sizes = new byte[256]; + byte[] headerByte = new byte[1]; + for (int header = 0; header < 256; header++) + { + switch (VariantEncodingHelper.GetBasicType((byte)header)) + { + case VariantBasicType.ShortString: + sizes[header] = (byte)(1 + VariantEncodingHelper.GetShortStringLength((byte)header)); + break; + + case VariantBasicType.Primitive: + VariantPrimitiveType type = VariantEncodingHelper.GetPrimitiveType((byte)header); + if (type <= VariantPrimitiveType.Uuid && + type != VariantPrimitiveType.Binary && + type != VariantPrimitiveType.String) + { + headerByte[0] = (byte)header; + sizes[header] = (byte)PrimitiveSize(headerByte); + } + break; + } + } + + return sizes; + } + + /// <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; + + default: + ValueSize(value); + break; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsContainer(byte header) => + VariantEncodingHelper.GetBasicType(header) >= VariantBasicType.Object; + + 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)) + { + return; + } + + long valuesStart = offsetsStart + (count + 1) * offsetSize; + RequireLength(value, valuesStart); + + long dataLength = value.Length - valuesStart; + long previous = ReadUnsigned(value.Slice((int)offsetsStart), offsetSize); + if (previous > dataLength) + { + throw Invalid("the first array offset is outside the array"); + } + + for (long i = 0; i < count; i++) + { + long end = ReadUnsigned(value.Slice((int)(offsetsStart + (i + 1) * offsetSize)), offsetSize); + if (end <= previous || end > dataLength) + { + throw Invalid($"array element {i} is empty, out of order or outside the array"); + } Review Comment: This error message conflates distinct failure modes (empty element `end == previous`, out-of-order `end < previous`, and out-of-bounds `end > dataLength`). Since callers/tests already assert on message substrings, making the message more specific would improve diagnosability. Suggest splitting the condition and throwing separate reasons for each case (or at least distinguishing out-of-bounds vs ordering). ########## test/Apache.Arrow.Operations.Tests/VariantJson/VariantJsonValidationTests.cs: ########## @@ -0,0 +1,89 @@ +// 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.IO; +using System.Text.Json; +using Apache.Arrow.Operations.VariantJson; +using Xunit; + +namespace Apache.Arrow.Operations.Tests +{ + public class VariantJsonValidationTests + { + // Metadata: version 1, 1-byte offsets, dictionary ["a", "b"]. + private static readonly byte[] s_metadata = { 0x01, 0x02, 0x00, 0x01, 0x02, (byte)'a', (byte)'b' }; + + // VariantValidator.DefaultMaxDepth, which this assembly can't see + private const int MaxDepth = 128; Review Comment: Hardcoding `128` duplicates `VariantValidator.DefaultMaxDepth` and will silently drift if the library default changes. Consider reading the value via reflection (e.g., by loading the `Apache.Arrow.Scalars` assembly and fetching `DefaultMaxDepth`), or exposing the limit through a public/internal-to-tests API so this test stays aligned with the implementation. -- 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]
