mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* mq: export logstore's log file offset range and control entry checks The topic table writer decides what is sealed from a partition's file offset ranges and drops the same control entries compaction drops, so it calls these instead of keeping copies. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: tell which of a partition's files its leader will not write again A topic table may only take what is sealed. The fence names a writer and an epoch, not a file, and each flushed window lands whole as a new file under it, so every log file but the one holding the highest offsets is sealed; the newest may still be followed by a window in flight. A sealed fence takes no more windows, so all of its files are. Parquet left by mq.topic.compact rewrites earlier logs and is always sealed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a topic table's copied offsets in its snapshot summary Each append records seaweedfs.mq.offsets, the first offset of every partition not yet in the table. A snapshot that rewrote files without carrying the map defers to its newest ancestor that has one; a table with snapshots and no map anywhere holds rows of unknown offsets and is not written to. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: build a topic table's rows from log entries A message becomes a row of its table: the system columns from the log entry, then the record's fields by name, or the whole message in _value for a schemaless topic. Rows are laid out in the table's current schema through iceberg-go's Arrow mapping, so the Parquet file they are written as carries the table's field ids and the types Iceberg readers expect. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: compare topic tables by name in topictable The table writer in the worker has to tell whether topic.conf still names the table a job was proposed for, by bucket ARN, namespace and name, the same way the broker compares a configure request with what is stored. The comparison moves next to the rest of the topic table layout so both call it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: keep a topic table's offset map through maintenance snapshots Compaction, delete rewrites and manifest rewrites keep a table's rows, so the offsets a topic table holds are unchanged by them. Their snapshots now carry the parent's seaweedfs.mq.offsets, so the topic writer and readers find the map on the current snapshot rather than only on an ancestor that snapshot expiry may remove. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: start a table's running totals at its first snapshot Totals were only carried from a parent that recorded them, so a table whose first snapshot the worker wrote never got total-records or total-data-files, and no later snapshot could carry them. A snapshot without a parent adds to an empty table, whose totals are zero. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: copy a topic's sealed log data into its Iceberg table copyTopicTable reads each partition from the offset the table's current snapshot records up to what its leader has sealed, through the merged reader that already serves log files and compacted parquet, and writes the rows as data files under data/<_partition>/ named by their offset range. A file holds one partition value, so it never spans partitions or days, and its rows are one contiguous offset run in offset order. The append goes through commitWithRetry and records the advanced offset map in seaweedfs.mq.offsets. Each attempt re-checks that topic.conf still names the table and that the table still names the topic, and re-reads the map: a partition another writer moved since this run planned keeps that writer's offset, and this run's files for it are removed, so no offset is appended twice. A run that dies before its commit leaves only unreferenced files for orphan removal. Log files are left in place; the broker cannot read the table yet. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: run mq_topic_table for topics that name an Iceberg table The worker registers an mq_topic_table job beside iceberg_maintenance and runs it in the Iceberg lane. Detection reads every topic.conf under /topics; a topic naming a table is due once one of its partitions has 128 MiB sealed past the table's offsets or a sealed file 5 minutes old. Execution takes the filer lock mq.table.<namespace>.<topic>, so one writer copies a topic at a time, and copies only while topic.conf still names the table the job was proposed for; a topic that left it ends the job without failing it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: copy only into the table whose UUID topic.conf recorded A table dropped and replaced at the topic's table name still carries the name, and may carry the topic's property if its creator copied it. The broker records the UUID of the table it created or adopted in topic.conf, so the writer checks it before planning and again before each commit attempt, and stops rather than append the topic's offsets to a table that is not the one the topic holds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: keep keyless and valueless messages in a topic table The table becomes a topic's only copy once copied logs are deleted, and the writer dropped what compaction drops: every message without a key or without a value. Those are data; a Kafka record with a null key is one. The only control entry the log holds is a publisher's close marker, which the broker stores without its Ctrl, as an entry with neither key nor value. IsControlMarker names exactly that, IsControlEntry keeps its wider rule for compaction, and the writer skips markers only. A keyless message gets a null _key. A skipped marker's offset stays below the partition's offset in the map, so the table records it as an offset that held no message rather than a gap left to fill. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: change a topic's table under its table writer's lock A configure that left a table checked it for snapshots, then saved topic.conf. The table writer checks topic.conf before each commit, so a detach saved between that check and the commit's CAS left a table holding the topic's data with no topic. The broker now takes the writer's filer lock, mq.table.<namespace>.<topic>, before the release check and keeps it through the topic.conf save, so it sees what the writer committed, and the writer sees the change before committing. The wait is bounded at 15 seconds: a configure behind a long copy is Unavailable and retried rather than holding the configure RPC. The lock key moves to topictable so the broker and the worker share it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: make a topic table's record columns optional A field's is_required became a required column, so a message missing that field could not be written and the table writer stopped at its offset. Once copied logs are deleted the table is the topic's only copy, so every message needs a row. Record fields now map to optional columns at every level; the system columns stay required. Adopting a table still refuses one whose record columns are required, since it could not take such a message. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a message its topic's record type cannot hold in _value A schematized topic's tombstone, or a value that is not a RecordValue of its type, stopped the table writer at its offset, and once copied logs are deleted the table is the only copy. Every topic table now has an optional _value column. A message whose value is empty, does not parse, carries bytes a RecordValue does not have, names a field the table lacks, or holds a value its column cannot take gets null record columns and its raw bytes in _value. A decoded message leaves _value null. A row is checked whole before any column takes it, so a fallback leaves no partial row behind. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: copy a topic's history into its table in bounded runs A run read every sealed offset past the table's map and committed only at the end, so a topic attached with a long history could not finish within the job's one-hour timeout: each attempt rewrote the same files, removed them on cancel, and the map never moved. A run now stops at a file boundary once it has written 4 GiB and commits the offsets its files cover; the next detection picks up the rest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: decode a record read back from compacted parquet into its columns logstore's parquet reader hands back a schematized row as its RecordValue, which still holds the file's _ts_ns, _key and _offset columns. The row writer took those for fields outside the table, so every message the copy read from mq.topic.compact's parquet landed as raw _value with null record columns. Those three fields are the entry's own and are now passed over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: map a repeated field already typed as a list to one list The Kafka protobuf and JSON Schema decoders describe a repeated field with both a ListType and IsRepeated, and their values are one ListValue deep. mapField wrapped the list type again, so the column became list<list<T>> and every message with a non-empty repeated field fell back to raw _value. Avro gives the item type with IsRepeated, which still gets wrapped once. MQ's own parquet schema already ignores IsRepeated on a list type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: keep a decimal past its column's precision in _value rescaleDecimal checked only that the rescaled value fit 128 bits, so an unscaled value from 10^38 up to 2^127 was written into the decimal(38,18) column, which engines then read as an overflow or null. The value is now checked against the column's precision, so such a message keeps its raw bytes in _value like any other value the record type cannot hold. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound a published decimal before rescaling it A DecimalValue's scale, precision and bytes come from the publisher, and rescaling to the column built 10^|18-scale| before checking anything, so one message with an extreme scale could hold a worker's CPU and memory on every retry of the copy. A scale or precision beyond the column's 38 digits, or a magnitude longer than 32 bytes, cannot fit decimal(38, 18) and is refused before any arithmetic; the message keeps its row with its bytes in _value like any other value its column cannot take. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: keep a topic table's files when its commit's outcome is unknown A commit whose update of the table entry failed without an answer, a reset connection or a deadline, may still have been applied by the filer. The run then deleted its data files and manifests, and commitWithRetry its new metadata file, leaving a committed snapshot pointing at files that were gone. Such a failure is now errCommitOutcomeUnknown, and commitWithRetry keeps the metadata file for it. The topic table writer reads the table again: a snapshot it built that is in the current lineage is a commit, kept and reported as one. Otherwise, or when the table cannot be read, the files stay for orphan removal, since an update still in flight could land after the read. Only a refused commit, a conflict or a stopped run, deletes them. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: count a partition's rows after its last flush copyPartition returned total and flush() in one statement, and Go does not order reading total against calling flush, so the rows of the last file could be left out of the count. The last flush now runs first. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: report the rows a topic table commit kept A run's rows_written was every row it staged, though a commit attempt drops the files of a partition another writer already moved, and a run that commits nothing reported its staged rows all the same. It is now the record count of the files the committed snapshot added. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: wait for a topic's table writer outside topicConfLock A configure that moved a topic off its table waited up to 15 seconds for the table writer's lock while holding topicConfLock, which every configure, lookup cache miss and rebalance of every topic takes, and a caller that gave up kept waiting. The configure now reads topic.conf first and, when the request moves the topic off the table it names, takes the writer's lock before topicConfLock, the order the writer keeps since it never takes topicConfLock. The wait ends when the caller's context does, and a grant that arrives after that is released. A configure that finds the table changed under topicConfLock without holding the writer's lock is Unavailable and retried. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: bound the topic.conf read a table change starts with The read that decides whether a configure must wait for the table writer runs before topicConfLock, and so before the 30 second bound lockTopicConf puts on calls made under it. A caller without a deadline then hung on a filer that took the read and never answered. The read now gets the same bound of its own, still outside topicConfLock. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: keep what an unanswered maintenance commit may reference Compaction, delete rewrite and manifest rewrite delete everything they wrote when their commit fails. When the failure is an update of the table entry that went unanswered, the filer may have applied it, and the table then points at data files, manifests and a manifest list that were just deleted. Those are now left for orphan removal on errCommitOutcomeUnknown, as the topic table writer already does; conflicts and other definite failures still clean up. Snapshot expiry deletes nothing before its commit succeeds and needed no change. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: test a topic table retry that keeps only one partition's files A run whose commit loses to a writer that copied only one of its partitions keeps the other partition's file. The test checks that the retry reports only that file's rows and that each offset lands once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: wait for the detach's refused lock request in the table lock test A fixed sleep did not show the detach had reached the table lock, so a late goroutine let the lookup pass with nothing waiting. The fake filer now counts refused lock requests and the test waits for the first one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: check the table writer's lock before saving a table change A configure that moves a topic off its table holds the writer's lock from its release check through the topic.conf save, but never looked at it again. A lease that lapsed meanwhile, its renewals failing, may already be the writer's, which can then commit to the table the configure is about to detach. The configure now checks that it still holds the lock right before the save and is Unavailable otherwise. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: check a topic table copy's lock and topic last before committing Each commit attempt checked the lock, topic.conf and the table's owner before writing its manifests and manifest list, and nothing after, so a lease that lapsed or a detach that landed while they were written went unnoticed. The attempt now checks again once they are written, the last step before commitWithRetry saves the metadata file and updates the table pointer. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: read a topic's conf with the topic table job's context The table writer and detection read topic.conf with ReadConfFile, which takes no context, so a filer that took the read and never answered held the job, its worker slot and its renewed table lock, and held up detection, past any cancel. They now read through ReadConfFileWithMetadata with the job's or the detection's context, so a cancelled job ends and lets its lock go. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
620 lines
19 KiB
Go
620 lines
19 KiB
Go
package iceberg
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"path"
|
|
"sort"
|
|
"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"
|
|
)
|
|
|
|
type deleteRewriteInput struct {
|
|
Entry iceberg.ManifestEntry
|
|
ReferencedPath string
|
|
Positions []int64
|
|
}
|
|
|
|
type deleteRewriteGroup struct {
|
|
SpecID int32
|
|
Partition map[int]any
|
|
PartitionKey string
|
|
ReferencedPath string
|
|
Inputs []deleteRewriteInput
|
|
TotalSize int64
|
|
}
|
|
|
|
// positionDeleteRow is the Iceberg position-delete schema: the spec reserves
|
|
// field ids 2147483546 (file_path) and 2147483545 (pos). file_path is
|
|
// dictionary-encoded: PyArrow cannot decode parquet-go's default
|
|
// DELTA_LENGTH_BYTE_ARRAY into the dictionary PyIceberg asks for, and the
|
|
// column repeats one data file's path anyway.
|
|
type positionDeleteRow struct {
|
|
FilePath string `parquet:"file_path,dict,id(2147483546)"`
|
|
Pos int64 `parquet:"pos,id(2147483545)"`
|
|
}
|
|
|
|
func hasEligibleDeleteRewrite(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
manifests []iceberg.ManifestFile,
|
|
config Config,
|
|
meta table.Metadata,
|
|
predicate *partitionPredicate,
|
|
) (bool, error) {
|
|
groups, _, err := collectDeleteRewriteGroups(ctx, filerClient, bucketName, dataPath, manifests, specByID(meta), meta.CurrentSchema())
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
for _, group := range groups {
|
|
if predicate != nil {
|
|
spec, ok := specByID(meta)[int(group.SpecID)]
|
|
if !ok {
|
|
continue
|
|
}
|
|
match, err := predicate.Matches(spec, group.Partition)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !match {
|
|
continue
|
|
}
|
|
}
|
|
if groupEligibleForRewrite(group, config) {
|
|
return true, nil
|
|
}
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
func collectDeleteRewriteGroups(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, dataPath string,
|
|
manifests []iceberg.ManifestFile,
|
|
specs map[int]iceberg.PartitionSpec,
|
|
schema *iceberg.Schema,
|
|
) (map[string]*deleteRewriteGroup, []iceberg.ManifestEntry, error) {
|
|
groups := make(map[string]*deleteRewriteGroup)
|
|
var allPositionEntries []iceberg.ManifestEntry
|
|
|
|
for _, mf := range manifests {
|
|
if mf.ManifestContent() != iceberg.ManifestContentDeletes {
|
|
continue
|
|
}
|
|
|
|
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
entries, err := s3tables.ReadManifest(mf, manifestData, true, specs, schema)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err)
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
if entry.DataFile().ContentType() != iceberg.EntryContentPosDeletes {
|
|
continue
|
|
}
|
|
|
|
allPositionEntries = append(allPositionEntries, entry)
|
|
if isPuffin(entry.DataFile()) {
|
|
continue
|
|
}
|
|
|
|
fileDeletes, err := readPositionDeleteFile(ctx, filerClient, bucketName, dataPath, entry.DataFile().FilePath())
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read position delete file %s: %w", entry.DataFile().FilePath(), err)
|
|
}
|
|
if len(fileDeletes) != 1 {
|
|
// Phase 1 only rewrites files that target a single data file.
|
|
continue
|
|
}
|
|
|
|
var referencedPath string
|
|
var positions []int64
|
|
for fp, pos := range fileDeletes {
|
|
normalized, err := normalizeIcebergPath(fp, bucketName, dataPath)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("resolve deleted file %s: %w", fp, err)
|
|
}
|
|
// The rewritten delete file has to name the data file the way the
|
|
// table does, so keep the absolute form readers compare against.
|
|
referencedPath = absoluteIcebergPath(bucketName, normalized)
|
|
positions = append(positions, pos...)
|
|
}
|
|
sort.Slice(positions, func(i, j int) bool { return positions[i] < positions[j] })
|
|
|
|
partKey := partitionKey(entry.DataFile().Partition())
|
|
groupKey := fmt.Sprintf("spec%d\x00%s\x00%s", entry.DataFile().SpecID(), partKey, referencedPath)
|
|
group, ok := groups[groupKey]
|
|
if !ok {
|
|
group = &deleteRewriteGroup{
|
|
SpecID: entry.DataFile().SpecID(),
|
|
Partition: entry.DataFile().Partition(),
|
|
PartitionKey: partKey,
|
|
ReferencedPath: referencedPath,
|
|
}
|
|
groups[groupKey] = group
|
|
}
|
|
group.Inputs = append(group.Inputs, deleteRewriteInput{
|
|
Entry: entry,
|
|
ReferencedPath: referencedPath,
|
|
Positions: positions,
|
|
})
|
|
group.TotalSize += entry.DataFile().FileSizeBytes()
|
|
}
|
|
}
|
|
|
|
return groups, allPositionEntries, nil
|
|
}
|
|
|
|
func groupEligibleForRewrite(group *deleteRewriteGroup, config Config) bool {
|
|
if group == nil {
|
|
return false
|
|
}
|
|
if len(group.Inputs) < 2 {
|
|
return false
|
|
}
|
|
if group.TotalSize > config.DeleteMaxFileGroupSizeBytes {
|
|
return false
|
|
}
|
|
target := config.DeleteTargetFileSizeBytes
|
|
if target <= 0 {
|
|
target = defaultDeleteTargetFileSizeMB * 1024 * 1024
|
|
}
|
|
outputFiles := int64(estimatedDeleteOutputFiles(group.TotalSize, target))
|
|
if config.DeleteMaxOutputFiles > 0 && outputFiles > config.DeleteMaxOutputFiles {
|
|
return false
|
|
}
|
|
return int64(len(group.Inputs)) >= config.DeleteMinInputFiles
|
|
}
|
|
|
|
func estimatedDeleteOutputFiles(totalSize, targetSize int64) int {
|
|
if totalSize <= 0 || targetSize <= 0 {
|
|
return 1
|
|
}
|
|
count := int(math.Ceil(float64(totalSize) / float64(targetSize)))
|
|
if count < 1 {
|
|
return 1
|
|
}
|
|
return count
|
|
}
|
|
|
|
func manifestEntrySeqNum(entry iceberg.ManifestEntry) *int64 {
|
|
seqNum := entry.SequenceNum()
|
|
if seqNum < 0 {
|
|
return nil
|
|
}
|
|
return &seqNum
|
|
}
|
|
|
|
func manifestEntryFileSeqNum(entry iceberg.ManifestEntry) *int64 {
|
|
if fileSeqNum := entry.FileSequenceNum(); fileSeqNum != nil {
|
|
value := *fileSeqNum
|
|
return &value
|
|
}
|
|
return manifestEntrySeqNum(entry)
|
|
}
|
|
|
|
func writeManifestWithContent(
|
|
filename string,
|
|
version int,
|
|
spec iceberg.PartitionSpec,
|
|
schema *iceberg.Schema,
|
|
snapshotID int64,
|
|
entries []iceberg.ManifestEntry,
|
|
content iceberg.ManifestContent,
|
|
) (iceberg.ManifestFile, []byte, error) {
|
|
var manifestBuf bytes.Buffer
|
|
w, err := iceberg.NewManifestWriter(version, &manifestBuf, spec, schema, snapshotID,
|
|
iceberg.WithManifestWriterContent(content))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
for _, entry := range entries {
|
|
var addErr error
|
|
switch entry.Status() {
|
|
case iceberg.EntryStatusADDED:
|
|
addErr = w.Add(entry)
|
|
case iceberg.EntryStatusEXISTING:
|
|
addErr = w.Existing(entry)
|
|
case iceberg.EntryStatusDELETED:
|
|
addErr = w.Delete(entry)
|
|
default:
|
|
addErr = fmt.Errorf("unexpected manifest entry status: %v", entry.Status())
|
|
}
|
|
if addErr != nil {
|
|
return nil, nil, addErr
|
|
}
|
|
}
|
|
if err := w.Close(); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
mf, err := w.ToManifestFile(filename, int64(manifestBuf.Len()))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return mf, manifestBuf.Bytes(), nil
|
|
}
|
|
|
|
func writePositionDeleteFile(rows []positionDeleteRow) ([]byte, error) {
|
|
var buf bytes.Buffer
|
|
writer := parquet.NewWriter(&buf, parquet.SchemaOf(new(positionDeleteRow)))
|
|
for _, row := range rows {
|
|
if err := writer.Write(&row); err != nil {
|
|
return nil, fmt.Errorf("write position delete row: %w", err)
|
|
}
|
|
}
|
|
if err := writer.Close(); err != nil {
|
|
return nil, fmt.Errorf("close position delete file: %w", err)
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
const skipDeleteRewriteV3 = "rewrite_position_delete_files skipped: position-delete files must not be added to a format-version 3 table"
|
|
|
|
func (h *Handler) rewritePositionDeleteFiles(
|
|
ctx context.Context,
|
|
filerClient filer_pb.SeaweedFilerClient,
|
|
bucketName, tablePath string,
|
|
config Config,
|
|
) (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
|
|
|
|
currentSnap := meta.CurrentSnapshot()
|
|
if currentSnap == nil || currentSnap.ManifestList == "" {
|
|
return "no current snapshot", nil, nil
|
|
}
|
|
// The spec forbids adding position-delete files to a v3 table ("Position
|
|
// delete files must not be added to v3 tables"; v3 writes deletion
|
|
// vectors), and this rewrite adds new ones. Compaction still applies and
|
|
// removes existing position deletes.
|
|
if hasRowLineage(meta.Version()) {
|
|
return skipDeleteRewriteV3, nil, nil
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
specs := specByID(meta)
|
|
schema := meta.CurrentSchema()
|
|
|
|
var dataManifests []iceberg.ManifestFile
|
|
var allEqualityEntries []iceberg.ManifestEntry
|
|
for _, mf := range manifests {
|
|
switch mf.ManifestContent() {
|
|
case iceberg.ManifestContentData:
|
|
dataManifests = append(dataManifests, mf)
|
|
case iceberg.ManifestContentDeletes:
|
|
manifestData, readErr := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
|
|
if readErr != nil {
|
|
return "", nil, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), readErr)
|
|
}
|
|
entries, parseErr := s3tables.ReadManifest(mf, manifestData, true, specs, schema)
|
|
if parseErr != nil {
|
|
return "", nil, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), parseErr)
|
|
}
|
|
for _, entry := range entries {
|
|
if entry.DataFile().ContentType() == iceberg.EntryContentEqDeletes {
|
|
allEqualityEntries = append(allEqualityEntries, entry)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
groupMap, allPositionEntries, err := collectDeleteRewriteGroups(ctx, filerClient, bucketName, dataPath, manifests, specs, schema)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if len(groupMap) == 0 {
|
|
return "no position delete files eligible for rewrite", nil, nil
|
|
}
|
|
|
|
type artifact struct {
|
|
dir, fileName string
|
|
}
|
|
var writtenArtifacts []artifact
|
|
keepArtifacts := false
|
|
defer func() {
|
|
if keepArtifacts || len(writtenArtifacts) == 0 {
|
|
return
|
|
}
|
|
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 delete rewrite: failed to clean up artifact %s/%s: %v", a.dir, a.fileName, err)
|
|
}
|
|
}
|
|
}()
|
|
|
|
specByID := specByID(meta)
|
|
predicate, err := parsePartitionPredicate(config.Where, meta)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
newSnapID := time.Now().UnixMilli()
|
|
version := meta.Version()
|
|
snapshotID := currentSnap.SnapshotID
|
|
seqNum := currentSnap.SequenceNumber + 1
|
|
metaDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "metadata")
|
|
dataDir := path.Join(s3tables.TablesPath, bucketName, dataPath, "data")
|
|
artifactSuffix := compactRandomSuffix()
|
|
|
|
replacedPaths := make(map[string]struct{})
|
|
var summary snapshotSummary
|
|
var rewrittenGroups int64
|
|
var skippedGroups int64
|
|
var deleteFilesRewritten int64
|
|
var deleteFilesWritten int64
|
|
var deleteBytesRewritten int64
|
|
|
|
sortedKeys := make([]string, 0, len(groupMap))
|
|
for key := range groupMap {
|
|
sortedKeys = append(sortedKeys, key)
|
|
}
|
|
sort.Strings(sortedKeys)
|
|
|
|
for _, key := range sortedKeys {
|
|
group := groupMap[key]
|
|
if predicate != nil {
|
|
spec, ok := specByID[int(group.SpecID)]
|
|
if !ok {
|
|
continue
|
|
}
|
|
match, err := predicate.Matches(spec, group.Partition)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if !match {
|
|
skippedGroups++
|
|
continue
|
|
}
|
|
}
|
|
if !groupEligibleForRewrite(group, config) {
|
|
skippedGroups++
|
|
continue
|
|
}
|
|
rows := make([]positionDeleteRow, 0)
|
|
for _, input := range group.Inputs {
|
|
for _, pos := range input.Positions {
|
|
rows = append(rows, positionDeleteRow{FilePath: input.ReferencedPath, Pos: pos})
|
|
}
|
|
replacedPaths[input.Entry.DataFile().FilePath()] = struct{}{}
|
|
deleteFilesRewritten++
|
|
deleteBytesRewritten += input.Entry.DataFile().FileSizeBytes()
|
|
}
|
|
sort.Slice(rows, func(i, j int) bool {
|
|
if rows[i].FilePath != rows[j].FilePath {
|
|
return rows[i].FilePath < rows[j].FilePath
|
|
}
|
|
return rows[i].Pos < rows[j].Pos
|
|
})
|
|
|
|
outputFiles := estimatedDeleteOutputFiles(group.TotalSize, config.DeleteTargetFileSizeBytes)
|
|
rowsPerFile := (len(rows) + outputFiles - 1) / outputFiles
|
|
if rowsPerFile < 1 {
|
|
rowsPerFile = len(rows)
|
|
}
|
|
|
|
for startIdx, fileIdx := 0, 0; startIdx < len(rows); startIdx, fileIdx = startIdx+rowsPerFile, fileIdx+1 {
|
|
endIdx := startIdx + rowsPerFile
|
|
if endIdx > len(rows) {
|
|
endIdx = len(rows)
|
|
}
|
|
outputRows := rows[startIdx:endIdx]
|
|
deleteBytes, err := writePositionDeleteFile(outputRows)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
fileName := fmt.Sprintf("rewrite-delete-%d-%s-%d.parquet", newSnapID, artifactSuffix, deleteFilesWritten)
|
|
if err := ensureFilerDir(ctx, filerClient, dataDir); err != nil {
|
|
return "", nil, fmt.Errorf("ensure data dir: %w", err)
|
|
}
|
|
if err := saveFilerFile(ctx, filerClient, dataDir, fileName, deleteBytes); err != nil {
|
|
return "", nil, fmt.Errorf("save rewritten delete file: %w", err)
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: dataDir, fileName: fileName})
|
|
|
|
spec, ok := specByID[int(group.SpecID)]
|
|
if !ok {
|
|
return "", nil, fmt.Errorf("partition spec %d not found", group.SpecID)
|
|
}
|
|
dfBuilder, err := iceberg.NewDataFileBuilder(
|
|
spec,
|
|
iceberg.EntryContentPosDeletes,
|
|
absoluteIcebergPath(bucketName, dataPath, "data", fileName),
|
|
iceberg.ParquetFile,
|
|
group.Partition,
|
|
nil, nil,
|
|
int64(len(outputRows)),
|
|
int64(len(deleteBytes)),
|
|
)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("build rewritten delete file: %w", err)
|
|
}
|
|
rewrittenDeleteFile := dfBuilder.Build()
|
|
summary.addFile(rewrittenDeleteFile)
|
|
addToSpec(group.SpecID, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &newSnapID, nil, nil, rewrittenDeleteFile))
|
|
deleteFilesWritten++
|
|
}
|
|
|
|
for _, input := range group.Inputs {
|
|
summary.removeFile(input.Entry.DataFile())
|
|
delEntry := iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusDELETED,
|
|
&newSnapID,
|
|
manifestEntrySeqNum(input.Entry),
|
|
manifestEntryFileSeqNum(input.Entry),
|
|
input.Entry.DataFile(),
|
|
)
|
|
addToSpec(group.SpecID, delEntry)
|
|
}
|
|
rewrittenGroups++
|
|
}
|
|
|
|
if rewrittenGroups == 0 {
|
|
return "no position delete files eligible for rewrite", nil, nil
|
|
}
|
|
|
|
for _, entry := range allEqualityEntries {
|
|
existingEntry := iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusEXISTING,
|
|
func() *int64 { id := entry.SnapshotID(); return &id }(),
|
|
manifestEntrySeqNum(entry),
|
|
manifestEntryFileSeqNum(entry),
|
|
entry.DataFile(),
|
|
)
|
|
addToSpec(entry.DataFile().SpecID(), existingEntry)
|
|
}
|
|
|
|
for _, entry := range allPositionEntries {
|
|
if _, replaced := replacedPaths[entry.DataFile().FilePath()]; replaced {
|
|
continue
|
|
}
|
|
existingEntry := iceberg.NewManifestEntry(
|
|
iceberg.EntryStatusEXISTING,
|
|
func() *int64 { id := entry.SnapshotID(); return &id }(),
|
|
manifestEntrySeqNum(entry),
|
|
manifestEntryFileSeqNum(entry),
|
|
entry.DataFile(),
|
|
)
|
|
addToSpec(entry.DataFile().SpecID(), existingEntry)
|
|
}
|
|
|
|
sortedSpecIDs := make([]int32, 0, len(specEntriesMap))
|
|
for specID := range specEntriesMap {
|
|
sortedSpecIDs = append(sortedSpecIDs, specID)
|
|
}
|
|
sort.Slice(sortedSpecIDs, func(i, j int) bool { return sortedSpecIDs[i] < sortedSpecIDs[j] })
|
|
|
|
allManifests := make([]iceberg.ManifestFile, 0, len(dataManifests)+len(sortedSpecIDs))
|
|
allManifests = append(allManifests, dataManifests...)
|
|
|
|
for _, specID := range sortedSpecIDs {
|
|
spec, ok := specByID[int(specID)]
|
|
if !ok {
|
|
return "", nil, fmt.Errorf("partition spec %d not found", specID)
|
|
}
|
|
manifestName := fmt.Sprintf("rewrite-delete-%d-%s-spec%d.avro", newSnapID, artifactSuffix, specID)
|
|
manifestPath := absoluteIcebergPath(bucketName, dataPath, "metadata", manifestName)
|
|
mf, manifestBytes, err := writeManifestWithContent(
|
|
manifestPath,
|
|
version,
|
|
spec,
|
|
meta.CurrentSchema(),
|
|
newSnapID,
|
|
specEntriesMap[specID].entries,
|
|
iceberg.ManifestContentDeletes,
|
|
)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("write delete manifest for spec %d: %w", specID, err)
|
|
}
|
|
if err := saveFilerFile(ctx, filerClient, metaDir, manifestName, manifestBytes); err != nil {
|
|
return "", nil, fmt.Errorf("save delete manifest for spec %d: %w", specID, err)
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: manifestName})
|
|
allManifests = append(allManifests, mf)
|
|
}
|
|
|
|
firstRowID := rowLineageFirstRowID(meta)
|
|
var manifestListBuf bytes.Buffer
|
|
addedRows, err := writeManifestList(version, &manifestListBuf, newSnapID, &snapshotID, &seqNum, firstRowID, allManifests)
|
|
if err != nil {
|
|
return "", nil, fmt.Errorf("write delete manifest list: %w", err)
|
|
}
|
|
manifestListName := fmt.Sprintf("snap-%d-%s.avro", newSnapID, artifactSuffix)
|
|
if err := saveFilerFile(ctx, filerClient, metaDir, manifestListName, manifestListBuf.Bytes()); err != nil {
|
|
return "", nil, fmt.Errorf("save delete manifest list: %w", err)
|
|
}
|
|
writtenArtifacts = append(writtenArtifacts, artifact{dir: metaDir, fileName: manifestListName})
|
|
|
|
manifestListLocation := absoluteIcebergPath(bucketName, dataPath, "metadata", manifestListName)
|
|
err = h.commitWithRetry(ctx, filerClient, bucketName, tablePath, state.MetadataFileName, config, func(currentMeta table.Metadata, builder *table.MetadataBuilder) error {
|
|
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": "rewrite_position_delete_files",
|
|
"delete-files-rewritten": fmt.Sprintf("%d", deleteFilesRewritten),
|
|
"delete-files-written": fmt.Sprintf("%d", deleteFilesWritten),
|
|
"delete-groups": fmt.Sprintf("%d", rewrittenGroups),
|
|
}),
|
|
SchemaID: func() *int {
|
|
id := meta.CurrentSchema().ID
|
|
return &id
|
|
}(),
|
|
}
|
|
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 delete rewrite: %w", err)
|
|
}
|
|
|
|
keepArtifacts = true
|
|
metrics := map[string]int64{
|
|
MetricDeleteFilesRewritten: deleteFilesRewritten,
|
|
MetricDeleteFilesWritten: deleteFilesWritten,
|
|
MetricDeleteBytesRewritten: deleteBytesRewritten,
|
|
MetricDeleteGroupsPlanned: rewrittenGroups,
|
|
MetricDeleteGroupsSkipped: skippedGroups,
|
|
MetricDurationMs: time.Since(start).Milliseconds(),
|
|
}
|
|
return fmt.Sprintf(
|
|
"rewrote %d position delete files into %d across %d group(s)",
|
|
deleteFilesRewritten,
|
|
deleteFilesWritten,
|
|
rewrittenGroups,
|
|
), metrics, nil
|
|
}
|