iceberg-capybara commented on code in PR #2746: URL: https://github.com/apache/iceberg-go/pull/2746#discussion_r4810008557
########## table/metadata_eager.go: ########## @@ -0,0 +1,395 @@ +// 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. + +package table + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "math" + "strings" + "unicode/utf8" +) + +// parseEagerMetadataV2 recognizes the ordinary v2 snapshot histories. +// Individual snapshots can fall back to the general decoder. +func parseEagerMetadataV2(data []byte) (*metadataV2, bool) { Review Comment: Addressed in the latest update, thanks! ########## table/metadata_eager.go: ########## @@ -0,0 +1,395 @@ +// 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. + +package table + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "math" + "strings" + "unicode/utf8" +) + +// parseEagerMetadataV2 recognizes the ordinary v2 snapshot histories. +// Individual snapshots can fall back to the general decoder. +func parseEagerMetadataV2(data []byte) (*metadataV2, bool) { + if len(data) < 4096 { Review Comment: Addressed in the latest update, thanks! ########## table/metadata_eager.go: ########## @@ -0,0 +1,395 @@ +// 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. + +package table + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "math" + "strings" + "unicode/utf8" +) + +// parseEagerMetadataV2 recognizes the ordinary v2 snapshot histories. +// Individual snapshots can fall back to the general decoder. +func parseEagerMetadataV2(data []byte) (*metadataV2, bool) { + if len(data) < 4096 { + return nil, false + } + versionKey := []byte(`"format-version"`) + versionAt := bytes.Index(data, versionKey) + if versionAt < 0 { + return nil, false + } + version := metadataJSONCursor{data: data, pos: versionAt + len(versionKey)} + if !version.take(':') || !version.take('2') || !utf8.Valid(data) { + return nil, false + } + + cursor := metadataJSONCursor{data: data} + if !cursor.take('{') { + return nil, false + } + + skeleton := make([]byte, 0, 1024) + var snapshots []Snapshot + previousEnd := 0 + for { + key, ok := cursor.objectField() + if !ok { + return nil, false + } + valueAt := cursor.pos + switch string(key) { + case "snapshots": + if snapshots != nil { + return nil, false + } + snapshots, ok = readMetadataArray(&cursor, readEagerSnapshot) + default: + if bytes.EqualFold(key, []byte("snapshots")) || !cursor.skipValue(1) { + return nil, false + } + valueAt = -1 + } + if !ok { + return nil, false + } + if valueAt >= 0 { + skeleton = append(skeleton, data[previousEnd:valueAt]...) + skeleton = append(skeleton, '[', ']') + previousEnd = cursor.pos + } + if cursor.take('}') { + break + } + if !cursor.take(',') { + return nil, false + } + } + if snapshots == nil { + return nil, false + } + + skeleton = append(skeleton, data[previousEnd:]...) + header, formatVersion, err := preflightMetadataBytes(skeleton) + if err != nil || formatVersion != 2 { + return nil, false + } + normalized, err := assignMissingPartitionFieldIDsFromMetadata(skeleton, header) + if err != nil { + return nil, false + } + next, err := decodeMetadataV2(normalized) + if err != nil || next.FormatVersion() != 2 { + return nil, false + } + next.SnapshotList = snapshots + if err := next.finishUnmarshal(); err != nil { + return nil, false + } + + return next, true +} + +type metadataJSONCursor struct { + data []byte + pos int +} + +func (c *metadataJSONCursor) take(value byte) bool { + c.pos = skipJSONSpace(c.data, c.pos) + if c.pos >= len(c.data) || c.data[c.pos] != value { + return false + } + c.pos++ + + return true +} + +func (c *metadataJSONCursor) objectField() ([]byte, bool) { + key, ok := c.stringBytes() + + return key, ok && c.take(':') +} + +func (c *metadataJSONCursor) stringBytes() ([]byte, bool) { + if !c.take('"') { + return nil, false + } + length := bytes.IndexByte(c.data[c.pos:], '"') + if length < 0 { + return nil, false + } + end := c.pos + length + if !plainMetadataString(c.data[c.pos:end]) { + return nil, false + } + value := c.data[c.pos:end] + c.pos = end + 1 + + return value, true +} + +// Check eight bytes at a time for JSON escapes or unescaped control bytes. +// Subtraction sets a high bit in a byte lane that contains a zero or a value +// below 0x20, respectively. +func plainMetadataString(value []byte) bool { + const highBits = 0x8080808080808080 + for len(value) >= 8 { + word := binary.LittleEndian.Uint64(value) + slashes := word ^ 0x5c5c5c5c5c5c5c5c + if (slashes-0x0101010101010101)&^slashes&highBits != 0 || + (word-0x2020202020202020)&^word&highBits != 0 { + return false + } + value = value[8:] + } + for _, ch := range value { + if ch == 0x5c || ch < 0x20 { + return false + } + } + + return true +} + +func (c *metadataJSONCursor) integer() (int64, bool) { + c.pos = skipJSONSpace(c.data, c.pos) + negative := c.pos < len(c.data) && c.data[c.pos] == '-' + if negative { + c.pos++ + } + digits := c.pos + var value uint64 + for c.pos < len(c.data) { + digit := c.data[c.pos] - '0' + if digit > 9 { + break + } + if c.pos == digits+19 { + return 0, false + } + value = value*10 + uint64(digit) + c.pos++ + } + if c.pos == digits || (c.pos > digits+1 && c.data[digits] == '0') { + return 0, false + } + if negative { + return -int64(value), value <= uint64(math.MaxInt64)+1 + } + + return int64(value), value <= math.MaxInt64 +} + +// Match encoding/json's nesting limit even when a history entry is later +// decoded out of its enclosing metadata object and history array. +const ( + maxMetadataJSONDepth = 10_000 + metadataHistoryEntryDepth = 2 +) + +// The retained bytes for this value are validated by encoding/json. +func (c *metadataJSONCursor) skipValue(enclosingDepth int) bool { + c.pos = skipJSONSpace(c.data, c.pos) + depth := enclosingDepth + for c.pos < len(c.data) { + switch c.data[c.pos] { + case '"': + c.pos = scanJSONString(c.data, c.pos) + + continue + case '[', '{': + depth++ + if depth > maxMetadataJSONDepth { + return false + } + case ']', '}': + if depth == enclosingDepth { + return true + } + depth-- + case ',': + if depth == enclosingDepth { + return true + } + } + c.pos++ + } + + return false +} + +func readMetadataArray[T any](c *metadataJSONCursor, entry func(*metadataJSONCursor) (T, bool)) ([]T, bool) { + if !c.take('[') { + return nil, false + } + if c.take(']') { + return []T{}, true + } + var values []T + for { + start := c.pos + value, ok := entry(c) + if !ok { + // A single entry can use the general decoder without slowing down + // the rest of the array. + c.pos = start + var decoded T + if !c.skipValue(metadataHistoryEntryDepth) || json.Unmarshal(c.data[start:c.pos], &decoded) != nil { + return nil, false + } + value = decoded + } + done := c.take(']') + // Reserve capacity only once we know the history has multiple entries. + if values == nil && !done { + values = make([]T, 0, 64) + } + values = append(values, value) + if done { + return values, true + } + if !c.take(',') { + return nil, false + } + } +} + +func readEagerSnapshot(c *metadataJSONCursor) (Snapshot, bool) { + var snapshot Snapshot + if !c.take('{') { + return snapshot, false + } + + const ( + snapshotIDField = 1 << iota + timestampField + sequenceField + parentField + manifestListField + schemaIDField + summaryField + required = snapshotIDField | timestampField + ) + seen := 0 + for { + key, ok := c.objectField() + if !ok { + return snapshot, false + } + var field int + switch string(key) { + case "snapshot-id": + field = snapshotIDField + snapshot.SnapshotID, ok = c.integer() + case "timestamp-ms": + field = timestampField + snapshot.TimestampMs, ok = c.integer() + case "sequence-number": + field = sequenceField + snapshot.SequenceNumber, ok = c.integer() + case "parent-snapshot-id": + field = parentField + var parent int64 + parent, ok = c.integer() + snapshot.ParentSnapshotID = &parent + case "manifest-list": + field = manifestListField + var value []byte + value, ok = c.stringBytes() + snapshot.ManifestList = string(value) + case "schema-id": + field = schemaIDField + var schemaID int64 + schemaID, ok = c.integer() + id := int(schemaID) + ok = ok && int64(id) == schemaID + snapshot.SchemaID = &id + case "summary": + field = summaryField + snapshot.Summary, ok = readEagerSummary(c) + default: Review Comment: Addressed in the latest update, thanks! ########## table/metadata_eager_test.go: ########## @@ -0,0 +1,234 @@ +// 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. + +package table + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestEagerMetadataV2Parity(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 64, 16, 0) + largeSummary := `"summary":{"operation":"append","note":"first","payload":"` + + strings.Repeat("é", 512) + `","note":"last","other":"preserved"}` + for _, test := range []struct { + name string + old string + new string + fast bool + }{ + {name: "canonical", fast: true}, + {name: "escaped field", old: `"snapshots":`, new: `"snap\u0073hots":`}, + {name: "case folded field", old: `"snapshots":`, new: `"Snapshots":`}, + {name: "duplicate history", old: `"snapshots":`, new: `"snapshots":[], "snapshots":`}, + {name: "malformed overwritten history", old: `"snapshots":`, new: `"snapshots":[{}], "snapshots":`}, + {name: "leading zero", old: `"sequence-number":1,`, new: `"sequence-number":01,`}, + {name: "escaped summary value", old: `"append"`, new: `"a\u0070pend"`, fast: true}, + {name: "null summary", old: `"summary":{"operation":"append"}`, new: `"summary":null`, fast: true}, + {name: "duplicate summary", old: `"summary":{"operation":"append"}`, new: `"summary":{"a":"b"},"summary":{"operation":"append"}`, fast: true}, + {name: "duplicate operation", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":"","operation":"append"}`, fast: true}, + {name: "summary growth and repeated property", old: `"summary":{"operation":"append"}`, new: largeSummary, fast: true}, + {name: "empty operation", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":""}`}, + {name: "empty summary", old: `"summary":{"operation":"append"}`, new: `"summary":{}`, fast: true}, + {name: "integer overflow", old: `"sequence-number":1,`, new: `"sequence-number":9223372036854775808,`}, + {name: "root trailing comma", old: `"snapshots":`, new: `"unknown":{"value":1,},"snapshots":`}, + {name: "summary trailing comma", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":"append",}`}, + {name: "control character", old: `"append"`, new: "\"ap\x01pend\""}, + {name: "invalid utf8", old: `"append"`, new: "\"ap\xffpend\""}, + } { + t.Run(test.name, func(t *testing.T) { + input := bytes.Clone(fixture) + if test.old != "" { + if !bytes.Contains(input, []byte(test.old)) { + t.Fatalf("fixture lacks %q", test.old) + } + input = bytes.Replace(input, []byte(test.old), []byte(test.new), 1) + } + _, fast := parseEagerMetadataV2(input) + if fast != test.fast { + t.Fatalf("fast path = %v, want %v", fast, test.fast) + } + want, wantErr := parseMetadataBytes(input) + got, gotErr := ParseMetadataBytes(input) + if wantErr != nil || gotErr != nil { + if wantErr == nil || gotErr == nil || wantErr.Error() != gotErr.Error() { + t.Fatalf("got error %v, expected %v", gotErr, wantErr) + } + + return + } + clear(input) + checkEagerMetadataEqual(t, got, want) + }) + } +} + +func checkEagerMetadataEqual(t *testing.T, got, want Metadata) { + t.Helper() + if !got.Equals(want) { + t.Fatal("parsed metadata differs from general decoder") + } + gotJSON, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + wantJSON, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotJSON, wantJSON) { + t.Fatal("serialized metadata differs from general decoder") + } +} + +func FuzzEagerMetadataV2Parity(f *testing.F) { Review Comment: Addressed in the latest update, thanks! ########## table/metadata_eager_test.go: ########## @@ -0,0 +1,234 @@ +// 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. + +package table + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestEagerMetadataV2Parity(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 64, 16, 0) + largeSummary := `"summary":{"operation":"append","note":"first","payload":"` + + strings.Repeat("é", 512) + `","note":"last","other":"preserved"}` + for _, test := range []struct { + name string + old string + new string + fast bool + }{ + {name: "canonical", fast: true}, + {name: "escaped field", old: `"snapshots":`, new: `"snap\u0073hots":`}, + {name: "case folded field", old: `"snapshots":`, new: `"Snapshots":`}, + {name: "duplicate history", old: `"snapshots":`, new: `"snapshots":[], "snapshots":`}, + {name: "malformed overwritten history", old: `"snapshots":`, new: `"snapshots":[{}], "snapshots":`}, + {name: "leading zero", old: `"sequence-number":1,`, new: `"sequence-number":01,`}, + {name: "escaped summary value", old: `"append"`, new: `"a\u0070pend"`, fast: true}, + {name: "null summary", old: `"summary":{"operation":"append"}`, new: `"summary":null`, fast: true}, + {name: "duplicate summary", old: `"summary":{"operation":"append"}`, new: `"summary":{"a":"b"},"summary":{"operation":"append"}`, fast: true}, + {name: "duplicate operation", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":"","operation":"append"}`, fast: true}, + {name: "summary growth and repeated property", old: `"summary":{"operation":"append"}`, new: largeSummary, fast: true}, + {name: "empty operation", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":""}`}, + {name: "empty summary", old: `"summary":{"operation":"append"}`, new: `"summary":{}`, fast: true}, + {name: "integer overflow", old: `"sequence-number":1,`, new: `"sequence-number":9223372036854775808,`}, + {name: "root trailing comma", old: `"snapshots":`, new: `"unknown":{"value":1,},"snapshots":`}, + {name: "summary trailing comma", old: `"summary":{"operation":"append"}`, new: `"summary":{"operation":"append",}`}, + {name: "control character", old: `"append"`, new: "\"ap\x01pend\""}, + {name: "invalid utf8", old: `"append"`, new: "\"ap\xffpend\""}, + } { + t.Run(test.name, func(t *testing.T) { + input := bytes.Clone(fixture) + if test.old != "" { + if !bytes.Contains(input, []byte(test.old)) { + t.Fatalf("fixture lacks %q", test.old) + } + input = bytes.Replace(input, []byte(test.old), []byte(test.new), 1) + } + _, fast := parseEagerMetadataV2(input) + if fast != test.fast { + t.Fatalf("fast path = %v, want %v", fast, test.fast) + } + want, wantErr := parseMetadataBytes(input) + got, gotErr := ParseMetadataBytes(input) + if wantErr != nil || gotErr != nil { + if wantErr == nil || gotErr == nil || wantErr.Error() != gotErr.Error() { + t.Fatalf("got error %v, expected %v", gotErr, wantErr) + } + + return + } + clear(input) + checkEagerMetadataEqual(t, got, want) + }) + } +} + +func checkEagerMetadataEqual(t *testing.T, got, want Metadata) { + t.Helper() + if !got.Equals(want) { + t.Fatal("parsed metadata differs from general decoder") + } + gotJSON, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + wantJSON, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotJSON, wantJSON) { + t.Fatal("serialized metadata differs from general decoder") + } +} + +func FuzzEagerMetadataV2Parity(f *testing.F) { + f.Add(benchmarkMetadataJSON(1, 1, 64, 16, 0)) + f.Fuzz(func(t *testing.T, input []byte) { + got, fast := parseEagerMetadataV2(input) + if !fast { + return + } + want, err := parseMetadataBytes(input) + if err != nil { + t.Fatalf("specialized decoder accepted input rejected by general decoder: %v", err) + } + checkEagerMetadataEqual(t, got, want) + }) +} + +func TestEagerMetadataV2LargeDocumentOwnership(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 64, 16, 0) + input := append([]byte(`{"future-annotation":"`), bytes.Repeat([]byte{'x'}, 1<<20)...) + input = append(input, '"', ',') + input = append(input, fixture[1:]...) + + want, err := parseMetadataBytes(input) + if err != nil { + t.Fatal(err) + } + got, fast := parseEagerMetadataV2(input) + if !fast { + t.Fatal("large metadata did not take the fast path") + } + clear(input) + checkEagerMetadataEqual(t, got, want) +} + +func TestEagerMetadataV2HistoryDepth(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 64, 16, 0) + for _, field := range []string{"snapshots"} { Review Comment: Addressed in the latest update, thanks! -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
