Files
seaweedfs/weed/s3api/s3tables/vector_namespace_test.go
T
8bb5c069ec iceberg, s3tables: new tables take only fresh locations (#13160)
* s3tables, iceberg, lance: the catalog assigns every new location; an existing name answers only a reader

A REST create without a location gets <ns>/<name>-<uuid> (#12475) and a
location another record holds is refused (#12473), but a location a
client names is still taken: the REST create's location field and
warehouse property, S3 Tables CreateTable and CreateView with a
MetadataLocation, the Lance declare's location. A free location a client
picks can be one another caller holds staged write credentials for
(stage markers are not claims), or files no record claims any more.
Separately, CreateTable of a name that already holds a table returns
that table (ARN, version token, metadata location) to any caller who may
create, including one who may not read it.

- A REST create or create view naming a location (field or property,
  stage-create or not, the bare bucket included) is refused with 400
  before anything is written; the location is always placeNewEntry's:
  <ns>/<name>-<uuid> in the bucket, or under the operator's
  ICEBERG_WAREHOUSE (no longer under a client's warehouse property).
- A create commit uses a stage marker only when its assign-uuid matches
  the staged table's UUID (PyIceberg and Java send it); any other create
  commit is placed at a fresh <name>-<uuid>, never at the bare name path
  and never at another caller's staged location. Its updates may not set
  another location than the one assigned (400).
- S3 Tables CreateTable and CreateView naming a MetadataLocation are
  refused with 400 (ErrClientTableLocation) unless the call is the
  process's own (WithCatalogAssignedLocation: the REST create, create
  view and create commit at the location they placed; the Lance declare
  at the dataset's name path and register at an existing dataset). AWS's
  CreateTable takes no location either.
- A Lance declare naming a location is refused with 400 (register is for
  existing datasets).
- CreateTable of an existing name answers the table only to a caller who
  may GetTable it; a caller who may only create gets 409
  TableAlreadyExists and nothing about it.

Tests: TestAClientCreateNamesNoLocation (positive controls: a client
create without a location, the catalog's own create with one),
TestARESTCreateNamesNoLocation, TestACreateCommitCannotSetAnotherLocation,
TestACreateCommitTakesOnlyItsOwnStage (the stager's own commit is the
positive control), TestCreateExistingTableAnswersOnlyAReaderWithIt (a
reader gets the table). Existing tests adapted: the s3tables fixtures and
request helpers run as the catalog's own calls (assignedCtx), as do the
iceberg tests that seed tables through the manager;
iceberg_create_table_conflict_test.go's creates send no location and
newConflictEnv points placeNewEntry at conflictLocation, so its races
still collide on one location; TestCreatePathsRefuseAnotherTablesLocation
expects 400 for the three create paths and 409 for the register;
TestCreateTableWithoutLocationUsesItsOwnDirectory drops the bare-bucket
body; lance TestIcebergTablesAreInvisible seeds its Iceberg table as the
catalog; TestDeclareOfAnExistingTableKeepsItsLocation expects 400 for a
declare naming the index's location; TestDeregisterAndReregisterNeedUpdateTable
(#12552) expects 409 instead of 404 for the register and the declare of
a caller without GetTable: the table stays deregistered and nothing is
vended. Each rule is red with it undone.

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

* iceberg: a create may name a fresh location

A REST CreateTable naming a location (Trino always sends one built from
the namespace location, Spark LOCATION, PyIceberg location=) is accepted
again when nothing is stored under it and no live stage holds it; a used
or staged location answers 400. The check runs after the create's
authorization and before anything is written. A bare-bucket location
still gets the assigned <name>-<uuid>. CreateView always uses the
assigned location: a view holds only metadata files.

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

* lance: a declare may restate its name path as its location

pylance and other namespace clients may send the location they expect;
the dataset's own name path is accepted, any other location still
answers 400.

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

* iceberg: a commit cannot set another location on an existing table

CommitTable and CommitTransaction applied a set-location update, so a
table's metadata could name a location outside the directory its record
holds. Such a commit now answers 400 and nothing is written.

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

* iceberg: the fresh-location check pages through every stage marker

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

* iceberg: a fresh location stays apart from stages and tables above or under it

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

* iceberg: a create checks its location again after claiming it

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

* s3tables, iceberg: a live stage holds its location against every create

The catalog counts each live stage-create as a root of the record it
would commit to, so a native create, register, rename or move over a
stage's location is refused. The fresh-location check reads the same
roots, so a stage also backs out of a record that claimed an ancestor
after its first check. A location held by a record or stage answers 409,
as the create gate already did.

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

* iceberg: a create removes only the stages its location covers

A create or commit used to drop every stage marker of its name, which
freed the location of a stage whose credentials were still live.
Expired markers now go with their staged metadata.

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

* iceberg: an assigned stage location checks its claim again too

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

* iceberg: a stage marker lasts as long as its vended credentials

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

* iceberg: test a create that runs while a stage checks its claim

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

* iceberg: a stage holds its location against a create of the same name

A live stage-create now counts under its marker rather than under the
record of its name, so a same-name create over its location is refused
and a stage refuses a same-name table created over its location. Only a
staged commit takes the location its own stage holds.

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

* s3tables: a stage holds only its location against its own record's create

A live stage keeps the path of the record it would commit to away from
other records' files, but a create of that same record writes it: the
stage then holds only its location against it. A stage at its name path
can commit while a later stage of its name, elsewhere, is live.

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

* iceberg: a staged commit's create gate reads its location as a create does

The gate maps a metadata file's location to its table directory, so the
bare location of a stage under a metadata directory resolved to the
namespace and conflicted with the stage's own claim.

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

* iceberg, lance: tests from master create through the catalog's own call

Their creates name a location, which only the catalog's own calls may, and
a caller who may only create gets 409 for an existing name whatever
location its register names.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 -08:00

294 lines
14 KiB
Go

package s3tables
import (
"context"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const vectorTestBucket = "vecns"
func vectorTestARN(t *testing.T) string {
t.Helper()
arn, err := BuildBucketARN(DefaultRegion, DefaultAccountID, vectorTestBucket)
require.NoError(t, err)
return arn
}
// seedVectorBucket lays down, through a trusted Manager, a bucket of the given
// format holding vector/idx (with a policy and a tag) and other/t, the shape
// the S3 Vectors gateway leaves behind.
func seedVectorBucket(t *testing.T, fs *s3tablestest.MemFiler, format string) *Manager {
t.Helper()
trusted := NewManager()
trusted.SetTrusted(true)
run := func(operation string, req interface{}) {
t.Helper()
require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), operation, req, nil, ""))
}
arn := vectorTestARN(t)
run("CreateTableBucket", &CreateTableBucketRequest{Name: vectorTestBucket, Format: format})
for _, ns := range []string{VectorIndexNamespace, "other"} {
run("CreateNamespace", &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{ns}})
}
run("CreateTable", &CreateTableRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}, Name: "idx", Format: format})
run("CreateTable", &CreateTableRequest{TableBucketARN: arn, Namespace: []string{"other"}, Name: "t", Format: format})
run("PutTablePolicy", &PutTablePolicyRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}, Name: "idx",
ResourcePolicy: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:GetTable","Resource":"*"}]}`})
idx, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
run("TagResource", &TagResourceRequest{ResourceARN: idx.TableARN, Tags: map[string]string{"k": "v"}})
return trusted
}
func getTestTable(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, namespace, name string) (*GetTableResponse, error) {
t.Helper()
var resp GetTableResponse
err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{
TableBucketARN: vectorTestARN(t), Namespace: []string{namespace}, Name: name}, &resp, "")
return &resp, err
}
// vectorWrite labels a case "Operation detail" when an operation appears twice.
type vectorWrite struct {
operation string
request interface{}
}
func (w vectorWrite) op() string {
op, _, _ := strings.Cut(w.operation, " ")
return op
}
// vectorNamespaceWrites lists the catalog writes that reach vector/idx or move
// a table across the namespace boundary.
func vectorNamespaceWrites(t *testing.T, indexARN, versionToken string) []vectorWrite {
arn := vectorTestARN(t)
vector := []string{VectorIndexNamespace}
return []vectorWrite{
{"UpdateNamespace", &UpdateNamespaceRequest{TableBucketARN: arn, Namespace: vector, Properties: map[string]string{"a": "b"}}},
{"CreateTable", &CreateTableRequest{TableBucketARN: arn, Namespace: vector, Name: "fresh", Format: FormatLance}},
{"RegisterTable", &RegisterTableRequest{TableBucketARN: arn, Namespace: vector, Name: "registered",
MetadataLocation: "s3://" + vectorTestBucket + "/vector/registered/metadata/v1.metadata.json"}},
// at idx's own root: the catalog refuses an update that moves a record's root
// before anything is written (ErrLocationMove), so only a write the fence
// sees tests the fence
{"UpdateTable", &UpdateTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx", VersionToken: versionToken,
MetadataLocation: "s3://" + vectorTestBucket + "/vector/idx"}},
{"DeleteTable", &DeleteTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}},
{"RenameTable out", &RenameTableRequest{TableBucketARN: arn, SourceNamespace: vector, SourceName: "idx",
DestNamespace: []string{"other"}, DestName: "moved"}},
{"RenameTable in", &RenameTableRequest{TableBucketARN: arn, SourceNamespace: []string{"other"}, SourceName: "t",
DestNamespace: vector, DestName: "t"}},
{"PutTablePolicy", &PutTablePolicyRequest{TableBucketARN: arn, Namespace: vector, Name: "idx",
ResourcePolicy: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:*","Resource":"*"}]}`}},
{"DeleteTablePolicy", &DeleteTablePolicyRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}},
{"TagResource", &TagResourceRequest{ResourceARN: indexARN, Tags: map[string]string{"x": "y"}}},
{"UntagResource", &UntagResourceRequest{ResourceARN: indexARN, TagKeys: []string{"k"}}},
{"PutTableMaintenanceConfiguration", &PutTableMaintenanceConfigurationRequest{TableBucketARN: arn, Namespace: vector, Name: "idx",
Type: MaintenanceTypeIcebergCompaction, Value: &MaintenanceConfigurationValue{Status: "enabled"}}},
}
}
func untrustedManager() *Manager {
m := NewManager()
m.SetDefaultAllow(false)
return m
}
// A caller holding s3tables:* still cannot change the index namespace of a
// vector bucket, and nothing it tried is left behind.
func TestVectorNamespaceRefusesUntrustedWrites(t *testing.T) {
fs := s3tablestest.Start(t)
trusted := seedVectorBucket(t, fs, FormatLance)
before, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
m := untrustedManager()
granted := []string{"s3tables:*"}
for _, tc := range vectorNamespaceWrites(t, before.TableARN, before.VersionToken) {
t.Run(tc.operation, func(t *testing.T) {
got := runRequestAs(t, m, fs, tc.op(), tc.request, granted)
assert.Equal(t, 403, got.status)
assert.Equal(t, ErrCodeAccessDenied, got.body.Type)
assert.Equal(t, vectorNamespaceReadOnly, got.body.Message)
})
}
after, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
assert.Equal(t, before.VersionToken, after.VersionToken)
assert.Equal(t, before.MetadataLocation, after.MetadataLocation)
_, err = getTestTable(t, trusted, fs, "other", "t")
assert.NoError(t, err)
for _, absent := range [][2]string{{VectorIndexNamespace, "fresh"}, {VectorIndexNamespace, "registered"}, {VectorIndexNamespace, "t"}, {"other", "moved"}} {
_, err := getTestTable(t, trusted, fs, absent[0], absent[1])
assert.Error(t, err, "%s/%s should not exist", absent[0], absent[1])
}
var tags ListTagsForResourceResponse
require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), "ListTagsForResource",
&ListTagsForResourceRequest{ResourceARN: before.TableARN}, &tags, ""))
assert.Equal(t, map[string]string{"k": "v"}, tags.Tags)
}
func TestVectorNamespaceCannotBeCreatedOrDeleted(t *testing.T) {
fs := s3tablestest.Start(t)
trusted := NewManager()
trusted.SetTrusted(true)
m := untrustedManager()
granted := []string{"s3tables:*"}
arn := vectorTestARN(t)
ctx := context.Background()
client := NewManagerClient(fs.Client)
require.NoError(t, trusted.Execute(ctx, client, "CreateTableBucket", &CreateTableBucketRequest{Name: vectorTestBucket, Format: FormatLance}, nil, ""))
create := &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}}
got := runRequestAs(t, m, fs, "CreateNamespace", create, granted)
assert.Equal(t, 403, got.status)
assert.Equal(t, vectorNamespaceReadOnly, got.body.Message)
require.NoError(t, trusted.Execute(ctx, client, "CreateNamespace", create, nil, ""))
got = runRequestAs(t, m, fs, "DeleteNamespace", &DeleteNamespaceRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}}, granted)
assert.Equal(t, 403, got.status)
assert.Equal(t, vectorNamespaceReadOnly, got.body.Message)
require.NoError(t, trusted.Execute(ctx, client, "GetNamespace", &GetNamespaceRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}}, nil, ""))
other := &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"other"}}
assert.Equal(t, 200, runRequestAs(t, m, fs, "CreateNamespace", other, granted).status)
}
// The vector engine declares an index the gateway already created; that
// CreateTable writes nothing and keeps succeeding, as do reads.
func TestVectorNamespaceAllowsReadsAndExistingCreate(t *testing.T) {
fs := s3tablestest.Start(t)
trusted := seedVectorBucket(t, fs, FormatLance)
before, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
m := untrustedManager()
granted := []string{"s3tables:*"}
arn := vectorTestARN(t)
vector := []string{VectorIndexNamespace}
for _, tc := range []vectorWrite{
{"CreateTable", &CreateTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx", Format: FormatLance}},
{"GetTable", &GetTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}},
{"ListTables", &ListTablesRequest{TableBucketARN: arn, Namespace: vector}},
{"GetNamespace", &GetNamespaceRequest{TableBucketARN: arn, Namespace: vector}},
{"GetTablePolicy", &GetTablePolicyRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}},
{"ListTagsForResource", &ListTagsForResourceRequest{ResourceARN: before.TableARN}},
} {
t.Run(tc.operation, func(t *testing.T) {
assert.Equal(t, 200, runRequestAs(t, m, fs, tc.op(), tc.request, granted).status)
})
}
after, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
assert.Equal(t, before.VersionToken, after.VersionToken)
require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), "DeleteTable",
&DeleteTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}, nil, ""), "the trusted path stays writable")
}
// An Iceberg bucket's namespace named vector is an ordinary namespace.
func TestVectorNamespaceOfIcebergBucketIsWritable(t *testing.T) {
fs := s3tablestest.Start(t)
trusted := seedVectorBucket(t, fs, FormatIceberg)
before, err := getTestTable(t, trusted, fs, VectorIndexNamespace, "idx")
require.NoError(t, err)
m := untrustedManager()
granted := []string{"s3tables:*"}
for _, tc := range vectorNamespaceWrites(t, before.TableARN, before.VersionToken) {
switch tc.operation {
case "CreateTable", "UpdateTable", "DeleteTable", "RenameTable out":
continue // covered below: they need an Iceberg request or would consume idx
}
t.Run(tc.operation, func(t *testing.T) {
got := runRequestAs(t, m, fs, tc.op(), tc.request, granted)
assert.Equal(t, 200, got.status, "%+v", got.body)
})
}
arn := vectorTestARN(t)
vector := []string{VectorIndexNamespace}
assert.Equal(t, 200, runRequestAs(t, m, fs, "CreateTable",
&CreateTableRequest{TableBucketARN: arn, Namespace: vector, Name: "fresh", Format: FormatIceberg}, granted).status)
assert.Equal(t, 200, runRequestAs(t, m, fs, "DeleteTable",
&DeleteTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}, granted).status)
}
// A caller without a grant gets the answer an Iceberg bucket of the same name
// and shape gives: the read-only rule never tells it the bucket exists or
// holds vectors.
func TestVectorNamespaceDenialHidesBucketFormat(t *testing.T) {
lanceFS := s3tablestest.Start(t)
lance := seedVectorBucket(t, lanceFS, FormatLance)
icebergFS := s3tablestest.Start(t)
seedVectorBucket(t, icebergFS, FormatIceberg)
idx, err := getTestTable(t, lance, lanceFS, VectorIndexNamespace, "idx")
require.NoError(t, err)
m := untrustedManager()
arn := vectorTestARN(t)
writes := append(vectorNamespaceWrites(t, idx.TableARN, idx.VersionToken),
vectorWrite{"CreateNamespace", &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}}},
vectorWrite{"DeleteNamespace", &DeleteNamespaceRequest{TableBucketARN: arn, Namespace: []string{VectorIndexNamespace}}})
for _, tc := range writes {
t.Run(tc.operation, func(t *testing.T) {
got := runUnauthorizedRequest(t, m, lanceFS, tc.op(), tc.request)
want := runUnauthorizedRequest(t, m, icebergFS, tc.op(), tc.request)
assert.Equal(t, want, got)
assert.NotEqual(t, vectorNamespaceReadOnly, got.body.Message)
})
}
}
// A deferred create writes into the bucket before it registers anything, so
// its gate refuses the vector namespace as the create itself would.
func TestAuthorizeCreateTableRefusesVectorNamespace(t *testing.T) {
identity := &testIdentity{Name: "reader", Account: &testIdentityAccount{Id: "reader"}, Actions: []string{"s3tables:*"}}
ctx := s3_constants.SetIdentityInContext(assignedCtx(), identity)
req := &CreateTableRequest{TableBucketARN: vectorTestARN(t), Namespace: []string{VectorIndexNamespace}, Name: "fresh"}
lanceFS := s3tablestest.Start(t)
seedVectorBucket(t, lanceFS, FormatLance)
err := untrustedManager().AuthorizeCreateTable(ctx, NewManagerClient(lanceFS.Client), req, "reader")
var apiErr *S3TablesError
require.ErrorAs(t, err, &apiErr)
assert.Equal(t, ErrCodeAccessDenied, apiErr.Type)
assert.Equal(t, vectorNamespaceReadOnly, apiErr.Message)
icebergFS := s3tablestest.Start(t)
seedVectorBucket(t, icebergFS, FormatIceberg)
assert.NoError(t, untrustedManager().AuthorizeCreateTable(ctx, NewManagerClient(icebergFS.Client), req, "reader"))
}
// Behind the fence a rewrite that leaves the entry as stored, as an
// idempotent repair does, passes without writing; any real change is refused.
func TestVectorNamespaceFencePassesOnlyNoOpUpdates(t *testing.T) {
fs := s3tablestest.Start(t)
seedVectorBucket(t, fs, FormatLance)
h := untrustedManager().handler
fence := &vectorNamespaceFence{h: h, filer: NewManagerClient(fs.Client)}
idxPath := GetTablePath(vectorTestBucket, VectorIndexNamespace, "idx")
stored := fs.Get(GetNamespacePath(vectorTestBucket, VectorIndexNamespace), "idx").Extended[ExtendedKeyMetadata]
err := fence.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return h.setExtendedAttribute(context.Background(), client, idxPath, ExtendedKeyMetadata, stored)
})
require.NoError(t, err)
assert.False(t, fence.tripped.Load())
err = fence.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return h.setExtendedAttribute(context.Background(), client, idxPath, ExtendedKeyMetadata, []byte(`{}`))
})
assert.ErrorIs(t, err, errVectorNamespaceReadOnly)
assert.True(t, fence.tripped.Load())
assert.Equal(t, stored, fs.Get(GetNamespacePath(vectorTestBucket, VectorIndexNamespace), "idx").Extended[ExtendedKeyMetadata])
}