zeroshade commented on code in PR #2746: URL: https://github.com/apache/iceberg-go/pull/2746#discussion_r4803323100
########## table/metadata_eager_test.go: ########## @@ -0,0 +1,295 @@ +// 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 TestEagerMetadataV2FullyPopulatedSnapshotFastPath(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 1, 0, 0) + start := bytes.Index(fixture, []byte(`"snapshots":[{`)) + if start < 0 { + t.Fatal("fixture has no snapshot history") + } + fixture = replaceSnapshotJSON(fixture, []byte(`"snapshot-id":1,`), + []byte(`"parent-snapshot-id":0,"schema-id":0,"snapshot-id":1,`)) + input := append([]byte(`{"future-annotation":"`), bytes.Repeat([]byte{'x'}, 4096)...) + input = append(input, '"', ',') + input = append(input, fixture[1:]...) + + got, fast := parseEagerMetadataV2(input) + if !fast { + t.Fatal("fully populated v2 snapshot did not take the fast path") + } + if len(got.SnapshotList) != 1 { + t.Fatalf("got %d snapshots, want 1", len(got.SnapshotList)) + } + snapshot := got.SnapshotList[0] + if snapshot.SnapshotID != 1 || snapshot.TimestampMs != 60_000 || + snapshot.SequenceNumber != 1 || snapshot.ManifestList == "" || + snapshot.ParentSnapshotID == nil || *snapshot.ParentSnapshotID != 0 || + snapshot.SchemaID == nil || *snapshot.SchemaID != 0 || + snapshot.Summary == nil || snapshot.Summary.Operation != OpAppend { + t.Fatalf("fast path did not retain the complete snapshot: %+v", snapshot) + } +} + +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) { + base := benchmarkMetadataJSON(1, 1, 1, 0, 0) + f.Add(metadataEagerFuzzSeed(base)) + withEscapedKey := replaceSnapshotJSON(base, []byte(`"snapshot-id":1,`), []byte(`"snapshot\u002did":1,`)) + f.Add(metadataEagerFuzzSeed(withEscapedKey)) + withNullParent := replaceSnapshotJSON(base, []byte(`"snapshot-id":1,`), + []byte(`"parent-snapshot-id":null,"snapshot-id":1,`)) + f.Add(metadataEagerFuzzSeed(withNullParent)) + withNestedField := replaceSnapshotJSON(base, []byte(`"timestamp-ms":60000`), + []byte(`"timestamp-ms":60000,"future":{"nested":[null,{"flag":true}]}`)) + f.Add(metadataEagerFuzzSeed(withNestedField)) + withNonStringSummary := replaceSnapshotJSON(base, []byte(`"summary":{"operation":"append"}`), + []byte(`"summary":{"operation":"append","metric":42}`)) + f.Add(metadataEagerFuzzSeed(withNonStringSummary)) + f.Fuzz(func(t *testing.T, input []byte) { + 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 + } + checkEagerMetadataEqual(t, got, want) + }) +} + +func metadataEagerFuzzSeed(data []byte) []byte { + const minSeedSize = 4097 + prefix := []byte(`{"future-annotation":"`) + const suffix = `",` + padding := max(0, minSeedSize-len(prefix)-len(suffix)-(len(data)-1)) + seed := make([]byte, 0, len(prefix)+padding+len(suffix)+len(data)-1) + seed = append(seed, prefix...) + seed = append(seed, bytes.Repeat([]byte{'x'}, padding)...) + seed = append(seed, suffix...) + seed = append(seed, data[1:]...) + + return seed +} + +func replaceSnapshotJSON(data, old, new []byte) []byte { + start := bytes.Index(data, []byte(`"snapshots":[{`)) + if start < 0 { + return data + } + + return append(data[:start], bytes.Replace(data[start:], old, new, 1)...) Review Comment: `data[:start]` keeps `data`'s spare capacity, so this `append` writes into the caller's buffer (here `cap=1024`, `len=916`). `FuzzEagerMetadataV2Parity` reuses one `base` for four replacements, so every replacement after the first starts from a damaged document. I checked on this head: after the escaped-key seed is built, `base` itself no longer takes the fast path, and the null-parent seed doesn't contain `"parent-snapshot-id":null` at all. Built from a fresh `base` each time, all five seeds behave as intended. ```suggestion return slices.Concat(data[:start], bytes.Replace(data[start:], old, new, 1)) ``` ########## table/metadata_eager.go: ########## @@ -0,0 +1,400 @@ +// 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 strict subset of v2 metadata used by Review Comment: This covers the decline-and-fall-back half. Could it also state the other half explicitly: the fast path must never accept input that `encoding/json` would reject? That's the invariant someone editing the parser has to keep, and it's what the fuzz target checks. ########## table/metadata_eager_test.go: ########## @@ -0,0 +1,295 @@ +// 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 TestEagerMetadataV2FullyPopulatedSnapshotFastPath(t *testing.T) { + fixture := benchmarkMetadataJSON(1, 1, 1, 0, 0) + start := bytes.Index(fixture, []byte(`"snapshots":[{`)) + if start < 0 { + t.Fatal("fixture has no snapshot history") + } + fixture = replaceSnapshotJSON(fixture, []byte(`"snapshot-id":1,`), + []byte(`"parent-snapshot-id":0,"schema-id":0,"snapshot-id":1,`)) + input := append([]byte(`{"future-annotation":"`), bytes.Repeat([]byte{'x'}, 4096)...) + input = append(input, '"', ',') + input = append(input, fixture[1:]...) + + got, fast := parseEagerMetadataV2(input) + if !fast { + t.Fatal("fully populated v2 snapshot did not take the fast path") + } + if len(got.SnapshotList) != 1 { + t.Fatalf("got %d snapshots, want 1", len(got.SnapshotList)) + } + snapshot := got.SnapshotList[0] + if snapshot.SnapshotID != 1 || snapshot.TimestampMs != 60_000 || + snapshot.SequenceNumber != 1 || snapshot.ManifestList == "" || + snapshot.ParentSnapshotID == nil || *snapshot.ParentSnapshotID != 0 || + snapshot.SchemaID == nil || *snapshot.SchemaID != 0 || + snapshot.Summary == nil || snapshot.Summary.Operation != OpAppend { + t.Fatalf("fast path did not retain the complete snapshot: %+v", snapshot) + } +} + +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: FYI: locally `-fuzztime 30s` ran 30 inputs (about 1/s), while one full parity check on a seed takes ~46 µs (benchmarked), so the target isn't the bottleneck. I suspect fuzzer overhead on the large `table` package but haven't confirmed. Either way, 30–60 inputs isn't meaningful coverage for a parser that reads untrusted metadata. Could you run it much longer (minutes, and say how long in the description), or move the target into a smaller package so it gets real throughput? -- 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]
