Skip to content

fix(#4952,#4957,#4958,#4960): pool discipline, TimeSeries threading, storage/WAL and LSM low-severity cleanups (2026-07 audit) - #5063

Merged
lvca merged 9 commits into
mainfrom
fix/4952-4957-4958-4960-pools-lows
Jul 7, 2026
Merged

lvca merged 9 commits into
mainfrom
fix/4952-4957-4958-4960-pools-lows

Conversation

@lvca

@lvca lvca commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

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

Issue Verdict Summary
#4952 fixed PartitionedTriangleOp now runs chunk 0 on the calling thread (caller-runs-chunk-0 discipline of parallelForRange) instead of submitting all chunks and blocking - removes the pool-starvation deadlock risk when reached from a pool thread.
#4957 fixed TimeSeriesEngine.appendBatch falls back to sequential in-thread shard writes when the calling thread has an enclosing transaction (honors the appendSamples threading contract; keeps parallel dispatch otherwise).
#4958 fixed (7 of 9 checkboxes; 1 already-fixed, 1 left open with rationale) WAL read/write helpers loop to completion with per-call buffers; per-page delta clamped to remaining file size (OOM-Error escape during recovery); getStats() snapshot semantics + read-only NPE guard; cache-miss counter actually counted; nested suspendFlushAndExecute runs the callback; preserved WALs renamed to .wal.corrupt + WAL pool counter seeded past existing files (and the ha-raft snapshot checksum skips the preserved .corrupt files like it already skipped .wal); LocalBucket free-space stats measured on the content region with thread-safe counters.
#4960 fixed (5 of 6 checkboxes; the rollback counter drift and the DESC rescan left open with rationale) BufferBloomFilter hardened (modulo bound, atomic add, k=2 probes from the Murmur64 halves); LSMTreeIndex.mutable made volatile; close() cancels a scheduled compaction instead of a silent no-op and logs when one is in progress; splitIndex verifies the new-file lock outcome; onAfterLoad restores 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

Red-first evidence

Every deterministic finding got a failing test before the fix (details in the commit messages):

  • PartitionedTriangleOpCallerRunsTest: chunk 0 observed on ArcadeDB-QueryWorker-1 instead of the calling thread (the deadlock itself is a scheduling race; the test pins the fix's thread-affinity contract).
  • Issue4957AppendBatchTransactionTest: live ArcadeDB-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 made ByteBuffer.allocate(Integer.MAX_VALUE) throw an OutOfMemoryError that 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: stray txlog_0.wal grew from 64 bytes after one commit (adopted as active WAL); corrupt-gap file survived under its .wal name.
  • Issue4960LSMCloseDuringCompactionTest: close() left the index COMPACTION_SCHEDULED and 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.

Issue4508TornWALRecoveryTest and WALVersionGapRecoveryTest were updated for the deliberate behavior change (preserved corrupt WALs now carry the .corrupt suffix).

Tests

  • 16 new regression tests across 8 classes, all green.
  • Focused suites com.arcadedb.graph.**, com.arcadedb.index.**, com.arcadedb.engine.** (includes engine.timeseries) with -DexcludedGroups=benchmark,slow: 1296 tests, 0 failures, 0 errors (re-run after the follow-up commit).
  • ha-raft SnapshotManagerTest + SnapshotManifestVerificationTest: 13 tests, 0 failures.
  • OpenCypher triangle/GAV algo tests: 62 tests, 0 failures (AlgoTriangleCount, AlgoLocalClusteringCoefficient, GAVEligibility, MatchRelationshipStepOptimization).

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 .corrupt rename.
  • ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java - one-line skip-list extension; sibling HA branches may touch this file.

…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.
@mergify

mergify Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 16 complexity

Metric Results
Complexity 16

View in Codacy

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +833 to +834
final File[] existingWALFiles = new File(database.getDatabasePath()).listFiles((dir, name) -> name.endsWith(".wal"));
if (existingWALFiles != null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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)

Comment on lines +62 to +65
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);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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);
}

Comment on lines +392 to +395
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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: PR #5063 - pool discipline, TimeSeries threading, storage/WAL & LSM cleanups

Overall 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 (MurmurHash.hash64, BasePage.getMaxContentSize, LockManager.LOCK_STATUS, imports, etc.) all exist and line up. Nice work.

What looks correct and well done

Minor observations (non-blocking)

  1. BufferBloomFilter.mightContain is unsynchronized while add is synchronized. For the documented build-then-publish usage this is fine, but there is no happens-before on the buffer bytes unless the filter is safely published (e.g. via a final field / AtomicReference) to readers. Worth a one-line note at the wiring-in point ([lsm] Low-severity LSM cleanups (BufferBloomFilter, unsafe publication, ops nits) #4960 follow-up) so a future caller doesn't publish it through a plain field and reintroduce a visibility-based false negative.
  2. synchronized add will become a contention point if the filter is ever populated on a write hot path. Acceptable now (not wired in), but flag it for the wiring-in PR - a CAS/VarHandle-per-byte or per-region lock may be preferable there.
  3. Bloom buffer sizing assumes slots is a multiple of 8: with e.g. slots=10 the caller-provided Binary(slots/8) is 1 byte but the max byte index is (slots-1)/8 = 1, out of bounds. Pre-existing and callers use powers of two, but an assertion/ceilDiv in the constructor would make the contract explicit.
  4. TransactionManager.activeWALFilePool remains non-volatile and getStats() is called from the Profiler thread. Reading it into a local (final WALFile[] pool = activeWALFilePool) with a null-guard is a real improvement over the old direct iteration, so this is strictly better than before; just noting the field itself still isn't safely published (pre-existing).
  5. cacheMiss semantics change: the counter now increments on any readCache miss, including the truly-not-found path, not only successful loads. That is the correct definition for a hit/miss ratio, but if any dashboard previously treated cacheMiss as "pages loaded from disk," the meaning shifts slightly. Fine, just worth being aware of.

Tests

Coverage 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 Issue4508TornWALRecoveryTest assertion update for the .corrupt rename is appropriate. The TimeSeriesEngine in-thread fallback is validated by observing forbidden TS-Shard-* thread creation, which is a good deterministic proxy for the threading contract.

I could not run mvn compile in this sandbox (approval gate), but imports and referenced APIs all check out, and the PR reports the focused suites green (1295 tests, 0 failures).

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

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 38.02817% with 88 lines in your changes missing coverage. Please review.
✅ Project coverage is 36.10%. Comparing base (74d3fd5) to head (7eb158d).
⚠️ Report is 67 commits behind head on main.

Files with missing lines Patch % Lines
...m/arcadedb/server/ha/raft/SnapshotHttpHandler.java 29.62% 19 Missing ⚠️
...in/java/com/arcadedb/engine/BufferBloomFilter.java 0.00% 16 Missing ⚠️
...encypher/executor/steps/PartitionedTriangleOp.java 0.00% 14 Missing ⚠️
...n/java/com/arcadedb/engine/TransactionManager.java 57.14% 8 Missing and 4 partials ⚠️
...m/arcadedb/engine/timeseries/TimeSeriesEngine.java 0.00% 7 Missing ⚠️
...main/java/com/arcadedb/index/lsm/LSMTreeIndex.java 22.22% 6 Missing and 1 partial ⚠️
...ine/src/main/java/com/arcadedb/engine/WALFile.java 70.00% 4 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/engine/LocalBucket.java 76.92% 2 Missing and 1 partial ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 60.00% 0 Missing and 2 partials ⚠️
...va/com/arcadedb/index/lsm/LSMTreeIndexMutable.java 50.00% 1 Missing ⚠️
... and 1 more
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code Review: PR #5063 - pool discipline, TimeSeries threading, storage/WAL and LSM low-severity cleanups

Overall this is a high-quality, well-scoped PR. The red-first (failing test before fix) discipline, the per-hunk #issue comments explaining why each change is correct, and the honest "deliberately left open" section all make this easy to review. I verified each source change against the surrounding code and existing patterns. Findings below are mostly confirmations plus a few minor observations - I found no blocking correctness issues.

Strengths / confirmed-correct

Minor observations / questions (non-blocking)

  1. BufferBloomFilter - add is synchronized but mightContain is not. This correctly fixes the dropped-bit read-modify-write race between concurrent adds, and the "build then publish for reading" contract makes it safe today. Worth calling out for whoever wires it into the LSM read path: without a happens-before between a concurrent add and mightContain (i.e. safe publication of the whole filter), a reader could observe a stale byte and return a false negative - the exact failure the fix guards against. A one-line note on mightContain ("only safe after the filter is fully published; no concurrent adds") would preserve that intent. Also note capacity (slots) and the backing Binary size must stay in sync (buffer >= ceil(slots/8) bytes) - pre-existing, but now that floorMod can address the top byte it is load-bearing.

  2. LSMTreeIndexMutable.onAfterLoad - currentMutablePages = Math.max(1, getTotalPages()). getTotalPages() includes the header/root page, so this can over-count the mutable pages by the header count, nudging auto-compaction slightly earlier after a restart. Since this is pacing-only (and strictly better than the old hardcoded 1), it's fine - just flagging that "reflects the pages actually in the file" in the test comment is approximate rather than exact.

  3. TransactionManager.checkIntegrity rename-failure path. If renameTo(...".corrupt") returns false, the code logs a WARNING and continues, leaving the file under its .wal name where the very next createWALFilePool() could re-scan/adopt it. Best-effort-with-warning is a reasonable degradation, but on some filesystems renameTo can fail silently; consider Files.move(...) (throws with a cause) if you want the failure to be louder/atomic. Not required.

  4. Issue4957AppendBatchTransactionTest relies on Thread.getAllStackTraces() to detect live ArcadeDB-TS-Shard-* threads. It's isolated correctly (thread names embed the per-engine type name), but liveness-based assertions are inherently a bit fragile across CI environments. It passes as written; just noting it's the least-robust of the new tests.

Style / conventions

  • Matches CLAUDE.md conventions well: final on locals/params, assertThat(...).isTrue() style, no System.out, Apache headers present, no new dependencies, no em-dashes in code. Nice.
  • The docs/release-26.7.2.md entry is thorough and the "deliberately left open" items are documented with rationale on the issues - good traceability.

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).
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

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

  • PartitionedTriangleOp caller-runs-chunk-0 (#4952): chunk 0 now runs in-thread and only 1..N-1 are submitted; futures is sized threadCount-1, launched tracks the actual count, and awaitFutures(futures, launched) never touches the trailing nulls. Edge cases check out: threadCount==1 submits nothing and runs the whole range in-thread; the start >= nodeCount break leaves the skipped partialCounts at 0. Correct and matches the parallelForRange discipline.
  • TimeSeriesEngine.appendBatch (#4957): the inThread branch writes sequentially and returns before ever dereferencing the null futures list; IOException propagates directly, consistent with the parallel path's unwrapping. Per-shard grouping is preserved in both branches. Good.
  • getCachedPage miss counter (#4958): moving cacheMiss.incrementAndGet() ahead of the early return page counts exactly one miss per real miss regardless of load outcome. Correct.
  • TransactionManager.getStats() snapshot (#4958): confirmed the accumulators are only mutated at retirement in cleanWALFiles() (lines ~921-922), so the new "retired totals + live active counters computed on the fly" avoids both the polling inflation and the double-count at retirement. The pool != null guard fixes the read-only NPE. Correct.
  • WAL pool counter seeding (#4958): .wal.corrupt files are correctly excluded from the endsWith(\".wal\") scan, so renamed corrupt files are neither re-adopted nor re-scanned. Recovery builds its pool from the existing files via a separate path, so createWALFilePool() is only the fresh-pool path - seeding past stray txlog_N.wal here is the right behavior and won't orphan files on a clean restart (those are deleted on close).
  • WALFile read/write loops + delta clamp (#4958): per-call buffers + readFully loop + pos + deltaSize > getSize() guard (long arithmetic, no overflow) + EOFException -> null all line up with the existing "return null == truncated/corrupt" contract.
  • LocalBucket free-space stats (#4958): switching to getMaxContentSize() matches how the rest of the class computes available space (record positions are content-relative, e.g. lines 1845/1910), so the old getPageSize() form did overstate by the header size. Fix is consistent.
  • LSMTreeIndex (#4960): volatile mutable, the COMPACTION_SCHEDULED -> UNAVAILABLE CAS in close() (the scheduled task's own CAS will then fail cleanly), and the tryLockFile outcome check in splitIndex are all sound.

Minor observations (non-blocking)

  1. BufferBloomFilter.mightContain visibility. add() is synchronized but mightContain() reads the shared Binary bytes with no synchronization or volatile. The build-then-publish contract in the Javadoc makes this safe only if callers publish the filter through a safe-publication edge (final/volatile field, or a happens-before via a lock/queue). Since the class isn't wired in yet, consider adding a one-line note at the (future) call site, or documenting the publication requirement on the constructor, so a later integrator doesn't publish it via a plain field.

  2. BufferBloomFilter buffer sizing. There's no validation that the provided Binary holds at least ceil(capacity/8) bytes. With capacity not a multiple of 8 the top bits can index a byte past a tightly-sized buffer. Pre-existing and all tests use power-of-two slots, but a cheap constructor assert would harden it before it goes on the read path.

  3. LocalBucket.changesFromLastStats reset race. Increments now happen off-lock (atomic) while the reset set(0L) runs inside the freeSpaceInPages monitor. Increments landing between the get() > 0 check and the set(0L) are lost. This is only a stats-gathering heuristic (strictly better than the previous non-atomic long), so it's fine - just noting it's not fully lock-consistent.

Tests

Coverage is strong: 16 new regression tests across 8 classes, red-first where deterministic, and the honest notes on the two non-deterministic races (BufferBloomFilter dropped-bit, the triangle deadlock scheduling race) are appreciated rather than overclaiming. Issue4508TornWALRecoveryTest / WALVersionGapRecoveryTest are correctly updated for the deliberate .corrupt rename, and the ha-raft SnapshotManager skip-list extension keeps the snapshot checksum consistent with it.

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
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: PR #5063 - pool discipline, TS threading, storage/WAL and LSM low-severity cleanups

Reviewed 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 #issue reference and rationale, the "deliberately left open" items are called out honestly, and nearly every fix ships a red-first regression test. The changes are small and localized as advertised. Overall LGTM - the notes below are minor/non-blocking.

Strengths

  • Correctness fixes are sound. BufferBloomFilter now reduces every bit index with Math.floorMod(..., capacity) (the old h > capacity ? h % capacity : h let h == capacity address one bit past the region), add() is synchronized, and the constructor validates buffer.limit() >= ceil(slots/8). The publication contract for the lock-free mightContain is clearly documented.
  • PartitionedTriangleOp now follows the same caller-runs-chunk-0 discipline as GraphAlgorithms (verified against lines 99/760/880 of olap/GraphAlgorithms.java): submit chunks 1..N-1, run chunk 0 in-thread, awaitFutures(futures, launched). The start >= nodeCount break plus the launched counter correctly avoids awaiting trailing null slots. Consistent with the existing convention.
  • WAL hardening is solid: readFully loop closes the partial-channel.read decode-garbage bug, append loops until fully written, and the pos + deltaSize > getSize() clamp closes the real ByteBuffer.allocate(Integer.MAX_VALUE) OOM-escape during recovery (nicely proven by Issue4958WALLowSeverityTest).
  • .wal.corrupt rename + logFileCounter seeding is a genuine data-safety fix (preserved WALs were being re-adopted as active because WALFile opens rw without truncation). Good that Files.move is used over renameTo and that the ha-raft snapshot checksum was updated to skip .corrupt symmetrically with .wal.
  • getStats() snapshot semantics correctly stops the polling-frequency inflation + double-count-at-retirement, and adds the read-only null-pool guard.
  • Test coverage is strong (16 new regression tests), and the honest note that the BufferBloomFilter dropped-bit race doesn't reproduce deterministically is appreciated.

Minor observations (non-blocking)

  1. PartitionedTriangleOp - chunk-0 exception path. If countRange(...) for chunk 0 (run on the calling thread) throws, control never reaches awaitFutures, so the already-submitted chunks 1..N-1 are neither awaited nor cancelled and keep writing into partialCounts after the caller has unwound. This mirrors the pre-existing pattern in GraphAlgorithms, so it's consistent rather than a new regression, but a try { chunk0 } finally { awaitFutures(...) } (or cancel-on-throw) would make the operator fully leak-safe. Low severity given the bounded pool.

  2. LocalBucket free-space semantics change. Switching the denominator/numerator from getPageSize() to page.getMaxContentSize() in gatherPageStatistics() changes the actual free-space values fed into freeSpaceInPages, which drives space-reuse decisions (not just a reported metric). The fix is correct in principle (the header was being counted as free), but it's worth confirming the space-reuse regression tests exercise the REUSE_SPACE_MODE.HIGH path so the changed thresholds don't shift reuse behavior unexpectedly.

  3. gatherPageStatistics failed-scan retry. On exception the counter is restored with a single incrementAndGet() rather than the count that getAndSet(0L) consumed, so a failed scan can undercount pending changes. Acknowledged as pacing-only in the comment; fine, just noting the asymmetry.

  4. Issue4957AppendBatchTransactionTest relies on Thread.getAllStackTraces() observing lazily-created ArcadeDB-TS-Shard-* threads - the author already flags this as the least robust of the new tests. It's deterministic as written, but if it ever flakes in CI, instrumenting the shard executor dispatch count would be the more robust signal.

  5. BufferBloomFilter is not yet wired into the LSM read path (dead code hardened ahead of use). That's a reasonable "fix before wiring" call and clearly documented; just flagging that the concurrency contract (add under lock, mightContain lock-free only after safe publication) will need to be honored by whoever integrates it.

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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code review — PR #5063 (pools/TimeSeries/WAL/LSM low-severity audit)

Reviewed all 11 production changes and the 8 new/updated test classes against CLAUDE.md. This is a high-quality, well-documented batch: each fix is scoped, the inline #issue comments explain the "why," and the red-first tests are genuinely tied to the defects. Nothing here looks blocking. Below are the details I verified plus a few minor suggestions.

Verified correct

  • PartitionedTriangleOp — caller-runs-chunk-0 matches parallelForRange discipline. futures[threadCount-1], the launched counter, awaitFutures(futures, launched), and the partialCounts[threadIdx] mapping all line up; empty trailing chunks (start >= nodeCount) are correctly skipped and leave partialCounts at 0. The try/finally + chunk0Completed handling keeps chunk-0's exception primary while still guaranteeing no background chunk outlives the frame.
  • BufferBloomFilter — synchronized add / lock-free mightContain with the documented build-then-publish contract, Math.floorMod(..., capacity) closing the one-bit-past-the-region bug, the requiredBytes guard, and k=2 probes from the two hash64 halves (hash64 exists with the used signature).
  • TransactionManager.getStats() snapshot semantics + read-only null-pool guard; createWALFilePool counter seeding; checkIntegrity .corrupt rename.
  • PageManager — cacheMiss.incrementAndGet() now fires exactly once on a real miss; nested suspendFlushAndExecute runs the callback while only the outermost caller owns/restores the suspend flag.
  • WALFile — per-page deltaSize clamp to remaining file (pos + deltaSize > getSize()), full-read/full-write loops, and EOFException->null handled in both getTransaction and the footer-scan catch (IOException) (EOFException is an IOException).
  • LocalBucket — volatile timeOfLastStats + AtomicLong changesFromLastStats with getAndSet(0L) at the decision point and restore-on-exception; getMaxContentSize() replacing getPageSize() for free-space math.
  • LSMTreeIndex — volatile mutable, close() also CAS-ing COMPACTION_SCHEDULED -> UNAVAILABLE (with a loud WARNING for COMPACTION_IN_PROGRESS), and splitIndex checking the tryLockFile outcome.
  • TimeSeriesEngine — inThread = database.isTransactionActive() gate keeps shard writes in-thread under an enclosing tx; the futures-null path with continue/early return is consistent.

Minor suggestions (non-blocking)

  1. WALFile.readInt/readLong now allocate a fresh ByteBuffer per field read. During recovery each transaction reads ~7 ints/page across many pages, so this trades the old shared-buffer thread-safety bug for a burst of tiny allocations - slightly against the repo's GC mantra. Recovery is a rare path so it's acceptable, but a ThreadLocal reusable buffer (or a single scratch buffer threaded through getTransaction) would keep both correctness and low churn.
  2. checkIntegrity uses Files.move(...) without REPLACE_EXISTING. If a same-named <name>.wal.corrupt already exists from a prior aborted recovery, the move throws FileAlreadyExistsException, which is logged and swallowed - leaving the original .wal in place. On the next restart that leftover .wal can be re-scanned and re-aborted, the exact loop this fix aims to break. Consider StandardCopyOption.REPLACE_EXISTING or a uniquified suffix.
  3. LSMTreeIndexMutable.onAfterLoad: currentMutablePages = Math.max(1, getTotalPages()). getTotalPages() includes the page-0 header, so this may overcount data pages by one and schedule auto-compaction a single page early. Benign, but worth confirming currentMutablePages semantics elsewhere (does createNewPage's increment exclude the header?) so the counter stays consistent across a create-vs-reload lifecycle.
  4. Test tagging. None of the new tests carry @Tag("slow")/@Tag("benchmark"). The 2000-node graph and multithreaded bloom tests look fast enough to stay unmarked, but per CLAUDE.md please confirm they stay well under a second in CI; the PartitionedTriangleOpCallerRunsTest thread-affinity assertion in particular is worth a sanity check for flakiness under a loaded shared pool.

Test coverage

Strong. 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 .corrupt rename behavior change.

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.
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

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 - try/finally in PartitionedTriangleOp, Files.move(..., REPLACE_EXISTING) in checkIntegrity, and the BufferBloomFilter bounds checks are all present in the tree, beyond what the first commit's diff shows).

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 CLAUDE.md. Nice job.

A few observations, one of which is worth a second look before merge.

1. suspendFlushAndExecute semantic change vs. the HA snapshot path (worth confirming)

The change makes the callback always run, even for a non-owning (nested/concurrent) caller where setSuspended returns false. That is correct for the intended nested-backup case, but it changes behavior for a scenario the HA code explicitly coded around:

ha-raft/.../SnapshotHttpHandler.java:174-187 does:

final boolean[] executed = { false };
db.getPageManager().suspendFlushAndExecute(db, () -> { executed[0] = true; serveSnapshotZip(...); });
if (!executed[0]) {
  // Flush was already suspended by another concurrent snapshot request; serve directly.
  serveSnapshotZip(...);
}

With the new semantics executed[0] is now always true, so:

  • the if (!executed[0]) fallback branch (and the explanatory comment at lines 175-178) is now dead code - please clean it up or re-verify, since a stale "this path handles the concurrent case" comment is a future-maintainer trap;
  • more importantly, a concurrent (cross-thread, not nested-same-thread) non-owning caller now runs serveSnapshotZip on its own thread while a different thread owns the suspension. When the owner's callback returns it calls setSuspended(db, false) and the flush thread can resume - potentially mid-read for the non-owner still streaming files. This isn't a regression (the old fallback also read outside its own suspension), and HA guards this with a read lock + CONCURRENCY_SEMAPHORE, so it may be unreachable in practice - but the "only the outermost caller owns the flag" comment quietly assumes strictly-nested, same-thread usage. Please confirm two different threads can't be inside suspendFlushAndExecute(db, ...) for the same db at once, or the non-owner can observe a resumed flush.

FullBackupFormat and PostVerifyDatabaseHandler callers look unaffected.

2. createWALFilePool counter seeding - looks correct, one note

The seed scan (endsWith(".wal")) correctly ignores the renamed .wal.corrupt files, and it runs single-threaded at open, so the non-atomic get()/set() loop is fine. Worth noting the seed only matters on the first pool creation (constructor) when preserved .wal files survive a crash; the post-checkIntegrity call finds nothing because files were dropped or renamed - which matches the intent. No action needed.

3. PartitionedTriangleOpCallerRunsTest - timing-based leak assertion

chunkZeroFailureStillAwaitsBackgroundChunks relies on Thread.sleep(150) in the stubbed view plus Thread.sleep(300) after unwind, then asserts lastBackgroundCall < unwoundAt. This is a wall-clock race; under a loaded CI runner a background thread could wake late and still be scheduled after the 300ms window, giving a false green (or, if the finally-await is ever broken, a flaky red). A CountDownLatch/CyclicBarrier handshake would make the leak-detection deterministic. The other test in the class (thread-affinity of chunk 0) is fine. Not blocking.

4. Minor

  • TransactionManager.getStats() snapshot fix is correct - the accumulators are only mutated at retirement (cleanWALFiles, ~line 927), so adding active files on the fly no longer double-counts. Good catch.
  • LocalBucket free-space now measured on getMaxContentSize(): division ... / (getMaxContentSize() - contentHeaderSize) stays safely positive for real page sizes; no new divide-by-zero risk.
  • BufferBloomFilter: mightContain reads unsynchronized while add is synchronized. Given the documented build-then-safely-publish contract (and that it's not yet wired in) this is acceptable, and the ctor bounds/slots % 8 validation closes the out-of-region write. Good.

Tests

Coverage is strong - 8 new classes, red-first evidence per finding, honest notes where a race couldn't be made deterministically (the bloom dropped-bit case). The WAL/preserved-file and reload-counter tests exercise the real restart paths. Only the timing-based leak test above would I harden.

Nothing here blocks merge in my view; item #1 (the HA executed[0] dead branch + cross-thread suspension assumption) is the one I'd want the author to confirm or tidy.

…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.
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

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 SnapshotHttpHandler executed[0] dead branch + the cross-thread suspension hazard opened by the suspendFlushAndExecute "always run the callback" change) has since been properly resolved by the round-5 perDatabaseSuspendLock. That fix is sound: the per-database ReentrantLock serializes both the snapshot-ZIP and checksum entries into suspendFlushAndExecute, so the single thread inside always owns the flush suspension for the whole read, the CONCURRENCY_SEMAPHORE still bounds admission, and executeInReadLock stays shared. The added SnapshotHttpHandlerSuspendLockTest and the honest comment about the residual BACKUP/verify exposure (a pre-existing property of the ownership model, out of this handler's scope) are the right call. Good work closing the loop.

Only new observations below; I won't rehash the earlier threads.

1. perDatabaseSuspendLock is never pruned (minor leak)

perDatabaseSuspendLock.computeIfAbsent(databaseName, ...) adds one ReentrantLock per distinct database name for the handler's lifetime and nothing ever removes it. In steady state this is bounded by the number of databases, so it's benign - but if databases are dropped and recreated under fresh names (or per-test churn on a long-lived server), the map grows without bound. If a drop hook is reachable from the handler's server reference, evicting the entry there would clean it up; otherwise a one-line note that the map intentionally lives for the handler's lifetime would save a future reader the double-take.

2. WALFile.append recomputes writePos from channel.size() once, then loops

long writePos = channel.size();
while (buffer.hasRemaining())
  writePos += channel.write(buffer, writePos);

The partial-write loop is correct (positional write advances the buffer, hasRemaining shrinks). This is safe only because appends to a given WALFile are already externally serialized - the same single-writer assumption the pre-fix channel.write(buffer, channel.size()) relied on, so no regression. Worth a one-line comment pinning that assumption, since the new local writePos reads at first glance like it could tolerate concurrent appenders (it can't - two concurrent appenders would both seed from the same channel.size()).

3. getTransaction delta clamp - correct, confirming the arithmetic

pos + deltaSize > getSize() promotes to long before the add (pos is long), so the deltaSize == Integer.MAX_VALUE case that motivated the fix cannot overflow the comparison. The clamp rejects exactly the records that can't fit in the remaining file, which is the intended pre-allocation guard. Issue4958WALLowSeverityTest pins the OOM-escape path.

4. gatherPageStatistics getAndSet(0L) / restore-on-exception - correct

The round-2/3 evolution (consume the counter atomically at the decision point, restore max(consumed, 1) on scan failure) is self-consistent: on firstRun with a throwing scan, timeOfLastStats stays 0, so the next call re-enters and retries - no permanently-lost stats, no double-scan wedge. Fine.

Tests

Coverage remains strong - red-first evidence per deterministic finding, the honest analytic note on the bloom dropped-bit race, and the updated .corrupt-rename assertions in the two existing WAL recovery tests. One carry-over from the prior review still worth a glance: PartitionedTriangleOpCallerRunsTest's leak assertion leans on Thread.sleep-based wall-clock windows; a latch/barrier handshake would make it deterministic under loaded CI. Not blocking.

Net: the fixes are surgical, well-documented with the why + issue number, and respect the pool-discipline rules in CLAUDE.md. Nothing here blocks merge; items 1-2 are small hardening/comment nits.

Review generated with Claude Code.

…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.
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

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)

  • PartitionedTriangleOp caller-runs-chunk-0 - chunk 0 covers [0, min(chunkSize, nodeCount)), submitted chunks cover t*chunkSize.. for t>=1, and awaitFutures(futures, launched) tolerates the trailing nulls left when start >= nodeCount breaks early (the impl skips nulls defensively). The try/finally with the chunk0Completed flag correctly keeps chunk 0's exception primary while still guaranteeing no background chunk outlives the frame.
  • LocalBucket.gatherPageStatistics - the getAndSet(0L) at the decision point plus restore-on-exception is a genuine improvement over the old get() > 0 / set(0) pair that dropped increments landing during the scan. The getMaxContentSize() switch is the right fix: record offsets are content-region-relative, so subtracting them from the physical getPageSize() overstated free space by the page header size on every page. The new denominator is consistent across all three sites.
  • TransactionManager.getStats() - correct. The accumulators are mutated only at file retirement (cleanWALFiles) and getStats() now produces an on-the-fly snapshot, eliminating both the polling-frequency inflation and the double-count-on-retirement. Read-only null-pool guard is a good catch.
  • createWALFilePool counter seeding and the .wal.corrupt rename are consistent: the listFiles(".wal") seed filter excludes .corrupt, so preserved files are neither re-adopted nor re-seeded, and SnapshotManager.computeFileChecksums skips them symmetrically. REPLACE_EXISTING correctly breaks the re-abort loop when a prior aborted recovery left a same-named .corrupt.
  • WALFile read/write loops and the pos + deltaSize > getSize() clamp are correct, and the single-writer assumption for append matches the existing acquire() serialization.
  • SnapshotHttpHandler per-database lock - correctly closes the ownership gap now that suspendFlushAndExecute always runs the callback. Lock ordering (dbSuspendLock -> read lock) is consistent and the lock is handler-local, so no inversion risk.
  • BufferBloomFilter - floorMod bound, synchronized add, k=2 probes, and the constructor size check are all correct hardening.

Minor points / suggestions (non-blocking)

  1. LSMTreeIndexMutable.onAfterLoad: Math.max(1, getTotalPages()) includes the header page in the count, so currentMutablePages is off by ~1 versus the true data-page count. Conservative and strictly better than the old hardcoded 1, but a one-line note that the header page is intentionally counted would avoid a future "why +1?" question.
  2. WALFile.readLong/readInt now allocate a fresh ByteBuffer per call. Recovery path only, so correctness is fine, but getTransaction can issue many per record. A single reusable buffer scoped to the getTransaction invocation would avoid the churn without reintroducing the shared-mutable-state bug the old static buffers had.
  3. PartitionedTriangleOp finally catches only RuntimeException. If a background chunk surfaces an Error from awaitFutures while chunk 0 also failed, the Error masks chunk 0's exception. Extreme edge (Error is typically fatal), acceptable, just flagging.
  4. SnapshotHttpHandler: holding dbSuspendLock across the whole ZIP stream serializes concurrent snapshot/checksum requests for the same database (e.g. two followers resyncing at once). Intended correctness tradeoff and documented, but worth being explicit that same-DB snapshot concurrency drops to 1.
  5. Comment style nits (cosmetic): several comments reference "fix(#4952,#4957,#4958,#4960): pool discipline, TimeSeries threading, storage/WAL and LSM low-severity cleanups (2026-07 audit) #5063 review round N", baking review iterations into permanent source; referencing the issue alone would age better. The ALL-CAPS block in LocalBucket.gatherPageStatistics is louder than surrounding house style.

Test coverage

Strong. 16 new regression tests across 8 classes, each tied to a specific finding with a documented red-first failure. The honest note on BufferBloomFilterCorrectnessTest (dropped-bit race not reproducing deterministically) is appreciated. All new tests are quick, so the absence of @Tag("slow") is correct (the heaviest is ~200k in-memory adds).

Verdict

Looks 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.

@lvca lvca self-assigned this Jul 7, 2026
@lvca lvca added this to the 26.7.2 milestone Jul 7, 2026
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Code Review: PR #5063 - Pool discipline, TimeSeries threading, storage/WAL and LSM cleanups

Thorough 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

  • PartitionedTriangleOp caller-runs-chunk-0 (#4952): the try/finally that guarantees submitted chunks 1..N-1 are always awaited even when chunk 0 throws is the subtle-but-correct part, and the chunkZeroFailureStillAwaitsBackgroundChunks test pins it with a pure latch handshake (no wall-clock sleeps). futures[] sized threadCount-1 with a launched counter and awaitFutures(futures, launched) correctly handles the early-break case where start >= nodeCount.
  • WALFile: the readFully loop + per-call buffers removes both the shared-unsynchronized-buffer hazard and the partial-read-decodes-garbage bug; the pos + deltaSize > getSize() clamp closes the OutOfMemoryError-escapes-recovery path cleanly, and the added EOFException -> return null matches the existing benign-corruption contract.
  • TransactionManager.getStats(): switching to snapshot semantics (accumulators read once, active files added on the fly) fixes the polling-inflation and read-only NPE in one move. The createWALFilePool counter-seeding correctly filters on .wal so preserved .wal.corrupt files are excluded from adoption.
  • SnapshotHttpHandler: the per-database ReentrantLock correctly closes the ownership gap in suspendFlushAndExecute (non-owner streaming files while the owner resumes flush mid-read). Good that SnapshotManager.computeFileChecksums was updated in the same PR to skip .corrupt so the new suffix does not diverge node checksums.
  • LocalBucket.gatherPageStatistics: getAndSet(0L) at the decision point plus restore-on-exception (addAndGet(max(consumed,1))) is the right way to avoid losing increments that land during a scan. Nice property: two concurrent callers cannot double-scan because only the one that wins getAndSet sees a non-zero count.

Minor observations / follow-ups

  1. LocalBucket comment style (gatherPageStatistics, ~line 2099): the round-3 restore comment is in ALL CAPS (THE COUNTER WAS ALREADY CONSUMED. RESTORE...), inconsistent with the sentence-case comments elsewhere in the file. Cosmetic only.

  2. PageManager.getCachedPage cache-miss semantics: moving cacheMiss.incrementAndGet() before loadPage now counts a miss even when loadPage returns null (page genuinely absent, !isNew). Arguably more correct as a "readCache miss" definition, but a slight semantic widening vs. "miss that loaded a page." Worth a one-line note on the metric if the hit/miss ratio is consumed downstream.

  3. WALFile.append loop: while (buffer.hasRemaining()) writePos += channel.write(buffer, writePos); is correct for a FileChannel; a theoretical write()==0 would spin, but that does not happen for regular file channels, so this is fine in practice. Noted only for completeness.

  4. SnapshotHttpHandler lock-after-semaphore ordering: dbSuspendLock.lock() (unbounded wait) is acquired after a CONCURRENCY_SEMAPHORE permit is already held, so a slow in-progress snapshot for DB X can pin a permit while a second same-DB request blocks on the lock, transiently reducing effective cross-database concurrency below HA_SNAPSHOT_MAX_CONCURRENT. Consistent with the intended per-DB serialization and acceptable, but worth being aware of under multi-follower resync.

  5. BufferBloomFilter: add synchronized while mightContain stays lock-free is the right build-then-publish trade-off and is well documented. Since the class is not wired into the read path yet, the eventual integration must honor the documented safe-publication requirement (final/volatile handoff) or the false-negative guarantee is lost - the javadoc already calls this out prominently.

Test coverage

Excellent. 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 concurrentAddsDoNotDropBits (race not provable in a single run, deterministic post-fix) and the latch-based determinism in the triangle-op leak test are the right level of rigor.

Nice work - no blocking issues found. The items above are minor/cosmetic or informational.

🤖 Generated with Claude Code

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 16 complexity

Metric Results
Complexity 16

View in Codacy

🟢 Coverage 45.07% diff coverage · -36.25% coverage variation

Metric Results
Coverage variation ✅ -36.25% coverage variation
Diff coverage ✅ 45.07% diff coverage

View coverage diff in Codacy

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.

hoogenbj pushed a commit to Locstat/arcadedb that referenced this pull request Jul 7, 2026
…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)
hoogenbj pushed a commit to Locstat/arcadedb that referenced this pull request Jul 7, 2026
…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.
oc007us pushed a commit to oc007us/arcadedb-grpc that referenced this pull request Jul 8, 2026
…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.
robfrank pushed a commit that referenced this pull request Aug 14, 2026
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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
… 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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant