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

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

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

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

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

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

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

Tests:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:51:16 -08:00

315 lines
16 KiB
Go

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)
}
}