Files
seaweedfs/weed/s3api/iceberg/metadata_cache.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

156 lines
4.3 KiB
Go

package iceberg
import (
"bytes"
"container/list"
"encoding/json"
"reflect"
"sync"
"github.com/apache/iceberg-go/table"
)
// tableMetadataCache keeps the parsed and rendered forms of recently read table
// metadata. An entry is used only when the stored bytes equal the bytes it was
// parsed from; the key (bucket and metadata location) only finds the
// candidate. The parsed metadata is shared between requests and never
// modified: the metadata builder copies what it changes.
var tableMetadataCache = newMetadataCache(64 << 20)
// metadataCostFactor estimates an entry's memory as a multiple of its source
// bytes: the kept source, the parsed form and the rendered form.
const metadataCostFactor = 6
type cachedMetadata struct {
source []byte
parsed table.Metadata
renderOnce sync.Once
rendered []byte
renderErr error
}
// renders reports whether md is this entry's own parsed metadata, so its
// rendering may stand for md.
func (e *cachedMetadata) renders(md table.Metadata) bool {
if e == nil || md == nil || reflect.ValueOf(md).Kind() != reflect.Pointer {
return false
}
return md == e.parsed
}
// render returns the metadata as a load response carries it. The bytes are
// shared and must not be modified.
func (e *cachedMetadata) render() ([]byte, error) {
e.renderOnce.Do(func() {
b, err := json.Marshal(e.parsed)
if err != nil {
e.renderErr = err
return
}
e.rendered = ensureMetadataSpecCompliance(b)
})
return e.rendered, e.renderErr
}
type metadataCacheItem struct {
key string
entry *cachedMetadata
cost int
}
type metadataCache struct {
mu sync.Mutex
max int
size int
ll *list.List
items map[string]*list.Element
}
func newMetadataCache(maxBytes int) *metadataCache {
return &metadataCache{max: maxBytes, ll: list.New(), items: make(map[string]*list.Element)}
}
// parse returns source parsed, from the cache when an entry for the same
// bucket and location holds byte-identical source. A parse error is never
// cached.
func (c *metadataCache) parse(bucket, location string, source []byte) (*cachedMetadata, error) {
cost := len(source) * metadataCostFactor
if location == "" || cost > c.max/4 {
md, err := table.ParseMetadataBytes(source)
if err != nil {
return nil, err
}
return &cachedMetadata{source: source, parsed: md}, nil
}
key := bucket + "\x00" + location
c.mu.Lock()
var candidate *cachedMetadata
if el, ok := c.items[key]; ok {
candidate = el.Value.(*metadataCacheItem).entry
c.ll.MoveToFront(el)
}
c.mu.Unlock()
// an entry's source never changes, so compare outside the lock
if candidate != nil && bytes.Equal(candidate.source, source) {
return candidate, nil
}
// parse a private copy: the parsed form may keep slices of its input
own := bytes.Clone(source)
md, err := table.ParseMetadataBytes(own)
if err != nil {
return nil, err
}
return c.put(key, &cachedMetadata{source: own, parsed: md}, cost), nil
}
// remember keeps a commit's new version, parsed from exactly these bytes, and
// drops the version it replaced. The caller hands over source and parsed.
func (c *metadataCache) remember(bucket, location string, source []byte, parsed table.Metadata, replaced string) {
if replaced != "" {
c.forget(bucket, replaced)
}
cost := len(source) * metadataCostFactor
if location == "" || parsed == nil || cost > c.max/4 {
return
}
c.put(bucket+"\x00"+location, &cachedMetadata{source: source, parsed: parsed}, cost)
}
// forget drops the entry for a version that has been replaced.
func (c *metadataCache) forget(bucket, location string) {
if location == "" {
return
}
key := bucket + "\x00" + location
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.items[key]; ok {
c.size -= el.Value.(*metadataCacheItem).cost
c.ll.Remove(el)
delete(c.items, key)
}
}
func (c *metadataCache) put(key string, entry *cachedMetadata, cost int) *cachedMetadata {
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.items[key]; ok {
item := el.Value.(*metadataCacheItem)
c.size -= item.cost
c.ll.Remove(el)
delete(c.items, key)
}
c.items[key] = c.ll.PushFront(&metadataCacheItem{key: key, entry: entry, cost: cost})
c.size += cost
for c.size > c.max {
el := c.ll.Back()
item := el.Value.(*metadataCacheItem)
c.ll.Remove(el)
delete(c.items, item.key)
c.size -= item.cost
}
return entry
}