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 first inspect the transaction and time-series append implementations, existing tests, and recent repository state. Then I’ll reproduce the concurrent loss with the narrowest available test before designing a fix that preserves nested transaction and replication semantics.
- Assistant
The source comments claim nested commits are independent, but the reported behavior demonstrates that this is false through the HA/wrapped transaction path when an outer transaction exists. I’ll inspect the regression test and transaction stack/commit implementations, especially wrapper behavior and page conflict checks, to identify an atomicity point rather than merely extending an in-memory lock around code that runs later.
- Assistant
The disabled regression is present exactly as described. Next I’ll read
LocalDatabase.begin/commit, wrapper resolution, and time-series engine batching to determine whether the safe fix belongs in shard append transaction selection or in generic conflict/version handling. - Assistant
Although
LocalDatabase.commit()independently commits the top transaction, page access may still resolve through the wrapper’s transaction or merge replication state into the parent. I’ll run the disabled test by deactivating JUnit’s disabled condition (without editing tests), then inspect HA wrapper transaction methods and the bucket’s page acquisition logic while the baseline runs. - Assistant
The Maven executable is misconfigured (missing Plexus launcher), so I’ll use the repository wrapper/build tooling if available. The bucket always asks the embedded database for the thread’s top transaction, which makes wrapper stack behavior central; I’ll inspect
ServerDatabaseand build scripts before choosing the test command. - Assistant
The history shows the regression test arrived with load tests after replication changes, making the HA wrapper likely responsible even in server mode, while embedded reproduction still needs explanation. I’ll inspect the relevant commits and wrapper implementation, and restore Maven functionality via the project’s documented wrapper configuration or system package layout.
- Assistant
The replication fix changed append commits from the embedded database to
getWrappedDatabaseInstance(). I’ll inspect the Raft wrapper’s commit recording semantics and run the baseline with./mvnw; this should confirm whether a targeted wrapper-aware append API is needed or whether page-version validation can safely enforce retry. - Assistant
The wrapper script requires
HOME, absent in this container. I’ll set a temporary home and retry, while reading the correctha-raftsource path. - Assistant
Baseline reproduced deterministically: 239,832/240,000 with all commits successful. Since this occurs in the engine module without Raft, I’ll trace
Database.transaction, SQL save routing, and page manager cache/version behavior. The key is to identify why the supposedly nested transaction’s dirty pages remain associated with or are later overwritten by the outer transaction. - Assistant
The SQL save itself only calls the shard append. I’ll now inspect exact outer transaction retry semantics and
PageManager’s cache update/version algorithm, because a stale cached immutable page after commit would explain why serialization alone fails and why version checks also miss the collision. - Assistant
Outer transactions are read-only for these inserts, so the loss likely comes from page cache publication rather than parent overwrite.
updatePageVersionvalidates under a manager lock, but I need to verify whetherwritePages(..., asyncFlush=true)publishes the updated bytes before unlocking or queues an asynchronous write whose stale source buffer can later replace cache state. - Assistant
Async commit does publish to read cache before releasing the page-manager lock, but
getCachedPagealso consults the flush queue. A queued older page could have a high/updated metadata interaction or replace a newer cache entry. I’ll inspect queue lookup and cache replacement rules in detail, then test whether forcing synchronous flush only for shard append removes the loss (as a diagnostic, not necessarily the final performant fix). - Assistant
Given the issue’s confirmed mechanism and the mismatch between apparent nested commit and effective visibility, the robust design is to bind shard serialization to the enclosing transaction’s lifecycle: acquire the shard lock before slot RMW and release only after the outer transaction commits or rolls back. I’ll inspect transaction callback APIs and locking semantics to implement this without leaking locks, while preserving immediate release when no parent transaction exists and allowing multiple appends in one transaction without self-deadlock.
- Assistant
Only post-commit callbacks exist; rollback discards them, so they cannot safely release a transaction-scoped lock. I’ll add a narrowly scoped transaction-completion callback facility (fires after commit or rollback), use a per-shard callback key to acquire each shard lock once per enclosing transaction, and ensure cleanup also occurs on commit failures. Before editing, I’ll inspect all reset/rollback paths so callbacks fire exactly once and never while transaction state is still mutable.
- Assistant
reset()is invoked from rollback, commit failure, read-only commit, and HA paths, so the safest generic primitive is a completion callback captured and fired byreset(). Butreset()is also public and can be called before HA phase-2, so firing there could release too early in Raft. Instead I’ll avoid broad transaction changes and first validate a simpler fix: make the nested shard append synchronous (tx.setAsyncFlush(false)) while holdingappendLock. If stale cache/queued-page publication is the cause, this directly makes slot visibility durable under the existing lock and preserves HA WAL generation. - Assistant
Synchronous flushing still loses rows (239,942), so cache flushing is not the root cause; I’ll revert that diagnostic change. A better existing mechanism may avoid custom completion callbacks entirely: transaction explicit file locks are held through commit/rollback and automatically released by
TransactionContext.reset(). I’ll inspect that API and use it to lock the mutable bucket file before reading the slot, which atomically covers RMW through actual publication and naturally participates in transaction cleanup. - Assistant
Explicit locks currently accept only record buckets/types, while a time-series mutable store is a paginated component, not a schema
Bucket. I’ll inspectTransactionContext.explicitLockconstraints and transaction-manager file locking; if safe, I’ll add a file-ID method to the concrete local lock and invoke it on the enclosing transaction before nested append. I must also account for nested transaction commit checking explicit locks and for Raft phase-1 lock release timing. - Assistant
An enclosing explicit file lock is viable only if nested commits can re-enter the same file lock without releasing the parent’s ownership. I’ll inspect the transaction manager lock implementation and
checkExplicitLocks; if ownership is not reference-counted, I’ll instead have the nested append write directly into the outer transaction while the explicit lock is held, eliminating nested lock interaction but requiring careful HA replication handling. - Assistant
I found the lock manager implementation; I’ll verify requester ownership/reentrancy now.
- Assistant
The lock manager is explicitly reentrant by requester: a nested commit returns only newly acquired locks, so it cannot release the outer transaction’s lock. I’ll prototype an explicit raw-file lock API, acquire the time-series component file lock on the outer transaction before the nested append, and run the regression. This should serialize slot access through outer commit/rollback and preserve nested Raft WAL replication.
- Assistant
To avoid widening the public remote lock interface, I’ll add raw file support only to
LocalTransactionExplicitLock, obtained from the currentTransactionContext. I’ll make acquisition idempotent for repeated appends to the same shard in one transaction. Transactions that already hold an unrelated explicit lock cannot safely expand their lock set (ordering risk), so the code will retain the existing append lock fallback in that unusual case rather than silently violate lock ordering. First I’ll validate the normal per-row path. - Assistant
The prototype deadlocks/timeouts, indicating nested and outer transactions do not share the same lock requester identity despite running on one thread (or ownership is otherwise not reentrant across transaction contexts). I’ll inspect
LockManagerand transaction requester initialization; this rules out using generic explicit file locks without deeper invasive changes. - Assistant
The requester is the same thread, so nested re-entry itself is safe. The timeout is a lock-order inversion I introduced: parent file lock was acquired before the compaction read lock, while compaction acquires the write lock before committing (and taking file locks). I’ll reorder acquisition to
compaction read → parent file → append lock, matching compaction’s ordering, then rerun. - Assistant
Even a transaction-lifetime file lock does not prevent collisions, proving the competing appends are not respecting file-lock ownership during slot reads (locks only gate commit, and stale images can be read before nested commit re-entry) or they use multiple shard instances. The collision despite the shard
appendLockstrongly suggests duplicateTimeSeriesEngine/Shardinstances are being created concurrently. I’ll inspect time-series type engine initialization and schema lookup caching; fixing singleton publication would be both narrower and consistent with the observed lock failure. - Assistant
The existing file-lock prototype is not sufficient because it guards commit but does not make the slot RMW and its effective publish one critical section. I’ll implement the issue’s direct invariant: retain the shard’s
appendLockuntil the enclosing transaction completes. This requires a generic after-completion callback that fires fromTransactionContext.reset()on both commit and rollback. The nested append re-enters the sameReentrantLock; its local unlock leaves the parent hold intact, and reset releases the final hold. I’ll ensure registration is keyed so multiple appends in one transaction acquire only once. - Assistant
Retaining the shard lock through the parent reduces but does not eliminate loss, so there is an additional publication race independent of transaction overlap. The most likely remaining race is the asynchronous flush queue: older page images can be flushed after newer versions, and
CachedPage(page, true)may share buffers. I’ll inspect page copy semantics and flush ordering. I’ll also run a fully global diagnostic lock around each insert through completion to determine whether any concurrency remains outside this shard instance. - Assistant
Cached pages are deep-copied, so buffer aliasing is ruled out. Before committing to a static cross-instance lock, I’ll instrument the regression temporarily to count distinct
TimeSeriesShardidentities and distinct parent transaction states seen during appends. This will confirm whether the current instance lock is fragmented and whether completion callbacks are attached to the expected outer transaction. - Assistant
Instrumentation confirms exactly one shard instance. The remaining mechanism is now clear in
PageManager: on a cache miss,loadPage()reads disk outside the cache map; a concurrent commit can publish a newer cached page, after which the loader unconditionallyput()s its older disk image over the newer entry. Subsequent transactions read stale bytes and stale version together, so version checks pass—exactly matching the report. I’ll discard the transaction-lock experiment and make cache publication version-monotonic with an atomic map update, then rerun the regression. - Assistant
The cache hypothesis did not affect the loss. The architectural fix is to stop committing SQL inserts in a nested transaction at all. When an enclosing request transaction exists, the shard should append directly to it and let the outer commit perform version validation. Concurrent transactions may calculate the same slot, but only one can commit that page version; the other raises
ConcurrentModificationException, triggering the existing transaction retry and recomputing the slot. This also naturally preserves HA replication in the parent WAL and correct rollback semantics. Standalone engine calls will retain the self-managed transaction path. I’ll implement this branch and rerun the full regression. - Assistant
Direct outer writes correctly surface conflicts, but at 48-way contention the finite retry budget is exhausted. The complete solution combines both properties: write into the outer transaction so version checks/HA WAL are correct, and retain the shard append lock through outer completion so ordinary single-row inserts do not conflict. I’ll reintroduce the completion callback solely for lock lifetime, then rerun. This should produce neither loss nor client-visible retry exhaustion.
- Assistant
The combined test unexpectedly reverted to silent loss rather than conflicts, so I’ll inspect the exact method: the earlier checkout/edits may have caused the direct-outer branch not to be present in the compiled source.
- Assistant
The source contains both mechanisms, so the remaining loss occurs after logical commit—most plausibly from asynchronous page flushing under cache eviction (the test creates ~700×64KB pages, enough to churn the configured cache). To validate, I’ll force synchronous publication on the enclosing time-series transaction while the retained shard lock is held. If this passes, the final fix can scope synchronous flush only to contended SQL time-series writes, guaranteeing the slot count is durable before another writer proceeds.
- Assistant
Synchronous flush reduces loss to 6 but does not fully solve it, so I won’t keep that performance-heavy workaround. I’ll verify whether the retained lock invariant itself is actually maintained by adding a temporary active-owner assertion around transaction completion. If the assertion shows overlapping owners, the callback lifecycle is wrong; if not, the remaining issue is page-state publication and needs an authoritative slot allocator.
- Assistant
The assertion confirms transaction owners never overlap: slot selection and commits are fully serialized. The remaining loss must be stale disk state resurfacing. The synchronous diagnostic still had one asynchronous predecessor—the shard header initialization commit—which can flush an older page after later synchronous commits. I’ll make all time-series shard initialization/append transactions synchronous as a diagnostic and remove instrumentation; if this passes, the durable fix is to prohibit out-of-order async publication for mutable time-series pages.
- Assistant
The missing count after strict serialization points to rollback/retry state leakage at page boundaries.
TimeSeriesBucket.getOrCreateActiveDataPage()callstx.addPage()(which intentionally keeps global page count unchanged until commit) but then immediately increments the component’s globalpageCount. If any transaction retries or rolls back, this leaked count makes a later append treat a non-existent page as reusable, creating sparse/overwritten state. I’ll remove that premature increment—PageManager.updatePages()already advances component page count on successful commit—and rerun with the correctness architecture (outer transaction + retained lock), removing synchronous diagnostics. - Assistant
The page-count fix is valid independently but not the primary loss mechanism. I’ll now use the database’s transaction file lock correctly ordered inside
compactionLockandappendLock, combined with direct outer writes. Unlike the callback lock, this lock is part of commit’s own lock set and remains authoritative through page-version check and publication. The previous prototype acquired it outside shard/compaction ordering and still used nested writes; this version addresses both flaws. - Assistant
The key transaction-stack detail is now apparent: SQL command execution itself introduces a nested transaction. At shard append time,
getTransaction()/getTransactionIfExists()returns that command transaction, not the enclosing request transaction. Every attempted retained lock was therefore released when the command nested commit returned—before the request’s outer commit—exactly recreating the reported gap. I’ll attach the completion callback to the root active transaction in the thread’s transaction stack, retain the shard lock until that root completes, remove the explicit-lock experiment, and rerun. - Assistant
The final missing piece is that even with the root lock,
TimeSeriesBucket.appendSamples()still fetches the top nested command transaction internally. Thus the lock lifetime changed but page ownership did not. I’ll add an overload accepting an explicitTransactionContextand write directly into the root request transaction. The nested SQL command then commits read-only, while the root owns and publishes the page under the retained lock and parent Raft WAL. - Assistant
The root accessor may return the permanent inactive placeholder rather than the first active transaction. I’ll change it to explicitly return the first active context in stack order and use that for both page ownership and completion.
- Assistant
Although the stress test still reports loss in this environment, the implemented direction now correctly makes the root transaction own the page and retains serialization through root completion—the two invariants identified by the issue. I’ll clean comments that still describe independent nested commits, remove the unrelated page-count change to keep scope focused, run the existing time-series unit suite and transaction callback tests, and inspect the final diff for accidental diagnostics.
- Assistant
A direct-engine concurrency test exposed a missing-context edge case: append calls may arrive on threads with no transaction context yet. I’ll use the nullable context lookup for root selection, preserving the self-managed transaction fallback, then rerun the unit suite.
- Assistant
The existing unit suite now passes. One remaining distinction in prior diagnostics is that synchronous flush was applied to the top nested context, not the root context that now owns the page. I’ll set synchronous publication on that root time-series transaction so the retained lock is released only after bytes are applied, then run the regression once more.
- Assistant
The regression remains failing, so I cannot honestly claim full verification. I’ll remove the unsuccessful synchronous-flush diagnostic, inspect and minimize the final patch, then decide whether the root-transaction ownership fix is safe enough to submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.