package iceberg import ( "bytes" "encoding/json" "errors" "net/http/httptest" "strings" "sync" "testing" "github.com/apache/iceberg-go" "github.com/apache/iceberg-go/table" ) // legacyLoadTableResultJSON is how a load response was encoded before the // hand-assembled MarshalJSON: json.Marshal of the struct with the metadata as a // RawMessage, then the encoder's own pass over MarshalJSON's output. func legacyLoadTableResultJSON(t *testing.T, r LoadTableResult) []byte { t.Helper() metaBytes, err := json.Marshal(r.Metadata) if err != nil { t.Fatal(err) } metaBytes = ensureMetadataSpecCompliance(metaBytes) inner, err := json.Marshal(struct { MetadataLocation string `json:"metadata-location,omitempty"` Metadata json.RawMessage `json:"metadata"` Config iceberg.Properties `json:"config"` StorageCredentials []StorageCredential `json:"storage-credentials,omitempty"` }{r.MetadataLocation, metaBytes, r.Config, r.StorageCredentials}) if err != nil { t.Fatal(err) } out, err := json.Marshal(json.RawMessage(inner)) if err != nil { t.Fatal(err) } return out } func metadataWithProperties(t *testing.T, props iceberg.Properties) table.Metadata { t.Helper() base := metadataWithSnapshots(t, []int64{11, 12, 13}, 11) builder, err := table.MetadataBuilderFromBase(base, "") if err != nil { t.Fatal(err) } if err := builder.SetProperties(props); err != nil { t.Fatal(err) } md, err := builder.Build() if err != nil { t.Fatal(err) } return md } // A client parses these bytes: the hand-assembled response must be the bytes // the encoder produced before, rendered from the cache or not. func TestLoadTableResultMarshalBytes(t *testing.T) { md := metadataWithProperties(t, iceberg.Properties{"note": " 
 \"q\""}) raw, err := json.Marshal(md) if err != nil { t.Fatal(err) } cache := newMetadataCache(64 << 20) cached, err := cache.parse("bkt", "s3://bkt/ns/t/metadata/v3.metadata.json", raw) if err != nil { t.Fatal(err) } if _, err := cached.render(); err != nil { t.Fatal(err) } creds := []StorageCredential{{Prefix: "s3://bkt/ns/t", Config: iceberg.Properties{"s3.session-token": "x"}}} cases := map[string]LoadTableResult{ "bare": {Metadata: cached.parsed, Config: iceberg.Properties{}}, "nil config": {Metadata: cached.parsed}, "location": {MetadataLocation: "s3://bkt/ns/t/metadata/v3.metadata.json", Metadata: cached.parsed, Config: iceberg.Properties{"s3.endpoint": "http://h<1>"}}, "credentials": {MetadataLocation: "s3://bkt/ns/t/m.json", Metadata: cached.parsed, Config: iceberg.Properties{}, StorageCredentials: creds}, "no credentials": {Metadata: cached.parsed, Config: iceberg.Properties{}, StorageCredentials: []StorageCredential{}}, "nil metadata": {Config: iceberg.Properties{}}, } for name, r := range cases { want := legacyLoadTableResultJSON(t, r) got, err := r.MarshalJSON() if err != nil { t.Fatalf("%s: %v", name, err) } if !bytes.Equal(got, want) { t.Errorf("%s: MarshalJSON\n got %s\nwant %s", name, got, want) } if r.Metadata != nil { r.cached = cached if got, _ := r.MarshalJSON(); !bytes.Equal(got, want) { t.Errorf("%s from the cache's rendering:\n got %s\nwant %s", name, got, want) } } } // a Metadata replaced after the load (?snapshots=refs) is marshalled itself, never the cached full document refs, err := applySnapshotsParam(httptest.NewRequest("GET", "/v1/namespaces/ns/tables/t?snapshots=refs", nil), cached.parsed) if err != nil || len(refs.Snapshots()) >= len(cached.parsed.Snapshots()) { t.Fatalf("precondition: refs-only metadata keeps fewer snapshots (%v)", err) } filtered := LoadTableResult{Metadata: refs, Config: iceberg.Properties{}, cached: cached} got, err := filtered.MarshalJSON() if err != nil { t.Fatal(err) } if want := legacyLoadTableResultJSON(t, filtered); !bytes.Equal(got, want) { t.Errorf("a replaced Metadata was answered with the cache's rendering:\n got %s\nwant %s", got, want) } } // The cache is a memo of ParseMetadataBytes: an entry is used only for // byte-identical source, a parse error is never kept, and its size is bounded. func TestMetadataCacheHitsOnlyIdenticalBytes(t *testing.T) { cache := newMetadataCache(64 << 20) a, err := json.Marshal(metadataWithProperties(t, iceberg.Properties{"v": "1"})) if err != nil { t.Fatal(err) } b, err := json.Marshal(metadataWithProperties(t, iceberg.Properties{"v": "2"})) if err != nil { t.Fatal(err) } loc := "s3://bkt/ns/t/metadata/v1.metadata.json" first, err := cache.parse("bkt", loc, a) if err != nil { t.Fatal(err) } again, err := cache.parse("bkt", loc, bytes.Clone(a)) if err != nil || again != first { t.Fatalf("identical bytes at the same location: got a new entry (%v)", err) } // the same key with other bytes is parsed from those bytes, never served the old entry other, err := cache.parse("bkt", loc, b) if err != nil || other == first || other.parsed.Properties()["v"] != "2" { t.Fatalf("other bytes under the same key served %v (%v)", other.parsed.Properties(), err) } // another bucket with the same location string and bytes is its own entry if elsewhere, _ := cache.parse("other", loc, b); elsewhere == other { t.Fatal("an entry crossed buckets") } // the caller's buffer changing later cannot change the entry buf := bytes.Clone(a) kept, _ := cache.parse("bkt", "s3://bkt/ns/t/metadata/v9.metadata.json", buf) for i := range buf { buf[i] = ' ' } if kept.parsed.Properties()["v"] != "1" || !bytes.Equal(kept.source, a) { t.Fatal("the entry aliases the caller's buffer") } // a document that does not parse is an error every time, and nothing is kept bad := []byte(`{"format-version": 2, "table-uuid": "x"}`) for i := 0; i < 2; i++ { if _, err := cache.parse("bkt", "s3://bkt/ns/bad/metadata/v1.metadata.json", bad); err == nil { t.Fatal("unparseable metadata parsed") } } if _, ok := cache.items["bkt\x00s3://bkt/ns/bad/metadata/v1.metadata.json"]; ok { t.Fatal("a parse error was cached") } // a commit's new version, parsed from the bytes it stored, is a hit for the next load; the version it replaced is gone next, err := json.Marshal(metadataWithProperties(t, iceberg.Properties{"v": "3"})) if err != nil { t.Fatal(err) } parsedNext, err := table.ParseMetadataBytes(next) if err != nil { t.Fatal(err) } cache.remember("bkt", "s3://bkt/ns/t/metadata/v2.metadata.json", next, parsedNext, loc) if hit, _ := cache.parse("bkt", "s3://bkt/ns/t/metadata/v2.metadata.json", bytes.Clone(next)); hit == nil || hit.parsed != parsedNext { t.Fatal("the committed version was parsed again") } if _, ok := cache.items["bkt\x00"+loc]; ok { t.Fatal("the replaced version is still kept") } // bounded: entries are evicted oldest first and the accounted size stays under the limit small := newMetadataCache(len(a) * metadataCostFactor * 5) for i := 0; i < 20; i++ { if _, err := small.parse("bkt", "s3://bkt/ns/t/metadata/v"+strings.Repeat("x", i)+".json", a); err != nil { t.Fatal(err) } } if small.size > small.max || small.ll.Len() != len(small.items) || len(small.items) > 5 { t.Fatalf("size %d of %d, %d entries", small.size, small.max, len(small.items)) } } // Entries are shared between concurrent requests: loads render and read them // while commits build new metadata on them (go test -race). func TestMetadataCacheSharedEntryUnderConcurrency(t *testing.T) { cache := newMetadataCache(64 << 20) raw, err := json.Marshal(metadataWithSnapshots(t, []int64{1, 2, 3, 4, 5}, 2)) if err != nil { t.Fatal(err) } loc := "s3://bkt/ns/t/metadata/v5.metadata.json" // parsed once before the workers start, so every one of them is handed this // same entry (a worker that parsed its own copy would race on nothing) shared, err := cache.parse("bkt", loc, raw) if err != nil { t.Fatal(err) } var wg sync.WaitGroup errs := make(chan error, 64) for i := 0; i < 32; i++ { wg.Add(1) go func(i int) { defer wg.Done() e, err := cache.parse("bkt", loc, raw) if err != nil { errs <- err return } if e != shared { errs <- errors.New("a worker was given its own entry, not the shared one") return } if i%2 == 0 { if _, err := e.render(); err != nil { errs <- err } _ = e.parsed.CurrentSnapshot() return } builder, err := table.MetadataBuilderFromBase(e.parsed, loc) if err != nil { errs <- err return } if err := builder.RemoveSnapshots([]int64{1}, false); err != nil { errs <- err return } if _, err := builder.Build(); err != nil { errs <- err } }(i) } wg.Wait() close(errs) for err := range errs { t.Fatal(err) } if n := len(shared.parsed.Snapshots()); n != 5 { t.Fatalf("a commit's builder changed the shared metadata: %d snapshots, want 5", n) } }