lszskye commented on code in PR #594:
URL: https://github.com/apache/paimon-cpp/pull/594#discussion_r4679104130


##########
src/paimon/core/append/append_file_compaction_planner.cpp:
##########
@@ -0,0 +1,441 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "paimon/append/append_file_compaction_planner.h"
+
+#include <algorithm>
+#include <iterator>
+#include <limits>
+#include <unordered_map>
+#include <utility>
+
+#include "fmt/format.h"
+#include "paimon/common/file_index/file_index_format_utils.h"
+#include "paimon/common/types/data_field.h"
+#include "paimon/common/utils/path_util.h"
+#include "paimon/common/utils/scope_guard.h"
+#include "paimon/common/utils/string_utils.h"
+#include "paimon/core/core_options.h"
+#include "paimon/core/deletionvectors/deletion_vector.h"
+#include "paimon/core/deletionvectors/deletion_vectors_index_file.h"
+#include "paimon/core/index/index_file_handler.h"
+#include "paimon/core/io/data_file_meta.h"
+#include "paimon/core/io/data_file_path_factory.h"
+#include "paimon/core/manifest/index_manifest_file.h"
+#include "paimon/core/manifest/manifest_file.h"
+#include "paimon/core/manifest/manifest_list.h"
+#include "paimon/core/operation/append_only_file_store_scan.h"
+#include "paimon/core/schema/schema_manager.h"
+#include "paimon/core/schema/table_schema.h"
+#include "paimon/core/table/bucket_mode.h"
+#include "paimon/core/utils/branch_manager.h"
+#include "paimon/core/utils/field_mapping.h"
+#include "paimon/core/utils/file_store_path_factory.h"
+#include "paimon/core/utils/index_file_path_factories.h"
+#include "paimon/core/utils/snapshot_manager.h"
+#include "paimon/defs.h"
+#include "paimon/executor.h"
+#include "paimon/file_index/file_index_format.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/io/byte_array_input_stream.h"
+#include "paimon/memory/bytes.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/scan_context.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+// Keep the pool alive until the last embedded-index reference releases its 
bytes.
+struct EmbeddedIndexOwner {
+    std::shared_ptr<MemoryPool> pool;
+    std::shared_ptr<Bytes> bytes;
+};
+
+Result<std::optional<FileIndexMeta>> ReadFileIndexMeta(
+    const std::shared_ptr<DataFileMeta>& file,
+    const std::shared_ptr<DataFilePathFactory>& path_factory,
+    const std::shared_ptr<FileSystem>& file_system, const 
std::shared_ptr<MemoryPool>& pool) {
+    FileIndexMeta meta;
+    std::shared_ptr<InputStream> input;
+    if (file->embedded_index) {
+        auto owner =
+            std::make_shared<EmbeddedIndexOwner>(EmbeddedIndexOwner{pool, 
file->embedded_index});
+        meta.embedded_index = std::shared_ptr<const Bytes>(owner, 
owner->bytes.get());
+        input = 
std::make_shared<ByteArrayInputStream>(meta.embedded_index->data(),
+                                                       
meta.embedded_index->size());
+    } else {
+        for (const auto& extra_file : file->extra_files) {
+            if (!extra_file || !StringUtils::EndsWith(extra_file.value(),
+                                                      
DataFilePathFactory::INDEX_PATH_SUFFIX)) {
+                continue;
+            }
+            if (meta.index_file_path) {
+                return Status::Invalid("multiple file index containers for ", 
file->file_name);
+            }
+            meta.index_file_path = 
path_factory->ToAlignedPath(extra_file.value(), file);
+        }
+        if (!meta.index_file_path) {
+            return std::optional<FileIndexMeta>();
+        }
+        PAIMON_ASSIGN_OR_RAISE(input, 
file_system->Open(meta.index_file_path.value()));
+    }
+    ScopeGuard close_guard([&input]() { (void)input->Close(); });
+    PAIMON_ASSIGN_OR_RAISE(FileIndexFormatUtils::FileIndexEntries entries,
+                           FileIndexFormatUtils::ReadIndexEntries(input, 
pool));
+    PAIMON_ASSIGN_OR_RAISE(int64_t container_length, input->Length());
+    for (const auto& [column, indexes] : entries) {
+        auto& ranges = meta.indexes[column];
+        for (const auto& [type, range] : indexes) {
+            const auto& [offset, length] = range;
+            if (offset == FileIndexFormat::EMPTY_INDEX_FLAG) {
+                if (length != 0) {
+                    return Status::Invalid("invalid empty index range for ", 
file->file_name);
+                }
+            } else if (offset < 0 || length < 0 || offset > container_length ||
+                       length > container_length - offset) {
+                return Status::Invalid("index range is outside container for 
", file->file_name);
+            }
+            ranges.emplace(type, FileIndexRange{range.first, range.second});
+        }
+    }
+    close_guard.Release();
+    PAIMON_RETURN_NOT_OK(input->Close());
+    return std::optional<FileIndexMeta>(std::move(meta));
+}
+
+Status BuildRowIdMapping(const std::shared_ptr<DeletionVector>& dv, int64_t 
target_start,
+                         FileCompactionInfo* info) {
+    if (info->source_row_count < 0) {
+        return Status::Invalid("negative row count for ", info->file_name);
+    }
+    int64_t deleted_count = 0;
+    if (dv) {
+        PAIMON_ASSIGN_OR_RAISE(deleted_count, dv->GetCardinality());
+    }
+    if (deleted_count < 0 || deleted_count > info->source_row_count) {
+        return Status::Invalid("invalid deletion vector cardinality for ", 
info->file_name);
+    }
+    info->live_row_count = info->source_row_count - deleted_count;
+    if (info->live_row_count > std::numeric_limits<int64_t>::max() - 
target_start) {
+        return Status::Invalid("compacted row count exceeds int64 range");
+    }
+
+    int64_t source_start = 0;
+    int64_t mapped_count = 0;
+    int64_t visited_deletions = 0;
+    auto append_range = [&](int64_t end) -> bool {
+        if (end > source_start) {
+            int64_t length = end - source_start;
+            if (length > info->live_row_count - mapped_count) {
+                return false;
+            }
+            info->row_id_mapping.push_back({source_start, target_start + 
mapped_count, length});
+            mapped_count += length;
+        }
+        return true;
+    };
+    if (dv) {
+        bool invalid_position = false;
+        // Both supported DV encodings enumerate deleted positions in 
ascending order.
+        PAIMON_RETURN_NOT_OK(dv->ForEachDeletedPosition([&](int64_t position) {
+            if (invalid_position) {
+                return;
+            }
+            if (position < source_start || position >= info->source_row_count) 
{
+                invalid_position = true;
+                return;
+            }
+            if (!append_range(position)) {
+                invalid_position = true;
+                return;
+            }
+            source_start = position + 1;
+            ++visited_deletions;
+        }));
+        if (invalid_position || visited_deletions != deleted_count) {
+            return Status::Invalid("invalid deletion vector positions for ", 
info->file_name);
+        }
+    }
+    if (!append_range(info->source_row_count) || mapped_count != 
info->live_row_count) {
+        return Status::Invalid("deletion vector cardinality does not match 
positions for ",
+                               info->file_name);
+    }
+    return Status::OK();
+}
+
+struct PlanningContext {
+    Snapshot snapshot;
+    std::shared_ptr<SnapshotManager> snapshot_manager;
+    std::shared_ptr<SchemaManager> schema_manager;
+    std::shared_ptr<TableSchema> table_schema;
+    CoreOptions core_options;
+};
+
+using DeletionVectors = std::map<std::string, std::shared_ptr<DeletionVector>>;
+
+Status ValidateInputs(const std::string& table_path, const 
std::set<std::string>& file_names,
+                      const std::optional<int64_t>& snapshot_id) {
+    if (table_path.empty()) {
+        return Status::Invalid("table path is empty");
+    }
+    if (file_names.empty()) {
+        return Status::Invalid("compaction planning requires at least one 
input file");
+    }
+    for (const auto& name : file_names) {
+        PAIMON_RETURN_NOT_OK(PathUtil::CheckSinglePathComponent("data file", 
name));
+    }
+    if (snapshot_id && snapshot_id.value() < Snapshot::FIRST_SNAPSHOT_ID) {
+        return Status::Invalid("snapshot id must be greater than or equal to 
1");
+    }
+    return Status::OK();
+}
+
+Result<PlanningContext> LoadPlanningContext(const std::string& table_path,
+                                            const std::string& 
normalized_branch,
+                                            const std::optional<int64_t>& 
snapshot_id,
+                                            const std::map<std::string, 
std::string>& options,
+                                            const std::shared_ptr<FileSystem>& 
file_system) {
+    PAIMON_ASSIGN_OR_RAISE(CoreOptions temporary_options,
+                           CoreOptions::FromMap(options, file_system));
+    auto snapshot_manager = 
std::make_shared<SnapshotManager>(temporary_options.GetFileSystem(),
+                                                              table_path, 
normalized_branch);

Review Comment:
   Could we follow the existing initialization order in 
[AppendCompactCoordinator](https://github.com/apache/paimon-cpp/blob/d0b5f60bbcff888df6301aca2eb1473f102ae0b8/src/paimon/core/append/append_compact_coordinator.cpp#L179-L198)?
   
   It first loads the schema using the temporary filesystem, merges the schema 
options with the caller-provided options to build core_options, and then 
constructs both SnapshotManager and SchemaManager using 
core_options.GetFileSystem().
   
   Here, snapshot_manager keeps using the temporary filesystem, so filesystem 
settings provided only through the schema options would not be applied to 
snapshot reads. Could we initialize it after resolving the merged options?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to