iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files (#13131)

* iceberg maintenance: recognise deletion vectors whose format is written in lowercase

Iceberg maintenance tells a Puffin deletion vector from a Parquet position-delete file by its `file_format`, compared exactly with iceberg-go's constant `PUFFIN`. DuckDB records the format in lowercase, `puffin` (as it records `parquet`, which compaction already compares without case). Such a vector was never taken for a vector:

- the data file it covers was not kept out of compaction bins, and
- the vector itself was handed to the Parquet position-delete reader, which cannot read a Puffin file, so compacting any table holding one failed (and the position-delete rewrite tried to read it the same way).

The fix adds `isPuffin`, a case-insensitive comparison, and uses it at the four places that compared the format.

Test: `TestLowercasePuffinDeletionVector` wraps a deletion-vector entry so its format reads `puffin` (as the Avro reader passes it through) and checks that the data file it covers is excluded and that `collectPositionDeletes` does not try to read the vector. It fails without the change (`dv paths = map[]`).

`go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files

Compaction has no reader for Puffin deletion vectors (DVs), so every data file a vector covers is kept out of compaction for good (`excludeDeletionVectorFiles`). A format-version 3 table that is reloaded with DELETE + INSERT (DuckDB writes a vector hiding all of the old file) keeps the old file and its vector forever, and every reader pays for both. Bins also form only from `min_input_files` small files per partition, so deleted rows never enter the decision.

This builds on #13127 (the case-insensitive `puffin` format check); the first commit on this branch is that PR.

Changes:

- **Vectors are applied.** The vectors of the compaction candidates are read with iceberg-go's `table/dv` (length, magic and CRC checked, and the decoded cardinality checked against the manifest's `record_count`) and joined with the Parquet position deletes the merge already applies. A vector that does not decode keeps its file out of every bin, as before, so a file never merges without its deletes. One Puffin file is read once per run even when it holds several vectors.
- **A consumed vector leaves with its data file.** When the snapshot removes a data file, the delete manifests holding its vector are rewritten (that vector `DELETED`, the other entries `EXISTING`); manifests without one are carried as they are. Vectors are matched by the data file they cover, never by the Puffin file path, because one Puffin file may hold the vectors of several data files (Spark writes them that way) and the vectors of files left in place must stay.
- **A bin whose deletes leave no row writes no empty file**; its files are just removed.
- **New setting `delete_ratio_threshold_percent`** (default 0 = off, so bin selection is unchanged unless set; Iceberg's own `rewrite_data_files` uses 30%). When set, a Parquet file whose vector deletes at least that share of its rows is rewritten in a bin of its own, whatever `min_input_files` says, packed by live bytes up to the target size. A file whose decoded vector deletes exactly positions 0..n-1 is dropped without being read; a manifest count that says "all" with positions that do not is rewritten row by row instead. Only files under the target file size are taken (the merge reads a file whole into memory), except a file dropped unread.
- **Detection reads no vector**: a DV's `record_count` is its cardinality, which is all the ratio needs. With `apply_deletes` off, planning ignores vectors (execution skips tables with deletes then). The planning-index cache key includes the ratio.

Tests (`deletion_vector_test.go`):

- a vector with a lowercase `puffin` format is matched to its data file under either path spelling;
- a merge with a vector and a Parquet position delete: every file merges minus its deleted rows, row ids kept, and the delete files leave the table (ratio off);
- a reloaded table: the wholly deleted file and its vector are dropped without the file being read (it is not even present), the new file untouched;
- ratio past / under / vector not decodable / manifest count says all but positions do not / partly deleted file past the target size left alone;
- two vectors in one Puffin file, only one data file compacted: the other file's vector stays;
- detection with the ratio on and off.

Each was checked red against a mutation of the rule it covers (exact format compare, vectors not applied, vector consumed by Puffin path, size check skipped, whole-file check skipped). `go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg compact: check a deletion vector's blob range without overflow

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

* iceberg detection: key the cached compaction plan on apply_deletes

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

* iceberg detection: skip a table with deletes while apply_deletes is off

Execution already skips it, so detection proposed a job that never ran.

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

* iceberg compact: a drop-only bin is not held to the sort input cap

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

* iceberg compact: split delete-heavy bins at the sort input cap

The packer counted live bytes only, so two partly deleted files could
share a bin the sort input cap then dropped on every run.

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

* iceberg compact: compare the delete ratio in whole rows

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

* iceberg compact: merge delete-heavy files in the order of their bounds

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

* iceberg compact: read only the vectors of files a bin can take

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

* iceberg compact: pack a vector whose count and positions disagree by its whole size

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-30 10:22:30 -08:00
1 parent 347f1cf705
commit bf14326c3c
10 files changed
+1120 -291

No files matched your search

+106 -64
View File
@@ -11,6 +11,7 @@ import (
"io"
"os"
"path"
"slices"
"sort"
"strings"
"time"
@@ -32,6 +33,9 @@ type compactionBin struct {
SpecID int32
Entries []iceberg.ManifestEntry
TotalSize int64
// DropOnly: every row of every file is deleted; the files
// leave the table without being read and nothing is written for them.
DropOnly bool
}
// compactDataFiles reads manifests to find small Parquet data files, groups
@@ -113,7 +117,7 @@ func (h *Handler) compactDataFiles(
var positionDeletes map[string][]int64
var eqDeleteGroups []equalityDeleteGroup
var allDeleteEntries []iceberg.ManifestEntry
var dvPaths map[string]bool
var dvs *deletionVectorSet
if config.ApplyDeletes && len(deleteManifests) > 0 {
for _, mf := range deleteManifests {
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
@@ -128,7 +132,7 @@ func (h *Handler) compactDataFiles(
}
var err error
dvPaths, err = deletionVectorPaths(allDeleteEntries, bucketName, dataPath)
dvs, err = indexDeletionVectors(allDeleteEntries, bucketName, dataPath)
if err != nil {
return "", nil, err
}
@@ -137,7 +141,7 @@ func (h *Handler) compactDataFiles(
// predicate so out-of-scope deletes don't affect the merge.
var posDeleteEntries, eqDeleteEntries []iceberg.ManifestEntry
for _, entry := range allDeleteEntries {
if entry.DataFile().FileFormat() == iceberg.PuffinFile {
if isPuffin(entry.DataFile()) {
continue
}
inScope, err := deleteInPredicateScope(entry, predicate, specsByID, schema)
@@ -170,10 +174,7 @@ func (h *Handler) compactDataFiles(
}
}
candidateEntries, err := excludeDeletionVectorFiles(allEntries, dvPaths, bucketName, dataPath)
if err != nil {
return "", nil, err
}
candidateEntries := allEntries
if predicate != nil {
filtered := make([]iceberg.ManifestEntry, 0, len(candidateEntries))
for _, entry := range candidateEntries {
@@ -192,6 +193,41 @@ func (h *Handler) compactDataFiles(
candidateEntries = filtered
}
// Read the deletion vectors of the candidates; a file whose
// vector cannot be read stays out of every bin. The positions join the
// Parquet position deletes the merge already applies.
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
if dvs != nil && len(dvs.entries) > 0 {
var covered []string
for _, entry := range candidateEntries {
df := entry.DataFile()
key, err := normalizeIcebergPath(df.FilePath(), bucketName, dataPath)
if err != nil {
return "", nil, fmt.Errorf("resolve data file %s: %w", df.FilePath(), err)
}
// a file at the target size enters no bin unless it may be dropped whole
if df.FileSizeBytes() >= targetSize && (config.DeleteRatioThresholdPercent <= 0 || dvs.deletedShare(key, df.Count()) < 1) {
continue
}
if dvs.covers(key) {
covered = append(covered, key)
}
}
dvs.read(ctx, filerClient, bucketName, dataPath, covered)
if positionDeletes == nil {
positionDeletes = map[string][]int64{}
}
for key, positions := range dvs.positions {
merged := append(append([]int64(nil), positionDeletes[key]...), positions...)
sort.Slice(merged, func(i, j int) bool { return merged[i] < merged[j] })
positionDeletes[key] = slices.Compact(merged) // a legacy position delete may name a row the vector does
}
}
heavyEntries, candidateEntries, err := splitDeleteHeavy(candidateEntries, dvs, config.DeleteRatioThresholdPercent, targetSize, bucketName, dataPath)
if err != nil {
return "", nil, err
}
minInputFiles, err := compactionMinInputFiles(config.MinInputFiles)
if err != nil {
return "", nil, err
@@ -199,9 +235,14 @@ func (h *Handler) compactDataFiles(
// Build compaction bins: group small data files by partition, each bin's
// files in the order of their bounds so the merged file keeps the
// ordering its inputs had.
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
// ordering its inputs had. Files with many deleted rows get bins of
// their own, whatever min_input_files says.
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles, meta)
heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, bucketName, dataPath)
if err != nil {
return "", nil, err
}
bins = append(bins, heavyBins...)
initialBinCount := len(bins)
bins = filterCompactionBinsByPlan(bins, config, rewritePlan)
if len(bins) == 0 {
@@ -248,6 +289,20 @@ func (h *Handler) compactDataFiles(
return entrySeqNum(entry)
}
// removeBinEntries marks a bin's files removed by this snapshot.
removeBinEntries := func(bin compactionBin) {
for _, entry := range bin.Entries {
summary.removeFile(entry.DataFile())
deletedManifestEntries = append(deletedManifestEntries, iceberg.NewManifestEntry(
iceberg.EntryStatusDELETED,
&newSnapID,
entrySeqNum(entry), entryFileSeqNum(entry),
entry.DataFile(),
))
}
totalMerged += len(bin.Entries)
}
metaDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "metadata")
dataDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "data")
@@ -279,6 +334,15 @@ func (h *Handler) compactDataFiles(
default:
}
if bin.DropOnly {
// every row is deleted: the files go, nothing is read or written
removeBinEntries(bin)
if onProgress != nil {
onProgress(binIdx, len(bins))
}
continue
}
mergedFileName := fmt.Sprintf("compact-%d-%d-%s-%d.parquet", snapshotID, newSnapID, artifactSuffix, binIdx)
mergedFilePath := absoluteIcebergPath(bucketName, dataPath, "data", mergedFileName)
@@ -302,6 +366,11 @@ func (h *Handler) compactDataFiles(
glog.Warningf("iceberg compact: failed to merge bin %d (%d files): %v", binIdx, len(bin.Entries), err)
goto binDone
}
if recordCount == 0 {
// the deletes left no row: no empty file is written
removeBinEntries(bin)
goto binDone
}
// A default-CRS geometry column declares no CRS (geometry_crs.go). A
// footer that cannot be rewritten leaves the file as written: valid,
// only labelled differently.
@@ -379,18 +448,7 @@ func (h *Handler) compactDataFiles(
newManifestEntries = append(newManifestEntries, newEntry)
// Mark original entries as deleted
for _, entry := range bin.Entries {
summary.removeFile(entry.DataFile())
delEntry := iceberg.NewManifestEntry(
iceberg.EntryStatusDELETED,
&newSnapID,
entrySeqNum(entry), entryFileSeqNum(entry),
entry.DataFile(),
)
deletedManifestEntries = append(deletedManifestEntries, delEntry)
}
totalMerged += len(bin.Entries)
removeBinEntries(bin)
}
binDone:
@@ -399,7 +457,7 @@ func (h *Handler) compactDataFiles(
}
}
if len(newManifestEntries) == 0 {
if totalMerged == 0 {
return "no bins successfully compacted", nil, nil
}
@@ -503,7 +561,25 @@ func (h *Handler) compactDataFiles(
}
}
if carryDeletes {
allManifests = append(allManifests, deleteManifests...)
// A deletion vector whose data file this compaction removed leaves
// with it; the rest of the delete files carry on.
consumed, err := consumedDeletionVectors(dvs, deletedManifestEntries, bucketName, dataPath)
if err != nil {
return "", nil, err
}
if len(consumed) == 0 {
allManifests = append(allManifests, deleteManifests...)
} else {
rewritten, names, err := rewriteDeleteManifestsWithout(ctx, filerClient, bucketName, dataPath, metaDir,
deleteManifests, consumed, version, specLookup, schema, newSnapID, artifactSuffix, &summary)
for _, name := range names {
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: name})
}
if err != nil {
return "", nil, err
}
allManifests = append(allManifests, rewritten...)
}
} else {
// All files were compacted, so the deletes leave the table with them.
for _, entry := range allDeleteEntries {
@@ -766,46 +842,12 @@ func partitionKey(partition map[int]any) string {
return strings.Join(parts, "\x00")
}
// deletionVectorPaths names the data files a Puffin deletion-vector entry
// covers, normalized to merge-time keys. Merging a covered file needs a
// Puffin reader to apply the vector; without one the merge would resurrect
// deleted rows, so the file must stay out of compaction bins.
func deletionVectorPaths(entries []iceberg.ManifestEntry, bucketName, dataPath string) (map[string]bool, error) {
paths := make(map[string]bool)
for _, entry := range entries {
df := entry.DataFile()
if df.ContentType() != iceberg.EntryContentPosDeletes || df.FileFormat() != iceberg.PuffinFile {
continue
}
ref := df.ReferencedDataFile()
if ref == nil || *ref == "" {
return nil, fmt.Errorf("deletion vector %s has no referenced data file", df.FilePath())
}
normalized, err := normalizeIcebergPath(*ref, bucketName, dataPath)
if err != nil {
return nil, fmt.Errorf("resolve deletion vector source %s: %w", *ref, err)
}
paths[normalized] = true
}
return paths, nil
}
// excludeDeletionVectorFiles drops entries a deletion vector covers.
func excludeDeletionVectorFiles(entries []iceberg.ManifestEntry, dvPaths map[string]bool, bucketName, dataPath string) ([]iceberg.ManifestEntry, error) {
if len(dvPaths) == 0 {
return entries, nil
}
kept := make([]iceberg.ManifestEntry, 0, len(entries))
for _, entry := range entries {
normalized, err := normalizeIcebergPath(entry.DataFile().FilePath(), bucketName, dataPath)
if err != nil {
return nil, fmt.Errorf("resolve data file %s: %w", entry.DataFile().FilePath(), err)
}
if !dvPaths[normalized] {
kept = append(kept, entry)
}
}
return kept, nil
// isPuffin reports whether a delete file is a Puffin deletion vector. The
// format is compared without case: some writers (DuckDB among them) record
// it as "puffin", as they record "parquet", while iceberg-go's constant is
// "PUFFIN".
func isPuffin(df iceberg.DataFile) bool {
return strings.EqualFold(string(df.FileFormat()), string(iceberg.PuffinFile))
}
// collectPositionDeletes reads position delete Parquet files and returns a map
@@ -820,7 +862,7 @@ func collectPositionDeletes(
result := make(map[string][]int64)
for _, entry := range deleteEntries {
df := entry.DataFile()
if df.ContentType() != iceberg.EntryContentPosDeletes || df.FileFormat() == iceberg.PuffinFile {
if df.ContentType() != iceberg.EntryContentPosDeletes || isPuffin(df) {
continue // Puffin is a deletion vector, not a row-level delete file
}
fileDeletes, err := readPositionDeleteFile(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath())
+16 -7
View File
@@ -24,13 +24,16 @@ const (
defaultDeleteMinInputFiles = 2
defaultDeleteMaxGroupSizeMB = 256
defaultDeleteMaxOutputFiles = 8
defaultRewriteStrategy = "binpack"
rewriteStrategyAuto = "auto"
defaultSortBufferRows = 262144
minSortBufferRows = 1024
defaultMinManifestsToRewrite = 5
minManifestsToRewrite = 2
defaultOperations = "all"
// a data file whose deletion vector deletes at least this share of its rows
// (percent) is rewritten in a bin of its own; 0 = off
defaultDeleteRatioThresholdPercent = 0
defaultRewriteStrategy = "binpack"
rewriteStrategyAuto = "auto"
defaultSortBufferRows = 262144
minSortBufferRows = 1024
defaultMinManifestsToRewrite = 5
minManifestsToRewrite = 2
defaultOperations = "all"
// Metric keys returned by maintenance operations.
MetricFilesMerged = "files_merged"
@@ -121,6 +124,8 @@ type Config struct {
DeleteMinInputFiles int64
DeleteMaxFileGroupSizeBytes int64
DeleteMaxOutputFiles int64
// DeleteRatioThresholdPercent: see defaultDeleteRatioThresholdPercent; 0 turns the delete-driven selection off
DeleteRatioThresholdPercent int64
MinManifestsToRewrite int64
Operations string
TablePropertiesOverride bool
@@ -150,6 +155,7 @@ func ParseConfig(values map[string]*plugin_pb.ConfigValue) Config {
DeleteMinInputFiles: readInt64Config(values, "delete_min_input_files", defaultDeleteMinInputFiles),
DeleteMaxFileGroupSizeBytes: readSizeMBConfig(values, "delete_max_file_group_size_mb", defaultDeleteMaxGroupSizeMB),
DeleteMaxOutputFiles: readInt64Config(values, "delete_max_output_files", defaultDeleteMaxOutputFiles),
DeleteRatioThresholdPercent: readInt64Config(values, "delete_ratio_threshold_percent", defaultDeleteRatioThresholdPercent),
MinManifestsToRewrite: readInt64Config(values, "min_manifests_to_rewrite", defaultMinManifestsToRewrite),
Operations: readStringConfig(values, "operations", defaultOperations),
TablePropertiesOverride: readBoolConfig(values, "table_properties_override", true),
@@ -197,6 +203,9 @@ func applyThresholdDefaults(cfg Config) Config {
if cfg.DeleteMaxFileGroupSizeBytes <= 0 {
cfg.DeleteMaxFileGroupSizeBytes = defaultDeleteMaxGroupSizeMB * 1024 * 1024
}
if cfg.DeleteRatioThresholdPercent < 0 || cfg.DeleteRatioThresholdPercent > 100 {
cfg.DeleteRatioThresholdPercent = defaultDeleteRatioThresholdPercent
}
if cfg.DeleteMaxOutputFiles <= 0 {
cfg.DeleteMaxOutputFiles = defaultDeleteMaxOutputFiles
}
+1 -1
View File
@@ -107,7 +107,7 @@ func collectDeleteRewriteGroups(
}
allPositionEntries = append(allPositionEntries, entry)
if entry.DataFile().FileFormat() == iceberg.PuffinFile {
if isPuffin(entry.DataFile()) {
continue
}
@@ -0,0 +1,388 @@
package iceberg
import (
"context"
"fmt"
"sort"
"strings"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
"github.com/apache/iceberg-go/table/dv"
"github.com/seaweedfs/seaweedfs/weed/glog"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
// Deletion vectors in compaction.
//
// A format-version-3 DELETE or UPDATE leaves the data file in place and writes
// a Puffin deletion vector (DV) naming the deleted row positions of that one
// file. Without a DV reader every file a DV covered would be left out of
// compaction for good: a table reloaded with DELETE + INSERT would keep its
// old file and the vector that hides all of it, and every reader would pay for
// both. The vector is read and applied like a Parquet position delete, and
// a file whose deleted share passes delete_ratio_threshold_percent is
// rewritten on its own (or, when every row is deleted, dropped without being
// read), whatever min_input_files says.
// deletionVectorSet is what compaction knows about the vectors of a snapshot,
// keyed by the normalized path of the data file each one covers.
type deletionVectorSet struct {
// positions decoded from each vector, sorted; filled only when read
positions map[string][]int64
// the vector entries, for the commit that removes a consumed vector
entries map[string]iceberg.ManifestEntry
// deleted-row count from the manifest (a DV's record_count is its
// cardinality, spec v3), for planning without opening the Puffin file
cardinality map[string]int64
// files whose vector could not be used: they stay out of compaction
unusable map[string]bool
}
// indexDeletionVectors collects the DV entries of a snapshot without reading
// them. A data file named by two vectors is invalid (one DV per file, spec v3)
// and is kept out of compaction rather than merged with either.
func indexDeletionVectors(deleteEntries []iceberg.ManifestEntry, bucketName, dataPath string) (*deletionVectorSet, error) {
set := &deletionVectorSet{
positions: map[string][]int64{},
entries: map[string]iceberg.ManifestEntry{},
cardinality: map[string]int64{},
unusable: map[string]bool{},
}
for _, entry := range deleteEntries {
df := entry.DataFile()
if df.ContentType() != iceberg.EntryContentPosDeletes || !isPuffin(df) {
continue
}
ref := df.ReferencedDataFile()
if ref == nil || *ref == "" {
return nil, fmt.Errorf("deletion vector %s has no referenced data file", df.FilePath())
}
key, err := normalizeIcebergPath(*ref, bucketName, dataPath)
if err != nil {
return nil, fmt.Errorf("resolve deletion vector source %s: %w", *ref, err)
}
if _, dup := set.entries[key]; dup {
set.unusable[key] = true
continue
}
set.entries[key] = entry
set.cardinality[key] = df.Count()
if df.ContentOffset() == nil || df.ContentSizeInBytes() == nil {
set.unusable[key] = true
}
}
return set, nil
}
func (s *deletionVectorSet) covers(key string) bool {
if s == nil {
return false
}
_, ok := s.entries[key]
return ok
}
// read decodes the vectors of the given data files, each checked against its
// manifest cardinality (dv.DeserializeDV checks length, magic and CRC too). A
// vector that cannot be read marks its file unusable; it never fails the run,
// and it never lets the file merge without its deletes.
func (s *deletionVectorSet) read(ctx context.Context, filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string, keys []string) {
if s == nil {
return
}
puffins := map[string][]byte{}
for _, key := range keys {
entry, ok := s.entries[key]
if !ok || s.unusable[key] {
continue
}
if _, done := s.positions[key]; done {
continue
}
positions, err := readDeletionVector(ctx, filerClient, bucketName, dataPath, entry.DataFile(), puffins)
if err != nil {
glog.Warningf("iceberg compact: deletion vector for %s not applied, file left as it is: %v", key, err)
s.unusable[key] = true
continue
}
s.positions[key] = positions
}
}
func readDeletionVector(ctx context.Context, filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string, df iceberg.DataFile, cache map[string][]byte) ([]int64, error) {
data, ok := cache[df.FilePath()]
if !ok {
var err error
data, err = loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, df.FilePath())
if err != nil {
return nil, fmt.Errorf("read %s: %w", df.FilePath(), err)
}
cache[df.FilePath()] = data
}
offset, size := *df.ContentOffset(), *df.ContentSizeInBytes()
if offset < 0 || size <= 0 || offset > int64(len(data)) || size > int64(len(data))-offset {
return nil, fmt.Errorf("blob [%d, +%d) outside %s (%d bytes)", offset, size, df.FilePath(), len(data))
}
bitmap, err := dv.DeserializeDV(data[offset:offset+size], df.Count())
if err != nil {
return nil, fmt.Errorf("decode %s: %w", df.FilePath(), err)
}
positions := make([]int64, 0, bitmap.Cardinality())
for pos := range bitmap.Positions() {
positions = append(positions, int64(pos))
}
sort.Slice(positions, func(i, j int) bool { return positions[i] < positions[j] })
return positions, nil
}
// deletedShare is the share (0..1) of a data file's rows its vector deletes,
// from manifest counts. A file with no vector, or with a count the manifest
// does not give, is 0.
func (s *deletionVectorSet) deletedShare(key string, records int64) float64 {
if s == nil || records <= 0 || s.unusable[key] {
return 0
}
n, ok := s.cardinality[key]
if !ok || n <= 0 {
return 0
}
if n >= records {
return 1
}
return float64(n) / float64(records)
}
// coversWholeFile: the vector deletes every position of a records-row file.
// Once decoded (execution) the positions must be exactly 0..records-1, so a
// vector naming a position past the end never drops a file with a live row;
// such a file is rewritten instead, its deletes applied row by row. Planning,
// which decodes nothing, goes by the manifest count.
func (s *deletionVectorSet) coversWholeFile(key string, records int64) bool {
positions, decoded := s.positions[key]
if !decoded {
return true
}
return int64(len(positions)) == records && records > 0 && positions[0] == 0 && positions[len(positions)-1] == records-1
}
// splitDeleteHeavy separates the files compaction rewrites because of their
// deletes from the rest, and drops the files whose vector cannot be used.
// thresholdPercent 0 turns the delete-driven selection off; covered files then
// only merge in ordinary bins, with their deletes applied.
func splitDeleteHeavy(entries []iceberg.ManifestEntry, dvs *deletionVectorSet, thresholdPercent, targetSize int64,
bucketName, dataPath string) (heavy, rest []iceberg.ManifestEntry, err error) {
for _, entry := range entries {
key, err := normalizeIcebergPath(entry.DataFile().FilePath(), bucketName, dataPath)
if err != nil {
return nil, nil, fmt.Errorf("resolve data file %s: %w", entry.DataFile().FilePath(), err)
}
if dvs != nil && dvs.unusable[key] {
continue
}
df := entry.DataFile()
share := dvs.deletedShare(key, df.Count())
if thresholdPercent > 0 && share > 0 && min(dvs.cardinality[key], df.Count())*100 >= thresholdPercent*df.Count() &&
// only Parquet merges; a file past the target size is read whole into memory by the merge, so it is
// taken only when it is dropped unread (every row deleted)
strings.EqualFold(string(df.FileFormat()), string(iceberg.ParquetFile)) &&
(df.FileSizeBytes() < targetSize || (share >= 1 && dvs.coversWholeFile(key, df.Count()))) {
heavy = append(heavy, entry)
continue
}
rest = append(rest, entry)
}
return heavy, rest, nil
}
// buildDeleteHeavyBins groups delete-heavy files by partition spec and value.
// A file whose every row is deleted goes to a drop-only bin (removed, never
// read). The others (each under targetSize, splitDeleteHeavy) pack in the
// order of their bounds, like buildCompactionBins, by their live bytes up to
// targetSize, and by their input bytes up to inputCap (0 = no cap).
func buildDeleteHeavyBins(entries []iceberg.ManifestEntry, dvs *deletionVectorSet, targetSize, inputCap int64,
meta table.Metadata, bucketName, dataPath string) ([]compactionBin, error) {
type group struct {
drop compactionBin
rewrite []iceberg.ManifestEntry
live map[string]int64
}
groups := map[string]*group{}
var order []string
for _, entry := range entries {
df := entry.DataFile()
key, err := normalizeIcebergPath(df.FilePath(), bucketName, dataPath)
if err != nil {
return nil, err
}
partKey := partitionKey(df.Partition())
gk := fmt.Sprintf("spec%d\x00%s", df.SpecID(), partKey)
g, ok := groups[gk]
if !ok {
g = &group{drop: compactionBin{PartitionKey: partKey, Partition: df.Partition(), SpecID: df.SpecID(), DropOnly: true},
live: map[string]int64{}}
groups[gk] = g
order = append(order, gk)
}
share := dvs.deletedShare(key, df.Count())
if share >= 1 && dvs.coversWholeFile(key, df.Count()) {
g.drop.Entries = append(g.drop.Entries, entry)
g.drop.TotalSize += df.FileSizeBytes()
continue
}
g.rewrite = append(g.rewrite, entry)
live := int64(float64(df.FileSizeBytes()) * (1 - share))
if share >= 1 {
// the count says every row, the positions do not: count the whole file
live = df.FileSizeBytes()
}
g.live[df.FilePath()] = live
}
sort.Strings(order)
var bins []compactionBin
for _, gk := range order {
g := groups[gk]
if len(g.drop.Entries) > 0 {
bins = append(bins, g.drop)
}
resolveCompactionOrder(meta, g.rewrite).sortEntries(g.rewrite)
var cur compactionBin
var curLive int64
flush := func() {
if len(cur.Entries) > 0 {
bins = append(bins, cur)
}
cur, curLive = compactionBin{}, 0
}
for _, entry := range g.rewrite {
df := entry.DataFile()
live := g.live[df.FilePath()]
if len(cur.Entries) > 0 && (curLive+live > targetSize || (inputCap > 0 && cur.TotalSize+df.FileSizeBytes() > inputCap)) {
flush()
}
if len(cur.Entries) == 0 {
cur = compactionBin{PartitionKey: g.drop.PartitionKey, Partition: g.drop.Partition, SpecID: g.drop.SpecID}
}
cur.Entries = append(cur.Entries, entry)
cur.TotalSize += df.FileSizeBytes()
curLive += live
}
flush()
}
return bins, nil
}
// consumedDeletionVectors names, by the normalized path of the data file each
// covers, the vectors whose data file the compaction removed: they leave the
// table with it. Never keyed by the Puffin file: one Puffin file may hold the
// vectors of several data files (Spark writes them so), and the vectors of the
// files left in place must stay.
func consumedDeletionVectors(dvs *deletionVectorSet, removed []iceberg.ManifestEntry, bucketName, dataPath string) (map[string]bool, error) {
consumed := map[string]bool{}
if dvs == nil {
return consumed, nil
}
for _, entry := range removed {
key, err := normalizeIcebergPath(entry.DataFile().FilePath(), bucketName, dataPath)
if err != nil {
return nil, err
}
if _, ok := dvs.entries[key]; ok {
consumed[key] = true
}
}
return consumed, nil
}
// consumedVector: a delete entry is a vector whose data file is consumed.
func consumedVector(df iceberg.DataFile, consumed map[string]bool, bucketName, dataPath string) (bool, error) {
if df.ContentType() != iceberg.EntryContentPosDeletes || !isPuffin(df) {
return false, nil
}
ref := df.ReferencedDataFile()
if ref == nil || *ref == "" {
return false, nil
}
key, err := normalizeIcebergPath(*ref, bucketName, dataPath)
if err != nil {
return false, err
}
return consumed[key], nil
}
// rewriteDeleteManifestsWithout writes, for each delete manifest holding a
// consumed vector, a new manifest where that vector is DELETED and every other
// entry EXISTING; a manifest without one is kept as it is. It returns the
// snapshot's delete manifests and the names it wrote (for cleanup on failure).
func rewriteDeleteManifestsWithout(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath, metaDir string,
deleteManifests []iceberg.ManifestFile,
consumed map[string]bool,
version int,
specs map[int]iceberg.PartitionSpec,
schema *iceberg.Schema,
newSnapID int64,
suffix string,
summary *snapshotSummary,
) ([]iceberg.ManifestFile, []string, error) {
var out []iceberg.ManifestFile
var written []string
for i, mf := range deleteManifests {
data, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
if err != nil {
return nil, written, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err)
}
entries, err := s3tables.ReadManifest(mf, data, true, specs, schema)
if err != nil {
return nil, written, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err)
}
hit := false
gone := make([]bool, len(entries))
for i, entry := range entries {
if gone[i], err = consumedVector(entry.DataFile(), consumed, bucketName, dataPath); err != nil {
return nil, written, err
}
hit = hit || gone[i]
}
if !hit {
out = append(out, mf)
continue
}
spec, ok := specs[int(mf.PartitionSpecID())]
if !ok {
return nil, written, fmt.Errorf("partition spec %d of %s not in table metadata", mf.PartitionSpecID(), mf.FilePath())
}
rewritten := make([]iceberg.ManifestEntry, 0, len(entries))
for i, entry := range entries {
df := entry.DataFile()
if gone[i] {
summary.removeFile(df)
rewritten = append(rewritten, iceberg.NewManifestEntry(iceberg.EntryStatusDELETED, &newSnapID,
manifestEntrySeqNum(entry), manifestEntryFileSeqNum(entry), df))
continue
}
snap := entry.SnapshotID()
rewritten = append(rewritten, iceberg.NewManifestEntry(iceberg.EntryStatusEXISTING, &snap,
manifestEntrySeqNum(entry), manifestEntryFileSeqNum(entry), df))
}
name := fmt.Sprintf("compact-%d-%s-deletes%d.avro", newSnapID, suffix, i)
newMf, body, err := writeManifestWithContent(absoluteIcebergPath(bucketName, dataPath, "metadata", name),
version, spec, schema, newSnapID, rewritten, iceberg.ManifestContentDeletes)
if err != nil {
return nil, written, fmt.Errorf("write delete manifest: %w", err)
}
if err := saveFilerFile(ctx, filerClient, metaDir, name, body); err != nil {
return nil, written, fmt.Errorf("save delete manifest: %w", err)
}
written = append(written, name)
out = append(out, newMf)
}
return out, written, nil
}
+529 -172
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"math"
"path"
"strings"
"testing"
@@ -11,61 +12,132 @@ import (
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
"github.com/apache/iceberg-go/table/dv"
"github.com/parquet-go/parquet-go"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
// A deletion-vector entry names its data file in referenced_data_file; the
// match against candidates is on the normalized path either side takes.
func TestDeletionVectorPathMatching(t *testing.T) {
spec := *iceberg.UnpartitionedSpec
const dvTestDataDir = "/buckets/test-bucket/ns/tbl/data"
// putDeletionVector stores a Puffin-shaped file holding one deletion vector
// (after a 4-byte header, so the blob offset is not 0) and returns the
// manifest entry a v3 writer commits for it.
func putDeletionVector(t *testing.T, fs *fakeFilerServer, setup tableSetup, name, ref string, positions ...uint64) iceberg.ManifestEntry {
t.Helper()
bitmap := dv.NewRoaringPositionBitmap()
for _, p := range positions {
bitmap.Set(p)
}
blob, err := dv.SerializeDV(bitmap)
if err != nil {
t.Fatalf("serialize dv: %v", err)
}
content := append([]byte("PFA1"), blob...)
fs.putEntry(dvTestDataDir, name, &filer_pb.Entry{Name: name, Content: content})
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentPosDeletes,
setup.fileRef("data", name), iceberg.PuffinFile, map[int]any{}, nil, nil, int64(len(positions)), int64(len(content)))
if err != nil {
t.Fatalf("build dv file: %v", err)
}
dfb.ReferencedDataFile(ref).ContentOffset(4).ContentSizeInBytes(int64(len(blob)))
snapID := int64(1)
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
}
newEntry := func(path, ref string) iceberg.ManifestEntry {
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentPosDeletes, path,
iceberg.PuffinFile, map[int]any{}, nil, nil, 0, 8)
func dvDataEntry(t *testing.T, name string, count int64) iceberg.ManifestEntry {
snapID := int64(1)
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, *iceberg.UnpartitionedSpec, "data/"+name, count))
}
// liveFiles lists the current snapshot's live data and delete files.
func liveFiles(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) (data, deletes []iceberg.DataFile) {
t.Helper()
ctx := context.Background()
state, err := loadCurrentMetadata(ctx, client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
}
manifests, err := loadCurrentManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata)
if err != nil {
t.Fatalf("loadCurrentManifests: %v", err)
}
for _, mf := range manifests {
body, err := loadFileByIcebergPath(ctx, client, setup.BucketName, state.DataPath, mf.FilePath())
if err != nil {
t.Fatalf("build dv file: %v", err)
t.Fatalf("read manifest: %v", err)
}
if ref != "" {
dfb.ReferencedDataFile(ref)
entries, err := s3tables.ReadManifest(mf, body, true, specByID(state.Metadata), state.Metadata.CurrentSchema())
if err != nil {
t.Fatalf("parse manifest: %v", err)
}
for _, e := range entries {
if e.Status() == iceberg.EntryStatusDELETED {
continue
}
if mf.ManifestContent() == iceberg.ManifestContentData {
data = append(data, e.DataFile())
} else {
deletes = append(deletes, e.DataFile())
}
}
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
}
return data, deletes
}
paths, err := deletionVectorPaths([]iceberg.ManifestEntry{
newEntry("metadata/dv.puffin", "s3://test-bucket/ns/tbl/data/f1.parquet"),
}, "test-bucket", "ns/tbl")
func readLiveRows(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup, df iceberg.DataFile) (ids, rowIDs []any) {
t.Helper()
state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("deletionVectorPaths: %v", err)
t.Fatalf("loadCurrentMetadata: %v", err)
}
if !paths["ns/tbl/data/f1.parquet"] {
t.Fatalf("dv paths = %v, want the normalized f1 path", paths)
body, err := loadFileByIcebergPath(context.Background(), client, setup.BucketName, state.DataPath, df.FilePath())
if err != nil {
t.Fatalf("read %s: %v", df.FilePath(), err)
}
ids, _, rowIDs, _ = mergedColumns(t, body)
return ids, rowIDs
}
dataEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, "data/f1.parquet", 3))
otherEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, "data/f2.parquet", 2))
kept, err := excludeDeletionVectorFiles([]iceberg.ManifestEntry{dataEntry, otherEntry}, paths, "test-bucket", "ns/tbl")
type lowercasePuffinEntry struct{ iceberg.ManifestEntry }
func (e lowercasePuffinEntry) DataFile() iceberg.DataFile {
return lowercasePuffinFile{e.ManifestEntry.DataFile()}
}
type lowercasePuffinFile struct{ iceberg.DataFile }
func (f lowercasePuffinFile) FileFormat() iceberg.FileFormat { return "puffin" }
// The vector's data file is matched on the normalized path either side takes:
// a miss here would merge the file without its deletes.
func TestDeletionVectorPathMatching(t *testing.T) {
fs, _ := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
// DuckDB's format is "puffin", in lowercase: compared exactly, its vectors were never taken for vectors
entry := lowercasePuffinEntry{putDeletionVector(t, fs, setup, "dv.puffin", "s3://test-bucket/ns/tbl/data/f1.parquet", 0)}
set, err := indexDeletionVectors([]iceberg.ManifestEntry{entry}, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("excludeDeletionVectorFiles: %v", err)
t.Fatalf("indexDeletionVectors: %v", err)
}
if len(kept) != 1 || kept[0].DataFile().FilePath() != "data/f2.parquet" {
t.Fatalf("kept %d entries, want only f2", len(kept))
for _, p := range []string{"data/f1.parquet", "s3://test-bucket/ns/tbl/data/f1.parquet"} {
key, err := normalizeIcebergPath(p, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("normalize %s: %v", p, err)
}
if !set.covers(key) {
t.Fatalf("%s not matched to its vector (keys %v)", p, set.entries)
}
}
}
// A Puffin deletion vector is not a Parquet position-delete file: it must not
// reach readPositionDeleteFile, and the data file it covers must stay
// uncompacted until something applies the vector. Other files still merge and
// ordinary Parquet position deletes still apply.
// Vectors are applied like Parquet position deletes: every file merges, each
// minus its deleted rows, row IDs kept; with every file rewritten the delete
// files leave the table.
func TestCompactDataFilesDeletionVector(t *testing.T) {
fs, client := startFakeFiler(t)
ctx := context.Background()
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
spec := *iceberg.UnpartitionedSpec
snapID := int64(1)
@@ -74,16 +146,6 @@ func TestCompactDataFilesDeletionVector(t *testing.T) {
putDataFileRows(t, fs, "f2.parquet", []lineageDataRow{{3, "c"}, {4, "d"}})
putDataFileRows(t, fs, "f3.parquet", []lineageDataRow{{5, "e"}})
dataEntries := []iceberg.ManifestEntry{
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, "data/f1.parquet", 2)),
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, "data/f2.parquet", 2)),
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, "data/f3.parquet", 1)),
}
// An ordinary Parquet position delete against f2's first row.
type posRow struct {
FilePath string `parquet:"file_path"`
Pos int64 `parquet:"pos"`
@@ -96,169 +158,258 @@ func TestCompactDataFilesDeletionVector(t *testing.T) {
if err := w.Close(); err != nil {
t.Fatalf("close pos delete: %v", err)
}
dataDir := "/buckets/test-bucket/ns/tbl/data"
fs.putEntry(dataDir, "pd1.parquet", &filer_pb.Entry{Name: "pd1.parquet", Content: pdBuf.Bytes()})
// The vector itself is never opened, but the file should exist like a real
// engine's write would leave it.
fs.putEntry(dataDir, "dv.puffin", &filer_pb.Entry{Name: "dv.puffin", Content: []byte("puffin-bytes")})
fs.putEntry(dvTestDataDir, "pd1.parquet", &filer_pb.Entry{Name: "pd1.parquet", Content: pdBuf.Bytes()})
posDF, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentPosDeletes,
setup.fileRef("data", "pd1.parquet"), iceberg.ParquetFile, map[int]any{}, nil, nil, 1, int64(pdBuf.Len()))
if err != nil {
t.Fatalf("build pos delete file: %v", err)
}
dvDF, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentPosDeletes,
setup.fileRef("data", "dv.puffin"), iceberg.PuffinFile, map[int]any{}, nil, nil, 0, 12)
if err != nil {
t.Fatalf("build dv file: %v", err)
}
dvDF.ReferencedDataFile("s3://test-bucket/ns/tbl/data/f1.parquet")
deleteEntries := []iceberg.ManifestEntry{
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, posDF.Build()),
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dvDF.Build()),
}
writeV3Table(t, fs, setup, dataEntries, deleteEntries, 0, 5)
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 2), dvDataEntry(t, "f2.parquet", 2), dvDataEntry(t, "f3.parquet", 1)},
[]iceberg.ManifestEntry{
iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, posDF.Build()),
putDeletionVector(t, fs, setup, "dv.puffin", "s3://test-bucket/ns/tbl/data/f1.parquet", 1),
}, 0, 5)
handler := NewHandler(nil)
config := Config{
TargetFileSizeBytes: 4096,
MinInputFiles: 2,
ApplyDeletes: true,
}
result, _, err := handler.compactDataFiles(ctx, client, setup.BucketName, setup.tablePath(), config, nil)
config := Config{TargetFileSizeBytes: 4096, MinInputFiles: 2, ApplyDeletes: true}
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 2 files into 1") {
if !strings.Contains(result, "compacted 3 files into 1") {
t.Fatalf("unexpected result: %q", result)
}
state, err := loadCurrentMetadata(ctx, client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
data, deletes := liveFiles(t, client, setup)
if len(data) != 1 || len(deletes) != 0 {
t.Fatalf("live data %d, deletes %d; want 1 merged file and no delete files", len(data), len(deletes))
}
manifests, err := loadCurrentManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata)
if err != nil {
t.Fatalf("loadCurrentManifests: %v", err)
ids, rowIDs := readLiveRows(t, client, setup, data[0])
if len(ids) != 3 || ids[0] != int64(1) || ids[1] != int64(4) || ids[2] != int64(5) {
t.Fatalf("merged ids = %v, want [1 4 5] (f1 minus its vector's row, f2 minus its position delete, f3)", ids)
}
var dataMfs, deleteMfs []iceberg.ManifestFile
for _, mf := range manifests {
if mf.ManifestContent() == iceberg.ManifestContentData {
dataMfs = append(dataMfs, mf)
} else {
deleteMfs = append(deleteMfs, mf)
}
}
if len(deleteMfs) != 1 {
t.Fatalf("delete manifests carried = %d, want 1 (the vector still applies to f1)", len(deleteMfs))
}
var merged iceberg.DataFile
var f1Live bool
for _, mf := range dataMfs {
manifestData, err := loadFileByIcebergPath(ctx, client, setup.BucketName, state.DataPath, mf.FilePath())
if err != nil {
t.Fatalf("read manifest: %v", err)
}
entries, err := s3tables.ReadManifest(mf, manifestData, false, specByID(state.Metadata), state.Metadata.CurrentSchema())
if err != nil {
t.Fatalf("parse manifest: %v", err)
}
for _, e := range entries {
df := e.DataFile()
switch {
case e.Status() == iceberg.EntryStatusADDED:
merged = df
case e.Status() == iceberg.EntryStatusEXISTING && df.FilePath() == "data/f1.parquet":
f1Live = true
}
}
}
if !f1Live {
t.Fatal("f1 is covered by a deletion vector and must stay live")
}
if merged == nil {
t.Fatal("no merged file added")
}
mergedData, err := loadFileByIcebergPath(ctx, client, setup.BucketName, state.DataPath, merged.FilePath())
if err != nil {
t.Fatalf("read merged file: %v", err)
}
ids, _, rowIDs, _ := mergedColumns(t, mergedData)
if len(ids) != 2 || ids[0] != int64(4) || ids[1] != int64(5) {
t.Fatalf("merged ids = %v, want [4 5] (f2 minus its deleted row, f3)", ids)
}
if rowIDs[0] != int64(3) || rowIDs[1] != int64(4) {
t.Fatalf("merged _row_id = %v, want [3 4]", rowIDs)
if rowIDs[0] != int64(0) || rowIDs[1] != int64(3) || rowIDs[2] != int64(4) {
t.Fatalf("merged _row_id = %v, want [0 3 4]", rowIDs)
}
}
// Detection applies the same exclusion compaction does: a table whose only
// binable files are all covered by deletion vectors is not a candidate, while
// unaffected files still qualify.
func TestDetectSchedulesDeletionVector(t *testing.T) {
spec := *iceberg.UnpartitionedSpec
snapID := int64(1)
// A table reloaded with DELETE + INSERT: the old file is wholly deleted by its
// vector, the new one is alone. min_input_files is not met, yet the old file
// and its vector leave the table, without the old file being read (it is not
// even in the store here), and the new file is untouched.
func TestCompactDropsWhollyDeletedFile(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "new.parquet", []lineageDataRow{{1, "a"}, {2, "b"}, {3, "c"}})
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dvDataEntry(t, "old.parquet", 3), dvDataEntry(t, "new.parquet", 3)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/old.parquet", 0, 1, 2)},
0, 6)
dataEntry := func(name string, count int64) iceberg.ManifestEntry {
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, spec, name, count))
config := Config{TargetFileSizeBytes: 4096, MinInputFiles: 10, ApplyDeletes: true, DeleteRatioThresholdPercent: 30}
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
dvEntry := func(t *testing.T, ref string) iceberg.ManifestEntry {
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentPosDeletes,
"data/dv.puffin", iceberg.PuffinFile, map[int]any{}, nil, nil, 0, 12)
if !strings.Contains(result, "compacted 1 files into 0") {
t.Fatalf("unexpected result: %q", result)
}
data, deletes := liveFiles(t, client, setup)
if len(data) != 1 || data[0].FilePath() != "data/new.parquet" {
t.Fatalf("live data files = %v, want only data/new.parquet", data)
}
if len(deletes) != 0 {
t.Fatalf("live delete files = %d, want 0 (the vector leaves with its file)", len(deletes))
}
}
// A file past the ratio is rewritten alone; one under it, or one whose vector
// does not decode, is left exactly as it was (never merged without its deletes).
func TestCompactDeleteRatio(t *testing.T) {
rows := []lineageDataRow{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}
config := Config{TargetFileSizeBytes: 4096, MinInputFiles: 10, ApplyDeletes: true, DeleteRatioThresholdPercent: 30}
t.Run("past the ratio", func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "f1.parquet", rows)
writeV3Table(t, fs, setup, []iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 4)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/f1.parquet", 1, 3)}, 0, 4)
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 1 files into 1") {
t.Fatalf("unexpected result: %q", result)
}
data, deletes := liveFiles(t, client, setup)
if len(data) != 1 || len(deletes) != 0 || data[0].Count() != 2 {
t.Fatalf("live data %v, deletes %d; want one 2-row file and no delete files", data, len(deletes))
}
ids, rowIDs := readLiveRows(t, client, setup, data[0])
if len(ids) != 2 || ids[0] != int64(1) || ids[1] != int64(3) || rowIDs[0] != int64(0) || rowIDs[1] != int64(2) {
t.Fatalf("rows = %v / _row_id %v, want ids [1 3] row ids [0 2]", ids, rowIDs)
}
})
// the count says every row, the positions say otherwise: rewritten, never dropped
t.Run("count covers the file, positions do not", func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "f1.parquet", rows[:3])
writeV3Table(t, fs, setup, []iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 3)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/f1.parquet", 0, 1, 5)}, 0, 3)
if _, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil); err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
data, _ := liveFiles(t, client, setup)
if len(data) != 1 {
t.Fatalf("live data files = %v, want the rewritten file holding row 3", data)
}
if ids, _ := readLiveRows(t, client, setup, data[0]); len(ids) != 1 || ids[0] != int64(3) {
t.Fatalf("rows = %v, want [3]", ids)
}
})
// a partly deleted file past the target size is not read whole into memory: left as it is
t.Run("past the target size", func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "f1.parquet", rows)
writeV3Table(t, fs, setup, []iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 4)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/f1.parquet", 1, 3)}, 0, 4)
small := config
small.TargetFileSizeBytes = 512 // the entry says 1024 bytes
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), small, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if strings.Contains(result, "compacted") {
t.Fatalf("unexpected compaction: %q", result)
}
})
untouched := func(t *testing.T, positions []uint64, corrupt bool) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "f1.parquet", rows)
dvEntry := putDeletionVector(t, fs, setup, "dv.puffin", "data/f1.parquet", positions...)
if corrupt {
e := fs.getEntry(dvTestDataDir, "dv.puffin")
e.Content[len(e.Content)-1] ^= 0xff // CRC no longer matches
}
writeV3Table(t, fs, setup, []iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 4)},
[]iceberg.ManifestEntry{dvEntry}, 0, 4)
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if strings.Contains(result, "compacted") {
t.Fatalf("unexpected compaction: %q", result)
}
data, deletes := liveFiles(t, client, setup)
if len(data) != 1 || data[0].FilePath() != "data/f1.parquet" || len(deletes) != 1 {
t.Fatalf("live data %v, deletes %d; want f1 and its vector unchanged", data, len(deletes))
}
}
t.Run("under the ratio", func(t *testing.T) { untouched(t, []uint64{2}, false) })
t.Run("vector does not decode", func(t *testing.T) { untouched(t, []uint64{0, 1, 2}, true) })
}
// Two vectors in one Puffin file (Spark writes them so): compacting the file
// one covers removes that vector only; the other file keeps its vector, and
// its deleted row stays deleted.
func TestCompactSharedPuffinKeepsOtherVector(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
rows := []lineageDataRow{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}
putDataFileRows(t, fs, "fa.parquet", rows)
putDataFileRows(t, fs, "fb.parquet", rows)
blob := func(positions ...uint64) []byte {
b := dv.NewRoaringPositionBitmap()
for _, p := range positions {
b.Set(p)
}
out, err := dv.SerializeDV(b)
if err != nil {
t.Fatalf("serialize dv: %v", err)
}
return out
}
ba, bb := blob(1, 3), blob(0)
content := append(append([]byte("PFA1"), ba...), bb...)
fs.putEntry(dvTestDataDir, "shared.puffin", &filer_pb.Entry{Name: "shared.puffin", Content: content})
vector := func(ref string, count, offset int64, b []byte) iceberg.ManifestEntry {
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentPosDeletes,
setup.fileRef("data", "shared.puffin"), iceberg.PuffinFile, map[int]any{}, nil, nil, count, int64(len(content)))
if err != nil {
t.Fatalf("build dv file: %v", err)
}
dfb.ReferencedDataFile(ref)
dfb.ReferencedDataFile(ref).ContentOffset(offset).ContentSizeInBytes(int64(len(b)))
snapID := int64(1)
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
}
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dvDataEntry(t, "fa.parquet", 4), dvDataEntry(t, "fb.parquet", 4)},
[]iceberg.ManifestEntry{vector("data/fa.parquet", 2, 4, ba), vector("data/fb.parquet", 1, int64(4+len(ba)), bb)},
0, 8)
config := Config{TargetFileSizeBytes: 4096, MinInputFiles: 10, ApplyDeletes: true, DeleteRatioThresholdPercent: 30}
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 1 files into 1") {
t.Fatalf("unexpected result: %q (fa alone past the ratio, fb under it)", result)
}
data, deletes := liveFiles(t, client, setup)
var fbLive bool
for _, df := range data {
fbLive = fbLive || df.FilePath() == "data/fb.parquet"
}
if !fbLive || len(data) != 2 {
t.Fatalf("live data %v, want fb and fa's rewrite", data)
}
if len(deletes) != 1 || deletes[0].ReferencedDataFile() == nil || *deletes[0].ReferencedDataFile() != "data/fb.parquet" {
t.Fatalf("live delete files %v, want fb's vector only", deletes)
}
}
// Detection proposes the reloaded table although min_input_files is not met,
// and does not when the ratio selection is off.
func TestDetectSchedulesDeletionVector(t *testing.T) {
config := Config{
SnapshotRetentionMs: hoursToMs(24 * 365),
MaxSnapshotsToKeep: 10,
TargetFileSizeBytes: 4096,
MinInputFiles: 2,
MinInputFiles: 10,
Operations: "compact",
ApplyDeletes: true,
}
t.Run("unaffected files stay eligible", func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dataEntry("data/f1.parquet", 1), dataEntry("data/f2.parquet", 1), dataEntry("data/f3.parquet", 1)},
[]iceberg.ManifestEntry{dvEntry(t, "data/f1.parquet")},
0, 3)
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), client, config, "", "", "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
if len(tables) != 1 {
t.Fatalf("expected 1 compaction candidate (f2+f3 still binable), got %d", len(tables))
}
})
t.Run("all binable files covered", func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dataEntry("data/f1.parquet", 1), dataEntry("data/f2.parquet", 1)},
[]iceberg.ManifestEntry{dvEntry(t, "data/f1.parquet")},
0, 2)
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), client, config, "", "", "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
if len(tables) != 0 {
t.Fatalf("expected no candidates (only the covered f1 and the lone f2 remain), got %d", len(tables))
}
})
for _, tc := range []struct {
name string
threshold int64
want int
}{{"ratio on", 30, 1}, {"ratio off", 0, 0}} {
t.Run(tc.name, func(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dvDataEntry(t, "old.parquet", 3), dvDataEntry(t, "new.parquet", 3)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/old.parquet", 0, 1, 2)},
0, 6)
cfg := config
cfg.DeleteRatioThresholdPercent = tc.threshold
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), client, cfg, "", "", "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
if len(tables) != tc.want {
t.Fatalf("candidates = %d, want %d", len(tables), tc.want)
}
})
}
}
// writeV3Table stores a format-version-3 table in the fake filer: a data
@@ -373,3 +524,209 @@ func writeV3Table(t *testing.T, fs *fakeFilerServer, setup tableSetup,
}
func ptrInt64(v int64) *int64 { return &v }
func TestReadDeletionVectorBlobPastTheEnd(t *testing.T) {
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentPosDeletes,
"data/dv.puffin", iceberg.PuffinFile, map[int]any{}, nil, nil, 1, 8)
if err != nil {
t.Fatalf("build dv file: %v", err)
}
dfb.ReferencedDataFile("data/f1.parquet").ContentOffset(math.MaxInt64).ContentSizeInBytes(2)
cache := map[string][]byte{"data/dv.puffin": make([]byte, 8)}
if _, err := readDeletionVector(context.Background(), nil, "test-bucket", "ns/tbl", dfb.Build(), cache); err == nil {
t.Fatal("blob past the end of the Puffin file was accepted")
}
}
func TestCompactionPlanningConfigHashCoversApplyDeletes(t *testing.T) {
on := Config{ApplyDeletes: true, DeleteRatioThresholdPercent: 30}
off := on
off.ApplyDeletes = false
if compactionPlanningConfigHash(on) == compactionPlanningConfigHash(off) {
t.Fatal("apply_deletes on and off share a cached compaction plan")
}
}
// Execution skips a table with deletes while apply_deletes is off, so
// detection must not propose it either.
func TestDetectSkipsDeletesWhenApplyDeletesOff(t *testing.T) {
config := Config{
SnapshotRetentionMs: hoursToMs(24 * 365),
MaxSnapshotsToKeep: 10,
TargetFileSizeBytes: 4096,
MinInputFiles: 2,
Operations: "compact",
}
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
writeV3Table(t, fs, setup,
[]iceberg.ManifestEntry{dvDataEntry(t, "a.parquet", 3), dvDataEntry(t, "b.parquet", 3)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/a.parquet", 0)},
0, 6)
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), client, config, "", "", "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
if len(tables) != 0 {
t.Fatalf("candidates = %d, want 0: execution skips this table", len(tables))
}
}
// A drop-only bin reads nothing, so the sort input cap does not apply to it.
func TestSortInputCapKeepsDropOnlyBin(t *testing.T) {
config := Config{SortMaxInputBytes: 100}
plan := &compactionRewritePlan{strategy: "sort"}
bins := filterCompactionBinsByPlan([]compactionBin{
{TotalSize: 1000, DropOnly: true},
{TotalSize: 1000},
}, config, plan)
if len(bins) != 1 || !bins[0].DropOnly {
t.Fatalf("bins = %+v, want only the drop-only bin", bins)
}
}
// Under the sort input cap, delete-heavy files pack by their input bytes too:
// two half-deleted 75-byte files fit a 100-byte cap by live bytes, but not
// together by the bytes the merge reads.
func TestDeleteHeavyBinsKeepSortInputCap(t *testing.T) {
dvs := &deletionVectorSet{cardinality: map[string]int64{}, entries: map[string]iceberg.ManifestEntry{}}
var entries []iceberg.ManifestEntry
for _, name := range []string{"a.parquet", "b.parquet"} {
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData, "data/"+name,
iceberg.ParquetFile, map[int]any{}, nil, nil, 4, 75)
if err != nil {
t.Fatalf("build data file: %v", err)
}
snapID := int64(1)
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build()))
key, err := normalizeIcebergPath("data/"+name, "test-bucket", "ns/tbl")
if err != nil {
t.Fatal(err)
}
dvs.cardinality[key] = 2
}
bins, err := buildDeleteHeavyBins(entries, dvs, 100, 100, nil, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("buildDeleteHeavyBins: %v", err)
}
for _, bin := range bins {
if bin.TotalSize > 100 {
t.Fatalf("bin reads %d bytes, past the 100-byte sort input cap", bin.TotalSize)
}
}
if len(bins) != 2 {
t.Fatalf("bins = %d, want 2", len(bins))
}
}
// 29 of 50 rows is exactly 58%: a float share (29.0/50*100 = 57.99...) missed it.
func TestSplitDeleteHeavyAtExactThreshold(t *testing.T) {
snapID := int64(1)
entry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil,
mustDataFile(t, *iceberg.UnpartitionedSpec, "data/a.parquet", 50))
key, err := normalizeIcebergPath("data/a.parquet", "test-bucket", "ns/tbl")
if err != nil {
t.Fatal(err)
}
dvs := &deletionVectorSet{cardinality: map[string]int64{key: 29}}
heavy, _, err := splitDeleteHeavy([]iceberg.ManifestEntry{entry}, dvs, 58, 4096, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("splitDeleteHeavy: %v", err)
}
if len(heavy) != 1 {
t.Fatal("a file deleted exactly at the threshold was not selected")
}
}
// Delete-heavy files merge in the order of their bounds, not manifest order.
func TestDeleteHeavyBinsFollowBounds(t *testing.T) {
meta, err := table.NewMetadata(newTestSchema(), iceberg.UnpartitionedSpec, table.UnsortedSortOrder, "s3://test-bucket/ns/tbl", nil)
if err != nil {
t.Fatalf("create metadata: %v", err)
}
dvs := &deletionVectorSet{cardinality: map[string]int64{}}
var entries []iceberg.ManifestEntry
for _, f := range []struct {
name string
lo, hi int64
}{{"c.parquet", 20, 29}, {"a.parquet", 0, 9}, {"b.parquet", 10, 19}} {
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData, "data/"+f.name,
iceberg.ParquetFile, map[int]any{}, nil, nil, 10, 100)
if err != nil {
t.Fatalf("build data file: %v", err)
}
lo, _ := iceberg.Int64Literal(f.lo).MarshalBinary()
hi, _ := iceberg.Int64Literal(f.hi).MarshalBinary()
dfb.LowerBoundValues(map[int][]byte{1: lo}).UpperBoundValues(map[int][]byte{1: hi})
snapID := int64(1)
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build()))
key, err := normalizeIcebergPath("data/"+f.name, "test-bucket", "ns/tbl")
if err != nil {
t.Fatal(err)
}
dvs.cardinality[key] = 5
}
bins, err := buildDeleteHeavyBins(entries, dvs, 4096, 0, meta, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("buildDeleteHeavyBins: %v", err)
}
if len(bins) != 1 || len(bins[0].Entries) != 3 {
t.Fatalf("bins = %+v, want one bin of 3 files", bins)
}
for i, want := range []string{"data/a.parquet", "data/b.parquet", "data/c.parquet"} {
if got := bins[0].Entries[i].DataFile().FilePath(); got != want {
t.Fatalf("file %d = %s, want %s", i, got, want)
}
}
}
// A covered file at the target size enters no bin, so its vector is not read.
func TestCompactSkipsVectorOfFileAtTargetSize(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "test-bucket", Namespace: "ns", TableName: "tbl"}
putDataFileRows(t, fs, "f1.parquet", []lineageDataRow{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}})
writeV3Table(t, fs, setup, []iceberg.ManifestEntry{dvDataEntry(t, "f1.parquet", 4)},
[]iceberg.ManifestEntry{putDeletionVector(t, fs, setup, "dv.puffin", "data/f1.parquet", 1)}, 0, 4)
var read bool
fs.beforeLookup = func(_ *fakeFilerServer, req *filer_pb.LookupDirectoryEntryRequest) {
if req.Name == "dv.puffin" {
read = true
}
}
config := Config{TargetFileSizeBytes: 512, MinInputFiles: 2, ApplyDeletes: true} // the entry says 1024 bytes
if _, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil); err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if read {
t.Fatal("read the vector of a file no bin can take")
}
}
// A file whose count says every row is deleted but whose positions do not is
// rewritten, and packs by its whole size rather than by zero live bytes.
func TestDeleteHeavyBinsCountWholeFileWhenPositionsDisagree(t *testing.T) {
dvs := &deletionVectorSet{cardinality: map[string]int64{}, positions: map[string][]int64{}}
var entries []iceberg.ManifestEntry
for _, name := range []string{"a.parquet", "b.parquet"} {
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData, "data/"+name,
iceberg.ParquetFile, map[int]any{}, nil, nil, 4, 75)
if err != nil {
t.Fatalf("build data file: %v", err)
}
snapID := int64(1)
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build()))
key, err := normalizeIcebergPath("data/"+name, "test-bucket", "ns/tbl")
if err != nil {
t.Fatal(err)
}
dvs.cardinality[key] = 4
dvs.positions[key] = []int64{4, 5, 6, 7}
}
bins, err := buildDeleteHeavyBins(entries, dvs, 100, 0, nil, "test-bucket", "ns/tbl")
if err != nil {
t.Fatalf("buildDeleteHeavyBins: %v", err)
}
if len(bins) != 2 || bins[0].DropOnly || bins[1].DropOnly {
t.Fatalf("bins = %+v, want two rewrite bins of one file each", bins)
}
}
+18 -6
View File
@@ -466,6 +466,10 @@ func hasEligibleCompaction(
specIDs := make(map[int32]struct{})
for _, mf := range manifests {
if mf.ManifestContent() != iceberg.ManifestContentData {
if !config.ApplyDeletes {
// execution skips a table with deletes while apply_deletes is off
return false, nil
}
continue
}
dataManifests = append(dataManifests, mf)
@@ -482,7 +486,7 @@ func hasEligibleCompaction(
schema := meta.CurrentSchema()
var allEntries []iceberg.ManifestEntry
var dvPaths map[string]bool
var dvs *deletionVectorSet
for _, mf := range dataManifests {
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
if err != nil {
@@ -512,15 +516,14 @@ func hasEligibleCompaction(
}
deleteEntries = append(deleteEntries, entries...)
}
if dvPaths, err = deletionVectorPaths(deleteEntries, bucketName, dataPath); err != nil {
if dvs, err = indexDeletionVectors(deleteEntries, bucketName, dataPath); err != nil {
return false, err
}
}
candidateEntries, err := excludeDeletionVectorFiles(allEntries, dvPaths, bucketName, dataPath)
if err != nil {
return false, err
}
// Planning reads no vector: a vector's manifest record_count is its
// cardinality, which is all the delete ratio needs.
candidateEntries := allEntries
if predicate != nil {
filtered := make([]iceberg.ManifestEntry, 0, len(candidateEntries))
for _, entry := range candidateEntries {
@@ -544,8 +547,17 @@ func hasEligibleCompaction(
return false, fmt.Errorf("resolve rewrite strategy: %w", err)
}
heavyEntries, candidateEntries, err := splitDeleteHeavy(candidateEntries, dvs, config.DeleteRatioThresholdPercent, compactionTargetSizeForPlan(config, rewritePlan), bucketName, dataPath)
if err != nil {
return false, err
}
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles, meta)
heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, bucketName, dataPath)
if err != nil {
return false, err
}
bins = append(bins, heavyBins...)
bins = filterCompactionBinsByPlan(bins, config, rewritePlan)
return len(bins) > 0, nil
}
+1
View File
@@ -1772,6 +1772,7 @@ func TestDetectSchedulesCompactionWithDeleteManifestPresent(t *testing.T) {
TargetFileSizeBytes: 4096,
MinInputFiles: 2,
Operations: "compact",
ApplyDeletes: true,
}
tables, err := handler.scanTablesForMaintenance(context.Background(), client, config, "", "", "", 0)
+48 -37
View File
@@ -186,6 +186,15 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_BOOL,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TOGGLE,
},
{
Name: "delete_ratio_threshold_percent",
Label: "Delete Ratio Threshold (%)",
Description: "A data file whose deletion vector deletes at least this share of its rows is rewritten with its deletes applied, alone if need be, whatever Min Input Files says; a file with every row deleted is dropped without being read. 0 turns this off.",
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
MaxValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 100}},
},
{
Name: "rewrite_strategy",
Label: "Rewrite Strategy",
@@ -328,25 +337,26 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
},
},
DefaultValues: map[string]*plugin_pb.ConfigValue{
"target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultTargetFileSizeMB}},
"min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinInputFiles}},
"delete_target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteTargetFileSizeMB}},
"delete_min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMinInputFiles}},
"delete_max_file_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxGroupSizeMB}},
"delete_max_output_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxOutputFiles}},
"min_manifests_to_rewrite": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinManifestsToRewrite}},
"snapshot_retention_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSnapshotRetentionHours}},
"max_snapshots_to_keep": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxSnapshotsToKeep}},
"orphan_older_than_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultOrphanOlderThanHours}},
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"sort_buffer_rows": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSortBufferRows}},
"sort_spill_dir": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultTargetFileSizeMB}},
"min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinInputFiles}},
"delete_ratio_threshold_percent": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteRatioThresholdPercent}},
"delete_target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteTargetFileSizeMB}},
"delete_min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMinInputFiles}},
"delete_max_file_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxGroupSizeMB}},
"delete_max_output_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxOutputFiles}},
"min_manifests_to_rewrite": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinManifestsToRewrite}},
"snapshot_retention_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSnapshotRetentionHours}},
"max_snapshots_to_keep": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxSnapshotsToKeep}},
"orphan_older_than_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultOrphanOlderThanHours}},
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"sort_buffer_rows": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSortBufferRows}},
"sort_spill_dir": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
},
},
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
@@ -362,24 +372,25 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
ExecutionTimeoutSeconds: 3600,
},
WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{
"target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultTargetFileSizeMB}},
"min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinInputFiles}},
"delete_target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteTargetFileSizeMB}},
"delete_min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMinInputFiles}},
"delete_max_file_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxGroupSizeMB}},
"delete_max_output_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxOutputFiles}},
"snapshot_retention_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSnapshotRetentionHours}},
"max_snapshots_to_keep": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxSnapshotsToKeep}},
"orphan_older_than_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultOrphanOlderThanHours}},
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"sort_buffer_rows": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSortBufferRows}},
"sort_spill_dir": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultTargetFileSizeMB}},
"min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinInputFiles}},
"delete_ratio_threshold_percent": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteRatioThresholdPercent}},
"delete_target_file_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteTargetFileSizeMB}},
"delete_min_input_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMinInputFiles}},
"delete_max_file_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxGroupSizeMB}},
"delete_max_output_files": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDeleteMaxOutputFiles}},
"snapshot_retention_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSnapshotRetentionHours}},
"max_snapshots_to_keep": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxSnapshotsToKeep}},
"orphan_older_than_hours": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultOrphanOlderThanHours}},
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"sort_buffer_rows": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSortBufferRows}},
"sort_spill_dir": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
},
}
}
+2 -2
View File
@@ -172,8 +172,8 @@ func (idx *planningIndex) rewriteManifestsEligible(config Config) (bool, bool) {
}
func compactionPlanningConfigHash(config Config) string {
return fmt.Sprintf("target=%d|min=%d|strategy=%s|sortcap=%d",
config.TargetFileSizeBytes, config.MinInputFiles,
return fmt.Sprintf("target=%d|min=%d|delratio=%d|applydeletes=%t|strategy=%s|sortcap=%d",
config.TargetFileSizeBytes, config.MinInputFiles, config.DeleteRatioThresholdPercent, config.ApplyDeletes,
config.RewriteStrategy, config.SortMaxInputBytes)
}
+11 -2
View File
@@ -128,14 +128,23 @@ func compactionTargetSizeForPlan(config Config, plan *compactionRewritePlan) int
return targetSize
}
func filterCompactionBinsByPlan(bins []compactionBin, config Config, plan *compactionRewritePlan) []compactionBin {
// compactionInputCapForPlan is the most input bytes one sorted bin may read; 0 = no cap.
func compactionInputCapForPlan(config Config, plan *compactionRewritePlan) int64 {
if plan == nil || plan.strategy != "sort" || config.SortMaxInputBytes <= 0 {
return 0
}
return config.SortMaxInputBytes
}
func filterCompactionBinsByPlan(bins []compactionBin, config Config, plan *compactionRewritePlan) []compactionBin {
inputCap := compactionInputCapForPlan(config, plan)
if inputCap <= 0 {
return bins
}
filtered := make([]compactionBin, 0, len(bins))
for _, bin := range bins {
if bin.TotalSize <= config.SortMaxInputBytes {
if bin.DropOnly || bin.TotalSize <= inputCap {
filtered = append(filtered, bin)
}
}