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

856 lines
36 KiB
Go

package iceberg
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"google.golang.org/grpc"
)
// A table created without a location gets a directory named after it and its
// UUID, so it never lands on files another table left under its name.
func TestCreateTableWithoutLocationUsesItsOwnDirectory(t *testing.T) {
const bucket = "warehouse"
for _, body := range []string{`{"name":"orders"}`, `{"name":"orders","location":"s3://warehouse"}`} {
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
if w.Code != http.StatusOK {
t.Fatalf("%s: status = %d (body: %s)", body, w.Code, w.Body.String())
}
var created struct {
MetadataLocation string `json:"metadata-location"`
Metadata struct {
Location string `json:"location"`
TableUUID string `json:"table-uuid"`
} `json:"metadata"`
}
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
t.Fatalf("decode: %v", err)
}
want := "s3://warehouse/finance/orders-" + created.Metadata.TableUUID
if created.Metadata.TableUUID == "" || created.Metadata.Location != want {
t.Errorf("%s: location = %q, want %q", body, created.Metadata.Location, want)
}
if !strings.HasPrefix(created.MetadataLocation, want+"/metadata/") {
t.Errorf("%s: metadata-location = %q, want one under %s", body, created.MetadataLocation, want)
}
}
}
// A REST create may name a location only while nothing is stored under it and
// no live stage holds it; a view always gets the location the catalog assigns.
func TestARESTCreateTakesOnlyAFreshLocation(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := &writeLogFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
used := path.Join(s3tables.TablesPath, bucket, "finance", "used")
fc.entries[used] = &filer_pb.Entry{Name: "used", IsDirectory: true}
fc.entries[path.Join(used, "data")] = &filer_pb.Entry{Name: "data", IsDirectory: true}
s := NewServer(fc, nil)
create := func(body string) (int, string) {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
var res struct {
Metadata struct {
Location string `json:"location"`
} `json:"metadata"`
}
_ = json.Unmarshal(w.Body.Bytes(), &res)
return w.Code, res.Metadata.Location
}
if code, location := create(`{"name":"fresh","location":"s3://warehouse/finance/fresh"}`); code != http.StatusOK || location != "s3://warehouse/finance/fresh" {
t.Errorf("create at a fresh location: %d at %q, want 200 there", code, location)
}
_, staged := create(`{"name":"orders","stage-create":true}`)
if staged == "" {
t.Fatal("stage-create returned no location")
}
for name, c := range map[string]struct {
body string
want int
}{
"location with files": {`{"name":"mine1","location":"s3://warehouse/finance/used"}`, http.StatusBadRequest},
"another caller's stage": {`{"name":"mine2","location":"` + staged + `"}`, http.StatusConflict},
"stage over a stage": {`{"name":"mine3","location":"` + staged + `","stage-create":true}`, http.StatusConflict},
} {
fc.created = nil
if code, _ := create(c.body); code != c.want {
t.Errorf("%s: status = %d, want %d", name, code, c.want)
}
if len(fc.created) != 0 {
t.Errorf("%s: a refused create wrote %v", name, fc.created)
}
}
w := httptest.NewRecorder()
s.handleCreateView(w, withActions(createViewAt(t, "v", "s3://warehouse/finance/used"), "alice", creatorActions...))
var view struct {
Metadata struct {
Location string `json:"location"`
} `json:"metadata"`
}
_ = json.Unmarshal(w.Body.Bytes(), &view)
if w.Code != http.StatusOK || !strings.HasPrefix(view.Metadata.Location, "s3://warehouse/finance/v-") {
t.Errorf("create view naming a location: %d at %q, want 200 at an assigned location", w.Code, view.Metadata.Location)
}
}
func TestTableLocation(t *testing.T) {
for name, tc := range map[string]struct {
resp s3tables.GetTableResponse
want string
}{
"metadata": {s3tables.GetTableResponse{MetadataLocation: "s3://b/ns/t-1/metadata/v2.metadata.json", WarehouseLocation: "s3://b/ns/t-0"}, "s3://b/ns/t-1"},
"warehouse": {s3tables.GetTableResponse{WarehouseLocation: "s3://b/ns/t-0/"}, "s3://b/ns/t-0"},
"legacy": {s3tables.GetTableResponse{}, "s3://b/ns/t"},
} {
if got := tableLocation(tc.resp, "b", []string{"ns"}, "t"); got != tc.want {
t.Errorf("%s: tableLocation = %q, want %q", name, got, tc.want)
}
}
}
// Two creates can both find a name free. The one the catalog registers second
// is a conflict and leaves nothing in the directory the server picked for it.
func TestCreateTableThatLosesTheRaceIsConflict(t *testing.T) {
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
first := httptest.NewRecorder()
raceAtSecondLookup(fc, s3tables.GetTablePath(bucket, "finance", "orders"), func() {
s.handleCreateTable(first, newCreateTableRequest(t, bucket, "finance", `{"name":"orders"}`, "alice"))
})
second := httptest.NewRecorder()
s.handleCreateTable(second, newCreateTableRequest(t, bucket, "finance", `{"name":"orders"}`, "alice"))
won := decodeCreated(t, first)
if second.Code != http.StatusConflict {
t.Fatalf("losing create = %d (%s), want 409", second.Code, second.Body.String())
}
wonDir := path.Join(s3tables.TablesPath, strings.TrimPrefix(won.Metadata.Location, "s3://"))
for p := range fc.entries {
if strings.HasPrefix(p, s3tables.GetTablePath(bucket, "finance", "orders-")) && p != wonDir && !strings.HasPrefix(p, wonDir+"/") {
t.Errorf("losing create left %s", p)
}
}
}
// Two commits of one staged table pick the same metadata file name. The one
// that finds the table registered, and moved on to newer metadata, fails
// without removing the file the registered table's history still names.
func TestStagedCommitThatLosesTheRaceFails(t *testing.T) {
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
tableUUID := uuid.New()
location := "s3://" + bucket + "/finance/orders-" + tableUUID.String()
base, err := newTableMetadata(tableUUID, location, nil, nil, nil, nil)
if err != nil {
t.Fatal(err)
}
input := createOnCommitInput{
bucketARN: buildTableBucketARN(bucket),
markerBucket: bucket,
namespace: []string{"finance"},
tableName: "orders",
identityName: "alice",
location: location,
tableUUID: tableUUID,
baseMetadata: base,
}
if _, reqErr := s.finalizeCreateOnCommit(context.Background(), input); reqErr != nil {
t.Fatalf("first commit: %+v", reqErr)
}
ctx := context.Background()
mgr := s3tables.NewManagerClient(fc)
var registered s3tables.GetTableResponse
if err := s.tablesManager.Execute(ctx, mgr, "GetTable", &s3tables.GetTableRequest{TableBucketARN: input.bucketARN, Namespace: input.namespace, Name: "orders"}, &registered, "alice"); err != nil {
t.Fatal(err)
}
if err := s.tablesManager.Execute(ctx, mgr, "UpdateTable", &s3tables.UpdateTableRequest{
TableBucketARN: input.bucketARN, Namespace: input.namespace, Name: "orders", VersionToken: registered.VersionToken,
MetadataVersion: 2, MetadataLocation: location + "/metadata/v2.metadata.json",
}, nil, "alice"); err != nil {
t.Fatal(err)
}
_, reqErr := s.finalizeCreateOnCommit(ctx, input)
if reqErr == nil || reqErr.status != http.StatusConflict {
t.Fatalf("second commit error = %+v, want a conflict", reqErr)
}
published := path.Join(s3tables.TablesPath, strings.TrimPrefix(location, "s3://"), "metadata", "v1.metadata.json")
if _, ok := fc.entries[published]; !ok {
t.Errorf("losing commit removed %s", published)
}
}
// Two clients can stage the same name, each at a location of its own. A commit
// lands at the location of its own stage, never at the location of another
// stage, even once its own marker is gone.
func TestStagedCommitKeepsItsOwnLocation(t *testing.T) {
const bucket = "warehouse"
for _, ownMarkerGone := range []bool{false, true} {
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
stage := func() createdResult {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"orders","stage-create":true}`, "alice"))
return decodeCreated(t, w)
}
first, second := stage(), stage()
if ownMarkerGone {
markerDir := stageCreateMarkerDir(bucket, []string{"finance"}, "orders")
for p, entry := range fc.entries {
if path.Dir(p) == markerDir && strings.Contains(string(entry.Content), first.Metadata.TableUUID) {
delete(fc.entries, p)
}
}
}
body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + first.Metadata.TableUUID + `"}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/orders", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "orders"})
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
w := httptest.NewRecorder()
s.handleUpdateTable(w, r)
committed := decodeCreated(t, w)
if strings.HasPrefix(committed.MetadataLocation, second.Metadata.Location+"/") {
t.Errorf("own marker gone %v: commit landed at the other stage's %s", ownMarkerGone, committed.MetadataLocation)
}
if !ownMarkerGone && (!strings.HasPrefix(committed.MetadataLocation, first.Metadata.Location+"/metadata/") || committed.Metadata.Location != first.Metadata.Location) {
t.Errorf("commit landed at %s (location %s), want under %s", committed.MetadataLocation, committed.Metadata.Location, first.Metadata.Location)
}
}
}
type createdResult struct {
MetadataLocation string `json:"metadata-location"`
Metadata struct {
Location string `json:"location"`
TableUUID string `json:"table-uuid"`
ViewUUID string `json:"view-uuid"`
} `json:"metadata"`
}
func decodeCreated(t *testing.T, w *httptest.ResponseRecorder) createdResult {
t.Helper()
if w.Code != http.StatusOK {
t.Fatalf("status = %d (body: %s)", w.Code, w.Body.String())
}
var created createdResult
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
t.Fatalf("decode: %v", err)
}
return created
}
// raceAtSecondLookup runs create at the second lookup of record: after the
// handler found the name free, as the catalog looks at it again.
func raceAtSecondLookup(fc *memFiler, record string, create func()) {
seen := 0
fc.onLookup = func(p string) {
if p != record {
return
}
seen++
if seen == 2 {
fc.onLookup = nil
create()
}
}
}
// A create commit's metadata names the location the catalog assigned it: a
// set-location elsewhere would have the table's files claimed at one location
// and written at another, and is refused with 400.
func TestACreateCommitCannotSetAnotherLocation(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
fc := newMemFiler()
seedNamespace(fc, "warehouse", "finance", "alice")
s := NewServer(fc, nil)
commit := func(name, updates string) (int, string) {
r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/"+name,
strings.NewReader(`{"requirements":[{"type":"assert-create"}],"updates":[`+updates+`]}`))
r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": name})
w := httptest.NewRecorder()
s.handleUpdateTable(w, withActions(r, "alice", "s3tables:CreateTable", "s3tables:UpdateTable", "s3tables:GetTable"))
return w.Code, w.Body.String()
}
if code, body := commit("moved", `{"action":"set-location","location":"s3://warehouse/finance/elsewhere"}`); code != http.StatusBadRequest {
t.Errorf("create commit with a set-location elsewhere: %d (%.200s), want 400", code, body)
}
if _, ok := fc.entries[s3tables.GetTablePath("warehouse", "finance", "moved")]; ok {
t.Error("a refused create commit left a catalog record")
}
// positive control: the same create commit without it
if code, body := commit("kept", ""); code != http.StatusOK {
t.Errorf("create commit: %d (%.200s), want 200", code, body)
}
}
// A create commit picks up a stage only by the UUID that stage assigned: a
// commit without assign-uuid, or with another UUID, is placed at a fresh
// location of its own, never at a location another caller staged (and holds
// write credentials for). The stager's own commit, carrying the staged UUID
// as PyIceberg and Java send it, still lands on its stage.
func TestACreateCommitTakesOnlyItsOwnStage(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
fc := newMemFiler()
seedNamespace(fc, "warehouse", "finance", "alice")
s := NewServer(fc, nil)
stage := func(name string) (location, tableUUID string) {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, "warehouse", "finance", `{"name":"`+name+`","stage-create":true}`, "alice"))
if w.Code != http.StatusOK {
t.Fatalf("stage %s: %d (%.200s)", name, w.Code, w.Body.String())
}
var res struct {
Metadata struct {
Location string `json:"location"`
TableUUID string `json:"table-uuid"`
} `json:"metadata"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil || res.Metadata.Location == "" {
t.Fatalf("stage %s: no location in %.200s (%v)", name, w.Body.String(), err)
}
return strings.TrimSuffix(res.Metadata.Location, "/"), res.Metadata.TableUUID
}
commit := func(caller, name, updates string) (int, string) {
r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/"+name,
strings.NewReader(`{"requirements":[{"type":"assert-create"}],"updates":[`+updates+`]}`))
r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": name})
w := httptest.NewRecorder()
s.handleUpdateTable(w, withActions(r, caller, "s3tables:CreateTable", "s3tables:UpdateTable", "s3tables:GetTable"))
var res struct {
MetadataLocation string `json:"metadata-location"`
}
_ = json.Unmarshal(w.Body.Bytes(), &res)
return w.Code, res.MetadataLocation
}
staged, _ := stage("orders")
code, got := commit("bob", "orders", "")
if code != http.StatusOK {
t.Fatalf("bob's create commit: %d, want 200", code)
}
if strings.HasPrefix(got, staged+"/") {
t.Errorf("bob's create commit landed on alice's staged location %s", got)
}
if !strings.HasPrefix(got, "s3://warehouse/finance/orders-") {
t.Errorf("a create commit without a stage is placed at %s, want a fresh finance/orders-<uuid>", got)
}
// positive control: the stager's own commit names the staged UUID
staged, stagedUUID := stage("invoices")
code, got = commit("alice", "invoices", `{"action":"assign-uuid","uuid":"`+stagedUUID+`"}`)
if code != http.StatusOK || !strings.HasPrefix(got, staged+"/") {
t.Errorf("the stager's create commit: %d at %s, want 200 at %s", code, got, staged)
}
}
// A commit or a transaction on an existing table cannot set another location.
func TestACommitCannotMoveATable(t *testing.T) {
fc := newMemFiler()
seedNamespace(fc, "warehouse", "finance", "alice")
s := NewServer(fc, nil)
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, "warehouse", "finance", `{"name":"orders"}`, "alice"))
if w.Code != http.StatusOK {
t.Fatalf("create: %d (%.200s)", w.Code, w.Body.String())
}
before := string(fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")].Extended[s3tables.ExtendedKeyMetadata])
commit := func(updates string) int {
r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/orders",
strings.NewReader(`{"requirements":[],"updates":[`+updates+`]}`))
r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"})
w := httptest.NewRecorder()
s.handleUpdateTable(w, withActions(r, "alice", "s3tables:UpdateTable", "s3tables:GetTable"))
return w.Code
}
moveTo := `{"action":"set-location","location":"s3://warehouse/finance/elsewhere"}`
if code := commit(moveTo); code != http.StatusBadRequest {
t.Errorf("commit with set-location elsewhere: %d, want 400", code)
}
tr := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader(
`{"table-changes":[{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":[],"updates":[`+moveTo+`]}]}`))
tr = mux.SetURLVars(tr, map[string]string{"prefix": "warehouse"})
tw := httptest.NewRecorder()
s.handleCommitTransaction(tw, withActions(tr, "alice", "s3tables:UpdateTable", "s3tables:GetTable"))
if tw.Code != http.StatusBadRequest {
t.Errorf("transaction with set-location elsewhere: %d (%.200s), want 400", tw.Code, tw.Body.String())
}
if after := string(fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")].Extended[s3tables.ExtendedKeyMetadata]); after != before {
t.Error("a refused move changed the table")
}
if code := commit(`{"action":"set-properties","updates":{"k":"v"}}`); code != http.StatusOK {
t.Errorf("plain commit: %d, want 200", code)
}
}
// listingCapFiler answers a listing that names no limit with a few entries,
// as a filer's dirListLimit does.
type listingCapFiler struct{ *memFiler }
func (f *listingCapFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
return fn(f)
}
func (f *listingCapFiler) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) {
if in.Limit == 0 {
in = &filer_pb.ListEntriesRequest{Directory: in.Directory, Prefix: in.Prefix, StartFromFileName: in.StartFromFileName, InclusiveStartFrom: in.InclusiveStartFrom, Limit: 3}
}
return f.memFiler.ListEntries(ctx, in, opts...)
}
func TestAFreshLocationCheckReadsEveryStage(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := &listingCapFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
markers := seedStageDirs(fc.memFiler, bucket, "finance")
for i := 0; i <= stageListPageSize; i++ {
name := fmt.Sprintf("t%05d", i)
fc.seed(path.Join(markers, name), &filer_pb.Entry{Name: name, IsDirectory: true})
}
live, _ := json.Marshal(stageCreateMarker{
Location: "s3://warehouse/finance/held",
ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano),
})
fc.seed(path.Join(markers, fmt.Sprintf("t%05d", stageListPageSize), "x.json"), &filer_pb.Entry{Name: "x.json", Content: live})
w := httptest.NewRecorder()
NewServer(fc, nil).handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"mine","location":"s3://warehouse/finance/held"}`, "alice"))
if w.Code != http.StatusConflict {
t.Fatalf("create at a location a stage past the first page holds: %d %s, want 409", w.Code, w.Body.String())
}
}
// seedStageDirs adds the directories a stage-create marker of namespace sits
// under and returns the namespace's marker directory.
func seedStageDirs(fc *memFiler, bucket, namespace string) string {
staged := path.Join(s3tables.TablesPath, bucket, stageCreateMarkerDirName)
markers := path.Join(staged, stageCreateMarkerNamespaceKey([]string{namespace}))
fc.seed(staged, &filer_pb.Entry{Name: stageCreateMarkerDirName, IsDirectory: true})
fc.seed(markers, &filer_pb.Entry{Name: path.Base(markers), IsDirectory: true})
return markers
}
func TestAFreshLocationIsApartFromOtherTables(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
pending := path.Join(s3tables.TablesPath, bucket, "finance", "pending")
fc.seed(pending, &filer_pb.Entry{Name: "pending", IsDirectory: true})
fc.seed(path.Join(pending, "metadata"), &filer_pb.Entry{Name: "metadata", IsDirectory: true})
fc.seed(path.Join(pending, "metadata", "v1.metadata.json"), &filer_pb.Entry{Name: "v1.metadata.json"})
s := NewServer(fc, nil)
create := func(body string) int {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
return w.Code
}
if code := create(`{"name":"shared","location":"s3://warehouse/finance/shared","stage-create":true}`); code != http.StatusOK {
t.Fatalf("stage at a fresh location: %d", code)
}
if code := create(`{"name":"deep","location":"s3://warehouse/finance/deep/table","stage-create":true}`); code != http.StatusOK {
t.Fatalf("stage at a fresh nested location: %d", code)
}
tables := 0
for name, c := range map[string]struct {
location string
want int
}{
"under a stage": {"s3://warehouse/finance/shared/child", http.StatusConflict},
"above a stage": {"s3://warehouse/finance/deep", http.StatusConflict},
"under another table's files": {"s3://warehouse/finance/pending/child", http.StatusBadRequest},
} {
for _, stage := range []string{"false", "true"} {
tables++
if code := create(fmt.Sprintf(`{"name":"t%d","location":%q,"stage-create":%s}`, tables, c.location, stage)); code != c.want {
t.Errorf("%s (stage %s): status = %d, want %d", name, stage, code, c.want)
}
}
}
if code := create(`{"name":"sibling","location":"s3://warehouse/finance/shared2"}`); code != http.StatusOK {
t.Errorf("create beside a stage: %d, want 200", code)
}
}
// claimRaceFiler runs onCreate once, right after the first write it matches.
type claimRaceFiler struct {
*memFiler
onCreate func(p string) bool
}
func (f *claimRaceFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
return fn(f)
}
func (f *claimRaceFiler) CreateEntry(ctx context.Context, in *filer_pb.CreateEntryRequest, opts ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
resp, err := f.memFiler.CreateEntry(ctx, in, opts...)
if err == nil && f.onCreate != nil && f.onCreate(path.Join(in.Directory, in.Entry.Name)) {
f.onCreate = nil
}
return resp, err
}
func TestARacingCreateBacksOutOfAnOverlappingLocation(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
markers := path.Join(s3tables.TablesPath, bucket, stageCreateMarkerDirName, stageCreateMarkerNamespaceKey([]string{"finance"}))
otherStage := func(fc *claimRaceFiler, location string) {
live, _ := json.Marshal(stageCreateMarker{
TableUUID: uuid.NewString(),
Location: location,
ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano),
})
seedStageDirs(fc.memFiler, bucket, "finance")
fc.seed(path.Join(markers, "other"), &filer_pb.Entry{Name: "other", IsDirectory: true})
fc.seed(path.Join(markers, "other", "o.json"), &filer_pb.Entry{Name: "o.json", Content: live})
}
cases := []struct {
name, body string
ownWrite string
want int
race func(fc *claimRaceFiler)
}{
{"stage after a stage", `{"name":"a","location":"s3://warehouse/finance/shared","stage-create":true}`, path.Join(markers, "a"), http.StatusConflict,
func(fc *claimRaceFiler) { otherStage(fc, "s3://warehouse/finance/shared/child") }},
{"create after a stage", `{"name":"a","location":"s3://warehouse/finance/shared"}`, path.Join(s3tables.TablesPath, bucket, "finance/shared/metadata"), http.StatusConflict,
func(fc *claimRaceFiler) { otherStage(fc, "s3://warehouse/finance/shared") }},
{"stage after a native create", `{"name":"a","location":"s3://warehouse/finance/lance1/data","stage-create":true}`, path.Join(markers, "a"), http.StatusConflict,
func(fc *claimRaceFiler) {
fc.seed(path.Join(s3tables.TablesPath, bucket, "finance/lance1"), &filer_pb.Entry{Name: "lance1", IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: []byte(`{"format":"LANCE"}`)}})
}},
{"stage after a create", `{"name":"a","location":"s3://warehouse/finance/shared/child","stage-create":true}`, path.Join(markers, "a"), http.StatusBadRequest,
func(fc *claimRaceFiler) {
dir := path.Join(s3tables.TablesPath, bucket, "finance/shared/metadata")
fc.seed(path.Dir(dir), &filer_pb.Entry{Name: "shared", IsDirectory: true})
fc.seed(dir, &filer_pb.Entry{Name: "metadata", IsDirectory: true})
fc.seed(path.Join(dir, "v1.metadata.json"), &filer_pb.Entry{Name: "v1.metadata.json"})
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fc := &claimRaceFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
var written []string
fc.onCreate = func(p string) bool {
if path.Dir(p) != tc.ownWrite || !strings.HasSuffix(p, ".json") {
return false
}
written = append(written, p)
tc.race(fc)
return true
}
w := httptest.NewRecorder()
NewServer(fc, nil).handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", tc.body, "alice"))
if w.Code != tc.want {
t.Fatalf("status = %d %s, want %d", w.Code, w.Body.String(), tc.want)
}
if len(written) != 1 {
t.Fatalf("the race never ran")
}
for p := range fc.entries {
if strings.HasPrefix(p, tc.ownWrite+"/") {
t.Errorf("a create that backed out left %s", p)
}
}
})
}
}
// A create removes only the stages of its name that its own location covers;
// another stage keeps holding its location while its credentials are live.
func TestACreateKeepsTheStagesItDoesNotCover(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
create := func(body string) int {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
return w.Code
}
markers := func(table string) int {
n := 0
for p := range fc.entries {
if path.Dir(p) == stageCreateMarkerDir(bucket, []string{"finance"}, table) && strings.HasSuffix(p, ".json") {
n++
}
}
return n
}
if code := create(`{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusOK {
t.Fatalf("stage: %d", code)
}
if code := create(`{"name":"t","location":"s3://warehouse/finance/y"}`); code != http.StatusOK {
t.Fatalf("create of the staged name elsewhere: %d", code)
}
if markers("t") != 1 {
t.Errorf("the create removed a stage it does not cover")
}
if code := create(`{"name":"u","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusConflict {
t.Errorf("stage at the location of a live stage whose name was taken: %d, want 409", code)
}
stage := func() createdResult {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"v","stage-create":true}`, "alice"))
return decodeCreated(t, w)
}
first, second := stage(), stage()
body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + first.Metadata.TableUUID + `"}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/v", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "v"})
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
w := httptest.NewRecorder()
s.handleUpdateTable(w, r)
decodeCreated(t, w)
if markers("v") != 1 {
t.Fatalf("a commit left %d stages of its name, want only the other one", markers("v"))
}
if code := create(`{"name":"w","location":"` + second.Metadata.Location + `","stage-create":true}`); code != http.StatusConflict {
t.Errorf("stage at the location of the stage a commit did not take: %d, want 409", code)
}
}
func TestAnAssignedStageBacksOutOfARacingStage(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := &claimRaceFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
s := NewServer(fc, nil)
create := func(body string) int {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
return w.Code
}
if code := create(`{"name":"a","stage-create":true}`); code != http.StatusOK {
t.Fatalf("stage at an assigned location: %d", code)
}
if code := create(`{"name":"b","stage-create":true}`); code != http.StatusOK {
t.Fatalf("second stage at an assigned location: %d", code)
}
t.Setenv("ICEBERG_WAREHOUSE", "s3://warehouse/finance/base")
markers := seedStageDirs(fc.memFiler, bucket, "finance")
raced := false
fc.onCreate = func(p string) bool {
if path.Dir(p) != path.Join(markers, "orders") {
return false
}
live, _ := json.Marshal(stageCreateMarker{
TableUUID: uuid.NewString(),
Location: "s3://warehouse/finance/base",
ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano),
})
fc.seed(path.Join(markers, "outer"), &filer_pb.Entry{Name: "outer", IsDirectory: true})
fc.seed(path.Join(markers, "outer", "o.json"), &filer_pb.Entry{Name: "o.json", Content: live})
raced = true
return true
}
if code := create(`{"name":"orders","stage-create":true}`); code != http.StatusConflict {
t.Errorf("stage assigned under a racing stage: %d, want 409", code)
}
if !raced {
t.Fatal("the race never ran")
}
for p := range fc.entries {
if strings.HasPrefix(p, path.Join(markers, "orders")+"/") {
t.Errorf("a stage that backed out left %s", p)
}
}
}
func TestAStageHoldsItsLocationWhileItsCredentialsLast(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
s.s3Endpoint = "http://s3.example:8333"
expiry := time.Now().Add(stageCreateMarkerTTL + 96*time.Hour).Truncate(time.Millisecond)
s.SetCredentialVendor(&stubVendor{credentials: &VendedCredentials{AccessKeyID: "ASIA", SecretAccessKey: "s", SessionToken: "t", Expiration: expiry}})
r := newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`, "alice")
r.Header.Set(accessDelegationHeader, "vended-credentials")
w := httptest.NewRecorder()
s.handleCreateTable(w, r)
decodeCreated(t, w)
found := false
for p, e := range fc.entries {
if path.Dir(p) != stageCreateMarkerDir(bucket, []string{"finance"}, "t") || !strings.HasSuffix(p, ".json") {
continue
}
var marker stageCreateMarker
if err := json.Unmarshal(e.Content, &marker); err != nil {
t.Fatal(err)
}
expiresAt, err := time.Parse(time.RFC3339Nano, marker.ExpiresAt)
if err != nil {
t.Fatal(err)
}
if expiresAt.Before(expiry) {
t.Errorf("stage marker expires at %v, before its credentials at %v", expiresAt, expiry)
}
found = true
}
if !found {
t.Fatal("no stage marker")
}
}
func TestACreateDuringAStageLeavesItsClaim(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := &claimRaceFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
s := NewServer(fc, nil)
create := func(body string) int {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
return w.Code
}
raced := false
fc.onCreate = func(p string) bool {
if raced || path.Dir(p) != stageCreateMarkerDir(bucket, []string{"finance"}, "t") || !strings.HasSuffix(p, ".json") {
return false
}
raced = true
if code := create(`{"name":"t","location":"s3://warehouse/finance/y"}`); code != http.StatusOK {
t.Errorf("create of the staged name elsewhere: %d", code)
}
return true
}
if code := create(`{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusOK {
t.Fatalf("stage: %d", code)
}
if !raced {
t.Fatal("the race never ran")
}
if code := create(`{"name":"u","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusConflict {
t.Errorf("stage at the location of a live stage: %d, want 409", code)
}
}
func TestAStageBacksOutOfASameNameCreateOverItsLocation(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := &claimRaceFiler{memFiler: newMemFiler()}
seedNamespace(fc.memFiler, bucket, "finance", "alice")
s := NewServer(fc, nil)
raced := false
fc.onCreate = func(p string) bool {
if raced || !strings.Contains(p, "/"+stageCreateMarkerDirName+"/") || !strings.HasSuffix(p, "/metadata/v1.metadata.json") {
return false
}
raced = true
err := s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(fc), "CreateTable", &s3tables.CreateTableRequest{
TableBucketARN: buildTableBucketARN(bucket),
Namespace: []string{"finance"},
Name: "t",
Format: s3tables.FormatLance,
}, &s3tables.CreateTableResponse{}, "alice")
if err != nil {
t.Errorf("lance create of the staged name: %v", err)
}
return true
}
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/t/data","stage-create":true}`, "alice"))
if !raced {
t.Fatal("the race never ran")
}
if w.Code != http.StatusConflict {
t.Errorf("stage under a same-name table: %d, want 409 (body: %s)", w.Code, w.Body.String())
}
markerDir := stageCreateMarkerDir(bucket, []string{"finance"}, "t")
for p := range fc.entries {
if path.Dir(p) == markerDir && strings.HasSuffix(p, ".json") {
t.Errorf("stage marker %s left behind", p)
}
}
}
// commitStage commits the stage of table that handed out uuid.
func commitStage(t *testing.T, s *Server, bucket, table, uuid string) *httptest.ResponseRecorder {
t.Helper()
body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + uuid + `"}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/"+table, strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": table})
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
w := httptest.NewRecorder()
s.handleUpdateTable(w, r)
return w
}
// Another live stage of the same name holds its own location, not the record
// path this commit writes.
func TestAStageAtItsNamePathCommitsBesideASameNameStage(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
stage := func(body string) createdResult {
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice"))
return decodeCreated(t, w)
}
first := stage(`{"name":"t","location":"s3://warehouse/finance/t","stage-create":true}`)
second := stage(`{"name":"t","stage-create":true}`)
if second.Metadata.Location == first.Metadata.Location {
t.Fatalf("both stages at %s", first.Metadata.Location)
}
committed := decodeCreated(t, commitStage(t, s, bucket, "t", first.Metadata.TableUUID))
if committed.Metadata.Location != first.Metadata.Location {
t.Errorf("commit at %s, want %s", committed.Metadata.Location, first.Metadata.Location)
}
}
// A stage whose location has a metadata segment of its own commits there.
func TestAStageUnderAMetadataDirectoryCommits(t *testing.T) {
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true")
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/metadata/t","stage-create":true}`, "alice"))
staged := decodeCreated(t, w)
committed := decodeCreated(t, commitStage(t, s, bucket, "t", staged.Metadata.TableUUID))
if committed.Metadata.Location != staged.Metadata.Location {
t.Errorf("commit at %s, want %s", committed.Metadata.Location, staged.Metadata.Location)
}
}