Repository navigation
fix(#4952,#4957,#4958,#4960): pool discipline, TimeSeries threading, storage/WAL and LSM low-severity cleanups (2026-07 audit) - #5063
Conversation
…WAL and LSM low-severity cleanups Fixes four grouped findings of the 2026-07 engine audit (tracking issue #4962). #4952 - PartitionedTriangleOp submitted ALL chunks (including chunk 0) to the shared query-engine pool and blocked in Future.get(). Reached from a pool thread (or with the pool full of blocked producers) the caller waited on tasks queued behind threads that were themselves waiting: a pool-starvation deadlock only mitigated by the bounded queue's caller-runs rejection. The operator now runs chunk 0 on the calling thread and submits only chunks 1..N-1, the same caller-runs-chunk-0 discipline as GraphAlgorithms.parallelForRange. Red-first: PartitionedTriangleOpCallerRunsTest failed on unfixed code with chunk 0 observed on "ArcadeDB-QueryWorker-1" instead of the calling thread (the deadlock itself is a scheduling race, so the test verifies the fix's observable thread-affinity contract; the triangle count stays correct). #4957 - TimeSeriesEngine.appendBatch dispatched every shard write to the shardExecutor even when the caller had an enclosing transaction open, violating the transaction-threading rule documented on appendSamples: each TS-Shard thread ran with its own fresh DatabaseContext/transaction, publishing the shard pages out of band with the enclosing commit and, under HA, reordering the page versions on the Raft log. appendBatch now falls back to sequential in-thread shard writes when a transaction is active (keeping the at-most-S-transactions batching win) and keeps the parallel dispatch otherwise. Red-first: Issue4957AppendBatchTransactionTest failed on unfixed code with live "ArcadeDB-TS-Shard-tx_batch-0/1" threads spawned by a batch appended inside a transaction (the executor threads are created lazily on first dispatch, so their existence deterministically identifies the path taken); the HA reordering itself needs a cluster to observe. #4958 - low-severity storage/WAL cleanups, each independently red-tested where deterministically possible: - WALFile.readLong/readInt: per-call buffers with a full-read loop (the shared instance buffers were unsynchronized and a partial channel.read decoded stale garbage); on EOF the record is treated as truncated (null), matching the explicit size checks. - WALFile.append: loops until the buffer is fully written (a partial write left a torn record the #4508 gap detector then flagged as corruption). - WALFile.getTransaction: the per-page delta size is clamped to the remaining file size. Red-first: a crafted header with changesTo=Integer.MAX_VALUE-1 made ByteBuffer.allocate throw OutOfMemoryError("Requested array size exceeds VM limit") which escaped the catch(Exception) recovery guard and killed the surefire fork (Issue4958WALLowSeverityTest). - TransactionManager.getStats: returns a snapshot instead of folding every active WAL file's cumulative counters into the accumulators on each call (totals inflated with polling frequency and were double-counted again at file retirement); no longer NPEs on read-only databases (no active pool). Red-first: Issue4958StorageStatsTest (inflation + NPE). - PageManager.getCachedPage: cache misses are actually counted (the increment sat after an early return, so cacheMiss stayed at ~0 forever). Red-first: Issue4958StorageStatsTest#pageCacheMissIsCounted. - PageManager.suspendFlushAndExecute: a nested call (snapshot during backup) now runs the callback under the outer suspension instead of silently skipping it - the single production caller is the full backup, which previously produced a silent no-op in the nested case. Red-first: Issue4958StorageStatsTest#nestedSuspendFlushStillExecutesTheCallback. - TransactionManager.createWALFilePool seeds logFileCounter past existing txlog_<n>.wal files, and the corrupt-gap branch of checkIntegrity renames the preserved files to .wal.corrupt. WALFile opens "rw" without truncation, so restarting the counter at 0 adopted a preserved file as an ACTIVE WAL: new transactions were appended after the old (possibly corrupt) content and the old records replayed again on the next recovery. Red-first: Issue4958PreservedWALTest (stray txlog_0.wal grew from 64 bytes on unfixed code; corrupt-gap file survived under its .wal name). The existing Issue4508TornWALRecoveryTest was updated for the deliberate rename. - LocalBucket: free-space statistics measure the usable content region (page.getMaxContentSize()) instead of the physical page size (overstated by the page header), and timeOfLastStats/changesFromLastStats are now volatile/AtomicLong (both were mutated outside the freeSpaceInPages monitor on the delete and updatePageStatistics paths). Deliberately NOT fixed here (kept open on #4958): the activeWALFilePool element publication (fixing it properly needs an AtomicReferenceArray refactor across a conflict-heavy file; the 10ms retry loop re-reads the array through a synchronized call, bounding the staleness in practice). The "waitAllPagesOfDatabaseAreFlushed loops forever while suspended" sub-item was already fixed by the #4928 bounded no-progress wait. #4960 - low-severity LSM cleanups: - BufferBloomFilter (dead code, hardened before wiring in): the bit index is always reduced modulo capacity (a hash equal to capacity addressed one bit PAST the region, corrupting the adjacent byte of the shared buffer); add() is synchronized (the non-atomic RMW could drop a concurrently-set bit = a false negative, the one failure a bloom filter must never have); two probes derived from the 64-bit Murmur halves replace the single 32-bit probe. BufferBloomFilterCorrectnessTest covers no-false-negatives single-threaded and under 8-thread contention; honest note: the dropped-bit race did not reproduce red deterministically (a saturated filter masks drops and an unsaturated one makes same-byte interleavings rare), so the concurrency fix is verified analytically and by contract. - LSMTreeIndex.mutable is volatile: swapped under the write lock by splitIndex but read unlocked by getFileId/getKeyTypes/getBinaryKeyTypes/convertKeys and metadata paths - an unfenced reader could see a stale or partially published instance. - LSMTreeIndex.close() cancels a scheduled-but-not-started compaction (CAS COMPACTION_SCHEDULED -> UNAVAILABLE) instead of being a silent no-op, and logs a WARNING when an in-progress compaction blocks the close. Red-first: Issue4960LSMCloseDuringCompactionTest (status stayed COMPACTION_SCHEDULED and the index was left open on unfixed code). - splitIndex checks the tryLockFile outcome for the new file instead of ignoring it (a failure can only be a bug, but proceeding unlocked would corrupt the swap in silence). Deliberately NOT fixed here (kept open on #4960): the onAfterLoad currentMutablePages=1 undercount (pre-existing TODO; affects only auto-compaction pacing) and the O(n^2) descending rescan in LSMTreeIndexUnderlyingPageCursor.getKeys() (perf-only). Tests: new PartitionedTriangleOpCallerRunsTest, Issue4957AppendBatchTransactionTest, Issue4958StorageStatsTest, Issue4958WALLowSeverityTest, Issue4958PreservedWALTest, BufferBloomFilterCorrectnessTest, Issue4960LSMCloseDuringCompactionTest (15 tests, all red on unfixed code where deterministically possible, all green after). Focused suites com.arcadedb.graph.**, com.arcadedb.index.**, com.arcadedb.engine.** (includes engine.timeseries.**) green, benchmarks excluded; plus the OpenCypher triangle/GAV algo tests.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 16 |
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
There was a problem hiding this comment.
Code Review
This pull request introduces comprehensive hardening and cleanups across storage, WAL, LSM, and TimeSeries components, addressing issues like pool-starvation deadlocks, out-of-band transaction commits, and WAL corruption handling. The review feedback highlights several key improvement opportunities: adding a null check for database.getDatabasePath() to prevent a potential NullPointerException, optimizing BufferBloomFilter.hash64 by reusing a ThreadLocal buffer to avoid garbage collection pressure, handling potential renameTo failures on Windows when renaming corrupt WAL files, and caching the file size in WALFile.getTransaction to avoid redundant system calls.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| final File[] existingWALFiles = new File(database.getDatabasePath()).listFiles((dir, name) -> name.endsWith(".wal")); | ||
| if (existingWALFiles != null) |
There was a problem hiding this comment.
If database.getDatabasePath() returns null (which can happen for in-memory or custom databases), passing it directly to new File(...) will throw a NullPointerException. Adding a null check prevents this crash.
final String dbPath = database.getDatabasePath();
final File[] existingWALFiles = dbPath != null ? new File(dbPath).listFiles((dir, name) -> name.endsWith(".wal")) : null;
if (existingWALFiles != null)| private long hash64(final int value) { | ||
| final byte[] b = new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value }; | ||
| final int hash = MurmurHash.hash32(b, 4, hashSeed); | ||
| final int h = hash != Integer.MIN_VALUE ? Math.abs(hash) : Integer.MAX_VALUE; | ||
| return MurmurHash.hash64(b, 4, hashSeed); | ||
| } |
There was a problem hiding this comment.
The hash64 method allocates a new byte[4] array on every single call. Since add and mightContain are on the hot path for Bloom filter operations, this constant allocation introduces significant garbage collection pressure. Reusing a thread-safe ThreadLocal<byte[]> buffer avoids these allocations entirely.
| private long hash64(final int value) { | |
| final byte[] b = new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value }; | |
| final int hash = MurmurHash.hash32(b, 4, hashSeed); | |
| final int h = hash != Integer.MIN_VALUE ? Math.abs(hash) : Integer.MAX_VALUE; | |
| return MurmurHash.hash64(b, 4, hashSeed); | |
| } | |
| private static final ThreadLocal<byte[]> THREAD_LOCAL_BUFFER = ThreadLocal.withInitial(() -> new byte[4]); | |
| private long hash64(final int value) { | |
| final byte[] b = THREAD_LOCAL_BUFFER.get(); | |
| b[0] = (byte) (value >>> 24); | |
| b[1] = (byte) (value >>> 16); | |
| b[2] = (byte) (value >>> 8); | |
| b[3] = (byte) value; | |
| return MurmurHash.hash64(b, 4, hashSeed); | |
| } |
| final File walFile = new File(file.getFilePath()); | ||
| if (walFile.exists() && !walFile.renameTo(new File(walFile.getParentFile(), walFile.getName() + ".corrupt"))) | ||
| LogManager.instance().log(this, Level.WARNING, | ||
| "Error on renaming preserved WAL file '%s' to '%s.corrupt'", null, walFile, walFile.getName()); |
There was a problem hiding this comment.
The renameTo operation can fail (especially on Windows) if the destination .corrupt file already exists from a previous recovery attempt. If it fails, the corrupt WAL file retains its .wal extension and will be scanned again on the next startup. Using a unique suffix/counter when the destination file exists ensures the rename succeeds and preserves all corrupt files for inspection.
final File walFile = new File(file.getFilePath());
if (walFile.exists()) {
File corruptFile = new File(walFile.getParentFile(), walFile.getName() + ".corrupt");
int counter = 1;
while (corruptFile.exists()) {
corruptFile = new File(walFile.getParentFile(), walFile.getName() + "." + counter + ".corrupt");
counter++;
}
if (!walFile.renameTo(corruptFile))
LogManager.instance().log(this, Level.WARNING,
"Error on renaming preserved WAL file '%s' to '%s'", null, walFile, corruptFile.getName());
}| // but a corrupt per-page header can still declare a huge deltaSize (up to Integer.MAX_VALUE) | ||
| // and trigger a transient ~2GB allocation, or an OutOfMemoryError that escapes the | ||
| // catch(Exception) recovery guard below, before the read would fail. | ||
| if (deltaSize <= 0 || tx.pages[i].changesFrom < 0 || pos + deltaSize > getSize()) |
There was a problem hiding this comment.
Calling getSize() (which queries channel.size()) inside the loop for every page in the transaction can be a performance bottleneck due to redundant system calls. Consider querying getSize() once at the beginning of getTransaction and storing it in a local variable fileSize to reuse across all checks in this method.
Review: PR #5063 - pool discipline, TimeSeries threading, storage/WAL & LSM cleanupsOverall this is a high-quality, carefully scoped PR. The per-issue verdict table, the "deliberately left open" section with rationale, and the red-first regression tests (15 tests / 7 classes) make it easy to reason about. I verified the changed source against the surrounding code and the referenced helper methods ( What looks correct and well done
Minor observations (non-blocking)
TestsCoverage is strong and honest - I especially appreciate the candid note that the Bloom dropped-bit race can't be proven absent by a single run, and that the fix is verified by contract plus the no-false-negative property under 8 threads. The I could not run Nothing here is blocking - the observations above are hardening notes for the eventual Bloom-filter wiring-in and documentation nits. LGTM. Automated review by Claude. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #5063 +/- ##
=============================================
- Coverage 65.50% 36.10% -29.41%
- Complexity 840 1127 +287
=============================================
Files 1687 1687
Lines 135056 135124 +68
Branches 28887 28907 +20
=============================================
- Hits 88470 48781 -39689
- Misses 34506 77240 +42734
+ Partials 12080 9103 -2977 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…orrupt preservation follow-ups Follow-up to the grouped 2026-07 audit commit for #4952/#4957/#4958/#4960 (tracking issue #4962). #4960 - LSMTreeIndexMutable.onAfterLoad() hardcoded currentMutablePages = 1 (the pre-existing TODO). currentMutablePages counts the not-yet-compacted pages that pace auto-compaction: onAfterCommit schedules a compaction once the counter reaches indexCompactionMinPagesSchedule. Since splitIndex starts a fresh file containing only uncompacted pages, every page of a reloaded mutable file counts towards the next compaction; restarting the counter at 1 deferred the scheduled compaction by up to a full threshold of new pages after every restart. onAfterLoad now restores the counter from the file (max(1, getTotalPages())). Red-first: Issue4960LSMReloadCompactionCounterTest failed on unfixed code with counter=1 vs the 4 pages actually in the reloaded file. #4958 follow-ups to the .wal.corrupt preservation rename shipped in the previous commit: - WALVersionGapRecoveryTest now asserts the preserved files under their .corrupt name (it asserted surviving .wal files and went red after the deliberate rename, same update as Issue4508TornWALRecoveryTest). - ha-raft SnapshotManager skips *.corrupt in the snapshot checksum exactly like it already skips *.wal: the preserved evidence files are node-local and would otherwise diverge the per-node snapshot checksums. Still deliberately open on #4958 (reasoning unchanged): the activeWALFilePool element publication. A minimal VarHandle variant was prototyped and discarded - TransactionManager is a conflict epicenter across the parallel audit branches and the 10ms retry loop already bounds the staleness by re-reading the array through a synchronized call. Tests: Issue4960LSMReloadCompactionCounterTest (red on unfixed code, green after), WALVersionGapRecoveryTest, SnapshotManagerTest, SnapshotManifestVerificationTest; focused suites com.arcadedb.engine.** (incl. engine.timeseries.**), com.arcadedb.index.**, com.arcadedb.graph.** green (1296 tests, 0 failures), plus PartitionedTriangleOpCallerRunsTest and AlgoTriangleCountTest.
Code Review: PR #5063 - pool discipline, TimeSeries threading, storage/WAL and LSM low-severity cleanupsOverall this is a high-quality, well-scoped PR. The red-first (failing test before fix) discipline, the per-hunk Strengths / confirmed-correct
Minor observations / questions (non-blocking)
Style / conventions
Verdict: LGTM. The observations above are minor and can be addressed in follow-ups (or ignored where the current behavior is intentional). The concurrency-sensitive changes correctly reuse the project's established pool-discipline and safe-publication patterns. |
Point-by-point response to the LGTM review: 1. BufferBloomFilter (taken): documented the publication contract on mightContain (lock-free read is only safe after the filter is fully built and safely published, no concurrent adds; otherwise a stale byte can produce a false negative) and the capacity-vs-buffer invariant in the class javadoc (buffer must be >= ceil(slots/8) bytes, load-bearing now that floorMod can address the top byte). 2. Issue4960LSMReloadCompactionCounterTest (taken): softened the assertion message to acknowledge that getTotalPages() includes the header/root page, so the restored mutable-pages counter is an approximate, pacing-only signal rather than an exact count. 3. TransactionManager.checkIntegrity (taken): the preserved-WAL rename to '.corrupt' now uses Files.move instead of File.renameTo, so a failure carries a cause and the rename is atomic where the filesystem supports it. Best-effort semantics are preserved: the IOException is caught, logged as WARNING with the exception, and recovery continues. 4. Issue4957AppendBatchTransactionTest liveness check (acknowledged, no change): the Thread.getAllStackTraces() probe for lazily-created ArcadeDB-TS-Shard-* threads is admittedly the least robust of the new tests, but there is no trivially more robust alternative short of instrumenting the shard executor itself; the per-type thread naming keeps it isolated and it is deterministic as written. Verified: engine compiles; all PR-focused tests pass (BloomFilterTest, BufferBloomFilterCorrectnessTest, Issue4508TornWALRecoveryTest, Issue4958PreservedWALTest, Issue4958StorageStatsTest, Issue4958WALLowSeverityTest, WALVersionGapRecoveryTest, Issue4957AppendBatchTransactionTest, Issue4960LSMReloadCompactionCounterTest, Issue4960LSMCloseDuringCompactionTest, PartitionedTriangleOpCallerRunsTest: 23 tests, 0 failures).
Code Review - PR #5063 (pools/TimeSeries/WAL/LSM low-severity audit fixes)Overall this is a high-quality, well-scoped PR: each fix is small and localized, every deterministic finding ships a red-first regression test, and the commit messages / release notes explain the why clearly. I traced each change against the surrounding code and it holds up. Detailed notes below. Correctness - looks right
Minor observations (non-blocking)
TestsCoverage is strong: 16 new regression tests across 8 classes, red-first where deterministic, and the honest notes on the two non-deterministic races ( Nice work - the deliberately-left-open items are all documented with rationale on the issues. LGTM modulo the minor notes above. Automated review by Claude. |
…atomic stats-counter consume - BufferBloomFilter: document the safe-publication requirement on the constructor (final/volatile field or lock/queue happens-before) so a later integrator does not publish the filter via a plain field and risk stale-byte false negatives on the lock-free read path - BufferBloomFilter: validate at construction that the Binary can address ceil(slots/8) bytes, throwing IllegalArgumentException with actual/required sizes; regression test for undersized and exactly-sized buffers - LocalBucket.gatherPageStatistics: consume changesFromLastStats with a single getAndSet(0L) at the decision point instead of get()>0 plus a trailing set(0L), so increments landing during the scan are carried into the next cycle rather than wiped; a failed scan re-bumps the counter so it is retried
Review: PR #5063 - pool discipline, TS threading, storage/WAL and LSM low-severity cleanupsReviewed all 8 production-code changes plus the 8 new/updated test classes. This is a high-quality, well-scoped audit PR: each finding is documented inline with a Strengths
Minor observations (non-blocking)
Nothing here blocks merge. Nice, disciplined cleanup work with clear commit-level traceability. |
… stats counter on failed scan Addresses the five round-3 review notes: 1. PartitionedTriangleOp chunk-0 exception path (fixed): chunk 0 now runs inside try/finally so the already-submitted chunks 1..N-1 are ALWAYS awaited; previously a chunk-0 exception unwound execute() while background chunks kept writing into partialCounts and holding pool threads. Chunk 0's own exception stays primary (a secondary await failure never masks it). New regression test chunkZeroFailureStillAwaitsBackgroundChunks verified red pre-fix, green post-fix. GraphAlgorithms deliberately untouched (out of the PR's footprint). 2. gatherPageStatistics failed-scan retry asymmetry (fixed): the counter consumed by getAndSet(0L) is captured in a local and restored with addAndGet(max(consumed, 1)) on the exception path instead of a single incrementAndGet(), so a failed scan no longer undercounts the pending changes; max(.., 1) still guarantees a retry on the firstRun case. 3. REUSE_SPACE_MODE.HIGH coverage (verified, no change needed): RecordRecyclingTest (both tests) sets BUCKET_REUSE_SPACE_MODE=high and does insert/delete/insert cycles asserting freed pages are reused (max RID position bounded across 10 cycles), and SchemaReloadDoesNotEagerScanBucketsTest.lazyPageStatisticsStillWorkAfterReload asserts the lazy gatherPageStatistics scan fires in HIGH mode. Both pass against the new getMaxContentSize() free-space math (re-run locally: 2/2 and 2/2 green). 4. Issue4957AppendBatchTransactionTest thread-observation fragility: acknowledged (repeat of round 1, already documented in the test); if it ever flakes in CI, instrumenting the shard executor dispatch count is the agreed more robust signal. 5. BufferBloomFilter future-integration contract: acknowledged; whoever wires it into the LSM read path must honor add() under lock and lock-free mightContain() only after safe publication, as documented on the class.
Code review — PR #5063 (pools/TimeSeries/WAL/LSM low-severity audit)Reviewed all 11 production changes and the 8 new/updated test classes against Verified correct
Minor suggestions (non-blocking)
Test coverageStrong. Each deterministic finding has a failing-first regression test, the honest note on the bloom-filter dropped-bit race (verified analytically) is appropriate, and the two updated WAL recovery tests correctly track the Nice work - the fixes are surgical and the documentation trail (PR body + inline comments + release notes) is exemplary. Review generated with Claude Code. |
…tion move Round 4 (fourth consecutive LGTM) had one catch worth taking: Files.move without REPLACE_EXISTING throws FileAlreadyExistsException when a prior ABORTED recovery left a same-named .corrupt file behind - the exception is logged and swallowed, the original .wal stays in place, and the next restart re-scans and re-aborts it: the exact loop the preservation rename exists to break. The stale .corrupt being replaced is evidence from the SAME file's earlier failed attempt, so overwriting it is correct. Acknowledged without change: - readInt/readLong per-call buffers: recovery-only path, the tiny allocations are acceptable there; a ThreadLocal scratch buffer is the noted alternative if recovery throughput ever matters. - onAfterLoad page-count pacing (+1 from the header page): benign, pacing-only, consistent with createNewPage's counting at worst one page early; documented in round 2's test comment as approximate. - Test tagging: the new tests run well under a second each locally (the 71.9s RecordRecyclingTest predates this PR and is already tagged); PartitionedTriangleOpCallerRunsTest asserts thread NAMES not timing, so pool load does not flake it. Focused tests green: Issue4958PreservedWALTest 2/2, Issue4958WALLowSeverityTest 2/2.
Code review - PR #5063 (pools / TimeSeries threading / storage-WAL-LSM low-severity audit)Reviewed against the final state of the branch (the PR has clearly been through several review rounds - Overall this is high-quality, disciplined work: every fix is scoped, heavily commented with the why and the issue number, backed by a red-first regression test, and the deliberately-deferred items are documented with rationale rather than silently dropped. The concurrency changes respect the pool-discipline rules in A few observations, one of which is worth a second look before merge. 1.
|
…atch-based leak test Point 1 (suspendFlushAndExecute vs SnapshotHttpHandler): confirmed the reviewer's cross-thread concern is REAL, not just a dead branch. Two threads CAN be inside suspendFlushAndExecute(db, ...) for the same database at once on the snapshot path: CONCURRENCY_SEMAPHORE admits HA_SNAPSHOT_MAX_CONCURRENT (default 2) requests - e.g. two followers resyncing the same database - and executeInReadLock is a SHARED lock. The suspend flag is first-caller-owned (putIfAbsent), so the second thread (a) skips waitForCurrentFlushToComplete and can read files while a flush batch is still mid-write, and (b) keeps streaming while the owner's exit synchronously flushes the deferred batches to disk: torn reads either way. Fix: removed the dead executed[0] fallback and its stale "concurrent case" comment, and serialized the handler's snapshot and checksums paths with a per-database ReentrantLock so the single thread inside suspendFlushAndExecute always owns the suspension for its whole read. Requests beyond the semaphore limit still 503 fast. Overlap with OTHER callers (SQL BACKUP DATABASE, database verify) is a pre-existing exposure of the ownership model, documented at the lock, out of this handler's scope (would need refcounted suspension in PageManager - a follow-up design item, not a regression of #4958). Point 3 (timing-based leak test): chunkZeroFailureStillAwaitsBackground- Chunks reworked to a pure latch handshake, no wall-clock sleeps. Every background chunk parks at its first view access; chunk 0 throws only after one is provably parked; a releaser thread frees them only once the caller is genuinely parked in awaitFutures (Java-level WAITING - a preempted thread still reports RUNNABLE, so CI load cannot fake it). Broken path: execute() unwinds while every chunk is still parked, so the completion latch is provably still up at capture - deterministic red in both directions. Red-check performed: with the chunk-0 try/finally temporarily reverted the test fails on the intended assertion; restored byte-identically, then green 3/3 (0.09s vs the old ~0.5s). Acknowledged without change (reviewer confirmed correct): - Point 2: createWALFilePool counter seeding - seed only matters on the first pool creation with preserved .wal files; post-checkIntegrity call finds nothing by design. - Point 4: getStats() snapshot fix, LocalBucket getMaxContentSize() division safety, BufferBloomFilter unsynchronized mightContain under the build-then-publish contract. Tests green: PartitionedTriangleOpCallerRunsTest 2/2 (x3), SnapshotHttpHandlerSuspendLockTest 3/3 (new), SnapshotHttpHandler- DisconnectTest 7/7, SnapshotWriteStallTest 4/4, SnapshotThrottleTest 2/2, SnapshotManifestVerificationTest 8/8.
Supplementary review - PR #5063 (current tree, post round-5)Reviewed against the final branch state. Two earlier reviews are already on this PR; their main blocking item (the Only new observations below; I won't rehash the earlier threads. 1.
|
…document lock-map lifetime The supplementary review confirmed the round-5 SnapshotHttpHandler fix sound and self-confirmed two earlier items (getTransaction delta clamp, gatherPageStatistics restore-on-exception). Two nits taken: - WALFile.append: one-line comment pinning the single-writer assumption the partial-write loop inherits from the pre-fix code (appends are serialized by acquire(); the local writePos tolerates partial writes, not concurrent writers). - perDatabaseSuspendLock: documented that entries are deliberately never pruned - one small lock per database NAME ever snapshotted, bounded by the server's database count; pruning on drop would need lifecycle callbacks this handler does not have. Note for the record: the review's 'carry-over' about the sleep-based PartitionedTriangleOpCallerRunsTest is stale - round 5 (5af8d87) already replaced it with a deterministic CountDownLatch handshake, red-checked in both directions.
Review: pool discipline / TimeSeries threading / storage-WAL-LSM cleanups (#5063)Overall this is a careful, well-scoped PR. Each fix is small and localized, the reasoning is documented inline, and every deterministic finding has a red-first regression test. I traced the major changes end to end and they hold up. Correctness (verified as sound)
Minor points / suggestions (non-blocking)
Test coverageStrong. 16 new regression tests across 8 classes, each tied to a specific finding with a documented red-first failure. The honest note on VerdictLooks good to merge from a correctness standpoint. The points above are all minor/optional. Nice work on the disciplined red-first approach and the inline rationale on the deliberately-deferred items. |
Code Review: PR #5063 - Pool discipline, TimeSeries threading, storage/WAL and LSM cleanupsThorough review of the diff (already merged). Overall this is high-quality, defensive work: every finding is paired with a red-first regression test, the inline comments explain why each change is safe (not just what changed), and the deliberately-left-open items are documented with rationale. Below are observations by area, then a short list of minor items worth a follow-up glance. Strengths
Minor observations / follow-ups
Test coverageExcellent. 16 new regression tests across 8 classes, each reproducing the specific defect (corrupt-header OOM, polling inflation, read-only NPE, silent nested-suspend skip, preserved-WAL reuse, LSM close-during-compaction, reload counter undercount, bloom false-negative race). The honest note on Nice work - no blocking issues found. The items above are minor/cosmetic or informational. 🤖 Generated with Claude Code |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 16 |
🟢 Coverage 45.07% diff coverage · -36.25% coverage variation
Metric Results Coverage variation ✅ -36.25% coverage variation Diff coverage ✅ 45.07% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (74d3fd5) 135056 100587 74.48% Head commit (7eb158d) 166927 (+31871) 63810 (-36777) 38.23% (-36.25%) Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch:
<coverage of head commit> - <coverage of common ancestor commit>Diff coverage details
Coverable lines Covered lines Diff coverage Pull request (#5063) 142 64 45.07% Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified:
<covered lines added or modified>/<coverable lines added or modified> * 100%
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
…uspenders own their windows PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every caller's callback regardless (ArcadeData#4958). With two concurrent suspenders on the same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot serving - any combination), the non-owner (a) skipped waitForCurrentFlushToComplete, so it could read a page while a flush batch was mid-write, and (b) kept streaming while the owner's exit synchronously flushed the deferred batches to disk - torn reads either way. The suspension is now a per-database REFCOUNT: - setSuspended(db, true) increments the count under the existing per-database suspend lock; it returns true only for the first suspender (0 -> 1). - setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach, Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just drops one reference and the database stays suspended for the remaining suspenders. An unbalanced release is a no-op instead of corrupting state. - A new suspender arriving while the last release is mid-way through the deferred-batch writes waits (timed, uninterruptible with interrupt-flag restore) until the resume completes, so a fresh window can never overlap those page writes. The gate (resumingDatabases) is cleared in a finally that also heals a stuck count if the resume ever escapes with an exception. - PageManager.suspendFlushAndExecute acquires/releases one reference per caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an interrupt during the wait no longer leaks the suspension (pre-existing leak: the flag was set before the wait and never restored on throw). The wait is cheap for non-first suspenders (the flush thread is parked deferring). The ArcadeData#4728 deferred-RAM backpressure accounting and the ArcadeData#5012 per-database suspend bookkeeping are unchanged: batches deferred across overlapping windows are flushed exactly once, by the last suspender's exit. Decision on the HA SnapshotHttpHandler per-database lock (ArcadeData#5063 review round 5): it STAYS, documented as resource discipline rather than correctness. With refcounting it is no longer needed to own the suspension, but it serializes same-database zip streaming: two followers resyncing the same multi-GB database at once would double the read I/O and keep flushing suspended for the UNION of both windows, growing the deferred backlog toward the ArcadeData#4728 cap. TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the pre-fix code (stash-run-unstash); all three methods failed on the exact defect: - overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false after the first of two overlapping suspendFlushAndExecute callers exited while the second was still inside its callback (expected true, was false). - setSuspendedIsRefCounted: the first release of two suspenders cleared the flag (expected release to return false and the db to stay suspended). - suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired immediately while the resume was mid-way through the deferred writes (contract test for the new gate; pre-fix it became a non-owner). PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the resume's count-check now takes the per-database lock, so it serializes behind the flush thread's paused suspended-check and the deferred batch is flushed synchronously in Phase 1 rather than re-enqueued; the assertion now accepts either outcome (flushed or re-enqueued) and still rejects the stranded case. The fake page's file id is now non-existent so the (now reachable) synchronous flush cannot write into a real file of the test database. Verification (all green): - engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest, PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest, PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest, Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest, Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest, PageManagerReadCache*Test (28 tests, 1 skipped stress test) - ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest, SnapshotThrottleTest (9 tests) - integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's suspendFlushAndExecute end-to-end)
…try, page-stats math, LSM counter drift, context prune) Four small residuals collected from the 2026-07 audit follow-up PRs (ArcadeData#5060-ArcadeData#5063), plus a file-enumeration audit reported on the issue. 1. TransactionContext.kill() lock symmetry: kill() (test-only API) released explicitLockedFiles but nulled lockedFiles WITHOUT unlocking, so killing a transaction caught in COMMIT_1ST_PHASE (where lockFilesInOrder populates lockedFiles) leaked the LockManager entries until TransactionManager.kill() closed the whole lock manager. Fix mirrors reset()'s release block, using the pure getRequester() like every other release path. Test (red-first): Issue5067KillLockSymmetryTest drives commit1stPhase(true), kills the tx and asserts a foreign requester can lock the bucket file (returned NO on timeout before the fix). 2. LocalBucket.updatePageStatistics free-space math: the threshold denominator was getPageSize() - contentHeaderSize, the same header overstatement ArcadeData#4958 fixed in gatherPageStatistics. Both now measure against the usable content region (physical size minus BasePage.PAGE_HEADER_SIZE minus the content header). Only skews the GATHER_STATS_MIN_SPACE_PERC threshold by the 8-byte header, no deterministic public observation point; covered by the existing bucket/stats suites. 3. LSMTreeIndexMutable currentMutablePages drift on rollback: createNewPage() increments the counter eagerly inside the transaction, so a rollback (e.g. a commit failed in 1st phase after applying index changes) discards the pages but not the increments; the counter drifted upward for the rest of the run (self-correcting only on reload after ArcadeData#5063's onAfterLoad fix) and inflated the auto-compaction scheduling check. onAfterCommit now clamps the counter to the real page count (the transaction's page counters are already published at that point), keeping the drift from scheduling compaction early without touching the rollback path. Test (red-first): Issue5067MutablePagesCounterDriftTest creates index pages via direct mutable-index puts in a rolled-back tx (counter 9 vs 1 real page before the fix) and asserts a subsequent commit re-aligns it. 4. DatabaseContext empty-entry retention (appended on the issue from PR ArcadeData#5060 final review): since the closing thread no longer prunes foreign CONTEXTS entries (that removal raced the owner's init() re-registration, the ArcadeData#4939 fix), an empty per-thread entry lingered for any live thread that opened+closed a database, accumulating on large long-lived pools (~500 Undertow workers) under open/close churn. The periodic sweep (invoked from init() every 1000th call) now opportunistically drops live threads' empty entries with a claim/re-check protocol: value-keyed remove of the exact entry, re-check emptiness, putIfAbsent the same entry back if the owner repopulated concurrently. Ordering argument documented inline: the owner's map.put always precedes its CONTEXTS registration check in init(), so either the re-check sees the repopulation and restores, or the owner sees the removal and re-registers; no live registration can be lost. No rollbacks run in the new branch, so the two-level claim discipline is untouched; the prune is allocation-free. Test (red-first): DatabaseContextLifecycleTest# sweepPrunesEmptyEntryOfLiveThreadAfterForeignClose, including owner re-registration after the prune. 5. Node-local file-enumeration audit (.wal.corrupt evidence files, report only): FileManager registration (extension allowlist), full backup and snapshot serving (registered ComponentFiles + explicit .ts.sealed), WAL adoption (endsWith(".wal") cannot match ".wal.corrupt"), fingerprint (suffix allowlist) and the ha-raft checksum (skip-list already extended in ArcadeData#4958) are all safe; no code changes needed. Details on the issue. Tests: the three new red-first tests plus ACIDTransactionTest, ExplicitLockingTransactionTest, LockTimeoutRetryTest, DatabaseContextLifecycleTest (9/9), Issue4511/4547 lock-leak tests, TransactionContextRemoveFileTest, ProtocolContextTest, Issue4958StorageStatsTest, LocalBucketRecordPositionTest, Issue4960 LSM counter/close tests, ConcurrentCompactionTest, MultipleDatabasesTest - all green.
…caffolding trim
Two deferred items from the audit's final review rounds:
- The invalid-MAX_PAGE_RAM ConfigurationException printed the byte value
with an 'MB' suffix (maxRAM is already multiplied by 1024*1024 when the
message is built); it now divides back so a bad value reads in the unit
it names.
- The review-round chronology left in comments across the audit-touched
files ('#NNNN review round N', 'taken after three rounds', ...) is
trimmed to plain issue references - the invariant statements stay, the
PR-history narration goes, as the final ArcadeData#5063/ArcadeData#5060/ArcadeData#5070 rounds asked.
No behavior change beyond the message unit. Lifecycle, commit-ordering,
context-lifecycle and flush-robustness suites green.
Point-by-point response to the LGTM review: 1. BufferBloomFilter (taken): documented the publication contract on mightContain (lock-free read is only safe after the filter is fully built and safely published, no concurrent adds; otherwise a stale byte can produce a false negative) and the capacity-vs-buffer invariant in the class javadoc (buffer must be >= ceil(slots/8) bytes, load-bearing now that floorMod can address the top byte). 2. Issue4960LSMReloadCompactionCounterTest (taken): softened the assertion message to acknowledge that getTotalPages() includes the header/root page, so the restored mutable-pages counter is an approximate, pacing-only signal rather than an exact count. 3. TransactionManager.checkIntegrity (taken): the preserved-WAL rename to '.corrupt' now uses Files.move instead of File.renameTo, so a failure carries a cause and the rename is atomic where the filesystem supports it. Best-effort semantics are preserved: the IOException is caught, logged as WARNING with the exception, and recovery continues. 4. Issue4957AppendBatchTransactionTest liveness check (acknowledged, no change): the Thread.getAllStackTraces() probe for lazily-created ArcadeDB-TS-Shard-* threads is admittedly the least robust of the new tests, but there is no trivially more robust alternative short of instrumenting the shard executor itself; the per-type thread naming keeps it isolated and it is deterministic as written. Verified: engine compiles; all PR-focused tests pass (BloomFilterTest, BufferBloomFilterCorrectnessTest, Issue4508TornWALRecoveryTest, Issue4958PreservedWALTest, Issue4958StorageStatsTest, Issue4958WALLowSeverityTest, WALVersionGapRecoveryTest, Issue4957AppendBatchTransactionTest, Issue4960LSMReloadCompactionCounterTest, Issue4960LSMCloseDuringCompactionTest, PartitionedTriangleOpCallerRunsTest: 23 tests, 0 failures). (cherry picked from commit ce5d883)
…atomic stats-counter consume - BufferBloomFilter: document the safe-publication requirement on the constructor (final/volatile field or lock/queue happens-before) so a later integrator does not publish the filter via a plain field and risk stale-byte false negatives on the lock-free read path - BufferBloomFilter: validate at construction that the Binary can address ceil(slots/8) bytes, throwing IllegalArgumentException with actual/required sizes; regression test for undersized and exactly-sized buffers - LocalBucket.gatherPageStatistics: consume changesFromLastStats with a single getAndSet(0L) at the decision point instead of get()>0 plus a trailing set(0L), so increments landing during the scan are carried into the next cycle rather than wiped; a failed scan re-bumps the counter so it is retried (cherry picked from commit 630ce69)
… stats counter on failed scan Addresses the five round-3 review notes: 1. PartitionedTriangleOp chunk-0 exception path (fixed): chunk 0 now runs inside try/finally so the already-submitted chunks 1..N-1 are ALWAYS awaited; previously a chunk-0 exception unwound execute() while background chunks kept writing into partialCounts and holding pool threads. Chunk 0's own exception stays primary (a secondary await failure never masks it). New regression test chunkZeroFailureStillAwaitsBackgroundChunks verified red pre-fix, green post-fix. GraphAlgorithms deliberately untouched (out of the PR's footprint). 2. gatherPageStatistics failed-scan retry asymmetry (fixed): the counter consumed by getAndSet(0L) is captured in a local and restored with addAndGet(max(consumed, 1)) on the exception path instead of a single incrementAndGet(), so a failed scan no longer undercounts the pending changes; max(.., 1) still guarantees a retry on the firstRun case. 3. REUSE_SPACE_MODE.HIGH coverage (verified, no change needed): RecordRecyclingTest (both tests) sets BUCKET_REUSE_SPACE_MODE=high and does insert/delete/insert cycles asserting freed pages are reused (max RID position bounded across 10 cycles), and SchemaReloadDoesNotEagerScanBucketsTest.lazyPageStatisticsStillWorkAfterReload asserts the lazy gatherPageStatistics scan fires in HIGH mode. Both pass against the new getMaxContentSize() free-space math (re-run locally: 2/2 and 2/2 green). 4. Issue4957AppendBatchTransactionTest thread-observation fragility: acknowledged (repeat of round 1, already documented in the test); if it ever flakes in CI, instrumenting the shard executor dispatch count is the agreed more robust signal. 5. BufferBloomFilter future-integration contract: acknowledged; whoever wires it into the LSM read path must honor add() under lock and lock-free mightContain() only after safe publication, as documented on the class. (cherry picked from commit f8f7ea9)
…tion move Round 4 (fourth consecutive LGTM) had one catch worth taking: Files.move without REPLACE_EXISTING throws FileAlreadyExistsException when a prior ABORTED recovery left a same-named .corrupt file behind - the exception is logged and swallowed, the original .wal stays in place, and the next restart re-scans and re-aborts it: the exact loop the preservation rename exists to break. The stale .corrupt being replaced is evidence from the SAME file's earlier failed attempt, so overwriting it is correct. Acknowledged without change: - readInt/readLong per-call buffers: recovery-only path, the tiny allocations are acceptable there; a ThreadLocal scratch buffer is the noted alternative if recovery throughput ever matters. - onAfterLoad page-count pacing (+1 from the header page): benign, pacing-only, consistent with createNewPage's counting at worst one page early; documented in round 2's test comment as approximate. - Test tagging: the new tests run well under a second each locally (the 71.9s RecordRecyclingTest predates this PR and is already tagged); PartitionedTriangleOpCallerRunsTest asserts thread NAMES not timing, so pool load does not flake it. Focused tests green: Issue4958PreservedWALTest 2/2, Issue4958WALLowSeverityTest 2/2. (cherry picked from commit 5337657)
…atch-based leak test Point 1 (suspendFlushAndExecute vs SnapshotHttpHandler): confirmed the reviewer's cross-thread concern is REAL, not just a dead branch. Two threads CAN be inside suspendFlushAndExecute(db, ...) for the same database at once on the snapshot path: CONCURRENCY_SEMAPHORE admits HA_SNAPSHOT_MAX_CONCURRENT (default 2) requests - e.g. two followers resyncing the same database - and executeInReadLock is a SHARED lock. The suspend flag is first-caller-owned (putIfAbsent), so the second thread (a) skips waitForCurrentFlushToComplete and can read files while a flush batch is still mid-write, and (b) keeps streaming while the owner's exit synchronously flushes the deferred batches to disk: torn reads either way. Fix: removed the dead executed[0] fallback and its stale "concurrent case" comment, and serialized the handler's snapshot and checksums paths with a per-database ReentrantLock so the single thread inside suspendFlushAndExecute always owns the suspension for its whole read. Requests beyond the semaphore limit still 503 fast. Overlap with OTHER callers (SQL BACKUP DATABASE, database verify) is a pre-existing exposure of the ownership model, documented at the lock, out of this handler's scope (would need refcounted suspension in PageManager - a follow-up design item, not a regression of #4958). Point 3 (timing-based leak test): chunkZeroFailureStillAwaitsBackground- Chunks reworked to a pure latch handshake, no wall-clock sleeps. Every background chunk parks at its first view access; chunk 0 throws only after one is provably parked; a releaser thread frees them only once the caller is genuinely parked in awaitFutures (Java-level WAITING - a preempted thread still reports RUNNABLE, so CI load cannot fake it). Broken path: execute() unwinds while every chunk is still parked, so the completion latch is provably still up at capture - deterministic red in both directions. Red-check performed: with the chunk-0 try/finally temporarily reverted the test fails on the intended assertion; restored byte-identically, then green 3/3 (0.09s vs the old ~0.5s). Acknowledged without change (reviewer confirmed correct): - Point 2: createWALFilePool counter seeding - seed only matters on the first pool creation with preserved .wal files; post-checkIntegrity call finds nothing by design. - Point 4: getStats() snapshot fix, LocalBucket getMaxContentSize() division safety, BufferBloomFilter unsynchronized mightContain under the build-then-publish contract. Tests green: PartitionedTriangleOpCallerRunsTest 2/2 (x3), SnapshotHttpHandlerSuspendLockTest 3/3 (new), SnapshotHttpHandler- DisconnectTest 7/7, SnapshotWriteStallTest 4/4, SnapshotThrottleTest 2/2, SnapshotManifestVerificationTest 8/8. (cherry picked from commit 5af8d87)
…document lock-map lifetime The supplementary review confirmed the round-5 SnapshotHttpHandler fix sound and self-confirmed two earlier items (getTransaction delta clamp, gatherPageStatistics restore-on-exception). Two nits taken: - WALFile.append: one-line comment pinning the single-writer assumption the partial-write loop inherits from the pre-fix code (appends are serialized by acquire(); the local writePos tolerates partial writes, not concurrent writers). - perDatabaseSuspendLock: documented that entries are deliberately never pruned - one small lock per database NAME ever snapshotted, bounded by the server's database count; pruning on drop would need lifecycle callbacks this handler does not have. Note for the record: the review's 'carry-over' about the sleep-based PartitionedTriangleOpCallerRunsTest is stale - round 5 (5af8d87) already replaced it with a deterministic CountDownLatch handshake, red-checked in both directions. (cherry picked from commit 3b5e2da)
…caffolding trim
Two deferred items from the audit's final review rounds:
- The invalid-MAX_PAGE_RAM ConfigurationException printed the byte value
with an 'MB' suffix (maxRAM is already multiplied by 1024*1024 when the
message is built); it now divides back so a bad value reads in the unit
it names.
- The review-round chronology left in comments across the audit-touched
files ('#NNNN review round N', 'taken after three rounds', ...) is
trimmed to plain issue references - the invariant statements stay, the
PR-history narration goes, as the final #5063/#5060/#5070 rounds asked.
No behavior change beyond the message unit. Lifecycle, commit-ordering,
context-lifecycle and flush-robustness suites green.
(cherry picked from commit 6c70024)
…own their windows PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every caller's callback regardless (#4958). With two concurrent suspenders on the same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot serving - any combination), the non-owner (a) skipped waitForCurrentFlushToComplete, so it could read a page while a flush batch was mid-write, and (b) kept streaming while the owner's exit synchronously flushed the deferred batches to disk - torn reads either way. The suspension is now a per-database REFCOUNT: - setSuspended(db, true) increments the count under the existing per-database suspend lock; it returns true only for the first suspender (0 -> 1). - setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach, Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just drops one reference and the database stays suspended for the remaining suspenders. An unbalanced release is a no-op instead of corrupting state. - A new suspender arriving while the last release is mid-way through the deferred-batch writes waits (timed, uninterruptible with interrupt-flag restore) until the resume completes, so a fresh window can never overlap those page writes. The gate (resumingDatabases) is cleared in a finally that also heals a stuck count if the resume ever escapes with an exception. - PageManager.suspendFlushAndExecute acquires/releases one reference per caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an interrupt during the wait no longer leaks the suspension (pre-existing leak: the flag was set before the wait and never restored on throw). The wait is cheap for non-first suspenders (the flush thread is parked deferring). The #4728 deferred-RAM backpressure accounting and the #5012 per-database suspend bookkeeping are unchanged: batches deferred across overlapping windows are flushed exactly once, by the last suspender's exit. Decision on the HA SnapshotHttpHandler per-database lock (#5063 review round 5): it STAYS, documented as resource discipline rather than correctness. With refcounting it is no longer needed to own the suspension, but it serializes same-database zip streaming: two followers resyncing the same multi-GB database at once would double the read I/O and keep flushing suspended for the UNION of both windows, growing the deferred backlog toward the #4728 cap. TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the pre-fix code (stash-run-unstash); all three methods failed on the exact defect: - overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false after the first of two overlapping suspendFlushAndExecute callers exited while the second was still inside its callback (expected true, was false). - setSuspendedIsRefCounted: the first release of two suspenders cleared the flag (expected release to return false and the db to stay suspended). - suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired immediately while the resume was mid-way through the deferred writes (contract test for the new gate; pre-fix it became a non-owner). PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the resume's count-check now takes the per-database lock, so it serializes behind the flush thread's paused suspended-check and the deferred batch is flushed synchronously in Phase 1 rather than re-enqueued; the assertion now accepts either outcome (flushed or re-enqueued) and still rejects the stranded case. The fake page's file id is now non-existent so the (now reachable) synchronous flush cannot write into a real file of the test database. Verification (all green): - engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest, PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest, PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest, Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest, Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest, PageManagerReadCache*Test (28 tests, 1 skipped stress test) - ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest, SnapshotThrottleTest (9 tests) - integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's suspendFlushAndExecute end-to-end) (cherry picked from commit e3fd04a)
…stats math, LSM counter drift, context prune) Four small residuals collected from the 2026-07 audit follow-up PRs (#5060-#5063), plus a file-enumeration audit reported on the issue. 1. TransactionContext.kill() lock symmetry: kill() (test-only API) released explicitLockedFiles but nulled lockedFiles WITHOUT unlocking, so killing a transaction caught in COMMIT_1ST_PHASE (where lockFilesInOrder populates lockedFiles) leaked the LockManager entries until TransactionManager.kill() closed the whole lock manager. Fix mirrors reset()'s release block, using the pure getRequester() like every other release path. Test (red-first): Issue5067KillLockSymmetryTest drives commit1stPhase(true), kills the tx and asserts a foreign requester can lock the bucket file (returned NO on timeout before the fix). 2. LocalBucket.updatePageStatistics free-space math: the threshold denominator was getPageSize() - contentHeaderSize, the same header overstatement #4958 fixed in gatherPageStatistics. Both now measure against the usable content region (physical size minus BasePage.PAGE_HEADER_SIZE minus the content header). Only skews the GATHER_STATS_MIN_SPACE_PERC threshold by the 8-byte header, no deterministic public observation point; covered by the existing bucket/stats suites. 3. LSMTreeIndexMutable currentMutablePages drift on rollback: createNewPage() increments the counter eagerly inside the transaction, so a rollback (e.g. a commit failed in 1st phase after applying index changes) discards the pages but not the increments; the counter drifted upward for the rest of the run (self-correcting only on reload after #5063's onAfterLoad fix) and inflated the auto-compaction scheduling check. onAfterCommit now clamps the counter to the real page count (the transaction's page counters are already published at that point), keeping the drift from scheduling compaction early without touching the rollback path. Test (red-first): Issue5067MutablePagesCounterDriftTest creates index pages via direct mutable-index puts in a rolled-back tx (counter 9 vs 1 real page before the fix) and asserts a subsequent commit re-aligns it. 4. DatabaseContext empty-entry retention (appended on the issue from PR #5060 final review): since the closing thread no longer prunes foreign CONTEXTS entries (that removal raced the owner's init() re-registration, the #4939 fix), an empty per-thread entry lingered for any live thread that opened+closed a database, accumulating on large long-lived pools (~500 Undertow workers) under open/close churn. The periodic sweep (invoked from init() every 1000th call) now opportunistically drops live threads' empty entries with a claim/re-check protocol: value-keyed remove of the exact entry, re-check emptiness, putIfAbsent the same entry back if the owner repopulated concurrently. Ordering argument documented inline: the owner's map.put always precedes its CONTEXTS registration check in init(), so either the re-check sees the repopulation and restores, or the owner sees the removal and re-registers; no live registration can be lost. No rollbacks run in the new branch, so the two-level claim discipline is untouched; the prune is allocation-free. Test (red-first): DatabaseContextLifecycleTest# sweepPrunesEmptyEntryOfLiveThreadAfterForeignClose, including owner re-registration after the prune. 5. Node-local file-enumeration audit (.wal.corrupt evidence files, report only): FileManager registration (extension allowlist), full backup and snapshot serving (registered ComponentFiles + explicit .ts.sealed), WAL adoption (endsWith(".wal") cannot match ".wal.corrupt"), fingerprint (suffix allowlist) and the ha-raft checksum (skip-list already extended in #4958) are all safe; no code changes needed. Details on the issue. Tests: the three new red-first tests plus ACIDTransactionTest, ExplicitLockingTransactionTest, LockTimeoutRetryTest, DatabaseContextLifecycleTest (9/9), Issue4511/4547 lock-leak tests, TransactionContextRemoveFileTest, ProtocolContextTest, Issue4958StorageStatsTest, LocalBucketRecordPositionTest, Issue4960 LSM counter/close tests, ConcurrentCompactionTest, MultipleDatabasesTest - all green. (cherry picked from commit 55f3980)
Fixes the "pools-and-lows" group of the 2026-07 engine audit (tracking issue #4962): closes #4952, closes #4957, closes #4958 (fixed items listed below), closes #4960 (fixed items listed below).
Per-issue verdicts
PartitionedTriangleOpnow runs chunk 0 on the calling thread (caller-runs-chunk-0 discipline ofparallelForRange) instead of submitting all chunks and blocking - removes the pool-starvation deadlock risk when reached from a pool thread.TimeSeriesEngine.appendBatchfalls back to sequential in-thread shard writes when the calling thread has an enclosing transaction (honors theappendSamplesthreading contract; keeps parallel dispatch otherwise).getStats()snapshot semantics + read-only NPE guard; cache-miss counter actually counted; nestedsuspendFlushAndExecuteruns the callback; preserved WALs renamed to.wal.corrupt+ WAL pool counter seeded past existing files (and the ha-raft snapshot checksum skips the preserved.corruptfiles like it already skipped.wal);LocalBucketfree-space stats measured on the content region with thread-safe counters.BufferBloomFilterhardened (modulo bound, atomicadd, k=2 probes from the Murmur64 halves);LSMTreeIndex.mutablemadevolatile;close()cancels a scheduled compaction instead of a silent no-op and logs when one is in progress;splitIndexverifies the new-file lock outcome;onAfterLoadrestores the uncompacted-pages counter from the file instead of hardcoding 1 (auto-compaction was deferred by up to a full threshold of new pages after every restart).Items deliberately left open
activeWALFilePoolelement publication: a proper fix is anAtomicReferenceArrayrefactor acrossTransactionManager(a conflict epicenter for the sibling audit branches); a minimal VarHandle variant was prototyped and discarded for the same reason. The committer's 10 ms retry loop re-reads the element through a synchronizedacquire, bounding staleness in practice. Marked as remaining on the issue.waitAllPagesOfDatabaseAreFlushedforever-loop while suspended: already fixed by the [storage] Flush-thread IOException drops the rest of the batch and hangs close() #4928 bounded no-progress wait (verified against current main).createNewPagecounter drift on rollback (second half of thecurrentMutablePagescheckbox): still open; the reload undercount - the impactful half - is fixed here, and the drift self-corrects on the next reload with that fix in place.getKeys()descending O(n^2): perf-only, no correctness impact.Red-first evidence
Every deterministic finding got a failing test before the fix (details in the commit messages):
PartitionedTriangleOpCallerRunsTest: chunk 0 observed onArcadeDB-QueryWorker-1instead of the calling thread (the deadlock itself is a scheduling race; the test pins the fix's thread-affinity contract).Issue4957AppendBatchTransactionTest: liveArcadeDB-TS-Shard-*threads spawned by a batch appended inside a transaction (lazy pool-thread creation makes the forbidden dispatch deterministically observable).Issue4958WALLowSeverityTest: crafted corrupt page header madeByteBuffer.allocate(Integer.MAX_VALUE)throw anOutOfMemoryErrorthat escaped the recovery guard and killed the surefire fork.Issue4958StorageStatsTest: stats inflation with polling, read-only NPE, cache-miss stuck at 0, nested suspend silently skipping the callback (the single production caller is full backup - the nested case produced a silent no-op backup).Issue4958PreservedWALTest: straytxlog_0.walgrew from 64 bytes after one commit (adopted as active WAL); corrupt-gap file survived under its.walname.Issue4960LSMCloseDuringCompactionTest:close()left the indexCOMPACTION_SCHEDULEDand open.Issue4960LSMReloadCompactionCounterTest: after a reopen the counter read 1 while the reloaded file held 4 uncompacted pages.BufferBloomFilterCorrectnessTest: honest note - the dropped-bit race did not reproduce deterministically (saturation masks drops; unsaturated filters make same-byte interleavings rare), so the atomicity fix is verified analytically and by contract; the no-false-negative property is tested single- and multi-threaded.Issue4508TornWALRecoveryTestandWALVersionGapRecoveryTestwere updated for the deliberate behavior change (preserved corrupt WALs now carry the.corruptsuffix).Tests
com.arcadedb.graph.**,com.arcadedb.index.**,com.arcadedb.engine.**(includesengine.timeseries) with-DexcludedGroups=benchmark,slow: 1296 tests, 0 failures, 0 errors (re-run after the follow-up commit).SnapshotManagerTest+SnapshotManifestVerificationTest: 13 tests, 0 failures.Conflict risks (files sibling audit branches may touch)
docs/release-26.7.2.md- every audit branch appends here; conflict expected and trivial.engine/src/main/java/com/arcadedb/engine/TransactionManager.java,PageManager.java- shared with the WAL/tx sibling groups (changes here are small and localized: getStats, createWALFilePool seeding, checkIntegrity rename, cache-miss counter, suspendFlushAndExecute).engine/src/main/java/com/arcadedb/index/lsm/LSMTreeIndex.java,LSMTreeIndexMutable.java- just modified by the merged fix/4946-4947 branch; these changes were written against that state.engine/src/test/java/com/arcadedb/engine/Issue4508TornWALRecoveryTest.java,WALVersionGapRecoveryTest.java- assertions updated for the.corruptrename.ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java- one-line skip-list extension; sibling HA branches may touch this file.