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 the relevant files mentioned in the issue.
Assistant
Now let me look at the TimeSeriesBucket.java to understand the appendSamples method and the slot RMW issue.
Assistant
Let me understand the transaction model - how nested transactions work and whether the nested commit actually publishes changes.
Assistant
So nested transactions push a new TransactionContext. When the nested transaction commits, it calls
current.getLastTransaction().commit(). Let me look at the TransactionContext.commit() to understand whether it actually publishes page changes or defers them to the outer transaction.Assistant
Now let me understand whether the nested transaction's commit actually publishes page changes. Let me look at commit1stPhase and commit2ndPhase.
Assistant
Let me look at the TimeSeriesEngine to understand how appendSamples is called and the relationship between databases.
Assistant
Let me look at the SaveElementStep to see how a SQL INSERT routes to appendSamples.
Assistant
Let me look at how
getPageToModifyworks in the transaction context and how pages are cached.Assistant
Let me find the regression test file mentioned in the issue.
Assistant
Let me first try to build and reproduce the issue. Let me check the build setup.
Assistant
Let me look at the PageManager to understand the version check and page caching.
Assistant
Now let me understand
getCachedPageandgetMostRecentVersionOfPageand how the read cache works.Assistant
Now I see the cache.
getCachedPagechecksreadCache.get(pageId). When thread A commits its nested tx,updatePageVersioncallspage.incrementVersion()and thenwritePageswrites the page and puts it in the readCache. So the readCache would have the updated page with count N+1.But wait —
page.useAsMutable()returns "a view of the page. THIS PREVENT CONCURRENCY ON THE BUFFER POSITION". Let me look at CachedPage and MutablePage to understand the buffer sharing.Actually, the key issue might be more subtle. Let me look at
getMostRecentVersionOfPage.Assistant
Let me trace how the TimeSeriesEngine is created and what database it receives.
Assistant
Let me look at how
database.transaction()works in the embedded case.Assistant
Let me look at
useAsMutable,modify(), and the buffer sharing between CachedPage and MutablePage.Assistant
Now let me look at CachedPage.useAsMutable to understand buffer sharing.
Assistant
Let me check
getTransaction()in LocalDatabase and DatabaseContextTL to understand the transaction stack.Assistant
Let me check
getWrappedDatabaseInstanceto see if it returns the same instance in standalone.Assistant
Let me build and reproduce. First, let me create a temporary enabled copy of the test to reproduce without modifying the original.
Assistant
The engine compiles. Now let me create a temporary test (enabled) to reproduce the issue without modifying the existing test.
Assistant
The surefire plugin isn't available offline. Let me try online mode or check what's available.
Assistant
Reproduced: 121 samples lost. Now let me understand the actual mechanism. Let me look at
writePagesand the async flush path.Assistant
Let me add debug instrumentation to understand the actual mechanism. Let me instrument
TimeSeriesBucket.appendSamples.Assistant
Now let me instrument
TimeSeriesBucket.appendSamplesto detect slot collisions:Assistant
Let me update the temp test to enable the diagnostic hook:
Assistant
The collisions are confirmed - the page version is high and advancing, but the slot read is stale. Let me add deeper debug to understand the transaction identity and whether the nested commit publishes. Let me instrument the shard and bucket:
Assistant
Let me add targeted debug in PageManager.updatePages to see what version is being published, and correlate. Let me set up clean instrumentation:
Assistant
Now let me add debug in the shard to log, after commit, the page version by re-reading. And in PageManager.updatePages to log published versions. Let me instrument PageManager.updatePages and updatePageVersion to log when ENABLED and fileId == TARGET_FILE_ID.
Actually, let me reconsider. The collision shows readVer for both prev and cur. In the earlier run, both were 239. Let me re-run with the prevReadVer captured to confirm both reads had the same version.
But the key question: after thread 168 commits, what version does the readCache have? Let me add a debug read AFTER commit in the shard: re-read the active data page's sample count and version using a fresh transaction (outside the lock? no, inside, before releasing lock).
Actually, let me add debug right after db.commit() in the shard (still holding appendLock): open a quick read transaction, read the active data page count + version, log it. This tells me what the next append will see.
Let me add a helper method to the bucket to read the active page count+version without modifying.
Assistant
Let me update the test to set the target file id and reduce the line budget. Let me get the bucket's fileId via the schema:
Assistant
No DIAG output? That means the page never had pageNumber==1 being updated, or the LINE_BUDGET got consumed by collisions before reaching updatePage logs... Actually the LINE_BUDGET is shared between collision and updatepage logs. The collisions might have consumed the budget. Let me check — actually no DIAG output at all means either TARGET_FILE_ID didn't match, or page 1 was never updated (maybe the data starts at a different page number), or the build didn't pick up changes.
Wait — exit code 0? But the test should fail (samples lost). Unless the test passed this time?? Let me check. Actually maybe the grep found nothing and the test... let me run without grep to see.
Assistant
No output at all? That's strange. Let me run without grep:
Assistant
The package is wrong. Let me fix:
Assistant
Let me simplify - remove the target file filter and log all page-1 updates:
Assistant
The UPDATEPAGE logs show each commit sees
pageVer == mostRecent(no conflict), version increments by 1 each append. But collisions happen at high versions. Let me check the page size and max samples per page:Assistant
The collisions happen right at version 239 (page-1-full boundary). Let me log every append's (pageNum, count, version) to see the actual sequence:
Assistant
Let me look at the full sequence, especially the page 1→2 transition and any count anomalies:
Assistant
The first 280 appends are clean. Collisions happen later. Let me revert to the collision detector and add the most-recent-version read at collision time to determine if it's a stale version or stale content:
Assistant
No collisions? Let me check if the test ran and lost samples:
Assistant
getImmutablePagereturns ImmutablePage whose getVersion() returns long? Let me check. Actually getVersion is probably int. The error is "long to int" at col 124.mostRecent = ...getVersion()— getVersion returns long? Let me cast.Assistant
Now I understand the bug. Page 1 (the first data page) gets reset to count 0 at version 239, even though it was full of 238 samples. This means
getOrCreateActiveDataPageread a staledataPageCount=0from the header and re-allocated page 1, destroying its contents. Let me instrumentgetOrCreateActiveDataPageto confirm:Assistant
Let me use a separate budget for the newpage log to avoid the collision detector consuming it:
Assistant
Let me re-read
getOrCreateActiveDataPagecarefully:Assistant
The bug is confirmed:
getOrCreateActiveDataPagereads a staledataPageCount=0at header version 60531 and resets page 1, destroying its samples. Let me add a focused dump at the anomaly to understand the stale read source:Assistant
The readCache itself has the header at version 57058 with
dataPageCount=0. A commit produced this. Let me check ifclearDataPagesor auto-compaction is involved:Assistant
Let me add a ring buffer to capture the appends leading up to the anomaly:
Assistant
No RING DUMP output? Maybe the anomaly didn't trigger because LINE_BUDGET=20 but the anomaly detection... Let me check if it ran. Maybe the test passed this time (no loss)? Or compilation issue. Let me run full.
Assistant
The test references removed DiagHook fields. Let me fix the test:
Assistant
The ring shows
dpc=251steady, then suddenlydpc=0at version 59847 (skipping 59846). The header'sdataPageCountis being reset to 0. Let me test a hypothesis: is async flush involved? Let me check the async flush config:Assistant
asyncFlush = trueby default. Let me empirically test with synchronous flush to see if it's involved. Let me check for a global config:Assistant
Let me empirically test the async flush hypothesis by temporarily disabling it:
Assistant
Still loses with sync flush - so async flush is NOT the cause. Let me revert and re-verify the transaction identity (nested vs outer):
Assistant
depth=2confirms nested tx is used. Let me check whether the outer transaction T0 also touches the bucket pages. Let me look at SaveElementStep:Assistant
Let me verify whether the nested commit's publish is visible to a fresh read immediately after commit (inside the lock). Let me add clean debug in the shard:
Assistant
Now let me also log the read in the bucket's getOrCreateActiveDataPage into the ring, and dump the ring when dpc drops. Let me add a ring entry at the read and dump on anomaly. Let me also reduce noise: only log when timestamps.length==1.
Let me update the bucket to add ring entries and anomaly dump.
Assistant
The smoking gun:
AFTCOMMIT ver=58341 dpc=245thenREAD ver=58342 dpc=0— a commit at 58342 setdpc=0but has NO AFTCOMMIT/READ log, meaning it's from a different code path.clearDataPages()setsdpc=0— this is compaction! Let me checkscheduleContinuousAggregateRefresh:Assistant
Let me check where
clearDataPagesis called and whether compaction is auto-triggered:Assistant
Let me search for who calls
compact()orcompactAll()— there may be an auto-maintenance scheduler:Assistant
There's a
TimeSeriesMaintenanceSchedulerthat auto-compacts. Let me look at it:Assistant
The maintenance scheduler auto-compacts at t=5s, during the inserts. Compaction's Phase 4 clears the mutable bucket, but appends after the snapshot are lost. Let me read
compactInternalfully:Assistant
Compaction is carefully designed to capture concurrent appends. Let me check if the maintenance scheduler can be disabled, to isolate whether compaction is the cause:
Assistant
Let me test by temporarily increasing the maintenance scheduler's initial delay so it doesn't fire during the test:
Assistant
With the maintenance scheduler disabled, NO loss (240000/240000). So concurrent auto-compaction is the trigger. Let me re-read the exact locking in
appendSamplesand compaction to find the race:Assistant
Root cause found! With compaction disabled, no loss. The bug is in the compaction-vs-append race: Phase 4c reads tail pages starting at
phase4aPageCount + 1, but appends during the lock-free Phase 4b write to pagephase4aPageCountitself (the partial last page). Those writes are missed by both 4a (snapshot before the writes) and 4c (starts after that page), then 4c clears the mutable — losing them.Let me look at
readPagesRangeForCompactionto understand its range semantics:Assistant
Confirmed the bug. Phase 4a snapshots pages
lastFullPage+1..phase4aPageCount(including the partial last page), and Phase 4c readsphase4aPageCount+1..finalPageCount— but appends during the lock-free Phase 4b write to pagephase4aPageCountitself, which neither captures. Then 4c clears the mutable, losing those samples.The fix: Phase 4a should read only the full pages (up to
phase4aPageCount - 1), and Phase 4c should read fromphase4aPageCount(inclusive) to capture the partial page's 4b delta.Let me revert all debug instrumentation and apply the fix:
Assistant
Good, all debug reverted. Now let me apply the fix to
compactInternalin TimeSeriesShard.java:Assistant
Now let me apply the fix. First, Phase 4a - exclude the partial last page:
Assistant
Now Phase 4c - include the partial page:
Assistant
Let me verify the changes:
Assistant
Now let me rebuild and run the repro test (compaction is now re-enabled since I reverted the scheduler):
Assistant
Let me recreate the temp test cleanly without DiagHook references:
Assistant
The fix works - 240000/240000 with compaction enabled. Let me run it multiple times to ensure stability (the issue was intermittent):
Assistant
Stable. Let me also test the multi-shard case and a longer run to trigger multiple compaction cycles:
Assistant
Multi-shard 960k inserts - no loss. Let me run a longer test to trigger 2 compaction cycles (>65s):
Assistant
Let me push to ~75s to ensure 2 compaction cycles fire during inserts:
Assistant
Excellent - 75s with 2 compaction cycles, 2.4M inserts, no loss. Now let me run the existing time series test suite to ensure I didn't break anything:
Assistant
There's a
TimeSeriesConcurrentWriteNoDuplicatesTest,BucketAlignedCompactionTest, andTimeSeriesAccuracyTest. Let me run the compaction and accuracy-related tests:Assistant
All 30 pass. Let me look at the existing
TimeSeriesConcurrentWriteNoDuplicatesTestto understand the difference and make sure my understanding is complete:Assistant
This test uses
engine.appendSamplesdirectly (no schema registration, so no auto-compaction) — it validates the appendLock, which my fix doesn't touch. Good.Let me run the broader time series test package to ensure nothing is broken:
Assistant
The pattern needs a different format. Let me use the package with
*or list the test classes. Let me use-Dtest='TimeSeries*,BucketAligned*,TagFilter*,Continuous*,WindowFunction*,AggregationMetrics*,CreateTimeSeriesTypeStatement*,DictionaryCodecOverflow*,PromQL*'etc. Actually, let me just run with the surefire includes for the package. Let me try-Dtest='*TimeSeries*,*Compaction*,*Bucket*,*Tag*,*Aggregate*,*PromQL*,*Window*,*Codec*,*Gap*,*Interpolate*,*Rate*,*Correlate*,*MovingAvg*,*FirstLast*,*Namespace*,*Phase2*,*Vector*'.Actually simpler: run the whole engine test suite for the timeseries package via surefire
<includes>. Let me just specify a broad pattern.Assistant
The broad run timed out (PromQL tests are slow). Let me run a focused set of compaction-relevant tests:
Assistant
All passing. Now let me clean up the temporary test files and review my final diff:
Assistant
The diff is clean and minimal. Let me do a final compile check and re-run the most directly relevant compaction tests together to confirm:
Assistant
All tests pass. Let me do a final review of the complete changed section to ensure correctness:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.