Copilot commented on code in PR #535:
URL: https://github.com/apache/arrow-dotnet/pull/535#discussion_r4800890567
##########
src/Apache.Arrow.Operations/VariantJson/VariantJsonWriter.cs:
##########
@@ -96,8 +100,13 @@ public static string ToJson(VariantValue value, bool
indented = false)
/// <param name="writer">The JSON writer to write to.</param>
/// <param name="metadata">The variant metadata bytes.</param>
/// <param name="value">The variant value bytes.</param>
+ /// <exception cref="InvalidDataException">
+ /// Objects and arrays are nested more than 128 deep, or the values of
an object's
+ /// fields overlap or extend outside the object.
+ /// </exception>
public static void WriteTo(Utf8JsonWriter writer, byte[] metadata,
byte[] value)
{
+ VariantValidator.Validate(value);
VariantReader reader = new VariantReader(metadata, value);
WriteReader(writer, reader);
}
Review Comment:
`VariantValidator` is declared `internal` in `Apache.Arrow.Scalars`, but
it’s being referenced from `Apache.Arrow.Operations`. If these are separate
assemblies (as the folder structure suggests), this won’t compile. Fix by
either (mandatory): (1) making the validator API accessible to Operations
(e.g., `public`), (2) adding `InternalsVisibleTo` for the Operations assembly,
or (3) relocating the validator into a shared assembly/module used by both.
##########
src/Apache.Arrow.Scalars/Variant/VariantReader.cs:
##########
@@ -577,7 +577,20 @@ private void EnsurePrimitiveType(VariantPrimitiveType
expected)
/// Materializes this variant value into a <see cref="VariantValue"/>
object.
/// Recursively materializes objects and arrays.
/// </summary>
+ /// <exception cref="System.IO.InvalidDataException">
+ /// Objects and arrays are nested more than 128 deep, or the values of
an object's
+ /// fields overlap or extend outside the object.
+ /// </exception>
public VariantValue ToVariantValue()
+ {
+ VariantValidator.Validate(_value);
+ return Materialize();
+ }
Review Comment:
The exception documentation is now incomplete: `VariantValidator` can also
reject malformed arrays (offset ordering/out-of-bounds) and truncated
primitives/strings, plus other structural issues (e.g., empty value). Consider
rewording to describe malformed variant values more generally, or enumerating
the full set of validation reasons this method can throw for.
##########
src/Apache.Arrow.Scalars/Variant/VariantValueWriter.cs:
##########
@@ -554,7 +554,17 @@ public void WriteTimestampNtzNanos(long nanos)
/// <see
cref="VariantMetadataBuilder.CollectFieldNames(VariantReader)"/> during
/// the metadata-collection phase of a two-pass encode to accumulate
them.
/// </remarks>
+ /// <exception cref="System.IO.InvalidDataException">
+ /// Objects and arrays are nested more than 128 deep, or the values of
an object's
+ /// fields overlap or extend outside the object. Nothing has been
written when this is thrown.
+ /// </exception>
public void CopyValue(VariantReader source)
+ {
+ VariantValidator.Validate(source.Value);
+ CopyValueCore(source);
+ }
Review Comment:
The doc comment claims only object depth/overlap/out-of-bounds are rejected,
but the validator can also reject arrays and truncated primitives/strings.
Also, the sentence “Nothing has been written when this is thrown.” is only
guaranteed for validation failures; later `InvalidDataException`s from
`CopyValueCore` (e.g., while reading field names) could occur after some output
has been written. Consider clarifying that this guarantee applies specifically
to validation failures, or avoid making an output atomicity guarantee in the
exception documentation.
##########
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];
+ 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)
+ {
+ sizes[header] = (byte)PrimitiveSize(new[] {
(byte)header });
+ }
+ 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;
+ }
+ }
+
+ /// <summary>
+ /// Objects and arrays have basic types 2 and 3.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static bool IsContainer(byte header) => (header & 0x02) != 0;
Review Comment:
`IsContainer` relies on a header-bit invariant that isn’t obviously tied to
`VariantEncodingHelper.GetBasicType`. For long-term maintainability (and to
avoid silent misclassification if the encoding changes), prefer deriving this
from `VariantEncodingHelper.GetBasicType(header)` (object/array), or centralize
the bit-level assumption inside `VariantEncodingHelper` with a clearly
documented contract.
##########
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];
+ 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)
+ {
+ sizes[header] = (byte)PrimitiveSize(new[] {
(byte)header });
+ }
+ break;
Review Comment:
`PrimitiveSize(new[] { (byte)header })` allocates a new array for each
header during static initialization (up to 256 allocations). This can be
avoided by using a non-allocating path (e.g., a dedicated `PrimitiveSize(byte
header)` helper, or a stackalloc/span-based call) to reduce startup allocations.
##########
test/Apache.Arrow.Operations.Tests/VariantJson/VariantJsonValidationTests.cs:
##########
@@ -0,0 +1,86 @@
+// 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' };
+
+ [Fact]
+ public void ArraysNestedToTheLimit_AreWritten()
+ {
+ string json = VariantJsonWriter.ToJson(s_metadata,
NestedArrays(128));
+
+ Assert.Equal(new string('[', 128) + "null" + new string(']', 128),
json);
Review Comment:
This test duplicates the depth limit (`128`) in multiple places. Consider
introducing a named constant in this test file (e.g., `const int MaxDepth =
128;`) and using it in both the value construction and expected JSON, so the
intent is clearer and future changes are localized.
##########
test/Apache.Arrow.Scalars.Tests/VariantValidatorTests.cs:
##########
@@ -0,0 +1,440 @@
+// 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.Collections.Generic;
+using System.IO;
+using Apache.Arrow.Scalars.Variant;
+using Xunit;
+
+namespace Apache.Arrow.Scalars.Tests
+{
+ public class VariantValidatorTests
+ {
+ // Metadata: version 1, 1-byte offsets, dictionary ["a", "b"].
+ private static readonly byte[] s_metadata = { 0x01, 0x02, 0x00, 0x01,
0x02, (byte)'a', (byte)'b' };
+
+ private const int MaxDepth = VariantValidator.DefaultMaxDepth;
+
+ // ---------------------------------------------------------------
+ // Nesting depth
+ // ---------------------------------------------------------------
+
+ [Fact]
+ public void ArraysNestedToTheLimit_Materialize()
+ {
+ VariantValue value = new VariantReader(s_metadata,
NestedArrays(MaxDepth)).ToVariantValue();
+
+ int depth = 0;
+ while (value.IsArray)
+ {
+ value = value.AsArray()[0];
+ depth++;
+ }
+ Assert.Equal(MaxDepth, depth);
+ Assert.True(value.IsNull);
+ }
+
+ [Fact]
+ public void ObjectsNestedToTheLimit_Materialize()
+ {
+ VariantValue value = new VariantReader(s_metadata,
NestedObjects(MaxDepth)).ToVariantValue();
+
+ int depth = 0;
+ while (value.IsObject)
+ {
+ value = value.AsObject()["a"];
+ depth++;
+ }
+ Assert.Equal(MaxDepth, depth);
+ }
+
+ [Theory]
+ [InlineData(MaxDepth + 1)]
+ [InlineData(100_000)]
+ public void ArraysNestedPastTheLimit_AreRejected(int depth)
+ {
+ AssertRejectedEverywhere(NestedArrays(depth), "nested more than
128 deep");
+ }
Review Comment:
These tests hardcode `128` in the expected error substring, even though the
depth limit is already referenced via `MaxDepth`. If `DefaultMaxDepth` changes,
the test will fail for the wrong reason. Consider building the expected
substring from `MaxDepth` (e.g., interpolating it) to keep the test 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]