eskabetxe commented on code in PR #262:
URL:
https://github.com/apache/flink-connector-jdbc/pull/262#discussion_r4643695994
##########
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);
Review Comment:
Same gap for the listed prepared transactions: with a prefix, the first
branch requires xid.getFormatId() == baseTransaction.getFormatId() (202 vs
203), so leftovers from before the prefix are never rolled back. Suggest a
fallback for prefix-less ids of the same job/subtask/parallelism, e.g.:
```
if (baseTransaction.getPrefixBytes() != null
&& transactionId.getPrefixBytes() == null
&& Arrays.equals(transactionId.getJobId(),
baseTransaction.getJobId())
&& transactionId.getSubtaskId() == baseTransaction.getSubtaskId()
&& transactionId.getNumberOfSubtasks() ==
baseTransaction.getNumberOfSubtasks()) {
return true;
}
```
##########
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
Review Comment:
When the sink has a prefix, a job that adopts it stops cleaning up its own
leftovers created before the prefix (formatId 202, no prefix bytes), because
isOwnedUnderPrefix compares prefix bytes and null != "books". A jobId match
cannot be another job that "may still run", it is this very job. So on the most
likely adoption path (add a prefix, restart from the last checkpoint) the
failed attempt's prepared transactions keep their locks, and the restarted job
can block against its own rows until lock_timeout.
Can we keep the jobId match as an additional "own" condition?
I added two tests locally (prepare(jobId, 0, 1, 5, 1) then restore/rollback
with prefix "books"), both fail on this branch and pass with
Arrays.equals(hanging.getJobId(), baseTransaction.getJobId()) ||
isOwnedUnderPrefix(hanging), with all 17 existing DerbyXaTransactionTest cases
still green.
##########
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:
out.writeByte(prefix == null ? -1 : prefix.length) uses a signed byte as
flag and length. It works while the prefix is capped at 43 bytes, but silently
desynchronises the stream if a length ever reaches 128 (read back as null,
remaining bytes left unread). A writeInt, or a boolean flag plus a length,
would be safer.
Related nit at line 92: readTransactionIds doesn't validate size >= 0, so
corrupt state throws IllegalArgumentException from new ArrayList<>(size)
instead of an IOException.
##########
flink-connector-jdbc-core/src/main/java/org/apache/flink/connector/jdbc/core/datastream/sink/writer/JdbcWriter.java:
##########
@@ -113,7 +117,16 @@ public JdbcWriter(
exactlyOnceOptions,
transactionId,
((XaConnectionProvider) connectionProvider));
+ if (!exactlyOnceOptions.getTransactionIdPrefix().isPresent()
+ && transactionId.getSubtaskId() == 0) {
Review Comment:
This warnings fires for every exactly-once sink start without a prefix, i.e.
for every existing user and also for brand-new jobs where nothing was ever left
behind. It reads like an error but is only a recommendation. Can we either gate
it on initContext.getRestoredCheckpointId().isPresent(), or log it from
recoverState/rollbackPreparedTxs only when something was actually skipped? Also
the example call is missing its argument: withTransactionIdPrefix("my-sink").
##########
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:
isPrepared(xid) runs xaConnectionProvider.recover() inside the catch
(RuntimeException e). If that second listing also fails (which is the usual
reason the rollback failed) the new exception replaces the original, so the job
reports the wrong cause and the rollback error is lost.
Suggest catching it and rethrowing the original with e.addSuppressed(...).
##########
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:
Since withRecoveredAndRollback is now a no-op, users who set it to false
precisely because of the old "must be disabled when rescaling" warning will
keep carrying that call. Could the deprecation javadoc say explicitly that the
flag can be dropped, instead of just "has no effect"?
##########
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:
isOwnedUnderPrefix returns true for two prefix-less ids, since
Arrays.equals(null, null) is true. It is only safe today because every caller
checks baseTransaction.getPrefixBytes() != null first; if we relax those guards
(see the two comments above), please move that check inside this method.
##########
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:
Question: hanging xids under the prefix that this writer doesn't own are
deliberately kept out of hangingXids, so they never reach the writer state.
They are recovered only by their owner listing prepared transactions at open.
if that owner can't list them (the exact case this branch anticipates at
line 172), nothing holds them for retry and they are stranded until manual
cleanup. Is that leak acceptable, or should they be re-appended to the state
best-effort?
--
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]