OK, so getPageToModify and updatePageVersion are in the PageManager. Let me look at them to understand the page version checking mechanism. I need to understand how the version check works and why it's not catching the conflict.
But first, let me think about the root cause again. The issue says:
a following serialized append reads a stale sampleCountInPage — the prior append's count → N+1 increment is not visible
So the problem is that when the nested TX commits, the page is updated in the PageManager, but the actual dirty data isn't flushed to the shared page cache yet. Or, the page version is updated but the content read by the next TX is stale.
Let me look at the page manager's getPageToModify and updatePageVersion to understand the flow.
Actually, let me focus on the core issue. The problem is:
- Thread A reads page, writes count=N+1
- Thread A commits nested TX
- Thread B reads page, sees count=N (STALE!)
This can only happen if:
- The page manager's dirty set isn't properly flushed between TX commits, OR
- The page version check isn't catching the conflict
Let me look at the updatePageVersion method to understand the version check.
Actually, wait. I think I finally understand the issue!
When db.commit() is called on the nested TX, it commits the changes to the page manager. But the popIfNotLastTransaction() is called, which removes the nested TX from the transaction stack. This means the nested TX's modifiedPages map is DISCARDED (set to null).
But here's the key: when the outer TX eventually commits, it looks at the outer TX's modifiedPages map, which does NOT include the pages modified by the nested TX (because they were in the nested TX's map, which was discarded).
So the outer TX's commit doesn't see the page changes made by the nested TX. And if the outer TX is committing multiple appends that were all nested inside it, the page changes from ALL the nested appends are lost!
Wait, but that doesn't make sense either. The nested TX commit calls updatePages, which updates the page versions. So the pages should be visible to subsequent reads.
Let me think about this differently. Maybe the issue is with how the page manager's dirty set works.
When the nested TX commits:
updatePages is called, which writes the modified pages to disk
- The page version is updated in the PageManager
- The dirty set is cleared for these pages
When the next nested TX begins and tries to read the page:
- It calls
getPageToModify
- If the page is in the dirty set (from the outer TX), it returns the dirty copy
- Otherwise, it loads the page from disk (or from the page cache)
But if the nested TX commit wrote the pages to disk and updated the page version, then the next read should see the updated data.
UNLESS... the issue is that the nested TX commit doesn't actually flush the dirty set. Let me check the code.
Actually, looking at the TransactionContext.commit2ndPhase:
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush);
This calls updatePages which:
- Writes the WAL
- Updates the page versions
- Flushes the pages to disk
After this, the pages should be on disk with the updated data and version.
When the next TX begins and reads the page:
- If the page is already in the page cache (from the previous load), it should have the latest data
- If the page needs to be loaded, it should load from disk with the latest version
So why would the read be stale?
OK, I think I need to look at the actual code flow more carefully. Let me look at the getPageToModify method.
Actually, let me re-think this. The issue says the collision detector confirmed that the reads are stale. So something IS going wrong. Let me focus on making a fix.
The issue description suggests:
Any fix needs to make the slot read-modify-write atomic with respect to the actual publish without breaking HA replication
The simplest fix would be to not use nested transactions at all. Instead, the TimeSeriesShard.appendSamples should operate directly within the outer transaction's context. This way, all appends share the same TX and see each other's changes.
But the problem with this approach is that the appendLock is supposed to prevent MVCC conflicts on page 0. If we don't use nested TX, multiple concurrent appends would modify page 0 within the same outer TX, and the MVCC conflict detection might kick in.
Actually wait, if all appends are within the same outer TX, there's no MVCC conflict because they're all in the same transaction. The MVCC conflict only arises when multiple TRANSACTIONS modify the same page.
So the fix could be:
- Remove the nested TX from
TimeSeriesShard.appendSamples
- Just use the outer TX directly
But wait, the code comment says:
Route through the HA wrapper so the mutable-bucket page writes are shipped to followers via the Raft WAL (TX_ENTRY)
So the HA replication needs the writes to go through the wrapped database. But if we use the outer TX directly, the writes would go through the original database, not the wrapped database.
Hmm, this is tricky. Let me think about this more carefully.
Actually, I think the issue is specifically with the nested TX behavior. When a nested TX commits, it:
- Commits its own changes to the page manager
- Pops itself from the transaction stack
But the outer TX's dirty set is NOT updated with the nested TX's changes. This means:
- The nested TX's changes are flushed to disk
- But the outer TX doesn't know about these changes
When the next nested TX begins:
- It creates a new TransactionContext
- It reads from the page manager
Since the previous nested TX committed and flushed to disk, the next nested TX should see the updated data. So the issue must be elsewhere.
OK, let me look at this from a completely different angle. Let me check if the database in TimeSeriesBucket.appendSamples is the same as the one used by TimeSeriesShard.appendSamples.
Actually, I realize I've been going in circles. Let me just look at the actual fix needed based on the issue description.
The issue says:
The core tension is that appendLock serializes the in-memory append but the durable publish is deferred to the enclosing transaction's commit
So the fix should make the slot read-modify-write atomic. One simple approach:
- Keep the appendLock serialization
- Don't use nested transactions
- Instead, just read/write the pages directly within the outer transaction's context
But wait, there's a complication. The code says:
Route through the HA wrapper so the mutable-bucket page writes are shipped to followers via the Raft WAL
If we don't route through the HA wrapper, the writes won't be replicated to followers.
Hmm, actually, looking at the code more carefully:
public TimeSeriesShard(final DatabaseInternal database, ...) {
this.database = database;
// ...
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.initHeaderPage();
db.commit();
}
}
The mutableBucket is initialized with database (the original), not getWrappedDatabaseInstance(). So mutableBucket.database is the original database.
And in appendSamples:
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues); // Uses database, not db!
db.commit();
}
So mutableBucket.appendSamples uses database (the original), while db.begin() and db.commit() use the wrapped database.
If the original database and wrapped database have the SAME database path, then getTransaction() returns the same transaction context for both. But if they have DIFFERENT paths, they have DIFFERENT transaction contexts.
For a LocalDatabase, getWrappedDatabaseInstance() returns this, so the paths are the same. But for a ServerDatabase, getWrappedDatabaseInstance() returns the wrapped LocalDatabase, and getDatabasePath() is forwarded. So the paths are still the same.
Wait, but looking at ServerDatabase.getDatabasePath():
@Override
public String getDatabasePath() {
return wrapped.getDatabasePath();
}
So ServerDatabase.getDatabasePath() returns the same path as the wrapped database. And ServerDatabase.getTransactionIfExists() also delegates to the wrapped database.
So for ServerDatabase, the transaction context is the same as the wrapped database's context.
OK, I think the issue is simpler than I thought. Let me look at the LocalDatabase's getTransaction():
Actually, let me just look at how the transaction context is managed. The key is in DatabaseContext:
public DatabaseContextTL getContext(final String databasePath) {
DatabaseContextTL result = contexts.get(databasePath);
if (result == null) {
synchronized (this) {
result = contexts.get(databasePath);
if (result == null) {
result = new DatabaseContextTL();
contexts.put(databasePath, result);
}
}
}
return result;
}
So the transaction context is keyed by databasePath. If two databases have the same path, they share the same DatabaseContextTL.
And in DatabaseContextTL:
public TransactionContext getLastTransaction() {
return transactions.isEmpty() ? null : transactions.peekLast();
}
So if multiple threads call begin() on the same database path, they push their transactions onto the same DatabaseContextTL. But since each thread pushes its own transaction, they should see the latest transaction on their thread.
Wait, no. The DatabaseContextTL is per-database-path, not per-thread. So multiple threads sharing the same database path share the same DatabaseContextTL. And getLastTransaction() returns the last transaction on the stack, which might be from a different thread!
Hmm, but that doesn't seem right. Transactions are typically per-thread. Let me look at DatabaseContextTL more carefully.
Actually, looking at the code:
public static class DatabaseContextTL {
private Deque<TransactionContext> transactions = new ArrayDeque<>();
public TransactionContext getLastTransaction() {
return transactions.isEmpty() ? null : transactions.peekLast();
}
public void pushTransaction(TransactionContext tx) {
transactions.addLast(tx);
}
public TransactionContext popIfNotLastTransaction() {
if (transactions.size() > 1)
return transactions.pollLast();
return null;
}
public boolean isTransactionActive() {
return !transactions.isEmpty() && transactions.peekLast().isActive();
}
}
OK so the DatabaseContextTL has a deque of transactions. Multiple threads push their transactions onto the same deque. getLastTransaction() returns the last one, which is the most recently pushed.
This means that if Thread A pushes a transaction, and then Thread B pushes a transaction, getLastTransaction() returns Thread B's transaction, regardless of which thread calls it.
This is the race condition! Let me trace through the scenario:
-
Thread A: begin() -> pushes TX1
-
Thread A: db.begin() -> creates nested TX2, pushes TX2
-
Thread A: mutableBucket.appendSamples -> calls database.getTransaction() -> returns TX2 (last transaction on the deque)
-
Thread A: TX2 reads page, writes data, increments count
-
Thread A: db.commit() -> commits TX2, pops TX2
-
Thread A: appendLock.unlock()
-
Thread A: database.commit() -> commits TX1
-
Thread B: begin() -> pushes TX3
-
Thread B: db.begin() -> creates nested TX4, pushes TX4
-
Thread B: mutableBucket.appendSamples -> calls database.getTransaction() -> returns TX4
-
...
OK, this looks correct. Thread B's TX4 is the last transaction when Thread B begins, so Thread B sees its own transaction.
But wait, the issue is that Thread A's nested TX commits before Thread B's nested TX begins. So between steps 5 and 9, there's no transaction active. When Thread B calls begin(), it creates TX3, which is the top-level transaction. When Thread B calls db.begin(), it creates TX4, which is nested inside TX3.
So the flow is:
- Thread A: begin() -> TX1
- Thread A: db.begin() -> TX2 (nested inside TX1)
- Thread A: append -> TX2 reads/writes/count
- Thread A: db.commit() -> commits TX2, pops TX2
- Thread A: appendLock.unlock()
- Thread A: (TX1 still active)
- Thread B: begin() -> TX3 (pushed onto the same deque)
- Thread B: db.begin() -> TX4 (nested inside TX3, pushed onto the same deque)
- Thread B: append -> TX4 reads/writes/count
- Thread B: db.commit() -> commits TX4, pops TX4
- Thread B: appendLock.unlock()
Now, the question is: when TX4 (Thread B's nested TX) reads the page, does it see the count that TX2 (Thread A's nested TX) incremented?
The answer depends on how getPageToModify works. If the page is already loaded in the page cache (with the dirty changes from TX2), then TX4 should see the updated count. But if the page was flushed to disk between TX2's commit and TX4's read, then TX4 reads from disk, which should have the updated count.
So why would TX4 see a stale count?
Actually, I think the issue is that the page manager's getPageToModify might return the page from the dirty set of a DIFFERENT transaction. Let me check.
Hmm, actually, I think the issue might be more subtle. Let me look at the actual getPageToModify implementation.
Wait, I think I need to actually run the test to see the error. But first, let me understand the page version check mechanism.
Actually, let me focus on the fix. Based on the issue description, the simplest fix is to ensure that the per-page sample count is atomically incremented within the appendLock.
The approach would be:
- Remove the nested TX from TimeSeriesShard.appendSamples
- Operate directly on the outer transaction's pages
- Use a compare-and-swap (CAS) mechanism to atomically increment the sample count
But this is complex because it requires understanding the page versioning mechanism.
Alternatively, a simpler fix would be:
- Keep the appendLock
- After each append's nested TX commits, force a flush of the dirty pages to the page cache so subsequent reads see the changes
But this might not work if the nested TX commit doesn't flush to the page cache.
Actually, the simplest fix would be to not use nested TX at all. Instead, use the outer TX's context directly:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
This way, mutableBucket.appendSamples reads the outer TX's context, and all appends within the same outer TX share the same dirty page set.
But wait, the issue says:
The batched InfluxDB line-protocol path (POST /api/v1/ts/{db}/write) is not affected.
And looking at the batched path:
public void appendBatch(final long[] allTimestamps, final Object[][] allColumnValues) throws IOException {
// ...
futures.add(CompletableFuture.runAsync(() -> {
try {
shards[shardIdx].appendSamples(shardTs, shardCols);
} catch (final IOException e) {
throw new CompletionException(e);
}
}, shardExecutor));
// ...
}
The batched path also calls TimeSeriesShard.appendSamples, which uses nested TX. So why is the batched path safe?
Because the batched path groups all samples for a shard into a single call. So there's only one nested TX per shard, not multiple. The appendLock ensures only one call per shard runs at a time. And since there's only one call, there's no stale read issue.
The issue only happens when there are MULTIPLE nested TX calls to the same shard, each with its own begin/commit.
So the fix is to NOT use nested TX for single-row appends when an outer TX is already active. Instead, operate directly within the outer TX.
But wait, the batched path also calls appendSamples which uses nested TX. So why doesn't it have the same issue?
Because the batched path runs appendSamples with MULTIPLE samples in a single call. Within a single call, the appendSamples method iterates over the samples and reads/writes the count for each one. Since all these reads/writes happen within the same nested TX, the count increment is visible to the next iteration of the loop.
But in the single-row path, there's only ONE sample per call, and the nested TX commits immediately. So the next call sees a fresh nested TX with a potentially stale count.
So the fix could be:
- Don't use nested TX for single-row appends
- Instead, operate directly within the outer TX
Let me implement this fix.
Actually, wait. Looking at the batched path more carefully:
futures.add(CompletableFuture.runAsync(() -> {
try {
shards[shardIdx].appendSamples(shardTs, shardCols); // Multiple samples in one call
} catch (final IOException e) {
throw new CompletionException(e);
}
}, shardExecutor));
The batched path uses CompletableFuture.runAsync which runs the appends asynchronously. These are DIFFERENT from the outer TX's thread. And each appendSamples call is a separate transaction with its own nested TX.
But the issue says the batched path is NOT affected. Why?
Because the batched path dispatches appends to DIFFERENT shards (one per shard). Even though they're all running in parallel, each shard handles only one call at a time (due to the round-robin distribution and the appendLock).
Wait, but the issue says the batched path is safe because "there is never a second concurrent transaction reading a stale slot on the same page". This is because the batched path groups all samples for each shard into a single transaction.
OK so the issue is specifically with single-row appends, where each append is its own transaction.
Now, the key question is: should we remove the nested TX or should we fix the page versioning?
I think the simplest fix is to remove the nested TX for single-row appends. Instead, just operate directly within whatever TX is currently active.
But there's a complication: the HA replication. The code comment says:
Route through the HA wrapper so the mutable-bucket page writes are shipped to followers via the Raft WAL (TX_ENTRY)
If we remove the nested TX, the writes would go through the outer TX. But the outer TX might be on the original database, not the wrapped database. So the writes wouldn't be replicated.
Hmm, but looking at the code, the outer TX is started by the caller, and the caller should be using the wrapped database if they want HA replication. So if we just operate within the outer TX's context, the writes should be properly replicated.
Actually, let me look at the SaveElementStep to see how the outer TX is started:
OK, I think I'm overcomplicating this. Let me just look at the simplest fix: remove the nested TX from TimeSeriesShard.appendSamples.
If an outer TX is active, mutableBucket.appendSamples will operate within that TX. The appendLock will serialize the appends. The page changes will be committed when the outer TX commits.
If no outer TX is active, we need to start a new TX. We can do this by calling db.begin() without checking if there's already an active TX.
But wait, the issue is that the nested TX is specifically designed to avoid MVCC conflicts on page 0. If we remove the nested TX and operate within the outer TX, we might have MVCC conflicts if multiple appends modify page 0 concurrently.
But the appendLock serializes the appends, so there shouldn't be concurrent modifications to page 0 within the same outer TX. So there should be no MVCC conflict.
OK let me just implement the fix and test it.
Actually, wait. Let me re-read the issue description one more time:
TimeSeriesShard.appendSamples serializes appends per shard with a appendLock around a nested db.begin()/append/db.commit() on getWrappedDatabaseInstance() (and the comment there notes the lock exists specifically to avoid a commit-time ConcurrentModificationException on page 0).
So the appendLock exists to avoid MVCC conflicts on page 0. The MVCC conflict arises when TWO TRANSACTIONS both modify page 0. The nested TX isolates each append's changes to its own TX, so the MVCC conflict is avoided.
But the problem is that the nested TX commit doesn't flush the changes to the outer TX's dirty set. So subsequent appends don't see the previous append's changes.
The fix should be to either:
- Make the nested TX commit flush changes to the outer TX's dirty set, OR
- Remove the nested TX and operate directly within the outer TX
Option 2 is simpler, but I need to make sure the MVCC conflict issue doesn't arise.
Since the appendLock serializes the appends, there's no concurrency within the same outer TX. So there shouldn't be MVCC conflicts.
Let me implement option 2.
The fix:
- In TimeSeriesShard.appendSamples, remove the
db.begin()/db.commit() around the append
- Just call
mutableBucket.appendSamples directly, within the appendLock
This way, all appends within the same outer TX share the same TX context and see each other's changes.
But I need to make sure this works when there's NO outer TX active. In that case, we need to start a new TX.
Actually, let me check if there's a way to detect if an outer TX is active:
if (database.isTransactionActive()) {
// An outer TX is active, operate within it
mutableBucket.appendSamples(timestamps, columnValues);
} else {
// No outer TX active, start a new TX
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
} catch (final Exception e) {
if (db.isTransactionActive())
db.rollback();
throw e instanceof IOException ? (IOException) e : new IOException("Failed to append timeseries samples", e);
}
}
This should work for both cases:
- When an outer TX is active, all appends within the outer TX share the same TX context
- When no outer TX is active, each append has its own TX
But wait, case 2 is the same as before (nested TX). The issue is that when there's an outer TX, the nested TX commit doesn't flush changes to the outer TX.
Actually, let me reconsider. The issue is specifically when an outer TX is active. In that case, the nested TX commit doesn't flush to the outer TX's dirty set.
So the fix should be:
- When an outer TX is active, don't use nested TX. Operate directly within the outer TX.
- When no outer TX is active, use a top-level TX (not nested).
Let me implement this:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
if (database.isTransactionActive()) {
// Outer TX is active. Operate within it so all appends see each other's changes.
mutableBucket.appendSamples(timestamps, columnValues);
} else {
// No outer TX. Start a new TX on the wrapped database for HA replication.
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
} catch (final Exception e) {
if (db.isTransactionActive())
db.rollback();
throw e instanceof IOException ? (IOException) e : new IOException("Failed to append timeseries samples", e);
}
}
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
Wait, but there's still an issue. If an outer TX is active, but it's on the original database, and the HA replication is on the wrapped database, then the writes won't be replicated.
Actually, let me think about this more carefully. The outer TX is started by the caller, which should be the ServerDatabase or LocalDatabase. And the HA replication is on the wrapped database.
If the caller is using the ServerDatabase, then the outer TX is on the ServerDatabase, which delegates to the wrapped LocalDatabase. So the writes would be replicated.
If the caller is using the LocalDatabase directly (embedded mode), then the outer TX is on the LocalDatabase, and getWrappedDatabaseInstance() returns this. So the writes would still be replicated (since they're the same database).
So the fix should work for both cases.
But wait, there's another issue. The issue description says:
The append commit is nested inside the enclosing request transaction (LocalDatabase.begin() pushes a nested TransactionContext when a transaction is already active), and the durable publish is effectively deferred to the outer transaction commit (intentionally, so the bucket page writes ship to followers via the parent Raft WAL TX_ENTRY — the code references issue #4382).
So the outer TX commit is intentionally deferred so the writes ship to followers. If we operate within the outer TX, the writes would still ship to followers when the outer TX commits.
OK, I think my fix is correct. Let me implement it.
Actually, wait. I need to also consider the case where the outer TX is NOT on the wrapped database. If the caller uses the original database, but the HA replication is on the wrapped database, then the writes might not be replicated.
Let me check how the HA replication works. Looking at the code, the HA replication is triggered by the getWrappedDatabaseInstance(). The wrapped database is the HAReplicatedDatabase, which replicates writes to followers.
So if we operate within the outer TX (on the original database), the writes might not be replicated through the HA wrapper.
Hmm, but if the original database IS the wrapped database (which is the case for embedded mode), then the writes would be replicated.
For server mode, the original database is the ServerDatabase, which delegates to the wrapped LocalDatabase. And the HA replication is on the LocalDatabase. So the writes would be replicated through the LocalDatabase.
OK, I think the fix is safe. Let me implement it.
Wait, actually, I think there might be a different issue. Let me re-read the code:
public TimeSeriesShard(final DatabaseInternal database, ...) {
this.database = database;
// ...
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.initHeaderPage();
db.commit();
}
}
So the mutableBucket is initialized with database, not db. And in appendSamples:
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
}
So mutableBucket.appendSamples uses database, while db.begin() and db.commit() use db (the wrapped database).
If database and db are the same object, then mutableBucket.appendSamples and db.begin()/db.commit() share the same transaction context. The nested TX is pushed onto the stack by db.begin(), and mutableBucket.appendSamples reads from the same stack.
But the issue is that after db.commit() commits the nested TX and pops it, the next db.begin() creates a new nested TX, which doesn't see the previous nested TX's changes.
So the fix should be: don't use nested TX. Operate directly within the outer TX.
Let me implement this:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
This removes the nested TX entirely. All appends operate within the outer TX's context. The appendLock serializes the appends. The page changes are committed when the outer TX commits.
But I need to make sure this works when there's NO outer TX active. Let me check:
If no outer TX is active, database.isTransactionActive() returns false. And mutableBucket.appendSamples calls database.getTransaction() which returns null.
Looking at mutableBucket.appendSamples:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
final TransactionContext tx = database.getTransaction();
for (int i = 0; i < timestamps.length; i++) {
final MutablePage dataPage = getOrCreateActiveDataPage(tx);
// ...
}
}
And getOrCreateActiveDataPage:
private MutablePage getOrCreateActiveDataPage(final TransactionContext tx) throws IOException {
final MutablePage headerPage = tx.getPageToModify(new PageId(database, fileId, 0), pageSize, false);
// ...
}
So tx.getPageToModify() is called. If tx is null (no active TX), this would throw a NullPointerException.
Hmm, but if no TX is active, database.getTransaction() would return null, and database.getTransactionIfExists() would also return null (or might throw an exception).
Let me check how getTransaction() works:
@Override
public TransactionContext getTransaction() {
return getTransactionIfExists();
}
@Override
public TransactionContext getTransactionIfExists() {
if (!isTransactionActive())
return null;
return getTransaction();
}
So getTransactionIfExists() returns null if no TX is active.
And getTransaction() calls getTransactionIfExists(), which returns null if no TX is active.
So if no TX is active, mutableBucket.appendSamples would get a null TX, and calling tx.getPageToModify() would throw a NullPointerException.
But wait, the original code had db.begin() before calling mutableBucket.appendSamples(), which starts a TX. So the original code always has an active TX when calling mutableBucket.appendSamples().
If I remove the db.begin(), I need to make sure there's always an active TX. I can do this by starting a new TX if no outer TX is active:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
final boolean hadTx = database.isTransactionActive();
if (!hadTx) {
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
}
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
if (!hadTx) {
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.commit();
}
}
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
This way:
- If an outer TX is active, we operate within it
- If no outer TX is active, we start a new TX on the wrapped database
Wait, but this still has the issue of using different databases for the begin/commit and the append. Let me simplify:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
// Use the wrapped database for begin/commit to ensure HA replication
final DatabaseInternal db = database.getWrappedDatabaseInstance();
final boolean hadTx = database.isTransactionActive();
if (!hadTx) {
db.begin();
}
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
if (!hadTx) {
db.commit();
}
}
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
Hmm, but this still uses database.isTransactionActive() to check if there's an outer TX, and db.begin()/db.commit() to start/stop a TX. If database and db are the same, this should work.
But if they're different (e.g., ServerDatabase wraps LocalDatabase), then database.isTransactionActive() checks the ServerDatabase's transaction, and db.begin() starts a TX on the LocalDatabase.
Actually, looking at ServerDatabase:
@Override
public TransactionContext getTransactionIfExists() {
return wrapped.getTransactionIfExists();
}
So ServerDatabase.getTransactionIfExists() delegates to wrapped.getTransactionIfExists(). And wrapped is the LocalDatabase. So database.isTransactionActive() and db.isTransactionActive() would return the same value (assuming db is the wrapped LocalDatabase).
OK, I think the fix is correct. Let me implement it.
Actually, wait. I just realized something. The issue says:
That outer commit happens outside appendLock.
So the issue is that the outer TX commits AFTER the appendLock is released. And the nested TX commit flushes the changes to the page manager, but the outer TX's commit doesn't know about these changes.
But if I remove the nested TX and operate within the outer TX, the page changes would be in the outer TX's dirty set. And when the outer TX commits, it would flush all the changes.
So the fix is simply: remove the nested TX.
Let me implement this now.
Wait, but I need to think about the case where there's NO outer TX. In that case, we need to start a new TX. But if we use db.begin() (on the wrapped database), and the wrapped database is different from the original database, then the TX might not be visible to the caller.
Actually, looking at the LocalDatabase code:
protected DatabaseInternal wrappedDatabaseInstance = this;
So by default, the wrapped instance IS the same as the original. And for ServerDatabase:
@Override
public String getDatabasePath() {
return wrapped.getDatabasePath();
}
So the wrapped database has the same path as the original. And TransactionContext is keyed by database path. So database.getTransaction() and db.getTransaction() would return the same transaction context.
OK, I think the fix is correct. Let me implement it.
The fix:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
Wait, but this assumes there's always an outer TX active. If there's no outer TX, mutableBucket.appendSamples would get a null TX and fail.
Let me check if this is a valid assumption by looking at how the API is used.
Looking at the test:
database.transaction(() ->
database.command("sql", "INSERT INTO Reading SET ts = ?, sid = ?, v = ?", ts, "s" + threadIndex, v));
So the test always wraps the INSERT in a database.transaction(). So there's always an outer TX.
But what about the batched write path? Let me check:
Looking at PostTimeSeriesWriteHandler:
database.transaction(() -> {
// ...
engine.appendBatch(timestamps, columns);
// ...
});
So the batched write also wraps in a database.transaction().
But what about direct calls to engine.appendSamples() without a transaction? Let me check if there's any such path.
Actually, looking at the async executor:
// In DatabaseAsyncExecutorImpl
database.transaction(() -> {
engine.appendSamples(timestamps, columnValues);
});
So even the async path uses a transaction.
OK, I think it's safe to assume there's always an outer TX. But to be extra safe, let me add a fallback:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
If there's no outer TX, mutableBucket.appendSamples would get a null TX. Let me check if it would fail:
Looking at TimeSeriesBucket.appendSamples:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
final TransactionContext tx = database.getTransaction();
for (int i = 0; i < timestamps.length; i++) {
final MutablePage dataPage = getOrCreateActiveDataPage(tx);
// ...
}
}
If tx is null, getOrCreateActiveDataPage(tx) would be called with null, and tx.getPageToModify() would throw NullPointerException.
So I need to handle the case where there's no outer TX. Let me add a fallback:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
if (!database.isTransactionActive()) {
// No outer TX: start our own on the wrapped database for HA replication
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
return;
} catch (final Exception e) {
if (db.isTransactionActive())
db.rollback();
throw e instanceof IOException ? (IOException) e : new IOException("Failed to append timeseries samples", e);
}
}
// Outer TX is active: operate within it so all appends see each other's changes
mutableBucket.appendSamples(timestamps, columnValues);
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
Hmm, but this still has the issue of starting a new TX when there's no outer TX. And if there are multiple threads calling this without an outer TX, each would have its own TX, and the stale read issue would still occur.
But wait, the issue specifically happens when there's an OUTER TX. When there's no outer TX, each append has its own top-level TX. And when a top-level TX commits, it flushes the changes to disk. So the next append would read from disk and see the updated count.
So the issue ONLY happens when there's an outer TX and nested TXs. And my fix removes the nested TX when there's an outer TX.
OK, let me implement the fix now.
Actually, wait. Let me re-read the original code one more time:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
// Serialize concurrent appends on this shard to prevent MVCC conflicts.
// Two concurrent nested transactions both modifying page 0 would otherwise produce a
// ConcurrentModificationException at commit time (current v.X <> database v.Y).
appendLock.lock();
try {
// Route the append transaction through the HA wrapper so the mutable-bucket page writes are
// shipped to followers via the Raft WAL (TX_ENTRY).
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
} catch (final Exception e) {
if (db.isTransactionActive())
db.rollback();
throw e instanceof IOException ? (IOException) e : new IOException("Failed to append timeseries samples", e);
}
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
So the db.begin() creates a nested TX when an outer TX is active. And the nested TX commits and pops itself. But the outer TX's dirty set is NOT updated.
And mutableBucket.appendSamples uses database.getTransaction(), which returns the current TX on the stack. If a nested TX is active, it returns the nested TX.
Wait, but the original code has db.begin() before mutableBucket.appendSamples(). And db is database.getWrappedDatabaseInstance(). So db.begin() creates a TX on the wrapped database. And mutableBucket.appendSamples() uses database.getTransaction(), which checks the original database's transaction stack.
If the original database and wrapped database have the same path, they share the same transaction stack. So db.begin() pushes a TX onto the stack, and database.getTransaction() returns that TX.
But if they have DIFFERENT paths, they have DIFFERENT transaction stacks. So db.begin() pushes a TX onto the wrapped database's stack, and database.getTransaction() returns the original database's top-level TX (which might be an outer TX).
This is the bug! The db.begin() and database.getTransaction() might use DIFFERENT transaction stacks!
Let me verify this by checking if they have the same path.
For LocalDatabase:
database.getDatabasePath() returns the path
database.getWrappedDatabaseInstance() returns this
- So
db.getDatabasePath() == database.getDatabasePath(). They have the same path.
For ServerDatabase:
database.getDatabasePath() delegates to wrapped.getDatabasePath()
database.getWrappedDatabaseInstance() returns wrapped
- So
db.getDatabasePath() == database.getDatabasePath(). They have the same path.
So for both cases, the paths are the same. And the transaction stack is the same.
OK so the bug is NOT with different transaction stacks. The bug is with how the nested TX commit handles the dirty pages.
Let me re-read the issue one more time:
TimeSeriesShard.appendSamples serializes appends per shard with a appendLock around a nested db.begin()/append/db.commit() on getWrappedDatabaseInstance()
OK so the appends are serialized by appendLock. Each append:
- Begins a nested TX
- Writes to the page (including incrementing the sample count)
- Commits the nested TX
- Releases the appendLock
And the issue is that after step 3, the next append doesn't see the count that the previous append incremented.
This can only happen if the nested TX commit doesn't flush the dirty pages to the shared page cache. Or, the nested TX commit flushes the dirty pages, but the next append reads from a different path (e.g., from disk before the commit was flushed).
Let me check the nested TX commit flow:
TransactionContext.commit() is called on the nested TX
commit2ndPhase is called
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush) is called
In updatePages, the page versions are updated and the dirty pages are written to disk.
Then, the nested TX is popped:
current.popIfNotLastTransaction();
So the nested TX's modifiedPages map is DISCARDED. The page changes are in the page manager, not in the outer TX's dirty set.
When the next nested TX begins:
db.begin() pushes a new nested TX
mutableBucket.appendSamples calls database.getTransaction() which returns the new nested TX
- The new nested TX reads pages
The question is: does the new nested TX read the updated pages from the page manager?
Looking at how pages are obtained in TransactionContext:
public MutablePage getPageToModify(final PageId pageId, final int pageSize, final boolean readOnly) {
MutablePage page = modifiedPages.get(pageId);
if (page != null)
return page;
page = newPages.get(pageId);
if (page != null)
return page;
final BasePage loadedPage = database.getPageManager().getPage(pageId, readOnly);
// ...
}
So the new nested TX first checks its own modifiedPages and newPages maps. If the page is not in these maps, it loads the page from the page manager.
But the page manager has the updated pages (from the previous nested TX's commit). So the new nested TX should read the updated page.
Unless... the page was loaded before the previous nested TX committed, and is still in the page cache.
Let me check the page cache mechanism:
Actually, I think the issue might be with the page manager's cache. Let me look at getPage:
Hmm, this is getting complicated. Let me just implement the fix and test it.
The fix is to not use nested TX when an outer TX is active. This way, all appends share the same TX context and see each other's changes.
Actually, I just thought of something. Let me re-read the issue description:
a following serialized append reads a stale sampleCountInPage — the prior append's count → N+1 increment is not visible
The key word is "serialized". The appends ARE serialized by appendLock. But the stale read still occurs.
This means the issue is NOT with concurrent appends. It's with how the nested TX commit handles the page changes.
OK, I think the fix is clear. Let me implement it.
Actually, I want to think about this one more time. The issue says the collision detector confirmed the stale read. This means that after Thread A's nested TX commits, Thread B's nested TX reads a stale count.
For this to happen, the page must NOT have been updated between Thread A's commit and Thread B's read. But the nested TX commit calls updatePages, which updates the page manager. So the page should be updated.
Unless... the page is cached in the page cache, and the cached version is NOT updated by updatePages.
Let me check the updatePages implementation:
<tool_call>
<function=bash_terminal>
<parameter=command>
sed -n '280,350p' /arcadedb/engine/src/main/java/com/arcadedb/engine/PageManager.java
</tool_call>