mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* 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>
281 lines
9.1 KiB
Go
281 lines
9.1 KiB
Go
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
|
||
}
|