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