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 first inspect the transaction and time-series append implementations, locate the referenced regression test if present, and check repository status/build conventions. Then I’ll reproduce the loss before choosing the narrowest transaction-safe fix.
- Assistant
The current code’s comments assert that nested commits publish independently, but the reported behavior indicates the HA wrapper merges/defer-publishes them into the outer request transaction. I’ll inspect the exact regression test and
begin/commitimplementations for local and wrapped databases to establish which object owns each transaction stack and where lock scope must extend. - Assistant
The regression test is present and disabled, so I can reproduce without modifying it by selecting the method while enabling disabled tests via a temporary copy would violate no-test modification. Better create a temporary external harness or use JUnit config? First, I’ll inspect transaction commit internals and HA wrapper behavior; likely the correct fix is to prevent the append from being nested in the caller transaction at all while preserving replication, or to retain shard ownership until the true outer commit, which is impractical across calls.
- Assistant
Local nested transactions do call
TransactionContext.commit()immediately, yet each new transaction may still begin from a stale page cached in its outer transaction. The key likely is not deferred disk publish but transaction-local page visibility: after nested commit, the suspended outer context remains based on its old page snapshot; subsequent append nested under another outer transaction reads its own stale snapshot/cached page. I’ll inspect page lookup and commit version checks, plus the existing concurrency test that may cover direct engine calls but not enclosing transactions. - Assistant
I need the omitted commit and page-fetch sections to confirm whether commits merge into a parent and whether nested reads consult parent pages. I’ll also inspect
DatabaseInternalfor any API intended to suspend transactions or run independent transactions, avoiding a bespoke low-level transaction manipulation. - Assistant
There is no public suspension API.
TransactionContextitself reads the global page manager, so standalone nested appends should see the prior nested commit unless the outer commit later overwrites the same pages. That matches the issue exactly: the SQL insert’s outer transaction also receives/retains the time-series pages (likely through HA transaction phase handling), and after releasing the shard lock its outer commit can overwrite a later append. I’ll locate HA classes and the SaveElement routing to see how page changes are attached to the outer transaction. - Assistant
The engine transaction does enforce version checks, so the missing conflict implies the wrapper alters commit semantics as described. I’ll inspect the HA wrapper’s commit and transaction-phase interception now, then design a fix that works both embedded and HA without changing generic page conflict semantics globally.
- Assistant
I found the Raft implementation where nested/schema-recording commits are specially buffered. I’ll read that path in full because the fix must not regress issue #4382’s follower replication guarantee.
- Assistant
The same bug is reported embedded, so I’ll reproduce the supplied test without editing it by deactivating JUnit’s
DisabledConditionthrough the launcher configuration. This is a high-volume test, but it is the most faithful baseline and will clarify whether current repository state still exhibits the loss. - Assistant
The Maven wrapper requires
HOME, which is unset in this environment. I’ll rerun with a temporary home directory; this is environmental and does not require repository changes. - Assistant
The baseline reproduced deterministically: 127 acknowledged samples were lost. Since this is standalone, I’ll trace
getOrCreateActiveDataPage()carefully. A likely subtlety is that some bucket metadata/page lookup occurs before the nested transaction starts or uses an outer transaction reference, causing the nested write to clone a stale page object despite serialized commits. - Assistant
The serialized transaction should read from the page cache updated by the prior commit. The observed “high advancing version but stale count” suggests the page manager may choose a stale queued async-flush copy or a cache race rather than an old-version conflict. I’ll inspect active-page creation and cache replacement/flush-queue ordering, especially whether delayed older pages can overwrite newer cache entries.
- Assistant
putPageInReadCacheunconditionally replaces entries, which could allow stale async flush/load publication, but serialized append commits update it before unlock. I need the exact bucket method (located earlier than expected) and flush queue implementation to distinguish a generic cache ordering bug from the transaction scope bug described in the report. - Assistant
The flush queue’s
pageIndexintentionally tracks the newest pending page and removes entries conditionally, so it is probably not publishing old versions. The report’s “sealed-slot” terminology may refer to async transaction phase 1: the append lock ends aftercommit()returns, but in Raft commit returns after phase2. Embedded still odd. I’ll inspect transaction helper semantics andPageIddatabase identity; perhapsdatabase.transaction()retries by reusing a first-level transaction whose commit is outside the callback. - Assistant
A plausible shard-lock bypass is multiple
TimeSeriesShard/engine instances created concurrently for the same type, each with its own lock. I’ll inspect time-series type engine initialization and schema lookup publication. The fact that low concurrency often succeeds and 48 threads collide despite an apparently sound lock strongly points to lock identity rather than lock duration in standalone mode. - Assistant
Engine initialization is synchronized and singleton, ruling out duplicate locks. The report explicitly states the nested append’s changes are attached to the parent transaction despite comments claiming otherwise. I’ll verify this empirically with temporary diagnostics in source (then revert them): log transaction depth and modified-page counts before nested begin, after nested commit, and at lock release for a reduced/concurrent run. This avoids guessing at transaction internals.
- Assistant
Before instrumenting, I noticed transaction reset may retain immutable page snapshots. If the thread’s reusable outer
TransactionContextreads the time-series page before the nested append andreset()does not clear that cache, later transactions on the same worker can repeatedly supply stale content. I’ll inspect reset fields and transaction cache lifetime; this could exactly produce a stale count carrying a current version metadata value. - Assistant
immutablePagesis cleared in reset, so it does not leak across transactions. I’ll now add minimal temporary diagnostics only for cases where the append has a parent transaction, and sample a bounded number of events. The key measurements are parent modified pages before/after and nested depth. After one short run I’ll restore the file. - Assistant
The targeted insertion landed in
appendSamplesas intended. I’ll add a bounded post-commit print and run a much smaller temporary JUnit invocation via a generated external test is hard; the full test is only 17 seconds, and 20 sampled lines are sufficient. Then I’ll restore immediately. - Assistant
The diagnostics disprove deferred parent publication for embedded: the nested commit independently publishes two pages and leaves the parent clean. Therefore the root is in page publication under concurrency. I’ll inspect
CachedPageconstructors and page buffer copying. If “immutable” cache entries share mutable backing storage with transaction or flush objects, later metadata/version mutation can pair a newer version with stale row bytes—exactly the observed conflict bypass. - Assistant
Cached pages are deep-copied correctly. A robust narrow experiment is to force time-series nested commits to flush synchronously while holding
appendLock. If that eliminates loss, the fault is delayed async page publication/flush ordering; if not, we continue. I’ll locate transaction async-flush controls and test this as a temporary patch. - Assistant
I’ll temporarily set only the nested append transaction to synchronous flush and rerun the regression. This is diagnostic, not yet the intended fix because synchronous disk I/O per sample would severely hurt ingestion performance.
- Assistant
Synchronous flush reduced but did not eliminate loss, so delayed disk I/O is not the primary cause. I’ll directly verify the lock invariant using a temporary static active-counter inside the critical section. Any value above one proves multiple shard instances/locks; otherwise I’ll record page/count monotonicity across serialized entries.
- Assistant
The critical sections never overlap and there is one shard lock. Therefore some commit is publishing a page image that did not include the prior commit even though it enters later. I’ll record the header count read at the start of each nested transaction and compare it with the count from the previous completed critical section. This will pinpoint whether stale state is already returned by page lookup or appears only later during commit/scan.
- Assistant
The one header reset to zero is explained by compaction: mutable data was sealed and the mutable bucket cleared under the shard write lock. That reveals an important confounder—the “reused slot” can be legitimate after sealing. The final count spans sealed + mutable, so the loss may occur at the compaction handoff, not ordinary append commits. I’ll inspect automatic compaction triggers and run with compaction effectively disabled if configurable, to isolate the path.
- Assistant
The actual lost-update window is now clear in compaction:
- Phase 4a snapshots through the current partial/active last page.
- It releases the write lock and Phase 4b compresses that snapshot.
- Concurrent inserts append more rows to that same page without increasing page count.
- Phase 4c reads only pages with numbers greater than Phase 4a’s page count, then clears all mutable pages.
- Rows appended to the already-snapshotted last page are neither in the snapshot nor reread, so they are silently discarded.
The fix is to snapshot only pages that are already full/immutable in Phase 4a and deliberately leave the active last page for Phase 4c under the write lock. I’ll implement that boundary adjustment and update the phase comments to document the invariant.
- Assistant
The fix preserves lock-free compression for all immutable full pages while moving at most one active page into the final locked phase. I’ll rerun the exact 48×5000 disabled regression twice to verify the deterministic loss is gone across compaction cycles.
- Assistant
Both faithful regression runs stored all 240,000 samples, whereas the baseline lost 127–143 per run. Next I’ll run the focused time-series suite, especially explicit and concurrent compaction tests, to ensure the changed phase boundary causes neither duplicates nor omissions and does not break crash recovery.
- Assistant
The focused suite passed; the logged async-flush/closed-file messages come from intentional crash-recovery tests and did not fail tests. I’ll run all engine time-series tests (disabled tests remain normally skipped) and then inspect the final diff/status for accidental diagnostic residue.
- Assistant
All time-series tests passed and no diagnostics remain. I’ll make the surrounding phase comments precisely match the new invariant (Phase 4a handles only newly full pages; Phase 4c handles the active page), then perform one final compile/diff review.
- Assistant
I’ll adjust only comments—no functional change—to avoid future maintainers reintroducing the active-page snapshot bug based on stale documentation.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.