iceberg: a transaction's rollback never overwrites a later write (#13162)

* iceberg: a transaction's rollback never overwrites a later write

CommitTransaction rolls an already flipped table back with an
UpdateTable that names no version token: a commit that landed on the
table after the flip is overwritten, and the transaction's metadata file,
which that commit may build on, is deleted with it. A table that had no
metadata location before the transaction (created without one, never
committed) is not put back at all (an update leaves an empty location as
it is), yet its restore is reported done and the file it still points at
is deleted: the table then fails every load. And when the failing flip
lost a version race, the client was answered 409 CommitFailedException
even though a table left unrestored kept the transaction's change: a
client that refreshes and retries applies it twice.

- The flip records the version token it wrote, and the restore is
  conditional on it (it fails, and the file is kept, when anything wrote
  since).
- A table that had no metadata location before the transaction is
  reported unrestored, so it keeps the transaction's metadata and file.
- When any table is left unrestored the answer is 500
  CommitStateUnknownException; a full rollback still answers 409.

Tests: TestARolledBackTransactionNeverOverwritesALaterWrite (a write
before the rollback and one during the restore's write are both kept;
the file stays while referenced) and
TestARolledBackTransactionKeepsTheFileOfATableItCannotRestore (the table
still loads; the flip fails with a version race and the answer is 500).
The test filer (memFiler in iceberg_create_view_test.go) now answers a
lookup with a copy and refuses a conditional UpdateEntry whose
ExpectedExtended no longer holds, as the filer does; without it no
conditional write could fail in these tests. Red with the restore
unconditional, with the no-location table restored, and with 409 for an
unrestored table.

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

* iceberg: the failing-flip test filer fails only record writes

A storage marker written on a table's own directory carries the record
it read unchanged; failing or counting it moved the injected failure
and the concurrent write off the flip and the restore.

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>
This commit is contained in:
authored and GitHub committed 2026-11-30 11:31:38 -08:00
1 parent 8f4663f516
commit 4cda7ca0a4
3 files changed
+146 -8

No files matched your search

+23 -2
View File
@@ -46,6 +46,7 @@ type preparedTableCommit struct {
prevMetadataLoc string
prevMetadataVersion int
prevMetadata *s3tables.TableMetadata
flippedVersionToken string
}
// handleCommitTransaction commits changes to multiple tables in one request.
@@ -104,6 +105,14 @@ func (s *Server) handleCommitTransaction(w http.ResponseWriter, r *http.Request)
if err := s.flipTablePointer(r.Context(), bucketARN, identityName, pc); err != nil {
rolledBack := s.rollbackTablePointers(r.Context(), bucketARN, identityName, prepared[:i])
s.cleanupPreparedMetadata(r.Context(), prepared, cleanupSafeMetadata(prepared, i, rolledBack))
// 409 would have the client apply a change a table kept once more.
for _, restored := range rolledBack {
if !restored {
writeError(w, http.StatusInternalServerError, "CommitStateUnknownException",
"the transaction failed after some of its tables were committed, and not all of them could be rolled back: "+err.Error())
return
}
}
if isS3TablesConflict(err) {
writeError(w, http.StatusConflict, "CommitFailedException", "Version token mismatch")
return
@@ -318,10 +327,15 @@ func (s *Server) flipTablePointer(ctx context.Context, bucketARN, identityName s
MetadataLocation: pc.newMetadataLoc,
}
fitUpdateTableRequest(updateReq)
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var updateResp s3tables.UpdateTableResponse
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(ctx, mgrClient, "UpdateTable", updateReq, nil, identityName)
return s.tablesManager.Execute(ctx, mgrClient, "UpdateTable", updateReq, &updateResp, identityName)
})
if err == nil {
pc.flippedVersionToken = updateResp.VersionToken
}
return err
}
// rollbackTablePointers restores already-flipped tables to their full prior
@@ -334,6 +348,12 @@ func (s *Server) rollbackTablePointers(ctx context.Context, bucketARN, identityN
restored := make([]bool, len(flipped))
for i := range flipped {
pc := &flipped[i]
// An update cannot clear a metadata location, so such a table keeps
// the transaction's metadata and file.
if pc.prevMetadataLoc == "" || pc.flippedVersionToken == "" {
glog.Errorf("Iceberg: CommitTransaction cannot roll back %s: it had no metadata location before the transaction", pc.tableName)
continue
}
updateReq := buildTableRestoreRequest(bucketARN, pc)
fitUpdateTableRequest(updateReq)
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
@@ -362,6 +382,7 @@ func buildTableRestoreRequest(bucketARN string, pc *preparedTableCommit) *s3tabl
Metadata: cloneTableMetadata(pc.prevMetadata),
MetadataVersion: pc.prevMetadataVersion,
MetadataLocation: pc.prevMetadataLoc,
VersionToken: pc.flippedVersionToken,
}
}
@@ -23,6 +23,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// memFiler is a minimal in-memory SeaweedFilerClient backing the view handlers
@@ -59,7 +60,7 @@ func (m *memFiler) LookupDirectoryEntry(_ context.Context, in *filer_pb.LookupDi
if !ok {
return nil, filer_pb.ErrNotFound
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: entry}, nil
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
}
func (m *memFiler) CreateEntry(_ context.Context, in *filer_pb.CreateEntryRequest, _ ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
@@ -91,6 +92,13 @@ func (m *memFiler) DeleteEntry(_ context.Context, in *filer_pb.DeleteEntryReques
}
func (m *memFiler) UpdateEntry(_ context.Context, in *filer_pb.UpdateEntryRequest, _ ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
if entry, ok := m.entries[path.Join(in.Directory, in.Entry.Name)]; ok {
for key, want := range in.ExpectedExtended {
if string(entry.Extended[key]) != string(want) {
return nil, status.Errorf(codes.FailedPrecondition, "%s: %s changed", path.Join(in.Directory, in.Entry.Name), key)
}
}
}
m.entries[path.Join(in.Directory, in.Entry.Name)] = in.Entry
return &filer_pb.UpdateEntryResponse{}, nil
}
@@ -1,6 +1,7 @@
package iceberg
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -17,6 +18,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// registeredMetadata is a table's metadata.json with a schema and a snapshot,
@@ -360,12 +363,14 @@ func TestRegisterRefusesOversizedRemoteFilesAndNestedLocations(t *testing.T) {
}
// failingFlipFiler fails the catalog update of one table: the pointer flip of
// that table in a transaction.
// that table in a transaction. Writes that leave a record's metadata as it is,
// such as a storage marker on the record's own directory, pass.
type failingFlipFiler struct {
*memFiler
failPath string
// onFail runs as the failing flip is refused; beforeUpdate before every
// other update: each can land a concurrent write
failErr error
// onFail runs as the failing flip is refused, beforeUpdate before every
// other record write: each can land a concurrent write
onFail func()
beforeUpdate func(p string, conditional bool)
}
@@ -375,14 +380,21 @@ func (m *failingFlipFiler) WithFilerClient(_ bool, fn func(client filer_pb.Seawe
}
func (m *failingFlipFiler) UpdateEntry(ctx context.Context, in *filer_pb.UpdateEntryRequest, opts ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
if path.Join(in.Directory, in.Entry.Name) == m.failPath {
p := path.Join(in.Directory, in.Entry.Name)
if stored, ok := m.entries[p]; ok && bytes.Equal(stored.Extended[s3tables.ExtendedKeyMetadata], in.Entry.Extended[s3tables.ExtendedKeyMetadata]) {
return m.memFiler.UpdateEntry(ctx, in, opts...)
}
if p == m.failPath {
if m.onFail != nil {
m.onFail()
}
if m.failErr != nil {
return nil, m.failErr
}
return nil, errors.New("injected flip failure")
}
if m.beforeUpdate != nil {
m.beforeUpdate(path.Join(in.Directory, in.Entry.Name), len(in.ExpectedExtended) > 0)
m.beforeUpdate(p, len(in.ExpectedExtended) > 0)
}
return m.memFiler.UpdateEntry(ctx, in, opts...)
}
@@ -667,3 +679,100 @@ func TestInlineMetadataOverTheLimit(t *testing.T) {
t.Fatalf("inline content at the limit: %v", err)
}
}
// A rollback restores a table only while it is the one the flip left; a later
// write is kept, and so is the transaction's file.
func TestARolledBackTransactionNeverOverwritesALaterWrite(t *testing.T) {
for _, when := range []string{"before the rollback", "during the restore's write"} {
t.Run(when, func(t *testing.T) {
fc := &failingFlipFiler{memFiler: newMemFiler(), failPath: s3tables.GetTablePath("warehouse", "finance", "b")}
seedNamespace(fc.memFiler, "warehouse", "finance", "alice")
seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), false)
seedOwnedTable(fc.memFiler, "warehouse", "finance", "b", "alice")
s := NewServer(fc, nil)
registerLocationOnly(t, fc.memFiler, s)
ordersPath := s3tables.GetTablePath("warehouse", "finance", "orders")
concurrentWrite := func() {
var record map[string]any
_ = json.Unmarshal(fc.entries[ordersPath].Extended[s3tables.ExtendedKeyMetadata], &record)
record["versionToken"] = "a-later-write"
data, _ := json.Marshal(record)
fc.entries[ordersPath].Extended[s3tables.ExtendedKeyMetadata] = data
}
if when == "before the rollback" {
fc.onFail = concurrentWrite
} else {
conditional := 0
fc.beforeUpdate = func(p string, isConditional bool) {
if p == ordersPath && isConditional {
if conditional++; conditional == 2 { // the flip's, then the restore's
concurrentWrite()
}
}
}
}
body := `{"table-changes":[` +
`{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]},` +
`{"identifier":{"namespace":["finance"],"name":"b"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"})
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
w := httptest.NewRecorder()
s.handleCommitTransaction(w, r)
if w.Code < 400 {
t.Fatalf("transaction with a failing flip: status %d, want a failure", w.Code)
}
if !strings.Contains(string(fc.entries[ordersPath].Extended[s3tables.ExtendedKeyMetadata]), "a-later-write") {
t.Error("the rollback overwrote a write made after the flip")
}
location, _ := storedTableEntry(t, fc.memFiler, "orders")
if _, ok := fc.entries[path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(location))]; !ok || location == registeredLocation {
t.Errorf("orders points at %s: the transaction's file must stay while it is referenced", location)
}
})
}
}
// A table with no metadata location before the transaction keeps its change
// and file, and the answer is 500 CommitStateUnknownException, not 409.
func TestARolledBackTransactionKeepsTheFileOfATableItCannotRestore(t *testing.T) {
fc := &failingFlipFiler{memFiler: newMemFiler(), failPath: s3tables.GetTablePath("warehouse", "finance", "b"),
failErr: status.Error(codes.FailedPrecondition, "injected version race")}
seedNamespace(fc.memFiler, "warehouse", "finance", "alice")
seedOwnedTable(fc.memFiler, "warehouse", "finance", "b", "alice")
s := NewServer(fc, nil)
if err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "CreateTable",
&s3tables.CreateTableRequest{TableBucketARN: buildTableBucketARN("warehouse"), Namespace: []string{"finance"}, Name: "fresh", Format: s3tables.FormatIceberg}, nil, "alice")
}); err != nil {
t.Fatal(err)
}
body := `{"table-changes":[` +
`{"identifier":{"namespace":["finance"],"name":"fresh"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]},` +
`{"identifier":{"namespace":["finance"],"name":"b"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"})
w := httptest.NewRecorder()
s.handleCommitTransaction(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")))
if w.Code < 400 {
t.Fatalf("transaction with a failing flip: status %d, want a failure", w.Code)
}
location, _ := storedTableEntry(t, fc.memFiler, "fresh")
if location == "" {
t.Fatal("fresh has no metadata location: the transaction's change to it was not made")
}
if w.Code != http.StatusInternalServerError || !strings.Contains(w.Body.String(), "CommitStateUnknownException") {
t.Errorf("a transaction that kept a change answered %d %.200s, want 500 CommitStateUnknownException", w.Code, w.Body.String())
}
if _, ok := fc.entries["/buckets/"+strings.TrimPrefix(location, "s3://")]; !ok {
t.Errorf("fresh points at %s, which the rollback deleted", location)
}
lr := httptest.NewRequest(http.MethodGet, "/v1/warehouse/namespaces/finance/tables/fresh", nil)
lr = mux.SetURLVars(lr, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "fresh"})
lw := httptest.NewRecorder()
s.handleLoadTable(lw, lr.WithContext(s3_constants.SetIdentityNameInContext(lr.Context(), "alice")))
if lw.Code != http.StatusOK {
t.Errorf("load of fresh after the rollback: %d (%s)", lw.Code, lw.Body.String())
}
}