Files
seaweedfs/weed/worker/tasks/iceberg/deletion_vector.go
T
81f9231e2f iceberg compact: optional spatial clustering of geometry tables (#13135)
* iceberg compact: optional spatial clustering of geometry tables

Compaction of an Iceberg v3 table with a geometry column merges files in
manifest order (bin-pack) or by a declared sort order. Neither keeps nearby
geometries together: after a bin-pack every output file and row group spans
the whole extent of the table, so a reader can skip nothing by the geometry
bounds and row-group geospatial statistics. In one measurement a point lookup
on a table of places read 4.59 MB after bin-pack compaction and 0.55 MB after
a spatial one. A declared sort order cannot express this either: Iceberg v3
has no spatial sort transform, a geometry cannot be a sort source, and DuckDB
refuses INSERTs into a table that declares a sort order.

This adds an opt-in spatial order to the compaction job.

Spatial clustering (`spatial_clustering`, off by default). When on, a v3
table with no declared sort order and exactly one top-level geometry column
is rewritten in the Hilbert order of each row's bounding-box centre, whatever
`rewrite_strategy` says (a declared sort order is still honoured, since such a
table does not qualify):

- The 62-bit key (31 bits per axis) is computed from the WKB while the rows
  stream through the merge, carried as an extra last column through
  parquet-go's sorting writer into a temporary file in `sort_spill_dir`, and
  dropped when a plain writer copies the rows to the output. Row lineage is
  mapped before the key is added. The grid is the globe for a lon/lat CRS and
  the union of the bin's file bounds for a projected one. Null, empty and
  unreadable geometries sort last. The key only orders rows; pruning stays on
  the geometry bounds, so a poor key costs speed, never results.
- Files are listed by the key of their bound's centre before binning, so the
  bins of one partition cover compact areas.
- Row groups target `spatial_row_group_size_mb` (2 MB, capped by the table's
  `write.parquet.row-group-size-bytes`, at least 16 rows; an explicit
  `write.parquet.row-group-limit` still wins). A row group is what a spatial
  filter skips, and a row of a large polygon can be tens of kilobytes.
- A bin the order cannot be laid over (a projected column whose files carry
  no bounds, a geometry column the merge cannot find, e.g. after a rename in
  files without field ids) is bin-packed in bin-pack row groups.
- The table property `seaweedfs.compaction.spatial-column` names the column
  when a table has several, or opts a table out with `none`.
- The snapshot summary records `rewrite-strategy=spatial` and
  `spatial-column`, or `binpack` when every bin fell back, and
  `spatial-fallback-bins` when some did. The planning
  index's config hash covers the new settings.

Open time partitions (`spatial_hold_open_partitions`, default true, and
`spatial_open_partition_grace_minutes`, default 120; both only matter with
spatial clustering on). A spatially ordered partition has every row group
spanning its whole time range. On a day of vehicle positions, "where is every
vehicle now" read 2.51 MB of the spatially compacted day against 0.04 MB of
the files as written, while an area query on a closed day read 2.74 MB
against 19.35 MB. So a day or hour partition is left in write order until it
has ended plus the grace (late batches still land in it), and is ordered in
space after that. The job and detection hold the same bins; the planning
index caches its answer only until the first held partition is released, so
a table nobody writes to after midnight still gets its last day ordered.
Coarser time partitions and the other strategies are unchanged.

`github.com/twpayne/go-geom` (already in the module graph) becomes a direct
requirement for its WKB parser.

Tests:

- spatial_order_test.go: the Hilbert curve, plan resolution (version, sort
  order, one or several geometry columns, the property, opt-out), 2,400
  scattered points compacted end to end in spatial order with row ids kept
  and no key column written, the job setting off as control, nulls last, a
  projected CRS with and without file bounds, file ordering, and the
  row-group sizing.
- spatial_fallback_test.go: the bin-pack fallback uses bin-pack row groups;
  a geometry column the merge cannot find falls back, with the summary
  saying so.
- spatial_open_test.go: partition ends for day and hour across the value
  types a manifest reader returns and far from 1970; the hold, the grace and
  their controls; the planning index release time and config hash; on the
  fake filer, a day-partitioned geometry table where the job compacts the
  past day in spatial order and leaves today's files, a table of only today
  commits nothing, and the index records midnight UTC plus the grace (each
  with the hold off as control); spatial clustering is off by default.
- Mutation checks: a constant key fails the spatial order tests; disabling
  the hold fails four open-partition tests.
- go vet and go test (also with -race) of weed/worker/tasks/iceberg pass;
  go build ./weed passes.

* iceberg compact: give the spatial sort key a name no table column has

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

* iceberg compact: report spatial order only for bins it wrote

A bin skipped after a read or merge error no longer counts as
spatially ordered in the snapshot summary or the job result.

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

* iceberg compact: do not hold an open partition the spatial order cannot cover

A projected geometry column whose files carry no bounds is bin-packed,
so holding its open day or hour partition only left small files behind.

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

* iceberg compact: do not hold a drop-only bin in an open partition

A bin whose rows are all deleted removes its files and writes nothing, so
there is no spatial rewrite for an open day or hour partition to wait for.

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

* iceberg compact: pack delete-heavy files in the spatial file order

Delete-heavy bins took the table's order while the other bins of a spatial
plan list their files by the Hilbert key of their geometry bounds, so a
partition split into several delete-heavy bins merged overlapping areas.

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>
2026-11-30 10:51:16 -08:00

389 lines
14 KiB
Go

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
// plan's file order, like buildPlannedCompactionBins, 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, plan *compactionRewritePlan, 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)
}
compactionOrderFor(meta, g.rewrite, plan).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
}