Repository navigation
Add basic support of Delta commits for managed tables #1166
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
Changes from all commits
ad412c7
bf055f1
311cb22
7eb4caf
8c6992a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| package io.unitycatalog.server.persist; | ||
|
|
||
| import io.unitycatalog.server.exception.BaseException; | ||
| import io.unitycatalog.server.exception.ErrorCode; | ||
| import io.unitycatalog.server.model.ColumnInfos; | ||
| import io.unitycatalog.server.model.Commit; | ||
| import io.unitycatalog.server.model.CommitInfo; | ||
| import io.unitycatalog.server.model.CommitMetadataProperties; | ||
| import io.unitycatalog.server.model.DataSourceFormat; | ||
| import io.unitycatalog.server.model.Metadata; | ||
| import io.unitycatalog.server.model.TableType; | ||
| import io.unitycatalog.server.persist.dao.DeltaCommitDAO; | ||
| import io.unitycatalog.server.persist.dao.TableInfoDAO; | ||
| import io.unitycatalog.server.persist.utils.FileOperations; | ||
| import io.unitycatalog.server.persist.utils.TransactionManager; | ||
| import io.unitycatalog.server.utils.ServerProperties; | ||
| import io.unitycatalog.server.utils.ValidationUtils; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.Optional; | ||
| import java.util.UUID; | ||
| import org.hibernate.Session; | ||
| import org.hibernate.SessionFactory; | ||
| import org.hibernate.query.Query; | ||
|
|
||
| /** Repository for managing coordinated commits for managed Delta tables in Unity Catalog. */ | ||
| public class DeltaCommitRepository { | ||
|
|
||
| private final SessionFactory sessionFactory; | ||
| private final ServerProperties serverProperties; | ||
|
|
||
| public DeltaCommitRepository(SessionFactory sessionFactory, ServerProperties serverProperties) { | ||
| this.sessionFactory = sessionFactory; | ||
| this.serverProperties = serverProperties; | ||
| } | ||
|
|
||
| /** Commits a new version to a managed Delta table with coordinated commit semantics. */ | ||
| public void postCommit(Commit commit) { | ||
| serverProperties.checkManagedTableEnabled(); | ||
| validateCommit(commit); | ||
| TransactionManager.executeWithTransaction( | ||
| sessionFactory, | ||
| session -> { | ||
| UUID tableId = UUID.fromString(commit.getTableId()); | ||
| TableInfoDAO tableInfoDAO = session.get(TableInfoDAO.class, tableId); | ||
| if (tableInfoDAO == null) { | ||
| throw new BaseException(ErrorCode.NOT_FOUND, "Table not found: " + commit.getTableId()); | ||
| } | ||
| validateTableForCommit(commit, tableInfoDAO); | ||
| List<DeltaCommitDAO> firstAndLastCommits = getFirstAndLastCommits(session, tableId); | ||
| if (firstAndLastCommits.isEmpty()) { | ||
| handleOnboardingCommit(session, tableId, tableInfoDAO, commit); | ||
| } else { | ||
| DeltaCommitDAO firstCommit = firstAndLastCommits.get(0); | ||
| DeltaCommitDAO lastCommit = firstAndLastCommits.get(1); | ||
| assert firstCommit.getCommitVersion() <= lastCommit.getCommitVersion(); | ||
| if (commit.getCommitInfo() == null) { | ||
| // This is already checked in validateCommit() | ||
| assert commit.getLatestBackfilledVersion() != null; | ||
| throw new BaseException(ErrorCode.UNIMPLEMENTED, "Backfill is not implemented yet!"); | ||
| } else { | ||
| handleNormalCommit(session, tableId, commit, lastCommit); | ||
| } | ||
| } | ||
| return null; | ||
| }, | ||
| "Error committing to table: " + commit.getTableId(), | ||
| /* readOnly = */ false); | ||
| } | ||
|
|
||
| /** | ||
| * Handle an onboarding commit which is the very first commit sent to UC, and it's commiting a | ||
| * version. This commit does not do backfill because there is no version prior to this commit. | ||
| * This may be the first ever commit of the table since creation, or that the previous commits | ||
| * were just FS commits. In any way, the table will use UC as commit coordinator starting from | ||
| * this commit. | ||
| */ | ||
| private static void handleOnboardingCommit( | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| Session session, UUID tableId, TableInfoDAO tableInfoDAO, Commit commit) { | ||
| CommitInfo commitInfo = commit.getCommitInfo(); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo != null, | ||
| "Field can not be null: %s in onboarding commit", | ||
| Commit.JSON_PROPERTY_COMMIT_INFO); | ||
| saveCommit(session, tableId, commitInfo); | ||
| // TODO: update table metadata | ||
| } | ||
|
|
||
| /** | ||
| * Handle a normal commit which is commiting a version, and it's not the first version sent to UC. | ||
| * Optionally in the same commit it may also report backfilled version and/or update metadata. | ||
| */ | ||
| private static void handleNormalCommit( | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| Session session, UUID tableId, Commit commit, DeltaCommitDAO lastCommit) { | ||
| CommitInfo commitInfo = Objects.requireNonNull(commit.getCommitInfo()); | ||
| long lastCommitVersion = lastCommit.getCommitVersion(); | ||
| long newCommitVersion = commitInfo.getVersion(); | ||
| if (newCommitVersion <= lastCommitVersion) { | ||
| throw new BaseException( | ||
| ErrorCode.ALREADY_EXISTS, | ||
| "Commit version already accepted. Current table version is " + lastCommitVersion); | ||
| } | ||
| if (newCommitVersion > lastCommitVersion + 1) { | ||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, | ||
| String.format( | ||
| "Commit version must be the next version after the latest commit %d, but got %d", | ||
| lastCommitVersion, newCommitVersion)); | ||
| } | ||
| // TODO: check commit limit after implementing backfill | ||
| saveCommit(session, tableId, commitInfo); | ||
| // TODO: update table metadata | ||
| } | ||
|
|
||
| private static void saveCommit(Session session, UUID tableId, CommitInfo commitInfo) { | ||
| DeltaCommitDAO deltaCommitDAO = DeltaCommitDAO.from(tableId, commitInfo); | ||
| session.persist(deltaCommitDAO); | ||
| } | ||
|
|
||
| private List<DeltaCommitDAO> getFirstAndLastCommits(Session session, UUID tableId) { | ||
| // Use native SQL to get the first and last commits since HQL doesn't support UNION ALL | ||
| String sql = | ||
| "(SELECT * FROM uc_commits WHERE table_id = :tableId " | ||
| + "ORDER BY commit_version ASC LIMIT 1) " | ||
| + "UNION ALL " | ||
| + "(SELECT * FROM uc_commits WHERE table_id = :tableId " | ||
| + "ORDER BY commit_version DESC LIMIT 1)"; | ||
| Query<DeltaCommitDAO> query = session.createNativeQuery(sql, DeltaCommitDAO.class); | ||
| query.setParameter("tableId", tableId); | ||
| List<DeltaCommitDAO> result = query.getResultList(); | ||
| // Sort to ensure the first commit is at index 0 | ||
| result.sort(Comparator.comparing(DeltaCommitDAO::getCommitVersion)); | ||
| return result; | ||
| } | ||
|
|
||
| private static void validateCommit(Commit commit) { | ||
| // Validate the commit object | ||
| ValidationUtils.checkArgument( | ||
| commit.getTableId() != null && !commit.getTableId().isEmpty(), | ||
| "Field can not be empty: %s", | ||
| Commit.JSON_PROPERTY_TABLE_ID); | ||
| ValidationUtils.checkArgument( | ||
| commit.getTableUri() != null && !commit.getTableUri().isEmpty(), | ||
| "Field can not be empty: %s", | ||
| Commit.JSON_PROPERTY_TABLE_URI); | ||
|
|
||
| // Validate the commit info object | ||
| if (commit.getCommitInfo() != null) { | ||
| CommitInfo commitInfo = commit.getCommitInfo(); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo.getVersion() != null && commitInfo.getVersion() > 0, | ||
| "Field must be positive: %s", | ||
| CommitInfo.JSON_PROPERTY_VERSION); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo.getTimestamp() != null && commitInfo.getTimestamp() > 0, | ||
| "Field must be positive: %s", | ||
| CommitInfo.JSON_PROPERTY_TIMESTAMP); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo.getFileName() != null && !commitInfo.getFileName().isEmpty(), | ||
| "Field can not be empty: %s", | ||
| CommitInfo.JSON_PROPERTY_FILE_NAME); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo.getFileSize() != null && commitInfo.getFileSize() > 0, | ||
| "Field must be positive: %s", | ||
| CommitInfo.JSON_PROPERTY_FILE_SIZE); | ||
| ValidationUtils.checkArgument( | ||
| commitInfo.getFileModificationTimestamp() != null | ||
| && commitInfo.getFileModificationTimestamp() > 0, | ||
| "Field must be positive: %s", | ||
| CommitInfo.JSON_PROPERTY_FILE_MODIFICATION_TIMESTAMP); | ||
| if (commit.getMetadata() != null) { | ||
| Metadata metadata = commit.getMetadata(); | ||
| Optional<Map<String, String>> propertiesOpt = | ||
| Optional.ofNullable(metadata.getProperties()) | ||
| .map(CommitMetadataProperties::getProperties); | ||
| boolean hasProperties = propertiesOpt.map(p -> !p.isEmpty()).orElse(false); | ||
| boolean hasSchema = | ||
| Optional.ofNullable(metadata.getSchema()) | ||
| .map(ColumnInfos::getColumns) | ||
| .map(c -> !c.isEmpty()) | ||
| .orElse(false); | ||
|
|
||
| if (metadata.getDescription() == null && !hasProperties && !hasSchema) { | ||
| // metadata should only be set when there is an actual change in metadata. | ||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, | ||
| "At least one of description, properties, or schema must be set in commit.metadata"); | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| } | ||
| Optional<String> propertiesTableIdOpt = propertiesOpt.map(p -> p.get("ucTableId")); | ||
| if (propertiesTableIdOpt.isEmpty()) { | ||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, "commit does not contain ucTableId in the properties."); | ||
| } | ||
| if (!propertiesTableIdOpt.get().equals(commit.getTableId())) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just curious: so if it requires the
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is to ensure that the Delta table's log on the file system has the table id stored as a property. An extra check to ensure that the filesystem-based information and the catalog-based information is in sync. for example, if some buggy connector accidentally updated table A on the file system, but send the commit to table B in UC, then this check will catch it as table A's properties in the log will have a different id than the table B's id in UC.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please right this down as a comment. important information.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, | ||
| String.format( | ||
| "the table being committed (%s) does not match the properties ucTableId(%s).", | ||
| commit.getTableId(), propertiesTableIdOpt.get())); | ||
| } | ||
| } | ||
| } else { | ||
| // If commit info is null, then it should be a backfill only commit | ||
| if (commit.getLatestBackfilledVersion() == null) { | ||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, | ||
| "Either commit_info or latest_backfilled_version must be defined"); | ||
| } | ||
| if (commit.getMetadata() != null) { | ||
| throw new BaseException( | ||
| ErrorCode.INVALID_ARGUMENT, "metadata shouldn't be set for backfill only commit"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static void validateTable(TableInfoDAO tableInfoDAO) { | ||
| ValidationUtils.checkArgument( | ||
| tableInfoDAO.getType() != null | ||
| && tableInfoDAO.getType().equals(TableType.MANAGED.toString()), | ||
| "Only managed tables are supported for coordinated commits"); | ||
| ValidationUtils.checkArgument( | ||
| tableInfoDAO.getDataSourceFormat() != null | ||
| && tableInfoDAO.getDataSourceFormat().equals(DataSourceFormat.DELTA.toString()), | ||
| "Only delta tables are supported for coordinated commits"); | ||
| if (tableInfoDAO.getUrl() == null) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What's the meaning of this table uri ? is it exactly the table location ?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes. That's the storage location of the table. |
||
| throw new BaseException( | ||
| ErrorCode.DATA_LOSS, "Managed table doesn't have a URI: " + tableInfoDAO.getId()); | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
|
|
||
| private static void validateTableForCommit(Commit commit, TableInfoDAO tableInfoDAO) { | ||
| validateTable(tableInfoDAO); | ||
| ValidationUtils.checkArgument( | ||
| FileOperations.toStandardizedURIString(commit.getTableUri()) | ||
| .equals(FileOperations.toStandardizedURIString(tableInfoDAO.getUrl())), | ||
| "Table URI in commit %s does not match the table path %s", | ||
| commit.getTableUri(), | ||
| tableInfoDAO.getUrl()); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| package io.unitycatalog.server.persist.dao; | ||
|
|
||
| import io.unitycatalog.server.model.CommitInfo; | ||
| import jakarta.persistence.Column; | ||
| import jakarta.persistence.Entity; | ||
| import jakarta.persistence.Id; | ||
| import jakarta.persistence.Table; | ||
| import jakarta.persistence.UniqueConstraint; | ||
| import java.util.Date; | ||
| import java.util.UUID; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Builder; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import lombok.Setter; | ||
| import org.hibernate.annotations.UuidGenerator; | ||
|
|
||
| @Entity | ||
| @Table( | ||
| name = "uc_commits", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldnt the table name have delta as well then!
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| uniqueConstraints = {@UniqueConstraint(columnNames = {"table_id", "commit_version"})}) | ||
| // Lombok | ||
| @Getter | ||
| @Setter | ||
| @Builder | ||
| @AllArgsConstructor | ||
| @NoArgsConstructor | ||
| public class DeltaCommitDAO { | ||
| // This id is never used to identify a commit. We only look for commits by table_id and | ||
| // optionally commit_version. But this is a required field as a unique ID in the database. | ||
| @Id | ||
| @UuidGenerator | ||
| @Column(name = "id", columnDefinition = "BINARY(16)") | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| private UUID id; | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
|
|
||
| @Column(name = "table_id", nullable = false, columnDefinition = "BINARY(16)") | ||
|
tdas marked this conversation as resolved.
Resolved
|
||
| private UUID tableId; | ||
|
|
||
| @Column(name = "commit_version", nullable = false) | ||
| private Long commitVersion; | ||
|
|
||
| @Column(name = "commit_filename", nullable = false) | ||
| private String commitFilename; | ||
|
|
||
| @Column(name = "commit_filesize", nullable = false) | ||
| private Long commitFilesize; | ||
|
|
||
| @Column(name = "commit_file_modification_timestamp", nullable = false) | ||
| private Date commitFileModificationTimestamp; | ||
|
|
||
| @Column(name = "commit_timestamp", nullable = false) | ||
| private Date commitTimestamp; | ||
|
|
||
| @Column(name = "is_backfilled_latest_commit", nullable = false) | ||
| private Boolean isBackfilledLatestCommit; | ||
|
|
||
| public static DeltaCommitDAO from(UUID tableId, CommitInfo commitInfo) { | ||
| return DeltaCommitDAO.builder() | ||
| .tableId(tableId) | ||
| .commitVersion(commitInfo.getVersion()) | ||
| .commitFilename(commitInfo.getFileName()) | ||
| .commitFilesize(commitInfo.getFileSize()) | ||
| .commitFileModificationTimestamp(new Date(commitInfo.getFileModificationTimestamp())) | ||
| .commitTimestamp(new Date(commitInfo.getTimestamp())) | ||
| .isBackfilledLatestCommit(false) | ||
| .build(); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What if there is only one record in the
TableInfoDao, then thefirstAndLastCommitsshould only have one record, which will produce a out of bound error , right ?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No. This query always returns two records (or empty list). If there's only one record, it returns that same record twice.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adding a comment here in the follow up PR: https://github.com/unitycatalog/unitycatalog/pull/1169/files/d0d4f606101bc705a6a79514a2b4ba31b2b19b19..93dc85893930d1594b3a974cc48228c767f826ab#diff-df349b58b0a893abbc64af5ae060645fdd0d5175308fefdc4ff7336a93d3dec1R365