Elffuss BraidHub

kikocis/java-driver public

Merge pull request #696 from datastax/java1212

JAVA-1212: Don't retry non-idempotent statements by default.
Changeset75ab152b44cc640f23fbc3fb500f23eeef46a9326d566a6f24b2660a51442f2d
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-18 13:50 -07:00
CommitterGitHub <noreply@github.com> · 2016-07-18 13:50 -07:00
Parentsd66ff12cdb1a, 8597902e03c2

Browse the files at this changeset

9 files changed

modified changelog/README.md +1 −0
@@ -8,6 +8,7 @@
88 - [improvement] JAVA-1233: Update Snappy to 1.1.2.6.
99 - [bug] JAVA-1161: Preserve full time zone info in ZonedDateTimeCodec and DateTimeCodec.
1010 - [new feature] JAVA-1157: Allow asynchronous paging of Mapper Result.
11+- [improvement] JAVA-1212: Don't retry non-idempotent statements by default.
1112
1213 Merged from 3.0.x branch:
1314
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +57 −44
@@ -42,6 +42,7 @@
4242 */
4343 class RequestHandler {
4444 private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
45+ private static final AtomicBoolean WARNED_IDEMPOTENT = new AtomicBoolean();
4546
4647 final String id;
4748
@@ -353,6 +354,38 @@
353354 connection.release();
354355 }
355356
357+ private RetryPolicy.RetryDecision computeRetryDecisionOnRequestError(DriverException exception) {
358+ RetryPolicy.RetryDecision decision;
359+ if (statement.isIdempotentWithDefault(manager.cluster.getConfiguration().getQueryOptions())) {
360+ decision = retryPolicy().onRequestError(statement, request().consistency(), exception, retriesByPolicy);
361+ } else {
362+ logIdempotenceWarning();
363+ decision = RetryPolicy.RetryDecision.rethrow();
364+ }
365+ if (metricsEnabled()) {
366+ if (exception instanceof OperationTimedOutException) {
367+ metrics().getErrorMetrics().getClientTimeouts().inc();
368+ if (decision.getType() == Type.RETRY)
369+ metrics().getErrorMetrics().getRetriesOnClientTimeout().inc();
370+ if (decision.getType() == Type.IGNORE)
371+ metrics().getErrorMetrics().getIgnoresOnClientTimeout().inc();
372+ } else if (exception instanceof ConnectionException) {
373+ metrics().getErrorMetrics().getConnectionErrors().inc();
374+ if (decision.getType() == Type.RETRY)
375+ metrics().getErrorMetrics().getRetriesOnConnectionError().inc();
376+ if (decision.getType() == Type.IGNORE)
377+ metrics().getErrorMetrics().getIgnoresOnConnectionError().inc();
378+ } else {
379+ metrics().getErrorMetrics().getOthers().inc();
380+ if (decision.getType() == Type.RETRY)
381+ metrics().getErrorMetrics().getRetriesOnOtherErrors().inc();
382+ if (decision.getType() == Type.IGNORE)
383+ metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc();
384+ }
385+ }
386+ return decision;
387+ }
388+
356389 private void processRetryDecision(RetryPolicy.RetryDecision retryDecision, Connection connection, Exception exceptionToReport) {
357390 switch (retryDecision.getType()) {
358391 case RETRY:
@@ -490,12 +523,17 @@
490523 connection.release();
491524 assert err.infos instanceof WriteTimeoutException;
492525 WriteTimeoutException wte = (WriteTimeoutException) err.infos;
493- retry = retryPolicy.onWriteTimeout(statement,
494- wte.getConsistencyLevel(),
495- wte.getWriteType(),
496- wte.getRequiredAcknowledgements(),
497- wte.getReceivedAcknowledgements(),
498- retriesByPolicy);
526+ if (statement.isIdempotentWithDefault(manager.cluster.getConfiguration().getQueryOptions()))
527+ retry = retryPolicy.onWriteTimeout(statement,
528+ wte.getConsistencyLevel(),
529+ wte.getWriteType(),
530+ wte.getRequiredAcknowledgements(),
531+ wte.getReceivedAcknowledgements(),
532+ retriesByPolicy);
533+ else {
534+ logIdempotenceWarning();
535+ retry = RetryPolicy.RetryDecision.rethrow();
536+ }
499537 if (metricsEnabled()) {
500538 metrics().getErrorMetrics().getWriteTimeouts().inc();
501539 if (retry.getType() == Type.RETRY)
@@ -525,16 +563,7 @@
525563 connection.release();
526564 assert exceptionToReport instanceof OverloadedException;
527565 logger.warn("Host {} is overloaded.", connection.address);
528- retry = retryPolicy.onRequestError(statement,
529- request().consistency(),
530- (OverloadedException) exceptionToReport, retriesByPolicy);
531- if (metricsEnabled()) {
532- metrics().getErrorMetrics().getOthers().inc();
533- if (retry.getType() == Type.RETRY)
534- metrics().getErrorMetrics().getRetriesOnOtherErrors().inc();
535- if (retry.getType() == Type.IGNORE)
536- metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc();
537- }
566+ retry = computeRetryDecisionOnRequestError((OverloadedException) exceptionToReport);
538567 break;
539568 case SERVER_ERROR:
540569 connection.release();
@@ -542,16 +571,7 @@
542571 logger.warn("{} replied with server error ({}), defuncting connection.", connection.address, err.message);
543572 // Defunct connection
544573 connection.defunct(exceptionToReport);
545- retry = retryPolicy.onRequestError(statement,
546- request().consistency(),
547- (ServerError) exceptionToReport, retriesByPolicy);
548- if (metricsEnabled()) {
549- metrics().getErrorMetrics().getOthers().inc();
550- if (retry.getType() == Type.RETRY)
551- metrics().getErrorMetrics().getRetriesOnOtherErrors().inc();
552- if (retry.getType() == Type.IGNORE)
553- metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc();
554- }
574+ retry = computeRetryDecisionOnRequestError((ServerError) exceptionToReport);
555575 break;
556576 case IS_BOOTSTRAPPING:
557577 connection.release();
@@ -716,15 +736,7 @@
716736 connection.release();
717737
718738 if (exception instanceof ConnectionException) {
719- RetryPolicy retryPolicy = retryPolicy();
720- RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), (ConnectionException) exception, retriesByPolicy);
721- if (metricsEnabled()) {
722- metrics().getErrorMetrics().getConnectionErrors().inc();
723- if (decision.getType() == Type.RETRY)
724- metrics().getErrorMetrics().getRetriesOnConnectionError().inc();
725- if (decision.getType() == Type.IGNORE)
726- metrics().getErrorMetrics().getIgnoresOnConnectionError().inc();
727- }
739+ RetryPolicy.RetryDecision decision = computeRetryDecisionOnRequestError((ConnectionException) exception);
728740 processRetryDecision(decision, connection, exception);
729741 return;
730742 }
@@ -755,15 +767,7 @@
755767 try {
756768 connection.release();
757769
758- RetryPolicy retryPolicy = retryPolicy();
759- RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), timeoutException, retriesByPolicy);
760- if (metricsEnabled()) {
761- metrics().getErrorMetrics().getClientTimeouts().inc();
762- if (decision.getType() == Type.RETRY)
763- metrics().getErrorMetrics().getRetriesOnClientTimeout().inc();
764- if (decision.getType() == Type.IGNORE)
765- metrics().getErrorMetrics().getIgnoresOnClientTimeout().inc();
766- }
770+ RetryPolicy.RetryDecision decision = computeRetryDecisionOnRequestError(timeoutException);
767771 processRetryDecision(decision, connection, timeoutException);
768772 } catch (Exception e) {
769773 // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
@@ -789,6 +793,15 @@
789793 }
790794 }
791795
796+ private void logIdempotenceWarning() {
797+ if (WARNED_IDEMPOTENT.compareAndSet(false, true))
798+ logger.warn("Not retrying statement because it is not idempotent (this message will be logged only once). " +
799+ "Note that this version of the driver changes the default retry behavior for non-idempotent " +
800+ "statements: they won't be automatically retried anymore. The driver marks statements " +
801+ "non-idempotent by default, so you should explicitly call setIdempotent(true) if your statements " +
802+ "are safe to retry. See http://goo.gl/4HrSby for more details.");
803+ }
804+
792805 /**
793806 * The state of a SpeculativeExecution.
794807 * <p/>
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +8 −3
@@ -490,9 +490,14 @@
490490 * Whether this statement is idempotent, i.e. whether it can be applied multiple times
491491 * without changing the result beyond the initial application.
492492 * <p/>
493- * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
494- * If a statement is <em>not idempotent</em>, the driver will not schedule speculative
495- * executions for it.
493+ * If a statement is <em>not idempotent</em>, the driver will ensure that it never gets executed more than once,
494+ * which means:
495+ * <ul>
496+ * <li>avoiding {@link RetryPolicy retries} on write timeouts or request errors;</li>
497+ * <li>never scheduling {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
498+ * </li>
499+ * </ul>
500+ * (this behavior is implemented in the driver internals, the corresponding policies will not even be invoked).
496501 * <p/>
497502 * Note that this method can return {@code null}, in which case the driver will default to
498503 * {@link QueryOptions#getDefaultIdempotence()}.
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +0 −6
@@ -114,12 +114,6 @@
114114
115115 /**
116116 * {@inheritDoc}
117- * <p/>
118- * For historical reasons, this implementation triggers a retry on the next host in the query plan
119- * with the same consistency level, regardless of the statement's idempotence.
120- * Note that this breaks the general rule
121- * stated in {@link RetryPolicy#onRequestError(Statement, ConsistencyLevel, DriverException, int)}:
122- * "a retry should only be attempted if the request is known to be idempotent".
123117 */
124118 @Override
125119 public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +4 −0
@@ -25,7 +25,11 @@
2525 * if the statement is deemed non-idempotent (see {@link #isIdempotent(Statement)}).
2626 * <p/>
2727 * For all other cases, this policy delegates the decision to the child policy.
28+ *
29+ * @deprecated As of version 3.1.0, the driver doesn't retry non-idempotent statements for write timeouts or unexpected
30+ * errors anymore. It is no longer necessary to wrap your retry policies in this policy.
2831 */
32+@Deprecated
2933 public class IdempotenceAwareRetryPolicy implements RetryPolicy {
3034
3135 private final RetryPolicy childPolicy;
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +13 −7
@@ -41,6 +41,10 @@
4141 * </ul>
4242 */
4343 class RetryDecision {
44+
45+ private static final RetryDecision RETHROW_DECISION = new RetryDecision(Type.RETHROW, null, true);
46+ private static final RetryDecision IGNORE_DECISION = new RetryDecision(Type.IGNORE, null, true);
47+
4448 /**
4549 * The types of retry decisions.
4650 */
@@ -99,7 +103,7 @@
99103 * @return a {@link RetryDecision.Type#RETHROW} retry decision.
100104 */
101105 public static RetryDecision rethrow() {
102- return new RetryDecision(Type.RETHROW, null, true);
106+ return RETHROW_DECISION;
103107 }
104108
105109 /**
@@ -128,7 +132,7 @@
128132 * @return an {@link RetryDecision.Type#IGNORE} retry decision.
129133 */
130134 public static RetryDecision ignore() {
131- return new RetryDecision(Type.IGNORE, null, true);
135+ return IGNORE_DECISION;
132136 }
133137
134138 /**
@@ -194,6 +198,9 @@
194198
195199 /**
196200 * Defines whether to retry and at which consistency level on a write timeout.
201+ * <p/>
202+ * Note that if a statement is {@link Statement#isIdempotent() not idempotent}, the driver will never retry it on a
203+ * write timeout (this method won't even be called).
197204 *
198205 * @param statement the original query that timed out.
199206 * @param cl the requested consistency level of the write that timed out.
@@ -247,13 +254,12 @@
247254 * <li>On a client timeout, while waiting for the server response
248255 * (see {@link SocketOptions#getReadTimeoutMillis()});</li>
249256 * <li>On a connection error (socket closed, etc.);</li>
250- * <li>When the contacted host replies with an error, such as
251- * {@code OVERLOADED}, {@code IS_BOOTSTRAPPING}, {@code SERVER_ERROR}, etc.</li>
257+ * <li>When the contacted host replies with an {@code OVERLOADED} error or a {@code SERVER_ERROR}.</li>
252258 * </ol>
253259 * <p/>
254- * Note that when this method is invoked, <em>the driver cannot guarantee that the mutation has
255- * been effectively applied server-side</em>; a retry should only be attempted if the request
256- * is known to be idempotent.
260+ * Note that when such an error occurs, there is no guarantee that the mutation has been applied server-side or not.
261+ * Therefore, if a statement is {@link Statement#isIdempotent() not idempotent}, the driver will never retry it
262+ * (this method won't even be called).
257263 *
258264 * @param statement the original query that failed.
259265 * @param cl the requested consistency level for the operation.
modified manual/idempotence/README.md +5 −5
@@ -8,8 +8,9 @@
88 * `update my_table set list_col = [1] + list_col where pk = 1` is not idempotent: if `list_col` was initially empty,
99 it will contain `[1]` after the first execution, `[1, 1]` after the second, etc.
1010
11-Idempotence matters for [retries](../retries/) and [speculative query executions](../speculative_execution/). The
12-corresponding policies inspect the [Statement#isIdempotent()][isIdempotent] flag.
11+Idempotence matters for [retries](../retries/) and [speculative query executions](../speculative_execution/). The driver
12+will bypass those features if the [Statement#isIdempotent()][isIdempotent] flag is set to `false`, to ensure that the
13+statement does not get executed more than once.
1314
1415 In most cases, you must set that flag manually. The driver does not parse query strings, so it can't infer it
1516 automatically (except for statements coming from the query builder, see below).
@@ -121,9 +122,8 @@
121122 But overall the column changed from 1 to 2. There is no ordering of the two operations that can explain that change. We
122123 broke linearizability by doing a transparent retry at step 6.
123124
124-To avoid this, the driver considers lightweight transactions as non-idempotent, and provides a
125-[retry policy](../retries/) that doesn't retry non-idempotent statements. If linearizability is important for you, you
126-should use that policy, and ensure that lightweight transactions are appropriately flagged.
125+If linearizability is important for you, you should ensure that lightweight transactions are appropriately flagged as
126+not idempotent.
127127
128128 [isIdempotent]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#isIdempotent--
129129 [setDefaultIdempotence]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setDefaultIdempotence-boolean-
modified manual/retries/README.md +16 −27
@@ -79,7 +79,6 @@
7979 This is similar to `onReadTimeout`, but for write operations. The reason reads and writes are handled separately is
8080 because a read is obviously a non mutating operation, whereas a write is likely to be. If a write times out at the
8181 coordinator level, there is no way to know whether the mutation was applied or not on the non-answering replica.
82-Policy implementations are usually more conservative in `onWriteTimeout` in case the write was not idempotent.
8382
8483 If the policy rethrows the error, the user code will get a [WriteTimeoutException].
8584
@@ -98,9 +97,6 @@
9897 high; the coordinator temporarily refuses writes for these replicas (see [hinted handoffs] in the Cassandra
9998 documentation).
10099
101-In all these cases, there is no absolute certainty that the request was not applied by a host, so implementations must
102-consider the risk of retrying non-idempotent statements.
103-
104100 ### Hard-coded rules
105101
106102 There are a few cases where retrying is always the right thing to do. These are not covered by `RetryPolicy`, but
@@ -130,30 +126,24 @@
130126
131127 ### Retries and idempotence
132128
133-Retry policies should avoid retrying [idempotent queries] when it's not clear whether the query was applied or not.
134-
135-It's always safe to retry in `onReadTimeout`, since by definition we know that the query is a read, which doesn't mutate
136-any data. Similarly, `onUnavailable` is safe: the coordinator is telling us that it didn't find enough replicas, so we
137-know that it didn't try to apply the query.
138-
139-`onWriteTimeout` is not safe. The default retry policy is very conservative (it only retries batch log writes) so it
140-will never cause any issue. Custom implementations should check the statements' idempotent flag.
141-
142-`onRequestError` isn't safe either.
143-
144-**For historical reasons, the built-in retry policy implementations do not check the idempotent flag in
145-`onRequestError`**. This is based on the fact that:
129+If a query is [not idempotent][idempotence], the driver will not retry it if that could produce inconsistent results:
146130
147-* previous versions of the driver (which did `onRequestError` internally) didn't check the flag either;
148-* the majority of queries in an application should be idempotent;
149-* statements start out as non-idempotent by default.
131+* retrying in `onReadTimeout` is always safe, since by definition this error indicates that the query was a read, which
132+ didn't mutate any data;
133+* similarly, `onUnavailable` is safe: the coordinator is telling us that it didn't find enough replicas, so we know that
134+ it didn't try to apply the query.
135+* `onWriteTimeout` is **not safe**: some replicas failed to reply to the coordinator in time, but they might still have
136+ applied the mutation;
137+* `onRequestError` is **not safe** either: the query might have been applied before the error occurred. In particular,
138+ an `OperationTimedOutException` could be caused by a network issue that prevented a successful response to come back
139+ to the client.
150140
151-If `onRequestError` enforced idempotence strictly, this would cause a lot of queries that were legitimately retried with
152-previous driver versions to not be retried anymore. This would be a big behavioral change, so we decided to prefer
153-consistency with previous versions.
141+Therefore, the driver does not retry after a write timeout or request error if the statement is not idempotent. This is
142+handled internally, the retry policy methods are not even invoked in those cases.
154143
155-If you prefer strict handling of the idempotent flag, you can wrap your retry policy into an
156-[IdempotenceAwareRetryPolicy]. Make sure to position the flag properly on all statements.
144+Note that this behavior was introduced in version 3.1.0 of the driver. In previous versions, it was up to retry policy
145+implementations to handle idempotence (the new behavior is equivalent to what you achieved with
146+`IdempotenceAwareRetryPolicy` before).
157147
158148
159149 [RetryDecision]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html
@@ -183,11 +173,10 @@
183173 [SyntaxError]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/SyntaxError.html
184174 [AlreadyExistsException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/AlreadyExistsException.html
185175 [TruncateException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/TruncateException.html
186-[IdempotenceAwareRetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.html
187176
188177 [query plan]: ../load_balancing/#query-plan
189178 [connection pool]: ../pooling/
190179 [prepared]: ../statements/prepared/#preparing-on-multiple-nodes
191180 [driver read timeout]: ../socket_options/#driver-read-timeout
192181 [hinted handoffs]: https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_about_hh_c.html?scroll=concept_ds_ifg_jqx_zj__performance
193-[idempotent queries]: ../idempotence/
No newline at the end of the file
182+[idempotence]: ../idempotence/
No newline at the end of the file
modified upgrade_guide/README.md +32 −0
@@ -3,6 +3,38 @@
33 The purpose of this guide is to detail changes made by successive
44 versions of the Java driver.
55
6+### 3.1.0
7+
8+This version introduces an important change in the default retry behavior: statements that are not idempotent are not
9+always retried automatically anymore.
10+
11+Prior to 2.1.10, idempotence was not considered for retries. This exposed applications to the risk of applying a
12+non-idempotent statement twice (counter increment, list append...), or to more subtle bugs with lightweight transactions
13+(see [JAVA-819](https://datastax-oss.atlassian.net/browse/JAVA-819)).
14+
15+In 2.1.10 / 3.0.x, we introduced `IdempotenceAwareRetryPolicy`, which considers the `Statement#isIdempotent()` in the
16+retry decision process. However, for consistency with previous versions, this policy was not enabled by default (in
17+particular because statements are non-idempotent by default, and we didn't want applications to suddenly stop retrying
18+queries that were retried before).
19+
20+In 3.1.0, the default is now to **not retry** after a write timeout or request error if the statement is not idempotent.
21+This is handled internally, the retry policy methods are not even invoked in those cases (and therefore
22+`IdempotenceAwareRetryPolicy` has been deprecated). See the manual section about [retries](../manual/retries/) for more
23+information.
24+
25+In practice, here's what upgrading to 3.1.0 means for you:
26+
27+* if you were already handling idempotence in your application, there won't be any change, but you can stop wrapping
28+ your retry policy with `IdempotenceAwareRetryPolicy`;
29+* otherwise, you might want to review how your code positions the `setIdempotent` flag on statements. In most cases the
30+ driver can't compute in automatically (because it doesn't parse query strings), so it takes a conservative approach
31+ and sets it to `false` by default. If you know the query is idempotent, you should set it to `true` manually. See the
32+ [query idempotence](../manual/idempotence/) section of the manual.
33+
34+The driver logs a warning the first time it ignores a non-idempotent request; this warning will be removed in version
35+3.2.0.
36+
37+
638 ### 3.0.0
739
840 This version brings parity with Cassandra 2.2 and 3.0.