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 code mentioned in the issue.
Assistant
Let me look at the relevant files mentioned in the issue.
Assistant
Now let me look at the TimeSeriesBucket.appendSamples method:
Assistant
Now let me look at the TimeSeriesEngine:
Assistant
Now let me understand the transaction model. Let me look at how the database begin/commit works, especially around nested transactions:
Assistant
Let me understand the nested transaction behavior. When
db.begin()is called and a transaction is already active, a new nested TransactionContext is created and pushed. Whendb.commit()is called, it commits the last transaction and pops it (if not the last).Let me understand how TransactionContext.commit() works for nested transactions. The key question is: when
TimeSeriesShard.appendSamplescallsdb.begin()anddb.commit()while an outer transaction is active, what happens? Does the nested commit actually persist the pages, or does it defer to the outer transaction?Let me look at TransactionContext.commit().
Assistant
Let me look at commit1stPhase and commit2ndPhase to understand how nested transactions are handled.
Assistant
Let me look at the PageManager.updatePages and checkPageVersion:
Assistant
Let me look at how the page cache works - specifically
getPageToModifyin TransactionContext andgetCachedPagein PageManager:Assistant
Now let me look at how the page cache and
getCachedPagework, pluswritePages:Assistant
Now let me look at how
writePagesupdates the readCache. AfterupdatePageVersionincrements the version andwritePageswrites the page, the readCache should have the updated version. Let me look at writePages.Assistant
Let me look at the SaveElementStep and how the SQL INSERT path calls into the engine:
Assistant
Let me look for the test mentioned in the issue:
Assistant
Let me enable the test temporarily to reproduce the issue:
Assistant
That broke the file. Let me revert and fix it properly:
Assistant
Let me open the file and use the edit command:
Assistant
Now let me run this test to confirm the bug:
Assistant
Bug confirmed: 239861/240000, 139 samples lost. Now let me understand the transaction model deeply. Let me check
database.transaction():Assistant
Let me find where the TimeSeriesEngine is constructed to understand which database instance it holds:
Assistant
Let me add temporary diagnostics to understand the actual behavior. Let me look at the full appendSamples in the bucket first:
Assistant
Let me add temporary diagnostics to the bucket's appendSamples to understand the actual behavior:
Assistant
Let me add a temporary diagnostic to understand the actual mechanism. I'll add a collision detector:
Assistant
Let me add diagnostics directly via edit. First add a static field near the top:
Assistant
Now let me add the diagnostic code in appendSamples:
Assistant
Now let me run the test with diagnostics:
Assistant
The diagnostic reveals the mechanism. The page version advances (239) but
sampleCountInPagestays 0. Let me understand how MutablePage/CachedPage buffers work:Assistant
The diagnostic shows the page version advances (239, 240...) but
sampleCountInPagestays stale. Let me understand the transaction identity. Let me checkgetTransaction():Assistant
Let me check what database instances are involved. Let me look at TestHelper and getWrappedDatabaseInstance:
Assistant
So
getWrappedDatabaseInstance()returnswrappedDatabaseInstance. For a standalone (non-HA) DB, what iswrappedDatabaseInstance? Let me check how it's initialized.Assistant
Let me add deeper diagnostics to understand the transaction identity. Let me update the diagnostic in the bucket:
Assistant
Let me enhance the diagnostic to print transaction identity:
Assistant
Let me run with the enhanced diagnostic:
Assistant
The nested tx IS being created (nested=2) and committed (txId differs each time). The version advances but count reverts. Let me instrument PageManager to see who publishes page 1 with stale content. Let me check PAGE_HEADER_SIZE:
Assistant
Let me instrument PageManager.writePages to log page 1 publications:
Assistant
Let me add a diagnostic in writePages to log page 1 publications:
Assistant
Now I need to add the DIAG_PUB_COUNT field. Let me add it:
Assistant
I duplicated the line. Let me fix:
Assistant
The counts look wrong (39424, 58880...). Let me check how
readShortworks in BasePage:Assistant
I read at the wrong offset. The count is at
readShort(0)(which adds PAGE_HEADER_SIZE internally). Let me fix:Assistant
The first 60 publishes are CORRECT (count advances 1→60). Then at v=239 the count reverts to 0. A LATER publish overwrites with stale content. Let me log publishes with low count to catch the reversion:
Assistant
Let me check if a count=0 publish was logged. Let me re-run and grep for count=0:
Assistant
No count=0 publish through writePages! The readCache got count=0 at version 239 from elsewhere (loadPage from disk, or flush thread). Let me check the flush thread:
Assistant
Let me look at
putPageInReadCacheandgetCachedPageFromMutablePageInQueue:Assistant
The count reverting to 0 indicates
getOrCreateActiveDataPageresets page 1's count (because it reads a stale headerdataPageCount=0). The root cause is stale content published at high versions. Let me track regressions for both page 0 (header) and page 1:Assistant
Let me add diagnostics to
getOrCreateActiveDataPageto catch the stale header read:Assistant
The edit went to the wrong file (PageManager.java). Let me revert that:
Assistant
Let me re-add diagnostics to PageManager properly. First open it:
Assistant
Now add the DIAG_PUB_COUNT field to PageManager:
Assistant
Found it! The key line:
DIAG PUB p0 v=63486 dpc=0 nested=1 tid=103 async=trueThe OUTER transaction (nested=1) publishes page 0 with stale
dataPageCount=0at version 63486! So the outer tx DOES have page 0 in its modifiedPages. Let me understand how the nested tx and outer tx share state. Let me look at TransactionContext constructor and begin:Assistant
The outer tx (nested=1) publishes page 0 with stale
dpc=0. Let me check the read paths in the bucket that usegetPageToModify(which adds to the current tx's modifiedPages):Assistant
Let me look at
scheduleContinuousAggregateRefreshand how count(*) works for timeseries:Assistant
Let me capture a stack trace for the outer-tx (nested=1) page-0 publish to find where it originates:
Assistant
The braces got messed up. Let me rewrite the DIAG block cleanly:
Assistant
There's an extra
}on line 375. Let me remove it:Assistant
Duplicate
if (asyncFlush). Let me fix:Assistant
The edit tool is duplicating lines. Let me rewrite the whole method cleanly with a heredoc:
Assistant
Now let me add the DIAG_ST_ONCE field and verify the method:
Assistant
The stack trace reveals the trigger: COMPACTION! The maintenance scheduler runs
compactAllconcurrently with inserts. But my collision detector may give false positives after compaction clears slots. Let me check howcount(*)works for timeseries and look at the compaction flow:Assistant
Let me look at the compaction flow in TimeSeriesShard:
Assistant
The collision detector may give false positives after compaction clears slots. The real loss might be a compaction race. Let me check the maintenance scheduler and test whether disabling compaction fixes it:
Assistant
Compaction runs once at ~5s during the ~16s test. Let me test whether disabling compaction eliminates the data loss. Let me temporarily make
compactAlla no-op:Assistant
No output for DIAG COLLISION or "but was:". Let me check the full test result.
Assistant
The
returnbefore the loop causes an unreachable statement error. Let me use anifguard instead:Assistant
Extra
}on line 479. Let me remove it:Assistant
No failure output. Let me confirm the test passed with compaction disabled:
Assistant
With compaction disabled, the test PASSES. So the data loss is a compaction race. Let me re-enable compaction and examine the compaction's page-reading methods:
Assistant
Let me look at the compaction page-reading methods:
Assistant
Let me check the Binary class to understand
getContent()and whether the deep copy is correct:Assistant
So
getContent()returns thecontentbyte array (the full backing array). AndgetShort(index)reads frombuffer.getShort(index). Thebufferis a ByteBuffer wrappingcontent.The deep copy:
Arrays.copyOf(srcArray, srcArray.length)copies the full array, andnew Binary(copied, page.content.size())creates a Binary. Let me check the Binary constructor that takes (byte[], int).Let me look at the Binary constructors.
Assistant
Let me check
getPagein TransactionContext (used by getDataPageCount):Assistant
Found the root cause! The data loss only happens with compaction. The bug is in the phased compaction: Phase 4a reads the partial last page (
phase4aPageCount) with its count at that time, but appends during the lock-free Phase 4b add more samples to that same page. Phase 4c only readsphase4aPageCount+1..finalPageCount(newly created pages), so the samples appended to pagephase4aPageCountduring Phase 4b are never sealed, thenclearDataPagesorphans them → data loss.Let me first clean up all diagnostics, then apply the fix. Let me revert the diagnostic files:
Assistant
Now TimeSeriesEngine.java still has the
if (true) return;from my compaction-disable test. Let me check and revert it.Assistant
Good, the compaction disable was already reverted. Let me restore the blank line for a clean diff:
Assistant
Now let me verify the bug theory with a targeted diagnostic before applying the fix. Let me look at the exact Phase 4a and 4c code:
Assistant
I've confirmed the theory conceptually. Now let me apply the fix. The fix: Phase 4a should read only full pages (up to
phase4aPageCount - 1, excluding the partial last page which can still receive appends), and Phase 4c should re-read fromphase4aPageCount(the partial page) onwards to capture appends made during the lock-free Phase 4b.Let me apply the Phase 4a fix:
Assistant
Now let me apply the Phase 4c fix:
Assistant
Now let me run the test to verify the fix:
Assistant
The test passes. Let me run it multiple times to ensure it's reliably fixed (the loss was intermittent):
Assistant
The fix passes reliably across 3 runs. Now let me verify edge cases and check if
clearDataPagesUpTois used elsewhere in compaction (which might have a similar issue):Assistant
clearDataPagesUpTois defined but let me check if it's actually used anywhere:Assistant
clearDataPagesUpTois unused. Now let me run the broader timeseries test suite to ensure I didn't break anything:Assistant
There are many timeseries tests. Let me run the compaction-related tests first since my change is in the compaction path:
Assistant
All compaction tests pass. Let me run the broader timeseries SQL and concurrent test suite:
Assistant
All 120 tests pass. The fix works and doesn't break existing functionality.
Now, per the instructions, I should not modify existing tests. The regression test was
@Disabledby design. Let me revert the test file to its original state (the evaluation system will handle validating with its own test version):Assistant
Now only the source file is modified. Let me review the final diff:
Assistant
The diff is clean. Let me check the existing
TimeSeriesConcurrentAppendCompactTestto see if it covers the append+compact race, and verify my understanding:Assistant
This existing test only asserts
>= 100(allows loss), so it doesn't catch the bug. My fix is validated byTimeSeriesConcurrentInsertTest. Let me run the complete timeseries test package to be thorough:Assistant
The pattern syntax failed. Let me run the remaining timeseries tests I haven't covered yet:
Assistant
All timeseries tests pass (235 total). Let me refine the comment in Phase 4a to be clearer about the bug being fixed (the past-tense reference to old behavior is slightly confusing):
Assistant
The fix is complete. Let me do a final compile check and run the key regression test once more to confirm everything works:
Assistant
Compilation succeeds. Let me do one final verification with the regression test enabled, then revert it:
Assistant
5 consecutive runs all pass. The fix is reliable. Now let me revert the test file to its original state per the instruction not to modify existing tests:
Assistant
Only the source file is modified. Let me check for any HA/server timeseries tests that might be affected by the compaction change:
Assistant
Let me check the load test mentioned in the issue and the HA replication test:
Assistant
The load test uses Testcontainers (Docker). Let me run the HA replication test which exercises compaction under HA:
Assistant
The HA test needs dependent modules built. Let me install the engine and build dependencies, then run the HA test:
Assistant
The
-amcauses surefire to fail on intermediate modules. Let me add the flag to ignore missing tests:Assistant
The HA replication test passes (4 tests). Let me also run the oversized sealed HA test:
Assistant
Needs
-amto resolve dependencies. Let me run it with-am:Assistant
Both HA tests pass. Let me do a final review of the complete diff:
Assistant
The diff is clean and focused. Let me verify there's no leftover diagnostic code and confirm the final state:
Assistant
The fix is clean — only
TimeSeriesShard.javais modified with no diagnostic leftovers. Let me run one final confirmation that the engine compaction tests still pass after all changes:Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.