Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add concurrent writes reconciliation for non-blind INSERT in Delta Lake #20983

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,37 @@
package io.trino.plugin.deltalake;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.trino.plugin.deltalake.transactionlog.CommitInfoEntry;
import io.trino.plugin.deltalake.transactionlog.DeltaLakeTransactionLogEntry;
import io.trino.plugin.deltalake.transactionlog.MetadataEntry;
import io.trino.plugin.deltalake.transactionlog.ProtocolEntry;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static java.util.Objects.requireNonNull;

public class DeltaLakeCommitSummary
{
private final long version;
private final List<MetadataEntry> metadataUpdates;
private final Optional<ProtocolEntry> protocol;
private final boolean containingRemovedFiles;
private final Set<Map<String, Optional<String>>> addedFilesCanonicalPartitionValues;
private final Optional<Boolean> isBlindAppend;

public DeltaLakeCommitSummary(List<DeltaLakeTransactionLogEntry> transactionLogEntries)
public DeltaLakeCommitSummary(long version, List<DeltaLakeTransactionLogEntry> transactionLogEntries)
{
requireNonNull(transactionLogEntries, "transactionLogEntries is null");
ImmutableList.Builder<MetadataEntry> metadataUpdatesBuilder = ImmutableList.builder();
Optional<ProtocolEntry> optionalProtocol = Optional.empty();
Optional<CommitInfoEntry> optionalCommitInfo = Optional.empty();
ImmutableSet.Builder<Map<String, Optional<String>>> addedFilesCanonicalPartitionValuesBuilder = ImmutableSet.builder();

boolean removedFilesFound = false;
for (DeltaLakeTransactionLogEntry transactionLogEntry : transactionLogEntries) {
if (transactionLogEntry.getMetaData() != null) {
metadataUpdatesBuilder.add(transactionLogEntry.getMetaData());
Expand All @@ -47,13 +55,27 @@ else if (transactionLogEntry.getProtocol() != null) {
else if (transactionLogEntry.getCommitInfo() != null) {
optionalCommitInfo = Optional.of(transactionLogEntry.getCommitInfo());
}
else if (transactionLogEntry.getAdd() != null) {
addedFilesCanonicalPartitionValuesBuilder.add(transactionLogEntry.getAdd().getCanonicalPartitionValues());
}
else if (transactionLogEntry.getRemove() != null) {
removedFilesFound = true;
}
}

this.version = version;
metadataUpdates = metadataUpdatesBuilder.build();
protocol = optionalProtocol;
addedFilesCanonicalPartitionValues = addedFilesCanonicalPartitionValuesBuilder.build();
containingRemovedFiles = removedFilesFound;
isBlindAppend = optionalCommitInfo.flatMap(CommitInfoEntry::isBlindAppend);
}

public long getVersion()
{
return version;
}

public List<MetadataEntry> getMetadataUpdates()
{
return metadataUpdates;
Expand All @@ -64,6 +86,16 @@ public Optional<ProtocolEntry> getProtocol()
return protocol;
}

public boolean isContainingRemovedFiles()
{
return containingRemovedFiles;
}

public Set<Map<String, Optional<String>>> getAddedFilesCanonicalPartitionValues()
{
return addedFilesCanonicalPartitionValues;
}

public Optional<Boolean> getIsBlindAppend()
{
return isBlindAppend;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,6 @@
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.ColumnMappingMode.NAME;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.ColumnMappingMode.NONE;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.IsolationLevel;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.IsolationLevel.SERIALIZABLE;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.MAX_COLUMN_ID_CONFIGURATION_KEY;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.TIMESTAMP_NTZ_FEATURE_NAME;
import static io.trino.plugin.deltalake.transactionlog.DeltaLakeSchemaSupport.changeDataFeedEnabled;
Expand Down Expand Up @@ -1840,14 +1839,13 @@ private long commitInsertOperation(
TrinoFileSystem fileSystem = fileSystemFactory.create(session);
long currentVersion = getMandatoryCurrentVersion(fileSystem, handle.getLocation(), handle.getReadVersion());

boolean isBlindAppend = sourceTableHandles.stream()
List<DeltaLakeTableHandle> sameAsTargetSourceTableHandles = sourceTableHandles.stream()
.filter(sourceTableHandle -> sourceTableHandle instanceof DeltaLakeTableHandle)
.map(DeltaLakeTableHandle.class::cast)
.filter(tableHandle -> handle.getTableName().equals(tableHandle.getSchemaTableName())
// disregard time travel table handles
&& tableHandle.getReadVersion() >= handle.getReadVersion())
.findAny()
.isEmpty();
.collect(toImmutableList());
long readVersionValue = readVersion.get();
if (currentVersion > readVersionValue) {
String transactionLogDirectory = getTransactionLogDir(handle.getLocation());
Expand All @@ -1861,37 +1859,43 @@ private long commitInsertOperation(
catch (IOException e) {
throw new TrinoException(DELTA_LAKE_FILESYSTEM_ERROR, "Failed to access table metadata", e);
}
checkForInsertTransactionConflicts(session.getQueryId(), isBlindAppend, isolationLevel, new DeltaLakeCommitSummary(transactionLogEntries), version, attemptCount);
checkForInsertTransactionConflicts(session.getQueryId(), sameAsTargetSourceTableHandles, isolationLevel, new DeltaLakeCommitSummary(version, transactionLogEntries), attemptCount);
}

// Avoid re-reading already processed transaction log entries in case of retries
readVersion.set(currentVersion);
}
long commitVersion = currentVersion + 1;
writeTransactionLogForInsertOperation(session, handle, isBlindAppend, isolationLevel, dataFileInfos, commitVersion, currentVersion);
writeTransactionLogForInsertOperation(session, handle, sameAsTargetSourceTableHandles.isEmpty(), isolationLevel, dataFileInfos, commitVersion, currentVersion);
return commitVersion;
}

private void checkForInsertTransactionConflicts(
String queryId,
boolean isBlindAppend,
List<DeltaLakeTableHandle> sameAsTargetSourceTableHandles,
IsolationLevel isolationLevel,
DeltaLakeCommitSummary commitSummary,
long version,
int attemptCount)
{
checkNoMetadataUpdates(commitSummary);
checkNoProtocolUpdates(commitSummary);

if (!isBlindAppend) {
throw new TransactionFailedException("Conflicting concurrent writes with the current non blind append INSERT operation");
}
switch (isolationLevel) {
case WRITESERIALIZABLE -> {
if (!sameAsTargetSourceTableHandles.isEmpty()) {
// INSERT operations that contain sub-queries reading the same table support the same concurrency as MERGE.
List<TupleDomain<DeltaLakeColumnHandle>> enforcedSourcePartitionConstraints = sameAsTargetSourceTableHandles.stream()
.map(DeltaLakeTableHandle::getEnforcedPartitionConstraint)
.collect(toImmutableList());

if (isolationLevel == SERIALIZABLE) {
throw new TransactionFailedException("Conflicting concurrent writes with the current blind append INSERT operation on Serializable isolation level");
checkIfCommittedAddedFilesConflictWithCurrentOperation(TupleDomain.columnWiseUnion(enforcedSourcePartitionConstraints), commitSummary);
checkIfCommittedRemovedFilesConflictWithCurrentOperation(commitSummary);
}
}
case SERIALIZABLE -> throw new TransactionFailedException("Conflicting concurrent writes with the current INSERT operation on Serializable isolation level");
}

LOG.debug("Completed checking for conflicts in the query %s for target table version: %s Attempt: %s ", queryId, version, attemptCount);
LOG.debug("Completed checking for conflicts in the query %s for target table version: %s Attempt: %s ", queryId, commitSummary.getVersion(), attemptCount);
}

private static void checkNoProtocolUpdates(DeltaLakeCommitSummary commitSummary)
Expand All @@ -1908,6 +1912,48 @@ private static void checkNoMetadataUpdates(DeltaLakeCommitSummary commitSummary)
}
}

private static void checkIfCommittedAddedFilesConflictWithCurrentOperation(TupleDomain<DeltaLakeColumnHandle> enforcedSourcePartitionConstraints, DeltaLakeCommitSummary commitSummary)
{
Set<Map<String, Optional<String>>> addedFilesCanonicalPartitionValues = commitSummary.getIsBlindAppend().orElse(false)
// Do not conflict with blind appends. Blind appends can be placed before or after the current operation
// when backtracking which serializable sequence of operations led to the current state of the table.
? Set.of()
: commitSummary.getAddedFilesCanonicalPartitionValues();

if (addedFilesCanonicalPartitionValues.isEmpty()) {
return;
}

boolean readWholeTable = enforcedSourcePartitionConstraints.isAll();
if (readWholeTable) {
throw new TransactionFailedException("Conflicting concurrent writes found. Data files added in the modified table by concurrent write operation.");
}

Map<DeltaLakeColumnHandle, Domain> enforcedDomains = enforcedSourcePartitionConstraints.getDomains().orElseThrow();
boolean conflictingAddFilesFound = addedFilesCanonicalPartitionValues.stream()
.anyMatch(canonicalPartitionValues -> partitionMatchesPredicate(canonicalPartitionValues, enforcedDomains));
if (conflictingAddFilesFound) {
throw new TransactionFailedException("Conflicting concurrent writes found. Data files were added in the modified table by another concurrent write operation.");
}
}

private static void checkIfCommittedRemovedFilesConflictWithCurrentOperation(DeltaLakeCommitSummary commitSummary)
{
if (commitSummary.getIsBlindAppend().orElse(false)) {
findinpath marked this conversation as resolved.
Show resolved Hide resolved
// Do not conflict with blind appends. Blind appends can be placed before or after the current operation
// when backtracking which serializable sequence of operations led to the current state of the table.
checkState(!commitSummary.isContainingRemovedFiles(), "Blind append transaction %s cannot contain removed files", commitSummary.getVersion());
return;
}

if (!commitSummary.isContainingRemovedFiles()) {
return;
}

// TODO Pass active files of the target table read in DeltaLakeSplitSource to figure out whether the removed files do actually conflict with the read table partitions
findinpath marked this conversation as resolved.
Show resolved Hide resolved
throw new TransactionFailedException("Conflicting concurrent writes found. Data files were removed from the modified table by another concurrent write operation.");
}

private void writeTransactionLogForInsertOperation(
ConnectorSession session,
DeltaLakeInsertTableHandle insertTableHandle,
Expand Down Expand Up @@ -2037,7 +2083,7 @@ public void finishMerge(ConnectorSession session, ConnectorMergeTableHandle merg
}
long commitVersion = currentVersion + 1;

transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, createdTime, MERGE_OPERATION, handle.getReadVersion(), true));
transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, createdTime, MERGE_OPERATION, handle.getReadVersion(), false));
// TODO: Delta writes another field "operationMetrics" (https://github.com/trinodb/trino/issues/12005)

long writeTimestamp = Instant.now().toEpochMilli();
Expand Down Expand Up @@ -2256,7 +2302,7 @@ private void finishOptimize(ConnectorSession session, DeltaLakeTableExecuteHandl

long createdTime = Instant.now().toEpochMilli();
long commitVersion = readVersion + 1;
transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, createdTime, OPTIMIZE_OPERATION, readVersion, true));
transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, createdTime, OPTIMIZE_OPERATION, readVersion, false));
// TODO: Delta writes another field "operationMetrics" that I haven't
// seen before. It contains delete/update metrics. Investigate/include it.

Expand Down Expand Up @@ -3573,7 +3619,7 @@ private OptionalLong executeDelete(ConnectorSession session, ConnectorTableHandl
throw new TransactionConflictException(format("Conflicting concurrent writes found. Expected transaction log version: %s, actual version: %s", tableHandle.getReadVersion(), currentVersion));
}
long commitVersion = currentVersion + 1;
transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, writeTimestamp, operation, tableHandle.getReadVersion(), true));
transactionLogWriter.appendCommitInfoEntry(getCommitInfoEntry(session, IsolationLevel.WRITESERIALIZABLE, commitVersion, writeTimestamp, operation, tableHandle.getReadVersion(), false));

long deletedRecords = 0L;
boolean allDeletedFilesStatsPresent = true;
Expand Down
Loading