Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions crates/paimon/src/api/rest_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,8 @@ impl RESTApi {
// ==================== Commit Operations ====================

/// Commit a snapshot for a table.
/// Returns the server's reported `success`. An invalid response leaves
/// the publication outcome unknown.
///
/// Corresponds to Python `RESTApi.commit_snapshot`.
pub async fn commit_snapshot(
Expand All @@ -1267,10 +1269,12 @@ impl RESTApi {
"statistics": statistics,
});
let resp: serde_json::Value = self.client.post(&path, &request).await?;
Ok(resp
.get("success")
resp.get("success")
.and_then(|v| v.as_bool())
.unwrap_or(false))
.ok_or_else(|| crate::Error::UnexpectedError {
message: "REST snapshot commit response is missing a boolean success field".into(),
source: None,
})
}

/// Roll back a table through the server, optionally comparing its identity
Expand Down
5 changes: 5 additions & 0 deletions crates/paimon/src/io/file_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1781,6 +1781,11 @@ pub struct InputFile {
}

impl InputFile {
pub(crate) fn without_cache(mut self) -> Self {
self.cache = None;
self
}

pub fn location(&self) -> &str {
&self.path
}
Expand Down
47 changes: 41 additions & 6 deletions crates/paimon/src/table/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,19 @@ pub struct CompactPlanner {
}

pub(super) type CompactBuckets = HashSet<(Vec<u8>, i32, i32)>;
pub(super) type OverwriteL0Files = HashSet<(Vec<u8>, i32, String)>;

pub(super) fn within_overwrite_l0_scope(
overwrite_l0: Option<&OverwriteL0Files>,
partition: &[u8],
bucket: i32,
file: &DataFileMeta,
) -> bool {
file.level != 0
|| overwrite_l0.is_none_or(|files| {
files.contains(&(partition.to_vec(), bucket, file.file_name.clone()))
})
}

enum CompactPlannerKind {
Append(append::AppendCompactPlanner),
Expand Down Expand Up @@ -327,6 +340,13 @@ impl CompactPlanner {

/// Capture a snapshot without writing data or publishing metadata.
pub async fn plan(&self) -> Result<CompactPlan> {
self.plan_with_overwrite_l0(None).await
}

pub(super) async fn plan_with_overwrite_l0(
&self,
overwrite_l0: Option<&OverwriteL0Files>,
) -> Result<CompactPlan> {
ensure_supported(&self.table)?;
let mut reader = self.table.new_read_builder();
if let Some(filter) = &self.partition_filter {
Expand Down Expand Up @@ -391,7 +411,9 @@ impl CompactPlanner {
};
let tasks = match &self.kind {
CompactPlannerKind::Append(planner) => planner.plan_tasks(&source, &context)?,
CompactPlannerKind::PrimaryKey(planner) => planner.plan_tasks(&source, &context)?,
CompactPlannerKind::PrimaryKey(planner) => {
planner.plan_tasks(&source, &context, overwrite_l0)?
}
CompactPlannerKind::DataEvolution(planner) => {
planner
.plan_tasks(&self.table, &scan, &context, self.buckets.as_ref())
Expand Down Expand Up @@ -531,7 +553,7 @@ impl CompactExecutor {
pub async fn execute(&self, task: &CompactTask) -> Result<CompactResult> {
let inputs = self.capture_inputs(task).await?;
let round = CompactRound::for_task(task);
self.execute_captured(task, &inputs, &round).await
self.execute_captured(task, &inputs, &round, None).await
}

async fn capture_inputs(&self, task: &CompactTask) -> Result<CompactInputs> {
Expand Down Expand Up @@ -579,6 +601,7 @@ impl CompactExecutor {
task: &CompactTask,
inputs: &CompactInputs,
round: &CompactRound,
overwrite_l0: Option<&OverwriteL0Files>,
) -> Result<CompactResult> {
task.validate_target(&self.table)?;
let snapshot = &inputs.snapshot;
Expand All @@ -592,7 +615,8 @@ impl CompactExecutor {
.get(&key)
.map(Vec::as_slice)
.unwrap_or_default();
task.validate_inputs(&self.table, active).await?;
task.validate_inputs(&self.table, active, overwrite_l0)
.await?;
// validate_target proved the complete schema and branch are identical.
// Preserve already resolved catalog schemas in the shared manager;
// rebuilding it here would require REST-only schemas to exist on disk.
Expand Down Expand Up @@ -817,7 +841,12 @@ impl CompactTask {
}
}

async fn validate_inputs(&self, table: &Table, active: &[ManifestEntry]) -> Result<()> {
async fn validate_inputs(
&self,
table: &Table,
active: &[ManifestEntry],
overwrite_l0: Option<&OverwriteL0Files>,
) -> Result<()> {
if self.is_data_evolution() {
data_evolution::validate_inputs(
table,
Expand All @@ -834,6 +863,12 @@ impl CompactTask {
entry.partition() == self.partition
&& entry.bucket() == self.bucket
&& entry.total_buckets() == self.total_buckets
&& within_overwrite_l0_scope(
overwrite_l0,
entry.partition(),
entry.bucket(),
entry.file(),
)
})
.map(|entry| (entry.file().file_name.as_str(), entry))
.collect::<HashMap<_, _>>();
Expand Down Expand Up @@ -926,11 +961,11 @@ impl CompactTask {
}

/// Validate published PK file changes without depending on executor task metadata.
pub(super) fn validate_primary_key_changes(
pub(super) fn validate_primary_key_changes<'a>(
schema: &TableSchema,
changes: &[ManifestEntry],
changelog: &[ManifestEntry],
captured: &[ManifestEntry],
captured: impl IntoIterator<Item = &'a ManifestEntry>,
) -> Result<()> {
fn group(entry: &ManifestEntry) -> (&[u8], i32, i32) {
(entry.partition(), entry.bucket(), entry.total_buckets())
Expand Down
33 changes: 22 additions & 11 deletions crates/paimon/src/table/compact/automatic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ use std::future::Future;

use futures::stream::{FuturesUnordered, StreamExt};

use super::{prepare_results, CompactExecutor, CompactPlan, CompactRound, PreparedCompact};
use crate::table::{Table, TableCommit};
use super::{
prepare_results, CompactExecutor, CompactPlan, CompactRound, OverwriteL0Files, PreparedCompact,
};
use crate::table::{CommitMessage, Table, TableCommit};
use crate::{Error, Result};
#[cfg(test)]
mod metadata_tests;
Expand All @@ -31,7 +33,8 @@ pub(in crate::table) async fn execute_auto_plan(
plan: &CompactPlan,
executor: &CompactExecutor,
parallelism: usize,
) -> Result<PreparedCompact> {
overwrite_l0: Option<&OverwriteL0Files>,
) -> Result<(PreparedCompact, Vec<CommitMessage>)> {
// Total-bucket metadata can change, but tasks writing one physical bucket
// still run in order. Append/DE may produce several tasks for that bucket.
let mut buckets = BTreeMap::<_, Vec<_>>::new();
Expand All @@ -50,21 +53,29 @@ pub(in crate::table) async fn execute_auto_plan(
};
let (results, error) = run_buckets(buckets.into_values(), parallelism, |task| {
let (inputs, round) = captured.as_ref().expect("nonempty task plan");
executor.execute_captured(task, inputs, round)
executor.execute_captured(task, inputs, round, overwrite_l0)
})
.await;
let prepared = match error {
Some(error) => Err(error),
None => prepare_results(table, &results),
};
if prepared.is_err() {
// All started tasks have finished. Clean every successful output by
// its own task, regardless of completion order. No publication began.
let _ = TableCommit::new(table.clone(), "auto-compact-cleanup".into())
.abort_compact(&results)
.await;
match prepared {
Ok(prepared) => Ok((
prepared,
results
.iter()
.map(super::CompactResult::abort_message)
.collect(),
)),
Err(error) => {
// All started tasks have finished and no publication began.
let _ = TableCommit::new(table.clone(), "auto-compact-cleanup".into())
.abort_compact(&results)
.await;
Err(error)
}
}
prepared
}

async fn run_buckets<T, R, F, Fut>(
Expand Down
9 changes: 5 additions & 4 deletions crates/paimon/src/table/compact/automatic/metadata_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async fn automatic_tasks_read_captured_metadata_once_and_keep_bucket_indexes() {
let snapshot_path = table.snapshot_manager().snapshot_path(snapshot.id());
watched.push(snapshot_path.clone());
counter.watch(watched);
let prepared = execute_auto_plan(&table, &plan, &executor, 2)
let (prepared, _) = execute_auto_plan(&table, &plan, &executor, 2, None)
.await
.unwrap();
let counts = counter.counts();
Expand Down Expand Up @@ -140,7 +140,7 @@ async fn automatic_tasks_read_captured_metadata_once_and_keep_bucket_indexes() {
error.to_string().contains("snapshot was replaced"),
"{error}"
);
let error = execute_auto_plan(&table, &plan, &executor, 2)
let error = execute_auto_plan(&table, &plan, &executor, 2, None)
.await
.err()
.unwrap();
Expand Down Expand Up @@ -257,14 +257,15 @@ async fn automatic_pk_vector_header_reads_and_empty_stats_share_a_limit_across_b
"retained header reads and empty-segment stats exceeded one permit per round"
);
};
let executions = (0..rounds).map(|_| execute_auto_plan(&table, &plan, &executor, 2));
let executions = (0..rounds).map(|_| execute_auto_plan(&table, &plan, &executor, 2, None));
let (prepared, ()) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(futures::future::join_all(executions), check_limit)
})
.await
.expect("each round must start an index check while the other rounds are paused");
for result in prepared {
assert_eq!(result.unwrap().index_entries.unwrap().len(), 2);
let (prepared, _) = result.unwrap();
assert_eq!(prepared.index_entries.unwrap().len(), 2);
}
assert!(counter
.counts()
Expand Down
13 changes: 11 additions & 2 deletions crates/paimon/src/table/compact/primary_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ use arrow_array::{BooleanArray, Int8Array};
use arrow_schema::SchemaRef;
use futures::TryStreamExt;

use super::{split_files_by_bucket, validate_file, CompactContext, CompactTask};
use super::{
split_files_by_bucket, validate_file, within_overwrite_l0_scope, CompactContext, CompactTask,
OverwriteL0Files,
};
use crate::resource::ResourceContext;
use crate::spec::{
BigIntType, ChangelogProducer, DataField, DataFileMeta, DataType, MergeEngine, RowKind,
Expand Down Expand Up @@ -60,6 +63,7 @@ impl PrimaryKeyCompactPlanner {
&self,
source: &Plan,
context: &CompactContext,
overwrite_l0: Option<&OverwriteL0Files>,
) -> Result<Vec<CompactTask>> {
let mut tasks = Vec::new();
let options = context.schema.core_options();
Expand All @@ -68,7 +72,12 @@ impl PrimaryKeyCompactPlanner {
|| options.try_changelog_producer()? == ChangelogProducer::Lookup
|| options.merge_engine()? == MergeEngine::FirstRow
|| options.deletion_vectors_enabled();
for ((partition, bucket, total_buckets), files) in split_files_by_bucket(source) {
for ((partition, bucket, total_buckets), mut files) in split_files_by_bucket(source) {
if overwrite_l0.is_some() {
files.retain(|file| {
within_overwrite_l0_scope(overwrite_l0, &partition, bucket, file)
});
}
for file in &files {
validate_file(file, true)?;
}
Expand Down
14 changes: 11 additions & 3 deletions crates/paimon/src/table/snapshot_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//!
//! Reference:[org.apache.paimon.utils.SnapshotManager](https://github.com/apache/paimon/blob/release-1.3/paimon-core/src/main/java/org/apache/paimon/utils/SnapshotManager.java).
use crate::catalog::DEFAULT_MAIN_BRANCH;
use crate::io::FileIO;
use crate::io::{FileIO, InputFile};
use crate::spec::Snapshot;
use futures::future::try_join_all;
use std::str;
Expand Down Expand Up @@ -225,8 +225,16 @@ impl SnapshotManager {

/// Get a snapshot by id.
pub async fn get_snapshot(&self, snapshot_id: i64) -> crate::Result<Snapshot> {
let snapshot_path = self.snapshot_path(snapshot_id);
let snap_input = self.file_io.new_input(&snapshot_path)?;
let input = self.file_io.new_input(&self.snapshot_path(snapshot_id))?;
Self::read_snapshot(snapshot_id, input).await
}

pub(super) async fn get_snapshot_uncached(&self, snapshot_id: i64) -> crate::Result<Snapshot> {
let input = self.file_io.new_input(&self.snapshot_path(snapshot_id))?;
Self::read_snapshot(snapshot_id, input.without_cache()).await
}

async fn read_snapshot(snapshot_id: i64, snap_input: InputFile) -> crate::Result<Snapshot> {
if !snap_input.exists().await? {
return Err(crate::Error::SnapshotNotExist { snapshot_id });
}
Expand Down
Loading
Loading