MartijnVisser commented on code in PR #262:
URL:
https://github.com/apache/flink-connector-jdbc/pull/262#discussion_r4670867573
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/datasource/transactions/xa/XaTransaction.java:
##########
@@ -141,6 +156,90 @@ public void checkState() {
"inconsistent internal state");
}
+ /**
+ * Rolls back the prepared transactions left behind from the given
checkpoint on. Their records
+ * are replayed, and the committer only commits transactions of earlier
checkpoints.
+ */
+ public void rollbackPreparedTxs(long checkpointId) {
+ Collection<Xid> recovered;
+ try {
+ recovered = xaConnectionProvider.recover();
+ } catch (Exception e) {
+ LOG.warn(
+ "unable to recover prepared transactions, those left
behind that aren't in the"
+ + " restored state keep their locks",
+ e);
+
hangingXids.addAll(failOrRollback(unownedHangingXids).getForRetry());
+ return;
+ }
+ for (Xid xid : recovered) {
+ if (isLeftoverFromCheckpoint(xid, checkpointId)) {
+ LOG.info("rolling back a leftover transaction, xid={}", xid);
+ try {
+ xaConnectionProvider.rollback(xid);
+ } catch (RuntimeException e) {
+ if (isPrepared(xid)) {
Review Comment:
Fixed: the listing failure goes into the rollback failure as a suppressed
exception (`testRollbackPreparedTxsKeepsRollbackFailureIfListingFails`).
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/datasource/transactions/xa/XaTransaction.java:
##########
@@ -141,6 +156,90 @@ public void checkState() {
"inconsistent internal state");
}
+ /**
+ * Rolls back the prepared transactions left behind from the given
checkpoint on. Their records
+ * are replayed, and the committer only commits transactions of earlier
checkpoints.
+ */
+ public void rollbackPreparedTxs(long checkpointId) {
+ Collection<Xid> recovered;
+ try {
+ recovered = xaConnectionProvider.recover();
+ } catch (Exception e) {
+ LOG.warn(
+ "unable to recover prepared transactions, those left
behind that aren't in the"
+ + " restored state keep their locks",
+ e);
+
hangingXids.addAll(failOrRollback(unownedHangingXids).getForRetry());
+ return;
+ }
+ for (Xid xid : recovered) {
+ if (isLeftoverFromCheckpoint(xid, checkpointId)) {
+ LOG.info("rolling back a leftover transaction, xid={}", xid);
+ try {
+ xaConnectionProvider.rollback(xid);
+ } catch (RuntimeException e) {
+ if (isPrepared(xid)) {
+ throw e;
+ }
+ LOG.info("leftover transaction is gone already, xid={}",
xid);
+ }
+ }
+ }
+ }
+
+ /**
+ * A transaction id names the job, the subtask and the parallelism, and
the prefix if there is
+ * one. Without a prefix this writer only rolls back its own transactions:
another exactly-once
+ * sink of the job at the same parallelism can't run, as it starts the
same xids, and at another
+ * parallelism its xids differ only in the parallelism.
+ *
+ * <p>With a prefix it also rolls back those of earlier jobs and
parallelisms under the prefix,
+ * of the subtasks whose index is its own modulo the parallelism, so each
has a single owner as
+ * long as all writers can list them. At the same job and parallelism that
is only its own, as
+ * in BATCH the other writers may have prepared their transactions for the
committer already.
+ */
+ private boolean isLeftoverFromCheckpoint(Xid xid, long checkpointId) {
+ TransactionId transactionId;
+ try {
+ transactionId =
+ TransactionId.createFromXid(
+ xid.getFormatId(),
+ xid.getGlobalTransactionId(),
+ xid.getBranchQualifier());
+ } catch (IOException e) {
+ return false;
+ }
+ if (transactionId.getCheckpointId() < checkpointId) {
+ return false;
+ }
+ if (xid.getFormatId() == baseTransaction.getFormatId()
+ && Arrays.equals(
+ xid.getGlobalTransactionId(),
baseTransaction.getGlobalTransactionId())
+ && transactionId.getNumberOfSubtasks() ==
baseTransaction.getNumberOfSubtasks()) {
+ return true;
+ }
+ return baseTransaction.getPrefixBytes() != null &&
isOwnedUnderPrefix(transactionId);
+ }
+
+ private boolean isOwnedUnderPrefix(TransactionId transactionId) {
Review Comment:
Moved into the method: `owns()` checks the prefix itself now. An xid under a
prefix only matches a writer with that prefix, and xids without a prefix go
through the job id check.
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/core/datastream/sink/writer/JdbcWriterStateSerializer.java:
##########
@@ -38,30 +42,44 @@ public class JdbcWriterStateSerializer implements
SimpleVersionedSerializer<Jdbc
@Override
public int getVersion() {
- return 2;
+ // version 3 adds the transaction id prefix
+ return 3;
}
@Override
public byte[] serialize(JdbcWriterState state) throws IOException {
- final DataOutputSerializer out = new DataOutputSerializer(1);
- out.writeInt(state.getHanging().size());
- for (TransactionId tid : state.getHanging()) {
- byte[] tIdBytes = tid.serialize();
- out.writeByte(tIdBytes.length);
- out.write(tIdBytes, 0, tIdBytes.length);
- }
- out.writeInt(state.getPrepared().size());
- for (TransactionId tid : state.getPrepared()) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(bytes);
+ writeTransactionIds(out, state.getHanging());
+ writeTransactionIds(out, state.getPrepared());
+ out.flush();
+ return bytes.toByteArray();
+ }
+
+ private static void writeTransactionIds(
+ DataOutputStream out, Collection<TransactionId> transactionIds)
throws IOException {
+ out.writeInt(transactionIds.size());
+ for (TransactionId tid : transactionIds) {
byte[] tIdBytes = tid.serialize();
out.writeByte(tIdBytes.length);
- out.write(tIdBytes, 0, tIdBytes.length);
+ out.write(tIdBytes);
+ byte[] prefix = tid.getPrefixBytes();
+ out.writeByte(prefix == null ? -1 : prefix.length);
Review Comment:
Changed to an int length, with -1 for no prefix; version 3 isn't released,
so the layout can still change. `testSerDeWithPrefixOfLength` covers 0 to 256
bytes, and `readTransactionIds` now throws an `IOException` for a negative or
impossible size or prefix length (`testDeserializeCorruptState`).
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/datasource/transactions/xa/XaTransaction.java:
##########
@@ -122,16 +112,41 @@ public void close() throws Exception {
xaConnectionProvider.close();
currentTid = null;
hangingXids = null;
+ unownedHangingXids = null;
preparedXids = null;
}
+ /**
+ * Keeps only the hanging transactions of this job, which {@link #open}
rolls back. Those of
+ * another job may belong to a job that still runs and is about to commit
them, for example the
+ * job that took the savepoint this one restores. With a prefix it keeps
those under the prefix
+ * that it owns, see {@link #isLeftoverFromCheckpoint}, which also covers
earlier jobs; rolling
+ * them back here needs no listing of the prepared transactions.
+ */
public void recoverState(JdbcWriterState state) {
- hangingXids = new LinkedList<>(state.getHanging());
+ hangingXids = new LinkedList<>();
+ unownedHangingXids = new ArrayList<>();
+ for (TransactionId hanging : state.getHanging()) {
+ if (baseTransaction.getPrefixBytes() == null
+ ? Arrays.equals(hanging.getJobId(),
baseTransaction.getJobId())
+ : isOwnedUnderPrefix(hanging)) {
+ hangingXids.add(hanging);
+ } else if (baseTransaction.getPrefixBytes() != null
Review Comment:
That fallback is gone since the rebase on the current head of #259
(FLINK-41060): a writer that can't list the prepared transactions now fails
instead of warning. So the owner either rolls the xid back or fails, and the
restart restores the same checkpoint, whose state still names it. Re-appending
it to another writer's state would give it two owners.
`testRestoredHangingOfOtherSubtaskIsRolledBackByItsOwner` covers this, and
fails on 45f46811.
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/JdbcExactlyOnceOptions.java:
##########
@@ -109,12 +123,16 @@ public static class JDBCExactlyOnceOptionsBuilder {
private boolean allowOutOfOrderCommits =
DEFAULT_ALLOW_OUT_OF_ORDER_COMMITS;
private Optional<Integer> timeoutSec = Optional.empty();
private boolean transactionPerConnection =
DEFAULT_TRANSACTION_PER_CONNECTION;
+ @Nullable private String transactionIdPrefix;
/**
- * Toggle discovery and rollback of prepared transactions upon
recovery to prevent new
- * transactions from being blocked by the older ones. Each subtask
rollbacks its own
- * transaction. This flag must be disabled when rescaling to prevent
data loss.
+ * Was meant to toggle the rollback of prepared transactions on
recovery.
+ *
+ * @deprecated Has no effect. A restarted writer always rolls back the
prepared transactions
+ * left behind that belong to it, and only warns if it can't list
them; set {@link
Review Comment:
Updated: the Javadoc now says to drop the call, also where it was set to
false for a rescale.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]