forked from apache/cassandra-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 40
Anchor prepare cache entry via PreparedStatement back-reference #893
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nikagra
wants to merge
2
commits into
scylladb:scylla-4.x
Choose a base branch
from
nikagra:fix/prepare-cache-anchor-liveness
base: scylla-4.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+311
−2
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
279 changes: 279 additions & 0 deletions
279
...src/test/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncProcessorTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,279 @@ | ||
| /* | ||
| * 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 com.datastax.oss.driver.internal.core.cql; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| import com.datastax.oss.driver.api.core.cql.PrepareRequest; | ||
| import com.datastax.oss.driver.api.core.cql.PreparedStatement; | ||
| import com.datastax.oss.driver.shaded.guava.common.cache.Cache; | ||
| import java.lang.ref.WeakReference; | ||
| import java.util.Optional; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.CompletionStage; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
| import org.mockito.Mockito; | ||
|
|
||
| /** | ||
| * Unit tests for {@link CqlPrepareAsyncProcessor} focusing on the caching behavior of {@link | ||
| * CqlPrepareAsyncProcessor#process} with respect to defensive copies and weak-value retention. | ||
| */ | ||
| public class CqlPrepareAsyncProcessorTest { | ||
|
|
||
| private CqlPrepareAsyncProcessor processor; | ||
| private Cache<PrepareRequest, CompletableFuture<PreparedStatement>> cache; | ||
|
|
||
| @Before | ||
| public void setup() { | ||
| processor = new CqlPrepareAsyncProcessor(Optional.empty()); | ||
| cache = processor.getCache(); | ||
| } | ||
|
|
||
| /** | ||
| * When the cached future is already completed, process() should return the exact same instance | ||
| * (identity). This ensures callers hold a strong reference to the cached CF, preventing | ||
| * weak-value eviction under GC pressure. | ||
| */ | ||
| @Test | ||
| public void should_return_cached_future_directly_when_already_completed() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
| PreparedStatement ps = Mockito.mock(PreparedStatement.class); | ||
|
|
||
| // Pre-populate cache with a completed future | ||
| CompletableFuture<PreparedStatement> completed = CompletableFuture.completedFuture(ps); | ||
| cache.put(request, completed); | ||
|
|
||
| // process() should return the exact same object | ||
| CompletionStage<PreparedStatement> returned = processor.process(request, null, null, "test"); | ||
|
|
||
| assertThat(returned).isSameAs(completed); | ||
| } | ||
|
|
||
| /** | ||
| * When the cached future is still in-flight (not yet done), process() should return a defensive | ||
| * copy to protect the cache from cancellation by the caller. | ||
| */ | ||
| @Test | ||
| public void should_return_defensive_copy_when_future_is_in_flight() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
|
|
||
| // Pre-populate cache with an incomplete future | ||
| CompletableFuture<PreparedStatement> inFlight = new CompletableFuture<>(); | ||
| cache.put(request, inFlight); | ||
|
|
||
| CompletionStage<PreparedStatement> returned = processor.process(request, null, null, "test"); | ||
|
|
||
| // Should NOT be the same instance | ||
| assertThat(returned).isNotSameAs(inFlight); | ||
|
|
||
| // Cancelling the returned copy should NOT affect the cached future | ||
| returned.toCompletableFuture().cancel(false); | ||
| assertThat(inFlight.isCancelled()).isFalse(); | ||
| } | ||
|
|
||
| /** | ||
| * Verifies that returning the cached future directly (for completed entries) keeps the weak-value | ||
| * cache entry alive as long as the caller holds a reference to the returned stage. | ||
| */ | ||
| @Test | ||
| public void should_keep_cache_entry_alive_when_caller_holds_completed_future() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
| PreparedStatement ps = Mockito.mock(PreparedStatement.class); | ||
|
|
||
| CompletableFuture<PreparedStatement> completed = CompletableFuture.completedFuture(ps); | ||
| cache.put(request, completed); | ||
|
|
||
| // Simulate what a caller does: hold the returned stage | ||
| CompletionStage<PreparedStatement> held = processor.process(request, null, null, "test"); | ||
|
|
||
| // Create a weak reference to detect if cache entry would be collected | ||
| WeakReference<CompletableFuture<PreparedStatement>> weakRef = new WeakReference<>(completed); | ||
| // Drop our local strong reference | ||
| //noinspection UnusedAssignment | ||
| completed = null; | ||
|
|
||
| // Force GC | ||
| System.gc(); | ||
| Thread.sleep(100); | ||
|
|
||
| // The cache entry should still be alive because 'held' IS the cached CF | ||
| cache.cleanUp(); | ||
| assertThat(cache.getIfPresent(request)).isNotNull(); | ||
| assertThat(weakRef.get()).isNotNull(); | ||
|
|
||
| // Verify held is usable | ||
| assertThat(held.toCompletableFuture().get()).isSameAs(ps); | ||
| } | ||
|
|
||
| /** | ||
| * Demonstrates the problem this fix addresses: without the fix, a defensive copy would be the | ||
| * only reference returned, and if the caller doesn't hold it long enough, GC can evict the cache | ||
| * entry. This test shows that with the fix, even after the caller's reference goes out of scope, | ||
| * the behavior is correct for the next caller who retrieves it promptly. | ||
| */ | ||
| @Test | ||
| public void should_allow_gc_eviction_when_no_strong_references_remain() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
| PreparedStatement ps = Mockito.mock(PreparedStatement.class); | ||
|
|
||
| CompletableFuture<PreparedStatement> completed = CompletableFuture.completedFuture(ps); | ||
| cache.put(request, completed); | ||
|
|
||
| // Drop all strong references | ||
| //noinspection UnusedAssignment | ||
| completed = null; | ||
|
|
||
| // Force GC - weak value should be collected | ||
| for (int i = 0; i < 10; i++) { | ||
| System.gc(); | ||
| Thread.sleep(50); | ||
| cache.cleanUp(); | ||
| if (cache.getIfPresent(request) == null) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| // Cache entry may have been evicted (weak values) | ||
| // This is expected behavior - the fix ensures callers who DO hold a reference keep it alive | ||
| // We just verify the cache doesn't throw | ||
| assertThat(cache.size()).isGreaterThanOrEqualTo(0); | ||
|
Comment on lines
+143
to
+155
|
||
| } | ||
|
|
||
| /** | ||
| * Verifies that when a DefaultPreparedStatement holds the cache retainer (strong back-reference | ||
| * to the cached CF), the cache entry survives GC even when no other strong references exist. | ||
| */ | ||
| @Test | ||
| public void should_keep_cache_entry_alive_via_prepared_statement_retainer() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
|
|
||
| CompletableFuture<PreparedStatement> cachedFuture = new CompletableFuture<>(); | ||
| cache.put(request, cachedFuture); | ||
|
|
||
| // Simulate what the processor does: create a real DefaultPreparedStatement and set retainer | ||
| DefaultPreparedStatement ps = | ||
| new DefaultPreparedStatement( | ||
| java.nio.ByteBuffer.wrap(new byte[] {1, 2, 3, 4}), | ||
| "SELECT 1", | ||
| com.datastax.oss.driver.internal.core.cql.EmptyColumnDefinitions.INSTANCE, | ||
| java.util.Collections.emptyList(), | ||
| null, | ||
|
Comment on lines
+169
to
+176
|
||
| com.datastax.oss.driver.internal.core.cql.EmptyColumnDefinitions.INSTANCE, | ||
| null, | ||
| null, | ||
| java.util.Collections.emptyMap(), | ||
| null, | ||
| null, | ||
| null, | ||
| null, | ||
| null, | ||
| java.util.Collections.emptyMap(), | ||
| null, | ||
| null, | ||
| null, | ||
| -1, | ||
| null, | ||
| null, | ||
| false, | ||
| com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry.DEFAULT, | ||
| com.datastax.oss.driver.api.core.ProtocolVersion.V4, | ||
| null); | ||
|
|
||
| // Set the retainer — this is the key part of PR #2 | ||
| ps.setCacheRetainer(cachedFuture); | ||
| cachedFuture.complete(ps); | ||
|
|
||
| // Drop all references except PS itself | ||
| //noinspection UnusedAssignment | ||
| cachedFuture = null; | ||
|
|
||
| // Force GC | ||
| for (int i = 0; i < 10; i++) { | ||
| System.gc(); | ||
| Thread.sleep(50); | ||
| cache.cleanUp(); | ||
| } | ||
|
|
||
| // Cache entry should survive because PS holds the retainer | ||
| assertThat(cache.getIfPresent(request)).isNotNull(); | ||
| assertThat(cache.getIfPresent(request).get()).isSameAs(ps); | ||
| } | ||
|
|
||
| /** | ||
| * Verifies that when the PreparedStatement (and its retainer) is no longer reachable, the cache | ||
| * entry CAN be evicted — confirming we don't leak memory. | ||
| */ | ||
| @Test | ||
| public void should_evict_cache_entry_when_prepared_statement_is_unreachable() throws Exception { | ||
| PrepareRequest request = new DefaultPrepareRequest("SELECT 1"); | ||
|
|
||
| CompletableFuture<PreparedStatement> cachedFuture = new CompletableFuture<>(); | ||
| cache.put(request, cachedFuture); | ||
|
|
||
| DefaultPreparedStatement ps = | ||
| new DefaultPreparedStatement( | ||
| java.nio.ByteBuffer.wrap(new byte[] {1, 2, 3, 4}), | ||
| "SELECT 1", | ||
| com.datastax.oss.driver.internal.core.cql.EmptyColumnDefinitions.INSTANCE, | ||
| java.util.Collections.emptyList(), | ||
| null, | ||
| com.datastax.oss.driver.internal.core.cql.EmptyColumnDefinitions.INSTANCE, | ||
| null, | ||
| null, | ||
| java.util.Collections.emptyMap(), | ||
| null, | ||
| null, | ||
| null, | ||
| null, | ||
| null, | ||
| java.util.Collections.emptyMap(), | ||
| null, | ||
| null, | ||
| null, | ||
| -1, | ||
| null, | ||
| null, | ||
| false, | ||
| com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry.DEFAULT, | ||
| com.datastax.oss.driver.api.core.ProtocolVersion.V4, | ||
| null); | ||
|
|
||
| ps.setCacheRetainer(cachedFuture); | ||
| cachedFuture.complete(ps); | ||
|
|
||
| // Drop ALL strong references | ||
| //noinspection UnusedAssignment | ||
| cachedFuture = null; | ||
| //noinspection UnusedAssignment | ||
| ps = null; | ||
|
|
||
| // Force GC — weak value should be collected since nothing holds the CF | ||
| for (int i = 0; i < 10; i++) { | ||
| System.gc(); | ||
| Thread.sleep(50); | ||
| cache.cleanUp(); | ||
| if (cache.getIfPresent(request) == null) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| // Cache entry should have been evicted | ||
| assertThat(cache.getIfPresent(request)).isNull(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i feel like you don't need whole cache thing if you store this in the
DefaultPreparedStatement, but then you need to make this method exportable, whole thing look hacky, what if they have their own implementation of thePreparedStatement, then it won't work.Can you please check if then it makes sense to make this part of public API fo the
PreparedStatementand have a default function that stores cache retainer anchor?