Repository navigation
fix(#6281): an index build waits for the async BATCH, not just its tasks, and a flush backlog stays inside its own database - #6290
Conversation
…sks, and a flush backlog stays inside its own database Three independent follow-ups from #6259. Item 1 - Issue5279ConcurrentInsertTest.sustainedConcurrentInsertsOnASingleBucketNeverConflict tolerated up to two conflicts at attempts=1 and then demanded the exact full count. A conflict tolerated there means the record was NOT written, so the two assertions contradict each other and the run that actually uses the tolerance fails at the count (2000 against 2001) instead of passing at the tolerance meant to absorb it. Same trap PR #6223 fixed in the sibling Update class; the count now subtracts the conflicts. Both classes swept for the shape. Item 2 - a silent, empty index. DatabaseAsyncExecutorImpl.isProcessing() answers about TASKS, while a worker opens a transaction when it starts and keeps it open across up to ASYNC_TX_BATCH_SIZE (10240) of them. An executor whose queues happen to be drained therefore reports itself idle while still holding every record of the current batch uncommitted. TypeIndexBuilder.create() guarded with while (database.isAsyncProcessing()) database.async().waitCompletion(); so on the runs where that predicate answered false the guard was skipped entirely: the index was built by scanning a bucket that did not contain those records, and they committed afterwards with no entry ever added for them. The result is an index that is empty, readable, and reported healthy by CHECK DATABASE, while every lookup answers nothing. Reproduced deterministically (index entries 0 of 200, "select from V where id = 42" empty). The barrier is now unconditional - DatabaseInternal.waitForAsyncCompletion(), a do/while around waitCompletion(), which is the only operation that closes the open batch - and is used by TypeIndexBuilder, ManualIndexBuilder and REBUILD INDEX, which scans the buckets the same way. It reads the async field rather than async(), so a database that never used the async API neither waits nor grows a thread pool. isProcessing() is deliberately left answering about tasks: broadening it to "a transaction is open" would make it permanently true. ACIDTransactionTest.indexCreationWhileAsyncMustFail was vacuous - create() has drained the async executor for years, so its catch(NeedRetryException) never fired and its only assertion was the record count, which an empty index satisfies just as well as a complete one. Renamed to indexCreatedWhileAsyncInsertsAreInFlightSurvivesACrash and made to assert the index: countEntries() and a lookup for every record, after the crash and recovery. Item 3 - per-database flush budget. arcadedb.pageFlushQueue was one JVM-wide ArrayBlockingQueue: #6259 took the wait for room out of the page-manager lock, but one database's burst still consumed the admission budget of every other database in the process. The bound is now per database, held in a single count per database that covers both halves of an occupancy (reserved by a committer, then occupied by its batch until the flush thread polls it), and the shared queue carries no capacity of its own. One queue rather than one per database keeps global FIFO order for free - N queues would force the flush thread to choose between them on every poll, which is a fairness policy and a starvation risk this design does not have. The cost, stated in the field Javadoc, is that worst-case occupancy becomes pageFlushQueue x open databases batches. Regression tests: Issue6281AsyncBatchIndexBuildTest (fails on the previous code with an empty index) and Issue6281PerDatabaseFlushQueueTest.
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 14 |
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.
|
Tick the box to add this pull request to the merge queue (same as
|
ReviewWent through the full diff (engine async/index barrier, per-database flush-queue budget, and the two test fixes). Overall this is a careful, well-documented fix with strong regression coverage. A few notes: Correctness
Test coverage gap
Minor
What I liked
|
…es, and the two silent contract changes - PageManagerFlushSuspendDeferRaceTest and FlushRobustnessTest were missed by the sweep that routed every other white-box enqueue through offerBatch(). Neither could go negative today - the fabricated batch is the only thing ever charged against that database's budget in its own flush-thread instance, so the decrement lands on a missing key and no-ops - but both skipped the accounting invariant offerBatch()'s javadoc says every enqueue must exercise. - waitForAsyncCompletion() reads the async field without asyncLock while isAsyncProcessing() takes it: say why. The lock serializes the lazy creation in async(); the field is volatile and never reassigned, not even on close, so the read sees either no executor or the one and only one - and a lock there would be held across a blocking wait. - Math.max(1, pageFlushQueue) is a real contract change now that ArrayBlockingQueue's constructor no longer rejects a non-positive value. Documented as deliberate in both the constructor and the setting: with admission as the only bound, a budget of 0 refuses every publication for ever, which is worse than the startup failure it replaces. - Fixed a sentence dropped mid-edit in Issue6281AsyncBatchIndexBuildTest's javadoc.
ReviewI read through the full diff (engine/server/ha-raft) and cross-checked the two fixes described as "the real find" against the surrounding mechanisms they depend on. Overall this is a very carefully engineered PR: the reasoning is documented in-line at the exact spots a future reader will doubt it, and the regression tests reproduce each bug on the pre-fix code path rather than just asserting the new behavior. I did not run the build myself (tool sandboxing here blocks Item 1 - conflict-tolerance/count mismatchCorrect and minimal. Subtracting Item 2 -
|
…oo, and the rebuild claim was too strong - The barrier now sits AHEAD of RebuildIndexStatement's statsOnly branch, which returns early: that branch rescans the same records to recompute the BM25 counters, so it undercounted them by the same window. - Corrected the barrier's own comment on that path. It claimed a rebuild inside the window loses index entries, the way a CREATE INDEX does. It does not: those records staged their index operations when they were saved and applying them at commit repopulates what the scan could not see. A regression test written to catch a loss there passes with the call removed, which is why there is no such test - shipping one would have been the same vacuous coverage this PR removed from ACIDTransactionTest. What the window does cost is a rebuild computed over a partial view: the BM25 counters, the misplaced-record detection of #832, and the reported totals. - Release notes for 26.9.1, including the behaviour change the review asked to be called out: worst-case flush-pipeline occupancy is now pageFlushQueue x open databases batches, so a deployment that sized pageFlushQueue against total heap should re-check it.
ReviewThis is an unusually well-documented PR - the Javadoc/inline comments consistently explain the why (invariants, prior bugs, alternatives considered), which made this easy to verify. I traced all three items in detail; findings below. Likely deadlock: waitForAsyncCompletion() called from inside an async executor worker thread (high priority)LocalDatabase.waitForAsyncCompletion() calls executor.waitCompletion() unconditionally (do { executor.waitCompletion(); } while (isAsyncProcessing());). DatabaseAsyncExecutorImpl.waitCompletion(long) enqueues a completion marker on every worker's queue (including the calling thread's own, if the caller happens to be one of the executor's own AsyncThreads) and then blocks synchronously waiting for each marker's semaphore, in order. If the calling thread is one of those workers, the marker it just placed on its own queue can never be dequeued - the only consumer of that queue is the thread itself, and it's now parked waiting on the semaphore instead of looping back to poll. That is a self-deadlock, permanently losing one worker. This is reachable, not theoretical: database.async().command(...) (used by PostCommandHandler for HTTP requests with awaitResponse=false) runs the SQL command on one of the same DatabaseAsyncExecutorImpl worker threads. RebuildIndexStatement.buildIndex() already has an explicit guard for exactly this scenario (issue #2097 - "Index rebuild requires scheduling blocking tasks on all async threads, which will deadlock if we're already running on one of those threads" -> throws NeedRetryException when context.asyncMode is true), with its own regression test Issue2097AsyncRebuildIndexIT (async REBUILD INDEX * over HTTP). The problem: this PR adds ((DatabaseInternal) database).waitForAsyncCompletion(); at the top of RebuildIndexStatement.executeDDL(), before that asyncMode guard is ever reached (the guard lives inside buildIndex(), called later, and doesn't cover the statsOnly branch at all). So a REBUILD INDEX dispatched via async HTTP now hits the new unconditional wait first and hangs the worker - the #2097 protection becomes dead code for this path. Worth double-checking whether Issue2097AsyncRebuildIndexIT would actually catch this: it does database.async().waitCompletion(30000) from the test thread and doesn't check the boolean return value, then only asserts the index count is unchanged. Since the new wait hangs before buildIndex() ever touches the index (drop/rebuild happens later), the index would indeed be untouched - so the test would pass green while the worker thread is permanently stuck. That's the same "vacuous test hides a real bug" shape this very PR calls out for ACIDTransactionTest.indexCreationWhileAsyncMustFail. Same hazard applies to TypeIndexBuilder.create() / ManualIndexBuilder.create(), neither of which has an asyncMode guard at all. Before this PR the old while (isAsyncProcessing()) waitCompletion(); only deadlocked when a task happened to be queued/executing at that instant (probabilistic, apparently never hit in practice). Making the wait unconditional turns that into a certainty whenever CREATE INDEX / a manual index create runs from inside an async worker's own task (e.g. CREATE INDEX ... dispatched the same way over async HTTP). Suggest: have waitForAsyncCompletion() detect Thread.currentThread() being one of the executor's own workers (the codebase already has this pattern - see offerWaiting's Thread.currentThread() instanceof AsyncThread worker && worker.getOwner() == this) and either fail fast (NeedRetryException, consistent with the existing asyncMode guard) or handle it safely, rather than leaving each call site to reimplement the check inconsistently (currently only RebuildIndexStatement.buildIndex() has any guard, and it's now unreachable). Item 3 - per-database flush queue budgetTraced every path that adds/removes a batch from queue against slotsInUse (offerBatch, scheduleFlushOfPages, releaseQueueReservation, releaseSlotOfPolledBatch, resumeFlushing's defer/re-enqueue, removeAllPagesOfDatabase, closeAndJoin's sentinel, and all the white-box test call sites routed through offerBatch(..., false)). The accounting is consistently balanced - every enqueue that takes a slot has a matching release, deferred batches release on dequeue and re-reserve on re-enqueue, and a dropped database's budget is removed without producing a negative count on the batches still draining from the queue (covered by aDroppedDatabaseLeavesNoBudgetBehind). Nice test coverage on the concurrency edge cases (aDatabaseAtItsBoundDoesNotHoldTheCommittersOfAnother, theBoundIsPerDatabaseAndTheSharedQueueHasNoneOfItsOwn). One thing worth flagging prominently to operators (it is mentioned in the config Javadoc and release notes, so this is really just emphasis): arcadedb.pageFlushQueue changes from a JVM-wide cap to a per-database cap with the queue now unbounded (LinkedBlockingQueue). A process hosting many databases that all burst at once has a materially higher worst-case heap footprint than before (pageFlushQueue x open databases batches, each holding deep copies of dirty pages). Given this is a behavior change for anyone who tuned pageFlushQueue against total heap, it might be worth a WARNING-level log line at startup when running many databases with a non-default value, in addition to the docs. Item 1 - conflict-tolerant assertion fixCorrect and minimal. Confirmed conflicts (an AtomicInteger) is only mutated by the worker threads, and all of them are joined before it's read in the final assertions, so subtracting conflicts.get() from the expected count is safe and matches the sibling Issue5279ConcurrentUpdateTest pattern referenced in the description. Minor / nitLocalDatabase.waitForAsyncCompletion()'s do/while calls the void waitCompletion() overload, which internally swallows InterruptedException by restoring the interrupt flag and returning. If interrupted mid-wait, the loop doesn't check Thread.currentThread().isInterrupted() before looping again - if isAsyncProcessing() is still true, the next waitCompletion() call will immediately hit the same interrupted queue-offer and return again, potentially busy-spinning until the batch drains on its own. Same shape as the pre-existing while (isAsyncProcessing()) waitCompletion(); pattern this replaces, so not a new regression, but now that this is a documented, shared API used from four call sites, might be worth breaking out on interrupt. OverallItems 1 and 3 look solid and well-tested. Item 2's core fix (the barrier itself, TypeIndexBuilder/ManualIndexBuilder) addresses a real and well-reproduced bug - but the async-worker-thread deadlock risk above seems worth resolving or explicitly ruling out before merge, given it revives a scenario the codebase already had a dedicated regression test for. |
…side the executor it waits for A real regression this PR introduced, correctly caught in review. waitCompletion() enqueues a marker on EVERY worker - the caller's own included - and blocks until each has run, and the only consumer of a worker's queue is that worker. A worker that reaches the barrier parks on a marker nobody can dequeue and is lost for the life of the process. RebuildIndexStatement.buildIndex() has refused exactly this since issue #2097, but the barrier this PR added at the top of executeDDL() ran ahead of that guard, and never reached it at all on the statsOnly branch: #2097's protection became dead code for the path it was written for. Measured, with the guard removed: the surefire fork does not merely fail, it never finishes - killed after 400s - because the lost worker takes the database's close with it. - waitForAsyncCompletion() now refuses with NeedRetryException when the caller is one of this executor's own workers, using the same owner-checked `instanceof AsyncThread` test offerWaiting already uses. Refusing is the only honest answer: skipping the wait would put back the very bug the barrier closes, over the caller's own uncommitted batch, and committing that batch here would commit the enclosing task's writes mid-task, which is the per-task atomicity AsyncThread.executeTask guards. The guard now lives once, on the operation that cannot be satisfied, rather than once per call site that happens to remember it - TypeIndexBuilder and ManualIndexBuilder had no such guard at all. - #2097's own refusal is hoisted to the top of executeDDL(), ahead of the barrier, so it still answers first with the message it was written for and its integration test still asserts a refusal from where it expects one. Issue2097AsyncRebuildIndexIT: 3 tests green. - waitForAsyncCompletion()'s loop breaks on interrupt. waitCompletion() answers an interrupt by restoring the flag and returning, so the loop would otherwise spin: every further pass interrupted at its first queue offer, returning immediately. Pre-existing in the pattern this replaced, but worth closing now that it is shared API. - Issue6281AsyncBatchIndexBuildTest gains theBarrierRefusesToBeCalledFromOneOfTheExecutorsOwnWorkers. Not implemented, and why: a startup WARNING when many databases run with a non-default pageFlushQueue. The database count is not known where the flush thread is built (one JVM-wide thread, constructed once), and the throttle WARNING already names the database and reports the shared pipeline depth at the moment the budget actually bites - which is the point at which an operator can act on it. The tuning change is in the config javadoc and the release notes. engine: 12112 tests, 0 failures.
ReviewThis is an unusually well-documented PR (four review rounds are visible in the commit history, and it shows). I read through all three items in detail: the Correctness
One real (minor) issue
// Iterated directly rather than through a snapshot: ArrayBlockingQueue's iterator is weakly consistent and
// never throws ConcurrentModificationException, and this runs per replayed page, so the copy would be pure
// overhead. The walk is bounded by the flush queue depth (arcadedb.pageFlushQueue) plus the deferred backlog,This is now stale on two counts: Test coverageStrong. PerformanceThe queue-unbounding trade-off (JVM-wide SecurityNothing notable - no new external inputs, no new dependencies, no serialization changes. Nice work overall; the only thing I'd actually ask for before merge is the stale comment fix. |
…bed the old queue The only point raised, and correct: the walk in detachPendingPages() named ArrayBlockingQueue's iterator and claimed the walk is bounded by arcadedb.pageFlushQueue. Both went stale with this PR - the queue is a LinkedBlockingQueue and its depth is that setting times the number of open databases. The weak-consistency argument for iterating without a snapshot still holds (LinkedBlockingQueue's iterator is weakly consistent too), so only the bound and the class name needed correcting. Swept the rest of the file: every other ArrayBlockingQueue mention is deliberately historical - the field javadoc explaining what the queue used to be, the slotsInUse javadoc naming the property given up, and the constructor explaining why the capacity clamp replaced its IllegalArgumentException.
ReviewThis is a large, well-documented change addressing three independent problems from #6281. Overall the reasoning is sound, the fixes are backed by regression tests that fail on the old code, and the javadoc/comments do a good job of explaining why, not just what. A few notes below, none of which I'd consider blockers. Item 2 (async batch barrier) — solid
Item 3 (per-database flush budget) — solid, one thing worth double-checking
Item 1 (RebuildIndexStatement's #2097 guard) — minor nit
Test coverage
Nothing else stood outDidn't find any thread-safety, security, or performance issues beyond what's noted above. The queue-doorway invariant ("every enqueue goes through |
…nd why dropping a database's budget is safe Merge of origin/main: the only conflict was docs/release-26.9.1.md, where both sides appended a section at the end of the file. Both kept, #6196's first since it landed first. Review round 5, no blockers raised: - #2097's refusal is now MOVED rather than duplicated. Hoisting it to executeDDL() left the copy in buildIndex() unreachable - that method has one call site, below the hoisted check - and the two wordings had already drifted: the hoisted one fired before the index was resolved and so dropped the index name from the message. The name is carried up instead (and `REBUILD INDEX *`, which names no single index, says so), and buildIndex() keeps a comment pointing at where the check went and why it could not have stayed - the statsOnly branch returns without ever reaching it. - Documented, in removeAllPagesOfDatabase, the one-line confirmation the review asked for: nothing re-enters slotsInUse for a database after its budget is dropped. Every caller reaches it from LocalDatabase.close() - the drop path and the final purge alike - or from the test-only kill simulation, and close() has already set open=false, which is what the publication path and flushPage check. A live database never passes through, so a later computeIfAbsent cannot mint a budget that disagrees with batches still physically in the queue. Issue2097AsyncRebuildIndexIT: 3 green. Rebuild/index engine tests: 74 green.
Only conflict was docs/release-26.9.1.md again, where both sides append sections at the end of the file: all of them kept, in the order they landed (#6267, #6264, #6196, then #6281). GlobalConfiguration.java auto-merged - main touched a neighbouring setting, this branch rewrote PAGE_FLUSH_QUEUE's description. Full reactor builds; the flush-pipeline, async-barrier and configuration tests are green on the merge result.
ReviewThis is a well-scoped, well-documented fix for a genuinely nasty correctness bug (item 2: a Correctness / concurrencyI traced the full path: One thing worth a second look, not a blocker: Everything else
Nothing here blocks merging as far as I can tell from static review; the |
Same conflict shape as the previous two merges: docs/release-26.9.1.md, where both sides append a section at the end of the file. All kept, in landing order. Full reactor builds and the flush-pipeline, async-barrier and configuration tests are green on the merge result.
…ublish the number that still means something The one point raised, and a fair one. pageFlushQueueLength used to top out at arcadedb.pageFlushQueue, because that setting WAS the queue's capacity - so "length >= pageFlushQueue" was a natural full-pipeline alert. With the bound moved per database the field is a sum across every open database and can run to pageFlushQueue x open databases, which makes that comparison mean nothing. A published field quietly changing scale is worse than one that changes name. - pageFlushQueueMaxPerDatabase joins it: the busiest single database's share of the pipeline, which is exactly what the setting bounds, so it is the field to alert on and the one that carries the old signal. Surfaced in the profiler JSON under that name and in the text dump as flushQueueMaxPerDb, next to flushQueue. - Both fields document what they are, what they were, and which of them to compare against the setting. - Release notes call the change out for anyone with an existing alert on the old field. O(open databases) and read once per stats scrape - never on a write path.
ReviewI read through the full diff (engine flush pipeline, async executor barrier, index build/rebuild call sites, and the new/updated tests). Overall this is a very well-engineered fix with unusually thorough self-documentation — the commit history shows five review rounds that already caught and fixed several real issues (the statsOnly branch missing the barrier, the own-worker deadlock, the stale Correctness
Test coverage
Minor documentation nitIn Performance
SecurityNothing of concern — no new dependencies, no external input handling changed. Nit-free areas worth calling out positively
Nice work — this is a genuinely subtle bug (empty-but-healthy index) caught and fixed with real reproduction, and the flush-queue change is a sensible design (budget-over-one-queue vs. N queues) with the tradeoffs made explicit rather than hidden. |
ReviewWent through the full diff ( Item 2 -
|
… all, and it was worse than stated Three points raised, no blockers. The interesting one was the untested statsOnly claim, and checking it changed what the claim should say. - REBUILD INDEX ... WITH statsOnly = true recomputes the BM25 corpus counters by scanning the type and then OVERWRITING the counters with what the scan found. Run against an open async batch it finds nothing committed and writes "0 documents" over counters the records had already bumped when they were saved. Measured: 0 of 200 documents counted with the barrier removed, 200 with it. So this is not "computed over a partial view" as the previous round's comment hedged - the counters are left wrong, every BM25 score is computed against a corpus of zero, and unlike the index-entry case it does not heal itself. Now has a regression test, and the comment and release note say what was measured instead of what was reasoned. - The Math.max(1, pageFlushQueue) clamp has a test: a budget of 0 or -1 becomes 1 and admits exactly one batch. It used to be ArrayBlockingQueue's constructor that rejected a non-positive value, and there is no constructor left to reject it, so the clamp is now the only thing between a misconfiguration and a pipeline that refuses every publication for ever. - PAGE_FLUSH_QUEUE's javadoc said "...until issue #6281, which made one database's write burst throttle the commits of unrelated databases", where "which" reads as if the issue caused the bug rather than fixed it. Reworded. engine: 12204 tests, 0 failures.
…itor trade in the release notes Three points, all documentation, no blockers raised. - The release notes now say that CREATE INDEX, a manual index create and REBUILD INDEX raise NeedRetryException when run on one of the async executor's own worker threads (awaitResponse=false over HTTP, say). One correction to the review's framing: this is not a path that "could silently proceed" before. From a worker, isAsyncProcessing() is true by construction - that worker is executing a task - so the old guard always entered its loop and always parked on a marker only that same worker could dequeue. The change is a hang becoming a clear refusal, which is worth saying plainly either way. - Named the shared queueSlotLock trade in the same section: with many databases saturating their budgets at once, every poll wakes every waiter and each re-checks its own count. Deliberate, and the same shape as the deferred-RAM cap, but a different failure mode from the old single-queue design, so it should not have to be discovered. - Collapsed the double blank lines the repeated merges left before two unrelated headers.
ReviewThis is a well-documented, well-tested PR that fixes a genuinely serious bug (item 2: silent empty indexes from a mis-scoped async guard). The comment density is unusually high but earns its keep here - the reasoning behind each non-obvious choice (barrier placement, unbounded queue + per-database admission instead of per-database queues, Item 2 (async batch barrier) - solid
Item 3 (per-database flush budget) - one edge case worth a second look
If a new This "map keyed by Database but equals-by-path" pattern already exists for Everything else checked out
Minor
Nice work overall - the empty-index bug (item 2) is a real correctness issue worth fixing promptly, and the flush-queue budget redesign is thoughtful about avoiding the pitfalls of a naive per-database-queue approach. |
ReviewThis is a large, well-scoped PR (three independent items from #6281) that already went through 8 rounds of self-review addressing real issues (the RebuildIndexStatement Findings1.
If a database is closed and then reopened at the same path before that stale batch is polled, This pattern isn't unique to Things that look solid
Minor
|
…d a reopened database's budget Both rounds independently found the same real edge case, and it is worth the fix. LocalDatabase defines equality by database PATH, not by instance. removeAllPagesOfDatabase() emptied a closing database's queued batches but deliberately left the wrappers in the queue, and their `database` field still pointed at the closed instance - so a database dropped and recreated at the same path (a restore, a re-provision, plenty of tests) would have the NEW instance's budget decremented when one of those wrappers was finally polled. Assertion failure in the -ea lanes; silently one admission slot too many in production. Two changes, and the test pins the first: - removeAllPagesOfDatabase() now takes the emptied wrapper OUT of the queue. It carries no pages, so the poll would do nothing but release a slot belonging to a budget that has just been dropped. Removing it means the window does not exist rather than being survivable. - A batch carries the AtomicInteger its slot was charged on, captured at offerBatch(), and the release decrements THAT rather than looking the database up again. Defence in depth, and measured as such: with the queue removal in place the new test passes even with this reverted, because it can no longer reach the release. Kept because the removal has to be remembered at every future path that could leave a batch queued across a close, and the capture does not. Safe without volatile - written before queue.offer, read after queue.poll, and a BlockingQueue gives happens-before between them. Also from round 10: PageManagerFlushThread.queue drops from public to package-private. While it carried the capacity a direct queue.offer was merely impolite; now that admission is the only bound and offerBatch is the one place a slot is charged, a direct offer silently bypasses the accounting - which is what several white-box tests were doing before this issue swept them. Nothing outside the package used it. engine: 12205 tests, 0 failures. Full reactor builds.
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 14 |
🟢 Coverage 84.00% diff coverage · -6.56% coverage variation
Metric Results Coverage variation ✅ -6.56% coverage variation Diff coverage ✅ 84.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (bddef2e) 159127 125655 78.97% Head commit (929a6ab) 191526 (+32399) 138679 (+13024) 72.41% (-6.56%) 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 (#6290) 100 84 84.00% 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.
ReviewThis is a large, carefully-documented PR (10 rounds of self-review are visible in the commit history, and it shows — the javadoc on Correctness:
|
… the bucket scan, and it was not covered A real gap, correctly found. The barrier went into TypeIndexBuilder, ManualIndexBuilder and REBUILD INDEX, but BucketIndexBuilder.create() is reachable on its own through the public Schema.buildBucketIndex(...) - and that is how CHECK DATABASE ... FIX rebuilds an index it found damaged (DatabaseChecker). Reached that way it scanned a bucket that did not yet contain whatever an async worker was still holding in its open batch, and produced exactly the silently incomplete index this issue is about. The new test fails without the barrier: 0 entries of 200 records. Paying the barrier twice on the paths that already did costs one marker round-trip per worker on an executor that is drained by then; missing it once costs an index. Also removed from that method a CountDownLatch, semaphoreToStart, that the pause tasks counted down and NOTHING ever awaited - so the build began whether or not the workers had reached the pause it was meant to wait for. What it was reaching for is what the barrier now provides properly, so it is gone rather than left sitting there looking like a guard. The pause tasks themselves stay: they keep the workers from writing DURING the build, which is a different job and one they still do. engine: 12206 tests, 0 failures. Full reactor builds.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #6290 +/- ##
==========================================
+ Coverage 70.21% 70.23% +0.01%
==========================================
Files 1840 1840
Lines 159127 159173 +46
Branches 33559 33566 +7
==========================================
+ Hits 111736 111794 +58
+ Misses 33511 33506 -5
+ Partials 13880 13873 -7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Closes #6281.
Three independent items, plus an answer to the issue's open question.
Item 1 - two assertions that cannot both hold
Issue5279ConcurrentInsertTest.sustainedConcurrentInsertsOnASingleBucketNeverConflicttolerates up to two conflicts atattempts=1and then demands the exact full count. A conflict tolerated there means that record was not written, so the run that actually uses the tolerance fails at the count (2000 against 2001) instead of passing at the tolerance meant to absorb it.Same trap PR #6223 fixed in the sibling
Issue5279ConcurrentUpdateTest; the count now subtractsconflicts.get(). Both classes were swept for the shape - nothing else matched.Item 2 - the real find: a silent, empty index
DatabaseAsyncExecutorImpl.isProcessing()answers about tasks (queued or executing). An async workerbegin()s a transaction when it starts and keeps it open across up toASYNC_TX_BATCH_SIZE(10240 by default) tasks. So an executor whose queues happen to be drained reports itself idle while still holding every record of the current batch uncommitted.TypeIndexBuilder.create()guarded with:On the runs where that predicate answered
false, the guard was skipped entirely: the index was built by scanning a bucket that did not contain those records, and they committed afterwards with no entry ever added for them. The result is an index that is empty, readable, and reported healthy byCHECK DATABASE, while every lookup silently answers nothing.Reproduced deterministically before the fix - 200 records inserted,
index.countEntries()= 0,select from V where id = 42returns nothing:The fix is a barrier that cannot be skipped:
DatabaseInternal.waitForAsyncCompletion(), ado { waitCompletion() } while (isAsyncProcessing()).waitCompletion()is the only operation that closes the open batch - it enqueues a marker behind everything already submitted on every worker, and that marker commits - so it has to run even when the executor looks idle. It reads theasyncfield rather thanasync(), which would create the executor, so a database that never used the async API neither waits nor grows a thread pool.Applied to
TypeIndexBuilder,ManualIndexBuilderandRebuildIndexStatement-REBUILD INDEXscans the buckets the same way and had the same exposure.isProcessing()is deliberately left answering about tasks, with a Javadoc saying so: broadening it to "a transaction is open" would make it permanently true for as long as the workers are alive, which is no answer at all.The test the issue pointed at was vacuous
ACIDTransactionTest.indexCreationWhileAsyncMustFailexpected aNeedRetryExceptionfrom the creation. That expectation has been dead for years -create()drains the async executor rather than refusing - so thecatchwas never entered (verified: 0 of 100 runs) and the only assertion left was the record count, which an empty index satisfies just as well as a complete one. That is what it was hiding.Renamed to
indexCreatedWhileAsyncInsertsAreInFlightSurvivesACrashand made to assert the index itself:countEntries()and a lookup for every record, after the crash and recovery.Item 3 - per-database flush budget
arcadedb.pageFlushQueuewas one JVM-wideArrayBlockingQueue. #6259 took the wait for room out of the page-manager lock, so a full queue stopped freezing the whole JVM - but the coupling itself survived: one database's burst still consumed the admission budget of every other database in the process.A better alternative than the per-database queue the issue proposes: a per-database budget over ONE unbounded queue. A per-database queue bounds the same thing while forcing the single flush thread to choose between queues on every poll - a fairness policy, and a starvation risk, that a budget over one FIFO queue simply does not have. One queue keeps global FIFO order across databases for free.
slotsInUse: ConcurrentHashMap<BasicDatabase, AtomicInteger>merges the oldqueue.size() + reservationsinto ONE count per database, charged at reservation and released only when the batch leaves the queue - so a reservation and the batch it becomes are one continuous occupancy rather than two counters that have to agree. Every enqueue goes throughofferBatch, every poll through one release, and the count is asserted never to go negative.The property given up is named in the code:
queue.size()read the truth by construction, and anArrayBlockingQueuecannot say how many of its elements belong to database D. So is the cost: worst-case occupancy is nowpageFlushQueue x open databasesbatches, the same factor a per-database queue multiplies by, on a number that was never a byte bound to begin with (one batch is one transaction's dirty pages). The bound that is expressed in bytes remainsarcadedb.flushSuspendMaxDeferredRAM.The issue's open question
Item 2's root cause is a property of the index-build guard alone and has nothing to do with #6269: it fires whenever the async queues happen to be drained at the instant of the check, which thread scheduling on a loaded CI box makes more likely on some runs than others. The specific
page 0: keys cannot be read (Invalid position ...)warning was not reproduced locally, so I am not claiming it as explained - but the test that produced it now asserts the index rather than a bare warnings count, so a recurrence will say what is wrong instead of only that something is.Verification
Issue6281AsyncBatchIndexBuildTest(fails on the previous code:[every record must have an entry in the index] expected 200 but was 0),Issue6281PerDatabaseFlushQueueTest.engine: 12111 tests, 0 failures.server: 783 tests, 0 failures.