You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by zh...@apache.org on 2026/02/10 01:51:34 UTC
(seatunnel) branch dev updated: [Improve][Flink]supports multiple parallelisms and remove flink-specific logic from API (#10107)
This is an automated email from the ASF dual-hosted git repository.
zhouyao2023 pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new 89b3e1ce1c [Improve][Flink]supports multiple parallelisms and remove flink-specific logic from API (#10107)
89b3e1ce1c is described below
commit 89b3e1ce1c21f773fd8214fbce11f78a0e76ae0e
Author: cloverdew <cl...@gmail.com>
AuthorDate: Tue Feb 10 09:51:29 2026 +0800
[Improve][Flink]supports multiple parallelisms and remove flink-specific logic from API (#10107)
---
.../org/apache/seatunnel/api/event/EventType.java | 3 +-
.../api/sink/SupportSchemaEvolutionSinkWriter.java | 46 --
.../sink/multitablesink/MultiTableSinkWriter.java | 21 -
.../multitablesink/MultiTableWriterRunnable.java | 8 +
.../api/table/coordinator/SchemaCoordinator.java | 329 --------
.../api/table/coordinator/SchemaResponse.java | 53 --
.../api/table/schema/event/FlushEvent.java | 63 --
.../exception/SchemaCoordinationException.java | 9 -
.../schema/exception/SchemaEvolutionErrorCode.java | 32 +-
.../schema/exception/SchemaEvolutionException.java | 5 +-
.../exception/SchemaValidationException.java | 30 +-
.../exception/SinkWriterSchemaException.java | 33 +-
.../seatunnel/console/sink/ConsoleSinkWriter.java | 39 +-
.../jdbc/sink/JdbcExactlyOnceSinkWriter.java | 42 +-
.../seatunnel/jdbc/sink/JdbcSinkWriter.java | 38 +-
.../flink/execution/SinkExecuteProcessor.java | 25 +-
.../flink/execution/SinkExecuteProcessor.java | 23 +-
.../starter/flink/execution/SchemaOperator.java | 283 -------
.../flink/execution/SinkExecuteProcessor.java | 23 +-
.../flink/execution/SourceExecuteProcessor.java | 20 +-
.../cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java | 4 +-
.../src/test/resources/ddl/initial.sql | 60 --
.../translation/flink/sink/FlinkSinkWriter.java | 147 ++--
.../flink/schema/BroadcastSchemaSinkOperator.java | 222 ++++++
.../translation/flink/schema/SchemaOperator.java | 827 +++++++++++++++++++++
.../schema/coordinator/LocalSchemaCoordinator.java | 371 +++++++++
.../schema/coordinator/SinkStateProvider.java | 31 +-
.../translation/flink/sink/FlinkSinkWriter.java | 163 ++--
28 files changed, 1748 insertions(+), 1202 deletions(-)
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java
index 3272f65419..d7bd8eeac0 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java
@@ -30,6 +30,5 @@ public enum EventType {
LIFECYCLE_READER_CLOSE,
LIFECYCLE_WRITER_CLOSE,
READER_MESSAGE_DELAYED,
- JOB_STATUS,
- SCHEMA_CHANGE_FLUSH,
+ JOB_STATUS
}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SupportSchemaEvolutionSinkWriter.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SupportSchemaEvolutionSinkWriter.java
index 47c3839465..54727ec950 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SupportSchemaEvolutionSinkWriter.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SupportSchemaEvolutionSinkWriter.java
@@ -17,8 +17,6 @@
package org.apache.seatunnel.api.sink;
-import org.apache.seatunnel.api.table.coordinator.SchemaCoordinator;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
import java.io.IOException;
@@ -32,48 +30,4 @@ public interface SupportSchemaEvolutionSinkWriter {
* @throws IOException
*/
void applySchemaChange(SchemaChangeEvent event) throws IOException;
-
- /**
- * handle FlushEvent propagated from upstream
- *
- * @param event
- * @throws IOException
- */
- default void handleFlushEvent(FlushEvent event) throws IOException {
- flushData();
- sendFlushSuccessful(event);
- }
-
- /**
- * send success event to coordinator upon successful flash
- *
- * @param event
- * @throws IOException
- */
- default void sendFlushSuccessful(FlushEvent event) throws IOException {
- SchemaCoordinator coordinator = getSchemaCoordinator();
- if (coordinator == null && event != null && event.getJobId() != null) {
- coordinator = SchemaCoordinator.getOrCreateInstance(event.getJobId());
- }
-
- if (coordinator != null) {
- coordinator.notifyFlushSuccessful(event.getJobId(), event.tableIdentifier());
- }
- }
-
- /**
- * Get the schema coordinator instance for reporting flush completion
- *
- * @return the schema coordinator instance, or null if not available
- */
- default SchemaCoordinator getSchemaCoordinator() {
- return null;
- }
-
- /**
- * flush data to other system
- *
- * @throws IOException
- */
- default void flushData() throws IOException {}
}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
index 3721491ea9..706b7c0bf0 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
@@ -21,7 +21,6 @@ import org.apache.seatunnel.api.sink.MultiTableResourceManager;
import org.apache.seatunnel.api.sink.SinkWriter;
import org.apache.seatunnel.api.sink.SupportMultiTableSinkWriter;
import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSinkWriter;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.tracing.MDCTracer;
@@ -176,26 +175,6 @@ public class MultiTableSinkWriter
}
}
- @Override
- public void handleFlushEvent(FlushEvent event) throws IOException {
- subSinkErrorCheck();
- String targetTableId = event.tableIdentifier().toTablePath().getFullName();
- for (int i = 0; i < sinkWritersWithIndex.size(); i++) {
- for (Map.Entry<SinkIdentifier, SinkWriter<SeaTunnelRow, ?, ?>> sinkWriterEntry :
- sinkWritersWithIndex.get(i).entrySet()) {
- if (sinkWriterEntry.getKey().getTableIdentifier().equals(targetTableId)) {
- synchronized (runnable.get(i)) {
- SinkWriter<SeaTunnelRow, ?, ?> sink = sinkWriterEntry.getValue();
- if (sink instanceof SupportSchemaEvolutionSinkWriter) {
- ((SupportSchemaEvolutionSinkWriter) sink).handleFlushEvent(event);
- }
- }
- return;
- }
- }
- }
- }
-
@Override
public void write(SeaTunnelRow element) throws IOException {
if (element != null && element.getOptions() != null) {
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableWriterRunnable.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableWriterRunnable.java
index a715280c1f..cbb0ff0801 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableWriterRunnable.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableWriterRunnable.java
@@ -50,6 +50,14 @@ public class MultiTableWriterRunnable implements Runnable {
if (row == null) {
continue;
}
+ // control rows used for schema evolution / coordination
+ // are represented as SeaTunnelRow with zero fields (arity == 0)
+ if (row.getArity() == 0) {
+ log.debug(
+ "Skip control SeaTunnelRow with zero arity in MultiTableWriterRunnable: {}",
+ row);
+ continue;
+ }
SinkWriter<SeaTunnelRow, ?, ?> writer = tableIdWriterMap.get(row.getTableId());
if (writer == null) {
if (tableIdWriterMap.size() == 1) {
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaCoordinator.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaCoordinator.java
deleted file mode 100644
index 5b2b54d80e..0000000000
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaCoordinator.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * 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.seatunnel.api.table.coordinator;
-
-import org.apache.seatunnel.api.table.catalog.CatalogTable;
-import org.apache.seatunnel.api.table.catalog.TableIdentifier;
-import org.apache.seatunnel.api.table.schema.exception.SchemaCoordinationException;
-import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
-import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
-
-import lombok.Getter;
-import lombok.Setter;
-import lombok.ToString;
-import lombok.extern.slf4j.Slf4j;
-
-import java.io.Serializable;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.ReentrantLock;
-
-/** global unified coordinator for handling schema changes */
-@Slf4j
-public class SchemaCoordinator implements Serializable {
-
- private static final Map<String, SchemaCoordinator> JOB_COORDINATORS =
- new ConcurrentHashMap<>();
- private final Map<TableIdentifier, SchemaChangeState> schemaChangeStates;
- private final Map<TableIdentifier, Long> schemaVersions;
- private final Map<TableIdentifier, ReentrantLock> schemaLocks;
- private final Map<TableIdentifier, Map<String, CompletableFuture<SchemaResponse>>>
- pendingRequests;
- private final Map<TableIdentifier, Long> latestSchemaChangeTime = new ConcurrentHashMap<>();
-
- public SchemaCoordinator() {
- this.schemaChangeStates = new ConcurrentHashMap<>();
- this.schemaVersions = new ConcurrentHashMap<>();
- this.schemaLocks = new ConcurrentHashMap<>();
- this.pendingRequests = new ConcurrentHashMap<>();
- }
-
- public static SchemaCoordinator getOrCreateInstance(String jobId) {
- return JOB_COORDINATORS.computeIfAbsent(
- jobId,
- k -> {
- log.info("Creating new SchemaCoordinator instance for job: {}", jobId);
- return new SchemaCoordinator();
- });
- }
-
- public static void removeInstance(String jobId) {
- SchemaCoordinator removed = JOB_COORDINATORS.remove(jobId);
- if (removed != null) {
- log.info("Removed SchemaCoordinator instance for job: {}", jobId);
- }
- }
-
- public void notifyFlushSuccessful(String jobId, TableIdentifier tableId) {
- log.info("Received flush notification: jobId={}, tableId={}", jobId, tableId);
-
- ReentrantLock lock = schemaLocks.computeIfAbsent(tableId, k -> new ReentrantLock());
- lock.lock();
- try {
- SchemaChangeState state = schemaChangeStates.get(tableId);
- if (state == null) {
- log.warn("No schema change state found for table: {}", tableId);
- log.info("Available schema change states: {}", schemaChangeStates.keySet());
- return;
- }
-
- if (!state.getJobId().equals(jobId)) {
- log.warn(
- "Job ID mismatch: received jobId={}, expected jobId={}, tableId={}",
- jobId,
- state.getJobId(),
- tableId);
- return;
- }
-
- // update the schema change status
- state.incrementFlushCount();
- log.info(
- "Received flush successful notification for table {} ({}), count: {}/{}",
- tableId,
- jobId,
- state.getFlushCount(),
- state.getTotalOperators());
-
- if (state.isAllFlushed()) {
- // all operators have completed flushing. The schema change can now be finalized
- log.info("All operators flushed for table {}, completing schema change", tableId);
- completeSchemaChange(tableId, jobId);
- }
- } finally {
- lock.unlock();
- }
- }
-
- public CompletableFuture<SchemaResponse> requestSchemaChange(
- TableIdentifier tableId, String jobId, CatalogTable newSchema, int totalOperators) {
-
- ReentrantLock lock = schemaLocks.computeIfAbsent(tableId, k -> new ReentrantLock());
- lock.lock();
- try {
- SchemaChangeState existingState = schemaChangeStates.get(tableId);
- if (existingState != null && existingState.getJobId() != null) {
- log.warn(
- "Schema change already in progress for table: {}, existing jobId: {}, new jobId: {}",
- tableId,
- existingState.getJobId(),
- jobId);
- return CompletableFuture.completedFuture(
- SchemaResponse.failure(
- new SchemaCoordinationException(
- SchemaEvolutionErrorCode
- .SCHEMA_CHANGE_ALREADY_IN_PROGRESS,
- "Schema change already in progress",
- tableId,
- jobId)
- .getMessage()));
- }
-
- Long lastProcessedTime = latestSchemaChangeTime.get(tableId);
- if (lastProcessedTime != null && newSchema != null) {
- long currentTime = System.currentTimeMillis();
- if (currentTime <= lastProcessedTime) {
- log.warn(
- "Received outdated schema change event for table: {}, current time: {}, last processed: {}",
- tableId,
- currentTime,
- lastProcessedTime);
- return CompletableFuture.completedFuture(
- SchemaResponse.failure(
- new SchemaValidationException(
- SchemaEvolutionErrorCode.OUTDATED_SCHEMA_EVENT,
- "Schema change event is outdated",
- tableId,
- jobId)
- .getMessage()));
- }
- }
-
- if (newSchema != null && !isValidSchema(newSchema)) {
- log.error("Invalid schema structure for table: {}", tableId);
- return CompletableFuture.completedFuture(
- SchemaResponse.failure(
- new SchemaValidationException(
- SchemaEvolutionErrorCode.INVALID_SCHEMA_STRUCTURE,
- "Invalid schema structure",
- tableId,
- jobId)
- .getMessage()));
- }
- log.info("Processing schema change for table: {}, job: {}", tableId, jobId);
-
- CatalogTable currentSchema = null;
- if (existingState != null) {
- currentSchema = existingState.getCurrentSchema();
- }
-
- SchemaChangeState state =
- new SchemaChangeState(currentSchema, newSchema, jobId, totalOperators);
-
- schemaChangeStates.put(tableId, state);
- log.info(
- "SchemaChangeStates tableId: {}, state: {}",
- tableId,
- schemaChangeStates.get(tableId));
-
- // update the latest schema change time
- if (newSchema != null) {
- latestSchemaChangeTime.put(tableId, System.currentTimeMillis());
- }
-
- return waitForSchemaChangeConfirmation(tableId, jobId);
- } finally {
- lock.unlock();
- }
- }
-
- public CompletableFuture<SchemaResponse> waitForSchemaChangeConfirmation(
- TableIdentifier tableId, String jobId) {
- CompletableFuture<SchemaResponse> future = new CompletableFuture<>();
-
- // add the request to the waiting queue
- pendingRequests.computeIfAbsent(tableId, k -> new ConcurrentHashMap<>()).put(jobId, future);
- return future;
- }
-
- private void completeSchemaChange(TableIdentifier tableId, String jobId) {
- ReentrantLock lock = schemaLocks.computeIfAbsent(tableId, k -> new ReentrantLock());
- lock.lock();
- try {
- SchemaChangeState state = schemaChangeStates.get(tableId);
- if (state == null) {
- log.warn("No schema change state found for table: {} during completion", tableId);
- return;
- }
-
- if (!jobId.equals(state.getJobId())) {
- log.warn(
- "Job ID mismatch during completion: expected={}, actual={}, table={}",
- jobId,
- state.getJobId(),
- tableId);
- return;
- }
-
- if (!state.isAllFlushed()) {
- log.warn(
- "Attempting to complete schema change but not all operators have flushed: {}/{} for table {}",
- state.getFlushCount(),
- state.getTotalOperators(),
- tableId);
- return;
- }
-
- long newVersion = schemaVersions.getOrDefault(tableId, 0L) + 1;
- schemaVersions.put(tableId, newVersion);
-
- SchemaResponse response = SchemaResponse.success(state.getNewSchema(), newVersion);
-
- Map<String, CompletableFuture<SchemaResponse>> tableRequests =
- pendingRequests.get(tableId);
- if (tableRequests != null) {
- int completedCount = 0;
- for (CompletableFuture<SchemaResponse> future : tableRequests.values()) {
- if (!future.isDone()) {
- future.complete(response);
- completedCount++;
- }
- }
- log.info(
- "Completed {} pending schema change requests for table {}",
- completedCount,
- tableId);
- tableRequests.clear();
- }
-
- state.setCurrentSchema(state.getNewSchema());
- state.setNewSchema(null);
- state.setJobId(null);
- state.resetFlushCount();
-
- latestSchemaChangeTime.remove(tableId);
- log.info("Schema change completed for table {}, version: {}", tableId, newVersion);
- } finally {
- lock.unlock();
- }
- }
-
- private boolean isValidSchema(CatalogTable schema) {
- if (schema == null) {
- return false;
- }
-
- if (schema.getTableId() == null) {
- log.error("Schema has null table identifier");
- return false;
- }
-
- if (schema.getTableSchema() == null) {
- log.error("Schema has null table schema");
- return false;
- }
-
- if (schema.getTableSchema().getColumns().isEmpty()) {
- log.error("Schema has no columns");
- return false;
- }
-
- return true;
- }
-
- @Getter
- @Setter
- @ToString
- private static class SchemaChangeState {
- private CatalogTable currentSchema;
- private CatalogTable newSchema;
- private String jobId;
- private final AtomicInteger flushCount;
- private final int totalOperators;
-
- public SchemaChangeState(
- CatalogTable currentSchema,
- CatalogTable newSchema,
- String jobId,
- int totalOperators) {
- this.currentSchema = currentSchema;
- this.newSchema = newSchema;
- this.jobId = jobId;
- this.flushCount = new AtomicInteger(0);
- this.totalOperators = totalOperators;
- }
-
- public int getFlushCount() {
- return flushCount.get();
- }
-
- public void incrementFlushCount() {
- flushCount.incrementAndGet();
- }
-
- public void resetFlushCount() {
- flushCount.set(0);
- }
-
- public boolean isAllFlushed() {
- return flushCount.get() >= totalOperators;
- }
- }
-}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaResponse.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaResponse.java
deleted file mode 100644
index 62cd458292..0000000000
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/coordinator/SchemaResponse.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.seatunnel.api.table.coordinator;
-
-import org.apache.seatunnel.api.table.catalog.CatalogTable;
-
-import lombok.Getter;
-
-/** used to return change response information */
-@Getter
-public class SchemaResponse {
- private final boolean success;
- private final String message;
- private final CatalogTable currentSchema;
- private final Long schemaVersion;
-
- private SchemaResponse(
- boolean success, String message, CatalogTable currentSchema, Long schemaVersion) {
- this.success = success;
- this.message = message;
- this.currentSchema = currentSchema;
- this.schemaVersion = schemaVersion;
- }
-
- public static SchemaResponse success(CatalogTable currentSchema, Long schemaVersion) {
- String message = "Schema change completed successfully, current version: " + schemaVersion;
- return new SchemaResponse(true, message, currentSchema, schemaVersion);
- }
-
- public static SchemaResponse failure(String errorMessage) {
- return new SchemaResponse(false, errorMessage, null, null);
- }
-
- @Deprecated
- public String getErrorMessage() {
- return message;
- }
-}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/event/FlushEvent.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/event/FlushEvent.java
deleted file mode 100644
index 449c017eaf..0000000000
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/event/FlushEvent.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.seatunnel.api.table.schema.event;
-
-import org.apache.seatunnel.api.event.EventType;
-import org.apache.seatunnel.api.table.catalog.CatalogTable;
-import org.apache.seatunnel.api.table.catalog.TableIdentifier;
-
-import lombok.Getter;
-import lombok.Setter;
-import lombok.ToString;
-
-/** Used for communication between SchemaEvolutionOperator and sink */
-@Getter
-@Setter
-@ToString
-public class FlushEvent implements SchemaChangeEvent {
- private final TableIdentifier tableIdentifier;
- @Getter @Setter private CatalogTable changeAfter;
- @Getter @Setter private String jobId;
- @Getter @Setter private String statement;
- @Getter @Setter protected String sourceDialectName;
- private final Long createdTime;
- private final SchemaChangeEvent schemaChangeEvent;
- private final EventType eventType = EventType.SCHEMA_CHANGE_FLUSH;
-
- public FlushEvent(SchemaChangeEvent schemaChangeEvent) {
- this.schemaChangeEvent = schemaChangeEvent;
- this.tableIdentifier = schemaChangeEvent.tableIdentifier();
- this.jobId = schemaChangeEvent.getJobId();
- this.createdTime = System.currentTimeMillis();
- }
-
- @Override
- public TableIdentifier tableIdentifier() {
- return tableIdentifier;
- }
-
- @Override
- public long getCreatedTime() {
- return createdTime;
- }
-
- @Override
- public EventType getEventType() {
- return eventType;
- }
-}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaCoordinationException.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaCoordinationException.java
index 70435adf43..5245080484 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaCoordinationException.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaCoordinationException.java
@@ -25,15 +25,6 @@ import org.apache.seatunnel.api.table.catalog.TableIdentifier;
*/
public class SchemaCoordinationException extends SchemaEvolutionException {
- public SchemaCoordinationException(SchemaEvolutionErrorCode errorCode, String errorMessage) {
- super(errorCode, errorMessage);
- }
-
- public SchemaCoordinationException(
- SchemaEvolutionErrorCode errorCode, String errorMessage, Throwable cause) {
- super(errorCode, errorMessage, cause);
- }
-
public SchemaCoordinationException(
SchemaEvolutionErrorCode errorCode,
String errorMessage,
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionErrorCode.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionErrorCode.java
index 08c614b952..d1a293ab9f 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionErrorCode.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionErrorCode.java
@@ -21,38 +21,24 @@ import org.apache.seatunnel.common.exception.SeaTunnelErrorCode;
public enum SchemaEvolutionErrorCode implements SeaTunnelErrorCode {
- // Schema Coordination Errors
+ // schema coordination errors
SCHEMA_COORDINATOR_NOT_INITIALIZED("SE-01", "Schema coordinator is not initialized"),
SCHEMA_CHANGE_ALREADY_IN_PROGRESS(
"SE-02", "Schema change is already in progress for the table"),
SCHEMA_CHANGE_TIMEOUT("SE-03", "Schema change operation timed out"),
SCHEMA_CHANGE_COORDINATION_FAILED("SE-04", "Schema change coordination failed"),
- // Schema Validation Errors
+ // schema validation errors
INVALID_SCHEMA_STRUCTURE("SE-05", "Invalid schema structure provided"),
- SCHEMA_INCOMPATIBLE("SE-06", "Schema change is incompatible with current schema"),
- OUTDATED_SCHEMA_EVENT("SE-07", "Schema change event is outdated"),
- UNSUPPORTED_SCHEMA_CHANGE_TYPE("SE-08", "Schema change type is not supported"),
+ OUTDATED_SCHEMA_EVENT("SE-06", "Schema change event is outdated"),
+ UNSUPPORTED_SCHEMA_CHANGE_TYPE("SE-07", "Schema change type is not supported"),
- // Sink Writer Errors
- SCHEMA_CHANGE_APPLICATION_FAILED("SE-09", "Failed to apply schema change to sink writer"),
- FLUSH_OPERATION_FAILED("SE-10", "Flush operation failed during schema evolution"),
- SCHEMA_ROLLBACK_FAILED("SE-11", "Failed to rollback schema change"),
+ // sink writer errors
+ SCHEMA_CHANGE_APPLICATION_FAILED("SE-08", "Failed to apply schema change to sink writer"),
+ FLUSH_OPERATION_FAILED("SE-09", "Flush operation failed during schema evolution"),
- // Table and Database Errors
- TABLE_SCHEMA_UPDATE_FAILED("SE-12", "Failed to update table schema in database"),
- TABLE_NOT_FOUND("SE-13", "Target table not found"),
- INSUFFICIENT_PERMISSIONS("SE-14", "Insufficient permissions to modify table schema"),
-
- // Event Processing Errors
- SCHEMA_EVENT_PROCESSING_FAILED("SE-15", "Failed to process schema change event"),
- FLUSH_EVENT_PROCESSING_FAILED("SE-16", "Failed to process flush event"),
- SCHEMA_EVENT_DESERIALIZATION_FAILED("SE-17", "Failed to deserialize schema change event"),
-
- // Resource Management Errors
- RESOURCE_CLEANUP_FAILED("SE-18", "Failed to cleanup resources after schema change"),
- CONNECTION_POOL_EXHAUSTED("SE-19", "Database connection pool exhausted during schema change"),
- MEMORY_ALLOCATION_FAILED("SE-20", "Memory allocation failed during schema processing");
+ // event processing errors
+ SCHEMA_EVENT_PROCESSING_FAILED("SE-10", "Failed to process schema change event");
private final String code;
private final String description;
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionException.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionException.java
index 6d864c291a..ed5537392a 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionException.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaEvolutionException.java
@@ -22,10 +22,7 @@ import org.apache.seatunnel.common.exception.SeaTunnelRuntimeException;
import lombok.Getter;
-/**
- * Base exception class for schema evolution related errors. This exception provides detailed
- * context about schema evolution failures.
- */
+/** Base exception class for schema evolution related errors. */
@Getter
public class SchemaEvolutionException extends SeaTunnelRuntimeException {
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaValidationException.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaValidationException.java
index e213795d6f..b2aa451297 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaValidationException.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SchemaValidationException.java
@@ -20,20 +20,11 @@ package org.apache.seatunnel.api.table.schema.exception;
import org.apache.seatunnel.api.table.catalog.TableIdentifier;
/**
- * Exception thrown when schema validation fails. This includes invalid schema structures,
- * incompatible changes, and outdated events.
+ * Exception thrown when schema validation fails. This includes invalid schema structures, outdated
+ * events.
*/
public class SchemaValidationException extends SchemaEvolutionException {
- public SchemaValidationException(SchemaEvolutionErrorCode errorCode, String errorMessage) {
- super(errorCode, errorMessage);
- }
-
- public SchemaValidationException(
- SchemaEvolutionErrorCode errorCode, String errorMessage, Throwable cause) {
- super(errorCode, errorMessage, cause);
- }
-
public SchemaValidationException(
SchemaEvolutionErrorCode errorCode,
String errorMessage,
@@ -42,23 +33,6 @@ public class SchemaValidationException extends SchemaEvolutionException {
super(errorCode, errorMessage, tableIdentifier, jobId);
}
- public SchemaValidationException(
- SchemaEvolutionErrorCode errorCode,
- String errorMessage,
- TableIdentifier tableIdentifier,
- String jobId,
- Throwable cause) {
- super(errorCode, errorMessage, tableIdentifier, jobId, cause);
- }
-
- /** Create an exception for invalid schema structure */
- public static SchemaValidationException invalidSchema(
- TableIdentifier tableIdentifier, String jobId, String reason) {
- String message = String.format("Invalid schema structure: %s", reason);
- return new SchemaValidationException(
- SchemaEvolutionErrorCode.INVALID_SCHEMA_STRUCTURE, message, tableIdentifier, jobId);
- }
-
/** Create an exception for unsupported schema change types */
public static SchemaValidationException unsupportedChangeType(
TableIdentifier tableIdentifier, String jobId) {
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SinkWriterSchemaException.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SinkWriterSchemaException.java
index 864d79af0c..76ca63c537 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SinkWriterSchemaException.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/exception/SinkWriterSchemaException.java
@@ -20,28 +20,10 @@ package org.apache.seatunnel.api.table.schema.exception;
import org.apache.seatunnel.api.table.catalog.TableIdentifier;
/**
- * Exception thrown when sink writer schema operations fail. This includes schema application
- * failures, flush failures, and rollback issues.
+ * Exception thrown when sink writer schema operations fail, includes schema application failures.
*/
public class SinkWriterSchemaException extends SchemaEvolutionException {
- public SinkWriterSchemaException(SchemaEvolutionErrorCode errorCode, String errorMessage) {
- super(errorCode, errorMessage);
- }
-
- public SinkWriterSchemaException(
- SchemaEvolutionErrorCode errorCode, String errorMessage, Throwable cause) {
- super(errorCode, errorMessage, cause);
- }
-
- public SinkWriterSchemaException(
- SchemaEvolutionErrorCode errorCode,
- String errorMessage,
- TableIdentifier tableIdentifier,
- String jobId) {
- super(errorCode, errorMessage, tableIdentifier, jobId);
- }
-
public SinkWriterSchemaException(
SchemaEvolutionErrorCode errorCode,
String errorMessage,
@@ -62,17 +44,4 @@ public class SinkWriterSchemaException extends SchemaEvolutionException {
jobId,
cause);
}
-
- /** Create an exception for flush operation failures */
- public static SinkWriterSchemaException flushFailed(
- TableIdentifier tableIdentifier, String jobId, String reason, Throwable cause) {
- String message =
- String.format("Flush operation failed during schema evolution: %s", reason);
- return new SinkWriterSchemaException(
- SchemaEvolutionErrorCode.FLUSH_OPERATION_FAILED,
- message,
- tableIdentifier,
- jobId,
- cause);
- }
}
diff --git a/seatunnel-connectors-v2/connector-console/src/main/java/org/apache/seatunnel/connectors/seatunnel/console/sink/ConsoleSinkWriter.java b/seatunnel-connectors-v2/connector-console/src/main/java/org/apache/seatunnel/connectors/seatunnel/console/sink/ConsoleSinkWriter.java
index afae87ecf2..ee85e196a0 100644
--- a/seatunnel-connectors-v2/connector-console/src/main/java/org/apache/seatunnel/connectors/seatunnel/console/sink/ConsoleSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-console/src/main/java/org/apache/seatunnel/connectors/seatunnel/console/sink/ConsoleSinkWriter.java
@@ -22,8 +22,6 @@ import org.apache.seatunnel.shade.org.apache.commons.lang3.StringUtils;
import org.apache.seatunnel.api.sink.SinkWriter;
import org.apache.seatunnel.api.sink.SupportMultiTableSinkWriter;
import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSinkWriter;
-import org.apache.seatunnel.api.table.coordinator.SchemaCoordinator;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
import org.apache.seatunnel.api.table.schema.exception.SinkWriterSchemaException;
import org.apache.seatunnel.api.table.schema.handler.DataTypeChangeEventDispatcher;
@@ -51,7 +49,6 @@ public class ConsoleSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void>
private final AtomicLong rowCounter = new AtomicLong(0);
private final SinkWriter.Context context;
private final DataTypeChangeEventHandler dataTypeChangeEventHandler;
- private SchemaCoordinator schemaCoordinator;
boolean isPrintData = true;
int delayMs = 0;
@@ -88,42 +85,10 @@ public class ConsoleSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void>
}
}
- @Override
- public void handleFlushEvent(FlushEvent event) throws IOException {
- log.info("ConsoleSinkWriter handling FlushEvent for table: {}", event.tableIdentifier());
- try {
- flushData();
- log.info("ConsoleSinkWriter flush completed for table: {}", event.tableIdentifier());
- sendFlushSuccessful(event);
- } catch (Exception e) {
- log.error("ConsoleSinkWriter flush failed for table: {}", event.tableIdentifier(), e);
- throw SinkWriterSchemaException.flushFailed(
- event.tableIdentifier(), event.getJobId(), "Console flush operation failed", e);
- }
- }
-
- @Override
- public void sendFlushSuccessful(FlushEvent event) throws IOException {
- log.info(
- "ConsoleSinkWriter reporting flush success for table: {}", event.tableIdentifier());
- SupportSchemaEvolutionSinkWriter.super.sendFlushSuccessful(event);
- }
-
- @Override
- public SchemaCoordinator getSchemaCoordinator() {
- return schemaCoordinator;
- }
-
@Override
public void write(SeaTunnelRow element) {
- if (element != null && element.getOptions() != null) {
- if (element.getOptions().containsKey("flush_event")
- || element.getOptions().containsKey("schema_change_event")) {
- log.info(
- "ConsoleSinkWriter skipping schema event row: {}",
- element.getOptions().keySet());
- return;
- }
+ if (element.getArity() == 0) {
+ return;
}
String[] arr = new String[seaTunnelRowType.getTotalFields()];
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcExactlyOnceSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcExactlyOnceSinkWriter.java
index c97941f31e..2c617386c7 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcExactlyOnceSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcExactlyOnceSinkWriter.java
@@ -24,7 +24,6 @@ import org.apache.seatunnel.api.common.JobContext;
import org.apache.seatunnel.api.sink.SinkWriter;
import org.apache.seatunnel.api.table.catalog.TablePath;
import org.apache.seatunnel.api.table.catalog.TableSchema;
-import org.apache.seatunnel.api.table.schema.exception.SinkWriterSchemaException;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSinkConfig;
@@ -132,12 +131,8 @@ public class JdbcExactlyOnceSinkWriter extends AbstractJdbcSinkWriter<Void> {
@Override
public void write(SeaTunnelRow element) {
- if (element != null && element.getOptions() != null) {
- if (element.getOptions().containsKey("flush_event")
- || element.getOptions().containsKey("schema_change_event")) {
- LOG.debug("Skipping schema change event row: {}", element.getOptions().keySet());
- return;
- }
+ if (element.getArity() == 0) {
+ return;
}
tryOpen();
@@ -146,39 +141,6 @@ public class JdbcExactlyOnceSinkWriter extends AbstractJdbcSinkWriter<Void> {
outputFormat.writeRecord(copy);
}
- @Override
- public void flushData() throws IOException {
- tryOpen();
- outputFormat.checkFlushException();
- outputFormat.flush();
- }
-
- @Override
- public void handleFlushEvent(org.apache.seatunnel.api.table.schema.event.FlushEvent event)
- throws IOException {
- LOG.info(
- "JdbcExactlyOnceSinkWriter handling FlushEvent for table: {}",
- event.tableIdentifier());
- try {
- tryOpen();
- flushData();
- LOG.info(
- "JdbcExactlyOnceSinkWriter flush completed for table: {}",
- event.tableIdentifier());
- sendFlushSuccessful(event);
- } catch (Exception e) {
- LOG.error(
- "JdbcExactlyOnceSinkWriter flush failed for table: {}",
- event.tableIdentifier(),
- e);
- throw SinkWriterSchemaException.flushFailed(
- event.tableIdentifier(),
- event.getJobId(),
- "Exactly-once JDBC flush operation failed",
- e);
- }
- }
-
@Override
public Optional<XidInfo> prepareCommit() throws IOException {
tryOpen();
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
index 49d8b47ef6..3518015b1a 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
@@ -22,9 +22,6 @@ import org.apache.seatunnel.shade.com.zaxxer.hikari.HikariDataSource;
import org.apache.seatunnel.api.sink.MultiTableResourceManager;
import org.apache.seatunnel.api.table.catalog.TablePath;
import org.apache.seatunnel.api.table.catalog.TableSchema;
-import org.apache.seatunnel.api.table.coordinator.SchemaCoordinator;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
-import org.apache.seatunnel.api.table.schema.exception.SinkWriterSchemaException;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSinkConfig;
@@ -49,7 +46,6 @@ import java.util.Optional;
@Slf4j
public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager> {
private final Integer primaryKeyIndex;
- private SchemaCoordinator schemaCoordinator;
public JdbcSinkWriter(
TablePath sinkTablePath,
@@ -148,44 +144,14 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
@Override
public void write(SeaTunnelRow element) throws IOException {
- if (element != null && element.getOptions() != null) {
- if (element.getOptions().containsKey("flush_event")
- || element.getOptions().containsKey("schema_change_event")) {
- log.debug("Skipping schema change event row: {}", element.getOptions().keySet());
- return;
- }
+ if (element.getArity() == 0) {
+ return;
}
tryOpen();
outputFormat.writeRecord(element);
}
- @Override
- public void handleFlushEvent(FlushEvent event) throws IOException {
- log.info("JdbcSinkWriter handling FlushEvent for table: {}", event.tableIdentifier());
- try {
- flushData();
- log.info("JdbcSinkWriter flush completed for table: {}", event.tableIdentifier());
- sendFlushSuccessful(event);
- } catch (Exception e) {
- log.error("JdbcSinkWriter flush failed for table: {}", event.tableIdentifier(), e);
- throw SinkWriterSchemaException.flushFailed(
- event.tableIdentifier(), event.getJobId(), "JDBC flush operation failed", e);
- }
- }
-
- @Override
- public void flushData() throws IOException {
- tryOpen();
- outputFormat.checkFlushException();
- outputFormat.flush();
- }
-
- @Override
- public SchemaCoordinator getSchemaCoordinator() {
- return schemaCoordinator;
- }
-
@Override
public Optional<XidInfo> prepareCommit() throws IOException {
tryOpen();
diff --git a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-13-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-13-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
index 8fbf18d92d..8259302dca 100644
--- a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-13-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
+++ b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-13-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
@@ -29,6 +29,7 @@ import org.apache.seatunnel.api.sink.SaveModeHandler;
import org.apache.seatunnel.api.sink.SeaTunnelSink;
import org.apache.seatunnel.api.sink.SupportMultiTableSink;
import org.apache.seatunnel.api.sink.SupportSaveMode;
+import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSink;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.catalog.TableIdentifier;
import org.apache.seatunnel.api.table.catalog.TablePath;
@@ -42,8 +43,11 @@ import org.apache.seatunnel.common.exception.SeaTunnelRuntimeException;
import org.apache.seatunnel.core.starter.exception.TaskExecuteException;
import org.apache.seatunnel.plugin.discovery.seatunnel.SeaTunnelFactoryDiscovery;
import org.apache.seatunnel.plugin.discovery.seatunnel.SeaTunnelSinkPluginDiscovery;
+import org.apache.seatunnel.translation.flink.schema.BroadcastSchemaSinkOperator;
import org.apache.seatunnel.translation.flink.sink.FlinkSink;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.slf4j.Logger;
@@ -60,6 +64,7 @@ import java.util.stream.Collectors;
import static org.apache.seatunnel.api.common.SeaTunnelAPIErrorCode.HANDLE_SAVE_MODE_FAILED;
import static org.apache.seatunnel.api.options.ConnectorCommonOptions.PLUGIN_NAME;
import static org.apache.seatunnel.api.table.factory.FactoryUtil.discoverOptionalFactory;
+import static org.apache.seatunnel.common.constants.JobMode.STREAMING;
@SuppressWarnings({"unchecked", "rawtypes"})
public class SinkExecuteProcessor
@@ -153,9 +158,25 @@ public class SinkExecuteProcessor
: envParallelism
? envConfig.getInt(EnvCommonOptions.PARALLELISM.key())
: 1;
+
+ boolean isStreaming =
+ envConfig.hasPath("job.mode")
+ && STREAMING
+ .toString()
+ .equalsIgnoreCase(envConfig.getString("job.mode"));
+ DataStream<SeaTunnelRow> ds = stream.getDataStream();
+ if (isStreaming && sink instanceof SupportSchemaEvolutionSink) {
+ // insert broadcast-based schema operator to handle schema changes
+ ds =
+ ds.transform(
+ "BroadcastSchemaHandler",
+ TypeInformation.of(SeaTunnelRow.class),
+ new BroadcastSchemaSinkOperator())
+ .name("BroadcastSchemaHandler")
+ .setParallelism(parallelism);
+ }
DataStreamSink<SeaTunnelRow> dataStreamSink =
- stream.getDataStream()
- .sinkTo(new FlinkSink<>(sink, stream.getCatalogTables(), parallelism))
+ ds.sinkTo(new FlinkSink<>(sink, stream.getCatalogTables(), parallelism))
.name(String.format("%s-Sink", sink.getPluginName()));
dataStreamSink.setParallelism(parallelism);
}
diff --git a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-20-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-20-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
index 2e2fe54951..d8e9068808 100644
--- a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-20-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
+++ b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-20-starter/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
@@ -21,14 +21,20 @@ import org.apache.seatunnel.shade.com.typesafe.config.Config;
import org.apache.seatunnel.api.common.JobContext;
import org.apache.seatunnel.api.sink.SeaTunnelSink;
+import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSink;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.BroadcastSchemaSinkOperator;
import org.apache.seatunnel.translation.flink.sink.FlinkSink;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import java.net.URL;
import java.util.List;
+import static org.apache.seatunnel.common.constants.JobMode.STREAMING;
+
/** Sink execute processor for Flink 1.20. */
public class SinkExecuteProcessor extends AbstractSinkExecuteProcessor {
@@ -43,8 +49,21 @@ public class SinkExecuteProcessor extends AbstractSinkExecuteProcessor {
@Override
protected DataStreamSink<SeaTunnelRow> createVersionSpecificDataStreamSink(
DataStreamTableInfo stream, SeaTunnelSink sink, int parallelism, Config sinkConfig) {
- return stream.getDataStream()
- .sinkTo(new FlinkSink<>(sink, stream.getCatalogTables(), parallelism))
+ boolean isStreaming =
+ envConfig.hasPath("job.mode")
+ && STREAMING.toString().equalsIgnoreCase(envConfig.getString("job.mode"));
+ DataStream<SeaTunnelRow> ds = stream.getDataStream();
+ if (isStreaming && sink instanceof SupportSchemaEvolutionSink) {
+ // insert broadcast-based schema operator to handle schema changes
+ ds =
+ ds.transform(
+ "BroadcastSchemaHandler",
+ TypeInformation.of(SeaTunnelRow.class),
+ new BroadcastSchemaSinkOperator())
+ .name("BroadcastSchemaHandler")
+ .setParallelism(parallelism);
+ }
+ return ds.sinkTo(new FlinkSink<>(sink, stream.getCatalogTables(), parallelism))
.name(String.format("%s-Sink", sink.getPluginName()));
}
}
diff --git a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SchemaOperator.java b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SchemaOperator.java
deleted file mode 100644
index 0302a98957..0000000000
--- a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SchemaOperator.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * 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.seatunnel.core.starter.flink.execution;
-
-import org.apache.seatunnel.shade.com.typesafe.config.Config;
-
-import org.apache.seatunnel.api.source.SupportSchemaEvolution;
-import org.apache.seatunnel.api.table.catalog.CatalogTable;
-import org.apache.seatunnel.api.table.catalog.TableIdentifier;
-import org.apache.seatunnel.api.table.coordinator.SchemaCoordinator;
-import org.apache.seatunnel.api.table.coordinator.SchemaResponse;
-import org.apache.seatunnel.api.table.schema.SchemaChangeType;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
-import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
-import org.apache.seatunnel.api.table.schema.event.TableEvent;
-import org.apache.seatunnel.api.table.schema.exception.SchemaCoordinationException;
-import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
-import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
-import org.apache.seatunnel.api.table.type.SeaTunnelRow;
-
-import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
-import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
-import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
-
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicReference;
-
-/** operators added to the source and transformer pipelines to handle schema evolution */
-@Slf4j
-public class SchemaOperator extends AbstractStreamOperator<SeaTunnelRow>
- implements OneInputStreamOperator<SeaTunnelRow, SeaTunnelRow> {
- private final Map<TableIdentifier, CatalogTable> localSchemaState;
- private String jobId;
- private final SupportSchemaEvolution source;
- private final Config pluginConfig;
- private SchemaCoordinator schemaCoordinator;
- private final AtomicReference<CompletableFuture<SchemaResponse>> currentSchemaChangeFuture =
- new AtomicReference<>();
- private volatile Long lastProcessedEventTime;
-
- public SchemaOperator(String jobId, SupportSchemaEvolution source, Config pluginConfig) {
- this.jobId = jobId;
- this.source = source;
- this.pluginConfig = pluginConfig;
- this.localSchemaState = new ConcurrentHashMap<>();
- this.schemaCoordinator = SchemaCoordinator.getOrCreateInstance(jobId);
- }
-
- @Override
- public void open() throws Exception {
- super.open();
- try {
- String flinkJobId = getRuntimeContext().getJobId().toString();
- if (!flinkJobId.equals(this.jobId)) {
- log.info(
- "Updating SchemaCoordinator from SeaTunnel jobId {} to Flink jobId {}",
- this.jobId,
- flinkJobId);
- this.jobId = flinkJobId;
- this.schemaCoordinator = SchemaCoordinator.getOrCreateInstance(flinkJobId);
- }
- } catch (Exception e) {
- log.warn("Failed to get Flink jobId, using SeaTunnel jobId: {}", this.jobId, e);
- }
- }
-
- @Override
- public void processElement(StreamRecord<SeaTunnelRow> streamRecord) throws Exception {
- SeaTunnelRow element = streamRecord.getValue();
-
- if (!isSchemaEvolutionEnabled(pluginConfig)) {
- output.collect(new StreamRecord<>(element, streamRecord.getTimestamp()));
- return;
- }
-
- if ("__SCHEMA_CHANGE_EVENT__".equals(element.getTableId())
- && element.getOptions() != null) {
- Object object = element.getOptions().get("schema_change_event");
- if (object instanceof SchemaChangeEvent) {
- handleSchemaChangeEvent((SchemaChangeEvent) object);
- return;
- }
- }
-
- output.collect(new StreamRecord<>(element, streamRecord.getTimestamp()));
- }
-
- private void handleSchemaChangeEvent(SchemaChangeEvent schemaChangeEvent) throws Exception {
- List<SchemaChangeType> supportedTypes = source.supports();
- if (supportedTypes == null || supportedTypes.isEmpty()) {
- log.info(
- "Source: {} does not support any schema change types, skipping schema change event",
- source);
- return;
- }
-
- if (!isSchemaChangeSupported(schemaChangeEvent, supportedTypes)) {
- log.warn(
- "Schema change type {} not supported by source {}, skipping",
- schemaChangeEvent.getEventType(),
- source);
- return;
- }
-
- processSchemaChangeEvent(schemaChangeEvent);
- }
-
- private boolean isSchemaEvolutionEnabled(Config pluginConfig) {
- if (pluginConfig.hasPath("schema-changes.enabled")) {
- return pluginConfig.getBoolean("schema-changes.enabled");
- }
-
- if (pluginConfig.hasPath("debezium")) {
- Config debeziumConfig = pluginConfig.getConfig("debezium");
- if (debeziumConfig.hasPath("schema.changes.enabled")) {
- return debeziumConfig.getBoolean("schema.changes.enabled");
- }
- }
-
- return false;
- }
-
- private boolean isSchemaChangeSupported(
- SchemaChangeEvent event, List<SchemaChangeType> supportedTypes) {
- switch (event.getEventType()) {
- case SCHEMA_CHANGE_ADD_COLUMN:
- return supportedTypes.contains(SchemaChangeType.ADD_COLUMN);
- case SCHEMA_CHANGE_DROP_COLUMN:
- return supportedTypes.contains(SchemaChangeType.DROP_COLUMN);
- case SCHEMA_CHANGE_MODIFY_COLUMN:
- return supportedTypes.contains(SchemaChangeType.UPDATE_COLUMN);
- case SCHEMA_CHANGE_CHANGE_COLUMN:
- return supportedTypes.contains(SchemaChangeType.RENAME_COLUMN);
- case SCHEMA_CHANGE_UPDATE_COLUMNS:
- return supportedTypes.contains(SchemaChangeType.ADD_COLUMN)
- || supportedTypes.contains(SchemaChangeType.DROP_COLUMN)
- || supportedTypes.contains(SchemaChangeType.UPDATE_COLUMN)
- || supportedTypes.contains(SchemaChangeType.RENAME_COLUMN);
- default:
- log.error("Unknown schema change event type: {}", event.getEventType());
- throw SchemaValidationException.unsupportedChangeType(
- event.tableIdentifier(), jobId);
- }
- }
-
- private void processSchemaChangeEvent(SchemaChangeEvent schemaChangeEvent) throws Exception {
- TableIdentifier tableId = schemaChangeEvent.tableIdentifier();
- long eventTime = schemaChangeEvent.getCreatedTime();
-
- if (lastProcessedEventTime != null && eventTime <= lastProcessedEventTime) {
- throw SchemaValidationException.outdatedEvent(
- tableId, jobId, eventTime, lastProcessedEventTime);
- }
-
- // set the jobId for the schema change event to ensure proper coordination
- if (schemaChangeEvent instanceof TableEvent) {
- schemaChangeEvent.setJobId(jobId);
- }
-
- log.info(
- "Handling schema change event for table: {}, job: {}, event time: {}",
- tableId,
- jobId,
- eventTime);
-
- try {
- CompletableFuture<SchemaResponse> schemaChangeFuture =
- schemaCoordinator.requestSchemaChange(
- tableId, jobId, schemaChangeEvent.getChangeAfter(), 1);
- currentSchemaChangeFuture.set(schemaChangeFuture);
- sendFlushEventToDownstream(schemaChangeEvent);
-
- SchemaResponse response;
- try {
- response = schemaChangeFuture.get(60, TimeUnit.SECONDS);
- } catch (TimeoutException e) {
- log.error(
- "Schema change timeout for table: {}, directly failing the job",
- tableId,
- e);
- throw SchemaCoordinationException.timeout(tableId, jobId, 60, e);
- }
-
- if (!response.isSuccess()) {
- log.error(
- "Schema change failed for table: {}, directly failing the job. Error: {}",
- tableId,
- response.getMessage());
- throw new SchemaCoordinationException(
- SchemaEvolutionErrorCode.SCHEMA_CHANGE_COORDINATION_FAILED,
- "Schema change coordination failed: " + response.getMessage(),
- tableId,
- jobId);
- }
-
- sendSchemaChangeEventToDownstream(schemaChangeEvent);
- updateLocalSchemaState(tableId, schemaChangeEvent.getChangeAfter());
-
- lastProcessedEventTime = eventTime;
- log.info("Schema change completed successfully for table: {}", tableId);
- } catch (Exception e) {
- log.error("Schema change failed for table: {}, directly failing the job", tableId, e);
- throw e;
- } finally {
- currentSchemaChangeFuture.set(null);
- }
- }
-
- private void sendFlushEventToDownstream(SchemaChangeEvent schemaChangeEvent) {
- log.info("Send FlushEvent to downstream...");
- FlushEvent flushEvent = new FlushEvent(schemaChangeEvent);
-
- SeaTunnelRow flushRow = new SeaTunnelRow(0);
- Map<String, Object> options = new HashMap<>();
- options.put("flush_event", flushEvent);
- flushRow.setOptions(options);
-
- output.collect(new StreamRecord<>(flushRow));
- log.info(
- "FlushEvent sent to downstream for table: {}", schemaChangeEvent.tableIdentifier());
- }
-
- private void sendSchemaChangeEventToDownstream(SchemaChangeEvent schemaChangeEvent) {
- log.info("Send SchemaChangeEvent to downstream...");
-
- SeaTunnelRow schemaChangeRow = new SeaTunnelRow(0);
- Map<String, Object> options = new HashMap<>();
- options.put("schema_change_event", schemaChangeEvent);
- schemaChangeRow.setOptions(options);
-
- output.collect(new StreamRecord<>(schemaChangeRow));
- }
-
- private void updateLocalSchemaState(TableIdentifier tableId, CatalogTable newSchema) {
- if (newSchema != null) {
- localSchemaState.put(tableId, newSchema);
- log.debug("Updated local schema state for table: {}", tableId);
- }
- }
-
- @Override
- public void close() throws Exception {
- try {
- CompletableFuture<SchemaResponse> future = currentSchemaChangeFuture.get();
- if (future != null && !future.isDone()) {
- log.info("Cancelling ongoing schema change request during close");
- future.cancel(true);
- }
-
- if (jobId != null) {
- SchemaCoordinator.removeInstance(jobId);
- log.info("Removed SchemaCoordinator instance for job: {}", jobId);
- }
- } catch (Exception e) {
- log.warn("Error during SchemaOperator cleanup", e);
- } finally {
- super.close();
- }
- }
-}
diff --git a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
index 5c8749668d..4eb96091ee 100644
--- a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
+++ b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java
@@ -21,15 +21,21 @@ import org.apache.seatunnel.shade.com.typesafe.config.Config;
import org.apache.seatunnel.api.common.JobContext;
import org.apache.seatunnel.api.sink.SeaTunnelSink;
+import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSink;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.BroadcastSchemaSinkOperator;
import org.apache.seatunnel.translation.flink.sink.FlinkSink;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.transformations.SinkV1Adapter;
import java.net.URL;
import java.util.List;
+import static org.apache.seatunnel.common.constants.JobMode.STREAMING;
+
/** Sink execute processor for Flink 1.15. */
public class SinkExecuteProcessor extends AbstractSinkExecuteProcessor {
@@ -44,8 +50,21 @@ public class SinkExecuteProcessor extends AbstractSinkExecuteProcessor {
@Override
protected DataStreamSink<SeaTunnelRow> createVersionSpecificDataStreamSink(
DataStreamTableInfo stream, SeaTunnelSink sink, int parallelism, Config sinkConfig) {
- return stream.getDataStream()
- .sinkTo(
+ boolean isStreaming =
+ envConfig.hasPath("job.mode")
+ && STREAMING.toString().equalsIgnoreCase(envConfig.getString("job.mode"));
+ DataStream<SeaTunnelRow> ds = stream.getDataStream();
+ if (isStreaming && sink instanceof SupportSchemaEvolutionSink) {
+ // Insert broadcast-based schema operator to handle schema changes
+ ds =
+ ds.transform(
+ "BroadcastSchemaHandler",
+ TypeInformation.of(SeaTunnelRow.class),
+ new BroadcastSchemaSinkOperator())
+ .name("BroadcastSchemaHandler")
+ .setParallelism(parallelism);
+ }
+ return ds.sinkTo(
SinkV1Adapter.wrap(
new FlinkSink<>(sink, stream.getCatalogTables(), parallelism)))
.name(String.format("%s-Sink", sink.getPluginName()));
diff --git a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SourceExecuteProcessor.java b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SourceExecuteProcessor.java
index 5779752463..cd4e7b20a7 100644
--- a/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SourceExecuteProcessor.java
+++ b/seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SourceExecuteProcessor.java
@@ -36,6 +36,7 @@ import org.apache.seatunnel.common.constants.PluginType;
import org.apache.seatunnel.core.starter.execution.SourceTableInfo;
import org.apache.seatunnel.plugin.discovery.seatunnel.SeaTunnelFactoryDiscovery;
import org.apache.seatunnel.plugin.discovery.seatunnel.SeaTunnelSourcePluginDiscovery;
+import org.apache.seatunnel.translation.flink.schema.SchemaOperator;
import org.apache.seatunnel.translation.flink.source.FlinkSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
@@ -57,6 +58,7 @@ import java.util.function.Function;
import static org.apache.seatunnel.api.options.ConnectorCommonOptions.PLUGIN_NAME;
import static org.apache.seatunnel.api.options.ConnectorCommonOptions.PLUGIN_OUTPUT;
import static org.apache.seatunnel.api.table.factory.FactoryUtil.ensureJobModeMatch;
+import static org.apache.seatunnel.common.constants.JobMode.STREAMING;
@SuppressWarnings("unchecked,rawtypes")
public class SourceExecuteProcessor extends FlinkAbstractPluginExecuteProcessor<SourceTableInfo> {
@@ -91,9 +93,25 @@ public class SourceExecuteProcessor extends FlinkAbstractPluginExecuteProcessor<
sourceStream.setParallelism(parallelism);
}
+ boolean isStreaming =
+ envConfig.hasPath("job.mode")
+ && STREAMING
+ .toString()
+ .equalsIgnoreCase(envConfig.getString("job.mode"));
+
+ boolean enableSchemaChange = false;
+ for (Config cfg : pluginConfigs) {
+ if (cfg.hasPath("schema-changes.enabled")
+ && cfg.getBoolean("schema-changes.enabled")) {
+ enableSchemaChange = true;
+ break;
+ }
+ }
// add schema evolution functionality to cdc source
DataStream<SeaTunnelRow> evolvedStream = null;
- if (sourceTableInfo.getSource() instanceof SupportSchemaEvolution) {
+ if (isStreaming
+ && enableSchemaChange
+ && sourceTableInfo.getSource() instanceof SupportSchemaEvolution) {
evolvedStream =
sourceStream.transform(
"schema-evolution",
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java
index 4e91ded738..98bbd94063 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java
@@ -59,9 +59,9 @@ import static org.awaitility.Awaitility.await;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisabledOnContainer(
value = {},
- type = {EngineType.SPARK},
+ type = {EngineType.SPARK, EngineType.SEATUNNEL},
disabledReason =
- "Currently SPARK do not support cdc. In addition, the Flink engine only supports configuring single parallelism in the configuration file, and currently does not support multi-parallelism scenarios.")
+ "Currently SPARK do not support cdc, only test the change process related to Flink.")
public class MysqlCDCWithFlinkSchemaChangeIT extends TestSuiteBase implements TestResource {
private static final String MYSQL_DATABASE = "shop";
private static final String SOURCE_TABLE = "products";
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/ddl/initial.sql b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/ddl/initial.sql
deleted file mode 100644
index 17c3d05a4f..0000000000
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/ddl/initial.sql
+++ /dev/null
@@ -1,60 +0,0 @@
---
--- 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.
---
-
--- ----------------------------------------------------------------------------------------------------------------
--- DATABASE: $DBNAME$ (schema_evolution_test)
--- ----------------------------------------------------------------------------------------------------------------
-
--- Create the initial products table for schema evolution testing
-CREATE TABLE products (
- id INT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- description TEXT,
- weight DECIMAL(10,2),
- price DECIMAL(10,2) NOT NULL
-);
-
--- Create products_on_hand table for testing
-CREATE TABLE products_on_hand (
- product_id INTEGER NOT NULL PRIMARY KEY,
- quantity INTEGER NOT NULL,
- FOREIGN KEY (product_id) REFERENCES products(id)
-);
-
--- Insert initial test data
-INSERT INTO products VALUES
-(101, 'scooter', 'Small 2-wheel scooter', 3.14, 15.99),
-(102, 'car battery', '12V car battery', 8.1, 89.99),
-(103, '12-pack drill bits', '12-pack of drill bits with sizes ranging from #40 to #3', 0.8, 19.99),
-(104, 'hammer', '12oz carpenter''s hammer', 0.75, 12.99),
-(105, 'hammer', '14oz carpenter''s hammer', 0.875, 14.99),
-(106, 'hammer', '16oz carpenter''s hammer', 1.0, 16.99),
-(107, 'rocks', 'box of assorted rocks', 5.3, 9.99),
-(108, 'jacket', 'water resistent black wind breaker', 0.1, 39.99),
-(109, 'spare tire', '24 inch spare tire', 22.2, 99.99);
-
--- Insert initial inventory data
-INSERT INTO products_on_hand VALUES
-(101, 3),
-(102, 8),
-(103, 18),
-(104, 4),
-(105, 5),
-(106, 0),
-(107, 44),
-(108, 2),
-(109, 5);
diff --git a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
index 9945b39217..5241748f5e 100644
--- a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
@@ -26,11 +26,11 @@ import org.apache.seatunnel.api.sink.SinkWriter;
import org.apache.seatunnel.api.sink.SupportResourceShare;
import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSinkWriter;
import org.apache.seatunnel.api.sink.event.WriterCloseEvent;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
import org.apache.seatunnel.api.table.schema.exception.SinkWriterSchemaException;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.coordinator.LocalSchemaCoordinator;
import org.apache.flink.api.connector.sink2.CommittingSinkWriter;
import org.apache.flink.api.connector.sink2.StatefulSinkWriter;
@@ -96,63 +96,110 @@ public class FlinkSinkWriter<CommT, WriterStateT>
return;
}
- // Handle schema evolution events
- Map<String, Object> options = element.getOptions();
+ SeaTunnelRow seaTunnelRow = (SeaTunnelRow) element;
+ Map<String, Object> options = seaTunnelRow.getOptions();
- if (options != null && options.containsKey("flush_event")) {
- FlushEvent flushEvent = (FlushEvent) options.get("flush_event");
- log.info(
- "FlinkSinkWriter detected FlushEvent for table: {}",
- flushEvent.tableIdentifier());
-
- if (sinkWriter instanceof SupportSchemaEvolutionSinkWriter) {
- try {
- ((SupportSchemaEvolutionSinkWriter) sinkWriter).handleFlushEvent(flushEvent);
- log.info(
- "FlinkSinkWriter handled FlushEvent for table: {}",
- flushEvent.tableIdentifier());
- } catch (Exception e) {
- log.error("Failed to handle flush event", e);
- throw new SinkWriterSchemaException(
- SchemaEvolutionErrorCode.FLUSH_EVENT_PROCESSING_FAILED,
- "Failed to handle flush event in Flink sink writer",
- flushEvent.tableIdentifier(),
- flushEvent.getJobId(),
- e);
- }
- }
+ if (options != null && handleControlMessage(options)) {
+ return;
+ }
+
+ sinkWriter.write(element);
+ sinkWriteCount.inc();
+ sinkWriteBytes.inc(element.getBytesSize());
+ sinkWriterQPS.markEvent();
+ }
+
+ private boolean handleControlMessage(Map<String, Object> options) throws IOException {
+ if (options.containsKey("schema_change_ack")) {
+ log.debug("FlinkSinkWriter received schema change ack - filtering out control message");
+ return true;
+ }
+
+ if (options.containsKey("schema_change_event")) {
+ handleSchemaChangeEvent(
+ (SchemaChangeEvent) options.get("schema_change_event"), options);
+ return true;
+ }
+
+ return false;
+ }
+
+ private void handleSchemaChangeEvent(
+ SchemaChangeEvent schemaChangeEvent, Map<String, Object> options) throws IOException {
+ log.info(
+ "FlinkSinkWriter applying SchemaChangeEvent for table: {}",
+ schemaChangeEvent.tableIdentifier());
+
+ sinkWriter.prepareCommit();
+ if (!(sinkWriter instanceof SupportSchemaEvolutionSinkWriter)) {
+ log.warn(
+ "Sink writer {} does not support schema evolution, ignoring SchemaChangeEvent for table: {}",
+ sinkWriter.getClass().getSimpleName(),
+ schemaChangeEvent.tableIdentifier());
+ return;
}
- if (options != null && options.containsKey("schema_change_event")) {
- SchemaChangeEvent schemaChangeEvent =
- (SchemaChangeEvent) options.get("schema_change_event");
+ Long subtaskIdObj = (Long) options.get("schema_subtask_id");
+ int subtaskId = subtaskIdObj != null ? subtaskIdObj.intValue() : -1;
+ long epoch = schemaChangeEvent.getCreatedTime();
+ boolean success = false;
+
+ try {
+ ((SupportSchemaEvolutionSinkWriter) sinkWriter).applySchemaChange(schemaChangeEvent);
log.info(
- "FlinkSinkWriter detected SchemaChangeEvent for table: {}",
+ "FlinkSinkWriter successfully applied SchemaChangeEvent for table: {}",
schemaChangeEvent.tableIdentifier());
+ success = true;
+ } catch (Exception e) {
+ log.error(
+ "Failed to apply schema change for table: {}",
+ schemaChangeEvent.tableIdentifier(),
+ e);
+ } finally {
+ sendSchemaChangeAck(schemaChangeEvent, epoch, subtaskId, success);
+ }
- if (sinkWriter instanceof SupportSchemaEvolutionSinkWriter) {
- try {
- ((SupportSchemaEvolutionSinkWriter) sinkWriter)
- .applySchemaChange(schemaChangeEvent);
- log.info(
- "FlinkSinkWriter applied SchemaChangeEvent for table: {}",
- schemaChangeEvent.tableIdentifier());
- } catch (Exception e) {
- log.error("Failed to apply schema change", e);
- throw new SinkWriterSchemaException(
- SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
- "Failed to apply schema change in Flink sink writer",
- schemaChangeEvent.tableIdentifier(),
- schemaChangeEvent.getJobId(),
- e);
- }
- }
+ if (!success) {
+ throw new SinkWriterSchemaException(
+ SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
+ "Failed to apply schema change in Flink sink writer",
+ schemaChangeEvent.tableIdentifier(),
+ schemaChangeEvent.getJobId(),
+ null);
}
+ }
- sinkWriter.write(element);
- sinkWriteCount.inc();
- sinkWriteBytes.inc(element.getBytesSize());
- sinkWriterQPS.markEvent();
+ private void sendSchemaChangeAck(
+ SchemaChangeEvent schemaChangeEvent, long epoch, int subtaskId, boolean success) {
+ if (subtaskId < 0) {
+ log.warn(
+ "FlinkSinkWriter cannot send ack: subtask ID not found in schema change event options");
+ return;
+ }
+
+ try {
+ String jobId = schemaChangeEvent.getJobId();
+ if (jobId == null || jobId.trim().isEmpty()) {
+ jobId = "unknown-job";
+ log.warn("SchemaChangeEvent has no jobId, using default: {}", jobId);
+ }
+
+ LocalSchemaCoordinator coordinator = LocalSchemaCoordinator.getInstance(jobId);
+ coordinator.notifySchemaChangeApplied(
+ schemaChangeEvent.tableIdentifier(), epoch, subtaskId, success);
+ log.info(
+ "FlinkSinkWriter sent schema change ack to coordinator for table {} (epoch {}), subtask {}, success: {}",
+ schemaChangeEvent.tableIdentifier(),
+ epoch,
+ subtaskId,
+ success);
+ } catch (Exception e) {
+ log.error(
+ "Failed to send schema change ack to coordinator for table {} (epoch {})",
+ schemaChangeEvent.tableIdentifier(),
+ epoch,
+ e);
+ }
}
@Override
diff --git a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java
new file mode 100644
index 0000000000..b4cc194211
--- /dev/null
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java
@@ -0,0 +1,222 @@
+/*
+ * 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.seatunnel.translation.flink.schema;
+
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaCoordinationException;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
+import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.coordinator.LocalSchemaCoordinator;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * BroadcastSchemaSinkOperator is a Flink operator that coordinates schema changes across parallel
+ * sink subtasks using immediate application
+ */
+@Slf4j
+public class BroadcastSchemaSinkOperator extends AbstractStreamOperator<SeaTunnelRow>
+ implements OneInputStreamOperator<SeaTunnelRow, SeaTunnelRow> {
+
+ private transient Map<TableIdentifier, Long> lastProcessedEpoch;
+ private transient ListState<TableEpochEntry> lastProcessedEpochState;
+ private transient LocalSchemaCoordinator coordinator;
+ private String jobId;
+
+ @Getter
+ @Setter
+ public static class TableEpochEntry implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private TableIdentifier tableId = null;
+ private long epoch = 0L;
+
+ public TableEpochEntry() {}
+
+ public TableEpochEntry(TableIdentifier tableId, long epoch) {
+ this.tableId = tableId;
+ this.epoch = epoch;
+ }
+ }
+
+ @Override
+ public void initializeState(StateInitializationContext context) throws Exception {
+ super.initializeState(context);
+
+ ListStateDescriptor<TableEpochEntry> epochDescriptor =
+ new ListStateDescriptor<>("last-processed-epochs", TableEpochEntry.class);
+ lastProcessedEpochState = context.getOperatorStateStore().getListState(epochDescriptor);
+
+ this.lastProcessedEpoch = new HashMap<>();
+
+ if (context.isRestored()) {
+ for (TableEpochEntry entry : lastProcessedEpochState.get()) {
+ lastProcessedEpoch.put(entry.tableId, entry.epoch);
+ log.info(
+ "Restored last processed epoch {} for table {}",
+ entry.epoch,
+ entry.tableId);
+ }
+ }
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+ int subtaskId = getRuntimeContext().getIndexOfThisSubtask();
+ int parallelism = getRuntimeContext().getNumberOfParallelSubtasks();
+
+ this.jobId = getRuntimeContext().getJobId().toString();
+ this.coordinator = LocalSchemaCoordinator.getInstance(jobId);
+
+ if (subtaskId == 0) {
+ coordinator.registerSinkParallelism(parallelism);
+ }
+
+ // register this subtask as a state provider for the coordinator
+ coordinator.registerSinkStateProvider(
+ subtaskId, tableId -> lastProcessedEpoch.get(tableId));
+ log.info("BroadcastSchemaSinkOperator opened on subtask {}/{}", subtaskId, parallelism);
+ }
+
+ @Override
+ public void snapshotState(StateSnapshotContext context) throws Exception {
+ super.snapshotState(context);
+
+ lastProcessedEpochState.clear();
+ for (Map.Entry<TableIdentifier, Long> entry : lastProcessedEpoch.entrySet()) {
+ lastProcessedEpochState.add(new TableEpochEntry(entry.getKey(), entry.getValue()));
+ }
+
+ log.debug(
+ "Subtask {} snapshotted state with last processed epochs for {} tables",
+ getRuntimeContext().getIndexOfThisSubtask(),
+ lastProcessedEpoch.size());
+ }
+
+ @Override
+ public void processElement(StreamRecord<SeaTunnelRow> element) throws Exception {
+ SeaTunnelRow row = element.getValue();
+ Map<String, Object> options = row.getOptions();
+
+ if (options != null && options.containsKey("schema_change_broadcast")) {
+ SchemaChangeEvent event = (SchemaChangeEvent) options.get("schema_change_broadcast");
+ handleBroadcastedSchemaChange(event);
+ return;
+ }
+
+ output.collect(element);
+ }
+
+ private void handleBroadcastedSchemaChange(SchemaChangeEvent event) {
+ TableIdentifier tableId = event.tableIdentifier();
+ long epoch = event.getCreatedTime();
+ try {
+ Long lastEpoch = lastProcessedEpoch.get(tableId);
+ if (lastEpoch != null && epoch <= lastEpoch) {
+ log.info(
+ "Subtask {} already processed schema change for table {} (epoch {}), last processed: {}. "
+ + "Sending ACK to coordinator for this duplicate event.",
+ getRuntimeContext().getIndexOfThisSubtask(),
+ tableId,
+ epoch,
+ lastEpoch);
+
+ // send ACK for this already-processed event to avoid coordinator timeout
+ coordinator.notifySchemaChangeApplied(
+ tableId, epoch, getRuntimeContext().getIndexOfThisSubtask(), true);
+ return;
+ }
+ int subtaskId = getRuntimeContext().getIndexOfThisSubtask();
+ log.info(
+ "Subtask {} applying schema change immediately for table {} (epoch {}, change: {}). This prevents deadlock by allowing checkpoint barriers to propagate.",
+ subtaskId,
+ tableId,
+ epoch,
+ event.getClass().getSimpleName());
+
+ try {
+ emitApplySchemaEventToSink(event, epoch);
+ lastProcessedEpoch.put(tableId, epoch);
+
+ // send ACK to coordinator indicating this subtask has processed the schema change
+ coordinator.notifySchemaChangeApplied(tableId, epoch, subtaskId, true);
+
+ log.info(
+ "Subtask {} processed schema change for table {} (epoch {}) and sent ACK to coordinator.",
+ subtaskId,
+ tableId,
+ epoch);
+ } catch (Exception e) {
+ coordinator.notifySchemaChangeApplied(tableId, epoch, subtaskId, false);
+ throw e;
+ }
+ } catch (SchemaValidationException | SchemaCoordinationException e) {
+ log.error("Schema broadcast or coordination error", e);
+ throw e;
+ } catch (Exception e) {
+ log.error("Schema change dispatch failed", e);
+ throw new SchemaEvolutionException(
+ SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
+ e.getMessage(),
+ tableId,
+ jobId,
+ e);
+ }
+ }
+
+ private void emitApplySchemaEventToSink(SchemaChangeEvent event, long epoch) {
+ SeaTunnelRow schemaRow = new SeaTunnelRow(0);
+ Map<String, Object> opts = new HashMap<>();
+ opts.put("schema_change_event", event);
+ opts.put("schema_epoch", epoch);
+ opts.put("schema_subtask_id", (long) getRuntimeContext().getIndexOfThisSubtask());
+ schemaRow.setOptions(opts);
+
+ output.collect(new StreamRecord<>(schemaRow));
+
+ log.debug(
+ "Subtask {} emitted schema change event for table {}",
+ getRuntimeContext().getIndexOfThisSubtask(),
+ event.tableIdentifier());
+ }
+
+ @Override
+ public void close() throws Exception {
+ super.close();
+ log.info(
+ "BroadcastSchemaSinkOperator closed on subtask {}",
+ getRuntimeContext().getIndexOfThisSubtask());
+ }
+}
diff --git a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator.java
new file mode 100644
index 0000000000..3948e1c95a
--- /dev/null
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator.java
@@ -0,0 +1,827 @@
+/*
+ * 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.seatunnel.translation.flink.schema;
+
+import org.apache.seatunnel.shade.com.typesafe.config.Config;
+
+import org.apache.seatunnel.api.source.SupportSchemaEvolution;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.schema.SchemaChangeType;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.event.TableEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.coordinator.LocalSchemaCoordinator;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** operators added to the source and transformer pipelines to handle schema evolution */
+@Slf4j
+public class SchemaOperator extends AbstractStreamOperator<SeaTunnelRow>
+ implements OneInputStreamOperator<SeaTunnelRow, SeaTunnelRow> {
+
+ private static final int MAX_BUFFERED_ROWS_PER_KEY = 100000;
+ private final Map<TableIdentifier, CatalogTable> localSchemaState;
+ private String jobId;
+ private final SupportSchemaEvolution source;
+ private final Config pluginConfig;
+ private volatile Long lastProcessedEventTime;
+ private transient LocalSchemaCoordinator coordinator;
+ private transient Map<String, List<BufferedDataRow>> bufferedDataRows;
+ private volatile boolean schemaChangePending = false;
+ private volatile CompletableFuture<Boolean> pendingSchemaFuture = null;
+ private volatile boolean stateDirty = false;
+
+ private transient ListState<SchemaStateEntry> localSchemaStateStore;
+ private transient ListState<Long> lastProcessedEventTimeState;
+ private transient ListState<Boolean> schemaChangePendingState;
+ private transient ListState<BufferedDataEntry> bufferedDataRowsState;
+
+ public SchemaOperator(String jobId, SupportSchemaEvolution source, Config pluginConfig) {
+ this.jobId = jobId;
+ this.source = source;
+ this.pluginConfig = pluginConfig;
+ this.localSchemaState = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+ String flinkJobId = getRuntimeContext().getJobId().toString();
+ if (!flinkJobId.equals(this.jobId)) {
+ this.jobId = flinkJobId;
+ }
+ this.bufferedDataRows = new ConcurrentHashMap<>();
+ this.coordinator = LocalSchemaCoordinator.getInstance(this.jobId);
+
+ // if schema change was pending and we have buffered data, handle recovery scenario
+ if (schemaChangePending && pendingSchemaFuture == null) {
+ handleSchemaChangeRecovery();
+ }
+
+ log.info(
+ "SchemaOperator opened for job: {}, recovered state - lastProcessedEventTime: {}, schemaChangePending: {}, bufferedDataRows size: {}",
+ this.jobId,
+ this.lastProcessedEventTime,
+ this.schemaChangePending,
+ bufferedDataRows.size());
+ }
+
+ @Override
+ public void processElement(StreamRecord<SeaTunnelRow> streamRecord) {
+ SeaTunnelRow element = streamRecord.getValue();
+
+ if (!isSchemaEvolutionEnabled(pluginConfig)) {
+ output.collect(streamRecord);
+ return;
+ }
+
+ if ("__SCHEMA_CHANGE_EVENT__".equals(element.getTableId())
+ && element.getOptions() != null) {
+ Object object = element.getOptions().get("schema_change_event");
+ if (object instanceof SchemaChangeEvent) {
+ handleSchemaChangeEvent((SchemaChangeEvent) object);
+ return;
+ }
+ }
+
+ if (schemaChangePending) {
+ String tableId = element.getTableId();
+ if (tableId != null && lastProcessedEventTime != null) {
+ String key = createKey(tableId, lastProcessedEventTime);
+ bufferedDataRows(key, element, streamRecord.getTimestamp());
+ return;
+ }
+ }
+
+ output.collect(streamRecord);
+ }
+
+ private boolean isSchemaEvolutionEnabled(Config pluginConfig) {
+ if (pluginConfig.hasPath("schema-changes.enabled")) {
+ return pluginConfig.getBoolean("schema-changes.enabled");
+ }
+
+ return false;
+ }
+
+ private String createKey(String tableId, Long eventTime) {
+ return tableId + "#" + eventTime;
+ }
+
+ private void bufferedDataRows(String key, SeaTunnelRow element, long timestamp) {
+ try {
+ BufferedDataRow bufferedRow = new BufferedDataRow(element, timestamp);
+
+ synchronized (this) {
+ List<BufferedDataRow> bufferedList =
+ bufferedDataRows.computeIfAbsent(key, k -> new ArrayList<>());
+
+ if (bufferedList.size() >= MAX_BUFFERED_ROWS_PER_KEY) {
+ log.warn(
+ "Buffer for key {} exceeded max size {}, dropping oldest row",
+ key,
+ MAX_BUFFERED_ROWS_PER_KEY);
+ bufferedList.remove(0);
+ }
+
+ bufferedList.add(bufferedRow);
+ stateDirty = true;
+
+ log.debug(
+ "buffered data row for key: {}, total buffered: {}",
+ key,
+ bufferedList.size());
+ }
+ } catch (Exception e) {
+ log.error("Failed to buffer data for key: {}, dropping this data row", key, e);
+ }
+ }
+
+ private void handleSchemaChangeEvent(SchemaChangeEvent schemaChangeEvent) {
+ List<SchemaChangeType> supportedTypes = source.supports();
+ if (supportedTypes == null || supportedTypes.isEmpty()) {
+ log.info(
+ "Source: {} does not support any schema change types, skipping schema change event",
+ source);
+ return;
+ }
+
+ if (!isSchemaChangeSupported(schemaChangeEvent, supportedTypes)) {
+ log.warn(
+ "Schema change type {} not supported by source {}, skipping",
+ schemaChangeEvent.getEventType(),
+ source);
+ return;
+ }
+
+ processSchemaChangeEvent(schemaChangeEvent);
+ }
+
+ private boolean isSchemaChangeSupported(
+ SchemaChangeEvent event, List<SchemaChangeType> supportedTypes) {
+ switch (event.getEventType()) {
+ case SCHEMA_CHANGE_ADD_COLUMN:
+ return supportedTypes.contains(SchemaChangeType.ADD_COLUMN);
+ case SCHEMA_CHANGE_DROP_COLUMN:
+ return supportedTypes.contains(SchemaChangeType.DROP_COLUMN);
+ case SCHEMA_CHANGE_MODIFY_COLUMN:
+ return supportedTypes.contains(SchemaChangeType.UPDATE_COLUMN);
+ case SCHEMA_CHANGE_CHANGE_COLUMN:
+ return supportedTypes.contains(SchemaChangeType.RENAME_COLUMN);
+ case SCHEMA_CHANGE_UPDATE_COLUMNS:
+ return supportedTypes.contains(SchemaChangeType.ADD_COLUMN)
+ || supportedTypes.contains(SchemaChangeType.DROP_COLUMN)
+ || supportedTypes.contains(SchemaChangeType.UPDATE_COLUMN)
+ || supportedTypes.contains(SchemaChangeType.RENAME_COLUMN);
+ default:
+ log.error("Unknown schema change event type: {}", event.getEventType());
+ throw SchemaValidationException.unsupportedChangeType(
+ event.tableIdentifier(), jobId);
+ }
+ }
+
+ private void processSchemaChangeEvent(SchemaChangeEvent schemaChangeEvent) {
+ TableIdentifier tableId = schemaChangeEvent.tableIdentifier();
+ long eventTime = schemaChangeEvent.getCreatedTime();
+
+ try {
+ if (lastProcessedEventTime != null && eventTime <= lastProcessedEventTime) {
+ throw SchemaValidationException.outdatedEvent(
+ tableId, jobId, eventTime, lastProcessedEventTime);
+ }
+
+ if (schemaChangeEvent instanceof TableEvent) {
+ schemaChangeEvent.setJobId(jobId);
+ }
+
+ log.info(
+ "Starting schema change processing for table: {}, job: {}, event time: {}",
+ tableId,
+ jobId,
+ eventTime);
+
+ String key = createKey(tableId.toString(), eventTime);
+
+ // initialize buffer for this schema change
+ synchronized (this) {
+ List<BufferedDataRow> newBufferList = new ArrayList<>();
+ bufferedDataRows.put(key, newBufferList);
+ stateDirty = true;
+ }
+
+ schemaChangePending = true;
+
+ sendSchemaChangeEventToDownstream(schemaChangeEvent);
+ CatalogTable newSchema = schemaChangeEvent.getChangeAfter();
+ if (newSchema != null) {
+ localSchemaState.put(tableId, newSchema);
+ log.debug("Updated local schema state for table: {}", tableId);
+ }
+ lastProcessedEventTime = eventTime;
+
+ try {
+ log.info(
+ "Synchronously processing schema change for table {} (epoch {}). Business data buffered.",
+ tableId,
+ eventTime);
+ long timeoutMs = 300_000L;
+ boolean success = coordinator.requestSchemaChange(tableId, eventTime, timeoutMs);
+
+ if (success) {
+ if (schemaChangeEvent.getChangeAfter() != null) {
+ localSchemaState.put(tableId, schemaChangeEvent.getChangeAfter());
+ }
+ lastProcessedEventTime = eventTime;
+ log.info(
+ "Schema change for table {} (epoch {}) confirmed successfully by all sink subtasks.",
+ tableId,
+ eventTime);
+ } else {
+ log.error(
+ "Schema change for table {} (epoch {}) failed or timed out.",
+ tableId,
+ eventTime);
+ }
+
+ } catch (Exception e) {
+ log.error(
+ "Error during synchronous schema change processing for table {} (epoch {})",
+ tableId,
+ eventTime,
+ e);
+ } finally {
+ schemaChangePending = false;
+ pendingSchemaFuture = null;
+ releaseBufferedData(key, tableId);
+
+ log.info(
+ "Synchronous schema change processing completed for table {}, data flow resumed",
+ tableId);
+ }
+
+ log.info(
+ "Synchronous schema change processing completed for table {}. Checkpoint barriers can propagate normally.",
+ tableId);
+ } catch (Exception e) {
+ log.error("Error starting schema change processing", e);
+ schemaChangePending = false;
+ try {
+ schemaChangePendingState.clear();
+ schemaChangePendingState.add(false);
+ } catch (Exception stateException) {
+ log.error(
+ "Error updating schemaChangePending state during error handling",
+ stateException);
+ }
+ pendingSchemaFuture = null;
+ }
+ }
+
+ private void releaseBufferedData(String key, TableIdentifier tableId) {
+ try {
+ List<BufferedDataRow> bufferedRows;
+ synchronized (this) {
+ bufferedRows = bufferedDataRows.remove(key);
+ stateDirty = true;
+ }
+
+ if (bufferedRows != null && !bufferedRows.isEmpty()) {
+ log.info(
+ "Releasing {} buffered data rows after schema change processing for table {}",
+ bufferedRows.size(),
+ tableId);
+
+ for (BufferedDataRow buffered : bufferedRows) {
+ output.collect(new StreamRecord<>(buffered.row, buffered.timestamp));
+ }
+
+ log.info(
+ "Successfully released {} buffered rows for table {}",
+ bufferedRows.size(),
+ tableId);
+ }
+
+ } catch (Exception e) {
+ log.error(
+ "CRITICAL: Failed to release buffered data for key: {}. "
+ + "Data may be lost if this continues to fail!",
+ key,
+ e);
+
+ try {
+ Iterable<BufferedDataEntry> stateEntries = bufferedDataRowsState.get();
+ for (BufferedDataEntry entry : stateEntries) {
+ if (entry.key.equals(key)) {
+ List<BufferedDataRow> stateData = entry.bufferedRows;
+ if (stateData != null && !stateData.isEmpty()) {
+ synchronized (this) {
+ bufferedDataRows.put(key, new ArrayList<>(stateData));
+ stateDirty = true;
+ }
+ log.info(
+ "Restored {} rows to memory buffer for retry",
+ stateData.size());
+ }
+ break;
+ }
+ }
+ } catch (Exception restoreException) {
+ log.error("Failed to restore buffered data to memory", restoreException);
+ }
+
+ throw e;
+ }
+ }
+
+ private void handleSchemaChangeRecovery() {
+ log.info(
+ "Detected schema change pending after recovery with {} buffered entries. "
+ + "Querying sink state to determine correct recovery action.",
+ bufferedDataRows.size());
+
+ try {
+ // wait for sink operators to register their state providers with retry mechanism
+ waitForSinkStateProviders(10, 500);
+
+ boolean allDataReleased = true;
+ int totalReleased = 0;
+
+ for (Map.Entry<String, List<BufferedDataRow>> entry : bufferedDataRows.entrySet()) {
+ String key = entry.getKey();
+ List<BufferedDataRow> bufferedRows = entry.getValue();
+
+ if (bufferedRows == null || bufferedRows.isEmpty()) {
+ continue;
+ }
+
+ String[] keyParts = key.split("#");
+ if (keyParts.length != 2) {
+ log.warn("Invalid buffer key format: {}, releasing data", key);
+ releaseBufferedDataForKey(key, bufferedRows);
+ totalReleased += bufferedRows.size();
+ continue;
+ }
+
+ String tableIdStr = keyParts[0];
+ long epoch;
+ try {
+ epoch = Long.parseLong(keyParts[1]);
+ } catch (NumberFormatException e) {
+ log.warn("Invalid epoch in buffer key: {}, releasing data", key);
+ releaseBufferedDataForKey(key, bufferedRows);
+ totalReleased += bufferedRows.size();
+ continue;
+ }
+ TableIdentifier tableId;
+ String[] parts = tableIdStr.split("\\.");
+ if (parts.length < 3) {
+ throw new IllegalArgumentException("Invalid table id format: " + tableIdStr);
+ }
+ tableId = TableIdentifier.of(parts[0], parts[1], parts[2]);
+
+ // query sink processing status using string representation directly
+ LocalSchemaCoordinator.SchemaProcessingStatus status =
+ coordinator.querySchemaProcessingStatus(tableId, epoch);
+
+ switch (status) {
+ case FULLY_PROCESSED:
+ log.info(
+ "Schema change for table {} epoch {} fully processed, releasing {} buffered rows",
+ tableIdStr,
+ epoch,
+ bufferedRows.size());
+ releaseBufferedDataForKey(key, bufferedRows);
+ totalReleased += bufferedRows.size();
+ break;
+
+ case NOT_PROCESSED:
+ log.info(
+ "Schema change for table {} epoch {} not processed, need to restart coordination for {} buffered rows",
+ tableIdStr,
+ epoch,
+ bufferedRows.size());
+ restartSchemaChangeCoordination(tableId, epoch, key);
+ allDataReleased = false;
+ break;
+
+ case PARTIALLY_PROCESSED:
+ log.warn(
+ "Schema change for table {} epoch {} partially processed, need to restart coordination for {} buffered rows",
+ tableIdStr,
+ epoch,
+ bufferedRows.size());
+ restartSchemaChangeCoordination(tableId, epoch, key);
+ allDataReleased = false;
+ break;
+
+ default:
+ log.error(
+ "Unknown schema processing status: {}, releasing data to avoid deadlock",
+ status);
+ releaseBufferedDataForKey(key, bufferedRows);
+ totalReleased += bufferedRows.size();
+ }
+ }
+
+ // only reset schemaChangePending if all data was released
+ if (allDataReleased) {
+ schemaChangePending = false;
+ schemaChangePendingState.clear();
+ schemaChangePendingState.add(false);
+ log.info(
+ "Recovery completed: Released {} buffered data rows and resumed normal data flow.",
+ totalReleased);
+ } else {
+ log.info(
+ "Recovery in progress: Released {} buffered data rows, {} entries still need coordination.",
+ totalReleased,
+ bufferedDataRows.size());
+ }
+
+ } catch (Exception e) {
+ log.error(
+ "Error during schema change recovery, releasing all buffered data to avoid deadlock",
+ e);
+ releaseAllBufferedData();
+ }
+ }
+
+ private void waitForSinkStateProviders(int maxRetries, long retryIntervalMs)
+ throws InterruptedException {
+ for (int i = 0; i < maxRetries; i++) {
+ if (coordinator.querySchemaProcessingStatus(
+ TableIdentifier.of("test", "test", "test"), 0L)
+ != null) {
+ log.info("Sink state providers registered after {} retries", i);
+ return;
+ }
+ Thread.sleep(retryIntervalMs);
+ }
+ log.warn(
+ "Sink state providers not fully registered after {} retries, proceeding anyway",
+ maxRetries);
+ }
+
+ private void releaseBufferedDataForKey(String key, List<BufferedDataRow> bufferedRows) {
+ try {
+ for (BufferedDataRow buffered : bufferedRows) {
+ output.collect(new StreamRecord<>(buffered.row, buffered.timestamp));
+ }
+
+ synchronized (this) {
+ bufferedDataRows.remove(key);
+ stateDirty = true;
+ }
+ } catch (Exception e) {
+ log.error("Failed to release buffered data for key: {}", key, e);
+ }
+ }
+
+ private void restartSchemaChangeCoordination(TableIdentifier tableId, long epoch, String key) {
+ try {
+ log.info("Restarting schema change coordination for table {} epoch {}", tableId, epoch);
+
+ // create a new future for this coordination
+ CompletableFuture<Boolean> newFuture =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ long timeoutMs = 300_000L;
+ boolean success =
+ coordinator.requestSchemaChange(
+ tableId, epoch, timeoutMs);
+
+ if (success) {
+ log.info(
+ "Restarted schema change coordination successful for table {} epoch {}",
+ tableId,
+ epoch);
+ } else {
+ log.error(
+ "Restarted schema change coordination failed for table {} epoch {}",
+ tableId,
+ epoch);
+ }
+
+ return success;
+ } catch (Exception e) {
+ log.error(
+ "Error in restarted schema change coordination for table {} epoch {}",
+ tableId,
+ epoch,
+ e);
+ return false;
+ }
+ });
+
+ newFuture.whenComplete(
+ (success, throwable) -> {
+ try {
+ if (throwable != null) {
+ log.error(
+ "Restarted schema change future completed with exception",
+ throwable);
+ }
+
+ // release the buffered data
+ List<BufferedDataRow> bufferedRows = bufferedDataRows.get(key);
+ if (bufferedRows != null) {
+ releaseBufferedDataForKey(key, bufferedRows);
+ log.info(
+ "Released {} buffered rows after restarted coordination for key {}",
+ bufferedRows.size(),
+ key);
+ }
+
+ // check if this was the last pending coordination
+ if (bufferedDataRows.isEmpty()) {
+ schemaChangePending = false;
+ schemaChangePendingState.clear();
+ schemaChangePendingState.add(false);
+ log.info(
+ "All schema change coordination completed, resumed normal data flow");
+ }
+
+ } catch (Exception e) {
+ log.error("Error in restarted coordination completion handling", e);
+ }
+ });
+
+ if (pendingSchemaFuture == null) {
+ pendingSchemaFuture = newFuture;
+ }
+
+ } catch (Exception e) {
+ log.error(
+ "Failed to restart schema change coordination for table {} epoch {}, releasing data",
+ tableId,
+ epoch,
+ e);
+ List<BufferedDataRow> bufferedRows = bufferedDataRows.get(key);
+ if (bufferedRows != null) {
+ releaseBufferedDataForKey(key, bufferedRows);
+ }
+ }
+ }
+
+ private void releaseAllBufferedData() {
+ try {
+ int totalReleased = 0;
+ synchronized (this) {
+ for (Map.Entry<String, List<BufferedDataRow>> entry : bufferedDataRows.entrySet()) {
+ List<BufferedDataRow> bufferedRows = entry.getValue();
+ if (bufferedRows != null && !bufferedRows.isEmpty()) {
+ for (BufferedDataRow buffered : bufferedRows) {
+ output.collect(new StreamRecord<>(buffered.row, buffered.timestamp));
+ }
+ totalReleased += bufferedRows.size();
+ }
+ }
+
+ bufferedDataRows.clear();
+ stateDirty = true;
+ }
+
+ schemaChangePending = false;
+ schemaChangePendingState.clear();
+ schemaChangePendingState.add(false);
+
+ log.info("Emergency recovery: Released {} buffered data rows", totalReleased);
+ } catch (Exception e) {
+ log.error("Failed to release all buffered data during emergency recovery", e);
+ }
+ }
+
+ private void sendSchemaChangeEventToDownstream(SchemaChangeEvent schemaChangeEvent) {
+ log.info(
+ "Broadcasting SchemaChangeEvent to all downstream sink subtasks for table: {}",
+ schemaChangeEvent.tableIdentifier());
+ SeaTunnelRow broadcastRow = new SeaTunnelRow(0);
+ Map<String, Object> options = new HashMap<>();
+ options.put("schema_change_broadcast", schemaChangeEvent);
+ broadcastRow.setOptions(options);
+
+ output.collect(new StreamRecord<>(broadcastRow));
+ log.info(
+ "SchemaChangeEvent broadcast sent for table: {}",
+ schemaChangeEvent.tableIdentifier());
+ }
+
+ @Override
+ public void close() throws Exception {
+ try {
+ if (pendingSchemaFuture != null && !pendingSchemaFuture.isDone()) {
+ log.info("Cancelling ongoing schema change request during close");
+ pendingSchemaFuture.cancel(true);
+ }
+ } catch (Exception e) {
+ log.warn("Error during SchemaOperator cleanup", e);
+ } finally {
+ super.close();
+ }
+ }
+
+ @Override
+ public void snapshotState(StateSnapshotContext context) throws Exception {
+ super.snapshotState(context);
+
+ try {
+ // clear and update lastProcessedEventTime
+ lastProcessedEventTimeState.clear();
+ if (lastProcessedEventTime != null) {
+ lastProcessedEventTimeState.add(lastProcessedEventTime);
+ }
+
+ // clear and update schemaChangePending
+ schemaChangePendingState.clear();
+ schemaChangePendingState.add(schemaChangePending);
+
+ // clear and update local schema state
+ localSchemaStateStore.clear();
+ for (Map.Entry<TableIdentifier, CatalogTable> entry : localSchemaState.entrySet()) {
+ localSchemaStateStore.add(new SchemaStateEntry(entry.getKey(), entry.getValue()));
+ }
+
+ // batch sync buffered data to state only when dirty
+ if (stateDirty) {
+ bufferedDataRowsState.clear();
+ synchronized (this) {
+ for (Map.Entry<String, List<BufferedDataRow>> entry :
+ bufferedDataRows.entrySet()) {
+ bufferedDataRowsState.add(
+ new BufferedDataEntry(entry.getKey(), entry.getValue()));
+ }
+ stateDirty = false;
+ }
+ }
+
+ log.debug(
+ "SchemaOperator state snapshot completed using operator state for checkpoint: {}, lastProcessedEventTime: {}, schemaChangePending: {}, localSchemaState size: {}, bufferedDataRows size: {}",
+ context.getCheckpointId(),
+ lastProcessedEventTime,
+ schemaChangePending,
+ localSchemaState.size(),
+ bufferedDataRows.size());
+ } catch (Exception e) {
+ log.error("Error during state snapshot", e);
+ throw e;
+ }
+ }
+
+ @Override
+ public void initializeState(StateInitializationContext context) throws Exception {
+ super.initializeState(context);
+ if (this.bufferedDataRows == null) {
+ this.bufferedDataRows = new ConcurrentHashMap<>();
+ }
+
+ ListStateDescriptor<SchemaStateEntry> localSchemaStateDescriptor =
+ new ListStateDescriptor<>("localSchemaState", SchemaStateEntry.class);
+
+ ListStateDescriptor<Long> lastProcessedEventTimeDescriptor =
+ new ListStateDescriptor<>("lastProcessedEventTime", Long.class);
+
+ ListStateDescriptor<Boolean> schemaChangePendingDescriptor =
+ new ListStateDescriptor<>("schemaChangePending", Boolean.class);
+
+ ListStateDescriptor<BufferedDataEntry> bufferedDataRowsDescriptor =
+ new ListStateDescriptor<>("bufferedDataRows", BufferedDataEntry.class);
+
+ this.localSchemaStateStore =
+ context.getOperatorStateStore().getListState(localSchemaStateDescriptor);
+ this.lastProcessedEventTimeState =
+ context.getOperatorStateStore().getListState(lastProcessedEventTimeDescriptor);
+ this.schemaChangePendingState =
+ context.getOperatorStateStore().getListState(schemaChangePendingDescriptor);
+ this.bufferedDataRowsState =
+ context.getOperatorStateStore().getListState(bufferedDataRowsDescriptor);
+
+ if (context.isRestored()) {
+ // restore from operator state
+ Iterable<Long> eventTimes = lastProcessedEventTimeState.get();
+ for (Long eventTime : eventTimes) {
+ this.lastProcessedEventTime = eventTime;
+ break;
+ }
+
+ Iterable<Boolean> pendingFlags = schemaChangePendingState.get();
+ for (Boolean pending : pendingFlags) {
+ this.schemaChangePending = pending;
+ break;
+ }
+
+ // restore schema state
+ Iterable<SchemaStateEntry> schemaEntries = localSchemaStateStore.get();
+ for (SchemaStateEntry entry : schemaEntries) {
+ localSchemaState.put(entry.tableId, entry.catalogTable);
+ log.info("Restored schema state for table: {}", entry.tableId);
+ }
+
+ // restore buffered data rows
+ Iterable<BufferedDataEntry> bufferedEntries = bufferedDataRowsState.get();
+ if (bufferedEntries != null) {
+ synchronized (this) {
+ for (BufferedDataEntry entry : bufferedEntries) {
+ if (entry != null && entry.key != null && entry.bufferedRows != null) {
+ bufferedDataRows.put(entry.key, new ArrayList<>(entry.bufferedRows));
+ log.info(
+ "Restored {} buffered data rows for key: {}",
+ entry.bufferedRows.size(),
+ entry.key);
+ }
+ }
+ }
+ }
+ }
+
+ log.info(
+ "SchemaOperator state initialized using operator state - lastProcessedEventTime: {}, schemaChangePending: {}, localSchemaState size: {}, bufferedDataRows size: {}",
+ this.lastProcessedEventTime,
+ this.schemaChangePending,
+ localSchemaState.size(),
+ bufferedDataRows.size());
+ }
+
+ @Setter
+ @Getter
+ public static class BufferedDataRow implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private SeaTunnelRow row;
+ private long timestamp;
+
+ public BufferedDataRow() {}
+
+ public BufferedDataRow(SeaTunnelRow row, long timestamp) {
+ this.row = row;
+ this.timestamp = timestamp;
+ }
+ }
+
+ @Setter
+ @Getter
+ public static class SchemaStateEntry implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private TableIdentifier tableId;
+ private CatalogTable catalogTable;
+
+ public SchemaStateEntry() {}
+
+ public SchemaStateEntry(TableIdentifier tableId, CatalogTable catalogTable) {
+ this.tableId = tableId;
+ this.catalogTable = catalogTable;
+ }
+ }
+
+ @Setter
+ @Getter
+ public static class BufferedDataEntry implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String key;
+ private List<BufferedDataRow> bufferedRows;
+
+ public BufferedDataEntry() {}
+
+ public BufferedDataEntry(String key, List<BufferedDataRow> bufferedRows) {
+ this.key = key;
+ this.bufferedRows = bufferedRows;
+ }
+ }
+}
diff --git a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/LocalSchemaCoordinator.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/LocalSchemaCoordinator.java
new file mode 100644
index 0000000000..41310992a1
--- /dev/null
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/LocalSchemaCoordinator.java
@@ -0,0 +1,371 @@
+/*
+ * 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.seatunnel.translation.flink.schema.coordinator;
+
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.schema.exception.SchemaCoordinationException;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.lang.ref.WeakReference;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Local coordinator for schema change synchronization. This coordinator only manages temporary
+ * communication between SchemaOperator and sink subtasks. All persistent state is managed by
+ * BroadcastSchemaSinkOperator in Flink State.
+ */
+@Slf4j
+public class LocalSchemaCoordinator {
+
+ private static final Map<String, WeakReference<LocalSchemaCoordinator>> instances =
+ new ConcurrentHashMap<>();
+ private static final ScheduledExecutorService cleanupExecutor =
+ new ScheduledThreadPoolExecutor(
+ 1,
+ r -> {
+ Thread t = new Thread(r, "LocalSchemaCoordinator-Cleanup");
+ t.setDaemon(true);
+ return t;
+ });
+ private static final long DEFAULT_REQUEST_TTL_MS = 300_000L;
+ private static final long CLEANUP_INTERVAL_MS = 60_000L;
+ private final String jobId;
+ private final long requestTtlMs;
+ private volatile int sinkParallelism = 0;
+ private final Map<String, TimestampedPendingRequest> pendingRequests =
+ new ConcurrentHashMap<>();
+ private final Map<String, Set<Integer>> receivedAcks = new ConcurrentHashMap<>();
+ private final Map<Integer, SinkStateProvider> sinkStateProviders = new ConcurrentHashMap<>();
+
+ private LocalSchemaCoordinator(String jobId, long requestTtlMs) {
+ this.jobId = jobId;
+ this.requestTtlMs = requestTtlMs;
+
+ cleanupExecutor.scheduleWithFixedDelay(
+ this::performPeriodicCleanup,
+ CLEANUP_INTERVAL_MS,
+ CLEANUP_INTERVAL_MS,
+ TimeUnit.MILLISECONDS);
+
+ log.info(
+ "Created LocalSchemaCoordinator for jobId: {} with TTL: {}ms", jobId, requestTtlMs);
+ }
+
+ public static LocalSchemaCoordinator getInstance(String jobId) {
+ if (jobId == null || jobId.trim().isEmpty()) {
+ throw new IllegalArgumentException("JobId cannot be null or empty");
+ }
+
+ return instances
+ .compute(
+ jobId,
+ (key, weakRef) -> {
+ LocalSchemaCoordinator coordinator = null;
+ if (weakRef != null) {
+ coordinator = weakRef.get();
+ }
+
+ if (coordinator == null) {
+ coordinator =
+ new LocalSchemaCoordinator(jobId, DEFAULT_REQUEST_TTL_MS);
+ log.info(
+ "Created new LocalSchemaCoordinator instance for jobId: {}",
+ jobId);
+ }
+
+ return new WeakReference<>(coordinator);
+ })
+ .get();
+ }
+
+ public void registerSinkParallelism(int parallelism) {
+ this.sinkParallelism = parallelism;
+ log.info(
+ "Registered sink parallelism: {} for schema change coordination in jobId: {}",
+ parallelism,
+ jobId);
+ }
+
+ public void registerSinkStateProvider(int subtaskId, SinkStateProvider provider) {
+ sinkStateProviders.put(subtaskId, provider);
+ log.info("Registered sink state provider for subtask {} in jobId: {}", subtaskId, jobId);
+ }
+
+ public SchemaProcessingStatus querySchemaProcessingStatus(TableIdentifier tableId, long epoch) {
+ if (sinkStateProviders.isEmpty()) {
+ log.warn(
+ "No sink state providers registered, assuming schema change not processed for table {} epoch {}",
+ tableId,
+ epoch);
+ return SchemaProcessingStatus.NOT_PROCESSED;
+ }
+
+ int processedCount = 0;
+ int totalProviders = sinkStateProviders.size();
+
+ for (Map.Entry<Integer, SinkStateProvider> entry : sinkStateProviders.entrySet()) {
+ int subtaskId = entry.getKey();
+ SinkStateProvider provider = entry.getValue();
+
+ try {
+ Long lastProcessedEpoch = provider.getLastProcessedEpoch(tableId);
+ if (lastProcessedEpoch != null && lastProcessedEpoch >= epoch) {
+ processedCount++;
+ log.debug(
+ "Subtask {} has processed epoch {} for table {}, last processed: {}",
+ subtaskId,
+ epoch,
+ tableId,
+ lastProcessedEpoch);
+ } else {
+ log.debug(
+ "Subtask {} has NOT processed epoch {} for table {}, last processed: {}",
+ subtaskId,
+ epoch,
+ tableId,
+ lastProcessedEpoch);
+ }
+ } catch (Exception e) {
+ log.error("Error querying state from sink subtask {}", subtaskId, e);
+ }
+ }
+
+ if (processedCount == 0) {
+ return SchemaProcessingStatus.NOT_PROCESSED;
+ } else if (processedCount == totalProviders) {
+ return SchemaProcessingStatus.FULLY_PROCESSED;
+ } else {
+ return SchemaProcessingStatus.PARTIALLY_PROCESSED;
+ }
+ }
+
+ public enum SchemaProcessingStatus {
+ NOT_PROCESSED,
+ PARTIALLY_PROCESSED,
+ FULLY_PROCESSED
+ }
+
+ public boolean requestSchemaChange(TableIdentifier tableId, long epoch, long timeoutMs)
+ throws InterruptedException, SchemaCoordinationException {
+ String key = tableId.toString() + "#" + epoch;
+ int expectedAcks = sinkParallelism;
+ if (expectedAcks == 0) {
+ log.warn(
+ "Sink parallelism not registered yet. Cannot coordinate schema change for table {} (epoch {}). "
+ + "Assuming success to avoid deadlock.",
+ tableId,
+ epoch);
+ return true;
+ }
+ log.info(
+ "Requesting schema change for table {} (epoch {}). Waiting for all {} sink subtasks to apply after checkpoint completion.",
+ tableId,
+ epoch,
+ expectedAcks);
+
+ long now = System.currentTimeMillis();
+ TimestampedPendingRequest request =
+ new TimestampedPendingRequest(
+ tableId, epoch, expectedAcks, now, Math.min(timeoutMs, requestTtlMs));
+
+ pendingRequests.put(key, request);
+ receivedAcks.put(key, ConcurrentHashMap.newKeySet());
+
+ try {
+ Boolean result = request.future.get(timeoutMs, TimeUnit.MILLISECONDS);
+ if (result == null) {
+ throw SchemaCoordinationException.conflict(tableId, jobId, jobId);
+ }
+ if (!result) {
+ throw SchemaCoordinationException.conflict(tableId, jobId, jobId);
+ }
+ return result;
+ } catch (TimeoutException e) {
+ log.error(
+ "Schema change request for table {} (epoch {}) timed out after {}ms. "
+ + "Checkpoint may not have completed in time.",
+ tableId,
+ epoch,
+ timeoutMs);
+ request.future.cancel(true);
+ throw SchemaCoordinationException.timeout(tableId, jobId, timeoutMs / 1000, e);
+ } catch (ExecutionException e) {
+ log.error(
+ "Schema change request for table {} (epoch {}) failed with execution exception.",
+ tableId,
+ epoch,
+ e);
+ throw new SchemaEvolutionException(
+ SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
+ e.getMessage(),
+ tableId,
+ jobId,
+ e);
+ } finally {
+ pendingRequests.remove(key);
+ receivedAcks.remove(key);
+ }
+ }
+
+ public void notifySchemaChangeApplied(
+ TableIdentifier tableId, long epoch, int subtaskId, boolean success) {
+ String key = tableId.toString() + "#" + epoch;
+ TimestampedPendingRequest request = pendingRequests.get(key);
+
+ if (request == null) {
+ log.warn(
+ "Received application notification for unknown schema change request: table {} (epoch {}), subtask {}",
+ tableId,
+ epoch,
+ subtaskId);
+ return;
+ }
+
+ // check if this subtask already applied
+ Set<Integer> appliedSubtasks = receivedAcks.get(key);
+ if (appliedSubtasks == null) {
+ log.warn(
+ "Received application notification but no ack set found for table {} (epoch {}), subtask {}",
+ tableId,
+ epoch,
+ subtaskId);
+ return;
+ }
+
+ if (appliedSubtasks.contains(subtaskId)) {
+ log.warn(
+ "Subtask {} already applied schema change for table {} (epoch {}). Ignoring duplicate notification.",
+ subtaskId,
+ tableId,
+ epoch);
+ return;
+ }
+
+ appliedSubtasks.add(subtaskId);
+ log.info(
+ "Subtask {} applied schema change for table {} (epoch {}), success: {}. {}/{} subtasks applied.",
+ subtaskId,
+ tableId,
+ epoch,
+ success,
+ appliedSubtasks.size(),
+ request.expectedAcks);
+
+ if (!success) {
+ request.allSuccess.set(false);
+ }
+
+ // if all subtasks have applied, complete the future
+ if (appliedSubtasks.size() >= request.expectedAcks) {
+ if (request.appliedPhaseCompleteAtomic.compareAndSet(false, true)) {
+ boolean allSuccess = request.allSuccess.get();
+ request.future.complete(allSuccess);
+ log.info(
+ "All {} subtasks have applied schema change for table {} (epoch {}). Completing request with result: {}",
+ request.expectedAcks,
+ tableId,
+ epoch,
+ allSuccess);
+ }
+ }
+ }
+
+ private void performPeriodicCleanup() {
+ try {
+ int cleanedRequests = 0;
+ int cleanedAcks = 0;
+
+ // clean expired pending requests
+ for (Iterator<Map.Entry<String, TimestampedPendingRequest>> iterator =
+ pendingRequests.entrySet().iterator();
+ iterator.hasNext(); ) {
+ Map.Entry<String, TimestampedPendingRequest> entry = iterator.next();
+ if (entry.getValue().isExpired() && entry.getValue().future.isDone()) {
+ iterator.remove();
+ cleanedRequests++;
+ }
+ }
+
+ // clean orphaned ack sets
+ for (Iterator<Map.Entry<String, Set<Integer>>> iterator =
+ receivedAcks.entrySet().iterator();
+ iterator.hasNext(); ) {
+ Map.Entry<String, Set<Integer>> entry = iterator.next();
+ if (!pendingRequests.containsKey(entry.getKey())) {
+ iterator.remove();
+ cleanedAcks++;
+ }
+ }
+
+ if (cleanedRequests > 0 || cleanedAcks > 0) {
+ log.info(
+ "Periodic cleanup for jobId: {} completed. Cleaned {} expired requests, {} orphaned acks. "
+ + "Active requests: {}",
+ jobId,
+ cleanedRequests,
+ cleanedAcks,
+ pendingRequests.size());
+ }
+ } catch (Exception e) {
+ log.error("Error during periodic cleanup for jobId: {}", jobId, e);
+ }
+ }
+
+ private static class TimestampedPendingRequest {
+ final TableIdentifier tableId;
+ final long epoch;
+ final int expectedAcks;
+ final long createdTime;
+ final long ttlMs;
+ CompletableFuture<Boolean> future;
+ final AtomicBoolean allSuccess;
+ final AtomicBoolean appliedPhaseCompleteAtomic = new AtomicBoolean(false);
+
+ TimestampedPendingRequest(
+ TableIdentifier tableId,
+ long epoch,
+ int expectedAcks,
+ long createdTime,
+ long ttlMs) {
+ this.tableId = tableId;
+ this.epoch = epoch;
+ this.expectedAcks = expectedAcks;
+ this.createdTime = createdTime;
+ this.ttlMs = ttlMs;
+ this.future = new CompletableFuture<>();
+ this.allSuccess = new AtomicBoolean(true);
+ }
+
+ boolean isExpired() {
+ return System.currentTimeMillis() - createdTime > ttlMs;
+ }
+ }
+}
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/SinkStateProvider.java
similarity index 58%
copy from seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java
copy to seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/SinkStateProvider.java
index 3272f65419..d782372c7f 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/event/EventType.java
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/coordinator/SinkStateProvider.java
@@ -15,21 +15,20 @@
* limitations under the License.
*/
-package org.apache.seatunnel.api.event;
+package org.apache.seatunnel.translation.flink.schema.coordinator;
-public enum EventType {
- SCHEMA_CHANGE_ADD_COLUMN,
- SCHEMA_CHANGE_DROP_COLUMN,
- SCHEMA_CHANGE_MODIFY_COLUMN,
- SCHEMA_CHANGE_CHANGE_COLUMN,
- SCHEMA_CHANGE_UPDATE_COLUMNS,
- SCHEMA_CHANGE_RENAME_TABLE,
- LIFECYCLE_ENUMERATOR_OPEN,
- LIFECYCLE_ENUMERATOR_CLOSE,
- LIFECYCLE_READER_OPEN,
- LIFECYCLE_READER_CLOSE,
- LIFECYCLE_WRITER_CLOSE,
- READER_MESSAGE_DELAYED,
- JOB_STATUS,
- SCHEMA_CHANGE_FLUSH,
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+
+/**
+ * Interface for sink subtasks to provide their schema processing state This allows the coordinator
+ * to query the actual processing state during recovery
+ */
+public interface SinkStateProvider {
+ /**
+ * Get the last processed epoch for a specific table
+ *
+ * @param tableId the table identifier
+ * @return the last processed epoch, or null if never processed
+ */
+ Long getLastProcessedEpoch(TableIdentifier tableId);
}
diff --git a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
index b5dd8567e0..e7cc3c7860 100644
--- a/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
+++ b/seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java
@@ -25,11 +25,11 @@ import org.apache.seatunnel.api.sink.MultiTableResourceManager;
import org.apache.seatunnel.api.sink.SupportResourceShare;
import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSinkWriter;
import org.apache.seatunnel.api.sink.event.WriterCloseEvent;
-import org.apache.seatunnel.api.table.schema.event.FlushEvent;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
import org.apache.seatunnel.api.table.schema.exception.SinkWriterSchemaException;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.translation.flink.schema.coordinator.LocalSchemaCoordinator;
import org.apache.flink.api.connector.sink.Sink;
import org.apache.flink.api.connector.sink.SinkWriter;
@@ -37,7 +37,6 @@ import org.apache.flink.api.connector.sink.SinkWriter;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
-import java.io.InvalidClassException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -94,68 +93,110 @@ public class FlinkSinkWriter<InputT, CommT, WriterStateT>
if (element == null) {
return;
}
- if (element instanceof SeaTunnelRow) {
- SeaTunnelRow seaTunnelRow = (SeaTunnelRow) element;
- Map<String, Object> options = seaTunnelRow.getOptions();
-
- if (options != null && options.containsKey("flush_event")) {
- FlushEvent flushEvent = (FlushEvent) options.get("flush_event");
- log.info(
- "FlinkSinkWriter detected FlushEvent for table: {}",
- flushEvent.tableIdentifier());
-
- if (sinkWriter instanceof SupportSchemaEvolutionSinkWriter) {
- try {
- ((SupportSchemaEvolutionSinkWriter) sinkWriter)
- .handleFlushEvent(flushEvent);
- log.info(
- "FlinkSinkWriter handled FlushEvent for table: {}",
- flushEvent.tableIdentifier());
- } catch (Exception e) {
- log.error("Failed to handle flush event", e);
- throw new SinkWriterSchemaException(
- SchemaEvolutionErrorCode.FLUSH_EVENT_PROCESSING_FAILED,
- "Failed to handle flush event in Flink sink writer",
- flushEvent.tableIdentifier(),
- flushEvent.getJobId(),
- e);
- }
- }
- }
- if (options != null && options.containsKey("schema_change_event")) {
- SchemaChangeEvent schemaChangeEvent =
- (SchemaChangeEvent) options.get("schema_change_event");
- log.info(
- "FlinkSinkWriter detected SchemaChangeEvent for table: {}",
- schemaChangeEvent.tableIdentifier());
-
- if (sinkWriter instanceof SupportSchemaEvolutionSinkWriter) {
- try {
- ((SupportSchemaEvolutionSinkWriter) sinkWriter)
- .applySchemaChange(schemaChangeEvent);
- log.info(
- "FlinkSinkWriter applied SchemaChangeEvent for table: {}",
- schemaChangeEvent.tableIdentifier());
- } catch (Exception e) {
- log.error("Failed to apply schema change", e);
- throw new SinkWriterSchemaException(
- SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
- "Failed to apply schema change in Flink sink writer",
- schemaChangeEvent.tableIdentifier(),
- schemaChangeEvent.getJobId(),
- e);
- }
- }
+ SeaTunnelRow seaTunnelRow = (SeaTunnelRow) element;
+ Map<String, Object> options = seaTunnelRow.getOptions();
+
+ if (options != null && handleControlMessage(options)) {
+ return;
+ }
+
+ sinkWriter.write(seaTunnelRow);
+ sinkWriteCount.inc();
+ sinkWriteBytes.inc(seaTunnelRow.getBytesSize());
+ sinkWriterQPS.markEvent();
+ }
+
+ private boolean handleControlMessage(Map<String, Object> options) throws IOException {
+ if (options.containsKey("schema_change_ack")) {
+ log.debug("FlinkSinkWriter received schema change ack - filtering out control message");
+ return true;
+ }
+
+ if (options.containsKey("schema_change_event")) {
+ handleSchemaChangeEvent(
+ (SchemaChangeEvent) options.get("schema_change_event"), options);
+ return true;
+ }
+
+ return false;
+ }
+
+ private void handleSchemaChangeEvent(
+ SchemaChangeEvent schemaChangeEvent, Map<String, Object> options) throws IOException {
+ log.info(
+ "FlinkSinkWriter applying SchemaChangeEvent for table: {}",
+ schemaChangeEvent.tableIdentifier());
+
+ sinkWriter.prepareCommit();
+ if (!(sinkWriter instanceof SupportSchemaEvolutionSinkWriter)) {
+ log.warn(
+ "Sink writer {} does not support schema evolution, ignoring SchemaChangeEvent for table: {}",
+ sinkWriter.getClass().getSimpleName(),
+ schemaChangeEvent.tableIdentifier());
+ return;
+ }
+
+ Long subtaskIdObj = (Long) options.get("schema_subtask_id");
+ int subtaskId = subtaskIdObj != null ? subtaskIdObj.intValue() : -1;
+ long epoch = schemaChangeEvent.getCreatedTime();
+ boolean success = false;
+
+ try {
+ ((SupportSchemaEvolutionSinkWriter) sinkWriter).applySchemaChange(schemaChangeEvent);
+ log.info(
+ "FlinkSinkWriter successfully applied SchemaChangeEvent for table: {}",
+ schemaChangeEvent.tableIdentifier());
+ success = true;
+ } catch (Exception e) {
+ log.error(
+ "Failed to apply schema change for table: {}",
+ schemaChangeEvent.tableIdentifier(),
+ e);
+ } finally {
+ sendSchemaChangeAck(schemaChangeEvent, epoch, subtaskId, success);
+ }
+
+ if (!success) {
+ throw new SinkWriterSchemaException(
+ SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
+ "Failed to apply schema change in Flink sink writer",
+ schemaChangeEvent.tableIdentifier(),
+ schemaChangeEvent.getJobId(),
+ null);
+ }
+ }
+
+ private void sendSchemaChangeAck(
+ SchemaChangeEvent schemaChangeEvent, long epoch, int subtaskId, boolean success) {
+ if (subtaskId < 0) {
+ log.warn(
+ "FlinkSinkWriter cannot send ack: subtask ID not found in schema change event options");
+ return;
+ }
+
+ try {
+ String jobId = schemaChangeEvent.getJobId();
+ if (jobId == null || jobId.trim().isEmpty()) {
+ jobId = "unknown-job";
+ log.warn("SchemaChangeEvent has no jobId, using default: {}", jobId);
}
- sinkWriter.write((SeaTunnelRow) element);
- sinkWriteCount.inc();
- sinkWriteBytes.inc(((SeaTunnelRow) element).getBytesSize());
- sinkWriterQPS.markEvent();
- } else {
- throw new InvalidClassException(
- "only support SeaTunnelRow at now, the element Class is " + element.getClass());
+ LocalSchemaCoordinator coordinator = LocalSchemaCoordinator.getInstance(jobId);
+ coordinator.notifySchemaChangeApplied(
+ schemaChangeEvent.tableIdentifier(), epoch, subtaskId, success);
+ log.info(
+ "FlinkSinkWriter sent schema change ack to coordinator for table {} (epoch {}), subtask {}, success: {}",
+ schemaChangeEvent.tableIdentifier(),
+ epoch,
+ subtaskId,
+ success);
+ } catch (Exception e) {
+ log.error(
+ "Failed to send schema change ack to coordinator for table {} (epoch {})",
+ schemaChangeEvent.tableIdentifier(),
+ epoch,
+ e);
}
}