mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
* mq: read a topic table's data files back as log entries A view of a topic's table holds the current snapshot's offset map and, per _partition, its data files with the _offset and _ts_ns bounds from the manifests. A partition's rows are read by offset or by time, skipping files and then row groups whose bounds miss the read, and come back as the log entries they were copied from: key, timestamp, offset, and the message as _value or as the record re-encoded from its columns. Views are cached per topic, rechecked every few seconds, rebuilt only when the metadata location moves, reuse already-parsed manifests, and are evicted past a bound on the data files they hold. A table that is gone or replaced by another UUID reads as empty; one with delete files is refused. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a table-backed partition below its table's high-water mark from the table The merged reader takes the partition's table, looked up on every read so a table attached later is seen. An offset read below the mark reads the table up to the mark and continues into the log files and compacted parquet from the mark; a time read takes the table's rows after the time and then the files' entries at or above the mark. Log files left below the mark by a crash between the writer's commit and its delete are never read. The broker hands its partitions' disk reads to the table through the topic's cached view; a topic without a table, or whose topic.conf is gone, reads its files as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: start a table-backed partition's offsets at its table A partition whose log files below the table's high-water mark were deleted would reload with a high-water mark and log start taken from the files that are left. Loading it now continues its offsets no lower than the table's mark and starts its log at the table's lowest offset, or, when the table holds nothing of it, at the first file offset at or above the mark. A retired range of a repartitioned topic is read and bounded the same way, and a retention purge raises the log start likewise, so purging hot log files never makes the table's offsets out of range. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: keep a flushed data source's finished flag atomic The streaming goroutine sets finished while the merge loop reads it through HasMore, which the race detector reports on any scan that reads flushed data. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: scan a table-backed topic's history from its table The hybrid scanner hands each partition's merged read the topic's table, so a scan reads the table's data files below the partition's high-water mark, pruned by _partition, _offset and _ts_ns, and log files from the mark on, skipping any a crash left below it. Aggregations no longer answer such a topic from parquet statistics and log counts, which hold none of its table's rows; they scan instead. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a schematized row's raw _value back as its message A schematized topic's table can keep a message that is not a record, a tombstone or an undecodable value, as raw bytes in an optional _value with the record columns null. Such a row now reads back as those bytes; a row whose _value is null reads back as its record, and a schemaless topic's row as its _value as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: delete log files a topic table already holds A log file or compacted parquet whose every offset is below a partition's table high-water mark is never read again, so it can go. The mark used is that of the newest snapshot at least a minute old: a reader's view of the table is at most a few seconds old, so it already reads those offsets from the table and never from a file being deleted. Files without an offset range and the file holding the partition's highest offset are always kept. DeleteCoveredLogFiles is for the topic's writer after its commit; a leader also deletes them under its fence on load and on each retention pass, covering a writer that crashed between its commit and its delete. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: report a topic table's rows as parquet_archive A table-backed topic's scan labelled every row live_log, its table's included. The flushed data source now records the high-water mark of the table its merged read was handed and reports the rows below it, which come only from the table's parquet data files, as parquet_archive. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: delete the log files a topic table holds after each run Every mq_topic_table run now ends by deleting, in each partition, the log files wholly below the offsets of the newest snapshot at least LogDeleteGrace old, never the leader's newest file. A commit is never old enough on the run that makes it, so each run deletes what earlier ones copied; the partition's leader deletes the same files when no run follows. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a time read's position when nothing on disk follows it A time read that found nothing after its position returned a position at time zero: the parquet reader reports the newest time it delivered, which is none. A loop over an empty memory buffer then read the whole partition from the start, came back to the same empty read, and started over, so a query asking a broker for its unflushed messages streamed the partition forever. The merged and the table-tiered readers now keep the position when they deliver nothing past it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: publish a topic table view under the lock eviction reads it with A loaded view was stored under its entry's loading lock while eviction, run by another topic's load, read every entry's view under the cache's lock, so two topics refreshing at once raced. A view is now stored holding both locks: a load reads it under the first, eviction under the second. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep no topic table view larger than the whole view cache Eviction never dropped the view just loaded, so one topic whose table had more data files than the cache's bound stayed cached past it, and evicted every other topic's view on the way. Such a view is now answered and not kept; the others stay. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: look up a topic table's mark again where a read leaves the table A read kept the table mark it started with. One slow over the table's rows could outlast the grace: the writer commits past that mark, the logs below the new mark are deleted, and the read then lists the logs from its old mark and passes over the deleted offsets without a word. The read now asks for the table again each time it leaves it and reads on in the table up to the mark it finds, until the mark stops moving; a time read takes the rows between the marks by offset. A gap where the logs begin is checked against the table once more, and read from the table if it took it meanwhile. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a topic table's timestamps back without going through nanoseconds A timestamp or time column was turned into micros by way of nanoseconds, which overflow for dates before 1678 or after 2261, so a year 1 or year 9999 value came back as another date. Each unit now converts to micros directly. The table fixture wrote every topic's rows whole into _value once every table had that column, so the record columns these reads take went untested; it now writes a schematized topic's rows as columns. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: order a compaction bin by the first sort field that varies in it A topic table sorts by _partition, then _offset, and is partitioned by _partition, so every file of a bin holds one _partition. Ordering the bin by it kept the files in manifest order, and a merged file's offsets came out of order for the topic table reader, which delivers a data file's rows as offsets in order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: list a retired range from its table's lowest offset A topic lookup lists each retired range with the bounds of its own files, so once the table held a range's history and its log files went, the range was listed from its newest file on, while its reader serves the table's offsets below it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: never merge compaction inputs across a file left out of the merge A file already at the target size takes no part in compaction, yet small files on both sides of it in sort order went into one bin, so the merged file's bounds spanned it. For a topic table that is a data file whose _offset range overlaps another's, which a reader finishing one file before the next cannot read in order. An ordered bin is now cut wherever a file left out of the merge falls between two of its files, so every merged file covers a range no file outside its run lies in. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: merge a topic table's overlapping data files by offset when reading A partition's data files were read one after another by their lowest offset, which only reads in offset order while no two ranges overlap. A rewrite by another engine can leave a file spanning another one, and then a read from inside the overlap delivered the spanning file's later rows first, and a read that stopped early left the rows in between behind. Files whose offset ranges overlap are now read together, their rows merged by offset and an offset held twice delivered once. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: open a topic table's data files only as a read reaches them A merged read opened every file of an overlapping group before it delivered a row, and a file the manifest records no offset bounds for overlaps every other one, so a short fetch held a reader for each file of the partition's history. The files of a read now wait in a heap keyed by the lowest offset each can hold, and a file is opened only once nothing before that offset is left to deliver; a file without bounds is opened where the read starts, and its row groups' statistics skip what they rule out. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: retire no log file a topic's table does not hold yet Retention deleted a table-backed topic's log files by age alone, so with the table writer behind it deleted messages the table did not hold, and they were gone from both. On such a topic a file now expires only once all it holds is below the table's mark of a grace-old snapshot, the same files the leader deletes as covered; what the table holds ages out with table retention. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: bound a table-backed range's bounds by its caller's deadline The table lookup that widens a partition's bounds ran under a background context, so a retention pass or a retired-range lookup with a deadline waited on a stalled table catalog for as long as it stalled. It now runs under the caller's context. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check a topic table's mark again when a time read reaches its files A time read caught up with the table and then read the files above the mark it last saw. A view that had moved on meanwhile, with the logs below its new mark deleted before the files were listed, left the offsets between the two marks to neither. The time read now asks for the table again at the first file entry it would deliver, or after the files if they held none, and on a moved mark reads the table up to it before reading the files again. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: bound the topic table views kept, empty ones included, and keep those in use Eviction only counted data files, so views of tables holding none, and entries a failed first load left behind, were never dropped; and it could drop an entry while a caller was loading it, so the next caller loaded the same table again alongside. A failed first load now leaves no entry, at most maxCachedTopics views are kept, and an entry a caller still holds is never evicted. The eviction test now requires exactly the one eviction that makes room. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check a topic table afresh before deleting the logs below its mark A leader's covered-log delete and log retention took the table's mark from the cached view, up to a few seconds old, so a table rolled back to a lower mark meanwhile had its logs above that mark deleted although it no longer held them. Both now check the table before acting: the cache takes a maximum age, a read passes ViewRefresh and a delete zero. A cached view is also reused only for the same table state, since a commit that rewrote the metadata in place keeps its location. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: leave a sort field holding nulls to order a compaction bin A sort field whose bounds are one value in every file was taken as constant and the bin ordered by the next field, yet bounds leave nulls and NaNs out, so a column holding them besides its one value is not constant. A field is now skipped only when the files also record no null in it, and no NaN for a floating point one. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: delete a topic's covered logs only while it still names the table A run's log cleanup used the table metadata the run started with, so after the topic left the table, or the run lost its lock, it still deleted the logs below that table's marks. The cleanup now checks, when it runs, that it still holds the topic's lock and that topic.conf still names the table with its recorded UUID, and reads the marks from the table as it is then. It still runs after a run that failed otherwise. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: check a topic table again before each covered log it deletes The leader read the table's mark once, listed the files below it, then deleted them one by one, so a rollback or a detach landing in between went unseen and files the table no longer held were deleted. The delete now holds the table writer's lock, so the topic cannot leave the table meanwhile, and before each file reads topic.conf and the table afresh, stopping at the first file not below the mark it finds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: let a caller waiting on a topic table's load give up at its deadline A caller wanting the view a stalled load of the same table was making waited on a mutex, past its own deadline, for as long as the load stalled. The entry is now held by a one-token channel a waiter selects on with its context, so it returns at its deadline and lets go of the entry. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: give up a scan's table lookup when the query is cancelled The table a scan reads below each partition's mark was looked up under a background context, and the flushed data source waited on its channels alone, so a cancelled query stayed blocked on a stalled table catalog. The scan's context now reaches the topic.conf read and the table lookup, and the data source returns once it is done. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: take a topic table's lock only when a covered log is left to delete The leader's covered-log pass took the table writer's lock for every table-backed partition it leads once the table had a mark, every five minutes, even with nothing to delete. While a copy run held the lock, each such partition waited out the lock wait and logged a failure, holding up the rest of the retention tick. List the covered files first and take the lock only when there are some; the per-file checks under the lock stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drop a topic table view only with the last caller holding it An oversized view was removed while other callers still held it, so the next caller loaded it again alongside; an entry no load filled was removed only by a failing load that was its sole holder, so one whose callers failed or gave up in another order stayed; and eviction that found every candidate held left the cache above its bounds with nothing to evict again. Callers now let go through one release: the last one removes an entry no load filled or one marked to drop, as an oversized view is, and each release runs eviction again. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: check a topic's table again before each covered log the cleanup deletes The cleanup checked the lock, topic.conf and the table once, then deleted every file below the marks it read, so a detach, a dropped or replaced table, or a lapsed lease landing during the deletes went unseen. The deletes now check all three again before each file, with the mark of the table as it is then, and stop at the first file not below it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: let a flushed data source's producer close its own channels Next can return on the query's cancellation while the producer is still sending, and the merge then closes the source, which closed the result and error channels under that send. The producer now owns them: Close only signals it to stop, every send also selects on that signal, and the producer closes the result channel when it exits, after sending its one error if it has one. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: fail a scan whose data source fails after its first row The merge only logged an error from a source past its first row, the query's cancellation included, and returned the rows read so far, so a cancelled or timed-out COUNT or SUM answered with a wrong number. It now closes its sources and returns the error, and the scan wraps it, so a caller can tell the context's error from others. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: check a topic table again before each group retention deletes Retention read a table-backed partition's deletable mark once, chose its expired groups, then deleted them with no further look, as the covered-log delete did before it rechecked; a rollback in between left groups deleted that the table no longer held. The live and retired purges and the covered-log delete now share one guard: it holds the table writer's lock and, before each group or file, reads topic.conf and the table afresh, stopping at the first one not below the mark it finds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: bound a partition load's reads of what it already stores Loading a partition reads its files' offset range and, for a table-backed topic, the table's, while holding accessLock, under a background context, so a stalled filer or table catalog held every other partition operation for as long as it stalled. The reads now get the bound a load's fence take has; past it the load fails, as it does when the stored offsets cannot be read, and the caller retries. Falling back to the log files' bounds would start the log above the table's offsets with no later refresh to lower it, so consumers resetting to the earliest offset would skip the table's history. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: count a flushed source's pending error as more to read The merge asks HasMore before reading a source again, and HasMore looked only at buffered rows and whether the producer finished, so a producer that failed after its last row and finished before the merge asked had its error never read, and the scan returned the rows so far as its answer. An error waiting counts as more to read now, so Next returns it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: keep the table's files of a topic that left it before the delete A topic that left its table between the listing of what the table held and the guard the delete takes got no guard, which let every listed file go, though readers take those offsets from the logs again. Files chosen by the table's rules, the covered logs and the groups retention trimmed to the table's mark, are now kept when no table remains; files of a topic that had no table when the pass began still expire as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: order the pending-error merge test's row before its error The test's producer could send its error before the first Next took the row, and Next then picked either one, so on some runs the error came through the first read and the test passed without exercising HasMore. The producer now holds its error until the first Next has the row, and the merge asks again only after the producer has finished, so the test fails every time without the pending-error fix. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a topic table's chunk-backed files under the caller's context A manifest or manifest list stored in chunks was read through a stream reader built without a context, and the stream reader looked up and fetched each chunk under a background context even when built with one, so a stalled volume server held a partition load past its bound while it held accessLock. A chunk stream reader now looks up and fetches its chunks under the context it was built with, and a table's chunk-backed files are read with the caller's. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: keep the expiredLogFiles doc comment on expiredLogFiles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: let the table catalog read chunk-backed table metadata The broker's table catalog reached its filers through a client with no way to look up chunk locations, so a table whose catalog record holds only the location of its metadata, as one whose metadata outgrew a request does, failed to load once that file was stored in chunks: the topic's history could not be read. The client now resolves chunks the way the broker's own filer client does. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: read chunk-backed table metadata under the caller's context A catalog record holding only a metadata location had its chunk-backed file read by StreamContent, whose lookups and fetches run under a background context, so a stalled volume server held a table load past its caller's deadline: a broker loading a table-backed partition under accessLock past its bound. The read now streams under the read's own context, which already bounds its other filer calls. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * filer: give up a LookupFn volume lookup's retries at its caller's deadline LookupFn retried a failed volume lookup through util.Retry, which sleeps its backoff without looking at the caller's context, so a lookup failing near a deadline outlived it by up to the whole backoff; a table load under a broker's accessLock held it that long. The lookup now retries through util.RetryWithBackoff with the same transient-error rule and about the same total wait, which stops when the context is done. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1915 lines
65 KiB
Go
1915 lines
65 KiB
Go
package iceberg
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/apache/iceberg-go"
|
|
"github.com/apache/iceberg-go/table"
|
|
"github.com/parquet-go/parquet-go"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// compactionBin groups small data files from the same partition and spec for merging.
|
|
type compactionBin struct {
|
|
PartitionKey string
|
|
Partition map[int]any
|
|
SpecID int32
|
|
Entries []iceberg.ManifestEntry
|
|
TotalSize int64
|
|
// DropOnly: every row of every file is deleted; the files
|
|
// leave the table without being read and nothing is written for them.
|
|
DropOnly bool
|
|
}
|
|
|
|
// compactDataFiles reads manifests to find small Parquet data files, groups
|
|
// them by partition, reads and merges them using parquet-go, and commits new
|
|
// manifest entries.
|
|
func (h *Handler) compactDataFiles(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, tablePath string,
|
|
config Config,
|
|
onProgress func(binIdx, totalBins int),
|
|
) (string, map[string]int64, error) {
|
|
start := time.Now()
|
|
state, err := loadCurrentMetadata(ctx, filerClient, bucketName, tablePath)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("load metadata: %w", err)
|
|
}
|
|
meta, dataPath := state.Metadata, state.DataPath
|
|
predicate, err := parsePartitionPredicate(config.Where, meta)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
currentSnap := meta.CurrentSnapshot()
|
|
if currentSnap == nil || currentSnap.ManifestList == "" {
|
|
return "no current snapshot", nil, nil
|
|
}
|
|
|
|
rewritePlan, err := resolveCompactionRewritePlan(config, meta)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("resolve rewrite strategy: %w", err)
|
|
}
|
|
|
|
// Read manifest list
|
|
manifestListData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, currentSnap.ManifestList)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("read manifest list: %w", err)
|
|
}
|
|
manifests, err := s3tables.ReadManifestList(manifestListData)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("parse manifest list: %w", err)
|
|
}
|
|
|
|
// Separate data manifests from delete manifests.
|
|
var dataManifests, deleteManifests []iceberg.ManifestFile
|
|
for _, mf := range manifests {
|
|
if mf.ManifestContent() == iceberg.ManifestContentData {
|
|
dataManifests = append(dataManifests, mf)
|
|
} else {
|
|
deleteManifests = append(deleteManifests, mf)
|
|
}
|
|
}
|
|
|
|
// If delete manifests exist and apply_deletes is disabled (or not yet
|
|
// implemented for this code path), skip compaction to avoid producing
|
|
// incorrect results by dropping deletes.
|
|
if len(deleteManifests) > 0 && !config.ApplyDeletes {
|
|
return "compaction skipped: delete manifests present and apply_deletes is disabled", nil, nil
|
|
}
|
|
|
|
specsByID := specByID(meta)
|
|
schema := meta.CurrentSchema()
|
|
|
|
// Collect data file entries from data manifests
|
|
var allEntries []iceberg.ManifestEntry
|
|
for _, mf := range dataManifests {
|
|
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("read manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("parse manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
allEntries = append(allEntries, entries...)
|
|
}
|
|
|
|
// Collect delete entries if we need to apply deletes
|
|
var positionDeletes map[string][]int64
|
|
var eqDeleteGroups []equalityDeleteGroup
|
|
var allDeleteEntries []iceberg.ManifestEntry
|
|
var dvs *deletionVectorSet
|
|
if config.ApplyDeletes && len(deleteManifests) > 0 {
|
|
for _, mf := range deleteManifests {
|
|
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
allDeleteEntries = append(allDeleteEntries, entries...)
|
|
}
|
|
|
|
var err error
|
|
dvs, err = indexDeletionVectors(allDeleteEntries, bucketName, dataPath)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
// Separate position and equality deletes, filtering by partition
|
|
// predicate so out-of-scope deletes don't affect the merge.
|
|
var posDeleteEntries, eqDeleteEntries []iceberg.ManifestEntry
|
|
for _, entry := range allDeleteEntries {
|
|
if isPuffin(entry.DataFile()) {
|
|
continue
|
|
}
|
|
inScope, err := deleteInPredicateScope(entry, predicate, specsByID, schema)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if !inScope {
|
|
continue
|
|
}
|
|
switch entry.DataFile().ContentType() {
|
|
case iceberg.EntryContentPosDeletes:
|
|
posDeleteEntries = append(posDeleteEntries, entry)
|
|
case iceberg.EntryContentEqDeletes:
|
|
eqDeleteEntries = append(eqDeleteEntries, entry)
|
|
}
|
|
}
|
|
|
|
if len(posDeleteEntries) > 0 {
|
|
positionDeletes, err = collectPositionDeletes(ctx, filerClient, bucketName, dataPath, posDeleteEntries)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("collect position deletes: %w", err)
|
|
}
|
|
}
|
|
|
|
if len(eqDeleteEntries) > 0 {
|
|
eqDeleteGroups, err = collectEqualityDeletes(ctx, filerClient, bucketName, dataPath, eqDeleteEntries, schema, specsByID)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("collect equality deletes: %w", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
candidateEntries := allEntries
|
|
if predicate != nil {
|
|
filtered := make([]iceberg.ManifestEntry, 0, len(candidateEntries))
|
|
for _, entry := range candidateEntries {
|
|
spec, ok := specsByID[int(entry.DataFile().SpecID())]
|
|
if !ok {
|
|
continue
|
|
}
|
|
match, err := predicate.Matches(spec, entry.DataFile().Partition())
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if match {
|
|
filtered = append(filtered, entry)
|
|
}
|
|
}
|
|
candidateEntries = filtered
|
|
}
|
|
|
|
// Read the deletion vectors of the candidates; a file whose
|
|
// vector cannot be read stays out of every bin. The positions join the
|
|
// Parquet position deletes the merge already applies.
|
|
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
|
|
if dvs != nil && len(dvs.entries) > 0 {
|
|
var covered []string
|
|
for _, entry := range candidateEntries {
|
|
df := entry.DataFile()
|
|
key, err := normalizeIcebergPath(df.FilePath(), bucketName, dataPath)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("resolve data file %s: %w", df.FilePath(), err)
|
|
}
|
|
// a file at the target size enters no bin unless it may be dropped whole
|
|
if df.FileSizeBytes() >= targetSize && (config.DeleteRatioThresholdPercent <= 0 || dvs.deletedShare(key, df.Count()) < 1) {
|
|
continue
|
|
}
|
|
if dvs.covers(key) {
|
|
covered = append(covered, key)
|
|
}
|
|
}
|
|
dvs.read(ctx, filerClient, bucketName, dataPath, covered)
|
|
if positionDeletes == nil {
|
|
positionDeletes = map[string][]int64{}
|
|
}
|
|
for key, positions := range dvs.positions {
|
|
merged := append(append([]int64(nil), positionDeletes[key]...), positions...)
|
|
sort.Slice(merged, func(i, j int) bool { return merged[i] < merged[j] })
|
|
positionDeletes[key] = slices.Compact(merged) // a legacy position delete may name a row the vector does
|
|
}
|
|
}
|
|
heavyEntries, candidateEntries, err := splitDeleteHeavy(candidateEntries, dvs, config.DeleteRatioThresholdPercent, targetSize, bucketName, dataPath)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
minInputFiles, err := compactionMinInputFiles(config.MinInputFiles)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
// Build compaction bins: group small data files by partition, each bin's
|
|
// 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 := 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
|
|
}
|
|
|
|
// Build a lookup from spec ID to PartitionSpec for per-bin manifest writing.
|
|
specLookup := specsByID
|
|
|
|
version := meta.Version()
|
|
snapshotID := currentSnap.SnapshotID
|
|
// v3 row lineage: the snapshot starts at the table's next-row-id, and the
|
|
// merged files carry every row's _row_id and _last_updated_sequence_number
|
|
// (row_lineage.go).
|
|
lineage := hasRowLineage(version)
|
|
firstRowID := rowLineageFirstRowID(meta)
|
|
|
|
// Compute the snapshot ID for the commit up front so all manifest entries
|
|
// reference the same snapshot that will actually be committed.
|
|
newSnapID := time.Now().UnixMilli()
|
|
// Random suffix for artifact filenames to avoid collisions between
|
|
// concurrent compaction runs on different tables sharing a timestamp.
|
|
artifactSuffix := compactRandomSuffix()
|
|
|
|
// Process each bin: read source Parquet files, merge, write output
|
|
var newManifestEntries []iceberg.ManifestEntry
|
|
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()
|
|
if seqNum < 0 {
|
|
return nil
|
|
}
|
|
return &seqNum
|
|
}
|
|
|
|
entryFileSeqNum := func(entry iceberg.ManifestEntry) *int64 {
|
|
if fileSeqNum := entry.FileSequenceNum(); fileSeqNum != nil {
|
|
value := *fileSeqNum
|
|
return &value
|
|
}
|
|
return entrySeqNum(entry)
|
|
}
|
|
|
|
// removeBinEntries marks a bin's files removed by this snapshot.
|
|
removeBinEntries := func(bin compactionBin) {
|
|
for _, entry := range bin.Entries {
|
|
summary.removeFile(entry.DataFile())
|
|
deletedManifestEntries = append(deletedManifestEntries, iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusDELETED,
|
|
&newSnapID,
|
|
entrySeqNum(entry), entryFileSeqNum(entry),
|
|
entry.DataFile(),
|
|
))
|
|
}
|
|
totalMerged += len(bin.Entries)
|
|
}
|
|
|
|
metaDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "metadata")
|
|
dataDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "data")
|
|
|
|
// Track written artifacts so we can clean them up if the commit fails.
|
|
type artifact struct {
|
|
dir, fileName string
|
|
}
|
|
var writtenArtifacts []artifact
|
|
keepArtifacts := false
|
|
|
|
defer func() {
|
|
if keepArtifacts || len(writtenArtifacts) == 0 {
|
|
return
|
|
}
|
|
// Use a detached context so cleanup completes even if ctx was canceled.
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
for _, a := range writtenArtifacts {
|
|
if err := deleteFilerFile(cleanupCtx, filerClient, a.dir, a.fileName); err != nil {
|
|
glog.Warningf("iceberg compact: failed to clean up artifact %s/%s: %v", a.dir, a.fileName, err)
|
|
}
|
|
}
|
|
}()
|
|
|
|
for binIdx, bin := range bins {
|
|
select {
|
|
case <-ctx.Done():
|
|
return "", nil, ctx.Err()
|
|
default:
|
|
}
|
|
|
|
if bin.DropOnly {
|
|
// every row is deleted: the files go, nothing is read or written
|
|
removeBinEntries(bin)
|
|
if onProgress != nil {
|
|
onProgress(binIdx, len(bins))
|
|
}
|
|
continue
|
|
}
|
|
|
|
mergedFileName := fmt.Sprintf("compact-%d-%d-%s-%d.parquet", snapshotID, newSnapID, artifactSuffix, binIdx)
|
|
mergedFilePath := absoluteIcebergPath(bucketName, dataPath, "data", mergedFileName)
|
|
|
|
var mergedData []byte
|
|
var recordCount int64
|
|
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.
|
|
binEqDeleteGroups, scopeErr := eqDeleteGroupsForBin(eqDeleteGroups, bin, specsByID, schema)
|
|
if scopeErr != nil {
|
|
glog.Warningf("iceberg compact: bin %d (%d files) not compacted: %v", binIdx, len(bin.Entries), scopeErr)
|
|
goto binDone
|
|
}
|
|
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)
|
|
}
|
|
if err != nil {
|
|
glog.Warningf("iceberg compact: failed to merge bin %d (%d files): %v", binIdx, len(bin.Entries), err)
|
|
goto binDone
|
|
}
|
|
if recordCount == 0 {
|
|
// the deletes left no row: no empty file is written
|
|
removeBinEntries(bin)
|
|
goto binDone
|
|
}
|
|
// A default-CRS geometry column declares no CRS (geometry_crs.go). A
|
|
// footer that cannot be rewritten leaves the file as written: valid,
|
|
// only labelled differently.
|
|
if fixed, _, crsErr := withDefaultGeometryCRSUnset(mergedData, schema); crsErr != nil {
|
|
glog.Warningf("iceberg compact: geometry CRS left as written in bin %d: %v", binIdx, crsErr)
|
|
} else {
|
|
mergedData = fixed
|
|
}
|
|
|
|
// Write merged file to filer
|
|
if err := ensureFilerDir(ctx, filerClient, dataDir); err != nil {
|
|
return "", nil, fmt.Errorf("ensure data dir: %w", err)
|
|
}
|
|
if err := saveFilerFile(ctx, filerClient, dataDir, mergedFileName, mergedData); err != nil {
|
|
return "", nil, fmt.Errorf("save merged file: %w", err)
|
|
}
|
|
|
|
// Use the partition spec matching this bin's spec ID
|
|
{
|
|
binSpec, ok := specLookup[int(bin.SpecID)]
|
|
if !ok {
|
|
glog.Warningf("iceberg compact: spec %d not found for bin %d, skipping", bin.SpecID, binIdx)
|
|
_ = deleteFilerFile(ctx, filerClient, dataDir, mergedFileName)
|
|
goto binDone
|
|
}
|
|
|
|
// Create new DataFile entry for the merged file
|
|
dfBuilder, err := iceberg.NewDataFileBuilder(
|
|
binSpec,
|
|
iceberg.EntryContentData,
|
|
mergedFilePath,
|
|
iceberg.ParquetFile,
|
|
bin.Partition,
|
|
nil, nil,
|
|
recordCount,
|
|
int64(len(mergedData)),
|
|
)
|
|
if err != nil {
|
|
glog.Warningf("iceberg compact: failed to build data file entry for bin %d: %v", binIdx, err)
|
|
_ = deleteFilerFile(ctx, filerClient, dataDir, mergedFileName)
|
|
goto binDone
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: dataDir, fileName: mergedFileName})
|
|
|
|
// Record the column statistics readers prune files by; without
|
|
// them every scan has to read every compacted file.
|
|
if stats, statsErr := collectColumnStats(mergedData, schema); statsErr != nil {
|
|
glog.Warningf("iceberg compact: no column statistics for %s: %v", mergedFileName, statsErr)
|
|
} else {
|
|
stats.applyTo(dfBuilder)
|
|
}
|
|
|
|
// A merged file keeps its rows' row IDs, so its entry names the first
|
|
// materialized one instead of inheriting a fresh range at commit.
|
|
if lineage {
|
|
firstID, err := mergedFileFirstRowID(mergedData)
|
|
if err != nil {
|
|
glog.Warningf("iceberg compact: failed to read merged file lineage for bin %d: %v", binIdx, err)
|
|
_ = deleteFilerFile(ctx, filerClient, dataDir, mergedFileName)
|
|
goto binDone
|
|
}
|
|
if firstID != nil {
|
|
dfBuilder.FirstRowID(*firstID)
|
|
}
|
|
}
|
|
|
|
mergedDataFile := dfBuilder.Build()
|
|
summary.addFile(mergedDataFile)
|
|
newEntry := iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusADDED,
|
|
&newSnapID,
|
|
nil, nil,
|
|
mergedDataFile,
|
|
)
|
|
newManifestEntries = append(newManifestEntries, newEntry)
|
|
|
|
// Mark original entries as deleted
|
|
removeBinEntries(bin)
|
|
if fellBack {
|
|
spatialFallbackBins++
|
|
} else {
|
|
spatialBins++
|
|
}
|
|
}
|
|
|
|
binDone:
|
|
if onProgress != nil {
|
|
onProgress(binIdx, len(bins))
|
|
}
|
|
}
|
|
|
|
if totalMerged == 0 {
|
|
return "no bins successfully compacted", nil, nil
|
|
}
|
|
|
|
// Build entries for the new manifests:
|
|
// - ADDED entries for merged files
|
|
// - DELETED entries for original files
|
|
// - EXISTING entries for files that weren't compacted
|
|
compactedPaths := make(map[string]struct{})
|
|
for _, entry := range deletedManifestEntries {
|
|
compactedPaths[entry.DataFile().FilePath()] = struct{}{}
|
|
}
|
|
|
|
// Group all manifest entries by spec ID for per-spec manifest writing.
|
|
type specEntries struct {
|
|
specID int32
|
|
entries []iceberg.ManifestEntry
|
|
}
|
|
specEntriesMap := make(map[int32]*specEntries)
|
|
|
|
addToSpec := func(specID int32, entry iceberg.ManifestEntry) {
|
|
se, ok := specEntriesMap[specID]
|
|
if !ok {
|
|
se = &specEntries{specID: specID}
|
|
specEntriesMap[specID] = se
|
|
}
|
|
se.entries = append(se.entries, entry)
|
|
}
|
|
|
|
// New and deleted entries carry the spec ID from their bin
|
|
for _, entry := range newManifestEntries {
|
|
addToSpec(entry.DataFile().SpecID(), entry)
|
|
}
|
|
for _, entry := range deletedManifestEntries {
|
|
addToSpec(entry.DataFile().SpecID(), entry)
|
|
}
|
|
|
|
// Existing entries that weren't compacted
|
|
for _, entry := range allEntries {
|
|
if _, compacted := compactedPaths[entry.DataFile().FilePath()]; !compacted {
|
|
existingEntry := iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusEXISTING,
|
|
func() *int64 { id := entry.SnapshotID(); return &id }(),
|
|
entrySeqNum(entry), entryFileSeqNum(entry),
|
|
entry.DataFile(),
|
|
)
|
|
addToSpec(entry.DataFile().SpecID(), existingEntry)
|
|
}
|
|
}
|
|
|
|
// Write one manifest per spec ID, iterating in sorted order for
|
|
// deterministic manifest list construction.
|
|
sortedSpecIDs := make([]int32, 0, len(specEntriesMap))
|
|
for sid := range specEntriesMap {
|
|
sortedSpecIDs = append(sortedSpecIDs, sid)
|
|
}
|
|
sort.Slice(sortedSpecIDs, func(i, j int) bool { return sortedSpecIDs[i] < sortedSpecIDs[j] })
|
|
|
|
var allManifests []iceberg.ManifestFile
|
|
for _, sid := range sortedSpecIDs {
|
|
se := specEntriesMap[sid]
|
|
ps, ok := specLookup[int(se.specID)]
|
|
if !ok {
|
|
return "", nil, fmt.Errorf("partition spec %d not found in table metadata", se.specID)
|
|
}
|
|
|
|
var manifestBuf bytes.Buffer
|
|
manifestFileName := fmt.Sprintf("compact-%d-%s-spec%d.avro", newSnapID, artifactSuffix, se.specID)
|
|
newManifest, err := iceberg.WriteManifest(
|
|
absoluteIcebergPath(bucketName, dataPath, "metadata", manifestFileName),
|
|
&manifestBuf,
|
|
version,
|
|
ps,
|
|
schema,
|
|
newSnapID,
|
|
se.entries,
|
|
)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("write compact manifest for spec %d: %w", se.specID, err)
|
|
}
|
|
|
|
if err := saveFilerFile(ctx, filerClient, metaDir, manifestFileName, manifestBuf.Bytes()); err != nil {
|
|
return "", nil, fmt.Errorf("save compact manifest for spec %d: %w", se.specID, err)
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: manifestFileName})
|
|
allManifests = append(allManifests, newManifest)
|
|
}
|
|
|
|
// Carry forward delete manifests only if deletes were NOT applied.
|
|
// When deletes were applied, they've been consumed during the merge.
|
|
// Position deletes reference specific data files — if all those files
|
|
// were compacted, the deletes are fully consumed. Equality deletes
|
|
// apply broadly, so they're only consumed if all data files were compacted.
|
|
carryDeletes := !config.ApplyDeletes || (len(positionDeletes) == 0 && len(eqDeleteGroups) == 0)
|
|
if !carryDeletes {
|
|
// Deletes still apply to any file that wasn't compacted.
|
|
for _, entry := range allEntries {
|
|
if _, compacted := compactedPaths[entry.DataFile().FilePath()]; !compacted {
|
|
carryDeletes = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if carryDeletes {
|
|
// A deletion vector whose data file this compaction removed leaves
|
|
// with it; the rest of the delete files carry on.
|
|
consumed, err := consumedDeletionVectors(dvs, deletedManifestEntries, bucketName, dataPath)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if len(consumed) == 0 {
|
|
allManifests = append(allManifests, deleteManifests...)
|
|
} else {
|
|
rewritten, names, err := rewriteDeleteManifestsWithout(ctx, filerClient, bucketName, dataPath, metaDir,
|
|
deleteManifests, consumed, version, specLookup, schema, newSnapID, artifactSuffix, &summary)
|
|
for _, name := range names {
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: name})
|
|
}
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
allManifests = append(allManifests, rewritten...)
|
|
}
|
|
} else {
|
|
// All files were compacted, so the deletes leave the table with them.
|
|
for _, entry := range allDeleteEntries {
|
|
summary.removeFile(entry.DataFile())
|
|
}
|
|
}
|
|
|
|
// Write new manifest list
|
|
var manifestListBuf bytes.Buffer
|
|
seqNum := currentSnap.SequenceNumber + 1
|
|
addedRows, err := writeManifestList(version, &manifestListBuf, newSnapID, &snapshotID, &seqNum, firstRowID, allManifests)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("write compact manifest list: %w", err)
|
|
}
|
|
|
|
manifestListFileName := fmt.Sprintf("snap-%d-%s.avro", newSnapID, artifactSuffix)
|
|
if err := saveFilerFile(ctx, filerClient, metaDir, manifestListFileName, manifestListBuf.Bytes()); err != nil {
|
|
return "", nil, fmt.Errorf("save compact manifest list: %w", err)
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: manifestListFileName})
|
|
|
|
// Commit: add new snapshot and update main branch ref
|
|
manifestListLocation := absoluteIcebergPath(bucketName, dataPath, "metadata", manifestListFileName)
|
|
err = h.commitWithRetry(ctx, filerClient, bucketName, tablePath, state.MetadataFileName, config, func(currentMeta table.Metadata, builder *table.MetadataBuilder) error {
|
|
// Guard: verify table head hasn't advanced since we planned.
|
|
cs, err := checkCommitPlan(currentMeta, snapshotID, version, firstRowID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
newSnapshot := &table.Snapshot{
|
|
SnapshotID: newSnapID,
|
|
ParentSnapshotID: &snapshotID,
|
|
SequenceNumber: seqNum,
|
|
TimestampMs: newSnapID,
|
|
ManifestList: manifestListLocation,
|
|
Summary: summary.build(table.OpReplace, cs, map[string]string{
|
|
"maintenance": "compact_data_files",
|
|
"merged-files": fmt.Sprintf("%d", totalMerged),
|
|
"new-files": fmt.Sprintf("%d", len(newManifestEntries)),
|
|
"compaction-bins": fmt.Sprintf("%d", len(bins)),
|
|
"rewrite-strategy": rewritePlan.strategy,
|
|
}),
|
|
SchemaID: func() *int {
|
|
id := schema.ID
|
|
return &id
|
|
}(),
|
|
}
|
|
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
|
|
}
|
|
return builder.SetSnapshotRef(table.MainBranch, newSnapID, table.BranchRef)
|
|
})
|
|
if err != nil {
|
|
// a commit that may have landed references what was written, so orphan removal decides
|
|
keepArtifacts = errors.Is(err, errCommitOutcomeUnknown)
|
|
return "", nil, fmt.Errorf("commit compaction: %w", err)
|
|
}
|
|
|
|
keepArtifacts = true
|
|
metrics := map[string]int64{
|
|
MetricFilesMerged: int64(totalMerged),
|
|
MetricFilesWritten: int64(len(newManifestEntries)),
|
|
MetricBins: int64(len(bins)),
|
|
MetricDurationMs: time.Since(start).Milliseconds(),
|
|
}
|
|
result := fmt.Sprintf("compacted %d files into %d (across %d bins)", totalMerged, len(newManifestEntries), len(bins))
|
|
if rewritePlan.sorts() && (rewritePlan.spatial == nil || spatialBins > 0) {
|
|
result = fmt.Sprintf("%s using %s", result, rewritePlan.summaryLabel())
|
|
}
|
|
return result, metrics, nil
|
|
}
|
|
|
|
// buildCompactionBins groups small data files by partition for bin-packing.
|
|
// A file is "small" if it's below targetSize. A bin must have at least
|
|
// minFiles entries to be worth compacting.
|
|
//
|
|
// With an order, every bin lists its files by their bounds on the ordering
|
|
// column and an oversized partition is split into runs of consecutive files,
|
|
// so each merged file covers one contiguous range of that column. Without one
|
|
// 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
|
|
}
|
|
|
|
// Group entries by spec ID + partition key so that files from different
|
|
// partition specs are never mixed in the same compaction bin.
|
|
groups := make(map[string]*compactionBin)
|
|
// the files of each group no merge takes, which no merged file may span
|
|
outside := make(map[string][]iceberg.ManifestEntry)
|
|
for _, entry := range entries {
|
|
df := entry.DataFile()
|
|
partKey := partitionKey(df.Partition())
|
|
groupKey := fmt.Sprintf("spec%d\x00%s", df.SpecID(), partKey)
|
|
// DuckDB writes "parquet" lowercase.
|
|
if !strings.EqualFold(string(df.FileFormat()), string(iceberg.ParquetFile)) || df.FileSizeBytes() >= targetSize {
|
|
outside[groupKey] = append(outside[groupKey], entry)
|
|
continue
|
|
}
|
|
|
|
bin, ok := groups[groupKey]
|
|
if !ok {
|
|
bin = &compactionBin{
|
|
PartitionKey: partKey,
|
|
Partition: df.Partition(),
|
|
SpecID: df.SpecID(),
|
|
}
|
|
groups[groupKey] = bin
|
|
}
|
|
bin.Entries = append(bin.Entries, entry)
|
|
bin.TotalSize += df.FileSizeBytes()
|
|
}
|
|
|
|
// Filter to bins with enough files, splitting oversized bins. The merge
|
|
// order resolves per group over the files that survived the eligibility
|
|
// filter, so a file that can never participate (oversized, another
|
|
// format) cannot veto ordering for the ones that can.
|
|
var result []compactionBin
|
|
for groupKey, bin := range groups {
|
|
if len(bin.Entries) < minFiles {
|
|
continue
|
|
}
|
|
order := compactionOrderFor(meta, bin.Entries, plan)
|
|
order.sortEntries(bin.Entries)
|
|
cuts := order.cutsAround(bin.Entries, outside[groupKey])
|
|
if bin.TotalSize <= targetSize && len(cuts) == 0 {
|
|
result = append(result, *bin)
|
|
} else if order != nil {
|
|
runs, leftover := splitOrderedBin(*bin, targetSize, minFiles, cuts)
|
|
result = append(result, runs...)
|
|
if order.bestEffort && len(leftover) > 0 {
|
|
runtBin := compactionBin{PartitionKey: bin.PartitionKey, Partition: bin.Partition, SpecID: bin.SpecID, Entries: leftover}
|
|
packed := splitOversizedBin(runtBin, targetSize, minFiles)
|
|
if len(packed) == 0 {
|
|
// Stragglers cannot merge even with each other; repacking
|
|
// the whole bin lets them pair across the ordered runs.
|
|
// Only replace the runs when the repack yields bins —
|
|
// otherwise the runs stay valid compaction work.
|
|
if full := splitOversizedBin(*bin, targetSize, minFiles); len(full) > 0 {
|
|
result = result[:len(result)-len(runs)]
|
|
packed = full
|
|
}
|
|
}
|
|
result = append(result, packed...)
|
|
}
|
|
} else {
|
|
result = append(result, splitOversizedBin(*bin, targetSize, minFiles)...)
|
|
}
|
|
}
|
|
|
|
// Sort by spec ID then partition key for deterministic order
|
|
sort.Slice(result, func(i, j int) bool {
|
|
if result[i].SpecID != result[j].SpecID {
|
|
return result[i].SpecID < result[j].SpecID
|
|
}
|
|
return result[i].PartitionKey < result[j].PartitionKey
|
|
})
|
|
|
|
return result
|
|
}
|
|
|
|
// splitOversizedBin splits a bin whose total size exceeds targetSize into
|
|
// sub-bins that stay under targetSize. Bins that cannot reach minFiles
|
|
// without violating targetSize are left uncompacted rather than merged into
|
|
// oversized bins.
|
|
func splitOversizedBin(bin compactionBin, targetSize int64, minFiles int) []compactionBin {
|
|
// Sort largest-first for better packing.
|
|
sorted := make([]iceberg.ManifestEntry, len(bin.Entries))
|
|
copy(sorted, bin.Entries)
|
|
sort.Slice(sorted, func(i, j int) bool {
|
|
return sorted[i].DataFile().FileSizeBytes() > sorted[j].DataFile().FileSizeBytes()
|
|
})
|
|
|
|
var bins []compactionBin
|
|
current := compactionBin{
|
|
PartitionKey: bin.PartitionKey,
|
|
Partition: bin.Partition,
|
|
SpecID: bin.SpecID,
|
|
}
|
|
for _, entry := range sorted {
|
|
if current.TotalSize > 0 && current.TotalSize+entry.DataFile().FileSizeBytes() > targetSize {
|
|
bins = append(bins, current)
|
|
current = compactionBin{
|
|
PartitionKey: bin.PartitionKey,
|
|
Partition: bin.Partition,
|
|
SpecID: bin.SpecID,
|
|
}
|
|
}
|
|
current.Entries = append(current.Entries, entry)
|
|
current.TotalSize += entry.DataFile().FileSizeBytes()
|
|
}
|
|
if len(current.Entries) > 0 {
|
|
bins = append(bins, current)
|
|
}
|
|
|
|
var valid []compactionBin
|
|
var pending []compactionBin
|
|
for _, candidate := range bins {
|
|
if len(candidate.Entries) >= minFiles {
|
|
valid = append(valid, candidate)
|
|
continue
|
|
}
|
|
pending = append(pending, candidate)
|
|
}
|
|
|
|
// Try to fold entries from underfilled bins into valid bins when they fit.
|
|
for _, runt := range pending {
|
|
for _, entry := range runt.Entries {
|
|
bestIdx := -1
|
|
bestRemaining := int64(-1)
|
|
entrySize := entry.DataFile().FileSizeBytes()
|
|
for i := range valid {
|
|
remaining := targetSize - valid[i].TotalSize - entrySize
|
|
if remaining < 0 {
|
|
continue
|
|
}
|
|
if bestIdx == -1 || remaining < bestRemaining {
|
|
bestIdx = i
|
|
bestRemaining = remaining
|
|
}
|
|
}
|
|
if bestIdx >= 0 {
|
|
valid[bestIdx].Entries = append(valid[bestIdx].Entries, entry)
|
|
valid[bestIdx].TotalSize += entrySize
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(valid) == 0 {
|
|
return nil
|
|
}
|
|
return valid
|
|
}
|
|
|
|
// partitionKey creates a string key from a partition map for grouping.
|
|
// Values are JSON-encoded to avoid ambiguity when values contain commas or '='.
|
|
func partitionKey(partition map[int]any) string {
|
|
if len(partition) == 0 {
|
|
return "__unpartitioned__"
|
|
}
|
|
|
|
// Sort field IDs for deterministic key
|
|
ids := make([]int, 0, len(partition))
|
|
for id := range partition {
|
|
ids = append(ids, id)
|
|
}
|
|
sort.Ints(ids)
|
|
|
|
var parts []string
|
|
for _, id := range ids {
|
|
v, err := json.Marshal(partition[id])
|
|
if err != nil {
|
|
v = []byte(fmt.Sprintf("%x", fmt.Sprintf("%v", partition[id])))
|
|
}
|
|
parts = append(parts, fmt.Sprintf("%d=%s", id, v))
|
|
}
|
|
return strings.Join(parts, "\x00")
|
|
}
|
|
|
|
// isPuffin reports whether a delete file is a Puffin deletion vector. The
|
|
// format is compared without case: some writers (DuckDB among them) record
|
|
// it as "puffin", as they record "parquet", while iceberg-go's constant is
|
|
// "PUFFIN".
|
|
func isPuffin(df iceberg.DataFile) bool {
|
|
return strings.EqualFold(string(df.FileFormat()), string(iceberg.PuffinFile))
|
|
}
|
|
|
|
// collectPositionDeletes reads position delete Parquet files and returns a map
|
|
// from normalized data file path to sorted row positions that should be deleted.
|
|
// Paths are normalized so that absolute S3 URLs and relative paths match.
|
|
func collectPositionDeletes(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
deleteEntries []iceberg.ManifestEntry,
|
|
) (map[string][]int64, error) {
|
|
result := make(map[string][]int64)
|
|
for _, entry := range deleteEntries {
|
|
df := entry.DataFile()
|
|
if df.ContentType() != iceberg.EntryContentPosDeletes || isPuffin(df) {
|
|
continue // Puffin is a deletion vector, not a row-level delete file
|
|
}
|
|
fileDeletes, err := readPositionDeleteFile(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read position delete file %s: %w", entry.DataFile().FilePath(), err)
|
|
}
|
|
for filePath, positions := range fileDeletes {
|
|
normalized, err := normalizeIcebergPath(filePath, bucketName, dataPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve deleted file %s: %w", filePath, err)
|
|
}
|
|
result[normalized] = append(result[normalized], positions...)
|
|
}
|
|
}
|
|
// Sort positions for each file (binary search during filtering)
|
|
for filePath := range result {
|
|
sort.Slice(result[filePath], func(i, j int) bool {
|
|
return result[filePath][i] < result[filePath][j]
|
|
})
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// readPositionDeleteFile reads a position delete Parquet file and returns a map
|
|
// from data file path to row positions. The file must have columns "file_path"
|
|
// (string) and "pos" (int32 or int64).
|
|
func readPositionDeleteFile(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath, filePath string,
|
|
) (_ map[string][]int64, err error) {
|
|
defer recoverRead(&err, filePath)
|
|
data, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reader, err := newParquetReader(data, filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer reader.Close()
|
|
|
|
pqSchema := reader.Schema()
|
|
filePathIdx := -1
|
|
posIdx := -1
|
|
for i, col := range pqSchema.Columns() {
|
|
name := strings.Join(col, ".")
|
|
switch name {
|
|
case "file_path":
|
|
filePathIdx = i
|
|
case "pos":
|
|
posIdx = i
|
|
}
|
|
}
|
|
if filePathIdx < 0 || posIdx < 0 {
|
|
return nil, fmt.Errorf("position delete file %s missing required columns (file_path=%d, pos=%d)", filePath, filePathIdx, posIdx)
|
|
}
|
|
|
|
result := make(map[string][]int64)
|
|
rows := make([]parquet.Row, 256)
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
default:
|
|
}
|
|
n, readErr := reader.ReadRows(rows)
|
|
for i := 0; i < n; i++ {
|
|
row := rows[i]
|
|
fp := row[filePathIdx].String()
|
|
pos := row[posIdx].Int64()
|
|
result[fp] = append(result[fp], pos)
|
|
}
|
|
if readErr != nil {
|
|
if readErr == io.EOF {
|
|
break
|
|
}
|
|
return nil, fmt.Errorf("read rows from %s: %w", filePath, readErr)
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// equalityDeleteGroup holds the delete keys of the equality delete files that
|
|
// share one set of equality field IDs and one scope. An equality delete file
|
|
// applies only to data files with a lower data sequence number, and only in
|
|
// its own partition unless its spec is unpartitioned (Iceberg spec, "Scan
|
|
// Planning"): each key keeps the highest data sequence number of the delete
|
|
// files carrying it, and the group the partition it applies to.
|
|
type equalityDeleteGroup struct {
|
|
FieldIDs []int
|
|
Keys map[string]int64 // key -> highest data sequence number of a delete file carrying it
|
|
Scope deleteScope // where the group applies
|
|
}
|
|
|
|
// deleteInPredicateScope reports whether a delete file may apply to a bin a
|
|
// where filter keeps: an unpartitioned one always (it has no field a clause
|
|
// could match, and applies to every partition), one whose scope cannot be
|
|
// decided always (collectEqualityDeletes then refuses it rather than drop it),
|
|
// a partitioned one when its partition matches.
|
|
func deleteInPredicateScope(entry iceberg.ManifestEntry, predicate *partitionPredicate, specs map[int]iceberg.PartitionSpec, schema *iceberg.Schema) (bool, error) {
|
|
if predicate == nil {
|
|
return true, nil
|
|
}
|
|
scope, err := deleteFileScope(entry.DataFile(), specs, schema)
|
|
if err != nil {
|
|
return true, nil
|
|
}
|
|
if scope.global {
|
|
return true, nil
|
|
}
|
|
return predicate.Matches(specs[int(entry.DataFile().SpecID())], entry.DataFile().Partition())
|
|
}
|
|
|
|
// collectEqualityDeletes reads equality delete Parquet files and returns groups
|
|
// of delete keys, one per distinct set of equality field IDs and scope. This
|
|
// correctly handles the case where different delete files use different
|
|
// equality columns. A delete file without a data sequence number cannot be
|
|
// ordered against the rows it may delete, and is an error.
|
|
func collectEqualityDeletes(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
deleteEntries []iceberg.ManifestEntry,
|
|
schema *iceberg.Schema,
|
|
specs map[int]iceberg.PartitionSpec,
|
|
) ([]equalityDeleteGroup, error) {
|
|
groups := make(map[string]*equalityDeleteGroup)
|
|
var order []string
|
|
|
|
for _, entry := range deleteEntries {
|
|
if entry.DataFile().ContentType() != iceberg.EntryContentEqDeletes {
|
|
continue
|
|
}
|
|
eqFieldIDs := entry.DataFile().EqualityFieldIDs()
|
|
if len(eqFieldIDs) == 0 {
|
|
continue
|
|
}
|
|
|
|
seq := entry.SequenceNum()
|
|
if seq < 0 {
|
|
return nil, fmt.Errorf("equality delete file %s has no data sequence number", entry.DataFile().FilePath())
|
|
}
|
|
scope, err := deleteFileScope(entry.DataFile(), specs, schema)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
groupKey := fmt.Sprintf("%v\x00%s", eqFieldIDs, scope.key())
|
|
gs, ok := groups[groupKey]
|
|
if !ok {
|
|
gs = &equalityDeleteGroup{FieldIDs: eqFieldIDs, Keys: make(map[string]int64), Scope: scope}
|
|
groups[groupKey] = gs
|
|
order = append(order, groupKey)
|
|
}
|
|
|
|
keys, err := readEqualityDeleteFile(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath(), eqFieldIDs, schema)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read equality delete file %s: %w", entry.DataFile().FilePath(), err)
|
|
}
|
|
for k := range keys {
|
|
if cur, seen := gs.Keys[k]; !seen || seq > cur {
|
|
gs.Keys[k] = seq
|
|
}
|
|
}
|
|
}
|
|
|
|
result := make([]equalityDeleteGroup, 0, len(groups))
|
|
for _, k := range order {
|
|
result = append(result, *groups[k])
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// readEqualityDeleteFile reads an equality delete Parquet file and returns a set
|
|
// of composite keys built from the specified field IDs. The Iceberg schema is used
|
|
// to map field IDs to column names, which are then looked up in the Parquet schema.
|
|
func readEqualityDeleteFile(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath, filePath string,
|
|
fieldIDs []int,
|
|
icebergSchema *iceberg.Schema,
|
|
) (_ map[string]struct{}, err error) {
|
|
defer recoverRead(&err, filePath)
|
|
data, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reader, err := newParquetReader(data, filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer reader.Close()
|
|
|
|
colIndices, err := resolveEqualityColIndices(reader.Schema(), fieldIDs, icebergSchema, false)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve columns in %s: %w", filePath, err)
|
|
}
|
|
|
|
result := make(map[string]struct{})
|
|
rows := make([]parquet.Row, 256)
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
default:
|
|
}
|
|
n, readErr := reader.ReadRows(rows)
|
|
for i := 0; i < n; i++ {
|
|
key := buildEqualityKey(rows[i], colIndices)
|
|
result[key] = struct{}{}
|
|
}
|
|
if readErr != nil {
|
|
if readErr == io.EOF {
|
|
break
|
|
}
|
|
return nil, fmt.Errorf("read rows from %s: %w", filePath, readErr)
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// buildEqualityKey builds a composite string key from specific column values
|
|
// in a row. Each value is serialized as "kind:length:value" to avoid ambiguity
|
|
// between types (e.g., int 123 vs string "123") and to prevent collisions from
|
|
// values containing separator characters. A negative column index is a field
|
|
// the file lacks: the value there is null.
|
|
func buildEqualityKey(row parquet.Row, colIndices []int) string {
|
|
if len(colIndices) == 1 {
|
|
v := equalityKeyValue(row, colIndices[0])
|
|
s := v.String()
|
|
return fmt.Sprintf("%d:%d:%s", v.Kind(), len(s), s)
|
|
}
|
|
var b strings.Builder
|
|
for _, idx := range colIndices {
|
|
v := equalityKeyValue(row, idx)
|
|
s := v.String()
|
|
fmt.Fprintf(&b, "%d:%d:%s", v.Kind(), len(s), s)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func equalityKeyValue(row parquet.Row, idx int) parquet.Value {
|
|
if idx < 0 {
|
|
return parquet.NullValue()
|
|
}
|
|
return row[idx]
|
|
}
|
|
|
|
// resolveEqualityColIndices maps Iceberg field IDs to Parquet column indices.
|
|
// A file carrying field ids resolves by id, so a column renamed since the
|
|
// file was written still matches; one without ids falls back to the Iceberg
|
|
// name. allowMissing reads a column the file lacks as null (-1 marks it in
|
|
// the key): for data files only — an equality-delete file always carries
|
|
// its equality columns, so a missing one stays an error there.
|
|
func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, icebergSchema *iceberg.Schema, allowMissing bool) ([]int, error) {
|
|
if len(fieldIDs) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
colNameToIdx := make(map[string]int)
|
|
for i, col := range pqSchema.Columns() {
|
|
colNameToIdx[strings.Join(col, ".")] = i
|
|
}
|
|
idToIdx := make(map[int]int)
|
|
for _, f := range pqSchema.Fields() {
|
|
if f.Leaf() && f.ID() > 0 {
|
|
if idx, ok := colNameToIdx[f.Name()]; ok {
|
|
idToIdx[f.ID()] = idx
|
|
}
|
|
}
|
|
}
|
|
|
|
indices := make([]int, len(fieldIDs))
|
|
for i, fid := range fieldIDs {
|
|
field, ok := icebergSchema.FindFieldByID(fid)
|
|
if !ok {
|
|
return nil, fmt.Errorf("field ID %d not found in iceberg schema", fid)
|
|
}
|
|
idx, ok := idToIdx[fid]
|
|
if !ok && len(idToIdx) == 0 {
|
|
idx, ok = colNameToIdx[field.Name]
|
|
}
|
|
if !ok {
|
|
// An optional column added to the table after this file was
|
|
// written reads as null there (-1 marks it in the key).
|
|
if allowMissing && !field.Required {
|
|
indices[i] = -1
|
|
continue
|
|
}
|
|
return nil, fmt.Errorf("column %q (field ID %d) not found in parquet schema", field.Name, fid)
|
|
}
|
|
indices[i] = idx
|
|
}
|
|
return indices, nil
|
|
}
|
|
|
|
const (
|
|
// Iceberg's write.parquet.row-group-size-bytes default and PyIceberg's
|
|
// write.parquet.row-group-limit default.
|
|
defaultRowGroupSizeBytes = 128 * 1024 * 1024
|
|
defaultRowGroupRowLimit = 1048576
|
|
minRowGroupRows = 1024
|
|
)
|
|
|
|
// rowsPerRowGroup is the most rows one row group of a compacted file holds:
|
|
// the row limit, lowered so a row group stays near the byte size, estimated
|
|
// from the bin's inputs' bytes per row. parquet-go's writers have no limit of
|
|
// their own, so without one every compacted file is a single row group. The
|
|
// floor only protects the estimate — a configured row limit always wins.
|
|
func rowsPerRowGroup(bin compactionBin, config Config) int64 {
|
|
rows, sizeBytes := config.RowGroupRowLimit, config.RowGroupSizeBytes
|
|
explicit := rows > 0
|
|
if !explicit {
|
|
rows = defaultRowGroupRowLimit
|
|
}
|
|
if sizeBytes <= 0 {
|
|
sizeBytes = defaultRowGroupSizeBytes
|
|
}
|
|
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, 1)
|
|
if !explicit {
|
|
estimated = max(estimated, minRowGroupRows)
|
|
}
|
|
rows = min(rows, estimated)
|
|
}
|
|
if !explicit {
|
|
rows = max(rows, minRowGroupRows)
|
|
}
|
|
return rows
|
|
}
|
|
|
|
// rowsPerRowGroupFor is rowsPerRowGroup for the plan: a spatial rewrite
|
|
// targets the smaller spatial row group size (capped by row_group_size_mb or
|
|
// 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
|
|
// proportional to a single input file plus the output buffer.
|
|
func mergeParquetFiles(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
entries []iceberg.ManifestEntry,
|
|
positionDeletes map[string][]int64,
|
|
eqDeleteGroups []equalityDeleteGroup,
|
|
icebergSchema *iceberg.Schema,
|
|
rowGroupRows int64,
|
|
lineage bool,
|
|
) ([]byte, int64, error) {
|
|
// On a v1/v2 table the writer's schema is chosen before any row is
|
|
// written: the union of the bin's file schemas by field id, so a bin of
|
|
// progressively wider files merges in one pass instead of restarting
|
|
// (and rewriting every earlier file) on each wider one. The v3 merge
|
|
// keeps the first file's columns plus the lineage columns.
|
|
var target *parquet.Schema
|
|
if !lineage {
|
|
var err error
|
|
if target, err = binWriterSchema(ctx, filerClient, bucketName, dataPath, entries); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
}
|
|
for attempt := 0; ; attempt++ {
|
|
out, rows, err := mergeParquetFilesInto(ctx, filerClient, bucketName, dataPath, entries, positionDeletes,
|
|
eqDeleteGroups, icebergSchema, rowGroupRows, lineage, target)
|
|
var wider *widerSchemaError
|
|
if errors.As(err, &wider) && attempt < len(entries) {
|
|
target = wider.schema
|
|
continue
|
|
}
|
|
return out, rows, err
|
|
}
|
|
}
|
|
|
|
// binWriterSchema is the writer schema for a v1/v2 bin-pack merge: the union
|
|
// of the files' schemas by field id. Only each file's footer is read to learn
|
|
// its schema; the merge then downloads each file once. Files whose schemas
|
|
// cannot union (no field ids, nested or repeated columns, a field id or name
|
|
// carrying different types) merge only under the old rule — every file's
|
|
// schema equal to the first — and the bin is refused as before otherwise.
|
|
func binWriterSchema(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
entries []iceberg.ManifestEntry,
|
|
) (*parquet.Schema, error) {
|
|
var union schemaUnion
|
|
var first *parquet.Schema
|
|
unionable, allEqual := true, true
|
|
for _, entry := range entries {
|
|
source := entry.DataFile().FilePath()
|
|
schema, err := parquetSchemaByIcebergPath(ctx, filerClient, bucketName, dataPath, source)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("schema of %s: %w", source, err)
|
|
}
|
|
if schema == nil {
|
|
return nil, fmt.Errorf("no parquet schema found in %s", source)
|
|
}
|
|
if first == nil {
|
|
first = schema
|
|
} else if !schemasEqual(first, schema) {
|
|
allEqual = false
|
|
}
|
|
if unionable {
|
|
unionable = union.fold(schema, source) == nil
|
|
}
|
|
if !unionable && !allEqual {
|
|
return nil, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", source)
|
|
}
|
|
}
|
|
if !unionable || first == nil {
|
|
return nil, nil // every file spells the first file's schema
|
|
}
|
|
return union.schema(first.Name(), first), nil
|
|
}
|
|
|
|
// mergeParquetFilesInto merges with target as the writer's schema on a v1/v2
|
|
// table (nil: the first file's).
|
|
func mergeParquetFilesInto(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
entries []iceberg.ManifestEntry,
|
|
positionDeletes map[string][]int64,
|
|
eqDeleteGroups []equalityDeleteGroup,
|
|
icebergSchema *iceberg.Schema,
|
|
rowGroupRows int64,
|
|
lineage bool,
|
|
target *parquet.Schema,
|
|
) ([]byte, int64, error) {
|
|
if len(entries) == 0 {
|
|
return nil, 0, fmt.Errorf("no entries to merge")
|
|
}
|
|
|
|
// Load the first file to obtain the schema for the writer.
|
|
firstData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, entries[0].DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, 0, fmt.Errorf("read parquet file %s: %w", entries[0].DataFile().FilePath(), err)
|
|
}
|
|
firstReader, err := newParquetReader(firstData, entries[0].DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
parquetSchema := firstReader.Schema()
|
|
if parquetSchema == nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("no parquet schema found in %s", entries[0].DataFile().FilePath())
|
|
}
|
|
|
|
resolvedEqGroups, err := resolveEqualityDeleteGroupsForSchema(parquetSchema, eqDeleteGroups, icebergSchema)
|
|
if err != nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("resolve equality columns: %w", err)
|
|
}
|
|
|
|
// On a v3 table the output is the first file's columns plus the lineage
|
|
// columns (row_lineage.go).
|
|
outputSchema := parquetSchema
|
|
var layout *lineageLayout
|
|
if lineage {
|
|
if layout, err = newLineageLayout(parquetSchema); err != nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("schema of %s: %w", entries[0].DataFile().FilePath(), err)
|
|
}
|
|
outputSchema = layout.schema
|
|
} else if target != nil {
|
|
outputSchema = target
|
|
}
|
|
|
|
// joins is how one file enters the merge on a v1/v2 table: converted into
|
|
// the writer's schema when that covers it, with its equality-delete
|
|
// columns resolved on its own schema.
|
|
joins := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (parquet.Conversion, []resolvedEqDeleteGroup, error) {
|
|
if layout != nil {
|
|
return nil, resolvedEqGroups, nil // a v3 merge matches files with their lineage columns set aside
|
|
}
|
|
source := entry.DataFile().FilePath()
|
|
conv, err := evolvedFileConversion(outputSchema, reader.Schema(), source)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if schemasEqual(parquetSchema, reader.Schema()) {
|
|
return conv, resolvedEqGroups, nil
|
|
}
|
|
groups, err := resolveEqualityDeleteGroupsForSchema(reader.Schema(), eqDeleteGroups, icebergSchema)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("resolve equality columns in %s: %w", source, err)
|
|
}
|
|
return conv, groups, nil
|
|
}
|
|
|
|
var outputBuf bytes.Buffer
|
|
writer := parquet.NewWriter(&outputBuf, outputSchema, parquet.MaxRowsPerRowGroup(rowGroupRows))
|
|
|
|
drainReader := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (_ int64, err error) {
|
|
source := entry.DataFile().FilePath()
|
|
defer recoverRead(&err, source)
|
|
conv, groups, err := joins(reader, entry)
|
|
if err != nil {
|
|
reader.Close()
|
|
return 0, err
|
|
}
|
|
return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, groups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error {
|
|
if conv != nil {
|
|
if _, err := conv.Convert(filtered); err != nil {
|
|
return fmt.Errorf("convert rows from %s: %w", source, err)
|
|
}
|
|
}
|
|
if _, err := writer.WriteRows(filtered); err != nil {
|
|
return fmt.Errorf("write rows from %s: %w", source, err)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// Drain the first file.
|
|
totalRows, err := drainReader(firstReader, entries[0])
|
|
if err != nil {
|
|
writer.Close()
|
|
return nil, 0, err
|
|
}
|
|
firstData = nil // allow GC
|
|
|
|
// Process remaining files one at a time.
|
|
for _, entry := range entries[1:] {
|
|
select {
|
|
case <-ctx.Done():
|
|
writer.Close()
|
|
return nil, 0, ctx.Err()
|
|
default:
|
|
}
|
|
|
|
data, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
writer.Close()
|
|
return nil, 0, fmt.Errorf("read parquet file %s: %w", entry.DataFile().FilePath(), err)
|
|
}
|
|
|
|
reader, err := newParquetReader(data, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
writer.Close()
|
|
return nil, 0, err
|
|
}
|
|
rowsWritten, err := drainReader(reader, entry)
|
|
if err != nil {
|
|
writer.Close()
|
|
return nil, 0, err
|
|
}
|
|
totalRows += rowsWritten
|
|
// data goes out of scope here, eligible for GC before next iteration.
|
|
}
|
|
|
|
if err := writer.Close(); err != nil {
|
|
return nil, 0, fmt.Errorf("close writer: %w", err)
|
|
}
|
|
|
|
return outputBuf.Bytes(), totalRows, nil
|
|
}
|
|
|
|
type resolvedEqDeleteGroup struct {
|
|
colIndices []int
|
|
keys map[string]int64 // key -> highest data sequence number of a delete carrying it
|
|
}
|
|
|
|
// equalityDeletesFor returns the data sequence number of entry's data file: a
|
|
// row is deleted only by a key whose delete files' sequence number is higher.
|
|
// The groups are already the bin's (eqDeleteGroupsForBin). A data file without
|
|
// one, when deletes may apply to it, is an error rather than a guess.
|
|
func equalityDeletesFor(groups []resolvedEqDeleteGroup, entry iceberg.ManifestEntry) ([]resolvedEqDeleteGroup, int64, error) {
|
|
dataSeq := entry.SequenceNum()
|
|
if len(groups) > 0 && dataSeq < 0 {
|
|
return nil, 0, fmt.Errorf("data file %s has no data sequence number to order its equality deletes against", entry.DataFile().FilePath())
|
|
}
|
|
return groups, dataSeq, nil
|
|
}
|
|
|
|
func resolveEqualityDeleteGroupsForSchema(
|
|
parquetSchema *parquet.Schema,
|
|
eqDeleteGroups []equalityDeleteGroup,
|
|
icebergSchema *iceberg.Schema,
|
|
) ([]resolvedEqDeleteGroup, error) {
|
|
if len(eqDeleteGroups) == 0 || icebergSchema == nil {
|
|
return nil, nil
|
|
}
|
|
|
|
resolved := make([]resolvedEqDeleteGroup, 0, len(eqDeleteGroups))
|
|
for _, g := range eqDeleteGroups {
|
|
indices, err := resolveEqualityColIndices(parquetSchema, g.FieldIDs, icebergSchema, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resolved = append(resolved, resolvedEqDeleteGroup{colIndices: indices, keys: g.Keys})
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
func visitFilteredParquetRows(
|
|
ctx context.Context,
|
|
reader *parquet.Reader,
|
|
source, bucketName, dataPath string,
|
|
positionDeletes map[string][]int64,
|
|
resolvedEqGroups []resolvedEqDeleteGroup,
|
|
dataSeq int64, // the file's data sequence number: only later deletes apply to it
|
|
onRows func(rows []parquet.Row, positions []int64) error,
|
|
) (int64, error) {
|
|
defer reader.Close()
|
|
|
|
rows := make([]parquet.Row, 256)
|
|
filteredRows := make([]parquet.Row, 0, len(rows))
|
|
// each kept row's position in the file before any delete: what a v3
|
|
// _row_id is inherited from
|
|
filteredPositions := make([]int64, 0, len(rows))
|
|
normalizedSource, err := normalizeIcebergPath(source, bucketName, dataPath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
posDeletes := positionDeletes[normalizedSource]
|
|
posDeleteIdx := 0
|
|
var absolutePos int64
|
|
var totalRows int64
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return totalRows, ctx.Err()
|
|
default:
|
|
}
|
|
|
|
n, readErr := reader.ReadRows(rows)
|
|
if n > 0 {
|
|
filteredRows = filteredRows[:0]
|
|
filteredPositions = filteredPositions[:0]
|
|
for i := 0; i < n; i++ {
|
|
rowPos := absolutePos + int64(i)
|
|
for posDeleteIdx < len(posDeletes) && posDeletes[posDeleteIdx] < rowPos {
|
|
posDeleteIdx++
|
|
}
|
|
if posDeleteIdx < len(posDeletes) && posDeletes[posDeleteIdx] == rowPos {
|
|
posDeleteIdx++
|
|
continue
|
|
}
|
|
|
|
deleted := false
|
|
for _, g := range resolvedEqGroups {
|
|
key := buildEqualityKey(rows[i], g.colIndices)
|
|
if deleteSeq, ok := g.keys[key]; ok && deleteSeq > dataSeq {
|
|
deleted = true
|
|
break
|
|
}
|
|
}
|
|
if deleted {
|
|
continue
|
|
}
|
|
|
|
filteredRows = append(filteredRows, rows[i])
|
|
filteredPositions = append(filteredPositions, rowPos)
|
|
}
|
|
absolutePos += int64(n)
|
|
if len(filteredRows) > 0 {
|
|
if err := onRows(filteredRows, filteredPositions); err != nil {
|
|
return totalRows, err
|
|
}
|
|
totalRows += int64(len(filteredRows))
|
|
}
|
|
}
|
|
|
|
if readErr != nil {
|
|
if readErr == io.EOF {
|
|
return totalRows, nil
|
|
}
|
|
return totalRows, fmt.Errorf("read rows from %s: %w", source, readErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
func mergeParquetFilesSorted(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
entries []iceberg.ManifestEntry,
|
|
positionDeletes map[string][]int64,
|
|
eqDeleteGroups []equalityDeleteGroup,
|
|
icebergSchema *iceberg.Schema,
|
|
rewritePlan *compactionRewritePlan,
|
|
rowGroupRows int64,
|
|
lineage bool,
|
|
) ([]byte, int64, error) {
|
|
if len(entries) == 0 {
|
|
return nil, 0, fmt.Errorf("no entries to merge")
|
|
}
|
|
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 {
|
|
return nil, 0, fmt.Errorf("read parquet file %s: %w", entries[0].DataFile().FilePath(), err)
|
|
}
|
|
firstReader, err := newParquetReader(firstData, entries[0].DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
parquetSchema := firstReader.Schema()
|
|
if parquetSchema == nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("no parquet schema found in %s", entries[0].DataFile().FilePath())
|
|
}
|
|
|
|
outputSchema := parquetSchema
|
|
var layout *lineageLayout
|
|
if lineage {
|
|
if layout, err = newLineageLayout(parquetSchema); err != nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("schema of %s: %w", entries[0].DataFile().FilePath(), err)
|
|
}
|
|
outputSchema = layout.schema
|
|
}
|
|
|
|
// 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)
|
|
if err != nil {
|
|
firstReader.Close()
|
|
return nil, 0, fmt.Errorf("resolve equality columns: %w", err)
|
|
}
|
|
|
|
// Sorted rewrites stream rows through parquet-go's sorting writer rather
|
|
// than holding the whole bin: rows accumulate until sortBufferRows, then a
|
|
// sorted run is encoded into a temporary row group, and Close merges the
|
|
// runs into the output. The runs live in files from a buffer pool instead
|
|
// of on the heap, so a bin larger than memory sorts rather than failing.
|
|
spillDir := rewritePlan.spillDir
|
|
if spillDir == "" {
|
|
// NewFileBufferPool takes filepath.Abs of what it is given, and
|
|
// filepath.Abs("") is the working directory, not the temp directory.
|
|
spillDir = os.TempDir()
|
|
}
|
|
sortBufferRows := rewritePlan.bufferRows
|
|
if sortBufferRows < minSortBufferRows {
|
|
sortBufferRows = defaultSortBufferRows
|
|
}
|
|
|
|
var outputBuf bytes.Buffer
|
|
// 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...),
|
|
parquet.SortingBuffers(parquet.NewFileBufferPool(spillDir, "seaweedfs-iceberg-sort-*")),
|
|
),
|
|
)
|
|
// Closing returns the run files to the pool, which deletes them. A failure
|
|
// before that has to release them too, or the job leaves temp files behind.
|
|
closed := false
|
|
defer func() {
|
|
if !closed {
|
|
writer.Reset(io.Discard)
|
|
}
|
|
}()
|
|
|
|
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)
|
|
return writeErr
|
|
})
|
|
}
|
|
|
|
totalRows, err := writeRows(firstReader, entries[0])
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
for _, entry := range entries[1:] {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, 0, ctx.Err()
|
|
default:
|
|
}
|
|
|
|
data, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, 0, fmt.Errorf("read parquet file %s: %w", entry.DataFile().FilePath(), err)
|
|
}
|
|
|
|
reader, err := newParquetReader(data, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
if layout == nil && !schemasEqual(parquetSchema, reader.Schema()) {
|
|
reader.Close()
|
|
return nil, 0, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", entry.DataFile().FilePath())
|
|
}
|
|
|
|
rowsWritten, err := writeRows(reader, entry)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
totalRows += rowsWritten
|
|
}
|
|
|
|
if err := writer.Close(); err != nil {
|
|
return nil, 0, fmt.Errorf("close sorting writer: %w", err)
|
|
}
|
|
closed = true
|
|
|
|
if spool != nil {
|
|
if err := spool.copyTo(ctx, &outputBuf, outputSchema, rowGroupRows); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
}
|
|
return outputBuf.Bytes(), totalRows, nil
|
|
}
|
|
|
|
// compactRandomSuffix returns a short random hex string for use in artifact
|
|
// filenames to prevent collisions between concurrent runs.
|
|
func compactRandomSuffix() string {
|
|
b := make([]byte, 4)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return fmt.Sprintf("%x", time.Now().UnixNano()&0xFFFFFFFF)
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|
|
|
|
// schemasEqual compares two parquet schemas structurally, and their Iceberg
|
|
// field ids wherever both carry them.
|
|
func schemasEqual(a, b *parquet.Schema) bool {
|
|
if a == b {
|
|
return true
|
|
}
|
|
if a == nil || b == nil {
|
|
return false
|
|
}
|
|
return parquet.EqualNodes(a, b) && fieldIDsAgree(a, b)
|
|
}
|
|
|
|
// fieldIDsAgree reports whether two structurally equal nodes carry the same
|
|
// Iceberg field id at every position where both carry one. parquet-go's
|
|
// EqualNodes ignores field ids, so a column dropped and re-added under the
|
|
// same name and type (a new field id) looked like the old one, and a merge
|
|
// filed the old values under the new field, or the live values under the
|
|
// dropped one.
|
|
func fieldIDsAgree(a, b parquet.Node) bool {
|
|
if a.ID() > 0 && b.ID() > 0 && a.ID() != b.ID() {
|
|
return false
|
|
}
|
|
if a.Leaf() || b.Leaf() {
|
|
return a.Leaf() == b.Leaf()
|
|
}
|
|
fa, fb := a.Fields(), b.Fields()
|
|
if len(fa) != len(fb) {
|
|
return false
|
|
}
|
|
for i := range fa {
|
|
if fa[i].Name() != fb[i].Name() || !fieldIDsAgree(fa[i], fb[i]) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ensureFilerDir ensures a directory exists in the filer.
|
|
func ensureFilerDir(ctx context.Context, client filer_pb.SeaweedFilerClient, dirPath string) error {
|
|
parentDir := path.Dir(dirPath)
|
|
dirName := path.Base(dirPath)
|
|
|
|
_, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
|
Directory: parentDir,
|
|
Name: dirName,
|
|
})
|
|
if err == nil {
|
|
return nil // already exists
|
|
}
|
|
if !errors.Is(err, filer_pb.ErrNotFound) && status.Code(err) != codes.NotFound {
|
|
return fmt.Errorf("lookup dir %s: %w", dirPath, err)
|
|
}
|
|
|
|
resp, createErr := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
|
Directory: parentDir,
|
|
Entry: &filer_pb.Entry{
|
|
Name: dirName,
|
|
IsDirectory: true,
|
|
Attributes: &filer_pb.FuseAttributes{
|
|
Mtime: time.Now().Unix(),
|
|
Crtime: time.Now().Unix(),
|
|
FileMode: uint32(0755),
|
|
},
|
|
},
|
|
})
|
|
if createErr != nil {
|
|
return createErr
|
|
}
|
|
if resp.Error != "" && !strings.Contains(resp.Error, "exist") {
|
|
return fmt.Errorf("create dir %s: %s", dirPath, resp.Error)
|
|
}
|
|
return nil
|
|
}
|