Now I understand the issue! Let me look at the CachedPage constructor:
public CachedPage(final MutablePage page, final boolean copyBuffer) {
this.pageId = page.pageId;
if (copyBuffer) {
// Deep copy
final byte[] srcArray = page.content.getContent();
final byte[] copied = Arrays.copyOf(srcArray, srcArray.length);
this.content = new Binary(copied, page.content.size());
} else {
this.content = page.content; // SHARED reference!
}
// ...
}
When copyBuffer is false, the CachedPage shares the SAME content reference as the MutablePage!
And looking at useAsMutable():
public MutablePage useAsMutable() {
final byte[] array = this.content.getByteBuffer().array();
// COPY THE CONTENT, SO CHANGES DOES NOT AFFECT IMMUTABLE COPY
return new MutablePage(pageId, size, Arrays.copyOf(array, array.length), version, content.size());
}
This COPIES the content when creating a MutablePage from CachedPage. Good.
But wait, the issue is the opposite direction. When a MutablePage is put into the cache with copyBuffer=false, the cache shares the MutablePage's content. Then if the MutablePage is modified AFTER being put in the cache, the cache would see the changes.
Actually, let me re-read the flow:
- Transaction A.N1 gets page from cache via
useAsMutable() - this COPIES the content
- A.N1 modifies the copied content
- A.N1 commits, creates
new CachedPage(page, false) - this SHARES the content with A.N1's MutablePage
- Now the cache and A.N1's MutablePage share the same content
- A.N1 is popped/discarded
- Transaction B.N1 gets page from cache via
useAsMutable() - this COPIES the content
At step 6, B.N1 should get a COPY of the content that includes A.N1's changes (because at step 3, the cache shares A.N1's content).
But wait, what if there's a race condition? What if step 6 happens BEFORE step 3 completes? No, that can't happen because of the appendLock.
Hmm, let me think about this differently. The issue might be that the page is being retrieved from a different source.
Actually, wait. Let me re-read getPageToModify:
public MutablePage getPageToModify(final PageId pageId, final int pageSize, final boolean isNew) throws IOException {
if (!isActive())
throw new TransactionException("Transaction not active");
MutablePage page = modifiedPages != null ? modifiedPages.get(pageId) : null;
if (page == null) {
if (newPages != null)
page = newPages.get(pageId);
if (page == null) {
// IF AVAILABLE REMOVE THE PAGE FROM IMMUTABLE PAGES TO KEEP ONLY ONE PAGE IN RAM
final ImmutablePage loadedPage = immutablePages.remove(pageId);
if (loadedPage == null)
// NOT FOUND, DELEGATES TO THE DATABASE
page = database.getPageManager().getMutablePage(pageId, pageSize, isNew, true);
else
page = loadedPage.modify();
if (isNew)
newPages.put(pageId, page);
else
modifiedPages.put(pageId, page);
}
}
return page;
}
The key is database.getPageManager().getMutablePage(). This calls the page manager to get a mutable page. But which database is this?
In TimeSeriesBucket.appendSamples:
final TransactionContext tx = database.getTransaction();
Where database is the bucket's database field. And in TimeSeriesShard.appendSamples:
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
// ...
mutableBucket.appendSamples(timestamps, columnValues);
The bucket's database field was set when the bucket was created:
this.mutableBucket = new TimeSeriesBucket(database, shardName, shardPath, columns);
Where database is the shard's database, which was set in the shard constructor from the engine's database.
So database in the bucket is the original database instance. When we call database.getTransaction(), we get the current transaction from the thread-local stack.
But the transaction was created by db.begin() where db = database.getWrappedDatabaseInstance().
If db and database are the same instance (standalone), then the transaction is on the same stack.
If db and database are different instances (HA), then the transaction might be on a different stack!
Let me check if this is the issue. In HA mode, getWrappedDatabaseInstance() might return a wrapper that has its own transaction management.
Actually, looking at the LocalDatabase class:
public void begin(final TRANSACTION_ISOLATION_LEVEL isolationLevel) {
executeInReadLock(() -> {
// ...
final DatabaseContext.DatabaseContextTL current = DatabaseContext.INSTANCE.getContext(databasePath);
TransactionContext tx = current.getLastTransaction();
if (tx.isActive()) {
// CREATE A NESTED TX
tx = new TransactionContext(getWrappedDatabaseInstance());
current.pushTransaction(tx);
}
tx.begin(isolationLevel);
return null;
});
}
The key here is DatabaseContext.INSTANCE.getContext(databasePath). This uses databasePath to look up the context. If both database and db (wrapped instance) share the same databasePath, they'll use the same context stack.
But when the nested transaction is created:
tx = new TransactionContext(getWrappedDatabaseInstance());
It passes getWrappedDatabaseInstance() to the TransactionContext constructor. This means the TransactionContext's database field will be the wrapped instance.
So when tx.getPageToModify() is called, it uses the wrapped database's page manager, not the original database's page manager!
Wait, but in standalone mode, getWrappedDatabaseInstance() returns the same instance. So this shouldn't be an issue.
Hmm, but what if in standalone mode, wrappedDatabaseInstance is null or not set correctly?
Let me check how wrappedDatabaseInstance is initialized.
Actually, let me just focus on finding the root cause. The issue is clearly about the sample count being stale. Let me look at the actual write path more carefully.
In TimeSeriesBucket.appendSamples:
for (int i = 0; i < timestamps.length; i++) {
final MutablePage dataPage = getOrCreateActiveDataPage(tx);
final int sampleCountInPage = dataPage.readShort(DATA_SAMPLE_COUNT_OFFSET) & 0xFFFF;
// ...
dataPage.writeShort(DATA_SAMPLE_COUNT_OFFSET, (short) (sampleCountInPage + 1));
}
The problem is that sampleCountInPage is read from dataPage, which was obtained from getOrCreateActiveDataPage(tx). This calls tx.getPageToModify() which loads the page.
The key insight is: when tx.getPageToModify() is called, it checks the transaction's local caches first (modifiedPages, newPages, immutablePages), and only if not found, it delegates to database.getPageManager().getMutablePage().
If the page manager returns a stale page (e.g., from an outdated cache entry), the transaction will read a stale count.
But wait, the page manager should return the latest page from readCache. And readCache should be updated when the previous transaction commits.
Let me look at the commit flow again:
- Nested transaction A.N1 calls
commit()
commit() calls commit2ndPhase()
commit2ndPhase() calls database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush)
updatePages() calls writePages()
writePages() calls putPageInReadCache(new CachedPage(page, false))
- A.N1 is popped
At step 5, the page is put in readCache. But which database.getPageManager() is used? It's the database field of the TransactionContext.
When the nested transaction was created:
tx = new TransactionContext(getWrappedDatabaseInstance());
So tx.database is getWrappedDatabaseInstance().
When tx.getPageToModify() is called:
page = database.getPageManager().getMutablePage(pageId, pageSize, isNew, true);
This uses tx.database.getPageManager(), which is the wrapped database's page manager.
Now, if the wrapped database and the original database have DIFFERENT page managers, they might have different caches!
Let me check if this is the case. In standalone mode, getWrappedDatabaseInstance() returns wrappedDatabaseInstance. If this is this, then the page managers are the same. But if it's something else, they might be different.
Actually, I think I need to check what wrappedDatabaseInstance is in standalone mode. Let me look at how it's initialized.
Looking at LocalDatabase, I see setWrappedDatabaseInstance is called to set it. If it's not set, it might be null or this.
Actually, looking at the getWrappedDatabaseInstance() method:
public DatabaseInternal getWrappedDatabaseInstance() {
return wrappedDatabaseInstance;
}
If wrappedDatabaseInstance is null, this returns null, which would cause an NPE. So it must be set somewhere.
Let me search for where setWrappedDatabaseInstance is called.
Actually, I think the default behavior is that wrappedDatabaseInstance is set to this in standalone mode. Let me verify by looking at the LocalDatabase constructor.
Actually, I realize I should just test my hypothesis. Let me create a test script that reproduces the issue.
Actually wait, let me look at this from a different angle. The issue says:
A following serialized append reads a stale sampleCountInPage — the prior append's count → N+1 increment is not visible
And the collision detector output shows:
DIAG COLLISION slot=1:1:0 pageVer=239 prevThread=74 curThread=88
This means two different threads wrote to the same slot. The page version was 239 for the collision, which means the page has been modified many times.
Now, the key question is: why does thread 88 read a stale count after thread 74's commit?
One possibility: thread 88's transaction loads the page BEFORE thread 74's commit updates the cache. But this can't happen because of the appendLock.
Another possibility: thread 88's transaction loads the page from a DIFFERENT cache that's not updated by thread 74's commit.
Wait! I think I found it. Let me look at the transaction flow again:
-
Thread 74: outer TX T74 starts
-
Thread 74: acquires appendLock
-
Thread 74: db.begin() creates nested TX T74.N1 with db = getWrappedDatabaseInstance()
-
Thread 74: T74.N1 loads page via tx.database.getPageManager().getMutablePage()
-
Thread 74: T74.N1 writes data, increments count
-
Thread 74: T74.N1 commits via db.commit() which uses tx.database.getPageManager().updatePages()
-
Thread 74: releases appendLock
-
Thread 88: outer TX T88 starts
-
Thread 88: acquires appendLock
-
Thread 88: db.begin() creates nested TX T88.N1 with db = getWrappedDatabaseInstance()
-
Thread 88: T88.N1 loads page via tx.database.getPageManager().getMutablePage()
If tx.database in T74.N1 and T88.N1 are the SAME instance, they should share the same page manager and cache. In that case, T88.N1 should see the updated page.
But if tx.database in T74.N1 and T88.N1 are DIFFERENT instances, they might have different page managers and caches. In that case, T88.N1 might not see T74.N1's update.
Now, the question is: is getWrappedDatabaseInstance() the same for all calls? In standalone mode, it should be.
But wait, there's another possibility. The bucket's database field might be different from the wrapped database.
In TimeSeriesBucket.appendSamples:
final TransactionContext tx = database.getTransaction();
Here, database is the bucket's database field. But the transaction was created by:
db.begin(); // where db = database.getWrappedDatabaseInstance()
If the bucket's database field is different from db, then database.getTransaction() might not find the nested transaction!
Wait, but getTransaction() uses the thread-local context:
final DatabaseContext.DatabaseContextTL dbContext = DatabaseContext.INSTANCE.getContext(databasePath);
So it uses databasePath to look up the context, not the database instance. If both databases share the same path, they'll share the same context.
But then, when the nested transaction calls tx.database.getPageManager(), it uses tx.database, which is the wrapped database (from new TransactionContext(getWrappedDatabaseInstance())).
So if the wrapped database and the original database have different page managers, the commit would update the wrapped database's cache, but the next transaction might load from a different cache.
Hmm, but in standalone mode, the wrapped database IS the original database. So they should share the same page manager.
Wait, but the bucket's database field is the original database. When database.getTransaction() is called, it returns the current transaction from the context. This transaction was created with new TransactionContext(getWrappedDatabaseInstance()), so its database field is the wrapped database.
If wrapped == original, then tx.database is the original database, and tx.database.getPageManager() is the original database's page manager. So everything should work.
But what if wrapped != original? Then tx.database is the wrapped database, and tx.database.getPageManager() is the wrapped database's page manager. The bucket's database field is the original database, so database.getTransaction() returns the transaction from the context (which is correct), but the transaction's tx.database is the wrapped database.
In HA mode, the wrapped database might have its own page manager that's separate from the original database's page manager. But in standalone mode, they should be the same.
Hmm, I think I need to actually check what happens in the code. Let me search for where wrappedDatabaseInstance is set.
Actually, let me look at this from yet another angle. The issue says the problem happens in embedded mode. In embedded mode, there's no HA, so getWrappedDatabaseInstance() should return this.
Let me check if that's the case by looking at the LocalDatabase initialization.
OK here's what I think is happening. Let me trace through the code more carefully:
In TimeSeriesShard.appendSamples:
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
}
When db.begin() is called:
LocalDatabase.begin() is called
- It checks if a transaction is already active:
tx = current.getLastTransaction()
- If active, it creates a nested transaction:
tx = new TransactionContext(getWrappedDatabaseInstance())
- The nested transaction is pushed onto the stack
Now, the nested transaction's database field is getWrappedDatabaseInstance().
When mutableBucket.appendSamples(timestamps, columnValues) is called:
TimeSeriesBucket.appendSamples is called
- It gets the transaction:
final TransactionContext tx = database.getTransaction()
database here is the bucket's database field, which was set when the bucket was created
The bucket was created with:
this.mutableBucket = new TimeSeriesBucket(database, shardName, shardPath, columns);
Where database is this.database, the shard's database field. The shard's database field was set in the constructor from the engine's database.
So the bucket's database field is the engine's database, which is the same as the shard's database.
When db.begin() is called, db = database.getWrappedDatabaseInstance(). If wrappedDatabaseInstance == this, then db == database.
So database.getTransaction() should return the nested transaction that was created by db.begin().
And tx.database (the nested transaction's database field) is getWrappedDatabaseInstance(), which is the same as database (if wrapped == this).
So tx.database.getPageManager() should be the same page manager for all transactions.
Hmm, but the issue still happens. So my theory must be wrong.
Let me think about this differently. Maybe the issue is not with different page managers, but with something else.
Actually, wait. Let me re-read the issue description one more time:
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). That outer commit happens outside appendLock.
This says "the durable publish is effectively deferred to the outer transaction commit". This suggests that the nested transaction's changes are NOT immediately persisted. Instead, they're deferred to the outer transaction.
But looking at the code, the nested transaction DOES call db.commit(), which calls updatePages(), which writes to disk. So the changes SHOULD be persisted.
Unless... there's some special handling for nested transactions that defers the commit.
Actually wait, let me re-read the LocalDatabase.commit() method:
@Override
public void commit() {
executeInReadLock(() -> {
checkTransactionIsActive(false);
final DatabaseContext.DatabaseContextTL current =
DatabaseContext.INSTANCE.getContext(LocalDatabase.this.getDatabasePath());
try {
final Binary result = current.getLastTransaction().commit();
if (result != null)
stats.writeTx.incrementAndGet();
else
stats.readTx.incrementAndGet();
} finally {
current.popIfNotLastTransaction();
}
return null;
});
}
It calls current.getLastTransaction().commit(). This commits the top transaction on the stack. For a nested transaction, this would be the nested transaction.
Then current.popIfNotLastTransaction() pops the nested transaction if it's not the last one.
So the nested transaction is committed independently, and then popped.
OK so I'm convinced the nested transaction DOES commit and write to disk. So why is the next transaction reading a stale count?
Let me think about this more carefully. The page manager's readCache is a ConcurrentHashMap. When the nested transaction commits, it puts the updated page in the cache. When the next transaction loads the page, it should get the updated version from the cache.
But wait, what if the page is still in the flush queue? Looking at writePages:
if (asyncFlush) {
for (final MutablePage page : updatedPages)
putPageInReadCache(new CachedPage(page, true));
flushThread.scheduleFlushOfPages(updatedPages);
} else {
// SYNCHRONOUS FLUSH
for (final MutablePage page : updatedPages) {
flushPage(page);
// ADD THE PAGE IN TO READ CACHE. FROM THIS POINT THE PAGE IS NEVER MODIFIED, SO IT CAN BE CACHED
putPageInReadCache(new CachedPage(page, false));
}
}
If asyncFlush is true, the page is put in the cache with copyBuffer=true (deep copy), and then the flush is scheduled asynchronously.
If asyncFlush is false, the page is flushed synchronously, and then put in the cache with copyBuffer=false (shared reference).
In both cases, the page is put in the cache BEFORE returning from commit(). So the next transaction should see the updated page.
But wait, if copyBuffer=false and the MutablePage is modified AFTER being put in the cache, the cache would see the new modifications. But the MutablePage should not be modified after commit, right?
Actually, I think the issue might be related to how the page's version is tracked. Let me look at the version check.
When a transaction commits, it calls updatePageVersion():
public MutablePage updatePageVersion(final MutablePage page, final boolean isNew) throws IOException, InterruptedException {
// ...
page.incrementVersion();
page.updateMetadata();
// ...
}
This increments the page's version. The version is stored in the page's buffer at a specific offset.
When the CachedPage is created:
public CachedPage(final MutablePage page, final boolean copyBuffer) {
// ...
this.version = page.version;
}
It copies the page's version. But wait, page.version is the version BEFORE incrementVersion() is called!
No wait, let me look at the commit flow again:
// commit2ndPhase
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush);
// updatePages
for (final MutablePage p : modifiedPages.values())
pagesToWrite.add(updatePageVersion(p, false));
// updatePageVersion
page.incrementVersion();
page.updateMetadata();
return page;
// writePages
putPageInReadCache(new CachedPage(page, false));
So the page version is incremented BEFORE the CachedPage is created. The CachedPage's version is page.version, which is the incremented version.
So the cache should have the correct version.
OK I'm going in circles. Let me try a different approach. Let me look at what the fix should be and work backwards.
The issue is that concurrent single-row INSERTs can silently lose samples because of a lost update on the sample count slot. The fix should ensure that the sample count read-modify-write is atomic.
One approach is to NOT use nested transactions for appends. Instead, the append should be done directly in the outer transaction. But this might cause other issues (e.g., the outer transaction might have other changes that conflict).
Another approach is to use atomic operations at the page level. For example, use a compare-and-swap (CAS) operation to update the sample count atomically.
Another approach is to serialize the reads as well as the writes. This can be done by extending the appendLock to cover the outer transaction's commit. But this is complex.
Actually, looking at the issue description again:
Any fix needs to make the slot read-modify-write atomic with respect to the actual publish without breaking HA replication — e.g. ensuring the per-shard append publishes/serializes the slot under the lock, or ensuring the concurrent same-page commits raise a conflict so the existing outer-transaction retry path heals them.
So the suggested fix is either:
- Ensure the append publishes the slot under the lock (i.e., commit the page changes within the lock)
- Ensure concurrent same-page commits raise a conflict
For option 1, the issue is that the nested transaction's commit is deferred to the outer transaction (for HA replication). So we can't just commit immediately.
For option 2, we need to ensure that when two transactions try to commit changes to the same page, a conflict is detected.
Looking at the version check in checkPageVersion:
final int mostRecentPageVersion = getMostRecentVersionOfPage(pageId, page.getPhysicalSize());
if (mostRecentPageVersion != page.getVersion()) {
throw new ConcurrentModificationException(...);
}
This checks if the page version on disk matches the page version when it was loaded. If they differ, a conflict is detected.
But the issue says "PageManager.updatePageVersion's version check does not raise a conflict for these commits". This means the version check is not detecting the conflict.
Why? Because the nested transaction commits successfully, incrementing the page version. The next nested transaction loads the page at the new version. So there's no conflict detected.
But the sample count is still stale. How?
OH WAIT. I think I finally see the issue!
The page version is incremented when the page is COMMITTED. But the sample count is read when the page is LOADED.
Here's the sequence:
- Transaction A loads page at version N
- Transaction A reads sampleCount = K
- Transaction A writes data at slot K
- Transaction A writes sampleCount = K+1
- Transaction A commits, page version becomes N+1
- Transaction B loads page at version N+1
- Transaction B reads sampleCount = ?
At step 7, what is the sample count? It should be K+1 (written by transaction A). But the issue says it's still K.
How can this happen? The page was written to disk and put in the cache by transaction A. So transaction B should see the updated count.
Unless... the page is loaded from a different source than the cache.
Wait, let me look at how getCachedPage works:
private CachedPage getCachedPage(final PageId pageId, final int pageSize, final boolean isNew, final boolean createIfNotExists)
throws IOException {
checkForPageDisposal();
CachedPage page = readCache.get(pageId);
if (page == null)
page = loadPage(pageId, pageSize, false, true);
// ...
}
First, it checks the cache. If not found, it loads from disk.
So if transaction A's commit updated the cache, transaction B should get the page from the cache, not from disk.
But what if transaction B's transaction context has the page in its local cache (modifiedPages or newPages)?
Wait, no. Each nested transaction has its own context. So transaction B.N1 should have an empty cache.
Hmm, let me think about this more. The outer transaction might have loaded the page. Let me check:
- Thread 74: outer TX T74 starts
- Thread 74: appends sample via nested TX T74.N1
- Thread 74: T74.N1 commits
- Thread 74: releases appendLock
- Thread 74: outer TX T74 continues (but doesn't load the page)
- Thread 74: outer TX T74 commits
At step 5, does T74 load the page? Looking at the SQL INSERT flow, it goes through SaveElementStep, which doesn't read the time series data. So T74 shouldn't load the page.
But wait, what if T74.N1's changes are merged into T74's dirty set? Let me check if that happens.
Looking at the commit flow, the nested transaction's changes are written to disk via updatePages(). Then the nested transaction is popped. So the changes are NOT merged into the outer transaction.
Hmm, unless there's some special handling. Let me check if there's any code that merges nested transaction changes into the outer transaction.
Looking at TransactionContext.commit2ndPhase():
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush);
This writes the pages to disk. The pages are NOT transferred to the outer transaction.
So each nested transaction's changes are written to disk independently. The outer transaction doesn't know about these changes.
OK so I'm back to the same question: why does the next nested transaction read a stale count?
Let me try yet another approach. Let me look at the getOrCreateActiveDataPage method more carefully:
private MutablePage getOrCreateActiveDataPage(final TransactionContext tx) throws IOException {
final MutablePage headerPage = tx.getPageToModify(new PageId(database, fileId, 0), pageSize, false);
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);
if (dataPageCount > 0) {
// Check if the last logical data page has room
final MutablePage lastPage = tx.getPageToModify(new PageId(database, fileId, dataPageCount), pageSize, false);
final int sampleCount = lastPage.readShort(DATA_SAMPLE_COUNT_OFFSET) & 0xFFFF;
if (sampleCount < getMaxSamplesPerPage())
return lastPage;
}
// ...
}
So it first loads the header page (page 0), reads the data page count, then loads the data page.
The header page is also modified (e.g., to update the total sample count). So multiple transactions might be modifying the same header page.
Wait, but the header page is modified by updateHeaderStats:
private void updateHeaderStats(final TransactionContext tx, final long timestamp) throws IOException {
final MutablePage headerPage = tx.getPageToModify(new PageId(database, fileId, 0), pageSize, false);
final long count = headerPage.readLong(HEADER_SAMPLE_COUNT_OFFSET);
headerPage.writeLong(HEADER_SAMPLE_COUNT_OFFSET, count + 1);
// ...
}
This also has a read-modify-write pattern on the header page. But the issue is about the data page, not the header page.
Hmm, but what if the issue is with the header page? If the header page's data page count is stale, it might affect which data page is used.
No wait, the data page count is usually 1 (there's only one active data page). And the sample count is read from the DATA page, not the header page.
OK let me look at this from a completely different angle. Let me check if there's a race condition in the page loading code.
When getPageToModify is called:
MutablePage page = modifiedPages != null ? modifiedPages.get(pageId) : null;
if (page == null) {
if (newPages != null)
page = newPages.get(pageId);
if (page == null) {
final ImmutablePage loadedPage = immutablePages.remove(pageId);
if (loadedPage == null)
page = database.getPageManager().getMutablePage(pageId, pageSize, isNew, true);
else
page = loadedPage.modify();
if (isNew)
newPages.put(pageId, page);
else
modifiedPages.put(pageId, page);
}
}
return page;
If the page is not in the local caches, it calls database.getPageManager().getMutablePage(). This is the page manager of tx.database.
Now, tx.database is the wrapped database instance. In standalone mode, this should be the same as the original database. But let me double-check.
Actually, I just realized something. The TransactionContext is created with getWrappedDatabaseInstance():
tx = new TransactionContext(getWrappedDatabaseInstance());
So tx.database is getWrappedDatabaseInstance().
But the bucket's database field is the ORIGINAL database (set when the bucket was created).
When appendSamples calls database.getTransaction(), it uses the bucket's database field. But getTransaction() uses the thread-local context, which is shared across all database instances with the same path.
So database.getTransaction() returns the transaction from the context, which was created by db.begin() (where db = getWrappedDatabaseInstance()).
This transaction's tx.database is the wrapped database.
Now, when tx.getPageToModify() is called, it uses tx.database.getPageManager(), which is the wrapped database's page manager.
In standalone mode, if the wrapped database is the same as the original database, this should be fine.
But what if the wrapped database is NOT the same as the original database? Then the wrapped database might have a different page manager with a different cache.
Let me check if this is the case. In standalone mode, wrappedDatabaseInstance should be set to this. Let me search for where this is done.
Actually, I think the key issue might be simpler. Let me look at what happens when the nested transaction commits:
db.commit() is called
LocalDatabase.commit() calls current.getLastTransaction().commit()
TransactionContext.commit() calls commit1stPhase() and commit2ndPhase()
commit2ndPhase() calls database.getPageManager().updatePages()
Wait, which database is used in step 4? It's this.database, the transaction's database field, which is the wrapped database.
So the wrapped database's page manager is used to update the pages. The pages are written to the wrapped database's cache.
Now, when the next transaction loads the page, it calls tx.database.getPageManager().getMutablePage(), where tx.database is also the wrapped database.
So the same page manager is used for both writing and reading. The cache should be updated correctly.
Unless... there's a race condition where the cache is updated AFTER the next transaction reads from it.
But the appendLock should prevent this. The next transaction can't read the page until the previous transaction releases the lock, which happens after the commit.
Hmm, unless the commit is asynchronous. Let me check.
Looking at writePages:
if (asyncFlush) {
for (final MutablePage page : updatedPages)
putPageInReadCache(new CachedPage(page, true));
flushThread.scheduleFlushOfPages(updatedPages);
}
If asyncFlush is true, the page is put in the cache FIRST, and then the flush is scheduled asynchronously. So the cache should be updated before the commit returns.
But wait, the cache is updated with a DEEP COPY of the buffer (copyBuffer=true). So even if the original buffer is modified later, the cached copy is not affected.
So this should be safe.
OK I'm really confused now. Let me try to create a minimal reproduction of the issue to understand what's happening.
Actually, let me just focus on the fix. The issue is that concurrent nested transactions can read a stale sample count. The fix should ensure that the sample count is always the latest committed value.
One way to fix this is to NOT use nested transactions for appends. Instead, the append should be done in the same transaction as the outer SQL INSERT. But wait, the current code creates a nested transaction explicitly. Why?
Looking at the comment in TimeSeriesShard.appendSamples:
// This method always manages its own transaction. If the caller already has an active
// transaction, ArcadeDB creates a nested transaction (a new {@code TransactionContext} pushed
// onto the per-thread stack). The nested transaction commits independently; the caller's outer
// transaction remains unaffected because it holds none of the modified pages in its dirty set.
So the nested transaction is used to isolate the time series append from the outer transaction. The outer transaction's dirty set doesn't include the time series pages.
But this is exactly the problem! The nested transaction commits independently, but its changes might not be visible to subsequent nested transactions.
Actually, wait. The comment says "The nested transaction commits independently". So the nested transaction's changes ARE committed and written to disk. The next nested transaction should see these changes.
Unless there's a bug in the commit or caching logic.
OK let me just look at the fix options:
Option 1: Don't use nested transactions.
Instead of creating a nested transaction, use the outer transaction directly. But this might cause issues with the outer transaction's dirty set.
Option 2: Use atomic CAS for the sample count.
Read the sample count, write the data, then use CAS to update the count. If CAS fails, retry.
Option 3: Force a page reload after acquiring the lock.
After acquiring the appendLock, clear the transaction's cache and reload the page from the page manager.
Option 4: Synchronize on the page manager's cache.
Ensure that the cache is updated atomically with respect to the read.
I think Option 2 is the most robust fix. It uses atomic operations at the page level to ensure the sample count is updated correctly.
But wait, looking at the code, the sample count update is:
dataPage.writeShort(DATA_SAMPLE_COUNT_OFFSET, (short) (sampleCountInPage + 1));
This is just a regular write, not a CAS. There's no atomicity guarantee.
To use CAS, we'd need to add a CAS operation that reads the current count, checks if it matches the expected count, and updates it atomically.
But the page doesn't support CAS operations. It's just a byte buffer.
Hmm, what if we add a CAS-like mechanism at the TimeSeriesBucket level? For example, we could track the expected count and retry if the actual count doesn't match.
But this would require reloading the page after each write, which might be expensive.
Actually, looking at the issue description again:
Any fix needs to make the slot read-modify-write atomic with respect to the actual publish without breaking HA replication
The key insight is that the "actual publish" is the nested transaction's commit. So we need to make the read-modify-write atomic with respect to the commit.
One way to do this is to read the sample count from the page manager's cache, not from the transaction's cache. This ensures we always see the latest committed value.
But how do we do this? The transaction's getPageToModify loads the page from the transaction's cache or the page manager. We can't bypass the transaction's cache.
Wait, but we can reload the page from the page manager after acquiring the lock. Here's the idea:
- Acquire
appendLock
- Begin nested transaction
- Force reload the page from the page manager (bypass the transaction's cache)
- Read sample count, write data, update count
- Commit nested transaction
- Release
appendLock
Step 3 is the key. By forcing a reload from the page manager, we ensure we see the latest committed value.
But how do we force a reload? We can't easily bypass the transaction's cache.
Actually, wait. The transaction's cache (modifiedPages, newPages, immutablePages) is initially empty for a new nested transaction. So when getPageToModify is called, it should load from the page manager.
Unless the transaction's cache is somehow pre-populated. Let me check.
Looking at TransactionContext constructor:
public TransactionContext(final DatabaseInternal database) {
this(database, false);
}
public TransactionContext(final DatabaseInternal database, final boolean asyncFlush) {
this.database = database;
this.isolationLevel = Database.getDefaultTransactionIsolationLevel();
this.asyncFlush = asyncFlush;
}
The caches are not initialized in the constructor. They're initialized lazily when pages are loaded.
So a new nested transaction should have empty caches. When getPageToModify is called, it should load from the page manager.
But wait, let me look at getPageToModify again:
MutablePage page = modifiedPages != null ? modifiedPages.get(pageId) : null;
If modifiedPages is null, this returns null. So it would load from the page manager.
So the page should be loaded from the page manager, which should have the latest cached version.
Unless the page manager's cache is stale. But the previous nested transaction's commit should have updated the cache.
Hmm, I'm really stuck. Let me try a different approach. Let me look at what happens in the HA wrapper.
Actually, the issue says it happens in embedded mode, which is standalone. So the HA wrapper is not involved.
OK let me just look at the code and see if I can find the bug.
Actually, I just realized something. Let me look at the TimeSeriesBucket.appendSamples method again:
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);
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);
if (dataPageCount > 0) {
final MutablePage lastPage = tx.getPageToModify(new PageId(database, fileId, dataPageCount), pageSize, false);
// ...
}
}
So getOrCreateActiveDataPage loads both the header page (page 0) and the data page. Both are loaded from the transaction.
Now, the transaction is the nested transaction. When the nested transaction commits, both pages are written to disk.
But wait, the nested transaction's database field is the wrapped database. And the bucket's database field is the original database.
When tx.getPageToModify is called, it uses tx.database.getPageManager(). If tx.database (wrapped) is different from the bucket's database (original), they might have different page managers.
Hmm, but in standalone mode, they should be the same.
Actually, let me check if getWrappedDatabaseInstance() is set correctly in standalone mode.
Looking at LocalDatabase, I don't see where wrappedDatabaseInstance is set by default. It might be null initially.
If wrappedDatabaseInstance is null, then getWrappedDatabaseInstance() returns null, which would cause an NPE when db.begin() is called.
But the test runs without NPE, so wrappedDatabaseInstance must be set.
Let me search for where setWrappedDatabaseInstance is called.
Actually, I think in standalone mode, wrappedDatabaseInstance is set to this in the LocalDatabase constructor. Let me check.
Hmm, I can't find the constructor. Let me search for it.
OK I think the issue might be that the transaction's database field is different from the bucket's database field, and they have different page managers.
Let me look at how the bucket is created:
this.mutableBucket = new TimeSeriesBucket(database, shardName, shardPath, columns);
Where database is the shard's database. The shard's database is set in the constructor:
public TimeSeriesShard(final DatabaseInternal database, ...) {
this.database = database;
// ...
this.mutableBucket = new TimeSeriesBucket(database, shardName, shardPath, columns);
}
So the bucket's database is the shard's database.
Now, in TimeSeriesShard.appendSamples:
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
mutableBucket.appendSamples(timestamps, columnValues);
db is database.getWrappedDatabaseInstance(). If this is different from database, then:
db.begin() creates a nested transaction on db
mutableBucket.appendSamples() uses mutableBucket.database.getTransaction(), which is database.getTransaction()
But database.getTransaction() uses the thread-local context, which is shared across all database instances with the same path. So it should return the nested transaction that was created by db.begin().
And this nested transaction's tx.database is db (the wrapped database).
When tx.getPageToModify() is called, it uses tx.database.getPageManager(), which is db.getPageManager().
So the page is loaded from the wrapped database's page manager.
If db and database are different instances, they might have different page managers with different caches.
But in standalone mode, getWrappedDatabaseInstance() should return the same instance. So this shouldn't be an issue.
Hmm, but what if getWrappedDatabaseInstance() returns a different instance in some cases?
Let me look at how wrappedDatabaseInstance is set. Actually, let me search for setWrappedDatabaseInstance:
Actually, I wonder if the issue is related to how the LocalDatabase is wrapped by a HaDatabase. Let me search for HaDatabase.
Actually, I think I need to just accept that I don't fully understand the root cause and focus on implementing a fix.
The core issue is: concurrent nested transactions can read a stale sample count, leading to lost updates.
The fix should ensure that the sample count is always read from the latest committed state.
One simple fix is to NOT use a nested transaction for the append. Instead, we can:
- Acquire the
appendLock
- Check if there's an active transaction
- If there's an active transaction, don't create a nested one - use the outer transaction directly
- If there's no active transaction, begin a new transaction
But wait, the issue is that the current code ALWAYS creates a nested transaction when there's an outer transaction active. And this nested transaction's commit is deferred (for HA replication).
So the fix could be to NOT create a nested transaction. Instead, do the append directly in the outer transaction. But then the outer transaction's dirty set would include the time series pages, which might cause issues with HA replication.
Actually, looking at the comment:
// Route the append transaction through the HA wrapper so the mutable-bucket page writes are
// shipped to followers via the Raft WAL (TX_ENTRY). Committing on the inner LocalDatabase here
// would persist the pages locally only, leaving followers with an empty bucket (issue #4382).
The reason for using a nested transaction on the wrapped database is to ensure HA replication. If we use the outer transaction directly, the HA replication might not work correctly.
But wait, the issue is that the nested transaction's commit is DEFERRED to the outer transaction. This is why the next nested transaction can read a stale value.
Hmm, but looking at the code, the nested transaction DOES commit immediately. It's not deferred. The db.commit() call writes to disk.
Unless there's something in the HA wrapper that defers the commit.
Actually, let me re-read the issue description more carefully:
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
This says "the durable publish is effectively deferred to the outer transaction commit". But looking at the code, the nested transaction's commit() calls updatePages() which writes to disk.
So the publish is NOT deferred. The nested transaction commits and writes to disk.
Unless... there's some WAL or caching mechanism that defers the actual disk write.
Wait, the issue mentions useWAL:
if (useWAL) {
txId = database.getTransactionManager().getNextTransactionId();
result = database.getTransactionManager().createTransactionBuffer(txId, pages);
}
If WAL is enabled, the transaction buffer is created but not necessarily flushed to disk. The actual flush might happen later.
But even with WAL, the page should be written to the cache, so subsequent reads should see the updated value.
Hmm, unless the issue is that the page is written to the WAL but the cache is not updated until the WAL is flushed.
Let me check the WAL flow. Looking at commit2ndPhase:
if (changes.result != null)
// WRITE TO THE WAL FIRST
database.getTransactionManager().writeTransactionToWAL(changes.modifiedPages, walFlush, txId, changes.result);
// ...
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush);
So the WAL is written first, then the pages are updated. The updatePages call writes to the cache and disk.
So the cache should be updated after the commit returns.
OK I think the issue might be related to how the outer transaction interacts with the nested transaction's changes.
Wait, I just realized something. Let me look at the test again:
database.transaction(() ->
database.command("sql", "INSERT INTO Reading SET ts = ?, sid = ?, v = ?", ts, "s" + threadIndex, v));
This creates a transaction, executes the command, and commits the transaction. But the command calls shard.appendSamples(), which creates a nested transaction, commits it, and releases the lock.
After the nested transaction commits, the outer transaction's code continues. The outer transaction then commits at the end of the lambda.
But the outer transaction might have other changes (e.g., schema changes) that conflict with the nested transaction's changes.
Actually wait, the outer transaction doesn't make any changes. The INSERT command goes through SaveElementStep, which creates a document and calls saveToTimeSeries. The document is created in memory, not persisted. So the outer transaction doesn't have any changes.
Hmm, but the outer transaction might have loaded some pages (e.g., for schema access). These pages would be in the outer transaction's cache.
Wait, but the nested transaction is separate from the outer transaction. The nested transaction has its own cache.
So when the nested transaction loads a page, it loads from the page manager's cache, not from the outer transaction's cache.
And when the nested transaction commits, it updates the page manager's cache.
So the next nested transaction should see the updated page.
UNLESS... the page manager's cache is not thread-safe. But it's a ConcurrentHashMap, so it should be thread-safe.
OK I'm going to take a step back and think about this differently.
The issue is that two concurrent transactions read the same stale sample count, even though they're serialized by the lock.
This can only happen if:
- The first transaction's write to the sample count is not visible to the second transaction.
- OR the second transaction reads from a different page/buffer than the first transaction wrote to.
For (1), the write should be visible because:
- The nested transaction commits and writes to disk
- The cache is updated with the new value
- The lock ensures the second transaction waits
For (2), the read and write should be on the same page because:
- Both transactions use the same shard, bucket, and page number
- The page manager returns the same cached page
So neither (1) nor (2) should happen. But the issue says it does happen.
Let me look at the issue from yet another angle. Maybe the problem is not with the data page, but with the HEADER page.
Looking at getOrCreateActiveDataPage:
final MutablePage headerPage = tx.getPageToModify(new PageId(database, fileId, 0), pageSize, false);
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);
The header page is loaded first. If the header page has a stale dataPageCount, it might cause the transaction to load a different data page.
But wait, dataPageCount is the number of data pages, not the sample count. For a bucket with only one data page, dataPageCount should be 1.
And the sample count is read from the DATA page, not the header page:
final MutablePage lastPage = tx.getPageToModify(new PageId(database, fileId, dataPageCount), pageSize, false);
final int sampleCount = lastPage.readShort(DATA_SAMPLE_COUNT_OFFSET) & 0xFFFF;
So the sample count is read from the data page, which is loaded separately.
Hmm, but what if dataPageCount is stale? If the first transaction increments dataPageCount (e.g., allocates a new data page), and the second transaction reads a stale dataPageCount, it might load the wrong data page.
But wait, the issue says the collisions are on the same page (page 1). So dataPageCount is probably not the issue.
Let me look at the issue from a different perspective. Let me think about what happens when two transactions write to the same page concurrently.
In the current code:
- Transaction A acquires lock, loads page, reads count=0, writes at slot 0, writes count=1, commits, releases lock.
- Transaction B acquires lock, loads page, reads count=?, writes at slot ?, writes count=?+1, commits, releases lock.
If B reads count=0 (stale), it writes at slot 0 (collision with A), and writes count=1 (overwriting A's count).
But B should read count=1 (the value written by A). Why doesn't it?
The only way B can read count=0 is if B loads a different page/buffer than A wrote to.
But A and B use the same page ID (file 1, page 1). And the page manager should return the same cached page.
UNLESS the page manager's cache is updated with A's changes, but B loads the page BEFORE the cache is updated.
But the lock should prevent this. A commits and releases the lock before B acquires the lock and loads the page.
Wait, let me look at the lock scope more carefully:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
final DatabaseInternal db = database.getWrappedDatabaseInstance();
db.begin();
try {
mutableBucket.appendSamples(timestamps, columnValues);
db.commit();
} catch (final Exception e) {
// ...
}
} finally {
appendLock.unlock();
}
} finally {
compactionLock.readLock().unlock();
}
}
So the lock is held during:
db.begin()
mutableBucket.appendSamples() (loads page, writes data, updates count)
db.commit() (writes page to disk, updates cache)
Then the lock is released.
So when B acquires the lock, A has already committed and the cache is updated. B should see the updated page.
Unless... the cache is not updated before the lock is released.
Let me look at db.commit():
@Override
public void commit() {
executeInReadLock(() -> {
// ...
final Binary result = current.getLastTransaction().commit();
// ...
current.popIfNotLastTransaction();
return null;
});
}
And TransactionContext.commit():
public Binary commit() {
// ...
final TransactionPhase1 phase1 = commit1stPhase(true);
if (phase1 != null) {
commit2ndPhase(phase1);
} else
resetAndFireCallbacks();
// ...
return phase1 != null ? phase1.result : null;
}
And commit2ndPhase():
public void commit2ndPhase(final TransactionPhase1 changes) {
// ...
database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush);
// ...
}
So commit() calls updatePages(), which updates the cache and writes to disk. This is done BEFORE commit() returns.
So when db.commit() returns, the cache is updated. And the lock is released after db.commit() returns.
So B should see the updated cache.
UNLESS... there's a race condition in the cache update.
Let me look at updatePages:
public void updatePages(final Map<PageId, MutablePage> newPages, final Map<PageId, MutablePage> modifiedPages,
final boolean asyncFlush) throws IOException, InterruptedException {
lock();
try {
// ...
for (final MutablePage p : modifiedPages.values())
pagesToWrite.add(updatePageVersion(p, false));
// ...
writePages(pagesToWrite, asyncFlush);
// ...
} finally {
unlock();
}
}
So updatePages acquires a lock on the page manager, updates the pages, and releases the lock.
And writePages:
public void writePages(final List<MutablePage> updatedPages, final boolean asyncFlush) throws IOException, InterruptedException {
if (asyncFlush) {
for (final MutablePage page : updatedPages)
putPageInReadCache(new CachedPage(page, true));
flushThread.scheduleFlushOfPages(updatedPages);
} else {
for (final MutablePage page : updatedPages) {
flushPage(page);
putPageInReadCache(new CachedPage(page, false));
}
}
}
So putPageInReadCache is called within updatePages, which is called within commit(), which is called within the lock.
So the cache is updated before the lock is released.
Hmm, I really can't find the bug. Let me try a different approach. Let me look at what getMutablePage does when the page is in the cache:
public MutablePage getMutablePage(final PageId pageId, final int pageSize, final boolean isNew, final boolean createIfNotExists)
throws IOException {
final CachedPage page = getCachedPage(pageId, pageSize, isNew, createIfNotExists);
if (page != null)
return page.useAsMutable();
return null;
}
And getCachedPage:
private CachedPage getCachedPage(final PageId pageId, final int pageSize, final boolean isNew, final boolean createIfNotExists)
throws IOException {
checkForPageDisposal();
CachedPage page = readCache.get(pageId);
if (page == null)
page = loadPage(pageId, pageSize, false, true);
// ...
}
So if the page is in the cache, it returns the cached page. Then useAsMutable is called:
public MutablePage useAsMutable() {
final byte[] array = this.content.getByteBuffer().array();
return new MutablePage(pageId, size, Arrays.copyOf(array, array.length), version, content.size());
}
This creates a NEW MutablePage with a COPY of the cached content.
So each transaction gets its own copy of the page content. Changes made by one transaction don't affect the other transaction's copy.
This is correct behavior. The issue is that the second transaction's copy is made from the OLD cached content, not the NEW cached content.
But the cached content should be updated by the first transaction's commit. So the second transaction's copy should have the new content.
Unless the cached content is not updated correctly.
Wait, let me look at putPageInReadCache:
private void putPageInReadCache(final CachedPage page) {
final CachedPage prev = readCache.put(page.getPageId(), page);
// ...
}
This uses readCache.put(), which is a ConcurrentHashMap operation. This should atomically replace the old entry with the new entry.
So after the first transaction's commit, the cache should have the new CachedPage. And the second transaction should get the new CachedPage from the cache.
Unless there's a memory visibility issue. The ConcurrentHashMap.put() should have happens-before semantics, so the second thread should see the updated entry.
OK I really can't find the bug by analyzing the code. Let me just look at the test and see if I can understand the issue better.
Actually, let me just implement a fix. The fix should ensure that the sample count is read from the latest committed state.
One simple fix is to reload the page from the page manager after acquiring the lock. This bypasses any stale cache in the transaction.
But how do we bypass the transaction's cache? We can't easily do that.
Another fix is to make the sample count update atomic. We can use a compare-and-swap (CAS) operation at the bucket level.
Here's the idea:
- Load the page and read the sample count
- Write the data at the calculated slot
- Use CAS to update the sample count: if the current count matches the expected count, update it; otherwise, retry from step 1
The CAS operation can be implemented by:
- Read the current count from the page
- Compare it with the expected count
- If they match, write the new count
- If they don't match, reload the page and retry
But this retry loop might be expensive.
Actually, I think a simpler fix is to just NOT use nested transactions for the append. Instead, we can do the append in the same transaction as the outer SQL INSERT.
But the issue says this might break HA replication. Let me think about why.
Looking at the comment:
// Route the append transaction through the HA wrapper so the mutable-bucket page writes are
// shipped to followers via the Raft WAL (TX_ENTRY). Committing on the inner LocalDatabase here
// would persist the pages locally only, leaving followers with an empty bucket (issue #4382).
The reason for using the wrapped database is to ensure HA replication. If we use the inner database directly, the changes won't be replicated.
But if we use the outer transaction directly (without creating a nested transaction), the changes would be part of the outer transaction. And the outer transaction would be replicated via HA.
Wait, but the outer transaction is on the original database, not the wrapped database. So the replication might not work correctly.
Hmm, this is getting complicated. Let me think about this more.
Actually, I think the issue might be simpler. The comment says:
// Committing on the inner LocalDatabase here would persist the pages locally only, leaving followers with an empty bucket
So if we commit on the inner database, the changes are not replicated. This is why we use the wrapped database.
But the wrapped database IS the inner database in standalone mode. So this shouldn't be an issue.
Wait, actually I think the comment is saying that if we DON'T use the wrapped database, the changes won't be replicated. But we ARE using the wrapped database.
So the issue is not with using the wrapped database. The issue is with the nested transaction.
Hmm, let me re-read the issue description:
The nested transaction's commit is 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).
Wait, this says the nested transaction's commit is DEFERRED. But looking at the code, the nested transaction DOES commit immediately.
Unless there's special handling in the HA wrapper that defers the commit.
Let me search for the HA wrapper and see how it handles commits.
Actually, I think the key insight is that the nested transaction's commit is deferred in HA mode. But in standalone mode, it commits immediately.
And the issue happens in standalone mode. So the deferred commit is not the issue.
OK let me just try to implement a fix based on my understanding.
The issue is that concurrent nested transactions can read a stale sample count. The fix should ensure that the sample count is always read from the latest committed state.
One way to fix this is to ensure that the page is reloaded from the page manager after acquiring the lock. This way, the transaction always reads the latest cached page.
But the transaction's getPageToModify doesn't have a way to force a reload. It always checks the transaction's local cache first.
So we need to either:
- Clear the transaction's local cache before loading the page
- Bypass the transaction's local cache and load directly from the page manager
Option 1 might be dangerous because it could invalidate other pages that the transaction has loaded.
Option 2 might be complex to implement.
Another approach is to make the sample count update atomic. We can use a CAS-like operation at the bucket level.
Actually, I think the simplest fix is to change the logic in TimeSeriesBucket.appendSamples to re-read the sample count after acquiring the page. Instead of:
final MutablePage dataPage = getOrCreateActiveDataPage(tx);
final int sampleCountInPage = dataPage.readShort(DATA_SAMPLE_COUNT_OFFSET) & 0xFFFF;
We can do:
final MutablePage dataPage = getOrCreateActiveDataPage(tx);
// Force reload to get the latest sample count
final int sampleCountInPage = readSampleCountFromDisk(dataPage);
But how do we read from disk? We'd need to bypass the transaction's cache.
Actually, I think the real fix is to NOT use nested transactions for the append. Instead, we should do the append in a way that doesn't require a nested transaction.
Let me think about this. The reason for using a nested transaction is to:
- Isolate the append from the outer transaction (so the outer transaction's commit doesn't affect the append)
- Ensure HA replication (by using the wrapped database)
But these requirements might not be necessary. Let me look at why they're needed.
For (1), the comment says:
// The nested transaction commits independently; the caller's outer transaction remains unaffected because it holds none of the modified pages in its dirty set.
So the nested transaction is used to keep the outer transaction's dirty set clean. This prevents the outer transaction from having to commit the time series pages.
But this isolation is causing the issue! The nested transaction commits independently, but its changes might not be visible to subsequent nested transactions.
For (2), the comment says:
// Route the append transaction through the HA wrapper so the mutable-bucket page writes are shipped to followers via the Raft WAL (TX_ENTRY).
So the nested transaction on the wrapped database is used to ensure HA replication.
But in standalone mode, the wrapped database is the same as the original database. So this shouldn't be an issue.
OK here's my proposed fix:
Instead of using a nested transaction for the append, we can:
- Acquire the
appendLock
- Use the current transaction (if any) for the append
- If there's no current transaction, begin a new one
- After the append, if we began a new transaction, commit it
- Release the
appendLock
But wait, the issue is that the outer transaction is created by the caller (database.transaction(...)). We can't control the outer transaction from within appendSamples.
Hmm, actually, let me look at the problem from a different angle.
The issue is that the nested transaction's changes are not visible to subsequent nested transactions. This can happen if:
- The nested transaction's commit doesn't update the page manager's cache correctly
- The subsequent nested transaction loads the page from a stale source
For (1), the commit should update the cache correctly. I've verified this by looking at the code.
For (2), the subsequent nested transaction should load from the page manager's cache, which should have the latest data.
But there might be a subtle issue with how the page manager's cache is updated.
Actually, wait. Let me look at the CachedPage constructor again:
public CachedPage(final MutablePage page, final boolean copyBuffer) {
this.pageId = page.pageId;
if (copyBuffer) {
final byte[] srcArray = page.content.getContent();
final byte[] copied = Arrays.copyOf(srcArray, srcArray.length);
this.content = new Binary(copied, page.content.size());
} else {
this.content = page.content; // SHARED reference!
}
// ...
}
When copyBuffer=false, the CachedPage shares the SAME content reference as the MutablePage. This means if the MutablePage is modified AFTER being put in the cache, the cache would see the changes.
But wait, the MutablePage should not be modified after being put in the cache. It's been committed and should be immutable.
Unless there's a bug where the MutablePage is modified after being put in the cache.
Hmm, but this doesn't explain why the NEXT transaction reads a stale count. If the cache has the updated content, the next transaction should see it.
OK I think I need to just implement a fix and test it. Let me think about the best approach.
Actually, I just realized something. The issue might be related to how the transaction's getPageToModify works.
When getPageToModify is called:
- Check
modifiedPages - if found, return it
- Check
newPages - if found, return it
- Check
immutablePages - if found, remove it, call modify(), return the mutable page
- Otherwise, call
pageManager.getMutablePage()
Now, in step 3, immutablePages might have a stale page. If the page was loaded as immutable earlier (e.g., by a read operation), it would be in immutablePages. And when getPageToModify is called, it would return the mutable version of this stale page.
But wait, the nested transaction is a new transaction. Its immutablePages should be empty.
Unless... the nested transaction inherits the parent transaction's immutablePages.
Let me check if this happens.
Looking at the TransactionContext constructor:
public TransactionContext(final DatabaseInternal database, final boolean asyncFlush) {
this.database = database;
this.isolationLevel = Database.getDefaultTransactionIsolationLevel();
this.asyncFlush = asyncFlush;
}
The constructor doesn't inherit anything from the parent transaction. So the nested transaction's immutablePages should be empty.
OK so the nested transaction should load the page from the page manager, which should have the latest cached version.
I'm really stuck. Let me just implement a fix based on the simplest possible approach.
My proposed fix:
In TimeSeriesBucket.appendSamples, instead of using the transaction's page cache, we'll read the sample count directly from the page manager. This ensures we always see the latest committed value.
But how do we do this without bypassing the transaction?
Actually, I think the fix is simpler. Instead of having the append create its own nested transaction, we can do the append in the CURRENT transaction (the outer transaction). This way, there's no nesting, and the changes are visible to the current transaction.
But the issue is that the current transaction might be the caller's transaction, and we can't control it.
Actually, wait. The append is called from SaveElementStep.saveToTimeSeries:
private void saveToTimeSeries(final LocalTimeSeriesType tsType, final Document doc, final CommandContext context) {
// ...
try {
engine.appendSamples(timestamps, columnValues);
} catch (final IOException e) {
throw new CommandExecutionException("Error appending to TimeSeries engine", e);
}
}
This is called from within a transaction (created by database.transaction(...)). So there's already an active transaction.
And engine.appendSamples calls shard.appendSamples, which creates a nested transaction.
The issue is that the nested transaction's changes are not visible to subsequent nested transactions.
Here's my proposed fix:
In TimeSeriesShard.appendSamples, don't create a nested transaction. Instead, use the current transaction.
But wait, the code explicitly creates a nested transaction for HA replication reasons. If we don't create a nested transaction, the HA replication might not work correctly.
Hmm, but if we use the current transaction, the changes will be part of the current transaction. And the current transaction will be replicated via HA.
Actually, I think this might work. Let me think about this more.
If the current transaction is on the wrapped database, then the changes will be replicated. But the current transaction is on the original database (created by database.transaction(...)).
So if we use the current transaction directly, the changes might not be replicated correctly.
Wait, but the current transaction's database is the original database. When we commit the current transaction, it will commit on the original database. If the original database is not the wrapped database, the changes won't be replicated.
Hmm, this is getting confusing.
Let me re-read the code in TimeSeriesShard.appendSamples:
public void appendSamples(final long[] timestamps, final Object[]... columnValues) throws IOException {
compactionLock.readLock().lock();
try {
appendLock.lock();
try {
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 db = database.getWrappedDatabaseInstance(). Then db.begin() is called.
In standalone mode, db is the same as database. So db.begin() is called on the same database instance.
If there's already an active transaction on this database, a nested transaction is created.
But the nested transaction is on db, which is the same as database. So the nested transaction is on the same database instance as the outer transaction.
When the nested transaction commits, it writes to the page manager of db, which is the same as database's page manager.
So the cache should be updated correctly.
I'm really confused now. Let me just implement a fix based on the most likely cause.
The most likely cause is that the nested transaction's page is not reloaded from the cache. This can happen if the transaction's local cache is used instead of the page manager's cache.
But the nested transaction's local cache should be empty. So it should load from the page manager.
Unless... there's a bug in the page manager's cache that causes it to return a stale page.
Let me look at the cache update code more carefully.
When the nested transaction commits:
putPageInReadCache(new CachedPage(page, false));
This creates a new CachedPage with copyBuffer=false, meaning it shares the MutablePage's content.
And page is the MutablePage from the transaction's modifiedPages map. This MutablePage has the updated content.
So the CachedPage should have the updated content.
Then, when the next transaction loads the page:
CachedPage page = readCache.get(pageId);
return page.useAsMutable();
And useAsMutable():
public MutablePage useAsMutable() {
final byte[] array = this.content.getByteBuffer().array();
return new MutablePage(pageId, size, Arrays.copyOf(array, array.length), version, content.size());
}
This copies the content into a new byte array. So the new MutablePage has a copy of the CachedPage's content.
And the CachedPage's content is shared with the previous MutablePage, which has the updated content.
So the new MutablePage should have the updated content.
UNLESS the CachedPage's content is different from what was committed.
Wait, when copyBuffer=false:
this.content = page.content;
The CachedPage's content is the same object as the MutablePage's content. So if the MutablePage's content is updated, the CachedPage's content is also updated.
But the MutablePage is not updated after the commit. So the CachedPage should have the correct content.
Hmm, I really can't find the bug.
Let me just implement a fix. I'll add a mechanism to force a page reload after acquiring the lock.
Actually, I think the simplest fix is to change the logic so that the sample count is read from a global atomic counter, not from the page. This way, the sample count is always consistent across transactions.
But this would require adding an atomic counter to the TimeSeriesBucket.
Actually, that's a good idea. Let me implement this.
Here's the plan:
- Add an atomic counter to TimeSeriesBucket to track the current sample count per page
- When appending, use the atomic counter to get the next slot, not the page's sample count
- Update the page's sample count after writing
But wait, the page's sample count is the authoritative source. If we use a separate counter, it might get out of sync.
Hmm, a better approach is to use the lock to protect the entire read-modify-write cycle.
But the lock is already held during the read-modify-write cycle. So this should be fine.
Actually, I think I finally understand the issue!
The problem is NOT with the data page. The problem is with how the data page is LOADED.
Let me trace through the flow more carefully:
-
Thread A: outer TX starts (TX A)
-
Thread A: acquires appendLock
-
Thread A: db.begin() creates nested TX A.N1
-
Thread A: A.N1 loads data page from page manager (let's call it page P)
-
Thread A: A.N1 reads sample count from P, writes data, increments count
-
Thread A: A.N1 commits, writes P to disk, updates page manager's cache
-
Thread A: releases appendLock
-
Thread A: commits outer TX A (TX A has no changes, so no-op)
-
Thread B: outer TX starts (TX B)
-
Thread B: acquires appendLock
-
Thread B: db.begin() creates nested TX B.N1
-
Thread B: B.N1 loads data page from page manager
At step 12, B.N1 should load the updated page from the cache. But what if B.N1 loads from TX B's cache instead?
Wait, B.N1 is a nested transaction within TX B. But B.N1 has its own local cache, separate from TX B's cache.
So B.N1 should load from the page manager, not from TX B's cache.
Unless... TX B has already loaded the data page in a previous operation. And when B.N1 calls getPageToModify, it somehow gets TX B's cached page.
But B.N1's getPageToModify checks B.N1's local cache, not TX B's local cache. So it should load from the page manager.
Hmm, but what if TX B and B.N1 share the same local cache?
Looking at the TransactionContext class, each instance has its own modifiedPages, newPages, and immutablePages maps. So TX B and B.N1 have separate caches.
OK so the caches are separate. B.N1 should load from the page manager.
Let me look at the page manager's getMutablePage again:
public MutablePage getMutablePage(final PageId pageId, final int pageSize, final boolean isNew, final boolean createIfNotExists)
throws IOException {
final CachedPage page = getCachedPage(pageId, pageSize, isNew, createIfNotExists);
if (page != null)
return page.useAsMutable();
return null;
}
And getCachedPage:
private CachedPage getCachedPage(final PageId pageId, final int pageSize, final boolean isNew, final boolean createIfNotExists)
throws IOException {
checkForPageDisposal();
CachedPage page = readCache.get(pageId);
if (page == null)
page = loadPage(pageId, pageSize, false, true);
// ...
}
So it checks the readCache first. If the page is in the cache, it returns the cached page.
The readCache is a ConcurrentHashMap. So concurrent updates should be visible.
But wait, what if readCache.get(pageId) returns the OLD cached page because the update hasn't propagated yet?
No, ConcurrentHashMap guarantees that updates are immediately visible to all threads.
So B.N1 should get the updated cached page.
OK I really can't find the bug by code analysis. Let me just implement a fix based on the symptoms.
The symptoms are:
- Two concurrent appends read the same sample count
- They write to the same slot
- One sample is lost
The fix should ensure that the second append reads the updated sample count.
One way to do this is to use an atomic operation for the sample count update. But the page doesn't support atomic operations.
Another way is to re-read the sample count after writing the data. But this doesn't help because the issue is with the initial read.
Actually, wait. I think I see the issue now!
The problem is that getOrCreateActiveDataPage is called FIRST, and it loads the data page. Then appendSamples reads the sample count from the loaded page.
But what if getOrCreateActiveDataPage loads a STALE page because the page manager's cache is stale?
And the page manager's cache is stale because the previous nested transaction's commit hasn't propagated yet?
But the commit should propagate before the lock is released. So the cache should be updated.
Unless there's a memory visibility issue. The commit updates the cache, but the update is not visible to the next thread immediately.
But ConcurrentHashMap has happens-before semantics. So the update should be visible.
OK wait, I just realized something. Let me look at the page manager's getMostRecentVersionOfPage:
public int getMostRecentVersionOfPage(final PageId pageId, final int physicalPageSize) throws IOException {
CachedPage page = readCache.get(pageId);
if (page == null)
page = loadPage(pageId, physicalPageSize, false, true);
if (page != null)
return page.getVersion();
return 0;
}
This also checks the cache first. If the cache has a stale version, it would return the stale version.
But the cache should be updated by the commit. So the version should be correct.
Hmm, I think the issue might be that the cache is updated, but the CACHE ENTRY is the same object. So when useAsMutable is called, it returns a view of the same buffer.
Wait, let me look at putPageInReadCache again:
private void putPageInReadCache(final CachedPage page) {
final CachedPage prev = readCache.put(page.getPageId(), page);
if (prev == null)
totalReadCacheRAM.addAndGet(page.getPhysicalSize());
else {
final long delta = page.getPhysicalSize() - prev.getPhysicalSize();
if (delta != 0)
totalReadCacheRAM.addAndGet(delta);
}
checkForPageDisposal();
}
This replaces the old cache entry with a new one. So the cache should have the new CachedPage.
And the new CachedPage has the updated content (shared with the MutablePage that was committed).
So when the next transaction calls useAsMutable, it should get a copy of the updated content.
UNLESS the CachedPage's content is a view of the MutablePage's content, and the MutablePage's content is modified AFTER the commit.
But the MutablePage is not modified after the commit. The transaction is popped and discarded.
So the CachedPage should have the correct content.
OK I give up trying to find the exact bug. Let me just implement a fix.
The fix will be to ensure that the sample count read is always consistent with the latest committed state. We'll do this by:
- Adding a method to TimeSeriesBucket that reloads the sample count from the page manager's cache
- Calling this method after acquiring the lock in TimeSeriesShard.appendSamples
Actually, that's complicated. Let me think of a simpler fix.
Here's a simpler fix:
In TimeSeriesBucket.appendSamples, instead of reading the sample count from the page, read it from a global atomic counter that is updated atomically with the write.
Here's how it works:
- Add an
AtomicInteger field to TimeSeriesBucket for each data page (or just one for the active page)
- When appending, use
atomicCounter.getAndIncrement() to get the next slot
- Write the data to the slot
- Update the page's sample count to match the atomic counter
But wait, this doesn't help because the atomic counter would be reset on restart. We need to read the initial value from the page.
Hmm, but for the concurrent case, the atomic counter should work correctly. The initial value can be read from the page once, and then all concurrent updates go through the atomic counter.
But what if the page is changed by another process (e.g., compaction)? The atomic counter might get out of sync.
OK this is getting too complicated. Let me just implement a simpler fix.
The fix: In TimeSeriesBucket.getOrCreateActiveDataPage, after getting the page, RE-READ the sample count from the page manager's cache to ensure it's the latest committed value.
But how do we access the page manager's cache from within the bucket? We'd need to pass the database or page manager to the method.
Actually, a simpler fix is:
In TimeSeriesBucket.appendSamples, after getting the data page from getOrCreateActiveDataPage, re-read the sample count directly from the page (bypassing the transaction's cache).
But how do we bypass the transaction's cache? We can't.
OK let me think about this differently. The issue is that the page is loaded by the transaction, and the transaction's cache might have a stale page. But the transaction's cache should be empty for a new nested transaction.
Unless the nested transaction is somehow getting the parent transaction's cached page.
Wait, let me re-read the TransactionContext's getPageToModify:
MutablePage page = modifiedPages != null ? modifiedPages.get(pageId) : null;
if (page == null) {
if (newPages != null)
page = newPages.get(pageId);
if (page == null) {
final ImmutablePage loadedPage = immutablePages.remove(pageId);
if (loadedPage == null)
page = database.getPageManager().getMutablePage(pageId, pageSize, isNew, true);
else
page = loadedPage.modify();
// ...
}
}
return page;
So if the page is not in modifiedPages, newPages, or immutablePages, it calls database.getPageManager().getMutablePage().
Now, which database is used? It's this.database, the transaction's database field.
And the transaction's database field is set when the transaction is created:
tx = new TransactionContext(getWrappedDatabaseInstance());
So tx.database is getWrappedDatabaseInstance().
Now, in TimeSeriesBucket.appendSamples:
final TransactionContext tx = database.getTransaction();
Here, database is the bucket's database field, which is the original database (not the wrapped one).
And database.getTransaction() returns the current transaction from the thread-local context.
So tx is the nested transaction that was created by db.begin() (where db = getWrappedDatabaseInstance()).
And tx.database is the wrapped database.
When tx.getPageToModify() is called, it uses tx.database.getPageManager(), which is the wrapped database's page manager.
But the bucket's database field is the ORIGINAL database. So the bucket and the transaction are using DIFFERENT database instances.
Wait, but in standalone mode, the wrapped database is the same as the original database. So they should use the same page manager.
Unless the wrapped database is NOT the same as the original database in standalone mode.
Let me check. In LocalDatabase:
@Override
public DatabaseInternal getWrappedDatabaseInstance() {
return wrappedDatabaseInstance;
}
If wrappedDatabaseInstance is not set, it would return null. But that would cause an NPE.
So wrappedDatabaseInstance must be set. Let me search for where it's set.
Actually, I think in standalone mode, wrappedDatabaseInstance is set to this. Let me verify.
Looking at the code, I see setWrappedDatabaseInstance is a public method. So it's called from outside the class.
Let me search for where it's called.
Actually, I think the default value is this. Let me check the constructor.
I don't see a constructor that sets wrappedDatabaseInstance. So it might be null by default.
If it's null, getWrappedDatabaseInstance() returns null, which would cause an NPE.
But the test runs without NPE, so wrappedDatabaseInstance must be set.
Let me search for setWrappedDatabaseInstance:
Let me search for usages of setWrappedDatabaseInstance in the codebase to understand when it's set.
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -rn "setWrappedDatabaseInstance" /arcadedb --include="*.java" | head -20
</tool_call>