Files
seaweedfs/weed/s3api/s3tables/handler_location_owner_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

514 lines
26 KiB
Go

package s3tables
import (
"context"
"encoding/json"
"errors"
"net/http"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
func renameLocation(rel string) string {
return "s3://" + renameTestBucket + "/" + rel
}
// A table's files belong to one catalog record. A create, register, update or
// view naming a location at, under or above another record's files is refused,
// and so is one naming the files a renamed table left under its old name.
func TestLocationOwnedByOneRecord(t *testing.T) {
fs, m := startRenameManager(t)
bucketARN := mustBucketARN(t)
requireOK(t, m, fs, "CreateNamespace", &CreateNamespaceRequest{TableBucketARN: bucketARN, Namespace: []string{"ns2"}})
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{
TableBucketARN: bucketARN,
Namespace: []string{"ns"},
Name: "own",
Format: FormatIceberg,
MetadataLocation: renameLocation("ns/own/metadata/v1.metadata.json"),
})
refused := func(t *testing.T, operation string, input interface{}) {
t.Helper()
status, resp := runHandler(t, m, fs.Client, operation, input)
assert.Equal(t, http.StatusConflict, status, "%s: %+v", operation, resp)
assert.Equal(t, ErrCodeConflict, resp.Type)
assert.NotContains(t, resp.Message, "ns/t")
}
checkRefusals := func(t *testing.T) {
for _, location := range []string{
"ns/t/metadata/v3.metadata.json",
"ns/t/data/part/metadata/v1.metadata.json",
"ns/metadata/v1.metadata.json",
} {
refused(t, "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "alias", Format: FormatLance, MetadataLocation: renameLocation(location)})
refused(t, "RegisterTable", &RegisterTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "alias", MetadataLocation: renameLocation(location)})
refused(t, "CreateView", &CreateViewRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "alias", MetadataLocation: renameLocation(location)})
// the catalog refuses any update that moves a record's root (ErrLocationMove), before it looks at who holds the new one
status, resp := runHandler(t, m, fs.Client, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "own", MetadataVersion: 2, MetadataLocation: renameLocation(location)})
assert.Equal(t, http.StatusBadRequest, status, "UpdateTable: %+v", resp)
assert.NotContains(t, resp.Message, "ns/t")
}
assert.Nil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "alias"))
}
t.Run("live table", checkRefusals)
requireOK(t, m, fs, "RenameTable", &RenameTableRequest{
TableBucketARN: bucketARN,
SourceNamespace: []string{"ns"},
SourceName: "t",
DestNamespace: []string{"ns2"},
DestName: "t",
})
t.Run("renamed table", checkRefusals)
t.Run("free locations", func(t *testing.T) {
requireOK(t, m, fs, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "own", MetadataVersion: 2, MetadataLocation: renameLocation("ns/own/metadata/v2.metadata.json")})
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg, MetadataLocation: renameLocation("ns/t2/metadata/v1.metadata.json")})
requireOK(t, m, fs, "RegisterTable", &RegisterTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "t3", MetadataLocation: renameLocation("ns/t3/metadata/v1.metadata.json")})
})
}
// A drop of a record that shares its files with another is refused, so the
// other record keeps them.
func TestDeleteTableKeepsSharedFiles(t *testing.T) {
fs, m := startRenameManager(t)
aliasMeta, err := json.Marshal(tableMetadataInternal{
Name: "alias",
Namespace: "ns",
Format: FormatIceberg,
OwnerAccountID: DefaultAccountID,
MetadataVersion: 3,
MetadataLocation: renameLocation("ns/t/metadata/v3.metadata.json"),
})
require.NoError(t, err)
fs.Put(GetNamespacePath(renameTestBucket, "ns"), "alias", map[string][]byte{
ExtendedKeyMetadata: aliasMeta,
ExtendedKeyEntryType: []byte(EntryTypeTable),
})
for _, name := range []string{"alias", "t"} {
status, resp := runHandler(t, m, fs.Client, "DeleteTable", deleteTableRequest(t, name))
assert.Equal(t, http.StatusConflict, status, "%s: %+v", name, resp)
}
tablePath := GetTablePath(renameTestBucket, "ns", "t")
assert.NotNil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "t"))
assert.NotNil(t, fs.Get(path.Join(tablePath, "metadata"), "v3.metadata.json"))
}
// rootRaceClient lands a rival record over the same root the moment a write
// reaches the record at dir/name, the way a second create that read the root
// free before this record existed publishes its own.
type rootRaceClient struct {
filer_pb.SeaweedFilerClient
f *s3tablestest.MemFiler
dir string
name string
location string
planted bool
then func()
}
func (c *rootRaceClient) plant() {
if c.planted {
return
}
c.planted = true
if c.then != nil {
defer c.then()
}
rival, _ := json.Marshal(tableMetadataInternal{Name: "rival", Namespace: "ns", Format: FormatIceberg, MetadataLocation: c.location})
c.f.Put(c.dir, "rival", map[string][]byte{
ExtendedKeyMetadata: rival,
ExtendedKeyEntryType: []byte(EntryTypeTable),
ExtendedKeyDeleting: []byte(createClaim),
})
}
func (c *rootRaceClient) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest, opts ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
resp, err := c.SeaweedFilerClient.UpdateEntry(ctx, req, opts...)
if err == nil && req.Directory == c.dir && req.Entry.Name == c.name {
c.plant()
}
return resp, err
}
// listFailClient fails every listing once a write reaches the record at
// dir/name, so the check that follows the write cannot run.
type listFailClient struct {
filer_pb.SeaweedFilerClient
dir string
name string
failing bool
}
func (c *listFailClient) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest, opts ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
resp, err := c.SeaweedFilerClient.UpdateEntry(ctx, req, opts...)
if err == nil && req.Directory == c.dir && req.Entry.Name == c.name {
c.failing = true
}
return resp, err
}
func (c *listFailClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
if c.failing {
return nil, errors.New("listing unavailable")
}
return c.SeaweedFilerClient.ListEntries(ctx, in, opts...)
}
// Two writers that both read a root free each check it again once their record
// is written, so the one that sees the other backs out instead of both landing.
func TestLocationRaceBacksOut(t *testing.T) {
nsPath := GetNamespacePath(renameTestBucket, "ns")
location := renameLocation("ns/shared/metadata/v1.metadata.json")
t.Run("create", func(t *testing.T) {
fs, m := startRenameManager(t)
client := &rootRaceClient{SeaweedFilerClient: fs.Client, f: fs, dir: nsPath, name: "mine", location: location}
status, resp := runHandler(t, m, client, "CreateTable", &CreateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "mine", Format: FormatIceberg, MetadataLocation: location,
})
assert.Equal(t, http.StatusConflict, status, "%+v", resp)
require.True(t, client.planted)
if entry := fs.Get(nsPath, "mine"); entry != nil {
assert.NotContains(t, entry.Extended, ExtendedKeyMetadata)
}
})
t.Run("update", func(t *testing.T) {
fs, m := startRenameManager(t)
before := fs.Get(nsPath, "t").Extended[ExtendedKeyMetadata]
client := &rootRaceClient{SeaweedFilerClient: fs.Client, f: fs, dir: nsPath, name: "t", location: location}
status, resp := runHandler(t, m, client, "UpdateTable", &UpdateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t", MetadataVersion: 4, MetadataLocation: location,
})
// the catalog refuses the move before it writes anything (ErrLocationMove)
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
require.False(t, client.planted)
assert.Equal(t, string(before), string(fs.Get(nsPath, "t").Extended[ExtendedKeyMetadata]))
assert.NotContains(t, fs.Get(nsPath, "t").Extended, ExtendedKeyMoving)
})
// A rival reading the old root while the move is checked still finds it
// held, so a move that backs out never hands back a root someone took.
for _, operation := range []string{"UpdateTable", "UpdateView"} {
t.Run(operation+" keeps its old root while moving", func(t *testing.T) {
fs, m := startRenameManager(t)
oldLocation := renameLocation("ns/old/metadata/v1.metadata.json")
var update interface{}
if operation == "UpdateTable" {
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", Format: FormatIceberg, MetadataLocation: oldLocation})
update = &UpdateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", MetadataVersion: 2, MetadataLocation: location}
} else {
requireOK(t, m, fs, "CreateView", &CreateViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", MetadataLocation: oldLocation})
update = &UpdateViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", MetadataVersion: 2, MetadataLocation: location}
}
before := fs.Get(nsPath, "a").Extended[ExtendedKeyMetadata]
client := &rootRaceClient{SeaweedFilerClient: fs.Client, f: fs, dir: nsPath, name: "a", location: location}
status, resp := runHandler(t, m, client, operation, update)
// the catalog refuses the move before it writes anything (ErrLocationMove): the old root stays the record's
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
require.False(t, client.planted)
assert.ErrorIs(t, checkLocationUnclaimed(context.Background(), fs.Client, renameTestBucket, path.Join(nsPath, "b"), CatalogRecordRoot(renameTestBucket, path.Join(nsPath, "b"), oldLocation, "")), ErrLocationInUse)
assert.Equal(t, string(before), string(fs.Get(nsPath, "a").Extended[ExtendedKeyMetadata]))
assert.NotContains(t, fs.Get(nsPath, "a").Extended, ExtendedKeyMoving)
})
}
// Another update of the record landing while a move is checked cannot
// leave the record on the root a racing create took.
for _, other := range []string{"ns/shared/metadata/v2.metadata.json", "ns/old/metadata/v2.metadata.json"} {
t.Run("update moving under an update to "+other, func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", Format: FormatIceberg, MetadataLocation: renameLocation("ns/old/metadata/v1.metadata.json")})
client := &rootRaceClient{SeaweedFilerClient: fs.Client, f: fs, dir: nsPath, name: "a", location: location}
client.then = func() {
runHandler(t, m, fs.Client, "UpdateTable", &UpdateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", MetadataVersion: 3, MetadataLocation: renameLocation(other)})
}
status, resp := runHandler(t, m, client, "UpdateTable", &UpdateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "a", MetadataVersion: 2, MetadataLocation: location})
// refused before anything is written (ErrLocationMove)
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
require.False(t, client.planted)
assert.False(t, RootClaimed(mustRoots(t, fs), path.Join(nsPath, "rival"), path.Join(nsPath, "shared")))
assert.NotContains(t, fs.Get(nsPath, "a").Extended, ExtendedKeyMoving)
})
}
t.Run("update with a failed check", func(t *testing.T) {
fs, m := startRenameManager(t)
before := fs.Get(nsPath, "t").Extended[ExtendedKeyMetadata]
client := &listFailClient{SeaweedFilerClient: fs.Client, dir: nsPath, name: "t"}
status, resp := runHandler(t, m, client, "UpdateTable", &UpdateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t", MetadataVersion: 4, MetadataLocation: location,
})
// refused before anything is written (ErrLocationMove)
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
require.False(t, client.failing)
assert.Equal(t, string(before), string(fs.Get(nsPath, "t").Extended[ExtendedKeyMetadata]))
assert.NotContains(t, fs.Get(nsPath, "t").Extended, ExtendedKeyMoving)
})
t.Run("rename", func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "c", Format: FormatIceberg})
dropWarehouseLocation(t, fs, nsPath, "c")
client := &rootRaceClient{SeaweedFilerClient: fs.Client, f: fs, dir: nsPath, name: "dest", location: renameLocation("ns/dest/metadata/v1.metadata.json")}
status, resp := runHandler(t, m, client, "RenameTable", &RenameTableRequest{
TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: "c", DestNamespace: []string{"ns"}, DestName: "dest",
})
// c has no stored location: the catalog refuses its rename before anything is written
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
require.False(t, client.planted)
assert.Contains(t, fs.Get(nsPath, "c").Extended, ExtendedKeyMetadata)
if entry := fs.Get(nsPath, "dest"); entry != nil {
assert.NotContains(t, entry.Extended, ExtendedKeyMetadata)
}
})
}
// A move reserves its new root on the record, so a second move of the record
// waits for it, and an update that keeps the root clears a reservation a
// crashed move left behind.
func TestMoveReservationLeftBehind(t *testing.T) {
fs, m := startRenameManager(t)
nsPath := GetNamespacePath(renameTestBucket, "ns")
bucketARN := mustBucketARN(t)
entry := fs.Get(nsPath, "t")
leftover, _ := json.Marshal(tableMetadataInternal{Name: "t", Namespace: "ns", MetadataLocation: renameLocation("ns/elsewhere/metadata/v4.metadata.json")})
entry.Extended[ExtendedKeyMoving] = leftover
fs.Put(nsPath, "t", entry.Extended)
refused := renameLocation("ns/moved/metadata/v1.metadata.json")
assert.True(t, RootClaimed(mustRoots(t, fs), path.Join(nsPath, "other"), path.Join(nsPath, "elsewhere")))
status, resp := runHandler(t, m, fs.Client, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "t", MetadataVersion: 4, MetadataLocation: refused})
// the catalog refuses every move (ErrLocationMove)
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
requireOK(t, m, fs, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "t", MetadataVersion: 4, MetadataLocation: renameLocation("ns/t/metadata/v4.metadata.json")})
assert.NotContains(t, fs.Get(nsPath, "t").Extended, ExtendedKeyMoving)
assert.False(t, RootClaimed(mustRoots(t, fs), path.Join(nsPath, "other"), path.Join(nsPath, "elsewhere")))
status, resp = runHandler(t, m, fs.Client, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "t", MetadataVersion: 5, MetadataLocation: refused})
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
assert.NotContains(t, fs.Get(nsPath, "t").Extended, ExtendedKeyMoving)
}
// recordRoot returns the directory the record at dir/name keeps its files under.
func recordRoot(t *testing.T, fs *s3tablestest.MemFiler, dir, name string) string {
t.Helper()
entry := fs.Get(dir, name)
require.NotNil(t, entry)
var metadata tableMetadataInternal
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
return metadata.root(renameTestBucket, path.Join(dir, name))
}
// dropWarehouseLocation turns the record at dir/name into one written before
// tables got a directory of their own, which keeps its files under its path.
func dropWarehouseLocation(t *testing.T, fs *s3tablestest.MemFiler, dir, name string) {
t.Helper()
entry := fs.Get(dir, name)
require.NotNil(t, entry)
var metadata tableMetadataInternal
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
metadata.WarehouseLocation = ""
data, err := json.Marshal(&metadata)
require.NoError(t, err)
entry.Extended[ExtendedKeyMetadata] = data
}
func mustRoots(t *testing.T, fs *s3tablestest.MemFiler) map[string][]string {
t.Helper()
roots, err := CatalogRecordRoots(context.Background(), fs.Client, renameTestBucket)
require.NoError(t, err)
return roots
}
// A table that keeps its files elsewhere still owns its catalog entry: a view
// recorded at that entry would take it with the view's files on drop.
func TestLocationRefusesAnotherRecordsEntry(t *testing.T) {
fs, m := startRenameManager(t)
bucketARN := mustBucketARN(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{
TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "a", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/storage/metadata/v1.metadata.json"),
})
status, resp := runHandler(t, m, fs.Client, "CreateView", &CreateViewRequest{
TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "v", MetadataLocation: renameLocation("ns/a/metadata/v1.metadata.json"),
})
assert.Equal(t, http.StatusConflict, status, "%+v", resp)
}
// A record taken away by a rename or a delete while a move holds its
// reservation leaves the old name free: the move can no longer clear the
// reservation once the record is gone.
func TestRecordGoneDropsItsMoveReservation(t *testing.T) {
nsPath := GetNamespacePath(renameTestBucket, "ns")
reserve := func(t *testing.T, fs *s3tablestest.MemFiler, name string) {
t.Helper()
moving, _ := json.Marshal(tableMetadataInternal{Name: name, Namespace: "ns", Format: FormatIceberg, MetadataLocation: renameLocation("ns/target/metadata/v9.metadata.json")})
fs.Get(nsPath, name).Extended[ExtendedKeyMoving] = moving
}
reuse := func(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, name string) {
t.Helper()
assert.NotContains(t, fs.Get(nsPath, name).Extended, ExtendedKeyMoving)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: name, Format: FormatIceberg,
MetadataLocation: renameLocation("ns/fresh-" + name + "/metadata/v1.metadata.json"),
})
}
t.Run("rename", func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "r", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/r-files/metadata/v1.metadata.json"),
})
reserve(t, fs, "r")
requireOK(t, m, fs, "RenameTable", &RenameTableRequest{
TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: "r", DestNamespace: []string{"ns"}, DestName: "u",
})
assert.NotContains(t, fs.Get(nsPath, "u").Extended, ExtendedKeyMoving)
reuse(t, m, fs, "r")
})
t.Run("delete", func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "d", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/d-files/metadata/v1.metadata.json"),
})
reserve(t, fs, "d")
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "d"})
reuse(t, m, fs, "d")
})
}
// assignedCtx is the context of a catalog call this process makes: the
// Iceberg REST catalog and the Lance namespace pass the locations they were
// assigned (or, for a register, existing files), which a client's CreateTable
// or CreateView may not (WithCatalogAssignedLocation). Tests that are about
// another rule set up their tables through it.
func assignedCtx() context.Context {
return WithCatalogAssignedLocation(context.Background())
}
// A client's CreateTable or CreateView names no location: the catalog
// assigns one. Naming one is refused with 400 and nothing is created; only
// this process's own callers, which pass the location they were assigned, may.
func TestAClientCreateNamesNoLocation(t *testing.T) {
fs, m := startRenameManager(t)
bucketARN := mustBucketARN(t)
nsPath := GetNamespacePath(renameTestBucket, "ns")
client := func(op string, req interface{}) error {
return m.Execute(context.Background(), NewManagerClient(fs.Client), op, req, nil, "")
}
for name, c := range map[string]struct {
op string
req interface{}
}{
"iceberg table": {"CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/mine/metadata/v1.metadata.json")}},
"lance table": {"CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine2", Format: FormatLance,
MetadataLocation: renameLocation("ns/mine2")}},
"view": {"CreateView", &CreateViewRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine3",
MetadataLocation: renameLocation("ns/mine3/metadata/v1.metadata.json")}},
} {
var s3Err *S3TablesError
if assert.ErrorAs(t, client(c.op, c.req), &s3Err, name) {
assert.Equal(t, ErrCodeInvalidRequest, s3Err.Type, name)
}
}
for _, name := range []string{"mine", "mine2", "mine3"} {
assert.Nil(t, fs.Get(nsPath, name), name)
}
// positive controls: a client create without a location, and the catalog's own call with one
require.NoError(t, client("CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "plain", Format: FormatIceberg}))
require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/mine/metadata/v1.metadata.json")}, nil, ""))
}
// A live Iceberg stage-create holds its location like the record it commits
// to: a create over it is refused, while a create of the stage's name at
// another location, and any create once the stage has expired, goes ahead.
func TestALiveStageHoldsItsLocation(t *testing.T) {
fs, m := startRenameManager(t)
bucketARN := mustBucketARN(t)
stage := func(t *testing.T, table, location string, expiresAt time.Time) {
t.Helper()
content, err := json.Marshal(map[string]string{"location": renameLocation(location), "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)})
require.NoError(t, err)
stagedDir := path.Join(GetTableBucketPath(renameTestBucket), StagedTablesDirName)
fs.Put(GetTableBucketPath(renameTestBucket), StagedTablesDirName, nil)
fs.Put(stagedDir, "ns", nil)
fs.Put(path.Join(stagedDir, "ns"), table, nil)
dir := path.Join(stagedDir, "ns", table)
_, err = fs.Client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{Directory: dir, Entry: &filer_pb.Entry{Name: table + ".json", Content: content}})
require.NoError(t, err)
}
create := func(name string) (int, S3TablesError) {
return runHandler(t, m, fs.Client, "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: name, Format: FormatLance})
}
stage(t, "staged", "ns/lance1/data", time.Now().Add(time.Hour))
status, resp := create("lance1")
assert.Equal(t, http.StatusConflict, status, "%+v", resp)
assert.Nil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "lance1"))
stage(t, "lance2", "ns/lance2/data", time.Now().Add(time.Hour))
status, resp = create("lance2")
assert.Equal(t, http.StatusConflict, status, "a stage of the same name: %+v", resp)
assert.Nil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "lance2"))
stage(t, "lance4", "ns/lance4-x", time.Now().Add(time.Hour))
status, resp = create("lance4")
assert.Equal(t, http.StatusOK, status, "a stage of the same name elsewhere: %+v", resp)
stage(t, "expired", "ns/lance3/data", time.Now().Add(-time.Hour))
status, resp = create("lance3")
assert.Equal(t, http.StatusOK, status, "%+v", resp)
}
// An update may not move a table's root: its older snapshots keep naming files
// under the root it has, which a move would leave to no record. A table then
// registered over that root would load them, and its drop would purge them.
func TestUpdateCannotMoveATablesRoot(t *testing.T) {
fs, m := startRenameManager(t)
bucketARN := mustBucketARN(t)
nsPath := GetNamespacePath(renameTestBucket, "ns")
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "u", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/udir/metadata/v1.metadata.json")})
udata := path.Join(GetTablePath(renameTestBucket, "ns", "udir"), "data")
fs.Put(nsPath, "udir", nil)
fs.Put(GetTablePath(renameTestBucket, "ns", "udir"), "data", nil)
fs.PutFile(udata, "snap1.parquet", time.Now())
before := fs.Get(nsPath, "u").Extended[ExtendedKeyMetadata]
status, resp := runHandler(t, m, fs.Client, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "u",
MetadataVersion: 2, MetadataLocation: renameLocation("ns/u2/metadata/v2.metadata.json")})
assert.Equal(t, http.StatusBadRequest, status, "%+v", resp)
assert.Equal(t, string(before), string(fs.Get(nsPath, "u").Extended[ExtendedKeyMetadata]))
// the old root stays u's: an alias over it is refused, and u's files stay
status, resp = runHandler(t, m, fs.Client, "RegisterTable", &RegisterTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "alias",
MetadataLocation: renameLocation("ns/udir/metadata/v1.metadata.json")})
if status == http.StatusOK {
runHandler(t, m, fs.Client, "DeleteTable", &DeleteTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "alias"})
}
assert.Equal(t, http.StatusConflict, status, "an alias over u's root: %+v", resp)
assert.NotNil(t, fs.Get(udata, "snap1.parquet"), "u's earlier snapshot files")
// positive control: an update under the root u has works
requireOK(t, m, fs, "UpdateTable", &UpdateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "u",
MetadataVersion: 2, MetadataLocation: renameLocation("ns/udir/metadata/v2.metadata.json")})
}