ISSUE DESCRIPTION Time series: concurrent single-row SQL INSERTs silently lose samples…
- User
ISSUE DESCRIPTION
Time series: concurrent single-row SQL INSERTs silently lose samples (sealed-slot lost update)
Summary
Under many concurrent single-row
INSERT 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, noConcurrentModificationException), yet the stored row count comes up short. Confirmed real data loss: a full table scan returns the same short count ascount(*), and aGROUP BY sensor_idshows 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(== thearcadedata/arcadedb:latestimage 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.javaIt creates a
TIMESERIES TYPE … SHARDS 1, runs 48 threads × 5000 single-rowINSERTs (each in its owndatabase.transaction(...)), then assertscount(*) == 48*5000. Result: e.g. 239911 / 240000 — 89 samples lost, with no exception and no failed transaction.Enable it by removing the
@Disabledannotation.B. Over HTTP (against the published image)
codeCREATE TIMESERIES TYPE sensor TIMESTAMP ts TAGS (sid STRING) FIELDS (v DOUBLE) SHARDS 1Then 16 threads, each POSTing 5000 distinct single-row inserts to
POST /api/v1/command/{db}:json - Observed on
Assistant
I'll start by exploring the repository structure and understanding the relevant code paths mentioned in the issue.
Assistant
I'll start by exploring the repository structure and the relevant files mentioned in the issue.
Assistant
Now let me look at the TimeSeriesShard and TimeSeriesEngine files.
Assistant
Now let me look at the TimeSeriesEngine, specifically the
appendSamplesandappendBatchmethods.Assistant
Now let me look at the SaveElementStep.java to understand the routing of SQL INSERT into
engine.appendSamples.Assistant
Let me understand the transaction nesting mechanism to confirm the root cause.
Assistant
Let me look at how
LocalDatabase.begin()handles nested transactions.Assistant
Let me understand how the nested transaction commit actually publishes pages. Let me look at the commit phases and PageManager.
Assistant
Now let me look at
commit1stPhaseto understand the version check and how pages get published.Assistant
Let me look at the PageManager's
getMutablePage,checkPageVersion,updatePages, andupdatePageVersion.Assistant
Let me look at
getCachedPage,CachedPage,useAsMutable,loadPage, andgetMostRecentVersionOfPage.Assistant
Now I need to understand the actual mechanism of how a page is shared between transactions.
Let me look at the
CachedPageclass anduseAsMutable/useAsImmutable. The key question is whether the sameCachedPage(and the underlying buffer) is shared between the nested transactions, and whether the version increment is visible.Let me look at the CachedPage class.
Assistant
Let me look at the test file mentioned in the issue and check the WAL/transaction manager interaction.
Assistant
Let me check the build system and try to reproduce the issue first.
Assistant
Let me look at how the TimeSeriesEngine is created and what database instance it receives, plus the WAL transaction path.
Assistant
Let me build the engine module to reproduce the issue. First, let me check maven availability and the module structure.
Assistant
Good, mvnw works with HOME set. But Java 25 vs target 21. Let me check if Java 21 is available, since the build targets 21.
Assistant
Java 21 is available. Let me set up the environment and build the engine module.
Assistant
The engine compiles. Now let me write a quick reproduction script as a test to confirm the issue.
Assistant
Let me create a temporary reproduction test to confirm the issue.
Assistant
Offline mode is missing the surefire provider. Let me try without offline mode to fetch dependencies.
Assistant
The test passed. Let me increase to the exact reproduction parameters (48 threads × 5000) and add a smaller page size to maximize contention.
Assistant
I've reproduced the issue: 240000 expected, 239927 actual, 73 lost, 0 errors. Now let me understand the exact mechanism. Let me add diagnostics to trace the page version visibility. First let me look at the WAL transaction path.
Assistant
Let me add targeted diagnostics to confirm whether the nested commit publishes the page version. I'll instrument
TimeSeriesShard.appendSamples.Assistant
Let me add diagnostics. I'll add a diagnostic in the bucket's appendSamples to detect collisions, and in the shard to log page versions before/after commit.
Let me write the diagnostic directly into TimeSeriesBucket.appendSamples temporarily.
Actually, let me add a focused diagnostic: in
TimeSeriesBucket.appendSamples, record for each (fileId, pageNum) the slot used and the thread and the page version. When a collision is detected (same slot), print a message.Let me write a temporary diagnostic block.
Assistant
No collisions detected but samples are still lost. The slot collision isn't the mechanism in this case. Let me add a diagnostic in the shard that reads back the page count after commit to find where the loss occurs.
Assistant
getMostRecentVersionOfPageis private. Let me revert these diagnostics and write a cleaner comprehensive diagnostic that records all appends and analyzes them.Assistant
Now let me modify the repro test to dump and analyze the diagnostic data after the run.
Assistant
Now I see slot collisions (32420) but only 111 lost. Let me dump actual records to understand the pattern.
Assistant
The first80 didn't print — probably because the string with
\nand\\ngot mangled. Let me fix the printing. Actually the issue is the\\nin the python string became\nliteral in the java which is a newline... but it didn't show. Let me just print records with System.out.println per record for the first 40.Actually, the grep filter
grep -E "ERRORS=|EXPECTED=|DIAG"— the first80 line starts with "DIAG first80:" but the records are on subsequent lines that don't match the grep. Let me grep more broadly or use a different approach.Let me print the records in a single line joined.
Assistant
No output captured. The build might have failed because of the previous edit leaving duplicate code. Let me check the test file and re-run capturing all output.
Assistant
Let me rewrite the test cleanly.
Assistant
The first 60 records show clean incrementing slots (0,1,2,...) with incrementing versions. The collisions must happen elsewhere. Let me find the first collision and print records around it.
Assistant
I found the key pattern. Look at DIAGAROUND:
code[1p264s238v238]...[1p265s0v0][1p265s1v1][1p265s2v2] [1p1s0v239][1p1s1v240]...After page 265 gets a few samples, an append jumps BACK to page 1 (which already has 238 samples) at version 239 and re-writes slot 0. This means the header page's
HEADER_DATA_PAGE_COUNTwas read STALE, causing the append to reuse an old page and overwrite existing data. Let me examine the cache/flush path to understand why a stale read happens despite the appendLock serialization.Assistant
Let me check
popIfNotLastTransactionand how the transaction stack handles nested commits.Assistant
Let me check the default
asyncFlushanduseWALsettings, and how the timeseries transactions are configured.Assistant
Let me check whether
getWrappedDatabaseInstance()returns the same instance in standalone mode, and howDatabaseFactorycreates the database.Assistant
So in standalone,
wrappedDatabaseInstance = this(the LocalDatabase). SogetWrappedDatabaseInstance()returns the same instance. So the nested commit publishes to readCache synchronously. NOT deferred.So the issue author's "deferred to outer commit" claim applies to HA mode, not standalone. In standalone, the publish is synchronous. But the test still loses data. So in standalone, the mechanism is the cache race (eviction + stale reload), NOT deferral.
OK so let me directly confirm the cache race. Let me check the readCache size and whether page 0 gets evicted. Let me look at the eviction logic and
INITIAL_PAGE_CACHE_SIZEand maxRAM.Assistant
Page 0 (header) gets evicted under the 16MB test cache. Let me add a more targeted diagnostic recording the header page version and dataPageCount at each append to confirm the stale header read.
Assistant
No output captured. The build might have failed. Let me check.
Assistant
The diagnostic array uses
long[]but I passedintvalues — that's fine. The error is at line 532, which is theDIAG2.add(new long[]{...sampleCount})—sampleCountis int. Let me check line 532.Assistant
Line 532 is the
final int dataPageCount = headerPage.readInt(HEADER_DATA_PAGE_COUNT);. Wait, the error is "incompatible types: possible lossy conversion from long to int" at 532,45. Hmm. Let me check —headerPage.readIntreturns int. So that's fine. Wait the line numbers shifted. Let me look at line 532 column 45.Actually
Thread.currentThread().threadId()returnslong. In along[]array initializer that's fine. The issue:new long[]{..., hdrVer, dataPageCount, dataPageCount, sampleCount}— these are ints, auto-widened to long, fine.Wait, the error is at the ORIGINAL line 532 which after my edits... let me check the actual line 532.
Assistant
headerPage.getVersion()— let me check its return type. It might returnlong. Let me check.Assistant
getVersion()returnslong. Let me fix the diagnostic.Assistant
The header version is always fresh (increments cleanly, no backward jump) yet 51 samples lost. So the loss isn't (only) a stale header read. Let me examine the outer transaction path —
database.transactionanddatabase.command.Assistant
Let me check the default
transactionoverload and whetherjoinCurrentTxis true.Assistant
Let me check how
count(*)is implemented for timeseries, and verify the loss is real with a full scan.Assistant
count(*)usescountType. Let me check howcountTypehandles time series.Assistant
count(*)readsHEADER_SAMPLE_COUNTfrom page 0. Let me verify whether the loss is in the count (header) or in actual data (full scan) by modifying the test.Assistant
count(*) = full scan = engine countSamples = 95941, all consistent. So it's REAL data loss (rows overwritten + count increments lost). Let me instrument the publish path directly to see if the nested commit actually publishes the page version. Let me add a debug method to PageManager.
Assistant
Now let me instrument the shard's appendSamples to verify the publish happens and is visible after commit.
Assistant
Now let me add the DIAG_AFTER field to the bucket and instrument the bucket to record the header version read at append time, then compare with the after-commit version.
Assistant
The header version advances 96000 times (publish happens at nested commit) and header reads are never stale, yet 123 samples are lost. The staleness must be in the DATA page. Let me instrument the data page version read vs the most-recent version to detect staleness directly.
Assistant
Let me use a separate diagnostic list for the data page to avoid confusion with the shard's list.
Assistant
Both header and data page reads are NEVER stale, the header version advances 96000 times, yet 124 samples are lost. This is puzzling. Let me test whether the outer
database.transaction()wrapper is involved by trying auto-commit inserts instead.Assistant
Same loss with auto-commit (no outer transaction). So the loss is purely in the append path. Let me directly record the count values read and written per append to find duplicates — this will definitively show whether two appends read the same count.
Assistant
Key finding: 32862 duplicate HEADER_SAMPLE_COUNT reads but 0 duplicate data page count reads. So the header sample count is read stale/overwritten, but data page slots are unique. Yet full scan is also short. Let me measure the header page version vs the actual most-recent version at the
updateHeaderStatsread point.Assistant
The cached page version equals mostRecent (fresh version) but the count read is a duplicate (stale count). So the published page 0 has the incremented version but a STALE count. Let me examine
MutablePage.incrementVersion/updateMetadataand the deep-copy timing.Assistant
Let me dump the actual recorded (version, count, mrv) values around the first duplicate header count read to understand the pattern.
Assistant
Critical finding: at i65169, the header count READ drops from 65168 to 0 and the version jumps 65170→65172. So a commit published page 0 with a high version but count=0 (a reset/overwrite). This is a cache/flush race. Let me test whether a large page cache (no eviction) eliminates the loss.
Assistant
The "default" profile uses 4GB cache, so eviction is NOT the cause. Yet count resets to 0 and version jumps by 2 between consecutive appends — suggesting a second committer of page 0. Let me instrument
updatePageVersionto log every page-0 version increment with the thread.Assistant
Let me rewrite the test file cleanly to avoid variable conflicts.
Assistant
The publishes are monotonic (no jumps), 96003 total, exactly 4000 per worker thread. So no extra committer — yet count resets to 0. A publish must have written count=0 at a high version. Let me record the HEADER_SAMPLE_COUNT value at each page-0 publish to catch the bad publish.
Assistant
31991 HSC resets in publishes! The published HEADER_SAMPLE_COUNT goes backward. Let me capture the PUBR detail around the first reset.
Assistant
PUBR shows: at version 54167, the published page 0 has HSC=0, DPC=0 (initial state!). So a publish wrote the initial page-0 content at a high version. Let me examine the flush thread — it may replace the readCache entry with a stale disk-loaded version after flushing.
Assistant
Let me check
PAGE_VERSION_OFFSET,PAGE_CONTENTSIZE_OFFSET, andPAGE_HEADER_SIZE—updateMetadatawrites these and might overlap with the time series header layout.Assistant
PAGE_HEADER_SIZE=8, so updateMetadata writes bytes 0-7 (version/contentSize), not overlapping HSC at byte 15. Let me track object identity: record the identityHashCode of page 0 in
getOrCreateActiveDataPage, inupdateHeaderStats, and at publish time, to see if they differ.Assistant
The published page 0 object (idHC=341436356) DIFFERS from the one
updateHeaderStatswrote to (idHC=2054419006)! SogetPageToModify(page 0)returned different objects in the same transaction. Let me checkPageId.equals/hashCode— this may create two separate modifiedPages entries for page 0.Assistant
PageId.equals uses
Objects.equals(database, ...). Let me print the phase0 (getOrCreateActiveDataPage) identity for the same append to see whether it matches the published object or the updateHeaderStats object.Assistant
The published page-0 object (idHC=1040180857) differs from the one
updateHeaderStatsmodified (idHC=1999451157). So a different transaction commits a stale page 0. Let me check whether the SQLINSERTcommand itself runs in an outer transaction that could load and commit a stale page 0.Assistant
Let me find the INSERT statement's
executeand whether it auto-wraps in a transaction.Assistant
Let me look at how the execution plan handles auto-transactions.
Assistant
I was misaligning versions: the publish at version V is from the append that loaded at V-1. Let me properly match each publish to its append's phase0/phase1 by thread and loadVer=pubVer-1, and compare object identities.
Assistant
Let me look at the prior "fix: timeseries concurrency" commit to understand the intended design and the appendLock's purpose.
Assistant
Let me verify a key hypothesis: whether
database(bucket's field) is the same instance asdb = database.getWrappedDatabaseInstance(), and whether the transaction the bucket writes to is the same onedb.commit()commits. Let me add a diagnostic.Assistant
No output. Build failed? Let me check. The
databasefield in TimeSeriesBucket isDatabaseInternal(from PaginatedComponent). Let me check the visibility —getDatabase()might already exist. Anddatabasefield access. Let me check the build.Assistant
I reverted the diagnostics but the test still references them. Let me rewrite the test cleanly to only print the TX diagnostic.
Assistant
db == database(same instance), and the bucket's tx is consistent (DIAG_TX=0). So the published page 0 is the same tx's object, yet it has stale content. Let me checkBinary.getContent()— the deep copy source — and whether the flush thread could race with it.Assistant
Let me re-examine the GlobalConfiguration profiles to confirm the actual MAX_PAGE_RAM in the "default" test profile.
Assistant
The "default" profile uses 4GB cache (no eviction). Let me try forcing a synchronous flush on the append transaction to test whether the async flush is the culprit.
Assistant
No output. Let me check the build/run.
Assistant
The test still references DIAG_TX. Let me clean up the test to remove the diagnostic reference.
Assistant
Sync flush still loses (31). So async flush isn't the culprit. Let me check
checkBoundariesOnWrite— whether page writes actually update the modified range (which determines if a page is committed).Assistant
Let me add a direct diagnostic: in
updateHeaderStats, read back the written value, and inupdatePageVersion, read it — matched by object identity — to find what resets HSC between write and publish.Assistant
Let me verify whether
getOrCreateActiveDataPageandupdateHeaderStatsget the SAME page-0 object (identity), which would reveal a PageId-equality / double-entry problem.Assistant
Same object (PHASE0_vs_PHASE1_diffObject=0), yet HSC mismatches (4) ≈ losses (6). Let me test whether disabling the WAL eliminates the loss — the WAL write path may corrupt page 0.
Assistant
Let me simplify the test to just the loss check (removing diagnostic references).
Assistant
With
useWAL=false, the loss disappears (LOST=0)! So the WAL write path is the culprit. Let me examinecreateTransactionBufferandwriteTransactionToFileto see how they handle the page content.Assistant
writeTransactionToBuffercallsnewPage.getContent()returning a ByteBuffer and sets its.position()— mutating the page's ByteBuffer state. With WAL enabled this runs incommit1stPhasebeforeupdateMetadata/publish. Let me checkMutablePage.getContent()andBinary.putInt/putLong(absolute vs relative).Assistant
putInt/putLong(index,...)are absolute, so the WAL's position mutation shouldn't corrupt writes. Let me look atwriteTransactionToFile— it may modify page state or content.Assistant
writeTransactionToFileonly setssetWALFileand does I/O — no content corruption. But it's the WAL path. Let me test whether the fsync (walFlush) is the factor by settingTX_WAL_FLUSH=0(NO sync).Assistant
With
TX_WAL_FLUSH=0(no fsync), the loss disappears! So the fsync latency during the WAL write is the trigger. This points to cache eviction during slow commits. Let me check the test JVM heap and MAX_PAGE_RAM.Assistant
Let me definitively rule out eviction by setting a huge MAX_PAGE_RAM and large heap, with WAL+fsync enabled.
Assistant
Even with 30GB heap and 8GB cache, the loss persists with WAL+fsync. So eviction is NOT the cause. The fsync blocks the commit. Let me check
PaginatedComponentFile.write(used by the flush thread) — it may mutate the page's ByteBuffer, racing with the deep copy.Assistant
Let me check
Binary.getByteBuffer()— whether it returns a cached/shared ByteBuffer, which could be mutated concurrently by the WAL write and the flush thread.Assistant
getByteBuffer()returns the cachedbuffer, andwriteTransactionToBuffermutates its position. Let me check whetherBinary.getLong(index)/readLongare absolute or relative to the buffer position — this could explain a torn read after the WAL write mutates position.Assistant
Let me check
getLong(index)andgetInt(index).Assistant
getLong(index)is absolute, so PUBR is correct — the published page 0 genuinely has HSC=0. Let me record phase0/phase1 content + identity AND the publish, matched reliably by (thread, loadVer=pubVer-1), to see the full picture for a reset publish.Assistant
Let me check for duplicate HSC reads in
updateHeaderStats(DIAG_P1) — two appends reading the same count would confirm a stale read.Assistant
I've confirmed the torn readCache entry: thread 129 read page 0 at version 63008 but count=1 (stale). So readCache's page 0 has high version + stale count. Let me instrument
putPageInReadCacheto see if the torn entry is created at put time.Assistant
CachedPage has no
getContent(). Let me usegetByteBuffer()and fix the DIAG_PUT declaration.Assistant
Let me add the DIAG_PUT declaration next to DIAG_PUB.
Assistant
TORN_PUTS=34570 — the puts THEMSELVES are torn! At put version 61434, the CachedPage has version 61434 but hsc=0, dpc=0 (initial content). So the MutablePage in modifiedPages has high version + initial content, meaning
getPageToModifyreturned a different object than what's published. Let me verify by comparing theupdateHeaderStatsobject identity vs the published (put) object identity, matched by (thread, version).Assistant
The PHASE1_vs_PUT line didn't print. The match might have found 0 (no phase1 found for puts, because the put.ver != phase1.ver+1, or the thread matching is off). Let me check — the put thread is the committing thread (db.commit() runs in the append's thread). The phase1 thread is the updateHeaderStats thread (also the append's thread). So same thread. And put.ver = phase1.ver+1.
But the match found nothing (no PHASE1_vs_PUT line printed). Let me check — maybe the puts list filtering or the p1map key. Actually the line should always print. Let me re-run and capture all output.
Actually — the grep didn't capture "PHASE1_vs_PUT". Maybe the test threw before printing it (e.g., the puts list or p1map had an issue). Let me check the full output.
Assistant
The PHASE1_vs_PUT line is missing. The test must be failing before that line (the puts analysis). Let me check the full output for an exception.
Assistant
I've definitively confirmed the root cause: torn readCache entries —
putPageInReadCacheproduces CachedPages with a high version but INITIAL content (hsc=0, dpc=0). This requires WAL+fsync. Let me re-examine the exact current state of the shard's appendSamples and the commit flow to design the fix.Assistant
Let me re-add a clean diagnostic comparing the
updateHeaderStatsobject identity vs the published (put) object identity, matched by (thread, version), to determine if modifiedMaps has two page-0 entries.Assistant
I made a diagnostic error — DIAG_PUT recorded the CachedPage identity, not the MutablePage. The earlier reliable comparison showed the published MutablePage == updateHeaderStats's object. So the SAME object's content reverts to initial between the write and the deep copy. The commit path runs
compressPage— let me check if it corrupts the page content.Assistant
Let me reconsider. The async flush has MORE loss than sync. Let me look at the existing concurrent-write test from the prior fix to understand the expected behavior and the intended design.
Assistant
This existing test uses
engine.appendSamplesdirectly with 8×200=1600 samples. Let me run it to confirm it passes (small scale), then check if the loss manifests at scale.Assistant
The existing test passes (1600 samples). Let me create a scaled-up version using
engine.appendSamplesdirectly (not SQL) to isolate whether the loss is in the engine path or the SQL path.Assistant
With
engine.appendSamplesdirectly, NO LOSS (96000/96000)! So the loss is SQL-path-specific. The SQL INSERT does something the direct path doesn't. Let me examine the insert execution plan.Assistant
The insert plan:
CreateRecordStep→SetDocumentStep→UpdateSetStep→SaveElementStep. Let me checkCreateRecordStep— it may allocate a RID/touch page 0 for the time series type.Assistant
The loss is SQL-path-specific. Let me check
newDocumentfor a time series type — it may allocate a RID/touch page 0.Assistant
newDocumentcreates aMutableDocumentwith null RID (no page 0 touch). Let me check whether the SQL command path begins an outer transaction. Let me add a diagnostic insaveToTimeSeries.Assistant
txActive=false— no outer transaction in the SQL path. So the SQL and direct paths both create a root tx inengine.appendSamples. The difference must be the schema: the direct test used no STRING tag, the SQL path has asid STRINGtag. Let me test the direct path WITH a STRING tag.Assistant
Direct path with STRING tag also has NO loss. So the loss is specific to the SQL command execution path. Let me test using the type's engine directly (bypassing SQL) to isolate whether it's the type's engine or the SQL command path.
Assistant
Using the type's engine directly (bypassing SQL) loses 24! But a freshly-created engine doesn't. So the type's engine's
databasediffers. Let me checkschema.getDatabase().Assistant
Using the type's engine directly loses 24, but a freshly-created engine doesn't. Let me run both back-to-back with a diagnostic comparing the engine's database instance to find the difference.
Assistant
FRESH engine: LOST=0; TYPE engine: LOST=20; same schema/database. So the difference is how the type's engine/bucket is created during the DDL. Let me examine
CreateTimeSeriesTypeStatement.Assistant
This is just the toString/copy. Let me find the actual
executemethod.Assistant
CreateTimeSeriesTypeStatementextendsDDLStatement. Let me check how DDL is executed — whether it wraps in a transaction orrecordFileChanges.Assistant
Let me check
DDLExecutionPlan.executeInternal— DDL is likely wrapped in a transaction.Assistant
Let me check
TimeSeriesTypeBuilder.create— it may wrap the type/bucket creation in a transaction orrecordFileChanges.Assistant
The type's engine is created inside
schema.recordFileChanges(() -> { db.begin(); initEngine(); db.commit(); ... }). This is the key —recordFileChangesmay defer page publishes. Let me check it.Assistant
recordFileChangesjust runs under the write lock. The type's engine is created insidedb.begin()/commit()+recordFileChanges, the fresh engine isn't. Let me re-run the comparison a few times to confirm the FRESH engine is consistently loss-free vs the TYPE engine.Assistant
FRESH is consistently 0; TYPE consistently loses. The difference is the DDL context (
recordFileChanges+db.begin/commit). Let me check the bucket's page-0 version/state right after creation for both.Assistant
Both have sampleCount=0 after creation. Let me directly compare the database instances and the bucket's page-0 version for TYPE vs FRESH.
Assistant
Both use the same
LocalDatabase. The difference is the DDL'sdb.begin()/commit()wrappinginitEngine(). The FRESH engine (no such wrapper) doesn't lose. Let me test removing that wrapper.Assistant
Removing the wrapper didn't fully fix it (still loses). Let me revert and re-add the torn-put diagnostic for the FRESH engine to see if it has torn puts, confirming the readCache mechanism differs.
Assistant
FRESH has 0 torn puts; TYPE has 23177 torn puts. The difference is
recordFileChanges(write lock) wrapping the TYPE engine's creation. Let me test wrapping the FRESH engine creation inrecordFileChanges.Assistant
FRESH (wrapped in recordFileChanges) still has 0 torn puts. So the difference is the TYPE engine's maintenance scheduler (
schema.getTimeSeriesMaintenanceScheduler().schedule(...)), which may run compaction (clearDataPagesresets hsc=0, dpc=0 — matching the torn puts!) concurrently with appends. Let me check the maintenance scheduler.Assistant
The maintenance scheduler runs
engine.compactAll()at 5s initial delay, andclearDataPagesresets page 0 to hsc=0/dpc=0 — exactly matching the "torn puts"! The FRESH engine has no maintenance. Let me verify: run the TYPE engine with FEWER appends (finishing < 5s, before the first compaction tick).Assistant
With 4800 appends (finishing < 5s, before the first compaction): LOST=0! So the maintenance scheduler's compaction causes the loss. Let me examine
TimeSeriesShard.compact()to find the race between compaction and appends.Assistant
The compaction has a window between Phase 0 (write lock) and Phase 4 (write lock) where NO lock is held and appends run. The "torn puts" (hsc=0, dpc=0) are compaction's
clearDataPages. Let me see Phase 4 (the clear) and how the sealed store count is updated.Assistant
The "torn puts" are compaction's
clearDataPages. Let me directly test: cancel the maintenance task right after creating the type, then run the appends. If the loss disappears, compaction is confirmed.Assistant
With the maintenance task cancelled, LOST=0! So the maintenance scheduler's compaction causes the loss. Let me examine how the compaction reads/captures samples —
readFullPagesForCompaction/readPagesRangeForCompaction.Assistant
The compaction reads samples per page (DATA_SAMPLE_COUNT) and seals them, then
clearDataPages. If the sealed store doesn't actually receive the data, it's lost. Let me checkcommitTempCompactionFileandgetTotalSampleCount.Assistant
commitTempCompactionFileswaps innewBlockDirectory. IfappendBlocksToTempFile(Phase 4a/4c blocks) doesn't updatenewBlockDirectory, those blocks are missing from the sealed store → data loss. Let me checkappendBlocksToTempFile.Assistant
appendBlocksToTempFiledoesdirectory.add(entry), so the directory is updated. The "torn puts" I found were actually compaction'sclearDataPages(legitimate). So the loss is in the compaction's data capture. Let me add a diagnostic counting samples sealed vs samples in the bucket before clear.Assistant
FOUND THE BUG! The diagnostic shows
phase4aPageCount=304, finalPageCount=304. Phase 4a reads pageslastFullPage+1..304(page 304, partial). Appends during Phase 4b add rows to page 304 (finalPageCount stays 304). Phase 4c readsphase4aPageCount+1..finalPageCount=305..304= nothing! So page 304's rows added during 4b are never sealed — thenclearDataPagesloses them.The fix: Phase 4a should read only up to
phase4aPageCount-1(full pages), and Phase 4c should re-read fromphase4aPageCount(capturing the partial page's full current content including 4b's additions). Let me revert the diagnostic and implement the fix.Assistant
Now let me see Phase 4c's read range.
Assistant
Now I'll implement the fix. The bug: Phase 4a reads the partial last page (page
phase4aPageCount), then Phase 4b (lock-free) appends rows to it, but Phase 4c reads onlyphase4aPageCount+1..finalPageCount— missing the rows appended to that partial page during 4b, which are then lost byclearDataPages.The fix: Phase 4a reads only the full pages (
lastFullPage+1 .. phase4aPageCount-1), and Phase 4c re-reads fromphase4aPageCount(capturing the partial page's full current content including 4b's additions).Assistant
Now let me verify the fix with the reproduction test (TYPE engine direct, with maintenance running).
Assistant
The fix works — LOST=0 across 3 runs with maintenance active. Now let me verify with the SQL INSERT path (the original issue reproduction) and higher concurrency.
Assistant
The fix works for the SQL path with 48×5000=240000 inserts (exact issue reproduction). Now let me remove my temporary test and run the existing timeseries test suite to ensure no regressions.
Assistant
The wildcard matched the disabled test. Let me run specific timeseries test classes.
Assistant
Those SEVER logs are teardown-related (flush thread vs closed files in crash/truncate tests). Let me check the actual pass/fail summary.
Assistant
All timeseries tests pass (0 failures, 0 errors), including
TimeSeriesConcurrentAppendCompactTestandTimeSeriesCrashRecoveryTest. Let me clean up the stale surefire report and review the final diff.Assistant
The diff is clean and minimal, aligning the implementation with the original design intent (the comment at line ~430 says Phase 4 should read the partial last page + new pages, but the implementation wasn't re-reading it). Let me do a final clean compile and re-run the key concurrent tests to confirm.
Assistant
All tests pass, including
TimeSeriesConcurrentAppendCompactTest,TimeSeriesCrashRecoveryTest, andTimeSeriesConcurrentWriteNoDuplicatesTest. Let me do a final verification of the git status and confirm only the intended file is changed.Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.