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
18 changes: 18 additions & 0 deletions crates/paimon/src/table/aggregator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,21 @@ pub(crate) trait FieldAggregator: Send + Sync + std::fmt::Debug {

/// Materialize the current accumulator as a 1-row Arrow array.
fn result(&self) -> crate::Result<ArrayRef>;

/// Start from the accumulator before any input instead of NULL, for a
/// non-nullable field whose merge starts with a retraction. Returns false
/// when the aggregator has no such accumulator.
fn start_empty(&mut self) -> bool {
false
}

/// The cell of a retract result built only from retractions. A later merge
/// retracts this value again, so it must undo the accumulated retractions.
/// Returns `None` when no retracted value undoes them, as for a checked
/// sum at its minimum.
fn retraction_result(&self) -> crate::Result<Option<ArrayRef>> {
self.result().map(Some)
}
}

/// Construct an aggregator by `name` for a column of type `data_type`.
Expand Down Expand Up @@ -256,6 +271,9 @@ impl FieldAggregator for IgnoreRetractAgg {
fn result(&self) -> crate::Result<ArrayRef> {
self.0.result()
}
fn start_empty(&mut self) -> bool {
self.0.start_empty()
}
}

/// Helper: build a `ConfigInvalid` error for an unsupported (aggregator, type)
Expand Down
46 changes: 46 additions & 0 deletions crates/paimon/src/table/aggregator/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,52 @@ impl FieldAggregator for SumAgg {
}
})
}

fn start_empty(&mut self) -> bool {
match &mut self.state {
SumState::I8(acc) => *acc = Some(0),
SumState::I16(acc) => *acc = Some(0),
SumState::I32(acc) => *acc = Some(0),
SumState::I64(acc) => *acc = Some(0),
SumState::F32(acc) => *acc = Some(0.0),
SumState::F64(acc) => *acc = Some(0.0),
SumState::Decimal128 { acc, .. } => *acc = Some(0),
}
true
}

fn retraction_result(&self) -> crate::Result<Option<ArrayRef>> {
macro_rules! negate_integer {
($acc:expr) => {
match $acc {
// A checked sum at its minimum has no retracted value.
Some(value) if self.fail_on_overflow => match value.checked_neg() {
Some(negated) => Some(negated),
None => return Ok(None),
},
other => other.map(|value| value.wrapping_neg()),
}
};
}
Ok(Some(match &self.state {
SumState::I8(acc) => Arc::new(Int8Array::from(vec![negate_integer!(*acc)])),
SumState::I16(acc) => Arc::new(Int16Array::from(vec![negate_integer!(*acc)])),
SumState::I32(acc) => Arc::new(Int32Array::from(vec![negate_integer!(*acc)])),
SumState::I64(acc) => Arc::new(Int64Array::from(vec![negate_integer!(*acc)])),
SumState::F32(acc) => Arc::new(Float32Array::from(vec![acc.map(|value| -value)])),
SumState::F64(acc) => Arc::new(Float64Array::from(vec![acc.map(|value| -value)])),
SumState::Decimal128 {
precision,
scale,
acc,
} => {
let fitted = acc
.and_then(i128::checked_neg)
.filter(|v| decimal_fits_precision(*v, *precision));
decimal_array(*precision, *scale, fitted, "sum", &self.field_name)?
}
}))
}
}

// ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion crates/paimon/src/table/postpone_retract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl PostponeRetractValidator {
merge.merge(&[row], &buffer, &self.value_indices, &schema)?;
}
RetractMerge::PartialUpdate(merge) => {
merge.merge_unreduced(&[row], &buffer, &self.value_indices, &schema)?;
merge.validate_retract(&row, &buffer, &self.value_indices, &schema)?;
}
RetractMerge::Aggregate(merge) => {
merge.merge_ordered(&[&row], &buffer, &self.value_indices, &schema)?;
Expand Down
147 changes: 134 additions & 13 deletions crates/paimon/src/table/sort_merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,49 @@ impl PartialUpdateMergeFunction {
Ok(())
}

/// Seeds a merge that starts with a retraction under sequence groups:
/// required fields take the row's values, required aggregates start empty
/// when they can, and nullable fields stay NULL.
#[allow(clippy::too_many_arguments)]
fn init_from_retraction(
&self,
selected_by_col: &mut [Option<(usize, usize)>],
mut aggregators: Option<&mut [Option<Box<dyn FieldAggregator>>]>,
group_sequence_rows: &mut [Option<(usize, usize)>],
row: &MergeRow,
batch_buffer: &[BufferedBatch],
source_output_col_indices: &[usize],
output_schema: &SchemaRef,
) -> crate::Result<()> {
let source = Some((row.batch_idx, row.row_idx));
for (index, field) in output_schema.fields().iter().enumerate() {
let aggregator = aggregators
.as_mut()
.and_then(|aggregators| aggregators.get_mut(index))
.and_then(Option::as_mut);
let nullable = field.is_nullable();
selected_by_col[index] = if nullable { None } else { source };
if let Some(aggregator) = aggregator {
aggregator.reset();
if !nullable && !aggregator.start_empty() {
aggregator.agg(
batch_buffer[row.batch_idx]
.column_for_output(index, source_output_col_indices),
row.row_idx,
)?;
}
}
}
for (group, current) in self.sequence_groups.iter().zip(group_sequence_rows) {
let required = group
.sequence_indices
.iter()
.all(|&index| !output_schema.field(index).is_nullable());
*current = if required { source } else { None };
}
Ok(())
}

/// Java `updateNonNullFields`: ungrouped fields take the row's non-null
/// values, or feed their aggregator.
fn update_non_null_fields(
Expand Down Expand Up @@ -706,6 +749,7 @@ impl MergeFunction for PartialUpdateMergeFunction {
source_output_col_indices,
output_schema,
true,
false,
)
.map(Some)
}
Expand All @@ -725,12 +769,34 @@ impl PartialUpdateMergeFunction {
source_output_col_indices,
output_schema,
false,
false,
)? {
PickedMerge::Result(result) => Ok(result),
PickedMerge::Picked(_) => unreachable!("picked rows are only returned when requested"),
}
}

/// Fails when the table does not support this retraction. Only the
/// support is checked, so the row starts from the retracted value and
/// its retraction cannot overflow a sum.
pub(super) fn validate_retract(
&self,
row: &MergeRow,
batch_buffer: &[BufferedBatch],
source_output_col_indices: &[usize],
output_schema: &SchemaRef,
) -> crate::Result<()> {
self.merge_rows(
std::slice::from_ref(row),
batch_buffer,
source_output_col_indices,
output_schema,
false,
true,
)
.map(|_| ())
}

/// With `pick`, a live row is returned as the input rows its columns come from.
fn merge_rows(
&self,
Expand All @@ -739,6 +805,7 @@ impl PartialUpdateMergeFunction {
source_output_col_indices: &[usize],
output_schema: &SchemaRef,
pick: bool,
validate_only: bool,
) -> crate::Result<PickedMerge> {
if rows.is_empty() {
return Err(Error::UnexpectedError {
Expand Down Expand Up @@ -784,18 +851,34 @@ impl PartialUpdateMergeFunction {
continue;
}
if !initialized {
// Java initializes the row from the first retract before
// checking ignore-delete or applying sequence-group
// retractions. Keep that payload for later sparse updates.
Self::replace_with_source(
&mut selected_by_col,
aggregators.as_mut().map(|guard| guard.as_mut_slice()),
row.batch_idx,
row.row_idx,
batch_buffer,
source_output_col_indices,
)?;
group_sequence_rows.fill(Some((row.batch_idx, row.row_idx)));
if self.sequence_group_enabled && !self.ignore_delete && !validate_only {
// The retraction is applied to the groups below, so
// seed only the required fields, with aggregates
// empty: seeding the retracted value would let the
// retraction cancel it and keep the old value.
self.init_from_retraction(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep a checked sum writable when the retraction cancels a valid existing value. On a partial-update table with fields.seq.sequence-group=amount, a required BIGINT sum, and fields.amount.sum.fail-on-overflow=true, I committed +I(amount=i64::MIN, seq=1). Committing -U(i64::MIN, 2) and +U(i64::MIN, 3) separately reads i64::MIN as expected. Sending the same update pair in one commit on this head fails at prepare_commit with Aggregate function 'sum' overflowed on field 'amount'. Pre-merging the pair starts at zero and computes 0 - i64::MIN before the compensating add. Please keep the original records when that intermediate merge cannot be represented, or represent the intermediate delta exactly, and test both flush layouts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @JingsongLi. The .so.zst came from building the Go bindings in the same checkout, sorry about that. It's dropped in 801ff48. The overflow case came up on apache/paimon#11274 today as well, so I'll follow the representation that lands there and update this PR once it's settled.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve raw retractions in the postpone writer. On a bucket=-2 partial-update table with a sequence group and checked BIGINT sum, I committed +I(i64::MIN) and then wrote a single -U(i64::MIN) in a fresh writer. The same two commits succeed on 8105e1eb. On this head, write_arrow_batch fails with Aggregate function 'sum' overflowed on field 'amount'. The postpone writer stores the raw row, but its first-retract validator calls merge_unreduced, which now tries to compute 0 - i64::MIN. Please preserve validation of supported retractions without requiring an intermediate sum for this raw write, and cover the standalone retraction in the postpone writer tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @JingsongLi. The postpone writer only needs to know that the retraction is supported, so its check now starts the row from the retracted value as it did before this PR, and 0 - i64::MIN is never computed. postpone_writer_keeps_a_retraction_of_the_minimum writes the standalone -U(i64::MIN) after +I(i64::MIN); it fails on the previous head.

&mut selected_by_col,
aggregators.as_mut().map(|guard| guard.as_mut_slice()),
&mut group_sequence_rows,
row,
batch_buffer,
source_output_col_indices,
output_schema,
)?;
} else {
// Java initializes the row from the first retract before
// checking ignore-delete. Keep that payload for later
// sparse updates.
Self::replace_with_source(
&mut selected_by_col,
aggregators.as_mut().map(|guard| guard.as_mut_slice()),
row.batch_idx,
row.row_idx,
batch_buffer,
source_output_col_indices,
)?;
group_sequence_rows.fill(Some((row.batch_idx, row.row_idx)));
}
initialized = true;
}
if self.ignore_delete {
Expand Down Expand Up @@ -1032,6 +1115,21 @@ impl PartialUpdateMergeFunction {
}));
}

let only_retractions =
self.sequence_group_enabled && !saw_add && !current_delete_row && !self.ignore_delete;
// A later merge retracts this result again, so aggregates are written
// as values to retract. When one has no such value, the accumulated
// retractions are written as an add instead.
let retraction_cells = match aggregators.as_ref() {
Some(aggregators) if only_retractions => retraction_cells(aggregators)?,
_ => None,
};
let (result_kind, deleted) =
if only_retractions && aggregators.is_some() && retraction_cells.is_none() {
(RowKind::Insert, false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep retraction-only keys absent when a checked sum reaches its minimum. I wrote -U(i64::MAX, seq=1) and -U(1, seq=2) for a key with no prior row using bucket=1, fields.seq.sequence-group=amount, and a checked BIGINT sum. On this head, a table scan returns a live row with amount = i64::MIN before and after compaction. It happens with one commit or two and with required or nullable sums. The same combined-commit case on main returns zero rows. Please keep the ordered retracts when no single DELETE payload can represent them, and preserve the key's deleted state when producing scan results.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @JingsongLi, both reproduce. houlinchn compared a few designs for this on apache/paimon#11274 and asked which one to take, and the raw-records option there is what you describe here. I'll port the one you pick so both sides keep the same rows.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for confirming the reproductions. I retested bad54208 on e4b84b47. All 159 partial-update, primary-key compaction, row-kind, and postpone-writer tests passed. The separate checked-sum cases still reproduce. The paired minimum-value update fails in prepare_commit when written together and succeeds when split. An absent key with only the two retractions becomes a live row before and after compaction, with either nullability setting.

Please cover both cases in the port. Keep the original record order and row kinds wherever flush or compaction cannot encode the checked intermediate state in one record. The Java experiments also show where widening the accumulator still leaves an unrepresentable on-disk delta. Java comparison

} else {
(result_kind, deleted)
};
let output_columns: Vec<ArrayRef> = output_schema
.fields()
.iter()
Expand All @@ -1045,7 +1143,13 @@ impl PartialUpdateMergeFunction {
.and_then(|aggregators| aggregators.get(output_col_idx))
.and_then(Option::as_ref)
{
Some(aggregator) => aggregator.result()?,
Some(aggregator) => match retraction_cells
.as_ref()
.and_then(|cells| cells[output_col_idx].clone())
{
Some(cell) => cell,
None => aggregator.result()?,
},
None => match selected_by_col[output_col_idx] {
Some((batch_idx, row_idx)) => batch_buffer[batch_idx]
.column_for_output(output_col_idx, source_output_col_indices)
Expand Down Expand Up @@ -1085,6 +1189,23 @@ impl PartialUpdateMergeFunction {
}
}

/// Each aggregate's value to retract, or `None` when one has none.
fn retraction_cells(
aggregators: &[Option<Box<dyn FieldAggregator>>],
) -> crate::Result<Option<Vec<Option<ArrayRef>>>> {
let mut cells = Vec::with_capacity(aggregators.len());
for aggregator in aggregators {
cells.push(match aggregator {
Some(aggregator) => match aggregator.retraction_result()? {
Some(cell) => Some(cell),
None => return Ok(None),
},
None => None,
});
}
Ok(Some(cells))
}

fn compare_sequence_group_rows(
incoming_batch_idx: usize,
incoming_row_idx: usize,
Expand Down
3 changes: 2 additions & 1 deletion crates/paimon/tests/pk_compact/merge_engines_edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ async fn partial_update_retract_only_aggregate_state_refuses_lossy_compaction()
for table in [&control, &rewritten] {
write_batch(table, &update(Some(12), Some(3), None, 0)).await;
}
assert_eq!(state(&control).await, vec![(Some(12), Some(-2), None)]);
// -10 - 5 + 3: the first retraction does not cancel its own payload.
assert_eq!(state(&control).await, vec![(Some(12), Some(-12), None)]);
assert_eq!(state(&rewritten).await, state(&control).await);
}
}
Expand Down
Loading
Loading