Files
seaweedfs/weed/s3api/iceberg/vector_namespace_test.go
T
edbcc718d3 iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read (#13134)
* iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read

## Problem

In a remote-mounted bucket (`remote.mount` + `filer.remote.sync`), a table's `metadata.json` that is not cached locally is a filer entry holding only its `RemoteEntry`: no inline content, no chunks. The Iceberg REST catalog read metadata files as inline content (and, for a register, chunks), so such a file read as empty bytes, and an empty read was then treated as "no metadata":

- a table stored with its metadata location alone (registered, or created through the S3 Tables API) loaded as an empty table: no schema, no snapshots, and clients read no rows;
- a commit to it was refused on a table UUID mismatch for ever, and a commit without requirements replaced the table's history with an empty one;
- registering such a file failed with `unexpected end of JSON input`.

The same empty stand-ins were served when the file was gone or unreadable, and a synthetic empty table when stored metadata did not parse, with the same consequences.

## Fix

- `loadMetadataFile` (and through it `currentMetadataBytes` and RegisterTable) reads a remote-only file of a mounted bucket: its remote size is checked against a 64 MiB bound before anything is fetched, it is cached into the cluster with `CacheRemoteObjectToLocalCluster` (one retry: a cache can race an uncache or a write-back), then inline content or chunks are read.
- An empty file is `errEmptyMetadataFile`. A staged create's empty placeholder is still treated as absent where the staged commit reads it.
- A location whose file is gone or unreadable, or stored metadata that does not parse, fails load, commit and transaction instead of serving an empty stand-in a writer could commit over. A table created without a location (no metadata yet) still loads as a new empty table, and a catalog-only record (Lance) is never read as Iceberg.
- RegisterTable refuses, before anything is read, a metadata location that is not a file directly in a table's `metadata/` directory (a deeper path was read as the same-named file there), and refuses metadata whose own `location` is not the table location it is registered from (a file copied from another table names that table's files).
- The table UUID a commit or a transaction stores is the base metadata's, not a record's that disagrees with it.

`loadTableMetadataBlob` (used only by the manifest repair) is unchanged.

## Tests

- New `iceberg_register_load_test.go` (inline and remote-only files; a location-only table loads from its file and fails with the file gone; commits and transactions keep the history, and fail leaving the table unchanged when the file is gone; oversized remote files and nested locations refused) and `TestACommitStoresTheBaseMetadatasUUID`. Each rule is red with it undone, except the refusal of an entry still remote-only after two cache calls, which fails closed anyway (it reads as an empty file).
- Adapted: the fixtures of `iceberg_register_table_test.go` (`seedRegistrableMetadata`, `seedOversizedMetadata`) give the metadata the table's own location; `TestLoadTableResultOmitsConfigForCredentialVendingClients` and `seedOwnedTable` store the table with its metadata; `TestBuildLoadTableResultNeverReturnsNilMetadata` now expects an error for a location whose file cannot be read and for unparseable metadata, and keeps the empty-metadata and no-location cases.
- `go vet ./weed/s3api/iceberg/`, `go test -race ./weed/s3api/iceberg/` pass, and `weed` builds.

No unit test reads a chunked `metadata.json` (the in-memory filer has no volume servers); that path was checked against a real cluster with a remote-mounted bucket.

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

* iceberg: refuse commits to catalog-only tables

A Lance table loads as an empty Iceberg table, and a commit built on that
placeholder wrote Iceberg metadata and repointed the record's location
(the Lance dataset root) to it. Both commit paths now answer 400.

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

* iceberg: pass the metadata size limit to the remote cache request

The size check ran on the entry the lookup returned. A remote refresh
between the lookup and the cache call could swap in a larger object, which
the filer then downloaded whole. With MaxSize the filer checks the entry
it actually downloads.

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

* iceberg: apply the metadata size limit to inline content

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

---------

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

183 lines
7.5 KiB
Go

package iceberg
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
)
type openAuthenticator struct{}
func (openAuthenticator) AuthenticateRequest(*http.Request) (string, interface{}, s3err.ErrorCode) {
return s3tables.DefaultAccountID, nil, s3err.ErrNone
}
func (openAuthenticator) DefaultAllow() bool { return true }
// An index in a vector bucket is a catalog table the Iceberg catalog can load,
// but a caller holding every s3tables grant gets neither write credentials to
// it nor a commit into it.
func TestVectorIndexIsReadOnlyOverIceberg(t *testing.T) {
filer := s3tablestest.Start(t)
vendor := &stubVendor{credentials: &VendedCredentials{AccessKeyID: "ASIAEXAMPLE"}}
s := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{})
s.SetCredentialVendor(vendor)
s.s3Endpoint = "http://127.0.0.1:8333"
router := mux.NewRouter().SkipClean(true)
s.RegisterRoutes(router)
admin := s3tables.NewManager()
admin.SetTrusted(true)
client := s3tables.NewManagerClient(filer.Client)
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, "vec")
if err != nil {
t.Fatal(err)
}
metadata, _ := json.Marshal(map[string]any{"dimension": 4, "distanceMetric": "cosine"})
for _, op := range []struct {
name string
req interface{}
}{
{"CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: "vec", Format: s3tables.FormatLance}},
{"CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{s3tables.VectorIndexNamespace}}},
{"CreateTable", &s3tables.CreateTableRequest{TableBucketARN: arn, Namespace: []string{s3tables.VectorIndexNamespace},
Name: "idx", Format: s3tables.FormatLance, Metadata: &s3tables.TableMetadata{FullMetadata: metadata}}},
} {
if err := admin.Execute(t.Context(), client, op.name, op.req, nil, ""); err != nil {
t.Fatalf("%s: %v", op.name, err)
}
}
req := httptest.NewRequest(http.MethodGet, "/v1/vec/namespaces/vector/tables/idx", nil)
req.Header.Set(accessDelegationHeader, "vended-credentials")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("load = %d (%s)", rec.Code, rec.Body.String())
}
if vendor.gotPrefix != "vector/idx" || !vendor.gotReadOnly {
t.Errorf("vended prefix %q read-only %v, want vector/idx read-only", vendor.gotPrefix, vendor.gotReadOnly)
}
reqErr := s.authorizeCommit(t.Context(), arn, []string{s3tables.VectorIndexNamespace}, "idx", s3tables.DefaultAccountID)
if reqErr == nil || reqErr.status != http.StatusForbidden {
t.Errorf("commit authorization = %+v, want 403", reqErr)
}
}
// Stage-create registers nothing, so the catalog's own location and vector
// namespace checks never see it. It must not hand out write credentials to an
// index, whether the staged table names the index's location from another
// namespace or sits in the vector namespace itself.
func TestStageCreateCannotReachVectorIndex(t *testing.T) {
filer := s3tablestest.Start(t)
s := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{})
s.s3Endpoint = "http://127.0.0.1:8333"
router := mux.NewRouter().SkipClean(true)
s.RegisterRoutes(router)
admin := s3tables.NewManager()
admin.SetTrusted(true)
client := s3tables.NewManagerClient(filer.Client)
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, "vec")
if err != nil {
t.Fatal(err)
}
for _, op := range []struct {
name string
req interface{}
}{
{"CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: "vec", Format: s3tables.FormatLance}},
{"CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{s3tables.VectorIndexNamespace}}},
{"CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"other"}}},
{"CreateTable", &s3tables.CreateTableRequest{TableBucketARN: arn, Namespace: []string{s3tables.VectorIndexNamespace},
Name: "idx", Format: s3tables.FormatLance}},
} {
if err := admin.Execute(t.Context(), client, op.name, op.req, nil, ""); err != nil {
t.Fatalf("%s: %v", op.name, err)
}
}
for name, tc := range map[string]struct {
namespace, body string
status int
}{
"index location from another namespace": {"other", `{"name":"x","stage-create":true,"location":"s3://vec/vector/idx"}`, http.StatusBadRequest},
"vector namespace": {s3tables.VectorIndexNamespace, `{"name":"y","stage-create":true}`, http.StatusForbidden},
} {
t.Run(name, func(t *testing.T) {
vendor := &stubVendor{credentials: &VendedCredentials{AccessKeyID: "ASIAEXAMPLE"}}
s.SetCredentialVendor(vendor)
req := httptest.NewRequest(http.MethodPost, "/v1/vec/namespaces/"+tc.namespace+"/tables", strings.NewReader(tc.body))
req.Header.Set(accessDelegationHeader, "vended-credentials")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != tc.status {
t.Errorf("stage-create = %d (%s), want %d", rec.Code, rec.Body.String(), tc.status)
}
if vendor.gotPrefix != "" && !vendor.gotReadOnly {
t.Errorf("vended write credentials to %q", vendor.gotPrefix)
}
})
}
}
// A Lance dataset outside the vector namespace loads as an empty Iceberg
// table, but neither commit path may write Iceberg metadata over it: the
// record's location is the Lance client's dataset root.
func TestCatalogOnlyTableRefusesIcebergCommits(t *testing.T) {
filer := s3tablestest.Start(t)
s := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{})
router := mux.NewRouter().SkipClean(true)
s.RegisterRoutes(router)
admin := s3tables.NewManager()
admin.SetTrusted(true)
client := s3tables.NewManagerClient(filer.Client)
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, "lbk")
if err != nil {
t.Fatal(err)
}
const datasetRoot = "s3://lbk/ds/t.lance"
for _, op := range []struct {
name string
req interface{}
}{
{"CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: "lbk", Format: s3tables.FormatLance}},
{"CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"ds"}}},
{"CreateTable", &s3tables.CreateTableRequest{TableBucketARN: arn, Namespace: []string{"ds"},
Name: "t", Format: s3tables.FormatLance, MetadataLocation: datasetRoot}},
} {
if err := admin.Execute(t.Context(), client, op.name, op.req, nil, ""); err != nil {
t.Fatalf("%s: %v", op.name, err)
}
}
for name, tc := range map[string]struct{ path, body string }{
"commit table": {"/v1/lbk/namespaces/ds/tables/t", `{"requirements":[],"updates":[]}`},
"commit transaction": {"/v1/lbk/transactions/commit", `{"table-changes":[{"identifier":{"namespace":["ds"],"name":"t"},"requirements":[],"updates":[]}]}`},
} {
t.Run(name, func(t *testing.T) {
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)))
if rec.Code != http.StatusBadRequest {
t.Errorf("commit = %d (%s), want 400", rec.Code, rec.Body.String())
}
var got s3tables.GetTableResponse
if err := admin.Execute(t.Context(), client, "GetTable", &s3tables.GetTableRequest{TableBucketARN: arn, Namespace: []string{"ds"}, Name: "t"}, &got, ""); err != nil {
t.Fatal(err)
}
if got.MetadataLocation != datasetRoot {
t.Errorf("metadata location = %q, want %q", got.MetadataLocation, datasetRoot)
}
})
}
}