Time series: concurrent single-row SQL INSERTs silently lose samples (sealed-slot lost update)
Summary
Under many concurrent single-rowINSERT INTO <timeseriesType> SET ts=…, <tag>=…, <field>=… statements (each in its own transaction, as happens over the HTTP/wire protocols), the time series engine silently drops samples. The client receives success on every insert (HTTP 200, no exception, no ConcurrentModificationException), yet the stored row count comes up short. Confirmed real data loss: a full table scan returns the same short count as count(*), and a GROUP BY sensor_id shows specific series missing rows.
The batched InfluxDB line-protocol path (POST /api/v1/ts/{db}/write, which appends many samples in one engine call/transaction) is not affected. Single-threaded inserts are not affected.
Impact
Silent, unacknowledged data loss on the time series write path under concurrency. Severity is high because there is no error surfaced to the client — an application doing concurrent per-row ingestion over SQL (HTTP or gRPC) loses samples without any signal.
Environment
Observed on 26.6.1-SNAPSHOT (== the arcadedata/arcadedb:latest image at time of writing).
Reproduced both embedded (in-process engine) and over HTTP against the Docker image.
Reproduction
A. Embedded (fast, deterministic at high concurrency)
A disabled regression test is included in PR #4450:
engine/src/test/java/com/arcadedb/engine/timeseries/TimeSeriesConcurrentInsertTest.java
It creates a TIMESERIES TYPE … SHARDS 1, runs 48 threads × 5000 single-row INSERTs (each in its own database.transaction(...)), then asserts count(*) == 48*5000. Result: e.g. 239911 / 240000 — 89 samples lost, with no exception and no failed transaction.
Enable it by removing the @Disabled annotation.
B. Over HTTP (against the published image)
code
CREATE TIMESERIES TYPE sensor TIMESTAMP ts TAGS (sid STRING) FIELDS (v DOUBLE) SHARDS 1
Then 16 threads, each POSTing 5000 distinct single-row inserts to POST /api/v1/command/{db}:
json
Assistant
I'll analyze the issue carefully and work on a fix. Let me start by exploring the repository structure.
Assistant
Now let me understand the issue more clearly. The problem is that when the SQL INSERT path is used, it goes through engine.appendSamples which creates a transaction. Let me look at how this works:
Assistant
Now let me look at SaveElementStep to see how SQL INSERT calls into this:
Assistant
Now let me look at the test that demonstrates the issue:
Assistant
Now let me understand the issue better. Let me look at how transactions work and specifically look at the LocalDatabase for nested transactions:
Assistant
Now I understand the issue. Let me trace through the issue once more:
SQL INSERT INTO Reading SET ts=…, sid=…, v=… runs in its own transaction (call it outer TX1)
The path SaveElementStep → engine.appendSamples → shards[i].appendSamples opens a nested transaction on db (which is getWrappedDatabaseInstance())
In TimeSeriesBucket.appendSamples, the data page is fetched, the slot count is read, row is written, then the count is incremented
The nested transaction commits; the page write is committed
The OUTER transaction commits later, but the data is already in the page
Wait, let me re-read the issue. The issue 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)
Let me look at this more carefully. Let me see how nested transactions commit:
Assistant
Now let me check the MutablePage to understand page-level versioning and what data flows where:
Assistant
Let me check the actual transaction path for SQL inserts. First, let me look at the existing tests for time series:
Assistant
OK now I understand the full picture. Let me run the existing concurrent test to confirm it passes:
Assistant
Let me try to run the failing test to confirm the issue first:
Assistant
Let me first study the test path more carefully. The issue is about HTTP/SQL INSERT path. Let me check how the SQL INSERT path differs from the direct engine API:
Assistant
Now let me trace what happens in a SQL insert case:
SQL INSERT INTO Reading SET ts=…, sid=…, v=… is executed
The user calls database.transaction(() -> ...) or the framework calls it
LocalDatabase.begin() creates a transaction (outer)
The SQL execution reaches SaveElementStep.saveToTimeSeries
This calls engine.appendSamples(...) which calls shards[i].appendSamples(...)
Inside TimeSeriesShard.appendSamples, it acquires appendLock, then calls db.begin() again
Since db.getTransaction().isActive() returns true (we're in outer TX), LocalDatabase.begin() creates a NEW nested TX
This nested TX commits immediately, releasing the page write
The outer TX continues; later commits
Wait, the issue says "The append commit is nested inside the enclosing request transaction ... and the durable publish is effectively deferred to the transaction commit". Let me re-read the comment:
Assistant
Now I see. Each transaction has its own modifiedPages map. The nested TX has its own modifiedPages - when the nested TX commits, the version check happens, and the page is written. But since this is a nested TX, the parent's modifiedPages doesn't include the page.
Wait, but the page is written to disk with version v+1. So if the outer transaction tries to do anything with that page, it would read v+1. But the outer TX doesn't know about the page.
Let me re-read the issue: "a following serialized append reads a stalesampleCountInPage — the prior append's count → N+1 increment is not visible — so two appends compute the samerowOffset and write the same slot N; the later commit overwrites the earlier row."
So:
Thread A: nested TX reads page (say version 5) with sampleCount = N, writes row at slot N, increments count to N+1
Thread A: nested TX commits, page written with version 6
Thread B: gets the appendLock (after A releases it)
Thread B: nested TX reads page from disk, gets the page with sampleCount=N (but the page should have count=N+1!)
Assistant
Let me look at getCachedPage:
Assistant
Assistant
OK now let me look at getMutablePage in PageManager:
Assistant
OK so when thread B's nested TX starts, it calls getPageToModify which calls getMutablePage which calls getCachedPage. The page is in the cache with version V+1 (after thread A's commit). So thread B reads sampleCount = N+1 correctly.
Wait, but the issue says the count IS stale. Let me re-read more carefully:
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).
Hmm... wait, maybe the problem is that the page is NOT in the read cache after the nested commit, but in the write cache. Let me look at the commit2ndPhase:
Assistant
OK so updatePages calls writePages which puts the page in the read cache. So when thread B starts, the page is in the cache with version V+1. Thread B would read sampleCount = N+1 correctly.
So why does the issue occur? Let me look at it from a different angle. Let me actually run the failing test:
Assistant
Java 21 needed. Let me see what Java is available:
Assistant
Good. Let me use that Java. First, let me build the engine module:
Assistant
Good. Now let me first run the disabled test to confirm it reproduces the bug. Let me modify the disabled test temporarily:
Assistant
Let me just remove the @Disabled annotation:
Assistant
Let me delete the @Disabled annotation lines (43-47) temporarily for testing:
Assistant
Now let's also reduce the test to be faster. Let me run with smaller numbers first:
Assistant
Hmm, the test passed with my smaller version. Let me run it with larger numbers like the original (48 threads × 5000):
Assistant
The bug is reproduced: expected: 240000L but was: 239841L — 159 samples lost!
Now let me investigate why this happens. Let me re-read TimeSeriesShard.appendSamples:
Assistant
Assistant
Let me add a diagnostic to confirm what's happening:
Assistant
Let me add a "collision detector" similar to the one mentioned in the issue to confirm the exact mechanism:
Assistant
Let me add a collision detector that prints when the same slot is written twice:
Assistant
Now, let me think more carefully. I claimed that nested commit should flush the page. Let me trace more carefully...
Actually, I wonder if there's some caching of MutablePage in the read cache that has a stale version. Let me look at writePages and how the cache update works:
Assistant
OK so the page is in the read cache with the new version.
Now, let me check what happens when getMutablePage is called:
Assistant
So useAsMutable copies the content, including the version. Good.
Let me look at this from a different angle. Maybe the issue is that the NESTED TX's commit1stPhase doesn't actually update the read cache. Let me look at what happens between the checkPageVersion (in commit1stPhase) and updatePages (in commit2ndPhase):
OK wait, I see something. In commit1stPhase:
For each modified page, checkPageVersion is called and then it's added to pages list
The local variable pages is used to create the WAL buffer
The actual page version increment and write happens in commit2ndPhase via updatePages → updatePageVersion → writePages
So between commit1stPhase and commit2ndPhase:
The page is in the TX's modifiedPages with old version
The cached page in read cache is still at old version (or last flushed)
Let me look at what happens between A's and A releasing :
Assistant
Let me look at getOrCreateActiveDataPage:
Assistant
Hmm, OK. Let me now add a print to see if the same slot is being used by two threads. Let me add a print right at the read of sampleCountInPage:
Assistant
Wait, this looks fine — sampleCount is monotonically increasing. Let me check for any anomalies:
Assistant
OK I see! Looking carefully:
Page 1: sampleCount goes 0, 1, 2, 3, ..., 237 (page version 0 → 237) - THEN JUMPS TO page 2 at sampleCount=0, version=0
Wait! Look at page 1 sampleCount=237 pageVersion=237, and then sampleCount=238 pageVersion=238 for pageNum=2 (with sampleCount=0 pageVersion=0). That's because when filling page 1, sampleCount reached getMaxSamplesPerPage() and then it moved to page 2.
Wait, the SAME thread 128 wrote 109, 110, ..., 172 consecutively. That's weird. And then thread 118 wrote 173, 174, ..., 191, and thread 107 wrote 192 onwards. Let me look at the actual count:
Assistant
OK I now realize my output redirection is messed up — I lost the content. The original > /tmp/diag_full.txt overwrote with stderr only since the output of the test went to stdout but not stderr. Let me check the actual content:
Assistant
Hmm, the redirection didn't capture stderr. Let me capture both:
Assistant
240000 DIAG entries, exactly as expected. Let me look for anomalies:
Assistant
Hmm. The sample counts are unique... but that doesn't make sense — page 1 has 239 samples (sampleCount goes 0 to 238), and pages should have at most N samples. Let me check by page:
Assistant
OK each page has 478 entries — that's because it's being read for every sample. Wait, that's also weird. Each page should have just ~239 entries (one per sample). Unless... let me look at the test output more carefully:
Assistant
So page 1 has 478 entries. But expected ~239 (since 240000/2/501 ≈ 239 samples per page). So page 1 has 478 samples written! Twice as many as expected. That means there's DOUBLE WRITING — every sample is being written twice to the same page!
That's the bug — sample loss. Let me look for duplicates by looking at consecutive sample counts:
Assistant
OK so each sample count value 0-238 is duplicated! Every sample on page 1 was written TWICE — once with the original count, once with a stale count. So the FIRST write's data is overwritten by the SECOND write. The result: 239 writes but 239 lost = 0 net samples stored. So the bug is confirmed: page 1 ended up with only the last batch of writes.
Wait, let me verify. If each slot gets written twice, then the slot would contain only the second write's data. The "first" writes are lost. So we have 478 writes to page 1 with 239 distinct slots, meaning 239 writes are lost.
Now let me verify the test result: 240000 - 239 = 239761. Let me check:
Assistant
So 240000 - 239868 = 132 samples lost. OK, the loss depends on the run. But it's clear the bug exists.
Now, the question is — why does this happen? Let me look more carefully.
Then page 2 starts at sampleCount=0, pageVersion=0
So the page version increments monotonically. But the SAMPLE COUNT appears to be going up monotonically too in the order printed. Wait, but I said there are 478 entries with duplicates. Let me sort by appearance and check:
When the data page fills up (sampleCount=238, maxSamples=239), the code moves to a NEW page. But because of the stale read, thread 114 sees (the NEW page) at pageVersion=239, but in reality some other thread is concurrently writing to that page or the same page was reset.
Assistant
Assistant
OK, getTotalPages() returns the tx-scoped page count if any. Let me trace more carefully by adding more diagnostics. Actually, let me check the slot count:
Assistant
Wait, this is odd. Page 1 is being written again (sampleCount=0, pageVersion=239) even though page 2 should exist (getTotalPages=185!).
The issue is: after the first wave fills page 1, the HEADER should say dataPageCount=1. Then a new page is allocated (dataPageCount=2). When the second wave's thread sees page 1 with sampleCount=238 (full), it should allocate page 2.
But the second wave's thread sees sampleCount=0 on page 1! And pageVersion=239!
That means page 1 was reset. This can only happen via clearDataPages(). Or via the getOrCreateActiveDataPage reusing page 1 as a new page... wait, let me look at the code again:
java
final int newPageNum = dataPageCount + 1;
final MutablePage newPage;
if (newPageNum < getTotalPages()) {
// Physical page already exists — reuse it
newPage = tx.getPageToModify(new PageId(database, fileId, newPageNum), pageSize, false);
}
If dataPageCount=1 and getTotalPages()=185, then newPageNum=2. We allocate page 2.
But we see thread 130 writing to page 1 with sampleCount=0! So thread 130 didn't allocate page 2 — it allocated page 1!
The header version jumped to 43883, and dataPageCount is 0! How can this happen? Let me check if there's any code that resets dataPageCount to 0... let me search:
Assistant
Lines 489 and 518 set HEADER_DATA_PAGE_COUNT=0. Lines 489 is in clearDataPages. Let me see line 518:
Assistant
That's in initHeaderPage. So HEADER_DATA_PAGE_COUNT=0 happens at init time or after clearDataPages. Neither should happen during normal appends.
But the diagnostic shows headerVersion=43883 and dataPageCount=0! That means somehow the header page got RESET, or the writes were lost.
Let me trace this more carefully. The headerVersion jumped from say 1 to 43883. That means there were 43882 commits to the header page. But the header should ONLY have its dataPageCount incremented (1, 2, 3, ...) when a new page is allocated. Each commit should increment headerVersion by 1.
Assistant
So there's exactly ONE bad entry (plus the initial):
headerVersion=1, dataPageCount=0, getTotalPages=1 (initial - first call when type is created)
headerVersion=43883, dataPageCount=0, getTotalPages=185 (THIS IS THE BUG!)
Wait, what? dataPageCount=0 but getTotalPages=185! That means the header was reset to 0, but the file has 185 pages! How?
Let me look at the test sequence right before and after this:
Assistant
Now I see it! Look:
Header at version 43881: dataPageCount=184 (184 pages exist, page 184 was being filled)
Header at version 43883: dataPageCount=0, getTotalPages=185 (the header was reset!)
Between these two header reads, page 184 was at sampleCount=142, then thread 127 came in and saw headerVersion=43883 with dataPageCount=0!
But what code path could cause the header to be reset? Let me look at line 489:
Assistant
So clearDataPages resets dataPageCount to 0. This is called during compaction. But the test doesn't do any compaction... so why is it being called?
Wait — let me search for all callers of clearDataPages:
Assistant
So clearDataPages is called in the compaction process. The test doesn't trigger compaction explicitly. But the test runs and the pages filled up to 185 pages. Let me check what triggers compaction:
Assistant
So maintenance runs every DEFAULT_CHECK_INTERVAL_MS (probably 60s), but in the test we're appending fast. Let me check whether compactAll is the one being called:
Assistant
OK so compactAll is called by maintenance. Let me check if maybe the test runs maintenance or if there's a hidden trigger.
Actually wait, the test uses database.command("sql", "CREATE TIMESERIES TYPE ..."). That sets up the maintenance scheduler. The maintenance scheduler runs every 60s typically. But the test only takes ~40 seconds. So maintenance shouldn't trigger.
Hmm. Let me look at the diagnostic around when the reset happened. Page 184 was the latest. Total samples 184 * 239 = 43976 samples. Then suddenly headerVersion jumps to 43883 with dataPageCount=0! That means the test is approaching the maximum capacity, and then something resets the dataPageCount.
Wait, 43883 / 240 = 182. So after ~183 page allocations. Hmm.
Let me look at the timestamps in the diag to see when the reset happened. Let me find the time pattern:
Assistant
OK so we have 43880 → 43881 → 43883 (skip 43882!) → 43884... So between 43881 and 43883, a commit was made that didn't increment the version (or skipped one). That commit was the reset commit (dataPageCount=0).
So the bug is clear now: somewhere the clearDataPages (or similar reset) is being called, or someone is writing dataPageCount=0 to the header. But this isn't supposed to happen during appends.
Actually wait, let me think. We have headerVersion going from 43881 to 43883. The skipped version 43882 might be a clearDataPages call from the same thread, since clearDataPages writes to the header and would commit (incrementing version). But the test doesn't call compaction...
Hmm, wait. Could this be a CRASH RECOVERY? The TimeSeriesShard constructor does:
java
if (mutableBucket.isCompactionInProgress()) {
final long watermark = mutableBucket.getCompactionWatermark();
sealedStore.truncateToBlockCount(watermark);
mutableBucket.setCompactionInProgress(false);
database.commit();
}
But this is only at construction time. So it's not relevant for the running test.
Assistant
FOUND IT! The compact is being called! Let me see:
Assistant
So compact() is being called somehow. Let me check what triggers it. Let me look at the maintenance scheduler:
Assistant
So maintenance runs after 5s delay, then every 60s. The test takes ~40s, so maintenance might run once.
Looking at compactInternal:
It does Phase 0, 1, 2, 3, 4a, 4b, 4c
Phase 4c includes clearDataPages which is what we see
But wait, the compactionLock.writeLock() is supposed to prevent this. Let me re-check:
Assistant
So compactInternal takes writeLock at line 384, while appendSamples takes readLock at line 186. The two are mutually exclusive.
But wait — appendSamples releases the readLock BEFORE commit completes? Let me re-read:
Assistant
OK so appendSamples holds the readLock for the duration of the commit. Good. So if compact is running, appendSamples would be blocked.
So how can both be running? Maybe compact runs BEFORE the test fully starts, and clearDataPages wipes everything. Then the test continues appending to a clean bucket.
But that wouldn't explain why page 184 has 142 samples (184 * 239 = 43976 samples were written) and then suddenly the bucket is cleared.
Wait, let me re-read the diag:
code
Assistant
So in compactInternal, the writeLock is acquired at line 526 for Phase 4c (clearDataPages), held through the try block, and released at line 588. So during Phase 4c, no appendSamples can run.
But the diag shows appendSamples running. So either:
The diag is wrong
The writeLock was NOT held during clearDataPages
clearDataPages was called from elsewhere
Let me check if maybe there's a separate path:
Assistant
Only clearDataPages writes 0. And it's only called from TimeSeriesShard.compactInternal (line 572). Line 519 is in initHeaderPage, only called at file creation.
So compactInternal was running. But how can it run concurrently with appendSamples?
Let me look more carefully. Actually I see in the diag:
This is thread 127 reading the header. The dataPageCount=0! But thread 127 just printed the "DIAG-GOCADP" line — that's getOrCreateActiveDataPage. So thread 127 is in appendSamples flow!
But how could the header have been reset to dataPageCount=0? Let me look at the full sequence just before:
Assistant
Wait, these all say dataPageCount=10! That doesn't match what I saw before. Let me look more carefully:
Assistant
Wait, the file shows dataPageCount=10 for these versions. But the earlier output showed dataPageCount=184 for the same versions! Let me check the file:
Assistant
Wait, my earlier output was from a different run. Let me re-run and check. But first, let me check that I'm comparing the right things:
Assistant
OK so there's 1 DIAG-CLEARDATA event from thread 95. Let me find it in the timeline:
Maintenance triggers compactInternal which calls clearDataPages (writeLock is held for compactInternal)
clearDataPages resets dataPageCount to 0 and writes to header
Assistant
Yes, ReentrantReadWriteLock. A writeLock holder can re-acquire the readLock (it goes up to write count). So... no, that doesn't matter here. Different threads.
OK, I wonder if appendSamples is being called WITHOUT the readLock. Let me check SaveElementStep and the SQL flow. Wait, the engine.appendSamples calls shards[i].appendSamples(...). Let me check:
Assistant
Both go through shards[shardIdx].appendSamples(...). The single-sample path and the batch path both use the shard's appendSamples. So both should acquire readLock.
But wait, line 180 — in appendBatch — this is dispatched to shardExecutor (a different thread). The dispatch is CompletableFuture.runAsync(() -> shards[shardIdx].appendSamples(...), shardExecutor). So yes, the batch path also acquires the readLock.
So why is the lock not preventing concurrent execution?
Let me look at when this test runs the maintenance. The maintenance scheduler has initialDelay=5_000ms and then period=60_000ms. So it runs at T=5s, T=65s, T=125s, etc.
Test takes ~40s. So maintenance runs once at T=5s. Hmm. Let me check if the test maybe gets to a state where maintenance is running concurrently with appends:
Assistant
So just before the clearData:
Thread 143 wrote sample 196 on page 174, headerVersion=41545
Thread 95 (compact) does clearData, which would commit at headerVersion=41546 (with dataPageCount=0)
Then thread 96 reads headerVersion=41547 (with dataPageCount=0), creates page 1 with sampleCount=0
So the sequence is:
Thread 95 (compact) holds writeLock
Thread 95 does clearDataPages
Thread 95 commits, writeLock released
Thread 96 acquires readLock
Thread 96 reads header, sees dataPageCount=0
Thread 96 creates page 1, writes sample 0
But wait — between step 2 and 3, OTHER threads could be reading the header! Because the writeLock is held, no other thread should be in appendSamples. But... wait, let me look at this again.
Actually I see now. The compact is running while appends are running. The readLock/writeLock should prevent this. Let me check if maybe the lock is being acquired in the wrong scope:
Assistant
OK so the readLock IS acquired. Let me verify by looking at the compact path:
Assistant
OK so compactInternal does:
Take writeLock
db.begin
work
db.commit
Release writeLock
Phase 4c starts at line 526 with another writeLock acquisition. Let me see:
Assistant
So Phase 4a takes the writeLock briefly, then RELEASES it. Phase 4b is lock-free. Phase 4c takes the writeLock again.
But during Phase 4b, appendSamples CAN run. So new data is being written to the mutable bucket. Then Phase 4c takes the writeLock and reads the "tail" pages.
Now the question: when Phase 4c's clearDataPages is called, the writeLock is held. So no other appendSamples can run.
But the diag shows appendSamples running! Let me add a more detailed diagnostic:
Assistant
Now let me also add a log to check if writeLock is being released prematurely. Actually, let me just check if appendSamples is really taking the readLock:
Assistant
Hmm, I see the diag log shows:
Thread 107 starts but doesn't get the readlock
Thread 104 starts but doesn't get the readlock
Thread 95 (compact) does CLEARDATA
Thread 114 GOT-READLOCK
Thread 114 reads dataPageCount=0
So thread 95 (compact) holds the writeLock, and other threads are blocked on readLock acquisition. Thread 114 is the first to get the readlock after compact completes. And it sees dataPageCount=0.
So actually the locks ARE working correctly! The problem is that clearDataPages is the bug — it shouldn't be happening during the test.
But the test doesn't explicitly call compaction. So maintenance must be triggering it. Let me check the maintenance:
Assistant
So compactAll is only called by maintenance. And maintenance runs every 60s after a 5s initial delay. The test takes 40s. So maintenance runs ONCE at T=5s.
But wait, the test took 40s but the compact happened at line 176659 of 240000+ log lines. Let me see if this is the first compact or if it happens multiple times:
Assistant
Only one compact. So maintenance runs once.
But here's the problem: the compact happens during the test, when many threads are appending. The compactionLock.readLock/writeLock should prevent concurrent execution, but the COMPACT itself is allowed to run, and the data loss happens when compact finishes and the next append starts writing to a "fresh" page 1.
So this is a different bug than what the issue describes! The issue is about concurrent single-row INSERTs, and the trigger is data loss in slot read-modify-write. But the actual cause here is compaction wiping the bucket in the middle of the test.
But wait, the issue does say "the test creates a TIMESERIES TYPE ... SHARDS 1" and runs 48 threads × 5000 inserts. It should reproduce WITHOUT maintenance running, right? Let me re-read:
A disabled regression test is included in PR #4450
So the test is from PR #4450. Let me check if the test is expected to be deterministic or not. Looking at the issue:
Result: e.g. 239911 / 240000 — 89 samples lost, with no exception and no failed transaction.
Assistant
Good, no DIAG. Now let me think about this more carefully. The test loses 89 samples (out of 240000) according to the issue. But with compaction also running, the loss is much higher (100s). Maybe the loss WITHOUT compaction is what we need to fix.
Let me check the test runtime. With 48 threads × 5000 inserts, the test should take some time. Let me see what the test runtime is. Actually, the test might run fast enough that maintenance doesn't trigger. Let me check by disabling the maintenance scheduler:
Assistant
Assistant
So countSamples() counts both sealed and mutable. But the test does SELECT count(*) FROM Reading. Let me check the SQL count:
Assistant
Assistant
Actually, let me focus on the real issue. The issue says the bug is that two appends compute the same rowOffset. Let me see if maybe the issue is somewhere different from what I observed.
Let me look at the actual appendSamples of TimeSeriesBucket more carefully:
Assistant
OK let me run my test with a small modification to NOT trigger maintenance. Actually, let me see — the test in the original issue is from PR #4450. Maybe it disables maintenance. Let me look at the test:
Looking back at the test, it doesn't disable maintenance. So the test SHOULD trigger maintenance. And the loss is 89-159 samples. If compact wiping 175 pages caused the loss, we'd expect 175+ samples lost. So the actual loss is from a different mechanism.
But wait, my last diag run showed:
Pages 1-175 are filled (175 pages)
Compact happens, moves data to sealed store, clears header
Next appends fill pages 1-175 AGAIN (overwriting slot 0 of each)
Total samples in sealed + mutable = should be 240000
But the test reports 132-159 lost. So 240000 - 132 = 239868, and that should equal (sealed + mutable).
Let me actually run a different test to see what the real loss is. Let me try with 48 threads and 5000 to see the original test result, and let me also disable the maintenance:
Assistant
So CountFromTypeStep uses context.getDatabase().countType(targetName, true). Let me check this:
Assistant
OK so for TimeSeries, countType uses tsType.getEngine().countSamples(), which counts both sealed and mutable. So the count should include the data in the sealed store.
So if compact moves 41825 samples to sealed and then 175 new samples overwrite the first slot of each page, we have:
Sealed: 41825 (old data, before compact)
Mutable: depends
The mutable bucket has pages 1-175 with 175 samples written to slot 0 (overwriting old). But slots 1-238 of each page have the OLD data. However, the sampleCount on each page is 1 (not 239). So when we scan the mutable bucket, we only see 175 samples.
Wait, but countSamples() does getMutableBucket().getSampleCount(). Let me check:
Assistant
So getSampleCount reads from the HEADER's HEADER_SAMPLE_COUNT_OFFSET (8 bytes). This is the total count, not per-page. So this should be correct.
But countSamples() does:
java
Assistant
So 240000 - 239879 = 121 lost. Hmm, that's still small.
Wait, maybe the test takes only 22s. Let me see if maintenance triggers. With 22s, the initial 5s delay has passed and the first maintenance run would have happened. But the period is 60s, so only 1 run.
OK let me trace through with maintenance running ONCE at T=5s:
At T=0, test starts. Threads begin appending.
At T=5s, ~60000 inserts have been done (if 12000 inserts/sec). Pages 1-250 are filled. (250 pages × 239 samples = ~60000)
Maintenance runs. It calls compactAll, which calls compact for each shard. compact acquires writeLock, processes all pages, moves to sealed store, clears header.
After compact, the test continues. ~180000 more inserts to do.
New appends: pages 1-250 are reused, each gets 1 sample written (slot 0 overwritten). So we lose 250 samples.
New appends continue: pages 1-250 fill up again (239 samples each), then new pages 251, 252, etc.
So loss = 250 samples (one per reused page). The test reports 121 lost. Close but not exact.
But here's the thing: the data is in sealed store. So the count should be 240000. Unless something else is going wrong.
Let me look at this from a different angle. Let me run the test multiple times to see consistency:
Assistant
Consistent: ~120-130 lost per run. So the loss is reproducible.
Hmm, 130 lost vs 175 pages reset. Maybe maintenance runs AFTER all inserts are done? Let me check the maintenance timing.
Actually wait, the test does awaitTermination(5, TimeUnit.MINUTES). So it waits up to 5 minutes for the threads to finish. But the threads finish after ~22s. So the maintenance runs at T=5s (with 0-1s jitter). Then the test continues for ~17s.
Assistant
Hmm, getShardsInternal may not exist. Let me check:
Assistant
So:
actual = 239973 (27 lost)
sealedCount = 47399
mutableCount = 192574
47399 + 192574 = 239973 ✓ matches actual
So the count is consistent. The "loss" is 27 samples (240000 - 239973 = 27). And the loss is in either sealed or mutable, but they add up correctly.
Hmm 27 lost is much less than my 120 estimate. Let me run again:
Assistant
So the loss varies: 17 to 106 samples. That's small. But it's still real data loss.
Wait — the maintenance is making the test flaky, but the loss WITHOUT maintenance might be different. Let me think...
Actually, the loss from my analysis (compaction overwriting) should be 1 sample per page that was reset. With maintenance running at T=5s and ~60000 inserts done, that's ~250 pages reset, 250 samples overwritten. But those samples are in the sealed store (moved by compact). So they should be counted there.
But wait, when the new sample is written at slot 0 of a reset page, the slot 0 of the OLD page had a sample. That sample is now in the sealed store. The NEW sample is in the mutable. The total is preserved.
But there's also the HEADER_SAMPLE_COUNT. After compact, it's reset to 0. Then new appends increment it. So the total count is correctly tracked.
So how is the loss 17-106 samples? Let me check the actual page count:
Assistant
90 lost. dataPageCount=816, sealedCount=45104, mutableCount=194806. Sum = 239910 ✓.
OK so the loss is real but small. The data is in the sealed store, so the data should be in there.
Wait, I wonder if the loss is from the data being overwritten in the sealed store. Let me check if sealed store has duplicate data due to compaction.
Actually let me think about this more carefully. The compact processes pages 1-250 (at T=5s), moves them to sealed. Then new appends go to pages 1-250 (reusing them). The OLD data in slots 1-238 is still in the pages (just not counted). But the NEW data overwrites slot 0.
So:
Sealed: 60000 (moved from mutable by compact, correctly)
Mutable, slot 0 of pages 1-250: NEW (250 samples)
Mutable, slots 1-238 of pages 1-250: OLD (in disk but not counted)
Plus, slots 0-238 of pages 251+ (newly allocated): NEW
So mutable count = 250 (slot 0 of reused pages) + (180000 - 250) (other new samples) = 180000. Plus sealed 60000 = 240000.
Assistant
Wait, that's a hack. Let me think differently.
The issue says the loss is from concurrent single-row inserts without exception. The mechanism described is a stale slot count. But my diag shows no stale slot count.
Hmm wait, maybe the issue's mechanism is what I observed — but the description is wrong about the cause. Let me re-examine my diag output for the COMPACT event.
Actually, the loss could be from this: the compact's Phase 4b writes the data to a TEMP file. Then Phase 4c swaps the temp file into the sealed store AND clears the mutable header. The swap is atomic (within the TX). But during Phase 4b, appenders can be writing to the mutable bucket. Then Phase 4c reads the "tail pages" (new pages created during Phase 4b), processes them, and clears the header.
So Phase 4c reads:
Pages 1-250 (filled before Phase 4a)
Pages 251+ (filled during Phase 4b)
It processes all of them and writes to sealed. Then clears the header. So all the data is preserved in the sealed store.
But wait, there's a subtle issue. Phase 4a reads pages 1-250 (at T=5s). Then Phase 4b (no lock) compresses them. During Phase 4b, appenders can write to pages 251+. Phase 4c reads tail pages (251+).
So all data should be preserved. Let me run the test with a SHORTER test to see if compact is the cause:
Assistant
With 48 × 200 = 9600 inserts, the test PASSES! 9600/9600 exact. No loss. And no compaction (sealedCount=0).
So the loss in the original test (48 × 5000) is from compaction. Let me try 48 × 1500:
Assistant
Loss of 121 samples. With 48 × 1500 = 72000 inserts in 10.54s, maintenance ran once at T=5s.
Loss: 72000 - 71879 = 121. Sealed: 43806, Mutable: 28073, Total: 71879. So the loss is 121, much smaller than the 43806 in sealed. So it's not the 121 lost being overwritten slots in the mutable (that would be 1 per page reset, so ~200 pages reset, 200 lost).
Hmm, 121 vs 200. Off by ~2x. Let me try smaller:
Assistant
With 48 × 800 = 38400 inserts, ALL 38400 are in the sealed store! And no loss!
So the test passes when all data goes to sealed. But the test fails when there's both sealed and mutable. Interesting.
So compact happens, moves 43774 to sealed, then new appends go to mutable. Loss = 100.
Wait, only 18 pages in mutable. Each page reset loses 1 sample (slot 0 overwritten). So 18 lost. But 100 lost!
Hmm. Or 100 samples are the in-flight appends that didn't make it to either sealed or mutable.
Let me look at this more carefully. Maybe the data IS in the pages, but sampleCount doesn't reflect it. Let me check by scanning the actual data:
Assistant
scanCount=47951. count()=47900. So scanning gives 51 MORE than count()! That means the count(*) is UNDERCOUNTING, and the actual data is in the pages but not counted in sampleCount.
So the bug is: after compact, the page is "reused" with sampleCount=0, but the old data is still there. When new data is written, sampleCount is incremented. But the OLD data (slots 1-238) is still in the page and IS visible when scanning (because the scan reads sampleCount slots, but the new sampleCount=1 means only slot 0 is read).
Wait, but scanCount=47951 > count()=47900. So scanning reads MORE rows than count(). That means the scan reads slots 1-238 too? Let me check:
Assistant
Yes, scan reads sampleCount slots. So if sampleCount=1, scan reads 1 row. But scanCount=47951 > count(*)=47900 means scan reads more.
Let me look at the sealed store scan:
Assistant
So getTotalSampleCount sums the block directory entries. Each block has a sampleCount that's set when the block is written.
Let me check if maybe the sealed store is missing samples because of how the blocks are split:
Actually wait, the scan count is HIGHER than count(). So scanCount=47951 means the full scan reads 47951 rows. count()=47900 means the count is 47900. So 51 extra rows are visible to the scan but not counted.
Let me check the SQL count vs scan. Maybe count(*) is using a different path that doesn't include all rows:
Assistant
So count(*) uses CountFromTypeStep, which calls countType. For TimeSeries, it uses engine.countSamples(). Let me check what this does:
Assistant
So countSamples = sealed.getTotalSampleCount() + mutable.getSampleCount().
getSampleCount in mutable reads the header's HEADER_SAMPLE_COUNT_OFFSET which is incremented in updateHeaderStats. Each append increments this by 1. So this should be correct.
The scan reads slots 0 to sampleCount-1 of each page. So it reads the same as the count.
But scanCount=47951 > count(*)=47900. So scan reads more than count. How?
Oh wait, the difference might be in the sealed store. The scan reads from sealed and mutable. The count adds sealed.getTotalSampleCount() + mutable.getSampleCount(). If these differ, the count is wrong.
Maybe sealed store has duplicate samples because of how compact processes them. Let me check:
Assistant
OK, this looks correct. The data is added to the sealed store correctly.
But wait, let me look at the commitTempCompactionFile:
Assistant
OK, the sealed store looks correct. Let me check the actual scan:
Assistant
OK so scan reads sampleCount rows from each page. If sampleCount=1, it reads 1 row.
So scanCount should equal count. But it doesn't. So there's a difference.
Let me check: is the sealed store scan reading duplicates? Or maybe the count(*) is wrong but the scan is right.
Let me add a sealed scan:
Assistant
OK let me check what's different between count and scan. Let me see the engine's iterateQuery:
Assistant
Assistant
OK the count goes 0→1→2→3. Let me check after compact. The test has 48000 inserts. After compact, the count should be reset to 0. Then the next appends should show count going from 0 up.
Assistant
I can see count goes 0→1→2→...→10 in the initial phase, then it resets to 0 (compact), then 0→1→2→...→10 again. So the count IS reset to 0 after compact. And new appends go from 0.
So the count in the header is correctly reset and incremented. The issue is somewhere else.
Let me check the count that's actually in the header at the end:
Assistant
Hmm, getSampleCount is not being called. Let me check:
Assistant
Hmm, getSampleCount should be called. Let me check the test:
Assistant
No DIAG-GSC or DIAG-TEST output! Let me check the test:
Assistant
I see! Line 99 says rs.next() instead of rs2.next(). Bug in my test. Let me fix:
Assistant
Wait, only 1884 in mutable? But dataPageCount=8 only. 8 * 239 = 1912 max. 1884 makes sense (8 pages × ~235 average, or 7 full + 1 partial).
But the count is 47919 and scan is 47919. So no discrepancy this time. So count(*) and scan match.
But the loss is 48000 - 47919 = 81. Where did these 81 go?
sealedCount = 46035. mutable = 1884. Total = 47919.
So 81 are missing. They're not in the count and not in the scan.
Hmm, maybe the test has a different issue. Let me look at the maintenance:
Assistant
No errors. Let me also check if some appends are failing:
Assistant
So committed count is checked. If the test reaches the assertions, all 48000 inserts were committed. But count(*) shows 47919. So 81 are silently lost.
Let me try to find where the 81 are lost. Let me add the GOCADP diag back:
Assistant
So 2 times dataPageCount=0 is seen (initial + after compact). After compact, 8 pages are filled (8 * 478 = 3824 entries). 8 pages × 239 samples/page = 1912 max. But we have 3824 entries? That's 1912 entries per page on average.
Hmm wait, the test result said mutable=1884. 1884/239 = 7.88 pages. So ~8 pages. But 3824 / 8 = 478 entries per page. That's because the diag is in getOrCreateActiveDataPage, which is called for EVERY sample. So 1884 samples → 1884 calls to getOrCreateActiveDataPage. The 8 pages means 8 different pages were allocated. And each was called 478 times on average... that doesn't make sense.
Wait, 1884 / 8 = 235.5, not 478. So 478 is the number of getOrCreateActiveDataPage calls per page. But each sample is 1 call, so 1884 calls total. 1884/478 = 3.94. Hmm.
Let me look more carefully:
Assistant
So:
dataPageCount=1 to 174 with 239 calls each (for 174 pages, 239 calls = full page)
dataPageCount=174 with 194 calls (partial page)
dataPageCount=1 with 478 calls — WAIT THIS IS WEIRD
Actually, looking at this: dataPageCount=1 has 478 calls. That means getOrCreateActiveDataPage was called 478 times when dataPageCount=1. But each call should be one sample. So 478 samples? But 1 page × 239 = 239 max. So we have 478 calls for page 1?
Assistant
So at the beginning, headerVersion=2-4 had dataPageCount=1. Then later (headerVersion=41782+), dataPageCount=1 again. So after compact, the count is back to 1.
But 478 calls for dataPageCount=1 is weird. Let me check:
Assistant
Hmm let me check the dataPageCount=1 count:
Assistant
So 48000 calls total, 478 are for dataPageCount=1. The test is 48*1000=48000 inserts. 48000 - 478 = 47522. Hmm.
OK 478 calls for dataPageCount=1, of which 239 are the "pre-compact" calls (filling page 1). The other 239 are "post-compact" (filling page 1 again, after compact reset dataPageCount to 0 and the next append allocated page 1 again). That makes sense!
So the bug is:
Pre-compact: 174 pages filled, 174*239 = 41586 samples (plus a few more)
Compact: moves 41586 to sealed, clears dataPageCount to 0
Post-compact: 8 pages filled (1884 samples)
Total: 41586 + 1884 = 43470
But the test inserted 48000 samples. 48000 - 43470 = 4530 missing? That doesn't match the 81 loss.
Wait, my count might be off. Let me re-look at the dataPageCount distribution:
Assistant
So dataPageCount=1 to 19 have 478 calls each. dataPageCount=20+ have 239 calls each.
The 478 = 239 (pre-compact) + 239 (post-compact). So pages 1-19 were all reset by compact, and refilled post-compact.
Assistant
So 478 for dataPageCount=1-27, 243 for dataPageCount=28, 239 for dataPageCount=29+.
Wait, 27 pages have 478 calls each. So pre-compact dataPageCount reached 27, and post-compact also reached 27. And then post-compact went to 28 (243 calls = 239 + 4 partial), then 29+ with 239 (only post-compact).
So pre-compact dataPageCount went to 27, and post-compact went to 28 (243 = 239+4). Total post-compact pages = 28.
Hmm but the test shows mutable dataPageCount=8. Let me re-check:
Assistant
Assistant
OK 48000. So:
2 calls with dataPageCount=0 (initial + post-compact start)
dataPageCount=1 to 27 with 478 each = 27*478 = 12906 (combines pre + post)
dataPageCount=28 with 243 (239 pre + 4 post)
dataPageCount=29 to 173 with 239 each = 145*239 = 34655
But during Phase 1+2+3+4b, appenders can write to the mutable bucket. So new pages can be added. Phase 4a reads these new pages. Phase 4c clears the header (but only the new pages might be partially written).
Hmm, but Phase 4a uses the writeLock to snapshot. So it should get all the pages that were added during Phase 1+2+3+4b. Then Phase 4c processes them and clears the header.
So all the data should be in the sealed store. But 106 are missing.
Let me look at readFullPagesForCompaction and readPagesRangeForCompaction:
Assistant
Hmm, readPagesRangeForCompaction reads pages from fromPage to toPage. The sampleCount is read from the page. Then reads sampleCount rows.
So if the page has sampleCount=239, we read 239 rows. If sampleCount=194, we read 194 rows.
But here's a subtle bug: in readPagesRangeForCompaction, we read the page from the current transaction. If the page was being modified concurrently (without the write lock), we could get an inconsistent state.
Wait, but the function is called under the writeLock (Phase 4a). So no concurrent modification.
Hmm. Let me look at Phase 4a more carefully:
Assistant
Phase 4a reads pages lastFullPage + 1 to phase4aPageCount. Where lastFullPage = snapshotDataPageCount - 1 from Phase 0. So it reads pages AFTER Phase 0's snapshot.
Phase 0 saw 174 pages. Phase 1+2+3+4b runs without lock. So new pages might be added. Phase 4a reads them.
Then Phase 4c processes the data, swaps, and clears the header.
But what about the data that was ADDED during Phase 4b (between Phase 4a and Phase 4c)? Phase 4a snapshot might have been at 180 pages, then during Phase 4b, more pages (181, 182) might be added. Phase 4c then takes the writeLock, reads the new pages, processes them.
Let me look at Phase 4c:
Assistant
Phase 4c reads pages to (the new pages added during Phase 4b).
Assistant
Different numbers this time. dataPageCount=7, mutableCount=1463. So 7 pages. 1463 / 7 = 209. So pages are not all full. Last page is partial. 7 * 239 = 1673 max. 1463 / 7 = 209 avg.
So the data in the mutable is correct (counted correctly). The issue is sealedCount = 46452, but pre-compact samples = ?
OK let me just figure out the source of the loss. Let me add a per-shard diag to log the pre-compact sample count:
Assistant
Assistant
Assistant
Assistant
So:
snapshotDataPageCount = 191 (from Phase 0)
lastFullPage = 191 - 1 = 190
Phase 1+2 reads pages 1..190 (the full pages)
Phase 4a reads pages 191..phase4aPageCount (the partial last page and any new pages)
So page 191 is the partial last page. It's read in Phase 4a.
Assistant
Hmm, buildCompressedBlocks with returnSpill=true returns the spill. Let me check:
Assistant
Assistant
Assistant
OK so my proposed fix:
In Phase 4a, store phase4aData and the sample count of the partial last page (phase4aPartialPageSampleCount).
In Phase 4c, re-read the partial last page (page phase4aPageCount). Get the new sample count.
If the new sample count is higher, extract the new data (rows phase4aPartialPageSampleCount..newSampleCount-1) and add to .
Assistant
Let me actually remove the @Disabled:
Assistant
Let me look at the maintenance scheduler:
Assistant
Let me make a test that disables maintenance. Actually, let me just run the test with a much shorter period to disable maintenance effectively. Or better, let me modify the test to not have maintenance trigger:
Assistant
No cancelAll method. Let me add one:
Assistant
The original @Disabled was multi-line. After deletion, the method signature is gone. Let me fix:
Assistant
TEST PASSES WITH MAINTENANCE DISABLED!
So the bug is in the maintenance/compact path, not in the slot-count-stale path.
But wait, the issue says the test reproduces the bug WITHOUT maintenance. Let me re-read the issue:
Result: e.g. 239911 / 240000 — 89 samples lost, with no exception and no failed transaction.
Hmm, this is "e.g." which is an example. Maybe the loss is from the compact path.
But the issue's analysis says it's a slot-count-stale issue. Let me re-read more carefully:
The write position for a sample is a read-modify-write of the per-data-page sample count.
So the bug is in the read-modify-write of the sample count.
TimeSeriesShard.appendSamples serializes appends per shard with a around a nested
Assistant
OK so readShort reads from this.content. The content is the byte buffer of the page. It's a copy (per useAsMutable), so it shouldn't be stale.
OK so the issue's hypothesized mechanism is wrong. The actual bug is the compact one.
Assistant
Now let me think about the fix. Phase 4a reads pages lastFullPage + 1 to phase4aPageCount. This includes:
The partial last page at Phase 0 (page lastFullPage + 1 = snapshotDataPageCount)
Any new pages created during Phase 1+2+3
Wait actually, the partial last page at Phase 0 is page snapshotDataPageCount. The new pages created during Phase 1+2+3 are pages snapshotDataPageCount + 1, snapshotDataPageCount + 2, ....
So at Phase 4a time, we have:
Pages 1..lastFullPage = 1..snapshotDataPageCount-1: full
Of these, only the LAST page (phase4aPageCount) can be modified by appenders.
So in Phase 4c, we need to re-read page phase4aPageCount (if it exists) and extract the new data.
But wait, the new pages created during Phase 4b are pages . So is the LAST page that existed at Phase 4a time.
Assistant
Let me also look at readPagesRangeForCompaction to see if it has a way to read partial:
Assistant
OK so readPagesRangeForCompaction reads ALL samples (up to sampleCount) from each page.
Now let me think about the fix more carefully.
The bug: data added to page phase4aPageCount during Phase 4b is lost.
Fix: In Phase 4c, re-read page phase4aPageCount (if it exists), but only the NEW samples (added during Phase 4b).
To know what's new, we need to know the sample count of page phase4aPageCount at Phase 4a. We can compute this from phase4aData.
Actually, since phase4aData contains all the data read in Phase 4a, we can split it to get the data for the last page.
Hmm, but phase4aData is the combined data from all pages lastFullPage + 1 to phase4aPageCount. We can compute the sample count of the last page as the total count minus the count of all other pages.
Or we can just read the page and check its current sample count, then read only the new rows.
Let me design a fix:
Assistant
OK let me now design the fix. The cleanest approach is to:
In Phase 4a, also store the sample count of the last page (phase4aLastPageSampleCount).
In Phase 4c, re-read the last page, get the new sample count, and if there are new samples, add them to the to-be-compressed data.
Let me write the fix:
Assistant
OK now let me apply the fix carefully. First, let me look at the data structures:
Assistant
OK so readPagesRangeForCompaction(from, to) reads all samples from each page in [from, to].
Let me design the fix:
Phase 4a: Track phase4aLastPageSampleCount (sample count of page phase4aPageCount at Phase 4a time).
Phase 4c: Re-read the last page (page phase4aPageCount if it exists). If its current sample count is greater than phase4aLastPageSampleCount, extract the new data (rows phase4aLastPageSampleCount to currentCount - 1) and add to the to-be-compressed data.
Let me think about how to track phase4aLastPageSampleCount. The simplest way is to read the page at Phase 4a time and remember its sample count.
Let me write a method that reads JUST the sample count of a page:
Assistant
OK so getDataPageCount reads the header. Let me add a method to get the sample count of a specific page:
Actually, the simpler approach is: just re-read the page in Phase 4c and compute the new data based on what Phase 4a saw.
Hmm, but we need to remember what Phase 4a saw. Let me just add a parameter to track the phase4a sample count of the last page.
Actually, the simplest approach: Phase 4c re-reads page phase4aPageCount and gets the CURRENT sample count. Then we know the new data is at rows oldCount..currentCount-1. But we need to know oldCount.
OK let me just add the tracking:
Assistant
OK now let me think about the fix more concretely. Let me look at the test results to see if my fix is necessary:
Actually wait — I realized that the test PASSES when I disable maintenance. So in the original test (with maintenance), the loss is from compact. The fix should address the compact issue.
But the issue is from a user, and they reported the test as failing. So my fix needs to make the test pass.
Let me focus on the compact fix.
Now, the actual mechanism:
Phase 4a reads pages lastFullPage + 1 to phase4aPageCount. This includes the partial last page (at Phase 0) and any new pages.
During Phase 4b, appenders can write to the partial last page (page phase4aPageCount).
Phase 4c only reads pages phase4aPageCount + 1 to finalPageCount (new pages). The data on page phase4aPageCount (added during Phase 4b) is LOST.
Fix: In Phase 4c, also re-read page phase4aPageCount to capture new data.
Let me implement this:
Assistant
Now I need to add the readPageSampleCount and readPageRangeForCompaction methods to TimeSeriesBucket, and the mergeCompactionData3 helper to TimeSeriesShard:
Assistant
Now let me add the mergeCompactionData3 helper:
Assistant
OK let me add mergeCompactionData3:
Assistant
Wait, I need to also handle the case where partialTailData != null and tailData == null AND phase4bSpill == null. Let me check the logic:
Assistant
I have a bug: else if (partialTailData != null) toCompressFinal = mergeCompactionData(tailData, partialTailData); — but tailData could be null here! Let me fix the logic:
Assistant
Assistant
Now let me re-enable maintenance in the test and run it:
Assistant
TEST PASSES WITH MAINTENANCE ENABLED! Let me run it a few more times to confirm:
Assistant
All 3 runs pass! Now let me also run the other time series tests to make sure I didn't break anything:
Assistant
All 173 time series tests pass!
Now let me also test with the larger test size (48 × 5000 = 240000) to confirm:
Assistant
5/5 runs pass. Now let me also check the load tests referenced in the issue:
Assistant
Now let me also think about edge cases:
What if phase4aPageCount doesn't exist at Phase 4c time? This could happen if the page was... hmm, no, pages don't get deleted during compact. So phase4aPageCount should still exist.
What if the data on the page is the same as before? Then currentLastPageSampleCount == phase4aLastPageSampleCount, and partialTailData = null. We don't add anything extra. Good.
What if the page count decreased? E.g., the file was compacted. Hmm, this shouldn't happen during a single compact cycle.
Let me also check the maintenance test files:
Assistant
Hmm, this test ALREADY uses ConcurrentModificationException retries. So the test expects this. With my fix, the partial-last-page data is now captured, so there should be fewer (or no) ConcurrentModificationException issues.
Let me run this test:
Assistant
All concurrent tests pass! Let me also think about HA scenarios. Let me check the HA tests:
Assistant
Let me look at the compactionReplicatesSealedBlocksAndClearsMutable test:
Assistant
Assistant
10/10 passes.
Now let me also think about the OTHER bug described in the issue: stale slot count. My investigation showed the slot count is NOT stale. So maybe the issue's hypothesized mechanism is wrong, and the actual bug is the compact one I fixed.
But to be thorough, let me also look at the slot-count-stale path. Maybe there's a subtle bug I missed:
Assistant
OK this code looks correct. The slot count is read from the page, row is written, count is incremented. The same page is modified in the same TX. The lock is held (appendLock). So no race.
Hmm, but the issue says the slot count IS stale. Let me think about when this could happen.
Actually, wait. Let me look at the test from the issue more carefully. The test uses 48 threads × 5000 inserts. The threads each call database.transaction(() -> ...) to do each insert. The test was claimed to fail even WITHOUT maintenance.
But my test (with maintenance disabled) passes. So either:
The issue's hypothesized mechanism is wrong
There's a subtle race I missed
Let me think about what could make the slot count stale.
Assistant
OK so the SaveElementStep for TimeSeries:
Calls saveToTimeSeries(...) which does engine.appendSamples(...).
The SQL INSERT returns. The outer TX is still active (because the user's database.transaction() is still running).
The outer TX commits.
But in my test, I use database.transaction(() -> database.command("sql", "INSERT INTO Reading SET ts = ?, sid = ?, v = ?", ...)). So the user has an outer TX, runs the SQL command (which has the SaveElementStep), and then the outer TX commits.
So the flow is:
database.transaction() starts an OUTER TX
SQL command runs
Assistant
OK so on standalone, wrappedDatabaseInstance is... let me check what it's set to:
Assistant
Yes, on standalone, wrappedDatabaseInstance = this. So the nested TX is on the same instance.
OK so my fix should be the right one. Let me also clean up the diagnostic code in the test and confirm the original test passes:
Assistant
Now I need to enable the test. The issue says:
Enable it by removing the @Disabled annotation.
Let me re-enable it:
Assistant
Now let me also remove the unused import:
Assistant
Good. Now let me run the test:
Assistant
Now let me also remove the cancelAll method I added to TimeSeriesMaintenanceScheduler since it's not needed by the test anymore:
Actually wait, the test I wrote earlier used cancelAll. The original test doesn't. But the issue says the test should be enabled. Let me check if the cancelAll is needed...
The original test creates the type, which schedules maintenance. With my fix, the test should pass even with maintenance running. Let me verify by running multiple times:
Assistant
All 5 passes. So my fix works. The cancelAll method is not needed. Let me remove it:
Actually, let me keep cancelAll for now — it might be useful in the future for tests that need to isolate the append path. But the issue says "Interface: No new interfaces are introduced." — so I should remove it.
Let me also check if the test class uses it:
Actually, I removed the call to cancelAll in the test. So I should also remove the cancelAll method from the scheduler.
Assistant
Now let me also check the diff to make sure my changes are clean:
Assistant
Now let me also run the entire test suite to make sure I didn't break anything:
Assistant
All 173 tests pass! Let me also run the SQL tests since the SQL INSERT path is involved:
Assistant
All 1212 SQL tests pass! Let me also run the concurrent tests:
Assistant
All 10 concurrent tests pass! Now let me also look at the final diff:
Assistant
Clean diff. Let me look at the final code changes:
Assistant
The fix is clean. Let me also verify the final test passes consistently:
Assistant
5/5 pass. Let me also think about the impact of the fix:
The fix adds 2 new methods to TimeSeriesBucket (readPageSampleCount and readPageRangeForCompaction).
The fix adds 1 new method to TimeSeriesShard (mergeCompactionData3).
The fix modifies Phase 4a and Phase 4c of compactInternal to track and re-read the partial last page.
The fix enables the existing TimeSeriesConcurrentInsertTest test (removes @Disabled).
The fix is minimal and targeted. It addresses the specific bug where data added to the partial last page during Phase 4b (between Phase 4a's snapshot and Phase 4c's commit) was being lost when reset the page.
Assistant
10/10 pass!
Now let me also re-check the test for the original issue's description:
The issue mentions "the slot read-modify-write" as the cause. While I don't believe this is the actual root cause (my analysis shows the compact is the issue), my fix does address the actual data loss.
Let me also think about whether my fix is complete. The issue says:
Suggested direction (for discussion)
The core tension is that appendLock serializes the in-memory append but the durable publish is deferred to the enclosing transaction's commit (kept that way so writes ship via the parent Raft WAL). Any fix needs to make the slot read-modify-write atomic with respect to the actual publish without breaking HA replication
So the issue's suggested direction is to fix the slot read-modify-write. But the actual bug is the compact one. So the issue's analysis is wrong, but my fix addresses the actual bug.
Let me also verify by checking the actual data flow with my fix:
Assistant
All the fix elements are in place. Let me also do a final sanity check by running the related tests:
Assistant
All compact tests pass. Let me also check the full TimeSeries test suite one more time:
Assistant
All 173 TimeSeries tests pass.
Let me also do a final check to ensure the diff is clean and minimal:
Assistant
Clean diff, only 3 files changed. Let me also restore the original bucket and shard source files to make sure I'm not carrying any diagnostic code:
Assistant
No diagnostic code. Let me also verify the test file is clean:
Assistant
Clean. Let me also check the final file content of the test:
Assistant
Test is clean and matches the original (just with the @Disabled removed). Now let me also check the TimeSeriesBucket file:
Assistant
Clean addition. Let me also check TimeSeriesShard:
Assistant
Clean code. Let me also look at the mergeCompactionData3 helper:
Assistant
All good. Let me also run the full test suite one more time:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
{"language":"sql","command":"INSERT INTO sensor SET ts=<unique>, sid='s<thread>', v=<i>"}
SELECT count(*) FROM sensor returns short by 10–22 out of 80000 across runs.
Observations on the trigger
Concurrency level (thread count) is the driver, not total row count. 5 threads often look clean; 16–48 threads reliably lose.
SHARDS 1 maximizes it (all appends contend on one shard).
Single-threaded never loses.
The unfiltered SELECT count(*) reflects the true (short) count; a full row scan agrees with it (so it is real loss, not a count(*) artifact).
Root cause analysis
The write position for a sample is a read-modify-write of the per-data-page sample count. In TimeSeriesBucket.appendSamples (engine/.../engine/timeseries/TimeSeriesBucket.java):
java
final int sampleCountInPage = dataPage.readShort(DATA_SAMPLE_COUNT_OFFSET) & 0xFFFF; // read slot
final int rowOffset = DATA_ROWS_OFFSET + sampleCountInPage * rowSize;
dataPage.writeLong(rowOffset, timestamps[i]); // write row at slot
...
dataPage.writeShort(DATA_SAMPLE_COUNT_OFFSET, (short) (sampleCountInPage + 1)); // advance slot
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). 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 outsideappendLock.
A temporary collision detector added to appendSamples (recording fileId:pageNumber:slot per append) confirmed the mechanism: a following serialized append reads a stalesampleCountInPage — the prior append's count → N+1 increment is not visible — so two appends compute the samerowOffset and write the same slot N; the later commit overwrites the earlier row. The page version advances normally, and PageManager.updatePageVersion's version check does not raise a conflict for these commits, so the existing outer-transaction retries never kick in.
(slot reused across threads; page version high and advancing while the slot/count read is stale.)
Why the batched path is safe
TimeSeriesEngine.appendBatch groups all of a shard's samples into a single transaction per shard, so there is never a second concurrent transaction reading a stale slot on the same page.
Relevant code
engine/.../query/sql/executor/SaveElementStep.java — saveToTimeSeries routes a SQL INSERT into engine.appendSamples.
engine/.../engine/timeseries/TimeSeriesEngine.java — appendSamples (per-row) vs appendBatch (line protocol).
engine/.../engine/timeseries/TimeSeriesShard.java — appendSamples (appendLock + nested begin/commit on the wrapped instance).
engine/.../engine/timeseries/TimeSeriesBucket.java — getOrCreateActiveDataPage + appendSamples (the DATA_SAMPLE_COUNT_OFFSET slot RMW).
engine/.../engine/PageManager.java — updatePageVersion (the version conflict check that is not catching this).
Suggested direction (for discussion)
The core tension is that appendLock serializes the in-memory append but the durable publish is deferred to the enclosing transaction's commit (kept that way so writes ship via the parent Raft WAL). 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. This is a delicate change to the transaction/HA path and warrants careful design plus HA + performance verification.
Notes
A reliable embedded regression test is included (disabled) in PR #4450; enable once fixed.
The time series load tests in the same PR catch this at scale on the SQL protocols.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /arcadedb, current file: none) bash-$
outer
code
// 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).
So the nested TX commits, but the page writes are visible to the outer TX? Let me understand: when a nested TX commits, where do its dirty pages go?
Let me look at the commit flow:
Thread B: writes row at slot N, increments count to N+1
Thread B: commits, page written with version 7
Wait, but the page should have count=N+1 on disk after A commits. Unless... the read is reading the page from the cache which still has version 5? Let me look at the page caching:
OK so getMostRecentVersionOfPage reads from the read cache or disk. When the nested TX commits, the page is updated with new version and put in the read cache. So a subsequent read should see the new version.
Wait, let me re-trace:
Thread A: nested TX read page with version V (sampleCount=N), in getPageToModify → loads page from cache or disk
Thread A: writes row at slot N, increments count to N+1 → modifies the MutablePage in its TX
Thread A: nested TX commits → version becomes V+1, page is put in read cache
Thread B: gets appendLock, nested TX read page (via getMostRecentVersionOfPage, sees V+1 from cache) → loads page from cache
Thread B: reads sampleCount=N+1 (should be correct!), writes at slot N+1
Hmm, that seems fine. So where's the bug?
Wait, the issue says the append commit is nested inside the enclosing request transaction, "the durable publish is effectively deferred to the outer transaction commit". So the nested commit doesn't actually write to disk — the parent does. Let me re-read the comment:
Committing on the inner LocalDatabase here would persist the pages locally only, leaving followers with an empty bucket (issue #4382).
This comment is about HA Raft: nested commit on LocalDatabase doesn't go through Raft, so followers don't get the writes. But the writes ARE persisted locally.
Wait, but checkPageVersion is called from commit1stPhase. Let me look more carefully:
The nested TX's commit:
commit1stPhase(true) calls lockFilesInOrder and then checkPageVersion
checkPageVersion reads getMostRecentVersionOfPage which reads from read cache or disk
If the nested TX is the latest one to modify the page, the version check passes
updatePageVersion increments version and writes the page to cache+disk
So when thread B's nested TX starts, the page is in the cache with version V+1. Thread B's getPageToModify would load from cache and the page in B's TX's modifiedPages would have version V+1. Then B reads sampleCount = N+1, increments to N+2, etc.
Hmm, so where's the issue?
Wait, let me look at what happens with the OUTER transaction. After thread A's nested TX commits, the outer TX still has its own modifiedPages and newPages. The outer TX has NO pages in its modified pages (because the nested TX is separate). So when outer TX commits, it doesn't have any pages to write.
But the OUTER TX's pages are flushed elsewhere. Let me see — actually, when the nested TX is committed and the page is in read cache, but the page version is still V+1. So another thread B doing getPageToModify will load version V+1.
Let me see what actually happens... Maybe the issue is in getPageToModify:
OK so when this is called from SQL INSERT path:
Outer TX is active (from database.transaction(() -> ...) or db.begin())
TimeSeriesShard.appendSamples is called
appendLock.lock() — serialized
db.begin() — but since outer TX is active, this creates a NESTED TX
db.commit() — commits the NESTED TX (its pages are persisted)
appendLock.unlock()
OK now I need to figure out where the stale read comes from. Let me trace very carefully:
The nested TX has its own modifiedPages and newPages. When the nested TX commits:
commit1stPhase: builds a list of pages from modifiedPages + newPages, calls checkPageVersion on each
commit2ndPhase: calls database.getPageManager().updatePages(newPages, modifiedPages, asyncFlush), which calls updatePageVersion then writePages
So nested TX commits flush its pages. The page version is incremented and put in the read cache.
But — important detail — commit1stPhase does checkPageVersion(p, false). Let me re-read:
java
for (final Iterator<MutablePage> it = modifiedPages.values().iterator(); it.hasNext(); ) {
final MutablePage p = it.next();
final int[] range = p.getModifiedRange();
if (range[1] > 0) {
pageManager.checkPageVersion(p, false);
pages.add(p);
} else
// PAGE NOT MODIFIED, REMOVE IT
it.remove();
}
public void updatePages(...) {
lock();
try {
final List<MutablePage> pagesToWrite = new ArrayList<>(...);
if (newPages != null)
for (final MutablePage p : newPages.values())
pagesToWrite.add(updatePageVersion(p, true));
for (final MutablePage p : modifiedPages.values())
pagesToWrite.add(updatePageVersion(p, false));
writePages(pagesToWrite, asyncFlush);
...
} finally {
unlock();
}
}
So updatePageVersion is called TWICE for the same page: once in checkPageVersion (from commit1stPhase) and once in updatePageVersion (from updatePages in commit2ndPhase).
Looking at updatePageVersion:
java
public MutablePage updatePageVersion(final MutablePage page, final boolean isNew) throws IOException, InterruptedException {
final PageId pageId = page.getPageId();
final int mostRecentPageVersion = getMostRecentVersionOfPage(pageId, page.getPhysicalSize());
if (mostRecentPageVersion != page.getVersion()) {
...throw CME...
}
page.incrementVersion();
page.updateMetadata();
...
return page;
}
So checkPageVersion checks but doesn't increment. updatePageVersion increments. So the actual increment happens in commit2ndPhase.
Now, the question is: when does another thread (B) start reading? After thread A's appendLock.unlock(). By that point, A's nested TX has fully committed (both phases), so the page in cache has version V+1.
When thread B does getPageToModify, it goes through getMutablePage → getCachedPage → readCache.get(pageId) → returns the cached page with version V+1.
Then getPageToModify puts it in B's TX modifiedPages. B then reads sampleCount = N+1 correctly.
So the simple case shouldn't lose samples. But it does. Let me look more carefully at the test path:
Wait, the test uses database.transaction(() -> ...) and inside calls database.command("sql", "INSERT INTO Reading SET ..."). So inside the transaction, there's an outer TX and the SQL command is executed.
Let me trace more carefully. The user's test:
java
database.transaction(() ->
database.command("sql", "INSERT INTO Reading SET ts = ?, sid = ?, v = ?", ts, "s" + threadIndex, v));
database.transaction(Runnable) creates a transaction, runs the lambda, commits or rolls back. So there's an outer TX.
Now inside, database.command("sql", "INSERT INTO Reading SET ...") parses and executes the SQL. The INSERT step is SaveElementStep.saveToTimeSeries, which calls engine.appendSamples(...).
engine.appendSamples is the SINGLE-sample path. It calls shards[i].appendSamples(...). Inside TimeSeriesShard.appendSamples, we get appendLock, then db.begin(). Since outer TX is active, this creates a NESTED TX on the wrapped database.
Wait, the wrapped database. Let me see — database.getWrappedDatabaseInstance() returns... what? On standalone, the same instance. So we have outer TX on LocalDatabase, then nested TX on LocalDatabase. The nested TX's commit goes through LocalDatabase.commit().
LocalDatabase.commit() does:
java
final Binary result = current.getLastTransaction().commit();
...
current.popIfNotLastTransaction();
getLastTransaction() returns the innermost TX (nested). commit() runs commit1stPhase and commit2ndPhase. Then popIfNotLastTransaction() removes the nested TX, leaving the outer TX active.
So after the nested TX commits, the outer TX is still active. The data page has been written with version V+1.
Now the SQL INSERT step returns, database.command() returns, the user's database.transaction() calls commit() on the outer TX. The outer TX's modifiedPages and newPages should be empty (it didn't modify any pages). So commit1stPhase returns null (no changes). commit2ndPhase returns null.
OK so where's the bug?
Let me add diagnostic code to see the page version progression:
Both are inside db.commit(). So after db.commit() returns, the page is in read cache at version V+1.
OK so my trace seems right. Let me look more carefully. Let me add diagnostic code to print what's happening:
sampleCount=0
Wait, the sampleCount went from 238 to 0, and then back up. That means the page was REUSED. So getOrCreateActiveDataPage must have created a NEW page at pageNum=1 (because the old page 1 was "full") and the same page 1 was reused. But that doesn't match — page 2 starts later.
Actually let me look more carefully. The page number stays at 1, and the page version keeps going up. The sampleCount went to 238 (full), then 0 again (a new "instance" of page 1? or the page got reinitialized?).
Let me think about what getOrCreateActiveDataPage does:
Reads HEADER_DATA_PAGE_COUNT from page 0
If > 0, checks if the last page has room
If full or no pages, creates a new page
The new page is initialized with sampleCount=0 in its data bytes. But the page itself was previously used — it's an existing physical page that gets reinitialized.
So:
Thread A writes at page 1 with sampleCount=238, then page version=238
Thread A's commit finishes, page is in read cache with version 238
Thread B comes in, reads page 1 with sampleCount=238 (full). Decides to create a new page.
Thread B creates page 2 with sampleCount=0.
BUT — meanwhile, thread C reads page 1 sampleCount=238 (full), creates page 2 too (sampleCount=0)
Thread B/C writes at page 2 sampleCount=0, then increments to 1, page version=1
Hmm, but then we'd see two page 2 entries with sampleCount=0. Let me check:
Page 2 starts fine. So the issue must be that page 1's sampleCount goes from 238 (full) to 0 — that means a NEW page was created at pageNum=1. But page 1's physical location was reused (since getOrCreateActiveDataPage reuses existing physical pages).
Hmm wait, let me re-look at getOrCreateActiveDataPage:
java
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;
}
// Need a new (or reused) data page
final int newPageNum = dataPageCount + 1;
final MutablePage newPage;
if (newPageNum < getTotalPages()) {
// Physical page already exists — reuse it (typical after compaction clears the header)
newPage = tx.getPageToModify(new PageId(database, fileId, newPageNum), pageSize, false);
} else {
// Physical page does not yet exist — allocate it
newPage = tx.addPage(new PageId(database, fileId, newPageNum), pageSize);
pageCount.incrementAndGet();
}
// Initialise the page (old data bytes beyond sample-count are ignored by readers)
newPage.writeShort(DATA_SAMPLE_COUNT_OFFSET, (short) 0);
newPage.writeLong(DATA_MIN_TS_OFFSET, Long.MAX_VALUE);
newPage.writeLong(DATA_MAX_TS_OFFSET, Long.MIN_VALUE);
headerPage.writeInt(HEADER_DATA_PAGE_COUNT, newPageNum);
return newPage;
So when a new page is needed:
It reuses a physical page at newPageNum if it exists (otherwise creates one)
It INITIALIZES the page with sampleCount=0
So if page 1 was full (238) and we need a new page, we read the HEADER, see dataPageCount=1, last page full, so we allocate page 2 (newPageNum=2). The HEADER is updated to dataPageCount=2.
But wait — the page version for the HEADER must also be checked! And there might be a race here.
This suggests page 1 was reused. But newPageNum = dataPageCount + 1, and if dataPageCount was 1 before, newPageNum=2. So we'd expect page 2 to be the new page.
Unless... there's a stale HEADER read. If thread B reads HEADER dataPageCount=0 (stale!), then:
It creates new page at newPageNum=1
Initializes page 1 with sampleCount=0
Writes HEADER_DATA_PAGE_COUNT=1
But thread A is concurrently at sampleCount=238 on page 1. Thread A's commit will overwrite page 1 with sampleCount=239. Then thread B's increment to 1 happens AFTER thread A's commit. But both write to the SAME page 1!
Wait, the issue says:
a following serialized append reads a stalesampleCountInPage
So yes — thread B reads a stale page 1 with sampleCount=0. Then it writes row at slot 0 and increments to 1. Then it commits, page version goes to 240, and page 1 has thread B's row at slot 0 and the count=1.
Wait, but this doesn't match either. Let me look at the actual sequence again:
code
sampleCount=238 pageVersion=238 threadId=112 <-- last write to page 1
sampleCount=0 pageVersion=239 threadId=114 <-- !!! thread 114 reads page 1 with sampleCount=0???
sampleCount=1 pageVersion=240 threadId=118
This means thread 114 read sampleCount=0 from a page at version 239. But page 1 should have had sampleCount=238 at version 238. So thread 114 read a different page version.
Actually, the explanation is that page 1 was COMPLETELY reset and reinitialized! Let me think about when this happens:
The page was at version 238, sampleCount=238
Then a new write comes in, reads HEADER_DATA_PAGE_COUNT=1, sees page 1 has 238 samples (full)
So allocates page 2 (newPageNum=2)...
No wait, the pageNum is still 1 in the next entry. So thread 114 is reading page 1, not page 2.
Let me check the exact reading of HEADER_DATA_PAGE_COUNT. In getOrCreateActiveDataPage:
java
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);
If the HEADER page has version V and dataPageCount says 1, thread 114 sees 1, so allocates page 2 (newPageNum=2).
But wait, what if the HEADER has been modified to dataPageCount=2 already? Then thread 114 sees 2, reads page 2 with sampleCount=0 (empty). Writes at slot 0, increments to 1. So we'd expect page 2, not page 1, in the diag.
So how is page 1 being reused? Let me look at when HEADER_DATA_PAGE_COUNT=0. That happens initially (page 0 created) or after clearDataPages (compaction).
OH WAIT — I see now! Look at the sequence at page 1:
Sample count 0 to 238, version 0 to 238 → page 1 is filled
Now the dataPageCount in HEADER should be 1 (one data page).
When the page is FULL, the next call to getOrCreateActiveDataPage should:
See dataPageCount=1
Check last page (page 1), see sampleCount=238 = maxSamples, full
Create page 2 (newPageNum=2), set dataPageCount=2
But instead, we see another entry for PAGE 1 with sampleCount=0, version=239. So the next entry is for page 1, not page 2.
Hmm, that's strange. Unless pageCount.incrementAndGet() and headerPage.writeInt(HEADER_DATA_PAGE_COUNT, newPageNum) happen but the page number is incorrectly 1.
Actually wait — let me check what getTotalPages() returns. Maybe there's a confusion between getTotalPages() and dataPageCount:
This means thread 130 saw dataPageCount = 0 from the header! Let me check:
But there should only be ~1000 increments (one per new page allocated). Why is headerVersion 43883? Let me check:
Looking at the count of "dataPageCount=1" entries: 478. So there were 478 increments of dataPageCount (from 1 to 2, 2 to 3, etc.). Plus some increments from 0 to 1, etc.
So the headerVersion should be at most ~479 or so. But it's 43883! That means the header is being written MUCH more than just at page allocation.
Wait, but each appendSamples call writes to the header (in updateHeaderStats). Each thread's call writes to the header. So if 240000 samples were written, the header should have 240000 versions!
But wait, updateHeaderStats uses tx.getPageToModify(new PageId(database, fileId, 0), pageSize, false). This would put page 0 in the TX's modifiedPages. So when the nested TX commits, page 0 gets written too. So version increments.
But that means page 0 is written on EVERY append. So headerVersion would grow by N (number of appends).
Actually wait — within a single nested TX, multiple getPageToModify calls for page 0 should return the SAME MutablePage (the first one is cached in modifiedPages). So only ONE version increment per nested TX.
But each append is a SEPARATE nested TX (1 call = 1 outer database.transaction() = 1 nested TX). So each append writes to page 0 once. So headerVersion ≈ 240000. That matches 43883? No wait, 43883 is less than 240000, but it's much more than the 1000 expected.
Hmm wait, the database.transaction(...) test does 1 SQL INSERT per transaction. So 48 threads × 5000 inserts = 240000 transactions. Each transaction does 1 append. So headerVersion should be ~240000.
Let me check the actual count of dataPageCount=1 entries:
Let me add another diag to find who is doing the reset:
So at headerVersion=43881, dataPageCount=184, page 184 has 142 samples. Then the next observation is headerVersion=43883, dataPageCount=0!
So between observations 2 and 3, a clearDataPages was called by SOMEONE. But compactionLock should prevent this from happening while appendSamples is running...
Oh wait, compactionLock.writeLock() allows ONLY ONE writer. And appendSamples uses readLock which allows multiple readers BUT not while a writer holds. So they're mutually exclusive.
But the diag shows them BOTH running. Let me check: is compactInternal holding the writeLock when clearDataPages is called?
Maintenance's clearDataPages commits
Now appendSamples runs, but it sees dataPageCount=0
So getOrCreateActiveDataPage thinks no pages exist, creates page 1 from scratch
Sample loss: page 1 is reused, but the OLD data in page 1 (sampleCount was 0 to 238) is overwritten!
But the compactionLock.readLock/writeLock is supposed to prevent this!
These should be mutually exclusive. The writeLock waits for all readLocks to be released.
OH WAIT. I see the issue now. Look at appendSamples:
It acquires compactionLock.readLock() → blocks because compaction holds writeLock
WAIT FOR COMPACTION TO FINISH
Then it can proceed
But if compactInternal is RUNNING and has the writeLock, appendSamples is BLOCKED on the readLock. So they CAN'T run concurrently.
But the diag shows appendSamples printing DIAG messages while compactInternal is running. So something is wrong with the lock acquisition.
Let me look more carefully. The diag:
code
DIAG-CLEARDATA: fileId=1 threadId=95 ... (compactInternal, in Phase 4c, holding writeLock)
DIAG-GOCADP: fileId=1 headerVersion=41547 dataPageCount=0 getTotalPages=175 threadId=96 (appendSamples, has readLock)
So thread 95 (compact) is holding writeLock, and thread 96 (append) is reading the header. But appendSamples should be blocked on readLock acquisition!
Wait, I see — but actually the lock is REENTRANT. Let me check:
Actually wait — looking at the diag more carefully:
Thread 107 and 104 are TRYING-READLOCK but never GOT-READLOCK (so they're blocked)
Thread 95 (compact) does CLEARDATA — the writeLock is held
Thread 114 GOT-READLOCK — this means compact's writeLock was released
Thread 114 reads dataPageCount=0 (the result of clearDataPages)
So the lock works as expected. The issue is: after clearDataPages, the page 1 is reset but its data is preserved (because we only reset the header). Then the next append writes to page 1 with sampleCount=0, overwriting existing data!
This is the root cause! clearDataPages resets the header but the data in the pages is still there. When getOrCreateActiveDataPage sees dataPageCount=0, it allocates page 1 (the same physical page), initializes it with sampleCount=0, and then writes new data at slot 0, overwriting the previous sample at slot 0!
The page 1 is being "logically" cleared, but physically, the old data is still there. When the new data is written, it overwrites.
Now, why is compaction happening in the test? The test only does 240000 inserts. Let me check the default compaction trigger:
So in the original test, samples are lost WITHOUT compaction. So the issue is NOT compaction. There must be another mechanism causing the loss.
Let me remove the diag and re-run the test to see if the loss happens in a different way:
So maintenance is always scheduled when a time series type is created. So compaction WILL run after 5s.
OK so the bug we're seeing is partly due to compaction interfering. But the issue description also says samples are lost WITHOUT compaction. Let me think...
Actually, the issue mentions:
a full table scan returns the same short count as count(*), and a GROUP BY sensor_id shows specific series missing rows.
So the issue is slot reuse due to stale read of the slot count. But my diagnostic shows the slot count is read correctly...
Wait. Let me re-read the issue:
The page version advances normally, and PageManager.updatePageVersion's version check does not raise a conflict for these commits, so the existing outer-transaction retries never kick in.
So the issue is that the page version is incrementing but the SLOT COUNT is stale. This could happen if the page version advances but the data is reset to a previous state.
Let me re-examine. After compact:
Phase 4a: snapshot the data (the data is on disk, marked with version V)
Phase 4b: process the snapshot (no lock)
Phase 4c: take writeLock, read new tail data, append to sealed store, clearDataPages, commit
clearDataPages resets header to dataPageCount=0
Phase 4c commit increments header version to V+1
Now after Phase 4c commits, the header has dataPageCount=0 and version V+1.
When the next appendSamples comes:
Acquires readLock
Reads header, sees dataPageCount=0, version V+1
Creates page 1 (the existing physical page 1) with sampleCount=0
Writes sample at slot 0 — OVERWRITES the existing sample at slot 0
So compaction "clears" the data, but only at the header level. The actual data in page 1 (and all other pages) is still there, but logically invisible. When new data is appended, the new data overwrites the old.
This is the data loss pattern! Each compaction loses approximately one page worth of data (239 samples per page), because the first write to each page after compaction overwrites an existing sample.
Wait, but the test should reproduce without compaction. Let me check what happens with the FIRST compact:
BEFORE compact: headerVersion=41545, dataPageCount=174 (174 pages with samples)
Compact's Phase 4a reads pages 1-174
Compact's Phase 4b processes (no lock)
Compact's Phase 4c:
Phase 4c reads tail pages (last pages from Phase 4a to current)
Phase 4c appends to sealed store
Phase 4c calls clearDataPages which resets header to dataPageCount=0
Phase 4c commits
AFTER compact: headerVersion=41546 (or 41547), dataPageCount=0
Now appendSamples resumes. It reads header, sees dataPageCount=0, creates page 1. Writes sample 0 at slot 0, overwriting the OLD sample 0 that was on page 1.
So the loss is: for each page that was used BEFORE compact, the first sample written AFTER compact overwrites an existing sample. With 174 pages, we'd lose 174 samples. But the test reports higher losses.
Wait, with each compact, we lose dataPageCount samples (one per page). If compact happens multiple times... but maintenance runs once per 60s, so once per test run.
Hmm. Let me look at the test output again - 89 samples lost according to the issue. That's a different number than 174. So maybe the test doesn't trigger maintenance, and the 89-sample loss is from a different mechanism.
Let me look at the test runtime. With 48 threads × 5000 inserts, the test runs many transactions. The test takes about 40s based on the original 24k test that took 3.3s. So 48 threads × 5000 = 240000 inserts, would take ~40s. Maintenance runs at T=5s. So maintenance runs once.
If maintenance runs and clears 174 pages, the loss is 174. The issue reports 89. So there might be another mechanism.
Actually let me re-read the issue:
Result: e.g. 239911 / 240000 — 89 samples lost, with no exception and no failed transaction.
"e.g." suggests this is an example. So losses vary. The issue's description matches what I'm seeing, but the actual mechanism might be the compact.
OK so let me think about this. The actual bug, as described in the issue:
the time series engine silently drops samples. The client receives success on every insert (HTTP 200, no exception, no ConcurrentModificationException), yet the stored row count comes up short.
TimeSeriesShard.appendSamples serializes appends per shard with a appendLock around a nested db.begin()/append/db.commit() on getWrappedDatabaseInstance()
A temporary collision detector added to appendSamples (recording fileId:pageNumber:slot per append) confirmed the mechanism: a following serialized append reads a stalesampleCountInPage — the prior append's count → N+1 increment is not visible — so two appends compute the samerowOffset and write the same slot N; the later commit overwrites the earlier row.
OK so the issue says the slot count is stale. The issue's mechanism is different from what I observed (compaction wiping).
But I think the actual underlying cause is the SAME: a page is being "reset" (sample count goes back to 0) while other threads are still using it.
Now the question is: is the issue description accurate about the cause being stale slot count, or is the cause actually compaction?
Looking at my diagnostic output:
WITHOUT compaction (the case where dataPageCount=0 doesn't happen), the slot count progresses monotonically and there are no collisions
WITH compaction, the dataPageCount gets reset to 0, and the next append reuses page 1, overwriting the existing data
So my analysis shows the issue is compaction, not a stale read. But the issue description says the issue is a stale read.
Wait, let me re-read the issue more carefully:
slot reused across threads; page version high and advancing while the slot/count read is stale.
The issue says page version is high but slot count is stale. That's the opposite of what compaction does (compaction resets the slot count to 0, not stale).
Actually let me re-look at my earlier output. The first diag I added (before I added the GOCADP one) showed:
So between page 1 finishing (sampleCount=238) and page 2 starting (sampleCount=0), the pageVersion went up by 1. That's the version increment from the page 1 being marked as having dataPageCount=2 (writing to header).
Actually wait, looking at my SECOND diag output:
sampleCount=238 pageVersion=238 threadId=112
sampleCount=0 pageVersion=239 threadId=130 (back to page 1, count=0)
So between these two events, the page went from sampleCount=238 to sampleCount=0, AND the pageVersion went from 238 to 239. The pageNum stayed 1.
How can page 1 have sampleCount=0 but pageVersion=239? Only if the page was reset (the page data was overwritten with sampleCount=0). This happens in getOrCreateActiveDataPage when allocating a new page. But newPageNum = dataPageCount + 1, so if dataPageCount was 1, newPageNum=2, not 1.
UNLESS dataPageCount was 0 when the allocation happened! That would make newPageNum=1, which is what we see.
So the chain of events:
dataPageCount=1, page 1 has sampleCount=238
Some thread does clearDataPages (sets dataPageCount=0)
Another thread does getOrCreateActiveDataPage, sees dataPageCount=0, allocates page 1 with sampleCount=0
Page 1 is overwritten with new data
So this IS the compaction issue.
But here's the thing: the compactionLock is supposed to prevent this. Let me look at this more carefully. The appendSamples takes readLock. The compact takes writeLock (via compactInternal).
Wait, but appendSamples uses the compactionLock to prevent concurrent compaction. The compact path takes the writeLock for the entire compactInternal call (including all phases). But Phase 4b is lock-free, and at the start of Phase 4c, the writeLock is taken again.
So during Phase 4b, appends can run. Then Phase 4c takes the writeLock, which blocks new appends. But appends already in-flight (with readLock) can complete.
Hmm, but the diag showed that the lock was held during clearData (no appends running with GOT-READLOCK at that time). So the issue isn't concurrent execution of clearData and appendSamples.
OK let me think about this again. The issue is:
Compact runs (acquires writeLock, holds it)
compactInternal's Phase 4c calls clearDataPages (header is reset)
compactInternal commits, releases writeLock
AppendSamples acquires readLock
AppendSamples reads header, sees dataPageCount=0
AppendSamples allocates page 1 (the existing physical page 1), initializes with sampleCount=0
AppendSamples writes new sample at slot 0, OVERWRITING the old sample 0
The lock IS preventing concurrent execution. But after compact completes, the appenders correctly see the reset state and start overwriting.
The bug is that clearDataPages only resets the header but the actual page data is still on disk. When new samples are appended, they overwrite the old data.
Let me confirm by looking at getOrCreateActiveDataPage:
java
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;
}
// Need a new (or reused) data page
final int newPageNum = dataPageCount + 1;
final MutablePage newPage;
if (newPageNum < getTotalPages()) {
// Physical page already exists — reuse it (typical after compaction clears the header)
newPage = tx.getPageToModify(new PageId(database, fileId, newPageNum), pageSize, false);
} else {
// Physical page does not yet exist — allocate it
newPage = tx.addPage(new PageId(database, fileId, newPageNum), pageSize);
pageCount.incrementAndGet();
}
// Initialise the page (old data bytes beyond sample-count are ignored by readers)
newPage.writeShort(DATA_SAMPLE_COUNT_OFFSET, (short) 0);
newPage.writeLong(DATA_MIN_TS_OFFSET, Long.MAX_VALUE);
newPage.writeLong(DATA_MAX_TS_OFFSET, Long.MIN_VALUE);
headerPage.writeInt(HEADER_DATA_PAGE_COUNT, newPageNum);
return newPage;
So when dataPageCount=0 and a new page is allocated:
tx.getPageToModify(page 1, ...) loads the existing page 1 from disk
The page has OLD data (sampleCount=238, etc.)
We then writeShort(DATA_SAMPLE_COUNT_OFFSET, 0) to "initialize" it, but the ROW data is still there!
New writes overwrite the rows at slot 0, 1, 2, ...
So yes, the page is initialized with sampleCount=0 but the row data is preserved, so new writes overwrite old data.
This is the BUG. And this is happening for every page (1 through 175) in the next 175 appends.
Actually wait, but the test only loses 89 samples (or similar). If compaction wipes 175 pages, why are only 89 samples lost?
Hmm, maybe because compaction only "moves" the data to the sealed store, and the sealed store has its own data. So the "lost" samples are still in the sealed store! Let me check the test:
java
final ResultSet rs = database.query("sql", "SELECT count(*) AS cnt FROM Reading");
This queries the mutable bucket only? Or both?
Let me check:
So iterateQuery iterates BOTH sealed and mutable. So the count(*) should include both. And sealed store data is not lost — it's written before the clear.
So in the test, the data IS preserved in the sealed store. The 89-sample loss must be from a different mechanism.
Let me think more carefully. With my test (the smaller version, before compaction):
In the 48 threads case, compaction runs at T=5s, wiping 175 pages × 239 samples = 41825 samples. The 41825 samples are moved to sealed store. Then 41825 new slots are filled in the mutable bucket. But wait, with 240000 inserts and 41825 moved to sealed, we'd have 240000-41825=198175 in the mutable bucket. But each compact-affected slot's new write OVERWRITES an old one. So those 41825 are lost (overwritten by new data).
But the data is in the sealed store! So the total should be 240000 (sealed + mutable) - 41825 (overwritten) + 41825 (sealed) = 240000. So no loss.
Unless the new write doesn't overwrite, but actually the OLD slot is preserved because the page is REUSED but the slot is at a different offset.
Hmm wait. Let me re-think. After compact:
dataPageCount=0
Page 1's data is still on disk: 239 samples (at slots 0-238)
Next appender:
Sees dataPageCount=0
Allocates page 1, initializes sampleCount=0
BUT the row data at slots 0-238 is STILL there
The appender writes a new sample at slot 0, incrementing sampleCount=0→1
The old data at slot 0 is GONE (overwritten)
So we lose ONE sample per page per reset. With 175 pages reset, we lose 175 samples.
The data is in sealed store. So count = (sealed samples) + (mutable samples). The sealed has the OLD data (175 * 239 = 41825 samples). The mutable has the new data, but slot 0 of each page is overwritten, so 175 samples are missing from the mutable.
So total = 41825 (sealed) + (175 - 175) (mutable slots) + ... wait, this doesn't work out. Let me think again.
OK let me think more carefully. We have 240000 total inserts. The first 41825 (175 pages × 239 samples/page) all land in pages 1-175 of the mutable bucket. Then compact happens. Compact's Phase 4b writes all this data to the sealed store. Compact's Phase 4c clears the header (dataPageCount=0), but the data is still on disk.
After compact, we have:
Sealed store: 41825 samples (correct)
Mutable bucket: pages 1-175 each have 239 samples (in the on-disk data), but header says dataPageCount=0
Now new appends come in. The first 175 new appends each allocate a page (page 1, page 2, ..., page 175), initialize sampleCount=0, and write at slot 0. The OLD data at slot 0 is overwritten, but the OLD data at slots 1-238 is still there (just not counted in sampleCount).
So we have:
Sealed: 41825
Mutable, slot 0 of pages 1-175: NEW data (175 samples, correctly written)
Mutable, slots 1-238 of pages 1-175: OLD data (41825 - 175 = 41650 samples, but not counted in sampleCount!)
But the sampleCount on the pages is 1, not 239. So only 175 samples in the mutable are COUNTED.
Total counted = 41825 + 175 = 42000. But we had 240000 inserts!
Hmm, that doesn't match. Let me check the test result:
240000 - 239868 = 132 lost
42000 vs 240000 = 198000 lost
So the loss should be ~198000 if compact is the cause. But the test reports only 132 lost. So the loss is NOT from compact!
Let me re-examine. The test reports ~132-159 lost. This must be from a different mechanism — the "stale slot count" mechanism described in the issue. And compact wiping the data just adds more loss on top.
Wait, but my diagnostic shows the slot count is NOT stale — it goes monotonically. So maybe the test scenario is different.
Let me try running the test WITHOUT maintenance running. Let me set a long delay:
Actually, let me re-think the issue. The issue is "silent sample loss". The diag I added showed:
BEFORE compact: pages 1-175 each have ~239 samples (slot count is monotonically increasing, no duplicates)
Compact happens
AFTER compact: pages 1-175 each get a sample at slot 0, overwriting the old slot 0
So we lose 175 samples (one per page, the slot 0 of each). The data is in the sealed store. But the count(*) might not be counting the sealed store...
Wait, let me check. The test does SELECT count(*) FROM Reading. Let me see how this is executed for time series:
total += shard.getSealedStore().getTotalSampleCount();
total += shard.getMutableBucket().getSampleCount();
If getSampleCount returns the total header count, and the header is correctly maintained (incremented for each sample), then this should be correct.
But wait, after compact, clearDataPages resets:
HEADER_SAMPLE_COUNT_OFFSET = 0
HEADER_DATA_PAGE_COUNT = 0
So after compact, getSampleCount() returns 0 (header says 0 samples).
Then new appends come in. They write to the page. updateHeaderStats increments the count. So after 1 append, count is 1. After 175 appends, count is 175 (one per page, since the new appends fill slot 0 of each page).
But wait, after compact, the next appends go to pages 1, 2, 3, ..., 175, 176, ... (because dataPageCount starts at 0 and increases). So after 240000 - 41825 = 198175 new appends:
dataPageCount = ?
Each page can hold 239 samples, so 198175 / 239 = 829 new pages... but the new appends REUSE the existing pages 1-175, then go to new pages 176, 177, ...
Total dataPageCount = 175 (reused) + 829 (new) = 1004 pages? But getTotalPages was 175 before, so we'd need to allocate 829 new pages.
Actually wait, when we reuse page 1 (after compact), we use tx.getPageToModify(page 1). This loads page 1 from disk. We initialize it with sampleCount=0. We write the new sample at slot 0. We increment sampleCount to 1.
So after the 175 appends, pages 1-175 each have 1 sample. After 240000 - 41825 = 198175 appends, the pages are:
Pages 1-175: 239 samples each (filled completely)
Pages 176-1004: ~150 samples each (some pages)
Total samples in mutable: 175 * 239 + 829 * 150 ≈ 41825 + 124350 = 166175
Plus sealed: 41825. Total: 208000. But the test expects 240000. So 32000 lost.
Hmm that doesn't match 132-159 lost either.
Actually, I think the issue is more subtle. After compact, the data is in sealed store, BUT the data is moved there via the sealed store's compression. The original data had different timestamps/values. The sealed store has all of them. The mutable has new data. The total should be 240000.
Let me actually check: in the test, what's the actual loss number? Let me re-run the test and verify:
The first compact at T=5s processes all 250 pages (5s × 12000 inserts/sec / 239 = 250 pages). Then the test continues. Pages 1-250 are reset. New appends reuse them.
Each reused page (1-250) loses 1 sample (slot 0 overwritten). So loss = 250.
But we observe 120-130. Hmm, off by ~2x. Maybe the data IS in the sealed store, and the count is correct for sealed but not for mutable... let me check.
Actually wait, I might have miscounted. Let me look at the data flow more carefully:
Append 1-60000 (T=0-5s): fill pages 1-251
Compact at T=5s: process pages 1-251, move to sealed, clear header (dataPageCount=0)
Append 60001-60002 (T=5-5.001s): allocate page 1 (sampleCount=0), write sample 0. OLD sample 0 of page 1 is overwritten.
...
Append 60251-60252 (T=5.xx): allocate page 251, write sample 0. OLD sample 0 of page 251 is overwritten.
Append 60252-240000: continue filling
So the OLD data in pages 1-251 (slot 0) is overwritten by NEW data. But the OLD data is in the sealed store. So:
Sealed: 60000 (the original data)
Mutable slot 0 of pages 1-251: NEW data
Mutable slots 1-238 of pages 1-251: OLD data (overwritten at slot 0, but slots 1-238 are still old)
Wait! The OLD data is at slots 1-238 still. The sample count is correctly tracking the new data. So when we count samples in the mutable bucket, we only count the NEW samples (which is the new data + the 251 slot-0 samples).
But the OLD data is at slots 1-238. Those rows are NOT counted (sample count is 1-238, only the first 1 is "valid"). So we lose access to the OLD data in the mutable bucket.
But the OLD data is in the sealed store. So count = sealed (60000) + mutable (180000) = 240000.
So we should have NO loss. But we have 120-130 loss. So something else is wrong.
Let me actually instrument the count to see what sealed vs mutable count is:
But we observed 194806 in mutable, which is 180000 + 14806. So there's some overflow.
Hmm, let me think about the SLOT 0 overwrite. When slot 0 is overwritten, the OLD data is lost. But the OLD data is in the sealed store. So we shouldn't lose anything.
Unless... wait, what if multiple appends overwrite each other? If two appends both write to slot 0, one would be lost. But my diag showed sample counts are monotonic. So this shouldn't happen.
Let me look at this from a different angle. Let me run the test and check the mutable bucket's getDataPageCount before and after:
scanCount=47920, unique=47920. So no duplicates. count=47900. So scan is 20 MORE than count. The data is in the pages, but count says 47900 (not 47920).
Hmm, 20 less. That matches roughly the loss.
Actually wait, count=47900 and scan=47920. So count UNDER-counts by 20.
getSampleCount in mutable reads from the header. If the header is correct, count is correct. If the header is wrong, count is wrong.
But updateHeaderStats increments the count on every append. So if 240000 appends are done, the count should be 240000 (before compact) and 240000 - compact-moved (after compact).
But the test result shows:
sealedCount = 43774 (sealed has 43774 samples)
mutableCount = 4126 (mutable has 4126 samples)
Total via API = 47900
So 48000 inserts, 47900 in API count. So 100 missing in the API count.
But the SCAN reads 47920. So 20 more in the actual data.
So:
API count: 47900
Scan: 47920
Lost: 100 - 20 = 80 (or 100 - 0 = 100, depending on how we count)
The actual data loss is 80 samples (in the API count, 100 are missing, but 20 are still in the scan, meaning they exist in the pages but not counted).
So the API count is undercounting by 20. Why?
Let me check: maybe the header is being reset to 0 incorrectly during compact, and the count for the new appends is 4126 (not the actual number of appends after compact).
Actually, the test has:
48000 total inserts
Compact moves 43774 to sealed
4126 in mutable
43774 + 4126 = 47900 (count(*))
48000 - 47900 = 100 not accounted for
If 43774 went to sealed (the data that was there before compact), and 4126 in mutable (new data after compact), then 100 inserts are not in either. They must have been... lost? Or duplicated?
Wait, let me look at the sample count more carefully. The compact processes pages 1 to N (where N is the dataPageCount at the time of compact). Each page has up to 239 samples. So:
compact processes 43774 samples (from 183.16 pages, so ~184 pages × 239 samples = 43976, but only 43774?)
Hmm, 43774 / 239 = 183.16. That's not a whole number. So the compact didn't process complete pages.
Let me think. Maybe the compact was at T=5s when the dataPageCount was, say, 184 and the last page had some samples. So compact moved 183 * 239 + 137 = 43660 + 137 = 43797. Close to 43774.
Or maybe compact moved 43774 samples. Then 48000 - 43774 = 4226 new inserts after compact. But we see 4126 in mutable. So 100 are missing.
Where are those 100? Maybe they're in the sealed store with duplicates, and the count has the right total but the data is duplicated.
Let me check the actual scan vs unique count:
scan=47920, unique=47920. So no duplicates in the scan. The total is correct in the scan.
So count=47900, scan=47920. Difference of 20.
20 samples exist in the scan but not in the count. The count is from the header (HEADER_SAMPLE_COUNT_OFFSET).
After compact, the header is reset. Then 4226 new appends happen, but only 4126 are counted. So 100 are missing from the header.
Where did 100 appends go? They're not in the count. But they're not in the scan either (the scan shows 47920, but the count says 47900, and the actual data is 47920 in the scan).
Wait, let me re-check. 48000 - 47900 = 100 not in count. 48000 - 47920 = 80 not in scan. So 20 are in the scan but not in the count.
Hmm, this is confusing. Let me think about it more carefully.
Actually, the issue is the count of HEADER_SAMPLE_COUNT_OFFSET. After compact, the count is reset to 0. New appends increment it. So the count should reflect the NEW appends only.
So if 4226 new appends after compact, count = 4226. But we see 4126. So 100 appends are missing from the count.
But they're in the SCAN! The scan reads from the pages, and the sample count per page is 1 (for pages 1-184 after compact). So scan reads 184 rows for these pages. Plus the 4126 = 4310 from other pages. Total 4310 + 184 = 4494. Hmm that doesn't match 47920.
Let me reconsider. After compact, dataPageCount=0. New appends come in:
Actually let me just compute: 4226 / 239 = 17.68. So 17 full pages + 1 partial page (with 4226 - 17*239 = 4226 - 4063 = 163 samples).
Total dataPageCount after compact = 18 (1 partial page 1, 17 full pages 2-18, 1 partial page 19). Wait, 17 full pages would be 18 total pages.
Let me re-think:
Page 1: starts empty, fills to 239 (239 appends)
Page 2: starts empty, fills to 239 (239 appends)
...
Page 17: starts empty, fills to 239 (239 appends)
Page 18: starts empty, fills to 143 (143 appends, the remainder)
So 18 pages. But the diag showed dataPageCount=18, which matches.
So 18 pages in mutable. Each page has 1-239 samples. The TOTAL samples in mutable = 18 * (avg) but we computed 4226 total (the number of appends post-compact).
Wait, 4126 in mutable according to the API count. So 4226 - 4126 = 100 missing. 100 samples that should be in the mutable are not counted.
Now the SCAN reads based on sampleCount per page. So it should also miss the 100. But scan=47920 > count=47900. So scan has 20 MORE than count.
Hmm, let me check this differently. Let me look at the OLD data in the pages.
After compact, the OLD data is in slots 1-238 of each page (slot 0 was overwritten). The sampleCount=1 (just slot 0). So scan reads slot 0 only.
But wait — after the first append post-compact, the page has sampleCount=1, slot 0 is NEW data. Slots 1-238 are OLD data (not counted).
Then more appends come. Append 2: sampleCount=1 (still, since we read it as 1), write at slot 1, increment to 2. But slot 1 has OLD data, and we're writing NEW data over it. So we lose the OLD data at slot 1.
So for each reused page, we lose sampleCount OLD samples (1, 2, 3, ..., up to 238 for the last append before the page fills).
But these OLD samples are in the sealed store! So no loss.
Wait, no. The compact moved the OLD data to the sealed store. So the OLD data is duplicated. After compact:
Sealed: 43774 (the OLD data)
Mutable slot 0 of page 1: NEW
Mutable slots 1-238 of page 1: OLD (duplicated in sealed)
Now new appends fill page 1:
Append 1: write at slot 0, increment to 1 (NEW at slot 0)
Append 2: write at slot 1, increment to 2 (NEW at slot 1, OLD at slot 1 is overwritten)
...
Append 239: write at slot 238, increment to 239 (NEW at slot 238, OLD at slot 238 is overwritten)
So when page 1 is full (sampleCount=239), all 239 slots have NEW data, and the OLD data is fully overwritten.
But the count in the header is incremented correctly (1 per append).
Now consider the total:
Sealed: 43774
Mutable (after 4226 new appends): 4226 NEW samples
Total: 43774 + 4226 = 48000 ✓
So no loss if everything is correct.
But we observed 47900 in count, 47920 in scan. So 100 missing in count, 80 missing in scan.
The 100 missing in count means 100 appends are not reflected in the count. But the scan reads based on per-page sampleCount, which is incremented per append. So scan should match count.
Unless the count is decremented somewhere... like during compact!
Oh! Let me check what compact does to the count. After compact, the header is reset:
HEADER_SAMPLE_COUNT_OFFSET = 0
HEADER_DATA_PAGE_COUNT = 0
So the count is 0 after compact. Then 4226 new appends happen, count becomes 4226. But the count is 4126. So 100 appends are missing.
Maybe the count is being read from a stale header? Let me check:
OH WAIT! I think I see it now. The getOrCreateActiveDataPage is called ONCE per sample. And each call reads dataPageCount. If the page is full, it allocates a new page. So 239 calls for dataPageCount=1 means 239 samples in page 1 (the max). Then 239 calls for dataPageCount=2 means 239 samples in page 2. So 478 calls for dataPageCount=1 is impossible.
Unless... 239 is the MAX, and after that the page is full. So 239 calls for dataPageCount=1 means 239 samples in page 1 (the last sample sees dataPageCount=1, writes the 239th slot, increments to 239, then the next call sees dataPageCount=1 still, but sampleCount=239=full, so allocates page 2).
So 239 calls for dataPageCount=1 = 239 samples in page 1.
But we have 478 calls for dataPageCount=1! That means 478 samples were "associated" with dataPageCount=1. But each page only holds 239.
Unless some calls were DOUBLED — the same sample caused two calls. Or the count is for the AFTER state (dataPageCount=1 after the call, but the call may have been for sample N or N+1).
Actually let me re-read the diag:
java
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);
System.err.println("DIAG-GOCADP: headerVersion=" + headerPage.getVersion() + " dataPageCount=" + dataPageCount + ...);
So dataPageCount is the value BEFORE any modification. The appends increment it. So:
239 calls see dataPageCount=1, write to page 1, fill it. After the last write, dataPageCount=1, sampleCount=239.
1 call sees dataPageCount=1, but sampleCount=239=full, so allocates page 2. dataPageCount becomes 2.
238 calls see dataPageCount=2, write to page 2.
1 call sees dataPageCount=2, sampleCount=239=full, allocates page 3.
So 240 calls see dataPageCount=1, 240 calls see dataPageCount=2, ..., 240 calls see dataPageCount=N.
But we have 478 for dataPageCount=1. Hmm. Unless after compact, dataPageCount goes back to 1 (since pages are reused). Let me check:
The dataPageCount went up to 174 pre-compact (174 pages filled). So 174 pages × 239 = 41586 samples pre-compact. Wait but the count is 478 for 1-19, so 19*478 = 9082 calls (samples) for pages 1-19. That's odd because each page should only hold 239 samples.
OH I see. The 478 for dataPageCount=1 means 478 calls where dataPageCount=1 was observed. But the page 1 can only hold 239. So the rest of the calls (478 - 239 = 239) must be the post-compact calls.
OK so the total samples = 48000. Pre-compact: 41586 (174 pages × 239). Post-compact: 48000 - 41586 = 6414 samples. Each post-compact page has 239, so 6414 / 239 = 26.8 pages. But the test only shows 8 pages in mutable.
Wait, the diag shows dataPageCount went up to 174. So pre-compact: 174 pages. 174 * 239 = 41586.
But the diag shows dataPageCount=1-19 have 478 calls each. That means before compact, pages 1-19 had 239 calls each (filling them). After compact (dataPageCount=0), the next 19 pages also had 239 calls each (refilling). Wait no, after compact, dataPageCount goes back to 0, then increases.
Let me think again. The 478 for dataPageCount=1:
Before compact: dataPageCount goes 0, 1, 2, 3, ... 174. So for each value 1-174, we have 239 calls.
At some point, compact runs. It reads dataPageCount (say, 174) and processes all pages.
Compact's clearDataPages sets dataPageCount=0.
Post-compact: dataPageCount goes 0, 1, 2, ... N. So for each value 1-N, we have 239 calls.
So the pre-compact reached dataPageCount=174. The post-compact reached dataPageCount=19.
Pre-compact samples: 174 * 239 = 41586. But the last page might be partial, so let's say 41586 - 45 = 41541 (if the last page had 194 samples, 239-194=45). Actually 174239=41586, with 194 in the last page = 174239 - 45 = 41541. Hmm.
Wait the diag says dataPageCount=174 has 194 calls. So the last pre-compact page had 194 samples (out of 239). So pre-compact samples = 173 * 239 + 194 = 41347 + 194 = 41541.
Post-compact samples: 19 * 239 - 45 (if last page is partial) = 4541 - X. But the dataPageCount=19 is the last post-compact dataPageCount. Let me check the post-compact page count:
Oh wait! Now I see dataPageCount=28. Earlier I thought it was 8, but it was actually 28. Let me re-check:
mutableCount=6458. dataPageCount=28. So 28 pages in mutable. 6458 / 28 = 230.6 avg samples per page. So 28 pages with ~230 each. That's reasonable.
sealedCount=41436. So 41436 in sealed.
Total = 41436 + 6458 = 47894. count(*) = 47894. scan = 47894. So count and scan match.
48000 - 47894 = 106 missing. So 106 samples are LOST (not in count, not in scan).
So where are these 106 samples? They're in the slot 0 of each reused page that was overwritten by the new data, but the new data didn't make it to the count.
Wait, let me think:
Pre-compact: 27 pages, with each page having 239 samples (last page partial). Total = 27 * 239 = 6453 (if last is full). But last has 243 calls = 239 (pre) + 4 (post)? Hmm let me re-check.
The diag is dataPageCount=28 has 243 calls. So:
239 calls saw dataPageCount=28 pre-compact (filled the 28th page)
4 calls saw dataPageCount=28 post-compact (the 28th page got 4 new samples)
Pre-compact pages: 1-28, with page 28 having 243 calls. But pre-compact dataPageCount went up to 28. So pre-compact has 28 pages × 239 = 6692 samples (with page 28 also having 243 - 239 = 4 extra calls? That can't be right).
Hmm wait. Let me re-think. The diag prints dataPageCount BEFORE the modification. So:
Call 1: dataPageCount=0, allocate page 1, increment to 1
Call 2: dataPageCount=1, write to page 1, increment sampleCount, but dataPageCount stays 1
...
Call 239: dataPageCount=1, write to page 1 (last slot), increment sampleCount to 239
Call 240: dataPageCount=1, page 1 is full, allocate page 2, increment dataPageCount to 2
Call 241: dataPageCount=2, write to page 2
...
So 240 calls see dataPageCount=1 (239 writes + 1 allocate page 2). 240 calls see dataPageCount=2 (239 writes + 1 allocate page 3). Etc.
For page N (with sampleCount=239), we have 240 calls seeing dataPageCount=N.
But the diag shows 478 for dataPageCount=1-27. That's 478/2 = 239 per phase. Hmm wait 478 = 2392 = 2402 - 2.
Let me re-examine. 478 calls for dataPageCount=1. That means 478 appends saw dataPageCount=1. Each such append either writes to page 1 (if it has room) or allocates page 2 (if page 1 is full). 239 appends fill page 1. The 240th append allocates page 2. So 240 calls see dataPageCount=1.
But we have 478 = 2*239. Hmm. Maybe the count is:
239 pre-compact (filling page 1)
239 post-compact (filling page 1 again)
So 478 calls see dataPageCount=1 (239 pre, 239 post). The "allocate page 2" call would see dataPageCount=1, then increment to 2. So we'd have 1 extra call seeing dataPageCount=1 (the allocation).
Wait that means 239 + 1 = 240 pre-compact. So 240 + 240 = 480. But we have 478. So 2 are missing.
Hmm, or maybe the count is for the BEFORE state, and the allocation also sees the BEFORE state. Let me trace:
2nd append: dataPageCount=1, write to page 1, dataPageCount stays 1
...
240th append: dataPageCount=1, page 1 is full (sampleCount=239), allocate page 2, dataPageCount becomes 2
So 240 calls see dataPageCount=1, and the FIRST one of them was when dataPageCount was actually 0 (no, the first one was when dataPageCount=0 and we allocated page 1, so we see dataPageCount=0 in the diag, not 1).
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;
}
// Need a new (or reused) data page
final int newPageNum = dataPageCount + 1;
...
headerPage.writeInt(HEADER_DATA_PAGE_COUNT, newPageNum);
return newPage;
So the diag is printed BEFORE the increment. The increment happens at the end. So:
1st call: dataPageCount=0, allocate page 1 (newPageNum=1), increment to 1
2nd call: dataPageCount=1, last page is page 1, has room, return page 1
...
240th call: dataPageCount=1, page 1 is full, allocate page 2, increment to 2
241st call: dataPageCount=2, last page is page 2, has room, return page 2
...
So 1 call sees dataPageCount=0. 240 calls see dataPageCount=1 (239 writes + 1 allocation). 240 calls see dataPageCount=2 (239 writes + 1 allocation). Etc.
Now post-compact: dataPageCount=0, then 1, 2, ..., 28.
1 call sees dataPageCount=0
240 calls see dataPageCount=1
...
For dataPageCount=28: the page is partially filled (4 samples). So 4 calls see dataPageCount=28.
If post-compact has 28 pages, with the last partial: 1 + 240*27 + 4 = 6485 calls. Hmm.
Total = 41760 + 6485 = 48245. But we have 48000 calls. So 245 fewer than expected.
OK my model is off. Let me just look at the data. The total GOCADP calls is 48000. The sealed has 41436, mutable has 6458, total 47894. So 48000 - 47894 = 106 are not in count.
Let me check: maybe the 106 are the slot 0 of pages 1-19 (which had 19*239 = 4541 samples, but the slot 0 was overwritten, and we have 478-239 = 239 extra entries for each of pages 1-19?).
Actually wait, the dataPageCount=1 to 19 have 478 entries. So 19478 = 9082. If each of these is a call, then we have 9082 calls. But each call corresponds to 1 sample. So 9082 samples for pages 1-19. That's WAY more than 23919 = 4541.
So the diag is misleading. Let me re-read my code:
Total = 41586 + 6485 = 48071. But we have 48000 calls. So 71 fewer than expected.
Wait, maybe I miscounted. Let me re-check the diag for pre-compact.
Actually wait, the diag doesn't differentiate pre vs post. The 478 for dataPageCount=1 is 239 pre + 239 post. So I was right. The pre-compact had 239 calls for dataPageCount=1, post-compact had 239 calls for dataPageCount=1.
So pre-compact total = 41586 (samples). Post-compact total = 48000 - 41586 = 6414.
If post-compact has 28 pages with the last partial, the last page has (6414 - 27*239) = 6414 - 6453 = -39 samples. That's negative, so my count is off.
Let me try: 28 pages with 239 each (full) = 6692. But we have 6414. So 28 pages but only 6414/239 = 26.83 pages. So 26 full + 1 partial. The last page has 6414 - 26*239 = 6414 - 6214 = 200 samples. But the diag says dataPageCount=28 has 4 calls (post-compact only).
Hmm, 4 calls for dataPageCount=28 is only 4 samples. So the 28th page has only 4 samples post-compact. But the total post-compact should be 6414. Let me check:
If 27 pages are filled (each 239) + 1 page with 4 = 27*239 + 4 = 6453 + 4 = 6457. Close to 6414 (43 off).
Hmm, I'm getting confused. Let me just trust the diag:
So pre-compact writes 41542 samples. Post-compact writes 6458 samples.
But the test result says:
sealedCount = 41436
mutableCount = 6458
So 41436 (sealed) + 6458 (mutable) = 47894.
Pre-compact writes 41542, but only 41436 are in sealed. So 106 pre-compact samples are MISSING.
These 106 pre-compact samples were written to the mutable bucket before compact. Compact was supposed to move them all to sealed. But 106 are missing.
THIS IS THE BUG! Compact is supposed to move all pre-compact data to sealed, but 106 samples are lost during the compact process.
This is a different bug from what the issue describes! Let me look at the compact code:
phase4aPageCount + 1
finalPageCount
So the data flow is:
Phase 1+2: read pages 1-173, compress
Phase 3: write compressed data to temp file
Phase 4a: snapshot dataPageCount, read pages 174 to dataPageCount
Phase 4b: compress and append to temp
Phase 4c: read pages phase4aPageCount+1 to finalPageCount, compress, append to sealed, clear header
So all data should be in sealed. But we observed 106 missing.
Wait, but the read in Phase 4a and Phase 4c uses the CURRENT transaction. The current TX has its own modifiedPages and newPages. The appenders might have done db.begin/mutableBucket.appendSamples/db.commit in NESTED transactions, which are separate TXs from the compact's TX.
So when compact's Phase 4a reads the page, it gets a fresh copy from the cache or disk. The page is at the latest committed version. Good.
But the appenders could be CONCURRENTLY appending to the mutable bucket. They hold the readLock (compactionLock.readLock). Compact's Phase 4a holds the writeLock. They're mutually exclusive.
So Phase 4a sees the data at the time it acquired the writeLock. It reads pages 174+ (if any). The data on those pages is what was committed by appenders before Phase 4a.
Phase 4b processes this data. Lock-free. So new appenders can write new pages (175, 176, ...).
Phase 4c takes the writeLock. So it sees the latest data. It reads pages phase4aPageCount+1 to finalPageCount. So it reads the new pages that were created during Phase 4b.
So the data should be in sealed. But 106 are missing.
OH WAIT. Let me re-read the diag:
28 pages post-compact with mutable count = 6458
So mutable has 28 pages and 6458 samples. If the dataPageCount is 28, all 28 pages exist. Each is filled with at most 239 samples. 28 * 239 = 6692 max. We have 6458. So 28 pages with avg 230 samples each.
But wait, the diag shows dataPageCount=28 has only 4 calls. That means dataPageCount went 0, 1, 2, ..., 28 during post-compact. The 28th page only has 4 samples. So the 28th page is mostly empty.
But the test result says dataPageCount=28 (from the API). So the header says 28. But the actual data shows only 4 samples in the 28th page.
Wait, but the test also says mutableCount=6458. If dataPageCount=28 and only 4 samples in page 28, then the other pages have a lot of samples. Let me think: 28 pages, 6458 total samples. If page 28 has 4, then pages 1-27 have 6454 samples. 6454 / 27 = 239.04. So pages 1-27 are FULL (239 each). Page 28 has 4.
So 27 full + 1 partial = 27*239 + 4 = 6453 + 4 = 6457. But we have 6458. So 1 extra. Hmm.
Let me check by removing the diag and re-running:
preCompactSampleCount = 45620
sealedCount = 45827
So 207 MORE in sealed than pre-compact. That means compact moved MORE than preCompactSampleCount. Maybe compact is duplicating data?
If compact duplicates 207, then 45620 + 207 = 45827 (sealed) + 2136 (mutable) = 47963. So total = 47963. And 48000 - 47963 = 37 missing.
So compact duplicates 207 and 37 are lost. Net loss: 37 - 207 = wait that doesn't make sense.
Actually if pre-compact writes 45620 samples to mutable, then compact should move all 45620 to sealed. So sealed should be 45620. But we see 45827. So 207 EXTRA in sealed.
Where do the 207 extras come from? They must be NEW samples that were written during compact (during Phase 4a/4b/4c). These samples were moved to sealed by Phase 4c.
So the data flow:
Pre-compact: 45620 samples in mutable
During compact, new appends come in. Some go to sealed (via Phase 4a/4b/4c), some stay in mutable.
After compact: sealed has 45827 (45620 + 207), mutable has 2136 (the rest of post-compact)
Total: 47963
So the post-compact samples = 48000 - 45620 = 2380. But the test result shows mutable=2136, so 2380 - 2136 = 244 post-compact samples are in sealed. So sealed should have 45620 + 244 = 45864. But we see 45827. So 45864 - 45827 = 37. So 37 post-compact samples are missing.
OK so 37 are missing. But wait, we had the scanCount=47963. So the scan reads 47963 rows. count(*)=47963. So they match.
The 37 missing are not in count and not in scan. So they're really lost.
Let me check: 37 lost out of 48000. That's 0.077% loss. That's still a real loss.
Now, the issue says 89-159 lost. We're seeing 37 here. Different numbers but the same kind of loss.
The bug must be in how compact and concurrent appenders interact. Let me think about this.
Phase 0: snapshot 191 pages. So 191 * 239 = 45649 (max). But preCompactSampleCount = 45620. So 191 pages, with the last partial (45620 - 190*239 = 45620 - 45410 = 210). So 190 full + 1 partial (210).
Phase 1+2+3: read pages 1-190, compress, write to temp. So 190 * 239 = 45410 samples to temp.
Phase 4a: snapshot dataPageCount, read pages 191 to dataPageCount. So new pages added during Phase 1+2+3.
Phase 4b: compress and append to temp.
Phase 4c: read pages from phase4aPageCount+1 to finalPageCount, compress, append to temp. Then swap temp to sealed, clear header.
So all samples should be in sealed. But sealed has 45827, not 45620 + 207.
Hmm wait, let me re-read. preCompactSampleCount = 45620. sealed = 45827. So sealed has 207 MORE than pre-compact. So 207 samples were added during compact.
If during compact, 244 new samples came in (since 48000 - 45620 = 2380 post-compact, and 2136 stayed in mutable, so 244 went to sealed), then sealed should be 45620 + 244 = 45864. But it's 45827. So 45864 - 45827 = 37. So 37 post-compact samples were lost.
So the bug is that 37 post-compact samples were lost during compact. They should have been moved to sealed (via Phase 4c) but they weren't.
Let me look at the actual compact code more carefully. Let me look at how Phase 4c reads the tail data:
OK I see Phase 4c:
Reads tailData (pages from phase4aPageCount+1 to finalPageCount)
Combines with phase4bSpill (the spill from Phase 4b)
Builds compressed blocks and appends to sealed
Swaps temp file into sealed
Records time series sealed change
Clears mutable header
Commits
But wait — between step 4 (swap) and step 5 (record), what happens if the record fails? Hmm, the data is in sealed but the record hasn't been made.
Actually, this is for HA replication. The record is to notify followers.
But for our case (no HA), step 5 is a no-op. So the swap happens, then the header is cleared. The data in the sealed store should include the pre-compact + post-compact tail data.
Let me check the issue with the clearDataPages. After clear, the mutable's HEADER is reset:
HEADER_SAMPLE_COUNT_OFFSET = 0
HEADER_DATA_PAGE_COUNT = 0
But the page DATA is not touched (just the sample counts in the pages are... wait, no, clearDataPages only resets the header, not the pages).
So after clear:
Page 1 to N: have OLD data (sampleCount=239 each) but HEADER says dataPageCount=0
Header: dataPageCount=0, sampleCount=0
When new appenders come in:
Read HEADER dataPageCount=0
Allocate page 1 (reuse), initialize sampleCount=0
Write sample 0, increment to 1
So the slot 0 of each page is overwritten. But slots 1-238 still have OLD data.
Now, the issue: the OLD data in slots 1-238 of pages 1-N is NOT counted. The count in the HEADER was reset to 0. Only the NEW data is counted.
So the total in mutable = (number of post-compact appends). The total in sealed = (pre-compact samples) + (post-compact samples that were moved to sealed by compact's Phase 4c).
If Phase 4c moved all post-compact samples to sealed, then mutable should be 0. But we have 2136 in mutable. So Phase 4c moved SOME post-compact samples to sealed.
So 48000 - 47963 = 37 lost. Where are the 37 lost?
If pre-compact is 45620, and 48000 inserts total, then 2380 are post-compact. Of these 2380, 207 went to sealed (Phase 4c), 2136 stayed in mutable. So 2380 = 207 + 2136 + 37 lost. The 37 are lost somewhere.
Where? Maybe the 37 are samples that were written to the mutable bucket AFTER Phase 4c's read but BEFORE compact finishes? Let me think:
Phase 4c takes the writeLock, reads finalPageCount, reads tailData (pages phase4aPageCount+1 to finalPageCount), processes, swaps, clears header, releases lock. While the writeLock is held, no appenders can run.
So after Phase 4c commits and releases the lock, the mutable bucket's dataPageCount=0. Then new appenders can come in.
But what if an appender was IN PROGRESS (already past the compactionLock.readLock().lock() check, in the middle of db.begin()) when compact's writeLock was acquired? They'd be blocked at the readLock acquisition.
Wait, the readLock/writeLock are MUTUALLY EXCLUSIVE. If compact holds the writeLock, no reader can acquire the readLock. If a reader holds the readLock, compact's writeLock acquisition is blocked.
So Phase 4c's writeLock is held for the duration of db.begin/commit. While the writeLock is held, appenders are blocked at compactionLock.readLock().lock().
But what if an appender got past the readLock acquisition BEFORE Phase 4c's writeLock acquisition? Then it could still be running when Phase 4c starts. But that's a race — only one of them can have a lock at a time.
Hmm, let me re-think. The sequence:
Apparent A: readLock.lock() (acquires)
Compact: writeLock.lock() (waits for A to release)
But wait, the lock is held by Apparent A for the entire TX. The TX is db.begin/mutableBucket.appendSamples/db.commit. This is a NESTED TX if the outer TX is active. So A holds the readLock for the nested TX.
But the OUTER TX (the user's database.transaction(() -> ...)) is NOT under the readLock. The readLock is held only for the duration of the nested TX.
OK so the readLock IS held correctly.
Now, what if Phase 4a's readFullPagesForCompaction reads a page that was JUST written by a concurrent appender? Let me think.
Phase 4a: takes writeLock. So no appender is running. Reads pages 1 to phase4aPageCount. The pages are the latest committed. Good.
Phase 4b: no lock. Appenders can run. They write to the mutable bucket.
Phase 4c: takes writeLock. Reads tailData (pages phase4aPageCount+1 to finalPageCount). These are the new pages added during Phase 4b.
But wait, the new appenders in Phase 4b could be writing to:
Existing pages (if not full)
New pages (if existing is full)
If they write to EXISTING pages (e.g., page 191 if it's not full), then those existing pages are NOT in tailData. The data in those pages is lost during compact!
Yes, that's the bug! Let me confirm.
Phase 0: snapshot 191 pages.
Phase 1+2: read pages 1-190 (full pages).
Phase 3: write temp.
Phase 4a: snapshot, read pages 191+ (new pages).
Phase 4b: process.
Phase 4c: read pages from phase4aPageCount+1 to finalPageCount (NEW pages only).
So if during Phase 4b, an appender writes to page 191 (an existing page, not full), the new data is in page 191. Phase 4c only reads NEW pages (192+). So the new data in page 191 is LOST.
When Phase 4c clears the header, the data in page 191 is in the page (just not counted). After the clear, the data in page 191 is "stuck" — new appenders overwrite slot 0, but slots 1+ are OLD data.
But wait, the sampleCount in page 191 is incremented by the appender (during Phase 4b). Then Phase 4c reads finalPageCount = 191 (if no new pages added). The tailData is null. The page 191 data is NOT moved to sealed.
But then clearDataPages resets dataPageCount=0. The next appender allocates page 1 (reusing), writes slot 0, increments sampleCount=1.
The data in page 191 is now "orphaned" — not in sealed, not counted in mutable.
THIS IS THE BUG!
Now, the issue is that clearDataPages only resets the header, not the pages. The pages still have the data. But the data is not in sealed and not counted in mutable.
Wait, but the scan reads from the pages based on dataPageCount. After clear, dataPageCount=0, so the scan doesn't see the data.
So the data is truly lost.
Root cause: Phase 4c only processes pages that are NEW (from phase4aPageCount+1 to finalPageCount). It doesn't process data added to EXISTING pages during Phase 4b. When clearDataPages resets the header, the data in those existing pages is lost.
Now, the question is: how to fix this?
Option 1: In Phase 4c, also process data added to existing pages (pages 1 to phase4aPageCount that might have been modified).
Option 2: Don't use clearDataPages. Instead, only clear the specific pages that were processed.
Let me look at clearDataPagesUpTo:
So clearDataPagesUpTo clears pages 1..upToPage and recomputes the header from pages upToPage+1..totalDataPages.
But this isn't called from compact. Compact calls clearDataPages (all pages).
OK so the bug is real. Let me think about the fix.
Actually, the simplest fix is: In Phase 4c, also process the data added to existing pages (not just new pages). But the existing pages might be partially modified by appenders. We need to read them again and add to sealed.
OR: Use clearDataPagesUpTo(finalPageCount) which keeps the data in pages finalPageCount+1..totalDataPages.
But wait, the issue is that EXISTING pages (e.g., page 191) were modified by appenders. The new data needs to go to sealed.
Let me look at what the Phase 4c should do:
Read existing pages that might have new data (1 to phase4aPageCount)
Read new pages (phase4aPageCount+1 to finalPageCount)
Combine all, compress, write to sealed
Clear the header (and pages)
But the existing pages' old data was already moved to sealed in Phase 1+2+3. So we don't want to move the OLD data again. We only want to move the NEW data (added during Phase 4b).
This is tricky. Let me think about this more.
Actually, the cleanest approach is to NOT use clearDataPages (which loses the page data). Instead, use clearDataPagesUpTo(finalPageCount) which keeps pages after finalPageCount.
But the page data is still there. So if we call clearDataPagesUpTo(finalPageCount), the pages 1..finalPageCount are reset (sampleCount=0), and the header is recomputed. Pages finalPageCount+1..totalDataPages are kept (with their data).
But the OLD data in pages 1..finalPageCount is still in the pages (just not counted). When new appenders come in, they overwrite slot 0 of pages 1..finalPageCount, losing the OLD data.
Wait, but the OLD data is in the sealed store. So it's not lost.
Hmm, but clearDataPagesUpTo resets sampleCount=0 for those pages. The old data is still there. The new appenders can overwrite the old data.
But the new appenders will:
Read HEADER dataPageCount = finalPageCount (or some value)
Allocate a new page (finalPageCount+1)
Initialize sampleCount=0
Write sample 0, increment to 1
So the OLD pages 1..finalPageCount are not touched (they're "logically" gone). New appenders go to new pages.
So the OLD data in pages 1..finalPageCount is orphaned. But it's in the sealed store. So no loss.
OK so the fix is to use clearDataPagesUpTo(finalPageCount) instead of clearDataPages().
But wait, there's still the issue of data added to existing pages during Phase 4b. That data is in the existing pages, but the pages are being "cleared" by clearDataPagesUpTo. So that data would be lost too.
Actually, let me re-read. The data added to page 191 during Phase 4b is in page 191. The sampleCount of page 191 is incremented. If we call clearDataPagesUpTo(finalPageCount=191), page 191 is reset to sampleCount=0. So the data added to page 191 during Phase 4b is LOST.
So we need to also process the data added to existing pages during Phase 4b.
Hmm, but how do we know what was added? We don't track deltas. The page only has the current state.
OK the right approach is to re-read the data from existing pages that MIGHT have been modified. Then combine with tailData and write to sealed.
But we'd re-process the OLD data too. So we'd have duplicates in sealed.
Wait, the OLD data is already in sealed. So re-processing would duplicate it.
OK this is getting complex. Let me think of a different approach.
Alternative: snapshot the existing pages BEFORE Phase 4b (in Phase 4a), and re-read the existing pages AFTER Phase 4b (in Phase 4c). Then the diff is the new data.
This is more complex but avoids duplication.
Another alternative: don't allow appends to EXISTING pages during compact. Only allow appends to NEW pages.
This requires:
Phase 0 snapshot pageCount
During Phase 1+2+3+4b, if an appender wants to write to an existing page (1..pageCount), it must allocate a new page instead.
But this is also complex.
Simplest alternative: Process the ENTIRE data after Phase 4b, not just the tail. The OLD data in sealed is replaced (not duplicated) because the sealed store is rewritten.
Wait, but the sealed store is appended to (in Phase 3 and Phase 4b), not rewritten. If we re-process the old data, we'd duplicate it.
Hmm, but the sealed store is rewritten by commitTempCompactionFile which swaps the temp file. So the sealed store IS the temp file. The temp file was built from scratch (Phase 3 + Phase 4b). So if we re-add old data, it would be in the temp file.
But the old data in Phase 3 is the immutable pages 1..lastFullPage. Those are FULL pages. They don't change. So we can re-process them in Phase 4c if we want.
But actually, the issue is the PARTIAL last page (page 191 in our case). Phase 2 reads it and might create a spill (phase2Spill). Phase 4a reads pages 191+ (the new pages). Phase 4b processes.
But during Phase 4b, an appender could write to page 191 (the partial page). Then Phase 4c reads tailData (pages 192+). The new data in page 191 is LOST.
To fix this, we need to also read the data in page 191 in Phase 4c. But page 191 is not in tailData (since it's an existing page, not a new one).
Actually, the issue is that the partial last page (page 191) is treated as a "new page" only if it was newly created. If it existed in Phase 0, it's an existing page.
OK let me look at the code more carefully:
But what if during Phase 4b, an appender writes to page 191? Then page 191 has NEW data on top of OLD data. Phase 4a already read the OLD data of page 191. The new data is added during Phase 4b.
Phase 4c reads pages from phase4aPageCount+1 to finalPageCount (NEW pages). It does NOT re-read page 191. So the new data in page 191 (added during Phase 4b) is LOST.
So the bug is in Phase 4c. It needs to also re-read the existing pages that might have been modified during Phase 4b (i.e., pages 1 to phase4aPageCount, specifically the partial last page and any others that had room).
Actually wait, pages 1 to lastFullPage=190 are FULL. They CAN'T be modified by appenders (because appenders always go to the last page). So only page 191+ can be modified.
So Phase 4c should re-read pages phase4aPageCount+1... no wait, page 191 is the partial last page. If it's not full yet, appenders write to it. If it becomes full, they allocate a new page 192.
So during Phase 4b, the data added to page 191 is LOST.
Fix: In Phase 4c, re-read the partial last page (and any pages that might have been modified during Phase 4b) to capture the new data.
But how to do this without re-processing the OLD data?
Option: Use a phase4aSampleCount snapshot. For each page 1..phase4aPageCount, the sampleCount at Phase 4a was X. After Phase 4b, the sampleCount is Y (>= X). The new samples are at rows X..Y-1. Read only those.
But this requires knowing the sampleCount at Phase 4a. Phase 4a does read the data, so it knows.
Alternative: Just re-read the page and check if the sampleCount changed. If yes, the new data is at rows oldSampleCount..newSampleCount-1.
But this is complex. Let me think of a simpler fix.
Simpler fix: In Phase 4b, before processing, take a snapshot of the partial last page. Then process. If new data was added to the partial last page during Phase 4b, also process it in Phase 4c.
Actually, let me look at the existing code more carefully:
OK so phase2Spill is the spill from Phase 2. It contains the raw data of the last partial chunk of pages 1..190 (sorted). It does NOT contain data from page 191 (the partial last page).
So when Phase 4a reads page 191 (and new pages), it gets the data from those pages. Phase 4b combines with phase2Spill.
But if during Phase 4b, an appender writes to page 191, the new data is in page 191 but NOT in phase2Spill or phase4aData or phase4bSpill or tailData. So it's LOST.
This is the bug.
Now, the simplest fix is to track which pages were "potentially modified" between Phase 4a and Phase 4c, and re-read them. But that's complex.
A simpler approach: Phase 4c should re-read the partial last page (page 191) and any pages that have a sample count HIGHER than what Phase 4a read.
Actually, even simpler: Phase 4c should re-read ALL pages that existed at Phase 4a time, not just the new ones. The data is already in sealed (from Phase 1+2+3), so re-processing would duplicate it. But the sealed store is being rewritten via the temp file swap. So re-processing the OLD data in the temp file would re-add the OLD data.
Hmm, the temp file is built incrementally:
Phase 3: appends Phase 1+2 compressed blocks to temp
Phase 4b: appends Phase 4 compressed blocks to temp
Phase 4c: appends tailData compressed blocks to temp
If we add Phase 4c to also re-read pages 1..phase4aPageCount and add to temp, we'd duplicate the OLD data.
So we need to read the NEW data on existing pages, not the old data.
OK let me think about this differently. The issue is that during Phase 4b, an appender can write to a page that was already read by Phase 4a (specifically, the partial last page). The new data is lost.
Fix: Re-read the partial last page in Phase 4c to get the new data, and combine with tailData.
But we need to know which page was the partial last page at Phase 4a. That's phase4aPageCount or the original lastFullPage + 1.
Wait, actually the issue is more general. If at Phase 4a time, there are 191 pages (190 full + 1 partial), and the partial page has 210 samples. During Phase 4b, the appender can write 29 more samples to bring it to 239. Or write fewer.
The new data is at rows 210..newCount-1.
If at Phase 4a time, there are 192 pages (190 full + 2 partial), then page 192 is the new one. During Phase 4b, more appenders can write to page 192 (if not full) or allocate page 193.
So the issue is: pages that existed at Phase 4a and might have new data.
The simplest fix: In Phase 4c, re-read all pages from lastFullPage+1 to finalPageCount, and process ALL of them, but use the sample count from Phase 4a to skip the OLD data.
OR even simpler: Re-read the page and check if the sample count changed. If yes, the new data is at rows oldSampleCount..newSampleCount-1.
But this requires tracking the sample count at Phase 4a.
Actually, the simplest fix is to track the partial last page at Phase 4a and re-read it in Phase 4c.
Let me think about it. The partial last page at Phase 4a is lastFullPage + 1 if it was the partial page at Phase 0, or any new pages that were created during Phase 1+2+3.
Wait, actually pages 1..lastFullPage are full and immutable. Pages lastFullPage+1..phase4aPageCount are partial (might have data added during Phase 4b). Pages phase4aPageCount+1..finalPageCount are new (created during Phase 4b).
So we need to re-read pages lastFullPage+1..finalPageCount, but only the NEW data (not the data read by Phase 4a).
Hmm, but how to know what's new? We'd need to track the sample count at Phase 4a for each page.
OK let me look at this from a different angle. The simplest fix is to:
In Phase 4a, snapshot the sample count of each page.
In Phase 4c, re-read each page, and if the sample count is higher, extract the new data.
But this is complex.
Alternative simpler fix: Don't use clearDataPages (which loses page data). Instead, use clearDataPagesUpTo(finalPageCount).
This keeps pages finalPageCount+1..totalDataPages intact. The data in those pages is preserved (not in sealed, not lost).
But wait, clearDataPagesUpTo only clears pages 1..upToPage and resets their sampleCount=0. It also recomputes the header from pages upToPage+1..totalDataPages. So pages 1..finalPageCount are cleared (sampleCount=0), but the data is still in the pages (just not counted).
The NEW data added to existing pages (e.g., page 191) during Phase 4b would be in page 191, but the sampleCount of page 191 is reset to 0. So the data is "there" but not counted.
After clear, dataPageCount = finalPageCount. So pages 1..finalPageCount are "logically" gone. New appenders go to new pages finalPageCount+1, finalPageCount+2, etc.
So the OLD data in pages 1..finalPageCount is orphaned. But it's in the sealed store. So no loss.
But wait, the new data added during Phase 4b to existing pages is also lost! Because the sampleCount of those pages is reset to 0.
So this fix doesn't address the bug.
Hmm. Let me re-think.
OK so the actual bug is:
During Phase 4b, appenders can write to the partial last page (page 191 in our example) or any new pages.
Phase 4c reads only pages phase4aPageCount+1 to finalPageCount. So it doesn't read page 191 (which had new data added during Phase 4b).
The new data in page 191 is lost.
To fix this, we need to ensure that the new data in page 191 is captured.
Approach 1: Phase 4c re-reads all pages from lastFullPage+1 to finalPageCount, and uses the page state to determine what's new.
This requires tracking the sample count at Phase 4a. Complex.
Approach 2: Phase 4c re-reads all pages from lastFullPage+1 to finalPageCount, and assumes ALL data is new. Then re-processes it. But the OLD data is already in sealed, so we'd duplicate.
Not good.
Approach 3: Don't allow appends to existing pages during compact. Only allow appends to NEW pages.
This means during Phase 4b (and Phase 4a, 4c), if an appender wants to write to page 1..phase4aPageCount, it must allocate a new page instead.
This is simpler but requires changes to appendSamples.
Approach 4: Snapshot the partial last page at Phase 0, and re-read it at Phase 4c. If new data was added, merge it with the tail data.
This is similar to Approach 1 but more focused.
Let me think about Approach 3 more. The current appendSamples does:
Read HEADER dataPageCount
If > 0, write to last page (if it has room)
Otherwise, allocate new page
If during compact, we want to force allocation of new pages, we'd need a flag. Let me see if this is feasible.
Actually, this is what I think is the simplest fix:
In appendSamples, when reading the dataPageCount, if there's a compaction in progress, use the snapshot count from Phase 0 instead.
This way, appenders would always allocate a new page (because the snapshot count is "frozen" at the compact time).
But this requires sharing state between compact and appenders.
Let me look at setCompactionInProgress:
OK so isCompactionInProgress reads from the header. So appenders can check if compaction is in progress.
But the flag is set in Phase 0, BEFORE Phase 1+2+3+4a+4b. So the flag is set when compact starts.
Hmm, let me think about this. The simplest fix that doesn't require too many changes:
In appendSamples, check if compaction is in progress. If yes, don't use the last page; instead, always allocate a new page (using the snapshot count from Phase 0).
This way, appenders during compact would write to NEW pages (after the snapshot count). When compact finishes, the new pages (created during compact) would be properly handled by Phase 4c.
Let me look at the current appendSamples to see how this would work:
Actually wait, let me re-think. The issue is more subtle. Let me re-read the Phase 4c logic:
Phase 4c reads pages from phase4aPageCount+1 to finalPageCount. So if an appender creates a NEW page (because compaction is in progress and the snapshot count is frozen), that new page is BEYOND phase4aPageCount. So Phase 4c would see it.
YES! So if we force appenders to allocate new pages during compact, the new data would be in pages phase4aPageCount+1..finalPageCount. Phase 4c would read it. No loss.
The fix:
In Phase 0, snapshot dataPageCount. Store it somewhere (e.g., a volatile field in TimeSeriesShard, or in the header).
In appendSamples, if compaction is in progress, use the snapshot dataPageCount instead of the current one. This forces allocation of new pages.
But this requires the snapshot dataPageCount to be visible to appenders. Let me think about how to do this.
Looking at the header, we have HEADER_DATA_PAGE_COUNT (current count) and HEADER_COMPACTION_FLAG. We could add HEADER_COMPACTION_DATA_PAGE_COUNT (the snapshot count when compact started).
Actually, the snapshot count IS the current dataPageCount at Phase 0. So if we freeze the dataPageCount during compact, appenders would use the frozen value.
Let me think of an even simpler approach:
During compact (after Phase 0), set the HEADER_DATA_PAGE_COUNT to a SPECIAL VALUE (e.g., 0) to indicate "compact in progress, allocate new pages from this count". Then appenders, when they see this special value, allocate new pages.
But this is essentially what clearDataPages does. And we know clearDataPages causes the issue I'm trying to fix.
OK let me think differently. The simplest fix is:
Phase 4c should re-read the partial last page (and any existing pages that might have been modified) using the pageCount from Phase 4a as a baseline.
The pages that might be modified are: pages 1..phase4aPageCount where sampleCount < maxSamplesPerPage. So pages that are not full at Phase 4a time.
Actually, only the LAST page at Phase 4a time can be modified (because pages 1..lastFullPage are full, and pages lastFullPage+1..phase4aPageCount-1 must also be full if there are multiple partial pages... no wait, the partial last page is just one page).
Hmm wait, can there be multiple partial pages? Let me think.
getOrCreateActiveDataPage allocates a new page only if the last page is FULL. So there's only one partial page at any time. The partial last page is the page that's being filled.
So at Phase 4a, there's at most one partial page: lastFullPage + 1 (or the new pages added during Phase 1+2+3).
Actually, during Phase 1+2+3, new pages can be created. So at Phase 4a, we have:
Pages 1..lastFullPage: full, immutable
Pages lastFullPage+1..phase4aPageCount: partial, with the LAST one being the current partial
If lastFullPage + 1 == phase4aPageCount, there's only 1 partial page.
If lastFullPage + 1 < phase4aPageCount, there are multiple partial pages. But this shouldn't happen normally.
Wait, can it happen? Let me think. Phase 0 snapshots at T=0. Phase 1+2+3 runs (no lock). During this time, appenders can:
Write to the partial last page (filling it)
Allocate new pages (if the partial page becomes full)
So if during Phase 1+2+3, the partial page becomes full and a new page is allocated, then at Phase 4a, there would be 2 partial pages: the original partial page (now full) and the new one.
But the original partial page was already FULL at Phase 4a, so it's "full" in the sense of lastFullPage+1 (but it wasn't "lastFullPage" at Phase 0).
OK so the "partial pages" at Phase 4a time are: pages lastFullPage+1..phase4aPageCount. The LAST of these is the current partial page.
Only the LAST partial page can be modified by appenders. The others are full (otherwise more pages would have been allocated).
So the only page that needs to be re-read in Phase 4c is the LAST partial page at Phase 4a time, which is phase4aPageCount.
So Phase 4c should:
Re-read page phase4aPageCount (if it exists at Phase 4c time)
Compare with what was in phase4aData (which has the old sampleCount)
Extract the new samples (rows oldSampleCount..newSampleCount-1)
Add to sealed
But this is complex. And it requires tracking the sampleCount at Phase 4a.
Actually, an even simpler fix: just re-read the LAST page at Phase 4c and process ALL of its data. Since the OLD data is already in sealed, we'd duplicate it. But the sealed store is being rewritten, so we can just include the new data.
Wait, the sealed store IS being rewritten. Phase 3 + 4b writes compressed data to a TEMP file. Phase 4c appends more. Then commitTempCompactionFile swaps temp to sealed.
So the final sealed store contains:
Phase 3 + 4b's data
Phase 4c's data (tail)
If we add the new data on the partial last page in Phase 4c, the new data is in the temp file. The OLD data on the partial last page is in the temp file (from Phase 4b's processing of the partial page).
Wait, was the partial last page processed in Phase 4b? Let me check.
Phase 4a: reads pages lastFullPage+1..phase4aPageCount. This includes the partial last page.
Phase 4b: combines with phase2Spill, processes with buildCompressedBlocks(..., returnSpill=true). So Phase 4b might emit a spill (phase4bSpill) for the last partial chunk.
So Phase 4b does process the partial last page. But it uses the sampleCount at Phase 4a time.
If during Phase 4b, an appender writes to the partial last page, the new data is in the page but not in Phase 4a's read. So Phase 4b's processing doesn't include the new data.
So yes, the new data on the partial last page is lost.
OK my proposed fix: in Phase 4c, re-read the partial last page, and process the NEW data (rows oldSampleCount..newSampleCount-1).
Let me look at how to implement this. The key is to track the sample count of the partial last page at Phase 4a.
Actually, looking at phase4aData, it contains all the rows read in Phase 4a. So we can compute the sample count from it. Or we can read it from the page.
Let me look at the Phase 4c code:
toCompressFinal
Also include the existing tailData (for completely new pages).
Let me think about how to track phase4aPartialPageSampleCount. We can compute it from phase4aData if we know how many samples came from each page. Or we can just track the count of the partial page.
Actually, an even simpler approach: just track phase4aPageCount and phase4aPartialSampleCount (the sample count of the last page at Phase 4a).
OK now let me also think about the OTHER bug: the original issue is about the slot count being stale. Let me revisit that.
The issue describes:
a following serialized append reads a stalesampleCountInPage — the prior append's count → N+1 increment is not visible — so two appends compute the samerowOffset and write the same slot N; the later commit overwrites the earlier row.
This is a DIFFERENT bug. My diagnostic shows the slot count is NOT stale — it goes monotonically. So the issue description's mechanism is not what I'm seeing.
But the issue's SYMPTOM is the same: samples are lost.
So I need to figure out if the issue is about a different mechanism. Let me think...
Maybe the issue's mechanism is:
Thread A writes to slot N, increments to N+1
Thread B reads sampleCount = N+1 from a stale page, writes to slot N+1
Thread A's commit goes through
Thread B's commit fails (concurrent modification) OR succeeds and overwrites Thread A's row
But my diagnostic shows no concurrent modification errors. And the slot count is not stale.
Maybe the issue is the compact bug I'm investigating. The issue's description might be a hypothesis that turned out to be wrong, but the actual bug is the compact one.
OR maybe both bugs exist. The issue's mechanism is a separate bug that I haven't reproduced.
Let me check by disabling the compact and running the test:
appendLock
db.begin()/append/db.commit()
OK so the append is serialized per shard.
A temporary collision detector added to appendSamples (recording fileId:pageNumber:slot per append) confirmed the mechanism: a following serialized append reads a stalesampleCountInPage
So the slot collision detector shows a stale slot count.
OK so the issue's hypothesis is the slot count is stale. But my diagnostic shows it's not stale. So either:
The issue's hypothesis is wrong, and the actual bug is the compact one.
The slot count IS stale, but my diagnostic doesn't show it because of some other issue.
Let me re-examine my diagnostic. I printed sampleCountInPage from the page. The page is the one being modified. The page version increments with each commit.
But what if the page version is incremented but the SAMPLE COUNT is read from a CACHED value that's stale? Let me check:
But wait, the issue says "the test creates a TIMESERIES TYPE ... SHARDS 1" and runs 48 threads × 5000 inserts. With maintenance running at T=5s, the test would compact and lose data. So maybe the issue's example of "89 samples lost" IS from the compact path.
Let me focus on fixing the compact bug.
Actually, let me re-think the issue more carefully. The issue says:
the time series engine silently drops samples. The client receives success on every insert (HTTP 200, no exception, no ConcurrentModificationException), yet the stored row count comes up short.
So samples are dropped. The mechanism is silent.
Root cause analysis
The write position for a sample is a read-modify-write of the per-data-page sample count. In TimeSeriesBucket.appendSamples (engine/.../engine/timeseries/TimeSeriesBucket.java):
So the issue's hypothesis is the slot count is stale.
But my diagnostic shows the slot count is NOT stale.
Hmm. Let me check the actual flow once more.
Actually, wait. Let me check what happens when the page is FULL. When the page is full, the appender:
Sees dataPageCount=N, sampleCount=239
dataPageCount > 0, last page = page N, sampleCount=239 = maxSamplesPerPage
Allocates new page (newPageNum = N+1)
Initializes sampleCount=0
But what if between the read of dataPageCount and the write of newPageNum, another thread changes things? Let me check.
Actually, the read of dataPageCount is from the HEADER page (page 0). The write of newPageNum is also to the HEADER page. These are different bytes on the same page.
The appendLock is held during this time, so only one thread at a time. No race.
OK so my analysis is correct. The slot count is NOT stale. The bug must be in the compact path.
Let me now also check if the bug could happen with TimeSeriesEngine.appendBatch. The issue says batch is not affected. So batch is fine. Single-row is affected.
OK so the bug is in the compact path. Let me fix that.
The fix is: In Phase 4c, re-read the partial last page (page phase4aPageCount) to capture any new data added during Phase 4b.
Let me look at the current code and design the fix:
phase4aPageCount + 1, phase4aPageCount + 2, ...
phase4aPageCount
Let me re-look at the Phase 4c code:
java
final int finalPageCount = mutableBucket.getDataPageCount();
// Read only the tail pages created after Phase 4a's snapshot.
Object[] tailData = null;
if (finalPageCount > phase4aPageCount)
tailData = mutableBucket.readPagesRangeForCompaction(phase4aPageCount + 1, finalPageCount);
So tailData reads pages phase4aPageCount + 1 to finalPageCount. This misses page phase4aPageCount (which might have new data).
The fix: re-read page phase4aPageCount (if it exists) to get the new data, and combine with tailData.
Let me implement this:
In Phase 4a, store phase4aData (already done) and compute phase4aLastPageSampleCount (the sample count of the last page at Phase 4a time).
In Phase 4c, re-read page phase4aPageCount (if it exists), get its current sample count currentLastPageSampleCount. If currentLastPageSampleCount > phase4aLastPageSampleCount, extract rows phase4aLastPageSampleCount..currentLastPageSampleCount-1 as newLastPageData.
Combine newLastPageData with tailData and phase4bSpill for processing.
Let me implement this:
Now let me also check that the page range check phase4aPageCount > lastFullPage is correct:
If phase4aPageCount == lastFullPage + 1, then page lastFullPage + 1 is the partial last page. So we should re-read it. The condition phase4aPageCount > lastFullPage is true (191 > 190).
If phase4aPageCount == lastFullPage (which means no new pages after Phase 0), then... hmm, this is when all pages are full. But the partial last page is at snapshotDataPageCount = lastFullPage + 1. So if phase4aPageCount == lastFullPage, that means the partial last page was filled during Phase 1+2+3 and a new page was allocated, but no new partial page was created? That doesn't make sense.
Actually wait, the partial last page can be filled and a new one allocated. So phase4aPageCount = lastFullPage + 2 (the new partial page). And the new partial page has no data yet (or has some data from concurrent appenders).
So at Phase 4a:
Pages 1..lastFullPage: full
Page lastFullPage + 1: was the partial last page, now full
Page lastFullPage + 2: new partial page (could be empty or have data)
So phase4aPageCount = lastFullPage + 2 in this case. The LAST page is the new one.
If phase4aPageCount = lastFullPage + 1 (no new page allocated), then the partial last page is the same as before.
OK so the condition phase4aPageCount > lastFullPage is true when there's at least one partial page. The LAST page is phase4aPageCount. So we re-read it.
But wait, what if there are multiple partial pages? E.g., lastFullPage=190, phase4aPageCount=192. Then pages 191 and 192 are both partial. But only page 192 can be modified by appenders. Page 191 is full (otherwise a new page would have been allocated).
Actually no, the code in getOrCreateActiveDataPage allocates a new page only if the LAST page is full. So pages 191 and 192 can both be partial — page 191 was the partial last page, then got filled, then page 192 was allocated as the new partial page.
So at Phase 4a:
Pages 1..190: full
Page 191: was partial, now full
Page 192: partial (new partial last page)
The new appenders can only modify page 192 (the LAST page). So Phase 4c only needs to re-read page 192.
But phase4aPageCount = 192. So we re-read page 192. Good.
But wait, what if page 191 was filled and page 192 was allocated, but the OLD data of page 191 was in phase4aData. So phase4aData includes page 191's data. And page 192's data (if any). Phase 4b processes phase4aData. Page 191's data is processed and goes to sealed. Page 192's data is processed (might be a spill).
So Phase 4a's data includes BOTH page 191 (the just-filled page) and page 192 (the new partial page). Phase 4b processes both. Page 191 is fully processed (it's full). Page 192 might have a spill (if not full).
So Phase 4b's spill contains the data from page 192 (the new partial page). Phase 4c needs to handle new data added to page 192 during Phase 4b. So we re-read page 192 = phase4aPageCount. Good.
OK the condition is correct.
But wait, what if lastFullPage + 1 == phase4aPageCount? That means the partial last page at Phase 0 (page snapshotDataPageCount = lastFullPage + 1) hasn't been filled yet. And no new pages allocated. So pages lastFullPage + 1 to phase4aPageCount = lastFullPage + 1 is just one page (the partial last page).
In this case, we re-read page phase4aPageCount = lastFullPage + 1. Good.
What if phase4aPageCount == lastFullPage? That means no partial page at Phase 4a time. Hmm, but Phase 0 saw snapshotDataPageCount pages, so there should always be a partial page at Phase 0. Unless the partial page was filled between Phase 0 and Phase 4a AND a new page was allocated, and that new page was also filled, etc. But that's a lot of appends in Phase 1+2+3.
Actually, the partial page at Phase 0 is page snapshotDataPageCount = lastFullPage + 1. If it gets filled during Phase 1+2+3, then a new page is allocated. So at Phase 4a, phase4aPageCount >= lastFullPage + 2. So phase4aPageCount > lastFullPage is always true if there was a partial page at Phase 0.
If there was NO partial page at Phase 0 (i.e., the last page was full), then lastFullPage = snapshotDataPageCount. So the condition phase4aPageCount > lastFullPage is phase4aPageCount > snapshotDataPageCount. This would be true if new pages were allocated during Phase 1+2+3. So we'd re-read the new pages.
Hmm, but if the original last page was full, then there are no partial pages at Phase 0. The new pages are full too (no concurrent appenders wrote to them since they were just allocated... actually they might have been partially filled during Phase 1+2+3).
OK I think the condition is mostly correct. Let me build and test:
This test is important. Let me make sure it still passes (or at least check the code is correct). Let me look at how Phase 4a/4c interacts with HA:
The runWithCompactionReplication wrapper:
Sets up a session to capture WAL
The compaction mutations are recorded
After compaction, the wrapper ships the WAL to followers
The Phase 4a's TX is db.begin(); read; db.rollback(). The rollback means no WAL is written. So this is fine.
Phase 4c's TX is db.begin(); read tail; swap; clear; db.commit(). The commit writes the WAL. With HA, the wrapper captures this WAL and ships to followers. So followers get the same committed state.
The recordTimeSeriesSealedChange records the rewritten sealed store bytes. This is shipped to followers.
So the HA flow is:
Phase 4c reads the new data (now including the partial-last-page new rows with my fix)
Phase 4c swaps the sealed store
Phase 4c records the sealed store bytes
Phase 4c clears the mutable header
Phase 4c commits
The wrapper ships the WAL + sealed bytes to followers
Followers apply the same mutations
With my fix, the new data from the partial last page is included in the sealed store. So followers also get this data. Good.
But wait, there's a subtlety. The Phase 4a's snapshot is captured in the leader's TX. The HA wrapper uses runWithCompactionReplication to capture WAL. But Phase 4a's TX is rolled back. So no WAL. So followers don't see Phase 4a.
But followers have their own pages and their own data. So Phase 4a reads the leader's pages. Followers don't do this.
OK so the fix should work for HA too. Let me think about one more edge case.
Edge case: what if the appender writes to the partial last page AND allocates a new page during Phase 4b? Then at Phase 4c:
phase4aPageCount is the OLD page count (e.g., 191)
finalPageCount is the NEW page count (e.g., 192)
tailData reads page 192 (the new page)
partialTailData reads new data on page 191 (the partial last page)
Both are merged. Good.
Edge case: what if the partial last page gets filled during Phase 4b? Then no more appends go to that page (they go to the new page). At Phase 4c, currentLastPageSampleCount = 239. So partialTailData reads rows 210..238 (if the original was 210).
Edge case: what if the page count didn't change during Phase 4b (i.e., no new pages, no data added to the partial last page)? Then currentLastPageSampleCount == phase4aLastPageSampleCount and partialTailData = null. Good.
Edge case: what if Phase 4a saw no partial page (i.e., phase4aPageCount == lastFullPage)? Then phase4aLastPageSampleCount = 0. The condition phase4aPageCount > lastFullPage is false. So no re-read. Good.
Wait, but if phase4aPageCount == lastFullPage, there could still be NEW data added during Phase 4b. Hmm, no, if there's no partial page, appenders would allocate a new page. So a new page would be created. So phase4aPageCount would be > lastFullPage.
Unless the appenders were blocked (e.g., all threads are doing something else). In that case, no new data is added. So no issue.
OK the fix should be correct. Let me also check the test pass rate:
Actually, let me re-read the issue's description:
The page version advances normally, and PageManager.updatePageVersion's version check does not raise a conflict for these commits
So the page version advances but the slot count is stale. This means the page was modified but the slot count change was lost.
Hmm, this is interesting. Let me think...
OH WAIT. I think I understand now. The issue might be in HOW the nested transaction works.
When the SQL INSERT path runs:
User calls database.transaction(() -> insert). This creates an OUTER TX.
shard.appendSamples calls db.begin() (on wrapped DB). This creates a NESTED TX.
The nested TX writes to the data page.
The nested TX commits, incrementing the page version.
The outer TX still has no pages (the nested TX had its own modified pages).
The outer TX commits, with no pages. So the outer commit is a no-op.
But wait, what if the outer TX DOES have pages? The SaveElementStep might have done other operations. Let me check:
SaveElementStep calls engine.appendSamples(...) which uses a NESTED TX
SaveElementStep returns
SQL command returns
Outer TX commits (no pages, no-op)
So the outer TX commit is a no-op. The nested TX commit is the one that actually commits the data.
So the slot count is read and written in the SAME nested TX. The page version is checked in the nested TX commit. So no race.
Hmm, but the issue says the slot count is stale. Let me think about this more.
Actually, maybe the issue is that the test in the issue is e.g. 89 samples lost is a less common occurrence. And the test reports 89-159 lost. My test (with maintenance disabled) reports 0 lost. So maybe the issue's hypothesized mechanism is just wrong.
Let me also test with a different test setup to see if the bug can be triggered without compact. Maybe higher concurrency or specific patterns.
Actually, let me also check: the issue mentions db.begin()/append/db.commit() on getWrappedDatabaseInstance(). So the nested TX is on the wrapped database. On standalone, the wrapped database is the same as the outer DB. So the nested TX is on the same DB.
Let me check what getWrappedDatabaseInstance() returns:
clearDataPages
Let me also check the original issue once more to make sure I addressed the symptom:
Summary
Under many concurrent single-rowINSERT INTO <timeseriesType> SET ts=…, <tag>=…, <field>=… statements (each in its own transaction, as happens over the HTTP/wire protocols), the time series engine silently drops samples.
The test reproduces this. With my fix, no samples are dropped.
The batched InfluxDB line-protocol path (POST /api/v1/ts/{db}/write, which appends many samples in one engine call/transaction) is not affected. Single-threaded inserts are not affected.
The batched path uses appendBatch which goes through the same shard.appendSamples but with multiple samples in one call. The single-threaded path doesn't trigger compact. So neither is affected.
Concurrency level (thread count) is the driver, not total row count.
Higher concurrency = more data = more pages = more chance of compact being triggered.
SHARDS 1 maximizes it (all appends contend on one shard).
Yes.
Single-threaded never loses.
Correct.
OK my fix addresses the symptom. Let me also verify the test passes consistently: