laskoviymishka commented on code in PR #2680:
URL: https://github.com/apache/iceberg-go/pull/2680#discussion_r4688001818


##########
table/conflict_validation.go:
##########
@@ -482,15 +491,15 @@ func newConflictContext(ctx context.Context, base, 
current Metadata, branch stri
 }
 
 // forEachEntryInSnapshot visits entries in the selected manifest content
-// whose status matches includeStatus and whose entry snapshot ID matches
+// whose status is included and whose entry snapshot ID matches
 // snap. Entry snapshot IDs provide attribution across manifest rewrites,
 // which may carry entries from an earlier snapshot in a newer manifest.
 //
 // The visitor returns early if the callback returns a non-nil error.
 func (c *conflictContext) forEachEntryInSnapshot(
        snap Snapshot,
        content iceberg.ManifestContent,
-       includeStatus func(iceberg.ManifestEntryStatus) bool,
+       includeAdded, includeDeleted bool,

Review Comment:
   The call sites pass `true, false`, `true, true` and `false, true`, which 
doesn't say which flag is which, and the filter below relies on `&&` binding 
tighter than `||`. The logic is correct. Could we parenthesize the `&&` clauses 
and name the flags at the call sites (`/* includeAdded */ true`)?



##########
table/compaction_snapshot_validation.go:
##########
@@ -0,0 +1,349 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package table
+
+import (
+       "context"
+       "errors"
+       "fmt"
+       "slices"
+
+       "github.com/apache/iceberg-go"
+       iceio "github.com/apache/iceberg-go/io"
+)
+
+type compactionPlanningSnapshots struct {
+       id      *int64
+       missing bool
+}
+
+func (s *compactionPlanningSnapshots) add(id *int64) error {
+       if id == nil {
+               s.missing = true
+
+               return nil
+       }
+       if s.id == nil {
+               snapshotID := *id
+               s.id = &snapshotID
+       } else if *s.id != *id {
+               return fmt.Errorf("%w: compaction mixes planning snapshots %d 
and %d", ErrInvalidOperation, *s.id, *id)
+       }
+
+       return nil
+}
+
+func (s compactionPlanningSnapshots) resolve(explicitID *int64) (*int64, 
error) {
+       if explicitID != nil {
+               if s.id != nil && *s.id != *explicitID {
+                       return nil, fmt.Errorf("%w: worker planning snapshot %d 
differs from validation snapshot %d",
+                               ErrInvalidOperation, *s.id, *explicitID)
+               }
+
+               return explicitID, nil
+       }
+       if s.id != nil && s.missing {
+               return nil, fmt.Errorf("%w: compaction mixes inputs with and 
without a planning snapshot ID", ErrInvalidOperation)
+       }
+
+       return s.id, nil
+}
+
+func compactionPlanningSnapshotID(groups []CompactionTaskGroup) (*int64, 
error) {
+       var snapshots compactionPlanningSnapshots
+       for _, group := range groups {
+               for _, task := range group.Tasks {
+                       if err := snapshots.add(task.PlanningSnapshotID); err 
!= nil {
+                               return nil, err
+                       }
+               }
+       }
+
+       return snapshots.resolve(nil)
+}
+
+func compactionSourceFiles(groups []CompactionTaskGroup) ([]iceberg.DataFile, 
error) {
+       var files []iceberg.DataFile
+       for _, group := range groups {
+               for _, task := range group.Tasks {
+                       if task.File == nil {
+                               return nil, fmt.Errorf("%w: compaction task has 
no data file", ErrInvalidOperation)
+                       }
+                       files = append(files, task.File)
+               }
+       }
+
+       return files, nil
+}
+
+var errRewriteSourceRemoved = fmt.Errorf("%w: rewrite source file removed", 
ErrCommitFailed)
+
+func rewriteSourceRemoved(snapshotID int64, path string) error {
+       return fmt.Errorf("%w: snapshot %d removed %q after planning", 
errRewriteSourceRemoved, snapshotID, path)
+}
+
+func rewriteSourcePaths(files []iceberg.DataFile) map[string]struct{} {
+       paths := make(map[string]struct{}, len(files))
+       for _, df := range files {
+               paths[df.FilePath()] = struct{}{}
+       }
+
+       return paths
+}
+
+func validateRewriteConflicts(cc *conflictContext, files []iceberg.DataFile) 
error {
+       if len(files) == 0 || len(cc.concurrent) == 0 {
+               return nil
+       }
+       paths := rewriteSourcePaths(files)
+       if err := cc.forEachRemovedDataFile(func(snapshotID int64, path string) 
error {
+               if _, ok := paths[path]; ok {
+                       return rewriteSourceRemoved(snapshotID, path)
+               }
+
+               return nil
+       }); err != nil {
+               return err
+       }
+
+       return validateNoNewDeletesForRewrittenFiles(cc, files)
+}
+
+var errSnapshotHistoryIncompleteForRewrite = errors.New(
+       "cannot validate compaction: history may be incomplete under REST 
snapshot-loading-mode=refs; reload with snapshot-loading-mode=all",
+)
+
+// rewriteStartSnapshotID uses the transaction's base for plans without 
provenance.
+func (t *Transaction) rewriteStartSnapshotID(planned *int64) *int64 {
+       if planned != nil {
+               return planned
+       }
+       if base := latestSnapshotForBranch(t.tbl.metadata, t.branch); base != 
nil {
+               return &base.SnapshotID
+       }
+
+       return nil
+}
+
+// validateRewriteFromSnapshot covers changes already visible when the rewrite
+// is staged. The transaction's existing validators cover subsequent changes
+// discovered during commit retries.
+func (t *Transaction) validateRewriteFromSnapshot(ctx context.Context, meta 
*MetadataBuilder, head *Snapshot, snapshotID *int64, rewrittenFiles 
[]iceberg.DataFile) error {
+       if snapshotID == nil || (head != nil && head.SnapshotID == *snapshotID) 
{
+               return nil
+       }
+       current, err := meta.Build()
+       if err != nil {
+               return err
+       }
+       fs, err := t.tbl.fsF(ctx)
+       if err != nil {
+               return err
+       }
+       cc, err := newConflictContextAt(ctx, current, t.branch, head, 
snapshotID, fs, true)
+       if errors.Is(err, ErrCommitDiverged) && t.tbl.snapshotHistoryRefsOnly 
&& head != nil {
+               _, full, loadErr := loadStagedSnapshotHistory(ctx, t.tbl, meta, 
errSnapshotHistoryIncompleteForRewrite)
+               if loadErr != nil {
+                       return loadErr
+               }
+               current, err = full.Build()
+               if err != nil {
+                       return err
+               }
+               cc, err = newConflictContextAt(ctx, current, t.branch, 
current.SnapshotByID(head.SnapshotID), snapshotID, fs, true)
+       }
+       if err != nil {
+               return err
+       }
+
+       return validateRewriteConflicts(cc, rewrittenFiles)
+}
+
+// rewriteConflictsSincePlanning records added deletes and removed data paths
+// since planning. Each validation checks only the snapshots committed since
+// the previous check, then applies accumulated changes to the current batch.
+type rewriteConflictsSincePlanning struct {
+       checkedSnapshotID *int64
+       branch            string
+       deletes           []addedDelete
+       sourcePaths       map[string]struct{}
+       removedPaths      map[string]int64
+}
+
+func (d *rewriteConflictsSincePlanning) validate(ctx context.Context, current 
*Table, fs iceio.IO, groups []CompactionTaskGroup) error {
+       if err := d.advance(ctx, current, fs); err != nil {
+               return err
+       }
+       if len(d.deletes) == 0 && len(d.removedPaths) == 0 {
+               return nil
+       }
+
+       files, err := compactionSourceFiles(groups)
+       if err != nil {
+               return err
+       }
+       for _, file := range files {
+               if snapshotID, ok := d.removedPaths[file.FilePath()]; ok {
+                       return rewriteSourceRemoved(snapshotID, file.FilePath())
+               }
+       }
+       if len(d.deletes) == 0 {
+               return nil
+       }
+       rewritten, err := newRewrittenFileSet(files)
+       if err != nil {
+               return err
+       }
+       for _, added := range d.deletes {
+               if err := rewritten.conflict(added); err != nil {
+                       return err
+               }
+       }
+
+       return nil
+}
+
+// advance records changes up to the branch head before checking a batch.
+func (d *rewriteConflictsSincePlanning) advance(ctx context.Context, current 
*Table, fs iceio.IO) error {
+       // The rewrite validator binds no filters, so case sensitivity is moot.
+       head := latestSnapshotForBranch(current.metadata, d.branch)
+       cc, err := newConflictContextAt(ctx, current.metadata, d.branch, head, 
d.checkedSnapshotID, fs, true)
+       if errors.Is(err, ErrCommitDiverged) && current.snapshotHistoryRefsOnly 
&& head != nil {
+               full, loadErr := current.loadFullSnapshotHistory(ctx, 
errSnapshotHistoryIncompleteForRewrite)
+               if loadErr != nil {
+                       return loadErr
+               }
+               cc, err = newConflictContextAt(ctx, full.metadata, d.branch, 
head, d.checkedSnapshotID, fs, true)
+       }
+       if err != nil {
+               return err
+       }
+       deletes := d.deletes
+       err = cc.forEachAddedEntry(iceberg.ManifestContentDeletes, func(snap 
Snapshot, e iceberg.ManifestEntry) error {
+               added, err := newAddedDelete(snap, e.DataFile())
+               if err != nil {
+                       return err
+               }
+               deletes = append(deletes, added)
+
+               return nil
+       })
+       if err != nil {
+               return err
+       }
+       if err := cc.forEachRemovedDataFile(func(snapshotID int64, path string) 
error {
+               if _, ok := d.sourcePaths[path]; ok {
+                       if d.removedPaths == nil {
+                               d.removedPaths = make(map[string]int64)
+                       }
+                       d.removedPaths[path] = snapshotID
+               }
+
+               return nil
+       }); err != nil {
+               return err
+       }
+       d.checkedSnapshotID, d.deletes = &head.SnapshotID, deletes
+
+       return nil
+}
+
+// commitRewrite writes manifests against the private planning transaction and
+// publishes its updates and conflict checks together if staging is still 
valid.
+func (t *Transaction) commitRewrite(ctx context.Context, base 
*MetadataBuilder, parent *Snapshot, updater *snapshotProducer, rewritesData 
bool, validator conflictValidatorFunc) (err error) {
+       planning := updater.txn
+       updates, reqs, pins, err := planning.prepareRewriteCommit(ctx, updater, 
rewritesData)
+       if err != nil {
+               return err
+       }
+       defer func() {
+               if err != nil {
+                       cleanupCtx := context.WithoutCancel(ctx)
+                       for path := range updater.written.staged {
+                               if removeErr := updater.io.Remove(cleanupCtx, 
path); removeErr != nil {
+                                       err = errors.Join(err, 
fmt.Errorf("remove unstaged rewrite manifest %s: %w", path, removeErr))
+                               }
+                       }
+                       if removeErr := updater.io.Remove(cleanupCtx, 
updater.written.stagedList); removeErr != nil {
+                               err = errors.Join(err, fmt.Errorf("remove 
unstaged rewrite manifest list: %w", removeErr))
+                       }
+               }
+       }()
+
+       t.mx.Lock()
+       defer t.mx.Unlock()
+       if err := t.checkRewriteParentLocked(parent); err != nil {
+               return err
+       }
+       if t.meta != base {

Review Comment:
   Could we add a test for this branch? 
[`TestCompactionRejectsStaleRewriteAfterWritingManifests`](https://github.com/apache/iceberg-go/blob/b9f4056bd1df453608ef8ddbe9a350fae78ee3f1/table/rewrite_data_files_test.go#L1020-L1110)
 only reaches the `transaction head changed` check. Nothing stages a change 
that leaves the head alone, such as a `SetProperties` while the manifest list 
write is blocked. Nothing checks that the manifests are removed on this path 
either. No `_test.go` file contains `changed while staging`.



##########
table/rewrite_data_files.go:
##########
@@ -469,8 +474,12 @@ func (binPackStrategy) writeOptions() []WriteRecordOption 
{ return nil }
 // here. Distributed coordinators stage worker results via
 // [ExecuteCompactionGroup] and commit them via [Transaction.NewRewrite]
 // + [RewriteFiles.ApplyResult] + [RewriteFiles.Commit] instead.
-func (t *Transaction) RewriteDataFiles(ctx context.Context, groups 
[]CompactionTaskGroup, opts RewriteDataFilesOptions) (*RewriteResult, error) {
-       if _, err := t.txnMeta(); err != nil {
+// Plan all groups from the same snapshot. Tasks from [Scan.PlanFiles] carry

Review Comment:
   Without a blank `//` line, godoc merges this into the previous paragraph.
   
   ```suggestion
   //
   // Plan all groups from the same snapshot. Tasks from [Scan.PlanFiles] carry
   ```



##########
table/table.go:
##########
@@ -180,6 +180,33 @@ type Table struct {
        labels *iceberg.Labels
 }
 
+// loadFullSnapshotHistory loads the transaction's existing metadata revision.
+// Loading a newer revision could change the parent of already staged work.
+func (base *Table) loadFullSnapshotHistory(ctx context.Context, incomplete 
error) (*Table, error) {
+       loader, ok := base.cat.(FullSnapshotHistoryLoader)
+       if !ok {
+               return nil, fmt.Errorf("%w: %w", ErrInvalidOperation, 
incomplete)
+       }
+       full, err := loader.LoadTableWithFullSnapshotHistory(ctx, 
slices.Clone(base.identifier))
+       if err != nil {
+               return nil, fmt.Errorf("%w: load full snapshot history: %w", 
ErrInvalidOperation, err)
+       }
+       if full.snapshotHistoryRefsOnly {
+               return nil, fmt.Errorf("%w: %w", ErrInvalidOperation, 
incomplete)
+       }
+       if err := validateTableUUID(base.identifier, base.metadata.TableUUID(), 
full.metadata.TableUUID()); err != nil {
+               return nil, fmt.Errorf("%w: %w", ErrInvalidOperation, err)
+       }
+       if base.metadataLocation == "" || base.metadataLocation != 
full.metadataLocation {

Review Comment:
   Could this return a retryable `ErrCommitFailed`, like the `t.meta != base` 
guard, with partial progress [counting the batch as a failed 
group](https://github.com/apache/iceberg-go/blob/b9f4056bd1df453608ef8ddbe9a350fae78ee3f1/table/rewrite_data_files.go#L879-L882)?
 On refs-only tables with two or more snapshots between planning and the 
transaction head, compaction falls back to this load, and 
[`LoadTableWithFullSnapshotHistory`](https://github.com/apache/iceberg-go/blob/b9f4056bd1df453608ef8ddbe9a350fae78ee3f1/catalog/rest/rest.go#L2053-L2061)
 always returns the latest revision, so any later commit, even an unrelated 
append, trips it.
   
   With a test catalog whose metadata location moves per commit, atomic and 
distributed compaction fail here and `PartialProgress` returns the error with 0 
completed, 0 failed; without the peer commit all three pass. `main` never loads 
full history. The current test catalogs use a [fixed 
location](https://github.com/apache/iceberg-go/blob/b9f4056bd1df453608ef8ddbe9a350fae78ee3f1/table/rewrite_files_test.go#L66-L87),
 so a test that moves it would cover this.



##########
table/rewrite_data_files.go:
##########
@@ -480,14 +489,47 @@ func (t *Transaction) RewriteDataFiles(ctx 
context.Context, groups []CompactionT
                return &RewriteResult{}, nil
        }
 
+       snapshotID, err := compactionPlanningSnapshotID(groups)
+       if err != nil {
+               return nil, err
+       }
+       snapshotID = t.rewriteStartSnapshotID(snapshotID)
+       checkedHead := t.planningSnapshot(meta)

Review Comment:
   Should these reads of the live builder happen under `t.mx`? `main` already 
reads `meta` and calls `Build()` unlocked through 
[`StagedTable()`](https://github.com/apache/iceberg-go/blob/4f5b7f8562347e88d702aa661ba19f8c96a13308/table/transaction.go#L2720-L2725);
 this PR adds `planningSnapshot(meta)` here and `meta.Build()` in 
[`validateRewriteFromSnapshot`](https://github.com/apache/iceberg-go/blob/b9f4056bd1df453608ef8ddbe9a350fae78ee3f1/table/compaction_snapshot_validation.go#L146-L153).
 A `-race` test with a goroutine calling `SetProperties` on the same 
transaction reports `Build()` racing with `clone()` on both `main` and this 
branch. An issue works too if it's out of scope.



##########
table/table.go:
##########
@@ -823,7 +850,8 @@ func (t Table) doCommit(ctx context.Context, updates 
[]Update, reqs []Requiremen
                        // just because a peer advanced the head with a
                        // non-conflicting commit.
                        load := t.cat.LoadTable
-                       if loader, ok := t.cat.(FullSnapshotHistoryLoader); ok 
&& co.replay.hasExpirationRecords() {
+                       needsHistory := co.replay.hasExpirationRecords() || 
(t.snapshotHistoryRefsOnly && len(co.validators) > 0)

Review Comment:
   Does every validated commit need this, or only the rewrite? On refs-only 
tables, retrying an overwrite, delete, `RowDelta` or dynamic overwrite now 
fetches full snapshot history, where 
[`main`](https://github.com/apache/iceberg-go/blob/4f5b7f8562347e88d702aa661ba19f8c96a13308/table/table.go#L825-L828)
 did that only with expiration records. If only rewrites need it, could we gate 
on them? Otherwise a line in `releases.md` would tell REST users about the 
extra load.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to