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 time-series transaction and page-management code, repository status, and available regression tests. Then I’ll reproduce the loss (or build a temporary focused reproducer if the referenced test is absent), implement the narrowest concurrency fix that preserves transaction/HA behavior, and run targeted plus existing tests.
- Assistant
The repository already contains the reported regression test. The current comments claim nested commits are independent, but the observed behavior contradicts that specifically through the HA wrapper. I’ll inspect the test, wrapper/local transaction stack implementations, and commit/WAL flow to identify a fix based on actual transaction semantics rather than merely widening the existing in-memory lock.
- Assistant
I’ll now trace
LocalDatabase.begin/commit,DatabaseContext, and wrapper implementations across modules. The key question is whether an inner append can be force-published safely while an outer SQL transaction remains active, or whether page conflict detection must be strengthened so the outer transaction retries. - Assistant
Even embedded mode uses the same
LocalDatabasewrapper, so the failure is rooted in generic nested transaction commit behavior. I’ll inspectTransactionContext.commit()and page acquisition/version logic, then run the disabled test explicitly once to establish a baseline. - Assistant
The system Maven launcher is unavailable, so I’ll use the repository wrapper/build convention after checking the root. Before testing, I need the omitted beginning of
TransactionContext.commitandPageManager.updatePageVersion; these determine why the stale mutable-page snapshot can overwrite a newer committed page without conflict. - Assistant
At first glance, independent nested commits should conflict correctly or expose the latest cached page. The likely subtlety is that SQL’s
SaveElementStepretains a mutable time-series page in the outer transaction beforeTimeSeriesShardbegins its nested transaction, causing subsequent inner work to operate against snapshots that later outer commits publish. I’ll inspect that routing step and transaction phase/WAL wrapper behavior, and locate the project’s actual test launcher (the root appears to have.mvnbut no visiblemvnw). - Assistant
The append itself is invoked before the continuous-aggregate callback touches the outer transaction, so the outer SQL transaction initially has no time-series pages. Historical commits show this code was recently changed for concurrency and replication; inspecting those diffs should reveal the intended nesting semantics and may expose the regression directly.
- Assistant
The replication change is the inflection point: standalone nested commits are truly independent, but
RaftReplicatedDatabasemay intentionally defer a nested TX into the parent replication unit. I’ll inspect its begin/commit implementation and transaction broker. That should indicate whether a per-shard lock can be held until outer completion via callbacks, or whether a safer reservation mechanism is needed. - Assistant
I need the start of
RaftReplicatedDatabase.commit()and itsbegin()delegation. The prior output began mid-branch, so I’ll capture the complete control flow. I’ll also run the embedded regression through./mvnw; embedded mode should confirm whether this branch’s standalone semantics alone reproduce the reported loss. - Assistant
The HA commit does independently replicate every nested append, so holding
appendLockthroughdb.commit()should already protect it. The embedded baseline still needs execution; the wrapper failed only because this sandbox omitsHOME. I’ll rerun withHOME=/root, then inspect any failure report and transaction timing. - Assistant
The baseline reproduces deterministically (150 silently lost), satisfying the first critical step. Since the lock encloses the inner commit, a later operation outside that lock must be republishing a stale page. I’ll inspect
LocalDatabase.transaction()and SQL command transaction ownership, then add temporary runtime diagnostics (not tests) if needed to identify which transaction holds time-series pages at outer commit. - Assistant
A plausible mechanism is now narrower: the serialized commit updates page versions, but
PageManager’s asynchronous write/read-cache publication may allow the next locked append to load an older cached image. That would explain both same-slot reuse and why version checks pass (the stale cache’s version may be advanced independently). I’ll inspect cache publication and page cloning semantics, plusgetOrCreateActiveDataPage, before deciding whether the fix belongs in page management or the shard append path. - Assistant
Async cache publication occurs before returning from commit, so the next append should see the latest image. However, the same page is also queued for flush; if an older queued snapshot can later replace the read cache with itself, it can regress content while retaining a compatible version. I’ll inspect
CachedPage, cache replacement policy, and flush-thread behavior for this exact stale replacement race. - Assistant
The read cache itself only receives commit-time snapshots, not flush-time replacements. The remaining suspect is
pageIndex: scheduling multiple versions under onePageIdcan letloadPage/getMostRecentVersionretrieve an older queued mutable page during cache misses or eviction. I’ll inspect the untruncated scheduling/index methods and version lookup. - Assistant
The flush queue has a separate serious ordering risk, but it does not explain a hot page that remains cached. The most direct explanation left is multiple
TimeSeriesShardinstances (and therefore multiple locks) for one type—possibly due unsynchronized lazy engine initialization in schema/type lookup under 48 threads. I’ll inspectLocalTimeSeriesTypeengine lifecycle and schema loading. - Assistant
Engine initialization is synchronized and yields one shard/lock, ruling out duplicate lock domains. To isolate the page publication layer, I’ll rerun the regression with transaction async flushing disabled via the available configuration (or a temporary source toggle if it is not externally configurable). If synchronous flushing eliminates loss, the fix should enforce ordered publication/flush for these hot pages rather than alter transaction semantics.
- Assistant
setAsyncFlushis transaction-local, so I can make a temporary diagnostic change in production code for only the inner append transaction, run the existing regression unchanged, then either retain it only if it is an acceptable targeted fix or replace it with a better ordered-cache solution. This will distinguish transaction nesting from async page visibility. - Assistant
Synchronous flushing reduces but does not eliminate loss, confirming the issue is stale transaction state rather than merely flush ordering. I’ll now instrument (temporarily) the transaction immediately after the nested append commit to see whether the resumed outer transaction already owns modified or immutable time-series pages. This is the fastest way to validate the issue’s stated deferred-parent mechanism against this checkout.
- Assistant
The resumed outer transaction is clean, so the reported “outer publish” is not literally visible as dirty pages in this embedded path. I’ll perform one final isolation experiment: serialize all time-series appends JVM-wide instead of per shard. If loss remains, competing append instances are ruled out and the stale publisher is page/transaction infrastructure; if it disappears, lock identity is the defect and the durable fix is a shared lock keyed by physical bucket.
- Assistant
Global serialization still loses samples, proving append overlap is not the cause. The page cache has an unsafe publication primitive: any concurrent disk/flush-queue load unconditionally replaces the current cached page, even when the loaded snapshot has an older version. Once that regression occurs, version checking consults the regressed cache itself and accepts the stale page, producing exactly the silent lost update.
I’ll fix cache publication atomically so an older—or ambiguous equal-version—snapshot can never replace an already published page. Commit snapshots naturally have incremented versions; explicit overwrite already evicts first. Then I’ll rerun the unchanged regression under normal per-shard locking.
- Assistant
The cache guard did not resolve the regression, so I’ll revert that speculative change. The decisive experiment is consistent with the issue’s supplied root cause: even JVM-global append serialization fails because the lock is released before each enclosing transaction commits.
I’ll extend transaction contexts with an after-completion callback (runs on both commit and rollback), then defer releasing the shard’s reentrant append lock until the pre-existing enclosing transaction completes. Reentrancy supports multiple appends to the same shard in one transaction; one callback releases each acquisition. Standalone/batch calls with no enclosing transaction retain the current immediate-unlock behavior. This preserves HA replication in the parent WAL and makes serialization cover the actual publish.
- Assistant
Because compaction also must not clear the mutable bucket before the outer publish, I’ll defer both the append lock and compaction read lock together. The completion callback executes during transaction reset on the same thread, which is required by
ReentrantLock/ReentrantReadWriteLock. Error paths before callback registration still release immediately. - Assistant
Holding through outer completion substantially reduces but still does not eliminate loss, indicating a second race in asynchronous page durability/publication. I’ll combine completion-scoped serialization with synchronous flushing for the time-series append transaction. This is a targeted correctness tradeoff on the affected single-row path; batched ingestion remains amortized and unaffected in transaction count. If this passes repeatedly, I’ll assess performance and simplify the callback implementation.
- Assistant
The residual loss even with synchronous inner flush means I need direct evidence at the slot read, not further architectural guesses. I’ll add a temporary per-shard expected-count check under the now completion-scoped lock. It will report whether the mutable header regresses between appends; if it never regresses, the missing rows originate during rollover/scan rather than slot reuse.
- Assistant
The diagnostic reveals a compaction at 67,280 samples; the count reset is expected because rows move to sealed storage. The loss therefore occurs around repeated mutable-page reuse after compaction, not ordinary append serialization alone. I’ll inspect automatic compaction scheduling and the phase that clears/reuses pages. The lock handoff may protect transaction completion but not asynchronous flushes of pre-clear page images, which can later overwrite reused pages.
- Assistant
The compaction algorithm contains the actual loss window: Phase 4a snapshots the current partial page, releases the lock, then Phase 4c reads only pages whose numbers increased. Samples appended to the same partial page during Phase 4b are neither in the Phase 4a snapshot nor considered “tail pages,” and are erased by
clearDataPages(). The missing 10–150 rows match this brief window exactly.I’ll fix Phase 4c to re-read the portion of the last snapshotted page appended after Phase 4a, in addition to newly created pages. I need inspect the snapshot data format/helpers to avoid duplicate rows and preserve block spill merging.
- Assistant
I’ll discard the transaction callback experiment and implement the focused compaction fix:
- Record the row count in Phase 4a’s last snapshotted page.
- In Phase 4c, read rows appended to that same page starting at the recorded row index.
- Also read all later pages.
- Merge those delta rows with the Phase 4b spill before sealing and clearing.
This avoids both loss and duplication across page-boundary cases.
- Assistant
The unchanged 240,000-row regression now passes. I found one boundary case before broader testing: if Phase 4a sees zero pages and appends create page 1 during Phase 4b, the delta reader must start at page 1 rather than skip it. I’ll handle that case, review the diff for accidental diagnostics, then run the regression again plus the time-series compaction/concurrency test set.
- Assistant
The second high-concurrency run and targeted compaction tests pass with no failures. The fix covers: appends remaining on the same partial page, rollover into one or more new pages, and the zero-page snapshot boundary.
I’ll now run the complete engine time-series test package (without changing test sources), inspect Surefire summaries and repository diff/status, and ensure no temporary diagnostics or build artifacts are tracked.
- Assistant
All non-disabled time-series engine tests pass. The disabled regression remains skipped in the normal suite as expected, but it has passed twice when explicitly enabled after the fix. I’ll run it once more in isolation to verify repeatability, then perform final diff/status checks. No tests were modified, in accordance with the environment constraint.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.