Copilot commented on code in PR #11266: URL: https://github.com/apache/gravitino/pull/11266#discussion_r3322543119
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobStore.java: ########## @@ -0,0 +1,250 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.annotations.VisibleForTesting; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.Map; +import org.apache.gravitino.json.JsonUtils; +import org.apache.gravitino.storage.IdGenerator; +import org.apache.gravitino.storage.relational.utils.SessionUtils; + +/** + * Persistence for {@code iceberg_cleanup_job}, layered on the Gravitino entity store's shared + * relational backend. Async cleanup reuses the entity store's connection pool, transaction + * management, and per-backend SQL dispatch instead of opening its own JDBC connections. Row ids and + * timestamps are supplied by the application, keeping the SQL portable across H2, MySQL, and + * PostgreSQL. + */ +public class IcebergCleanupJobStore { + + private static final int MAX_ERROR_LENGTH = 2048; + + private final IdGenerator idGenerator; + + /** + * Creates a cleanup job store. + * + * @param idGenerator generator for new row ids + */ + public IcebergCleanupJobStore(IdGenerator idGenerator) { + this.idGenerator = idGenerator; + } + + /** + * Persists a new PENDING job. + * + * @param job job to persist + * @return generated id + */ + public long addJob(IcebergCleanupJob job) { + long id = idGenerator.nextId(); + long now = System.currentTimeMillis(); + IcebergCleanupJobPO po = toPO(job, id, now); + SessionUtils.doWithCommit(IcebergCleanupJobMapper.class, mapper -> mapper.insertCleanupJob(po)); + return id; + } + + /** + * Scans a small candidate window and takes the first available row via compare-and-swap. + * + * @param now current epoch millis, written as the initial heartbeat + * @param heartbeatTimeoutMs age past which a RUNNING heartbeat is stale + * @param window max candidates to consider + * @return the taken job, or {@code null} if nothing was available + */ + public IcebergCleanupJob takePendingJob(long now, long heartbeatTimeoutMs, int window) { + long heartbeatExpiry = now - heartbeatTimeoutMs; + List<Long> ids = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.selectCandidateJobIds(heartbeatExpiry, window)); + for (long id : ids) { + int marked = + SessionUtils.doWithCommitAndFetchResult( + IcebergCleanupJobMapper.class, + mapper -> mapper.markRunning(id, now, heartbeatExpiry)); + if (marked == 1) { + IcebergCleanupJobPO po = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, mapper -> mapper.selectById(id)); + return fromPO(po); + } + } + return null; + } + + /** + * Marks a RUNNING job SUCCEEDED. + * + * @param id job id + */ + public void markSucceeded(long id) { + long now = System.currentTimeMillis(); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.markFinished(id, IcebergCleanupJob.State.SUCCEEDED.name(), null, now)); + } + + /** + * Marks a RUNNING job FAILED immediately. + * + * @param id job id + * @param reason failure text + */ + public void markFailed(long id, String reason) { + long now = System.currentTimeMillis(); + String err = truncate(reason); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.markFinished(id, IcebergCleanupJob.State.FAILED.name(), err, now)); + } + + /** + * Records a transient failure: {@code attempts++}, then FAILED at the ceiling else PENDING. + * + * @param id job id + * @param reason failure text + * @param maxAttempts ceiling from config + */ + public void recordFailure(long id, String reason, int maxAttempts) { + long now = System.currentTimeMillis(); + String err = truncate(reason); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, mapper -> mapper.recordFailure(id, err, maxAttempts, now)); + } + + /** + * Refreshes a heartbeat with compare-and-swap ownership check. + * + * @param id job id + * @param lastHeartbeat previous heartbeat value + * @param now new heartbeat value + * @return {@code true} iff the row was still owned by the caller + */ + public boolean heartbeat(long id, long lastHeartbeat, long now) { + return SessionUtils.doWithCommitAndFetchResult( + IcebergCleanupJobMapper.class, mapper -> mapper.heartbeat(id, lastHeartbeat, now)) + == 1; + } + + /** + * Checks whether a PENDING or RUNNING job occupies the identifier. + * + * @param catalog catalog name + * @param namespace table namespace + * @param table table name + * @return true iff an active cleanup job exists for the identifier + */ + public boolean hasActiveJob(String catalog, String namespace, String table) { + Long id = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.selectActiveJobId(catalog, namespace, table)); + return id != null; Review Comment: `hasActiveJob`/`selectActiveJobId` are currently scoped only by (catalog, namespace, table) and ignore `metalake_name`, even though `iceberg_cleanup_job` rows include `metalake_name` and Gravitino catalog names are not globally unique across metalakes. This can cause false positives/negatives when multiple metalakes contain catalogs with the same name, and it can block or allow cleanup incorrectly. Consider threading `metalakeName` through `hasActiveJob(...)`, the mapper method, and the SQL predicate (and updating the supporting index) so the lookup is unambiguous. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobSQLProviderFactory.java: ########## @@ -0,0 +1,220 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import static org.apache.gravitino.iceberg.service.cleanup.IcebergCleanupJobMapper.TABLE_NAME; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.ibatis.annotations.Param; + +/** + * Supplies the SQL for {@link IcebergCleanupJobMapper}, dispatching by the entity store's + * configured JDBC backend. The statements are written with portable, parameterized SQL (the row id + * and all timestamps are generated by the application, not the database), so the {@link + * BaseProvider} serves MySQL, H2, and PostgreSQL alike. A backend that ever needs a divergent + * statement can be registered here by mapping its {@link JDBCBackendType} to a {@code BaseProvider} + * subclass that overrides only the affected methods. + */ +public class IcebergCleanupJobSQLProviderFactory { + + private static final BaseProvider BASE_PROVIDER = new BaseProvider(); + + private static final Map<JDBCBackendType, BaseProvider> PROVIDERS = + ImmutableMap.of( + JDBCBackendType.MYSQL, BASE_PROVIDER, + JDBCBackendType.H2, BASE_PROVIDER, + JDBCBackendType.POSTGRESQL, BASE_PROVIDER); + + private static BaseProvider getProvider() { + String databaseId = + SqlSessionFactoryHelper.getInstance() + .getSqlSessionFactory() + .getConfiguration() + .getDatabaseId(); + return PROVIDERS.get(JDBCBackendType.fromString(databaseId)); + } + + public static String insertCleanupJob(@Param("po") IcebergCleanupJobPO po) { + return getProvider().insertCleanupJob(po); + } + + public static String selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window) { + return getProvider().selectCandidateJobIds(heartbeatExpiry, window); + } + + public static String markRunning( + @Param("id") long id, + @Param("now") long now, + @Param("heartbeatExpiry") long heartbeatExpiry) { + return getProvider().markRunning(id, now, heartbeatExpiry); + } + + public static String selectById(@Param("id") long id) { + return getProvider().selectById(id); + } + + public static String markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now) { + return getProvider().markFinished(id, state, reason, now); + } + + public static String recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now) { + return getProvider().recordFailure(id, reason, maxAttempts, now); + } + + public static String heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now) { + return getProvider().heartbeat(id, lastHeartbeat, now); + } + + public static String selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table) { + return getProvider().selectActiveJobId(catalog, namespace, table); + } + + public static String deleteFinishedJobsByLegacyTimeline( + @Param("legacyTimeline") long legacyTimeline) { + return getProvider().deleteFinishedJobsByLegacyTimeline(legacyTimeline); + } + + public static String selectState(@Param("id") long id) { + return getProvider().selectState(id); + } + + /** Portable SQL shared by all supported JDBC backends. */ + static class BaseProvider { + + String insertCleanupJob(@Param("po") IcebergCleanupJobPO po) { + return "INSERT INTO " + + TABLE_NAME + + " (id, metalake_name, catalog_name, namespace, table_name, metadata_location," + + " file_io_impl, file_io_props, state, attempts, last_error, heartbeat_at, created_by," + + " updated_at) VALUES (#{po.id}, #{po.metalakeName}, #{po.catalogName}, #{po.namespace}," + + " #{po.tableName}, #{po.metadataLocation}, #{po.fileIOImpl}, #{po.fileIOProps}," + + " #{po.state}, #{po.attempts}, #{po.lastError}, #{po.heartbeatAt}, #{po.createdBy}," + + " #{po.updatedAt})"; + } + + String selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window) { + // A candidate row is PENDING, or RUNNING whose worker has gone silent. heartbeat_at is + // NOT NULL (it defaults to 0 and markRunning always writes the current time), so the + // staleness test is a plain comparison with no NULL branch and no three-valued-logic + // trap, which also keeps the predicate index-friendly. + return "SELECT id FROM " + + TABLE_NAME + + " WHERE state = 'PENDING'" + + " OR (state = 'RUNNING' AND heartbeat_at < #{heartbeatExpiry})" + + " ORDER BY updated_at LIMIT #{window}"; + } + + String markRunning( + @Param("id") long id, + @Param("now") long now, + @Param("heartbeatExpiry") long heartbeatExpiry) { + return "UPDATE " + + TABLE_NAME + + " SET state = 'RUNNING', heartbeat_at = #{now}, updated_at = #{now}" + + " WHERE id = #{id} AND (state = 'PENDING'" + + " OR (state = 'RUNNING' AND heartbeat_at < #{heartbeatExpiry}))"; + } + + String selectById(@Param("id") long id) { + return "SELECT id, metalake_name AS metalakeName, catalog_name AS catalogName, namespace," + + " table_name AS tableName, metadata_location AS metadataLocation," + + " file_io_impl AS fileIOImpl, file_io_props AS fileIOProps, state, attempts," + + " last_error AS lastError, heartbeat_at AS heartbeatAt, created_by AS createdBy," + + " updated_at AS updatedAt FROM " + + TABLE_NAME + + " WHERE id = #{id}"; + } + + String markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now) { + // Shared transition to a final state: SUCCEEDED (reason null) or FAILED (reason set). + return "UPDATE " + + TABLE_NAME + + " SET state = #{state}, last_error = #{reason}, heartbeat_at = 0," + + " updated_at = #{now} WHERE id = #{id} AND state = 'RUNNING'"; + } + + String recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now) { + // The state CASE must observe the pre-increment attempts value, so it MUST precede + // "attempts = attempts + 1" in the SET list. MySQL evaluates SET assignments left to + // right and later clauses see already-updated columns; if the increment came first the + // CASE would compare attempts + 2 and fail one attempt early. H2 and PostgreSQL evaluate + // every right-hand side against the original row, so state-first is correct there too, + // keeping this statement portable across all backends. + return "UPDATE " + + TABLE_NAME + + " SET state = CASE WHEN attempts + 1 >= #{maxAttempts} THEN 'FAILED' ELSE 'PENDING' END," + + " attempts = attempts + 1, last_error = #{reason}," + + " heartbeat_at = 0, updated_at = #{now} WHERE id = #{id} AND state = 'RUNNING'"; + } + + String heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now) { + return "UPDATE " + + TABLE_NAME + + " SET heartbeat_at = #{now}, updated_at = #{now}" + + " WHERE id = #{id} AND state = 'RUNNING' AND heartbeat_at = #{lastHeartbeat}"; + } + + String selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table) { + return "SELECT id FROM " + + TABLE_NAME + + " WHERE catalog_name = #{catalog} AND namespace = #{namespace}" + + " AND table_name = #{table} AND state IN ('PENDING', 'RUNNING') LIMIT 1"; + } Review Comment: This query does not filter by `metalake_name`, even though `iceberg_cleanup_job` includes it and catalog names are scoped by metalake in Gravitino. Without `metalake_name` in the predicate, workers can treat a job from a different metalake as an active job for this table name triple. Update the SQL (and mapper params) to include `metalake_name = #{metalake}` (or similar) and adjust the backing index accordingly. ########## scripts/postgresql/upgrade-1.2.0-to-1.3.0-postgresql.sql: ########## @@ -151,3 +151,22 @@ COMMENT ON COLUMN idp_user_group_rel.group_id IS 'idp group id'; COMMENT ON COLUMN idp_user_group_rel.current_version IS 'idp relation current version'; COMMENT ON COLUMN idp_user_group_rel.last_version IS 'idp relation last version'; COMMENT ON COLUMN idp_user_group_rel.deleted_at IS 'idp relation deleted at'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobMapper.java: ########## @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import java.util.List; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.SelectProvider; +import org.apache.ibatis.annotations.UpdateProvider; + +/** + * MyBatis mapper for the {@code iceberg_cleanup_job} table. SQL is supplied per backend by {@link + * IcebergCleanupJobSQLProviderFactory} and executed through the Gravitino entity store's shared + * {@code SqlSessionFactory}, so async cleanup reuses the relational backend's connection pool and + * multi-backend handling instead of opening its own JDBC connections. + */ +public interface IcebergCleanupJobMapper { + + String TABLE_NAME = "iceberg_cleanup_job"; + + @InsertProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "insertCleanupJob") + void insertCleanupJob(@Param("po") IcebergCleanupJobPO po); + + @SelectProvider( + type = IcebergCleanupJobSQLProviderFactory.class, + method = "selectCandidateJobIds") + List<Long> selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "markRunning") + int markRunning( + @Param("id") long id, @Param("now") long now, @Param("heartbeatExpiry") long heartbeatExpiry); + + @SelectProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "selectById") + IcebergCleanupJobPO selectById(@Param("id") long id); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "markFinished") + int markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "recordFailure") + int recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "heartbeat") + int heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now); + + @SelectProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "selectActiveJobId") + Long selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table); Review Comment: `selectActiveJobId` is missing a `metalake` parameter even though the table stores `metalake_name` and catalog names are scoped by metalake in Gravitino. This makes the API ambiguous and can cause cross-metalake collisions. Add a `@Param("metalake") String metalake` (or `metalakeName`) parameter and include it in the SQL predicate. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobStore.java: ########## @@ -0,0 +1,250 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.annotations.VisibleForTesting; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.Map; +import org.apache.gravitino.json.JsonUtils; +import org.apache.gravitino.storage.IdGenerator; +import org.apache.gravitino.storage.relational.utils.SessionUtils; + +/** + * Persistence for {@code iceberg_cleanup_job}, layered on the Gravitino entity store's shared + * relational backend. Async cleanup reuses the entity store's connection pool, transaction + * management, and per-backend SQL dispatch instead of opening its own JDBC connections. Row ids and + * timestamps are supplied by the application, keeping the SQL portable across H2, MySQL, and + * PostgreSQL. + */ +public class IcebergCleanupJobStore { + + private static final int MAX_ERROR_LENGTH = 2048; + + private final IdGenerator idGenerator; + + /** + * Creates a cleanup job store. + * + * @param idGenerator generator for new row ids + */ + public IcebergCleanupJobStore(IdGenerator idGenerator) { + this.idGenerator = idGenerator; + } + + /** + * Persists a new PENDING job. + * + * @param job job to persist + * @return generated id + */ + public long addJob(IcebergCleanupJob job) { + long id = idGenerator.nextId(); + long now = System.currentTimeMillis(); + IcebergCleanupJobPO po = toPO(job, id, now); + SessionUtils.doWithCommit(IcebergCleanupJobMapper.class, mapper -> mapper.insertCleanupJob(po)); + return id; + } + + /** + * Scans a small candidate window and takes the first available row via compare-and-swap. + * + * @param now current epoch millis, written as the initial heartbeat + * @param heartbeatTimeoutMs age past which a RUNNING heartbeat is stale + * @param window max candidates to consider + * @return the taken job, or {@code null} if nothing was available + */ + public IcebergCleanupJob takePendingJob(long now, long heartbeatTimeoutMs, int window) { + long heartbeatExpiry = now - heartbeatTimeoutMs; + List<Long> ids = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.selectCandidateJobIds(heartbeatExpiry, window)); + for (long id : ids) { + int marked = + SessionUtils.doWithCommitAndFetchResult( + IcebergCleanupJobMapper.class, + mapper -> mapper.markRunning(id, now, heartbeatExpiry)); + if (marked == 1) { + IcebergCleanupJobPO po = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, mapper -> mapper.selectById(id)); + return fromPO(po); + } + } + return null; + } + + /** + * Marks a RUNNING job SUCCEEDED. + * + * @param id job id + */ + public void markSucceeded(long id) { + long now = System.currentTimeMillis(); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.markFinished(id, IcebergCleanupJob.State.SUCCEEDED.name(), null, now)); + } + + /** + * Marks a RUNNING job FAILED immediately. + * + * @param id job id + * @param reason failure text + */ + public void markFailed(long id, String reason) { + long now = System.currentTimeMillis(); + String err = truncate(reason); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.markFinished(id, IcebergCleanupJob.State.FAILED.name(), err, now)); + } + + /** + * Records a transient failure: {@code attempts++}, then FAILED at the ceiling else PENDING. + * + * @param id job id + * @param reason failure text + * @param maxAttempts ceiling from config + */ + public void recordFailure(long id, String reason, int maxAttempts) { + long now = System.currentTimeMillis(); + String err = truncate(reason); + SessionUtils.doWithCommit( + IcebergCleanupJobMapper.class, mapper -> mapper.recordFailure(id, err, maxAttempts, now)); + } + + /** + * Refreshes a heartbeat with compare-and-swap ownership check. + * + * @param id job id + * @param lastHeartbeat previous heartbeat value + * @param now new heartbeat value + * @return {@code true} iff the row was still owned by the caller + */ + public boolean heartbeat(long id, long lastHeartbeat, long now) { + return SessionUtils.doWithCommitAndFetchResult( + IcebergCleanupJobMapper.class, mapper -> mapper.heartbeat(id, lastHeartbeat, now)) + == 1; + } + + /** + * Checks whether a PENDING or RUNNING job occupies the identifier. + * + * @param catalog catalog name + * @param namespace table namespace + * @param table table name + * @return true iff an active cleanup job exists for the identifier + */ + public boolean hasActiveJob(String catalog, String namespace, String table) { + Long id = + SessionUtils.getWithoutCommit( + IcebergCleanupJobMapper.class, + mapper -> mapper.selectActiveJobId(catalog, namespace, table)); + return id != null; Review Comment: `hasActiveJob`/`selectActiveJobId` are currently scoped only by (catalog, namespace, table) and ignore `metalake_name`, even though `iceberg_cleanup_job` rows include `metalake_name` and Gravitino catalog names are not globally unique across metalakes. This can cause false positives/negatives when multiple metalakes contain catalogs with the same name, and it can block or allow cleanup incorrectly. Consider threading `metalakeName` through `hasActiveJob(...)`, the mapper method, and the SQL predicate (and updating the supporting index) so the lookup is unambiguous. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobMapper.java: ########## @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import java.util.List; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.SelectProvider; +import org.apache.ibatis.annotations.UpdateProvider; + +/** + * MyBatis mapper for the {@code iceberg_cleanup_job} table. SQL is supplied per backend by {@link + * IcebergCleanupJobSQLProviderFactory} and executed through the Gravitino entity store's shared + * {@code SqlSessionFactory}, so async cleanup reuses the relational backend's connection pool and + * multi-backend handling instead of opening its own JDBC connections. + */ +public interface IcebergCleanupJobMapper { + + String TABLE_NAME = "iceberg_cleanup_job"; + + @InsertProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "insertCleanupJob") + void insertCleanupJob(@Param("po") IcebergCleanupJobPO po); + + @SelectProvider( + type = IcebergCleanupJobSQLProviderFactory.class, + method = "selectCandidateJobIds") + List<Long> selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "markRunning") + int markRunning( + @Param("id") long id, @Param("now") long now, @Param("heartbeatExpiry") long heartbeatExpiry); + + @SelectProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "selectById") + IcebergCleanupJobPO selectById(@Param("id") long id); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "markFinished") + int markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "recordFailure") + int recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now); + + @UpdateProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "heartbeat") + int heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now); + + @SelectProvider(type = IcebergCleanupJobSQLProviderFactory.class, method = "selectActiveJobId") + Long selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table); Review Comment: `selectActiveJobId` is missing a `metalake` parameter even though the table stores `metalake_name` and catalog names are scoped by metalake in Gravitino. This makes the API ambiguous and can cause cross-metalake collisions. Add a `@Param("metalake") String metalake` (or `metalakeName`) parameter and include it in the SQL predicate. ########## scripts/h2/schema-1.3.0-h2.sql: ########## @@ -612,3 +612,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB COMMENT='Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/mysql/upgrade-1.2.0-to-1.3.0-mysql.sql: ########## @@ -118,3 +118,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'local IdP user group relation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/mysql/schema-1.3.0-mysql.sql: ########## @@ -599,3 +599,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/mysql/upgrade-1.2.0-to-1.3.0-mysql.sql: ########## @@ -118,3 +118,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'local IdP user group relation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/postgresql/schema-1.3.0-postgresql.sql: ########## @@ -1054,3 +1054,22 @@ COMMENT ON COLUMN entity_change_log.entity_type IS 'METALAKE | CATALOG | SCHEMA COMMENT ON COLUMN entity_change_log.entity_full_name IS 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.'; COMMENT ON COLUMN entity_change_log.operate_type IS 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.'; COMMENT ON COLUMN entity_change_log.created_at IS 'timestamp of the change in millis'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/mysql/upgrade-1.2.0-to-1.3.0-mysql.sql: ########## @@ -118,3 +118,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'local IdP user group relation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/h2/schema-1.3.0-h2.sql: ########## @@ -612,3 +612,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB COMMENT='Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/mysql/schema-1.3.0-mysql.sql: ########## @@ -599,3 +599,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/h2/upgrade-1.2.0-to-1.3.0-h2.sql: ########## @@ -100,3 +100,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/h2/upgrade-1.2.0-to-1.3.0-h2.sql: ########## @@ -100,3 +100,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/postgresql/upgrade-1.2.0-to-1.3.0-postgresql.sql: ########## @@ -151,3 +151,22 @@ COMMENT ON COLUMN idp_user_group_rel.group_id IS 'idp group id'; COMMENT ON COLUMN idp_user_group_rel.current_version IS 'idp relation current version'; COMMENT ON COLUMN idp_user_group_rel.last_version IS 'idp relation last version'; COMMENT ON COLUMN idp_user_group_rel.deleted_at IS 'idp relation deleted at'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupJobSQLProviderFactory.java: ########## @@ -0,0 +1,220 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.cleanup; + +import static org.apache.gravitino.iceberg.service.cleanup.IcebergCleanupJobMapper.TABLE_NAME; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.ibatis.annotations.Param; + +/** + * Supplies the SQL for {@link IcebergCleanupJobMapper}, dispatching by the entity store's + * configured JDBC backend. The statements are written with portable, parameterized SQL (the row id + * and all timestamps are generated by the application, not the database), so the {@link + * BaseProvider} serves MySQL, H2, and PostgreSQL alike. A backend that ever needs a divergent + * statement can be registered here by mapping its {@link JDBCBackendType} to a {@code BaseProvider} + * subclass that overrides only the affected methods. + */ +public class IcebergCleanupJobSQLProviderFactory { + + private static final BaseProvider BASE_PROVIDER = new BaseProvider(); + + private static final Map<JDBCBackendType, BaseProvider> PROVIDERS = + ImmutableMap.of( + JDBCBackendType.MYSQL, BASE_PROVIDER, + JDBCBackendType.H2, BASE_PROVIDER, + JDBCBackendType.POSTGRESQL, BASE_PROVIDER); + + private static BaseProvider getProvider() { + String databaseId = + SqlSessionFactoryHelper.getInstance() + .getSqlSessionFactory() + .getConfiguration() + .getDatabaseId(); + return PROVIDERS.get(JDBCBackendType.fromString(databaseId)); + } + + public static String insertCleanupJob(@Param("po") IcebergCleanupJobPO po) { + return getProvider().insertCleanupJob(po); + } + + public static String selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window) { + return getProvider().selectCandidateJobIds(heartbeatExpiry, window); + } + + public static String markRunning( + @Param("id") long id, + @Param("now") long now, + @Param("heartbeatExpiry") long heartbeatExpiry) { + return getProvider().markRunning(id, now, heartbeatExpiry); + } + + public static String selectById(@Param("id") long id) { + return getProvider().selectById(id); + } + + public static String markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now) { + return getProvider().markFinished(id, state, reason, now); + } + + public static String recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now) { + return getProvider().recordFailure(id, reason, maxAttempts, now); + } + + public static String heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now) { + return getProvider().heartbeat(id, lastHeartbeat, now); + } + + public static String selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table) { + return getProvider().selectActiveJobId(catalog, namespace, table); + } + + public static String deleteFinishedJobsByLegacyTimeline( + @Param("legacyTimeline") long legacyTimeline) { + return getProvider().deleteFinishedJobsByLegacyTimeline(legacyTimeline); + } + + public static String selectState(@Param("id") long id) { + return getProvider().selectState(id); + } + + /** Portable SQL shared by all supported JDBC backends. */ + static class BaseProvider { + + String insertCleanupJob(@Param("po") IcebergCleanupJobPO po) { + return "INSERT INTO " + + TABLE_NAME + + " (id, metalake_name, catalog_name, namespace, table_name, metadata_location," + + " file_io_impl, file_io_props, state, attempts, last_error, heartbeat_at, created_by," + + " updated_at) VALUES (#{po.id}, #{po.metalakeName}, #{po.catalogName}, #{po.namespace}," + + " #{po.tableName}, #{po.metadataLocation}, #{po.fileIOImpl}, #{po.fileIOProps}," + + " #{po.state}, #{po.attempts}, #{po.lastError}, #{po.heartbeatAt}, #{po.createdBy}," + + " #{po.updatedAt})"; + } + + String selectCandidateJobIds( + @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window) { + // A candidate row is PENDING, or RUNNING whose worker has gone silent. heartbeat_at is + // NOT NULL (it defaults to 0 and markRunning always writes the current time), so the + // staleness test is a plain comparison with no NULL branch and no three-valued-logic + // trap, which also keeps the predicate index-friendly. + return "SELECT id FROM " + + TABLE_NAME + + " WHERE state = 'PENDING'" + + " OR (state = 'RUNNING' AND heartbeat_at < #{heartbeatExpiry})" + + " ORDER BY updated_at LIMIT #{window}"; + } + + String markRunning( + @Param("id") long id, + @Param("now") long now, + @Param("heartbeatExpiry") long heartbeatExpiry) { + return "UPDATE " + + TABLE_NAME + + " SET state = 'RUNNING', heartbeat_at = #{now}, updated_at = #{now}" + + " WHERE id = #{id} AND (state = 'PENDING'" + + " OR (state = 'RUNNING' AND heartbeat_at < #{heartbeatExpiry}))"; + } + + String selectById(@Param("id") long id) { + return "SELECT id, metalake_name AS metalakeName, catalog_name AS catalogName, namespace," + + " table_name AS tableName, metadata_location AS metadataLocation," + + " file_io_impl AS fileIOImpl, file_io_props AS fileIOProps, state, attempts," + + " last_error AS lastError, heartbeat_at AS heartbeatAt, created_by AS createdBy," + + " updated_at AS updatedAt FROM " + + TABLE_NAME + + " WHERE id = #{id}"; + } + + String markFinished( + @Param("id") long id, + @Param("state") String state, + @Param("reason") String reason, + @Param("now") long now) { + // Shared transition to a final state: SUCCEEDED (reason null) or FAILED (reason set). + return "UPDATE " + + TABLE_NAME + + " SET state = #{state}, last_error = #{reason}, heartbeat_at = 0," + + " updated_at = #{now} WHERE id = #{id} AND state = 'RUNNING'"; + } + + String recordFailure( + @Param("id") long id, + @Param("reason") String reason, + @Param("maxAttempts") int maxAttempts, + @Param("now") long now) { + // The state CASE must observe the pre-increment attempts value, so it MUST precede + // "attempts = attempts + 1" in the SET list. MySQL evaluates SET assignments left to + // right and later clauses see already-updated columns; if the increment came first the + // CASE would compare attempts + 2 and fail one attempt early. H2 and PostgreSQL evaluate + // every right-hand side against the original row, so state-first is correct there too, + // keeping this statement portable across all backends. + return "UPDATE " + + TABLE_NAME + + " SET state = CASE WHEN attempts + 1 >= #{maxAttempts} THEN 'FAILED' ELSE 'PENDING' END," + + " attempts = attempts + 1, last_error = #{reason}," + + " heartbeat_at = 0, updated_at = #{now} WHERE id = #{id} AND state = 'RUNNING'"; + } + + String heartbeat( + @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now) { + return "UPDATE " + + TABLE_NAME + + " SET heartbeat_at = #{now}, updated_at = #{now}" + + " WHERE id = #{id} AND state = 'RUNNING' AND heartbeat_at = #{lastHeartbeat}"; + } + + String selectActiveJobId( + @Param("catalog") String catalog, + @Param("namespace") String namespace, + @Param("table") String table) { + return "SELECT id FROM " + + TABLE_NAME + + " WHERE catalog_name = #{catalog} AND namespace = #{namespace}" + + " AND table_name = #{table} AND state IN ('PENDING', 'RUNNING') LIMIT 1"; + } Review Comment: This query does not filter by `metalake_name`, even though `iceberg_cleanup_job` includes it and catalog names are scoped by metalake in Gravitino. Without `metalake_name` in the predicate, workers can treat a job from a different metalake as an active job for this table name triple. Update the SQL (and mapper params) to include `metalake_name = #{metalake}` (or similar) and adjust the backing index accordingly. ########## scripts/mysql/schema-1.3.0-mysql.sql: ########## @@ -599,3 +599,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT(20) UNSIGNED NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` MEDIUMTEXT NOT NULL COMMENT 'JSON', + `state` VARCHAR(16) NOT NULL COMMENT 'PENDING|RUNNING|SUCCEEDED|FAILED', + `attempts` INT(10) NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL COMMENT 'truncated reason for the most recent failure, NULL until a job fails', + `heartbeat_at` BIGINT(20) NOT NULL DEFAULT 0 COMMENT 'last heartbeat from the worker, 0 when not running', + `created_by` VARCHAR(128) NOT NULL COMMENT 'principal that requested the drop (audit)', + `updated_at` BIGINT(20) NOT NULL COMMENT 'last state change, drives poll ordering and old finished-job cleanup', + PRIMARY KEY (`id`), + KEY `idx_state_updated` (`state`, `updated_at`), + KEY `idx_object` (`catalog_name`, `namespace`(255), `table_name`(255), `state`) Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/postgresql/schema-1.3.0-postgresql.sql: ########## @@ -1054,3 +1054,22 @@ COMMENT ON COLUMN entity_change_log.entity_type IS 'METALAKE | CATALOG | SCHEMA COMMENT ON COLUMN entity_change_log.entity_full_name IS 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.'; COMMENT ON COLUMN entity_change_log.operate_type IS 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.'; COMMENT ON COLUMN entity_change_log.created_at IS 'timestamp of the change in millis'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/postgresql/schema-1.3.0-postgresql.sql: ########## @@ -1054,3 +1054,22 @@ COMMENT ON COLUMN entity_change_log.entity_type IS 'METALAKE | CATALOG | SCHEMA COMMENT ON COLUMN entity_change_log.entity_full_name IS 'Dot-separated full name of the affected entity. For ALTER, stores the old name. For DROP, stores the entity name.'; COMMENT ON COLUMN entity_change_log.operate_type IS 'Operate type code: 1=ALTER, 2=DROP, 3=INSERT. Codes are stable and never re-used.'; COMMENT ON COLUMN entity_change_log.created_at IS 'timestamp of the change in millis'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/h2/schema-1.3.0-h2.sql: ########## @@ -612,3 +612,23 @@ CREATE TABLE IF NOT EXISTS `entity_change_log` ( PRIMARY KEY (`id`), KEY `idx_ecl_created_at` (`created_at`) ) ENGINE=InnoDB COMMENT='Append-only log of entity structural changes for targeted metadataIdCache invalidation'; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/h2/upgrade-1.2.0-to-1.3.0-h2.sql: ########## @@ -100,3 +100,23 @@ CREATE TABLE IF NOT EXISTS `idp_user_group_rel` ( KEY `idx_iuig_uid` (`user_id`), KEY `idx_iuig_gid` (`group_id`) ) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `iceberg_cleanup_job` ( + `id` BIGINT NOT NULL, + `metalake_name` VARCHAR(128) NOT NULL, + `catalog_name` VARCHAR(128) NOT NULL, + `namespace` VARCHAR(512) NOT NULL, + `table_name` VARCHAR(256) NOT NULL, + `metadata_location` VARCHAR(1024) NOT NULL, + `file_io_impl` VARCHAR(256) NOT NULL, + `file_io_props` CLOB NOT NULL, + `state` VARCHAR(16) NOT NULL, + `attempts` INT NOT NULL DEFAULT 0, + `last_error` VARCHAR(2048) NULL, + `heartbeat_at` BIGINT NOT NULL DEFAULT 0, + `created_by` VARCHAR(128) NOT NULL, + `updated_at` BIGINT NOT NULL, + PRIMARY KEY (`id`) +); +CREATE INDEX IF NOT EXISTS `idx_state_updated` ON `iceberg_cleanup_job` (`state`, `updated_at`); +CREATE INDEX IF NOT EXISTS `idx_object` ON `iceberg_cleanup_job` (`catalog_name`, `namespace`, `table_name`, `state`); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. ########## scripts/postgresql/upgrade-1.2.0-to-1.3.0-postgresql.sql: ########## @@ -151,3 +151,22 @@ COMMENT ON COLUMN idp_user_group_rel.group_id IS 'idp group id'; COMMENT ON COLUMN idp_user_group_rel.current_version IS 'idp relation current version'; COMMENT ON COLUMN idp_user_group_rel.last_version IS 'idp relation last version'; COMMENT ON COLUMN idp_user_group_rel.deleted_at IS 'idp relation deleted at'; + +CREATE TABLE IF NOT EXISTS iceberg_cleanup_job ( + id BIGINT NOT NULL PRIMARY KEY, + metalake_name VARCHAR(128) NOT NULL, + catalog_name VARCHAR(128) NOT NULL, + namespace VARCHAR(512) NOT NULL, + table_name VARCHAR(256) NOT NULL, + metadata_location VARCHAR(1024) NOT NULL, + file_io_impl VARCHAR(256) NOT NULL, + file_io_props TEXT NOT NULL, + state VARCHAR(16) NOT NULL, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(2048), + heartbeat_at BIGINT NOT NULL DEFAULT 0, + created_by VARCHAR(128) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_state_updated ON iceberg_cleanup_job (state, updated_at); +CREATE INDEX IF NOT EXISTS idx_object ON iceberg_cleanup_job (catalog_name, namespace, table_name, state); Review Comment: `idx_object` does not include `metalake_name`, but `iceberg_cleanup_job` rows are metalake-scoped. Without `metalake_name` in the index (and query predicate), lookups by (catalog, namespace, table, state) can collide across metalakes and the index won’t support the correct access pattern once metalake filtering is added. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
