CurtHagenlocher commented on code in PR #544:
URL: https://github.com/apache/arrow-dotnet/pull/544#discussion_r4808234794


##########
test/Apache.Arrow.Scalars.Tests/VariantValidatorTests.cs:
##########
@@ -0,0 +1,466 @@
+// 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 
{MaxDepth} deep");
+        }
+
+        [Theory]
+        [InlineData(MaxDepth + 1)]
+        [InlineData(100_000)]
+        public void ObjectsNestedPastTheLimit_AreRejected(int depth)
+        {
+            AssertRejectedEverywhere(NestedObjects(depth), $"nested more than 
{MaxDepth} deep");
+        }
+
+        [Fact]
+        public void PrimitivesAndStrings_AreNotAffected()
+        {
+            Assert.Equal(VariantValue.FromInt32(42), new 
VariantReader(s_metadata, new byte[] { 0x14, 42, 0, 0, 0 }).ToVariantValue());
+            Assert.Equal(VariantValue.FromString("hi"), new 
VariantReader(s_metadata, new byte[] { 0x09, (byte)'h', (byte)'i' 
}).ToVariantValue());
+        }
+
+        // ---------------------------------------------------------------
+        // Object field ranges
+        // ---------------------------------------------------------------
+
+        [Fact]
+        public void FieldValuesInAnyOrder_AreAccepted()
+        {
+            // {"a": "x", "b": "y"} with b's value stored before a's, as the 
spec allows.
+            byte[] value =
+            {
+                ObjectHeader(1), 2, 0, 1,  // object, 1-byte ids and offsets, 
2 fields: a, b
+                2, 0, 4,        // a starts at 2, b at 0; values are 4 bytes
+                0x05, (byte)'y',
+                0x05, (byte)'x',
+            };
+
+            VariantValue result = new VariantReader(s_metadata, 
value).ToVariantValue();
+
+            Assert.Equal(VariantValue.FromString("x"), result.AsObject()["a"]);
+            Assert.Equal(VariantValue.FromString("y"), result.AsObject()["b"]);
+        }
+
+        [Fact]
+        public void GapsBetweenFieldValues_AreAccepted()
+        {
+            byte[] value =
+            {
+                ObjectHeader(1), 2, 0, 1,
+                0, 3, 5,           // a at 0, b at 3; byte 2 belongs to neither
+                0x05, (byte)'x',
+                0xFF,
+                0x05, (byte)'y',
+            };
+
+            VariantValue result = new VariantReader(s_metadata, 
value).ToVariantValue();
+
+            Assert.Equal(VariantValue.FromString("x"), result.AsObject()["a"]);
+            Assert.Equal(VariantValue.FromString("y"), result.AsObject()["b"]);
+        }
+
+        [Fact]
+        public void FieldsSharingAValue_AreRejected()
+        {
+            byte[] value =
+            {
+                ObjectHeader(1), 2, 0, 1,
+                0, 0, 2,           // a and b both start at 0
+                0x05, (byte)'x',
+            };
+
+            AssertRejectedEverywhere(value, "overlap");
+        }
+
+        [Fact]
+        public void FieldStartingInsideAnotherFieldsValue_IsRejected()
+        {
+            byte[] value =
+            {
+                ObjectHeader(1), 2, 0, 1,
+                0, 1, 4,                              // b starts inside a
+                0x0D, 0x05, (byte)'q', (byte)'r',     // a = "\u0005qr"; read 
from byte 1, b = "q"
+            };
+
+            AssertRejectedEverywhere(value, "overlap");
+        }
+
+        [Fact]
+        public void SharedValuesNestedManyLevels_AreRejectedQuickly()
+        {
+            // Without the overlap check, materializing this would build 2^40 
values.
+            AssertRejectedEverywhere(SharedFieldValues(40), "overlap");
+        }
+
+        [Fact]
+        public void FieldValueExtendingPastTheObject_IsRejected()
+        {
+            byte[] value =
+            {
+                ObjectHeader(1), 1, 0,
+                0, 2,                                     // values are 2 
bytes...
+                0x0D, (byte)'a', (byte)'b', (byte)'c',    // ...but a's value 
is 4
+            };
+
+            AssertRejectedEverywhere(value, "truncated");
+        }
+
+        [Fact]
+        public void FieldOffsetPastTheObject_IsRejected()
+        {
+            byte[] value =
+            {
+                ObjectHeader(4), 1, 0,    // object, 1-byte ids, 4-byte 
offsets, 1 field
+                0xFF, 0xFF, 0xFF, 0xFF,   // a starts at 2^32 - 1
+                1, 0, 0, 0,
+                0x00,
+            };
+
+            AssertRejectedEverywhere(value, "outside the object");
+        }
+
+        [Fact]
+        public void ArrayOffsetsOutOfOrder_AreRejected()
+        {
+            byte[] value =
+            {
+                0x03, 2,       // array, 1-byte offsets, 2 elements
+                2, 0, 2,       // element 0 would be [2, 0)
+                0x00, 0x00,
+            };
+
+            AssertRejectedEverywhere(value, "out of order");
+        }
+
+        [Fact]
+        public void EmptyArrayElement_IsRejected()
+        {
+            byte[] value =
+            {
+                0x03, 2,
+                0, 0, 1,       // element 0 would be [0, 0)
+                0x00,
+            };
+
+            AssertRejectedEverywhere(value, "array element 0 is empty");
+        }
+
+        [Fact]
+        public void ArrayElementEndingOutsideTheArray_IsRejected()
+        {
+            byte[] value =
+            {
+                0x03, 1,
+                0, 5,          // element 0 would be [0, 5), but there is one 
byte
+                0x00,
+            };
+
+            AssertRejectedEverywhere(value, "array element 0 ends outside the 
array");
+        }
+
+        [Theory]
+        [InlineData(5)]
+        [InlineData(40)]
+        public void ManyFieldsStoredOutOfOrder_AreAccepted(int fieldCount)
+        {
+            (byte[] metadata, byte[] value) = 
EncodeFieldsInReverseOrder(fieldCount);
+
+            VariantValue result = new VariantReader(metadata, 
value).ToVariantValue();
+
+            Assert.Equal(fieldCount, result.AsObject().Count);
+            Assert.Equal(VariantValue.FromInt32(3), result.AsObject()["f03"]);
+        }
+
+        [Theory]
+        [InlineData(5)]
+        [InlineData(40)]
+        public void ManyFieldsWithTwoSharingAValue_AreRejected(int fieldCount)
+        {
+            (byte[] metadata, byte[] value) = 
EncodeFieldsInReverseOrder(fieldCount);
+            VariantEncodingHelper.ParseObjectHeader(value[0], out int 
fieldIdSize, out int offsetSize, out bool isLarge);
+            Assert.False(isLarge);
+            int offsetsStart = 2 + fieldCount * fieldIdSize;
+
+            // Point the last field at the first field's value.
+            value.AsSpan(offsetsStart, 
offsetSize).CopyTo(value.AsSpan(offsetsStart + (fieldCount - 1) * offsetSize, 
offsetSize));
+
+            InvalidDataException ex = Assert.Throws<InvalidDataException>(
+                () => new VariantReader(metadata, value).ToVariantValue());
+            Assert.Contains("overlap", ex.Message);
+        }
+
+        [Fact]
+        public void EmptyArrayWithOffsetOutsideTheArray_IsRejected()
+        {
+            byte[] value =
+            {
+                0x03, 0,       // array, 1-byte offsets, no elements
+                0xFF,          // its only offset points past the end
+            };
+
+            AssertRejectedEverywhere(value, "outside the array");
+        }
+
+        [Fact]
+        public void 
EmptyObjectWithoutItsOffset_IsRejectedWhenAnotherValueFollows()
+        {
+            // {"a": {}, "b": null}, but a's value omits the offset the spec 
requires, so the
+            // first byte of b's value is read as that offset and a overlaps b.
+            byte[] value =
+            {
+                ObjectHeader(1), 2, 0, 1,
+                0, 2, 3,
+                ObjectHeader(1), 0,    // a: an empty object without its offset
+                0x00,                  // b: null
+            };
+
+            AssertRejectedEverywhere(value, "overlap");
+        }
+
+        [Fact]
+        public void EmptyArrayWithPartOfItsOffset_IsRejected()
+        {
+            // An empty array with 2-byte offsets, and one byte of its offset
+            AssertRejectedEverywhere(new byte[] { 0x07, 0, 0 }, "truncated");
+        }
+
+        [Fact]
+        public void EmptyObjectWithPartOfItsOffset_IsRejected()
+        {
+            AssertRejectedEverywhere(new byte[] { ObjectHeader(4), 0, 0, 0, 0 
}, "truncated");
+        }
+
+        [Fact]
+        public void 
EmptyContainersWithWideOffsetsWithoutTheirOffset_AreAccepted()
+        {
+            Assert.Empty(new VariantReader(s_metadata, new byte[] { 0x07, 0 
}).ToVariantValue().AsArray());
+            Assert.Empty(new VariantReader(s_metadata, new byte[] { 
ObjectHeader(4), 0 }).ToVariantValue().AsObject());
+        }
+
+        [Fact]
+        public void ArrayElementLongerThanItsOffsetsAllow_IsRejected()
+        {
+            byte[] value =
+            {
+                0x03, 1,       // array, 1-byte offsets, 1 element
+                0, 1,
+                0x14,          // an int32 with no room for its four bytes
+            };
+
+            AssertRejectedEverywhere(value, "truncated");
+        }
+
+        [Fact]
+        public void ArrayElementStringLongerThanItsOffsetsAllow_IsRejected()
+        {
+            byte[] value =
+            {
+                0x03, 1,
+                0, 5,
+                0x40, 100, 0, 0, 0,    // a string of 100 bytes, none of which 
are present
+            };
+
+            AssertRejectedEverywhere(value, "truncated");
+        }
+
+        [Fact]
+        public void TruncatedPrimitive_IsRejected()
+        {
+            AssertRejectedEverywhere(new byte[] { 0x14, 0x01 }, "truncated");
+        }
+
+        [Fact]
+        public void ArrayOfPrimitives_IsAccepted()
+        {
+            byte[] value =
+            {
+                0x03, 3,
+                0, 5, 6, 9,
+                0x14, 7, 0, 0, 0,             // 7
+                0x00,                         // null
+                0x09, (byte)'h', (byte)'i',   // "hi"
+            };
+
+            VariantValue result = new VariantReader(s_metadata, 
value).ToVariantValue();
+
+            Assert.Equal(
+                new[] { VariantValue.FromInt32(7), VariantValue.Null, 
VariantValue.FromString("hi") },
+                result.AsArray());
+        }
+
+        [Fact]
+        public void ValidatorAcceptsTheSharedTestVectors()
+        {
+            VariantValidator.Validate(TestVectors.ObjectEmpty);
+            VariantValidator.Validate(TestVectors.ArrayEmpty);
+            VariantValidator.Validate(TestVectors.Object_Name_Alice);
+            Assert.Empty(new VariantReader(TestVectors.EmptyMetadata, 
TestVectors.ObjectEmpty).ToVariantValue().AsObject());
+            Assert.Empty(new VariantReader(TestVectors.EmptyMetadata, 
TestVectors.ArrayEmpty).ToVariantValue().AsArray());
+        }
+
+        // ---------------------------------------------------------------
+        // Helpers
+        // ---------------------------------------------------------------
+
+        private static void AssertRejectedEverywhere(byte[] value, string 
reason)
+        {
+            InvalidDataException ex = Assert.Throws<InvalidDataException>(
+                () => new VariantReader(s_metadata, value).ToVariantValue());
+            Assert.Contains(reason, ex.Message);
+
+            Assert.Throws<InvalidDataException>(
+                () => new VariantMetadataBuilder().CollectFieldNames(new 
VariantReader(s_metadata, value)));
+
+            VariantMetadataBuilder metadataBuilder = new 
VariantMetadataBuilder();
+            metadataBuilder.Add("a");
+            metadataBuilder.Add("b");
+            metadataBuilder.Build(out int[] idRemap);
+            using VariantValueWriter writer = new 
VariantValueWriter(metadataBuilder, idRemap);
+            Assert.Throws<InvalidDataException>(() => writer.CopyValue(new 
VariantReader(s_metadata, value)));
+        }
+
+        // The bit layout of object headers differs between releases, so build 
them.
+        private static byte ObjectHeader(int offsetSize) =>
+            VariantEncodingHelper.MakeObjectHeader(fieldIdSize: 1, offsetSize: 
offsetSize, isLarge: false);
+
+        // Fields f00..fNN with fNN = NN, inserted in reverse so the writer 
stores the values in
+        // the opposite order to the field offsets.
+        private static (byte[] Metadata, byte[] Value) 
EncodeFieldsInReverseOrder(int fieldCount)
+        {
+            Dictionary<string, VariantValue> fields = new Dictionary<string, 
VariantValue>();
+            for (int i = fieldCount - 1; i >= 0; i--)
+            {
+                fields[$"f{i:D2}"] = VariantValue.FromInt32(i);
+            }
+            return new 
VariantBuilder().Encode(VariantValue.FromObject(fields));

Review Comment:
   Thanks — the writer stores values in field order, so these cases never 
reached the sort. `EncodeFieldsInReverseOrder` now rewrites the encoded object 
so its values are stored in reverse order, and the 5- and 40-field cases now go 
through the insertion sort and `Array.Sort` respectively. The validator's 
comment about our writer's order is corrected too. The same change is going to 
main.



-- 
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