Skip to content
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 @@ -30,6 +30,7 @@
import io.unitycatalog.server.service.AuthService;
import io.unitycatalog.server.service.CatalogService;
import io.unitycatalog.server.service.CredentialService;
import io.unitycatalog.server.service.DeltaCommitsService;
import io.unitycatalog.server.service.ExternalLocationService;
import io.unitycatalog.server.service.FunctionService;
import io.unitycatalog.server.service.IcebergRestCatalogService;
Expand Down Expand Up @@ -185,6 +186,7 @@ private void addApiServices(
CredentialService credentialService = new CredentialService(authorizer, repositories);
ExternalLocationService externalLocationService =
new ExternalLocationService(authorizer, repositories);
DeltaCommitsService deltaCommitsService = new DeltaCommitsService(authorizer, repositories);
MetastoreService metastoreService = new MetastoreService(repositories);
// TODO: combine these into a single service in a follow-up PR
TemporaryTableCredentialsService temporaryTableCredentialsService =
Expand Down Expand Up @@ -248,6 +250,8 @@ private void addApiServices(
temporaryPathCredentialsService,
requestConverterFunction)
.annotatedService(BASE_PATH + "credentials", credentialService, requestConverterFunction)
.annotatedService(
BASE_PATH + "delta/preview/commits", deltaCommitsService, requestConverterFunction)
.annotatedService(
BASE_PATH + "external-locations", externalLocationService, requestConverterFunction);
addIcebergApiServices(
Expand Down
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);

Copy link
Copy Markdown
Collaborator

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 the firstAndLastCommits should only have one record, which will produce a out of bound error , right ?

@yili-db yili-db Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator Author

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.

@yili-db yili-db Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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(
Comment thread
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(
Comment thread
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");
Comment thread
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())) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Just curious: so if it requires the ucTableId of the commit properties is exactly matching the commit.getTableId() , then why do we need to set both id ? For me, it's good enough to set one of the id, then use the id in all of the places. It seems unlikely be buggy, since we unified the same field in a single field.

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.

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.

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.

please right this down as a comment. important information.
i think every question in a review that ask contextual information should be a recipe for a comment.

@yili-db yili-db Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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 ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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());
Comment thread
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
Expand Up @@ -25,6 +25,7 @@ public class Repositories {
private final ModelRepository modelRepository;
private final CredentialRepository credentialRepository;
private final ExternalLocationRepository externalLocationRepository;
private final DeltaCommitRepository deltaCommitRepository;

public Repositories(SessionFactory sessionFactory, ServerProperties serverProperties) {
this.sessionFactory = sessionFactory;
Expand All @@ -42,5 +43,6 @@ public Repositories(SessionFactory sessionFactory, ServerProperties serverProper
this.modelRepository = new ModelRepository(this, sessionFactory);
this.credentialRepository = new CredentialRepository(this, sessionFactory);
this.externalLocationRepository = new ExternalLocationRepository(this, sessionFactory);
this.deltaCommitRepository = new DeltaCommitRepository(sessionFactory, serverProperties);
}
}
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",

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.

shouldnt the table name have delta as well then!

@yili-db yili-db Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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)")
Comment thread
tdas marked this conversation as resolved.
Resolved
private UUID id;
Comment thread
tdas marked this conversation as resolved.
Resolved

@Column(name = "table_id", nullable = false, columnDefinition = "BINARY(16)")
Comment thread
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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.unitycatalog.server.persist.dao.CatalogInfoDAO;
import io.unitycatalog.server.persist.dao.ColumnInfoDAO;
import io.unitycatalog.server.persist.dao.CredentialDAO;
import io.unitycatalog.server.persist.dao.DeltaCommitDAO;
import io.unitycatalog.server.persist.dao.ExternalLocationDAO;
import io.unitycatalog.server.persist.dao.FunctionInfoDAO;
import io.unitycatalog.server.persist.dao.FunctionParameterInfoDAO;
Expand Down Expand Up @@ -69,6 +70,7 @@ private static SessionFactory createSessionFactory(Properties hibernatePropertie
configuration.addAnnotatedClass(MetastoreDAO.class);
configuration.addAnnotatedClass(CredentialDAO.class);
configuration.addAnnotatedClass(ExternalLocationDAO.class);
configuration.addAnnotatedClass(DeltaCommitDAO.class);

ServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
Expand Down
Loading