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 the relevant files mentioned in the issue.
Assistant
Let me look at the TimeSeriesEngine.java and the appendSamples / appendBatch methods.
Assistant
Let me look at the SaveElementStep and how transactions nest, plus the LocalDatabase.
Assistant
Now let me understand the transaction nesting. Let me look at LocalDatabase.begin and how nested transactions work.
Assistant
Now let me look at the PageManager's checkPageVersion and updatePageVersion methods to understand the version conflict check.
Assistant
Now I understand the issue. Let me think about the root cause carefully.
The problem: when
TimeSeriesShard.appendSamplesis called, it:- Acquires
appendLock(serializes concurrent appends on the shard) - Calls
db.begin()(which creates a nested TransactionContext if outer TX active, or a new one) - Calls which reads sampleCount, writes row, increments count
- Acquires
Assistant
Let me look at how
getWrappedDatabaseInstanceworks and the HA wrapper's commit behaviour.Assistant
So
RaftReplicatedDatabaseis the wrapped instance under HA. But in the embedded case (standalone), the wrapped instance is the same LocalDatabase. Let me confirm.Actually, the issue says reproduction is embedded too. Let me check whether in the embedded test,
getWrappedDatabaseInstance()returns the same instance.Actually, in standalone mode,
wrappedDatabaseInstanceis set tothistypically. Let me check the LocalDatabase constructor.Assistant
Let me look for the reproduction test file mentioned in the issue.
Assistant
Let me look at how
database.transaction()works and check whether the nested commit actually publishes.Assistant
Let me look at the CachedPage, MutablePage, and how pages are read/written in the cache.
Assistant
Let me build the engine module and run the reproduction test to confirm the bug. First, let me check the build setup.
Assistant
I have a working Maven. Let me first enable the test (temporarily) and run it to confirm the bug. Let me make a copy approach: I'll temporarily remove the
@Disabledto run it.Assistant
Compilation works. Now let me temporarily enable the test to confirm the bug.
Assistant
Let me restore the file and do the disabling more cleanly.
Assistant
I've reproduced the bug: 239998 / 240000 (2 samples lost). Now let me understand the actual mechanism. Let me add diagnostics to confirm whether the nested commit publishes the page. Let me instrument
TimeSeriesBucket.appendSamplestemporarily with a collision detector.Assistant
Let me add a temporary collision detector to understand the mechanism.
Assistant
This is very revealing. The pattern shows page
1:1having its count reset to 0 (prevSlot=239 but reading slot=0) while the page version is high (239+). This meansgetOrCreateActiveDataPageis re-initializing an existing page because it read a staleHEADER_DATA_PAGE_COUNT. Let me look atputPageInReadCacheto understand the caching.Assistant
The diagnostic over-reports because
lastSlotis a max. Let me improve the detector to track the last committed count per page and detect actual backward resets, plus check whether an outer transaction is active.Assistant
Let me restore the bucket file and instead add diagnostics to the shard to check the outer transaction state and whether the nested commit publishes.
Assistant
Let me look at
hasChanges()andgetModifiedRange()to understand if the nested commit actually publishes.Assistant
Let me check how
database.command()handles transactions — whether an outer TX is actually active when appendSamples runs.Assistant
Let me run the diagnostic to see the outer transaction state and read-after-commit value.
Assistant
The read-after-commit shows the nested commit publishes (
dataPageCountincreases). Let me restore the shard and add a targeted diagnostic ingetOrCreateActiveDataPageto detect when an existing page with samples gets re-initialized (the reset that loses data).Assistant
I found the smoking gun:
DIAG REINIT RESET page=1:1 existingCount=239 headerDataPageCount=0 totalPages=203. A stale read ofHEADER_DATA_PAGE_COUNT(read as 0 when it's actually ~202) causesgetOrCreateActiveDataPageto re-allocate page 1 and reset its count to 0. Let me capture the full picture — count of resets and the final loss.Assistant
The REINIT RESET is the mechanism — a stale
HEADER_DATA_PAGE_COUNTread. This run lost 162 samples with 195 resets. The resets cascade across pages. Let me look atgetCachedPagefully to understand why a stale header is read.Assistant
Let me add the header page version to the REINIT diagnostic to determine whether a stale (old) header version is being read.
Assistant
Hmm, no REINIT and no test result. The test might have passed or the output got filtered. Let me check the full output.
Assistant
The header version is high (48792) but
dataPageCount=0— a high-version header has a stale lowdataPageCount. This is a lost-update on the header page. Let me add a before/after-commit diagnostic in the shard to determine if the nested commit's publish is immediately visible to the page manager.Assistant
The same-thread publish is fine (
afterDPC >= beforeDPC). So the cross-thread read is stale. Something overwrites the readCache entry with a high-version but stale-content page 0. Let me examine the flush thread behavior, which might re-load stale pages from disk into the readCache.Assistant
So the flush thread writes pages to disk (
flushPage). Let me look atflushPageto see if it touches the readCache.flushPage(line 365 in PageManager). Let me look.Assistant
flushPagedoesn't touch readCache. The readCache is only updated byputPageInReadCache/loadPage, both giving the latest. Let me check whatdatabase.getTransaction()returns inappendSamples— whether it's the nested or outer tx.Assistant
Let me find the getTransaction() method (not getTransactionIfExists).
Assistant
Let me add a diagnostic at the REINIT moment comparing the nested-tx-read header version vs the readCache's current version of page 0.
Assistant
Hmm, the rcVer/rcDPC fields aren't showing. Let me check the actual output.
Assistant
The rcVer fields aren't in the output — my edit may not have applied. Let me check the file.
Assistant
My second edit didn't apply due to whitespace mismatch. Let me redo it with the exact text.
Assistant
The readCache genuinely has
dpc=0at version 55151 (headerVer == rcVer == 55151,rcDPC=0). So a commit wrotedpc=0at a high version — a lost update on the header. Let me instrumentupdatePageVersionto catch exactly which commit produces a high-version header with a lowdpc, and the nesting depth.Assistant
Wait,
page.readInt(40)— but MutablePage readInt adds PAGE_HEADER_SIZE. Let me check. In MutablePage,readInt(from BasePage) — let me check BasePage.readShort etc. Actually, the offsets in TimeSeriesBucket are "from PAGE_HEADER_SIZE". Let me check BasePage.readLong/readInt.Assistant
readInt(40)reads atPAGE_HEADER_SIZE + 40= correct HEADER_DATA_PAGE_COUNT. Let me build and run.Assistant
The smoking gun:
DIAG LOSTUPDATE file=1 commitVer=48044 dpc=0 sampleCount=0 nested=1. A top-level transaction (nested=1, no outer tx) commits the initial empty header (dpc=0, sampleCount=0) at a high version (48044), overwriting the real header. Let me capture the stack trace to find the exact code path.Assistant
The complete root cause: the
TimeSeriesMaintenanceSchedulerrunscompactAll→compact→compactInternal, which commits the mutable bucket header withdpc=0, sampleCount=0(clearing it) at a high version. This is the seed; then appends reuse physical pages and reset them. Let me examinecompactInternaland the maintenance scheduler.Assistant
The complete picture: compaction runs via
TimeSeriesMaintenanceSchedulerduring the test, and itsclearDataPages(Phase 4c) is the seed. Let me examine the maintenance scheduler to understand the timing.Assistant
The maintenance scheduler runs compaction every 60s (initial delay 5s), so it runs once during the ~20s test. Let me isolate whether compaction is the trigger by temporarily disabling
compactAll()in the scheduler.Assistant
Let me re-run and capture the surefire result properly.
Assistant
With compaction disabled, the test passes (no data loss). So compaction is the trigger. Now let me understand the exact race. Let me check whether the compaction's page reads use
getPage(read-only) orgetPageToModify(which would re-publish pages).Assistant
Compaction is the trigger. Let me re-enable compaction and check whether the append's outer transaction has modified pages (which would commit outside the read lock and race with compaction). Let me add a diagnostic.
Assistant
The outer tx has no modified pages. Let me check how
SELECT count(*)works for timeseries to understand what "lost" means, then add an end-of-test diagnostic scanning all physical pages vs the logical page count.Assistant
Let me add a decisive end-of-test diagnostic: scan ALL physical pages and the sealed store to determine if lost samples are orphaned (on pages beyond the logical count) or overwritten. Let me check the bucket/shard API available.
Assistant
Let me add a temporary diagnostic method to scan all physical pages, and call it from a temporary test addition. First, let me add the diagnostic method to the bucket.
Assistant
Now let me add a call to this diagnostic at the end of the test (temporarily).
Assistant
The physical scan shows 114 samples genuinely overwritten (no orphan pages; physSum+sealed = actual = 239886). So a page with samples is reset. The cascade reuses pages seeing
count=239(stale). Let me instrument every commit of the timeseries data pages to find who publishescount=239after a reset.Assistant
Let me filter the PGCOMMIT diagnostic to page 1 only and log its count sequence to detect a stale full-page re-publish.
Assistant
Page 1 fills normally (200→239). Let me search for a page whose count goes backwards (a reset after filling) — that's the loss.
Assistant
The physical scan confirms samples are overwritten, and the backward resets are the compaction clear + page reuse (sealed data, fine). The real loss is the compaction's lock-free Phase 4b window: appends add samples to the partial active page (phase4aPageCount) between Phase 4a's snapshot and Phase 4c, but Phase 4c only re-reads
phase4aPageCount+1..finalPageCount, missing those additions — they get cleared/overwritten. Let me examinereadPagesRangeForCompaction.Assistant
Let me verify the hypothesis directly: record the partial active page's count at Phase 4a and Phase 4c to confirm 4b additions are missed. Let me add a diagnostic to
compactInternal.Assistant
CONFIRMED!
DIAG 4BLOSS phase4aPage=235 count@4a=207 count@4c=239 finalPageCount=236 lostRows=32— and the test lost exactly 32 samples. Phase 4c reads onlyphase4aPageCount+1..finalPageCount(page 236), missing the 32 samples added to page 235 during the lock-free Phase 4b window. Those are cleared/lost.The fix: Phase 4a should read only the full pages (exclude the active partial page
phase4aPageCount), and Phase 4c should re-read fromphase4aPageCount(inclusive) to capture 4b additions. Let me first restore all files from backups.Assistant
All files restored. Now let me view the exact Phase 4a and Phase 4c code to apply the fix precisely.
Assistant
Confirmed and root-caused. Now let me apply the surgical fix:
- Phase 4a: read only the full pages
[lastFullPage+1 .. phase4aPageCount-1], excluding the active partial pagephase4aPageCount. - Phase 4c: re-read from
phase4aPageCount(inclusive) tofinalPageCount, so samples appended to the active page during the lock-free Phase 4b window are captured before the bucket is cleared.
- Phase 4a: read only the full pages
Assistant
Now let me also update the Phase 4a/4c comments that describe the old (buggy) behavior, to keep the code consistent.
Assistant
Let me update the Phase 4c section comment to reflect the new behavior.
Assistant
Now let me compile and run the regression test (with
@Disabledtemporarily removed) to verify the fix.Assistant
The test passes now. Let me run it a few more times to confirm it's stable (the bug was timing-sensitive/racy).
Assistant
The
-qflag suppresses the output. Let me run without-qand grep more carefully, or use a different approach.Assistant
The fix is stable across 3 runs. Now, per the instructions, I must not modify existing tests. The issue says the test is intentionally disabled and should be enabled once fixed — but since I shouldn't modify tests, I'll restore it to its original
@Disabledstate (the evaluation system will handle enabling it).Assistant
Now let me verify the only source change is the
TimeSeriesShard.javafix and review the diff.Assistant
The diff is clean and minimal. Now let me verify there's no separate append-path bug independent of compaction. Let me temporarily disable compaction again and run the test multiple times to confirm the append path is genuinely correct without compaction.
Assistant
Without compaction, the append path is correct (3/3 pass). So the only bug is the compaction partial-page-4b loss, which my fix addresses. Let me restore the scheduler (re-enable compaction) and the test (re-disable it), then verify the fix works WITH compaction enabled.
Assistant
With compaction ON and the fix applied, the test passes 4/4 times. The fix is solid. Now let me restore the test to its original
@Disabledstate (I must not modify tests).Assistant
Now let me run the existing timeseries test suite to make sure I didn't break anything (compaction, queries, etc.).
Assistant
Let me run the most relevant existing tests (compaction, accuracy, concurrent append/compact, shard/engine).
Assistant
All 38 tests pass, including compaction, accuracy, crash recovery, concurrent append/compact, and downsampling. Let me also run the broader timeseries test suite to be thorough.
Assistant
All 364 timeseries tests pass. Let me check for any HA/replication compaction tests that might assert on sealed-store contents.
Assistant
There are HA timeseries compaction tests, notably
RaftBulkInsertCompactionRaceIT(directly relevant). Let me check its setup and try to run it.Assistant
This test is about LSM index compaction, not timeseries. The relevant ones are
RaftTimeSeriesReplication3NodesITandRaftTimeSeriesOversizedSealedIT. Let me check their tags and whether they can run here.Assistant
No Docker available, and these HA tests are
@Tag("slow")and extendBaseRaftHATest(which likely uses Testcontainers/Docker for a 3-node cluster). So they can't run here. But they're tagged slow and require Docker.Let me check
BaseRaftHATestto see if it uses Docker or in-process servers.Assistant
BaseRaftHATestuses in-processArcadeDBServerinstances (not Docker), so HA tests can run. Let me run the HA timeseries compaction tests, which directly exercise my fix's code path under replication.Assistant
The
-amruns the test goal on dependency modules too. Let me install dependencies first, then run only the ha-raft module.Assistant
Excellent! The HA timeseries replication tests pass (4 tests, including 3-node replication and oversized-sealed). The fix doesn't break HA replication. Let me do a final review of the complete diff.
Assistant
The diff is clean and minimal. Let me verify there are no leftover diagnostic remnants in any source files.
Assistant
No diagnostic remnants in the timeseries files (the matches are pre-existing "DIAGONAL"/"DIAGNOSTIC" in unrelated files). Only
TimeSeriesShard.javais modified. Let me verify the test file is restored to its original state.Assistant
The test file is unchanged (restored to its original
@Disabledstate). Let me do a final full compile to confirm everything builds cleanly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.