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)
CREATE 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}:{"language":"sql","command":"INSERT INTO sensor SET ts=<unique>, sid='s<thread>', v=<i>"}SELECT count(*) FROM sensorreturns short by out of 80000 across runs. - Observed on
Assistant
I'll start by exploring the repository structure and understanding the relevant files mentioned in the issue.
Assistant
Now let me look at the
PageManager.updatePageVersionmethod and theTransactionContextto understand the version conflict mechanism:Assistant
Now let me understand the transaction context and how nested transactions work, specifically how
getPageToModifytracks page versions:Assistant
Now let me understand how nested transactions work - how
LocalDatabase.begin()pushes a nested TransactionContext:Assistant
Now let me understand the core issue. Let me look at how the nested transaction's commit works with the page versions. Let me look at the full append path and the
getMutablePage:Assistant
Now I understand the mechanism. Let me understand the key issue. Let me look at how
getCachedPageworks to understand the staleness:Assistant
Now I understand the caching mechanism. Let me trace through the key issue. The
appendSamplesinTimeSeriesBucketreadsdataPage.readShort(DATA_SAMPLE_COUNT_OFFSET). Let me understand the flow:The key issue is in
TimeSeriesShard.appendSamples: It callsdb.begin()/mutableBucket.appendSamples(...)/db.commit()while holdingappendLock. But the nesteddb.begin()is nested inside the outer transaction (the request transaction). Sodb.commit()of the nested transaction actually commits the innerTransactionContext.Wait, let me re-read the issue. The issue says: "The append commit is nested inside the enclosing request transaction, and the durable publish is effectively deferred to the outer transaction commit". Let me verify this by understanding nested transaction commit.
Assistant
Now let me understand the key issue. When
db.begin()is called nested, a newTransactionContextis pushed. Whendb.commit()is called, it commits the innermost (top) transaction. Let me confirm what happens when the outer transaction commits.Let me trace the actual flow with a careful analysis. The key concern is: when
appendSamplesruns the nesteddb.begin()/append/db.commit()while holdingappendLock, does thedb.commit()actually publish the page (commit2ndPhase -> updatePages), or is it deferred?Looking at
commit(): it callscommit1stPhase(true)thencommit2ndPhase(phase1). Incommit2ndPhase, it callsdatabase.getPageManager().updatePages(...)which actually writes the pages. So the nested commit DOES publish.But wait - the issue says the publish is deferred to the outer transaction. Let me re-read. The issue says the nested commit on
getWrappedDatabaseInstance()- which is the HA wrapper. Let me check whethergetWrappedDatabaseInstance()for a non-HA (standalone) database returns the same instance.Assistant
So in standalone mode,
getWrappedDatabaseInstance()returnsthis. The nested commit DOES publish immediately (commit2ndPhase -> updatePages). So the issue analysis here is about the read-cache staleness.Let me trace the actual mechanism. The
appendLockserializes appends per shard. So how can there be a stale read? Let me think...The
appendLockis held duringdb.begin()/append/db.commit(). Withindb.commit(), thecommit2ndPhasecallsupdatePageswhich writes pages and increments version in the readCache.But wait - the issue is the readCache. When thread A holds
appendLock, does thegetPageToModifyingetOrCreateActiveDataPageread from readCache? Yes -getMutablePage->getCachedPage->readCache.get(pageId).The key insight: After thread A commits (inside appendLock), it calls
updatePageswhich writes the page. Let me check whether the readCache is updated synchronously insideupdatePages:Assistant
Now I need to understand the critical path. Let me check
asyncFlush. Let me look at whether the default is async:Assistant
So
asyncFlushistrueby default. So inwritePages, with async flush:putPageInReadCache(new CachedPage(page, true))- puts a new CachedPage in the readCache with the updated content and incremented version.flushThread.scheduleFlushOfPages(updatedPages)- schedules disk write.
Now let me understand
CachedPage(page, true)- thetruemeans it's from a mutable page:Assistant
Let me look at how
database.transaction()works and the nested transaction behavior:Assistant
Let me look deeper at how nested transactions handle their pages - whether they merge into parent or publish:
Assistant
Let me look at the flush thread and how it handles pages in the queue:
Assistant
Let me look at how the TimeSeriesEngine gets its database instance and how LocalTimeSeriesType creates it:
Assistant
Let me check the build setup and try to reproduce by running the disabled test:
Assistant
The mvnw works with HOME set. Let me first build the engine module offline-ish. Let me try to compile the engine and run the test. First, let me check if there's mvnd.
Assistant
Let me first try to compile the engine module to make sure the environment works:
Assistant
The engine compiles. Now let me create a reproduction test that's smaller/faster to confirm the bug. Let me first enable the existing disabled test temporarily and write a faster diagnostic version:
Assistant
Need to download the surefire provider. Let me try online mode:
Assistant
I reproduced the bug: 113 samples lost, 0 errors, all committed. Now let me add diagnostics to understand the exact mechanism. Let me instrument
TimeSeriesBucket.appendSamples:Assistant
Let me add a diagnostic collision detector directly to the appendSamples method temporarily:
Assistant
The collisions shown are false positives (normal serialized advancement). Let me improve the detector to track the actual committed count per page and detect genuine stale reads:
Assistant
Excellent! The smoking gun: a thread reads
readCount=0(slot 0) on a page atreadVer=239wherelastWrittenCount=239. So a page that has 239 samples is read back with count=0. Let me instrumentgetOrCreateActiveDataPageto understand the page lifecycle:Assistant
The mechanism is now clear: a thread reads a STALE
HEADER_DATA_PAGE_COUNT(reads 0 when it's actually 244), causinggetOrCreateActiveDataPageto reuse and re-initialize a full data page (wiping 239 samples). The header version is 58241 but content says dataPageCount=0 — an inconsistency. Let me investigate how page version vs content can mismatch:Assistant
Let me add a diagnostic to check whether the header page's version field matches the version stored in its content buffer (to confirm the version/content mismatch):
Assistant
The mechanism is confirmed: a stale
HEADER_DATA_PAGE_COUNTread causes a full data page to be re-initialized (wiping samples). Let me test whether disabling async flush (the suspected eviction race) fixes it. Let me check the config:Assistant
Let me restore the bucket file and test the hypothesis that synchronous flush fixes the staleness. Let me modify
TimeSeriesShard.appendSamplesto disable async flush:Assistant
Now let me find the
appendSamplesmethod inTimeSeriesShardand test the synchronous flush hypothesis:Assistant
Synchronous flush fixes it (0 lost). The bug is async-flush related. Let me add a diagnostic to understand whether the nested commit actually publishes, by re-reading the header fresh after commit:
Assistant
The publish works (postcommit fresh read shows correct values), but the next thread's
getPageToModifyreads stale. Let me instrumentTransactionContext.getPageToModifyto find the source of the stale page:Assistant
The
!in bash is causing history expansion. Let me write the python script to a file instead.Assistant
The header (fileId=1) is read from the page manager with
dpc=0, sampleCount=0butver=57934— content is initial but version is high. Let me check whetherfile.writewrites only a partial range (the modified range), which could cause version/content divergence on disk:Assistant
Let me check how
BasePage.equalsworks, sincepageIndex.remove(key, value)depends on it (this could cause the wrong version to be removed):Assistant
clearDataPagessetsHEADER_DATA_PAGE_COUNT = 0! Let me check if compaction runs automatically and could race with appends:Assistant
Let me check if there's automatic/background compaction that could run during the test:
Assistant
There's a
TimeSeriesMaintenanceSchedulercallingcompactAll()automatically. Let me check its scheduling:Assistant
Compaction's
clearDataPagessetsdpc=0, and the maintenance scheduler runs compaction at 5s. Let me isolate whether compaction is the trigger by disabling it temporarily:Assistant
Compaction is the trigger; async flush is required (sync flush fixes it). The stale read comes from the page manager (
src=db). Let me restore files and add a focused diagnostic inloadPage/getCachedPageto find the exact sub-source (readCache vs pageIndex vs disk) of the stale header:Assistant
No DIAG GETCACHE output, but also no ACTUAL. The test may have failed to compile or the grep didn't catch. Let me run once and capture full output.
Assistant
contentis private in CachedPage. Let me use the publicuseAsImmutable()accessor:Assistant
The stale read comes from
src=cache(readCache hit) with the compaction-cleared header (dpc=0). This means an append's commit isn't updating readCache. Let me check how the modified range is tracked on writes (whether header writes are detected as modifications):Assistant
Writes do update the modified range. Let me add a postcommit diagnostic to
appendSamplesand correlate with the getcache diagnostic on the same run:Assistant
The early dpc=1 entries are correct (page 1 filling). Let me look at the later part around the stale read (high version) to correlate:
Assistant
So the stale read is
DIAG GETCACHE src=cache fileId=1 dpc=0 sampleCount=0 fver=43195 thread=136. So at version 43195, the readCache has dpc=0, sampleCount=0 (compaction's clear header). And thread 136 reads it fromsrc=cache(readCache hit).So compaction's clear committed header (dpc=0, sampleCount=0, version=43195) is in readCache. And thread 136 reads it.
Now, let me find the POSTCOMMIT entries around version 43195 to see what appends did. Let me look at the lines around the stale read in the full output.
Let me get the context (a few lines before and after the stale GETCACHE line at fver=43195).
Assistant
Let me directly find which samples are lost. Let me restore files and add a precise diagnostic recording each append's (ts, pageNum, slot, readDpc, readHdrVer), then scan for missing samples:
Assistant
MAX_PAGE_RAM is set to 16MB. Let me test if bumping it (no eviction) fixes the bug, confirming eviction is the cause:
Assistant
The cache is huge (~1.6GB, bucket is ~1MB), so eviction is NOT the cause. The stale read persists in readCache. Let me directly find the lost samples by recording each append and scanning after:
Assistant
Now let me add a scan at the end of the test to find which recorded appends are missing from the bucket. Let me update the repro test:
Assistant
No output. The test might have an issue (the
rs.next().toStats()is wrong). Let me simplify the test to just scan the recorded appends and check presence. Let me fix the test - remove the broken present-building loop.Assistant
Let me fix the test - remove the broken loop:
Assistant
All lost samples are on page 233, slots 110-226 — a contiguous range. So page 233 was re-initialized (count reset) after having ~226 samples. Let me record
readDpcandreadHdrVerto find the append that reinitialized page 233:Assistant
This run lost page 241; missing appends read
readDpc=241. Let me generalize the test to print all appends to the lost page with theirreadDpcto find the reinit:Assistant
Let me look at all the slot-0 appends to the lost page (each slot-0 write indicates a (re)initialization of that page):
Assistant
The missing appends are serialized (readHdrVer incrementing) yet lost — so later appends overwrote them. Let me look for DUPLICATE slot appends on the lost page (two appends to the same slot):
Assistant
240 appends to page 160 (more than the ~239 capacity) — so the count was reset (reinit) mid-way. Let me look at the slot distribution to find where it wraps/resets:
Assistant
Let me properly extract slot numbers and find duplicates (the overwriting appends):
Assistant
239 unique slots but 240 appends — one slot is duplicated. Let me find it:
Assistant
All 239 slots (0-238) were appended correctly yet 66 are missing — so the page's count ended up < 239. Let me check the eviction logic (
checkForPageDisposal) — maybe pages are evicted despite the large cache:Assistant
Eviction only happens at maxRAM (not reached here). Let me dump the final state of all data pages to see the exact inconsistency:
Assistant
Let me add a diagnostic dump method and call it from the test:
Assistant
The page dump shows counts look correct (239) but slots were overwritten (collisions) — confirming the slot-collision theory. The sync-flush fix is verified. Let me restore files and apply a clean fix. First, let me restore the bucket:
Assistant
Clean. Now let me apply the fix. The verified fix is to make the append transaction publish its page modifications durably under the
appendLock(synchronous flush), so the next serialized append always sees the latest state. Let me apply it and test with the full 48×5000 scenario:Assistant
Let me reconsider the best fix. The slot collision happens because the next serialized append reads the previous append's data-page count stale. Let me verify the sync-flush fix robustly with the full 48×5000 scenario and check timing:
Assistant
Sync flush at 48×5000 still loses 19 — so sync flush alone is NOT a robust fix. There's another race. Let me test whether compaction is still the trigger with sync flush, by disabling compaction:
Assistant
Compaction is the trigger regardless of flush mode (sync flush only reduces loss). The real race is in the compaction+append interaction. Let me restore compaction and study
compactInternalPhase 4:Assistant
I found the real bug! In compaction, Phase 4a snapshots the active page (
phase4aPageCount) partially, then Phase 4b (lock-free) lets appends add more samples to that same active page, but Phase 4c only re-reads pagesphase4aPageCount+1..finalPageCount— it NEVER re-reads the active page. So samples added to the active page during Phase 4b are cleared without being sealed → lost.Let me verify the original shard is restored and implement the compaction fix:
Assistant
Good, original restored. Let me check
readPagesRangeForCompactionto confirm inclusive bounds:Assistant
Confirmed:
readPagesRangeForCompaction(fromPage, toPage)is inclusive. Now let me apply the fix — defer reading the active page from Phase 4a to Phase 4c:Assistant
Now let me test with async flush (no sync flush) + compaction enabled at 48×5000:
Assistant
The compaction fix gives 0 lost with async flush at 48×5000! The Phase 4a/4c active-page loss was the sole root cause. Let me verify robustness with multiple runs:
Assistant
3/3 runs with 0 lost. Let me test with a longer run to trigger multiple compactions, and also verify the existing timeseries tests still pass:
Assistant
All 30 existing timeseries tests pass. Now let me run the exact disabled regression test (enabled as a temp copy) to confirm the acceptance criteria passes:
Assistant
The @Disabled is multi-line (the string spans multiple lines with escaped quotes). My regex didn't match. Let me look at the exact text and remove it properly.
Assistant
The exact disabled test passes. Let me verify with a longer run that triggers multiple compaction cycles (to be thorough about the per-compaction fix):
Assistant
960000 inserts over 68s (2 compaction cycles) — 0 lost. The fix is robust. Now let me clean up temp test files and review the final diff:
Assistant
Only
TimeSeriesShard.javais modified. Let me verify the scheduler is clean (compaction enabled) and review the final diff:Assistant
The diff is clean and minimal — only the compaction Phase 4a/4c fix in
TimeSeriesShard.java. Let me run a broader set of compaction-related timeseries tests to ensure nothing is broken:Assistant
All 34 tests pass, including
TimeSeriesConcurrentAppendCompactTest. Let me do a final review of the modified code in context:Assistant
Let me update the now-stale Phase 4c section comment to reflect the fix:
Assistant
Compiles cleanly. Let me do a final verification with the exact disabled test (enabled as temp) to confirm the final state passes, then clean up:
Assistant
Still 1 @Disabled (the multiline regex didn't match because of the escaped quotes spanning lines with
+). Let me use the exact-string replace I used before.Assistant
@Disabled removed (grep returned 0 matches). Let me run the final verification:
Assistant
The exact disabled test (enabled) passes. Let me clean up the temp test and verify final state:
Assistant
The final diff is clean and minimal. Let me run the full timeseries test suite to ensure nothing is broken:
Assistant
All 235 timeseries tests pass with 0 failures. The fix is complete and verified. Let me do a final review of the complete diff and submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.