zeroshade commented on code in PR #2815: URL: https://github.com/apache/iceberg-go/pull/2815#discussion_r4805493861
########## table/cow_delete_prune_internal_test.go: ########## @@ -0,0 +1,146 @@ +// 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 ( + "testing" + + "github.com/apache/iceberg-go" + iceio "github.com/apache/iceberg-go/io" + "github.com/stretchr/testify/require" +) + +func morDelete(t *testing.T, tbl *Table, filter iceberg.BooleanExpression) *Table { + t.Helper() + + txn := tbl.NewTransaction() + require.NoError(t, txn.Delete(t.Context(), filter, nil)) + tbl, err := txn.Commit(t.Context()) + require.NoError(t, err) + + return tbl +} + +func dataFilesByPartition(t *testing.T, tbl *Table) map[string]iceberg.ManifestEntry { + t.Helper() + + files := make(map[string]iceberg.ManifestEntry) + for entry, err := range tbl.CurrentSnapshot().entries(t.Context(), iceio.LocalFS{}, iceberg.ManifestContentData, true) { + require.NoError(t, err) + region, _ := entry.DataFile().Partition()[1000].(string) + files[region] = entry + } + + return files +} + +func deletePartitions(t *testing.T, entries []iceberg.ManifestEntry) []string { + t.Helper() + + regions := make([]string, 0, len(entries)) + for _, entry := range entries { + region, _ := entry.DataFile().Partition()[1000].(string) + regions = append(regions, region) + } + + return regions +} + +// A copy-on-write delete reads only the delete manifests whose partitions overlap the files it removes or rewrites (#2160). +// The table is v2: on v3 the second merge-on-read delete rewrites both deletion vectors into one manifest, which +// spans both partitions and so is always read. +func TestLiveDeletesForFilesPrunesDeleteManifests(t *testing.T) { + region, id := iceberg.Reference("region"), iceberg.Reference("id") + tbl := regionTestTable(t, iceberg.Properties{PropertyFormatVersion: "2", WriteDeleteModeKey: WriteModeMergeOnRead}) + tbl = morDelete(t, tbl, iceberg.NewAnd(iceberg.EqualTo(region, "west"), iceberg.EqualTo(id, int64(3)))) + tbl = morDelete(t, tbl, iceberg.NewAnd(iceberg.EqualTo(region, "east"), iceberg.EqualTo(id, int64(2)))) + + snap := tbl.CurrentSnapshot() + manifests, err := snap.Manifests(t.Context(), iceio.LocalFS{}) + require.NoError(t, err) + var deleteManifests []iceberg.ManifestFile + for _, m := range manifests { + if m.ManifestContent() == iceberg.ManifestContentDeletes { + deleteManifests = append(deleteManifests, m) + } + } + require.Len(t, deleteManifests, 2) + + files := dataFilesByPartition(t, tbl) + east, west := files["east"].DataFile(), files["west"].DataFile() + read := func(minSeq int64, files ...iceberg.DataFile) []string { + entries, err := liveDeletesForFiles(t.Context(), iceio.LocalFS{}, snap, tbl.Metadata(), files, minSeq) + require.NoError(t, err) + + return deletePartitions(t, entries) + } + + require.Equal(t, []string{"east"}, read(0, east)) + require.Equal(t, []string{"west"}, read(0, west)) + require.ElementsMatch(t, []string{"east", "west"}, read(0, east, west)) + + // Both deletes are older than a data file with a higher sequence number, so neither can apply to it. + newest := max(deleteManifests[0].SequenceNumber(), deleteManifests[1].SequenceNumber()) + require.Empty(t, read(newest+1, east, west)) +} + +// A delete file whose spec is unpartitioned can apply to a data file in any partition, so it is always read. +func TestLiveDeletesForFilesReadsUnpartitionedDeleteManifests(t *testing.T) { + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "region", Type: iceberg.PrimitiveTypes.String, Required: true}, + ) + tbl := identityPartitionTestTable(t, schema, *iceberg.UnpartitionedSpec, + iceberg.Properties{PropertyFormatVersion: "2", WriteDeleteModeKey: WriteModeMergeOnRead}) + tbl = addIDOnlyFile(t, tbl, "unpartitioned", nil, `[{"id":1},{"id":2}]`) + tbl = morDelete(t, tbl, iceberg.EqualTo(iceberg.Reference("id"), int64(2))) + + txn := tbl.NewTransaction() + require.NoError(t, txn.UpdateSpec(true).AddIdentity("region").Commit()) + tbl, err := txn.Commit(t.Context()) + require.NoError(t, err) + tbl = addIDOnlyFile(t, tbl, "west", map[int]any{1000: "west"}, `[{"id":3}]`) + + files := dataFilesByPartition(t, tbl) + entries, err := liveDeletesForFiles(t.Context(), iceio.LocalFS{}, tbl.CurrentSnapshot(), tbl.Metadata(), + []iceberg.DataFile{files["west"].DataFile()}, 0) + require.NoError(t, err) + require.Len(t, entries, 1) + require.Equal(t, iceberg.EntryContentPosDeletes, entries[0].DataFile().ContentType()) +} + +// Pruning keeps the deletes of the rewritten partition: a copy-on-write rewrite of east still drops the row an +// earlier merge-on-read delete removed, while the delete in west keeps applying. +func TestCopyOnWriteDeleteAppliesDeletesOfRewrittenPartition(t *testing.T) { Review Comment: Could you add a v3 case where the copy-on-write delete drops a file whole rather than rewriting it? For example, after merge-on-read deletes in both regions, `Delete(region = 'east')`. Then assert that no live DV references the removed file and that west's DV survives. The code handles it (removed files go into `files`, and sequence pruning is turned off), but a dropped file losing its DV would leave a dangling DV, which the spec forbids, so it's worth pinning. ########## table/transaction_delete.go: ########## @@ -629,6 +649,137 @@ func (t *Transaction) readPlanningDeletes(ctx context.Context, fs io.IO, builtMe return planningDeletes{positional: positional, dvs: dvs, equality: equality}, nil } +// liveDeletesForFiles returns the live entries of the delete manifests of snap that can hold a delete for one +// of files. A delete file applies to a data file only when both have the same spec and partition, or the delete +// file's spec is unpartitioned (spec "Scan Planning"), so a manifest is skipped when its spec is partitioned and +// its partition summaries rule out every affected partition of that spec. Every entry of a manifest has a +// sequence number at most the manifest's, and no delete applies to a data file with a higher sequence number, +// so a manifest older than minSeq is skipped too. Entries are not filtered: the delete indexes match them to +// data files. +func liveDeletesForFiles(ctx context.Context, fs io.IO, snap *Snapshot, meta Metadata, files []iceberg.DataFile, minSeq int64) ([]iceberg.ManifestEntry, error) { + partitionsBySpec := make(map[int][]map[int]any) + for _, f := range files { + specID := int(f.SpecID()) + partitionsBySpec[specID] = append(partitionsBySpec[specID], f.Partition()) + } + + manifests, err := snap.Manifests(ctx, fs) + if err != nil { + return nil, fmt.Errorf("failed to read delete manifests: %w", err) + } + + evaluators := make(map[int]func(iceberg.ManifestFile) (bool, error)) + var liveDeletes []iceberg.ManifestEntry + for _, m := range manifests { + // A manifest with neither added nor existing files holds only DELETED entries, which are skipped below. + if m.ManifestContent() != iceberg.ManifestContentDeletes || m.SequenceNumber() < minSeq || + (!m.HasAddedFiles() && !m.HasExistingFiles()) { + continue + } + + specID := int(m.PartitionSpecID()) + spec := meta.PartitionSpecByID(specID) + if spec != nil && !spec.IsUnpartitioned() { + partitions, ok := partitionsBySpec[specID] + if !ok { + continue + } + eval, ok := evaluators[specID] + if !ok { + eval = deleteManifestEvaluator(*spec, meta.CurrentSchema(), partitions) + evaluators[specID] = eval + } + if mightMatch, err := eval(m); err == nil && !mightMatch { + continue + } + } + + // Skip DELETED entries: a replaced DV stays behind as one, and merging it + // into a new DV would bring back deleted rows. See #1372. + for entry, err := range m.Entries(ctx, fs, true) { + if err != nil { + return nil, fmt.Errorf("failed to read delete manifests: %w", err) + } + liveDeletes = append(liveDeletes, entry) + } + } + + return liveDeletes, nil +} + +// deleteManifestEvaluator returns a manifest evaluator over the partition summaries of spec that matches the given +// partition tuples. It keeps every manifest when the tuples can't be turned into a filter, or when there are more +// than inPredicateLimit distinct tuples, since a manifest's summaries rarely rule out that many partitions. +func deleteManifestEvaluator(spec iceberg.PartitionSpec, schema *iceberg.Schema, partitions []map[int]any) func(iceberg.ManifestFile) (bool, error) { + keepAll := func(iceberg.ManifestFile) (bool, error) { return rowsMightMatch, nil } + + filter, err := partitionTuplesFilter(spec, partitions) + if err != nil { + return keepAll + } + eval, err := newManifestEvaluator(spec, schema, filter, true) + if err != nil { + return keepAll + } + + return eval +} + +// partitionTuplesFilter returns a filter on the partition fields of spec that matches exactly the given +// partition tuples, or AlwaysTrue when there are more than inPredicateLimit distinct tuples. +func partitionTuplesFilter(spec iceberg.PartitionSpec, partitions []map[int]any) (iceberg.BooleanExpression, error) { + var filter iceberg.BooleanExpression = iceberg.AlwaysFalse{} + // fmt prints maps with sorted keys, so equal tuples print the same. + seen := make(map[string]struct{}, len(partitions)) + for _, partition := range partitions { + key := fmt.Sprint(partition) Review Comment: nit: #2749 made `tblutils.CanonicalPartitionKey` / `AppendPartitionTuple` the shared partition-tuple encoding. Using it here instead of `fmt.Sprint` keeps one definition and treats `[]byte` vs `string` and the decimal forms consistently. A missed duplicate only adds a redundant clause, so this is about consistency, not correctness. ########## table/transaction_delete.go: ########## @@ -598,18 +600,36 @@ func (t *Transaction) classifyLiveDeletes(ctx context.Context, fs io.IO) (classi return classifyManifestEntries(liveDeletes) } -// readPlanningDeletes reads and indexes every live delete file of the planning snapshot. Copy-on-write -// uses it because a rewrite must apply every kind of delete to the rows it keeps. +// readPlanningDeletes reads and indexes the live delete files of the planning snapshot that can apply to the +// files a copy-on-write removes or rewrites. Copy-on-write uses it because a rewrite must apply every kind of +// delete to the rows it keeps, and a removed file must take its deletion vector with it. // // Delete manifests are not pruned by the row filter: with filter id=2 the rewrite keeps id=1, -// so a delete on id=1 must still be applied. -func (t *Transaction) readPlanningDeletes(ctx context.Context, fs io.IO, builtMeta Metadata) (planningDeletes, error) { +// so a delete on id=1 must still be applied. They are pruned by the affected files instead; see liveDeletesForFiles. +func (t *Transaction) readPlanningDeletes(ctx context.Context, fs io.IO, builtMeta Metadata, removed []iceberg.DataFile, rewritten []iceberg.ManifestEntry) (planningDeletes, error) { meta, err := t.txnMeta() if err != nil { return planningDeletes{}, err } - classified, err := t.classifyLiveDeletes(ctx, fs) + var liveDeletes []iceberg.ManifestEntry + if s := t.planningSnapshot(meta); s != nil { + files := slices.Clip(removed) + // A removed file's sequence number is not known here, so only prune by sequence number when every file is rewritten. Review Comment: nit (optional, fine as a follow-up): one whole-file drop turns sequence pruning off for the whole operation. If the caller passed the manifest entries for removed files too (it has them when classifying), mixed drop-and-rewrite operations could prune by sequence number as well. ########## table/transaction_delete.go: ########## @@ -575,8 +576,9 @@ type planningDeletes struct { // classifyLiveDeletes reads every live delete file of the planning snapshot and sorts it by kind. // -// Known limitation (#2160): every live delete manifest of the snapshot is read on each call, -// with no partition pruning, so a narrow delete or rewrite on a delete-heavy table pays for all of them. +// Known limitation: every live delete manifest of the snapshot is read on each call, with no +// partition pruning, so a narrow merge-on-read delete on a delete-heavy table pays for all of them. +// Copy-on-write prunes them instead; see readPlanningDeletes. Review Comment: nit: this PR closes #2160, but merge-on-read still reads every delete manifest (rightly, so it can't skip a DV and write a second one). Could you either keep #2160 open for the merge-on-read half or open a follow-up issue and link it here, so this limitation stays tracked? -- 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]
