From 81f9231e2f9023d4956f393869207c394e60efc6 Mon Sep 17 00:00:00 2001 From: Javier de la Torre Date: Mon, 30 Nov 2026 19:51:16 +0100 Subject: [PATCH] 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 * 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 * 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 * 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 * 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 --------- Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- go.mod | 2 +- weed/worker/tasks/iceberg/compact.go | 170 +++++- weed/worker/tasks/iceberg/compact_order.go | 6 + weed/worker/tasks/iceberg/config.go | 21 + weed/worker/tasks/iceberg/deletion_vector.go | 8 +- .../tasks/iceberg/deletion_vector_test.go | 6 +- weed/worker/tasks/iceberg/detection.go | 50 +- weed/worker/tasks/iceberg/geometry_bounds.go | 14 + .../tasks/iceberg/geometry_fixture_test.go | 54 +- weed/worker/tasks/iceberg/handler.go | 116 ++-- weed/worker/tasks/iceberg/planning_index.go | 20 +- weed/worker/tasks/iceberg/sort_strategy.go | 23 +- .../tasks/iceberg/spatial_fallback_test.go | 106 ++++ weed/worker/tasks/iceberg/spatial_open.go | 97 ++++ .../worker/tasks/iceberg/spatial_open_test.go | 314 ++++++++++ weed/worker/tasks/iceberg/spatial_order.go | 280 +++++++++ .../tasks/iceberg/spatial_order_test.go | 549 ++++++++++++++++++ weed/worker/tasks/iceberg/spatial_spool.go | 90 +++ 18 files changed, 1833 insertions(+), 93 deletions(-) create mode 100644 weed/worker/tasks/iceberg/spatial_fallback_test.go create mode 100644 weed/worker/tasks/iceberg/spatial_open.go create mode 100644 weed/worker/tasks/iceberg/spatial_open_test.go create mode 100644 weed/worker/tasks/iceberg/spatial_order.go create mode 100644 weed/worker/tasks/iceberg/spatial_order_test.go create mode 100644 weed/worker/tasks/iceberg/spatial_spool.go diff --git a/go.mod b/go.mod index d017ddaade..0aabdbe168 100644 --- a/go.mod +++ b/go.mod @@ -99,6 +99,7 @@ require ( github.com/tikv/client-go/v2 v2.0.7 github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365 github.com/twmb/avro v1.9.0 + github.com/twpayne/go-geom v1.6.1 github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43 github.com/valyala/bytebufferpool v1.0.0 github.com/viant/ptrie v1.0.1 @@ -434,7 +435,6 @@ require ( github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect github.com/twmb/murmur3 v1.1.8 // indirect - github.com/twpayne/go-geom v1.6.1 // indirect github.com/twpayne/go-kml/v3 v3.2.1 // indirect github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/ulikunitz/xz v0.5.15 // indirect diff --git a/weed/worker/tasks/iceberg/compact.go b/weed/worker/tasks/iceberg/compact.go index ea9c4d48ff..6873f4ea21 100644 --- a/weed/worker/tasks/iceberg/compact.go +++ b/weed/worker/tasks/iceberg/compact.go @@ -237,15 +237,20 @@ func (h *Handler) compactDataFiles( // files in the order of their bounds so the merged file keeps the // 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) + bins := buildPlannedCompactionBins(candidateEntries, targetSize, minInputFiles, meta, rewritePlan) + heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, rewritePlan, bucketName, dataPath) if err != nil { return "", nil, err } bins = append(bins, heavyBins...) initialBinCount := len(bins) bins = filterCompactionBinsByPlan(bins, config, rewritePlan) + beforeHold := len(bins) + bins, _ = holdOpenTimePartitions(bins, specsByID, rewritePlan, config, time.Now()) if len(bins) == 0 { + if beforeHold > 0 { + return fmt.Sprintf("no files eligible for compaction: %d bin(s) in open time partitions, left in write order until they close", beforeHold), nil, nil + } return compactionNoEligibleMessage(config, rewritePlan, initialBinCount), nil, nil } @@ -272,6 +277,8 @@ func (h *Handler) compactDataFiles( var deletedManifestEntries []iceberg.ManifestEntry var summary snapshotSummary totalMerged := 0 + // written bins of a spatial plan: in spatial order, and bin-packed because the order could not be laid over them + spatialBins, spatialFallbackBins := 0, 0 entrySeqNum := func(entry iceberg.ManifestEntry) *int64 { seqNum := entry.SequenceNum() @@ -348,7 +355,8 @@ func (h *Handler) compactDataFiles( var mergedData []byte var recordCount int64 - rowGroupRows := rowsPerRowGroup(bin, config) + fellBack := false + rowGroupRows := rowsPerRowGroupFor(bin, config, rewritePlan) // Only the equality deletes of the bin's partition (or unpartitioned // ones) apply to it. When that cannot be told, the bin is left as it // is rather than merged without deletes that may apply. @@ -357,8 +365,16 @@ func (h *Handler) compactDataFiles( glog.Warningf("iceberg compact: bin %d (%d files) not compacted: %v", binIdx, len(bin.Entries), scopeErr) goto binDone } - if rewritePlan != nil && rewritePlan.strategy == "sort" { + if rewritePlan.sorts() { mergedData, recordCount, err = mergeParquetFilesSorted(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, binEqDeleteGroups, schema, rewritePlan, rowGroupRows, lineage) + // a bin the spatial order cannot be laid over (a projected column + // whose files carry no bounds, a geometry column the merge cannot + // find) is bin-packed, in bin-pack row groups + if errors.Is(err, errSpatialOrderUnavailable) { + glog.V(1).Infof("iceberg compact: bin %d bin-packed: %v", binIdx, err) + fellBack = true + mergedData, recordCount, err = mergeParquetFiles(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, binEqDeleteGroups, schema, rowsPerRowGroup(bin, config), lineage) + } } else { mergedData, recordCount, err = mergeParquetFiles(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, binEqDeleteGroups, schema, rowGroupRows, lineage) } @@ -449,6 +465,11 @@ func (h *Handler) compactDataFiles( // Mark original entries as deleted removeBinEntries(bin) + if fellBack { + spatialFallbackBins++ + } else { + spatialBins++ + } } binDone: @@ -631,6 +652,17 @@ func (h *Handler) compactDataFiles( if rewritePlan != nil && rewritePlan.strategy == "sort" { newSnapshot.Summary.Properties["sort-fields"] = rewritePlan.summaryLabel() } + if rewritePlan != nil && rewritePlan.spatial != nil { + // the summary says what was written: a run whose every bin fell back is a bin-pack + if spatialBins > 0 { + newSnapshot.Summary.Properties["spatial-column"] = rewritePlan.spatial.column + } else { + newSnapshot.Summary.Properties["rewrite-strategy"] = "binpack" + } + if spatialFallbackBins > 0 { + newSnapshot.Summary.Properties["spatial-fallback-bins"] = fmt.Sprintf("%d", spatialFallbackBins) + } + } setRowLineage(newSnapshot, version, firstRowID, addedRows) if err := builder.AddSnapshot(newSnapshot); err != nil { return err @@ -649,7 +681,7 @@ func (h *Handler) compactDataFiles( MetricDurationMs: time.Since(start).Milliseconds(), } result := fmt.Sprintf("compacted %d files into %d (across %d bins)", totalMerged, len(newManifestEntries), len(bins)) - if rewritePlan != nil && rewritePlan.strategy == "sort" { + if rewritePlan.sorts() && (rewritePlan.spatial == nil || spatialBins > 0) { result = fmt.Sprintf("%s using %s", result, rewritePlan.summaryLabel()) } return result, metrics, nil @@ -665,6 +697,13 @@ func (h *Handler) compactDataFiles( // the files keep manifest order and an oversized partition is packed // largest-first. func buildCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minFiles int, meta table.Metadata) []compactionBin { + return buildPlannedCompactionBins(entries, targetSize, minFiles, meta, nil) +} + +// buildPlannedCompactionBins is buildCompactionBins for a rewrite plan: a +// spatial plan lists each group's files by the Hilbert key of their geometry +// bound (spatial_order.go) instead of the table's order. +func buildPlannedCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minFiles int, meta table.Metadata, plan *compactionRewritePlan) []compactionBin { if minFiles < 2 { minFiles = 2 } @@ -706,7 +745,7 @@ func buildCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minF if len(bin.Entries) < minFiles { continue } - order := resolveCompactionOrder(meta, bin.Entries) + order := compactionOrderFor(meta, bin.Entries, plan) order.sortEntries(bin.Entries) if bin.TotalSize <= targetSize { result = append(result, *bin) @@ -1201,6 +1240,45 @@ func rowsPerRowGroup(bin compactionBin, config Config) int64 { return rows } +// rowsPerRowGroupFor is rowsPerRowGroup for the plan: a spatial rewrite +// targets the smaller spatial row group size (capped by the table's +// write.parquet.row-group-size-bytes), with a floor of minSpatialRowGroupRows +// rows instead of minRowGroupRows, since a row group is what a spatial filter +// skips and a row of a large polygon can be tens of kilobytes (5,210 +// administrative areas in 3 row groups read 377 MB per point lookup, in 82 +// row groups of 64 rows 62 MB). A configured row limit still wins, as it does +// for rowsPerRowGroup. +func rowsPerRowGroupFor(bin compactionBin, config Config, plan *compactionRewritePlan) int64 { + if plan == nil || plan.strategy != rewriteStrategySpatial { + return rowsPerRowGroup(bin, config) + } + rows := config.RowGroupRowLimit + explicit := rows > 0 + if !explicit { + rows = defaultRowGroupRowLimit + } + sizeBytes := config.SpatialRowGroupSizeBytes + if sizeBytes <= 0 { + sizeBytes = defaultSpatialRowGroupSizeMB * bytesPerMB + } + if config.RowGroupSizeBytes > 0 && config.RowGroupSizeBytes < sizeBytes { + sizeBytes = config.RowGroupSizeBytes + } + var totalRows int64 + for _, entry := range bin.Entries { + totalRows += entry.DataFile().Count() + } + if totalRows > 0 && bin.TotalSize > 0 { + bytesPerRow := max(bin.TotalSize/totalRows, 1) + estimated := max(sizeBytes/bytesPerRow, minSpatialRowGroupRows) + rows = min(rows, estimated) + } + if !explicit { + rows = max(rows, minSpatialRowGroupRows) + } + return rows +} + // mergeParquetFiles reads multiple small Parquet files and merges them into // a single Parquet file, optionally filtering out rows matching position or // equality deletes. Files are processed one at a time to keep memory usage @@ -1556,9 +1634,18 @@ func mergeParquetFilesSorted( if len(entries) == 0 { return nil, 0, fmt.Errorf("no entries to merge") } - if rewritePlan == nil || rewritePlan.strategy != "sort" { + if !rewritePlan.sorts() { return nil, 0, fmt.Errorf("sorted merge requires sort rewrite plan") } + spatial := rewritePlan.strategy == rewriteStrategySpatial && rewritePlan.spatial != nil + var extent geoBox4 + if spatial { + var ok bool + if extent, ok = rewritePlan.spatial.extent(entries); !ok { + // a projected column whose files carry no geometry bounds: nothing to lay the grid over + return nil, 0, fmt.Errorf("%w: no geometry bounds on the bin's files", errSpatialOrderUnavailable) + } + } firstData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, entries[0].DataFile().FilePath()) if err != nil { @@ -1584,10 +1671,31 @@ func mergeParquetFilesSorted( outputSchema = layout.schema } - sortingColumns, err := rewritePlan.parquetSortingColumns(outputSchema) - if err != nil { - firstReader.Close() - return nil, 0, fmt.Errorf("resolve parquet sorting columns: %w", err) + // The spatial order sorts by a key computed from each row's geometry, + // carried as an extra last column through the sort and dropped on the way + // to the output (spatial_order.go, spatial_spool.go). + sortSchema := outputSchema + var keyer *spatialKeyer + keyColumn := 0 + var sortingColumns []parquet.SortingColumn + if spatial { + col := geometryLeafIndex(outputSchema, rewritePlan.spatial.fieldID, rewritePlan.spatial.column) + if col < 0 { + // e.g. files without field ids whose geometry column was renamed since: the caller bin-packs the bin + firstReader.Close() + return nil, 0, fmt.Errorf("%w: no geometry column %q in %s", errSpatialOrderUnavailable, rewritePlan.spatial.column, entries[0].DataFile().FilePath()) + } + keyer = &spatialKeyer{column: col, extent: extent} + keyColumn = len(outputSchema.Columns()) + var keyName string + sortSchema, keyName = keyedSchema(outputSchema) + sortingColumns = []parquet.SortingColumn{parquet.Ascending(keyName)} + } else { + sortingColumns, err = rewritePlan.parquetSortingColumns(outputSchema) + if err != nil { + firstReader.Close() + return nil, 0, fmt.Errorf("resolve parquet sorting columns: %w", err) + } } resolvedEqGroups, err := resolveEqualityDeleteGroupsForSchema(parquetSchema, eqDeleteGroups, icebergSchema) @@ -1613,7 +1721,20 @@ func mergeParquetFilesSorted( } var outputBuf bytes.Buffer - writer := parquet.NewSortingWriter[any](&outputBuf, sortBufferRows, outputSchema, + // The spatial key must not reach the output: a spatial merge sorts into a + // temporary file and a plain writer writes the output from it without the + // key (spatial_spool.go). + var sortedOut io.Writer = &outputBuf + var spool *sortSpool + if keyer != nil { + if spool, err = newSortSpool(spillDir); err != nil { + firstReader.Close() + return nil, 0, err + } + defer spool.remove() + sortedOut = spool.file + } + writer := parquet.NewSortingWriter[any](sortedOut, sortBufferRows, sortSchema, parquet.MaxRowsPerRowGroup(rowGroupRows), parquet.SortingWriterConfig( parquet.SortingColumns(sortingColumns...), @@ -1629,9 +1750,29 @@ func mergeParquetFilesSorted( } }() + var keyed []parquet.Row + var keyedValues []parquet.Value // backing store of keyed, reused per batch: the writer copies the values it is handed writeRows := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (_ int64, err error) { defer recoverRead(&err, entry.DataFile().FilePath()) return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, resolvedEqGroups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error { + if keyer != nil { + // the key goes after each row's values in a buffer of our own, never into the reader's or the mapper's + need := 0 + for _, row := range filtered { + need += len(row) + 1 + } + if cap(keyedValues) < need { + keyedValues = make([]parquet.Value, 0, need) + } + keyedValues, keyed = keyedValues[:0], keyed[:0] + for _, row := range filtered { + start := len(keyedValues) + keyedValues = append(keyedValues, row...) + keyedValues = append(keyedValues, parquet.Int64Value(keyer.key(row)).Level(0, 0, keyColumn)) + keyed = append(keyed, parquet.Row(keyedValues[start:len(keyedValues):len(keyedValues)])) + } + filtered = keyed + } // The writer's row buffer copies the values it is handed, so these // rows need no cloning out of the reader's own buffer first. _, writeErr := writer.WriteRows(filtered) @@ -1677,6 +1818,11 @@ func mergeParquetFilesSorted( } closed = true + if spool != nil { + if err := spool.copyTo(ctx, &outputBuf, outputSchema, rowGroupRows); err != nil { + return nil, 0, err + } + } return outputBuf.Bytes(), totalRows, nil } diff --git a/weed/worker/tasks/iceberg/compact_order.go b/weed/worker/tasks/iceberg/compact_order.go index ffda8acc73..6432b6e612 100644 --- a/weed/worker/tasks/iceberg/compact_order.go +++ b/weed/worker/tasks/iceberg/compact_order.go @@ -20,6 +20,9 @@ type compactionOrder struct { // table's declared sort order; runs it cannot form may still merge by // size since contiguous ranges are a preference, not a requirement. bestEffort bool + // set: files are ordered by the Hilbert key of their geometry bound's + // centre (spatial_order.go) + spatial *spatialFileKey } func resolveCompactionOrder(meta table.Metadata, entries []iceberg.ManifestEntry) *compactionOrder { @@ -92,6 +95,9 @@ func (o *compactionOrder) coversEntries(entries []iceberg.ManifestEntry) bool { // key is the bound a file is ordered by: its lower bound on the column for an // ascending order, its upper bound for a descending one. func (o *compactionOrder) key(entry iceberg.ManifestEntry) (iceberg.Literal, bool) { + if o.spatial != nil { + return o.spatial.of(entry) + } df := entry.DataFile() raw := df.LowerBoundValues()[o.fieldID] if o.descending { diff --git a/weed/worker/tasks/iceberg/config.go b/weed/worker/tasks/iceberg/config.go index b286bcbb66..9b3edcdbe2 100644 --- a/weed/worker/tasks/iceberg/config.go +++ b/weed/worker/tasks/iceberg/config.go @@ -34,6 +34,11 @@ const ( defaultMinManifestsToRewrite = 5 minManifestsToRewrite = 2 defaultOperations = "all" + // a spatial rewrite's row groups: small enough that an area query skips most of a file + defaultSpatialRowGroupSizeMB = 2 + minSpatialRowGroupRows = 16 + // a closed day or hour partition still takes late batches for a while: its spatial rewrite waits + defaultSpatialOpenPartitionGraceMinutes = 120 // Metric keys returned by maintenance operations. MetricFilesMerged = "files_merged" @@ -139,6 +144,14 @@ type Config struct { // properties; zero means the default. RowGroupSizeBytes int64 RowGroupRowLimit int64 + // SpatialClustering (off by default) writes a v3 table with one geometry column and no declared sort order in the + // spatial order of its geometries (spatial_order.go), in row groups of about SpatialRowGroupSizeBytes. + SpatialClustering bool + SpatialRowGroupSizeBytes int64 + // SpatialHoldOpenPartitions leaves a day or hour partition in write (time) order until it has closed and + // SpatialOpenPartitionGrace has passed (spatial_open.go). + SpatialHoldOpenPartitions bool + SpatialOpenPartitionGrace time.Duration } // ParseConfig extracts an iceberg maintenance Config from plugin config values. @@ -165,6 +178,14 @@ func ParseConfig(values map[string]*plugin_pb.ConfigValue) Config { SortMaxInputBytes: readSizeMBConfig(values, "sort_max_input_mb", 0), SortBufferRows: readInt64Config(values, "sort_buffer_rows", defaultSortBufferRows), SortSpillDir: strings.TrimSpace(readStringConfig(values, "sort_spill_dir", "")), + SpatialClustering: readBoolConfig(values, "spatial_clustering", false), + SpatialRowGroupSizeBytes: readSizeMBConfig(values, "spatial_row_group_size_mb", defaultSpatialRowGroupSizeMB), + SpatialHoldOpenPartitions: readBoolConfig(values, "spatial_hold_open_partitions", true), + SpatialOpenPartitionGrace: time.Duration(readInt64Config(values, "spatial_open_partition_grace_minutes", + defaultSpatialOpenPartitionGraceMinutes)) * time.Minute, + } + if cfg.SpatialOpenPartitionGrace < 0 { + cfg.SpatialOpenPartitionGrace = 0 } // Clamp the fields that are always defaulted by worker config parsing. diff --git a/weed/worker/tasks/iceberg/deletion_vector.go b/weed/worker/tasks/iceberg/deletion_vector.go index 3b9ec42995..5468ecdbf2 100644 --- a/weed/worker/tasks/iceberg/deletion_vector.go +++ b/weed/worker/tasks/iceberg/deletion_vector.go @@ -202,10 +202,10 @@ func splitDeleteHeavy(entries []iceberg.ManifestEntry, dvs *deletionVectorSet, t // 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). +// 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, bucketName, dataPath string) ([]compactionBin, error) { + meta table.Metadata, plan *compactionRewritePlan, bucketName, dataPath string) ([]compactionBin, error) { type group struct { drop compactionBin rewrite []iceberg.ManifestEntry @@ -250,7 +250,7 @@ func buildDeleteHeavyBins(entries []iceberg.ManifestEntry, dvs *deletionVectorSe if len(g.drop.Entries) > 0 { bins = append(bins, g.drop) } - resolveCompactionOrder(meta, g.rewrite).sortEntries(g.rewrite) + compactionOrderFor(meta, g.rewrite, plan).sortEntries(g.rewrite) var cur compactionBin var curLive int64 flush := func() { diff --git a/weed/worker/tasks/iceberg/deletion_vector_test.go b/weed/worker/tasks/iceberg/deletion_vector_test.go index e41a06da89..a3539b5eb8 100644 --- a/weed/worker/tasks/iceberg/deletion_vector_test.go +++ b/weed/worker/tasks/iceberg/deletion_vector_test.go @@ -605,7 +605,7 @@ func TestDeleteHeavyBinsKeepSortInputCap(t *testing.T) { } dvs.cardinality[key] = 2 } - bins, err := buildDeleteHeavyBins(entries, dvs, 100, 100, nil, "test-bucket", "ns/tbl") + bins, err := buildDeleteHeavyBins(entries, dvs, 100, 100, nil, nil, "test-bucket", "ns/tbl") if err != nil { t.Fatalf("buildDeleteHeavyBins: %v", err) } @@ -666,7 +666,7 @@ func TestDeleteHeavyBinsFollowBounds(t *testing.T) { } dvs.cardinality[key] = 5 } - bins, err := buildDeleteHeavyBins(entries, dvs, 4096, 0, meta, "test-bucket", "ns/tbl") + bins, err := buildDeleteHeavyBins(entries, dvs, 4096, 0, meta, nil, "test-bucket", "ns/tbl") if err != nil { t.Fatalf("buildDeleteHeavyBins: %v", err) } @@ -722,7 +722,7 @@ func TestDeleteHeavyBinsCountWholeFileWhenPositionsDisagree(t *testing.T) { dvs.cardinality[key] = 4 dvs.positions[key] = []int64{4, 5, 6, 7} } - bins, err := buildDeleteHeavyBins(entries, dvs, 100, 0, nil, "test-bucket", "ns/tbl") + bins, err := buildDeleteHeavyBins(entries, dvs, 100, 0, nil, nil, "test-bucket", "ns/tbl") if err != nil { t.Fatalf("buildDeleteHeavyBins: %v", err) } diff --git a/weed/worker/tasks/iceberg/detection.go b/weed/worker/tasks/iceberg/detection.go index 0c3672a43d..131630b85d 100644 --- a/weed/worker/tasks/iceberg/detection.go +++ b/weed/worker/tasks/iceberg/detection.go @@ -453,13 +453,28 @@ func hasEligibleCompaction( meta table.Metadata, predicate *partitionPredicate, ) (bool, error) { + eligible, _, err := compactionEligibility(ctx, filerClient, bucketName, dataPath, manifests, config, meta, predicate) + return eligible, err +} + +// compactionEligibility is hasEligibleCompaction plus when the first open time partition it held back +// (spatial_open.go) is released: the planning index caches the answer only until then. +func compactionEligibility( + ctx context.Context, + filerClient filer_pb.SeaweedFilerClient, + bucketName, dataPath string, + manifests []iceberg.ManifestFile, + config Config, + meta table.Metadata, + predicate *partitionPredicate, +) (bool, time.Time, error) { if len(manifests) == 0 { - return false, nil + return false, time.Time{}, nil } minInputFiles, err := compactionMinInputFiles(config.MinInputFiles) if err != nil { - return false, err + return false, time.Time{}, err } var dataManifests []iceberg.ManifestFile @@ -468,7 +483,7 @@ func hasEligibleCompaction( if mf.ManifestContent() != iceberg.ManifestContentData { if !config.ApplyDeletes { // execution skips a table with deletes while apply_deletes is off - return false, nil + return false, time.Time{}, nil } continue } @@ -476,10 +491,10 @@ func hasEligibleCompaction( specIDs[mf.PartitionSpecID()] = struct{}{} } if len(dataManifests) == 0 { - return false, nil + return false, time.Time{}, nil } if len(specIDs) > 1 { - return false, nil + return false, time.Time{}, nil } specsByID := specByID(meta) @@ -490,11 +505,11 @@ func hasEligibleCompaction( for _, mf := range dataManifests { manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath()) if err != nil { - return false, fmt.Errorf("read manifest %s: %w", mf.FilePath(), err) + return false, time.Time{}, fmt.Errorf("read manifest %s: %w", mf.FilePath(), err) } entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema) if err != nil { - return false, fmt.Errorf("parse manifest %s: %w", mf.FilePath(), err) + return false, time.Time{}, fmt.Errorf("parse manifest %s: %w", mf.FilePath(), err) } allEntries = append(allEntries, entries...) } @@ -508,16 +523,16 @@ func hasEligibleCompaction( } manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath()) if err != nil { - return false, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err) + return false, time.Time{}, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err) } entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema) if err != nil { - return false, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err) + return false, time.Time{}, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err) } deleteEntries = append(deleteEntries, entries...) } if dvs, err = indexDeletionVectors(deleteEntries, bucketName, dataPath); err != nil { - return false, err + return false, time.Time{}, err } } @@ -533,7 +548,7 @@ func hasEligibleCompaction( } match, err := predicate.Matches(spec, entry.DataFile().Partition()) if err != nil { - return false, err + return false, time.Time{}, err } if match { filtered = append(filtered, entry) @@ -544,22 +559,23 @@ func hasEligibleCompaction( rewritePlan, err := resolveCompactionRewritePlan(config, meta) if err != nil { - return false, fmt.Errorf("resolve rewrite strategy: %w", err) + return false, time.Time{}, 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 + return false, time.Time{}, err } targetSize := compactionTargetSizeForPlan(config, rewritePlan) - bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles, meta) - heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, bucketName, dataPath) + bins := buildPlannedCompactionBins(candidateEntries, targetSize, minInputFiles, meta, rewritePlan) + heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, rewritePlan, bucketName, dataPath) if err != nil { - return false, err + return false, time.Time{}, err } bins = append(bins, heavyBins...) bins = filterCompactionBinsByPlan(bins, config, rewritePlan) - return len(bins) > 0, nil + bins, release := holdOpenTimePartitions(bins, specsByID, rewritePlan, config, time.Now()) + return len(bins) > 0, release, nil } func compactionMinInputFiles(minInputFiles int64) (int, error) { diff --git a/weed/worker/tasks/iceberg/geometry_bounds.go b/weed/worker/tasks/iceberg/geometry_bounds.go index 34789c7d2d..f5c53c3ab0 100644 --- a/weed/worker/tasks/iceberg/geometry_bounds.go +++ b/weed/worker/tasks/iceberg/geometry_bounds.go @@ -69,3 +69,17 @@ func encodeGeometryPoint(x, y float64) []byte { binary.LittleEndian.PutUint64(b[8:], math.Float64bits(y)) return b } + +// decodeGeoPoint reads the (x, y) of a v3 geometry bound; false for anything +// else. +func decodeGeoPoint(b []byte) (x, y float64, ok bool) { + if len(b) < 16 { + return 0, 0, false + } + x = math.Float64frombits(binary.LittleEndian.Uint64(b)) + y = math.Float64frombits(binary.LittleEndian.Uint64(b[8:])) + if math.IsNaN(x) || math.IsNaN(y) || math.IsInf(x, 0) || math.IsInf(y, 0) { + return 0, 0, false + } + return x, y, true +} diff --git a/weed/worker/tasks/iceberg/geometry_fixture_test.go b/weed/worker/tasks/iceberg/geometry_fixture_test.go index 3e5966f0e8..450f5e62cb 100644 --- a/weed/worker/tasks/iceberg/geometry_fixture_test.go +++ b/weed/worker/tasks/iceberg/geometry_fixture_test.go @@ -26,8 +26,10 @@ import ( // geometry bounds of each file, as DuckDB writes them. const ( - geoTestIDField = 1 - geoTestGeomField = 2 + geoTestIDField = 1 + geoTestGeomField = 2 + geoTestDayField = 3 // geoTableOptions.dayPartitioned only + geoTestDayPartitionField = 1000 // its day partition field ) func wkbPoint(x, y float64) []byte { @@ -83,7 +85,11 @@ type geoRow struct { type geoFile struct { Name string Rows []geoRow - ParquetCRSSet bool // declare the default CRS in the Parquet logical type + ParquetCRSSet bool // declare the default CRS in the Parquet logical type + NoBounds bool // the manifest entry records no geometry bounds + GeomName string // the Parquet name of the geometry column ("" = geom) + NoFieldIDs bool // write no field ids (readers then match columns by name) + Day int32 // the file's day partition (days since the epoch) when the table is dayPartitioned } type geoTableOptions struct { @@ -93,6 +99,9 @@ type geoTableOptions struct { properties iceberg.Properties // fixup, when set, rewrites each input file after it is written fixup func(t *testing.T, data []byte) []byte + // dayPartitioned adds an optional date column the files do not carry and partitions the table by day of it, as a + // streaming table is often partitioned by day(ts); each file's partition is its Day + dayPartitioned bool } func geoTestSchema(geomType iceberg.Type) *iceberg.Schema { @@ -104,14 +113,23 @@ func geoTestSchema(geomType iceberg.Type) *iceberg.Schema { func writeGeoParquet(t *testing.T, rows []geoRow, crs string) []byte { t.Helper() - schema := parquet.NewSchema("table", parquet.Group{ - "id": parquet.FieldID(parquet.Compressed(parquet.Int(64), &zstd.Codec{}), geoTestIDField), - "geom": parquet.FieldID(parquet.Compressed(parquet.Optional(parquet.Geometry(crs)), &zstd.Codec{}), geoTestGeomField), - }) + return writeGeoParquetWith(t, rows, crs, "geom", true) +} + +// writeGeoParquetWith is writeGeoParquet with the geometry column's Parquet +// name and, optionally, no field ids. +func writeGeoParquetWith(t *testing.T, rows []geoRow, crs, geomName string, fieldIDs bool) []byte { + t.Helper() + id := parquet.Compressed(parquet.Int(64), &zstd.Codec{}) + geom := parquet.Compressed(parquet.Optional(parquet.Geometry(crs)), &zstd.Codec{}) + if fieldIDs { + id, geom = parquet.FieldID(id, geoTestIDField), parquet.FieldID(geom, geoTestGeomField) + } + schema := parquet.NewSchema("table", parquet.Group{"id": id, geomName: geom}) geomCol, idCol := -1, -1 for i, p := range schema.Columns() { switch strings.Join(p, ".") { - case "geom": + case geomName: geomCol = i case "id": idCol = i @@ -190,6 +208,12 @@ func populateGeoTable(t *testing.T, fs *fakeFilerServer, setup tableSetup, files } schema := geoTestSchema(geomType) spec := *iceberg.UnpartitionedSpec + if opt.dayPartitioned { + schema = iceberg.NewSchema(0, append(schema.Fields(), + iceberg.NestedField{ID: geoTestDayField, Type: iceberg.PrimitiveTypes.Date, Name: "day", Required: false})...) + spec = iceberg.NewPartitionSpecID(0, iceberg.PartitionField{SourceIDs: []int{geoTestDayField}, FieldID: geoTestDayPartitionField, + Name: "day_day", Transform: iceberg.DayTransform{}}) + } location := "s3://" + setup.BucketName + "/" + setup.dataPath() props := iceberg.Properties{"format-version": "3"} for k, v := range opt.properties { @@ -218,12 +242,20 @@ func populateGeoTable(t *testing.T, fs *fakeFilerServer, setup tableSetup, files if f.ParquetCRSSet && crs == "" { crs = iceberg.DefaultGeoCRS } - data := writeGeoParquet(t, f.Rows, crs) + geomName := f.GeomName + if geomName == "" { + geomName = "geom" + } + data := writeGeoParquetWith(t, f.Rows, crs, geomName, !f.NoFieldIDs) if opt.fixup != nil && !f.ParquetCRSSet { data = opt.fixup(t, data) } putFile(dataDir, f.Name, data) - dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, setup.fileRef("data", f.Name), iceberg.ParquetFile, map[int]any{}, nil, nil, int64(len(f.Rows)), int64(len(data))) + partition := map[int]any{} + if opt.dayPartitioned { + partition[geoTestDayPartitionField] = iceberg.Date(f.Day) + } + dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, setup.fileRef("data", f.Name), iceberg.ParquetFile, partition, nil, nil, int64(len(f.Rows)), int64(len(data))) if err != nil { t.Fatalf("data file %s: %v", f.Name, err) } @@ -233,7 +265,7 @@ func populateGeoTable(t *testing.T, fs *fakeFilerServer, setup tableSetup, files } lower := map[int][]byte{geoTestIDField: geoLE64(lo)} upper := map[int][]byte{geoTestIDField: geoLE64(hi)} - if xmin, ymin, xmax, ymax, ok := footerGeoBox(t, data); ok { + if xmin, ymin, xmax, ymax, ok := footerGeoBox(t, data); ok && !f.NoBounds { lower[geoTestGeomField], upper[geoTestGeomField] = xyBound(xmin, ymin), xyBound(xmax, ymax) } dfb.LowerBoundValues(lower) diff --git a/weed/worker/tasks/iceberg/handler.go b/weed/worker/tasks/iceberg/handler.go index b68d40df30..1b1ab7b863 100644 --- a/weed/worker/tasks/iceberg/handler.go +++ b/weed/worker/tasks/iceberg/handler.go @@ -218,6 +218,36 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor { FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING, Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT, }, + { + Name: "spatial_clustering", + Label: "Spatial Clustering", + Description: "Write a format-version 3 table with one geometry column and no declared sort order in the Hilbert order of its geometries, so readers skip files and row groups by location. The table property seaweedfs.compaction.spatial-column names the column when there are several, or opts the table out with none. Off by default.", + FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_BOOL, + Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TOGGLE, + }, + { + Name: "spatial_hold_open_partitions", + Label: "Hold Open Time Partitions", + Description: "With spatial clustering, leave a day or hour partition in the order it was written until it has closed (plus the grace below), then order it in space: a spatially ordered partition answers area queries, a time-ordered one the newest rows, which is what an open partition is asked for.", + FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_BOOL, + Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TOGGLE, + }, + { + Name: "spatial_open_partition_grace_minutes", + Label: "Open Partition Grace (minutes)", + Description: "How long after a day or hour partition ends its spatial rewrite waits for late rows.", + 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}}, + }, + { + Name: "spatial_row_group_size_mb", + Label: "Spatial Row Group Size (MB)", + Description: "Approximate compressed size of one row group of a spatially ordered file; the table property write.parquet.row-group-size-bytes caps it. Small row groups are what a spatial filter skips.", + 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: 1}}, + }, { Name: "sort_max_input_mb", Label: "Sort Max Input (MB)", @@ -337,26 +367,30 @@ 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_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: ""}}, + "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: ""}}, + "spatial_clustering": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: false}}, + "spatial_row_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSpatialRowGroupSizeMB}}, + "spatial_hold_open_partitions": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}}, + "spatial_open_partition_grace_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSpatialOpenPartitionGraceMinutes}}, + "where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}}, }, }, AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{ @@ -372,25 +406,29 @@ 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_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: ""}}, + "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: ""}}, + "spatial_clustering": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: false}}, + "spatial_row_group_size_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSpatialRowGroupSizeMB}}, + "spatial_hold_open_partitions": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}}, + "spatial_open_partition_grace_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultSpatialOpenPartitionGraceMinutes}}, + "where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}}, }, } } diff --git a/weed/worker/tasks/iceberg/planning_index.go b/weed/worker/tasks/iceberg/planning_index.go index 0a1f8072b7..7dac30bd92 100644 --- a/weed/worker/tasks/iceberg/planning_index.go +++ b/weed/worker/tasks/iceberg/planning_index.go @@ -30,6 +30,9 @@ type planningIndex struct { type planningIndexCompaction struct { ConfigHash string `json:"configHash"` Eligible bool `json:"eligible"` + // RecheckAfterMs: an open time partition was held back (spatial_open.go) and is released then; past it the cached answer + // is stale even when the table has not changed + RecheckAfterMs int64 `json:"recheckAfterMs,omitempty"` } type planningIndexRewriteManifests struct { @@ -158,6 +161,9 @@ func (idx *planningIndex) compactionEligible(config Config) (bool, bool) { if idx.Compaction.ConfigHash != compactionPlanningConfigHash(config) { return false, false } + if idx.Compaction.RecheckAfterMs > 0 && time.Now().UnixMilli() >= idx.Compaction.RecheckAfterMs { + return false, false + } return idx.Compaction.Eligible, true } @@ -172,9 +178,14 @@ func (idx *planningIndex) rewriteManifestsEligible(config Config) (bool, bool) { } func compactionPlanningConfigHash(config Config) string { - return fmt.Sprintf("target=%d|min=%d|delratio=%d|applydeletes=%t|strategy=%s|sortcap=%d", + // The open-partition hold and grace change which bins are eligible, and so does the spatial plan (its sort cap and + // file order), so a cached answer must not survive a change of any of them. A change of the table property + // seaweedfs.compaction.spatial-column is not seen here: the index is keyed on the snapshot, so that waits for the + // next write. + return fmt.Sprintf("target=%d|min=%d|delratio=%d|applydeletes=%t|strategy=%s|sortcap=%d|hold=%t|grace=%d|spatial=%t", config.TargetFileSizeBytes, config.MinInputFiles, config.DeleteRatioThresholdPercent, config.ApplyDeletes, - config.RewriteStrategy, config.SortMaxInputBytes) + config.RewriteStrategy, config.SortMaxInputBytes, + config.SpatialHoldOpenPartitions, int64(config.SpatialOpenPartitionGrace/time.Second), config.SpatialClustering) } func operationRequested(ops []string, wanted string) bool { @@ -226,7 +237,7 @@ func buildPlanningIndexFromManifests( } if operationRequested(ops, "compact") { - eligible, err := hasEligibleCompaction(ctx, filerClient, bucketName, dataPath, manifests, config, meta, nil) + eligible, release, err := compactionEligibility(ctx, filerClient, bucketName, dataPath, manifests, config, meta, nil) if err != nil { return nil, err } @@ -234,6 +245,9 @@ func buildPlanningIndexFromManifests( ConfigHash: compactionPlanningConfigHash(config), Eligible: eligible, } + if !release.IsZero() { + index.Compaction.RecheckAfterMs = release.UnixMilli() + } } if operationRequested(ops, "rewrite_manifests") { diff --git a/weed/worker/tasks/iceberg/sort_strategy.go b/weed/worker/tasks/iceberg/sort_strategy.go index 37db38ca0e..9f8d87c073 100644 --- a/weed/worker/tasks/iceberg/sort_strategy.go +++ b/weed/worker/tasks/iceberg/sort_strategy.go @@ -13,6 +13,8 @@ import ( type compactionRewritePlan struct { strategy string sortFields []compactionSortField + // set for the spatial strategy (spatial_order.go) + spatial *spatialPlan // Carried on the plan so the merge does not need the whole Config. bufferRows int64 spillDir string @@ -29,6 +31,13 @@ func resolveCompactionRewritePlan(config Config, meta table.Metadata) (*compacti if strategy == "" { strategy = defaultRewriteStrategy } + // A v3 table with one geometry column and no declared sort order is written in spatial order whatever the + // strategy (spatial_order.go); a declared sort order is honoured as before. + if strategy == defaultRewriteStrategy || strategy == rewriteStrategyAuto || strategy == "sort" { + if sp := resolveSpatialPlan(config, meta); sp != nil { + return &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: sp, bufferRows: config.SortBufferRows, spillDir: config.SortSpillDir}, nil + } + } if strategy == defaultRewriteStrategy { return &compactionRewritePlan{strategy: defaultRewriteStrategy}, nil } @@ -120,9 +129,14 @@ func resolveCompactionSortFields(meta table.Metadata) ([]compactionSortField, er return fields, nil } +// sorts reports whether the plan sorts rows (sort or spatial): the sort input cap applies to both. +func (p *compactionRewritePlan) sorts() bool { + return p != nil && (p.strategy == "sort" || p.strategy == rewriteStrategySpatial) +} + func compactionTargetSizeForPlan(config Config, plan *compactionRewritePlan) int64 { targetSize := config.TargetFileSizeBytes - if plan != nil && plan.strategy == "sort" && config.SortMaxInputBytes > 0 && config.SortMaxInputBytes < targetSize { + if plan.sorts() && config.SortMaxInputBytes > 0 && config.SortMaxInputBytes < targetSize { return config.SortMaxInputBytes } return targetSize @@ -130,7 +144,7 @@ func compactionTargetSizeForPlan(config Config, plan *compactionRewritePlan) int // 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 { + if !plan.sorts() || config.SortMaxInputBytes <= 0 { return 0 } return config.SortMaxInputBytes @@ -152,13 +166,16 @@ func filterCompactionBinsByPlan(bins []compactionBin, config Config, plan *compa } func compactionNoEligibleMessage(config Config, plan *compactionRewritePlan, initialBinCount int) string { - if plan != nil && plan.strategy == "sort" && config.SortMaxInputBytes > 0 && initialBinCount > 0 { + if plan.sorts() && config.SortMaxInputBytes > 0 && initialBinCount > 0 { return fmt.Sprintf("no files eligible for sorted compaction within %d MB sort input cap", config.SortMaxInputBytes/bytesPerMB) } return "no files eligible for compaction" } func (p *compactionRewritePlan) summaryLabel() string { + if p != nil && p.strategy == rewriteStrategySpatial && p.spatial != nil { + return fmt.Sprintf("spatial (%s)", p.spatial.column) + } if p == nil || p.strategy != "sort" { return defaultRewriteStrategy } diff --git a/weed/worker/tasks/iceberg/spatial_fallback_test.go b/weed/worker/tasks/iceberg/spatial_fallback_test.go new file mode 100644 index 0000000000..91112e5c1a --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_fallback_test.go @@ -0,0 +1,106 @@ +package iceberg + +import ( + "bytes" + "path" + "strings" + "testing" + + "github.com/apache/iceberg-go" + "github.com/parquet-go/parquet-go" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" +) + +// A bin the spatial order cannot be laid over is bin-packed. + +// A projected column whose files carry no bounds is bin-packed in bin-pack row groups, not the spatial ones. +func TestCompactSpatialFallbackUsesBinpackRowGroups(t *testing.T) { + feet, err := iceberg.GeometryTypeOf("EPSG:2913") + if err != nil { + t.Fatal(err) + } + var files []geoFile + for f := 0; f < 3; f++ { + var rows []geoRow + for i := 0; i < 300; i++ { + rows = append(rows, geoRow{ID: int64(f*300 + i), Geom: wkbPoint(7.6e6+float64(i), 6.8e5+float64(f))}) + } + files = append(files, geoFile{Name: "p" + string(rune('a'+f)) + ".parquet", Rows: rows, NoBounds: true}) + } + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + populateGeoTable(t, fs, setup, files, geoTableOptions{icebergType: feet, parquetCRS: "EPSG:2913"}) + // spatial row groups of 1 KB would cut these 900 rows into dozens; bin-pack's default holds them in one + compactGeo(t, client, setup, Config{SpatialClustering: true, SpatialRowGroupSizeBytes: 1024}) + for name, data := range compactedFiles(t, fs, setup) { + f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data))) + if err != nil { + t.Fatal(err) + } + if n := len(f.Metadata().RowGroups); n != 1 { + t.Errorf("%s: %d row groups; the bin-packed fallback should use bin-pack sizing (1)", name, n) + } + if rows := readSpatialOutput(t, data); len(rows) != 900 { + t.Errorf("%s: %d rows, want 900", name, len(rows)) + } + } +} + +// Files without field ids whose geometry column has another name than the table's: the merge cannot find the column +// to order by and bin-packs the bin rather than failing it. +func TestCompactSpatialFallsBackWhenTheGeometryColumnIsNotFound(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + files := fiveGeoFiles() + for i := range files { + files[i].GeomName, files[i].NoFieldIDs = "shape", true + } + populateGeoTable(t, fs, setup, files, geoTableOptions{}) + result := compactGeo(t, client, setup, Config{SpatialClustering: true}) + if !strings.Contains(result, "compacted 5 files into 1") { + t.Fatalf("result %q: the bin was not compacted", result) + } + // the summary says what was written: every bin fell back, so this was a bin-pack + props := currentTableMetadata(t, client, setup).CurrentSnapshot().Summary.Properties + if props["rewrite-strategy"] != "binpack" || props["spatial-column"] != "" || props["spatial-fallback-bins"] != "1" { + t.Errorf("snapshot summary %v", props) + } + for name, data := range compactedFiles(t, fs, setup) { + f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data))) + if err != nil { + t.Fatal(err) + } + if f.NumRows() != 200 { + t.Errorf("%s: %d rows, want 200", name, f.NumRows()) + } + if _, ok := f.Schema().Lookup(spatialKeyColumn); ok { + t.Errorf("%s: a spatial key column was written", name) + } + } +} + +// One bin falls back and the other cannot be read: nothing was written in spatial order, so the summary says bin-pack. +func TestCompactSpatialSummaryCountsOnlyWrittenBins(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + files := scatteredGeoFiles(6, 50, 11) + for i := range files { + files[i].Day = 20000 + if i < 3 { + files[i].Day = 20001 + files[i].GeomName, files[i].NoFieldIDs = "shape", true + } + } + populateGeoTable(t, fs, setup, files, geoTableOptions{dayPartitioned: true}) + dataDir := path.Join(s3tables.TablesPath, setup.BucketName, setup.tablePath(), "data") + fs.putEntry(dataDir, files[3].Name, &filer_pb.Entry{Name: files[3].Name, Content: []byte("not parquet")}) + result := compactGeo(t, client, setup, Config{SpatialClustering: true}) + if !strings.Contains(result, "compacted 3 files into 1 (across 2 bins)") || strings.Contains(result, "spatial") { + t.Fatalf("result %q", result) + } + props := currentTableMetadata(t, client, setup).CurrentSnapshot().Summary.Properties + if props["rewrite-strategy"] != "binpack" || props["spatial-column"] != "" || props["spatial-fallback-bins"] != "1" { + t.Errorf("snapshot summary %v", props) + } +} diff --git a/weed/worker/tasks/iceberg/spatial_open.go b/weed/worker/tasks/iceberg/spatial_open.go new file mode 100644 index 0000000000..0fe1ee5fcc --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_open.go @@ -0,0 +1,97 @@ +package iceberg + +import ( + "math" + "time" + + "github.com/apache/iceberg-go" +) + +// The spatial strategy leaves a time partition that is still open in the order it was written. A spatially compacted partition is ordered by location, so every row group spans all of +// its time range: on a day of vehicle positions (1.44 M rows), "where is every vehicle now" (the last ten minutes) read +// 2.51 MB of the compacted day against 0.04 MB of the rolls as written, while an area query read 2.74 MB against 19.4. +// So a day or hour partition is compacted only once it has closed and SpatialOpenPartitionGrace has passed (late +// batches still land in it): the rolls it holds by then are the bin min_input_files asks for, and the spatial order +// then serves the area questions a closed partition answers. Other strategies are unchanged (bin-pack keeps the +// write order), and so are coarser time partitions (a month would stay uncompacted for a month). + +// timePartitionEnd is when the time range of a partition ends, for the first partition field whose transform is day +// or hour; ok is false when the spec has none (or the value is missing or not a number). +func timePartitionEnd(spec iceberg.PartitionSpec, partition map[int]any) (time.Time, bool) { + for i := 0; i < spec.NumFields(); i++ { + field := spec.Field(i) + var unitSeconds int64 + switch field.Transform.(type) { + case iceberg.DayTransform: + unitSeconds = 86400 + case iceberg.HourTransform: + unitSeconds = 3600 + default: + continue + } + n, ok := partitionOrdinal(partition[field.FieldID]) + // in seconds, not a Duration: nanoseconds overflow outside 1677-2262, and a historical day would be held for + // centuries + if !ok || n >= math.MaxInt64/unitSeconds || n < math.MinInt64/unitSeconds { + continue + } + return time.Unix((n+1)*unitSeconds, 0).UTC(), true + } + return time.Time{}, false +} + +// partitionOrdinal is a day or hour partition value as days or hours since the epoch, however the manifest reader +// typed it. +func partitionOrdinal(v any) (int64, bool) { + switch n := v.(type) { + case iceberg.Date: + return int64(n), true + case int32: + return int64(n), true + case int64: + return n, true + case int: + return int64(n), true + } + return 0, false +} + +// holdOpenTimePartitions drops, under the spatial strategy, the bins of time partitions that have not closed plus +// the grace, and says when the first of them is released (the zero time when none was held): the planning index +// must not cache "nothing to compact" past it, or a table nobody writes to after midnight would keep its last day +// unordered. +func holdOpenTimePartitions(bins []compactionBin, specs map[int]iceberg.PartitionSpec, plan *compactionRewritePlan, + config Config, now time.Time) ([]compactionBin, time.Time) { + if plan == nil || plan.strategy != rewriteStrategySpatial || !config.SpatialHoldOpenPartitions { + return bins, time.Time{} + } + var release time.Time + kept := make([]compactionBin, 0, len(bins)) + for _, bin := range bins { + // a drop-only bin writes nothing, and a bin the order cannot be laid over is bin-packed, in write order: + // nothing to wait for + if bin.DropOnly { + kept = append(kept, bin) + continue + } + if plan.spatial != nil { + if _, ok := plan.spatial.extent(bin.Entries); !ok { + kept = append(kept, bin) + continue + } + } + spec, ok := specs[int(bin.SpecID)] + if ok { + if end, isTime := timePartitionEnd(spec, bin.Partition); isTime { + if at := end.Add(config.SpatialOpenPartitionGrace); now.Before(at) { + if release.IsZero() || at.Before(release) { + release = at + } + continue + } + } + } + kept = append(kept, bin) + } + return kept, release +} diff --git a/weed/worker/tasks/iceberg/spatial_open_test.go b/weed/worker/tasks/iceberg/spatial_open_test.go new file mode 100644 index 0000000000..9fdafe0073 --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_open_test.go @@ -0,0 +1,314 @@ +package iceberg + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/apache/iceberg-go" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +func daySpec() iceberg.PartitionSpec { + return iceberg.NewPartitionSpecID(1, iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1000, Name: "ts_day", Transform: iceberg.DayTransform{}}) +} + +func TestTimePartitionEnd(t *testing.T) { + day := daySpec() + hour := iceberg.NewPartitionSpecID(2, iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1001, Name: "ts_hour", Transform: iceberg.HourTransform{}}) + month := iceberg.NewPartitionSpecID(3, iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1002, Name: "ts_month", Transform: iceberg.MonthTransform{}}) + identity := iceberg.NewPartitionSpecID(4, iceberg.PartitionField{SourceIDs: []int{1}, FieldID: 1003, Name: "route", Transform: iceberg.IdentityTransform{}}) + // day 20731 is 2026-10-05: it ends at 2026-10-06 00:00 UTC, however the manifest reader typed it + want := time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC) + for _, v := range []any{iceberg.Date(20731), int32(20731), int64(20731), 20731} { + if end, ok := timePartitionEnd(day, map[int]any{1000: v}); !ok || !end.Equal(want) { + t.Errorf("day %T(%v): end %v ok %v, want %v", v, v, end, ok, want) + } + } + // far from 1970 the end is still exact: nanoseconds would overflow outside 1677-2262 + for _, d := range []time.Time{time.Date(1600, 6, 1, 0, 0, 0, 0, time.UTC), time.Date(9999, 12, 31, 0, 0, 0, 0, time.UTC)} { + n := int32(d.Unix() / 86400) + if end, ok := timePartitionEnd(day, map[int]any{1000: iceberg.Date(n)}); !ok || !end.Equal(d.AddDate(0, 0, 1)) { + t.Errorf("day %s: end %v ok %v, want %v", d.Format("2006-01-02"), end, ok, d.AddDate(0, 0, 1)) + } + } + if _, ok := timePartitionEnd(day, map[int]any{1000: int64(1) << 62}); ok { + t.Errorf("a day number past any time.Time was given an end") + } + // hour 497544 is 2026-10-05 00:00 UTC: it ends an hour later + if end, ok := timePartitionEnd(hour, map[int]any{1001: int32(497544)}); !ok || !end.Equal(time.Date(2026, 10, 5, 1, 0, 0, 0, time.UTC)) { + t.Errorf("hour: end %v ok %v", end, ok) + } + for name, c := range map[string]struct { + spec iceberg.PartitionSpec + part map[int]any + }{ + "month (coarser than a day)": {month, map[int]any{1002: int32(681)}}, + "identity": {identity, map[int]any{1003: "L1"}}, + "day value missing": {day, map[int]any{}}, + "day value not a number": {day, map[int]any{1000: "2026-10-05"}}, + "unpartitioned": {*iceberg.UnpartitionedSpec, map[int]any{}}, + } { + if _, ok := timePartitionEnd(c.spec, c.part); ok { + t.Errorf("%s: a time partition end was found", name) + } + } +} + +func TestHoldOpenTimePartitions(t *testing.T) { + day := daySpec() + month := iceberg.NewPartitionSpecID(3, iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1002, Name: "ts_month", Transform: iceberg.MonthTransform{}}) + specs := map[int]iceberg.PartitionSpec{1: day, 3: month, 0: *iceberg.UnpartitionedSpec} + now := time.Date(2026, 10, 6, 1, 30, 0, 0, time.UTC) // 01:30 on 2026-10-06 (day 20732) + bins := []compactionBin{ + {PartitionKey: "today", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20732)}}, // open + {PartitionKey: "yesterday", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20731)}}, // closed 90 min ago + {PartitionKey: "older", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20730)}}, // closed a day ago + {PartitionKey: "month", SpecID: 3, Partition: map[int]any{1002: int32(681)}}, // coarser: never held + {PartitionKey: "unpartitioned", SpecID: 0, Partition: map[int]any{}}, + } + spatial := &compactionRewritePlan{strategy: rewriteStrategySpatial} + keys := func(bs []compactionBin) []string { + var out []string + for _, b := range bs { + out = append(out, b.PartitionKey) + } + return out + } + config := Config{SpatialHoldOpenPartitions: true, SpatialOpenPartitionGrace: 2 * time.Hour} + kept, release := holdOpenTimePartitions(bins, specs, spatial, config, now) + // yesterday ended at 00:00 and its grace runs to 02:00: held, and the first released + if got := keys(kept); len(got) != 3 || got[0] != "older" || got[1] != "month" || got[2] != "unpartitioned" { + t.Errorf("kept %v, want [older month unpartitioned]", got) + } + if want := time.Date(2026, 10, 6, 2, 0, 0, 0, time.UTC); !release.Equal(want) { + t.Errorf("release %v, want %v", release, want) + } + // past the grace, yesterday is compacted; today is still held, released at midnight plus the grace + kept, release = holdOpenTimePartitions(bins, specs, spatial, config, now.Add(time.Hour)) + if got := keys(kept); len(got) != 4 || got[0] != "yesterday" { + t.Errorf("past the grace: kept %v", got) + } + if want := time.Date(2026, 10, 7, 2, 0, 0, 0, time.UTC); !release.Equal(want) { + t.Errorf("past the grace: release %v, want %v", release, want) + } + // controls: bin-pack is never held, nor is anything with the hold off + for name, c := range map[string]struct { + plan *compactionRewritePlan + config Config + }{ + "binpack": {&compactionRewritePlan{strategy: defaultRewriteStrategy}, config}, + "no plan": {nil, config}, + "hold off": {spatial, Config{SpatialHoldOpenPartitions: false, SpatialOpenPartitionGrace: 2 * time.Hour}}, + } { + if kept, release := holdOpenTimePartitions(bins, specs, c.plan, c.config, now); len(kept) != len(bins) || !release.IsZero() { + t.Errorf("%s: kept %d of %d bins, release %v", name, len(kept), len(bins), release) + } + } +} + +// A projected column whose files carry no bounds is bin-packed (compact.go), so its open partition is not held. +func TestHoldOpenTimePartitionsSkipsBinsWithoutSpatialExtent(t *testing.T) { + specs := map[int]iceberg.PartitionSpec{1: daySpec()} + now := time.Date(2026, 10, 6, 1, 30, 0, 0, time.UTC) + bins := []compactionBin{{PartitionKey: "today", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20732)}}} + config := Config{SpatialHoldOpenPartitions: true, SpatialOpenPartitionGrace: 2 * time.Hour} + projected := &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: &spatialPlan{fieldID: 2, column: "geom"}} + if kept, release := holdOpenTimePartitions(bins, specs, projected, config, now); len(kept) != 1 || !release.IsZero() { + t.Errorf("projected without bounds: kept %d bins, release %v; want the bin kept", len(kept), release) + } + geographic := &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: &spatialPlan{fieldID: 2, column: "geom", geographic: true}} + if kept, _ := holdOpenTimePartitions(bins, specs, geographic, config, now); len(kept) != 0 { + t.Errorf("geographic: kept %d bins, want the open partition held", len(kept)) + } +} + +// A drop-only bin (every row deleted) writes no file, so an open partition does not hold it back. +func TestHoldOpenTimePartitionsKeepsDropOnlyBins(t *testing.T) { + specs := map[int]iceberg.PartitionSpec{1: daySpec()} + now := time.Date(2026, 10, 6, 1, 30, 0, 0, time.UTC) + config := Config{SpatialHoldOpenPartitions: true, SpatialOpenPartitionGrace: 2 * time.Hour} + plan := &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: &spatialPlan{fieldID: 2, column: "geom", geographic: true}} + bins := []compactionBin{ + {PartitionKey: "today", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20732)}, DropOnly: true}, + {PartitionKey: "today", SpecID: 1, Partition: map[int]any{1000: iceberg.Date(20732)}}, + } + kept, release := holdOpenTimePartitions(bins, specs, plan, config, now) + if len(kept) != 1 || !kept[0].DropOnly { + t.Errorf("kept %+v, want only the drop-only bin", kept) + } + if want := time.Date(2026, 10, 7, 2, 0, 0, 0, time.UTC); !release.Equal(want) { + t.Errorf("release %v, want %v for the held rewrite bin", release, want) + } +} + +// A planning index that held an open partition back answers from its cache only until the partition is released: +// past it, detection recomputes, so a table nobody writes to after midnight still has its last day ordered. +func TestPlanningIndexCompactionRechecksAfterRelease(t *testing.T) { + config := Config{TargetFileSizeBytes: 128 << 20, MinInputFiles: 10, RewriteStrategy: "binpack"} + idx := &planningIndex{Compaction: &planningIndexCompaction{ConfigHash: compactionPlanningConfigHash(config), Eligible: false}} + if eligible, cached := idx.compactionEligible(config); !cached || eligible { + t.Fatalf("control: an index without a release answers from its cache: eligible %v cached %v", eligible, cached) + } + idx.Compaction.RecheckAfterMs = time.Now().Add(time.Hour).UnixMilli() + if _, cached := idx.compactionEligible(config); !cached { + t.Errorf("before the release the cache answers") + } + idx.Compaction.RecheckAfterMs = time.Now().Add(-time.Minute).UnixMilli() + if _, cached := idx.compactionEligible(config); cached { + t.Errorf("past the release the cached answer is stale and must not be used") + } +} + +// Changing the hold or the grace is a different plan for the same snapshot: a cached answer must not survive it. +func TestPlanningConfigHashCoversTheHold(t *testing.T) { + base := Config{TargetFileSizeBytes: 128 << 20, MinInputFiles: 10, RewriteStrategy: "binpack", SpatialHoldOpenPartitions: true, SpatialOpenPartitionGrace: 2 * time.Hour} + off, longer, flat := base, base, base + off.SpatialHoldOpenPartitions = false + longer.SpatialOpenPartitionGrace = 3 * time.Hour + flat.SpatialClustering = !base.SpatialClustering + if h := compactionPlanningConfigHash(base); h == compactionPlanningConfigHash(off) || h == compactionPlanningConfigHash(longer) { + t.Errorf("the hash %q does not change with the hold or the grace", h) + } + if h := compactionPlanningConfigHash(base); h == compactionPlanningConfigHash(flat) { + t.Errorf("the hash %q does not change with spatial_clustering", h) + } + if compactionPlanningConfigHash(base) != compactionPlanningConfigHash(base) { + t.Errorf("control: the hash is not stable") + } +} + +// openDayGeoTable is a spatial-eligible v3 table partitioned by day: three files of today (UTC) and three of a day +// that ended long ago. +func openDayGeoTable(t *testing.T, todayFiles, pastFiles int) (*fakeFilerServer, filer_pb.SeaweedFilerClient, tableSetup, int32) { + t.Helper() + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "positions"} + today := int32(time.Now().UTC().Unix() / 86400) + files := scatteredGeoFiles(todayFiles+pastFiles, 200, 60) + for i := range files { + files[i].Day = today + if i >= todayFiles { + files[i].Day = today - 3 + } + } + populateGeoTable(t, fs, setup, files, geoTableOptions{dayPartitioned: true}) + return fs, client, setup, today +} + +func spatialHoldConfig(hold bool) Config { + return Config{SpatialClustering: true, RowGroupRowLimit: 100, SortBufferRows: minSortBufferRows, + SpatialHoldOpenPartitions: hold, SpatialOpenPartitionGrace: 2 * time.Hour} +} + +// filesByDay counts the table's live data files per day partition, and how many of them compaction wrote. +func filesByDay(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) (all, compacted map[int32]int) { + t.Helper() + all, compacted = map[int32]int{}, map[int32]int{} + for _, e := range currentDataEntries(t, client, setup) { + df := e.DataFile() + n, ok := partitionOrdinal(df.Partition()[geoTestDayPartitionField]) + if !ok { + t.Fatalf("%s: partition %v has no day", df.FilePath(), df.Partition()) + } + all[int32(n)]++ + if strings.Contains(df.FilePath(), "/compact-") { + compacted[int32(n)]++ + } + } + return all, compacted +} + +// The job itself (compactDataFiles) leaves today's partition as written and orders the day that has ended. +func TestCompactLeavesTodaysPartitionInWriteOrder(t *testing.T) { + _, client, setup, today := openDayGeoTable(t, 3, 3) + result := compactGeo(t, client, setup, spatialHoldConfig(true)) + if !strings.Contains(result, "compacted 3 files into 1") || !strings.Contains(result, "spatial (geom)") { + t.Fatalf("result %q, want the past day's 3 files compacted in spatial order", result) + } + all, compacted := filesByDay(t, client, setup) + if all[today] != 3 || compacted[today] != 0 { + t.Errorf("today: %d files, %d compacted; want the 3 rolls untouched", all[today], compacted[today]) + } + if all[today-3] != 1 || compacted[today-3] != 1 { + t.Errorf("the past day: %d files, %d compacted; want 1 compacted file", all[today-3], compacted[today-3]) + } + + // control: with the hold off the same table has both days compacted, so the test can tell + _, client, setup, today = openDayGeoTable(t, 3, 3) + if result := compactGeo(t, client, setup, spatialHoldConfig(false)); !strings.Contains(result, "compacted 6 files into 2") { + t.Fatalf("hold off: result %q, want both days compacted", result) + } + if all, compacted := filesByDay(t, client, setup); all[today] != 1 || compacted[today] != 1 { + t.Errorf("hold off: today has %d files, %d compacted; want 1 compacted file", all[today], compacted[today]) + } +} + +// A table whose only small files are today's commits nothing, and says why. +func TestCompactOfOnlyAnOpenPartitionCommitsNothing(t *testing.T) { + _, client, setup, _ := openDayGeoTable(t, 3, 0) + before := currentTableMetadata(t, client, setup).CurrentSnapshot().SnapshotID + result := compactGeo(t, client, setup, spatialHoldConfig(true)) + if !strings.Contains(result, "in open time partitions, left in write order") { + t.Errorf("result %q", result) + } + if after := currentTableMetadata(t, client, setup).CurrentSnapshot().SnapshotID; after != before { + t.Errorf("snapshot %d became %d: a held table was committed to", before, after) + } +} + +// Detection's planning index answers as the job does, and records when the held partition is released, so its cached +// answer expires then. +func TestPlanningIndexHoldsTodayAndRecordsTheRelease(t *testing.T) { + for name, c := range map[string]struct { + today, past int + wantEligible bool + }{ + "today only": {3, 0, false}, + "today and past day": {3, 3, true}, + } { + t.Run(name, func(t *testing.T) { + _, client, setup, today := openDayGeoTable(t, c.today, c.past) + ctx := context.Background() + state, err := loadCurrentMetadata(ctx, client, setup.BucketName, setup.tablePath()) + if err != nil { + t.Fatal(err) + } + manifests, err := loadCurrentManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata) + if err != nil { + t.Fatal(err) + } + config := spatialHoldConfig(true) + config.TargetFileSizeBytes, config.MinInputFiles = 256<<20, 2 + idx, err := buildPlanningIndexFromManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata, config, []string{"compact"}, manifests) + if err != nil || idx == nil || idx.Compaction == nil { + t.Fatalf("index %+v, err %v", idx, err) + } + if idx.Compaction.Eligible != c.wantEligible { + t.Errorf("eligible %v, want %v", idx.Compaction.Eligible, c.wantEligible) + } + release := time.Unix(int64(today+1)*86400, 0).Add(2 * time.Hour) + if idx.Compaction.RecheckAfterMs != release.UnixMilli() { + t.Errorf("recheckAfterMs %d, want %d (midnight UTC plus the grace)", idx.Compaction.RecheckAfterMs, release.UnixMilli()) + } + // control: with the hold off, today is eligible and nothing is held + config.SpatialHoldOpenPartitions = false + idx, err = buildPlanningIndexFromManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata, config, []string{"compact"}, manifests) + if err != nil || !idx.Compaction.Eligible || idx.Compaction.RecheckAfterMs != 0 { + t.Errorf("hold off: index %+v, err %v", idx.Compaction, err) + } + }) + } +} + +// Spatial clustering is opt-in; once on, it holds open partitions by default. +func TestParseConfigSpatialDefaults(t *testing.T) { + c := ParseConfig(nil) + if c.SpatialClustering { + t.Error("spatial clustering is on by default") + } + if !c.SpatialHoldOpenPartitions || c.SpatialOpenPartitionGrace != 2*time.Hour { + t.Errorf("defaults: hold %v grace %v, want true 2h", c.SpatialHoldOpenPartitions, c.SpatialOpenPartitionGrace) + } +} diff --git a/weed/worker/tasks/iceberg/spatial_order.go b/weed/worker/tasks/iceberg/spatial_order.go new file mode 100644 index 0000000000..a1ffc03e65 --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_order.go @@ -0,0 +1,280 @@ +package iceberg + +import ( + "errors" + "math" + "strings" + + "github.com/apache/iceberg-go" + "github.com/apache/iceberg-go/table" + "github.com/parquet-go/parquet-go" + "github.com/twpayne/go-geom/encoding/wkb" +) + +// Spatial order: the compaction of an Iceberg v3 table with one geometry column writes its rows in the Hilbert order of +// each row's bounding-box centre, so that every output file and row group covers a compact area and a reader skips the +// rest by the geometry bounds and row-group statistics. +// +// The order is computed here from the geometry itself, not from a stored column and not from an Iceberg sort order: +// v3 has no spatial sort transform, geometry cannot be a sort source, and DuckDB 1.5.6 refuses every INSERT into a +// table that declares a sort order, so declaring one would break plain INSERTs. The key only orders rows; pruning stays on +// the geometry bounds, so a key that is off costs speed, never results. +// +// A table qualifies when it is format-version 3, declares no sort order (a declared order is honoured as before), and +// has exactly one top-level geometry column, or names one in seaweedfs.compaction.spatial-column; that property set to +// "none" (or "false") opts the table out. The job turns it on with spatial_clustering (off by default). + +const ( + rewriteStrategySpatial = "spatial" + + // tablePropSpatialColumn names the geometry column to cluster by, or "none"/"false" to opt out. + tablePropSpatialColumn = "seaweedfs.compaction.spatial-column" + + // hilbertOrder: bits per axis. 31 keeps the key (2*31 bits) in a positive int64; over the whole lon/lat extent a + // cell is about 1.7e-7 degrees (2 cm). + hilbertOrder = 31 + + // spatialKeyColumn travels as the last column of the sort and is dropped from the output (spatial_spool.go). + spatialKeyColumn = "_seaweedfs_spatial_key" + + // a key for a row whose geometry is null, empty or unreadable: such rows sort last + spatialKeyNone = math.MaxInt64 +) + +// errSpatialOrderUnavailable: the bin cannot be put in spatial order (no geometry bounds to lay the grid over, or no +// geometry column the merge can find); the caller bin-packs it instead. +var errSpatialOrderUnavailable = errors.New("no spatial order for this bin") + +// spatialPlan is the spatial part of a rewrite plan. +type spatialPlan struct { + fieldID int + column string + geographic bool // lon/lat: the key spans the whole globe, the same for every bin and run +} + +// resolveSpatialPlan is the spatial plan for the table, or nil when it does not qualify. +func resolveSpatialPlan(config Config, meta table.Metadata) *spatialPlan { + if !config.SpatialClustering || meta == nil || meta.Version() < 3 || meta.CurrentSchema() == nil { + return nil + } + if !meta.SortOrder().IsUnsorted() { + return nil + } + named := strings.TrimSpace(meta.Properties()[tablePropSpatialColumn]) + switch strings.ToLower(named) { + case "none", "false", "off": + return nil + } + var chosen []iceberg.NestedField + for _, f := range meta.CurrentSchema().Fields() { + if _, ok := f.Type.(iceberg.GeometryType); !ok { + continue + } + if named == "" || f.Name == named { + chosen = append(chosen, f) + } + } + if len(chosen) != 1 { + return nil + } + g := chosen[0].Type.(iceberg.GeometryType) + return &spatialPlan{fieldID: chosen[0].ID, column: chosen[0].Name, geographic: isLonLatCRS(g.CRS())} +} + +func isLonLatCRS(crs string) bool { + switch strings.ToUpper(strings.TrimSpace(crs)) { + case strings.ToUpper(iceberg.DefaultGeoCRS), "EPSG:4326", "SRID:4326", "OGC:CRS83", "EPSG:4269": + return true + } + return false +} + +// spatialExtent is the box the key's grid spans: the globe for a lon/lat column, else the union of the bin's file +// bounds. False when a projected column's files carry no bounds at all (the bin is then bin-packed). +func (p *spatialPlan) extent(entries []iceberg.ManifestEntry) (geoBox4, bool) { + if p.geographic { + return geoBox4{-180, -90, 180, 90}, true + } + var box geoBox4 + has := false + for _, e := range entries { + b, ok := entryGeoBox(e, p.fieldID) + if !ok { + continue + } + if !has { + box, has = b, true + continue + } + box = box.union(b) + } + return box, has +} + +type geoBox4 struct{ xmin, ymin, xmax, ymax float64 } + +func (b geoBox4) union(o geoBox4) geoBox4 { + return geoBox4{math.Min(b.xmin, o.xmin), math.Min(b.ymin, o.ymin), math.Max(b.xmax, o.xmax), math.Max(b.ymax, o.ymax)} +} + +// entryGeoBox is a data file's geometry bound from its manifest entry. +func entryGeoBox(e iceberg.ManifestEntry, fieldID int) (geoBox4, bool) { + if e == nil || e.DataFile() == nil { + return geoBox4{}, false + } + df := e.DataFile() + x0, y0, ok0 := decodeGeoPoint(df.LowerBoundValues()[fieldID]) + x1, y1, ok1 := decodeGeoPoint(df.UpperBoundValues()[fieldID]) + if !ok0 || !ok1 || x0 > x1 || y0 > y1 { + return geoBox4{}, false + } + return geoBox4{x0, y0, x1, y1}, true +} + +// spatialKeyer computes a row's key from the WKB of its geometry column. +type spatialKeyer struct { + column int // leaf index of the geometry column in the rows + extent geoBox4 +} + +func (k spatialKeyer) key(row parquet.Row) int64 { + for _, v := range row { + if v.Column() != k.column { + continue + } + if v.IsNull() { + return spatialKeyNone + } + g, err := wkb.Unmarshal(v.ByteArray()) + if err != nil || g == nil { + return spatialKeyNone + } + b := g.Bounds() + if b == nil || b.IsEmpty() { + return spatialKeyNone + } + cx, cy := (b.Min(0)+b.Max(0))/2, (b.Min(1)+b.Max(1))/2 + if math.IsNaN(cx) || math.IsNaN(cy) { + return spatialKeyNone + } + return int64(hilbertIndex(hilbertOrder, gridCell(cx, k.extent.xmin, k.extent.xmax), gridCell(cy, k.extent.ymin, k.extent.ymax))) + } + return spatialKeyNone +} + +// gridCell is v's cell on an axis of 2^hilbertOrder cells over [lo, hi], clamped. +func gridCell(v, lo, hi float64) uint64 { + const cells = uint64(1) << hilbertOrder + if !(hi > lo) || math.IsNaN(v) { + return 0 + } + f := (v - lo) / (hi - lo) * float64(cells) + if f <= 0 { + return 0 + } + if f >= float64(cells-1) { + return cells - 1 + } + return uint64(f) +} + +// hilbertIndex is the distance along the Hilbert curve of the cell (x, y) on a 2^order × 2^order grid (the classic +// xy2d: at each scale, the quadrant's position on the curve, then the rotation that keeps the curve continuous). +func hilbertIndex(order uint, x, y uint64) uint64 { + n := uint64(1) << order + var d uint64 + for s := n >> 1; s > 0; s >>= 1 { + var rx, ry uint64 + if x&s != 0 { + rx = 1 + } + if y&s != 0 { + ry = 1 + } + d += s * s * ((3 * rx) ^ ry) + if ry == 0 { + if rx == 1 { + x = n - 1 - x + y = n - 1 - y + } + x, y = y, x + } + } + return d +} + +// spatialFileOrder orders a group's candidate files by the Hilbert key of their bound's centre, so that bins split +// from one partition cover compact areas. Nil when a file has no geometry bound. The order is best effort, as an +// inferred order is in compact_order.go: files a run cannot take are still bin-packed rather than left behind. +func spatialFileOrder(plan *spatialPlan, entries []iceberg.ManifestEntry) *compactionOrder { + if plan == nil || len(entries) == 0 { + return nil + } + extent, ok := plan.extent(entries) + if !ok { + return nil + } + for _, e := range entries { + if _, ok := entryGeoBox(e, plan.fieldID); !ok { + return nil + } + } + return &compactionOrder{fieldID: plan.fieldID, typ: iceberg.PrimitiveTypes.Int64, bestEffort: true, + spatial: &spatialFileKey{fieldID: plan.fieldID, extent: extent}} +} + +type spatialFileKey struct { + fieldID int + extent geoBox4 +} + +func (k *spatialFileKey) of(e iceberg.ManifestEntry) (iceberg.Literal, bool) { + b, ok := entryGeoBox(e, k.fieldID) + if !ok { + return nil, false + } + x := gridCell((b.xmin+b.xmax)/2, k.extent.xmin, k.extent.xmax) + y := gridCell((b.ymin+b.ymax)/2, k.extent.ymin, k.extent.ymax) + return iceberg.Int64Literal(int64(hilbertIndex(hilbertOrder, x, y))), true +} + +// compactionOrderFor is the order a partition group's files are listed in: spatial for a spatial plan when every file +// has a geometry bound, else the table's (resolveCompactionOrder). +func compactionOrderFor(meta table.Metadata, entries []iceberg.ManifestEntry, plan *compactionRewritePlan) *compactionOrder { + if plan != nil && plan.spatial != nil { + if o := spatialFileOrder(plan.spatial, entries); o != nil { + return o + } + } + return resolveCompactionOrder(meta, entries) +} + +// keyedSchema is schema with the spatial key appended as its last column (a required int64), and the key column's +// name: spatialKeyColumn, suffixed until no column of schema has it. +func keyedSchema(schema *parquet.Schema) (*parquet.Schema, string) { + name := spatialKeyColumn + for taken := true; taken; { + taken = false + for _, f := range schema.Fields() { + if f.Name() == name { + name, taken = name+"_", true + break + } + } + } + fields := append(append([]parquet.Field{}, schema.Fields()...), + lineageField{Node: parquet.Leaf(parquet.Int64Type), name: name}) + return parquet.NewSchema(schema.Name(), &orderedGroup{Node: schema, fields: fields}), name +} + +// geometryLeafIndex is the leaf index of the top-level column with the field id (or the name) in schema, -1 if none. +func geometryLeafIndex(schema *parquet.Schema, fieldID int, name string) int { + leaf := 0 + for _, f := range schema.Fields() { + if f.Leaf() && (f.ID() == fieldID || (f.ID() == 0 && f.Name() == name)) { + return leaf + } + leaf += leafCount(f) + } + return -1 +} diff --git a/weed/worker/tasks/iceberg/spatial_order_test.go b/weed/worker/tasks/iceberg/spatial_order_test.go new file mode 100644 index 0000000000..4368c03c8b --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_order_test.go @@ -0,0 +1,549 @@ +package iceberg + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "sort" + "strings" + "testing" + + "github.com/apache/iceberg-go" + "github.com/apache/iceberg-go/table" + "github.com/parquet-go/parquet-go" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/twpayne/go-geom/encoding/wkb" +) + +// The spatial order of a compacted geometry table (spatial_order.go). + +func TestHilbertIndexIsACurve(t *testing.T) { + for order := uint(1); order <= 6; order++ { + n := uint64(1) << order + cells := make(map[uint64][2]uint64, n*n) + for x := uint64(0); x < n; x++ { + for y := uint64(0); y < n; y++ { + d := hilbertIndex(order, x, y) + if d >= n*n { + t.Fatalf("order %d: index %d of (%d, %d) out of range", order, d, x, y) + } + if prev, dup := cells[d]; dup { + t.Fatalf("order %d: index %d for (%d, %d) and %v", order, d, x, y, prev) + } + cells[d] = [2]uint64{x, y} + } + } + for d := uint64(1); d < n*n; d++ { + a, b := cells[d-1], cells[d] + dx, dy := int64(a[0])-int64(b[0]), int64(a[1])-int64(b[1]) + if dx*dx+dy*dy != 1 { + t.Fatalf("order %d: steps %d -> %d jump from %v to %v", order, d-1, d, a, b) + } + } + } + // the key of the full order fits a positive int64 + if top := hilbertIndex(hilbertOrder, 1< math.MaxInt64 || int64(top) < 0 { + t.Fatalf("a %d-bit key %d does not fit a positive int64", 2*hilbertOrder, top) + } +} + +func TestGridCellClamps(t *testing.T) { + const last = uint64(1)< 0.15 { + t.Errorf("%s: a row group covers %.0f%% of the extent on average; in spatial order it is a few percent", name, 100*avg) + } + } + geo, _ := compactedGeoBounds(t, client, setup) + for p, b := range geo { + if b == nil || b.xmin < -10 || b.xmax > 10 || b.ymin < -5 || b.ymax > 5 { + t.Errorf("%s: geometry bound %v, want one inside the data's extent", p, b) + } + } +} + +// The control: the same table bin-packed (spatial clustering off) keeps the input order, and its row groups each span +// most of the extent. +func TestCompactWithoutSpatialClusteringKeepsInputOrder(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + populateGeoTable(t, fs, setup, scatteredGeoFiles(6, 400, 58), geoTableOptions{}) + result := compactGeo(t, client, setup, Config{SpatialClustering: false, RowGroupRowLimit: 100}) + if strings.Contains(result, "spatial") { + t.Fatalf("result %q", result) + } + for name, data := range compactedFiles(t, fs, setup) { + rows := readSpatialOutput(t, data) + world := geoBox4{-180, -90, 180, 90} + descending := 0 + for i := 1; i < len(rows); i++ { + if keyOfWKB(t, rows[i].Geom, world) < keyOfWKB(t, rows[i-1].Geom, world) { + descending++ + } + } + if descending < len(rows)/4 { + t.Errorf("%s: only %d descending steps: the control is ordered, so the test cannot tell", name, descending) + } + } +} + +// Rows without a usable geometry (null, unparseable) sort after every other row, and are all kept. +func TestCompactSpatialOrderPutsUnkeyedRowsLast(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + files := scatteredGeoFiles(3, 50, 7) + files[1].Rows = append(files[1].Rows, geoRow{ID: 1000, Geom: nil}, geoRow{ID: 1001, Geom: []byte("garbage")}) + populateGeoTable(t, fs, setup, files, geoTableOptions{}) + compactGeo(t, client, setup, Config{SpatialClustering: true}) + for name, data := range compactedFiles(t, fs, setup) { + rows := readSpatialOutput(t, data) + if len(rows) != 152 { + t.Fatalf("%s: %d rows, want 152", name, len(rows)) + } + tail := map[int64]bool{rows[len(rows)-1].ID: true, rows[len(rows)-2].ID: true} + if !tail[1000] || !tail[1001] { + t.Errorf("%s: last rows %d, %d; want the null and the unparseable one", name, rows[len(rows)-2].ID, rows[len(rows)-1].ID) + } + } +} + +// A projected CRS lays the grid over the files' bounds; without any bound the bin is bin-packed, rows intact. +func TestCompactSpatialProjectedCRS(t *testing.T) { + feet, err := iceberg.GeometryTypeOf("EPSG:2913") + if err != nil { + t.Fatal(err) + } + projected := func(noBounds bool) []geoFile { + r := rand.New(rand.NewSource(3)) + var files []geoFile + id := int64(0) + for f := 0; f < 4; f++ { + var rows []geoRow + for i := 0; i < 200; i++ { + rows = append(rows, geoRow{ID: id, Geom: wkbPoint(7.6e6+r.Float64()*1e5, 6.8e5+r.Float64()*1e5)}) + id++ + } + files = append(files, geoFile{Name: fmt.Sprintf("p%d.parquet", f), Rows: rows, NoBounds: noBounds}) + } + return files + } + for _, noBounds := range []bool{false, true} { + t.Run(fmt.Sprintf("noBounds=%v", noBounds), func(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + populateGeoTable(t, fs, setup, projected(noBounds), geoTableOptions{icebergType: feet, parquetCRS: "EPSG:2913"}) + compactGeo(t, client, setup, Config{SpatialClustering: true}) + for name, data := range compactedFiles(t, fs, setup) { + rows := readSpatialOutput(t, data) + if len(rows) != 800 { + t.Fatalf("%s: %d rows, want 800", name, len(rows)) + } + extent := geoBox4{math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)} + for _, r := range rows { + g, _ := wkb.Unmarshal(r.Geom) + b := g.Bounds() + extent = extent.union(geoBox4{b.Min(0), b.Min(1), b.Max(0), b.Max(1)}) + } + descending := 0 + for i := 1; i < len(rows); i++ { + if keyOfWKB(t, rows[i].Geom, extent) < keyOfWKB(t, rows[i-1].Geom, extent) { + descending++ + } + } + if !noBounds && descending != 0 { + t.Errorf("%s: %d descending steps over the files' extent", name, descending) + } + if noBounds && descending == 0 { + t.Errorf("%s: sorted although no file had a bound to lay the grid over", name) + } + } + }) + } +} + +// A bin's files are listed by the Hilbert key of their bound's centre. +func TestSpatialFileOrder(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + centres := [][2]float64{{50, 50}, {-50, -50}, {50, -50}, {-50, 50}, {0, 0}} + var files []geoFile + for i, c := range centres { + files = append(files, geoFile{Name: fmt.Sprintf("c%d.parquet", i), Rows: []geoRow{{int64(i), wkbBox(c[0]-1, c[1]-1, c[0]+1, c[1]+1)}}}) + } + populateGeoTable(t, fs, setup, files, geoTableOptions{}) + entries := currentDataEntries(t, client, setup) + plan := &spatialPlan{fieldID: geoTestGeomField, column: "geom", geographic: true} + order := spatialFileOrder(plan, entries) + if order == nil { + t.Fatal("no spatial file order although every file has a bound") + } + order.sortEntries(entries) + world := geoBox4{-180, -90, 180, 90} + var keys []int64 + for _, e := range entries { + b, _ := entryGeoBox(e, geoTestGeomField) + keys = append(keys, int64(hilbertIndex(hilbertOrder, gridCell((b.xmin+b.xmax)/2, world.xmin, world.xmax), gridCell((b.ymin+b.ymax)/2, world.ymin, world.ymax)))) + } + if !sort.SliceIsSorted(keys, func(i, j int) bool { return keys[i] < keys[j] }) { + t.Errorf("files not in key order: %v", keys) + } + // a file without a geometry bound leaves the table's own order in place + files[2].NoBounds = true + fs2, client2 := startFakeFiler(t) + populateGeoTable(t, fs2, setup, files, geoTableOptions{}) + if o := spatialFileOrder(plan, currentDataEntries(t, client2, setup)); o != nil { + t.Error("a spatial file order although one file has no bound") + } +} + +// Under a spatial plan, delete-heavy files pack in the Hilbert order of their geometry bounds, like any other bin. +func TestDeleteHeavyBinsFollowSpatialOrder(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + centres := [][2]float64{{50, 50}, {-50, -50}, {50, -50}, {-50, 50}, {0, 0}} + var files []geoFile + for i, c := range centres { + box := wkbBox(c[0]-1, c[1]-1, c[0]+1, c[1]+1) + files = append(files, geoFile{Name: fmt.Sprintf("c%d.parquet", i), Rows: []geoRow{{int64(2 * i), box}, {int64(2*i + 1), box}}}) + } + populateGeoTable(t, fs, setup, files, geoTableOptions{}) + entries := currentDataEntries(t, client, setup) + dvs := &deletionVectorSet{cardinality: map[string]int64{}} + for _, e := range entries { + key, err := normalizeIcebergPath(e.DataFile().FilePath(), setup.BucketName, setup.tablePath()) + if err != nil { + t.Fatal(err) + } + dvs.cardinality[key] = 1 + } + world := geoBox4{-180, -90, 180, 90} + keys := func(es []iceberg.ManifestEntry) []int64 { + var out []int64 + for _, e := range es { + b, _ := entryGeoBox(e, geoTestGeomField) + out = append(out, int64(hilbertIndex(hilbertOrder, gridCell((b.xmin+b.xmax)/2, world.xmin, world.xmax), gridCell((b.ymin+b.ymax)/2, world.ymin, world.ymax)))) + } + return out + } + sorted := func(k []int64) bool { return sort.SliceIsSorted(k, func(i, j int) bool { return k[i] < k[j] }) } + if sorted(keys(entries)) { + t.Fatal("control: the files are already in key order") + } + plan := &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: &spatialPlan{fieldID: geoTestGeomField, column: "geom", geographic: true}} + bins, err := buildDeleteHeavyBins(entries, dvs, 1<<30, 0, currentTableMetadata(t, client, setup), plan, setup.BucketName, setup.tablePath()) + if err != nil { + t.Fatalf("buildDeleteHeavyBins: %v", err) + } + if len(bins) != 1 || bins[0].DropOnly || len(bins[0].Entries) != len(centres) { + t.Fatalf("bins = %+v, want one rewrite bin of %d files", bins, len(centres)) + } + if k := keys(bins[0].Entries); !sorted(k) { + t.Errorf("files not in key order: %v", k) + } +} + +func currentTableMetadata(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) table.Metadata { + t.Helper() + state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath()) + if err != nil { + t.Fatalf("loadCurrentMetadata: %v", err) + } + return state.Metadata +} + +// assertRowLineageCommitted: a new current snapshot with first-row-id = the previous next-row-id, and the table's +// next-row-id advanced by exactly its added-rows. +func assertRowLineageCommitted(t *testing.T, before, after table.Metadata) *table.Snapshot { + t.Helper() + snap := after.CurrentSnapshot() + if snap == nil || snap.SnapshotID == before.CurrentSnapshot().SnapshotID { + t.Fatalf("no new snapshot committed") + } + if snap.FirstRowID == nil || snap.AddedRows == nil { + t.Fatalf("snapshot %d lacks row lineage: first-row-id %v, added-rows %v", snap.SnapshotID, snap.FirstRowID, snap.AddedRows) + } + if *snap.FirstRowID != before.NextRowID() { + t.Errorf("first-row-id = %d, want the previous next-row-id %d", *snap.FirstRowID, before.NextRowID()) + } + if after.NextRowID() != *snap.FirstRowID+*snap.AddedRows { + t.Errorf("next-row-id = %d, want first-row-id %d + added-rows %d", after.NextRowID(), *snap.FirstRowID, *snap.AddedRows) + } + return snap +} + +// The spatial plan's row groups (rowsPerRowGroupFor): the spatial byte target, the table's +// write.parquet.row-group-size-bytes capping it, the 16-row floor, the explicit limit, and the bin-pack control. +func TestRowsPerRowGroupForSpatial(t *testing.T) { + bin := func(rows, bytes int64) compactionBin { + snapID := int64(1) + dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData, "s3://b/data/a.parquet", + iceberg.ParquetFile, map[int]any{}, nil, nil, rows, bytes) + if err != nil { + t.Fatal(err) + } + return compactionBin{Entries: []iceberg.ManifestEntry{iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())}, TotalSize: bytes} + } + spatial := &compactionRewritePlan{strategy: rewriteStrategySpatial, spatial: &spatialPlan{column: "geom"}} + kb := bin(100000, 100000*1024) // 1 KiB a row + for _, tc := range []struct { + name string + bin compactionBin + config Config + plan *compactionRewritePlan + want int64 + }{ + {"2 MB spatial row groups", kb, Config{}, spatial, 2048}, + {"spatial size set", kb, Config{SpatialRowGroupSizeBytes: 4 << 20}, spatial, 4096}, + {"the table's row-group size caps it", kb, Config{RowGroupSizeBytes: 1 << 20}, spatial, 1024}, + {"a larger table row-group size does not lift it", kb, Config{RowGroupSizeBytes: 64 << 20}, spatial, 2048}, + {"large polygons: 100 KiB a row", bin(1000, 1000*100*1024), Config{}, spatial, 20}, + {"the 16-row floor", bin(100, 100*1024*1024), Config{}, spatial, minSpatialRowGroupRows}, + {"an explicit row limit wins", kb, Config{RowGroupRowLimit: 100}, spatial, 100}, + {"bin-pack control", kb, Config{}, &compactionRewritePlan{strategy: defaultRewriteStrategy}, 131072}, + {"no plan", kb, Config{}, nil, 131072}, + } { + if got := rowsPerRowGroupFor(tc.bin, tc.config, tc.plan); got != tc.want { + t.Errorf("%s: %d rows, want %d", tc.name, got, tc.want) + } + } +} + +// A geometry column whose Parquet name is the spatial key's: the key takes another name, and the rows still come +// out in spatial order. +func TestCompactSpatialKeyNameAvoidsATableColumn(t *testing.T) { + fs, client := startFakeFiler(t) + setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"} + files := scatteredGeoFiles(4, 300, 7) + for i := range files { + files[i].GeomName = spatialKeyColumn + } + populateGeoTable(t, fs, setup, files, geoTableOptions{}) + result := compactGeo(t, client, setup, Config{SpatialClustering: true, SortBufferRows: minSortBufferRows}) + if !strings.Contains(result, "compacted 4 files into 1") || !strings.Contains(result, "spatial (geom)") { + t.Fatalf("result %q", result) + } + for name, data := range compactedFiles(t, fs, setup) { + f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data))) + if err != nil { + t.Fatal(err) + } + col := -1 + for _, n := range []string{"geom", spatialKeyColumn} { + if leaf, ok := f.Schema().Lookup(n); ok { + col = leaf.ColumnIndex + } + } + if _, keyWritten := f.Schema().Lookup(spatialKeyColumn + "_"); col < 0 || keyWritten { + t.Fatalf("%s: columns %v", name, f.Schema().Columns()) + } + reader := parquet.NewReader(f) + rows := make([]parquet.Row, 1200) + n, _ := reader.ReadRows(rows) + if n != 1200 { + t.Fatalf("%s: %d rows, want 1200", name, n) + } + world := geoBox4{-180, -90, 180, 90} + prev, descending := int64(-1), 0 + for _, row := range rows[:n] { + var geom []byte + for _, v := range row { + if v.Column() == col && !v.IsNull() { + geom = v.ByteArray() + } + } + k := keyOfWKB(t, geom, world) + if k < prev { + descending++ + } + prev = k + } + if descending != 0 { + t.Errorf("%s: %d descending steps in the spatial key", name, descending) + } + } +} diff --git a/weed/worker/tasks/iceberg/spatial_spool.go b/weed/worker/tasks/iceberg/spatial_spool.go new file mode 100644 index 0000000000..d77b66cd91 --- /dev/null +++ b/weed/worker/tasks/iceberg/spatial_spool.go @@ -0,0 +1,90 @@ +package iceberg + +import ( + "context" + "fmt" + "io" + "os" + + "github.com/parquet-go/parquet-go" +) + +// A spatial merge sorts by a key that is not a column of the output (spatial_order.go): the key travels as an extra +// last column through parquet-go's sorting writer into a temporary file, and a plain writer then writes the output +// from it in the same order without the key. + +type sortSpool struct { + file *os.File +} + +func newSortSpool(dir string) (*sortSpool, error) { + f, err := os.CreateTemp(dir, "seaweedfs-iceberg-sorted-*.parquet") + if err != nil { + return nil, fmt.Errorf("create sort spool: %w", err) + } + return &sortSpool{file: f}, nil +} + +func (s *sortSpool) remove() { + if s == nil || s.file == nil { + return + } + name := s.file.Name() + _ = s.file.Close() + _ = os.Remove(name) + s.file = nil +} + +// copyTo writes the spooled rows, in their order, to out with schema, dropping the last value of each row (the key: it is +// the spool's last leaf, so its value ends every row). +func (s *sortSpool) copyTo(ctx context.Context, out io.Writer, schema *parquet.Schema, rowGroupRows int64) error { + info, err := s.file.Stat() + if err != nil { + return fmt.Errorf("stat sort spool: %w", err) + } + spooled, err := parquet.OpenFile(s.file, info.Size()) + if err != nil { + return fmt.Errorf("open sort spool: %w", err) + } + if got, want := len(spooled.Schema().Columns()), len(schema.Columns())+1; got != want { + return fmt.Errorf("sort spool has %d columns, want %d", got, want) + } + writer := parquet.NewWriter(out, schema, parquet.MaxRowsPerRowGroup(rowGroupRows)) + rows := make([]parquet.Row, 256) + for _, rg := range spooled.RowGroups() { + reader := rg.Rows() + for { + select { + case <-ctx.Done(): + reader.Close() + writer.Close() + return ctx.Err() + default: + } + n, readErr := reader.ReadRows(rows) + if n > 0 { + batch := rows[:n] + for i, row := range batch { + batch[i] = row[:len(row)-1] + } + if _, err := writer.WriteRows(batch); err != nil { + reader.Close() + writer.Close() + return fmt.Errorf("write sorted rows: %w", err) + } + } + if readErr != nil { + reader.Close() + if readErr == io.EOF { + break + } + writer.Close() + return fmt.Errorf("read sort spool: %w", readErr) + } + } + } + if err := writer.Close(); err != nil { + return fmt.Errorf("close writer: %w", err) + } + return nil +}