You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "tolbertam (via GitHub)" <gi...@apache.org> on 2025/02/21 00:03:43 UTC
[PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
tolbertam opened a new pull request, #3917:
URL: https://github.com/apache/cassandra/pull/3917
Updates SystemKeyspace.writePreparedStatement to accept a timestamp associated with the Prepared creation time. Using this timestamp will ensure that an INSERT into system.prepared_statements will always precede the timestamp for the same Prepared in SystemKeyspace.removePreparedStatement.
Additionally, any clusters currently experiencing a leaky system.prepared_statements table from this bug may struggle to bounce into a version with this fix as
SystemKeyspace.loadPreparedPreparedStatements currently does not paginate the query to system.prepared_statements, causing heap OOMs. To fix this this patch adds pagingation at 5000 rows, which should allow nodes to come up and delete older prepared statements that may no longer be used as
the cache fills up (which should happen immediately).
Adds #testAsyncPstmtInvalidation which almost always reproduces the issue without this fix.
Adds #testPreloadPreparedStatements to verify pagination behavior.
This patch does not address the issue of Caffeine immediately evicting a prepared statement, however it will prevent the
system.prepared_statements table from growing unbounded. For most users this should be adequate, as the cache should only be filled when there are erroneously many unique prepared statements. In such a case we can expect that clients will constantly prepare statements regardless of whether or not the cache is evicting statements.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080793274
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
- if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
- row.getString("query_string"),
- row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
+ Prepared prepared = onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
+ row.getString("query_string"),
+ row.has("logged_keyspace") ? row.getString("logged_keyspace") : null);
+ if (prepared != null)
+ {
counter++;
+ preparedBytesLoaded += Math.max(0, prepared.pstmntSize);
+ }
+
+ if (counter % pageSize == 0)
+ {
+ if (possibleLeakDetected)
+ {
+ logger.warn("Detected prepared statement cache filling up during preload after preparing {} " +
Review Comment:
new variant:
> WARN [main] 2025-05-08 21:31:54,578 SystemKeyspace.java:1904 - Detected prepared statement cache filling up during preload after preparing 463 statements (loaded 1.1 MiB with prepared_statements_cache_size being 1 MiB). This could be an indication that prepared statements leaked prior to CASSANDRA-19703 being fixed. Returning early to prevent indefinite startup. Consider truncating system.prepared_statements to clear out leaked prepared statements.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2083578597
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -131,6 +128,16 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
+ public static void evictPreparedStatement(MD5Digest key, RemovalCause cause)
Review Comment:
:+1:, looking at it again now I just realized this doesn't even need to be public, so I'll reduce the visibility to private.
We ended up only needing this as a separate method to ensure it gets invoked in `PstmtPersistenceTest` and apparently byteman is still able to instrument around it with private visibility.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034780650
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
This is just testing statement load but not that paging is being exercised when doing so. Wouldn't we want to check specifically paging is being hit instead with byteman i.e.? Maybe you could reuse any of the other tests to check paging was indeed hit while loading pstmnts
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045819163
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam that's helpful, but until I looked carefully at the code it wasn't clear what the eviction policy was (LRU?) or if bad statements (i.e, not fully qualified) will eventually be evicted or not. Mentioning Caffeine and the eviction policy used.
How about something like this:
"To ensure optimal performance, it's important to use bind markers (?) for all non-constant values in your SQL statements. If you include literal values directly in the query instead, each variation will be treated as a unique statement that must be prepared and cached separately.
When the Caffeine-managed cache reaches its maximum size, older or less frequently used statements are evicted, leading to additional overhead as previously prepared statements must be re-prepared."
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042010682
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
Here you could check cache size every page, not every record for perf reasons, dropping `max` which we wouldn't need anymore and would not adapt to the cache size which is user configurable..
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2036595740
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Rather than doing a sort of E2E test, which will be heavy on CI and execution times, we could target the actual fix itself. I picture this as adding to `testPstmtInvalidation` some byteman checking timestamps where used both in inserts and deletions. But that's just me, just a suggestion.
That way you test the specifics and avoid adding unnecessary CI load.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2076731972
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,200 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ while (!QueryProcessor.isPreparedStatementCacheNearlyFull())
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ cnt++;
+ }
+ if (statementsLoadedBeforeFull == -1) {
+ statementsLoadedBeforeFull = cnt;
+ }
+ QueryProcessor.clearPreparedStatements(true);
+ }
+
+ // Ensure the page size we use is less than the number of statments it took to load the cache.
+ int pageSize = statementsLoadedBeforeFull / 10;
+ // We should only expect to load how many statements we were able to load before filling the cache
+ // + a buffer of a page size + another possible page.
Review Comment:
we allow a buffer of 2 pages for:
one page to hit the boundary where we detect we might have leaked +
additional page that we are allowed to read before exiting early.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2077439698
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
That 1% you added is like the 5% I was suggesting iiuc.
But you know sometimes I'm just an idiot. As every pstmnt comes with it's size precomputed now, you can add those as you load them. Then compare against the max weight of the cache trashing and simplifying all this.
Apologies about the noise. I don't know how I didn't think about it before :shrug:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2036605419
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
You could just add some byteman to `testCachedPreparedStatements` on reload and test the paging is hit there. My 2cts.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042202931
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
Think best I could do is just check every X rows and then check to see if we've started evicting, pushed something for that and hopefully that looks good!
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034780650
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
This is just testing statement load but not that paging is being exercised when doing so. Wouldn't we want to check specifically paging is being hit instead with byteman i.e.?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2046969384
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
That sounds great to me. I just pushed a change which takes your suggestions as is with a few tweaks, how does that look?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2854239800
Aren't we missing a test we stop loading pstmnts once cache is full? Maybe you could use byteman to capture the call to the log warn method. That with a modified yaml to have a smaller pstmnts cache somehow should do the trick. I think it's one important feature we're not testing unless I am missing sthg.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2077759858
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
Review Comment:
Hopefully it's ok to change the type signature here? I don't expect this method is used outside of the codebase itself and tests.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080799312
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ long initialEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
+ // load prepared statements until we detect any eviction, on eviction we assume cache was filled.
+ while (QueryProcessor.metrics.preparedStatementsEvicted.getCount() == initialEvicted)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
Review Comment:
Unless i'm misunderstanding, it's should be necessary as we just need the prepared statement query.
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ long initialEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
+ // load prepared statements until we detect any eviction, on eviction we assume cache was filled.
+ while (QueryProcessor.metrics.preparedStatementsEvicted.getCount() == initialEvicted)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
Review Comment:
Unless i'm misunderstanding, it shouldn't be necessary as we just need the prepared statement query.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2081040496
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -131,6 +128,16 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
+ public static void evictPreparedStatement(MD5Digest key, RemovalCause cause)
Review Comment:
I would add annotation VisibleForTesting here? It is not intended to be called iiuc
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045527359
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,38 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0
+ && QueryProcessor.metrics.preparedStatementsEvicted.getCount() - initialStatementsEvicted > 0)
Review Comment:
I hadn't considered that as this method would be called on startup before listening on CQL, but there could always be internal preparations and statements evicted for other reasons. I agree that testing against the cache size would probably be more reliable. Will fix that :+1:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045635126
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
Review Comment:
was able to make this work, thanks!
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042047785
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
that would make a ton more sense, thanks for the suggestion :+1:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2804154000
IIUc here we're fixing 3 things:
- Ordering of timestamps preventing the leak
- Paged reading when preloading to further soften any leaks
- Stop preloading when cache is already full to prevent trashing the cache upon leaks
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042001480
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.recordEvictionTimestamp($key);")
+ }
+ )
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ // page size passed to preloadPreparedStatements
+ private static final int PRELOAD_PAGE_SIZE = 100;
+ // recorded page invocations in preloadPreparedStatements
+ private static int PAGE_INVOCATIONS = 0;
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(int pageSize)
+ {
+ if (pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ PAGE_INVOCATIONS++;
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
Review Comment:
Formatting
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042050216
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -35,20 +43,32 @@
import org.apache.cassandra.transport.Dispatcher;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.MD5Digest;
+import org.jboss.byteman.contrib.bmunit.BMRule;
+import org.jboss.byteman.contrib.bmunit.BMRules;
+import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
import static java.util.Collections.emptyMap;
import static org.apache.cassandra.service.QueryState.forInternalCalls;
import static org.junit.Assert.*;
+@RunWith(BMUnitRunner.class)
public class PstmtPersistenceTest extends CQLTester
{
+ private static final CompletableFuture<?>[] futureArray = new CompletableFuture[0];
+
+ private static final ConcurrentMap<MD5Digest, Long> preparedStatementLoadTimestamps = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<MD5Digest, Long> preparedStatementRemoveTimestamps = new ConcurrentHashMap<>();
+
@Before
public void setUp()
{
+ preparedStatementLoadTimestamps.clear();
+ preparedStatementRemoveTimestamps.clear();
+
QueryProcessor.clearPreparedStatements(false);
}
-
- @Test
+
+
Review Comment:
this most have been incidentally removed when I was experimenting with byteman annotations, good catch, will add that back.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034776690
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Does this deterministically fail without the fix? Have you explored using byteman to try to register if the righ code paths are hit instead i.e.?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045819163
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam that's helpful, but until I looked carefully at the code it wasn't clear what the eviction policy was (LRU?) or if bad statements (i.e, not correctly qualified) will eventually be evicted or not. Mentioning Caffeine and the eviction policy used.
How about something like this:
"To ensure optimal performance, it's important to use bind markers '?' for all non-constant values in your SQL statements. If you include literal values directly in the query instead, each variation will be treated as a unique statement that must be prepared and cached separately. This will soon overflow the prepared statement cache, which is small by design.
When the Caffeine-managed cache reaches its maximum size, older or less frequently used statements are evicted, leading to additional overhead as previously prepared statements must be re-prepared."
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2036588266
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -155,6 +155,12 @@ private enum InternalStateInstance
}
public void preloadPreparedStatements()
+ {
+ preloadPreparedStatements(5000);
Review Comment:
Right. A warning with an explanation of why that could be a problem would be great. And indeed the bug is present no matter what. It's just that some lib versions make it more visible or less.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040848056
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
I couldn't find a good example of paging tests using byteman to assert that paging actually happened, but I did find a lot of good inspiration in tests using byteman generally to make this work, hopefully the way I went about this looks alright.
I figured I would keep this test since `testCachedPreparedStatements` only creates a very small amount of prepared statements (~7) and working with on the order of hundreds of statements made it a little easier to validate paging.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080811494
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
Review Comment:
that sounds better, thanks for the suggestion! I've updated to match this short of the logging validation.
I'm not finding a lot of precedence around validating logging other than for logging specific functionality (`AuditLoggerAuthTest`, `StatusLoggerTest`, `NoSpamLoggerTest`). Since we are able to concisely validate that we short circuit preloading statements it feels adequate to me.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079184413
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,200 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ while (!QueryProcessor.isPreparedStatementCacheNearlyFull())
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ cnt++;
+ }
+ if (statementsLoadedBeforeFull == -1) {
+ statementsLoadedBeforeFull = cnt;
+ }
+ QueryProcessor.clearPreparedStatements(true);
+ }
+
+ // Ensure the page size we use is less than the number of statments it took to load the cache.
+ int pageSize = statementsLoadedBeforeFull / 10;
+ // We should only expect to load how many statements we were able to load before filling the cache
+ // + a buffer of a page size + another possible page.
Review Comment:
I would trash that and just loop and break when you go over the limit. it's just 2 local variable reads on startup and you drop unnecessary complexity of the code.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079141396
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ long initialEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
+ // load prepared statements until we detect any eviction, on eviction we assume cache was filled.
+ while (QueryProcessor.metrics.preparedStatementsEvicted.getCount() == initialEvicted)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ cnt++;
+ }
+
+ if (statementsLoadedBeforeFull == -1) {
Review Comment:
braces formatting
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2041974585
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
Review Comment:
`a more` is a typo?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042131221
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.recordEvictionTimestamp($key);")
+ }
+ )
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ // page size passed to preloadPreparedStatements
+ private static final int PRELOAD_PAGE_SIZE = 100;
+ // recorded page invocations in preloadPreparedStatements
+ private static int PAGE_INVOCATIONS = 0;
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(int pageSize)
+ {
+ if (pageSize == PRELOAD_PAGE_SIZE)
Review Comment:
improved this by passing in the query and validating the table name.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040869134
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@bschoening , following up on [your comment](https://issues.apache.org/jira/browse/CASSANDRA-19703?focusedCommentId=17932752&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17932752), how does this look?
In particular I think the second paragraph would be useful in that it emphasizes that one should qualify all values with bind markers to avoid preparing every query which decreases performance for multiple reasons.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2081045842
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1866,52 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+
+ // As the cache size may be briefly exceeded before statements are evicted, we allow loading 110% the cache size
+ // to avoid logging early.
+ long cacheSize = new DataStorageSpec.LongBytesBound(DatabaseDescriptor.getPreparedStatementsCacheSizeMiB(),
+ DataStorageSpec.DataStorageUnit.MEBIBYTES).toBytes();
+ long preparedBytesLoadThreshold = (long) (cacheSize * 1.1);
Review Comment:
We better align to the code when the cache's size is initialized at the top of the class:
`cacheSize=capacityToBytes(DatabaseDescriptor.getPreparedStatementsCacheSizeMiB())`
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2076730354
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
> Aren't we missing a test we stop loading pstmnts once cache is full? Maybe you could use byteman to capture the call to the log warn method. That with a modified yaml to have a smaller pstmnts cache somehow should do the trick. I think it's one important feature we're not testing unless I am missing sthg.
I'm glad you brought this up as it pushed me to exercise how effective this logic could be, and apparently it was not very effective as is!
We deployed an early version of this fix in late 2024/early 2025, at which time we didn't have any short circuiting logic, so we would just page indefinitely (which was better than OOMing but still not great). When we encountered this, we would simply just truncate the `system.prepared_statements` table. So this particular piece of logic hadn't really been put through its paces.
After writing a test (`testPreloadPreparedStatementsUntilCacheFull`) I found that it was *very* difficult to encounter a full cache as Caffeine, while it allows going past the maximum weight, is very effective at evicting quickly below it. Therefore, I think we need to add some kind of negative buffer. I found that testing against 99% of the cache size was very effective.
To avoid potentially logging that there might be a leak when we previously just had a nearly full cache, we now allow paging one addition time (`possibleLeakDetected`), at which point if we still haven't exhausted the result set, we'll log the message and exit earlier.
In terms of validating where we stop once the cache is full, I found that we could easily detect this by updating `preloadPreparedStatements` to return an `int` and then comparing the total number of rows returned against the maximum amount we should expect (I added some github comments to the test I added to expand on this more). I think this is more precise than testing against the log entry, which also does indeed get logged in the test:
> WARN [main] 2025-05-06 22:36:42,581 SystemKeyspace.java:1888 - Detected prepared statement cache filling up during preload after preparing 492 statements. This could be an indication that prepared statements leaked prior to CASSANDRA-19703 being fixed. Returning early to prevent indefinite startup. Consider truncating system.prepared_statements to clear out leaked prepared statements.
Hopefully that all sounds right!
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2077772598
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
- if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
- row.getString("query_string"),
- row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
+ Prepared prepared = onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
+ row.getString("query_string"),
+ row.has("logged_keyspace") ? row.getString("logged_keyspace") : null);
+ if (prepared != null)
+ {
counter++;
+ preparedBytesLoaded += Math.max(0, prepared.pstmntSize);
+ }
+
+ if (counter % pageSize == 0)
+ {
+ if (possibleLeakDetected)
+ {
+ logger.warn("Detected prepared statement cache filling up during preload after preparing {} " +
Review Comment:
What this looks like:
> WARN [main] 2025-05-07 09:30:16,724 SystemKeyspace.java:1898 - Detected prepared statement cache filling up during preload after preparing 492 statements (1.17 MiB of 1 MiB cache size). This could be an indication that prepared statements leaked prior to CASSANDRA-19703 being fixed. Returning early to prevent indefinite startup. Consider truncating system.prepared_statements to clear out leaked prepared statements.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079139693
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
Review Comment:
We need it to pull the size so it is justifiable imo
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2084660598
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -128,7 +131,8 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
- public static void evictPreparedStatement(MD5Digest key, RemovalCause cause)
+
Review Comment:
:+1: sorry about that, fixed.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034776690
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Does this deterministically fail without the fix?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040865854
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -101,6 +102,12 @@ public class QueryProcessor implements QueryHandler
// counters. Callers of processStatement are responsible for correctly notifying metrics
public static final CQLMetrics metrics = new CQLMetrics();
+ // Paging size to use when preloading prepared statements.
+ public static final int PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE = 5000;
+
+ // Maximum number of prepared statements to preload from prepared statement cache.
+ public static final int PRELOAD_PREPARED_STATEMENTS_MAX = 1_000_000;
Review Comment:
does 1 million feel about right here? Would there be any value in making this configurable? I can't imagine anyone would actually want to do this, but we could make it a system property if that has some value.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] 4.1: CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam closed pull request #3917: 4.1: CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE
URL: https://github.com/apache/cassandra/pull/3917
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2041981169
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
OK sgtm. I'd reuse other test cases but we're getting in personal taste territory and I prefer to favor authorship in this cases.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042007900
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -101,6 +102,12 @@ public class QueryProcessor implements QueryHandler
// counters. Callers of processStatement are responsible for correctly notifying metrics
public static final CQLMetrics metrics = new CQLMetrics();
+ // Paging size to use when preloading prepared statements.
+ public static final int PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE = 5000;
+
+ // Maximum number of prepared statements to preload from prepared statement cache.
+ public static final int PRELOAD_PREPARED_STATEMENTS_MAX = 1_000_000;
Review Comment:
Thinking about it we don't need to come up with this new limit. We already have a limit on the cache size in MB. Once you hit that it makes no sense to just be trashing the cache. So just drop this and monitor cache size instead. Once you've reached the max cache size you can stop loading. Does it make sense?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2043828277
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,38 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0
+ && QueryProcessor.metrics.preparedStatementsEvicted.getCount() - initialStatementsEvicted > 0)
Review Comment:
We can't rely on the evictions counter imo. We have code in QueryProcessor invalidating entries, other proceses could be invalidating stuff, also iirc on collisions evictions where triggered inside caffeine, etc. Why not just check the size?
```
eviction = cache.policy().eviction().orElseThrow()
long currentWeight = eviction.weightedSize().orElseThrow()
```
Give it an extra 5% (?) to accommodate for Caffeine async evictions that may occasionally go over the limit and we should be ok
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045819163
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam that's helpful, but until I looked carefully at the code it wasn't clear what the eviction policy was (LRU?) or if bad statements (i.e, not correctly qualified) will eventually be evicted or not. Mentioning Caffeine and the eviction policy used.
How about something like this:
"To ensure optimal performance, it's important to use bind markers '?' for all non-constant values in your SQL statements. If you include literal values directly in the query instead, each variation will be treated as a unique statement that must be prepared and cached separately.
When the Caffeine-managed cache reaches its maximum size, older or less frequently used statements are evicted, leading to additional overhead as previously prepared statements must be re-prepared."
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042130461
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
Review Comment:
agree that it looks awkward (for some reason me IDE really wanted to coerce me into it). Pushed something which looks a bit better hopefully.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045643799
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,38 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0
+ && QueryProcessor.metrics.preparedStatementsEvicted.getCount() - initialStatementsEvicted > 0)
Review Comment:
Pushed something that I think this should be sufficient, but do have a small inkling of doubt.
We could consider adding a 5% or so buffer as you suggested, but by under-compensating (e.g. `currentSize >= maximumSize * 0.95`) so we can handle the case of the cache being evicted right below it's capacity.
I suspect if we page through leaked statements we will eventually hit a case where the cache is briefly above its capacity and it will cut off.
If we do add an under-compensation, it's possible that we will erroneously stop and log a warning which may not be correct. On the other hand we could always adjust that warning to indicate that it's possible we stopped because the cache was close to full.
In the usual case, the prepared statement cache should not really approach close to getting full unless non-fully qualified statements are being prepared anyways, so it might be useful to warn in that case as well ("Detected that the prepared statement cache was close to full on preload, please investigate whether your statements being prepared are fully qualified"). Thoughts?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2046972438
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,28 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+===== Prepared Statement Caching
+
+Prepared Statements are cached by cassandra in-memory using a
+https://github.com/ben-manes/caffeine[Caffeine]-managed cache which
+can be configured using
+xref:managing/configuration/cass_yaml_file.adoc#_prepared_statements_cache_size[`prepared_statements_cache_size`].
+The cache is also persisted to the `system.prepared_statements` table
+so it can be preloaded into memory on startup.
+
+To ensure optimal performance, it's important to use a bind `<variable>`
Review Comment:
Note: opted to use `<variable>` over bind marker to match the preceding documentation.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2076685870
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
I think it doesn't have to be too precise. We may in fact page several times more than what would be ideal, but the important thing is that we stop and don't page indefinitely.
We could make it more sensitive by changing the calculation to be some value less than the maximum weight (something like 95%). The downside of doing that is we may drop prepared statements that we may have been able to cache otherwise and would also notify the user that the cache may be leaky when it in fact that isn't the issue.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079185171
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
- if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
- row.getString("query_string"),
- row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
+ Prepared prepared = onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
+ row.getString("query_string"),
+ row.has("logged_keyspace") ? row.getString("logged_keyspace") : null);
+ if (prepared != null)
+ {
counter++;
+ preparedBytesLoaded += Math.max(0, prepared.pstmntSize);
+ }
+
+ if (counter % pageSize == 0)
+ {
+ if (possibleLeakDetected)
+ {
+ logger.warn("Detected prepared statement cache filling up during preload after preparing {} " +
Review Comment:
Nice :-)
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2865653574
LGTM modulus the 2 minor issues I mentioned last. I would still heavily compact junits but that's just me. We need another C* committer to +1 this now right?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080830916
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1866,52 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+
+ // As the cache size may be briefly exceeded before statements are evicted, we allow loading 110% the cache size
+ // to avoid logging early.
+ long cacheSize = new DataStorageSpec.LongBytesBound(DatabaseDescriptor.getPreparedStatementsCacheSizeMiB(),
+ DataStorageSpec.DataStorageUnit.MEBIBYTES).toBytes();
+ long preparedBytesLoadThreshold = (long) (cacheSize * 1.1);
Review Comment:
I found that we still need a small buffer to avoid erroneously logging. In my testing found that we often loaded a statement or two past the cache size. A 10% buffer should be more than adequate.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] 4.1: CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2894356289
squashed with no changes.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045819163
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam that's helpful, but until I looked carefully at the code it wasn't clear what the eviction policy was (LRU?) or if bad statements (i.e, not fully qualified) will eventually be evicted or not. Mentioning Caffeine and the eviction policy used.
How about something like this:
"To ensure optimal performance, it's important to use bind markers '?' for all non-constant values in your SQL statements. If you include literal values directly in the query instead, each variation will be treated as a unique statement that must be prepared and cached separately.
When the Caffeine-managed cache reaches its maximum size, older or less frequently used statements are evicted, leading to additional overhead as previously prepared statements must be re-prepared."
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034780650
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
This is just testing statement load but not that paging is being exercised when doing so. Wouldn't we want to check specifically paging instead?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040866531
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -109,15 +116,8 @@ public class QueryProcessor implements QueryHandler
.executor(ImmediateExecutor.INSTANCE)
.maximumWeight(capacityToBytes(DatabaseDescriptor.getPreparedStatementsCacheSizeMiB()))
.weigher(QueryProcessor::getSizeOfPreparedStatementForCache)
- .removalListener((key, prepared, cause) -> {
- MD5Digest md5Digest = (MD5Digest) key;
- if (cause.wasEvicted())
- {
- metrics.preparedStatementsEvicted.inc();
- lastMinuteEvictionsCount.incrementAndGet();
- SystemKeyspace.removePreparedStatement(md5Digest);
- }
- }).build();
+ .removalListener((key, prepared, cause) -> evictPreparedStatement(key, cause))
Review Comment:
This may look a bit unnecessary, but needed this to instrument byteman to detect when this happens as `removePreparedStatement` is called in other code paths. I think the code is marginally more concise/unharmfull in any case.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042139638
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
Updated this to short circuit on detection of cache eviction, I still need to update this to do the evaluation on page boundaries which I haven't figured out how to detect yet (need to find something like `isExhausted()` on page boundary which I haven't stumbled into yet).
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079138901
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
Review Comment:
This is extremely hard to read imo. I understand your worried about pulling the size from the cache etc. But that is not the case anymore as we have that as a config value. Just loop and break KISS
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2084445644
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -128,7 +131,8 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
- public static void evictPreparedStatement(MD5Digest key, RemovalCause cause)
+
Review Comment:
Extra blank line
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2877444587
went ahead and rebased and squashed the commits as I had updated from trunk previously which messed with the history a bit. Made no changes and ensured a clean diff before pushing.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080811958
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
Review Comment:
:+1: hopefully it's more concise now that I've removed the validation at paging boundaries.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2870598456
Pushed some changes which hopefully addresses the remaining feedback, hopefully everything looks ok! I merged in recent changes from 4.1 and ran a [full CI run](https://issues.apache.org/jira/browse/CASSANDRA-19703?focusedCommentId=17950821&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17950821). I'll find a second reviewer tomorrow.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] 4.1: CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2889208595
> I think we need 4.0 as well
Technically the bug is not likely to be encountered on 4.0 as Caffeine is running an older version that behaves differently, but it wouldn't hurt to do so, create a branch.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] 4.1: CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#issuecomment-2889458258
Added two small changes (c85d156 and 3c80c2e) which I have squashed on the other branches. I have added test results to [the jira](https://issues.apache.org/jira/browse/CASSANDRA-19703?focusedCommentId=17952487&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17952487). Can squash into a single commit assuming everything looks good.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080793822
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -131,6 +129,28 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
+ /**
+ * @return The maximum capacity, in bytes, of the prepared statements cache. If no capacity is established,
+ * {@link Long#MAX_VALUE} is returned.
+ */
+ public static long getPreparedStatementsCacheMaximumCapacity()
Review Comment:
removed
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2077756472
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
That does sound like a more effective way of doing this, thanks! I just pushed 42496b5, hopefully that looks good.
I kept the logic there that only tests this on page boundaries because I found in testing that Caffeine's caching behavior allows us to load past the cache size, so in order to prevent erroneously logging on startup its worth having a buffer before we log and stop iterating.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079119140
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -131,6 +129,28 @@ public class QueryProcessor implements QueryHandler
DatabaseDescriptor.getPreparedStatementsCacheSizeMiB());
}
+ /**
+ * @return The maximum capacity, in bytes, of the prepared statements cache. If no capacity is established,
+ * {@link Long#MAX_VALUE} is returned.
+ */
+ public static long getPreparedStatementsCacheMaximumCapacity()
Review Comment:
Trash this. You already have `DatabaseDescriptor.getPreparedStatementsCacheSizeMiB()`
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079182257
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
You can trash all that as you have a config property for the max cache size. Commented inline.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2075039925
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
I like this explanation a lot +1
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2043805104
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
Review Comment:
Nit: Not aligned by one space
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045819163
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam that's helpful, but until I looked carefully at the code it wasn't clear what the eviction policy was (LRU?) or if bad statements (i.e, not fully qualified) will eventually be evicted or not. Mentioning Caffeine and the eviction policy used.
How about something like this:
"To ensure optimal performance, it's important to use bind markers (?) for all non-constant values in your SQL statements. If you include literal values directly in the query instead, each variation will be treated as a unique statement that must be prepared separately.
This increases the number of distinct prepared statements, which in turn reduces the effectiveness of the Caffeine-managed cache. When the cache reaches its maximum size, older or less frequently used statements are evicted, leading to additional overhead as previously prepared statements must be re-prepared."
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045523631
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
Review Comment:
🤔 maybe, i'll see if I can make it work. The main reason I did this was because we need to use `ClientState.getTimestamp()` to generate a timestamp to record when this was invoked (since we don't use explicit timestamps on the delete) But perhaps I can make this works with lambdas, or alternative change `evictPreparedStatement` to require a client timestamp.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034731320
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -155,6 +155,12 @@ private enum InternalStateInstance
}
public void preloadPreparedStatements()
+ {
+ preloadPreparedStatements(5000);
Review Comment:
That 5K should be a constant defined somewhere imo
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2035555235
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Not deterministically because the behavior relies on ordering between competing threads and the underlying caffeine cache behavior, but it reproduces very consistently with the previous implementation. The larger `statementsToPrepare` is, the more possibility the test will fail.
I will think whether I can test for something more specific than the assertion at line 205 which checks to ensure no statements leaked. Leaking prepared statements should effectively not be possible with the introduction of the use of client timestamps.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042133412
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.recordEvictionTimestamp($key);")
+ }
+ )
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ // page size passed to preloadPreparedStatements
+ private static final int PRELOAD_PAGE_SIZE = 100;
+ // recorded page invocations in preloadPreparedStatements
+ private static int PAGE_INVOCATIONS = 0;
Review Comment:
sounds good, updated and also changed to AtomicInteger since we're incrementing an existing value.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2043886743
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
Added a note of checking the cache size directly rather than the evictions counter which is not deterministic.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045597854
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,38 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0
+ && QueryProcessor.metrics.preparedStatementsEvicted.getCount() - initialStatementsEvicted > 0)
Review Comment:
Was just thinking this through and I was cautiously worried about two things:
1. Incidentally warning the user that they might have hit a leak, when they really haven't (e.g. if cache was full on restart and we detected it was full and we 5% wasn't enough of a buffer)
2. Not detecting the cache is full because 5% is too big of a buffer
But I just realized that one thing we can use in our favor is that we only evaluate this on paging boundaries, so its exceedingly unlikely that either of those 2 cases would be a problem with a page size of 5000. Therefore, I think it's ok to do this, and that we also don't need a 5% buffer, as evaluating on page boundaries acts as a buffer in itself. Will push something shortly that will should work I hope.
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,38 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0
+ && QueryProcessor.metrics.preparedStatementsEvicted.getCount() - initialStatementsEvicted > 0)
Review Comment:
Was just thinking this through and I was cautiously worried about two things:
1. Incidentally warning the user that they might have hit a leak, when they really haven't (e.g. if cache was full on restart and we detected it was full and we 5% wasn't enough of a buffer)
2. Not detecting the cache is full because 5% is too big of a buffer and paging indefinitely.
But I just realized that one thing we can use in our favor is that we only evaluate this on paging boundaries, so its exceedingly unlikely that either of those 2 cases would be a problem with a page size of 5000. Therefore, I think it's ok to do this, and that we also don't need a 5% buffer, as evaluating on page boundaries acts as a buffer in itself. Will push something shortly that will should work I hope.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2075046205
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
I am only worried here we'd detect only the problem if _both_ we're on a page boundary and caffeine happens to be reporting full. Which could be a racy or rare event. But if you say it works for you in production so be it. It's better than nothing and we can always tweak if we reports from the field suggesting a change.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2076851926
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
> I found that it was very difficult to encounter a full cache
That is exactly what I was referring to. We were trying to detect a full cache _and_ only at page boundaries. Which sounded very improbable at face value knowing caffeine.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2080818914
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -178,7 +400,6 @@ private MD5Digest prepareStatement(String stmt, ClientState clientState)
private MD5Digest prepareStatement(String stmt, String keyspace, String table, ClientState clientState)
{
- System.out.println(stmt + String.format(stmt, keyspace + "." + table));
Review Comment:
Not sure how that println got in there but it's been there for 4 years apparently, figure it's ok to remove.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2081046137
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1862,17 +1865,61 @@ public static void resetPreparedStatements()
preparedStatements.truncateBlockingWithoutSnapshot();
}
- public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Prepared> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ boolean possibleLeakDetected = false;
+ // accumulate the number of bytes loaded into the prepared cache, if it exceeds the cache size, assume we've
+ // encountered a leak and stop loading prepared statements.
+ long preparedBytesLoaded = 0L;
+ long cacheCapacity = QueryProcessor.getPreparedStatementsCacheMaximumCapacity();
for (UntypedResultSet.Row row : resultSet)
{
- if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
- row.getString("query_string"),
- row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
+ Prepared prepared = onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
+ row.getString("query_string"),
+ row.has("logged_keyspace") ? row.getString("logged_keyspace") : null);
+ if (prepared != null)
+ {
counter++;
+ preparedBytesLoaded += Math.max(0, prepared.pstmntSize);
+ }
+
+ if (counter % pageSize == 0)
+ {
+ if (possibleLeakDetected)
+ {
+ logger.warn("Detected prepared statement cache filling up during preload after preparing {} " +
Review Comment:
I think it now reads much cleaner :-)
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2035557751
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
When I wrote this test I was more of the mindset of ensuring that introducing paging didn't put us in position where we missed preloading statements, less about the paging itself, but I think that should definitely be verifiable, will add that :+1:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2035566355
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -155,6 +155,12 @@ private enum InternalStateInstance
}
public void preloadPreparedStatements()
+ {
+ preloadPreparedStatements(5000);
Review Comment:
:+1: agreed, especially since its used in multiple places. I'll introduce a constant.
One thing we've learned since deploying this is that paging does prevent OOMing Cassandra on start up, but the fact that in some cases we preload millions of leaked statements, it can defer startup almost indefinitely. To get around that we've truncated the prepared_statements table, but have only had to do that in like 2 or 3 out of hundreds of clusters. I've considered capping the number of statements read and then perhaps truncating the table after, but that feels somewhat wrong to do, especially since the leaking statement issue should go away after this fix, and given this bug has been present for a long time (but exacerbated by the caffeine library change in 4.1+), it didn't feel right to do that. I think I'll add a warning after ~100k rows are read and leave it at that.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2041973384
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -35,20 +43,32 @@
import org.apache.cassandra.transport.Dispatcher;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.MD5Digest;
+import org.jboss.byteman.contrib.bmunit.BMRule;
+import org.jboss.byteman.contrib.bmunit.BMRules;
+import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
import static java.util.Collections.emptyMap;
import static org.apache.cassandra.service.QueryState.forInternalCalls;
import static org.junit.Assert.*;
+@RunWith(BMUnitRunner.class)
public class PstmtPersistenceTest extends CQLTester
{
+ private static final CompletableFuture<?>[] futureArray = new CompletableFuture[0];
+
+ private static final ConcurrentMap<MD5Digest, Long> preparedStatementLoadTimestamps = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<MD5Digest, Long> preparedStatementRemoveTimestamps = new ConcurrentHashMap<>();
+
@Before
public void setUp()
{
+ preparedStatementLoadTimestamps.clear();
+ preparedStatementRemoveTimestamps.clear();
+
QueryProcessor.clearPreparedStatements(false);
}
-
- @Test
+
+
Review Comment:
Why remove this?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042007900
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -101,6 +102,12 @@ public class QueryProcessor implements QueryHandler
// counters. Callers of processStatement are responsible for correctly notifying metrics
public static final CQLMetrics metrics = new CQLMetrics();
+ // Paging size to use when preloading prepared statements.
+ public static final int PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE = 5000;
+
+ // Maximum number of prepared statements to preload from prepared statement cache.
+ public static final int PRELOAD_PREPARED_STATEMENTS_MAX = 1_000_000;
Review Comment:
Thinking about it we don't need to come up with this new limit. We already have a limit on the cache size in MB. Once you hit that it makes no sense to just be trashing the cache. So just drop this and monitor cache instead.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042010682
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1865,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE,
+ QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize, int max)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter >= max)
Review Comment:
Here you could check cache size every page, not every record for perf reasons, dropping `max' which we won't need.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040848056
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt < statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ assertNotEquals("Should have evicted some prepared statements", 0, numberOfEvictedStatements() - initialEvicted);
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ @Test
+ public void testPreloadPreparedStatements() throws Throwable
Review Comment:
I couldn't find a good example of paging tests using byteman to assert that paging actually happened, but I did find a lot of good inspiration in tests using byteman generally to make this work, hopefully the way I went about this looks alright.
I figured I would keep this test since `testCachedPreparedStatements` only creates a very small amount of prepared statements (~7) and working with on the order of hundreds of statements made it a little easier to validate paging and also validate the additional logic I had to prevent loading past a maximum amount of statements.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2077439698
##########
src/java/org/apache/cassandra/db/SystemKeyspace.java:
##########
@@ -1863,16 +1864,37 @@ public static void resetPreparedStatements()
}
public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded)
+ {
+ return loadPreparedStatements(onLoaded, QueryProcessor.PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE);
+ }
+
+ public static int loadPreparedStatements(TriFunction<MD5Digest, String, String, Boolean> onLoaded, int pageSize)
{
String query = String.format("SELECT prepared_id, logged_keyspace, query_string FROM %s.%s", SchemaConstants.SYSTEM_KEYSPACE_NAME, PREPARED_STATEMENTS);
- UntypedResultSet resultSet = executeOnceInternal(query);
+ UntypedResultSet resultSet = executeOnceInternalWithPaging(query, pageSize);
int counter = 0;
+ long initialStatementsEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
for (UntypedResultSet.Row row : resultSet)
{
if (onLoaded.accept(MD5Digest.wrap(row.getByteArray("prepared_id")),
row.getString("query_string"),
row.has("logged_keyspace") ? row.getString("logged_keyspace") : null))
counter++;
+
+ if (counter % pageSize == 0 && QueryProcessor.isPreparedStatementCacheFull())
+ {
+ // In the event that we detect that the prepared statement cache has filled up, return early to prevent
Review Comment:
That 1% you added is like the 5% I was suggesting iiuc.
But you know sometimes I'm just an idiot. As every pstmnt comes with it's size precomputed now, you can add those as you load them. Then compare against the max weight of the cache trashing and simplifying all this. You stop loading when the accumulated size > caffeine max weight.
Trash all those page boundaries, cache full methods, counters, % guards,...
Apologies about the noise. I don't know how I didn't think about it before :shrug:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079223770
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
Review Comment:
An alternative no relying on cache evictions could be:
```
While(insertedPstmntsSize < Config.pStmntCacheSize)
{
insert pstmnt
insertedPstmntsSize += pstmnt.size
insertedPstmntsCount ++
}
count = preloadPreparedStaments()
Assert counts match
Assert warn was issued
```
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2081049515
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -178,7 +400,6 @@ private MD5Digest prepareStatement(String stmt, ClientState clientState)
private MD5Digest prepareStatement(String stmt, String keyspace, String table, ClientState clientState)
{
- System.out.println(stmt + String.format(stmt, keyspace + "." + table));
Review Comment:
That's amazing lol. Good catch
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2079151482
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,203 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementRemoveTimestamps.put($key, org.apache.cassandra.service.ClientState.getTimestamp());"
+ )
+ })
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(ReadQuery query, int pageSize)
+ {
+ TableMetadata metadata = query.metadata();
+ if (metadata.keyspace.equals(SchemaConstants.SYSTEM_KEYSPACE_NAME) &&
+ metadata.name.equals(SystemKeyspace.PREPARED_STATEMENTS) &&
+ pageSize == PRELOAD_PAGE_SIZE)
+ {
+ for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace())
+ {
+ if (stackTraceElement.getClassName().equals(QueryProcessor.class.getName()) && stackTraceElement.getMethodName().equals("preloadPreparedStatements"))
+ {
+ pageInvocations.incrementAndGet();
+ return;
+ }
+ }
+ }
+ }
+
+ @Test
+ @BMRule(name = "CapturePageInvocations",
+ targetClass = "PartitionRangeQueryPager",
+ targetMethod = "nextPageReadQuery(int)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.nextPageReadQuery($this.query, $pageSize)")
+ public void testPreloadPreparedStatements() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Prepare more statements than the paging size to ensure paging works properly.
+ int statementsToPrepare = 750;
+
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
+ }
+
+ // Capture how many statements are in memory before clearing cache.
+ long statementsInMemory = numberOfStatementsInMemory();
+ long statementsOnDisk = numberOfStatementsOnDisk();
+ assertEquals(statementsOnDisk, statementsInMemory);
+
+ // Drop prepared statements from cache only and ensure the cache empties out.
+ QueryProcessor.clearPreparedStatements(true);
+ assertEquals(0, numberOfStatementsInMemory());
+
+ // Load prepared statements and ensure the cache size matches max
+ QueryProcessor.instance.preloadPreparedStatements(PRELOAD_PAGE_SIZE);
+
+ long statementsInMemoryAfterLoading = numberOfStatementsInMemory();
+ // Ensure size of cache matches statements that were on disk before preload
+ assertEquals("Statements prepared - evicted (expected) does not match statements in memory (actual)",
+ statementsOnDisk, statementsInMemoryAfterLoading);
+
+ // Number of statements on disk shold match memory
+ assertEquals(statementsInMemoryAfterLoading, numberOfStatementsOnDisk());
+
+ // Ensure only executed the expected amount of pages.
+ int expectedPageInvocations = (int) Math.ceil(statementsInMemoryAfterLoading / (double) PRELOAD_PAGE_SIZE);
+ assertEquals(expectedPageInvocations, pageInvocations.get());
+ }
+
+ @Test
+ public void testPreloadPreparedStatementsUntilCacheFull()
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // Fill up and clear the prepared statement cache several times to load up the system.prepared_statements table.
+ // This simulates a 'leak' of prepared statements akin to CASSANDRA-19703 as the system.prepared_statements
+ // table is able to grow to a larger size than the in memory prepared statement cache. In such a case we
+ // should detect a possible leak and defer paging indefinitely by returning early in preloadPreparedStatements.
+ int fillIterations = 5;
+ int cnt = 1;
+ int statementsLoadedBeforeFull = -1;
+ for (int fillIteration = 0; fillIteration < fillIterations; fillIteration++)
+ {
+ long initialEvicted = QueryProcessor.metrics.preparedStatementsEvicted.getCount();
+ // load prepared statements until we detect any eviction, on eviction we assume cache was filled.
+ while (QueryProcessor.metrics.preparedStatementsEvicted.getCount() == initialEvicted)
+ {
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
Review Comment:
No variables bound?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042001171
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.recordEvictionTimestamp($key);")
+ }
+ )
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ // page size passed to preloadPreparedStatements
+ private static final int PRELOAD_PAGE_SIZE = 100;
+ // recorded page invocations in preloadPreparedStatements
+ private static int PAGE_INVOCATIONS = 0;
+
+ /**
+ * Invoked whenever paging happens in testPreloadPreparedStatements, increments PAGE_INVOCATIONS when we detect
+ * paging happening in the path of QueryProcessor.preloadPreparedStatements with the expected page size.
+ */
+ @SuppressWarnings("unused")
+ private static void nextPageReadQuery(int pageSize)
+ {
+ if (pageSize == PRELOAD_PAGE_SIZE)
Review Comment:
This is super hacky and brittle. Can't you access through `$0` the query member of `PartitionRangeQueryPager` to check it is indeed the right CF and that should be enough?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2041976042
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
Review Comment:
Formatting
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2041996064
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +162,179 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"),
+ @BMRule(name = "CaptureEvictTimestamps",
+ targetClass = "QueryProcessor",
+ targetMethod = "evictPreparedStatement(MD5Digest, RemovalCause)",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.recordEvictionTimestamp($key);")
+ }
+ )
+ public void testAsyncPstmtInvalidation() throws Throwable
+ {
+ ClientState clientState = ClientState.forInternalCalls();
+ createTable("CREATE TABLE %s (key int primary key, val int)");
+
+ // prepare statements concurrently in a thread pool to exercise bug encountered in CASSANDRA-19703 where
+ // delete from table occurs before the insert due to early eviction.
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+
+ long initialEvicted = numberOfEvictedStatements();
+ try
+ {
+ int statementsToPrepare = 10000;
+ List<CompletableFuture<MD5Digest>> prepareFutures = new ArrayList<>(statementsToPrepare);
+ for (int cnt = 1; cnt <= statementsToPrepare; cnt++)
+ {
+ final int localCnt = cnt;
+ prepareFutures.add(CompletableFuture.supplyAsync(() -> prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + localCnt, clientState), executor));
+ }
+
+ // Await completion
+ CompletableFuture.allOf(prepareFutures.toArray(futureArray)).get(10, TimeUnit.SECONDS);
+
+ long evictedStatements = numberOfEvictedStatements() - initialEvicted;
+ assertNotEquals("Should have evicted some prepared statements", 0, evictedStatements);
+
+ // Recorded prepared statement removals should match metrics
+ assertEquals("Actual evicted statements does not match metrics", evictedStatements, preparedStatementRemoveTimestamps.size());
+
+ // For each prepared statement evicted, assert the time it was deleted is greater than the timestamp
+ // used for when it was loaded.
+ for (Map.Entry<MD5Digest, Long> evictedStatementEntry : preparedStatementRemoveTimestamps.entrySet())
+ {
+ MD5Digest key = evictedStatementEntry.getKey();
+ long deletionTimestamp = evictedStatementEntry.getValue();
+ long insertionTimestamp = preparedStatementLoadTimestamps.get(key);
+
+ assertTrue(String.format("Expected deletion timestamp for prepared statement (%d) to be greater than insertion timestamp (%d)",
+ deletionTimestamp, insertionTimestamp),
+ deletionTimestamp > insertionTimestamp);
+ }
+
+ // ensure the number of statements on disk match the number in memory, if number of statements on disk eclipses in memory, there was a leak.
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+ }
+ finally
+ {
+ executor.shutdown();
+ }
+ }
+
+ // page size passed to preloadPreparedStatements
+ private static final int PRELOAD_PAGE_SIZE = 100;
+ // recorded page invocations in preloadPreparedStatements
+ private static int PAGE_INVOCATIONS = 0;
Review Comment:
This should probably be volatile and lowercase as it is not a constant. Both should be defined at the top where we define such stuff in all tests, just for consistency.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2042201475
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -101,6 +102,12 @@ public class QueryProcessor implements QueryHandler
// counters. Callers of processStatement are responsible for correctly notifying metrics
public static final CQLMetrics metrics = new CQLMetrics();
+ // Paging size to use when preloading prepared statements.
+ public static final int PRELOAD_PREPARED_STATEMENTS_FETCH_SIZE = 5000;
+
+ // Maximum number of prepared statements to preload from prepared statement cache.
+ public static final int PRELOAD_PREPARED_STATEMENTS_MAX = 1_000_000;
Review Comment:
:+1: (further discussion [here](https://github.com/apache/cassandra/pull/3917#discussion_r2042139638))
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2036595740
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Rather than doing a sort of E2E test, which will be heavy on CI and execution times, we could target the actual fix itself. I picture this as adding to `testPstmtInvalidation` some byteman checking timestamps were used both in inserts and deletions. But that's just me, just a suggestion.
That way you test the specifics and avoid adding unnecessary CI load.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2043869924
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
Review Comment:
Could this be removed and call `put` directly as you do with `preparedStatementLoadTimestamps`?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bschoening (via GitHub)" <gi...@apache.org>.
bschoening commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2046984826
##########
doc/modules/cassandra/pages/cql/cql_singlefile.adoc:
##########
@@ -239,6 +239,20 @@ provide values for `LIMIT`, `TIMESTAMP`, and `TTL` clauses. If anonymous
bind markers are used, the names for the query parameters will be
`[limit]`, `[timestamp]`, and `[ttl]`, respectively.
+Prepared Statements are cached by cassandra in-memory which can be
Review Comment:
@tolbertam looks great, thanks!
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040858768
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Thanks for the byteman instrumentation suggestion. I added something for that which enables the test to ensure that all load timestamps precede delete timestamps and it seems to work quite well.
While it looks like the test is doing quite a bit, it's not actually doing much more than `testPstmtInvalidation` other than preparing statements asynchronously with a concurrency of 10 in an executor and with some additional validation. The test takes on the order of ~1200ms where testPstmtInvalidation takes ~500ms.
I think there is still some value in it as it is more representative of how prepared statements can be prepared in practice (multiple threads preparing statements concurrently), but I'm also ok with just merging the validation i added here into `testPstmtInvalidation`, let me know what you think :+1:
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2040864803
##########
src/java/org/apache/cassandra/cql3/QueryProcessor.java:
##########
@@ -155,6 +155,12 @@ private enum InternalStateInstance
}
public void preloadPreparedStatements()
+ {
+ preloadPreparedStatements(5000);
Review Comment:
I added something for this that logs when we exceed `QueryProcessor.PRELOAD_PREPARED_STATEMENTS_MAX` (1 million).
I thought a little bit more about how I would have wanted this to work, and rather than having it just log and continue plugging away for hours or days, that we just short circuit and stop reading after an excessive amount of rows.
> WARN [main] 2025-04-12 20:17:30,536 SystemKeyspace.java:1893 - Preloaded 250 prepared statements. This could be an indication that prepared statements leaked prior to CASSANDRA-19703 being fixed. Returning early to prevent indefinite startup. Consider truncating system.prepared_statements to clear out leaked prepared statements.
The up side here is no user intervention is needed here unless one *really* wants the optimization of prepared statements being preloaded on startup. If one gets into this situation where you have leaked over 1 million prepared statements, it's likely the operator wasn't aware that they hadn't benefitted from this functionality for quite some time and that misconfigurations in application code had caused a lot of unique prepared statements.
The downside is that the prepared statement table may eventually never be drained without user intervention. But I consider this a better tradeoff than nodes not starting after hours or days.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2045516921
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
Review Comment:
🤦 good catch,will fix this shortly.
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +172,172 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+ /**
+ * Invoked by byteman whenever QueryProcessor.evictPreparedStatement is called in testAsyncPstmtInvalidation
+ */
+ @SuppressWarnings("unused")
+ private static void recordEvictionTimestamp(MD5Digest key)
+ {
+ preparedStatementRemoveTimestamps.put(key, ClientState.getTimestamp());
+ }
+
+
+ @Test
+ @BMRules(rules= {
+ @BMRule(name = "CaptureWriteTimestamps",
+ targetClass = "SystemKeyspace",
+ targetMethod = "writePreparedStatement(String, MD5Digest, String, long)",
+ targetLocation = "AT INVOKE executeInternal",
+ action = "org.apache.cassandra.cql3.PstmtPersistenceTest.preparedStatementLoadTimestamps.put($key, $timestamp);"
+ ),
+ @BMRule(name = "CaptureEvictTimestamps",
Review Comment:
🤦 good catch, will fix this shortly.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-19703: Ensure prepared_statement INSERT timestamp precedes eviction DELETE [cassandra]
Posted by "bereng (via GitHub)" <gi...@apache.org>.
bereng commented on code in PR #3917:
URL: https://github.com/apache/cassandra/pull/3917#discussion_r2034776690
##########
test/unit/org/apache/cassandra/cql3/PstmtPersistenceTest.java:
##########
@@ -142,19 +148,103 @@ public void testPstmtInvalidation() throws Throwable
createTable("CREATE TABLE %s (key int primary key, val int)");
+ long initialEvicted = numberOfEvictedStatements();
+
for (int cnt = 1; cnt < 10000; cnt++)
{
prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt, clientState);
- if (numberOfEvictedStatements() > 0)
+ if (numberOfEvictedStatements() - initialEvicted > 0)
{
+ assertEquals("Number of statements in table and in cache don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
+ // prepare a more statements to trigger more evictions
+ for (int cnt2 = cnt + 1; cnt2 < cnt + 10; cnt2++)
+ prepareStatement("INSERT INTO %s (key, val) VALUES (?, ?) USING TIMESTAMP " + cnt2, clientState);
+
+ // each new prepared statement should have caused an eviction
+ assertEquals("eviction count didn't increase by the expected number", 10, numberOfEvictedStatements() - initialEvicted);
+ assertEquals("Number of statements in memory (expected) and table (actual) don't match", numberOfStatementsInMemory(), numberOfStatementsOnDisk());
+
return;
}
}
fail("Prepared statement eviction does not work");
}
+
+
+ @Test
+ public void testAsyncPstmtInvalidation() throws Throwable
Review Comment:
Does this deterministically fail without the fix? Have you explored using byteman to try to register if the right code paths are hit instead i.e.?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org