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 inspect the transaction and time-series append implementations, locate any existing regression test, and identify the narrowest way to make slot allocation visible/serialized through the outer commit while preserving replication semantics. Then I’ll reproduce the loss, implement the fix, and run focused and broader tests.
- Assistant
The current comments assume nested commits publish independently, but the reported behavior demonstrates that this is false when routed through the HA/wrapped database: the wrapper folds the nested write into the parent transaction. I’ll inspect the wrapper/local transaction stack and the included test to determine whether locking can be extended to the actual outer commit (likely via transaction lifecycle hooks) rather than changing WAL routing.
- Assistant
There are transaction callbacks, so I’ll examine exactly how nested contexts merge callbacks/pages and how commit/rollback callbacks behave. A robust fix must release a shard lock on both outer commit and rollback, avoid deadlocking repeated inserts in one transaction, and continue to work when no outer transaction exists.
- Assistant
The existing callback mechanism is commit-only and therefore cannot safely hold
appendLockthrough an outer transaction (rollback would leak the lock). Before designing a new completion callback, I’ll reproduce the issue by running the supplied test with JUnit’s disabled condition temporarily deactivated, without modifying the test file. This also establishes whether standalone nested commits are truly deferred in this checkout. - Assistant
The Maven wrapper requires
HOMEin this environment; I’ll rerun with it set. - Assistant
The failure reproduces exactly (101 silently lost). Next I’ll trace which transaction owns mutable pages during nested append. The likely issue is that
TimeSeriesBucketcaches a mutable page obtained before/independently of the nested context, or the wrapped database resolves to the parent context; understanding that may permit a much smaller fix than lifecycle locking. - Assistant
TimeSeriesBucket.appendSamplesexplicitly receives aTransactionContext; I’ll inspect how it obtains that context and how pages are loaded/versioned. - Assistant
I’ll locate
getTransaction()dispatch and wrapper commit semantics; this should explain why a nested begin doesn’t isolate the bucket write. - Assistant
I found the wrapper in the HA module and will read both the default context lookup and wrapper begin/commit behavior.
- Assistant
The embedded database’s
wrappedDatabaseInstancemay still be a server wrapper even in-process tests. I’ll inspect the full Raft commit nesting logic and test database setup. - Assistant
The wrapper path confirms nested contexts are normally pushed, but the parent SQL execution evidently still owns or later republishes the stale page. I’ll inspect
SaveElementStepand page version application to identify whether the outer transaction has the same time-series page and can be prevented from overwriting it. - Assistant
I requested the wrong PageManager range; I’ll inspect the version check and transaction phase locking.
- Assistant
A better fit than retaining a Java lock is the transaction engine’s explicit file lock: it is held until commit/rollback, participates in ordered commit locking, and makes page loading plus publication atomic. I’ll inspect its API and semantics to see if the time-series shard can acquire its bucket file before touching the sample count.
- Assistant
Explicit locks can only be acquired once and before modifications, making them unsuitable inside
appendSampleswhen the outer SQL transaction may already have changes. Instead, the safest targeted strategy is likely a transaction-scoped lock callback. I’ll inspect rollback/reset and lock ownership details, then add a generic after-completion callback if needed. This allows the per-shard lock to remain held until the context that actually publishes the pages completes. - Assistant
Holding locks until arbitrary multi-shard transaction completion risks lock-order deadlocks. Before taking that route, I’ll inspect the page cache write/read synchronization. Since nested commit should be independent in standalone mode, a cache visibility bug could explain why a serialized successor reads an older version even after commit.
- Assistant
A plausible concrete race is that an older asynchronously flushing page replaces a newer cache entry after the serialized commit, making the next append read stale content while retaining a high/current version. I’ll inspect cache insertion and flush queue completion behavior, which aligns closely with the observed “high version but reused slot.”
- Assistant
This reveals a general lost-update enabler:
loadPage()can begin on a cache miss, obtain an old disk/flush-queue snapshot, and then unconditionally overwrite a newer cache entry installed by a commit. Subsequent version checks consult that regressed cache, so they accept the stale page and increment it—exactly why no conflict is raised. I’ll make cache installation monotonic by page version using an atomic map operation, preserving the newest page when a delayed load completes. Then I’ll rerun the regression before considering any time-series-specific lock changes. - Assistant
I’ll verify version types and then patch
putPageInReadCacheatomically, including correct cache-RAM accounting only when an entry is actually installed. - Assistant
I’ll apply the monotonic cache insertion. Equal-version replacement remains allowed for compatibility (equivalent committed snapshot/version); only a strictly older page is rejected.
- Assistant
The monotonic check reduced but did not eliminate losses. A delayed load can evidently carry the same version with stale content (for example, overlapping queued snapshots derived from the same base version), so version equality cannot safely justify replacement. Since page versions identify a committed snapshot, an existing equal-version cache entry should be retained. I’ll strengthen insertion to replace only with a strictly newer version and rerun.
- Assistant
The cache hypothesis is not sufficient, so I’ll revert that unrelated change. I’ll implement the issue’s required invariant directly: retain the per-shard append lock on the outer transaction until it commits or rolls back. To do that safely, I need transaction completion callbacks (not commit-only callbacks). I’ll add a minimal callback API to
TransactionContext, invoked on both successful commit and rollback/reset, and use an idempotent key so multiple same-shard inserts in one transaction don’t re-lock. First I’ll map every transaction termination path to avoid lock leaks. - Assistant
The termination points are compact: successful commits use
resetAndFireCallbacks, rollback and failed phase-2 usereset. HA also directly resets read-only/non-leader contexts. I’ll add completion callbacks and ensure all these termination paths fire them while preserving after-commit callbacks only on success. Then the shard can register unlock on the pre-existing outer context before creating the nested append context. - Assistant
I’ll implement the completion callback plumbing and transaction-scoped shard locking now. The callback key is shard-instance-specific, and reentrant calls in the same outer transaction immediately release only their extra lock hold; the original hold remains until completion. Transactions without an outer context retain the previous begin→commit lock scope.
- Assistant
I’ll update
TimeSeriesShard.appendSamplesso the lock’s lifetime matches the outer publishing transaction, and revise its documentation to describe the actual nested/HA behavior rather than the incorrect “independent commit” assumption. - Assistant
The transaction-scoped lock still has no effect, which strongly suggests concurrent commands are not sharing the same
TimeSeriesShardJava instance (for example schema/type engines are reconstructed per context), or the callback is attached to a different context than expected. I’ll inspect engine/shard ownership and add narrowly bounded temporary diagnostics if necessary to verify instance identity and lock lifetime. - Assistant
The remaining ambiguity is the nested context itself: even while the outer lock is retained, nested publication can still interact with the parent/cache in ways that bypass the intended ownership. The clean invariant is to write directly into an existing caller transaction, which both preserves atomic rollback semantics and guarantees HA includes pages in the parent WAL. Only callers without a transaction need an internally managed transaction. I’ll change the method accordingly; this removes the problematic nested transaction entirely for SQL inserts while retaining standalone append support.
- Assistant
Because a correctly retained shared lock makes slot reuse impossible, I’ll verify the key assumption directly with temporary diagnostics: print each distinct shard instance used and detect if more than one transaction is inside the supposedly retained critical section. I’ll remove these diagnostics immediately after the run.
- Assistant
The shard instance is shared. I’ll now verify whether the outer transaction is detected and whether callback registration actually retains the lock; if both are true, the stale read must originate below the Java critical section (most likely asynchronous page cache/flush ordering).
- Assistant
The lock is definitely retained across each outer transaction, so stale content is being reintroduced asynchronously after commit. I’ll inspect flush queue ordering and cache removal. A serialized append stream can still lose updates if async flush writes page versions out of order or removes a newer cache entry by page ID when an older queued version finishes.
- Assistant
The flush queue is FIFO, but the transaction lock ends before asynchronous durability, and queue/cache interactions can still expose older snapshots. As a diagnostic and potential correctness fix, I’ll force the outer transaction containing the time-series RMW to flush synchronously while the shard lock is held. This makes publication (disk and cache) complete before unlock; if the regression passes, it confirms the sealed-slot invariant requires synchronous page publication rather than only transaction completion.
- Assistant
Synchronous publication confirms the diagnosis and makes the regression pass. I’ll complete the no-outer path by making its internally created transaction synchronous as well, so direct concurrent engine callers have the same guarantee. Then I’ll inspect the diff for lifecycle correctness and run focused time-series, transaction callback, rollback, and HA compilation/tests.
- Assistant
The diff review exposed an important compaction edge case: if only
appendLockis retained, compaction can acquire its write lock before the outer transaction publishes, violating the existing documented invariant and potentially clearing uncommitted mutable pages. I’ll retain the compaction read lock in the same completion callback and release both together, including rollback/failure paths. - Assistant
The first synchronous run passed but the combined rerun failed, so there remains an older-snapshot source. One obvious source is shard header initialization, whose commit is asynchronous and can remain queued when ingestion begins. I’ll make all time-series shard initialization commits synchronous too and run the high-concurrency regression repeatedly, not just once.
- Assistant
The consistent failure despite serialized synchronous commits means each outer transaction has already cached an immutable time-series page before acquiring the shard lock. Locking publication cannot refresh transaction-local snapshots; after waiting,
getPageToModifyclones that stale cached page and reuses its slot. I’ll add a narrow transaction API to discard immutable pages for this shard file after acquiring the lock (without touching modified pages, so repeated inserts in one transaction remain intact), then rerun three times. - Assistant
I found the page-cache boundary and will add the targeted eviction method there, then invoke it only for an active outer transaction while the shard lock is held.
- Assistant
The transaction-local snapshot eviction is not enough, so the stale snapshot is in the shared page cache. My earlier monotonic cache experiment ran without transaction-scoped serialization, where equal-base concurrent writers still existed; it was inconclusive for the combined invariant. I’ll combine atomic non-regressing cache insertion with the transaction lock/direct write and rerun repeatedly. With serialized writers, every committed version is unique and delayed older/equal loads must never replace the current cache entry.
- Assistant
The combined cache safeguards still do not change the result. I’ll use the issue’s decisive diagnostic: record each
(file,page,slot)selected insideTimeSeriesBucket.appendSamplesand report reuse. This will confirm whether current failures are still slot collisions or whether the count discrepancy now has another cause. - Assistant
The raw detector shows massive slot reuse because compaction intentionally seals and reuses mutable pages; most reports are legitimate across compaction generations. This points to the remaining loss occurring at the mutable→sealed boundary rather than ordinary append publication. I’ll inspect compaction triggering and phase ordering, especially whether completion callbacks release the append and compaction locks in a window that lets the next append read a pre-clear snapshot.
- Assistant
The real race is now clear in compaction Phase 4: Phase 4a snapshots the current partial last page, releases the write lock, and Phase 4c only reads newly created pages. Samples appended to that same partial page during Phase 4b are neither in the snapshot nor considered “tail pages,” then
clearDataPages()deletes them. This exactly explains dozens of losses per maintenance cycle.I’ll fix Phase 4 by tracking the last page’s sample count at the snapshot and reading the appended row suffix from that page in Phase 4c, then merging it with newly created tail pages. This preserves the intended short lock windows and avoids blocking ingestion during compression.
- Assistant
I’ll discard the exploratory transaction/cache changes now that the exact loss window is identified, keeping the solution minimal and avoiding synchronous-flush performance costs or new callback APIs. The final fix will only add a compaction suffix read and use it in Phase 4c.
- Assistant
I’ll implement the suffix-aware read API in
TimeSeriesBucket, capture the Phase 4a last-page row count, and have Phase 4c include rows appended after that count plus all newly created pages before clearing the mutable bucket. - Assistant
The implementation is in place. I’ll update the Phase 4c comment to match the suffix behavior and run the 240k-row regression three times to verify deterministically across multiple maintenance cycles.
- Assistant
All three high-concurrency runs now store exactly 240,000 rows. I’ll run the broader time-series compaction suite and concurrent-write test, then compile the HA module because this compaction path participates in replicated schema/WAL handling.
- Assistant
The selected suite passed 19 tests, but the glob omitted
TimeSeriesConcurrentAppendCompactTest; I’ll run that explicitly and compileha-raftwith dependencies to validate the replicated compaction integration. - Assistant
The concurrent append/compact test passes, and the full HA reactor package succeeds. I’ll perform a final diff/status review, check for accidental diagnostics or generated changes, and verify the suffix reader’s boundary handling (partial page fills, new pages, and no appended rows).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.