Files
seaweedfs/weed/s3api/iceberg/metadata_cache_test.go
T
672ba10b2b iceberg: parse each table metadata version once and encode the load response once (#13129)
* iceberg: parse each table metadata version once and encode the load response once

Under an Iceberg commit load, about half of the S3/Iceberg server's CPU went into the JSON of the same metadata document. A writer loads a table and then commits to it, and each request parsed the stored metadata again (`table.ParseMetadataBytes`, 17% of CPU in a profile). The load then marshalled it, `json.Marshal` compacted and validated the whole document again around the `json.RawMessage` inside `MarshalJSON`, and the response encoder did that once more around the result (8%). The cost grows with a table's snapshot history.

Changes:

- `tableMetadataCache` keeps the parsed form (and, lazily, the rendered response form) of recently read metadata documents, keyed by bucket and metadata location and bounded at 64 MiB (an entry is charged 6x its source size; a document over a quarter of the bound is never cached). An entry is used only when the stored bytes are byte-identical to the bytes it was parsed from, so a hit returns exactly what parsing would; the key only finds the candidate, and a parse error is never cached. Load table, commit table and commit transaction read through it.
- The parsed metadata is shared read-only between requests: iceberg-go guards its lazily decoded snapshots with its own `sync.Once` and lock, and the metadata builder copies what it changes (`TestMetadataCacheSharedEntryUnderConcurrency`, run with `-race`).
- A table commit remembers the version it stored (parsed from exactly those bytes), so the next load of it is a hit, and drops the version it replaced; a transaction commit drops the versions it replaced.
- `LoadTableResult.MarshalJSON` assembles the response around the rendered metadata instead of re-encoding it as a `RawMessage`, and `writeLoadResult` writes those bytes without the encoder's extra pass. The rendering is used only while `Metadata` is still the cache entry's own parsed metadata; a filtered (`?snapshots=refs`) or replaced `Metadata` is marshalled as before. An encoding failure is now a 500 rather than an empty 200.

The response bytes are the same as before: `TestLoadTableResultMarshalBytes` compares them with the previous encoding, including HTML and U+2028 escaping, with and without a metadata location, config and storage credentials. `TestMetadataCacheHitsOnlyIdenticalBytes` covers the byte check, parse errors, eviction and the commit remember/forget path.

Measured on one server at 8 concurrent writers, about 20 commits/s, CPU sampled over 20 s: 30.0 s before, 21.7 s after.

`go vet ./weed/s3api/iceberg`, `go test ./weed/s3api/iceberg` and `go test -race -run 'MetadataCache|LoadTableResult' ./weed/s3api/iceberg` pass; `go build ./weed` builds.

* iceberg: the shared-entry concurrency test shares one entry

The test started from an empty cache, so each worker could miss and parse
its own copy, and it passed without readers and builders ever sharing an
object. The entry is now parsed before the workers start, and each worker
checks that it was handed that entry. A cache that returns a fresh copy now
fails the test.

* iceberg: keep the snapshots=refs check inline and log the parse error directly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: shorten the metadata cache comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:50:59 -08:00

255 lines
8.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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": "<a&b> 
 \"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<y>"}}}
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)
}
}